Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: Implement Wheel of Fortune feature with spin mechanics and UI
fudjia656863ff06de
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 403887d18..84dc7ca21 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Documentation accuracy pass: every tutorial verified against the shipped platform** — We cross-referenced all 300+ docs and specs against the actual codebase and fixed everything that had drifted. The embed snippet in ten tutorials now uses the real two-line form that works on any site, four tutorials that demonstrated retired or never-shipped APIs were rewritten against the live component, the troubleshooting guide now reflects the current Cloud Run production stack with the correct session and storage details, and the manifest, quick-start, and API references now list exactly the providers, attributes, and endpoints that exist today. Every code sample in the affected docs runs as written. (`/docs/tutorials/embed-in-30-seconds`) `[docs, fix]`- **Eight new market-intelligence APIs join the x402 catalog** — Agents can now pay fractions of a cent for answers, not just data: a one-call DeFi radar (TVL movers, top fee earners, top DEX volumes), a yield scanner with per-pool risk flags across 15,000+ live pools, a stablecoin peg monitor with depeg alerts, an exploit-history check for any protocol, a top-coins momentum heatmap with market-breadth stats, a multi-chain gas oracle covering Ethereum, Base, and Solana in one call, a market-mood index that blends Fear & Greed with live sentiment from 192 news feeds, and a per-ticker news pulse measuring coverage velocity. Prices run $0.001–$0.005 USDC per call, settled instantly via x402 on Solana or Base, and every endpoint refuses payment when its live data source is down — you are never charged for a missing answer. (`/docs/x402-endpoints`) `[feature]`- **Market data no longer rides on a single source** — The numbers on the markets pages used to blank out whenever CoinGecko rate-limited us. Now every core datapoint fails over across free, keyless backup APIs before it ever shows an error. The global stats bar falls back CoinGecko → CoinPaprika → CoinLore, the coins table backs up on CoinLore, the ETH price on the gas tracker and the BTC price on the exchanges page fail over to DefiLlama, the SOL price now draws on seven independent feeds, and the Solana token panels gained DefiLlama as a fourth source. Same numbers, same pages — they just stay up through an upstream outage instead of going blank. (`/coins`) `[improvement, infra]`+- **Meet your agent: the site now hands every visitor a living agent — and a command line to drive it** — three.ws now works the way it always promised: through your agent. Land on any page and within seconds a named 3D companion introduces itself — yours to keep, and one click turns it into a real agent on your account. The ⌘K search palette grew into a real command line: type “forge a bronze dragon statue” and a real 3D model is generated right inside the panel, “digest” reads you the day's crypto news as clustered stories, “price btc” quotes live market data, and “ask …” gets a streamed answer from the site agent — all free, no account needed, and your companion waves when the work lands. Market pages (/markets, /coins) now navigate without reloading, so your agent walks with you instead of blinking out on every click; the market surfaces also adopted the sitewide typeface for one consistent look. (`/docs/agent-shell`) `[feature, improvement]`- **Premium: one monthly pass instead of paying per call** — Go Premium for $9.99/30 days and stop paying the Data API per search: one Solana payment — in $THREE at 20% off, SOL, or USDC — mints an API key with unmetered archive search and lets your wallet sign in on the archive page instead of paying. Two new dashboard surfaces ship with it: a developer console at /dashboard/data-api (buy or renew the pass, manage and rotate API keys, live usage, copy-paste quickstarts) and Billing & Passes at /dashboard/billing (pass status, on-chain payment history, your subscriptions and paid services in one place). Renewals stack — renewing early adds 30 days to the end, never losing time. (`/docs/premium`) `[feature]`- **Richer coin pages, plus new exchange, category, and DeFi-yields detail pages** — Every coin page now shows far more of what the data already offers: a 1h-to-1y price-performance matrix, a circulating-vs-max supply bar with the market-cap/FDV ratio, all-time high and low with the drawdown and recovery multiple, the community bullish/bearish sentiment split, GitHub and social activity, and a full exchange-listings table with spread, order-book depth, and a trust rating for each venue. Exchanges and crypto categories, which used to only send you off-site or filter a table, now have their own detail pages — an exchange page with a trust badge, wash-volume-adjusted volume, a volume-history chart, and its markets, and a category page with the sector's rank, stats, and full coin list. And a brand-new DeFi Yields explorer covers roughly 15,000 live pools across every chain and protocol, filterable and sortable, each with its own APY and TVL history chart. All of it is real, key-free data. (`/yields`) `[feature, improvement]`- **The Market Data API: every market feed, now buyable per call** — All the live data behind the /markets pages — coin prices and profiles, price history, sector rankings, exchanges, derivatives, the global snapshot with Fear & Greed, ETH gas, trending assets, DeFi TVL by protocol and chain, 15,000 yield pools, stablecoin pegs, protocol fees and revenue, DEX volumes, and the full exploit database — is now a 17-endpoint paid API that agents can discover and buy autonomously. Each call costs $0.001 USDC over x402 on Solana or Base (the one-call market-pulse bundle is $0.005), with no API key or account needed, and a failed fetch never charges the buyer. The browser pages stay free for people; the paid endpoints are listed in the public x402 discovery catalog, and the free index at /api/x402/market documents everything with runnable examples. (`/docs/market-data-api`) `[feature]`@@ -281,7 +282,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-04-- **Markets — Live Crypto Prices** (`/coins`) — Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.+- **Coins — Live Prices & Market Caps** (`/coins`) — Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.- **Tutorial · 3D Store Guide for Shopify (No Code)** (`/tutorials/shopify-store-guide`) — Design a walking 3D store guide in the Tour Builder playground, preview it, and paste it into Shopify — point, click, done, no code.- **30+ background jobs were unreachable in production — payouts, subscriptions, and buybacks are back** — A routing gap meant every background job served by the shared cron dispatcher — payment distribution, subscription billing, royalty settlement, club and coin payouts, $THREE buybacks, and the pump.fun monitors — returned 404 in production while working fine in development. The route is fixed and a test now fails the suite if a new job is ever added without it. The x402 payment engine also no longer stalls when its wallet key is pasted into configuration with quotes, spaces, or line breaks — all common paste formats now load cleanly. `[fix, infra]`- **36 npm packages refreshed — every published SDK and MCP server now matches the platform** — A full audit of the @three-ws npm catalog found 36 packages whose published builds had fallen behind the platform — SDK improvements, MCP tool updates, and registry manifests that existed here but not on npm. All 36 are republished and current, including the core SDK, the page narrator, the React components, the Solana agent kit, and the full MCP server family. Two broken package builds were repaired along the way, and the Shopify store-guide tutorial now points at the fresh releases. (`/tutorials/shopify-store-guide`) `[sdk, improvement]`diff --git a/STRUCTURE.md b/STRUCTURE.mdindex a0a728043..2efed4e99 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -15,6 +15,7 @@ bottom.| Surface | Location | Status | Notes ||---|---|---|---|| Web renderer / viewer | [avatar-sdk/](avatar-sdk) `→ /viewer` | Published as `@three-ws/avatar` | `<agent-3d>` web component |+| Agent shell (companion identity + agentic ⌘K + persistent navigation) | [src/agents/guest-agent.js](src/agents/guest-agent.js), [src/shared/agent-names.js](src/shared/agent-names.js), [src/walk-companion-identity.js](src/walk-companion-identity.js), [public/search.js](public/search.js), [src/view-transitions.js](src/view-transitions.js), [src/shell/page-lifecycle.js](src/shell/page-lifecycle.js) | Live | The agent IS the interface: every visitor gets a named ephemeral agent in the first five seconds (auto-summoned corner companion with an identity chip; “Claim →” prefills /create-agent and POST /api/agents makes it real); the ⌘K palette executes real commands in place (forge → free text→3D lane, digest → clustered news, price → live market data, ask → streamed /api/chat) and announces completions so the companion reacts; pages marked data-shell (`/markets`, `/coins`) navigate by swapping only the main element so the agent and shell never unload (page modules re-init via onPageReady). Docs: [docs/agent-shell.md](docs/agent-shell.md). Tests: [tests/search-commands.test.js](tests/search-commands.test.js), [tests/guest-agent.test.js](tests/guest-agent.test.js), [tests/agent-names.test.js](tests/agent-names.test.js) || Walk companion + playground | [walk-sdk/](walk-sdk) `→ /walk-companion.js` | Published as `@three-ws/walk` | Corner mascot + full-page stroll/platformer playground + diverse avatar picker. App entries: [src/walk-companion.js](src/walk-companion.js), [src/walk-playground.js](src/walk-playground.js) || React avatar creator | [avatar-sdk/](avatar-sdk) `→ /react` `/creator` | Published as `@three-ws/avatar` | Same package, React subpath || Talking page guide | [page-agent-sdk/](page-agent-sdk) | Published as `@three-ws/page-agent` | Drop-in rigged 3D agent that narrates any page + visitor avatar picker. `<page-agent>` web component. Rigged-only catalog. `preset="…"` resolves one of 5 personas (greeting/role/suggested-prompt chips/tool allowlist) — see [page-agent-sdk/README.md#persona-presets](page-agent-sdk/README.md#persona-presets). See [page-agent-sdk/PUBLISHING.md](page-agent-sdk/PUBLISHING.md) |diff --git a/data/changelog.json b/data/changelog.jsonindex b368dede0..0d94911f8 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -13129,6 +13129,16 @@"docs"],"link": "/docs/x402-distribution"+ },+ {+ "date": "2026-07-11",+ "title": "Meet your agent: the site now hands every visitor a living agent — and a command line to drive it",+ "summary": "three.ws now works the way it always promised: through your agent. Land on any page and within seconds a named 3D companion introduces itself — yours to keep, and one click turns it into a real agent on your account. The ⌘K search palette grew into a real command line: type “forge a bronze dragon statue” and a real 3D model is generated right inside the panel, “digest” reads you the day's crypto news as clustered stories, “price btc” quotes live market data, and “ask …” gets a streamed answer from the site agent — all free, no account needed, and your companion waves when the work lands. Market pages (/markets, /coins) now navigate without reloading, so your agent walks with you instead of blinking out on every click; the market surfaces also adopted the sitewide typeface for one consistent look.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/docs/agent-shell"}]-}+}\ No newline at end of filediff --git a/docs/agent-shell.md b/docs/agent-shell.mdnew file mode 100644index 000000000..d72c9743d--- /dev/null+++ b/docs/agent-shell.md@@ -0,0 +1,126 @@+# The agent shell — your agent, the command line, and persistent navigation++three.ws is the platform where every user owns a living, embodied AI agent — and+the agent shell makes that agent the way you *use* the site, not just something+you build on it. It has three layers, each usable on every page:++1. **Your agent, in the first five seconds.** Every visitor gets a named agent+ immediately — no account, no wallet.+2. **An agentic ⌘K command line.** The search palette executes real work in+ place: generate a 3D model, read the day's news, quote a coin, ask a+ question.+3. **A persistent shell.** On shell-enabled pages, navigation swaps only the+ page content — the header, the command line, and your walking agent are+ never torn down.++---++## 1. Your agent (the companion with an identity)++On a first visit, the corner companion summons itself a couple of seconds after+the page loads and introduces itself with a generated name ("Turbo Kraken",+"Chrome Koi") and a light 3D body. The identity is an **ephemeral agent+draft** stored locally — nothing is created server-side until the visitor+claims it.++- The chip under the avatar shows the agent's name. For guests it carries a+ **Claim →** link into `/create-agent`, which prefills the wizard from the+ draft; finishing the wizard `POST /api/agents` creates the real agent (with+ its wallets) and clears the draft. Signed-in visitors see their canonical+ agent's name (from [src/agents/active-agent.js](../src/agents/active-agent.js)).+- The agent reacts to work done through the ⌘K palette — it waves and comments+ when a forge finishes or a digest arrives (`tws:palette-action` DOM events,+ mirrored onto the agent bus as `action:taken`).+- Auto-summon is polite: it waits for `load` + idle, skips visitors with+ `prefers-reduced-motion` or `Save-Data`, skips full-screen 3D/camera routes+ (`/play`, `/tour`, `/scan`, …), and never re-summons after the visitor closes+ the companion. The existing nav "Walk" toggle keeps working exactly as+ before.++Key modules: [src/agents/guest-agent.js](../src/agents/guest-agent.js) (draft+store), [src/shared/agent-names.js](../src/shared/agent-names.js) (namer),+[src/walk-companion-identity.js](../src/walk-companion-identity.js) (chip,+introduction, reactions), auto-start gate in [public/nav.js](../public/nav.js).++## 2. The ⌘K command line++Press **⌘K / Ctrl-K** anywhere. Beyond search, the palette parses executable+verbs and runs them in place against the real public APIs — no account needed:++| Command | Example | What happens |+| --- | --- | --- |+| `forge <prompt>` (also `make`, `generate`, `imagine`) | `forge a bronze dragon statue` | `POST /api/forge` on the free text→3D lane, polls to completion, returns open/download/refine links for the real GLB |+| `digest` (also `briefing`, `what happened today`) | `digest` | `GET /api/news/digest` — the last 24h clustered into narratives, rendered as rows |+| `price <coin>` or `$ticker` | `price btc`, `$sol` | `GET /api/coin/markets` + `/detail`, falling back to pump.fun token search |+| `ask <question>` (or any query ending in `?`) | `ask what is x402?` | `POST /api/chat` — the site agent's answer streamed into the panel; honors the free lane's `retry_after` backoff when it's at capacity |++Grammar rules: commands are strict verb-first parses — a bare verb (`forge`)+or a plain search query is never hijacked. A natural question ("how do agents+pay each other?") is *offered* as an Ask row under the search results, never+auto-run. `Esc` steps back from a run panel to the results; typing does the+same.++For other surfaces: `window.__twsSearch.parseCommand(q)` exposes the grammar,+and `window.__twsSearch.runCommand(q)` opens the palette and executes — both in+[public/search.js](../public/search.js).++## 3. The persistent shell++Pages that mark themselves with `data-shell` on their root `html` element get+same-document navigation: clicking between two shell pages fetches the+destination, swaps only the `main` element (plus title/meta), and pushes+history — the header, footer, corner stack, palette, and companion survive+untouched. Back/forward work the same way. Anything unexpected (an unmarked+destination, a fetch error) falls back to a normal full navigation, so the+shell can only ever *add* continuity.++Page modules opt in through one contract —+[src/shell/page-lifecycle.js](../src/shell/page-lifecycle.js):++```js+import { onPageReady } from './shell/page-lifecycle.js';++onPageReady(({ signal }) => init(), {+ match: (path) => path.replace(/\/$/, '') === '/markets',+});+```++`init` runs on first load and again on every shell navigation back to a+matching path; the previous run's `AbortSignal` is aborted first, so intervals+and document listeners registered with `{ signal }` clean themselves up.++Requirements for a shell page:++- `data-shell` on the `html` element, and `main` as a **direct child of+ `body`** (the standard page skeleton).+- The page's module initializes via `onPageReady` and its async renderers+ tolerate their target elements disappearing mid-flight (a navigation can land+ while a fetch is pending).++Live proof pages: `/markets` and `/coins`+([pages/markets.html](../pages/markets.html),+[pages/coins.html](../pages/coins.html)). The swapper lives in+[src/view-transitions.js](../src/view-transitions.js), which is inlined on+every page by the `view-transitions` plugin in+[vite.config.js](../vite.config.js).++**Caution for that inlined file:** it must stay dependency-free, keep exactly+one `export function`, and contain no HTML-looking sequences in comments or+strings — in dev, runtime-fetched fragments would otherwise render its source+as DOM (the plugin also explicitly skips `nav.html`/`footer.html` fragments for+this reason).++---++## How the pieces reinforce each other++The shell is one loop, not three features: the visitor lands and meets their+agent → the agent points them at ⌘K → a command does real work (a forged model,+a digest) → the agent reacts, building the relationship → **Claim** turns the+relationship into an account with a real agent. Ambient discovery routes+through the agent too — the old "have you tried…" toast stays out of the corner+while the companion is live.++Related: [web-component.md](web-component.md) (the embeddable `agent-3d`+avatar), [coin-pages.md](coin-pages.md) (the market surfaces the shell+navigates), [STRUCTURE.md](../STRUCTURE.md) (surface map).diff --git a/docs/start-here.md b/docs/start-here.mdindex c368d8d44..31a4392b6 100644--- a/docs/start-here.md+++ b/docs/start-here.md@@ -64,6 +64,7 @@ If you're here to create and share agents rather than write code, follow this pa- **Just exploring?** → Open [Discover](/discover) to browse agents others have built- **Creating your first agent** → Go to [/start](/start) — a 5-step wizard walks you through it+- **Wondering who the little character in the corner is?** → [The agent shell](./agent-shell.md) — every visitor gets a named agent in the first five seconds (claim it to make it real), the ⌘K palette runs real commands (`forge …`, `digest`, `price btc`, `ask …`), and shell pages navigate without ever unloading your agent- **Meeting avatars in the worlds?** → Press <kbd>I</kbd> on anyone in `/play`, `/city`, a coin world, or `/agora` to see who they are — the [avatar inspector](./avatar-inspector.md) shows their reputation, wallet, and profile- **Making 3D models?** → [The free 3D Studio MCP](./mcp-studio.md) turns a prompt into a model, avatar, or rigged character — and lets you refine it by talking to it (*"make it metallic"*) with a revertable version history. Publish a model as remixable and earn on-chain royalties when others build on it: [the remix economy](./remix.md)- **Trading?** → [The trading surfaces](./trading-surfaces.md) maps the solo stack (Radar, Coin Intelligence, Live Trade Feed, Watchlist, Mission Control); [trading arenas](./trading-arenas.md) covers tournaments, the theater, vaults, and swarms; [Oracle](./oracle.md) is the conviction engine underneath all of itdiff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 6eb87643a..b3447669c 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -277,6 +277,9 @@ const ACTION_RATES = {// Combat (W07): attack rides at a swing/shot cadence a touch above the fastest// weapon's cooldown (pistol ~430ms); loot is a deliberate, rare action.attack: 5, loot: 4,+ // Wheel of Fortune (W09) — deliberate, low-frequency, currency/payment-mutating+ // actions, throttled like the boutique's above.+ spinInfo: 4, spinFree: 3, spinPaidPrep: 3, spinPaidSettle: 3,};// Spatial voice signaling. The room only relays SDP/ICE between two peers (the@@ -438,6 +441,10 @@ export class WalkRoom extends Room {// quote TTL so a verified purchase can never re-grant a cosmetic twice, while// memory stays bounded (a nonce only needs to outlive its ~90s quote window).this._boutiqueNonces = new Map(); // nonce → settledAt (ms)+ // Wheel of Fortune (W09) replay guard — same shape and same reasoning as+ // _boutiqueNonces above: a settled paid-spin nonce can never roll a second+ // prize, and only needs to outlive its ~90s quote TTL.+ this._spinNonces = new Map(); // nonce → settledAt (ms)// Build permissions & anti-grief (R19). Ownership and density are tracked// off-schema (peers don't render them) but persisted with the build so they// survive a restart. blockOwners: key → owner id. blockCounts: owner id → how@@ -531,6 +538,7 @@ export class WalkRoom extends Room {// receives the authoritative result via profile/inv/xpgain/levelup/notice.this.onMessage('fish', (client) => this._handleFish(client));registerActivityHandlers(this); // W06 gather/craft: chop, mine, cook+ registerSpinHandlers(this); // W09 Wheel of Fortune: spinInfo, spinFree, spinPaidPrep, spinPaidSettleregisterCombatHandlers(this); // W07 combat: attack, lootthis.onMessage('equip', (client, payload) => this._handleEquip(client, payload));this.onMessage('consume', (client, payload) => this._handleConsume(client, payload));@@ -1996,6 +2004,12 @@ export class WalkRoom extends Room {for (const [nonce, ts] of this._boutiqueNonces) if (ts < cutoff) this._boutiqueNonces.delete(nonce);}+ // Same reasoning as _pruneBoutiqueNonces above, for paid-spin settlement.+ _pruneSpinNonces() {+ const cutoff = Date.now() - 5 * 60_000;+ for (const [nonce, ts] of this._spinNonces) if (ts < cutoff) this._spinNonces.delete(nonce);+ }+// Write this session's economy profile through to the account-keyed store,// merging onto any existing record so unrelated fields for the same account// are preserved. Synchronous + debounced.diff --git a/pages/coins.html b/pages/coins.htmlindex 525e2b4ac..ba8302e1a 100644--- a/pages/coins.html+++ b/pages/coins.html@@ -33,7 +33,7 @@/><metaproperty="og:image"- content="https://three.ws/api/page-og?s=crypto&t=Markets+%E2%80%94+Live+Crypto+Prices&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins"+ content="https://three.ws/api/page-og?s=crypto&t=Coins+%E2%80%94+Live+Prices+%26+Market+Caps&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins"/><meta property="og:image:width" content="1200" /><meta property="og:image:height" content="630" />@@ -46,7 +46,7 @@/><metaname="twitter:image"- content="https://three.ws/api/page-og?s=crypto&t=Markets+%E2%80%94+Live+Crypto+Prices&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins"+ content="https://three.ws/api/page-og?s=crypto&t=Coins+%E2%80%94+Live+Prices+%26+Market+Caps&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&p=%2Fcoins"/><meta name="theme-color" content="#09090b" /><link rel="icon" href="/favicon.ico" sizes="any" />diff --git a/prompts/robinhood-chain/PLAN.md b/prompts/robinhood-chain/PLAN.mdnew file mode 100644index 000000000..1a0fb4dd6--- /dev/null+++ b/prompts/robinhood-chain/PLAN.md@@ -0,0 +1,135 @@+# Robinhood Chain Campaign — Research + Build Plan++> Drafted 2026-07-11 from a 4-agent research sweep (chain facts, GitHub, npm, infra/gap landscape).+> COMMIT GATE: everything in this campaign references a non-$THREE crypto project. Per CLAUDE.md,+> no commit ships without explicit owner approval of that content. Owner directed this campaign+> on 2026-07-11; confirm approval per-commit or get a blanket sign-off before the first push.++## Ground truth (verified 2026-07-11)++- **Mainnet LIVE since 2026-07-01.** Permissionless Arbitrum Orbit L2, settles to Ethereum,+ blobs DA, ETH gas, 100ms blocks, ERC-4337 supported.+- **Chain ID 4663** (mainnet) / **46630** (testnet). Public RPC `https://rpc.mainnet.chain.robinhood.com`,+ Alchemy is the recommended provider (`robinhood-mainnet.g.alchemy.com/v2/{key}`), Blockscout+ explorer + Pro API at `robinhoodchain.blockscout.com`, public sequencer feed+ `wss://feed.mainnet.chain.robinhood.com`. Testnet faucet drips ETH + test Stock Tokens+ (TSLA, AMZN, PLTR, NFLX, AMD): `https://faucet.testnet.chain.robinhood.com/`.+- **`viem@^2.55.0` ships `robinhood` + `robinhoodTestnet` chain defs** (published 2026-07-08).+ No custom chain config needed anywhere.+- **Assets:** ~95 tokenized Stock Tokens (plain ERC-20, 18 decimals, each with a live Chainlink+ price feed; corporate actions via ERC-8056 `uiMultiplier()`); **USDG** (Paxos) is the dollar+ rail (>$260M week one); **no native chain token** (airdrop talk is pure speculation).+ Memecoin meta is real: $560M+/day DEX volume, NOXA + "The Odyssey" pump.fun-style launchpads+ graduating coins to Uniswap v3, CASHCAT hit ~$150M cap.+- **Programmatic trading is open:** Uniswap v2/v3/v4 + UniswapX, 1inch, Arcus (zero-fee stock+ DEX), Lighter (perps), Morpho are live. Stock Tokens are standard transferable ERC-20s.+- **Compliance line:** Stock Tokens may not be offered/sold to US persons (also CA/UK/CH limits).+ Enforced legally + at issuance/front-ends, not at contract level. Memecoins carry no such+ restriction. → Stock Token BUY flows must be geo-gated; display/data is fine; memecoin swaps+ are unrestricted.+- **Official tooling vacuum:** no Robinhood SDK, no official chain MCP (their Trading MCP at+ `agent.robinhood.com/mcp/trading` is brokerage-only, US-only), no market-data REST API for+ Stock Tokens, no launchpad firehose, chain absent from Graph Studio. Robinhood's GitHub org+ has zero original chain repos.+- **Ecosystem is ~2 weeks old:** ~40 repos, almost all 0-star. Standouts: `nhevers/project-r0x`+ (MIT, 122★, x402 facilitator + USDG agent OS on chain 4663 — the one serious competitor,+ squarely in our x402 lane), `arambarnett/robinhood-chain-mcp` (MIT, read-only chain MCP),+ `ismailmoazami/robinhood-chain-quickstart` (MIT Foundry template),+ `BankrBot/skills` hoodmarkets pack (known-contracts.json = Stock Token address source).+ `adrydevel/robinhood-chain-sdk` is the closest SDK but license-ambiguous (README-MIT, no+ LICENSE file) — do not fork until resolved; build clean-room instead.+- **Data providers we already integrate cover the chain:** DefiLlama has chain/RWA/bridge pages+ (our fixture already carries chainId 4663), CoinGecko API has live+historical chain data plus+ "Robinhood Chain Meme" and "Robinhood Chain Stocks Ecosystem" categories, GeckoTerminal ++ DEXTools track its pools, Dune has full support.+- **Distribution:** Robinhood committed $1M to Arbitrum Open House 2026 (4 buildathons + 2+ founder houses). Priority verticals: DEXs, perps, lending.++## Confirmed market gaps (nobody has these)++1. Unified tokenized-equity market-data API (Robinhood + xStocks + Ondo in one schema:+ price, 24/7 candles, holders, DEX volume, premium/discount vs underlying, multipliers).+ RWA.xyz is enterprise-paid; CoinGecko has no equity semantics.+2. Cross-venue tokenized-stock screener ("DEX Screener for equities") with arb/premium alerts.+3. MCP server + agent tooling for the chain itself (not the brokerage).+4. Portfolio tracking that reads `uiMultiplier()` correctly (every generic tracker misstates+ balances after splits/dividends).+5. Launchpad/memecoin WebSocket firehose (PumpPortal-equivalent) — raw material is the public+ sequencer feed + Blockscout.+6. x402-payable APIs on/for the chain (r0x is day-one; no incumbent).+7. A polished chain SDK on npm (zero exist).++## Workstreams++### RH-01 — Chain plumbing (foundation, do first)+`api/_lib/robinhood-chain.js`: viem clients (public RPC + Alchemy failover), chain constants,+Stock Token registry (seed from Robinhood docs /chain/contracts + BankrBot known-contracts.json,+refresh from Blockscout), Chainlink feed reader with staleness guards, `uiMultiplier()` reader,+USDG address/decimals. Testnet twin for E2E (faucet-funded). Everything below consumes this.++### RH-02 — Market Data API + x402 (`api/v1/robinhood/*`)+Extends the existing Market Data API + x402 catalog patterns (`api/v1/market`, `api/v1/tokenized`):+- `/api/v1/robinhood/stocks` — all Stock Tokens: Chainlink price, DEX price, premium/discount,+ multiplier-adjusted, 24h volume/liquidity (GeckoTerminal/CoinGecko + on-chain).+- `/api/v1/robinhood/stocks/:symbol` — detail incl. candles, holders (Blockscout), feeds.+- `/api/v1/robinhood/coins` — memecoins/launchpad tokens (CoinGecko category + GeckoTerminal pools).+- `/api/v1/robinhood/chain` — TVL/protocols/bridge flows (DefiLlama — extend existing provider).+- `/api/v1/robinhood/portfolio/:address` — multiplier-correct portfolio valuation (gap #4).+- `/api/v1/tokenized/equities` — THE flagship: unified cross-issuer equity API+ (Robinhood + xStocks public API + Ondo/Chainlink feeds) in one schema (gap #1).+Pricing: free tier + x402 USDC per-call above quota, same rails as the rest of the catalog.+Register in the x402 directory + `api/v1/_catalog.js`.++### RH-03 — SDK: `@three-ws/robinhood-chain` (first real SDK in market)+Clean-room TypeScript, `viem@^2.55.0` peer dep. Modules: stockTokens (registry/prices/+multipliers), swap (Uniswap v3/UniswapX quoting + execution, memecoin + stock paths),+launchpads (NOXA/Odyssey watch), usdg (transfers + x402-style payment helper), portfolio.+Publish under `packages/`, README + runnable examples, testnet E2E in CI. npm publish needs+owner token (known blocker — queue behind walk/tour/IRL publishes).++### RH-04 — MCP server + agent skill+`robinhood-chain` MCP: token discovery, quotes (Chainlink + DEX), swap building, portfolio,+launchpad feed — wraps RH-01/RH-02/RH-03. Paid tools via x402 like our existing MCP. Plus a+Claude Agent Skill. The two existing MIT MCPs are read-only and 0-star; ours is the productized+one wired to real market data.++### RH-05 — /markets integration (display)+- Robinhood Chain section in /markets: stocks table (24/7 equity prices — a thing CoinGecko+ can't show properly), memecoin screener, chain TVL page.+- Detail pages per Stock Token and per coin, following the markets detail-page patterns.+- Cross-venue equity screener page: same ticker across Robinhood Chain / xStocks / Ondo with+ premium/discount + arb spread (gap #2 — screenshot bait).++### RH-06 — Purchase flow+Swap on chain 4663 via Uniswap/1inch routed through our existing EVM wallet flows (MetaMask+agentic CLI already in stack; chain def from viem). Memecoins: open to all. Stock Tokens:+geo-gate buy UI for US (display remains open); server-side check + clear disclosure copy.+Bridge deep-links (LI.FI/Relay/Across) for funding.++### RH-07 — /play: Live 3D worlds for Robinhood Chain coins+Port the pump.fun /play formula: deterministic 3D world per launchpad coin (NOXA graduations,+CoinGecko meme category), walk in as avatar, live trades driving the world via a firehose built+on `wss://feed.mainnet.chain.robinhood.com` (gap #5 — this firehose is also sellable via RH-02).+Stretch: Stock Token "trading floors" — a 3D floor per ticker (AAPL floor at 2am on a Saturday,+live Chainlink tape) — display-only, no geo issue.++### RH-08 — x402 USDG settlement rail (accept payments ON the chain)+Add Robinhood Chain USDG as an accepted x402 settlement network for our existing paid endpoints+(we already run multi-rail: Solana USDC, X Layer). r0x proves demand; we'd be the first+established x402 catalog accepting USDG-on-4663. Needs: settlement wallet on 4663, facilitator+support, tiny ETH gas float.++## Sequencing++Phase 1 (now): RH-01 → RH-02 (stocks/coins/chain endpoints) + RH-05 (markets display).+Phase 2: RH-07 (/play worlds — needs the firehose from RH-02), RH-03 (SDK).+Phase 3: RH-04 (MCP), RH-06 (purchase), RH-08 (USDG rail).+Marketing: X thread per phase (x-posting playbook); submit toolkit to Arbitrum Open House+buildathons for distribution.++## Owner decisions needed+1. Blanket commit approval for Robinhood Chain content in this campaign, or per-commit sign-off?+2. RH-06 Stock Token purchase geo-gating: US-block buy UI only, or exclude Stock Token+ purchase entirely (display + memecoin swaps only) at launch?+3. RH-08 needs a funded settlement wallet on chain 4663 (ETH gas float; owner keys policy).+4. npm publish token for RH-03 (existing blocker across all package publishes).diff --git a/public/changelog.json b/public/changelog.jsonindex 11bdd6c49..ad6617df0 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-11T21:30:10.459Z",+ "generated_at": "2026-07-11T22:01:34.847Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -128,6 +128,17 @@"infra"]},+ {+ "date": "2026-07-11",+ "type": "update",+ "title": "Meet your agent: the site now hands every visitor a living agent — and a command line to drive it",+ "summary": "three.ws now works the way it always promised: through your agent. Land on any page and within seconds a named 3D companion introduces itself — yours to keep, and one click turns it into a real agent on your account. The ⌘K search palette grew into a real command line: type “forge a bronze dragon statue” and a real 3D model is generated right inside the panel, “digest” reads you the day's crypto news as clustered stories, “price btc” quotes live market data, and “ask …” gets a streamed answer from the site agent — all free, no account needed, and your companion waves when the work lands. Market pages (/markets, /coins) now navigate without reloading, so your agent walks with you instead of blinking out on every click; the market surfaces also adopted the sitewide typeface for one consistent look.",+ "link": "/docs/agent-shell",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-07-11","type": "update",@@ -2663,7 +2674,7 @@{"date": "2026-07-04","type": "launch",- "title": "Markets — Live Crypto Prices",+ "title": "Coins — Live Prices & Market Caps","summary": "Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.","link": "/coins","tags": [diff --git a/public/changelog.xml b/public/changelog.xmlindex 426f2c5e3..8bb1e5349 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -102,6 +102,14 @@<category>improvement</category><description>The numbers on the markets pages used to blank out whenever CoinGecko rate-limited us. Now every core datapoint fails over across free, keyless backup APIs before it ever shows an error. The global stats bar falls back CoinGecko → CoinPaprika → CoinLore, the coins table backs up on CoinLore, the ETH price on the gas tracker and the BTC price on the exchanges page fail over to DefiLlama, the SOL price now draws on seven independent feeds, and the Solana token panels gained DefiLlama as a fourth source. Same numbers, same pages — they just stay up through an upstream outage instead of going blank.</description></item>+ <item>+ <title>Meet your agent: the site now hands every visitor a living agent — and a command line to drive it</title>+ <link>https://three.ws/docs/agent-shell</link>+ <guid isPermaLink="false">2026-07-11:Meet your agent: the site now hands every visitor a living agent — and a command line to drive it</guid>+ <pubDate>Sat, 11 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>three.ws now works the way it always promised: through your agent. Land on any page and within seconds a named 3D companion introduces itself — yours to keep, and one click turns it into a real agent on your account. The ⌘K search palette grew into a real command line: type “forge a bronze dragon statue” and a real 3D model is generated right inside the panel, “digest” reads you the day's crypto news as clustered stories, “price btc” quotes live market data, and “ask …” gets a streamed answer from the site agent — all free, no account needed, and your companion waves when the work lands. Market pages (/markets, /coins) now navigate without reloading, so your agent walks with you instead of blinking out on every click; the market surfaces also adopted the sitewide typeface for one consistent look.</description>+ </item><item><title>Premium: one monthly pass instead of paying per call</title><link>https://three.ws/docs/premium</link>@@ -2039,9 +2047,9 @@<description>On the Avatars and Agents dashboards, the wallet identity chip — address, ownership, live balance, rarity and the vanity shortcut — was crammed onto a single line and spilled past the edge of narrow cards, bleeding into the card beside it. It now fills the card footer as a tidy rounded block and wraps its badges onto a second line when space is tight, so every card stays clean at any width. The Community and Characters galleries get the same fix.</description></item><item>- <title>Markets — Live Crypto Prices</title>+ <title>Coins — Live Prices & Market Caps</title><link>https://three.ws/coins</link>- <guid isPermaLink="false">2026-07-04:Markets — Live Crypto Prices</guid>+ <guid isPermaLink="false">2026-07-04:Coins — Live Prices & Market Caps</guid><pubDate>Sat, 04 Jul 2026 12:00:00 GMT</pubDate><category>launch</category><description>Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.</description>diff --git a/public/features.json b/public/features.jsonindex e21c82c54..2c994d191 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-11T21:30:10.446Z",+ "generated_at": "2026-07-11T22:01:34.834Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -1438,7 +1438,7 @@},{"path": "/coins",- "title": "Markets — Live Crypto Prices",+ "title": "Coins — Live Prices & Market Caps","description": "Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.","added": "2026-07-04","auth": null,diff --git a/public/llms-full.txt b/public/llms-full.txtindex 99cb8bf2b..a52f323e6 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -873,7 +873,7 @@ URL: https://three.ws/coin-intelEvery pump.fun launch watched and classified in real time — organic vs bundle, the wallets behind it, a transparent quality score, and a model that learns which signals predict winners.-### Markets — Live Crypto Prices+### Coins — Live Prices & Market CapsURL: https://three.ws/coinsdiff --git a/public/llms.txt b/public/llms.txtindex b7ce7b993..7f0affe7b 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -161,7 +161,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [ETH Vanity (CREATE2)](https://three.ws/eth-vanity): Grind a vanity smart-contract address using the ThreeWSFactory CREATE2 deployer on BSC.- [Pump Visualizer](https://three.ws/pump-visualizer): 3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene.- [Coin Intelligence](https://three.ws/coin-intel): Every pump.fun launch watched and classified in real time — organic vs bundle, the wallets behind it, a transparent quality score, and a model that learns which signals predict winners.-- [Markets — Live Crypto Prices](https://three.ws/coins): Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.+- [Coins — Live Prices & Market Caps](https://three.ws/coins): Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.- [Crypto Market Heatmap](https://three.ws/heatmap): A live market heatmap of the top cryptocurrencies: every tile is a coin, sized by market cap and colored by its 24h or 7d price move. See where money is flowing across the whole market at a glance, then click any tile for its full profile.- [Crypto Fear & Greed Index](https://three.ws/fear-greed): The Crypto Fear & Greed Index — live market sentiment from 0 (Extreme Fear) to 100 (Extreme Greed), shown on a gauge with a week-over-week delta, a full interactive history chart, and a labelled scale explaining what each reading means.- [Ethereum Gas Tracker](https://three.ws/gas): Live Ethereum gas fees straight from the chain — slow, standard, and fast tiers in gwei with USD cost estimates for transfers, token sends, DEX swaps, and NFT mints. Real on-chain fee history, refreshed automatically, no API key required.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex e2279e0ca..aed42fc07 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -56,6 +56,25 @@.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }.sm-brand:hover { text-decoration: none; }</style>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <meta property="og:title" content="Sitemap · three.ws">+ <meta property="og:description" content="Human-readable index of every page on three.ws.">+ <meta property="og:url" content="https://three.ws/sitemap">+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="Sitemap — three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Sitemap · three.ws">+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script></head><body><header class="sm-topbar">@@ -1109,7 +1128,7 @@</li><li><a href="/coins">- <span class="sm-title">Markets — Live Crypto Prices</span>+ <span class="sm-title">Coins — Live Prices & Market Caps</span><span class="sm-path">/coins</span><span class="sm-desc">Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.</span></a>diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex eb908dee4..0b6a4748c 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -66,6 +66,7 @@ import { ensurePlayAccess } from './play-gate.js';import { clearStoredPass, refreshPlayPass, loadStoredPass, storePass } from './play-auth.js';import { PlaySystems } from './play-systems.js';import { PlayActivities } from './play-activities.js';+import { WheelStation } from './wheel-station.js';import { PlayOnboard } from './play-onboard.js';import { log } from '../shared/log.js';import { openAvatarInspector, isAvatarInspectorOpen, closeAvatarInspector } from '../shared/avatar-inspector.js';@@ -1189,6 +1190,14 @@ export class CoinCommunities {net: this.net,ui: this.ui,});+ // W09: Fortune's Folly, the Mainland Wheel of Fortune. Another sibling —+ // its own landmark, its own prompt, lazy-loads the actual spin UI (and the+ // @solana/web3.js it drags in for the paid path) only on first interact.+ this.wheelStation = new WheelStation({+ scene: this.scene,+ getPlayer: () => ({ x: this.localPos.x, y: this.localPos.y, z: this.localPos.z }),+ net: this.net,+ });this.net.on('profile', (snap) => { this.playSystems?.setProfile(snap); this._onCosmeticsProfile(snap); });this.net.on('inv', (delta) => this.playSystems?.applyInv(delta));this.net.on('xpgain', (g) => this.playSystems?.onXpGain(g));@@ -1554,6 +1563,7 @@ export class CoinCommunities {if (this.combat) { this.combat.dispose(); this.combat = null; }if (this.playSystems) { this.playSystems.dispose(); this.playSystems = null; }if (this.playActivities) { this.playActivities.dispose(); this.playActivities = null; }+ if (this.wheelStation) { this.wheelStation.dispose(); this.wheelStation = null; }this._disposeFriends();if (this.agentCommerce) { this.agentCommerce.dispose(); this.agentCommerce = null; }if (this.intelKiosk) { this.intelKiosk.dispose(); this.intelKiosk = null; }@@ -2480,7 +2490,7 @@ export class CoinCommunities {// Talk to the nearest townsperson (vendor/quest/flavor); if none is// in range, try the Intel Kiosk, then fall through to the Agent// Exchange.- if (!this.worldLife?.interact() && !this.intelKiosk?.interact() && !this.combat?.interact()) this.agentCommerce?.interact();+ if (!this.worldLife?.interact() && !this.intelKiosk?.interact() && !this.combat?.interact() && !this.wheelStation?.interact()) this.agentCommerce?.interact();return;}// F is contextual: enter/exit a nearby vehicle takes priority (the@@ -3320,6 +3330,7 @@ export class CoinCommunities {this._updateVoice();this.playSystems?.tick(dt);this.playActivities?.tick(dt);+ this.wheelStation?.tick(dt);this.agentCommerce?.tick(dt);this.intelKiosk?.tick(dt);if (this.worldLife) { this.worldLife.setRealPeers(this.remotes.size); this.worldLife.tick(dt); }diff --git a/src/game/community-net.js b/src/game/community-net.jsindex f557ea4a3..ab035727b 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -141,6 +141,11 @@ export class CommunityNet {store: new Set(), // ({sell:[{item,label,price}], buy:[{item,qty,price,label}]})boutique: new Set(), // ({listings, owned, configured}) — premium cosmetics priced in $THREEboutiqueQuote: new Set(), // ({id, price, quoteToken, txBase64}) — unsigned $THREE purchase to sign+ // Wheel of Fortune (W09) — Fortune's Folly, the Mainland casino wheel.+ spinInfo: new Set(), // ({segments, now, nextFreeSpinAt, avgLevel, minLevel, eligible, atWheel, paidAvailable, symbol, costUsd})+ spinPrep: new Set(), // ({tx, tokenAmount, symbol, costUsd, quote}) — unsigned paid-spin tx to sign+ spinResult: new Set(), // ({mode, index, label, got, overflow, nextFreeSpinAt?}) — the server's roll+ spinDenied: new Set(), // ({reason, ...}) — a spin request refusedquests: new Set(), // ({offers, active, day}) — jobs board + active runs (W05)questComplete: new Set(), // ({id, title, reward, kind, coop}) — a mission/heist finishedcombat: new Set(), // ({role:'attacker'|'victim', target:'mob'|'player', kind?, mobHp?, mobMaxHp?, playerHp, playerMaxHp, dealt, dead, attacker?}) — a swing/shot's result@@ -319,6 +324,11 @@ export class CommunityNet {this.room.onMessage('store', (msg) => this._emit('store', msg || {}));this.room.onMessage('boutique', (msg) => this._emit('boutique', msg || {}));this.room.onMessage('boutiqueQuote', (msg) => this._emit('boutiqueQuote', msg || {}));+ // Wheel of Fortune (W09).+ this.room.onMessage('spinInfo', (msg) => this._emit('spinInfo', msg || {}));+ this.room.onMessage('spinPrep', (msg) => this._emit('spinPrep', msg || {}));+ this.room.onMessage('spinResult', (msg) => this._emit('spinResult', msg || {}));+ this.room.onMessage('spinDenied', (msg) => this._emit('spinDenied', msg || {}));// Quests, jobs & heists (W05): the board + active runs and completion events.this.room.onMessage('quests', (msg) => this._emit('quests', msg || {}));this.room.onMessage('questComplete', (msg) => this._emit('questComplete', msg || {}));@@ -593,6 +603,15 @@ export class CommunityNet {requestBoutique() { this._send('boutiqueReq'); }boutiqueQuote(id, wallet) { this._send('boutiqueQuote', { id, wallet }); }boutiqueSettle(quoteToken, txSig) { this._send('boutiqueSettle', { quoteToken, txSig }); }+ // Wheel of Fortune (W09). spinInfo() asks for the current segments/eligibility/+ // cooldown snapshot; spinFree() attempts the 12h free spin; spinPaidPrep(wallet)+ // prices a $3-in-$THREE paid spin and returns the unsigned tx to sign (the+ // reply arrives via the 'spinPrep' event); spinPaidSettle() hands back the+ // broadcast signature for the server to verify on-chain before it rolls.+ spinInfo() { this._send('spinInfo'); }+ spinFree() { this._send('spinFree'); }+ spinPaidPrep(wallet) { this._send('spinPaidPrep', { wallet }); }+ spinPaidSettle(quote, txSig) { this._send('spinPaidSettle', { quote, txSig }); }// Quests, jobs & heists (W05). Server-authoritative: accept/abandon a mission and// interact at a quest object; the board + progress arrive via the 'quests' event// and completions via 'questComplete'. questInteract acts on the zone the serverdiff --git a/src/game/spin-wheel-ui.js b/src/game/spin-wheel-ui.jsindex dda96e2f5..34462e904 100644--- a/src/game/spin-wheel-ui.js+++ b/src/game/spin-wheel-ui.js@@ -1,34 +1,22 @@-// Wheel of Fortune — the in-world spinner UI for /play (Task 19).+// Wheel of Fortune — the in-world spinner UI for /play (Task 19/W09).//-// Opened when the player reaches the Mainland casino wheel. The SERVER owns-// every outcome: this module renders the 20-segment wheel, requests a spin, and-// animates the wheel to land on exactly the segment the server rolled — it never-// decides a prize. Two ways to spin:+// Opened when the player reaches Fortune's Folly, the Mainland casino wheel+// (multiplayer/src/wheel-station.js renders the landmark + prompt; this module+// is lazy-imported on first interaction). The SERVER owns every outcome: this+// module renders the 20-segment wheel, requests a spin, and animates the wheel+// to land on exactly the segment the server rolled — it never decides a prize.+// Two ways to spin:// • Free — one per account every 12h, with a live countdown.-// • Paid — $3 in $THREE (50% burned / 50% to treasury). The server builds the-// split transaction, the player's wallet signs + broadcasts it, and the-// server verifies it on-chain before rolling. The paid spin never touches the+// • Paid — $3 in $THREE, split 50% to the holder-rewards pool / 50% to the+// treasury (see multiplayer/src/game-token.js — the platform never burns+// supply; the share that historically went to the incinerator now+// reflects back to holders instead). The server builds the split+// transaction, the player's wallet signs + broadcasts it, and the server+// verifies it on-chain before rolling. The paid spin never touches the// free-spin timer.//// Loaded as its own lazy chunk (dynamic import on first wheel interaction) so the// Solana signing path never weighs down the main /play bundle.-//-// STATUS (verified 2026-07-10): this client module is complete, but nothing-// mounts it — zero importers of `openSpinWheel` anywhere in the repo, and there-// is no `spinInfo`/`spinPrep`/`spinResult`/`spinDenied` handler on EITHER-// Colyseus room (grep multiplayer/src/rooms/*.js — zero hits) and no `spinInfo`/-// `spinFree`/`spinPaid` method on `community-net.js`/`walk-net.js`. This is not-// a wiring gap like play-intro.js/friends-panel.js were — the entire server-// side (spin RNG, the 12h free-spin cooldown ledger, the $3-in-$THREE-// split-payment transaction build + on-chain verification before granting a-// paid spin, prize/reward granting into the existing economy) has never been-// built. Mirror the boutique purchase flow's proven pattern-// (multiplayer/src/game-token.js + src/game/boutique-purchase.js: server-// builds the tx, wallet signs, server re-verifies on RPC before granting)-// rather than writing new on-chain verification logic from scratch — but do-// build it carefully and reviewed, not rushed: this moves real money. No world-// zone/NPC ("Fortune's Folly · Mainland" per this file's own header) spawns-// the interaction that would call openSpinWheel() either.import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';@@ -164,7 +152,7 @@ class SpinWheel {// sees exactly what they'll sign before the wallet prompt appears.const tkn = fmtAtomics(m.tokenAmount);const sym = m.symbol || this.info?.symbol || '$THREE';- if (tkn && this.paidSub) this.paidSub.textContent = `${tkn} ${sym} · 50% burned, 50% treasury`;+ if (tkn && this.paidSub) this.paidSub.textContent = `${tkn} ${sym} · 50% to holder rewards, 50% treasury`;this._runWalletPayment(m).catch((err) => this._payError(err));}@@ -246,9 +234,19 @@ class SpinWheel {this._prep = null;this._settleAttempts = 0;this.resultLine.textContent = '';- this._status('Preparing your payment…', '');+ this._status('Connecting your wallet…', '');this._sync();- this.net.spinPaidPrep();+ // Same connect + address-extraction step boutique-purchase.js uses — the+ // server prices the quote for a specific buyer, so it needs the address+ // before it can build anything.+ let address = wallet.publicKey?.toString?.();+ if (!address) {+ try { await wallet.connect(); } catch (err) { this._payError(err); return; }+ address = wallet.publicKey?.toString?.();+ }+ if (!address) { this._status('Could not read your wallet address.', 'err'); this.busy = false; this.phase = 'ready'; this._sync(); return; }+ this._status('Preparing your payment…', '');+ this.net.spinPaidPrep(address);}async _runWalletPayment(prep) {@@ -510,7 +508,7 @@ class SpinWheel {if (!this.info) this.paidSub.textContent = '';else if (!lvlOk) this.paidSub.textContent = `Reach level ${min} to play`;else if (!this.info.paidAvailable) this.paidSub.textContent = 'Connect a Solana wallet to buy spins';- else this.paidSub.textContent = `$${cost} in ${sym} · 50% burned, 50% treasury`;+ else this.paidSub.textContent = `$${cost} in ${sym} · 50% to holder rewards, 50% treasury`;this._syncFree();}diff --git a/src/game/wheel-station.js b/src/game/wheel-station.jsnew file mode 100644index 000000000..8c37a0d32--- /dev/null+++ b/src/game/wheel-station.js@@ -0,0 +1,161 @@+// Fortune's Folly — the Wheel of Fortune landmark for /play (W09/Task 19).+//+// A single fixed prop in the plaza (multiplayer/src/world-features.js WHEEL — the+// same coordinates the server validates proximity against, so the marker and the+// authoritative range check can never drift). Renders a simple, readable casino+// wheel silhouette, shows a contextual "E — Spin the Wheel" prompt as the player+// walks up, and lazy-imports the actual spin UI (src/game/spin-wheel-ui.js —+// pulls in @solana/web3.js for the paid path) only on the first interaction, so+// that weight never touches the initial /play bundle.++import {+ Group, Mesh, CylinderGeometry, ConeGeometry, RingGeometry, TorusGeometry,+ MeshStandardMaterial, MeshBasicMaterial, DoubleSide,+} from 'three';+import { WHEEL, wheelInRange } from '../../multiplayer/src/world-features.js';++function el(tag, props = {}) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(props)) {+ if (k === 'class') n.className = v;+ else if (k === 'text') n.textContent = v;+ else if (k === 'hidden') n.hidden = !!v;+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);+ else if (v != null) n.setAttribute(k, v);+ }+ return n;+}++export class WheelStation {+ /**+ * @param {object} opts+ * @param {import('three').Scene} opts.scene+ * @param {() => ({x,y,z})} opts.getPlayer local avatar pose+ * @param {object} opts.net CommunityNet — handed straight to the spin UI+ */+ constructor({ scene, getPlayer, net }) {+ this.scene = scene;+ this.getPlayer = getPlayer;+ this.net = net;+ this._t = 0;+ this._near = false;+ this._wheel = null; // the open SpinWheel controller, or null++ this._buildScene();+ this._buildPrompt();+ }++ _buildScene() {+ const spot = WHEEL[0];+ const g = new Group();+ g.position.set(spot.x, 0, spot.z);++ // A short plinth the wheel stands on.+ const base = new Mesh(+ new CylinderGeometry(spot.r * 0.85, spot.r, 0.5, 16),+ new MeshStandardMaterial({ color: 0x3a2a10, roughness: 0.85 }),+ );+ base.position.y = 0.25;+ base.castShadow = true;+ g.add(base);++ // The wheel face itself — a flat gold disc with alternating dark wedge+ // spokes, canted slightly toward the plaza so it reads from a distance.+ const face = new Mesh(+ new CylinderGeometry(spot.r * 0.8, spot.r * 0.8, 0.12, 20),+ new MeshStandardMaterial({ color: 0xf5c542, roughness: 0.4, metalness: 0.3 }),+ );+ face.rotation.x = Math.PI / 2;+ face.position.y = 1.7;+ face.castShadow = true;+ g.add(face);+ for (let i = 0; i < 20; i += 2) {+ const a = (i / 20) * Math.PI * 2;+ const wedge = new Mesh(+ new CylinderGeometry(spot.r * 0.8, spot.r * 0.8, 0.13, 20, 1, false, a, (Math.PI * 2) / 20),+ new MeshStandardMaterial({ color: 0x2b2f38, roughness: 0.5 }),+ );+ wedge.rotation.x = Math.PI / 2;+ wedge.position.y = 1.7;+ g.add(wedge);+ }+ const rim = new Mesh(+ new TorusGeometry(spot.r * 0.8, 0.06, 8, 24),+ new MeshStandardMaterial({ color: 0xffd76a, roughness: 0.3, metalness: 0.6 }),+ );+ rim.rotation.x = Math.PI / 2;+ rim.position.y = 1.7;+ g.add(rim);++ // A pointer flag on top so "which way is up" reads even while idle.+ const pointer = new Mesh(+ new ConeGeometry(0.14, 0.4, 4),+ new MeshBasicMaterial({ color: 0xff4d4d }),+ );+ pointer.position.set(0, 2.2, spot.r * 0.8);+ pointer.rotation.x = Math.PI;+ g.add(pointer);++ this._marker = new Mesh(+ new RingGeometry(spot.r + 0.4, spot.r + 0.6, 32),+ new MeshBasicMaterial({ color: 0xffc857, transparent: true, opacity: 0.18, side: DoubleSide }),+ );+ this._marker.rotation.x = -Math.PI / 2;+ this._marker.position.y = 0.04;+ g.add(this._marker);++ this.scene.add(g);+ this._group = g;+ this._face = face;+ }++ _buildPrompt() {+ this.btn = el('button', { class: 'ps-action wh-action', hidden: true, text: '🎡 Spin the Wheel', onclick: () => this.interact() });+ document.body.appendChild(this.btn);+ }++ tick(dt) {+ this._t += dt;+ this._face.rotation.z = this._t * 0.15; // a slow idle spin, purely decorative+ const p = this.getPlayer?.();+ const near = !!(p && wheelInRange(p.x, p.z));+ if (near !== this._near) {+ this._near = near;+ this.btn.hidden = !near || !!this._wheel;+ }+ const glow = 0.14 + Math.sin(this._t * 1.6) * 0.06;+ this._marker.material.opacity = near ? glow + 0.22 : glow;+ }++ // Public: act if in range. SYNCHRONOUS — the E-key chain in coincommunities.js+ // calls every system's interact() as `!a.interact() && !b.interact() && …`+ // to find whichever one consumed the press; a Promise is always truthy, so+ // an async return here would silently short-circuit that chain regardless of+ // whether the player was actually in range. The real lazy-import + open work+ // happens in the fire-and-forget helper below; this returns the in-range+ // verdict immediately, exactly like vehicles.interact() already does.+ interact() {+ if (!this._near) return false;+ if (!this._wheel) this._open();+ return true;+ }++ async _open() {+ this.btn.hidden = true;+ const { openSpinWheel } = await import('./spin-wheel-ui.js');+ this._wheel = openSpinWheel({ net: this.net, onClose: () => { this._wheel = null; this.btn.hidden = !this._near; } });+ }++ dispose() {+ this._wheel?.close?.();+ this._wheel = null;+ if (this._group) {+ this.scene.remove(this._group);+ this._group.traverse((n) => {+ if (n.isMesh) { n.geometry?.dispose?.(); const ms = Array.isArray(n.material) ? n.material : [n.material]; ms.forEach((m) => m?.dispose?.()); }+ });+ this._group = null;+ }+ this.btn?.remove();+ }+}diff --git a/tests/spin-wheel.test.js b/tests/spin-wheel.test.jsnew file mode 100644index 000000000..49132c541--- /dev/null+++ b/tests/spin-wheel.test.js@@ -0,0 +1,269 @@+// Wheel of Fortune server logic (W09/Task 19) — the RNG, level/cooldown/pack+// gates, and payment-settlement wiring in multiplayer/src/spin-wheel.js.+//+// game-token.js's split-payment primitives are mocked here — they make real+// Solana RPC calls and are already the exact code path the $THREE boutique+// exercises in production; this suite's job is to prove spin-wheel.js calls+// them correctly and never grants a prize without either a valid free-spin+// window or a verified on-chain payment.++import { describe, it, expect, beforeEach, vi } from 'vitest';++vi.mock('../multiplayer/src/game-token.js', () => ({+ buildSpinPayment: vi.fn(),+ verifySpinPayment: vi.fn(),+ isWalletAddress: (s) => typeof s === 'string' && s.length >= 32 && s.length <= 44,+ tokenConfigured: vi.fn(() => true),+ TOKEN_DECIMALS: 6,+ TOKEN_SYMBOL: '$THREE',+}));++const gameToken = await import('../multiplayer/src/game-token.js');+const {+ WHEEL_SEGMENTS, FREE_SPIN_COOLDOWN_MS, MIN_AVG_LEVEL, SPIN_COST_USD,+ handleSpinInfo, handleSpinFree, handleSpinPaidPrep, handleSpinPaidSettle, registerSpinHandlers,+} = await import('../multiplayer/src/spin-wheel.js');+const { newProfile, serializeProfile, restoreProfile } = await import('../multiplayer/src/economy.js');+const { WHEEL } = await import('../multiplayer/src/world-features.js');++// A profile at the wheel's exact coordinates, at (or above) the level gate so+// tests can reach the RNG/payment paths without simulating XP grinding.+function eligibleProfile() {+ const p = newProfile('acct-1');+ for (const skill of Object.keys(p.levels)) p.levels[skill] = MIN_AVG_LEVEL;+ return p;+}++function makeRoom({ profile, x = WHEEL[0].x, z = WHEEL[0].z } = {}) {+ const sent = [];+ const room = {+ state: { players: new Map([['s1', { x, z }]]) },+ econ: new Map([['s1', profile || eligibleProfile()]]),+ _spinNonces: new Map(),+ _pruneSpinNonces: vi.fn(),+ _actionOk: () => true,+ _sendInv: vi.fn(),+ _questEvent: vi.fn(),+ _persistEcon: vi.fn(),+ };+ const client = { sessionId: 's1', send: (type, msg) => sent.push({ type, msg }) };+ return { room, client, sent };+}++beforeEach(() => { vi.clearAllMocks(); });++describe('WHEEL_SEGMENTS — the paytable the client\'s fixed-angle wheel must match', () => {+ it('has exactly 20 segments, matching spin-wheel-ui.js\'s fixed wedge count', () => {+ expect(WHEEL_SEGMENTS.length).toBe(20);+ });+ it('is uniform-odds — every segment 5%, summing to exactly 100%', () => {+ expect(WHEEL_SEGMENTS.every((s) => s.oddsPct === 5)).toBe(true);+ expect(WHEEL_SEGMENTS.reduce((n, s) => n + s.oddsPct, 0)).toBe(100);+ });+ it('every segment has a positive amount and a label', () => {+ for (const s of WHEEL_SEGMENTS) {+ expect(s.label).toBeTruthy();+ expect(s.kind === 'gold' ? s.gold : s.qty).toBeGreaterThan(0);+ }+ });+});++describe('handleSpinInfo', () => {+ it('reports position/level/cooldown truthfully', () => {+ const { room, client, sent } = makeRoom();+ handleSpinInfo(room, client);+ const info = sent[0].msg;+ expect(sent[0].type).toBe('spinInfo');+ expect(info.atWheel).toBe(true);+ expect(info.eligible).toBe(true);+ expect(info.segments.length).toBe(20);+ expect(info.minLevel).toBe(MIN_AVG_LEVEL);+ expect(info.costUsd).toBe(SPIN_COST_USD);+ });+ it('reports not eligible and not at the wheel away from it, below level', () => {+ const { room, client, sent } = makeRoom({ profile: newProfile('acct-2'), x: 0, z: 0 });+ handleSpinInfo(room, client);+ const info = sent[0].msg;+ expect(info.atWheel).toBe(false);+ expect(info.eligible).toBe(false);+ });+});++describe('handleSpinFree — gates, in priority order', () => {+ it('denies not_at_wheel when away from the wheel, even if eligible', () => {+ const { room, client, sent } = makeRoom({ x: 0, z: 0 });+ handleSpinFree(room, client);+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'not_at_wheel' } });+ });+ it('denies level when at the wheel but under the average-level floor', () => {+ const { room, client, sent } = makeRoom({ profile: newProfile('acct-3') });+ handleSpinFree(room, client);+ expect(sent[0].type).toBe('spinDenied');+ expect(sent[0].msg.reason).toBe('level');+ expect(sent[0].msg.avgLevel).toBe(1);+ expect(sent[0].msg.minLevel).toBe(MIN_AVG_LEVEL);+ });+ it('denies cooldown when a free spin was already used', () => {+ const profile = eligibleProfile();+ profile.nextFreeSpinAt = Date.now() + 60_000;+ const { room, client, sent } = makeRoom({ profile });+ handleSpinFree(room, client);+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'cooldown', nextFreeSpinAt: profile.nextFreeSpinAt } });+ });+ it('denies pack_full when the pack has no room for wood, stone, or coal', () => {+ const profile = eligibleProfile();+ // Fill every slot with a non-stackable, unrelated item so nothing further fits.+ for (const s of profile.inv) { s.item = 'rod'; s.qty = 1; }+ const { room, client, sent } = makeRoom({ profile });+ handleSpinFree(room, client);+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'pack_full' } });+ });+ it('grants a real prize, sets the 12h cooldown, and persists — the success path', () => {+ const profile = eligibleProfile();+ const { room, client, sent } = makeRoom({ profile });+ const before = Date.now();+ handleSpinFree(room, client);+ expect(sent[0].type).toBe('spinResult');+ expect(sent[0].msg.mode).toBe('free');+ expect(sent[0].msg.index).toBeGreaterThanOrEqual(0);+ expect(sent[0].msg.index).toBeLessThan(20);+ expect(sent[0].msg.got).toBeGreaterThan(0);+ expect(profile.nextFreeSpinAt).toBeGreaterThanOrEqual(before + FREE_SPIN_COOLDOWN_MS);+ expect(room._sendInv).toHaveBeenCalledWith(client, profile);+ expect(room._persistEcon).toHaveBeenCalledWith('s1');+ });+ it('a second free spin immediately after denies on cooldown (no double-grant)', () => {+ const profile = eligibleProfile();+ const { room, client, sent } = makeRoom({ profile });+ handleSpinFree(room, client);+ expect(sent[0].type).toBe('spinResult');+ handleSpinFree(room, client);+ expect(sent[1].type).toBe('spinDenied');+ expect(sent[1].msg.reason).toBe('cooldown');+ });+});++describe('roll fairness — many spins land roughly uniformly across all 20 indices', () => {+ it('every index is reachable and no index dominates over a large sample', () => {+ const counts = new Array(20).fill(0);+ const N = 4000;+ for (let i = 0; i < N; i++) {+ const profile = eligibleProfile();+ const { room, client, sent } = makeRoom({ profile });+ handleSpinFree(room, client);+ counts[sent[0].msg.index]++;+ }+ expect(counts.every((c) => c > 0)).toBe(true);+ // Expected ~200/segment; a generous band catches a real bias without being flaky.+ const expected = N / 20;+ for (const c of counts) {+ expect(c).toBeGreaterThan(expected * 0.5);+ expect(c).toBeLessThan(expected * 1.5);+ }+ });+});++describe('handleSpinPaidPrep', () => {+ it('denies not_at_wheel / level / pack_full before ever touching payment', async () => {+ const away = makeRoom({ x: 0, z: 0 });+ await handleSpinPaidPrep(away.room, away.client, { wallet: '1'.repeat(32) });+ expect(away.sent[0].msg.reason).toBe('not_at_wheel');+ expect(gameToken.buildSpinPayment).not.toHaveBeenCalled();++ const underLevel = makeRoom({ profile: newProfile('acct-4') });+ await handleSpinPaidPrep(underLevel.room, underLevel.client, { wallet: '1'.repeat(32) });+ expect(underLevel.sent[0].msg.reason).toBe('level');+ expect(gameToken.buildSpinPayment).not.toHaveBeenCalled();+ });+ it('denies no_wallet when the payload carries no valid Solana address', async () => {+ const { room, client, sent } = makeRoom();+ await handleSpinPaidPrep(room, client, {});+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'no_wallet' } });+ expect(gameToken.buildSpinPayment).not.toHaveBeenCalled();+ });+ it('denies token_unavailable when the platform has no treasury configured', async () => {+ gameToken.tokenConfigured.mockReturnValueOnce(false);+ const { room, client, sent } = makeRoom();+ await handleSpinPaidPrep(room, client, { wallet: '1'.repeat(32) });+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'token_unavailable' } });+ });+ it('denies price_unavailable when buildSpinPayment cannot price the spin', async () => {+ gameToken.buildSpinPayment.mockResolvedValueOnce(null);+ const { room, client, sent } = makeRoom();+ await handleSpinPaidPrep(room, client, { wallet: '1'.repeat(32) });+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'price_unavailable' } });+ });+ it('sends the built quote/tx untouched to the client on success', async () => {+ gameToken.buildSpinPayment.mockResolvedValueOnce({+ txBase64: 'BASE64TX', quoteToken: 'QUOTE.SIG', quote: { total: '3000000' },+ });+ const wallet = '1'.repeat(32);+ const { room, client, sent } = makeRoom();+ await handleSpinPaidPrep(room, client, { wallet });+ expect(gameToken.buildSpinPayment).toHaveBeenCalledWith({ buyerWallet: wallet, usd: SPIN_COST_USD });+ expect(sent[0]).toEqual({+ type: 'spinPrep',+ msg: { tx: 'BASE64TX', tokenAmount: '3000000', symbol: '$THREE', costUsd: SPIN_COST_USD, quote: 'QUOTE.SIG' },+ });+ });+});++describe('handleSpinPaidSettle', () => {+ it('denies no_signature when the quote or signature is missing', async () => {+ const { room, client, sent } = makeRoom();+ await handleSpinPaidSettle(room, client, {});+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'no_signature' } });+ expect(gameToken.verifySpinPayment).not.toHaveBeenCalled();+ });+ it('relays the verifier\'s refusal reason verbatim on a bad/underpaid/unfound payment', async () => {+ gameToken.verifySpinPayment.mockResolvedValueOnce({ ok: false, reason: 'treasury_underpaid' });+ const { room, client, sent } = makeRoom();+ await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sig'.repeat(12) });+ expect(sent[0]).toEqual({ type: 'spinDenied', msg: { reason: 'treasury_underpaid' } });+ });+ it('grants a real prize once verified — the paid success path', async () => {+ gameToken.verifySpinPayment.mockResolvedValueOnce({ ok: true, nonce: 'nonce-1' });+ const profile = eligibleProfile();+ const { room, client, sent } = makeRoom({ profile });+ await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sig'.repeat(12) });+ expect(sent[0].type).toBe('spinResult');+ expect(sent[0].msg.mode).toBe('paid');+ expect(room._persistEcon).toHaveBeenCalledWith('s1');+ // A paid spin does NOT touch the free-spin cooldown.+ expect(profile.nextFreeSpinAt).toBe(0);+ });+ it('refuses to grant a second prize for an already-settled nonce (replay protection)', async () => {+ gameToken.verifySpinPayment.mockResolvedValue({ ok: true, nonce: 'nonce-replay' });+ const profile = eligibleProfile();+ const { room, client, sent } = makeRoom({ profile });+ await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sig'.repeat(12) });+ expect(sent[0].type).toBe('spinResult');+ await handleSpinPaidSettle(room, client, { quote: 'q', txSig: 'sig'.repeat(12) });+ expect(sent[1]).toEqual({ type: 'spinDenied', msg: { reason: 'already_settled' } });+ });+});++describe('registerSpinHandlers', () => {+ it('registers exactly the four message types spin-wheel-ui.js sends', () => {+ const handlers = new Map();+ const room = { onMessage: (type, fn) => handlers.set(type, fn) };+ registerSpinHandlers(room);+ expect([...handlers.keys()].sort()).toEqual(['spinFree', 'spinInfo', 'spinPaidPrep', 'spinPaidSettle']);+ });+});++describe('nextFreeSpinAt persistence — must survive a reconnect (unlike the ephemeral cd map)', () => {+ it('round-trips through serializeProfile/restoreProfile', () => {+ const profile = newProfile('acct-persist');+ profile.nextFreeSpinAt = 1234567890;+ const restored = restoreProfile(serializeProfile(profile), 'acct-persist');+ expect(restored.nextFreeSpinAt).toBe(1234567890);+ });+ it('a fresh profile starts with no cooldown', () => {+ expect(newProfile('x').nextFreeSpinAt).toBe(0);+ });+ it('restoreProfile clamps a corrupt negative value to 0', () => {+ const restored = restoreProfile({ nextFreeSpinAt: -999 }, 'x');+ expect(restored.nextFreeSpinAt).toBe(0);+ });+});