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: friends, play-pass, token payments, presence, cosmetics, spin-wheel, game systems + tests
nirholas5d8e9c1a2b7a
diff --git a/api/_lib/account-auth.js b/api/_lib/account-auth.jsnew file mode 100644index 000000000..01e743bf5--- /dev/null+++ b/api/_lib/account-auth.js@@ -0,0 +1,14 @@+// Resolve the calling account for endpoints that accept either a browser+// session (cookie) or a programmatic bearer token (OAuth / API key). Returns+// { userId } or null. Mirrors the inline pattern used across api/threews/* but+// shared so the friends endpoints stay consistent.++import { getSessionUser, authenticateBearer, extractBearer } from './auth.js';++export async function resolveAccount(req, res) {+ const session = await getSessionUser(req, res);+ if (session) return { userId: session.id, source: 'session' };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId, source: bearer.source };+ return null;+}diff --git a/api/_lib/env.js b/api/_lib/env.jsindex d36f5bd16..ac45f1227 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -100,6 +100,22 @@ export const env = {return opt('CRON_SECRET');},+ // ── multiplayer bridge (presence + live DM delivery) ─────────────────────+ // Shared HMAC secret between this API and the standalone Colyseus server. The+ // API mints short-lived presence tickets (api/friends/presence-ticket) the+ // realm rooms verify before publishing a player's presence, and signs the+ // internal notify webhook. Falls back to HOLDER_PASS_SECRET (already shared+ // with the multiplayer process) so a single secret configures both gates.+ get MULTIPLAYER_SHARED_SECRET() {+ return opt('MULTIPLAYER_SHARED_SECRET') || opt('HOLDER_PASS_SECRET') || 'dev-insecure-multiplayer-secret';+ },+ // Base URL of the multiplayer server's internal API, used to push live DMs /+ // friend events to connected clients. Optional: when unset, delivery falls+ // back to the client's polling backstop and the durable offline queue.+ get MULTIPLAYER_INTERNAL_URL() {+ return trimSlash(opt('MULTIPLAYER_INTERNAL_URL') || opt('MULTIPLAYER_URL'));+ },+// Platform fee basis points for agent monetization (100 bps = 1%).// Read by api/_lib/fee.js on cold-start. Default 250 (2.5%).get PLATFORM_FEE_BPS() {@@ -538,6 +554,43 @@ export const env = {return opt('MODELSCOPE_API_KEY');},+ // ── $THREE on-chain token layer (api/_lib/token/*) ────────────────────────+ // Shared primitives for premium token-priced actions (paid spins, token+ // marketplace sales). Centralized here so no mint/treasury/burn literals are+ // scattered across endpoints. The platform $THREE mint is the same constant+ // used by api/rider/* and api/three-token; override for devnet/test mints.+ get THREE_TOKEN_MINT() {+ return opt('THREE_TOKEN_MINT', 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');+ },+ // pump.fun mints are 6-decimal. Override only if a non-pump mint is configured.+ get THREE_TOKEN_DECIMALS() {+ return parseInt(opt('THREE_TOKEN_DECIMALS', '6'), 10);+ },+ // Treasury wallet that receives the treasury share of every split. REQUIRED in+ // production — token/config.js fails loudly (mirrors HOLDER_PASS_SECRET) rather+ // than silently routing funds to a placeholder.+ get THREE_TREASURY_WALLET() {+ return opt('THREE_TREASURY_WALLET');+ },+ // Burn address — defaults to the Solana incinerator, whose associated token+ // account is unspendable (no key exists), so tokens transferred there are+ // permanently removed from circulation. Verifiable as a plain destination.+ get THREE_BURN_ADDRESS() {+ return opt('THREE_BURN_ADDRESS', '1nc1nerator11111111111111111111111111111111');+ },+ // HMAC secret used to sign payment quotes so a client cannot tamper with the+ // quoted token amount or split after the server prices it. REQUIRED in+ // production (token/quote.js boot guard). NEVER log this value.+ get THREE_QUOTE_SECRET() {+ return opt('THREE_QUOTE_SECRET');+ },+ // Validity window (seconds) for an issued quote. Short enough that a quoted+ // price can't be exploited after the market moves; long enough to sign + send+ // one transaction. Default 90s.+ get THREE_QUOTE_TTL_S() {+ return parseInt(opt('THREE_QUOTE_TTL_S', '90'), 10);+ },+// Rider payment gate — Solana wallet that receives $THREE, and Helius webhook secret.get RIDER_VAULT_ADDRESS() {return opt('RIDER_VAULT_ADDRESS');diff --git a/api/_lib/friends-store.js b/api/_lib/friends-store.jsnew file mode 100644index 000000000..fef2e56f6--- /dev/null+++ b/api/_lib/friends-store.js@@ -0,0 +1,285 @@+// Friends store — the durable social graph, direct-message history, and mute+// list. Every function takes the authenticated account id (a users.id UUID) as+// its first argument and is responsible for keeping the graph consistent in both+// directions. Presence (online / current realm) is volatile and lives in Redis;+// see presence-store.js. The API endpoints in api/friends/* are thin wrappers+// around these queries.++import { sql } from './db.js';++// Columns safe to expose for any account other than the caller. Never leak+// email, wallet, plan, or admin flags through the social graph.+const PUBLIC_USER_COLS = sql`u.id, u.display_name, u.username, u.avatar_url`;++function toProfile(row) {+ if (!row) return null;+ return {+ id: row.id,+ name: row.display_name || row.username || 'Anonymous',+ username: row.username || null,+ avatarUrl: row.avatar_url || null,+ };+}++// ── search ───────────────────────────────────────────────────────────────────+// Find accounts by display name or username, excluding the caller and anyone+// they've already muted. The caller's existing relationship to each hit is+// annotated so the UI can render "Add" vs "Pending" vs "Friends" inline.+export async function searchUsers(meId, q, limit = 12) {+ const term = String(q || '').trim();+ if (term.length < 2) return [];+ const like = `%${term.replace(/[%_]/g, (m) => `\\${m}`)}%`;+ const rows = await sql`+ select ${PUBLIC_USER_COLS}+ from users u+ where u.deleted_at is null+ and u.id <> ${meId}+ and (u.display_name ilike ${like} or u.username ilike ${like})+ order by+ (lower(u.username) = lower(${term}) or lower(u.display_name) = lower(${term})) desc,+ length(coalesce(u.username, u.display_name)) asc+ limit ${Math.min(Math.max(limit, 1), 25)}+ `;+ if (!rows.length) return [];++ const ids = rows.map((r) => r.id);+ const rels = await sql`+ select requester_id, addressee_id, status from friendships+ where (requester_id = ${meId} and addressee_id = any(${ids}))+ or (addressee_id = ${meId} and requester_id = any(${ids}))+ `;+ const relFor = new Map();+ for (const r of rels) {+ const other = r.requester_id === meId ? r.addressee_id : r.requester_id;+ if (r.status === 'accepted') relFor.set(other, 'friends');+ else relFor.set(other, r.requester_id === meId ? 'outgoing' : 'incoming');+ }++ return rows.map((r) => ({ ...toProfile(r), relationship: relFor.get(r.id) || 'none' }));+}++// ── requests ───────────────────────────────────────────────────────────────+// Send a friend request. Returns { status } where status is:+// 'requested' — a fresh pending invite was created+// 'accepted' — the other account had already invited us, so this auto-accepts+// 'exists' — an identical pending/accepted relationship already existed+// Guards self-add, unknown targets, and duplicate requests in either direction.+export async function sendRequest(meId, toId) {+ if (toId === meId) {+ throw Object.assign(new Error('You cannot add yourself.'), { status: 400, code: 'self_add' });+ }+ const [target] = await sql`select id from users where id = ${toId} and deleted_at is null`;+ if (!target) throw Object.assign(new Error('User not found.'), { status: 404, code: 'not_found' });++ // Look at the relationship from either direction first.+ const [existing] = await sql`+ select id, requester_id, addressee_id, status from friendships+ where (requester_id = ${meId} and addressee_id = ${toId})+ or (requester_id = ${toId} and addressee_id = ${meId})+ limit 1+ `;+ if (existing) {+ if (existing.status === 'accepted') return { status: 'exists', relationship: 'friends' };+ // Pending. If they invited us, accepting their invite is the right move.+ if (existing.requester_id === toId) {+ await sql`update friendships set status = 'accepted', responded_at = now() where id = ${existing.id}`;+ return { status: 'accepted', relationship: 'friends', friendshipId: existing.id };+ }+ return { status: 'exists', relationship: 'outgoing', friendshipId: existing.id };+ }++ const [row] = await sql`+ insert into friendships (requester_id, addressee_id, status)+ values (${meId}, ${toId}, 'pending')+ returning id+ `;+ return { status: 'requested', relationship: 'outgoing', friendshipId: row.id };+}++// Accept a pending request addressed to me. Returns the now-friend's profile.+export async function acceptRequest(meId, otherId) {+ const [row] = await sql`+ update friendships set status = 'accepted', responded_at = now()+ where requester_id = ${otherId} and addressee_id = ${meId} and status = 'pending'+ returning id+ `;+ if (!row) throw Object.assign(new Error('No pending request from that user.'), { status: 404, code: 'no_request' });+ const [u] = await sql`select ${PUBLIC_USER_COLS} from users u where u.id = ${otherId}`;+ return { friendshipId: row.id, friend: toProfile(u) };+}++// Decline a pending incoming request — deletes it so a future request is clean.+export async function declineRequest(meId, otherId) {+ const rows = await sql`+ delete from friendships+ where requester_id = ${otherId} and addressee_id = ${meId} and status = 'pending'+ returning id+ `;+ if (!rows.length) throw Object.assign(new Error('No pending request from that user.'), { status: 404, code: 'no_request' });+ return { ok: true };+}++// Remove an accepted friend OR cancel a pending outgoing request — both are a+// row delete keyed to the unordered pair.+export async function removeFriend(meId, otherId) {+ await sql`+ delete from friendships+ where (requester_id = ${meId} and addressee_id = ${otherId})+ or (requester_id = ${otherId} and addressee_id = ${meId})+ `;+ return { ok: true };+}++export async function areFriends(meId, otherId) {+ const [row] = await sql`+ select 1 from friendships+ where status = 'accepted'+ and ((requester_id = ${meId} and addressee_id = ${otherId})+ or (requester_id = ${otherId} and addressee_id = ${meId}))+ limit 1+ `;+ return !!row;+}++// ── graph listing ─────────────────────────────────────────────────────────+// One round-trip view of the caller's whole graph: accepted friends, incoming+// pending requests, and outgoing pending requests. Unread DM counts per friend+// are folded in so the UI can badge threads without a second call. Presence is+// merged at the endpoint layer (it lives in Redis, not Postgres).+export async function listGraph(meId) {+ const rows = await sql`+ select f.id as friendship_id, f.status, f.requester_id, f.created_at, f.responded_at,+ ${PUBLIC_USER_COLS}+ from friendships f+ join users u on u.id = (case when f.requester_id = ${meId} then f.addressee_id else f.requester_id end)+ where (f.requester_id = ${meId} or f.addressee_id = ${meId})+ and u.deleted_at is null+ order by f.created_at desc+ `;++ const unread = await unreadCounts(meId);++ const friends = [];+ const incoming = [];+ const outgoing = [];+ for (const r of rows) {+ const profile = toProfile(r);+ const entry = { ...profile, friendshipId: r.friendship_id };+ if (r.status === 'accepted') {+ friends.push({ ...entry, since: r.responded_at || r.created_at, unread: unread[r.id] || 0 });+ } else if (r.requester_id === meId) {+ outgoing.push({ ...entry, requestedAt: r.created_at });+ } else {+ incoming.push({ ...entry, requestedAt: r.created_at });+ }+ }+ friends.sort((a, b) => (a.name || '').localeCompare(b.name || ''));+ return { friends, incoming, outgoing };+}++// ── direct messages ──────────────────────────────────────────────────────+// Fetch a thread between me and `otherId`, oldest→newest, capped to `limit`.+// `beforeId` paginates older history (cursor = the oldest id currently shown).+export async function getThread(meId, otherId, { limit = 50, beforeId = null } = {}) {+ const cap = Math.min(Math.max(limit, 1), 100);+ const rows = beforeId+ ? await sql`+ select id, sender_id, recipient_id, body, created_at, read_at+ from direct_messages+ where ((sender_id = ${meId} and recipient_id = ${otherId})+ or (sender_id = ${otherId} and recipient_id = ${meId}))+ and created_at < (select created_at from direct_messages where id = ${beforeId})+ order by created_at desc+ limit ${cap}+ `+ : await sql`+ select id, sender_id, recipient_id, body, created_at, read_at+ from direct_messages+ where (sender_id = ${meId} and recipient_id = ${otherId})+ or (sender_id = ${otherId} and recipient_id = ${meId})+ order by created_at desc+ limit ${cap}+ `;+ return rows.reverse().map((m) => ({+ id: m.id,+ from: m.sender_id,+ to: m.recipient_id,+ body: m.body,+ ts: m.created_at,+ mine: m.sender_id === meId,+ read: !!m.read_at,+ }));+}++// Persist a DM. Returns the stored row, or null when the recipient has muted the+// sender (the message is silently dropped — never stored, never delivered). The+// caller is responsible for confirming `meId` and `toId` are friends first.+export async function sendDM(meId, toId, body) {+ if (await isMutedBy(toId, meId)) return null; // recipient muted me → suppress+ const [row] = await sql`+ insert into direct_messages (sender_id, recipient_id, body)+ values (${meId}, ${toId}, ${body})+ returning id, sender_id, recipient_id, body, created_at+ `;+ return {+ id: row.id,+ from: row.sender_id,+ to: row.recipient_id,+ body: row.body,+ ts: row.created_at,+ };+}++// Mark every message from `otherId` to me as read. Returns count cleared.+export async function markThreadRead(meId, otherId) {+ const rows = await sql`+ update direct_messages set read_at = now()+ where recipient_id = ${meId} and sender_id = ${otherId} and read_at is null+ returning id+ `;+ return rows.length;+}++// Per-sender unread counts for the caller → { senderId: count }.+export async function unreadCounts(meId) {+ const rows = await sql`+ select sender_id, count(*)::int as n+ from direct_messages+ where recipient_id = ${meId} and read_at is null+ group by sender_id+ `;+ const out = {};+ for (const r of rows) out[r.sender_id] = r.n;+ return out;+}++// ── mutes (Task 14) ──────────────────────────────────────────────────────+// Does `muterId` mute `mutedId`? Used to suppress inbound DMs from the muted+// account. Reads are hot (one per DM send) so keep the query trivial.+export async function isMutedBy(muterId, mutedId) {+ const [row] = await sql`+ select 1 from user_mutes where muter_id = ${muterId} and muted_id = ${mutedId} limit 1+ `;+ return !!row;+}++export async function muteUser(meId, targetId) {+ if (targetId === meId) {+ throw Object.assign(new Error('You cannot mute yourself.'), { status: 400, code: 'self_mute' });+ }+ await sql`+ insert into user_mutes (muter_id, muted_id) values (${meId}, ${targetId})+ on conflict (muter_id, muted_id) do nothing+ `;+ return { ok: true };+}++export async function unmuteUser(meId, targetId) {+ await sql`delete from user_mutes where muter_id = ${meId} and muted_id = ${targetId}`;+ return { ok: true };+}++export async function listMutes(meId) {+ const rows = await sql`select muted_id from user_mutes where muter_id = ${meId}`;+ return rows.map((r) => r.muted_id);+}diff --git a/api/_lib/migrations/2026-06-01-friends.sql b/api/_lib/migrations/2026-06-01-friends.sqlnew file mode 100644index 000000000..ca49487dd--- /dev/null+++ b/api/_lib/migrations/2026-06-01-friends.sql@@ -0,0 +1,62 @@+-- Migration: account-level friends graph, direct messages, and mute list.+--+-- Friends are keyed to accounts (users.id), not ephemeral session/socket ids, so+-- a friendship survives reconnects and realm changes. Presence + which realm a+-- friend is in is volatile and lives in Redis (see api/_lib/presence-store.js);+-- only the durable social graph and the message history live here.++begin;++-- A single row models the relationship in both directions. `requester_id` sent+-- the invite; `addressee_id` received it. While `status = 'pending'` only the+-- addressee may accept/decline. Once `accepted`, both sides see each other as a+-- friend regardless of which column they sit in. Declining or removing deletes+-- the row outright (no tombstone) so a fresh request can be sent later.+create table if not exists friendships (+ id uuid primary key default gen_random_uuid(),+ requester_id uuid not null references users(id) on delete cascade,+ addressee_id uuid not null references users(id) on delete cascade,+ status text not null default 'pending' check (status in ('pending', 'accepted')),+ created_at timestamptz not null default now(),+ responded_at timestamptz,+ constraint friendships_no_self check (requester_id <> addressee_id),+ constraint friendships_pair_uniq unique (requester_id, addressee_id)+);+-- "who wants to be my friend" (incoming) and "who have I asked" (outgoing) ++-- "list my friends" all key off one side of the pair plus status.+create index if not exists friendships_addressee_idx on friendships (addressee_id, status);+create index if not exists friendships_requester_idx on friendships (requester_id, status);++-- Direct messages between two accounts. Delivered live over the socket when the+-- recipient is online (see social-hub on the multiplayer server) and always+-- persisted here so an offline recipient reads them on next login. `read_at`+-- drives unread badges and is stamped when the recipient opens the thread.+create table if not exists direct_messages (+ id uuid primary key default gen_random_uuid(),+ sender_id uuid not null references users(id) on delete cascade,+ recipient_id uuid not null references users(id) on delete cascade,+ body text not null,+ created_at timestamptz not null default now(),+ read_at timestamptz+);+-- A thread is every message between an unordered pair, newest first. Indexing on+-- the canonical (least, greatest) ordering lets either direction hit one index.+create index if not exists dm_pair_idx+ on direct_messages (least(sender_id, recipient_id), greatest(sender_id, recipient_id), created_at desc);+-- Unread badge: count messages addressed to me that I haven't opened yet.+create index if not exists dm_unread_idx+ on direct_messages (recipient_id, sender_id) where read_at is null;++-- Mute list (Task 14): if `muter_id` mutes `muted_id`, the muted account's+-- direct messages are suppressed for the muter — never delivered, never stored+-- on the muter's side, and never counted as unread. Mutually independent: a mute+-- by A does not stop A from messaging B.+create table if not exists user_mutes (+ muter_id uuid not null references users(id) on delete cascade,+ muted_id uuid not null references users(id) on delete cascade,+ created_at timestamptz not null default now(),+ primary key (muter_id, muted_id),+ constraint user_mutes_no_self check (muter_id <> muted_id)+);++commit;diff --git a/api/_lib/migrations/2026-06-01-token-payments.sql b/api/_lib/migrations/2026-06-01-token-payments.sqlnew file mode 100644index 000000000..0357e00f0--- /dev/null+++ b/api/_lib/migrations/2026-06-01-token-payments.sql@@ -0,0 +1,56 @@+-- Migration: token_payments — settled $THREE on-chain payments ledger.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-06-01-token-payments.sql+-- Idempotent.+--+-- Records every verified token payment for the premium-action layer (Task 18),+-- consumed by Task 19 (paid spins) and Task 20 (token-priced listings). One row+-- per settled payment. The UNIQUE constraints on nonce and tx_signature are the+-- source of truth for replay / double-submit protection — a second settle of the+-- same quote or transaction violates them and is surfaced as already_settled.+--+-- No secrets are stored: only public on-chain facts (amounts, destinations via+-- the splits jsonb, tx signature) plus the quoted USD/price for reconciliation.++begin;++create table if not exists token_payments (+ id uuid primary key default gen_random_uuid(),+ -- Nullable: a payment may originate from a wallet not linked to a user row.+ user_id uuid references users(id) on delete set null,+ payer_wallet text,+ -- What the payment unlocked: 'spin', 'marketplace_sale', etc.+ purpose text not null,+ mint text not null,+ decimals int not null,+ -- Quoted USD amount and the live token price at quote time (for audit/recon).+ usd numeric(20, 6) not null,+ price_usd numeric(38, 18) not null,+ -- Total charged, in token atomics (string-safe via numeric).+ total_atomics numeric(40, 0) not null,+ -- Resolved split legs: [{ role, address, bps, atomics }].+ splits jsonb not null,+ -- Per-quote nonce (also the on-chain memo) and the settled transaction.+ nonce text not null unique,+ tx_signature text not null unique,+ network text not null default 'mainnet',+ slot bigint,+ -- Optional link back to the spin / listing the payment settled.+ ref_type text,+ ref_id text,+ confirmed_at timestamptz not null default now(),+ created_at timestamptz not null default now()+);++create index if not exists token_payments_purpose_created+ on token_payments (purpose, created_at desc);++create index if not exists token_payments_user+ on token_payments (user_id, created_at desc);++create index if not exists token_payments_ref+ on token_payments (ref_type, ref_id);++create index if not exists token_payments_payer+ on token_payments (payer_wallet, created_at desc);++commit;diff --git a/api/_lib/play-pass.js b/api/_lib/play-pass.jsnew file mode 100644index 000000000..b6a1d7e91--- /dev/null+++ b/api/_lib/play-pass.js@@ -0,0 +1,148 @@+// Play pass — the wallet-first entry credential for /play.+//+// Two short-lived, HMAC-signed tokens live here, both keyed on the same shared+// secret as the holder pass (HOLDER_PASS_SECRET) so the standalone Colyseus+// process can verify them with nothing but that secret — no Solana RPC, no DB:+//+// 1. NONCE — issued by GET /api/play/nonce, embedded in the message the+// wallet signs, and handed back to POST /api/play/verify. Self-verifying+// (HMAC + exp) so we never need a cross-instance nonce store on serverless.+// 2. PLAY PASS — minted by POST /api/play/verify once a wallet has both proven+// ownership (ed25519 signature over the nonce) and cleared the game-token+// balance floor. Sealed { wallet, mint, balance, tier:'play', iat, exp } so+// the game server (multiplayer/src/play-pass.js) admits the player and binds+// the verified wallet as their account id without re-checking the chain.+//+// Format (both tokens): base64url(JSON(payload)) + '.' + base64url(HMAC-SHA256).+// The payload's `k` field namespaces the two so a nonce can never be replayed as+// a pass or vice-versa. Keep verifyPlayPass in the game server byte-compatible+// with signPlayPass here.++import crypto from 'node:crypto';++// The game token a wallet must hold to enter, and how much of it. PLAY_GATE_MINT+// is the canonical knob; it falls back to THREE_MINT (the platform's own token)+// so pinning $THREE in one place lights up the gate. An empty mint means the+// gate is OFF — /play stays open, exactly as before it was pinned.+export const PLAY_GATE_MINT = (process.env.PLAY_GATE_MINT || process.env.THREE_MINT || '').trim();+// Minimum whole-token balance. The world guide asks for ≥ 1 unit of the token.+export const PLAY_GATE_MIN = (() => {+ const n = Number(process.env.PLAY_GATE_MIN);+ return Number.isFinite(n) && n > 0 ? n : 1;+})();++// A nonce is single-use in spirit but stateless in fact (no shared store on+// serverless), so keep its window tight: long enough to connect a wallet and+// approve a signature, short enough that a captured nonce is near-worthless.+const NONCE_TTL_S = 5 * 60;+// Lifetime of a minted pass — long enough to finish loading into the world after+// the check, short enough that a wallet that offloads its tokens can't ride an+// old pass for long. The game server re-checks balance on a cadence too.+const PASS_TTL_S = 10 * 60;++const DEV_SECRET = 'three-ws-holder-pass-dev-secret';++let _warned = false;+function secret() {+ const s = process.env.HOLDER_PASS_SECRET;+ if (s) return s;+ // Fail closed in production: minting credentials with a publicly-known secret+ // would let anyone forge entry. wrap() turns this throw into a 500.+ if (process.env.NODE_ENV === 'production') {+ throw new Error(+ '[play-pass] HOLDER_PASS_SECRET is required in production — refusing to mint passes with the dev secret.',+ );+ }+ if (!_warned) {+ _warned = true;+ console.warn(+ '[play-pass] HOLDER_PASS_SECRET is not set — using the insecure dev secret. ' ++ 'Set HOLDER_PASS_SECRET in production or the play gate can be forged.',+ );+ }+ return DEV_SECRET;+}++function b64url(buf) {+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+}++function hmac(body) {+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());+}++function safeEqual(a, b) {+ const ba = Buffer.from(a);+ const bb = Buffer.from(b);+ if (ba.length !== bb.length) return false;+ return crypto.timingSafeEqual(ba, bb);+}++function seal(payload) {+ const body = b64url(JSON.stringify(payload));+ return `${body}.${hmac(body)}`;+}++function open(token, kind) {+ if (typeof token !== 'string' || token.length < 16 || token.length > 4096) return null;+ const dot = token.indexOf('.');+ if (dot <= 0) return null;+ const body = token.slice(0, dot);+ const sig = token.slice(dot + 1);+ if (!safeEqual(sig, hmac(body))) return null;+ let payload;+ try {+ payload = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));+ } catch {+ return null;+ }+ if (!payload || typeof payload !== 'object' || payload.k !== kind) return null;+ const now = Date.now() / 1000;+ if (typeof payload.exp !== 'number' || payload.exp < now) return null;+ if (typeof payload.iat !== 'number' || payload.iat > now + 60) return null;+ return payload;+}++/**+ * Issue a fresh sign-in nonce.+ * @returns {{ nonce: string, exp: number }} the self-verifying nonce token + its+ * epoch-seconds expiry. The whole `nonce` string is what the wallet signs and+ * what the client returns to /verify.+ */+export function issueNonce() {+ const now = Math.floor(Date.now() / 1000);+ return {+ nonce: seal({ k: 'play-nonce', r: crypto.randomBytes(16).toString('hex'), iat: now, exp: now + NONCE_TTL_S }),+ exp: now + NONCE_TTL_S,+ };+}++/**+ * Verify a nonce token. Returns its payload or null when missing, tampered, or+ * expired.+ * @param {unknown} nonce+ */+export function verifyNonce(nonce) {+ return open(nonce, 'play-nonce');+}++/**+ * Seal a verified, token-holding wallet into a play pass.+ * @param {{ wallet: string, mint: string, balance: number }} claims+ * @returns {string} the compact pass token+ */+export function signPlayPass({ wallet, mint, balance }) {+ const now = Math.floor(Date.now() / 1000);+ return seal({+ k: 'play-pass',+ tier: 'play',+ wallet,+ mint,+ balance: Math.round((Number(balance) || 0) * 1e6) / 1e6,+ // Signed so the game server displays the real requirement, never a+ // client-supplied one.+ minBalance: PLAY_GATE_MIN,+ iat: now,+ exp: now + PASS_TTL_S,+ });+}diff --git a/api/_lib/presence-store.js b/api/_lib/presence-store.jsnew file mode 100644index 000000000..7afbd17e8--- /dev/null+++ b/api/_lib/presence-store.js@@ -0,0 +1,120 @@+// Presence store — the volatile half of the friends system. Who is online and+// which realm they're in changes by the second and is shared across every+// realm-room instance, so it lives in Redis (Upstash REST), not Postgres.+//+// Ownership: the standalone multiplayer server is the source of truth. When a+// player joins a realm room it verifies their presence ticket (minted here),+// then writes `presence:<userId>` with a short TTL and refreshes it on a+// heartbeat; on leave it deletes the key. This API only ever READS presence+// (to annotate the friends list) and MINTS the tickets — it never writes+// presence itself, so a stale process can't claim a user is online forever.+//+// This module also signs the tickets and fires the internal notify webhook the+// API uses to push live DMs / friend events to the multiplayer server.++import { Redis } from '@upstash/redis';+import { env } from './env.js';+import { hmacSha256, constantTimeEquals } from './crypto.js';++const PRESENCE_PREFIX = 'presence:';+const TICKET_TTL_SEC = 600; // 10 min — the client refreshes well before expiry++let _redis = null;+let _redisTried = false;+function redis() {+ if (_redisTried) return _redis;+ _redisTried = true;+ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {+ _redis = new Redis({ url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN });+ }+ return _redis;+}++// ── presence reads ──────────────────────────────────────────────────────────+// Resolve presence for a set of account ids → { id: { online, realm } }. Ids+// without a live key are reported offline. Tolerant of a Redis outage: returns+// everyone offline rather than throwing, so the friends list still renders.+export async function readPresence(userIds) {+ const ids = [...new Set((userIds || []).filter(Boolean))];+ const out = {};+ for (const id of ids) out[id] = { online: false, realm: null };+ if (!ids.length) return out;+ const r = redis();+ if (!r) return out;+ try {+ const keys = ids.map((id) => PRESENCE_PREFIX + id);+ const vals = await r.mget(...keys);+ ids.forEach((id, i) => {+ const v = vals[i];+ if (!v) return;+ const rec = typeof v === 'string' ? safeParse(v) : v;+ if (rec && typeof rec === 'object') {+ out[id] = { online: true, realm: rec.realm || null };+ }+ });+ } catch (err) {+ console.warn('[presence] read failed:', err?.message);+ }+ return out;+}++function safeParse(s) {+ try {+ return JSON.parse(s);+ } catch {+ return null;+ }+}++// ── presence tickets ──────────────────────────────────────────────────────+// A presence ticket proves to the multiplayer server that the bearer is a+// specific authenticated account, without that server needing to read our+// session cookie or call back to verify. Format: base64url(JSON{uid,exp}).base64url(hmac).+export async function signPresenceTicket(userId) {+ const exp = Math.floor(Date.now() / 1000) + TICKET_TTL_SEC;+ const payload = base64url(JSON.stringify({ uid: userId, exp }));+ const sig = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, payload);+ return { token: `${payload}.${sig}`, expiresIn: TICKET_TTL_SEC };+}++// Verify a ticket and return its userId, or null. Mirrored byte-for-byte on the+// multiplayer side (multiplayer/src/presence-token.js); keep the two in sync.+export async function verifyPresenceTicket(token) {+ if (typeof token !== 'string' || !token.includes('.')) return null;+ const [payload, sig] = token.split('.');+ if (!payload || !sig) return null;+ const expected = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, payload);+ if (!constantTimeEquals(sig, expected)) return null;+ const data = safeParse(Buffer.from(payload, 'base64url').toString('utf8'));+ if (!data || !data.uid || !data.exp) return null;+ if (data.exp < Math.floor(Date.now() / 1000)) return null;+ return data.uid;+}++function base64url(s) {+ return Buffer.from(s, 'utf8').toString('base64url');+}++// ── live delivery ──────────────────────────────────────────────────────────+// Ask the multiplayer server to push an event to a connected account. Used for+// live DM delivery and friend-request/accept toasts. Best-effort and fire-and-+// forget: the recipient may be offline (durable queue covers them on next login)+// or the bridge may be unconfigured. Never throws into the request path.+export async function notifyMultiplayer(type, toUserId, payload = {}) {+ const base = env.MULTIPLAYER_INTERNAL_URL;+ if (!base) return { delivered: false, reason: 'unconfigured' };+ try {+ const sig = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, `notify:${toUserId}:${type}`);+ const res = await fetch(`${base}/internal/notify`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-mp-signature': sig },+ body: JSON.stringify({ type, to: toUserId, payload }),+ signal: AbortSignal.timeout(2500),+ });+ if (!res.ok) return { delivered: false, reason: `http_${res.status}` };+ const body = await res.json().catch(() => ({}));+ return { delivered: !!body?.delivered, reason: body?.reason };+ } catch (err) {+ return { delivered: false, reason: err?.name === 'TimeoutError' ? 'timeout' : 'error' };+ }+}diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 2f93a9ad8..183620bf0 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -77,6 +77,9 @@ export const limits = {getLimiter('avatar:rollback', { limit: 10, window: '1 h' }).limit(userId),chatUser: (userId) => getLimiter('chat:user', { limit: 40, window: '1 m' }).limit(userId),chatIp: (ip) => getLimiter('chat:ip', { limit: 60, window: '1 m' }).limit(ip),+ // Direct messages between friends — its own bucket so DM spam can't starve+ // world-chat posting and vice versa. Mirrors world chat's order of magnitude.+ dmSend: (userId) => getLimiter('dm:send', { limit: 30, window: '1 m' }).limit(userId),// Demo /api/x402-pay — agent wallet pays real USDC per call, so we keep the// per-IP burst small (6/min ≈ $0.006/min) and rely on the agent wallet// balance as the global ceiling.diff --git a/api/_lib/token/config.js b/api/_lib/token/config.jsnew file mode 100644index 000000000..9f624d674--- /dev/null+++ b/api/_lib/token/config.js@@ -0,0 +1,146 @@+// $THREE on-chain token layer — shared config + split policy.+//+// Centralizes the mint, decimals, treasury wallet, and burn address so no+// literal addresses are scattered across the paid-action endpoints (Task 19+// paid spins, Task 20 token-priced listings). Mirrors the HOLDER_PASS_SECRET+// boot guard: a value that, if wrong/unset, would route real funds to the+// wrong place fails loudly in production rather than silently mis-paying.++import { env } from '../env.js';++export const TOKEN_MINT = env.THREE_TOKEN_MINT;+export const TOKEN_DECIMALS = env.THREE_TOKEN_DECIMALS;+export const TOKEN_SYMBOL = '$THREE';++// Smallest-unit multiplier (10 ** decimals) as a BigInt for atomics math.+export const ATOMICS_PER_TOKEN = 10n ** BigInt(TOKEN_DECIMALS);++function badRequest(message) {+ const e = new Error(message);+ e.status = 400;+ e.code = 'bad_request';+ return e;+}++// ── Required addresses (fail-closed in production) ──────────────────────────++let _treasuryWarned = false;+/**+ * Treasury wallet that receives the treasury share of every split.+ * Production MUST set THREE_TREASURY_WALLET; otherwise we'd route the platform's+ * cut to a placeholder. In dev we fall back to the burn address so the split+ * still has two valid destinations and no real wallet is silently credited.+ */+export function treasuryWallet() {+ const w = env.THREE_TREASURY_WALLET;+ if (w) return w;+ if (process.env.NODE_ENV === 'production') {+ throw new Error(+ '[token] THREE_TREASURY_WALLET is required in production — refusing to route treasury funds to an unset address.',+ );+ }+ if (!_treasuryWarned) {+ _treasuryWarned = true;+ console.warn(+ '[token] THREE_TREASURY_WALLET is not set — falling back to the burn address for dev. ' ++ 'Set THREE_TREASURY_WALLET in production or the treasury share is burned.',+ );+ }+ return burnAddress();+}++/** The burn sink. Defaults to the Solana incinerator (unspendable ATA). */+export function burnAddress() {+ return env.THREE_BURN_ADDRESS;+}++// ── Split policy ────────────────────────────────────────────────────────────+//+// Each policy is an ordered list of legs { role, bps }. bps across legs must+// sum to 10_000. Roles 'burn' and 'treasury' resolve to the config addresses+// above; 'seller' resolves to a per-call address (a marketplace listing's+// payout wallet). Tasks 19/20 reuse the same verified-payment path by naming a+// different policy here — the split ratio is a parameter, not a fork of logic.+export const SPLIT_POLICIES = Object.freeze({+ // Task 19 — paid wheel spins: half burned, half to treasury.+ spin: [+ { role: 'burn', bps: 5000 },+ { role: 'treasury', bps: 5000 },+ ],+ // Task 20 — token-priced marketplace sales: seller keeps 95%, 5% to treasury.+ marketplace_sale: [+ { role: 'seller', bps: 9500 },+ { role: 'treasury', bps: 500 },+ ],+});++function resolveRole(role, { sellerWallet } = {}) {+ if (role === 'burn') return burnAddress();+ if (role === 'treasury') return treasuryWallet();+ if (role === 'seller') {+ if (!sellerWallet) throw badRequest('sellerWallet is required for this split policy');+ return sellerWallet;+ }+ throw new Error(`[token] unknown split role: ${role}`);+}++/**+ * Resolve a named policy into concrete legs with destination addresses.+ * @returns {{ role: string, bps: number, address: string }[]}+ */+export function resolveSplitLegs(policyName, opts = {}) {+ const policy = SPLIT_POLICIES[policyName];+ if (!policy) throw badRequest(`unknown split policy: ${policyName}`);+ const sum = policy.reduce((s, l) => s + l.bps, 0);+ // Defensive: a mis-edited policy must never silently under/over-allocate.+ if (sum !== 10_000)+ throw new Error(`[token] split policy ${policyName} bps sum ${sum} != 10000`);+ return policy.map((leg) => ({+ role: leg.role,+ bps: leg.bps,+ address: resolveRole(leg.role, opts),+ }));+}++/**+ * Distribute a total (atomics) across legs by bps. Any rounding remainder is+ * assigned to the highest-bps leg so the per-leg atomics always sum to exactly+ * the total — no dust is created or lost.+ * @param {bigint|string|number} totalAtomics+ * @param {{ role: string, bps: number, address: string }[]} legs+ * @returns {{ role: string, bps: number, address: string, atomics: bigint }[]}+ */+export function applySplit(totalAtomics, legs) {+ const total = BigInt(totalAtomics);+ let allocated = 0n;+ const out = legs.map((leg) => {+ const atomics = (total * BigInt(leg.bps)) / 10_000n;+ allocated += atomics;+ return { ...leg, atomics };+ });+ const remainder = total - allocated;+ if (remainder !== 0n && out.length > 0) {+ let idx = 0;+ for (let i = 1; i < out.length; i++) if (out[i].bps > out[idx].bps) idx = i;+ out[idx].atomics += remainder;+ }+ return out;+}++/** Public, non-secret config for clients to display and build transactions. */+export function publicConfig() {+ return {+ mint: TOKEN_MINT,+ symbol: TOKEN_SYMBOL,+ decimals: TOKEN_DECIMALS,+ treasury: treasuryWallet(),+ burn_address: burnAddress(),+ quote_ttl_seconds: env.THREE_QUOTE_TTL_S,+ split_policies: Object.fromEntries(+ Object.entries(SPLIT_POLICIES).map(([k, legs]) => [+ k,+ legs.map((l) => ({ role: l.role, bps: l.bps })),+ ]),+ ),+ };+}diff --git a/api/_lib/token/index.js b/api/_lib/token/index.jsnew file mode 100644index 000000000..a285aa614--- /dev/null+++ b/api/_lib/token/index.js@@ -0,0 +1,14 @@+// $THREE on-chain token layer — public surface consumed by Task 19 (paid+// spins) and Task 20 (token-priced listings) and the /api/token endpoint.+//+// Typical consumer flow:+// import { issueQuote, verifyAndSettlePayment } from '../_lib/token/index.js';+// const { token, quote } = await issueQuote({ purpose:'spin', usd: 0.50,+// splitPolicy:'spin', refType:'spin', refId });+// // ...client signs+sends one tx, returns { quoteToken: token, txSignature }+// await verifyAndSettlePayment({ quoteToken: token, txSignature, userId });++export * from './config.js';+export * from './price.js';+export { issueQuote, verifyQuote } from './quote.js';+export { verifyOnChain, settlePayment, verifyAndSettlePayment, listPayments } from './payments.js';diff --git a/api/_lib/token/payments.js b/api/_lib/token/payments.jsnew file mode 100644index 000000000..4ef3c6887--- /dev/null+++ b/api/_lib/token/payments.js@@ -0,0 +1,233 @@+// On-chain verification + settlement + audit for the $THREE token layer.+//+// Flow (server-authoritative — a client "paid" claim is never trusted):+// 1. verifyQuote() — quote untampered + unexpired+// 2. nonce-unused — fast reject of a replayed quote before any RPC+// 3. verifyOnChain() — tx confirmed, memo == nonce, each split leg credited+// 4. settlePayment() — record with UNIQUE(nonce) + UNIQUE(tx_signature); a+// duplicate insert is a replay/double-submit, surfaced+// as already_settled rather than crediting twice.++import { Connection } from '@solana/web3.js';+import { sql } from '../db.js';+import { env } from '../env.js';+import { verifyQuote } from './quote.js';++const MEMO_PROGRAM = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';++function rpcUrl(network) {+ return network === 'devnet' ? env.SOLANA_RPC_URL_DEVNET : env.SOLANA_RPC_URL;+}++function verifyError(message, status = 422, code = 'verification_failed', extra = {}) {+ return Object.assign(new Error(message), { status, code, ...extra });+}++// Net atomics credited to an owner across all of its token accounts for `mint`,+// computed from pre/post token balances. Robust to which transfer variant was+// used and to the destination ATA being created within the same transaction+// (it simply has no pre-balance entry). Works uniformly for the burn address,+// treasury, and a marketplace seller.+function creditedTo(tx, { mint, ownerAddress }) {+ const pre = tx.meta?.preTokenBalances || [];+ const post = tx.meta?.postTokenBalances || [];+ let delta = 0n;+ for (const p of post) {+ if (p.mint !== mint || p.owner !== ownerAddress) continue;+ const before = pre.find((x) => x.accountIndex === p.accountIndex);+ const beforeAmt = BigInt(before?.uiTokenAmount?.amount ?? '0');+ const afterAmt = BigInt(p.uiTokenAmount?.amount ?? '0');+ delta += afterAmt - beforeAmt;+ }+ return delta;+}++/**+ * Verify the on-chain transaction satisfies the quote.+ * @returns {Promise<{ confirmedAt: string, slot: number|null, credited: object }>}+ */+export async function verifyOnChain({ quote, txSignature, network = 'mainnet' }) {+ const connection = new Connection(rpcUrl(network), 'confirmed');+ let tx;+ try {+ tx = await connection.getParsedTransaction(txSignature, {+ maxSupportedTransactionVersion: 0,+ commitment: 'confirmed',+ });+ } catch {+ throw verifyError(+ 'transaction not found — may need more confirmations',+ 422,+ 'tx_not_found',+ );+ }+ if (!tx) throw verifyError('transaction not found', 422, 'tx_not_found');+ if (tx.meta?.err) throw verifyError('transaction failed on-chain', 422, 'tx_failed');++ // Memo must equal the quote nonce — binds this tx to this exact quote and+ // blocks a transfer whose numbers happen to line up from a different intent.+ const memoIx = tx.transaction.message.instructions.find(+ (ix) => ix.programId?.toString() === MEMO_PROGRAM,+ );+ const memo = typeof memoIx?.parsed === 'string' ? memoIx.parsed : null;+ if (!memo || memo !== quote.nonce) {+ throw verifyError('transaction memo does not match quote nonce', 422, 'memo_mismatch');+ }++ // Every split leg must have received at least its share. Underpaying any leg+ // (including the burn) voids the whole payment.+ const credited = {};+ for (const leg of quote.legs) {+ const need = BigInt(leg.atomics);+ const got = creditedTo(tx, { mint: quote.mint, ownerAddress: leg.address });+ credited[leg.role] = got.toString();+ if (got < need) {+ throw verifyError(+ `split leg "${leg.role}" received ${got} < required ${need}`,+ 422,+ 'split_underpaid',+ { role: leg.role, required: need.toString(), received: got.toString() },+ );+ }+ }++ return { confirmedAt: new Date().toISOString(), slot: tx.slot ?? null, credited };+}++function isUniqueViolation(err) {+ return err?.code === '23505' || /duplicate key|unique constraint/i.test(err?.message || '');+}++/**+ * Record a verified payment. Returns { id, replay, created_at }. A duplicate+ * nonce or tx_signature resolves to { replay: true } (the prior settled row).+ */+export async function settlePayment({+ quote,+ txSignature,+ network,+ payerWallet,+ userId,+ confirmation,+}) {+ try {+ const [row] = await sql`+ insert into token_payments+ (user_id, payer_wallet, purpose, mint, decimals, usd, price_usd,+ total_atomics, splits, nonce, tx_signature, network, slot, ref_type, ref_id, confirmed_at)+ values+ (${userId ?? null}, ${payerWallet ?? null}, ${quote.purpose}, ${quote.mint}, ${quote.decimals},+ ${quote.usd}, ${quote.priceUsd}, ${quote.total}, ${JSON.stringify(quote.legs)}::jsonb,+ ${quote.nonce}, ${txSignature}, ${network}, ${confirmation?.slot ?? null},+ ${quote.refType ?? null}, ${quote.refId ?? null}, now())+ returning id, created_at+ `;+ return { id: row.id, replay: false, created_at: row.created_at };+ } catch (err) {+ if (isUniqueViolation(err)) {+ const [existing] = await sql`+ select id, created_at from token_payments+ where nonce = ${quote.nonce} or tx_signature = ${txSignature}+ limit 1+ `;+ return {+ id: existing?.id ?? null,+ replay: true,+ created_at: existing?.created_at ?? null,+ };+ }+ throw err;+ }+}++/**+ * Full verified-payment path reused by Task 19 (paid spins) and Task 20+ * (token-priced listings). Validates the quote, rejects replays, verifies the+ * transaction on-chain, records the settlement.+ * @returns {Promise<{ ok: true, payment_id: string, quote: object, confirmation: object }>}+ */+export async function verifyAndSettlePayment({+ quoteToken,+ txSignature,+ payerWallet = null,+ userId = null,+ network,+}) {+ const quote = verifyQuote(quoteToken);+ const net = network || quote.network || 'mainnet';++ // Fast pre-check (the UNIQUE constraint in settlePayment is the source of+ // truth, but this avoids an RPC round-trip on an obvious replay).+ const [used] =+ await sql`select id, tx_signature from token_payments where nonce = ${quote.nonce} limit 1`;+ if (used) {+ throw verifyError('quote already settled', 409, 'already_settled', {+ tx_signature: used.tx_signature,+ });+ }++ const confirmation = await verifyOnChain({ quote, txSignature, network: net });+ const settled = await settlePayment({+ quote,+ txSignature,+ network: net,+ payerWallet,+ userId,+ confirmation,+ });+ if (settled.replay) {+ throw verifyError('payment already settled', 409, 'already_settled');+ }++ return { ok: true, payment_id: settled.id, quote, confirmation };+}++/**+ * Audit read for reconciliation. Keyset paginated by created_at. No secrets are+ * stored on the row, so the whole record is safe to return to an authorized reader.+ */+export async function listPayments({+ purpose = null,+ userId = null,+ refType = null,+ refId = null,+ limit = 50,+ before = null,+} = {}) {+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);+ const rows = await sql`+ select id, user_id, payer_wallet, purpose, mint, decimals, usd, price_usd,+ total_atomics, splits, nonce, tx_signature, network, slot,+ ref_type, ref_id, confirmed_at, created_at+ from token_payments+ where (${purpose}::text is null or purpose = ${purpose})+ and (${userId}::uuid is null or user_id = ${userId})+ and (${refType}::text is null or ref_type = ${refType})+ and (${refId}::text is null or ref_id = ${refId})+ and (${before}::timestamptz is null or created_at < ${before})+ order by created_at desc+ limit ${cap + 1}+ `;+ const hasMore = rows.length > cap;+ const items = (hasMore ? rows.slice(0, cap) : rows).map((r) => ({+ id: r.id,+ user_id: r.user_id,+ payer_wallet: r.payer_wallet,+ purpose: r.purpose,+ mint: r.mint,+ decimals: r.decimals,+ usd: Number(r.usd),+ price_usd: Number(r.price_usd),+ total_atomics: r.total_atomics,+ splits: r.splits,+ nonce: r.nonce,+ tx_signature: r.tx_signature,+ network: r.network,+ slot: r.slot,+ ref_type: r.ref_type,+ ref_id: r.ref_id,+ confirmed_at: r.confirmed_at,+ created_at: r.created_at,+ }));+ return { items, next_cursor: hasMore ? items[items.length - 1].created_at : null };+}diff --git a/api/_lib/token/price.js b/api/_lib/token/price.jsnew file mode 100644index 000000000..f00a9fcb8--- /dev/null+++ b/api/_lib/token/price.js@@ -0,0 +1,117 @@+// Live $THREE price + USD→token quoting.+//+// Price source mirrors the rest of the platform: Jupiter Lite is the primary+// Solana price feed (same source api/_lib/balances.js uses; no key, knows+// pump.fun bonding curves), with Birdeye as a keyed fallback (the source+// api/three-token uses). A short cache smooths bursts without letting a quote+// drift far from the live market — the quote's own expiry is the hard guard.++import { cacheGet, cacheSet } from '../cache.js';+import { TOKEN_MINT, TOKEN_DECIMALS, ATOMICS_PER_TOKEN } from './config.js';++const PRICE_TTL_S = 30;+const PRICE_CACHE_KEY = `token:price:${TOKEN_MINT}`;++async function fetchJson(url, opts = {}) {+ const r = await fetch(url, opts);+ if (!r.ok) {+ const body = await r.text().catch(() => String(r.status));+ throw Object.assign(new Error(`upstream ${r.status}: ${body.slice(0, 160)}`), {+ status: 502,+ });+ }+ return r.json();+}++async function jupiterPrice(mint) {+ const data = await fetchJson(`https://lite-api.jup.ag/price/v3?ids=${mint}`);+ const usd = data?.[mint]?.usdPrice ?? data?.[mint]?.price;+ const n = Number(usd);+ return Number.isFinite(n) && n > 0 ? n : null;+}++async function birdeyePrice(mint) {+ const key = process.env.BIRDEYE_API_KEY;+ if (!key) return null;+ const data = await fetchJson(`https://public-api.birdeye.so/defi/price?address=${mint}`, {+ headers: { 'X-API-KEY': key, accept: 'application/json' },+ });+ const n = Number(data?.data?.value);+ return Number.isFinite(n) && n > 0 ? n : null;+}++/**+ * Live USD price of one whole token. Throws 503 price_unavailable when no feed+ * returns a usable number — a paid action must never proceed on a guessed price.+ * @param {{ fresh?: boolean }} [opts]+ * @returns {Promise<{ priceUsd: number, source: string, mint: string, at: string }>}+ */+export async function getTokenPriceUsd({ fresh = false } = {}) {+ if (!fresh) {+ const cached = await cacheGet(PRICE_CACHE_KEY);+ if (cached?.priceUsd) return cached;+ }++ let priceUsd = null;+ let source = null;+ try {+ priceUsd = await jupiterPrice(TOKEN_MINT);+ if (priceUsd) source = 'jupiter';+ } catch (err) {+ console.warn('[token] jupiter price failed:', err?.message);+ }+ if (!priceUsd) {+ try {+ priceUsd = await birdeyePrice(TOKEN_MINT);+ if (priceUsd) source = 'birdeye';+ } catch (err) {+ console.warn('[token] birdeye price failed:', err?.message);+ }+ }+ if (!priceUsd) {+ throw Object.assign(new Error('live token price unavailable'), {+ status: 503,+ code: 'price_unavailable',+ });+ }++ const value = { priceUsd, source, mint: TOKEN_MINT, at: new Date().toISOString() };+ await cacheSet(PRICE_CACHE_KEY, value, PRICE_TTL_S);+ return value;+}++/**+ * Quote a USD amount as a token amount at the current live price.+ * @param {number} usd positive USD amount to convert+ * @returns {Promise<{ usd: number, priceUsd: number, source: string, priceAt: string, tokenAmount: number, atomics: bigint }>}+ */+export async function quoteTokenForUsd(usd) {+ const usdNum = Number(usd);+ if (!Number.isFinite(usdNum) || usdNum <= 0) {+ throw Object.assign(new Error('usd must be a positive number'), {+ status: 400,+ code: 'bad_request',+ });+ }+ const { priceUsd, source, at } = await getTokenPriceUsd();+ const tokenAmount = usdNum / priceUsd;+ // Convert to atomics with BigInt to avoid float drift on large token counts:+ // floor(tokenAmount * 10^decimals). We scale through micro-precision on the+ // USD/price ratio so a sub-cent price still rounds correctly.+ const scaled = Math.round(tokenAmount * Number(ATOMICS_PER_TOKEN));+ const atomics = BigInt(scaled);+ if (atomics <= 0n) {+ throw Object.assign(new Error('quoted amount rounds to zero at current price'), {+ status: 422,+ code: 'amount_too_small',+ });+ }+ return { usd: usdNum, priceUsd, source, priceAt: at, tokenAmount, atomics };+}++/** Decimal token amount (human units) from atomics, for display. */+export function atomicsToTokens(atomics) {+ return Number(BigInt(atomics)) / Number(ATOMICS_PER_TOKEN);+}++export { TOKEN_DECIMALS };diff --git a/api/_lib/token/quote.js b/api/_lib/token/quote.jsnew file mode 100644index 000000000..dade4213c--- /dev/null+++ b/api/_lib/token/quote.js@@ -0,0 +1,152 @@+// Signed payment quotes for the $THREE token layer.+//+// The server prices a USD amount, splits it per policy, and seals the result+// into a compact HMAC-signed token: base64url(JSON(payload)) + '.' + sig.+// The client builds and sends one transaction from the quote's legs, then+// returns the quote token + tx signature on settle. Signing it means the client+// cannot tamper with the token amount, the split ratio, or the destinations+// after the server priced them — and the embedded `exp` enforces a short+// validity window so a stale price can't be exploited after the market moves.+//+// Boot guard mirrors api/_lib/holder-pass.js: production MUST set+// THREE_QUOTE_SECRET or quotes would be forgeable by anyone reading this source.++import crypto from 'node:crypto';+import { env } from '../env.js';+import { randomToken } from '../crypto.js';+import {+ TOKEN_MINT,+ TOKEN_DECIMALS,+ TOKEN_SYMBOL,+ resolveSplitLegs,+ applySplit,+} from './config.js';+import { quoteTokenForUsd } from './price.js';++const DEV_SECRET = 'three-ws-token-quote-dev-secret';++let _warned = false;+function secret() {+ const s = env.THREE_QUOTE_SECRET;+ if (s) return s;+ if (process.env.NODE_ENV === 'production') {+ throw new Error(+ '[token] THREE_QUOTE_SECRET is required in production — refusing to sign payment quotes with the dev secret.',+ );+ }+ if (!_warned) {+ _warned = true;+ console.warn(+ '[token] THREE_QUOTE_SECRET is not set — using the insecure dev secret. ' ++ 'Set THREE_QUOTE_SECRET in production or payment quotes can be forged.',+ );+ }+ return DEV_SECRET;+}++function b64url(buf) {+ return Buffer.from(buf)+ .toString('base64')+ .replace(/=+$/, '')+ .replace(/\+/g, '-')+ .replace(/\//g, '_');+}+function b64urlToBuf(s) {+ return Buffer.from(s.replace(/-/g, '+').replace(/_/g, '/'), 'base64');+}+function hmac(body) {+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());+}++function quoteError(message, status = 422, code = 'invalid_quote') {+ return Object.assign(new Error(message), { status, code });+}++/**+ * Price a USD amount, split it, and return a signed quote.+ * @param {{+ * purpose: string, // 'spin' | 'marketplace_sale' | ...+ * usd: number, // USD amount to charge+ * splitPolicy: string, // a key of SPLIT_POLICIES+ * sellerWallet?: string, // required when the policy has a 'seller' leg+ * network?: 'mainnet'|'devnet',+ * refType?: string|null, // links the payment to a spin / listing for audit+ * refId?: string|null,+ * }} params+ */+export async function issueQuote({+ purpose,+ usd,+ splitPolicy,+ sellerWallet = null,+ network = 'mainnet',+ refType = null,+ refId = null,+}) {+ const priced = await quoteTokenForUsd(usd);+ const legs = applySplit(priced.atomics, resolveSplitLegs(splitPolicy, { sellerWallet }));+ const now = Math.floor(Date.now() / 1000);+ const nonce = await randomToken(16);++ const payload = {+ v: 1,+ purpose,+ network,+ mint: TOKEN_MINT,+ decimals: TOKEN_DECIMALS,+ symbol: TOKEN_SYMBOL,+ usd: priced.usd,+ priceUsd: priced.priceUsd,+ priceSource: priced.source,+ total: priced.atomics.toString(),+ // Destinations + per-leg atomics the client must satisfy on-chain.+ legs: legs.map((l) => ({+ role: l.role,+ address: l.address,+ bps: l.bps,+ atomics: l.atomics.toString(),+ })),+ // The nonce doubles as the transaction memo, binding the on-chain tx to+ // this exact quote and serving as the replay-protection key at settle.+ nonce,+ refType,+ refId,+ iat: now,+ exp: now + env.THREE_QUOTE_TTL_S,+ };++ const body = b64url(Buffer.from(JSON.stringify(payload)));+ const token = `${body}.${hmac(body)}`;+ return { token, quote: payload, expiresAt: new Date(payload.exp * 1000).toISOString() };+}++/**+ * Verify a quote token's signature and expiry, returning the payload.+ * Throws (422 invalid_quote / 410 quote_expired) on any tamper or timeout.+ */+export function verifyQuote(token) {+ if (typeof token !== 'string' || !token.includes('.'))+ throw quoteError('malformed quote token');+ const [body, sig] = token.split('.');+ if (!body || !sig) throw quoteError('malformed quote token');++ const expected = hmac(body);+ const a = Buffer.from(sig);+ const b = Buffer.from(expected);+ if (a.length !== b.length || !crypto.timingSafeEqual(a, b))+ throw quoteError('quote signature invalid');++ let payload;+ try {+ payload = JSON.parse(b64urlToBuf(body).toString('utf8'));+ } catch {+ throw quoteError('quote payload unreadable');+ }++ const now = Math.floor(Date.now() / 1000);+ if (!payload.exp || payload.exp < now) throw quoteError('quote expired', 410, 'quote_expired');+ if (!payload.nonce || !Array.isArray(payload.legs) || payload.legs.length === 0) {+ throw quoteError('quote missing required fields');+ }+ return payload;+}diff --git a/api/agent-delegate.js b/api/agent-delegate.jsindex efcbb5fef..5faf155d0 100644--- a/api/agent-delegate.js+++ b/api/agent-delegate.js@@ -36,7 +36,12 @@ export default wrap(async (req, res) => {if (err instanceof AgentNotFoundError)return error(res, 404, 'not_found', 'target agent not found');if (err instanceof LlmUnavailableError)- return error(res, 503, 'llm_unavailable', 'agent delegation is not available right now');+ return error(+ res,+ 503,+ 'llm_unavailable',+ 'agent delegation is not available right now',+ );return error(res, 502, 'upstream_error', `LLM call failed: ${err.message}`);}});diff --git a/api/friends/index.js b/api/friends/index.jsnew file mode 100644index 000000000..f76156fcb--- /dev/null+++ b/api/friends/index.js@@ -0,0 +1,98 @@+// /api/friends+// GET — the caller's whole social graph: accepted friends (with live presence+// + unread DM counts), incoming requests, outgoing requests.+// POST — graph mutations via { action, ... }:+// request { to } send a friend request (auto-accepts a reciprocal one)+// accept { userId } accept an incoming request+// decline { userId } decline an incoming request+// remove { userId } remove a friend / cancel an outgoing request+// mute { userId } mute an account (suppress their DMs)+// unmute { userId } unmute an account+//+// Validates the caller owns the account (session or bearer). Guards self-add,+// duplicates, and unknown targets in the store layer; rate-limited per account.++import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { resolveAccount } from '../_lib/account-auth.js';+import { readPresence, notifyMultiplayer } from '../_lib/presence-store.js';+import {+ listGraph,+ sendRequest,+ acceptRequest,+ declineRequest,+ removeFriend,+ muteUser,+ unmuteUser,+} from '../_lib/friends-store.js';++function isUuid(v) {+ return typeof v === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const auth = await resolveAccount(req, res);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');+ const me = auth.userId;++ if (req.method === 'GET') {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ return json(res, 200, { data: await graphWithPresence(me) });+ }++ // POST — a graph mutation. Tighter limit: 60 actions/min per account.+ const rl = await limits.chatUser(me);+ if (!rl.success) return error(res, 429, 'rate_limited', 'slow down');++ const body = await readJson(req).catch(() => ({}));+ const action = String(body.action || '');+ const target = body.to ?? body.userId;+ if (action !== 'request' && action !== 'accept' && action !== 'decline' &&+ action !== 'remove' && action !== 'mute' && action !== 'unmute') {+ return error(res, 400, 'bad_action', 'unknown action');+ }+ if (!isUuid(target)) return error(res, 400, 'bad_target', 'invalid user id');++ switch (action) {+ case 'request': {+ const result = await sendRequest(me, target);+ // Notify the other account: a fresh invite, or that we accepted theirs.+ if (result.status === 'requested') notifyMultiplayer('friend_request', target, { from: me });+ else if (result.status === 'accepted') notifyMultiplayer('friend_accept', target, { from: me });+ return json(res, 200, { data: result });+ }+ case 'accept': {+ const result = await acceptRequest(me, target);+ notifyMultiplayer('friend_accept', target, { from: me });+ return json(res, 200, { data: result });+ }+ case 'decline':+ return json(res, 200, { data: await declineRequest(me, target) });+ case 'remove':+ return json(res, 200, { data: await removeFriend(me, target) });+ case 'mute':+ return json(res, 200, { data: await muteUser(me, target) });+ case 'unmute':+ return json(res, 200, { data: await unmuteUser(me, target) });+ }+});++async function graphWithPresence(me) {+ const graph = await listGraph(me);+ const ids = [+ ...graph.friends.map((f) => f.id),+ ...graph.incoming.map((f) => f.id),+ ...graph.outgoing.map((f) => f.id),+ ];+ const presence = await readPresence(ids);+ const annotate = (u) => ({ ...u, ...(presence[u.id] || { online: false, realm: null }) });+ return {+ friends: graph.friends.map(annotate),+ incoming: graph.incoming.map(annotate),+ outgoing: graph.outgoing.map(annotate),+ };+}diff --git a/api/friends/messages.js b/api/friends/messages.jsnew file mode 100644index 000000000..019e1800e--- /dev/null+++ b/api/friends/messages.js@@ -0,0 +1,81 @@+// /api/friends/messages+// GET ?with=<userId>&before=<msgId> — fetch a DM thread (oldest→newest) and+// mark the other side's messages read. `before` paginates older history.+// POST { to, body } — send a DM to a friend.+//+// DMs require an accepted friendship. They deliver live over the socket when the+// recipient is online and are always persisted so an offline recipient reads+// them on next login. If the recipient has muted the sender the message is+// silently dropped (Task 14). Rate-limited and length-capped like world chat.++import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { resolveAccount } from '../_lib/account-auth.js';+import { notifyMultiplayer } from '../_lib/presence-store.js';+import { areFriends, getThread, markThreadRead, sendDM } from '../_lib/friends-store.js';++const MAX_BODY_LEN = 2000;++function isUuid(v) {+ return typeof v === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);+}++// Strip control chars + collapse whitespace, matching the world-chat cleaner.+function clean(str, maxLen) {+ if (typeof str !== 'string') return '';+ return str.replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/[ \t]+/g, ' ').trim().slice(0, maxLen);+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const auth = await resolveAccount(req, res);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');+ const me = auth.userId;++ if (req.method === 'GET') {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const url = new URL(req.url, 'http://x');+ const other = url.searchParams.get('with');+ const beforeId = url.searchParams.get('before');+ if (!isUuid(other)) return error(res, 400, 'bad_target', 'invalid user id');+ if (beforeId && !isUuid(beforeId)) return error(res, 400, 'bad_cursor', 'invalid cursor');+ if (!(await areFriends(me, other))) {+ return error(res, 403, 'not_friends', 'you can only message friends');+ }++ const messages = await getThread(me, other, { beforeId });+ // Opening the thread reads it — clear unread on the first (non-paginated) load.+ if (!beforeId) await markThreadRead(me, other);+ return json(res, 200, { data: { messages } });+ }++ // POST — send a DM.+ const rl = await limits.dmSend(me);+ if (!rl.success) return error(res, 429, 'rate_limited', 'you are sending messages too fast');++ const payload = await readJson(req).catch(() => ({}));+ const to = payload.to;+ const body = clean(payload.body, MAX_BODY_LEN);+ if (!isUuid(to)) return error(res, 400, 'bad_target', 'invalid user id');+ if (!body) return error(res, 400, 'empty', 'message is empty');+ if (typeof payload.body === 'string' && payload.body.length > MAX_BODY_LEN) {+ return error(res, 400, 'too_long', `keep it under ${MAX_BODY_LEN} characters`);+ }+ if (!(await areFriends(me, to))) {+ return error(res, 403, 'not_friends', 'you can only message friends');+ }++ const message = await sendDM(me, to, body);+ if (!message) {+ // Recipient muted the sender — the message was suppressed. Report success+ // so the sender can't probe who has muted them, but don't deliver.+ return json(res, 200, { data: { message: null, suppressed: true } });+ }++ notifyMultiplayer('dm', to, { message });+ return json(res, 200, { data: { message } });+});diff --git a/api/friends/presence-ticket.js b/api/friends/presence-ticket.jsnew file mode 100644index 000000000..d89f9cc8e--- /dev/null+++ b/api/friends/presence-ticket.js@@ -0,0 +1,24 @@+// GET /api/friends/presence-ticket+// Mint a short-lived, HMAC-signed ticket the client hands to the multiplayer+// realm room on join. The room verifies it (without a callback to us) and then+// publishes the bearer's presence — so a client can never claim to be online as+// another account. The client refreshes the ticket before it expires.++import { cors, error, json, method, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { resolveAccount } from '../_lib/account-auth.js';+import { signPresenceTicket } from '../_lib/presence-store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const auth = await resolveAccount(req, res);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const { token, expiresIn } = await signPresenceTicket(auth.userId);+ return json(res, 200, { data: { token, expiresIn } });+});diff --git a/api/friends/search.js b/api/friends/search.jsnew file mode 100644index 000000000..5d7c5f0a2--- /dev/null+++ b/api/friends/search.js@@ -0,0 +1,25 @@+// GET /api/friends/search?q=<term>+// Search accounts by display name / username to add as friends. Each hit is+// annotated with the caller's existing relationship so the UI renders the right+// action inline (Add / Pending / Friends).++import { cors, error, json, method, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { resolveAccount } from '../_lib/account-auth.js';+import { searchUsers } from '../_lib/friends-store.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const auth = await resolveAccount(req, res);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const url = new URL(req.url, 'http://x');+ const q = url.searchParams.get('q') || '';+ const results = await searchUsers(auth.userId, q);+ return json(res, 200, { data: { results } });+});diff --git a/api/play/nonce.js b/api/play/nonce.jsnew file mode 100644index 000000000..a4ab462a4--- /dev/null+++ b/api/play/nonce.js@@ -0,0 +1,32 @@+// GET /api/play/nonce+//+// Hands the /play sign-in flow a fresh, self-verifying nonce to embed in the+// message the wallet signs. Also tells the client whether the token gate is even+// active (required) and what it demands (mint + minBalance) so the gate UI can+// state the exact requirement and skip the whole flow when the platform hasn't+// pinned a game token yet.+import { cors, error, json, method, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { issueNonce, PLAY_GATE_MINT, PLAY_GATE_MIN } from '../_lib/play-pass.js';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;+ res.setHeader('cache-control', 'no-store');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const { nonce, exp } = issueNonce();+ return json(res, 200, {+ data: {+ nonce,+ expiresAt: new Date(exp * 1000).toISOString(),+ // The gate is only enforced once the platform pins a game token. When no+ // mint is configured the client skips sign-in entirely (open /play).+ required: !!PLAY_GATE_MINT,+ mint: PLAY_GATE_MINT,+ minBalance: PLAY_GATE_MIN,+ },+ });+});diff --git a/api/play/verify.js b/api/play/verify.jsnew file mode 100644index 000000000..22fb5e3c5--- /dev/null+++ b/api/play/verify.js@@ -0,0 +1,134 @@+// POST /api/play/verify { address, signature, nonce }+//+// The server half of wallet-first sign-in for /play. Proves the caller controls+// `address` (ed25519 signature over the exact message embedding our server+// nonce), then reads that wallet's on-chain balance of the game token from real+// Solana RPC and gates entry on PLAY_GATE_MIN. On success it mints a short-lived+// play pass the standalone Colyseus server trusts (multiplayer/src/play-pass.js),+// binding the verified wallet as the account id for persistence + the social+// graph. The wallet is proven here, never taken on trust from a join option, so+// a forged session can't reach the game room.+//+// Responses (200 unless the request itself is malformed):+// { ok: true, wallet, balance, mint, symbol, decimals, playPass, expiresAt }+// { ok: false, reason: 'balance_too_low', wallet, balance, mint, symbol,+// minBalance, acquireUrl }+// Hard errors the gate UI routes on:+// 400 nonce_invalid — missing/expired/forged nonce (re-fetch and retry)+// 401 bad_signature — signature didn't match the address+// 400 gate_disabled — no game token pinned (client shouldn't have called us)+// 502 balance_unavailable — RPC/price feed down+import { ed25519 } from '@noble/curves/ed25519.js';+import bs58mod from 'bs58';+import { z } from 'zod';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { getBalances } from '../_lib/balances.js';+import { verifyNonce, signPlayPass, PLAY_GATE_MINT, PLAY_GATE_MIN } from '../_lib/play-pass.js';++const bs58 = bs58mod.default || bs58mod;+const SOL_MINT = 'So11111111111111111111111111111111111111112';++const schema = z.object({+ address: z.string().trim().min(32).max(64),+ signature: z.string().trim().min(64).max(200),+ nonce: z.string().trim().min(16).max(4096),+});++// The message the wallet signs. MUST stay byte-identical to buildPlayMessage in+// src/game/play-auth.js — the server reconstructs it from the address + nonce and+// verifies the signature over these exact bytes, so any drift breaks every login.+function buildPlayMessage(address, nonce) {+ return [+ 'three.ws wants you to sign in with your Solana account:',+ address,+ '',+ 'Sign in to play three.ws. This proves you own this wallet and will not move any funds or tokens.',+ '',+ `Nonce: ${nonce}`,+ ].join('\n');+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;+ res.setHeader('cache-control', 'no-store');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ if (!PLAY_GATE_MINT) {+ return error(res, 400, 'gate_disabled', 'the token gate is not active');+ }++ const parsed = schema.safeParse(await readJson(req).catch(() => null));+ if (!parsed.success) return error(res, 400, 'validation_error', 'address, signature and nonce are required');+ const { address, signature, nonce } = parsed.data;++ // 1) The nonce must be one we issued and still live — defeats replaying a+ // signature captured from an old session.+ if (!verifyNonce(nonce)) {+ return error(res, 400, 'nonce_invalid', 'sign-in expired — please try again');+ }++ // 2) The signature must verify against the address over our exact message.+ let pubkey, sigBytes;+ try {+ pubkey = bs58.decode(address);+ sigBytes = bs58.decode(signature);+ } catch {+ return error(res, 400, 'validation_error', 'malformed address or signature');+ }+ if (pubkey.length !== 32 || sigBytes.length !== 64) {+ return error(res, 400, 'validation_error', 'malformed address or signature');+ }+ const msgBytes = new TextEncoder().encode(buildPlayMessage(address, nonce));+ let ok = false;+ try {+ ok = ed25519.verify(sigBytes, msgBytes, pubkey);+ } catch {+ ok = false;+ }+ if (!ok) {+ return error(res, 401, 'bad_signature', 'signature did not match the wallet');+ }++ // 3) Read the proven wallet's on-chain balance of the game token from real RPC.+ let balances;+ try {+ balances = await getBalances({ chain: 'solana', address });+ } catch (err) {+ const status = err?.status === 503 ? 503 : 502;+ return error(res, status, 'balance_unavailable', err?.message || 'could not read on-chain balance');+ }++ const holding =+ PLAY_GATE_MINT === SOL_MINT+ ? balances?.native+ : (balances?.tokens ?? []).find((t) => t.mint === PLAY_GATE_MINT);+ const balance = Math.round((holding?.amount || 0) * 1e6) / 1e6;+ const symbol = holding?.symbol || (PLAY_GATE_MINT === SOL_MINT ? 'SOL' : '$THREE');+ const decimals = holding?.decimals ?? null;+ const minBalance = PLAY_GATE_MIN;++ // 4) Gate on the floor. Short of it → an honest, actionable refusal with where+ // to acquire the token; clear of it → a signed pass the game server trusts.+ if (balance >= minBalance) {+ const playPass = signPlayPass({ wallet: address, mint: PLAY_GATE_MINT, balance });+ return json(res, 200, {+ data: { ok: true, wallet: address, balance, mint: PLAY_GATE_MINT, symbol, decimals, playPass, expiresAt: new Date(Date.now() + 10 * 60 * 1000).toISOString() },+ });+ }+ return json(res, 200, {+ data: {+ ok: false,+ reason: 'balance_too_low',+ wallet: address,+ balance,+ mint: PLAY_GATE_MINT,+ symbol,+ minBalance,+ acquireUrl: `https://jup.ag/swap/SOL-${PLAY_GATE_MINT}`,+ },+ });+});diff --git a/api/token/[action].js b/api/token/[action].jsnew file mode 100644index 000000000..36a478ef6--- /dev/null+++ b/api/token/[action].js@@ -0,0 +1,208 @@+// $THREE on-chain token layer — HTTP surface.+//+// GET /api/token/config — public token + split config (for clients)+// GET /api/token/price — live USD price (+ optional ?usd= quote)+// POST /api/token/quote — issue a signed payment quote (auth)+// POST /api/token/settle — verify an on-chain tx + record it (auth)+// GET /api/token/payments — settled-payment audit read (admin)+//+// The quote → settle pair is the generic, demoable end-to-end flow. Task 19 and+// Task 20 reuse the same library (api/_lib/token) directly from their own+// endpoints with purpose-specific refs; this surface keeps the layer exercisable+// on its own and powers shared UI (price display, the pay helper in src).++import { z } from 'zod';+import { env } from '../_lib/env.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { parse } from '../_lib/validate.js';+import { publicConfig } from '../_lib/token/config.js';+import { getTokenPriceUsd, quoteTokenForUsd } from '../_lib/token/price.js';+import { issueQuote, verifyAndSettlePayment, listPayments } from '../_lib/token/index.js';++// Allowlisted purposes for the generic quote endpoint. Each maps to a split+// policy and a sanity ceiling so this surface can't be used to mint an absurd+// quote. Task 19/20 set their own refs when calling the library directly.+const PURPOSES = {+ spin: { policy: 'spin', maxUsd: 100, requiresSeller: false },+ marketplace_sale: { policy: 'marketplace_sale', maxUsd: 1_000_000, requiresSeller: true },+};++const SOLANA_ADDRESS = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'invalid Solana address');++function isAdmin(user) {+ if (!user) return false;+ if (user.is_admin) return true;+ const w = (user.wallet_address || '').toLowerCase();+ return Boolean(w) && env.ADMIN_ADDRESSES.has(w);+}++// ── GET /api/token/config ────────────────────────────────────────────────────++async function handleConfig(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ return json(res, 200, publicConfig());+}++// ── GET /api/token/price ───────────────────────────────────────────────────++async function handlePrice(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;+ if (!method(req, res, ['GET'])) return;+ const url = new URL(req.url, 'http://x');+ const price = await getTokenPriceUsd();+ const usdParam = url.searchParams.get('usd');+ let quote = null;+ if (usdParam != null) {+ const q = await quoteTokenForUsd(Number(usdParam));+ quote = { usd: q.usd, token_amount: q.tokenAmount, atomics: q.atomics.toString() };+ }+ return json(res, 200, {+ mint: price.mint,+ price_usd: price.priceUsd,+ source: price.source,+ as_of: price.at,+ ...(quote ? { quote } : {}),+ });+}++// ── POST /api/token/quote ────────────────────────────────────────────────────++const quoteSchema = z.object({+ purpose: z.enum(Object.keys(PURPOSES)),+ usd: z.number().positive(),+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),+ seller_wallet: SOLANA_ADDRESS.optional(),+ ref_type: z.string().max(64).optional(),+ ref_id: z.string().max(128).optional(),+});++async function handleQuote(req, res) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;+ const user = await getSessionUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(quoteSchema, await readJson(req));+ const purpose = PURPOSES[body.purpose];+ if (body.usd > purpose.maxUsd) {+ return error(+ res,+ 422,+ 'amount_too_large',+ `usd exceeds the ${body.purpose} ceiling of ${purpose.maxUsd}`,+ );+ }+ if (purpose.requiresSeller && !body.seller_wallet) {+ return error(res, 400, 'seller_required', 'seller_wallet is required for this purpose');+ }++ const { token, quote, expiresAt } = await issueQuote({+ purpose: body.purpose,+ usd: body.usd,+ splitPolicy: purpose.policy,+ sellerWallet: body.seller_wallet ?? null,+ network: body.network,+ refType: body.ref_type ?? null,+ refId: body.ref_id ?? null,+ });++ return json(res, 201, {+ quote_token: token,+ purpose: quote.purpose,+ network: quote.network,+ mint: quote.mint,+ decimals: quote.decimals,+ symbol: quote.symbol,+ usd: quote.usd,+ price_usd: quote.priceUsd,+ price_source: quote.priceSource,+ total_atomics: quote.total,+ // Destinations + per-leg atomics + the memo the client must attach.+ legs: quote.legs,+ memo: quote.nonce,+ expires_at: expiresAt,+ });+}++// ── POST /api/token/settle ───────────────────────────────────────────────────++const settleSchema = z.object({+ quote_token: z.string().min(40),+ tx_signature: z.string().min(80).max(100),+ network: z.enum(['mainnet', 'devnet']).optional(),+ payer_wallet: SOLANA_ADDRESS.optional(),+});++async function handleSettle(req, res) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;+ const user = await getSessionUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = parse(settleSchema, await readJson(req));+ const result = await verifyAndSettlePayment({+ quoteToken: body.quote_token,+ txSignature: body.tx_signature,+ payerWallet: body.payer_wallet ?? user.wallet_address ?? null,+ userId: user.id,+ network: body.network,+ });++ return json(res, 200, {+ ok: true,+ payment_id: result.payment_id,+ purpose: result.quote.purpose,+ usd: result.quote.usd,+ total_atomics: result.quote.total,+ legs: result.quote.legs,+ credited: result.confirmation.credited,+ tx_signature: body.tx_signature,+ slot: result.confirmation.slot,+ ref_type: result.quote.refType ?? null,+ ref_id: result.quote.refId ?? null,+ });+}++// ── GET /api/token/payments (audit) ──────────────────────────────────────────++async function handlePayments(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;+ const user = await getSessionUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ if (!isAdmin(user)) return error(res, 403, 'forbidden', 'admin access required');++ const url = new URL(req.url, 'http://x');+ const page = await listPayments({+ purpose: url.searchParams.get('purpose') || null,+ refType: url.searchParams.get('ref_type') || null,+ refId: url.searchParams.get('ref_id') || null,+ limit: Number(url.searchParams.get('limit')) || 50,+ before: url.searchParams.get('before') || null,+ });+ return json(res, 200, page);+}++// ── dispatcher ────────────────────────────────────────────────────────────────++const DISPATCH = {+ config: handleConfig,+ price: handlePrice,+ quote: handleQuote,+ settle: handleSettle,+ payments: handlePayments,+};++export default wrap(async (req, res) => {+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();+ const fn = DISPATCH[action];+ if (!fn) return error(res, 404, 'not_found', `unknown token action: ${action}`);+ return fn(req, res);+});diff --git a/multiplayer/src/cosmetics.js b/multiplayer/src/cosmetics.jsnew file mode 100644index 000000000..da7030875--- /dev/null+++ b/multiplayer/src/cosmetics.js@@ -0,0 +1,172 @@+// Cosmetics shop — the catalog of visual-only looks players buy with gold, and+// the deterministic rotation that decides which ones are on sale right now.+//+// Cosmetics are STRICTLY visual. Nothing here touches combat, stats, movement,+// or any other gameplay value — a cosmetic only changes how an avatar renders+// (a body tint, a worn prop, a ground aura). The server owns purchase + rotation+// authority; the client is sent this catalog so it can render any peer's+// equipped look, and a live shop snapshot (offers + countdowns) when the shop+// opens. Pure + dependency-free so the rotation is unit-tested without a room+// (mirrors quests.js).+//+// Visual spec (`visual`), interpreted only by the client cosmetics renderer:+// { tint: '#rrggbb' } recolour the avatar's body materials+// { prop: '/path.glb', anchor: 'head' } attach a prop (auto-fitted to the head)+// { aura: '#rrggbb' } a glowing ring at the avatar's feet+// A cosmetic may combine fields (e.g. a tint + an aura).++// Rarity tiers, lowest → highest. The colour drives the catalog card accent on+// the client so rarity reads at a glance; kept here so server + client agree.+export const RARITIES = {+ common: { label: 'Common', color: '#9aa7b4' },+ uncommon: { label: 'Uncommon', color: '#4fb477' },+ rare: { label: 'Rare', color: '#4a90e2' },+ epic: { label: 'Epic', color: '#b06ff0' },+ legendary: { label: 'Legendary', color: '#f0a23a' },+};++// The full catalog. `rotation` is one of:+// 'always' — always on sale (a permanent staple)+// 'daily' — part of the daily-rotating pool (a subset is offered each UTC day)+// 'weekly' — part of the weekly-rotating pool (a subset offered each UTC week)+// Prices are in gold. Ids are stable — never renumber a live cosmetic, since+// ownership and the equipped selection persist by id (Task 16).+export const COSMETICS = [+ // ---- Always available (the staples) ----------------------------------+ { id: 'tint-ash', name: 'Ashen Cloak', rarity: 'common', price: 60, rotation: 'always', visual: { tint: '#6b6f76' } },+ { id: 'tint-crimson', name: 'Crimson Dye', rarity: 'common', price: 80, rotation: 'always', visual: { tint: '#c0392b' } },+ { id: 'tint-azure', name: 'Azure Dye', rarity: 'common', price: 80, rotation: 'always', visual: { tint: '#2e86de' } },+ { id: 'hat-beanie', name: 'Wool Beanie', rarity: 'common', price: 120, rotation: 'always', visual: { prop: '/accessories/hat-beanie.glb', anchor: 'head' } },++ // ---- Daily rotation pool (DAILY_OFFER_COUNT offered each day) ----------+ { id: 'tint-emerald', name: 'Emerald Dye', rarity: 'uncommon', price: 140, rotation: 'daily', visual: { tint: '#1abc9c' } },+ { id: 'tint-violet', name: 'Violet Dye', rarity: 'uncommon', price: 140, rotation: 'daily', visual: { tint: '#8e44ad' } },+ { id: 'hat-baseball', name: 'Field Cap', rarity: 'uncommon', price: 200, rotation: 'daily', visual: { prop: '/accessories/hat-baseball.glb', anchor: 'head' } },+ { id: 'tint-gold', name: 'Gilded Sheen', rarity: 'rare', price: 360, rotation: 'daily', visual: { tint: '#f1c40f' } },+ { id: 'aura-ember', name: 'Ember Aura', rarity: 'rare', price: 420, rotation: 'daily', visual: { aura: '#ff6b35' } },++ // ---- Weekly rotation pool (WEEKLY_OFFER_COUNT offered each week) -------+ { id: 'hat-cowboy', name: "Ranger's Hat", rarity: 'rare', price: 480, rotation: 'weekly', visual: { prop: '/accessories/hat-cowboy.glb', anchor: 'head' } },+ { id: 'aura-frost', name: 'Frost Aura', rarity: 'epic', price: 700, rotation: 'weekly', visual: { aura: '#6bd3ff' } },+ { id: 'aura-radiant', name: 'Radiant Aura', rarity: 'epic', price: 760, rotation: 'weekly', visual: { aura: '#ffe27a', tint: '#fff4cf' } },+ { id: 'aura-void', name: 'Void Aura', rarity: 'legendary', price: 1400, rotation: 'weekly', visual: { aura: '#9b59b6', tint: '#2c2c54' } },+];++// How many of each rotating pool are on sale at once. Kept below each pool's+// size so the set genuinely changes from one period to the next.+export const DAILY_OFFER_COUNT = 3;+export const WEEKLY_OFFER_COUNT = 2;++const BY_ID = new Map(COSMETICS.map((c) => [c.id, c]));+const DAILY_POOL = COSMETICS.filter((c) => c.rotation === 'daily').map((c) => c.id);+const WEEKLY_POOL = COSMETICS.filter((c) => c.rotation === 'weekly').map((c) => c.id);+const ALWAYS = COSMETICS.filter((c) => c.rotation === 'always').map((c) => c.id);++const DAY_MS = 24 * 60 * 60 * 1000;++export function cosmeticById(id) {+ return BY_ID.get(id) || null;+}++// A stable 32-bit hash of a string (FNV-1a) — same constant the quest roller+// uses, so rotations are deterministic across processes and restarts.+function hashString(s) {+ let h = 0x811c9dc5;+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return h >>> 0;+}++// Epoch ms of the most recent UTC midnight at or before `now`.+function startOfUtcDay(now) {+ const d = new Date(now);+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());+}++// 'YYYY-MM-DD' (UTC) for `now` — the key the daily rotation is seeded with.+export function dailyKey(now) {+ return new Date(startOfUtcDay(now)).toISOString().slice(0, 10);+}++// Epoch ms of the next UTC midnight — when the daily set rotates. The client+// renders a live countdown to this and re-requests the shop when it passes.+export function nextDailyReset(now) {+ return startOfUtcDay(now) + DAY_MS;+}++// Epoch ms of UTC Monday 00:00 at or before `now` (ISO week start).+function startOfUtcWeek(now) {+ const dow = (new Date(now).getUTCDay() + 6) % 7; // Mon=0 … Sun=6+ return startOfUtcDay(now) - dow * DAY_MS;+}++// Week key — the Monday date string the weekly rotation is seeded with.+export function weekKey(now) {+ return new Date(startOfUtcWeek(now)).toISOString().slice(0, 10);+}++// Epoch ms of the next UTC Monday — when the weekly set rotates.+export function nextWeeklyReset(now) {+ return startOfUtcWeek(now) + 7 * DAY_MS;+}++// Deterministically pick `count` distinct ids from `pool` for a rotation key.+// Seeded Fisher–Yates (xorshift32 PRNG) — identical to the daily-quest roller,+// so a period's offers are fixed and reproducible on every server/restart.+function rollOffers(pool, key, count) {+ if (count >= pool.length) return [...pool];+ const seed = hashString(key);+ const idx = pool.map((_, i) => i);+ let state = seed || 1;+ const rand = () => {+ state ^= state << 13; state >>>= 0;+ state ^= state >> 17;+ state ^= state << 5; state >>>= 0;+ return state / 0xffffffff;+ };+ for (let i = idx.length - 1; i > 0; i--) {+ const j = Math.floor(rand() * (i + 1));+ [idx[i], idx[j]] = [idx[j], idx[i]];+ }+ return idx.slice(0, count).map((i) => pool[i]);+}++// The current offer board: which cosmetic ids are buyable right now, split by+// bucket, plus the epoch-ms moments each rotation next turns over (for the+// client countdowns). Server-authoritative — derived purely from `now`.+export function currentOffers(now) {+ return {+ always: [...ALWAYS],+ daily: rollOffers(DAILY_POOL, dailyKey(now), DAILY_OFFER_COUNT),+ weekly: rollOffers(WEEKLY_POOL, weekKey(now), WEEKLY_OFFER_COUNT),+ dailyResetAt: nextDailyReset(now),+ weeklyResetAt: nextWeeklyReset(now),+ };+}++// Whether a given cosmetic is on sale at `now`. Always-cosmetics are always+// offered; rotating ones only during their current window. The buy handler+// gates on this so a client can't purchase something not currently for sale.+export function isOffered(id, now) {+ const c = BY_ID.get(id);+ if (!c) return false;+ if (c.rotation === 'always') return true;+ const offers = currentOffers(now);+ return c.rotation === 'daily' ? offers.daily.includes(id) : offers.weekly.includes(id);+}++// The catalog as sent to the client: every cosmetic's id, name, rarity, price,+// rotation, and visual spec, plus the rarity palette. The client renders peers'+// equipped looks and the shop/wardrobe entirely from this — no prices or visuals+// are hard-coded client-side.+export function clientCatalog() {+ return {+ rarities: RARITIES,+ cosmetics: COSMETICS.map((c) => ({+ id: c.id, name: c.name, rarity: c.rarity, price: c.price,+ rotation: c.rotation, visual: c.visual,+ })),+ };+}diff --git a/multiplayer/src/game-token.js b/multiplayer/src/game-token.jsnew file mode 100644index 000000000..85a235433--- /dev/null+++ b/multiplayer/src/game-token.js@@ -0,0 +1,405 @@+// Game-token economy — the on-chain primitives the in-game marketplace (Task 20)+// and any future paid action (Task 19 spins) settle through. This is the Task 18+// layer: token config, a live USD→token quote with a short validity window, the+// split transaction the buyer signs, and on-chain verification of that payment+// before any in-game value is released.+//+// The token is $THREE (the platform token). A USD-priced sale quotes to a $THREE+// amount at the live market price; the buyer's wallet sends ONE transaction that+// splits the $THREE between the seller's wallet and the treasury per the+// configured ratio (95/5 for marketplace sales). The server NEVER trusts a+// client "paid" claim — it re-fetches the confirmed transaction from Solana RPC+// and checks both legs landed at the right destinations for the right amounts.+//+// Quotes are sealed into an HMAC-SHA256 token (identical construction to+// realm-transfer.js / holder-pass.js) so a client can't move the price, swap the+// recipient, or replay an old quote after the market moves.++import crypto from 'node:crypto';+import { Connection, PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js';+import { getAssociatedTokenAddress, createAssociatedTokenAccountInstruction, createTransferInstruction } from '@solana/spl-token';++// --- config ----------------------------------------------------------------++// $THREE mint (overridable so a test deployment can point at a devnet mint).+export const TOKEN_MINT = process.env.GAME_TOKEN_MINT || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+export const TOKEN_DECIMALS = Number(process.env.GAME_TOKEN_DECIMALS || 6);+export const TOKEN_SYMBOL = '$THREE';++// The burn sink for paid-spin splits. Defaults to the canonical Solana+// incinerator (an unspendable address) — sending $THREE to its ATA removes the+// tokens from circulation. Matches api/_lib/token/config.js's burn address so+// both token layers burn to the same place.+export const BURN_ADDRESS =+ process.env.GAME_TOKEN_BURN || process.env.THREE_BURN_ADDRESS || '1nc1nerator11111111111111111111111111111111';++const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+const BIRDEYE_BASE = 'https://public-api.birdeye.so';+// SPL memo program — a memo carrying the quote nonce binds the on-chain tx to+// one specific quote so an unrelated transfer of the right size can't settle it.+const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+const QUOTE_TTL_SECONDS = 90; // long enough to approve in a wallet, short enough that a price can't be exploited+const PRICE_CACHE_MS = 30_000;+const DEV_SECRET = 'three-ws-game-token-dev-secret';++let _treasuryWarned = false;+// The treasury wallet that receives the platform's cut. Fail loud in production+// if it isn't configured (mirrors the HOLDER_PASS_SECRET boot guard) — without it+// the split has nowhere to send the 5% and the sale can't settle.+export function treasuryWallet() {+ const w = process.env.GAME_TOKEN_TREASURY || process.env.PAYMENT_RECIPIENT_SOLANA || '';+ if (w) return w;+ if (process.env.NODE_ENV === 'production') {+ throw new Error('[game-token] GAME_TOKEN_TREASURY is required in production — refusing to settle token sales without a treasury wallet.');+ }+ if (!_treasuryWarned) {+ _treasuryWarned = true;+ console.warn('[game-token] no GAME_TOKEN_TREASURY/PAYMENT_RECIPIENT_SOLANA set — token-priced listings are disabled until one is configured.');+ }+ return '';+}++export function tokenConfigured() {+ return !!treasuryWallet();+}++// Is this account id a real Solana wallet address (vs. a guest id like `g_…`)?+// Token listings require a wallet on both sides — the seller to receive the+// on-chain proceeds, the buyer to pay — so we gate on a valid base58 pubkey.+export function isWalletAddress(id) {+ if (typeof id !== 'string' || id.length < 32 || id.length > 44) return false;+ try { new PublicKey(id); return true; } catch { return false; }+}++let _secretWarned = false;+function secret() {+ const s = process.env.GAME_TOKEN_SECRET || process.env.HOLDER_PASS_SECRET || process.env.REALM_TRANSFER_SECRET;+ if (s) return s;+ if (process.env.NODE_ENV === 'production') {+ throw new Error('[game-token] GAME_TOKEN_SECRET (or HOLDER_PASS_SECRET) is required in production — refusing to sign quotes with the dev secret.');+ }+ if (!_secretWarned) {+ _secretWarned = true;+ console.warn('[game-token] no GAME_TOKEN_SECRET/HOLDER_PASS_SECRET set — using the insecure dev secret. Set one in production or token quotes can be forged.');+ }+ return DEV_SECRET;+}++// --- live price ------------------------------------------------------------++let _priceCache = { value: 0, at: 0 };++// Jupiter Lite is the primary feed — no API key, knows pump.fun bonding curves,+// and is the same source api/_lib/token/price.js + balances.js use. Returns null+// if unavailable so the caller can fall back.+async function jupiterPriceUsd() {+ const resp = await fetch(`https://lite-api.jup.ag/price/v3?ids=${TOKEN_MINT}`);+ if (!resp.ok) throw new Error(`jupiter ${resp.status}`);+ const body = await resp.json();+ const price = Number(body?.[TOKEN_MINT]?.usdPrice ?? body?.[TOKEN_MINT]?.price);+ return Number.isFinite(price) && price > 0 ? price : null;+}++// Birdeye is the keyed fallback (the source api/three-token uses).+async function birdeyePriceUsd() {+ const apiKey = process.env.BIRDEYE_API_KEY;+ if (!apiKey) return null;+ const resp = await fetch(`${BIRDEYE_BASE}/defi/price?address=${TOKEN_MINT}`, {+ headers: { 'X-API-KEY': apiKey, accept: 'application/json' },+ });+ if (!resp.ok) throw new Error(`birdeye ${resp.status}`);+ const body = await resp.json();+ const price = Number(body?.data?.value);+ return Number.isFinite(price) && price > 0 ? price : null;+}++// Live $THREE price in USD. Tries Jupiter first, then Birdeye. Cached briefly so+// a burst of quote requests is one upstream call. Returns 0 when no feed yields+// a usable number — callers treat 0 as "can't quote" and refuse the paid action+// rather than guessing a price.+export async function fetchTokenPriceUsd() {+ const now = Date.now();+ if (_priceCache.value > 0 && now - _priceCache.at < PRICE_CACHE_MS) return _priceCache.value;+ for (const [name, fn] of [['jupiter', jupiterPriceUsd], ['birdeye', birdeyePriceUsd]]) {+ try {+ const price = await fn();+ if (price > 0) {+ _priceCache = { value: price, at: now };+ return price;+ }+ } catch (err) {+ console.warn(`[game-token] ${name} price fetch failed:`, err?.message);+ }+ }+ return _priceCache.value || 0;+}++// Raw token base units for a USD amount at the live price. Returns null if the+// price feed is unavailable (so the caller can refuse the quote rather than guess).+export async function quoteTokenForUsd(usd) {+ const price = await fetchTokenPriceUsd();+ if (!(price > 0)) return null;+ const tokens = usd / price;+ const raw = BigInt(Math.round(tokens * 10 ** TOKEN_DECIMALS));+ return { price, tokens, raw };+}++// --- signed quote ----------------------------------------------------------++function b64url(buf) {+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+}+function b64urlDecode(str) {+ return Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8');+}+function hmac(body) {+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());+}+function safeEqual(a, b) {+ const ba = Buffer.from(a), bb = Buffer.from(b);+ if (ba.length !== bb.length) return false;+ return crypto.timingSafeEqual(ba, bb);+}++// Seal a settlement quote. `raw` amounts are strings (BigInt isn't JSON-safe).+export function signQuote(payload) {+ const now = Math.floor(Date.now() / 1000);+ const body = b64url(JSON.stringify({ ...payload, iat: now, exp: now + QUOTE_TTL_SECONDS }));+ return `${body}.${hmac(body)}`;+}++export function verifyQuote(token) {+ if (typeof token !== 'string' || token.length < 16 || token.length > 8192) return null;+ const dot = token.indexOf('.');+ if (dot <= 0) return null;+ const body = token.slice(0, dot);+ const sig = token.slice(dot + 1);+ if (!safeEqual(sig, hmac(body))) return null;+ let p;+ try { p = JSON.parse(b64urlDecode(body)); } catch { return null; }+ if (!p || typeof p !== 'object') return null;+ const now = Date.now() / 1000;+ if (typeof p.exp !== 'number' || p.exp < now) return null;+ if (typeof p.iat !== 'number' || p.iat > now + 60) return null;+ if (p.exp - p.iat > QUOTE_TTL_SECONDS + 5) return null;+ return p;+}++// --- split transaction -----------------------------------------------------++// Split `rawTotal` base units into seller / treasury legs by basis points.+// Treasury gets the remainder so the two legs always sum to exactly the total.+export function splitAmount(rawTotal, treasuryBps) {+ const total = BigInt(rawTotal);+ const treasury = (total * BigInt(treasuryBps)) / 10000n;+ const seller = total - treasury;+ return { seller, treasury };+}++// Build the unsigned transaction the buyer signs: two $THREE transfers from the+// buyer's token account — sellerRaw to the seller, treasuryRaw to the treasury —+// creating either destination's associated token account first if it's missing+// (the buyer pays that rent). Buyer is the sole signer and fee payer. Returned+// base64 is handed to the client to deserialize, sign, and broadcast.+export async function buildSplitTransaction({ buyerWallet, sellerWallet, sellerRaw, treasuryRaw }) {+ const conn = new Connection(SOLANA_RPC, 'confirmed');+ const mint = new PublicKey(TOKEN_MINT);+ const buyer = new PublicKey(buyerWallet);+ const seller = new PublicKey(sellerWallet);+ const treasury = new PublicKey(treasuryWallet());++ const buyerATA = await getAssociatedTokenAddress(mint, buyer);+ const sellerATA = await getAssociatedTokenAddress(mint, seller);+ const treasuryATA = await getAssociatedTokenAddress(mint, treasury);++ const tx = new Transaction();+ const [sellerAcct, treasuryAcct] = await Promise.all([+ conn.getAccountInfo(sellerATA),+ conn.getAccountInfo(treasuryATA),+ ]);+ if (!sellerAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, sellerATA, seller, mint));+ if (!treasuryAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, treasuryATA, treasury, mint));+ tx.add(createTransferInstruction(buyerATA, sellerATA, buyer, BigInt(sellerRaw)));+ tx.add(createTransferInstruction(buyerATA, treasuryATA, buyer, BigInt(treasuryRaw)));++ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ tx.feePayer = buyer;+ tx.recentBlockhash = blockhash;+ return tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64');+}++// Verify a settled split payment on-chain. Confirms the signature is finalized+// and that the transaction moved at least sellerRaw $THREE to the seller's token+// account AND at least treasuryRaw to the treasury's, by comparing pre/post token+// balances. Pre/post deltas (rather than instruction parsing) make this robust to+// however the wallet assembled the transfer. Returns { ok, reason }.+export async function verifySplitPayment({ txSig, sellerWallet, sellerRaw, treasuryRaw }) {+ if (typeof txSig !== 'string' || txSig.length < 32 || txSig.length > 128) return { ok: false, reason: 'bad_signature' };+ const conn = new Connection(SOLANA_RPC, 'confirmed');+ let tx;+ try {+ tx = await conn.getParsedTransaction(txSig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });+ } catch (err) {+ return { ok: false, reason: 'rpc_error' };+ }+ if (!tx) return { ok: false, reason: 'not_found' };+ if (tx.meta?.err) return { ok: false, reason: 'tx_failed' };++ const mint = TOKEN_MINT;+ const seller = new PublicKey(sellerWallet);+ const treasury = new PublicKey(treasuryWallet());+ const sellerATA = (await getAssociatedTokenAddress(new PublicKey(mint), seller)).toBase58();+ const treasuryATA = (await getAssociatedTokenAddress(new PublicKey(mint), treasury)).toBase58();++ // Net change for an owner's $THREE token account across this transaction.+ const delta = (ownerATA) => {+ const pre = (tx.meta?.preTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);+ const post = (tx.meta?.postTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);+ const preAmt = BigInt(pre?.uiTokenAmount?.amount || '0');+ const postAmt = BigInt(post?.uiTokenAmount?.amount || '0');+ return postAmt - preAmt;+ };++ const sellerGain = delta(sellerATA);+ const treasuryGain = delta(treasuryATA);+ if (sellerGain < BigInt(sellerRaw)) return { ok: false, reason: 'seller_underpaid' };+ if (treasuryGain < BigInt(treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };+ return { ok: true, sellerGain: sellerGain.toString(), treasuryGain: treasuryGain.toString() };+}++// Resolve the account address for a token-balance entry's index across the+// transaction's account-key list (parsed transactions expose keys as objects).+function accountKeyAt(tx, index) {+ const keys = tx.transaction?.message?.accountKeys || [];+ const k = keys[index];+ if (!k) return '';+ return typeof k === 'string' ? k : k.pubkey?.toBase58?.() || String(k.pubkey || '');+}++// --- paid wheel spins (Task 19) ---------------------------------------------+//+// A spin costs $3 in $THREE, split 50% burned / 50% to treasury. The flow+// mirrors marketplace settlement but with two fixed destinations (burn ++// treasury) and a memo binding the on-chain tx to the exact quote it settles:+// buildSpinPayment() → client signs+broadcasts → verifySpinPayment().+// Replay protection (a settled signature/nonce can't roll a second prize) is the+// caller's responsibility — the GameRoom tracks consumed nonces per process and+// the short quote TTL bounds the window.++// Split a total into burn + treasury legs by basis points. Treasury absorbs the+// rounding remainder so the two legs always sum to exactly the total.+export function splitBurnTreasury(rawTotal, burnBps = 5000) {+ const total = BigInt(rawTotal);+ const burn = (total * BigInt(burnBps)) / 10000n;+ const treasury = total - burn;+ return { burn, treasury };+}++function memoInstruction(nonce) {+ return new TransactionInstruction({ keys: [], programId: MEMO_PROGRAM_ID, data: Buffer.from(nonce, 'utf8') });+}++/**+ * Price a paid spin and build the unsigned split transaction the player signs.+ * Returns null when the live price feed is unavailable (the caller must refuse+ * the spin rather than charge a guessed amount) or when no treasury is set.+ * @param {{ buyerWallet: string, usd: number }} params+ * @returns {Promise<null | { quoteToken: string, txBase64: string, quote: object }>}+ */+export async function buildSpinPayment({ buyerWallet, usd }) {+ if (!tokenConfigured()) return null;+ const priced = await quoteTokenForUsd(usd);+ if (!priced || !(priced.raw > 0n)) return null;+ const { burn: burnRaw, treasury: treasuryRaw } = splitBurnTreasury(priced.raw, 5000);+ const treasuryAddr = treasuryWallet();+ const nonce = crypto.randomBytes(16).toString('hex');++ const conn = new Connection(SOLANA_RPC, 'confirmed');+ const mint = new PublicKey(TOKEN_MINT);+ const buyer = new PublicKey(buyerWallet);+ const burn = new PublicKey(BURN_ADDRESS);+ const treasury = new PublicKey(treasuryAddr);++ const buyerATA = await getAssociatedTokenAddress(mint, buyer);+ const burnATA = await getAssociatedTokenAddress(mint, burn);+ const treasuryATA = await getAssociatedTokenAddress(mint, treasury);++ const tx = new Transaction();+ const [burnAcct, treasuryAcct] = await Promise.all([+ conn.getAccountInfo(burnATA),+ conn.getAccountInfo(treasuryATA),+ ]);+ if (!burnAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, burnATA, burn, mint));+ if (!treasuryAcct) tx.add(createAssociatedTokenAccountInstruction(buyer, treasuryATA, treasury, mint));+ tx.add(createTransferInstruction(buyerATA, burnATA, buyer, burnRaw));+ tx.add(createTransferInstruction(buyerATA, treasuryATA, buyer, treasuryRaw));+ tx.add(memoInstruction(nonce));++ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ tx.feePayer = buyer;+ tx.recentBlockhash = blockhash;+ const txBase64 = tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64');++ const quotePayload = {+ purpose: 'spin',+ mint: TOKEN_MINT,+ decimals: TOKEN_DECIMALS,+ symbol: TOKEN_SYMBOL,+ buyer: buyerWallet,+ usd,+ priceUsd: priced.price,+ total: priced.raw.toString(),+ tokens: priced.tokens,+ burnAddr: BURN_ADDRESS,+ burnRaw: burnRaw.toString(),+ treasuryAddr,+ treasuryRaw: treasuryRaw.toString(),+ nonce,+ };+ const quoteToken = signQuote(quotePayload);+ return { quoteToken, txBase64, quote: { ...quotePayload, ttlSeconds: QUOTE_TTL_SECONDS } };+}++/**+ * Verify a settled paid spin on-chain: the quote is untampered + unexpired, the+ * tx carries the quote's memo nonce, the buyer matches, and both the burn and+ * treasury legs received at least their share. Pre/post token-balance deltas+ * make this robust to how the wallet assembled the transfers.+ * @param {{ quoteToken: string, txSig: string, buyerWallet?: string }} params+ * @returns {Promise<{ ok: boolean, reason?: string, nonce?: string, quote?: object }>}+ */+export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {+ const q = verifyQuote(quoteToken);+ if (!q || q.purpose !== 'spin') return { ok: false, reason: 'bad_quote' };+ if (buyerWallet && q.buyer && q.buyer !== buyerWallet) return { ok: false, reason: 'buyer_mismatch' };+ if (typeof txSig !== 'string' || txSig.length < 32 || txSig.length > 128) return { ok: false, reason: 'bad_signature' };++ const conn = new Connection(SOLANA_RPC, 'confirmed');+ let tx;+ try {+ tx = await conn.getParsedTransaction(txSig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });+ } catch {+ return { ok: false, reason: 'rpc_error' };+ }+ if (!tx) return { ok: false, reason: 'not_found' };+ if (tx.meta?.err) return { ok: false, reason: 'tx_failed' };++ // Memo must equal the quote nonce — binds this tx to this exact quote.+ const memoIx = (tx.transaction?.message?.instructions || []).find(+ (ix) => ix.programId?.toString() === MEMO_PROGRAM_ID.toBase58(),+ );+ const memo = typeof memoIx?.parsed === 'string' ? memoIx.parsed : null;+ if (!memo || memo !== q.nonce) return { ok: false, reason: 'memo_mismatch' };++ const mint = TOKEN_MINT;+ const burnATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.burnAddr))).toBase58();+ const treasuryATA = (await getAssociatedTokenAddress(new PublicKey(mint), new PublicKey(q.treasuryAddr))).toBase58();+ const delta = (ownerATA) => {+ const pre = (tx.meta?.preTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);+ const post = (tx.meta?.postTokenBalances || []).find((b) => b.mint === mint && accountKeyAt(tx, b.accountIndex) === ownerATA);+ return BigInt(post?.uiTokenAmount?.amount || '0') - BigInt(pre?.uiTokenAmount?.amount || '0');+ };+ if (delta(burnATA) < BigInt(q.burnRaw)) return { ok: false, reason: 'burn_underpaid' };+ if (delta(treasuryATA) < BigInt(q.treasuryRaw)) return { ok: false, reason: 'treasury_underpaid' };+ return { ok: true, nonce: q.nonce, quote: q };+}diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex f9f523f72..39b4bf296 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -15,13 +15,20 @@import http from 'node:http';import express from 'express';-import { Server } from '@colyseus/core';+import { Server, matchMaker } from '@colyseus/core';import { WebSocketTransport } from '@colyseus/ws-transport';import { monitor } from '@colyseus/monitor';import { WalkRoom } from './rooms/WalkRoom.js';import { GameRoom } from './rooms/GameRoom.js';+import { REALMS } from './rooms/realms.js';import { blockStore } from './block-store.js';+import { flushAllPlayers } from './playerStore.js';+import { marketplaceStore } from './marketplaceStore.js';+import { SERVERS } from './servers.js';+import { PRESENCE_HASH } from './presence-keys.js';+import { socialHub } from './social-hub.js';+import { verifyNotifySignature } from './presence-token.js';const PORT = Number(process.env.PORT || 2567);const HOST = process.env.HOST || '0.0.0.0';@@ -47,6 +54,17 @@ if (process.env.NODE_ENV === 'production' && !process.env.HOLDER_PASS_SECRET) {process.exit(1);}+// Surface the platform token gate's state at boot so a misconfigured deploy is+// obvious in the logs. The gate itself is enforced in WalkRoom.onAuth; an unset+// mint leaves walk_world open (the default until $THREE is pinned).+const PLAY_GATE_MINT = (process.env.PLAY_GATE_MINT || process.env.THREE_MINT || '').trim();+if (PLAY_GATE_MINT) {+ const min = Number(process.env.PLAY_GATE_MIN) > 0 ? Number(process.env.PLAY_GATE_MIN) : 1;+ console.log(`[multiplayer] play gate ENABLED — require ≥ ${min} of ${PLAY_GATE_MINT} (wallet sign-in)`);+} else {+ console.log('[multiplayer] play gate OFF (set PLAY_GATE_MINT or THREE_MINT to require wallet sign-in + token balance)');+}+const app = express();// Liveness probes for the host platform (Fly/Railway/Render).@@ -54,6 +72,25 @@ app.get(['/health', '/healthz'], (_req, res) => {res.json({ ok: true, name: 'three.ws-multiplayer' });});+// Internal friends delivery webhook (Task 15). The three.ws API calls this after+// persisting a DM or friend-graph change to push it live to every socket the+// recipient account has open here. HMAC-signed with the shared secret so only+// the API can inject events; returns whether the recipient was online (the API+// uses that to decide live vs. next-login delivery). Body is small JSON; an+// unsigned or malformed request is rejected before any work.+app.post('/internal/notify', express.json({ limit: '16kb' }), (req, res) => {+ const { type, to, payload } = req.body || {};+ const sig = req.headers['x-mp-signature'];+ if (typeof type !== 'string' || typeof to !== 'string' || !type || !to) {+ return res.status(400).json({ error: 'bad_request' });+ }+ if (!verifyNotifySignature(to, type, sig)) {+ return res.status(401).json({ error: 'bad_signature' });+ }+ const delivered = socialHub.deliver(to, type, payload || {});+ res.json({ delivered });+});+// Admin monitor UI — exposes live room/client state, so it must NOT be open to// the world in production. Mount it only when protected by basic-auth creds// (MONITOR_USER + MONITOR_PASS), or, outside production, openly for local dev.@@ -143,15 +180,112 @@ gameServer.define('walk_world', WalkRoom).filterBy(['coin', 'tier']);// the definition's options and read by GameRoom.onCreate. Mainland/Whisperwood/// Pond/Mine are safe; Wilderness is the danger+pvp realm that drops death-bags.// Mine is the enclosed cave interior reached through the Mainland mine entrance.-for (const realm of ['mainland', 'wilderness', 'whisperwood', 'pond', 'mine']) {- gameServer.define(`game_${realm}`, GameRoom, { realm });+//+// Server dimension (Task 23): filterBy(['server']) splits each realm definition+// into one room per chosen world instance, exactly as walk_world is split by+// coin/tier above. A joinOrCreate for game_mainland with {server:'s2'} matches+// only rooms created with server='s2', so the two worlds never merge — players+// on different servers can't see each other in any realm, chat, or /who. A+// missing/forged server option collapses to the default instance (see+// servers.cleanServer / GameRoom.onCreate).+// One room definition per realm, sourced from REALMS so a newly-defined realm is+// reachable the moment it's added to realms.js — no separate list to keep in sync.+for (const realm of Object.keys(REALMS)) {+ gameServer.define(`game_${realm}`, GameRoom, { realm }).filterBy(['server']);}+// --- Multi-server discovery + presence (Task 23) ---------------------------+// Read-only JSON the /play login picker and a friends panel consume from the+// (different-origin) static site, so they carry permissive CORS. Both read live+// truth — never cached or faked numbers.++// CORS for the public read-only endpoints. The population counts and presence+// flags are not sensitive, so we allow any origin to GET them; no credentials+// are involved. OPTIONS preflights short-circuit here.+function publicJsonCors(_req, res, next) {+ res.set('Access-Control-Allow-Origin', '*');+ res.set('Access-Control-Allow-Methods', 'GET, OPTIONS');+ res.set('Access-Control-Allow-Headers', 'Content-Type');+ res.set('Cache-Control', 'no-store');+ if (_req.method === 'OPTIONS') return res.status(204).end();+ next();+}++// GET /servers — the world-instance roster with REAL live population. Population+// is the sum of connected clients across every game_* room whose metadata names+// that server, queried through the matchmaker (so it's correct across all+// horizontally-scaled instances, not just this process). The least-full server+// is recommended so the picker can nudge balancing without ever faking a count.+app.get('/servers', publicJsonCors, async (_req, res) => {+ const counts = Object.fromEntries(SERVERS.map((s) => [s.id, 0]));+ try {+ const rooms = await matchMaker.query({});+ for (const r of rooms) {+ if (typeof r.name !== 'string' || !r.name.startsWith('game_')) continue;+ const sid = r.metadata?.server;+ if (sid && sid in counts) counts[sid] += r.clients || 0;+ }+ } catch (err) {+ console.warn('[multiplayer] /servers query failed:', err?.message);+ return res.status(503).json({ error: 'population_unavailable' });+ }+ // Recommend exactly one server — the least-full — preferring the first in+ // roster order on a tie so the suggestion is stable between polls.+ let recommended = SERVERS[0]?.id || null;+ let min = Infinity;+ for (const s of SERVERS) {+ if (counts[s.id] < min) { min = counts[s.id]; recommended = s.id; }+ }+ res.json({+ servers: SERVERS.map((s) => ({+ id: s.id,+ name: s.name,+ blurb: s.blurb,+ players: counts[s.id],+ recommended: s.id === recommended,+ })),+ });+});++// GET /presence?ids=a,b,c — for a friends panel (Task 15): resolve which+// server+realm each named account is currently on, or that they're offline.+// Reads the shared presence hash GameRoom maintains on join/leave. Capped at a+// sane batch size so a single request can't sweep the whole registry.+app.get('/presence', publicJsonCors, async (req, res) => {+ const ids = String(req.query.ids || '')+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ .slice(0, 100);+ if (!ids.length) return res.json({ presence: {} });+ let all = {};+ try {+ all = (await gameServer.presence.hgetall(PRESENCE_HASH)) || {};+ } catch (err) {+ console.warn('[multiplayer] /presence read failed:', err?.message);+ return res.status(503).json({ error: 'presence_unavailable' });+ }+ const presence = {};+ for (const id of ids) {+ const raw = all[id];+ if (!raw) { presence[id] = { online: false }; continue; }+ try {+ const e = JSON.parse(raw);+ presence[id] = { online: true, server: e.server || '', realm: e.realm || '', name: e.name || '' };+ } catch {+ presence[id] = { online: false };+ }+ }+ res.json({ presence });+});+gameServer.listen(PORT, HOST).then(() => {console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);- console.log(`[multiplayer] rooms: walk_world, game_{mainland,wilderness,whisperwood,pond,mine}`);+ console.log(`[multiplayer] rooms: walk_world, game_{${Object.keys(REALMS).join(',')}}`);+ console.log(`[multiplayer] world instances: ${SERVERS.map((s) => `${s.id} (${s.name})`).join(', ')}`);+ console.log(`[multiplayer] discovery: GET /servers, GET /presence?ids=`);console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);}).catch((err) => {@@ -187,6 +321,20 @@ const shutdown = async (signal) => {} catch (err) {console.error('[multiplayer] final block flush error:', err);}+ // Same guarantee for player progression (Task 16): persist every account whose+ // debounced profile save hadn't landed yet, so a redeploy never resets a player.+ try {+ await flushAllPlayers();+ } catch (err) {+ console.error('[multiplayer] final player flush error:', err);+ }+ // And the marketplace (Task 20): flush any debounced listing/payout writes so a+ // redeploy never drops an active listing or a seller's owed proceeds.+ try {+ await marketplaceStore.flushAll();+ } catch (err) {+ console.error('[multiplayer] final market flush error:', err);+ }process.exit(0);};process.on('SIGTERM', () => shutdown('SIGTERM'));diff --git a/multiplayer/src/items.js b/multiplayer/src/items.jsindex 827c58b19..e1a40e09e 100644--- a/multiplayer/src/items.js+++ b/multiplayer/src/items.js@@ -165,6 +165,32 @@ export function cookBurnChance(level) {return Math.max(0, Math.min(0.4, c));}+// ---------------------------------------------------------------------------+// Fishing+// ---------------------------------------------------------------------------++// Catch chance for a single cast: 40% at level 1 on average (quality 1) water,+// rising +0.5% per fishing level and scaled by the spot's quality multiplier+// (richer water both catches more often and yields doubles more often). Capped at+// 95% so even the best angler on the best water is never guaranteed a fish.+// Pure and deterministic (the cast handler rolls the RNG) so the odds are honest+// and unit-testable, mirroring cookBurnChance.+export function fishCatchChance(level, quality = 1) {+ const lvl = Math.max(1, level | 0);+ const q = quality > 0 ? quality : 1;+ const c = (0.4 + 0.005 * (lvl - 1)) * q;+ return Math.max(0, Math.min(0.95, c));+}++// Chance that a successful cast hauls in two fish instead of one. Zero at level 1,+// growing with level and spot quality, clamped at 45% so a double is always a+// treat rather than the norm.+export function fishDoubleChance(level, quality = 1) {+ const lvl = Math.max(1, level | 0);+ const q = quality > 0 ? quality : 1;+ return Math.max(0, Math.min(0.45, 0.02 * (lvl - 1) * q));+}+export function clientItemRegistry() {const out = {};for (const [id, it] of Object.entries(ITEMS)) {diff --git a/multiplayer/src/marketplaceStore.js b/multiplayer/src/marketplaceStore.jsnew file mode 100644index 000000000..e4422087e--- /dev/null+++ b/multiplayer/src/marketplaceStore.js@@ -0,0 +1,217 @@+// MarketplaceStore — durable persistence for the player-to-player marketplace+// (Task 20): the live listings every player can browse, and the pending payouts+// owed to sellers who were offline when their goods sold.+//+// This is the in-game item economy — distinct from the platform's AGENT+// marketplace under `api/marketplace*`. Listings here are account-scoped (keyed+// to a player's stable account id / wallet) and must survive a seller's+// disconnect, the room emptying, AND a server restart, so a buyer in one realm+// can purchase goods a seller listed from another realm yesterday.+//+// Same two-tier model as block-store.js:+// 1. In-process memory — the multiplayer server runs as a single always-on+// instance, so the Maps below already let a listing outlive both the+// seller's session and the room it was created in.+// 2. Upstash Redis (REST), used when UPSTASH_REDIS_REST_URL + _TOKEN are set —+// upgrades durability across restarts/redeploys. Writes are debounced and+// flushed on shutdown so a busy market doesn't hammer Redis.+//+// Escrow lives HERE, not in any inventory: when a player lists, the offered+// item(s) or gold are removed from them and stored on the listing object. That+// is the escrow — there is exactly one copy of the goods, so nothing can be+// listed-and-spent or duplicated. Cancel returns the escrow to the seller; a+// sale delivers it to the buyer.++const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';+const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';+const SAVE_DEBOUNCE_MS = 2500;+const LISTINGS_KEY = 'market:listings';+const PAYOUTS_KEY = 'market:payouts';+const SETTLED_KEY = 'market:settled'; // on-chain tx signatures already consumed (replay guard)++let _seq = 0;+function newId() {+ // Monotonic + time so ids sort by recency and never collide within a process.+ _seq = (_seq + 1) % 0xffffff;+ return `lst_${Date.now().toString(36)}${_seq.toString(36).padStart(4, '0')}`;+}++class MarketplaceStore {+ constructor() {+ this._listings = new Map(); // id -> listing+ this._payouts = new Map(); // sellerId -> [{ gold, items:[{item,qty}], reason, listingId, ts }]+ this._settled = new Set(); // tx signatures consumed by a token settlement+ this._saveTimer = null;+ this._redis = null;+ this._redisReady = null;+ this._loaded = false;+ this._durable = false;++ if (REDIS_URL && REDIS_TOKEN) {+ this._redisReady = import('@upstash/redis')+ .then(async ({ Redis }) => {+ this._redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });+ await this._redis.ping();+ this._durable = true;+ await this._hydrate();+ console.log('[marketplace-store] persistence: memory + Upstash Redis (verified)');+ })+ .catch((err) => {+ this._redis = null;+ console.error('[marketplace-store] Redis unreachable — listings are MEMORY-ONLY and will not survive a restart:', err?.message);+ });+ } else {+ console.log('[marketplace-store] persistence: memory-only (set UPSTASH_REDIS_REST_URL/_TOKEN for cross-restart durability)');+ }+ }++ get durable() { return this._durable; }+ async ready() { if (this._redisReady) await this._redisReady; }++ async _hydrate() {+ if (this._loaded || !this._redis) return;+ try {+ const [rawL, rawP, rawS] = await Promise.all([+ this._redis.get(LISTINGS_KEY),+ this._redis.get(PAYOUTS_KEY),+ this._redis.get(SETTLED_KEY),+ ]);+ const parse = (raw) => (typeof raw === 'string' ? JSON.parse(raw) : raw) || null;+ const L = parse(rawL);+ if (L && typeof L === 'object') for (const v of Object.values(L)) if (v && v.id) this._listings.set(v.id, v);+ const P = parse(rawP);+ if (P && typeof P === 'object') for (const [k, v] of Object.entries(P)) if (Array.isArray(v) && v.length) this._payouts.set(k, v);+ const S = parse(rawS);+ if (Array.isArray(S)) for (const sig of S) if (typeof sig === 'string') this._settled.add(sig);+ } catch (err) {+ console.warn('[marketplace-store] hydrate failed:', err?.message);+ }+ this._loaded = true;+ }++ // ---- listings ---------------------------------------------------------++ // Active listings, most-recent first. Optionally excluding one seller (so the+ // Buy tab can hide your own goods if desired — the caller decides).+ activeListings() {+ const out = [];+ for (const l of this._listings.values()) if (l.status === 'active') out.push(l);+ out.sort((a, b) => b.createdAt - a.createdAt);+ return out;+ }++ listingsBySeller(sellerId) {+ const out = [];+ for (const l of this._listings.values()) if (l.seller === sellerId) out.push(l);+ out.sort((a, b) => b.createdAt - a.createdAt);+ return out;+ }++ get(id) { return this._listings.get(id) || null; }++ // Create a listing. `escrow` is the goods already removed from the seller:+ // either { item, qty } (gold listing) or { gold } (gold-for-token listing).+ create(listing) {+ const id = newId();+ const rec = { id, ...listing, status: 'active', createdAt: Date.now() };+ this._listings.set(id, rec);+ this._scheduleSave();+ return rec;+ }++ update(id, patch) {+ const l = this._listings.get(id);+ if (!l) return null;+ Object.assign(l, patch);+ this._scheduleSave();+ return l;+ }++ // Prune sold/cancelled listings older than `maxAgeMs` so the store and the Buy+ // snapshot don't grow without bound. Active listings are never pruned.+ prune(maxAgeMs = 1000 * 60 * 60 * 24 * 7) {+ const cutoff = Date.now() - maxAgeMs;+ let removed = 0;+ for (const [id, l] of this._listings) {+ if (l.status !== 'active' && (l.closedAt || l.createdAt) < cutoff) {+ this._listings.delete(id);+ removed++;+ }+ }+ if (removed) this._scheduleSave();+ return removed;+ }++ // ---- pending payouts (offline-seller proceeds) ------------------------++ // Queue value owed to a seller who isn't online to receive it now. Drained on+ // their next join. Durable, so owed proceeds survive a restart until claimed.+ enqueuePayout(sellerId, payout) {+ if (!sellerId) return;+ const list = this._payouts.get(sellerId) || [];+ list.push({ ...payout, ts: Date.now() });+ this._payouts.set(sellerId, list);+ this._scheduleSave();+ }++ // Take and clear all pending payouts for a seller (called on join). Returns the+ // list; the caller is responsible for actually delivering them.+ drainPayouts(sellerId) {+ const list = this._payouts.get(sellerId);+ if (!list || !list.length) return [];+ this._payouts.delete(sellerId);+ this._scheduleSave();+ return list;+ }++ hasPendingPayouts(sellerId) {+ return (this._payouts.get(sellerId)?.length || 0) > 0;+ }++ // ---- on-chain replay guard -------------------------------------------++ isSettled(txSig) { return this._settled.has(txSig); }+ markSettled(txSig) {+ if (!txSig) return;+ this._settled.add(txSig);+ // Bound the set so a long-lived process doesn't accumulate signatures forever.+ if (this._settled.size > 5000) {+ const first = this._settled.values().next().value;+ this._settled.delete(first);+ }+ this._scheduleSave();+ }++ // ---- persistence ------------------------------------------------------++ _scheduleSave() {+ if (!this._redis && !this._redisReady) return; // memory-only+ if (this._saveTimer) return;+ const handle = setTimeout(() => { this._saveTimer = null; this.flush(); }, SAVE_DEBOUNCE_MS);+ if (typeof handle.unref === 'function') handle.unref();+ this._saveTimer = handle;+ }++ async flush() {+ if (this._saveTimer) { clearTimeout(this._saveTimer); this._saveTimer = null; }+ if (!this._redisReady) return;+ await this._redisReady;+ if (!this._redis) return;+ try {+ await Promise.all([+ this._redis.set(LISTINGS_KEY, JSON.stringify(Object.fromEntries(this._listings))),+ this._redis.set(PAYOUTS_KEY, JSON.stringify(Object.fromEntries(this._payouts))),+ this._redis.set(SETTLED_KEY, JSON.stringify([...this._settled])),+ ]);+ this._durable = true;+ } catch (err) {+ console.error('[marketplace-store] save failed — market durability degraded:', err?.message);+ }+ }++ async flushAll() { await this.flush(); }+}++// One store shared by every GameRoom in the process — that shared memory is+// exactly what lets a listing outlive its seller's session and its room.+export const marketplaceStore = new MarketplaceStore();diff --git a/multiplayer/src/play-pass.js b/multiplayer/src/play-pass.jsnew file mode 100644index 000000000..ecfc5b62d--- /dev/null+++ b/multiplayer/src/play-pass.js@@ -0,0 +1,84 @@+// Play pass verification — the game-server half of the wallet-first /play gate.+//+// The Vercel API (api/_lib/play-pass.js) proves a wallet owns its key (ed25519+// signature over a server nonce) and holds ≥ the game-token floor, then seals+// { wallet, mint, balance, tier:'play', iat, exp } into an HMAC-SHA256 token.+// This process re-derives the signature with the same shared secret and checks+// it, so WalkRoom.onAuth can admit a player and bind their verified wallet as+// the account id without ever touching Solana RPC. Keep byte-for-byte compatible+// with signPlayPass().++import crypto from 'node:crypto';++const DEV_SECRET = 'three-ws-holder-pass-dev-secret';++let _warned = false;+function secret() {+ const s = process.env.HOLDER_PASS_SECRET;+ if (s) return s;+ if (process.env.NODE_ENV === 'production') {+ throw new Error(+ '[play-pass] HOLDER_PASS_SECRET is required in production — refusing to verify passes with the dev secret.',+ );+ }+ if (!_warned) {+ _warned = true;+ console.warn(+ '[play-pass] HOLDER_PASS_SECRET is not set — using the insecure dev secret. ' ++ 'Set HOLDER_PASS_SECRET in production or the play gate can be entered with a forged pass.',+ );+ }+ return DEV_SECRET;+}++function b64url(buf) {+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+}++function hmac(body) {+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());+}++// Constant-time compare so a forged token can't be brute-forced byte by byte.+function safeEqual(a, b) {+ const ba = Buffer.from(a);+ const bb = Buffer.from(b);+ if (ba.length !== bb.length) return false;+ return crypto.timingSafeEqual(ba, bb);+}++/**+ * Verify a play pass and return its payload, or null if the token is missing,+ * malformed, tampered with, or expired.+ * @param {unknown} token+ * @returns {{ wallet: string, mint: string, balance: number, minBalance?: number, tier: string, iat: number, exp: number } | null}+ */+export function verifyPlayPass(token) {+ if (typeof token !== 'string' || token.length < 16 || token.length > 4096) return null;+ const dot = token.indexOf('.');+ if (dot <= 0) return null;+ const body = token.slice(0, dot);+ const sig = token.slice(dot + 1);+ if (!safeEqual(sig, hmac(body))) return null;++ let payload;+ try {+ payload = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));+ } catch {+ return null;+ }+ if (!payload || typeof payload !== 'object') return null;+ if (payload.k !== 'play-pass' || payload.tier !== 'play') return null;+ if (typeof payload.exp !== 'number' || payload.exp * 1000 < Date.now()) return null;+ // Reject future-dated passes (clock skew / forged iat) and any whose lifetime+ // exceeds the issuer's TTL — a defence against a tampered exp slipping past the+ // HMAC if the secret ever leaks.+ const now = Date.now() / 1000;+ if (typeof payload.iat !== 'number' || payload.iat > now + 60) return null;+ if (payload.exp - payload.iat > 15 * 60) return null;+ if (typeof payload.wallet !== 'string' || !payload.wallet) return null;+ if (typeof payload.mint !== 'string' || !payload.mint) return null;+ if (typeof payload.balance !== 'number' || !Number.isFinite(payload.balance) || payload.balance < 0) return null;+ if (payload.minBalance != null && (typeof payload.minBalance !== 'number' || !Number.isFinite(payload.minBalance) || payload.minBalance < 0)) return null;+ return payload;+}diff --git a/multiplayer/src/playerStore.js b/multiplayer/src/playerStore.jsindex 81a35a61c..296be7703 100644--- a/multiplayer/src/playerStore.js+++ b/multiplayer/src/playerStore.js@@ -1,49 +1,194 @@-// Cross-realm player persistence.+// Cross-realm, cross-restart player persistence (Task 16).//-// Colyseus rooms are independent, but a player's inventory, gold, skills, bank,-// and cosmetics must travel between realms (and survive a disconnect/reconnect-// within a session). This module is a process-wide store keyed by a stable-// playerId — the wallet address once authenticated, otherwise a guest id the-// client persists in localStorage.+// A player's full progression — name, inventory, hotbar, bank, gold, skill XP,+// hp, cosmetics (owned + equipped), quest/tutorial/daily state, and last realm —+// is keyed to a stable account id (the wallet address once authenticated per+// Task 17, otherwise a guest id the client persists in localStorage). It must+// travel between realms, survive a disconnect/reconnect, AND survive a server+// restart or redeploy.//-// Single-process only. When the multiplayer server scales horizontally, swap-// this Map for Redis (the get/save interface stays identical).--const store = new Map(); // playerId -> SavedState--const TTL_MS = 1000 * 60 * 60 * 6; // forget idle guests after 6h to bound memory--/**- * @typedef {object} SavedState- * @property {string} name- * @property {number} color- * @property {number} gold- * @property {{item:string,qty:number}[]} inv- * @property {{item:string,qty:number}[]} hotbar- * @property {{item:string,qty:number}[]} bank- * @property {number} activeSlot- * @property {{woodcutting:number,mining:number,fishing:number,cooking:number,combat:number}} xp- * @property {string} cosmetic- * @property {number} savedAt- */--export function loadPlayer(playerId) {- const s = store.get(playerId);- if (!s) return null;- if (Date.now() - s.savedAt > TTL_MS) { store.delete(playerId); return null; }- return s;-}+// Two tiers, the same shape block-store.js uses for voxel builds:+// 1. In-process memory (this Map). The server runs as a single always-on+// instance, so the Map alone already carries a profile between realms (each+// realm is its own room in one process) and across a reconnect. It is also+// the synchronous read/write cache that keeps loadPlayer/savePlayer cheap on+// the hot path — the GameRoom persists on every meaningful change and reads+// back inside its eviction/leave paths, all synchronously against the Map.+// 2. Upstash Redis (REST), used when UPSTASH_REDIS_REST_URL + _TOKEN are set.+// This is what makes a profile durable across restarts and shareable across+// instances (Task 23): each account is one JSON value under `player:<id>`,+// written write-behind (debounced a few seconds after the last change) and+// flushed on leave / dispose / shutdown. A single SET is atomic, so a+// profile is never half-written.+//+// The interface is identical with or without Redis configured, and identical for+// a wallet id vs. a guest id — so Task 17 (wallet auth) and Task 23 (scaling) are+// drop-ins. Without Redis the server is exactly as durable as before (in-process+// only); with it, progress outlives the process.+//+// One-active-session-per-account integrity (Task 16 rule 6) is enforced upstream+// by the presence-based eviction in GameRoom (see presence-keys.js): a fresh+// login persists and disconnects the stale session before taking over, so two+// sessions never fork-and-clobber one profile. This module is purely the store.-export function savePlayer(playerId, state) {- store.set(playerId, { ...state, savedAt: Date.now() });-}+const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';+const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';++const SAVE_DEBOUNCE_MS = 3000; // collapse a burst of saves into one Redis write+const KEY_PREFIX = 'player:';+const REDIS_TTL_S = 60 * 60 * 24 * 90; // 90d, refreshed on every flush — bounds abandoned-guest growth+const MEM_TTL_MS = 1000 * 60 * 60 * 6; // evict idle cache entries after 6h (a returning player rehydrates from Redis)++function redisKey(id) { return KEY_PREFIX + id; }++class PlayerStore {+ constructor() {+ this._mem = new Map(); // accountId → record (synchronous cache + memory-only tier)+ this._saveTimers = new Map(); // accountId → debounce handle+ this._redis = null;+ this._redisReady = null;+ // True only once a real Redis round-trip has succeeded — same honesty as+ // block-store: we never claim durability we haven't proven.+ this._durable = false;+ this._writeFailures = 0;+ if (REDIS_URL && REDIS_TOKEN) {+ this._redisReady = import('@upstash/redis')+ .then(async ({ Redis }) => {+ this._redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });+ await this._redis.ping();+ this._durable = true;+ console.log('[player-store] persistence: memory + Upstash Redis (verified)');+ })+ .catch((err) => {+ this._redis = null;+ console.error('[player-store] Redis unreachable — profiles are MEMORY-ONLY and will not survive a restart:', err?.message);+ });+ } else {+ console.log('[player-store] persistence: memory-only (set UPSTASH_REDIS_REST_URL/_TOKEN for cross-restart durability)');+ }++ // Evict idle cache entries so the Map doesn't grow without bound. An online+ // player keeps `savedAt` fresh (the room persists on every change), so only+ // offline/abandoned records age out — and in durable mode they remain safe in+ // Redis, rehydrated on the player's next join.+ const sweep = setInterval(() => {+ const now = Date.now();+ for (const [id, rec] of this._mem) {+ if (this._saveTimers.has(id)) continue; // a pending write is in flight — keep it+ if (now - (rec?.savedAt || 0) > MEM_TTL_MS) this._mem.delete(id);+ }+ }, 1000 * 60 * 30);+ if (typeof sweep.unref === 'function') sweep.unref();+ }-export function hasPlayer(playerId) {- return store.has(playerId);+ get durable() { return this._durable; }+ async ready() { if (this._redisReady) await this._redisReady; }++ // Pull an account's profile from Redis into the in-process cache so the+ // synchronous loadPlayer() that follows finds it. A cache hit returns instantly+ // (no network); only a miss — a fresh process after a restart, or a player who+ // last played on another instance — touches Redis. Call this (and await it) on+ // join, before loadPlayer.+ async hydrate(accountId) {+ if (!accountId) return null;+ if (this._mem.has(accountId)) return this._mem.get(accountId);+ if (this._redisReady) {+ try {+ await this._redisReady;+ const raw = this._redis ? await this._redis.get(redisKey(accountId)) : null;+ const obj = typeof raw === 'string' ? JSON.parse(raw) : raw; // Upstash may auto-parse JSON+ if (obj && typeof obj === 'object') {+ this._mem.set(accountId, obj);+ return obj;+ }+ } catch (err) {+ console.warn(`[player-store] hydrate failed for ${accountId}:`, err?.message);+ }+ }+ return null;+ }++ // Synchronous read of the cached profile (null if this account has no record in+ // the cache). After a restart, call hydrate() first so a returning player isn't+ // mistaken for a brand-new one.+ load(accountId) {+ return this._mem.get(accountId) || null;+ }++ has(accountId) {+ return this._mem.has(accountId);+ }++ // Synchronous write: update the cache now and arm a debounced durable write.+ // Stamps savedAt so the cache sweep can tell fresh records from abandoned ones.+ save(accountId, state) {+ if (!accountId) return;+ const record = { ...state, savedAt: Date.now() };+ this._mem.set(accountId, record);+ this._scheduleSave(accountId);+ }++ _scheduleSave(accountId) {+ if (!this._redis && !this._redisReady) return; // memory-only: nothing to flush+ if (this._saveTimers.has(accountId)) return;+ const handle = setTimeout(() => {+ this._saveTimers.delete(accountId);+ this.flush(accountId);+ }, SAVE_DEBOUNCE_MS);+ if (typeof handle.unref === 'function') handle.unref();+ this._saveTimers.set(accountId, handle);+ }++ // Write the account's current profile to Redis now (one atomic SET). Called by+ // the debounce timer and on leave/dispose/shutdown so the final state lands.+ // No-op without Redis.+ async flush(accountId) {+ const pending = this._saveTimers.get(accountId);+ if (pending) { clearTimeout(pending); this._saveTimers.delete(accountId); }+ if (!this._redisReady) return;+ await this._redisReady;+ if (!this._redis) return;+ const record = this._mem.get(accountId);+ if (!record) return;+ try {+ await this._redis.set(redisKey(accountId), JSON.stringify(record), { ex: REDIS_TTL_S });+ if (this._writeFailures > 0) {+ console.log(`[player-store] Redis writes recovered after ${this._writeFailures} failure(s)`);+ this._writeFailures = 0;+ }+ this._durable = true;+ } catch (err) {+ this._writeFailures++;+ if (this._writeFailures >= 3) {+ this._durable = false;+ console.error(`[player-store] Redis save failing (${this._writeFailures}×) for ${accountId} — durability DEGRADED, progress at risk:`, err?.message);+ } else {+ console.warn(`[player-store] save failed for ${accountId}:`, err?.message);+ }+ }+ }++ // Flush every account that still holds in-memory state. Called on process+ // shutdown (SIGTERM on redeploy) so a profile whose debounce timer hadn't fired+ // isn't lost between the last change and the instance going away.+ async flushAll() {+ if (!this._redisReady) return;+ await Promise.allSettled([...this._mem.keys()].map((id) => this.flush(id)));+ }}-// Periodic sweep so abandoned guest records don't accumulate forever.-setInterval(() => {- const now = Date.now();- for (const [id, s] of store) if (now - s.savedAt > TTL_MS) store.delete(id);-}, 1000 * 60 * 30).unref?.();+// One store shared by every GameRoom instance in the process — that shared memory+// is what lets a profile travel between realms without a Redis hop.+export const playerStore = new PlayerStore();++// Backwards-compatible functional API. The GameRoom persists synchronously on the+// hot path (loadPlayer/savePlayer), and the durable Redis tier rides underneath+// via the write-behind cache. hydratePlayer/flushPlayer/flushAllPlayers expose the+// async durability hooks for the join, leave/dispose, and shutdown paths.+export function loadPlayer(playerId) { return playerStore.load(playerId); }+export function savePlayer(playerId, state) { return playerStore.save(playerId, state); }+export function hasPlayer(playerId) { return playerStore.has(playerId); }+export function hydratePlayer(playerId) { return playerStore.hydrate(playerId); }+export function flushPlayer(playerId) { return playerStore.flush(playerId); }+export function flushAllPlayers() { return playerStore.flushAll(); }+export function playerStoreReady() { return playerStore.ready(); }diff --git a/multiplayer/src/presence-keys.js b/multiplayer/src/presence-keys.jsnew file mode 100644index 000000000..49b147133--- /dev/null+++ b/multiplayer/src/presence-keys.js@@ -0,0 +1,34 @@+// Shared presence keys for the multi-server account registry (Task 23).+//+// Both GameRoom (writer) and index.js (the /presence + /servers HTTP readers)+// reference these, so they live in one place to stay in lock-step. The store is+// the Colyseus `presence` instance — a process-local map in single-instance+// mode, or Redis when REDIS_URI is set — so the same keys work whether the host+// runs one process or many.++// Hash of currently-online accounts: field = account id (playerId), value =+// JSON { server, realm, name, sid, ts }. Lets a friends panel (or /presence)+// resolve which server+realm any account is on without joining its room.+export const PRESENCE_HASH = 'kg:presence';++// Pub/sub channel a room subscribes to per online account, so a fresh login of+// the same account anywhere on the cluster can evict the stale session and+// enforce one active session per account (the Task 16 integrity rule).+export function evictChannel(playerId) {+ return `kg:evict:${playerId}`;+}++// Pub/sub channel a room subscribes to per online account so a marketplace sale+// settled in another realm/room can deliver the seller's gold proceeds to their+// live session immediately (Task 20). The nudge just triggers a drain of the+// durable payout queue, so delivery is exactly-once whether the seller is online+// (nudge) or claims them on next join.+export function payoutChannel(playerId) {+ return `kg:payout:${playerId}`;+}++// Close code the server uses when it disconnects a session because the same+// account logged in elsewhere. The client routes on this to show a "signed in+// on another server" screen instead of silently reconnecting into a fight with+// the new session.+export const TAKEOVER_CLOSE_CODE = 4001;diff --git a/multiplayer/src/presence-token.js b/multiplayer/src/presence-token.jsnew file mode 100644index 000000000..85d5688da--- /dev/null+++ b/multiplayer/src/presence-token.js@@ -0,0 +1,55 @@+// Presence-ticket verification — the multiplayer half of the friends presence+// handshake. The Vercel API mints a ticket (api/_lib/presence-store.js →+// signPresenceTicket) for an authenticated account; a realm room verifies it+// here on join and trusts the returned account id, so a client can never claim+// another account's presence.+//+// Keep byte-for-byte in sync with the API signer:+// token = base64url(JSON{uid,exp}) + '.' + base64url(HMAC_SHA256(secret, payload))+// secret = MULTIPLAYER_SHARED_SECRET (falls back to HOLDER_PASS_SECRET, then a+// public dev secret — the same fallback chain the API uses).++import crypto from 'node:crypto';++function secret() {+ return (+ process.env.MULTIPLAYER_SHARED_SECRET ||+ process.env.HOLDER_PASS_SECRET ||+ 'dev-insecure-multiplayer-secret'+ );+}++function timingSafeEqualStr(a, b) {+ const ab = Buffer.from(a);+ const bb = Buffer.from(b);+ if (ab.length !== bb.length) return false;+ return crypto.timingSafeEqual(ab, bb);+}++// Verify a presence ticket → the trusted account id (uid), or null if the+// signature is wrong, the payload is malformed, or the ticket has expired.+export function verifyPresenceTicket(token) {+ if (typeof token !== 'string' || !token.includes('.')) return null;+ const [payload, sig] = token.split('.');+ if (!payload || !sig) return null;+ const expected = crypto.createHmac('sha256', secret()).update(payload).digest('base64url');+ if (!timingSafeEqualStr(sig, expected)) return null;+ let data;+ try {+ data = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));+ } catch {+ return null;+ }+ if (!data || !data.uid || !data.exp) return null;+ if (data.exp < Math.floor(Date.now() / 1000)) return null;+ return data.uid;+}++// Verify the signature on an internal /internal/notify webhook from the API.+// The API signs HMAC_SHA256(secret, `notify:<to>:<type>`); we recompute and+// compare in constant time so a third party can't inject fake DMs/events.+export function verifyNotifySignature(to, type, sig) {+ if (typeof sig !== 'string' || !sig) return false;+ const expected = crypto.createHmac('sha256', secret()).update(`notify:${to}:${type}`).digest('base64url');+ return timingSafeEqualStr(sig, expected);+}diff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.jsindex 0cca1f988..4f885725e 100644--- a/multiplayer/src/rooms/GameRoom.js+++ b/multiplayer/src/rooms/GameRoom.js@@ -11,14 +11,30 @@// one tile (8-way) of the player's current tile, and walkable. That makes// teleport-cheating impossible without a separate max-step heuristic.-import { Room } from '@colyseus/core';+import { Room, matchMaker } from '@colyseus/core';-import { GameState, GamePlayer, ResourceNode, Mob, Slot, Tombstone } from '../schemas/game.js';-import { REALMS, DEFAULT_REALM, isBlocked, inBounds, realmLayout, fishingSpotNear } from './realms.js';-import { runCommand } from './commands.js';-import { STACKABLE_ITEMS, isEdible, healValue, isMount, mountStepMs, rollLoot, itemLabel, clientItemRegistry, cookBurnChance } from '../items.js';+import { GameState, GamePlayer, ResourceNode, Mob, Slot, Tombstone, Structure } from '../schemas/game.js';+import { REALMS, DEFAULT_REALM, isBlocked, inBounds, realmLayout, fishingSpotNear, portalAt, rollerAt, rollerDelta, inNoPvpZone, wheelLandmark } from './realms.js';+import { signTransfer, verifyTransfer } from './realm-transfer.js';+import { runCommand, commandManifest } from './commands.js';+import { STACKABLE_ITEMS, isEdible, healValue, isMount, mountStepMs, rollLoot, itemLabel, clientItemRegistry, cookBurnChance, fishCatchChance, fishDoubleChance } from '../items.js';import { cleanAvatarUrl } from '../avatar-url.js';-import { loadPlayer, savePlayer } from '../playerStore.js';+import { loadPlayer, savePlayer, hydratePlayer, flushPlayer } from '../playerStore.js';+import { cleanServer } from '../servers.js';+import { PRESENCE_HASH, evictChannel, payoutChannel, TAKEOVER_CLOSE_CODE } from '../presence-keys.js';+import { socialHub } from '../social-hub.js';+import { verifyPresenceTicket } from '../presence-token.js';+import { cosmeticById, isOffered, currentOffers, clientCatalog } from '../cosmetics.js';+import { marketplaceStore } from '../marketplaceStore.js';+import {+ TOKEN_SYMBOL, TOKEN_DECIMALS, tokenConfigured, isWalletAddress,+ quoteTokenForUsd, signQuote, verifyQuote, splitAmount, buildSplitTransaction, verifySplitPayment,+ buildSpinPayment, verifySpinPayment,+} from '../game-token.js';+import {+ rollSpin, spinSegments, isSpinSettled, markSpinSettled,+ FREE_SPIN_COOLDOWN_MS, SPIN_MIN_AVG_LEVEL, PAID_SPIN_USD,+} from '../spin-wheel.js';import {TUTORIAL_STEPS, TUTORIAL_REWARD, GUIDE_DONE, BADGES, DAILY_POOL,dailyDef, nextResetAt, freshQuestState, normalizeQuestState, currentStep,@@ -39,6 +55,15 @@ const HOTBAR_SIZE = 6;const MAX_STACK = 999;const BANK_SIZE = 48;+// Marketplace (Task 20). Bounds keep a single listing's numbers sane and stop a+// player from flooding the board. The treasury cut applies ONLY to token sales+// (gold sales are fee-free) — 500 bps = 5%, leaving 95% to the seller's wallet.+const MAX_LISTINGS_PER_SELLER = 20;+const MARKET_GOLD_MAX = 0xffffffff;+const MARKET_USD_MIN = 0.01;+const MARKET_USD_MAX = 100_000;+const MARKET_TREASURY_BPS = 500;+// Which items stack is owned by the item registry (items.js) so cooking, loot,// banking, and the shop all agree. cookedFish + potions land here automatically.const STACKABLE = STACKABLE_ITEMS;@@ -54,7 +79,7 @@ const LEVEL_CAP = 99;// floods. Movement is the hot path so it gets the most headroom. Chat sits low:// a few lines a second is plenty for conversation and turns a scripted flood into// dropped messages (with feedback — see _handleChat).-const RATE_LIMITS = { step: 20, gather: 6, attack: 6, fish: 6, cook: 6, consume: 6, ui: 30, chat: 4 };+const RATE_LIMITS = { step: 20, gather: 6, attack: 6, fish: 6, cook: 6, consume: 6, ui: 30, chat: 4, mkt: 4, spin: 4 };// World chat: hard cap on a single message. Longer messages are rejected (not// silently truncated) so the sender knows their line didn't go through whole.@@ -74,11 +99,8 @@ const COOK_BATCH_MAX = 5; // raw fish processed per cook action (one cooldown)const COOK_XP = 12; // cooking XP per fish successfully cooked (burns yield none)const CONSUME_COOLDOWN_MS = 1100; // pace between bites — no instant heal-spamconst FISH_COOLDOWN_MS = 1500; // per-cast reel time — sets casting cadence on the real clock-// Catch curve: chance rises with fishing level and the spot's quality, hard-capped-// so even the richest water is never a guaranteed haul.-const FISH_BASE_CHANCE = 0.40; // catch chance at level 1 on an average (quality 1) spot-const FISH_CHANCE_PER_LEVEL = 0.005; // +0.5% per fishing level-const FISH_CHANCE_CAP = 0.95;+// The catch + double-haul curves live in items.js (fishCatchChance/fishDoubleChance)+// as pure functions, so the odds are unit-tested and shared, not inlined here.const RESPAWN_PLAYER_MS = 4000;const RESPAWN_MOB_MS = 8000;@@ -98,6 +120,24 @@ const TOMBSTONE_GRACE_MS = 45000; // last 45s: open to anyone adjacentconst FOUNTAIN_HEAL_PER_TICK = 6; // hp restored per sim tick near the fountainconst REGEN_PER_TICK = 1; // passive hp regen out of combat+// Arena rollers (Task 22): how often a moving-floor strip shoves a standing+// player one tile. Slower than the sim tick so the push reads as a deliberate+// nudge to learn, not a blur — ~two pushes a second.+const ROLLER_PUSH_MS = 500;++// Player-built structures (Task 07). `cost` is the EXACT material bill, deducted+// atomically on placement (no partial spend, no negative balance). `lifetimeMs`+// 0 == permanent (the shack, a landmark) — a firepit burns out after its window,+// healing adjacent players like the fountain until it decays. `cap` is how many+// of that kind one player may own at once; the shack's cap of 1 is enforced+// within the realm — and since the shack is Whisperwood-only (realms.js), the+// single Whisperwood room IS the cross-realm scope, so "one per player across+// realms" holds. `heal` is the per-tick HP a firepit restores to anyone beside it.+const STRUCTURE_DEFS = {+ firepit: { cost: { stone: 20, coal: 20, wood: 50 }, lifetimeMs: 30000, cap: Infinity, heal: FOUNTAIN_HEAL_PER_TICK },+ shack: { cost: { wood: 500, stone: 200 }, lifetimeMs: 0, cap: 1, heal: 0 },+};+// XP curve: cumulative XP required for a level. Early levels fly by, later// ones grind — matches the guide ("early levels come quickly").function levelForXp(xp) {@@ -142,19 +182,40 @@ export class GameRoom extends Room {// Off-schema, server-only per-player data: XP totals, private bank, and// per-action cooldown/rate windows. None of this needs to sync to peers.this.priv = new Map(); // sessionId -> { xp, bank: Slot[], cooldowns, rate }+ // Per-session subscription to the account's eviction channel (Task 23+ // single-active-session). sessionId -> { channel, handler }.+ this._evictSubs = new Map();+ // Per-session subscription to the account's marketplace payout channel (Task+ // 20), so a sale settled elsewhere can deliver gold proceeds to this seat.+ // sessionId -> { channel, handler }.+ this._payoutSubs = new Map();+ // Sim-tick counter that paces periodic profile autosaves.+ this._saveTick = 0;}- onCreate(options) {+ async onCreate(options) {// The room definition pins which realm this instance hosts. An unknown or// missing name falls back to the default realm so the room never boots into// an undefined map.const name = REALMS[options?.realm] ? options.realm : DEFAULT_REALM;this.realm = REALMS[name];- // Monotonic id source for tombstones spawned by this room.+ // Which world instance this room belongs to (Task 23). filterBy(['server'])+ // in index.js guarantees every client matched here passed the same server+ // option, but we still resolve it defensively so a forged/missing value can+ // never create a room for a non-existent instance.+ this.server = cleanServer(options?.server);+ // Monotonic id sources for tombstones and player-built structures (Task 07)+ // spawned by this room.this._tombSeq = 0;+ this._structSeq = 0;this.setState(new GameState());this.state.realm = this.realm.name;+ this.state.server = this.server;+ // Publish (realm, server) onto the room listing so the /servers endpoint can+ // sum live population per instance through the matchmaker — across every+ // horizontally-scaled process, not just this one.+ await this.setMetadata({ realm: this.realm.name, server: this.server });this.setPatchRate(PATCH_RATE_MS);this.autoDispose = true;@@ -174,10 +235,53 @@ export class GameRoom extends Room {this.onMessage('skills', (c) => this._sendSkills(c));this.onMessage('tombLoot', (c, p) => this._handleTombLoot(c, p));this.onMessage('setAvatar', (c, p) => this._handleAvatar(c, p));+ // Friends presence (Task 15): the client (re)asserts its presence ticket on+ // this channel — used after a portal handoff, where the new room's seat+ // reservation carries no join options, so the ticket can't ride onJoin.+ // Idempotent with the onJoin registration; the verified account id is the+ // trust anchor, never a raw client field.+ this.onMessage('presence', (c, ticket) => {+ const uid = verifyPresenceTicket(ticket);+ if (!uid) return;+ c.userData = { ...(c.userData || {}), accountUid: uid };+ socialHub.register(uid, c, this.realm.name);+ });+ // Cosmetics shop (Task 21): request the live shop board, buy a cosmetic from+ // the current rotation, and equip/unequip an owned (purchased) cosmetic. All+ // gold + ownership + rotation checks are server-authoritative below.+ this.onMessage('shopOpen', (c) => this._sendShop(c));+ this.onMessage('buyCosmetic', (c, p) => this._handleBuyCosmetic(c, p));+ this.onMessage('equipCosmetic', (c, p) => this._handleEquipCosmetic(c, p));+ this.onMessage('unequipCosmetic', (c) => this._handleUnequipCosmetic(c));// Mounts (Task 09): use the active hotbar item (ride a mount), leave the saddle,// and a generic slash-command channel (Task 13's chat forwards /dismount here).this.onMessage('use', (c, p) => this._handleUse(c, p));this.onMessage('dismount', (c) => this._handleDismount(c));+ // Building (Task 07): place a firepit/shack on an adjacent tile, paying its+ // exact material cost. Pickup/lock/unlock are slash-commands routed through+ // the command channel below (their actions live on this room).+ this.onMessage('build', (c, p) => this._handleBuild(c, p));+ // Player-to-player marketplace (Task 20): browse active listings, list your+ // own goods (item-for-gold or gold-for-token), cancel a listing (returns the+ // escrow), buy a gold listing with in-game gold, and the two-step on-chain+ // flow for token listings (quote → settle). Escrow, gold transfers, and the+ // 95/5 token split are all server-authoritative below. Distinct from the+ // platform AGENT marketplace under api/marketplace*.+ this.onMessage('mktOpen', (c) => this._sendMarket(c));+ this.onMessage('mktList', (c, p) => this._handleMarketList(c, p));+ this.onMessage('mktCancel', (c, p) => this._handleMarketCancel(c, p));+ this.onMessage('mktBuyGold', (c, p) => this._handleMarketBuyGold(c, p));+ this.onMessage('mktTokenQuote', (c, p) => this._handleMarketTokenQuote(c, p));+ this.onMessage('mktTokenSettle', (c, p) => this._handleMarketTokenSettle(c, p));++ // Wheel of Fortune (Task 19): info/eligibility + free spin (12h cooldown),+ // and the two-step paid spin ($3 in $THREE, 50% burned / 50% to treasury)+ // that settles on-chain before the prize is rolled. The roll is always+ // server-authoritative — the client only animates to the chosen segment.+ this.onMessage('spinInfo', (c) => this._sendSpinInfo(c));+ this.onMessage('spinFree', (c) => this._handleSpinFree(c));+ this.onMessage('spinPaidPrep', (c, p) => this._handleSpinPaidPrep(c, p));+ this.onMessage('spinPaidSettle', (c, p) => this._handleSpinPaidSettle(c, p));this.onMessage('command', (c, p) => this._handleCommand(c, p));// Quests (tutorial + dailies). The client only ever requests a snapshot,// talks to the guide, or asks to turn a finished quest in — all progress is@@ -210,7 +314,7 @@ export class GameRoom extends Room {}}- onJoin(client, options) {+ async onJoin(client, options) {const name = clean(options?.name, 24) || `guest-${client.sessionId.slice(0, 4)}`;// Stable account key: the wallet address / persistent guest id the client// sends (Task 16), falling back to the ephemeral session id when absent.@@ -218,6 +322,21 @@ export class GameRoom extends Room {// it so they survive a disconnect/reconnect.const playerId = clean(options?.pid, 80) || client.sessionId;const now = Date.now();+ // Single active session per account (Task 16 integrity rule, enforced across+ // world instances for Task 23): announce this login on the account's eviction+ // channel BEFORE loading the profile. Any live session of the same account —+ // in any realm, on any server, in any process — persists itself and+ // disconnects in response, so two windows can never both mutate and clobber+ // the one shared profile. In single-instance mode the stale session persists+ // synchronously here, so the load below already sees its latest state.+ this.presence.publish(evictChannel(playerId), { exceptSession: client.sessionId, ts: now });+ // Pull the durable profile into the in-process cache before the synchronous+ // load below (Task 16). A cache hit (a session already live in this process,+ // or a record left warm from a recent visit) returns instantly; a miss — the+ // first join after a restart/redeploy, or a player whose last session was on+ // another instance (Task 23) — fetches it from Redis. Without this, a returning+ // player on a fresh process would look brand-new and be reset to the starter kit.+ await hydratePlayer(playerId);const saved = loadPlayer(playerId);const quests = normalizeQuestState(saved?.quests, playerId, now) || freshQuestState(playerId, now);@@ -246,6 +365,13 @@ export class GameRoom extends Room {// every peer renders them as their real avatar, not the default capsule.p.cosmetic = cleanAvatarUrl(options?.avatar);p.badges = (quests.badges || []).join(',');+ // Restore the persisted purse + owned/equipped cosmetics (Task 16/21), keyed+ // to the stable account id so a purchase and the look the player chose survive+ // a disconnect/realm transfer. Owned ids are filtered to ones still in the+ // catalogue so a removed cosmetic never lingers; the equipped id must be owned.+ const cos = this._loadCosmetics(saved);+ p.gold = Number.isFinite(saved?.gold) ? Math.min(0xffffffff, Math.max(0, saved.gold | 0)) : 0;+ p.cosmeticId = cos.equipped;p.tsServer = now;this.state.players.set(client.sessionId, p);@@ -258,18 +384,100 @@ export class GameRoom extends Room {cooldowns: { gather: 0, attack: 0, fish: 0, cook: 0, consume: 0, step: 0 },rate: new Map(),quests,+ // Owned shop cosmetics (a Set of catalogue ids) + the equipped id. The+ // equipped id is mirrored onto the synced schema (p.cosmeticId); ownership+ // stays server-side and is only ever sent to its owner via the shop board.+ cosmetics: { owned: cos.owned, equipped: cos.equipped },+ // Wheel of Fortune (Task 19): when this account may next take its free spin.+ // Persisted per account so the 12h cooldown survives a disconnect/realm hop+ // and can't be reset by reconnecting. Paid spins never touch this timer.+ spin: { nextFreeSpinAt: Number.isFinite(saved?.spin?.nextFreeSpinAt) ? saved.spin.nextFreeSpinAt : 0 },});+ // Arriving through a portal: a signed transfer restores the haul the player+ // carried out of the previous realm and lands them at the portal's exit tile+ // instead of the realm's default spawn. An unsigned/expired/tampered token is+ // ignored — the player simply spawns fresh, never gaining forged items.+ const transfer = options?.transfer ? verifyTransfer(options.transfer) : null;+ if (transfer && transfer.to === this.realm.name) {+ if (transfer.carry) this._applyCarry(p, this.priv.get(client.sessionId), transfer.carry);+ const dtx = transfer.tx | 0, dty = transfer.ty | 0;+ if (inBounds(this.realm, dtx, dty) && !isBlocked(this.realm, dtx, dty)) {+ p.tx = dtx;+ p.ty = dty;+ }+ } else if (saved?.profile) {+ // No in-session carry token — this is a fresh login (first connect, a+ // reconnect, or a switch to another world instance). Restore the+ // account-scoped profile so items, hotbar, bank, skills, and mount are+ // identical regardless of which server the player chose (Task 23). The+ // profile is realm-agnostic; position stays this realm's spawn. Uses the+ // same defensively-bounded applier as portal carries, so a corrupt saved+ // blob can't inject out-of-range items or skill levels.+ this._applyCarry(p, this.priv.get(client.sessionId), saved.profile);+ }++ // Register this session as the account's live presence + subscribe to its+ // eviction channel so a later login elsewhere can take this seat over. The+ // presence row records which server+realm the account is on, which a friends+ // panel (Task 15) reads via GET /presence to show "online on Server 2 ·+ // Mainland". Cleared/transferred on leave (see onLeave).+ const channel = evictChannel(playerId);+ const handler = (msg) => this._onEvict(playerId, msg);+ await this.presence.subscribe(channel, handler);+ this._evictSubs.set(client.sessionId, { channel, handler });+ // Marketplace payout channel (Task 20): a sale settled in another realm/room+ // nudges this seat to drain its durable payout queue, so gold proceeds land+ // live instead of waiting for the next login. Subscribed per-session and torn+ // down on leave alongside the eviction subscription.+ const payChan = payoutChannel(playerId);+ const payHandler = () => this._drainMarketPayouts(client.sessionId);+ await this.presence.subscribe(payChan, payHandler);+ this._payoutSubs.set(client.sessionId, { channel: payChan, handler: payHandler });+ await this.presence.hset(+ PRESENCE_HASH,+ playerId,+ JSON.stringify({ server: this.server, realm: this.realm.name, name, sid: client.sessionId, ts: now }),+ );++ // Account-level friends presence (Task 15). The PRESENCE_HASH above is keyed+ // by playerId and powers seat eviction/takeover; the friends graph keys off+ // the three.ws account id (users.id), which a presence ticket carries in+ // verified, spoof-proof form. Register it with the social hub so friends see+ // "online · <realm>" via the friends API and can DM this player live.+ const accountUid = verifyPresenceTicket(options?.presence);+ if (accountUid) {+ client.userData = { ...(client.userData || {}), accountUid };+ socialHub.register(accountUid, client, this.realm.name);+ }++ // Claim any proceeds owed while this account was offline (gold from sales of+ // its listings). Drains the durable queue and credits the live player.+ this._drainMarketPayouts(client.sessionId);+// Hand the client the full static realm layout (geometry, fountain, bank// counter, fishing/cooking tiles, safe camp, portals, and the// safe/pvp/danger flags) so it renders exactly the tiles the server treats// as solid/interactive — and knows whether this realm drops death-bags.// Dynamic objects (nodes, mobs, players, tombstones) arrive via synced- // schema state instead.- client.send('realm', realmLayout(this.realm));+ // schema state instead. The build catalogue (which structures this realm+ // permits, with their authoritative costs) rides along so the client's build+ // menu + affordability never drift from the server (Task 07).+ const layout = realmLayout(this.realm);+ layout.buildCatalog = this._buildCatalog();+ client.send('realm', layout);// Item catalogue (icons, labels, mount tuning) so the hotbar can label items and// the scene can render the right steed. Static — sent once per join.client.send('items', clientItemRegistry());+ // Cosmetics catalogue (Task 21): id → name, rarity, price, rotation, and the+ // visual spec. Static, sent once per join so the client can render any peer's+ // equipped cosmetic immediately; the live shop board (offers + countdowns ++ // owned + gold) is fetched on demand via 'shopOpen'.+ client.send('cosmetics', clientCatalog());+ // Slash-command manifest (Task 13) so the chat input can autocomplete and+ // describe commands as the player types '/'. Generated from the same+ // registry that powers /help and the router, so the hint never drifts.+ client.send('commands', commandManifest());// Hand over the player's quest state (tutorial step, today's dailies +// progress, reset countdown, earned badges) so the quest panel and the// guide's "!"/"?" marker render immediately on entry.@@ -278,13 +486,80 @@ export class GameRoom extends Room {console.log(`[${this.realm.name} ${this.roomId}] +join ${name} (n=${this.state.players.size})`);}- onLeave(client) {- this._persistPlayer(client.sessionId);- this.state.players.delete(client.sessionId);- this.priv.delete(client.sessionId);+ async onLeave(client) {+ const sid = client.sessionId;+ const priv = this.priv.get(sid);+ // An evicted session already persisted itself synchronously inside _onEvict;+ // persisting again here would write a now-stale snapshot over whatever the+ // new session has since done, so skip it. A normal leave persists as usual.+ if (!priv?._evicted) {+ this._persistPlayer(sid);+ // Force the final state to durable storage now rather than waiting on the+ // debounce timer (Task 16): a clean disconnect must not lose the last few+ // seconds if the process is torn down before the timer fires. No-op when+ // Redis isn't configured. The evicted path is skipped — its successor+ // session owns the record now and flushes on its own.+ if (priv?.playerId) await flushPlayer(priv.playerId);+ }++ // Drop the account's eviction subscription and clear its presence row — but+ // only if the row is still OURS. A takeover overwrites the row with the new+ // session's id on its own join, and that newer session must not be erased by+ // the old one's delayed disconnect.+ const sub = this._evictSubs.get(sid);+ if (sub) {+ try { this.presence.unsubscribe(sub.channel, sub.handler); } catch {}+ this._evictSubs.delete(sid);+ }+ const paySub = this._payoutSubs.get(sid);+ if (paySub) {+ try { this.presence.unsubscribe(paySub.channel, paySub.handler); } catch {}+ this._payoutSubs.delete(sid);+ }+ if (priv?.playerId) {+ try {+ const raw = await this.presence.hget(PRESENCE_HASH, priv.playerId);+ if (raw && JSON.parse(raw).sid === sid) await this.presence.hdel(PRESENCE_HASH, priv.playerId);+ } catch {}+ }++ if (client.userData?.accountUid) socialHub.unregister(client.userData.accountUid, client);++ this.state.players.delete(sid);+ this.priv.delete(sid);+ }++ // React to another login of the same account (published on its eviction channel+ // from onJoin). Enforces one active session per account across all realms and+ // world instances: persist the stale local session NOW (so the new session loads+ // the latest profile) and disconnect it with the takeover code, after telling it+ // why so the client shows a "signed in elsewhere" screen instead of reconnecting.+ _onEvict(playerId, msg) {+ const except = msg?.exceptSession || '';+ for (const [sid, priv] of this.priv) {+ if (priv.playerId !== playerId || sid === except || priv._evicted) continue;+ this._persistPlayer(sid);+ priv._evicted = true; // suppress the duplicate persist in onLeave+ const c = this._clientFor(sid);+ if (c) {+ try { c.send('takeover', { reason: 'signed-in-elsewhere' }); } catch {}+ try { c.leave(TAKEOVER_CLOSE_CODE); } catch {}+ }+ }}- onDispose() {+ async onDispose() {+ // Belt-and-suspenders (Task 16): a normal dispose follows every client's+ // onLeave (which already persisted + flushed), but a forced teardown can skip+ // those — so persist and flush any session still resident before the room is+ // gone. Mirrors WalkRoom awaiting blockStore.flush on dispose.+ const ids = new Set();+ for (const [sid, priv] of this.priv) {+ if (priv?._evicted || !priv?.playerId) continue;+ this._persistPlayer(sid);+ ids.add(priv.playerId);+ }+ await Promise.allSettled([...ids].map((pid) => flushPlayer(pid)));console.log(`[${this.realm.name} ${this.roomId}] disposed`);}@@ -293,6 +568,10 @@ export class GameRoom extends Room {_handleStep(client, payload) {const p = this.state.players.get(client.sessionId);if (!p || p.dead) return;+ // A portal handshake is in flight — the client is about to leave for the+ // destination realm. Freeze further movement so a queued step can't trigger+ // a second transfer (or move the soon-to-be-snapshotted player off the tile).+ if (this.priv.get(client.sessionId)?.transferring) return;if (!this._rateOk(client.sessionId, 'step')) return;if (!payload || typeof payload !== 'object') return;@@ -325,6 +604,122 @@ export class GameRoom extends Room {p.tsServer = Date.now();// Tutorial: the very first step is simply learning to walk.this._questProgress(client, { kind: 'move', n: 1 });++ // Stepping onto a portal tile carries the player to its destination realm.+ // Each realm is its own room instance, so the move is a seat reservation in+ // the destination room plus a signed snapshot of everything the player is+ // carrying — the client tears down this seat and joins the other room.+ const portal = portalAt(this.realm, tx, ty);+ if (portal) {+ // Combat-LEVEL gate (Task 11): a gated portal (e.g. the northern cave)+ // refuses entry until the player's combat level meets the threshold. The+ // player keeps standing on the tile — no transfer, no bounce — and is told+ // what they need. Server-authoritative: a client can't forge its way past.+ if (portal.gate && !this._meetsGate(p, portal.gate)) {+ client.send('notice', { kind: 'portal', text: `You need Combat ${portal.gate.combat} to enter here (you're ${this._combatLevel(p)}).` });+ return;+ }+ this._beginTransfer(client, p, portal);+ }+ }++ // ----- realm traversal -------------------------------------------------++ // Reserve a seat in the destination realm and hand the client a transfer it+ // can consume. The player's full carry (inventory, hotbar, bank, gold, skills,+ // hp, mount) rides in an HMAC-signed token so the destination room can restore+ // it without trusting the client — a forged or replayed carry is rejected there.+ async _beginTransfer(client, p, portal) {+ const priv = this.priv.get(client.sessionId);+ if (!priv || priv.transferring) return;+ const dest = REALMS[portal.to] ? portal.to : DEFAULT_REALM;+ const destRealm = REALMS[dest];+ const tx = Number.isFinite(portal.toTx) ? portal.toTx : destRealm.spawn.tx;+ const ty = Number.isFinite(portal.toTy) ? portal.toTy : destRealm.spawn.ty;+ priv.transferring = true;+ const token = signTransfer({ to: dest, tx, ty, carry: this._snapshotCarry(client, p) });+ try {+ const reservation = await matchMaker.joinOrCreate(`game_${dest}`, {+ name: p.name,+ avatar: p.cosmetic,+ pid: priv.playerId,+ transfer: token,+ });+ // Persist quests now so the destination room (which reloads them by pid)+ // sees the same progress this room had at the moment of the step.+ this._persistPlayer(client.sessionId);+ client.send('portal', { to: dest, reservation });+ } catch (err) {+ priv.transferring = false;+ console.error(`[${this.realm.name} ${this.roomId}] portal → ${dest} failed:`, err?.message ?? err);+ client.send('notice', { kind: 'portal', text: 'The way is blocked right now. Try again.' });+ }+ }++ // Snapshot everything a player carries between realms. Quests persist by pid+ // (reloaded in the destination's onJoin), so only the in-memory haul rides here.+ _snapshotCarry(client, p) {+ return this._serializeProfile(p, this.priv.get(client.sessionId));+ }++ // The account-scoped, realm-agnostic profile: inventory, hotbar, bank, gold,+ // skills (raw XP), vitals, and mount. Used both as the portal carry payload and+ // as the persisted profile blob (Task 16/23) — one serializer so the two never+ // drift, and so switching world instances restores exactly what a portal would.+ _serializeProfile(p, priv) {+ const slots = (arr) => arr.map((s) => ({ item: s.item, qty: s.qty }));+ return {+ inv: slots(p.inv),+ hotbar: slots(p.hotbar),+ activeSlot: p.activeSlot,+ bank: (priv?.bank || []).map((s) => ({ item: s.item, qty: s.qty })),+ gold: p.gold,+ hp: p.hp,+ maxHp: p.maxHp,+ xp: { ...(priv?.xp || {}) },+ mounted: !!p.mounted,+ mount: p.mount || '',+ };+ }++ // Restore a verified carry onto a freshly-joined player in the destination room.+ // Slot arrays are rebuilt defensively (the token is signed, but we still bound+ // indices and quantities so a malformed-but-signed payload can't corrupt state).+ _applyCarry(p, priv, carry) {+ const fill = (target, src, size) => {+ for (let i = 0; i < size; i++) {+ const s = src && src[i];+ const item = s && typeof s.item === 'string' ? s.item : '';+ target[i].item = item;+ target[i].qty = item && Number.isFinite(s.qty) ? Math.max(0, Math.min(999, s.qty | 0)) : 0;+ }+ };+ fill(p.inv, carry.inv, INV_SIZE);+ fill(p.hotbar, carry.hotbar, HOTBAR_SIZE);+ if (Number.isFinite(carry.activeSlot)) {+ p.activeSlot = Math.max(-1, Math.min(HOTBAR_SIZE - 1, carry.activeSlot | 0));+ }+ if (priv) {+ for (let i = 0; i < BANK_SIZE; i++) {+ const s = carry.bank && carry.bank[i];+ const item = s && typeof s.item === 'string' ? s.item : '';+ priv.bank[i] = { item, qty: item && Number.isFinite(s.qty) ? Math.max(0, Math.min(999, s.qty | 0)) : 0 };+ }+ if (carry.xp && typeof carry.xp === 'object') {+ for (const skill of SKILLS) {+ const v = Number.isFinite(carry.xp[skill]) ? Math.max(0, carry.xp[skill]) : 0;+ priv.xp[skill] = v;+ p[skill] = levelForXp(v);+ }+ }+ }+ if (Number.isFinite(carry.gold)) p.gold = Math.max(0, Math.min(0xffffffff, carry.gold | 0));+ if (Number.isFinite(carry.maxHp) && carry.maxHp > 0) p.maxHp = carry.maxHp | 0;+ if (Number.isFinite(carry.hp)) p.hp = Math.max(0, Math.min(p.maxHp, carry.hp | 0));+ if (carry.mounted && typeof carry.mount === 'string' && carry.mount) {+ p.mounted = true;+ p.mount = carry.mount;+ }}_isWalkable(tx, ty) {@@ -342,6 +737,11 @@ export class GameRoom extends Room {for (const [, m] of this.state.mobs) {if (!m.dead && m.tx === tx && m.ty === ty) return false;}+ // Player-built structures are solid — you stand beside a firepit/shack,+ // never on it (Task 07), exactly like the fountain.+ for (const [, s] of this.state.structures) {+ if (s.tx === tx && s.ty === ty) return false;+ }return true;}@@ -436,15 +836,11 @@ export class GameRoom extends Room {const lvl = p.fishing;const quality = spot.quality || 1;- const chance = Math.min(- FISH_CHANCE_CAP,- (FISH_BASE_CHANCE + FISH_CHANCE_PER_LEVEL * (lvl - 1)) * quality,- );+ const chance = fishCatchChance(lvl, quality);if (Math.random() < chance) {// Yield: usually one fish, with a skill/quality-scaled shot at a double haul.- const doubleChance = Math.min(0.45, 0.02 * (lvl - 1) * quality);- const want = 1 + (Math.random() < doubleChance ? 1 : 0);+ const want = 1 + (Math.random() < fishDoubleChance(lvl, quality) ? 1 : 0);const leftover = this._addItem(p, 'fish', want);const caught = want - leftover;if (caught <= 0) {@@ -610,8 +1006,16 @@ export class GameRoom extends Room {const p = this.state.players.get(client.sessionId);if (!p || p.dead) return;if (!this._rateOk(client.sessionId, 'attack')) return;- const mob = this.state.mobs.get(String(payload?.id ?? ''));- if (!mob || mob.dead) return;+ const targetId = String(payload?.id ?? '');+ const mob = this.state.mobs.get(targetId);+ // No mob with that id → maybe it's another player. PvP rides the same 'attack'+ // intent + cooldown; the dedicated handler enforces this realm's PvP rules.+ if (!mob) {+ const victim = this.state.players.get(targetId);+ if (victim && victim !== p) this._attackPlayer(client, p, victim);+ return;+ }+ if (mob.dead) return;const priv = this.priv.get(client.sessionId);const now = Date.now();@@ -642,6 +1046,53 @@ export class GameRoom extends Room {p.tsServer = now;}+ // ----- player vs player (Task 04 rules, enforced for the wild realms + Arena) ----++ // Strike another player. Server-authoritative and gated by the realm's rules:+ // PvP must be ON, neither fighter may stand in a PvP-immune tile (a wilderness+ // safe camp or an Arena spectator stand), and the attacker must be adjacent and+ // off cooldown. Damage flows through the shared _damagePlayer funnel, so a fatal+ // blow drops a death-bag in danger realms (the wilds) and is a clean, item-safe+ // knockout in the Arena (danger:false). On a kill the victor takes combat XP and+ // a small bounty.+ _attackPlayer(client, attacker, victim) {+ if (!this.realm.pvp) {+ client.send('notice', { kind: 'pvp', text: 'This is a peaceful realm — you can’t attack other players here.' });+ return;+ }+ if (victim.dead) return;+ // A spectator stand / safe camp shields BOTH sides: you can't be hit while in+ // one, and you can't reach out of the floor to hit someone standing in it.+ if (inNoPvpZone(this.realm, attacker.tx, attacker.ty)) {+ client.send('notice', { kind: 'pvp', text: 'Step out of the safe zone to fight.' });+ return;+ }+ if (inNoPvpZone(this.realm, victim.tx, victim.ty)) {+ client.send('notice', { kind: 'pvp', text: `${victim.name} is in a safe zone.` });+ return;+ }++ const priv = this.priv.get(client.sessionId);+ const now = Date.now();+ if (now < priv.cooldowns.attack) return;+ if (!this._adjacent(attacker, victim)) return;++ const hasSword = attacker.hotbar[attacker.activeSlot]?.item === 'sword';+ const base = 4 + Math.floor(attacker.combat * 0.8) + (hasSword ? 6 : 0);+ const dmg = base + Math.floor(Math.random() * 4);+ priv.cooldowns.attack = now + ATTACK_COOLDOWN_MS;++ const fatal = this._damagePlayer(victim, dmg, { by: attacker.id, byName: attacker.name });+ attacker.tsServer = now;+ if (fatal) {+ const bounty = 8 + Math.floor(Math.random() * 8);+ attacker.gold = Math.min(0xffffffff, attacker.gold + bounty);+ this._grantXp(client, attacker, 'combat', 18 + Math.floor(Math.random() * 10));+ client.send('notice', { kind: 'kill', text: `You defeated ${victim.name} (+${bounty}g).` });+ this._questProgress(client, { kind: 'combat', n: 1 });+ }+ }+// ----- mounts & loot ---------------------------------------------------// Roll a slain mob's loot table and hand the killer their winnings. Mounts are@@ -825,11 +1276,163 @@ export class GameRoom extends Room {}}- // ----- structure actions (Task 07 firepit/shack; invoked by /pickup /lock /unlock) ----+ // ----- building (Task 07: firepit / shack) -----------------------------++ // The structures this realm permits, each with its authoritative cost + lifetime,+ // sent to the client on join so the build menu and ghost validity mirror the+ // server exactly. `cap` 0 means unlimited (the client renders no cap note).+ _buildCatalog() {+ const out = {};+ for (const kind of this.realm.structures || []) {+ const def = STRUCTURE_DEFS[kind];+ if (def) out[kind] = { cost: { ...def.cost }, lifetimeMs: def.lifetimeMs, cap: Number.isFinite(def.cap) ? def.cap : 0 };+ }+ return out;+ }++ // Place a structure on an adjacent tile, paying its EXACT material cost. The+ // server is the sole authority: it re-validates the realm rules, the target+ // tile, the per-player cap, and the full material bill, and deducts atomically+ // (the cost is checked payable before a single item is spent) so there is no+ // free build and no negative balance. A firepit gets an `expiresAt`; a shack is+ // permanent. The client's build-mode ghost mirrors these gates for instant+ // feedback, but a forged 'build' that skips them gets nothing here.+ _handleBuild(client, payload) {+ const p = this.state.players.get(client.sessionId);+ if (!p || p.dead) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ // You build with your hands, not from the saddle — mirrors the gather gate.+ if (p.mounted) { client.send('notice', { kind: 'build', text: 'Dismount before you build.' }); return; }+ if (!payload || typeof payload !== 'object') return;++ const kind = String(payload.kind ?? '');+ const def = STRUCTURE_DEFS[kind];+ if (!def) return;++ // Realm rules (Task 01): the realm must permit this structure kind. Shacks+ // are Whisperwood-only; firepits are allowed wherever building makes sense.+ if (!(this.realm.structures || []).includes(kind)) {+ client.send('notice', { kind: 'build', text: `You can’t build a ${kind} here.` });+ return;+ }++ if (!Number.isFinite(payload.tx) || !Number.isFinite(payload.ty)) return;+ const tx = payload.tx | 0;+ const ty = payload.ty | 0;++ // Must sit on a tile right next to the builder (8-way) — never under them.+ const dx = Math.abs(tx - p.tx);+ const dy = Math.abs(ty - p.ty);+ if (dx === 0 && dy === 0) { client.send('notice', { kind: 'build', text: 'Step back a tile to place it.' }); return; }+ if (dx > 1 || dy > 1) { client.send('notice', { kind: 'build', text: 'Build on a tile right beside you.' }); return; }++ // The tile must be free and buildable: walkable (so not blocked, not on a+ // node/mob/another structure) and clear of portals, the bank counter, the+ // fountain, fishing/cooking spots, and any standing player.+ if (!this._isBuildable(tx, ty)) { client.send('notice', { kind: 'build', text: 'You can’t build there.' }); return; }++ // Per-player cap (shack: one). Counted on the live structure map.+ if (Number.isFinite(def.cap)) {+ let owned = 0;+ for (const [, s] of this.state.structures) if (s.kind === kind && s.owner === p.id) owned++;+ if (owned >= def.cap) {+ client.send('notice', { kind: 'build', text: `You can only have ${def.cap} ${kind}${def.cap === 1 ? '' : 's'} — pick it up first.` });+ return;+ }+ }++ // Exact material cost — verify the whole bill is payable before spending any+ // of it, then deduct atomically.+ if (!this._canAfford(p, def.cost)) {+ client.send('notice', { kind: 'build', text: `Need ${this._missingCost(p, def.cost)} to build a ${kind}.` });+ return;+ }+ this._spendCost(p, def.cost);++ const now = Date.now();+ const s = new Structure();+ s.id = `st_${this.realm.name}_${p.id}_${++this._structSeq}`;+ s.kind = kind;+ s.owner = p.id;+ s.ownerName = p.name;+ s.tx = tx;+ s.ty = ty;+ s.expiresAt = def.lifetimeMs ? now + def.lifetimeMs : 0;+ s.locked = false;+ this.state.structures.set(s.id, s);+ p.tsServer = now;+ client.send('notice', { kind: 'build', text: `Built a ${kind}.` });+ }++ // A tile is buildable when it's walkable (bounds + not blocked + no node/mob/+ // structure on it) AND clear of the interactive/landmark tiles a structure+ // must never cover or block: portals, the bank counter, the fountain, and the+ // fishing/cooking spots — plus any tile a player is currently standing on.+ _isBuildable(tx, ty) {+ if (!this._isWalkable(tx, ty)) return false;+ for (const [, pl] of this.state.players) {+ if (!pl.dead && pl.tx === tx && pl.ty === ty) return false;+ }+ if (portalAt(this.realm, tx, ty)) return false;+ if ((this.realm.bankZone || []).some((t) => t.tx === tx && t.ty === ty)) return false;+ const f = this.realm.fountain;+ if (f && f.tx === tx && f.ty === ty) return false;+ for (const sp of this.realm.fishing || []) if (sp.tx === tx && sp.ty === ty) return false;+ for (const ck of this.realm.cooking || []) if (ck.tx === tx && ck.ty === ty) return false;+ return true;+ }++ // Total quantity of `item` the player holds across backpack + hotbar — materials+ // usually live in the backpack, but count both so a stack dragged to the hotbar+ // still pays.+ _countMaterial(p, item) {+ let n = 0;+ for (const s of p.inv) if (s.item === item) n += s.qty;+ for (const s of p.hotbar) if (s.item === item) n += s.qty;+ return n;+ }++ _canAfford(p, cost) {+ for (const [item, qty] of Object.entries(cost)) {+ if (this._countMaterial(p, item) < qty) return false;+ }+ return true;+ }++ // A human-readable summary of what the player is short for `cost` — drives the+ // honest "Need 200 more wood" notice.+ _missingCost(p, cost) {+ const parts = [];+ for (const [item, qty] of Object.entries(cost)) {+ const short = qty - this._countMaterial(p, item);+ if (short > 0) parts.push(`${short} more ${itemLabel(item)}`);+ }+ return parts.join(', ');+ }++ // Atomically remove a paid cost from the pack (backpack first, then hotbar),+ // emptying slots as they zero out. Only ever called after _canAfford passes, so+ // it never under-pays or drives a slot negative.+ _spendCost(p, cost) {+ for (const [item, qty] of Object.entries(cost)) {+ let left = qty;+ for (const arr of [p.inv, p.hotbar]) {+ for (const s of arr) {+ if (left <= 0) break;+ if (s.item !== item) continue;+ const take = Math.min(s.qty, left);+ s.qty -= take;+ left -= take;+ if (s.qty === 0) s.item = '';+ }+ }+ }+ }++ // ----- structure actions (firepit/shack; invoked by /pickup /lock /unlock) ----// These operate on real synced state.structures and never throw on the empty- // case: until Task 07's building action places a structure the map is empty, so- // they honestly report "nothing placed" — and the moment structures exist they- // work unchanged. Only the owner can act, and only on a structure beside them.+ // case: with no structure placed they honestly report "nothing placed". Only the+ // owner can act, and only on a structure beside them.pickupStructure(p) {const owned = [];@@ -1183,14 +1786,721 @@ export class GameRoom extends Room {return out;}- // Persist the player's quest state through the Task 16 save interface, keyed- // by the stable account id. Read-merge-write so we only ever own the quest- // slice and never clobber other persisted fields.+ // Persist the player's cross-session state through the Task 16 save interface,+ // keyed by the stable account id. Read-merge-write so we only ever own the+ // slices we manage (quests, gold, cosmetics) and never clobber other fields a+ // future system persists. Gold + owned/equipped cosmetics ride here so a+ // purchase and the look the player chose survive a disconnect/realm transfer._persistPlayer(sessionId) {const priv = this.priv.get(sessionId);- if (!priv || !priv.playerId || !priv.quests) return;+ if (!priv || !priv.playerId) return;+ const p = this.state.players.get(sessionId);const prev = loadPlayer(priv.playerId) || {};- savePlayer(priv.playerId, { ...prev, quests: priv.quests });+ const next = { ...prev };+ if (priv.quests) next.quests = priv.quests;+ if (p) {+ next.gold = p.gold;+ next.name = p.name;+ // Full account-scoped profile (Task 16/23): inventory, hotbar, bank,+ // skills, and mount, so the same account loads identical progression on+ // any world instance. Same shape a portal carry uses (_serializeProfile).+ next.profile = this._serializeProfile(p, priv);+ }+ if (priv.cosmetics) {+ next.cosmetics = { owned: [...priv.cosmetics.owned], equipped: priv.cosmetics.equipped };+ }+ if (priv.spin) next.spin = { nextFreeSpinAt: priv.spin.nextFreeSpinAt | 0 };+ savePlayer(priv.playerId, next);+ }++ // ----- cosmetics shop (Task 21) ----------------------------------------++ // Rebuild a player's owned/equipped cosmetics from a persisted save, dropping+ // any id no longer in the catalogue (so a removed cosmetic never lingers) and+ // guaranteeing the equipped id is one the player actually owns.+ _loadCosmetics(saved) {+ const ownedIds = Array.isArray(saved?.cosmetics?.owned) ? saved.cosmetics.owned : [];+ const owned = new Set(ownedIds.filter((id) => cosmeticById(id)));+ const wanted = saved?.cosmetics?.equipped || '';+ const equipped = owned.has(wanted) ? wanted : '';+ return { owned, equipped };+ }++ // Send the requesting player the live shop board: the full catalogue, which+ // ids are on sale right now (split daily/weekly/always), the next-rotation+ // timestamps for real countdowns, the ids they already own, their equipped id,+ // and their current gold. Everything the shop + wardrobe render from.+ // Client 'shopOpen' request — rate-limited like any UI fetch, then emits the+ // board. The post-mutation refreshes (after buy/equip/unequip) go through+ // _emitShop directly: they are server-initiated, not client requests, so they+ // must never be dropped by the rate limiter or the UI would show stale state.+ _sendShop(client) {+ if (!this._rateOk(client.sessionId, 'ui')) return;+ this._emitShop(client);+ }++ _emitShop(client) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv || !priv.cosmetics) return;+ client.send('shop', {+ offers: currentOffers(Date.now()),+ owned: [...priv.cosmetics.owned],+ equipped: priv.cosmetics.equipped,+ gold: p.gold,+ });+ }++ // Buy a cosmetic: it must exist, be on sale in the current rotation, not be+ // already owned, and the player must have the gold. On success we debit gold,+ // grant permanent ownership, persist, and refresh the board. Every failure+ // path returns a clear notice instead of silently no-op'ing.+ _handleBuyCosmetic(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv || !priv.cosmetics) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ const id = String(payload?.id ?? '');+ const cosmetic = cosmeticById(id);+ if (!cosmetic) { client.send('notice', { kind: 'shop', text: 'That cosmetic doesn’t exist.' }); return; }+ if (priv.cosmetics.owned.has(id)) {+ client.send('notice', { kind: 'shop', text: `You already own the ${cosmetic.name}.` });+ return;+ }+ if (!isOffered(id, Date.now())) {+ client.send('notice', { kind: 'shop', text: `The ${cosmetic.name} isn’t on sale right now.` });+ return;+ }+ if (p.gold < cosmetic.price) {+ client.send('notice', { kind: 'shop', text: `Need ${cosmetic.price - p.gold} more gold for the ${cosmetic.name}.` });+ return;+ }+ p.gold -= cosmetic.price;+ priv.cosmetics.owned.add(id);+ p.tsServer = Date.now();+ this._persistPlayer(client.sessionId);+ client.send('notice', { kind: 'shop', text: `Bought the ${cosmetic.name}!` });+ this._emitShop(client);+ }++ // Equip an owned cosmetic — sets the synced cosmeticId so every peer renders+ // the new look, persists the choice, and refreshes the board. Equipping is+ // purely visual: it never touches gold, stats, inventory, or any gameplay+ // value. You can only equip a cosmetic you actually own.+ _handleEquipCosmetic(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv || !priv.cosmetics) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ const id = String(payload?.id ?? '');+ if (!priv.cosmetics.owned.has(id)) {+ client.send('notice', { kind: 'shop', text: 'You don’t own that cosmetic.' });+ return;+ }+ if (priv.cosmetics.equipped === id) return;+ priv.cosmetics.equipped = id;+ p.cosmeticId = id;+ p.tsServer = Date.now();+ this._persistPlayer(client.sessionId);+ client.send('notice', { kind: 'shop', text: `Equipped the ${cosmeticById(id)?.name || 'cosmetic'}.` });+ this._emitShop(client);+ }++ // Revert to the default look — clears the equipped cosmetic. Always allowed+ // (no-op if nothing is equipped) and, like equipping, strictly visual.+ _handleUnequipCosmetic(client) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv || !priv.cosmetics) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ if (!priv.cosmetics.equipped) return;+ priv.cosmetics.equipped = '';+ p.cosmeticId = '';+ p.tsServer = Date.now();+ this._persistPlayer(client.sessionId);+ client.send('notice', { kind: 'shop', text: 'Reverted to your default look.' });+ this._emitShop(client);+ }++ // ----- marketplace (Task 20) -------------------------------------------+ //+ // A global, account-scoped player-to-player market backed by marketplaceStore+ // (durable, process-wide) so a buyer in any realm can purchase goods a seller+ // listed from anywhere. Two listing types:+ // • gold — an item stack for in-game gold; seller gets the full+ // amount, no fee. Buyer pays gold, receives the item.+ // • goldForToken — in-game gold priced in USD, paid on-chain with $THREE.+ // 95% of the token goes to the seller's wallet, 5% to the+ // treasury; the buyer receives the escrowed gold once the+ // payment is verified on-chain.+ // The offered goods are escrowed on the listing the moment it's created — they+ // leave the seller's inventory/purse immediately — so nothing can be listed and+ // spent twice. Cancel returns the escrow; a sale delivers it to the buyer.++ // Send the requesting player the live market board: every active listing, their+ // own listings (any status), and the token-payment capability flags the Sell+ // tab needs to decide whether goldForToken listings are offerable.+ _sendMarket(client) {+ const priv = this.priv.get(client.sessionId);+ if (!priv) return;+ if (!this._rateOk(client.sessionId, 'ui')) return;+ const me = priv.playerId;+ client.send('market', {+ listings: marketplaceStore.activeListings().map((l) => this._marketView(l, me)),+ mine: marketplaceStore.listingsBySeller(me).map((l) => this._marketView(l, me)),+ token: { enabled: tokenConfigured(), symbol: TOKEN_SYMBOL, decimals: TOKEN_DECIMALS, treasuryBps: MARKET_TREASURY_BPS },+ canToken: isWalletAddress(me),+ });+ }++ // A client-safe projection of a listing. The seller's account id is never sent —+ // only their display name — and `mine` lets the UI badge/disable a viewer's own+ // listings on the Buy tab.+ _marketView(l, viewerId) {+ const v = {+ id: l.id,+ type: l.type,+ seller: l.sellerName || 'Trader',+ mine: l.seller === viewerId,+ status: l.status,+ createdAt: l.createdAt,+ };+ if (l.type === 'gold') { v.item = l.item; v.qty = l.qty; v.priceGold = l.priceGold; }+ else { v.goldAmount = l.goldAmount; v.priceUsd = l.priceUsd; }+ if (l.status !== 'active') { v.buyer = l.buyerName || null; v.closedAt = l.closedAt || null; }+ return v;+ }++ // Create a listing, escrowing the offered goods out of the seller immediately.+ _handleMarketList(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'mkt')) return;+ const type = payload?.type === 'goldForToken' ? 'goldForToken' : 'gold';++ const activeCount = marketplaceStore.listingsBySeller(priv.playerId).filter((l) => l.status === 'active').length;+ if (activeCount >= MAX_LISTINGS_PER_SELLER) {+ client.send('notice', { kind: 'market', text: `You can have at most ${MAX_LISTINGS_PER_SELLER} active listings.` });+ return;+ }++ if (type === 'gold') {+ const item = typeof payload?.item === 'string' ? payload.item : '';+ const qty = Math.max(1, Math.min(MAX_STACK, payload?.qty | 0));+ const priceGold = Math.max(1, Math.min(MARKET_GOLD_MAX, payload?.priceGold | 0));+ if (!item || !Number.isFinite(payload?.qty) || !Number.isFinite(payload?.priceGold)) {+ client.send('notice', { kind: 'market', text: 'Pick an item, amount, and price.' });+ return;+ }+ // Escrow: pull the exact quantity out of the backpack. If the player doesn't+ // actually hold it, _removeInvItem returns what it could remove — we restore+ // it and refuse, so a listing can never escrow goods that weren't there.+ const removed = this._removeInvItem(p, item, qty);+ if (removed < qty) {+ if (removed > 0) this._addItem(p, item, removed); // put back the partial pull+ client.send('notice', { kind: 'market', text: `You don't have ${qty} ${itemLabel(item)} to list.` });+ return;+ }+ const rec = marketplaceStore.create({+ seller: priv.playerId, sellerName: p.name, type: 'gold',+ item, qty, priceGold,+ });+ p.tsServer = Date.now();+ this._persistPlayer(client.sessionId);+ client.send('notice', { kind: 'market', text: `Listed ${qty}× ${itemLabel(item)} for ${priceGold} gold.` });+ this._broadcastMarketDirty();+ this._sendMarket(client);+ return;+ }++ // goldForToken — list in-game gold priced in USD, settled on-chain in $THREE.+ if (!tokenConfigured()) {+ client.send('notice', { kind: 'market', text: 'Token sales are unavailable right now.' });+ return;+ }+ if (!isWalletAddress(priv.playerId)) {+ client.send('notice', { kind: 'market', text: 'Connect a wallet to sell gold for tokens.' });+ return;+ }+ const goldAmount = Math.max(1, Math.min(MARKET_GOLD_MAX, payload?.goldAmount | 0));+ const priceUsd = Number(payload?.priceUsd);+ if (!Number.isFinite(payload?.goldAmount) || !Number.isFinite(priceUsd) || priceUsd < MARKET_USD_MIN || priceUsd > MARKET_USD_MAX) {+ client.send('notice', { kind: 'market', text: `Set a gold amount and a USD price ($${MARKET_USD_MIN}–$${MARKET_USD_MAX}).` });+ return;+ }+ if (p.gold < goldAmount) {+ client.send('notice', { kind: 'market', text: `You only have ${p.gold} gold to list.` });+ return;+ }+ // Escrow the gold out of the purse now.+ p.gold -= goldAmount;+ const rec = marketplaceStore.create({+ seller: priv.playerId, sellerName: p.name, type: 'goldForToken',+ goldAmount, priceUsd: Math.round(priceUsd * 100) / 100, sellerWallet: priv.playerId,+ });+ p.tsServer = Date.now();+ this._persistPlayer(client.sessionId);+ client.send('notice', { kind: 'market', text: `Listed ${goldAmount} gold for $${rec.priceUsd} in ${TOKEN_SYMBOL}.` });+ this._broadcastMarketDirty();+ this._sendMarket(client);+ }++ // Cancel a listing you own and reclaim the escrow. Active listings only.+ _handleMarketCancel(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'mkt')) return;+ const l = marketplaceStore.get(String(payload?.id ?? ''));+ if (!l || l.seller !== priv.playerId) { client.send('notice', { kind: 'market', text: 'Listing not found.' }); return; }+ if (l.status !== 'active') { client.send('notice', { kind: 'market', text: 'That listing is no longer active.' }); return; }++ marketplaceStore.update(l.id, { status: 'cancelled', closedAt: Date.now() });+ if (l.type === 'gold') {+ this._deliverItemsTo(p, priv, l.item, l.qty);+ client.send('notice', { kind: 'market', text: `Cancelled — ${l.qty}× ${itemLabel(l.item)} returned.` });+ } else {+ p.gold = Math.min(MARKET_GOLD_MAX, p.gold + l.goldAmount);+ client.send('notice', { kind: 'market', text: `Cancelled — ${l.goldAmount} gold returned.` });+ }+ p.tsServer = Date.now();+ this._persistPlayer(client.sessionId);+ this._broadcastMarketDirty();+ this._sendMarket(client);+ }++ // Buy a gold listing with in-game gold: debit the buyer, deliver the escrowed+ // item, and credit the seller the full price (no fee). Synchronous, so the+ // check-and-claim is atomic — two buyers can't both win the same listing.+ _handleMarketBuyGold(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'mkt')) return;+ const l = marketplaceStore.get(String(payload?.id ?? ''));+ if (!l || l.type !== 'gold') { client.send('notice', { kind: 'market', text: 'Listing not found.' }); return; }+ if (l.status !== 'active') { client.send('notice', { kind: 'market', text: 'That listing was just taken.' }); return; }+ if (l.seller === priv.playerId) { client.send('notice', { kind: 'market', text: "You can't buy your own listing." }); return; }+ if (p.gold < l.priceGold) {+ client.send('notice', { kind: 'market', text: `Need ${l.priceGold - p.gold} more gold.` });+ return;+ }+ // Claim the listing before mutating balances so a duplicate buy that slips in+ // finds it already sold.+ marketplaceStore.update(l.id, { status: 'sold', buyer: priv.playerId, buyerName: p.name, closedAt: Date.now() });+ p.gold -= l.priceGold;+ this._deliverItemsTo(p, priv, l.item, l.qty);+ // Pay the seller their gold wherever they are (or queue it durably if offline).+ this._payGoldTo(l.seller, l.priceGold, `Sold ${l.qty}× ${itemLabel(l.item)}`);+ p.tsServer = Date.now();+ this._persistPlayer(client.sessionId);+ client.send('notice', { kind: 'market', text: `Bought ${l.qty}× ${itemLabel(l.item)} for ${l.priceGold} gold.` });+ this._broadcastMarketDirty();+ this._sendMarket(client);+ }++ // Step 1 of an on-chain token purchase: quote the live $THREE amount for the+ // listing's USD price, build the unsigned split transaction (95% seller wallet+ // / 5% treasury) the buyer signs, and hand back a signed quote that binds the+ // amounts + recipients so the client can't tamper before settling.+ async _handleMarketTokenQuote(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'mkt')) return;+ if (!tokenConfigured()) { client.send('notice', { kind: 'market', text: 'Token payments are unavailable.' }); return; }+ const buyerWallet = priv.playerId;+ if (!isWalletAddress(buyerWallet)) {+ client.send('notice', { kind: 'market', text: 'Connect a Solana wallet to pay with tokens.' });+ return;+ }+ const l = marketplaceStore.get(String(payload?.id ?? ''));+ if (!l || l.type !== 'goldForToken' || l.status !== 'active') {+ client.send('notice', { kind: 'market', text: 'That listing is no longer available.' });+ return;+ }+ if (l.seller === buyerWallet) { client.send('notice', { kind: 'market', text: "You can't buy your own listing." }); return; }++ const quote = await quoteTokenForUsd(l.priceUsd);+ if (!quote) { client.send('notice', { kind: 'market', text: 'Live price unavailable — try again in a moment.' }); return; }+ // Re-check the listing survived the awaited quote (it could have been bought+ // or cancelled while we fetched the price).+ const still = marketplaceStore.get(l.id);+ if (!still || still.status !== 'active') { client.send('notice', { kind: 'market', text: 'That listing is no longer available.' }); return; }++ const { seller: sellerRaw, treasury: treasuryRaw } = splitAmount(quote.raw, MARKET_TREASURY_BPS);+ let txB64;+ try {+ txB64 = await buildSplitTransaction({+ buyerWallet, sellerWallet: l.sellerWallet,+ sellerRaw: sellerRaw.toString(), treasuryRaw: treasuryRaw.toString(),+ });+ } catch (err) {+ console.warn('[market] build split tx failed:', err?.message);+ client.send('notice', { kind: 'market', text: 'Could not prepare the payment. Try again.' });+ return;+ }+ const signed = signQuote({+ listingId: l.id, buyer: buyerWallet, sellerWallet: l.sellerWallet,+ usd: l.priceUsd, total: quote.raw.toString(), sellerRaw: sellerRaw.toString(), treasuryRaw: treasuryRaw.toString(),+ });+ client.send('marketQuote', {+ id: l.id,+ tx: txB64,+ quote: signed,+ symbol: TOKEN_SYMBOL,+ decimals: TOKEN_DECIMALS,+ tokenAmount: quote.raw.toString(),+ sellerAmount: sellerRaw.toString(),+ treasuryAmount: treasuryRaw.toString(),+ priceUsd: l.priceUsd,+ goldAmount: l.goldAmount,+ ttlMs: 90_000,+ });+ }++ // Step 2: the buyer has broadcast the signed transaction. Verify it on-chain+ // (both legs landed at the right destinations for the quoted amounts), then+ // release the escrowed gold to the buyer. The seller was paid directly in the+ // transaction. Goods are NEVER released before the payment verifies.+ async _handleMarketTokenSettle(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'mkt')) return;+ const q = verifyQuote(payload?.quote);+ if (!q) { client.send('notice', { kind: 'market', text: 'Your quote expired — get a fresh one.' }); return; }+ if (q.buyer !== priv.playerId) { client.send('notice', { kind: 'market', text: 'That quote was issued to a different wallet.' }); return; }+ const txSig = typeof payload?.txSig === 'string' ? payload.txSig.trim() : '';+ if (!txSig) { client.send('notice', { kind: 'market', text: 'Missing transaction signature.' }); return; }+ if (marketplaceStore.isSettled(txSig)) { client.send('notice', { kind: 'market', text: 'That payment was already settled.' }); return; }++ const l = marketplaceStore.get(q.listingId);+ if (!l || l.type !== 'goldForToken' || l.sellerWallet !== q.sellerWallet) {+ client.send('notice', { kind: 'market', text: 'That listing is no longer available.' });+ return;+ }+ if (l.status !== 'active') { client.send('notice', { kind: 'market', text: 'That listing is no longer available.' }); return; }+ // Claim it synchronously before the async verify so a second settle can't+ // double-release the same gold. Reverted to active if verification fails.+ marketplaceStore.update(l.id, { status: 'settling' });++ const verify = await verifySplitPayment({+ txSig, sellerWallet: q.sellerWallet, sellerRaw: q.sellerRaw, treasuryRaw: q.treasuryRaw,+ });+ const current = marketplaceStore.get(l.id);+ if (!current || current.status !== 'settling') {+ // Cancelled/evicted out from under us mid-verify — don't release.+ client.send('notice', { kind: 'market', text: 'That listing is no longer available.' });+ return;+ }+ if (!verify.ok) {+ marketplaceStore.update(l.id, { status: 'active' });+ const why = verify.reason === 'not_found' ? 'Payment not found on-chain yet — wait for confirmation and retry.'+ : verify.reason?.includes('underpaid') ? 'The payment amount did not match the quote.'+ : 'Could not verify the payment. No gold was released.';+ client.send('notice', { kind: 'market', text: why });+ return;+ }+ // Verified. Consume the signature, close the listing, deliver the gold.+ marketplaceStore.markSettled(txSig);+ marketplaceStore.update(l.id, { status: 'sold', buyer: priv.playerId, buyerName: p.name, txSig, closedAt: Date.now() });+ p.gold = Math.min(MARKET_GOLD_MAX, p.gold + l.goldAmount);+ p.tsServer = Date.now();+ this._persistPlayer(client.sessionId);+ client.send('marketSettled', { id: l.id, goldAmount: l.goldAmount, txSig });+ client.send('notice', { kind: 'market', text: `Paid — received ${l.goldAmount} gold.` });+ this._broadcastMarketDirty();+ this._sendMarket(client);+ }++ // ----- Wheel of Fortune (Task 19) --------------------------------------+ //+ // A 20-segment prize wheel by the Mainland casino. One free spin per account+ // every 12h, plus unlimited paid spins ($3 in $THREE, 50% burned / 50% to+ // treasury, settled on-chain). The SERVER rolls every outcome (spin-wheel.js);+ // the client only animates to the chosen segment. Spinning needs an average+ // skill level of SPIN_MIN_AVG_LEVEL and standing at the wheel.++ // True when the player stands on a tile adjacent (8-way) to the realm's wheel+ // landmark — the same "be at the counter" rule banking uses, so a client can't+ // spin from across the map.+ _atWheel(p) {+ const w = wheelLandmark(this.realm);+ return !!w && Math.abs(p.tx - w.tx) <= 1 && Math.abs(p.ty - w.ty) <= 1;+ }++ // Full spin gate (free + paid prep): the realm has a wheel, the player is at+ // it, and their average level qualifies. Returns a reason code, or null when+ // allowed. The level gate can never regress (levels only climb), so settle+ // re-checks level only — a player who paid then got nudged off the tile still+ // gets their spin.+ _spinBlockReason(p) {+ if (!wheelLandmark(this.realm)) return 'no_wheel';+ if (!this._atWheel(p)) return 'not_at_wheel';+ if (this._averageLevel(p) < SPIN_MIN_AVG_LEVEL) return 'level';+ return null;+ }++ // Tell the client exactly why a spin was refused, always with the fields its+ // designed states need (current/required level, free-spin countdown).+ _sendSpinDenied(client, p, priv, mode, reason) {+ client.send('spinDenied', {+ mode,+ reason,+ avgLevel: Math.round(this._averageLevel(p) * 10) / 10,+ minLevel: SPIN_MIN_AVG_LEVEL,+ nextFreeSpinAt: priv.spin.nextFreeSpinAt | 0,+ now: Date.now(),+ });+ }++ // Snapshot for the spinner UI: the authoritative segment table (with honest+ // odds), the player's standing against the level gate, the free-spin countdown,+ // and whether a paid spin is available (token configured + wallet connected).+ _sendSpinInfo(client) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'spin')) return;+ const avg = this._averageLevel(p);+ client.send('spinInfo', {+ segments: spinSegments(),+ avgLevel: Math.round(avg * 10) / 10,+ minLevel: SPIN_MIN_AVG_LEVEL,+ eligible: avg >= SPIN_MIN_AVG_LEVEL,+ atWheel: this._atWheel(p),+ nextFreeSpinAt: priv.spin.nextFreeSpinAt | 0,+ now: Date.now(),+ costUsd: PAID_SPIN_USD,+ symbol: TOKEN_SYMBOL,+ paidAvailable: tokenConfigured() && isWalletAddress(priv.playerId),+ });+ }++ // Roll one prize and grant it. Gold lands in the purse; items go to the+ // backpack and any overflow spills into a ground bag at the player's feet (the+ // same vessel mob loot uses), so a prize is never silently lost on a full pack.+ // Returns the server-decided segment + what actually landed for the client.+ _rollAndAward(client, p) {+ const roll = rollSpin();+ let awardedGold = 0, awardedQty = 0, overflow = 0;+ if (roll.kind === 'gold') {+ const before = p.gold;+ p.gold = Math.min(0xffffffff, p.gold + roll.gold);+ awardedGold = p.gold - before;+ } else {+ const left = this._addItem(p, roll.item, roll.qty);+ awardedQty = roll.qty - left;+ if (left > 0) { this._spawnLootBag(p, p.tx, p.ty, [new Slot(roll.item, left)]); overflow = left; }+ }+ p.tsServer = Date.now();+ const tail = overflow > 0 ? ` — ${overflow} waited in a bag at your feet (pack full)` : '';+ client.send('notice', { kind: 'spin', text: `The wheel landed on ${roll.label}!${tail}` });+ return {+ index: roll.index, kind: roll.kind, item: roll.item, qty: roll.qty, gold: roll.gold,+ label: roll.label, awardedGold, awardedQty, overflow,+ };+ }++ // Free spin: gated by level + wheel proximity + the persisted 12h cooldown.+ // The timer is consumed before the roll so the spin can't be repeated, and the+ // new nextFreeSpinAt is persisted + returned for the client's live countdown.+ _handleSpinFree(client) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'spin')) return;+ const reason = this._spinBlockReason(p);+ if (reason) { this._sendSpinDenied(client, p, priv, 'free', reason); return; }+ const now = Date.now();+ if (now < (priv.spin.nextFreeSpinAt | 0)) {+ this._sendSpinDenied(client, p, priv, 'free', 'cooldown');+ return;+ }+ priv.spin.nextFreeSpinAt = now + FREE_SPIN_COOLDOWN_MS;+ const result = this._rollAndAward(client, p);+ this._persistPlayer(client.sessionId);+ client.send('spinResult', { mode: 'free', ...result, nextFreeSpinAt: priv.spin.nextFreeSpinAt, now: Date.now() });+ }++ // Paid spin, step 1: price $3 in $THREE, build the 50/50 burn/treasury split+ // transaction the wallet signs, and hand back a signed quote binding the+ // amounts + destinations. No prize is rolled here — only after the payment+ // verifies at settle. Gated identically to a free spin so an ineligible player+ // can't even start paying.+ async _handleSpinPaidPrep(client) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'spin')) return;+ const reason = this._spinBlockReason(p);+ if (reason) { this._sendSpinDenied(client, p, priv, 'paid', reason); return; }+ if (!tokenConfigured()) { client.send('spinDenied', { mode: 'paid', reason: 'token_unavailable' }); return; }+ const buyerWallet = priv.playerId;+ if (!isWalletAddress(buyerWallet)) { client.send('spinDenied', { mode: 'paid', reason: 'no_wallet' }); return; }+ let prep;+ try {+ prep = await buildSpinPayment({ buyerWallet, usd: PAID_SPIN_USD });+ } catch (err) {+ console.warn('[spin] build payment failed:', err?.message);+ client.send('spinDenied', { mode: 'paid', reason: 'build_failed' });+ return;+ }+ if (!prep) { client.send('spinDenied', { mode: 'paid', reason: 'price_unavailable' }); return; }+ client.send('spinPrep', {+ tx: prep.txBase64,+ quote: prep.quoteToken,+ symbol: TOKEN_SYMBOL,+ decimals: TOKEN_DECIMALS,+ costUsd: PAID_SPIN_USD,+ tokenAmount: prep.quote.total,+ tokens: prep.quote.tokens,+ priceUsd: prep.quote.priceUsd,+ burnAmount: prep.quote.burnRaw,+ treasuryAmount: prep.quote.treasuryRaw,+ ttlMs: (prep.quote.ttlSeconds || 90) * 1000,+ });+ }++ // Paid spin, step 2: the wallet broadcast the signed transaction. Verify it+ // on-chain (both the burn and treasury legs landed, memo matches the quote),+ // reject replays, THEN roll + award. The free-spin timer is never touched.+ async _handleSpinPaidSettle(client, payload) {+ const p = this.state.players.get(client.sessionId);+ const priv = this.priv.get(client.sessionId);+ if (!p || !priv) return;+ if (!this._rateOk(client.sessionId, 'spin')) return;+ // Level can't regress mid-flow, so re-checking it (not wheel proximity) at+ // settle keeps a paid spin valid even if the player drifted off the tile+ // while approving in their wallet — they already committed real funds.+ if (this._averageLevel(p) < SPIN_MIN_AVG_LEVEL) { this._sendSpinDenied(client, p, priv, 'paid', 'level'); return; }+ const buyerWallet = priv.playerId;+ const txSig = typeof payload?.txSig === 'string' ? payload.txSig.trim() : '';+ if (!txSig) { client.send('spinDenied', { mode: 'paid', reason: 'no_signature' }); return; }+ if (isSpinSettled(txSig)) { client.send('spinDenied', { mode: 'paid', reason: 'already_settled' }); return; }++ const verify = await verifySpinPayment({ quoteToken: payload?.quote, txSig, buyerWallet });+ if (!verify.ok) {+ const why = verify.reason === 'not_found' ? 'not_found'+ : verify.reason?.includes('underpaid') ? 'underpaid'+ : verify.reason === 'bad_quote' ? 'quote_expired'+ : 'verify_failed';+ client.send('spinDenied', { mode: 'paid', reason: why });+ return;+ }+ // Consume the signature BEFORE awarding so a concurrent/duplicate settle of+ // the same payment can never roll a second prize.+ markSpinSettled(txSig);+ const result = this._rollAndAward(client, p);+ this._persistPlayer(client.sessionId);+ client.send('spinResult', { mode: 'paid', ...result, txSig, nextFreeSpinAt: priv.spin.nextFreeSpinAt | 0, now: Date.now() });+ }++ // Credit a seller their gold proceeds. If they're online (in this room or any+ // other), the durable payout we enqueue is drained immediately via a presence+ // nudge; if they're offline it waits in the queue until their next login. Either+ // way the queue is the single source of truth, so delivery is exactly-once.+ _payGoldTo(sellerId, gold, reason) {+ marketplaceStore.enqueuePayout(sellerId, { gold, reason });+ try { this.presence.publish(payoutChannel(sellerId), { ts: Date.now() }); } catch {}+ // Fast path: if the seller is in THIS room, draining now avoids a round-trip+ // through pub/sub (and covers presence backends that don't echo to the+ // publishing process).+ for (const [sid, pr] of this.priv) {+ if (pr.playerId === sellerId) { this._drainMarketPayouts(sid); break; }+ }+ }++ // Deliver all queued marketplace proceeds for a session's account: gold into the+ // purse, items into the backpack (overflow to the bank, then re-queued if even+ // the bank is full so nothing is ever lost). Atomic drain — whether triggered by+ // a login or a live nudge, each payout is applied exactly once.+ _drainMarketPayouts(sessionId) {+ const p = this.state.players.get(sessionId);+ const priv = this.priv.get(sessionId);+ if (!p || !priv) return;+ const payouts = marketplaceStore.drainPayouts(priv.playerId);+ if (!payouts.length) return;+ let goldGained = 0;+ const itemsGained = [];+ for (const po of payouts) {+ if (po.gold) {+ const before = p.gold;+ p.gold = Math.min(MARKET_GOLD_MAX, p.gold + (po.gold | 0));+ goldGained += p.gold - before;+ }+ if (Array.isArray(po.items)) {+ for (const it of po.items) {+ if (it && it.item && it.qty > 0) {+ // Use the no-nudge delivery so a bank-full re-queue doesn't loop.+ const left = this._stowItem(p, priv, it.item, it.qty);+ const placed = it.qty - left;+ if (placed > 0) itemsGained.push({ item: it.item, qty: placed });+ if (left > 0) marketplaceStore.enqueuePayout(priv.playerId, { items: [{ item: it.item, qty: left }], reason: 'overflow' });+ }+ }+ }+ }+ p.tsServer = Date.now();+ this._persistPlayer(sessionId);+ const c = this._clientFor(sessionId);+ if (c && (goldGained > 0 || itemsGained.length)) {+ c.send('marketPayout', { gold: goldGained, items: itemsGained });+ }+ }++ // Tell every client in this room their open market panel is stale so it+ // refetches. Cross-room/realm panels refresh on their own open + poll; this just+ // keeps same-room browsers live as listings appear and sell.+ _broadcastMarketDirty() {+ this.broadcast('marketDirty', {});+ }++ // ----- marketplace item helpers ----------------------------------------++ // Total quantity of `item` the player holds in their backpack (not hotbar).+ _countInvItem(p, item) {+ let n = 0;+ for (const s of p.inv) if (s.item === item) n += s.qty;+ return n;+ }++ // Remove up to `qty` of `item` from the backpack, emptying slots as they drain.+ // Returns the quantity actually removed (< qty if the player didn't have enough).+ _removeInvItem(p, item, qty) {+ let need = qty;+ for (const s of p.inv) {+ if (need <= 0) break;+ if (s.item !== item) continue;+ const take = Math.min(s.qty, need);+ s.qty -= take;+ need -= take;+ if (s.qty <= 0) { s.item = ''; s.qty = 0; }+ }+ return qty - need;+ }++ // Place items into the backpack, overflowing to the bank, returning whatever+ // still didn't fit. No side effects beyond inventory/bank — used by the payout+ // drainer where re-queueing (not a nudge) handles a true overflow.+ _stowItem(p, priv, item, qty) {+ let left = this._addItem(p, item, qty);+ if (left > 0 && priv?.bank) left = this._bankAdd(priv.bank, item, left);+ return left;+ }++ // Deliver listing escrow back to a player on cancel / to a buyer on a gold sale:+ // backpack first, then bank, then a durable payout so a full inventory never+ // destroys the goods.+ _deliverItemsTo(p, priv, item, qty) {+ const left = this._stowItem(p, priv, item, qty);+ if (left > 0) {+ marketplaceStore.enqueuePayout(priv.playerId, { items: [{ item, qty: left }], reason: 'overflow' });+ const c = this._clientFor(p.id);+ if (c) c.send('notice', { kind: 'market', text: `${left}× ${itemLabel(item)} saved — your bags are full; claim it when you have room.` });+ }}// ----- inventory / hotbar ----------------------------------------------@@ -1405,6 +2715,22 @@ export class GameRoom extends Room {return sum;}+ // Authoritative combat level — the input every combat-level gate reads (Task 11).+ // Combat is its own trainable skill here, so the combat level IS that level; the+ // helper keeps the gate logic from reaching into the schema field directly, so a+ // future composite combat formula can change in exactly one place.+ _combatLevel(p) {+ return p.combat;+ }++ // Does the player clear a portal's gate? Today the only gate kind is a combat+ // floor; an unknown/empty gate never blocks (fail-open on shape, never on level).+ _meetsGate(p, gate) {+ if (!gate) return true;+ if (Number.isFinite(gate.combat) && this._combatLevel(p) < gate.combat) return false;+ return true;+ }+_adjacent(p, obj) {return Math.abs(p.tx - obj.tx) <= 1 && Math.abs(p.ty - obj.ty) <= 1;}@@ -1428,6 +2754,17 @@ export class GameRoom extends Room {_tick() {const now = Date.now();+ // Periodic profile autosave (Task 16/23). Most saves ride real events+ // (quest progress, gold/cosmetic changes, portal/leave), but a player who+ // only fishes or cooks could go a while without one — so flush every live+ // session about every 20s. Cheap (a few small objects into the store) and it+ // bounds how much progress a hard crash could cost. The leave/eviction paths+ // still save synchronously for the common case.+ if (++this._saveTick >= 80) {+ this._saveTick = 0;+ for (const sid of this.priv.keys()) this._persistPlayer(sid);+ }+// Resource + mob respawns.for (const [, n] of this.state.nodes) {if (n.depleted && now >= n.respawnAt) {@@ -1448,7 +2785,16 @@ export class GameRoom extends Room {if (now >= t.expiresAt) this.state.tombstones.delete(id);}- // Player healing + respawn — both keyed to THIS realm's spawn/fountain.+ // Player-built structures (Task 07): decay first, so a firepit never heals on+ // the same tick it burns out, then collect the live firepits for the heal pass.+ const firepits = [];+ for (const [id, s] of this.state.structures) {+ if (s.expiresAt && now >= s.expiresAt) { this.state.structures.delete(id); continue; }+ if (s.kind === 'firepit') firepits.push(s);+ }++ // Player healing + respawn — keyed to THIS realm's spawn/fountain, plus any+ // player-built firepit a player is standing beside.const fountain = this.realm.fountain;for (const [, p] of this.state.players) {if (p.dead) {@@ -1465,8 +2811,42 @@ export class GameRoom extends Room {if (p.hp < p.maxHp) {const nearFountain =!!fountain && Math.abs(p.tx - fountain.tx) <= 3 && Math.abs(p.ty - fountain.ty) <= 3;- p.hp = Math.min(p.maxHp, p.hp + (nearFountain ? FOUNTAIN_HEAL_PER_TICK : REGEN_PER_TICK));+ // A firepit heals players directly adjacent to it (8-way), at the+ // fountain's rate — a portable campfire heal.+ const nearFire = firepits.some((s) => Math.abs(p.tx - s.tx) <= 1 && Math.abs(p.ty - s.ty) <= 1);+ p.hp = Math.min(p.maxHp, p.hp + (nearFountain || nearFire ? FOUNTAIN_HEAL_PER_TICK : REGEN_PER_TICK));}}++ // Moving floor (Arena rollers): on its own slower cadence, shove every living+ // player who is standing on a roller one tile in the strip's direction. The+ // push is server-authoritative and respects walkability — it never moves a+ // player through a wall, onto a node/mob, off the map, or onto a portal tile+ // (rollers carry you around the floor; they never trigger a realm transfer).+ if (this.realm.rollers && now - (this._rollerAt || 0) >= ROLLER_PUSH_MS) {+ this._rollerAt = now;+ this._rollPlayers(now);+ }+ }++ // One roller push pass. Each player's destination is resolved against THIS+ // tick's occupancy, so two players can't be shoved onto the same tile in a way+ // that desyncs from walkability — the second simply isn't moved this push.+ _rollPlayers(now) {+ for (const [sid, p] of this.state.players) {+ if (p.dead) continue;+ if (this.priv.get(sid)?.transferring) continue;+ const roller = rollerAt(this.realm, p.tx, p.ty);+ if (!roller) continue;+ const [dx, dy] = rollerDelta(roller.dir);+ if (!dx && !dy) continue;+ const nx = p.tx + dx, ny = p.ty + dy;+ if (!this._isWalkable(nx, ny)) continue; // pushed against a wall/occupant — hold position+ if (portalAt(this.realm, nx, ny)) continue; // never roll a player through a portal+ p.tx = nx;+ p.ty = ny;+ p.motion = 'walk';+ p.tsServer = now;+ }}}diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 3407952b6..233722c4f 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -12,6 +12,21 @@ import { Player, Block, WalkState } from '../schemas.js';import { cleanAvatarUrl } from '../avatar-url.js';import { blockStore } from '../block-store.js';import { verifyHolderPass } from '../holder-pass.js';+import { socialHub } from '../social-hub.js';+import { verifyPresenceTicket } from '../presence-token.js';+import { verifyPlayPass } from '../play-pass.js';++// Platform entry gate (wallet-first sign-in + game-token balance). When a game+// token is pinned (PLAY_GATE_MINT, falling back to THREE_MINT) every join must+// carry a valid play pass — minted by api/play/verify after proving wallet+// ownership and a balance ≥ PLAY_GATE_MIN of that token. An unset mint leaves+// walk_world open exactly as before, so /walk and un-pinned deploys are+// unaffected. Read at boot: gate config doesn't change without a redeploy.+const PLAY_GATE_MINT = (process.env.PLAY_GATE_MINT || process.env.THREE_MINT || '').trim();+const PLAY_GATE_MIN = (() => {+ const n = Number(process.env.PLAY_GATE_MIN);+ return Number.isFinite(n) && n > 0 ? n : 1;+})();const MAX_CLIENTS_PER_ROOM = 50;const PATCH_RATE_HZ = 15;@@ -121,6 +136,22 @@ export class WalkRoom extends Room {// and reject otherwise. Returning false makes Colyseus answer the// matchmake/seat request with a 401 the client surfaces as the locked gate.static onAuth(client, options) {+ // Platform token gate (orthogonal to the per-coin holder tier below). When a+ // game token is pinned, no client reaches any world — General or Holders —+ // without a play pass proving a signed-in wallet holds ≥ the floor. Throw+ // (not return false) so a refusal arrives as a `play_pass`-prefixed error the+ // client routes back to its sign-in gate. The verified wallet is bound to the+ // session as the account id, never taken from an unsigned join option.+ if (PLAY_GATE_MINT) {+ const pass = verifyPlayPass(options?.playPass);+ if (!pass) throw new Error('play_pass_required');+ if (pass.mint !== PLAY_GATE_MINT) throw new Error('play_pass_mismatch');+ if (!(typeof pass.balance === 'number' && pass.balance >= PLAY_GATE_MIN)) {+ throw new Error('play_pass_required');+ }+ client.userData = { ...(client.userData || {}), account: pass.wallet, playBalance: pass.balance, playExp: pass.exp };+ }+const tier = cleanTier(options?.tier);if (tier !== 'holders') return true; // open General world@@ -142,7 +173,7 @@ export class WalkRoom extends Room {// Carry the verified holding + signed floor through to onJoin/onCreate so// in-world affordances and the displayed requirement come from the pass,// never from unsigned client options.- client.userData = { holderUsd: pass.usd, holderWallet: pass.wallet, holderMinUsd: pass.minUsd };+ client.userData = { ...(client.userData || {}), holderUsd: pass.usd, holderWallet: pass.wallet, holderMinUsd: pass.minUsd };return true;}@@ -218,6 +249,26 @@ export class WalkRoom extends Room {// is settled by now.await blockStore.ready();this.state.persistent = blockStore.durable;++ // Re-check policy for the token gate. The game server has no RPC of its own,+ // so "still holding the token" is re-proven by the client minting a fresh+ // play pass (which re-reads the chain) before the current one's 10-min TTL+ // runs out and reconnecting — onAuth then re-validates. To actively evict a+ // wallet that offloaded below the floor mid-session, we sweep once a minute+ // and disconnect any client whose bound pass has expired without a refresh.+ // The client refreshes ahead of expiry, so a holder never sees this; only a+ // wallet that stopped qualifying (or a forged-then-expired pass) gets dropped.+ if (PLAY_GATE_MINT) {+ this.clock.setInterval(() => {+ const nowS = Date.now() / 1000;+ for (const client of this.clients) {+ const exp = client.userData?.playExp;+ if (typeof exp === 'number' && exp < nowS) {+ try { client.leave(4002, 'play_pass_required'); } catch {}+ }+ }+ }, 60_000);+ }}onJoin(client, options) {@@ -233,8 +284,23 @@ export class WalkRoom extends Room {player.motion = 'idle';player.avatar = cleanAvatarUrl(options?.avatar);player.agent = clean(options?.agent, 64);+ // The account id is the wallet verified in onAuth — bound server-side, never+ // from a client option, so it's a trustworthy persistence + social-graph key.+ player.account = clean(client.userData?.account, 64);player.tsServer = Date.now();this.state.players.set(client.sessionId, player);++ // Friends presence (Task 15): a presence ticket signed by the three.ws API+ // proves which account this socket belongs to, independent of the wallet+ // holder gate. Register it so friends see this player as online in this+ // coin world and can DM them live. Spoof-proof — the account id comes from+ // the verified ticket, never a raw client option.+ const accountUid = verifyPresenceTicket(options?.presence);+ if (accountUid) {+ client.userData = { ...(client.userData || {}), accountUid };+ socialHub.register(accountUid, client, this.state.coinName || 'Mainland');+ }+const tierTag = this.state.tier === 'holders' ? ' tier=holders' : '';console.log(`[walk_world ${this.roomId} coin=${this.state.coin || 'mainland'}${tierTag}] +join ${client.sessionId} ${name} (n=${this.state.players.size})`,@@ -242,6 +308,7 @@ export class WalkRoom extends Room {}onLeave(client) {+ if (client.userData?.accountUid) socialHub.unregister(client.userData.accountUid, client);this.state.players.delete(client.sessionId);this._moveCounters.delete(client.sessionId);this._chatCooldowns.delete(client.sessionId);diff --git a/multiplayer/src/rooms/commands.js b/multiplayer/src/rooms/commands.jsindex d55db2b3c..caffe11c3 100644--- a/multiplayer/src/rooms/commands.js+++ b/multiplayer/src/rooms/commands.js@@ -65,6 +65,19 @@ export const COMMANDS = [},];+// Client-facing manifest of the registry: just the data the chat autocomplete+// needs (signature + aliases + description), never the server-side `run`+// handlers. Sent once on join so the client hint list is the SAME source of+// truth as /help — it can never drift from the real command set.+export function commandManifest() {+ return COMMANDS.map((c) => ({+ name: c.name,+ args: c.args || '',+ aliases: c.aliases.slice(),+ desc: c.desc,+ }));+}+// Resolve a name or alias (case-insensitive) to its command, or null.function resolve(name) {const n = String(name || '').toLowerCase();diff --git a/multiplayer/src/rooms/realms.js b/multiplayer/src/rooms/realms.jsindex fe4334d33..c46ff577e 100644--- a/multiplayer/src/rooms/realms.js+++ b/multiplayer/src/rooms/realms.js@@ -20,6 +20,19 @@//// `danger` realms drop a tombstone on death. `pvp` realms allow player combat// outside any safeCamp. Resource node ids must be unique WITHIN a realm.+//+// A few realms carry extra fields beyond the shared shape:+// • `cave: true` — render as an enclosed cavern (dark rock) not open sky.+// • `ring: {x0,y0,x1,y1}`— a practice boxing ring: a walkable, purely-cosmetic+// platform (no death risk) drawn with ropes + posts.+// • `seating: [{x0,y0,x1,y1}]` — spectator stands: walkable NO-PvP zones (like a+// mobile safeCamp) so onlookers aren't dragged into a fight.+// • `rollers: [{x0,y0,x1,y1,dir}]` — moving-floor strips. On the sim tick the+// server pushes any player standing on one tile in `dir`+// ('n'|'s'|'e'|'w'), respecting walkability — learn-the-+// flow movement, never a teleport.+// A portal may carry `gate: { combat }` — entry is refused until the player's+// combat level meets the threshold (the server checks it before the handoff).function nodesFrom(coords, kind, prefix) {return coords.map(([tx, ty], i) => ({ id: `${prefix}${i}`, kind, tx, ty }));@@ -43,6 +56,8 @@ const MAINLAND = {{ x0: 8, y0: 8, x1: 12, y1: 11 }, // bank building{ x0: 23, y0: 23, x1: 24, y1: 24 }, // fountain{ x0: 31, y0: 38, x1: 34, y1: 41 }, // the millpond (water — also in `water` below)+ { x0: 27, y0: 13, x1: 30, y1: 15 }, // Fortune's Folly casino (landmark — see `landmarks`)+ { x0: 28, y0: 17, x1: 28, y1: 17 }, // the Wheel of Fortune (interactable — players stand adjacent)],water: [{ x0: 31, y0: 38, x1: 34, y1: 41 }, // the millpond, fishable from its banks@@ -55,6 +70,15 @@ const MAINLAND = {npcs: [{ id: 'aldric', name: 'Aldric the Guide', kind: 'guide', tx: 26, ty: 29 },],+ // Fixed world landmarks (Task 19). A `casino` is a decorative building (its+ // footprint is in `blocked` above); a `wheel` is interactable — the client+ // renders it, a click walks the player adjacent, and standing beside it opens+ // the Wheel of Fortune. The wheel's own tile is blocked so players approach it+ // from an adjacent tile, exactly like the bank counter or an NPC.+ landmarks: [+ { id: 'fortunes-folly', kind: 'casino', tx: 28, ty: 14, label: "Fortune's Folly" },+ { id: 'wheel', kind: 'wheel', tx: 28, ty: 17, label: 'Wheel of Fortune' },+ ],nodes: [...nodesFrom([[12, 28], [14, 30], [16, 29], [13, 33], [15, 35], [11, 31], [18, 34], [20, 30],[17, 37], [19, 38], [10, 36], [22, 36], [8, 30], [9, 33], [21, 40], [13, 40]], 'tree', 't'),@@ -83,6 +107,10 @@ const MAINLAND = {], 1.0),cooking: [],safeCamp: null,+ // The Arena plaza: a practice boxing ring (cosmetic, walkable, zero death risk+ // since the Mainland is `safe`) beside the portal into the full Arena. A fresh+ // fighter can learn footwork in the ring before stepping through to real PvP.+ ring: { x0: 6, y0: 16, x1: 10, y1: 20 },structures: ['firepit'],portals: [{ x0: 23, y0: 0, x1: 25, y1: 0, to: 'wilderness', toTx: 20, toTy: 36 }, // north → wilderness safe camp@@ -93,6 +121,10 @@ const MAINLAND = {// mine's return portal lands the player back at (43,11), a tile clear of// this rect so they don't immediately bounce back in.{ x0: 43, y0: 9, x1: 44, y1: 9, to: 'mine', toTx: 16, toTy: 28 }, // NE → mine interior+ // Arena gate — a stone archway on the plaza just north-west of the ring. Steps+ // into the dedicated PvP Arena; its return strip lands the player at (12,21),+ // a tile clear of this rect (and beside the ring) so they don't bounce back in.+ { x0: 12, y0: 14, x1: 13, y1: 14, to: 'arena', toTx: 14, toTy: 24 }, // plaza → arena],};@@ -125,6 +157,11 @@ const WILDERNESS = {structures: ['firepit'],portals: [{ x0: 19, y0: 39, x1: 21, y1: 39, to: 'mainland', toTx: 24, toTy: 2 }, // south → mainland+ // North trail into the smaller, fully-PvP Wilderness North (no safe camp up+ // there). Lands at its southern return tile.+ { x0: 19, y0: 0, x1: 21, y1: 0, to: 'wilderness_north', toTx: 16, toTy: 28 }, // north → wilderness north+ // East trail into the full-size Wilderness East. Lands just inside its west edge.+ { x0: 39, y0: 18, x1: 39, y1: 20, to: 'wilderness_east', toTx: 2, toTy: 19 }, // east → wilderness east],};@@ -190,6 +227,10 @@ const POND = {structures: ['firepit'],portals: [{ x0: 0, y0: 17, x1: 0, y1: 19, to: 'mainland', toTx: 45, toTy: 24 }, // west → mainland+ // A narrow trail off the pond's quiet north shore crosses into the perils of+ // Wilderness East — leaving the safe pond for a full PvP+danger realm. Lands at+ // its southern edge.+ { x0: 17, y0: 0, x1: 19, y1: 0, to: 'wilderness_east', toTx: 19, toTy: 37 }, // north → wilderness east],};@@ -207,6 +248,7 @@ const POND = {const MINE = {name: 'mine',grid: 32,+ cave: true, // enclosed interior — rendered as a dark cavern, like the wilderness cavespawn: { tx: 16, ty: 28 }, // just inside the entrance, on the central corridorsafe: true, pvp: false, danger: false,blocked: [@@ -254,12 +296,192 @@ const MINE = {],};+// ---------------------------------------------------------------- Wilderness North+// A smaller, harsher spur reached from the top of the main Wilderness. The whole+// map is PvP — there is NO safe camp anywhere up here. Mob density is lower than+// the main Wilderness (fewer foes, but nowhere to catch your breath). At the far+// north a crag-flanked cave mouth holds a combat-LEVEL-GATED passage: only a+// hardened fighter (combat ≥ the portal's gate) may step through into the cave.+const WILDERNESS_NORTH = {+ name: 'wilderness_north',+ grid: 32,+ spawn: { tx: 16, ty: 28 }, // southern return tile, just inside the trail from the main Wilderness+ safe: false, pvp: true, danger: true,+ blocked: [+ // Crags flanking the northern cave mouth — they frame the gated passage at+ // x15..16 and read the far north as a rocky dead-end but for the cave.+ { x0: 8, y0: 0, x1: 14, y1: 1 },+ { x0: 17, y0: 0, x1: 23, y1: 1 },+ ],+ water: [],+ fountain: null,+ bankZone: [],+ nodes: [+ ...nodesFrom([[9, 12], [22, 10], [6, 20], [25, 18]], 'tree', 't'),+ ...nodesFrom([[12, 6], [20, 6], [7, 8]], 'rock', 'r'),+ ...nodesFrom([[15, 8]], 'coal', 'c'),+ ],+ // Lower density than the main Wilderness (5 mobs): two goblins and a lone ogre.+ mobs: [+ { id: 'g0', kind: 'goblin', tx: 12, ty: 16, hp: 34, roam: true, aggro: true },+ { id: 'g1', kind: 'goblin', tx: 22, ty: 14, hp: 34, roam: true, aggro: true },+ { id: 'o0', kind: 'ogre', tx: 16, ty: 10, hp: 80, roam: true, aggro: true },+ ],+ fishing: [],+ cooking: [],+ safeCamp: null, // no refuge — PvP across the whole map+ structures: ['firepit'],+ portals: [+ { x0: 15, y0: 31, x1: 17, y1: 31, to: 'wilderness', toTx: 20, toTy: 2 }, // south → main Wilderness top+ // The gated cave mouth. Entry needs combat ≥ 20; the server refuses an+ // under-level step with a notice and the player simply stays put.+ { x0: 15, y0: 0, x1: 16, y1: 0, to: 'wilderness_cave', toTx: 14, toTy: 24, gate: { combat: 20 } }, // far north → cave (gated)+ ],+};++// ---------------------------------------------------------------- Wilderness Cave+// The level-gated cavern beyond the northern gate — its own enclosed instance.+// Reaching it at all means you cleared the combat gate, so the danger is steep:+// trolls and ogres prowl a rich ore seam. PvP + danger like the open wilds, but+// underground (rendered as a dark cavern). A single passage south returns to+// Wilderness North.+const WILDERNESS_CAVE = {+ name: 'wilderness_cave',+ grid: 28,+ cave: true,+ spawn: { tx: 14, ty: 24 }, // arrival tile, just north of the return passage+ safe: false, pvp: true, danger: true,+ blocked: [+ // Cave shell — a one-tile rock wall around the whole interior.+ { x0: 0, y0: 0, x1: 27, y1: 0 },+ { x0: 0, y0: 1, x1: 0, y1: 27 },+ { x0: 27, y0: 1, x1: 27, y1: 27 },+ { x0: 1, y0: 27, x1: 26, y1: 27 },+ // Central ridge splitting upper/lower chambers, broken by a centre gap (x11..16).+ { x0: 4, y0: 12, x1: 10, y1: 13 },+ { x0: 17, y0: 12, x1: 23, y1: 13 },+ // Pillars — cover to fight and mine around.+ { x0: 7, y0: 18, x1: 8, y1: 19 },+ { x0: 19, y0: 18, x1: 20, y1: 19 },+ ],+ water: [],+ fountain: null,+ bankZone: [],+ nodes: [+ ...nodesFrom([[3, 3], [7, 2], [12, 3], [16, 3], [21, 2], [24, 4], [5, 8], [22, 8], [10, 9], [18, 9]], 'rock', 'r'),+ ...nodesFrom([[9, 4], [14, 6], [19, 5], [4, 22], [23, 22], [13, 16]], 'coal', 'c'),+ ],+ // Steep: two ogres, a troll, and a pair of goblins. All roam + aggro.+ mobs: [+ { id: 'tr0', kind: 'troll', tx: 14, ty: 8, hp: 140, roam: true, aggro: true },+ { id: 'o0', kind: 'ogre', tx: 6, ty: 6, hp: 80, roam: true, aggro: true },+ { id: 'o1', kind: 'ogre', tx: 22, ty: 16, hp: 80, roam: true, aggro: true },+ { id: 'g0', kind: 'goblin', tx: 9, ty: 20, hp: 34, roam: true, aggro: true },+ { id: 'g1', kind: 'goblin', tx: 18, ty: 22, hp: 34, roam: true, aggro: true },+ ],+ fishing: [],+ cooking: [],+ safeCamp: null,+ structures: [],+ portals: [+ { x0: 13, y0: 26, x1: 15, y1: 26, to: 'wilderness_north', toTx: 15, toTy: 2 }, // south passage → Wilderness North+ ],+};++// ---------------------------------------------------------------- Wilderness East+// A full-size wild expanse east of the main Wilderness, also reachable off the+// Pond's north shore. PvP + danger like the Wilderness, with the same kind of+// roaming foes and scattered resources, but no safe camp — the whole map is open.+const WILDERNESS_EAST = {+ name: 'wilderness_east',+ grid: 40,+ spawn: { tx: 4, ty: 20 },+ safe: false, pvp: true, danger: true,+ blocked: [],+ water: [],+ fountain: null,+ bankZone: [],+ nodes: [+ ...nodesFrom([[10, 8], [16, 12], [24, 10], [30, 16], [8, 24], [34, 26], [20, 30], [28, 34], [14, 34]], 'tree', 't'),+ ...nodesFrom([[12, 18], [26, 22], [33, 12], [9, 32], [22, 6]], 'rock', 'r'),+ ...nodesFrom([[18, 24], [31, 30], [15, 6]], 'coal', 'c'),+ ],+ mobs: [+ { id: 'g0', kind: 'goblin', tx: 14, ty: 16, hp: 34, roam: true, aggro: true },+ { id: 'g1', kind: 'goblin', tx: 26, ty: 14, hp: 34, roam: true, aggro: true },+ { id: 'g2', kind: 'goblin', tx: 20, ty: 26, hp: 34, roam: true, aggro: true },+ { id: 'g3', kind: 'goblin', tx: 32, ty: 22, hp: 34, roam: true, aggro: true },+ { id: 'o0', kind: 'ogre', tx: 22, ty: 18, hp: 80, roam: true, aggro: true },+ ],+ fishing: [],+ cooking: [],+ safeCamp: null,+ structures: ['firepit'],+ portals: [+ { x0: 0, y0: 18, x1: 0, y1: 20, to: 'wilderness', toTx: 37, toTy: 19 }, // west → main Wilderness east edge+ { x0: 17, y0: 39, x1: 19, y1: 39, to: 'pond', toTx: 18, toTy: 2 }, // south → Pond north shore+ ],+};++// ---------------------------------------------------------------- Arena+// A dedicated PvP scene reached from the Mainland plaza. PvP is on, but it is NOT+// a `danger` realm — death here costs no items (a sporting bout, not the wilds);+// you simply respawn at the south gate. The floor carries moving ROLLERS that+// shove a standing fighter one tile per push in their direction — read the flow,+// use it, or get walked into your opponent's reach. SEATING along both flanks is a+// no-PvP spectator zone. A south strip returns to the Mainland plaza.+const ARENA = {+ name: 'arena',+ grid: 28,+ spawn: { tx: 14, ty: 24 }, // south gate, on the return strip's doorstep+ safe: false, pvp: true, danger: false,+ blocked: [+ // Arena bowl wall — a solid ring around the whole floor (the south return+ // strip is an interior portal tile, so no gap is needed in the wall).+ { x0: 0, y0: 0, x1: 27, y1: 0 },+ { x0: 0, y0: 1, x1: 0, y1: 27 },+ { x0: 27, y0: 1, x1: 27, y1: 27 },+ { x0: 0, y0: 27, x1: 27, y1: 27 },+ ],+ water: [],+ fountain: null,+ bankZone: [],+ nodes: [],+ mobs: [],+ fishing: [],+ cooking: [],+ safeCamp: null,+ structures: [],+ // Spectator stands down the east and west flanks — walkable, but no PvP can be+ // dealt to or from anyone standing in them (enforced server-side alongside safeCamp).+ seating: [+ { x0: 1, y0: 6, x1: 3, y1: 21 },+ { x0: 24, y0: 6, x1: 26, y1: 21 },+ ],+ // A clockwise circulation of moving floor: the top belt drives east, the right+ // edge south, the bottom belt west, the left edge north — a loop a fighter learns+ // to ride or break out of.+ rollers: [+ { x0: 8, y0: 10, x1: 19, y1: 10, dir: 'e' },+ { x0: 19, y0: 11, x1: 19, y1: 15, dir: 's' },+ { x0: 8, y0: 16, x1: 19, y1: 16, dir: 'w' },+ { x0: 8, y0: 11, x1: 8, y1: 15, dir: 'n' },+ ],+ portals: [+ { x0: 12, y0: 26, x1: 15, y1: 26, to: 'mainland', toTx: 12, toTy: 21 }, // south strip → Mainland plaza+ ],+};+export const REALMS = {mainland: MAINLAND,wilderness: WILDERNESS,whisperwood: WHISPERWOOD,pond: POND,mine: MINE,+ wilderness_north: WILDERNESS_NORTH,+ wilderness_cave: WILDERNESS_CAVE,+ wilderness_east: WILDERNESS_EAST,+ arena: ARENA,};export const DEFAULT_REALM = 'mainland';@@ -286,6 +508,39 @@ export function inRect(rect, tx, ty) {return rect && tx >= rect.x0 && tx <= rect.x1 && ty >= rect.y0 && ty <= rect.y1;}+// The realm's spin-wheel landmark (Task 19), or null if this realm has none.+// The GameRoom uses its tile for the "stand adjacent to spin" check.+export function wheelLandmark(realm) {+ return (realm.landmarks || []).find((l) => l.kind === 'wheel') || null;+}++export function inAnyRect(rects, tx, ty) {+ if (!rects) return false;+ for (const r of rects) if (inRect(r, tx, ty)) return true;+ return false;+}++// Unit tile delta for a roller's push direction. Unknown directions don't move.+const ROLLER_DELTA = { n: [0, -1], s: [0, 1], e: [1, 0], w: [-1, 0] };+export function rollerDelta(dir) {+ return ROLLER_DELTA[dir] || [0, 0];+}++// The roller whose footprint covers (tx,ty), or null. The first match wins where+// strips overlap, so a corner belongs to whichever strip is listed first.+export function rollerAt(realm, tx, ty) {+ for (const r of realm.rollers || []) {+ if (inRect(r, tx, ty)) return r;+ }+ return null;+}++// True if (tx,ty) is a PvP-immune tile of this realm: inside the safe camp or any+// spectator-seating stand. Combat to/from such a tile is refused server-side.+export function inNoPvpZone(realm, tx, ty) {+ return inRect(realm.safeCamp, tx, ty) || inAnyRect(realm.seating, tx, ty);+}+// The best fishing spot within one tile (8-way, including the player's own tile)// of (tx,ty), or null if there's no fishable water in reach. "Best" = highest// quality, so standing where two spots overlap rewards the richer water.@@ -314,8 +569,18 @@ export function realmLayout(realm) {cooking: realm.cooking,safeCamp: realm.safeCamp,npcs: (realm.npcs || []).map((n) => ({ id: n.id, name: n.name, kind: n.kind, tx: n.tx, ty: n.ty })),+ landmarks: (realm.landmarks || []).map((l) => ({ id: l.id, kind: l.kind, tx: l.tx, ty: l.ty, label: l.label })),structures: realm.structures || [],- portals: realm.portals.map((p) => ({ x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y1, to: p.to })),+ // Portals carry their combat gate (if any) so the client can label a locked+ // gate and pre-warn before a wasted walk. toTx/toTy stay server-only.+ portals: realm.portals.map((p) => ({ x0: p.x0, y0: p.y0, x1: p.x1, y1: p.y1, to: p.to, gate: p.gate || null })),+ // Distinguishing scenery for the new realms — all optional, absent on the+ // classic four: an enclosed cave look, the practice boxing ring, spectator+ // stands, and the moving-floor rollers (with direction) the Arena renders.+ cave: !!realm.cave,+ ring: realm.ring || null,+ seating: realm.seating || [],+ rollers: (realm.rollers || []).map((r) => ({ x0: r.x0, y0: r.y0, x1: r.x1, y1: r.y1, dir: r.dir })),safe: realm.safe,pvp: realm.pvp,danger: realm.danger,diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.jsindex cd51d9d9a..835dd832c 100644--- a/multiplayer/src/schemas.js+++ b/multiplayer/src/schemas.js@@ -25,6 +25,10 @@ export class Player extends Schema {this.avatar = '';// Optional three.ws agent id this player is embodying (for cross-links).this.agent = '';+ // Verified Solana wallet address bound at sign-in — the account id this+ // player persists under and is known by in the social graph. Empty in the+ // open (un-gated) world; set from the play pass when the token gate is on.+ this.account = '';// True while this player is in spatial voice chat, so peers know to open a// WebRTC connection to them and the UI can mark their nameplate.this.voice = false;@@ -44,6 +48,7 @@ defineTypes(Player, {emoteTs: 'float64',avatar: 'string',agent: 'string',+ account: 'string',voice: 'boolean',tsServer: 'float64',});diff --git a/multiplayer/src/schemas/game.js b/multiplayer/src/schemas/game.jsindex 8b3163671..bdda07236 100644--- a/multiplayer/src/schemas/game.js+++ b/multiplayer/src/schemas/game.js@@ -57,7 +57,12 @@ export class GamePlayer extends Schema {this.mining = 1;this.fishing = 1;this.cooking = 1;- this.cosmetic = ''; // equipped cosmetic id ('' = default)+ this.cosmetic = ''; // base avatar URL (the player's chosen model; '' = default)+ // Equipped shop cosmetic id (Task 21), '' = none. Strictly visual: the client+ // layers this look (tint / worn prop / aura) over the base avatar. Synced so+ // every peer renders the player's equipped cosmetic. Server-authoritative —+ // only set after a validated purchase + equip, never from a raw client claim.+ this.cosmeticId = '';// Quest-awarded badges, as a comma-separated list of badge ids. Synced so// every peer renders the achievement on the player's nameplate (the// in-world "profile"). Server-authoritative — only the quest engine writes it.@@ -97,6 +102,7 @@ defineTypes(GamePlayer, {fishing: 'uint16',cooking: 'uint16',cosmetic: 'string',+ cosmeticId: 'string',badges: 'string',inv: [Slot],hotbar: [Slot],@@ -223,6 +229,10 @@ export class GameState extends Schema {constructor() {super();this.realm = 'mainland';+ // World instance id this room belongs to (Task 23). Synced so the client+ // can label the HUD with the server it actually landed on, confirming the+ // login pick rather than trusting its own local choice.+ this.server = 's1';this.players = new MapSchema();this.nodes = new MapSchema();this.mobs = new MapSchema();@@ -232,6 +242,7 @@ export class GameState extends Schema {}defineTypes(GameState, {realm: 'string',+ server: 'string',players: { map: GamePlayer },nodes: { map: ResourceNode },mobs: { map: Mob },diff --git a/multiplayer/src/servers.js b/multiplayer/src/servers.jsnew file mode 100644index 000000000..553ef7145--- /dev/null+++ b/multiplayer/src/servers.js@@ -0,0 +1,53 @@+// World instances ("servers") — Task 23.+//+// The platform runs N independent world instances on one host. A player picks+// one at login; each (realm, server) pair is its own Colyseus room (see the+// filterBy(['server']) in index.js), so two players on different servers never+// share a realm room, chat, or /who roster. Progression is account-scoped+// (playerStore), so the SAME account sees identical items/gold/skills on either+// server — only presence/visibility is isolated, never the profile.+//+// The roster is configurable without a code change via the GAME_SERVERS env:+// GAME_SERVERS="s1:Server 1:The original world.,s2:Server 2:A fresh start."+// Each entry is `id:name:blurb` (blurb optional). Ids are matched verbatim as a+// join option, so keep them short, stable, and url-safe — they never change once+// players have progressed, because the profile is shared anyway but the choice+// is remembered per browser.++const ID_RE = /^[a-z0-9][a-z0-9_-]{0,15}$/;++function parseEnv(raw) {+ if (typeof raw !== 'string' || !raw.trim()) return null;+ const out = [];+ const seen = new Set();+ for (const part of raw.split(',')) {+ const [id, name, ...rest] = part.split(':').map((s) => s.trim());+ if (!ID_RE.test(id) || seen.has(id)) continue;+ seen.add(id);+ out.push({ id, name: name || id, blurb: rest.join(':') || '' });+ }+ return out.length ? out : null;+}++// Default roster: two independent worlds on the same host, exactly as the world+// guide describes ("Server 1" / "Server 2").+const DEFAULT_SERVERS = [+ { id: 's1', name: 'Server 1', blurb: 'The original world. Most players are here.' },+ { id: 's2', name: 'Server 2', blurb: 'A second, fully independent world.' },+];++export const SERVERS = parseEnv(process.env.GAME_SERVERS) || DEFAULT_SERVERS;+export const SERVER_IDS = new Set(SERVERS.map((s) => s.id));+export const DEFAULT_SERVER = SERVERS[0].id;++// Resolve a client-supplied server id to a real instance, falling back to the+// default so a missing/forged value can never land a player in a non-existent+// world. Mirrors WalkRoom.cleanCoin / cleanTier's "unknown collapses to default"+// contract.+export function cleanServer(v) {+ return typeof v === 'string' && SERVER_IDS.has(v) ? v : DEFAULT_SERVER;+}++export function serverName(id) {+ return SERVERS.find((s) => s.id === id)?.name || id;+}diff --git a/multiplayer/src/social-hub.js b/multiplayer/src/social-hub.jsnew file mode 100644index 000000000..864f6782e--- /dev/null+++ b/multiplayer/src/social-hub.js@@ -0,0 +1,140 @@+// Social hub — the multiplayer server's half of the account-level friends+// system. It owns two responsibilities, both keyed to the verified account id+// (a users.id UUID resolved from a presence ticket), NOT the ephemeral Colyseus+// sessionId, so presence and delivery survive realm changes and reconnects:+//+// 1. Presence. While an account has at least one connected realm-room client,+// `presence:<uid>` is written to Upstash Redis with a short TTL and+// refreshed on a heartbeat. The Vercel friends API reads these keys to show+// a friend's online/offline + current realm — accurately across separate+// realm-room instances, and self-healing if this process dies (the TTL+// lapses instead of pinning a ghost online forever).+//+// 2. Live delivery. A per-account registry of connected clients lets the+// internal /internal/notify webhook (called by the API after it persists a+// DM or friend event) push the event to every socket that account has open.+// Offline recipients are covered by the durable Postgres queue the client+// drains on next login, so nothing is ever lost.++const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || process.env.three_KV_REST_API_URL || process.env.KV_REST_API_URL || '';+const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || process.env.three_KV_REST_API_TOKEN || process.env.KV_REST_API_TOKEN || '';+const PRESENCE_PREFIX = 'presence:';+const PRESENCE_TTL_SEC = 75; // refreshed every 30s; lapses ~45s after a hard drop+const HEARTBEAT_MS = 30_000;++class SocialHub {+ constructor() {+ // uid → Map(client → realmLabel). One account can hold several sockets+ // (a second tab, or /walk + /play at once); we track each so delivery+ // fans out and presence only clears when the last one leaves.+ this._byUid = new Map();+ this._redis = null;+ this._redisReady = null;+ if (REDIS_URL && REDIS_TOKEN) {+ this._redisReady = import('@upstash/redis')+ .then(({ Redis }) => {+ this._redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });+ console.log('[social-hub] presence: Upstash Redis');+ })+ .catch((err) => {+ this._redis = null;+ console.error('[social-hub] Redis unreachable — presence will not be visible to the friends API:', err?.message);+ });+ } else {+ console.log('[social-hub] presence DISABLED (set UPSTASH_REDIS_REST_URL/_TOKEN to publish presence)');+ }+ // One shared heartbeat refreshes every online account's TTL.+ this._heartbeat = setInterval(() => this._refreshAll(), HEARTBEAT_MS);+ if (typeof this._heartbeat.unref === 'function') this._heartbeat.unref();+ }++ // A realm room calls this on join once it has verified the presence ticket.+ register(uid, client, realm) {+ if (!uid || !client) return;+ let clients = this._byUid.get(uid);+ if (!clients) {+ clients = new Map();+ this._byUid.set(uid, clients);+ }+ clients.set(client, realm || null);+ this._writePresence(uid, realm);+ }++ // Realm room calls this on leave. Presence clears only when the account has+ // no remaining sockets anywhere.+ unregister(uid, client) {+ const clients = this._byUid.get(uid);+ if (!clients) return;+ clients.delete(client);+ if (clients.size === 0) {+ this._byUid.delete(uid);+ this._clearPresence(uid);+ } else {+ // Still online elsewhere — keep presence on a realm that's still live.+ const realm = [...clients.values()].pop();+ this._writePresence(uid, realm);+ }+ }++ // Push an event to every socket the account has open. Returns true if at+ // least one client received it (the API uses this to report live delivery).+ deliver(uid, type, payload = {}) {+ const clients = this._byUid.get(uid);+ if (!clients || clients.size === 0) return false;+ let sent = 0;+ for (const client of clients.keys()) {+ try {+ client.send('social', { type, ...payload });+ sent++;+ } catch (err) {+ console.warn('[social-hub] deliver failed:', err?.message);+ }+ }+ return sent > 0;+ }++ isOnline(uid) {+ const clients = this._byUid.get(uid);+ return !!(clients && clients.size > 0);+ }++ async _writePresence(uid, realm) {+ if (!this._redisReady) return;+ try {+ await this._redisReady;+ if (!this._redis) return;+ await this._redis.set(+ PRESENCE_PREFIX + uid,+ JSON.stringify({ realm: realm || null, ts: Date.now() }),+ { ex: PRESENCE_TTL_SEC },+ );+ } catch (err) {+ console.warn('[social-hub] presence write failed:', err?.message);+ }+ }++ async _clearPresence(uid) {+ if (!this._redisReady) return;+ try {+ await this._redisReady;+ if (!this._redis) return;+ await this._redis.del(PRESENCE_PREFIX + uid);+ } catch (err) {+ console.warn('[social-hub] presence clear failed:', err?.message);+ }+ }++ // Re-stamp the TTL for every still-connected account so a long-lived session+ // never lapses to "offline" while the socket is open.+ _refreshAll() {+ if (!this._byUid.size) return;+ for (const [uid, clients] of this._byUid) {+ const realm = [...clients.values()].pop();+ this._writePresence(uid, realm);+ }+ }+}++// One hub shared by every room in the process — that shared registry is what+// lets a DM reach an account no matter which realm room it's connected through.+export const socialHub = new SocialHub();diff --git a/multiplayer/src/spin-wheel.js b/multiplayer/src/spin-wheel.jsnew file mode 100644index 000000000..23e9b73cb--- /dev/null+++ b/multiplayer/src/spin-wheel.js@@ -0,0 +1,132 @@+// Wheel of Fortune — the authoritative prize table for the Mainland casino spin+// (Task 19).+//+// The SERVER owns the outcome. The 20 segments and their weights live here and+// nowhere else; both the free spin and the paid spin roll through `rollSpin()`,+// and the client only ever receives the chosen index to animate toward — it+// never decides a prize. The display list (`spinSegments()`) is the same table+// with weights surfaced as honest odds, so the wheel the player sees is exactly+// the wheel the server rolls.+//+// Distribution: gold is the jackpot at a true 1/20 (the gold leg's weight is+// 1/20 of the total). The remaining 19 segments pay wood, stone, or coal in+// varying amounts, weighted so small hauls are common and big ones are rare.++import crypto from 'node:crypto';++// Each segment is { kind:'gold'|'item', item?, qty?, gold?, weight }. Order here+// is the order around the wheel (index 0 at the top, clockwise). Weights sum to+// 100, with the single gold leg at weight 5 → exactly P(gold) = 5/100 = 1/20.+const SEGMENTS = [+ { kind: 'gold', gold: 200, weight: 5 }, // 0 — jackpot, ~1/20+ { kind: 'item', item: 'wood', qty: 5, weight: 12 },+ { kind: 'item', item: 'coal', qty: 6, weight: 6 },+ { kind: 'item', item: 'stone', qty: 10, weight: 9 },+ { kind: 'item', item: 'wood', qty: 25, weight: 4 },+ { kind: 'item', item: 'coal', qty: 3, weight: 9 },+ { kind: 'item', item: 'stone', qty: 5, weight: 11 },+ { kind: 'item', item: 'wood', qty: 50, weight: 2 },+ { kind: 'item', item: 'coal', qty: 15, weight: 3 },+ { kind: 'item', item: 'stone', qty: 25, weight: 4 },+ { kind: 'item', item: 'wood', qty: 10, weight: 10 },+ { kind: 'item', item: 'coal', qty: 25, weight: 2 },+ { kind: 'item', item: 'stone', qty: 15, weight: 6 },+ { kind: 'item', item: 'wood', qty: 15, weight: 7 },+ { kind: 'item', item: 'coal', qty: 10, weight: 4 },+ { kind: 'item', item: 'stone', qty: 50, weight: 2 },+ { kind: 'item', item: 'wood', qty: 100, weight: 1 }, // wood jackpot+ { kind: 'item', item: 'coal', qty: 40, weight: 1 },+ { kind: 'item', item: 'stone', qty: 80, weight: 1 },+ { kind: 'item', item: 'coal', qty: 60, weight: 1 }, // coal jackpot+];++const TOTAL_WEIGHT = SEGMENTS.reduce((s, seg) => s + seg.weight, 0);++const ITEM_LABEL = { wood: 'Wood', stone: 'Stone', coal: 'Coal' };++// Human-readable label for a segment, computed once so the client and any toast+// describe a prize identically. "200 Gold", "25 Wood", …+function segmentLabel(seg) {+ if (seg.kind === 'gold') return `${seg.gold} Gold`;+ return `${seg.qty} ${ITEM_LABEL[seg.item] || seg.item}`;+}++/**+ * The wheel as the client should render it: one entry per segment in wheel+ * order, with the prize, a label, and the segment's true probability (odds are+ * shown openly — the wheel isn't a black box). No secret state; safe to send.+ * @returns {{ index:number, kind:string, item:string|null, qty:number|null,+ * gold:number|null, label:string, oddsPct:number }[]}+ */+export function spinSegments() {+ return SEGMENTS.map((seg, index) => ({+ index,+ kind: seg.kind,+ item: seg.kind === 'item' ? seg.item : null,+ qty: seg.kind === 'item' ? seg.qty : null,+ gold: seg.kind === 'gold' ? seg.gold : null,+ label: segmentLabel(seg),+ oddsPct: Math.round((seg.weight / TOTAL_WEIGHT) * 1000) / 10,+ }));+}++/**+ * Roll one outcome using a cryptographically strong weighted draw. Returns the+ * winning segment index plus its reward, normalized to { gold } or { item, qty }.+ * This is the only place a spin's prize is decided.+ * @returns {{ index:number, kind:string, item:string|null, qty:number, gold:number, label:string }}+ */+export function rollSpin() {+ // randomInt is uniform over [0, TOTAL_WEIGHT) with no modulo bias.+ let roll = crypto.randomInt(0, TOTAL_WEIGHT);+ let index = 0;+ for (let i = 0; i < SEGMENTS.length; i++) {+ if (roll < SEGMENTS[i].weight) { index = i; break; }+ roll -= SEGMENTS[i].weight;+ }+ const seg = SEGMENTS[index];+ return {+ index,+ kind: seg.kind,+ item: seg.kind === 'item' ? seg.item : null,+ qty: seg.kind === 'item' ? seg.qty : 0,+ gold: seg.kind === 'gold' ? seg.gold : 0,+ label: segmentLabel(seg),+ };+}++export const SEGMENT_COUNT = SEGMENTS.length;+// 12h between free spins, tracked per account in the persisted profile.+export const FREE_SPIN_COOLDOWN_MS = 12 * 60 * 60 * 1000;+// Minimum average skill level required to spin (free or paid).+export const SPIN_MIN_AVG_LEVEL = 5;+// USD cost of one paid spin, settled in $THREE (50% burned / 50% to treasury).+export const PAID_SPIN_USD = 3;++// --- paid-spin replay guard (process-wide) ---------------------------------+//+// A settled payment signature must roll at most one prize, ever. Rooms are+// independent objects, so an in-room set wouldn't stop a player from settling+// the same signature again after a portal handoff to another realm. This shared+// map is the single source of truth across every room in the process; entries+// are swept after a TTL well beyond the 90s quote window so it never grows+// unbounded. (Horizontal scale would back this with the same Redis the+// presence/profile layers use; the interface stays identical.)+const _settledSigs = new Map(); // txSig -> settledAt(ms)+const SETTLED_TTL_MS = 60 * 60 * 1000;++export function isSpinSettled(txSig) {+ const at = _settledSigs.get(txSig);+ if (at == null) return false;+ if (Date.now() - at > SETTLED_TTL_MS) { _settledSigs.delete(txSig); return false; }+ return true;+}++export function markSpinSettled(txSig) {+ _settledSigs.set(txSig, Date.now());+}++setInterval(() => {+ const now = Date.now();+ for (const [sig, at] of _settledSigs) if (now - at > SETTLED_TTL_MS) _settledSigs.delete(sig);+}, 10 * 60 * 1000).unref?.();diff --git a/pages/game.html b/pages/game.htmlindex 25287957d..83589124c 100644--- a/pages/game.html+++ b/pages/game.html@@ -46,6 +46,7 @@<!-- In-world HUD --><header id="kg-topbar" hidden><span id="kg-realm">Mainland</span>+ <span id="kg-server" class="kg-server-chip" hidden></span><span class="kg-stat">online <b id="kg-online">0</b></span><buttonid="kg-skills-btn"@@ -134,12 +135,26 @@aria-label="Chat messages"></div><form id="kg-chat-form" class="kg-chat-form" autocomplete="off">+ <!-- Slash-command autocomplete: populated from the server command+ manifest as the player types '/'. role=listbox for screen readers;+ the input owns it via aria-controls / aria-activedescendant. -->+ <ul+ id="kg-chat-hint"+ class="kg-chat-hint"+ role="listbox"+ aria-label="Command suggestions"+ hidden+ ></ul><inputid="kg-chat-input"class="kg-chat-input"type="text"maxlength="200"autocomplete="off"+ role="combobox"+ aria-expanded="false"+ aria-autocomplete="list"+ aria-controls="kg-chat-hint"aria-label="Type a message"placeholder="Press Enter to chat…"/>@@ -199,6 +214,16 @@<i class="kg-action-dot" aria-hidden="true"></i><span class="kg-action-lbl">Cast line</span></button>+ <button+ id="kg-pickup"+ class="kg-action kg-action--pickup"+ type="button"+ hidden+ aria-label="Pick up your structure"+ >+ <i class="kg-action-dot" aria-hidden="true"></i+ ><span class="kg-action-lbl">Pick up</span>+ </button></div><!-- Death-bag recovery panel — opens when you tap an adjacent tombstone.@@ -257,6 +282,27 @@placeholder="guest"/></label>+ <!-- World-instance picker (Task 23). Real per-server population is+ fetched live from the multiplayer host's /servers endpoint and+ rendered into #kg-servers-list by _initServerPicker in iso-game.js.+ Items, gold, and skills are shared across servers; only who you see+ differs. -->+ <fieldset id="kg-servers" class="kg-servers" aria-label="Choose a server">+ <legend class="kg-servers-legend">Choose a server</legend>+ <div+ id="kg-servers-list"+ class="kg-servers-list"+ role="radiogroup"+ aria-label="World instances"+ aria-busy="true"+ >+ <div class="kg-servers-loading">Finding worlds…</div>+ </div>+ <p class="kg-servers-note">+ Items, gold, and skills are shared across servers — you’ll only see other players on the+ one you pick.+ </p>+ </fieldset><button id="kg-start-btn" class="kg-btn" type="button">Enter world</button><div class="kg-feats"><span class="kg-feat">Woodcutting</span>diff --git a/public/features.json b/public/features.jsonindex df629ec59..99f9009c5 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-31T08:37:15.832Z",+ "generated_at": "2026-06-01T03:35:16.249Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/verify-chat-commands.mjs b/scripts/verify-chat-commands.mjsnew file mode 100644index 000000000..d6ca1026b--- /dev/null+++ b/scripts/verify-chat-commands.mjs@@ -0,0 +1,127 @@+// Browser verification for Task 13 — the client slash-command autocomplete.+//+// The server command router (parse/validate/dispatch, /help, /who, rate-limit,+// unknown-command errors) is covered by a separate logic check; this harness+// drives the real /game page in a browser to exercise the NEW client UI:+// the autocomplete dropdown, keyboard navigation, Tab/Enter completion, and+// mouse selection — against the real DOM, CSS, and event wiring.+//+// It reaches the live IsoGame instance (window.__ISO__), puts it in the 'world'+// phase, and feeds it the command manifest exactly as the server sends it on+// join (commandManifest()). No multiplayer server required.+//+// npm run dev # http://localhost:3000+// node scripts/verify-chat-commands.mjs+import { chromium } from 'playwright';++const URL = process.env.GAME_URL || 'http://localhost:3000/game.html';+// Mirrors multiplayer/src/rooms/commands.js commandManifest() — the shape the+// server pushes over the 'commands' message on join.+const MANIFEST = [+ { name: 'help', args: '', aliases: ['commands', 'h', '?'], desc: 'List the commands you can use' },+ { name: 'who', args: '', aliases: ['players', 'online'], desc: 'List the players in your realm' },+ { name: 'pickup', args: '', aliases: ['take'], desc: 'Pick up your firepit or shack you are standing beside' },+ { name: 'lock', args: '', aliases: [], desc: 'Lock the structure beside you against stray clicks' },+ { name: 'unlock', args: '', aliases: [], desc: 'Unlock the structure beside you' },+ { name: 'dismount', args: '', aliases: ['unmount'], desc: 'Climb down from your mount' },+];++const ok = [];+const fail = [];+const check = (cond, msg) => (cond ? ok : fail).push(msg);++const browser = await chromium.launch();+const page = await browser.newContext({ viewport: { width: 1280, height: 800 } }).then((c) => c.newPage());+const consoleErrors = [];+// The colyseus + vite-HMR sockets fail without a running server / behind the+// github.dev proxy; those are environmental, not feature errors, so filter them.+const ENV_NOISE = /WebSocket|game-net|ERR_CONNECTION|vite|websocket/i;+page.on('console', (m) => { if (m.type() === 'error' && !ENV_NOISE.test(m.text())) consoleErrors.push(m.text()); });+page.on('pageerror', (e) => { if (!ENV_NOISE.test(e.message)) consoleErrors.push('pageerror: ' + e.message); });++await page.goto(URL, { waitUntil: 'domcontentloaded' });+await page.waitForFunction(() => window.__ISO__ && typeof window.__ISO__._onCommands === 'function', { timeout: 15000 });++// Put the game in-world and hand it the manifest exactly as the server would.+await page.evaluate((manifest) => {+ const g = window.__ISO__;+ g.phase = 'world';+ g._setHudPhase('world'); // hides the start overlay, reveals the chat panel+ g._onCommands(manifest);+}, MANIFEST);+check(true, 'reached in-world IsoGame and loaded command manifest');++const input = page.locator('#kg-chat-input');+await input.click();++// '/' → full registry, in registry order.+await input.type('/');+await page.waitForSelector('#kg-chat-hint:not([hidden])', { timeout: 3000 });+const all = await page.$$eval('#kg-chat-hint .kg-chat-hint-cmd', (els) => els.map((e) => e.textContent.trim()));+check(all.length === 6, `'/' lists all 6 commands (got ${all.length}: ${all.join(', ')})`);+check(all[0] === '/help' && all.includes('/dismount'), 'list is registry-ordered and complete');+const descs = await page.$$eval('#kg-chat-hint .kg-chat-hint-desc', (els) => els.map((e) => e.textContent.trim()));+check(descs.every((d) => d.length > 0), 'every suggestion shows a description');++// Alias match: 'unm' → /dismount (alias 'unmount').+await input.fill('/unm');+await page.waitForTimeout(80);+const alias = await page.$$eval('#kg-chat-hint .kg-chat-hint-cmd', (els) => els.map((e) => e.textContent.trim()));+check(alias.length === 1 && alias[0] === '/dismount', `alias 'unm' resolves to /dismount (got ${alias.join(', ')})`);++// Prefix narrowing: '/l' → /lock only.+await input.fill('/l');+await page.waitForTimeout(80);+const pre = await page.$$eval('#kg-chat-hint .kg-chat-hint-cmd', (els) => els.map((e) => e.textContent.trim()));+check(pre.length === 1 && pre[0] === '/lock', `'/l' narrows to /lock (got ${pre.join(', ')})`);++// Keyboard nav: ArrowDown highlights the first row.+await input.fill('/');+await page.waitForTimeout(60);+await input.press('ArrowDown');+const active1 = await page.$eval('#kg-chat-hint .kg-chat-hint-item--active .kg-chat-hint-cmd', (e) => e.textContent.trim()).catch(() => null);+check(active1 === '/help', `ArrowDown highlights first command (got ${active1})`);+await input.press('ArrowUp'); // wrap to last+const active2 = await page.$eval('#kg-chat-hint .kg-chat-hint-item--active .kg-chat-hint-cmd', (e) => e.textContent.trim()).catch(() => null);+check(active2 === '/dismount', `ArrowUp from first wraps to last (got ${active2})`);+const aria = await input.getAttribute('aria-activedescendant');+check(aria === 'kg-chat-hint-5', `aria-activedescendant tracks selection (got ${aria})`);++// Tab completes the highlighted command into the field and (no args) hides the hint.+await input.press('Tab');+check((await input.inputValue()) === '/dismount', `Tab completes highlighted command (got "${await input.inputValue()}")`);+check(await page.locator('#kg-chat-hint').isHidden(), 'hint hides after completing a no-arg command');++// Typing a space (args) hides the hint; clearing back to a bare name reopens it.+await input.fill('/who ');+await page.waitForTimeout(60);+check(await page.locator('#kg-chat-hint').isHidden(), 'hint hides once a space (args) is typed');++// Escape dismisses an open hint without closing the chat.+await input.fill('/p');+await page.waitForTimeout(60);+check(await page.locator('#kg-chat-hint').isVisible(), "'/p' reopens the hint");+await input.press('Escape');+check(await page.locator('#kg-chat-hint').isHidden(), 'Escape dismisses the hint');+check(await page.locator('#kg-chat-input').isVisible(), 'chat input still present after Escape');++// Mouse pick fills the input (it then sends via the net path).+await input.fill('/pi');+await page.waitForTimeout(60);+await page.locator('#kg-chat-hint .kg-chat-hint-item').first().click();+await page.waitForTimeout(60);+// After a pick the field is cleared by _sendChat; assert the hint closed cleanly.+check(await page.locator('#kg-chat-hint').isHidden(), 'mouse pick completes + closes the hint');++check(consoleErrors.length === 0, `no unexpected console errors (${consoleErrors.length}): ${consoleErrors.slice(0, 3).join(' | ')}`);++await browser.close();++console.log('\n=== client autocomplete ===');+ok.forEach((m) => console.log(' PASS ' + m));+if (fail.length) {+ console.log('\n=== FAILURES ===');+ fail.forEach((m) => console.log(' FAIL ' + m));+ process.exit(1);+}+console.log(`\nAll ${ok.length} checks passed.`);diff --git a/src/friends.js b/src/friends.jsnew file mode 100644index 000000000..3cd3ad449--- /dev/null+++ b/src/friends.js@@ -0,0 +1,294 @@+// Friends client — the browser-side data layer for the account-level friends+// system (Task 15). It owns the social-graph state (friends, incoming/outgoing+// requests, DM threads, unread counts), talks to the /api/friends endpoints, and+// reconciles live socket events with a polling backstop so the UI is correct+// whether or not the live channel is connected.+//+// Realtime is delivered over whichever Colyseus realm room the player is already+// connected to: the server pushes a 'social' message, the net wrapper forwards+// it here via handleSocial(), and we update state + emit 'change'. The presence+// ticket minted here is what lets that realm room publish the player's presence+// in the first place (see getPresenceTicket).+//+// The panel UI (game/friends-panel.js) is a pure view over this client.++import { apiFetch } from './api.js';++// ── presence ticket ─────────────────────────────────────────────────────────+// Short-lived, account-scoped token the realm room verifies before publishing+// presence. Cached and refreshed lazily; the net layer calls getPresenceTicket()+// on every (re)connect, so an expired ticket self-heals on the next connection.+let _ticket = null;+let _ticketExpEpoch = 0;++export async function getPresenceTicket() {+ const now = Date.now() / 1000;+ if (_ticket && _ticketExpEpoch - now > 60) return _ticket;+ try {+ const res = await apiFetch('/api/friends/presence-ticket', { allowAnonymous: true });+ if (!res.ok) return null;+ const { data } = await res.json();+ if (!data?.token) return null;+ _ticket = data.token;+ _ticketExpEpoch = now + (Number(data.expiresIn) || 600);+ return _ticket;+ } catch {+ return null;+ }+}++const LIST_POLL_MS = 20_000; // presence + unread refresh while the panel is open+const THREAD_POLL_MS = 5_000; // open-thread refresh — backstop for the live push++export class FriendsClient {+ constructor() {+ this.friends = [];+ this.incoming = [];+ this.outgoing = [];+ this.threads = new Map(); // friendId → [{id, from, to, body, ts, mine, read}]+ this.openWith = null; // friendId of the thread currently shown, or null+ this.loaded = false;+ this.loadError = null;++ this._listeners = new Set();+ this._listTimer = null;+ this._threadTimer = null;+ this._active = false; // panel is open → poll+ }++ // ── subscription ───────────────────────────────────────────────────────+ subscribe(fn) {+ this._listeners.add(fn);+ return () => this._listeners.delete(fn);+ }+ _emit() {+ for (const fn of this._listeners) {+ try {+ fn(this);+ } catch (e) {+ console.error('[friends] listener threw:', e);+ }+ }+ }++ // Total unread across all friends — for the HUD badge.+ get totalUnread() {+ return this.friends.reduce((n, f) => n + (f.unread || 0), 0);+ }++ friend(id) {+ return this.friends.find((f) => f.id === id) || null;+ }++ // ── lifecycle ────────────────────────────────────────────────────────────+ // Called when the panel opens: load fresh and begin light polling for+ // presence + unread changes. Idempotent.+ activate() {+ this._active = true;+ this.refresh();+ if (!this._listTimer) this._listTimer = setInterval(() => this.refresh(), LIST_POLL_MS);+ }++ // Called when the panel closes: stop polling. State is retained so reopening+ // is instant; live events still arrive via handleSocial while closed.+ deactivate() {+ this._active = false;+ this._stopListPoll();+ this._stopThreadPoll();+ }++ _stopListPoll() {+ if (this._listTimer) {+ clearInterval(this._listTimer);+ this._listTimer = null;+ }+ }+ _stopThreadPoll() {+ if (this._threadTimer) {+ clearInterval(this._threadTimer);+ this._threadTimer = null;+ }+ }++ // ── graph ─────────────────────────────────────────────────────────────────+ async refresh() {+ try {+ const res = await apiFetch('/api/friends', { allowAnonymous: true });+ if (res.status === 401) {+ this.loadError = 'signin';+ this.loaded = true;+ this._emit();+ return;+ }+ if (!res.ok) throw new Error(`friends ${res.status}`);+ const { data } = await res.json();+ this.friends = data.friends || [];+ this.incoming = data.incoming || [];+ this.outgoing = data.outgoing || [];+ this.loaded = true;+ this.loadError = null;+ } catch (err) {+ this.loadError = 'network';+ this.loaded = true;+ console.warn('[friends] refresh failed:', err?.message);+ }+ this._emit();+ }++ async search(q) {+ const term = String(q || '').trim();+ if (term.length < 2) return [];+ try {+ const res = await apiFetch(`/api/friends/search?q=${encodeURIComponent(term)}`, {+ allowAnonymous: true,+ });+ if (!res.ok) return [];+ const { data } = await res.json();+ return data.results || [];+ } catch {+ return [];+ }+ }++ async _action(action, userId) {+ const res = await apiFetch('/api/friends', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ action, userId }),+ });+ if (!res.ok) {+ const body = await res.json().catch(() => ({}));+ const err = new Error(body.error_description || 'request failed');+ err.code = body.error;+ throw err;+ }+ const { data } = await res.json();+ await this.refresh();+ return data;+ }++ sendRequest(userId) {+ return this._action('request', userId);+ }+ accept(userId) {+ return this._action('accept', userId);+ }+ decline(userId) {+ return this._action('decline', userId);+ }+ remove(userId) {+ return this._action('remove', userId);+ }+ mute(userId) {+ return this._action('mute', userId);+ }+ unmute(userId) {+ return this._action('unmute', userId);+ }++ // ── DM threads ────────────────────────────────────────────────────────────+ async openThread(friendId) {+ this.openWith = friendId;+ await this.loadThread(friendId);+ // Opening a thread reads it server-side; reflect that locally.+ const f = this.friend(friendId);+ if (f && f.unread) {+ f.unread = 0;+ this._emit();+ }+ this._stopThreadPoll();+ if (this._active) {+ this._threadTimer = setInterval(() => this.loadThread(friendId, { quiet: true }), THREAD_POLL_MS);+ }+ }++ closeThread() {+ this.openWith = null;+ this._stopThreadPoll();+ this._emit();+ }++ async loadThread(friendId, { quiet = false } = {}) {+ try {+ const res = await apiFetch(`/api/friends/messages?with=${encodeURIComponent(friendId)}`, {+ allowAnonymous: true,+ });+ if (!res.ok) throw new Error(`thread ${res.status}`);+ const { data } = await res.json();+ this.threads.set(friendId, data.messages || []);+ if (!quiet || this.openWith === friendId) this._emit();+ } catch (err) {+ if (!quiet) console.warn('[friends] thread load failed:', err?.message);+ }+ }++ // Send a DM. Optimism is avoided on purpose: the server enforces friendship,+ // mutes, length, and rate limits, so we surface its result rather than+ // guessing. The sent message is appended on success.+ async sendDM(friendId, body) {+ const text = String(body || '').trim();+ if (!text) return;+ const res = await apiFetch('/api/friends/messages', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ to: friendId, body: text }),+ });+ if (!res.ok) {+ const b = await res.json().catch(() => ({}));+ const err = new Error(b.error_description || 'could not send');+ err.code = b.error;+ throw err;+ }+ const { data } = await res.json();+ if (data.message) {+ const thread = this.threads.get(friendId) || [];+ thread.push({ ...data.message, mine: true, read: true });+ this.threads.set(friendId, thread);+ this._emit();+ }+ return data;+ }++ // ── realtime ────────────────────────────────────────────────────────────+ // Route a 'social' message forwarded from the realm-room socket. Live DMs are+ // appended to the right thread (or bump the unread badge); friend-graph events+ // trigger a refresh so requests/lists update without the user reopening.+ handleSocial(msg) {+ if (!msg || typeof msg !== 'object') return;+ switch (msg.type) {+ case 'dm': {+ const m = msg.message;+ if (!m) return;+ const friendId = m.from;+ const thread = this.threads.get(friendId) || [];+ // Guard against the live push racing a poll that already fetched it.+ if (!thread.some((x) => x.id === m.id)) {+ thread.push({ ...m, mine: false, read: this.openWith === friendId });+ this.threads.set(friendId, thread);+ }+ if (this.openWith === friendId) {+ // Reading it now — clear server-side unread too.+ this.loadThread(friendId, { quiet: true });+ } else {+ const f = this.friend(friendId);+ if (f) f.unread = (f.unread || 0) + 1;+ }+ this._emit();+ break;+ }+ case 'friend_request':+ case 'friend_accept':+ this.refresh();+ break;+ default:+ break;+ }+ }+}++// One shared client per page — the panel and the net wiring both reference it.+let _client = null;+export function friendsClient() {+ if (!_client) _client = new FriendsClient();+ return _client;+}diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex 8dd0418ee..91c0c9ebe 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -1400,3 +1400,113 @@ html, body {justify-content: center;}}++/* ---------------- play gate (wallet sign-in) ----------------+ Stands in front of /play when the platform token gate is on. Monochrome,+ sharp, white-on-black CTAs — same language as the lobby. Sits above the boot+ loader (z 80) and every HUD layer. */+.pg-root {+ position: fixed; inset: 0; z-index: 200;+ display: grid; place-items: center; padding: 24px;+ animation: pg-fade 0.28s ease both;+}+.pg-root.pg-leaving { animation: pg-fade 0.3s ease reverse forwards; pointer-events: none; }+.pg-backdrop {+ position: absolute; inset: 0;+ background: radial-gradient(circle at 50% 36%, #161618, #050505 74%);+ backdrop-filter: saturate(130%) blur(6px);+}+.pg-card {+ position: relative; z-index: 1;+ width: min(420px, 100%); padding: 34px 30px 28px;+ display: flex; flex-direction: column; align-items: center; text-align: center;+ background: var(--cc-panel-solid);+ border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius);+ box-shadow: var(--cc-shadow);+ animation: pg-rise 0.42s cubic-bezier(0.16, 0.84, 0.34, 1) both;+}+.pg-brand {+ display: flex; align-items: center; gap: 9px; margin-bottom: 22px;+ color: var(--cc-dim);+}+.pg-brand img { filter: drop-shadow(0 0 12px rgba(255, 255, 255, 0.25)); }+.pg-brand span { font-weight: 800; font-size: 11px; letter-spacing: 0.26em; }+.pg-icon {+ width: 56px; height: 56px; margin-bottom: 16px;+ display: grid; place-items: center;+ border: 1px solid var(--cc-edge); border-radius: 50%;+ color: var(--cc-text);+}+.pg-icon svg { width: 26px; height: 26px; }+.pg-title { margin: 0 0 8px; font-size: 21px; font-weight: 700; letter-spacing: -0.01em; color: var(--cc-text); }+.pg-sub { margin: 0 0 22px; font-size: 13.5px; line-height: 1.55; color: var(--cc-dim); max-width: 34ch; }+.pg-sub strong { color: var(--cc-text); font-weight: 600; }+.pg-error {+ margin: -8px 0 18px; padding: 9px 12px; width: 100%;+ font-size: 12.5px; line-height: 1.45; color: var(--cc-text);+ background: rgba(255, 255, 255, 0.05);+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);+}+.pg-fine { margin: 12px 0 0; font-size: 11px; letter-spacing: 0.04em; color: var(--cc-faint); }++/* buttons */+.pg-btn {+ -webkit-appearance: none; appearance: none; cursor: pointer;+ width: 100%; margin-top: 10px; padding: 13px 18px;+ font-family: inherit; font-size: 13px; font-weight: 600; letter-spacing: 0.03em;+ border-radius: var(--cc-radius-sm); border: 1px solid var(--cc-edge);+ background: transparent; color: var(--cc-text);+ text-decoration: none; display: inline-flex; align-items: center; justify-content: center;+ transition: transform 0.12s ease, background 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease;+}+.pg-btn:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.04); }+.pg-btn:active { transform: translateY(1px); }+.pg-btn:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-edge-hi); }+.pg-btn-primary {+ background: var(--cc-accent); color: var(--cc-ink); border-color: var(--cc-accent);+}+.pg-btn-primary:hover { background: #fff; box-shadow: var(--cc-glow); }+.pg-btn-ghost { color: var(--cc-dim); }+.pg-btn-ghost:hover { color: var(--cc-text); }++/* balance comparison (too-low state) */+.pg-balance {+ display: flex; align-items: center; justify-content: center; gap: 14px;+ width: 100%; margin: 2px 0 18px; padding: 14px;+ border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm);+ background: rgba(255, 255, 255, 0.02);+}+.pg-balance > div { display: flex; flex-direction: column; gap: 3px; }+.pg-balance-k { font-size: 10px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--cc-faint); }+.pg-balance-v { font-size: 18px; font-weight: 700; color: var(--cc-text); font-variant-numeric: tabular-nums; }+.pg-balance-need { color: var(--cc-text); }+.pg-balance-sep { color: var(--cc-faint); font-size: 16px; }++/* spinner + success check */+.pg-spinner {+ width: 38px; height: 38px; margin-bottom: 18px; border-radius: 50%;+ border: 2px solid var(--cc-edge); border-top-color: var(--cc-accent);+ animation: pg-spin 0.8s linear infinite;+}+.pg-check {+ width: 56px; height: 56px; margin-bottom: 16px; border-radius: 50%;+ display: grid; place-items: center; font-size: 26px; font-weight: 700;+ color: var(--cc-ink); background: var(--cc-accent); box-shadow: var(--cc-glow);+ animation: pg-pop 0.4s cubic-bezier(0.16, 0.84, 0.34, 1) both;+}++@keyframes pg-fade { from { opacity: 0; } to { opacity: 1; } }+@keyframes pg-rise { from { opacity: 0; transform: translateY(12px) scale(0.985); } to { opacity: 1; transform: none; } }+@keyframes pg-spin { to { transform: rotate(360deg); } }+@keyframes pg-pop { 0% { transform: scale(0.4); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }++@media (prefers-reduced-motion: reduce) {+ .pg-root, .pg-card, .pg-check { animation: none; }+ .pg-spinner { animation-duration: 1.4s; }+}++@media (max-width: 480px) {+ .pg-card { padding: 28px 20px 24px; }+ .pg-title { font-size: 19px; }+}diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 9bb1ef756..b78b1c411 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -35,6 +35,8 @@ import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';import { HOME_TOWN, isHomeTown } from './home-town.js';import { VoiceChat, voiceSupported } from './voice-chat.js';import { requestHolderPass, signInWithX, ensureSolanaWallet, getSession } from '../community/town-auth.js';+import { ensurePlayAccess } from './play-gate.js';+import { clearStoredPass } from './play-auth.js';const WORLD_RADIUS = 58; // a touch inside the server's 60m clampconst MOVE_SPEED = 4.2;@@ -232,6 +234,16 @@ export class CoinCommunities {this._loop = this._loop.bind(this);requestAnimationFrame(this._loop);+ // Wallet-first entry: when the platform has pinned a game token, the sign-in+ // gate stands in front of everything — connect a wallet, sign a nonce, and+ // hold ≥ the floor before any world opens. The verified wallet becomes the+ // account id we carry into every room. When no token is pinned the gate+ // resolves instantly (open /play) and nothing below changes. enter() awaits+ // this, so a deep link still drops in — just after the gate clears.+ this.playPass = '';+ this.account = '';+ this._playReady = this._ensurePlayAccess();+// Deep link: /play?coin=<mint>&name=&symbol=&image= drops straight into a// coin's community, so a community is a shareable URL.const p = new URLSearchParams(location.search);@@ -531,6 +543,10 @@ export class CoinCommunities {// ---------------------------------------------------------------- enter/leaveasync enter(coin, opts = {}) {if (this.phase !== 'lobby') return;+ // Clear the platform sign-in gate before anything else. Resolves instantly+ // when /play is open (no token pinned) or when we already hold a fresh pass.+ if (this._playReady) { try { await this._playReady; } catch { /* gate self-heals */ } }+ if (this.phase !== 'lobby') return; // backed out / re-entered while the gate was upconst tier = opts.tier === 'holders' ? 'holders' : 'general';// Entry does several awaits (gate, manifest, avatar GLB, room connect) and// the Leave button goes live the moment the HUD shows — well before connect@@ -661,6 +677,10 @@ export class CoinCommunities {coin: { mint: coin.mint, name: coin.name, symbol: coin.symbol, image: coin.image },tier: tier === 'holders' ? 'holders' : '',holderPass, holderMinUsd,+ // Platform token gate: the verified wallet + signed pass from sign-in. The+ // server binds the wallet (inside the pass) as the account id; harmless+ // when the server isn't gated.+ playPass: this.playPass, account: this.account,});if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));this.net.on('status', ({ status }) => {@@ -699,7 +719,19 @@ export class CoinCommunities {// A holder pass can expire (10 min) between minting and a mid-session// reconnect; if the server then refuses the join, drop the player back to// the lobby with a clear reason rather than looping on a dead pass.- this.net.on('denied', () => {+ this.net.on('denied', (reason) => {+ // The platform token gate evicted us (pass expired, or the wallet dropped+ // below the floor): force a fresh sign-in before they can play again — the+ // cached pass is now void, so clear it so the gate re-checks the chain.+ if (/play_pass/i.test(reason || '')) {+ clearStoredPass();+ this.playPass = '';+ this.account = '';+ this.ui.toast('Your session expired — sign in again to keep playing.', 'warn');+ this.leave();+ this._playReady = this._ensurePlayAccess();+ return;+ }this.ui.toast('Your holder pass expired — re-enter to verify your holdings.', 'warn');this.leave();});@@ -739,6 +771,25 @@ export class CoinCommunities {}, 4200);}+ // Wallet-first platform gate. Shows the sign-in screen (connect → sign nonce →+ // verify token balance) when the server requires it, and caches the verified+ // wallet + signed pass we attach to every room join. Self-healing: any failure+ // resolves to "open" rather than bricking /play, since the server is the real+ // authority — an unsigned join is refused there regardless.+ async _ensurePlayAccess() {+ try {+ const access = await ensurePlayAccess();+ if (access?.required) {+ this.playPass = access.playPass || '';+ this.account = access.wallet || '';+ }+ return access;+ } catch (err) {+ console.warn('[coincommunities] play gate error:', err?.message);+ return { required: false };+ }+ }+// Run the holder gate for a coin's Holders world. Drives the overlay through// its states and resolves to the verified pass data ({ holderPass, minUsd, … })// once the player clears the floor, or null if they back out. All the on-chaindiff --git a/src/game/community-net.js b/src/game/community-net.jsindex 764eaeb89..f35ec692a 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -51,6 +51,8 @@ export class CommunityNet {* @param {string} [opts.tier] '' (open General world) | 'holders' (gated)* @param {string} [opts.holderPass] signed pass required to join a holder world* @param {number} [opts.holderMinUsd] USD floor the holder world gated on (HUD)+ * @param {string} [opts.playPass] signed wallet+token pass for the platform gate+ * @param {string} [opts.account] verified wallet address bound as the account id* @param {string} [opts.url] server override*/constructor(opts = {}) {@@ -61,6 +63,11 @@ export class CommunityNet {this.tier = opts.tier === 'holders' ? 'holders' : '';this.holderPass = opts.holderPass || '';this.holderMinUsd = Number(opts.holderMinUsd) || 0;+ // Platform token gate: when the server is gated, every join must carry this+ // signed pass (proving wallet ownership + ≥ the token floor) or onAuth+ // refuses with a play_pass_* error. Sent for all tiers, not just holders.+ this.playPass = opts.playPass || '';+ this.account = opts.account || '';this.url = opts.url || defaultServerUrl();this.client = null;@@ -153,6 +160,10 @@ export class CommunityNet {name: this.name,avatar: this.avatar,agent: this.agent,+ // Platform gate: harmless when the server isn't gated (ignored), required+ // when it is. The verified wallet rides inside the signed pass; the server+ // binds it as the account id, so we never trust a raw `account` option.+ playPass: this.playPass,};// Holder worlds require a signed pass the server verifies in onAuth; carry// it (and the floor it gated on, for the seed room's HUD) only for holders.@@ -213,6 +224,11 @@ export class CommunityNet {this.room.onLeave((code) => {this._setStatus('offline');+ // 4002: the server evicted us because our play pass expired without a+ // refresh (the wallet may have dropped below the token floor). Reconnecting+ // would just fail onAuth again — surface it as a terminal denial so the+ // scene routes the player back to the sign-in gate.+ if (code === 4002) { this._setStatus('denied', 'play_pass_required'); this._emit('denied', 'play_pass_required'); return; }if (!this._destroyed && code !== 1000) this._scheduleReconnect();});this.room.onError((code, message) => console.warn('[community-net] room.onError', code, message));@@ -230,8 +246,8 @@ export class CommunityNet {// A holder-gate refusal (onAuth threw) is terminal, not a flaky link —// retrying with the same expired/invalid pass just loops. Surface it so// the scene can route the player back to the gate, and stop here.- if (/holder_pass/i.test(msg)) {- console.warn('[community-net] holder gate denied join:', msg);+ if (/holder_pass|play_pass/i.test(msg)) {+ console.warn('[community-net] gate denied join:', msg);this._setStatus('denied', msg);this._emit('denied', msg);return;diff --git a/src/game/cosmetics-visual.js b/src/game/cosmetics-visual.jsnew file mode 100644index 000000000..581fda611--- /dev/null+++ b/src/game/cosmetics-visual.js@@ -0,0 +1,143 @@+// Cosmetic visual layer — turns a cosmetic's `visual` spec (sent in the server+// catalogue) into renderable Three.js objects layered over an avatar rig. This+// is the ONLY thing a cosmetic does: it changes how an avatar looks. Nothing+// here reads or writes any gameplay value.+//+// Three visual primitives, any of which a cosmetic may combine:+// tint — recolour the avatar's body materials (a dye). Multiplies into each+// material's colour so textured models shift hue instead of going flat.+// prop — a GLB worn on the head (hats), auto-fitted to the avatar's height so+// one asset sits correctly on any model.+// aura — a glowing, slowly-spinning ring at the avatar's feet.+//+// applyCosmetic() returns a handle: tick(dt) animates the aura, dispose() fully+// removes the layer and restores the original material colours. The rig owner+// re-applies after every avatar (re)load, since loading clears the rig.++import {+ Group, Mesh, MeshBasicMaterial, RingGeometry, Box3, Vector3,+ AdditiveBlending, DoubleSide,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { dracoLoader } from './avatar-rig.js';++// Share the Draco-enabled decoder module + cache with the avatar loader so prop+// GLBs (which may be Draco-compressed) decode without a second decoder instance.+const _loader = new GLTFLoader();+_loader.setDRACOLoader(dracoLoader);++// Cache each prop's loaded scene once; every wearer gets a deep clone so they+// never share (and mutate) one another's meshes.+const _propCache = new Map(); // url -> Promise<Object3D|null>+function loadProp(url) {+ if (!_propCache.has(url)) {+ _propCache.set(url, _loader.loadAsync(url)+ .then((g) => g.scene)+ .catch((err) => { console.warn('[cosmetics] prop load failed:', url, err?.message); return null; }));+ }+ return _propCache.get(url);+}++// Recolour every body material, remembering each material's original colour so+// dispose() can restore it exactly. Dedupes by material (a model often shares+// one across meshes) so we store/restore each once.+function applyTint(rig, hex) {+ const restore = new Map(); // material -> original hex+ rig.traverse((n) => {+ if (!n.isMesh) return;+ const mats = Array.isArray(n.material) ? n.material : [n.material];+ for (const m of mats) {+ if (!m || !m.color || restore.has(m)) continue;+ restore.set(m, m.color.getHex());+ m.color.set(hex);+ }+ });+ return () => { for (const [m, orig] of restore) m.color?.setHex(orig); };+}++// A worn prop (hat). The GLB is auto-scaled so its width matches a head-ish+// target and seated near the top of the avatar, so a single asset fits models+// of any height without per-asset tuning.+const PROP_TARGET_WIDTH_M = 0.34; // ~ a human head's width+function mountProp(rig, height, url) {+ const holder = new Group();+ rig.add(holder);+ let cancelled = false;+ loadProp(url).then((scene) => {+ if (cancelled || !scene) return;+ const model = scene.clone(true);+ model.traverse((n) => { if (n.isMesh) { n.castShadow = true; n.receiveShadow = false; } });+ // Fit width to the target, then rest the prop on top of the head.+ const box = new Box3().setFromObject(model);+ const size = box.getSize(new Vector3());+ const span = Math.max(size.x, size.z) || 1;+ const scale = PROP_TARGET_WIDTH_M / span;+ model.scale.setScalar(scale);+ const fitted = new Box3().setFromObject(model);+ const center = fitted.getCenter(new Vector3());+ // Seat the prop's base around the crown of the head (≈0.86 of total height).+ model.position.x -= center.x;+ model.position.z -= center.z;+ model.position.y += height * 0.86 - fitted.min.y;+ holder.add(model);+ });+ // Dispose = detach the holder only. The clone shares the cached source's+ // geometry + materials (Object3D.clone(true) copies them by reference), so+ // those GPU resources live once in _propCache and are reused by every wearer —+ // disposing them here would corrupt the cache and other players' props. The+ // cache holds one parsed scene per prop URL (a handful total), so it's bounded,+ // not a leak; the clone's wrapper objects are freed for GC when the holder goes.+ return () => { cancelled = true; rig.remove(holder); };+}++// A glowing ground aura: a bright inner ring plus a softer outer halo, laid flat+// at the feet, additively blended so it reads as light. tick() spins it and+// gently pulses the halo.+function mountAura(rig, hex) {+ const group = new Group();+ const mkRing = (inner, outer, opacity) => {+ const geo = new RingGeometry(inner, outer, 48);+ const mat = new MeshBasicMaterial({+ color: hex, transparent: true, opacity,+ blending: AdditiveBlending, side: DoubleSide, depthWrite: false,+ });+ const ring = new Mesh(geo, mat);+ ring.rotation.x = -Math.PI / 2;+ return ring;+ };+ const core = mkRing(0.42, 0.58, 0.85);+ const halo = mkRing(0.58, 0.92, 0.28);+ group.add(halo, core);+ group.position.y = 0.03;+ rig.add(group);+ let t = 0;+ return {+ tick: (dt) => {+ t += dt;+ group.rotation.y += dt * 0.6;+ halo.material.opacity = 0.20 + 0.12 * (0.5 + 0.5 * Math.sin(t * 2));+ },+ dispose: () => {+ rig.remove(group);+ core.geometry.dispose(); core.material.dispose();+ halo.geometry.dispose(); halo.material.dispose();+ },+ };+}++// Apply a cosmetic `visual` spec to a rig at a known head-anchor `height`.+// Returns { tick(dt), dispose() }. Safe to call before the avatar model has+// finished loading — tint simply finds no meshes yet (callers re-apply on load),+// while a prop/aura attach to the rig regardless.+export function applyCosmetic(rig, height, visual) {+ if (!visual) return { tick() {}, dispose() {} };+ const undo = [];+ if (visual.tint) undo.push(applyTint(rig, visual.tint));+ if (visual.prop) undo.push(mountProp(rig, height, visual.prop));+ let aura = null;+ if (visual.aura) { aura = mountAura(rig, visual.aura); undo.push(aura.dispose); }+ return {+ tick: (dt) => aura?.tick(dt),+ dispose: () => { for (const fn of undo) { try { fn(); } catch {} } },+ };+}diff --git a/src/game/friends-panel.js b/src/game/friends-panel.jsnew file mode 100644index 000000000..604c4ede1--- /dev/null+++ b/src/game/friends-panel.js@@ -0,0 +1,495 @@+// Friends panel UI (Task 15) — a pure view over the shared FriendsClient. It+// renders into a container the host owns (the /play "friends" surface in+// iso-controls) and drives every account-level social interaction: incoming /+// outgoing requests, the friends list with live online + realm badges, a+// search-to-add flow, and per-friend DM threads with unread indicators.+//+// All state lives in the FriendsClient; this module subscribes to its 'change'+// signal and re-renders. Every state is designed: loading, signed-out, network+// error, empty graph, empty thread.++import { friendsClient } from '../friends.js';++const HOTKEY_NOTE = 'Press F to toggle this panel.';++function el(tag, attrs = {}, kids = []) {+ const n = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v == null || v === false) continue;+ if (k === 'class') n.className = v;+ else if (k === 'text') n.textContent = v;+ else if (k === 'html') n.innerHTML = v;+ else if (k === 'dataset') Object.assign(n.dataset, v);+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2).toLowerCase(), v);+ else if (v === true) n.setAttribute(k, '');+ else n.setAttribute(k, v);+ }+ for (const c of [].concat(kids)) {+ if (c == null || c === false) continue;+ n.append(c.nodeType ? c : document.createTextNode(String(c)));+ }+ return n;+}++function initials(name) {+ const parts = String(name || '?').trim().split(/\s+/).slice(0, 2);+ return parts.map((p) => p[0] || '').join('').toUpperCase() || '?';+}++function relTime(ts) {+ if (!ts) return '';+ const d = new Date(ts).getTime();+ if (!d) return '';+ const s = Math.max(0, (Date.now() - d) / 1000);+ if (s < 45) return 'just now';+ if (s < 90) return '1 min ago';+ if (s < 3600) return `${Math.round(s / 60)} min ago`;+ if (s < 5400) return '1 hr ago';+ if (s < 86400) return `${Math.round(s / 3600)} hr ago`;+ if (s < 172800) return 'yesterday';+ return `${Math.round(s / 86400)} d ago`;+}++function realmLabel(realm) {+ if (!realm) return '';+ return String(realm).replace(/[_-]+/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());+}++export class FriendsPanel {+ constructor(container) {+ this.root = container;+ this.client = friendsClient();+ this.tab = 'friends'; // 'friends' | 'requests' | 'add'+ this._searchResults = [];+ this._searchTerm = '';+ this._searching = false;+ this._searchSeq = 0;+ this._busy = new Set(); // userIds with an action in flight (disable buttons)+ this._error = null; // transient action error banner+ this._unsub = null;+ this._draft = ''; // preserved DM input across re-renders+ }++ mount() {+ if (this._mounted) return;+ this._mounted = true;+ this._unsub = this.client.subscribe(() => this.render());+ this.client.activate();+ this.render();+ }++ unmount() {+ this._mounted = false;+ if (this._unsub) this._unsub();+ this._unsub = null;+ this.client.closeThread();+ this.client.deactivate();+ }++ // Whether the panel is currently showing a DM thread (vs. the list tabs).+ get inThread() {+ return !!this.client.openWith;+ }++ async _run(userId, fn) {+ this._busy.add(userId);+ this._error = null;+ this.render();+ try {+ await fn();+ } catch (err) {+ this._error = err?.message || 'Something went wrong.';+ } finally {+ this._busy.delete(userId);+ this.render();+ }+ }++ // ── render ────────────────────────────────────────────────────────────────+ render() {+ if (!this._mounted) return;+ this.root.innerHTML = '';+ this.root.classList.add('kg-fr');++ const c = this.client;+ if (!c.loaded) {+ this.root.append(this._skeleton());+ return;+ }+ if (c.loadError === 'signin') {+ this.root.append(this._signedOut());+ return;+ }+ if (this.inThread) {+ this.root.append(this._threadView());+ return;+ }+ this.root.append(this._tabs(), this._error ? this._banner(this._error) : null, this._tabBody());+ }++ _skeleton() {+ const wrap = el('div', { class: 'kg-fr-skel' });+ for (let i = 0; i < 4; i++) wrap.append(el('div', { class: 'kg-fr-skel-row' }));+ return wrap;+ }++ _banner(msg) {+ return el('div', { class: 'kg-fr-banner', role: 'alert' }, msg);+ }++ _signedOut() {+ return el('div', { class: 'kg-fr-empty' }, [+ el('div', { class: 'kg-fr-empty-glyph', 'aria-hidden': 'true' }, '👥'),+ el('p', { class: 'kg-fr-empty-title' }, 'Sign in to add friends'),+ el('p', { class: 'kg-fr-empty-sub' }, 'Friends, presence, and direct messages are tied to your account.'),+ el('a', { class: 'kg-fr-btn kg-fr-btn--primary', href: `/login?next=${encodeURIComponent(location.pathname)}` }, 'Sign in'),+ ]);+ }++ _tabs() {+ const c = this.client;+ const reqCount = c.incoming.length;+ const mk = (id, label, badge) =>+ el(+ 'button',+ {+ class: 'kg-fr-tab' + (this.tab === id ? ' is-active' : ''),+ type: 'button',+ 'aria-selected': this.tab === id ? 'true' : 'false',+ onclick: () => {+ this.tab = id;+ this.render();+ },+ },+ [label, badge ? el('span', { class: 'kg-fr-pill' }, String(badge)) : null],+ );+ return el('div', { class: 'kg-fr-tabs', role: 'tablist' }, [+ mk('friends', 'Friends', c.totalUnread || null),+ mk('requests', 'Requests', reqCount || null),+ mk('add', 'Add', null),+ ]);+ }++ _tabBody() {+ if (this.tab === 'requests') return this._requestsTab();+ if (this.tab === 'add') return this._addTab();+ return this._friendsTab();+ }++ // ── friends list ────────────────────────────────────────────────────────+ _friendsTab() {+ const friends = this.client.friends;+ if (!friends.length) {+ return el('div', { class: 'kg-fr-empty' }, [+ el('div', { class: 'kg-fr-empty-glyph', 'aria-hidden': 'true' }, '🫂'),+ el('p', { class: 'kg-fr-empty-title' }, 'No friends yet'),+ el('p', { class: 'kg-fr-empty-sub' }, 'Search to add someone, then message them or see when they’re online.'),+ el('button', { class: 'kg-fr-btn kg-fr-btn--primary', type: 'button', onclick: () => { this.tab = 'add'; this.render(); } }, 'Search to add'),+ ]);+ }+ // Online first, then alphabetical (the store already sorts by name).+ const sorted = [...friends].sort((a, b) => Number(!!b.online) - Number(!!a.online));+ const list = el('ul', { class: 'kg-fr-list' });+ for (const f of sorted) list.append(this._friendRow(f));+ return list;+ }++ _friendRow(f) {+ const presence = f.online+ ? el('span', { class: 'kg-fr-status kg-fr-status--on' }, f.realm ? realmLabel(f.realm) : 'Online')+ : el('span', { class: 'kg-fr-status kg-fr-status--off' }, 'Offline');+ const open = () => this.client.openThread(f.id);+ return el('li', { class: 'kg-fr-row' }, [+ el('button', { class: 'kg-fr-rowmain', type: 'button', onclick: open, 'aria-label': `Open chat with ${f.name}` }, [+ this._avatar(f),+ el('span', { class: 'kg-fr-meta' }, [+ el('span', { class: 'kg-fr-name' }, f.name),+ presence,+ ]),+ f.unread ? el('span', { class: 'kg-fr-unread', title: `${f.unread} unread` }, String(f.unread)) : null,+ ]),+ el('div', { class: 'kg-fr-rowactions' }, [+ el('button', { class: 'kg-fr-icon', type: 'button', title: 'Message', 'aria-label': `Message ${f.name}`, onclick: open }, '✉'),+ el('button', {+ class: 'kg-fr-icon', type: 'button', title: 'Mute', 'aria-label': `Mute ${f.name}`,+ disabled: this._busy.has(f.id), onclick: () => this._run(f.id, () => this.client.mute(f.id)),+ }, '🔕'),+ el('button', {+ class: 'kg-fr-icon kg-fr-icon--danger', type: 'button', title: 'Remove friend', 'aria-label': `Remove ${f.name}`,+ disabled: this._busy.has(f.id),+ onclick: () => { if (confirm(`Remove ${f.name} from your friends?`)) this._run(f.id, () => this.client.remove(f.id)); },+ }, '✕'),+ ]),+ ]);+ }++ _avatar(u) {+ const dot = el('span', { class: 'kg-fr-dot ' + (u.online ? 'kg-fr-dot--on' : 'kg-fr-dot--off') });+ if (u.avatarUrl) {+ return el('span', { class: 'kg-fr-av' }, [+ el('img', { class: 'kg-fr-av-img', src: u.avatarUrl, alt: '', loading: 'lazy' }),+ dot,+ ]);+ }+ return el('span', { class: 'kg-fr-av kg-fr-av--mono' }, [+ el('span', { class: 'kg-fr-av-ini', 'aria-hidden': 'true' }, initials(u.name)),+ dot,+ ]);+ }++ // ── requests ──────────────────────────────────────────────────────────────+ _requestsTab() {+ const { incoming, outgoing } = this.client;+ if (!incoming.length && !outgoing.length) {+ return el('div', { class: 'kg-fr-empty' }, [+ el('div', { class: 'kg-fr-empty-glyph', 'aria-hidden': 'true' }, '📨'),+ el('p', { class: 'kg-fr-empty-title' }, 'No pending requests'),+ el('p', { class: 'kg-fr-empty-sub' }, 'Friend invites you send or receive show up here.'),+ ]);+ }+ const frag = el('div', { class: 'kg-fr-reqs' });+ if (incoming.length) {+ frag.append(el('h3', { class: 'kg-fr-subhead' }, 'Incoming'));+ const ul = el('ul', { class: 'kg-fr-list' });+ for (const u of incoming) ul.append(this._incomingRow(u));+ frag.append(ul);+ }+ if (outgoing.length) {+ frag.append(el('h3', { class: 'kg-fr-subhead' }, 'Sent'));+ const ul = el('ul', { class: 'kg-fr-list' });+ for (const u of outgoing) ul.append(this._outgoingRow(u));+ frag.append(ul);+ }+ return frag;+ }++ _incomingRow(u) {+ return el('li', { class: 'kg-fr-row' }, [+ el('div', { class: 'kg-fr-rowmain kg-fr-rowmain--static' }, [+ this._avatar(u),+ el('span', { class: 'kg-fr-meta' }, [+ el('span', { class: 'kg-fr-name' }, u.name),+ el('span', { class: 'kg-fr-status' }, `Sent ${relTime(u.requestedAt)}`),+ ]),+ ]),+ el('div', { class: 'kg-fr-rowactions' }, [+ el('button', {+ class: 'kg-fr-btn kg-fr-btn--primary kg-fr-btn--sm', type: 'button', disabled: this._busy.has(u.id),+ onclick: () => this._run(u.id, () => this.client.accept(u.id)),+ }, 'Accept'),+ el('button', {+ class: 'kg-fr-btn kg-fr-btn--ghost kg-fr-btn--sm', type: 'button', disabled: this._busy.has(u.id),+ onclick: () => this._run(u.id, () => this.client.decline(u.id)),+ }, 'Decline'),+ ]),+ ]);+ }++ _outgoingRow(u) {+ return el('li', { class: 'kg-fr-row' }, [+ el('div', { class: 'kg-fr-rowmain kg-fr-rowmain--static' }, [+ this._avatar(u),+ el('span', { class: 'kg-fr-meta' }, [+ el('span', { class: 'kg-fr-name' }, u.name),+ el('span', { class: 'kg-fr-status' }, `Requested ${relTime(u.requestedAt)}`),+ ]),+ ]),+ el('div', { class: 'kg-fr-rowactions' }, [+ el('span', { class: 'kg-fr-tagpending' }, 'Pending'),+ el('button', {+ class: 'kg-fr-btn kg-fr-btn--ghost kg-fr-btn--sm', type: 'button', disabled: this._busy.has(u.id),+ onclick: () => this._run(u.id, () => this.client.remove(u.id)),+ }, 'Cancel'),+ ]),+ ]);+ }++ // ── add / search ──────────────────────────────────────────────────────────+ _addTab() {+ const wrap = el('div', { class: 'kg-fr-add' });+ const input = el('input', {+ class: 'kg-fr-search', type: 'search', placeholder: 'Search by name or username…',+ value: this._searchTerm, autocomplete: 'off', spellcheck: 'false', 'aria-label': 'Search players',+ });+ input.addEventListener('input', () => this._onSearchInput(input.value));+ wrap.append(el('div', { class: 'kg-fr-searchwrap' }, [el('span', { class: 'kg-fr-search-ico', 'aria-hidden': 'true' }, '🔍'), input]));++ const results = el('div', { class: 'kg-fr-results' });+ if (this._searchTerm.trim().length < 2) {+ results.append(el('p', { class: 'kg-fr-hint' }, 'Type at least 2 characters to search.'));+ } else if (this._searching) {+ results.append(el('p', { class: 'kg-fr-hint' }, 'Searching…'));+ } else if (!this._searchResults.length) {+ results.append(el('p', { class: 'kg-fr-hint' }, `No players match “${this._searchTerm.trim()}”.`));+ } else {+ const ul = el('ul', { class: 'kg-fr-list' });+ for (const u of this._searchResults) ul.append(this._searchRow(u));+ results.append(ul);+ }+ wrap.append(results);+ // Keep focus + caret in the search box across re-renders.+ queueMicrotask(() => {+ if (this.tab === 'add' && document.contains(input)) {+ input.focus();+ const v = input.value;+ input.setSelectionRange?.(v.length, v.length);+ }+ });+ return wrap;+ }++ _onSearchInput(value) {+ this._searchTerm = value;+ const term = value.trim();+ const seq = ++this._searchSeq;+ clearTimeout(this._searchDebounce);+ if (term.length < 2) {+ this._searchResults = [];+ this._searching = false;+ this.render();+ return;+ }+ this._searching = true;+ this.render();+ this._searchDebounce = setTimeout(async () => {+ const res = await this.client.search(term);+ if (seq !== this._searchSeq) return; // a newer keystroke superseded this+ this._searchResults = res;+ this._searching = false;+ this.render();+ }, 280);+ }++ _searchRow(u) {+ let action;+ if (u.relationship === 'friends') {+ action = el('span', { class: 'kg-fr-tagpending kg-fr-tagpending--ok' }, 'Friends');+ } else if (u.relationship === 'outgoing') {+ action = el('span', { class: 'kg-fr-tagpending' }, 'Pending');+ } else if (u.relationship === 'incoming') {+ action = el('button', {+ class: 'kg-fr-btn kg-fr-btn--primary kg-fr-btn--sm', type: 'button', disabled: this._busy.has(u.id),+ onclick: () => this._run(u.id, async () => { await this.client.accept(u.id); this._refreshSearchRow(u.id, 'friends'); }),+ }, 'Accept');+ } else {+ action = el('button', {+ class: 'kg-fr-btn kg-fr-btn--primary kg-fr-btn--sm', type: 'button', disabled: this._busy.has(u.id),+ onclick: () => this._run(u.id, async () => {+ const r = await this.client.sendRequest(u.id);+ this._refreshSearchRow(u.id, r.relationship || 'outgoing');+ }),+ }, 'Add');+ }+ return el('li', { class: 'kg-fr-row' }, [+ el('div', { class: 'kg-fr-rowmain kg-fr-rowmain--static' }, [+ this._avatar(u),+ el('span', { class: 'kg-fr-meta' }, [+ el('span', { class: 'kg-fr-name' }, u.name),+ u.username ? el('span', { class: 'kg-fr-status' }, `@${u.username}`) : null,+ ]),+ ]),+ el('div', { class: 'kg-fr-rowactions' }, action),+ ]);+ }++ // Optimistically reflect a relationship change in the cached search results so+ // the row updates instantly (the full graph also refreshes underneath).+ _refreshSearchRow(id, relationship) {+ const row = this._searchResults.find((r) => r.id === id);+ if (row) row.relationship = relationship;+ this.render();+ }++ // ── DM thread ───────────────────────────────────────────────────────────+ _threadView() {+ const id = this.client.openWith;+ const f = this.client.friend(id);+ const msgs = this.client.threads.get(id);+ const head = el('div', { class: 'kg-fr-thread-head' }, [+ el('button', { class: 'kg-fr-back', type: 'button', 'aria-label': 'Back to friends', onclick: () => this.client.closeThread() }, '‹'),+ f ? this._avatar(f) : null,+ el('span', { class: 'kg-fr-meta' }, [+ el('span', { class: 'kg-fr-name' }, f ? f.name : 'Conversation'),+ el('span', { class: 'kg-fr-status' }, f ? (f.online ? (f.realm ? `Online · ${realmLabel(f.realm)}` : 'Online') : 'Offline') : ''),+ ]),+ ]);++ const scroll = el('div', { class: 'kg-fr-thread-msgs' });+ if (!msgs) {+ scroll.append(el('p', { class: 'kg-fr-hint' }, 'Loading messages…'));+ } else if (!msgs.length) {+ scroll.append(el('div', { class: 'kg-fr-thread-empty' }, [+ el('p', { class: 'kg-fr-empty-title' }, `Say hello to ${f ? f.name : 'your friend'}`),+ el('p', { class: 'kg-fr-empty-sub' }, 'Messages deliver instantly when they’re online, and wait for them when they’re not.'),+ ]));+ } else {+ let lastDay = '';+ for (const m of msgs) {+ const day = new Date(m.ts).toDateString();+ if (day !== lastDay) {+ scroll.append(el('div', { class: 'kg-fr-daysep' }, relDay(m.ts)));+ lastDay = day;+ }+ scroll.append(+ el('div', { class: 'kg-fr-msg ' + (m.mine ? 'kg-fr-msg--mine' : 'kg-fr-msg--theirs') }, [+ el('span', { class: 'kg-fr-msg-body' }, m.body),+ el('span', { class: 'kg-fr-msg-time', title: new Date(m.ts).toLocaleString() }, fmtTime(m.ts)),+ ]),+ );+ }+ }++ const input = el('input', {+ class: 'kg-fr-dm-input', type: 'text', maxlength: '2000', placeholder: 'Message…',+ value: this._draft, 'aria-label': 'Type a message',+ });+ const sendBtn = el('button', { class: 'kg-fr-dm-send', type: 'button', 'aria-label': 'Send' }, '➤');+ const submit = async () => {+ const text = input.value.trim();+ if (!text) return;+ input.value = '';+ this._draft = '';+ try {+ await this.client.sendDM(id, text);+ } catch (err) {+ this._draft = text;+ this._error = err?.message || 'Could not send.';+ this.render();+ }+ };+ input.addEventListener('input', () => { this._draft = input.value; });+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); submit(); }+ e.stopPropagation(); // don't let the game hotkeys eat typing+ });+ sendBtn.addEventListener('click', submit);++ const composer = el('div', { class: 'kg-fr-dm-bar' }, [input, sendBtn]);+ const view = el('div', { class: 'kg-fr-thread' }, [head, this._error ? this._banner(this._error) : null, scroll, composer]);++ // Pin to newest + focus the composer after paint.+ queueMicrotask(() => {+ scroll.scrollTop = scroll.scrollHeight;+ if (document.contains(input)) input.focus();+ });+ return view;+ }+}++function fmtTime(ts) {+ const d = new Date(ts);+ if (Number.isNaN(d.getTime())) return '';+ return d.toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });+}++function relDay(ts) {+ const d = new Date(ts);+ const today = new Date();+ const yest = new Date();+ yest.setDate(today.getDate() - 1);+ if (d.toDateString() === today.toDateString()) return 'Today';+ if (d.toDateString() === yest.toDateString()) return 'Yesterday';+ return d.toLocaleDateString([], { month: 'short', day: 'numeric' });+}++export { HOTKEY_NOTE };diff --git a/src/game/game-hud.js b/src/game/game-hud.jsindex 425f29201..6f340625b 100644--- a/src/game/game-hud.js+++ b/src/game/game-hud.js@@ -37,6 +37,14 @@ export function itemMeta(id) {return ITEM_META[id] || { icon: '📦', label: id ? id[0].toUpperCase() + id.slice(1) : '' };}+// Emoji shown on a worn-prop cosmetic's shop/wardrobe chip, by cosmetic id. The+// 3D prop itself is the real cosmetic; this is just the catalogue glyph.+const PROP_ICON = {+ 'hat-beanie': '🧢',+ 'hat-baseball': '🧢',+ 'hat-cowboy': '🤠',+};+const SKILL_LABEL = { combat: 'Combat', woodcutting: 'Woodcutting', mining: 'Mining', fishing: 'Fishing', cooking: 'Cooking' };function fmtCountdown(ms) {@@ -69,6 +77,32 @@ export class GameHud {this._bankOpen = false;this._npcOpen = false;this._resetAt = 0;+ // Cosmetics shop (Task 21): the static catalogue (id → entry) + rarity+ // palette, the latest live board (offers/owned/equipped), the current gold,+ // the open flag + active tab, and the rotation deadlines the ticker counts+ // down to (re-fetching the board when one elapses).+ this.cosmetics = new Map();+ this.rarities = {};+ this.shop = null;+ this.gold = 0;+ this._shopOpen = false;+ this._shopTab = 'shop';+ this._dailyResetAt = 0;+ this._weeklyResetAt = 0;+ // Marketplace (Task 20): the latest board (active listings + your own), the+ // token-payment capability flags, the open flag + active tab, per-listing+ // "busy" labels driven by the controller during an on-chain buy, an error+ // banner, and the Sell-form draft state (mode + selected item + inputs).+ this.market = { listings: [], mine: [], token: { enabled: false, symbol: '$THREE', decimals: 6, treasuryBps: 500 }, canToken: false };+ this._marketOpen = false;+ this._marketTab = 'buy';+ this._marketBusy = new Map(); // listingId -> status label shown on its card+ this._marketError = '';+ this._marketLoading = false;+ this._buyFilter = '';+ this._buySort = 'recent';+ this._sellMode = 'gold'; // 'gold' (item→gold) | 'token' (gold→$THREE)+ this._sellItem = ''; // selected backpack item id for a gold listingthis._build();// One shared 1Hz ticker drives the live reset countdown wherever it shows.this._tick = this._tick.bind(this);@@ -87,10 +121,31 @@ export class GameHud {<button id="kq-bank-btn" class="kq-tool-btn" type="button" aria-label="Open bank" title="Open bank" hidden><span class="kq-tool-ic">🏦</span><span class="kq-tool-lbl">Bank</span></button>+ <button id="kq-build-btn" class="kq-tool-btn" type="button" aria-label="Build (B)" title="Build (B)" hidden aria-expanded="false">+ <span class="kq-tool-ic">🔨</span><span class="kq-tool-lbl">Build</span>+ </button>+ <button id="kq-shop-btn" class="kq-tool-btn" type="button" aria-label="Cosmetics shop" title="Cosmetics shop" aria-expanded="false">+ <span class="kq-tool-ic">✨</span><span class="kq-tool-lbl">Shop</span>+ </button>+ <button id="kq-market-btn" class="kq-tool-btn" type="button" aria-label="Marketplace (M)" title="Marketplace (M)" aria-expanded="false">+ <span class="kq-tool-ic">🛒</span><span class="kq-tool-lbl">Market</span>+ </button>+ <span id="kq-gold" class="kq-gold" title="Gold"><span class="kq-gold-ic">🪙</span><b id="kq-gold-n">0</b></span></div><div id="kq-hotbar" class="kq-hotbar" hidden role="toolbar" aria-label="Hotbar"></div>+ <div id="kq-build-menu" class="kq-build-menu" hidden role="dialog" aria-label="Build menu">+ <header class="kq-build-head"><span class="kq-tool-ic">🔨</span><h2>Build</h2><button class="kq-x" id="kq-build-x" type="button" aria-label="Close">✕</button></header>+ <div class="kq-build-list" id="kq-build-list"></div>+ </div>++ <div id="kq-build-banner" class="kq-build-banner" hidden role="status">+ <span class="kq-build-banner-ic" id="kq-build-banner-ic">🔥</span>+ <span class="kq-build-banner-txt">Placing <b id="kq-build-banner-name">structure</b> · tap a tile to place</span>+ <button class="kq-btn kq-btn-ghost" id="kq-build-cancel" type="button">Cancel</button>+ </div>+<aside id="kq-quests" class="kq-panel" hidden aria-label="Quests"><header class="kq-panel-head"><h2>Quests</h2>@@ -119,6 +174,40 @@ export class GameHud {</div></div></div>++ <div id="kq-shop" class="kq-modal" hidden>+ <div class="kq-modal-card kq-shop-card" role="dialog" aria-modal="true" aria-label="Cosmetics shop">+ <button class="kq-x" id="kq-shop-x" type="button" aria-label="Close">✕</button>+ <header class="kq-shop-head">+ <span class="kq-tool-ic">✨</span>+ <h2>Cosmetics</h2>+ <span class="kq-shop-purse" title="Your gold">🪙 <b id="kq-shop-gold">0</b></span>+ </header>+ <div class="kq-shop-tabs" role="tablist">+ <button class="kq-shop-tab kq-shop-tab--on" id="kq-shop-tab-shop" type="button" role="tab" aria-selected="true">Shop</button>+ <button class="kq-shop-tab" id="kq-shop-tab-wardrobe" type="button" role="tab" aria-selected="false">Wardrobe</button>+ </div>+ <p class="kq-shop-note">Cosmetics are purely cosmetic — they change how you look, never how you play.</p>+ <div class="kq-shop-body" id="kq-shop-body"></div>+ </div>+ </div>++ <div id="kq-market" class="kq-modal" hidden>+ <div class="kq-modal-card kq-market-card" role="dialog" aria-modal="true" aria-label="Marketplace">+ <button class="kq-x" id="kq-market-x" type="button" aria-label="Close">✕</button>+ <header class="kq-market-head">+ <span class="kq-tool-ic">🛒</span>+ <h2>Marketplace</h2>+ <span class="kq-shop-purse" title="Your gold">🪙 <b id="kq-market-gold">0</b></span>+ </header>+ <div class="kq-market-tabs" role="tablist">+ <button class="kq-market-tab kq-market-tab--on" id="kq-market-tab-buy" type="button" role="tab" aria-selected="true">Buy</button>+ <button class="kq-market-tab" id="kq-market-tab-sell" type="button" role="tab" aria-selected="false">Sell</button>+ <button class="kq-market-tab" id="kq-market-tab-mine" type="button" role="tab" aria-selected="false">My Listings</button>+ </div>+ <div class="kq-market-body" id="kq-market-body"></div>+ </div>+ </div>`;document.body.appendChild(root);this.root = root;@@ -136,6 +225,19 @@ export class GameHud {this.elBank = root.querySelector('#kq-bank');this.elBankInv = root.querySelector('#kq-bank-inv');this.elBankStore = root.querySelector('#kq-bank-store');+ this.elBuildBtn = root.querySelector('#kq-build-btn');+ this.elBuildMenu = root.querySelector('#kq-build-menu');+ this.elBuildList = root.querySelector('#kq-build-list');+ this.elBuildBanner = root.querySelector('#kq-build-banner');+ this.elBuildBannerIc = root.querySelector('#kq-build-banner-ic');+ this.elBuildBannerName = root.querySelector('#kq-build-banner-name');+ this.elShopBtn = root.querySelector('#kq-shop-btn');+ this.elGoldN = root.querySelector('#kq-gold-n');+ this.elShop = root.querySelector('#kq-shop');+ this.elShopBody = root.querySelector('#kq-shop-body');+ this.elShopGold = root.querySelector('#kq-shop-gold');+ this.elShopTabShop = root.querySelector('#kq-shop-tab-shop');+ this.elShopTabWardrobe = root.querySelector('#kq-shop-tab-wardrobe');this.elQuestBtn.addEventListener('click', () => this.toggleQuests());root.querySelector('#kq-quests-x').addEventListener('click', () => this.closeQuests());@@ -146,6 +248,29 @@ export class GameHud {// Click the backdrop (outside the card) to dismiss modals.this.elNpc.addEventListener('click', (e) => { if (e.target === this.elNpc) this.closeNpc(); });this.elBank.addEventListener('click', (e) => { if (e.target === this.elBank) this.closeBank(); });+ this.elBuildBtn.addEventListener('click', () => this.toggleBuild());+ root.querySelector('#kq-build-x').addEventListener('click', () => this.closeBuild());+ root.querySelector('#kq-build-cancel').addEventListener('click', () => this.opts.onBuildCancel?.());+ this.elShopBtn.addEventListener('click', () => this.toggleShop());+ root.querySelector('#kq-shop-x').addEventListener('click', () => this.closeShop());+ this.elShop.addEventListener('click', (e) => { if (e.target === this.elShop) this.closeShop(); });+ this.elShopTabShop.addEventListener('click', () => this._setShopTab('shop'));+ this.elShopTabWardrobe.addEventListener('click', () => this._setShopTab('wardrobe'));++ // Marketplace (Task 20).+ this.elMarketBtn = root.querySelector('#kq-market-btn');+ this.elMarket = root.querySelector('#kq-market');+ this.elMarketBody = root.querySelector('#kq-market-body');+ this.elMarketGold = root.querySelector('#kq-market-gold');+ this.elMarketTabBuy = root.querySelector('#kq-market-tab-buy');+ this.elMarketTabSell = root.querySelector('#kq-market-tab-sell');+ this.elMarketTabMine = root.querySelector('#kq-market-tab-mine');+ this.elMarketBtn.addEventListener('click', () => this.toggleMarket());+ root.querySelector('#kq-market-x').addEventListener('click', () => this.closeMarket());+ this.elMarket.addEventListener('click', (e) => { if (e.target === this.elMarket) this.closeMarket(); });+ this.elMarketTabBuy.addEventListener('click', () => this._setMarketTab('buy'));+ this.elMarketTabSell.addEventListener('click', () => this._setMarketTab('sell'));+ this.elMarketTabMine.addEventListener('click', () => this._setMarketTab('mine'));}// Reveal the toolbar + hotbar once the player is in the world.@@ -370,7 +495,16 @@ export class GameHud {this.elBankBtn.hidden = !available;if (!available && this._bankOpen) this.closeBank();}- setInventory(inv) { this.inv = inv || []; if (this._bankOpen) this._renderBank(); }+ setInventory(inv) {+ this.inv = inv || [];+ if (this._bankOpen) this._renderBank();+ // The Sell tab picks from the backpack, so a pickup/drop while it's open keeps+ // the item picker honest. Drop a stale selection that no longer exists.+ if (this._marketOpen && this._marketTab === 'sell') {+ if (this._sellItem && !this.inv.some((s) => s && s.item === this._sellItem)) this._sellItem = '';+ this._renderMarket();+ }+ }setBank(slots) { this.bank = slots || []; if (this._bankOpen) this._renderBank(); }openBank() { this._bankOpen = true; this.elBank.hidden = false; this._renderBank(); }@@ -411,16 +545,699 @@ export class GameHud {return cell;}+ // ---------------------------------------------------------------- cosmetics shop+ // The persistent gold readout (toolbar + shop header). Drives buy affordability,+ // so an open shop re-renders when the purse changes.+ setGold(gold) {+ const g = Math.max(0, gold | 0);+ if (g === this.gold) return;+ this.gold = g;+ if (this.elGoldN) this.elGoldN.textContent = g.toLocaleString('en-US');+ if (this.elShopGold) this.elShopGold.textContent = g.toLocaleString('en-US');+ if (this.elMarketGold) this.elMarketGold.textContent = g.toLocaleString('en-US');+ if (this._shopOpen) this._renderShop();+ // The Sell tab's affordability + max-amount caps read off live gold.+ if (this._marketOpen && (this._marketTab === 'sell' || this._marketTab === 'buy')) this._renderMarket();+ }++ // The static catalogue (sent once on join): every cosmetic's id, name, rarity,+ // price, rotation, and visual, plus the rarity palette. Everything the shop ++ // wardrobe render from — no prices or rarities are hard-coded in the HUD.+ setCosmeticCatalog(list, rarities) {+ this.cosmetics = new Map((list || []).map((c) => [c.id, c]));+ this.rarities = rarities || {};+ if (this._shopOpen) this._renderShop();+ }++ // The live shop board (offers + rotation deadlines + owned ids + equipped + gold).+ setShop(snapshot) {+ this.shop = snapshot || null;+ if (snapshot) {+ this._dailyResetAt = snapshot.offers?.dailyResetAt || 0;+ this._weeklyResetAt = snapshot.offers?.weeklyResetAt || 0;+ if (Number.isFinite(snapshot.gold)) this.setGold(snapshot.gold);+ }+ if (this._shopOpen) this._renderShop();+ }++ toggleShop() { this._shopOpen ? this.closeShop() : this.openShop(); }+ openShop() {+ this._shopOpen = true;+ this.elShop.hidden = false;+ this.elShopBtn.setAttribute('aria-expanded', 'true');+ // Always pull a fresh board on open so offers + the countdown are current.+ this.opts.onShopOpen?.();+ this._renderShop();+ }+ closeShop() {+ this._shopOpen = false;+ this.elShop.hidden = true;+ this.elShopBtn.setAttribute('aria-expanded', 'false');+ }++ _setShopTab(tab) {+ this._shopTab = tab === 'wardrobe' ? 'wardrobe' : 'shop';+ const onShop = this._shopTab === 'shop';+ this.elShopTabShop.classList.toggle('kq-shop-tab--on', onShop);+ this.elShopTabWardrobe.classList.toggle('kq-shop-tab--on', !onShop);+ this.elShopTabShop.setAttribute('aria-selected', String(onShop));+ this.elShopTabWardrobe.setAttribute('aria-selected', String(!onShop));+ this._renderShop();+ }++ _renderShop() {+ if (!this._shopOpen) return;+ const body = this.elShopBody;+ if (!this.cosmetics.size) { body.replaceChildren(el('p', 'kq-empty', 'Loading the shop…')); return; }+ body.replaceChildren(this._shopTab === 'wardrobe' ? this._renderWardrobe() : this._renderShopCatalog());+ }++ // Buy tab: the rotating board grouped by bucket, each rotating group headed by a+ // live countdown to its next rotation. Cosmetics already owned read "Owned";+ // affordable ones get a Buy button; short ones show how much more gold is needed.+ _renderShopCatalog() {+ const frag = document.createDocumentFragment();+ if (!this.shop) { frag.appendChild(el('p', 'kq-empty', 'Loading the shop…')); return frag; }+ const owned = new Set(this.shop.owned || []);+ const offers = this.shop.offers || {};+ const section = (title, ids, resetId, resetAt) => {+ if (!ids || !ids.length) return;+ const sec = el('section', 'kq-shop-section');+ const head = el('div', 'kq-shop-section-head');+ head.appendChild(el('h3', 'kq-h3', title));+ if (resetId) {+ const r = el('span', 'kq-shop-reset', this._rotateText(resetAt));+ r.id = resetId;+ head.appendChild(r);+ }+ sec.appendChild(head);+ const grid = el('div', 'kq-cos-grid');+ for (const id of ids) {+ const c = this.cosmetics.get(id);+ if (c) grid.appendChild(this._shopCard(c, owned.has(id)));+ }+ sec.appendChild(grid);+ frag.appendChild(sec);+ };+ section('Daily rotation', offers.daily, 'kq-shop-daily-reset', this._dailyResetAt);+ section('Weekly rotation', offers.weekly, 'kq-shop-weekly-reset', this._weeklyResetAt);+ section('Always available', offers.always, null, 0);+ return frag;+ }++ _shopCard(c, owned) {+ const affordable = this.gold >= c.price;+ const card = el('div', `kq-cos-card kq-cos--${c.rarity}${owned ? ' kq-cos--owned' : affordable ? '' : ' kq-cos--short'}`);+ card.style.setProperty('--cos-accent', this._rarityColor(c.rarity));+ card.appendChild(this._cosSwatch(c));+ const meta = el('div', 'kq-cos-meta');+ meta.appendChild(el('div', 'kq-cos-name', c.name));+ meta.appendChild(el('div', 'kq-cos-rarity', this._rarityLabel(c.rarity)));+ card.appendChild(meta);+ const foot = el('div', 'kq-cos-foot');+ if (owned) {+ foot.appendChild(el('span', 'kq-cos-owned', '✓ Owned'));+ } else {+ foot.appendChild(el('span', 'kq-cos-price' + (affordable ? '' : ' kq-cos-price--short'), `🪙 ${c.price.toLocaleString('en-US')}`));+ const btn = el('button', 'kq-btn kq-cos-buy' + (affordable ? '' : ' kq-btn-disabled'), affordable ? 'Buy' : `Need ${(c.price - this.gold).toLocaleString('en-US')}`);+ btn.type = 'button';+ btn.disabled = !affordable;+ if (affordable) btn.addEventListener('click', () => this.opts.onBuyCosmetic?.(c.id));+ foot.appendChild(btn);+ }+ card.appendChild(foot);+ return card;+ }++ // Wardrobe tab: a "Default look" tile (unequip) plus every owned cosmetic, with+ // the equipped one highlighted. Equipping previews live on the avatar in-world.+ _renderWardrobe() {+ const frag = document.createDocumentFragment();+ const ownedIds = (this.shop?.owned || []).filter((id) => this.cosmetics.has(id));+ const equipped = this.shop?.equipped || '';+ frag.appendChild(el('p', 'kq-shop-sub', 'Equip an owned look — it shows on your avatar instantly, for you and everyone around you.'));+ const grid = el('div', 'kq-cos-grid');++ // Default (no cosmetic) tile.+ const def = el('div', 'kq-cos-card kq-cos--default' + (equipped ? '' : ' kq-cos--equipped'));+ def.appendChild(el('span', 'kq-cos-swatch kq-cos-swatch--default', '🙂'));+ const dmeta = el('div', 'kq-cos-meta');+ dmeta.appendChild(el('div', 'kq-cos-name', 'Default look'));+ dmeta.appendChild(el('div', 'kq-cos-rarity', 'No cosmetic'));+ def.appendChild(dmeta);+ const dfoot = el('div', 'kq-cos-foot');+ if (equipped) {+ const b = el('button', 'kq-btn kq-cos-equip', 'Equip');+ b.type = 'button';+ b.addEventListener('click', () => this.opts.onUnequipCosmetic?.());+ dfoot.appendChild(b);+ } else {+ dfoot.appendChild(el('span', 'kq-cos-equipped', '✓ Equipped'));+ }+ def.appendChild(dfoot);+ grid.appendChild(def);++ for (const id of ownedIds) {+ const c = this.cosmetics.get(id);+ const isEq = id === equipped;+ const card = el('div', `kq-cos-card kq-cos--${c.rarity}${isEq ? ' kq-cos--equipped' : ''}`);+ card.style.setProperty('--cos-accent', this._rarityColor(c.rarity));+ card.appendChild(this._cosSwatch(c));+ const meta = el('div', 'kq-cos-meta');+ meta.appendChild(el('div', 'kq-cos-name', c.name));+ meta.appendChild(el('div', 'kq-cos-rarity', this._rarityLabel(c.rarity)));+ card.appendChild(meta);+ const foot = el('div', 'kq-cos-foot');+ if (isEq) {+ foot.appendChild(el('span', 'kq-cos-equipped', '✓ Equipped'));+ } else {+ const b = el('button', 'kq-btn kq-cos-equip', 'Equip');+ b.type = 'button';+ b.addEventListener('click', () => this.opts.onEquipCosmetic?.(id));+ foot.appendChild(b);+ }+ card.appendChild(foot);+ grid.appendChild(card);+ }+ frag.appendChild(grid);++ if (!ownedIds.length) {+ const empty = el('div', 'kq-empty kq-shop-empty');+ empty.innerHTML = 'You don’t own any cosmetics yet.';+ const go = el('button', 'kq-btn kq-btn-ghost', 'Browse the shop →');+ go.type = 'button';+ go.addEventListener('click', () => this._setShopTab('shop'));+ empty.appendChild(go);+ frag.appendChild(empty);+ }+ return frag;+ }++ // A small visual chip for a cosmetic: auras glow, tints fill, props show their+ // emoji over a neutral chip — enough to tell looks apart at a glance.+ _cosSwatch(c) {+ const v = c.visual || {};+ const sw = el('span', 'kq-cos-swatch');+ if (v.aura) {+ sw.style.background = `radial-gradient(circle at 50% 55%, ${v.aura}, rgba(0,0,0,0.25) 72%)`;+ sw.style.boxShadow = `0 0 12px ${v.aura}`;+ } else if (v.tint) {+ sw.style.background = `linear-gradient(150deg, ${v.tint}, rgba(255,255,255,0.18))`;+ }+ if (v.prop) sw.textContent = PROP_ICON[c.id] || '🎩';+ return sw;+ }++ _rarityColor(rarity) { return this.rarities[rarity]?.color || '#9aa7b4'; }+ _rarityLabel(rarity) { return this.rarities[rarity]?.label || (rarity ? rarity[0].toUpperCase() + rarity.slice(1) : ''); }+ _rotateText(at) { return at ? `resets in ${fmtCountdown(at - Date.now())}` : ''; }++ // ---------------------------------------------------------------- build+ // The Build button shows only in realms that permit player building (the scene+ // derives this from the realm's structure list). Hidden elsewhere so a mine or+ // the wilderness town never offers a no-op button.+ setBuildAvailable(available) {+ if (!this.elBuildBtn) return;+ this.elBuildBtn.hidden = !available;+ if (!available) this.closeBuild();+ }++ // Render the buildable list. `items` is the scene's affordability-resolved view:+ // [{ kind, icon, label, desc, capNote, affordable, costs:[{item,icon,need,have,ok}] }]+ // Each row shows the live cost (red where short) and a Build button gated on+ // affordability — the authoritative server re-checks everything on placement.+ setBuildables(items) {+ this._buildables = items || [];+ if (this._buildOpen) this._renderBuild();+ }++ toggleBuild() { this._buildOpen ? this.closeBuild() : this.openBuild(); }+ openBuild() {+ if (this.elBuildBtn?.hidden) return;+ this._buildOpen = true;+ this.elBuildMenu.hidden = false;+ this.elBuildMenu.classList.add('kq-in');+ this.elBuildBtn?.setAttribute('aria-expanded', 'true');+ this._renderBuild();+ }+ closeBuild() {+ this._buildOpen = false;+ if (this.elBuildMenu) { this.elBuildMenu.classList.remove('kq-in'); this.elBuildMenu.hidden = true; }+ this.elBuildBtn?.setAttribute('aria-expanded', 'false');+ }++ _renderBuild() {+ const list = this.elBuildList;+ if (!list) return;+ const items = this._buildables || [];+ if (!items.length) { list.replaceChildren(el('p', 'kq-empty', 'Nothing to build here.')); return; }+ const frag = document.createDocumentFragment();+ for (const b of items) {+ const card = el('div', 'kq-build-card' + (b.affordable ? '' : ' kq-build-card--short'));+ const head = el('div', 'kq-build-card-head');+ head.appendChild(el('span', 'kq-build-ic', b.icon));+ const title = el('div', 'kq-build-titles');+ title.appendChild(el('div', 'kq-build-name', b.label + (b.capNote ? ` <span class="kq-build-cap">${b.capNote}</span>` : '')));+ title.appendChild(el('div', 'kq-build-desc', b.desc || ''));+ head.appendChild(title);+ card.appendChild(head);++ const costs = el('div', 'kq-build-costs');+ for (const c of b.costs || []) {+ const chip = el('span', 'kq-build-cost' + (c.ok ? '' : ' kq-build-cost--short'));+ chip.innerHTML = `<span class="kq-build-cost-ic">${c.icon}</span>${c.have}/${c.need}`;+ chip.title = `${c.have} of ${c.need} ${itemMeta(c.item).label}`;+ costs.appendChild(chip);+ }+ card.appendChild(costs);++ const btn = el('button', 'kq-btn kq-build-go' + (b.affordable ? '' : ' kq-btn-disabled'), b.affordable ? 'Build' : 'Need more');+ btn.type = 'button';+ btn.disabled = !b.affordable;+ btn.addEventListener('click', () => { this.opts.onBuildSelect?.(b.kind); this.closeBuild(); });+ card.appendChild(btn);+ frag.appendChild(card);+ }+ list.replaceChildren(frag);+ }++ // Build-mode banner: shown while a ghost is being placed, with a Cancel control+ // (the only cancel affordance on touch, where there's no right-click).+ showBuildBanner(meta) {+ if (!this.elBuildBanner) return;+ this.elBuildBannerIc.textContent = meta?.icon || '🔨';+ this.elBuildBannerName.textContent = meta?.label || 'structure';+ this.elBuildBanner.hidden = false;+ }+ hideBuildBanner() { if (this.elBuildBanner) this.elBuildBanner.hidden = true; }++ // ---------------------------------------------------------------- marketplace (Task 20)+ //+ // A player-to-player market with Buy / Sell / My Listings tabs. The board is the+ // server's authoritative snapshot (setMarket); every action flows back out+ // through opts callbacks so the controller owns the network + the on-chain token+ // flow. Gold buys are one click; token buys go through a controller-driven+ // quote → wallet-sign → settle sequence whose progress shows as a per-listing+ // busy label (setMarketBusy).++ toggleMarket() { this._marketOpen ? this.closeMarket() : this.openMarket(); }++ openMarket() {+ if (this._marketOpen) return;+ this._marketOpen = true;+ this._marketError = '';+ this._marketLoading = !this.market.listings.length && !this.market.mine.length;+ this.elMarket.hidden = false;+ this.elMarketBtn.setAttribute('aria-expanded', 'true');+ this._renderMarket();+ // Always refetch on open so the board is live, not whatever was last cached.+ this.opts.onMarketOpen?.();+ }++ closeMarket() {+ this._marketOpen = false;+ this.elMarket.hidden = true;+ this.elMarketBtn.setAttribute('aria-expanded', 'false');+ }++ _setMarketTab(tab) {+ this._marketTab = tab;+ for (const [name, btn] of [['buy', this.elMarketTabBuy], ['sell', this.elMarketTabSell], ['mine', this.elMarketTabMine]]) {+ const on = name === tab;+ btn.classList.toggle('kq-market-tab--on', on);+ btn.setAttribute('aria-selected', String(on));+ }+ // Re-pull a fresh board when switching to a browse tab so it never shows stale+ // listings after time on the Sell form.+ if (tab === 'buy' || tab === 'mine') this.opts.onMarketOpen?.();+ this._renderMarket();+ }++ // The server's market board: active listings, the player's own, and the token+ // capability flags. Clears the loading/error state and re-renders if open.+ setMarket(data) {+ if (!data) return;+ this.market = {+ listings: Array.isArray(data.listings) ? data.listings : [],+ mine: Array.isArray(data.mine) ? data.mine : [],+ token: data.token || this.market.token,+ canToken: !!data.canToken,+ };+ this._marketLoading = false;+ this._marketError = '';+ if (this._marketOpen) this._renderMarket();+ }++ // A listing changed somewhere — refetch if the market is open on a browse tab.+ marketDirty() {+ if (this._marketOpen && (this._marketTab === 'buy' || this._marketTab === 'mine')) this.opts.onMarketOpen?.();+ }++ setMarketError(msg) {+ this._marketError = msg || '';+ this._marketLoading = false;+ if (this._marketOpen) this._renderMarket();+ }++ // The controller drives these during an on-chain token buy so the listing's card+ // shows "Preparing…", "Confirm in wallet…", "Settling…", etc.+ setMarketBusy(id, label) {+ if (!id) return;+ this._marketBusy.set(id, label || 'Working…');+ if (this._marketOpen) this._renderMarket();+ }+ clearMarketBusy(id) {+ if (id) this._marketBusy.delete(id); else this._marketBusy.clear();+ if (this._marketOpen) this._renderMarket();+ }++ _fmtGold(n) { return Math.max(0, n | 0).toLocaleString('en-US'); }+ _fmtUsd(n) { return '$' + (Math.round(Number(n) * 100) / 100).toFixed(2); }++ _renderMarket() {+ if (!this.elMarketBody) return;+ let node;+ if (this._marketTab === 'sell') node = this._renderSell();+ else if (this._marketTab === 'mine') node = this._renderMine();+ else node = this._renderBuy();+ this.elMarketBody.replaceChildren(node);+ }++ // ---- Buy tab ----------------------------------------------------------+ _renderBuy() {+ const wrap = el('div', 'kq-market-pane');+ if (this._marketError) { wrap.appendChild(this._marketErrorEl()); return wrap; }+ if (this._marketLoading) { wrap.appendChild(this._marketSkeleton()); return wrap; }++ // Filter + sort controls.+ const controls = el('div', 'kq-market-controls');+ const search = el('input', 'kq-market-search');+ search.type = 'search';+ search.placeholder = 'Filter by item or seller…';+ search.value = this._buyFilter;+ search.setAttribute('aria-label', 'Filter listings');+ search.addEventListener('input', () => { this._buyFilter = search.value.toLowerCase(); this._renderBuyList(list); });+ const sort = el('select', 'kq-market-sort');+ sort.setAttribute('aria-label', 'Sort listings');+ for (const [val, label] of [['recent', 'Newest'], ['priceAsc', 'Price ↑'], ['priceDesc', 'Price ↓']]) {+ const o = el('option'); o.value = val; o.textContent = label; if (val === this._buySort) o.selected = true; sort.appendChild(o);+ }+ sort.addEventListener('change', () => { this._buySort = sort.value; this._renderBuyList(list); });+ controls.append(search, sort);+ wrap.appendChild(controls);++ const list = el('div', 'kq-market-list');+ this._renderBuyList(list);+ wrap.appendChild(list);+ return wrap;+ }++ _renderBuyList(list) {+ const q = this._buyFilter;+ let items = this.market.listings.slice();+ if (q) {+ items = items.filter((l) => {+ const label = l.type === 'gold' ? itemMeta(l.item).label : 'gold';+ return label.toLowerCase().includes(q) || (l.seller || '').toLowerCase().includes(q);+ });+ }+ const priceOf = (l) => (l.type === 'gold' ? l.priceGold : l.priceUsd * 1e9); // token prices sort above gold consistently+ if (this._buySort === 'priceAsc') items.sort((a, b) => priceOf(a) - priceOf(b));+ else if (this._buySort === 'priceDesc') items.sort((a, b) => priceOf(b) - priceOf(a));+ else items.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));++ if (!items.length) {+ const empty = el('div', 'kq-market-empty');+ empty.innerHTML = this._buyFilter+ ? '<div class="kq-market-empty-ic">🔍</div><p>No listings match that filter.</p>'+ : '<div class="kq-market-empty-ic">🛒</div><p><b>No listings yet — be the first to sell.</b></p><span>Open the Sell tab to list items for gold, or gold for $THREE.</span>';+ list.replaceChildren(empty);+ return;+ }+ const frag = document.createDocumentFragment();+ for (const l of items) frag.appendChild(this._buyCard(l));+ list.replaceChildren(frag);+ }++ _buyCard(l) {+ const card = el('div', 'kq-market-card-row' + (l.mine ? ' kq-market-mine' : ''));+ const icon = el('span', 'kq-market-ic', l.type === 'gold' ? itemMeta(l.item).icon : '🪙');+ const info = el('div', 'kq-market-info');+ const title = el('div', 'kq-market-title');+ if (l.type === 'gold') title.textContent = `${l.qty}× ${itemMeta(l.item).label}`;+ else title.textContent = `${this._fmtGold(l.goldAmount)} gold`;+ const sub = el('div', 'kq-market-sub');+ const seller = el('span', 'kq-market-seller'); seller.textContent = `by ${l.seller || 'Trader'}`;+ sub.appendChild(seller);+ info.append(title, sub);++ const right = el('div', 'kq-market-right');+ const price = el('div', 'kq-market-price');+ if (l.type === 'gold') price.innerHTML = `<span class="kq-market-coin">🪙</span>${this._fmtGold(l.priceGold)}`;+ else price.innerHTML = `<span class="kq-market-usd">${this._fmtUsd(l.priceUsd)}</span><span class="kq-market-token">in ${this.market.token.symbol}</span>`;+ right.appendChild(price);++ const busy = this._marketBusy.get(l.id);+ if (l.mine) {+ right.appendChild(el('span', 'kq-market-badge', 'Your listing'));+ } else if (busy) {+ const b = el('span', 'kq-market-busy'); b.innerHTML = `<span class="kq-spin"></span>${busy}`;+ right.appendChild(b);+ } else if (l.type === 'gold') {+ const buy = el('button', 'kq-btn kq-btn-primary kq-market-buy', 'Buy');+ buy.type = 'button';+ const afford = this.gold >= l.priceGold;+ if (!afford) { buy.disabled = true; buy.classList.add('kq-btn-disabled'); buy.title = 'Not enough gold'; }+ buy.addEventListener('click', () => this.opts.onMarketBuyGold?.(l.id));+ right.appendChild(buy);+ } else {+ // Token listing.+ if (!this.market.canToken) {+ const note = el('span', 'kq-market-note', 'Connect a wallet to buy');+ right.appendChild(note);+ } else {+ const buy = el('button', 'kq-btn kq-btn-primary kq-market-buy', `Buy with ${this.market.token.symbol}`);+ buy.type = 'button';+ buy.addEventListener('click', () => this.opts.onMarketBuyToken?.(l.id));+ right.appendChild(buy);+ }+ }+ card.append(icon, info, right);+ return card;+ }++ // ---- Sell tab ---------------------------------------------------------+ _renderSell() {+ const wrap = el('div', 'kq-market-pane kq-market-sell');+ // Mode toggle: items-for-gold vs gold-for-token.+ const modes = el('div', 'kq-market-modes');+ for (const [val, label] of [['gold', 'Item → Gold'], ['token', `Gold → ${this.market.token.symbol}`]]) {+ const b = el('button', 'kq-market-mode' + (this._sellMode === val ? ' kq-market-mode--on' : ''), label);+ b.type = 'button';+ b.addEventListener('click', () => { this._sellMode = val; this._renderMarket(); });+ modes.appendChild(b);+ }+ wrap.appendChild(modes);+ wrap.appendChild(this._sellMode === 'token' ? this._renderSellToken() : this._renderSellGold());+ return wrap;+ }++ _renderSellGold() {+ const pane = el('div', 'kq-market-sellform');+ // Aggregate backpack stacks by item so the picker shows one tile per item.+ const totals = new Map();+ for (const s of this.inv) if (s && s.item) totals.set(s.item, (totals.get(s.item) || 0) + s.qty);+ if (!totals.size) {+ pane.appendChild(el('p', 'kq-market-hint', 'Your backpack is empty — gather or loot something to sell.'));+ return pane;+ }+ pane.appendChild(el('label', 'kq-market-label', 'Choose an item to sell'));+ const grid = el('div', 'kq-market-pick');+ for (const [item, qty] of totals) {+ const m = itemMeta(item);+ const cell = el('button', 'kq-cell kq-market-pickcell' + (this._sellItem === item ? ' kq-cell--on' : ''));+ cell.type = 'button';+ cell.title = `${m.label} ×${qty}`;+ cell.setAttribute('aria-label', `${m.label} ×${qty}`);+ cell.setAttribute('aria-pressed', String(this._sellItem === item));+ cell.innerHTML = `<span class="kq-ic">${m.icon}</span><span class="kq-qty">${qty}</span>`;+ cell.addEventListener('click', () => { this._sellItem = item; this._renderMarket(); });+ grid.appendChild(cell);+ }+ pane.appendChild(grid);++ if (!this._sellItem) {+ pane.appendChild(el('p', 'kq-market-hint', 'Pick an item above to set the amount and price.'));+ return pane;+ }+ const held = totals.get(this._sellItem) || 0;+ const m = itemMeta(this._sellItem);++ const row = el('div', 'kq-market-fields');+ const qtyWrap = el('label', 'kq-market-field');+ qtyWrap.appendChild(el('span', 'kq-market-field-lbl', `Quantity (max ${held})`));+ const qtyInput = el('input', 'kq-market-input');+ qtyInput.type = 'number'; qtyInput.min = '1'; qtyInput.max = String(held); qtyInput.value = String(Math.min(1, held) || 1); qtyInput.step = '1';+ qtyWrap.appendChild(qtyInput);++ const priceWrap = el('label', 'kq-market-field');+ priceWrap.appendChild(el('span', 'kq-market-field-lbl', 'Price (gold)'));+ const priceInput = el('input', 'kq-market-input');+ priceInput.type = 'number'; priceInput.min = '1'; priceInput.step = '1'; priceInput.placeholder = 'e.g. 100';+ priceWrap.appendChild(priceInput);+ row.append(qtyWrap, priceWrap);+ pane.appendChild(row);++ const btn = el('button', 'kq-btn kq-btn-primary kq-market-list', `List ${m.label} for gold`);+ btn.type = 'button';+ btn.addEventListener('click', () => {+ const qty = Math.max(1, Math.min(held, qtyInput.value | 0));+ const price = priceInput.value | 0;+ if (!(price >= 1)) { priceInput.focus(); priceInput.classList.add('kq-input-bad'); return; }+ this.opts.onMarketListGold?.(this._sellItem, qty, price);+ this._sellItem = '';+ });+ pane.appendChild(btn);+ pane.appendChild(el('p', 'kq-market-fineprint', 'Gold sales have no fee — you receive the full price.'));+ return pane;+ }++ _renderSellToken() {+ const pane = el('div', 'kq-market-sellform');+ if (!this.market.token.enabled) {+ pane.appendChild(el('p', 'kq-market-hint', `${this.market.token.symbol} sales are unavailable right now.`));+ return pane;+ }+ if (!this.market.canToken) {+ pane.appendChild(el('p', 'kq-market-hint', 'Connect a Solana wallet to sell gold for tokens — your proceeds are paid on-chain to your wallet.'));+ return pane;+ }+ if (this.gold <= 0) {+ pane.appendChild(el('p', 'kq-market-hint', 'You have no gold to sell yet.'));+ return pane;+ }+ const feePct = (this.market.token.treasuryBps / 100).toFixed(0);+ const row = el('div', 'kq-market-fields');+ const goldWrap = el('label', 'kq-market-field');+ goldWrap.appendChild(el('span', 'kq-market-field-lbl', `Gold to sell (max ${this._fmtGold(this.gold)})`));+ const goldInput = el('input', 'kq-market-input');+ goldInput.type = 'number'; goldInput.min = '1'; goldInput.max = String(this.gold); goldInput.step = '1'; goldInput.placeholder = 'e.g. 1000';+ goldWrap.appendChild(goldInput);++ const usdWrap = el('label', 'kq-market-field');+ usdWrap.appendChild(el('span', 'kq-market-field-lbl', 'Price (USD)'));+ const usdInput = el('input', 'kq-market-input');+ usdInput.type = 'number'; usdInput.min = '0.01'; usdInput.step = '0.01'; usdInput.placeholder = 'e.g. 1.50';+ usdWrap.appendChild(usdInput);+ row.append(goldWrap, usdWrap);+ pane.appendChild(row);++ const btn = el('button', 'kq-btn kq-btn-primary kq-market-list', `List gold for ${this.market.token.symbol}`);+ btn.type = 'button';+ btn.addEventListener('click', () => {+ const goldAmount = Math.max(1, Math.min(this.gold, goldInput.value | 0));+ const usd = Math.round(Number(usdInput.value) * 100) / 100;+ if (!(goldAmount >= 1)) { goldInput.focus(); goldInput.classList.add('kq-input-bad'); return; }+ if (!(usd >= 0.01)) { usdInput.focus(); usdInput.classList.add('kq-input-bad'); return; }+ this.opts.onMarketListToken?.(goldAmount, usd);+ });+ pane.appendChild(btn);+ pane.appendChild(el('p', 'kq-market-fineprint', `Buyers pay in ${this.market.token.symbol}. You receive ${100 - Number(feePct)}% to your wallet; ${feePct}% goes to the treasury.`));+ return pane;+ }++ // ---- My Listings tab --------------------------------------------------+ _renderMine() {+ const wrap = el('div', 'kq-market-pane');+ if (this._marketError) { wrap.appendChild(this._marketErrorEl()); return wrap; }+ const mine = (this.market.mine || []).slice().sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));+ if (!mine.length) {+ const empty = el('div', 'kq-market-empty');+ empty.innerHTML = '<div class="kq-market-empty-ic">📦</div><p><b>You have no listings.</b></p><span>List items for gold or gold for $THREE from the Sell tab.</span>';+ wrap.appendChild(empty);+ return wrap;+ }+ const list = el('div', 'kq-market-list');+ for (const l of mine) list.appendChild(this._mineCard(l));+ wrap.appendChild(list);+ return wrap;+ }++ _mineCard(l) {+ const card = el('div', 'kq-market-card-row kq-market-status-' + l.status);+ const icon = el('span', 'kq-market-ic', l.type === 'gold' ? itemMeta(l.item).icon : '🪙');+ const info = el('div', 'kq-market-info');+ const title = el('div', 'kq-market-title');+ title.textContent = l.type === 'gold' ? `${l.qty}× ${itemMeta(l.item).label}` : `${this._fmtGold(l.goldAmount)} gold`;+ const sub = el('div', 'kq-market-sub');+ const price = l.type === 'gold' ? `🪙 ${this._fmtGold(l.priceGold)}` : `${this._fmtUsd(l.priceUsd)} in ${this.market.token.symbol}`;+ sub.textContent = price;+ info.append(title, sub);++ const right = el('div', 'kq-market-right');+ if (l.status === 'active') {+ right.appendChild(el('span', 'kq-market-statlbl kq-market-statlbl--active', 'Active'));+ const cancel = el('button', 'kq-btn kq-btn-ghost kq-market-cancel', 'Cancel');+ cancel.type = 'button';+ cancel.addEventListener('click', () => this.opts.onMarketCancel?.(l.id));+ right.appendChild(cancel);+ } else if (l.status === 'sold') {+ right.appendChild(el('span', 'kq-market-statlbl kq-market-statlbl--sold', l.buyer ? `Sold to ${l.buyer}` : 'Sold'));+ } else if (l.status === 'settling') {+ right.appendChild(el('span', 'kq-market-statlbl', 'Payment pending…'));+ } else {+ right.appendChild(el('span', 'kq-market-statlbl kq-market-statlbl--cancelled', 'Cancelled'));+ }+ card.append(icon, info, right);+ return card;+ }++ _marketErrorEl() {+ const e = el('div', 'kq-market-empty kq-market-err');+ e.innerHTML = `<div class="kq-market-empty-ic">⚠️</div><p>${this._marketError}</p>`;+ const retry = el('button', 'kq-btn kq-btn-ghost', 'Retry');+ retry.type = 'button';+ retry.addEventListener('click', () => { this._marketError = ''; this._marketLoading = true; this._renderMarket(); this.opts.onMarketOpen?.(); });+ e.appendChild(retry);+ return e;+ }++ _marketSkeleton() {+ const sk = el('div', 'kq-market-list');+ for (let i = 0; i < 4; i++) sk.appendChild(el('div', 'kq-market-card-row kq-market-skel'));+ return sk;+ }+// ---------------------------------------------------------------- ticker_tick() {- if (!this._resetAt) return;- const remaining = this._resetAt - Date.now();- if (remaining <= 0) { this.opts.onReset?.(); return; }- if (this._questOpen) {- const q = this.elQuestsBody.querySelector('#kq-reset-q');- if (q) q.textContent = this._resetText();- const inline = this.elQuestsBody.querySelector('.kq-reset-inline');- if (inline) inline.textContent = this._resetText();+ // Daily-quest reset countdown + auto re-fetch when the day turns over.+ if (this._resetAt) {+ if (this._resetAt - Date.now() <= 0) { this.opts.onReset?.(); }+ else if (this._questOpen) {+ const q = this.elQuestsBody.querySelector('#kq-reset-q');+ if (q) q.textContent = this._resetText();+ const inline = this.elQuestsBody.querySelector('.kq-reset-inline');+ if (inline) inline.textContent = this._resetText();+ }+ }+ // Cosmetics shop rotation countdowns. When a rotation elapses, re-fetch the+ // board so the new offers + a fresh countdown appear without a reconnect.+ if (this._shopOpen && this._shopTab === 'shop') {+ const now = Date.now();+ let rotated = false;+ if (this._dailyResetAt && now >= this._dailyResetAt) { this._dailyResetAt = 0; rotated = true; }+ if (this._weeklyResetAt && now >= this._weeklyResetAt) { this._weeklyResetAt = 0; rotated = true; }+ if (rotated) { this.opts.onShopOpen?.(); return; }+ const d = this.elShopBody.querySelector('#kq-shop-daily-reset');+ if (d) d.textContent = this._rotateText(this._dailyResetAt);+ const w = this.elShopBody.querySelector('#kq-shop-weekly-reset');+ if (w) w.textContent = this._rotateText(this._weeklyResetAt);+ }+ // Keep an open Buy/My-Listings board live as others list and sell — a light+ // refetch every few seconds (the Sell form is left alone so typing isn't lost).+ if (this._marketOpen && (this._marketTab === 'buy' || this._marketTab === 'mine')) {+ this._marketPoll = (this._marketPoll || 0) + 1;+ if (this._marketPoll >= 5) { this._marketPoll = 0; this.opts.onMarketOpen?.(); }}}diff --git a/src/game/game-net.js b/src/game/game-net.jsindex 5f75a05a0..1444f66ab 100644--- a/src/game/game-net.js+++ b/src/game/game-net.js@@ -10,7 +10,7 @@import { Client, getStateCallbacks } from 'colyseus.js';-const REALMS = ['mainland', 'wilderness', 'whisperwood', 'pond'];+const REALMS = ['mainland', 'wilderness', 'whisperwood', 'pond', 'mine', 'wilderness_north', 'wilderness_cave', 'wilderness_east', 'arena'];const DEFAULT_REALM = 'mainland';const RECONNECT_BASE_MS = 3000;const RECONNECT_MAX_MS = 60_000;@@ -41,6 +41,28 @@ function defaultServerUrl() {return 'ws://localhost:2567';}+// Derive the HTTP(S) origin of the multiplayer host from its ws(s):// URL, so the+// login picker can hit the server's plain-HTTP discovery endpoints (/servers,+// /presence) on the same host without a second config value.+export function gameHttpBase(url) {+ const u = (url || defaultServerUrl()).replace(/^ws(s?):\/\//i, 'http$1://');+ return u.replace(/\/+$/, '');+}++// Fetch the live world-instance roster + real population counts (Task 23) for the+// login picker. Returns the array of { id, name, blurb, players, recommended }.+// Throws on a network/HTTP error so the caller can fall back to a no-counts list+// rather than render stale or faked numbers.+export async function fetchServers(url) {+ const res = await fetch(`${gameHttpBase(url)}/servers`, {+ headers: { accept: 'application/json' },+ cache: 'no-store',+ });+ if (!res.ok) throw new Error(`/servers ${res.status}`);+ const data = await res.json();+ return Array.isArray(data?.servers) ? data.servers : [];+}+export class GameNet {constructor(opts = {}) {this.name = opts.name || 'guest';@@ -51,6 +73,15 @@ export class GameNet {// see or affect one another. Defaults to Mainland.this.realm = REALMS.includes(opts.realm) ? opts.realm : DEFAULT_REALM;this.roomName = `game_${this.realm}`;+ // Chosen world instance (Task 23). filterBy(['server']) on the server pins+ // every realm room of this session to the same instance, so the player only+ // ever matches others who picked the same server. '' lets the server resolve+ // its default; the server validates it regardless.+ this.server = typeof opts.server === 'string' ? opts.server : '';+ // Set true when the server disconnects us because the same account signed in+ // elsewhere — suppresses the auto-reconnect that would otherwise fight the+ // new session for the single allowed seat.+ this._takenOver = false;this.url = opts.url || defaultServerUrl();this.client = null;this.room = null;@@ -61,6 +92,7 @@ export class GameNet {status: new Set(),realm: new Set(), // (layout)items: new Set(), // (registry) — server item catalogue: icons, labels, mount tuning+ commands: new Set(), // ([{name, args, aliases, desc}]) — slash-command manifest for chat autocompletenotice: new Set(), // ({kind, text})chat: new Set(), // ({id, name, text, ts}) player msg | ({system, kind, text, ts}) system/command replybank: new Set(), // ({slots})@@ -80,11 +112,38 @@ export class GameNet {tombAdd: new Set(), // (tombstone, id)tombChange: new Set(), // (tombstone, id)tombRemove: new Set(), // (id)+ structAdd: new Set(), // (structure, id) — player-built firepit/shack (Task 07)+ structChange: new Set(), // (structure, id)+ structRemove: new Set(), // (id)quests: new Set(), // ({tutorial, daily, badges, guide, npc}) — requester's own quest snapshot+ takeover: new Set(), // ({reason}) — this account signed in elsewhere; this session is being closed+ cosmetics: new Set(), // ({rarities, cosmetics}) — static cosmetics catalogue (Task 21)+ shop: new Set(), // ({offers, owned, equipped, gold}) — live cosmetics shop board+ market: new Set(), // ({listings, mine, token, canToken}) — marketplace board (Task 20)+ marketDirty: new Set(), // () — a listing changed; open panels should refetch+ marketQuote: new Set(), // ({id, tx, quote, ...}) — unsigned split tx + signed quote for a token buy+ marketSettled: new Set(), // ({id, goldAmount, txSig}) — token purchase verified + gold delivered+ marketBuyFail: new Set(), // ({id}) — a token quote/settle was rejected; release the spinner+ marketPayout: new Set(), // ({gold, items}) — proceeds delivered for a sale completed while away+ // Wheel of Fortune (Task 19): board/eligibility, a paid-spin tx + quote to+ // sign, the server-rolled outcome to animate toward, and refusals with the+ // fields each designed state needs (level gate, free-spin countdown).+ spinInfo: new Set(), // ({segments, avgLevel, minLevel, eligible, atWheel, nextFreeSpinAt, now, costUsd, symbol, paidAvailable})+ spinPrep: new Set(), // ({tx, quote, tokenAmount, burnAmount, treasuryAmount, priceUsd, ttlMs, ...})+ spinResult: new Set(), // ({mode, index, kind, item, qty, gold, label, awardedGold, awardedQty, overflow, nextFreeSpinAt, txSig?})+ spinDenied: new Set(), // ({mode, reason, avgLevel, minLevel, nextFreeSpinAt, now})+ handoff: new Set(), // ({realm, sessionId}) — switched rooms via a portal; scene resets dynamic views+ social: new Set(), // ({type, ...}) — friends events: live DM, friend request/accept (Task 15)};+ // Optional async supplier of a presence ticket (Task 15). When provided,+ // its resolved token is sent on join so the realm room can publish this+ // account's presence to friends. Resolved fresh on every (re)connect so an+ // expired ticket self-heals.+ this.getPresence = typeof opts.getPresence === 'function' ? opts.getPresence : null;this._reconnectTimer = null;this._reconnectAttempts = 0;this._destroyed = false;+ this._transferring = false; // a portal room-handoff is in flight}on(event, fn) {@@ -106,44 +165,29 @@ export class GameNet {this._emit('status', { status, error });}+ // (Re)assert this account's presence ticket to the live room. Sent after every+ // bind so a portal handoff — whose seat reservation carries no join options —+ // still publishes presence + keeps live DM delivery flowing in the new realm.+ async _announcePresence() {+ if (!this.getPresence || !this.room) return;+ try {+ const token = await this.getPresence();+ if (token && this.room) this.room.send('presence', token);+ } catch {+ /* presence is best-effort; the friends list falls back to polling */+ }+ }+async connect() {if (this._destroyed) return;this._setStatus('connecting');try {this.client = new Client(this.url);- this.room = await this.client.joinOrCreate(this.roomName, { name: this.name, avatar: this.avatar, pid: this.pid });+ const presence = this.getPresence ? await this.getPresence().catch(() => null) : null;+ this.room = await this.client.joinOrCreate(this.roomName, { name: this.name, avatar: this.avatar, pid: this.pid, server: this.server, ...(presence ? { presence } : {}) });this.sessionId = this.room.sessionId;-- this.room.onMessage('realm', (layout) => this._emit('realm', layout));- this.room.onMessage('items', (r) => this._emit('items', r));- this.room.onMessage('notice', (n) => this._emit('notice', n));- this.room.onMessage('chat', (m) => this._emit('chat', m));- this.room.onMessage('bank', (b) => this._emit('bank', b));- this.room.onMessage('skills', (s) => this._emit('skills', s));- this.room.onMessage('levelup', (l) => this._emit('levelup', l));- this.room.onMessage('died', (d) => this._emit('died', d));- this.room.onMessage('cooked', (c) => this._emit('cooked', c));- this.room.onMessage('quests', (q) => this._emit('quests', q));-- const $ = getStateCallbacks(this.room);- const wire = (mapName, addEv, changeEv, removeEv) => {- $(this.room.state)[mapName].onAdd((item, id) => {- this._emit(addEv, item, id);- $(item).onChange(() => this._emit(changeEv, item, id));- });- $(this.room.state)[mapName].onRemove((_item, id) => this._emit(removeEv, id));- };- wire('players', 'playerAdd', 'playerChange', 'playerRemove');- wire('nodes', 'nodeAdd', 'nodeChange', 'nodeRemove');- wire('mobs', 'mobAdd', 'mobChange', 'mobRemove');- wire('tombstones', 'tombAdd', 'tombChange', 'tombRemove');-- this.room.onLeave((code) => {- this._setStatus('offline');- if (!this._destroyed && code !== 1000) this._scheduleReconnect();- });- this.room.onError((code, message) => console.warn('[game-net] room.onError', code, message));-+ this._bindRoom();+ this._announcePresence();this._reconnectAttempts = 0;this._setStatus('online');} catch (err) {@@ -153,6 +197,110 @@ export class GameNet {}}+ // Attach every message + state-sync handler to the current room. Used by the+ // initial connect AND by a portal handoff, which swaps in a brand-new room+ // object. onLeave is keyed to the specific room instance it was bound to, so a+ // superseded room (the one we just portalled out of) can't flip us offline or+ // trigger a phantom reconnect.+ _bindRoom() {+ const room = this.room;+ room.onMessage('realm', (layout) => this._emit('realm', layout));+ room.onMessage('items', (r) => this._emit('items', r));+ room.onMessage('commands', (c) => this._emit('commands', c));+ room.onMessage('notice', (n) => this._emit('notice', n));+ room.onMessage('chat', (m) => this._emit('chat', m));+ room.onMessage('bank', (b) => this._emit('bank', b));+ room.onMessage('skills', (s) => this._emit('skills', s));+ room.onMessage('levelup', (l) => this._emit('levelup', l));+ room.onMessage('died', (d) => this._emit('died', d));+ room.onMessage('cooked', (c) => this._emit('cooked', c));+ room.onMessage('quests', (q) => this._emit('quests', q));+ room.onMessage('cosmetics', (c) => this._emit('cosmetics', c));+ room.onMessage('shop', (s) => this._emit('shop', s));+ room.onMessage('market', (m) => this._emit('market', m));+ room.onMessage('marketDirty', () => this._emit('marketDirty'));+ room.onMessage('marketQuote', (q) => this._emit('marketQuote', q));+ room.onMessage('marketSettled', (s) => this._emit('marketSettled', s));+ room.onMessage('marketBuyFail', (f) => this._emit('marketBuyFail', f));+ room.onMessage('marketPayout', (p) => this._emit('marketPayout', p));+ room.onMessage('spinInfo', (m) => this._emit('spinInfo', m));+ room.onMessage('spinPrep', (m) => this._emit('spinPrep', m));+ room.onMessage('spinResult', (m) => this._emit('spinResult', m));+ room.onMessage('spinDenied', (m) => this._emit('spinDenied', m));+ // Friends (Task 15): live DM + friend request/accept events pushed by the+ // server's social hub to whichever realm room this account is connected to.+ room.onMessage('social', (m) => this._emit('social', m));+ // Portal traversal: the server reserved us a seat in the destination realm.+ room.onMessage('portal', ({ to, reservation }) => this._handlePortal(to, reservation));+ // Single-active-session (Task 23): the same account just signed in on another+ // tab/server, so the server is closing this seat. Mark it so the imminent+ // onLeave doesn't auto-reconnect into a tug-of-war, and surface it to the UI.+ room.onMessage('takeover', (m) => {+ if (room !== this.room) return;+ this._takenOver = true;+ this._emit('takeover', m || {});+ });++ const $ = getStateCallbacks(room);+ const wire = (mapName, addEv, changeEv, removeEv) => {+ $(room.state)[mapName].onAdd((item, id) => {+ this._emit(addEv, item, id);+ $(item).onChange(() => this._emit(changeEv, item, id));+ });+ $(room.state)[mapName].onRemove((_item, id) => this._emit(removeEv, id));+ };+ wire('players', 'playerAdd', 'playerChange', 'playerRemove');+ wire('nodes', 'nodeAdd', 'nodeChange', 'nodeRemove');+ wire('mobs', 'mobAdd', 'mobChange', 'mobRemove');+ wire('tombstones', 'tombAdd', 'tombChange', 'tombRemove');+ wire('structures', 'structAdd', 'structChange', 'structRemove');++ room.onLeave((code) => {+ if (room !== this.room) return; // superseded by a portal handoff — ignore+ // Taken over by another login (server close code 4001, or the takeover+ // message already flagged it): stay offline with a clear reason and do NOT+ // reconnect — the account's one allowed seat now belongs to the new session.+ if (this._takenOver || code === 4001) {+ this._setStatus('offline', 'Your account signed in on another server or tab.');+ return;+ }+ this._setStatus('offline');+ if (!this._destroyed && code !== 1000) this._scheduleReconnect();+ });+ room.onError((code, message) => console.warn('[game-net] room.onError', code, message));+ }++ // Consume the destination-realm seat reservation the server handed us, swap it+ // in as the live room, then leave the old one. Joining the new room before+ // leaving the old means the old room's onLeave sees `room !== this.room` and+ // stays quiet, so the UI never flickers offline mid-portal. On failure we keep+ // the old room rather than stranding the player.+ async _handlePortal(to, reservation) {+ if (this._destroyed || this._transferring || !this.client) return;+ this._transferring = true;+ const old = this.room;+ try {+ const next = await this.client.consumeSeatReservation(reservation);+ this.room = next;+ this.sessionId = next.sessionId;+ this.realm = REALMS.includes(to) ? to : this.realm;+ this.roomName = `game_${this.realm}`;+ try { old?.leave(true); } catch {}+ // Reset dynamic views + adopt the new session id BEFORE binding state+ // callbacks, which immediately replay the destination realm's entities.+ this._emit('handoff', { realm: this.realm, sessionId: this.sessionId });+ this._bindRoom();+ this._announcePresence();+ this._reconnectAttempts = 0;+ this._setStatus('online');+ } catch (err) {+ console.warn('[game-net] portal handoff failed:', err?.message ?? err);+ this.room = old; // never left it — stay put+ } finally {+ this._transferring = false;+ }+ }+// Exponential backoff with a hard ceiling. When the server is unreachable// (e.g. not deployed), each attempt costs a connection timeout — retrying// forever at a fixed interval floods the console. After MAX_RECONNECT_ATTEMPTS@@ -193,17 +341,46 @@ export class GameNet {questOpen() { this.room?.send('questOpen'); }npcTalk(id) { this.room?.send('npcTalk', { id }); }questTurnIn(id) { this.room?.send('questTurnIn', { id }); }+ // Cosmetics shop (Task 21): fetch the live board, buy a rotating cosmetic,+ // equip an owned one, or revert to the default look.+ shopOpen() { this.room?.send('shopOpen'); }+ buyCosmetic(id) { this.room?.send('buyCosmetic', { id }); }+ equipCosmetic(id) { this.room?.send('equipCosmetic', { id }); }+ unequipCosmetic() { this.room?.send('unequipCosmetic'); }+ // Marketplace (Task 20): fetch the board, list/cancel your own goods, buy a gold+ // listing, and the two-step on-chain flow for token listings (quote → settle).+ marketOpen() { this.room?.send('mktOpen'); }+ marketListGold(item, qty, priceGold) { this.room?.send('mktList', { type: 'gold', item, qty, priceGold }); }+ marketListToken(goldAmount, priceUsd) { this.room?.send('mktList', { type: 'goldForToken', goldAmount, priceUsd }); }+ marketCancel(id) { this.room?.send('mktCancel', { id }); }+ marketBuyGold(id) { this.room?.send('mktBuyGold', { id }); }+ marketTokenQuote(id) { this.room?.send('mktTokenQuote', { id }); }+ marketTokenSettle(quote, txSig) { this.room?.send('mktTokenSettle', { quote, txSig }); }+ // Wheel of Fortune (Task 19): fetch the board/eligibility, take the free spin,+ // and the two-step paid spin (prep builds the tx + quote; settle hands back the+ // broadcast signature for on-chain verification before the prize is rolled).+ spinInfo() { this.room?.send('spinInfo'); }+ spinFree() { this.room?.send('spinFree'); }+ spinPaidPrep() { this.room?.send('spinPaidPrep'); }+ spinPaidSettle(quote, txSig) { this.room?.send('spinPaidSettle', { quote, txSig }); }// Mounts (Task 09): ride the active hotbar item if it's a mount, leave the// saddle, and a generic slash-command channel (Task 13 chat forwards here).use(slot) { this.room?.send('use', slot == null ? {} : { slot }); }dismount() { this.room?.send('dismount'); }command(text) { this.room?.send('command', { text }); }+ // Building (Task 07): place a structure on an adjacent tile. Pickup/lock/unlock+ // go through the command channel above (/pickup, /lock, /unlock).+ build(kind, tx, ty) { this.room?.send('build', { kind, tx, ty }); }get state() { return this.room?.state ?? null; }retry() {if (this._reconnectTimer) { clearTimeout(this._reconnectTimer); this._reconnectTimer = null; }this._reconnectAttempts = 0;+ // A manual reconnect after a takeover is the player reclaiming the seat on+ // purpose — clear the flag so the connect path runs normally (and itself+ // evicts whatever session currently holds the account).+ this._takenOver = false;this.connect();}diff --git a/src/game/iso-controls.js b/src/game/iso-controls.jsindex ea01b24b8..34ee09bf8 100644--- a/src/game/iso-controls.js+++ b/src/game/iso-controls.js@@ -1,5 +1,6 @@-// Controls layer for the isometric MMO (/game) — the hotbar, the panel toggles-// (inventory · map · build · friends), and the rebindable Controls settings UI.+// Controls layer for the isometric MMO (/game) — hotbar selection, the panel+// toggles (inventory · map · build · friends), and the rebindable Controls+// settings UI.//// This module is the single home for discrete keyboard input. It owns one// capture-phase keydown listener that routes every game action through the@@ -9,13 +10,21 @@// touches it — when a pressed key isn't a bound action it lets the event flow// through to the renderer untouched.//+// The visual hotbar lives in game-hud.js (#kq-hotbar), fed by the renderer's+// authoritative player sync (it already reflects the active slot). This layer+// drives that hotbar by keyboard — selection routes through game._equipOrRide so+// 1–6 ride a mount slot just like a click does, and 0 sends equip(-1) to clear.+//// It attaches to the live IsoGame instance (window.__ISO__) and subscribes to the// network bus directly (game.net.on('playerChange', …)) for the local player's-// hotbar / inventory / active slot. That keeps the renderer (which is large and-// evolving) free of UI-coupling: this file is self-contained and self-mounting.+// inventory / active slot, which back the Inventory panel. That keeps the+// renderer (which is large and evolving) free of UI-coupling: this file is+// self-contained and self-mounting.import { Keybindings, ACTIONS, normalizeKey, keyLabel } from './keybindings.js';import { itemDisplay } from './items.js';+import { FriendsPanel } from './friends-panel.js';+import { friendsClient } from '../friends.js';const HOTBAR = 6;const INV = 24;@@ -29,12 +38,6 @@ const PLACEHOLDERS = {blurb: 'Place a firepit and raise a shack to claim a corner of the world.',note: 'Building arrives with Task 07.',},- friends: {- title: 'Friends',- glyph: '👥',- blurb: 'Send requests, see who’s online, and message friends directly.',- note: 'Friends arrive with Task 15.',- },};// Tiny DOM helper (mirrors the el() convention used elsewhere in src/game).@@ -63,10 +66,8 @@ export class IsoControls {this.game = game;this.kb = new Keybindings(localStorage.getItem('cc-name') || '');- // Local-player mirror, fed by the network bus.- this._hotbar = Array.from({ length: HOTBAR }, () => ({ item: '', qty: 0 }));+ // Local-player mirror, fed by the network bus — backs the Inventory panel.this._inv = Array.from({ length: INV }, () => ({ item: '', qty: 0 }));- this._activeSlot = -1;this._gold = 0;this._me = null;@@ -77,6 +78,14 @@ export class IsoControls {this._mapTimer = null;this._netBound = false;+ // Friends (Task 15): the shared social-graph client + the panel view bound+ // to the friends surface. The panel mounts lazily on first open; the client+ // lives for the session so the HUD unread badge stays live in the background.+ this._friends = friendsClient();+ this._friendsPanel = null;+ this._friendsBtn = null;+ this._friendsUnsub = null;+this._onKeyDown = this._onKeyDown.bind(this);this._sync = this._sync.bind(this);}@@ -86,7 +95,6 @@ export class IsoControls {if (this._mounted) return;this._mounted = true;- this._buildHotbar();this._buildGear();window.addEventListener('keydown', this._onKeyDown, true);@@ -116,7 +124,6 @@ export class IsoControls {_applyPhase(phase) {const world = phase === 'world';- if (this._hotbarEl) this._hotbarEl.hidden = !world;if (this._gearEl) this._gearEl.hidden = !world;if (world && !this._hintDone) {this._updateHint();@@ -134,82 +141,27 @@ export class IsoControls {item: arr?.[i]?.item || '',qty: arr?.[i]?.qty | 0,}));- this._hotbar = read(p.hotbar, HOTBAR);this._inv = read(p.inv, INV);- if (typeof p.activeSlot === 'number') this._activeSlot = p.activeSlot;this._gold = p.gold | 0;this._me = { tx: p.tx | 0, ty: p.ty | 0 };- this._renderHotbar();if (this._isOpen('inv')) this._renderInv();}// -------------------------------------------------------------- hotbar- _buildHotbar() {- const slots = [];- for (let i = 0; i < HOTBAR; i++) {- const slot = el(- 'button',- {- class: 'kg-hb-slot',- type: 'button',- dataset: { slot: String(i) },- onclick: () => this._select(i),- },- [- el('span', { class: 'kg-hb-key', 'aria-hidden': 'true' }),- el('span', { class: 'kg-hb-glyph', 'aria-hidden': 'true' }),- el('span', { class: 'kg-hb-qty', 'aria-hidden': 'true' }),- ],- );- slots.push(slot);- }- this._hbSlots = slots;- this._hotbarEl = el(- 'div',- {- id: 'kg-hotbar',- class: 'kg-hotbar',- role: 'toolbar',- 'aria-label': 'Hotbar',- hidden: true,- },- slots,- );- document.body.appendChild(this._hotbarEl);- this._renderHotbar();- }-- _renderHotbar() {- if (!this._hbSlots) return;- for (let i = 0; i < HOTBAR; i++) {- const btn = this._hbSlots[i];- const cell = this._hotbar[i] || { item: '', qty: 0 };- const disp = itemDisplay(cell.item);- const active = i === this._activeSlot;- const keyTxt = keyLabel(this.kb.get('hotbar' + (i + 1)));- btn.querySelector('.kg-hb-key').textContent = keyTxt;- btn.querySelector('.kg-hb-glyph').textContent = disp ? disp.glyph : '';- btn.querySelector('.kg-hb-qty').textContent = cell.qty > 1 ? String(cell.qty) : '';- btn.classList.toggle('kg-hb--active', active);- btn.classList.toggle('kg-hb--empty', !cell.item);- btn.setAttribute('aria-pressed', String(active));- const name = disp ? disp.name : 'empty';- btn.setAttribute(- 'aria-label',- `Hotbar ${i + 1} (${keyTxt}): ${name}${active ? ', selected' : ''}`,- );- btn.title = `${name} — press ${keyTxt}`;- }- }-// Select hotbar slot `i` (0-5); pass -1 to clear. Selecting is idempotent so// 1–6 always *set* the active slot per the world-guide spec; 0 clears.+ //+ // Selection routes through the renderer's _equipOrRide so a number key behaves+ // exactly like clicking the slot in the game-hud hotbar — equip, and ride the+ // steed if the slot holds a mount. The visual (active-slot highlight) is owned+ // by that hotbar, fed by the server's authoritative activeSlot patch. Clearing+ // has no slot to ride, so it sends equip(-1) straight to the net; the server+ // accepts -1 and patches activeSlot back, dropping the highlight._select(i) {const net = this.game.net;if (!net) return;- this._activeSlot = i;- net.equip(i);- this._renderHotbar();+ if (i >= 0 && typeof this.game._equipOrRide === 'function') this.game._equipOrRide(i);+ else net.equip(i);}// -------------------------------------------------------------- gear button@@ -763,7 +715,6 @@ export class IsoControls {}_onBindingsChanged() {- this._renderHotbar();this._updateHint();if (this._isOpen('settings')) {const msg = this._pendingMsg;@@ -788,7 +739,6 @@ export class IsoControls {clearInterval(this._syncTimer);if (this._mapTimer) clearInterval(this._mapTimer);this._unsub?.();- this._hotbarEl?.remove();this._gearEl?.remove();for (const k of Object.keys(this._surfaces)) this._surfaces[k].overlay.remove();this._surfaces = {};diff --git a/src/game/iso-game.css b/src/game/iso-game.cssindex c13b97392..3ee9768ca 100644--- a/src/game/iso-game.css+++ b/src/game/iso-game.css@@ -299,6 +299,10 @@ body.kg-loading-cursor {background: #5cb6e6;color: #5cb6e6;}+#kg-pickup .kg-action-dot {+ background: #c9a26b;+ color: #c9a26b;+}/* Cast is shown beside water even without a rod, so the player learns where tofish — muted + a help cursor signal it's gated until they hold a rod. */.kg-action--muted {@@ -465,6 +469,142 @@ body.kg-loading-cursor {padding: 4px 10px;}+/* ---------------------------------------------------------------- server picker+ Login-time world-instance chooser (Task 23). Radio cards with real live+ population; the recommended (least-full) server is badged. */+.kg-servers {+ border: 0;+ margin: 0 0 14px;+ padding: 0;+ text-align: left;+}+.kg-servers-legend {+ font-size: 11px;+ letter-spacing: 0.16em;+ text-transform: uppercase;+ color: var(--kg-dim);+ padding: 0;+ margin-bottom: 8px;+}+.kg-servers-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.kg-servers-loading {+ font-size: 13px;+ color: var(--kg-dim);+ padding: 10px 2px;+}+.kg-server-opt {+ position: relative;+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 11px 13px;+ border: 1px solid var(--kg-line);+ border-radius: 12px;+ background: rgba(0, 0, 0, 0.22);+ cursor: pointer;+ transition:+ border-color 0.15s,+ background 0.15s,+ transform 0.08s ease;+}+.kg-server-opt:hover {+ border-color: rgba(255, 255, 255, 0.28);+ background: rgba(255, 255, 255, 0.04);+}+.kg-server-opt:active {+ transform: translateY(1px);+}+.kg-server-opt input {+ position: absolute;+ opacity: 0;+ pointer-events: none;+}+.kg-server-opt[data-selected='true'] {+ border-color: var(--kg-accent);+ background: color-mix(in srgb, var(--kg-accent) 14%, transparent);+}+.kg-server-opt:focus-within {+ outline: 2px solid var(--kg-accent);+ outline-offset: 2px;+}+.kg-server-dot {+ flex: 0 0 auto;+ width: 9px;+ height: 9px;+ border-radius: 50%;+ background: #3ad07a;+ box-shadow: 0 0 0 3px color-mix(in srgb, #3ad07a 22%, transparent);+}+.kg-server-opt[data-empty='true'] .kg-server-dot {+ background: var(--kg-dim);+ box-shadow: none;+}+.kg-server-main {+ flex: 1 1 auto;+ min-width: 0;+}+.kg-server-name {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 14px;+ font-weight: 700;+ color: var(--kg-text);+}+.kg-server-blurb {+ font-size: 12px;+ color: var(--kg-dim);+ margin-top: 2px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.kg-server-pop {+ flex: 0 0 auto;+ font-size: 12px;+ color: var(--kg-dim);+ text-align: right;+ line-height: 1.25;+}+.kg-server-pop b {+ display: block;+ font-size: 15px;+ color: var(--kg-text);+}+.kg-server-rec {+ font-size: 9.5px;+ font-weight: 700;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: #0d1420;+ background: var(--kg-accent);+ border-radius: 999px;+ padding: 2px 7px;+}+.kg-servers-note {+ font-size: 11.5px;+ color: var(--kg-dim);+ line-height: 1.45;+ margin: 10px 2px 0;+}++/* Topbar chip naming the world instance you're on. */+.kg-server-chip {+ font-size: 11px;+ font-weight: 600;+ color: var(--kg-dim);+ border: 1px solid var(--kg-line);+ border-radius: 999px;+ padding: 2px 9px;+}+.kg-server-chip[hidden] {+ display: none;+}+.kg-spinner {width: 34px;height: 34px;@@ -649,6 +789,57 @@ body.kg-loading-cursor {.kg-chat-form {display: flex;+ position: relative; /* anchors the slash-command autocomplete above the input */+}++/* Slash-command autocomplete — floats just above the chat input. */+.kg-chat-hint {+ position: absolute;+ left: 0;+ right: 0;+ bottom: calc(100% + 6px);+ z-index: 10;+ margin: 0;+ padding: 4px;+ list-style: none;+ max-height: 216px;+ overflow-y: auto;+ pointer-events: auto;+ background: var(--kg-panel);+ border: 1px solid var(--kg-line);+ border-radius: 10px;+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.45);+}+.kg-chat-hint[hidden] {+ display: none;+}+.kg-chat-hint-item {+ display: flex;+ align-items: baseline;+ gap: 8px;+ padding: 6px 9px;+ border-radius: 7px;+ cursor: pointer;+ transition: background 0.12s;+}+.kg-chat-hint-item:hover,+.kg-chat-hint-item--active {+ background: rgba(120, 170, 255, 0.16);+}+.kg-chat-hint-cmd {+ flex: none;+ font-weight: 700;+ color: var(--kg-accent);+ font-variant-numeric: tabular-nums;+}+.kg-chat-hint-desc {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 12px;+ color: var(--kg-dim);}.kg-chat-input {pointer-events: auto;@@ -2130,9 +2321,123 @@ body.kg-loading-cursor {.kq-grid { grid-template-columns: repeat(6, 1fr); }}+/* ----- build menu + banner (Task 07) -------------------------------------- */+.kq-build-menu {+ position: fixed; top: 96px; right: 12px; z-index: 14; width: min(320px, 92vw);+ background: var(--kg-panel); border: 1px solid var(--kg-line); border-radius: 16px;+ box-shadow: 0 18px 50px rgba(0,0,0,0.55); backdrop-filter: blur(8px);+ padding: 14px; opacity: 0; transform: translateY(-8px) scale(.98);+ transition: opacity .18s, transform .18s cubic-bezier(.2,.7,.2,1);+}+.kq-build-menu[hidden] { display: none; }+.kq-build-menu.kq-in { opacity: 1; transform: none; }+.kq-build-head { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }+.kq-build-head h2 { margin: 0; font-size: 15px; font-weight: 800; }+.kq-build-head .kq-x { margin-left: auto; position: static; }+.kq-build-list { display: flex; flex-direction: column; gap: 10px; }+.kq-build-card {+ padding: 12px; border-radius: 12px; background: rgba(255,255,255,0.035);+ border: 1px solid var(--kg-line); transition: border-color .15s;+}+.kq-build-card--short { opacity: 0.92; }+.kq-build-card-head { display: flex; align-items: flex-start; gap: 10px; margin-bottom: 9px; }+.kq-build-ic { font-size: 26px; line-height: 1; }+.kq-build-titles { min-width: 0; }+.kq-build-name { font-size: 14px; font-weight: 800; display: flex; align-items: center; gap: 7px; }+.kq-build-cap { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--kg-dim); background: rgba(255,255,255,0.06); border-radius: 999px; padding: 2px 7px; }+.kq-build-desc { font-size: 12px; color: var(--kg-dim); line-height: 1.45; margin-top: 2px; }+.kq-build-costs { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 11px; }+.kq-build-cost {+ display: inline-flex; align-items: center; gap: 4px; font-size: 12px; font-weight: 700;+ color: var(--kg-text); background: rgba(110,231,135,0.1); border: 1px solid rgba(110,231,135,0.3);+ border-radius: 999px; padding: 3px 9px;+}+.kq-build-cost-ic { font-size: 13px; }+.kq-build-cost--short { color: #ff9a9a; background: rgba(255,90,90,0.1); border-color: rgba(255,90,90,0.35); }+.kq-build-go { width: 100%; padding: 9px; background: #ffce5c; color: #2a1c00; }++.kq-build-banner {+ position: fixed; left: 50%; bottom: 116px; transform: translateX(-50%); z-index: 12;+ display: inline-flex; align-items: center; gap: 12px; padding: 9px 9px 9px 15px;+ border-radius: 999px; font-size: 13px; font-weight: 700; color: var(--kg-text);+ background: rgba(13, 20, 32, 0.92); border: 1px solid var(--kg-accent);+ box-shadow: 0 10px 30px rgba(0,0,0,0.5); animation: kq-rise .2s cubic-bezier(.2,.7,.2,1);+}+.kq-build-banner[hidden] { display: none; }+.kq-build-banner-ic { font-size: 18px; }+.kq-build-banner .kq-btn-ghost { margin-top: 0; width: auto; padding: 6px 14px; }+@media (max-width: 560px) {+ .kq-build-menu { top: auto; bottom: 150px; right: 8px; left: 8px; width: auto; }+ .kq-build-banner { bottom: 84px; }+}++/* ----- gold readout (toolbar) --------------------------------------------- */+.kq-gold {+ display: inline-flex; align-items: center; gap: 5px; padding: 8px 13px; border-radius: 10px;+ font-size: 13px; font-weight: 800; color: #ffce5c; font-variant-numeric: tabular-nums;+ background: var(--kg-panel); border: 1px solid var(--kg-line); box-shadow: 0 6px 20px rgba(0,0,0,0.35);+}+.kq-gold-ic { font-size: 14px; }++/* ----- cosmetics shop (Task 21) ------------------------------------------- */+.kq-shop-card { max-width: 620px; }+.kq-shop-head { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding-right: 34px; }+.kq-shop-head h2 { margin: 0; font-size: 17px; font-weight: 800; }+.kq-shop-purse {+ margin-left: auto; display: inline-flex; align-items: center; gap: 5px; font-size: 13px; font-weight: 800;+ color: #ffce5c; font-variant-numeric: tabular-nums; background: rgba(255,206,92,0.1);+ border: 1px solid rgba(255,206,92,0.32); border-radius: 999px; padding: 4px 12px;+}+.kq-shop-tabs { display: flex; gap: 6px; margin-bottom: 10px; }+.kq-shop-tab {+ flex: 1; cursor: pointer; font: inherit; font-size: 13px; font-weight: 700; padding: 8px 10px;+ color: var(--kg-dim); background: rgba(255,255,255,0.04); border: 1px solid var(--kg-line);+ border-radius: 10px; transition: color .15s, border-color .15s, background .15s;+}+.kq-shop-tab:hover { color: var(--kg-text); border-color: var(--kg-accent); }+.kq-shop-tab:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }+.kq-shop-tab--on { color: #0d1420; background: var(--kg-text); border-color: var(--kg-text); }+.kq-shop-note { margin: 0 0 14px; font-size: 11px; color: var(--kg-dim); line-height: 1.45; }+.kq-shop-sub { margin: 0 0 12px; font-size: 12px; color: var(--kg-dim); line-height: 1.45; }+.kq-shop-section { margin-bottom: 20px; }+.kq-shop-section-head { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin-bottom: 10px; }+.kq-shop-reset { font-size: 11px; font-weight: 700; color: #ffce5c; font-variant-numeric: tabular-nums; }++.kq-cos-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }+.kq-cos-card {+ --cos-accent: #9aa7b4;+ display: flex; flex-direction: column; align-items: center; text-align: center; gap: 8px;+ padding: 14px 12px 12px; border-radius: 14px; background: rgba(255,255,255,0.035);+ border: 1px solid var(--kg-line); border-top: 3px solid var(--cos-accent);+ transition: border-color .15s, transform .08s, background .15s;+}+.kq-cos-card.kq-cos--equipped { background: rgba(110,231,135,0.08); border-color: rgba(110,231,135,0.5); }+.kq-cos-card.kq-cos--short { opacity: 0.78; }+.kq-cos-swatch {+ width: 58px; height: 58px; border-radius: 50%; display: grid; place-items: center;+ font-size: 30px; line-height: 1; background: rgba(255,255,255,0.06); border: 1px solid var(--kg-line);+}+.kq-cos-swatch--default { background: rgba(255,255,255,0.06); }+.kq-cos-meta { display: flex; flex-direction: column; gap: 2px; }+.kq-cos-name { font-size: 13px; font-weight: 800; color: var(--kg-text); }+.kq-cos-rarity { font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; color: var(--cos-accent); }+.kq-cos-foot { display: flex; align-items: center; justify-content: center; gap: 8px; margin-top: auto; padding-top: 4px; }+.kq-cos-price { font-size: 12px; font-weight: 800; color: #ffce5c; font-variant-numeric: tabular-nums; }+.kq-cos-price--short { color: #ff9a9a; }+.kq-cos-owned { font-size: 12px; font-weight: 800; color: var(--kg-dim); }+.kq-cos-equipped { font-size: 12px; font-weight: 800; color: #6ee787; }+.kq-cos-buy { background: #ffce5c; color: #2a1c00; padding: 6px 14px; }+.kq-cos-equip { background: var(--kg-text); color: #0d1420; padding: 6px 14px; }+.kq-shop-empty { display: flex; flex-direction: column; align-items: center; gap: 10px; text-align: center; margin-top: 16px; }+.kq-shop-empty .kq-btn-ghost { margin-top: 0; width: auto; }+@media (max-width: 480px) {+ .kq-cos-grid { grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); }+ .kq-gold .kq-gold-ic + b { display: inline; }+}+@media (prefers-reduced-motion: reduce) {- .kq-panel, .kq-progress i, .kq-tool-btn, .kq-slot, .kq-cell { transition: none; }- .kq-modal-card { animation: none; }+ .kq-panel, .kq-progress i, .kq-tool-btn, .kq-slot, .kq-cell, .kq-build-menu, .kq-shop-tab, .kq-cos-card { transition: none; }+ .kq-modal-card, .kq-build-banner { animation: none; }.kq-npc-marker, .kq-dot { animation: none; }}diff --git a/src/game/iso-game.js b/src/game/iso-game.jsindex 586364de9..c616c56a5 100644--- a/src/game/iso-game.js+++ b/src/game/iso-game.js@@ -29,12 +29,14 @@ import {} from 'three';import nipplejs from 'nipplejs';-import { GameNet } from './game-net.js';+import { GameNet, fetchServers } from './game-net.js';+import { getPresenceTicket } from '../friends.js';import {loadManifest, resolveAvatarUrl, buildAvatar, newAnim, CLIP_IDLE, CLIP_WALK,} from './avatar-rig.js';import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';import { GameHud } from './game-hud.js';+import { applyCosmetic } from './cosmetics-visual.js';const TILE = 1.0; // world units per tileconst STEP_INTERVAL_MS = 165; // walk cadence — one authoritative step per tile@@ -65,6 +67,18 @@ const fmtXp = (n) => Math.round(n).toLocaleString('en-US');const EDIBLE = new Set(['cookedFish', 'healthPotion']);const FOOD_LABEL = { cookedFish: 'cooked fish', healthPotion: 'potion' };+// Player-built structures (Task 07): presentation only — icon, label, and a short+// pitch for the build menu. The realm's allowed kinds and the authoritative costs+// arrive from the server (the realm message's `buildCatalog`), so this never+// hard-codes prices and never drifts from what the server will actually charge.+const STRUCTURE_META = {+ firepit: { icon: '🔥', label: 'Firepit', desc: 'Heals allies beside it for ~30s, then burns out.' },+ shack: { icon: '🛖', label: 'Shack', desc: 'A permanent landmark. One per builder.' },+};+// Material icons for the build-menu cost chips (mirrors items.js labels/icons; the+// HUD has its own copy for backpack rendering — this keeps the scene self-contained).+const MATERIAL_ICON = { wood: '🪵', stone: '🪨', coal: '⚫' };+// Lightweight item presentation for the death-bag recovery panel: a readable// label + a chip colour per known item. Unknown items fall back to a titlecase// of their id and a neutral chip, so a future item never renders blank.@@ -87,13 +101,20 @@ const itemColor = (id) => ITEM_COLOR[id] || '#7d8696';// (T6 polishes remote-specific touches like HP bars on top of this baseline).// ---------------------------------------------------------------------------class GamePlayerView {- constructor(scene, tileToWorld, player, isLocal) {+ constructor(scene, tileToWorld, player, isLocal, cosmeticFor) {this.scene = scene;this.tileToWorld = tileToWorld;this.isLocal = isLocal;this.id = player.id;+ // Resolver (id → visual spec) from the server cosmetics catalogue. Lets this+ // view layer any peer's equipped cosmetic (tint / prop / aura) over the base+ // avatar. Strictly visual — never consulted for anything gameplay-affecting.+ this._cosmeticFor = cosmeticFor || (() => null);this.rig = new Group();+ // Tag the rig so a PvP-realm raycast can resolve a click on this body back to its+ // player id (the local player is filtered out at the call site, you can't hit yourself).+ this.rig.userData.playerId = player.id;this.anim = newAnim();this.height = 1.7;@@ -133,6 +154,11 @@ class GamePlayerView {this._saddleY = 0;this._rideRate = 1.5;this._avatarUrl = null;+ // Equipped cosmetic (Task 21): the id and the live visual handle layered over+ // the avatar. Re-applied after every avatar (re)load, since loading clears the+ // rig. Both local player and peers render their equipped look.+ this._cosmeticId = player.cosmeticId || '';+ this._cosmeticHandle = null;this.setAvatar(player.cosmetic || '');}@@ -140,14 +166,38 @@ class GamePlayerView {const next = url || AVATAR_DEFAULT;if (next === this._avatarUrl) return;this._avatarUrl = next;+ // Loading rebuilds the rig from scratch, so drop the cosmetic layer first+ // (restoring any tinted materials) and re-mount it once the new model lands.+ this._disposeCosmetic();this.rig.clear();this.anim = newAnim();resolveAvatarUrl(next).then((u) => buildAvatar(this.rig, u, this.anim).then(({ height }) => {this.height = height;this.anim.crossfadeTo(this.motion === 'walk' ? CLIP_WALK : CLIP_IDLE, 0);+ this._mountCosmetic();}));}+ // Equip (or clear) the cosmetic this view renders. No-op if unchanged; mounts+ // the new look immediately when the model is already loaded (re-mounts after a+ // reload via setAvatar's callback otherwise).+ setCosmetic(id) {+ const next = id || '';+ if (next === this._cosmeticId) return;+ this._cosmeticId = next;+ this._mountCosmetic();+ }++ _mountCosmetic() {+ this._disposeCosmetic();+ const visual = this._cosmeticId ? this._cosmeticFor(this._cosmeticId) : null;+ if (visual) this._cosmeticHandle = applyCosmetic(this.rig, this.height, visual);+ }++ _disposeCosmetic() {+ if (this._cosmeticHandle) { this._cosmeticHandle.dispose(); this._cosmeticHandle = null; }+ }+apply(player) {const moved = player.tx !== this.tx || player.ty !== this.ty;this.tx = player.tx; this.ty = player.ty;@@ -175,6 +225,10 @@ class GamePlayerView {// Peers' avatars are server-authoritative (the local player owns its own// look). setAvatar self-guards, so this is a no-op until a peer changes.if (!this.isLocal) this.setAvatar(player.cosmetic || '');+ // The equipped cosmetic is server-authoritative for everyone (including us,+ // after an equip round-trips), so peers AND the local player track it here.+ // setCosmetic self-guards, so it's a no-op until the equipped id changes.+ this.setCosmetic(player.cosmeticId || '');// Mark when the server says we moved so the loop can settle us to idle on// arrival without waiting for a separate motion patch.if (moved) this._movedAt = performance.now();@@ -212,6 +266,8 @@ class GamePlayerView {}// A mounted, moving rider reads faster — nudge the walk clip rate while riding.this.anim?.update(dt * (this.mounted && this.motion === 'walk' ? this._rideRate : 1));+ // Animate the equipped cosmetic (e.g. a slowly-spinning, pulsing aura).+ this._cosmeticHandle?.tick(dt);}// Mount or dismount the steed under this avatar. `def` is the registry mount@@ -264,6 +320,7 @@ class GamePlayerView {}dispose() {+ this._disposeCosmetic();this.scene.remove(this.rig);if (this._steed) this.scene.remove(this._steed);this.label.remove();@@ -282,10 +339,21 @@ export class IsoGame {this.mobViews = new Map(); // id -> { group, mob }this.npcViews = new Map(); // id -> { group, npc, label, markerEl }this.tombViews = new Map(); // id -> { group, tomb, label, nameEl, ttlEl }+ this.structViews = new Map(); // id -> { group, struct, ring, flame } (Task 07)this.keys = new Set();this.realm = null;this.myId = null;+ // Build mode (Task 07): when non-null we're placing a structure — a ghost+ // preview snaps to the tile under the cursor and turns green/red for valid/+ // invalid placement; a tap places it, right-click/Esc cancels, and movement+ // clicks are suppressed until we exit. `_buildCatalog` is the server-sent cost+ // table for the current realm; `_hoverPtr` tracks the cursor so the ghost+ // follows it without a drag.+ this._buildMode = null; // { kind, ghost } | null+ this._buildCatalog = {};+ this._hoverPtr = null;+// Click-to-interact: a tap on a node/mob/NPC sets a target the loop walks// to and then services (gather/attack/talk); a tap on open ground sets a// move-to tile. _interactAccum paces repeated gather/attack while adjacent.@@ -318,10 +386,11 @@ export class IsoGame {this._skillsTimer = null;// World chat: open flag (drives the expanded vs. click-through collapsed- // state) and the per-account mute set. Mutes are keyed by display name —- // the stable identity until accounts land — and persisted locally;- // Task 16 migrates this to the account-scoped profile store. The closer- // fn is the document listener that dismisses an open mute popover.+ // state) and the per-account mute set. Mutes are keyed by display name and+ // persisted under the player's stable account id (Task 16) — wallet, else a+ // durable guest id — so a block list follows the account across sessions and+ // two accounts on one machine never share one. The closer fn is the document+ // listener that dismisses an open mute popover.this._chatOpen = false;this.muted = this._loadMuted();this._muteMenuCloser = null;@@ -347,6 +416,24 @@ export class IsoGame {onDeposit: (i) => this.net?.bankDeposit(i, 999),onWithdraw: (i) => this.net?.bankWithdraw(i, 999),onReset: () => this.net?.questOpen(),+ onBuildSelect: (kind) => this._enterBuildMode(kind),+ onBuildCancel: () => this._exitBuildMode(),+ // Cosmetics shop (Task 21): open re-fetches the live board; buy/equip/+ // unequip route to the authoritative server, which echoes a fresh board.+ onShopOpen: () => this.net?.shopOpen(),+ onBuyCosmetic: (id) => this.net?.buyCosmetic(id),+ onEquipCosmetic: (id) => this.net?.equipCosmetic(id),+ onUnequipCosmetic: () => this.net?.unequipCosmetic(),+ // Marketplace (Task 20): open fetches the live board; list/cancel/buy-gold+ // route straight to the authoritative server. A token buy is a multi-step+ // on-chain flow the controller drives (_buyTokenListing): quote → wallet+ // sign+send → server-verified settle.+ onMarketOpen: () => this.net?.marketOpen(),+ onMarketListGold: (item, qty, price) => this.net?.marketListGold(item, qty, price),+ onMarketListToken: (gold, usd) => this.net?.marketListToken(gold, usd),+ onMarketCancel: (id) => this.net?.marketCancel(id),+ onMarketBuyGold: (id) => this.net?.marketBuyGold(id),+ onMarketBuyToken: (id) => this._buyTokenListing(id),});this._loop = this._loop.bind(this);@@ -415,7 +502,7 @@ export class IsoGame {// walls, and a tight, dim atmosphere. Surface realms keep the open sky// look. Background + fog are reset on every realm build, so walking back// up to the Mainland restores daylight cleanly.- const isCave = layout.name === 'mine';+ const isCave = !!layout.cave || layout.name === 'mine';this.scene.background.set(isCave ? 0x130f0b : 0x223a55);this.scene.fog.color.set(isCave ? 0x130f0b : 0x223a55);this.scene.fog.near = isCave ? 16 : 48;@@ -487,10 +574,18 @@ export class IsoGame {// Fishing + cooking spots, if the realm has them.this._paintTiles(layout.fishing, 0x3aa0d0, 0.6);this._paintTiles(layout.cooking, 0xff7a3a, 0.6);- // Portals.+ // Portals. An open portal glows violet; a combat-gated one (e.g. the northern+ // cave) is barred with a red archway so its locked state reads before you step on.for (const p of layout.portals || []) {- this._paintTiles(this._rectTiles(p), 0xae7bff, 0.7);+ const tiles = this._rectTiles(p);+ if (p.gate) { this._paintTiles(tiles, 0xd0455a, 0.75); this._buildGateArch(p); }+ else this._paintTiles(tiles, 0xae7bff, 0.7);}+ // Arena fittings: spectator stands (no-PvP), the practice boxing ring, and the+ // moving floor rollers — drawn with directional chevrons so the flow is legible.+ this._buildSeating(layout.seating);+ this._buildRing(layout.ring);+ this._buildRollers(layout.rollers);// Fixed NPCs (Aldric the Guide, …) — distinct characters with a nameplate +// quest marker. Rebuilt with the realm since they ride in the realm layout.@@ -500,7 +595,20 @@ export class IsoGame {const sp = this._tileToWorld(layout.spawn?.tx ?? grid / 2, layout.spawn?.ty ?? grid / 2);this._camTarget.set(sp.x, 0, sp.z);- this.hud.realm.textContent = (layout.name || 'realm').replace(/^\w/, (m) => m.toUpperCase());+ this.hud.realm.textContent = this._realmLabel(layout.name);++ // Topbar world-instance chip (Task 23). Read the server off the synced state+ // (authoritative — confirms which instance we actually landed on) so it can+ // never disagree with what the login picker requested.+ this._updateServerChip();++ // Building (Task 07): the realm's authoritative cost table + allowed kinds.+ // Show the Build button only where this realm permits building, and leave any+ // build mode from a previous realm — its ghost no longer matches these rules.+ this._buildCatalog = layout.buildCatalog || {};+ this._exitBuildMode();+ this.q?.setBuildAvailable(Object.keys(this._buildCatalog).length > 0);+ this._refreshBuildMenu();}// ---------------------------------------------------------------- NPCs@@ -585,6 +693,119 @@ export class IsoGame {}}+ // Title-case a realm id for the HUD, turning multi-word ids into readable labels+ // ('wilderness_north' → 'Wilderness North', 'arena' → 'Arena').+ _realmLabel(name) {+ return (name || 'realm').split('_').map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');+ }++ // A red barred archway over a combat-gated portal — the locked-gate state, drawn+ // so a player reads "you can't just walk in here" before stepping onto the tile.+ _buildGateArch(p) {+ const cx = (p.x0 + p.x1) / 2, cy = (p.y0 + p.y1) / 2;+ const c = this._tileToWorld(cx, cy);+ const g = new Group();+ const mat = new MeshStandardMaterial({ color: 0x7a1f2a, roughness: 0.7, emissive: 0x5a0f1a, emissiveIntensity: 0.5 });+ const postGeo = new BoxGeometry(0.3, 2.4, 0.3);+ const left = new Mesh(postGeo, mat); left.position.set(-TILE * 0.5, 1.2, 0);+ const right = new Mesh(postGeo, mat); right.position.set(TILE * 0.5, 1.2, 0);+ const lintel = new Mesh(new BoxGeometry(TILE * 1.2, 0.35, 0.35), mat); lintel.position.set(0, 2.45, 0);+ left.castShadow = right.castShadow = lintel.castShadow = true;+ g.add(left, right, lintel);+ g.position.set(c.x, 0, c.z);+ this.staticGroup.add(g);+ }++ // Spectator stands: a cool slate tint over the walkable seating tiles plus a corner+ // post at each end, so the stands read as off-floor (and the server keeps them PvP-free).+ _buildSeating(rects) {+ if (!rects?.length) return;+ const postMat = new MeshStandardMaterial({ color: 0x44516a, roughness: 0.9 });+ for (const r of rects) {+ this._paintTiles(this._rectTiles(r), 0x5b7fa6, 0.5);+ for (const [px, py] of [[r.x0, r.y0], [r.x1, r.y0], [r.x0, r.y1], [r.x1, r.y1]]) {+ const post = new Mesh(new CylinderGeometry(0.12, 0.12, 1.0, 8), postMat);+ const w = this._tileToWorld(px, py);+ post.position.set(w.x, 0.5, w.z); post.castShadow = true;+ this.staticGroup.add(post);+ }+ }+ }++ // The practice boxing ring (Mainland plaza): a canvas mat with four corner posts+ // and two rope heights. Purely cosmetic + walkable — no death risk on the safe hub.+ _buildRing(ring) {+ if (!ring) return;+ const w = (ring.x1 - ring.x0 + 1) * TILE, d = (ring.y1 - ring.y0 + 1) * TILE;+ const cx = (ring.x0 + ring.x1) / 2, cy = (ring.y0 + ring.y1) / 2;+ const c = this._tileToWorld(cx, cy);+ const g = new Group();+ this._paintTiles(this._rectTiles(ring), 0x2f6b8a, 0.45); // the canvas+ const postMat = new MeshStandardMaterial({ color: 0xb23b3b, roughness: 0.6 });+ const ropeMat = new MeshStandardMaterial({ color: 0xe6e6e6, roughness: 0.5 });+ const hx = w / 2 - 0.3, hz = d / 2 - 0.3;+ const corners = [[-hx, -hz], [hx, -hz], [hx, hz], [-hx, hz]];+ for (const [sx, sz] of corners) {+ const post = new Mesh(new CylinderGeometry(0.1, 0.1, 1.3, 8), postMat);+ post.position.set(sx, 0.65, sz); post.castShadow = true; g.add(post);+ }+ for (const h of [0.5, 0.95]) {+ for (let i = 0; i < 4; i++) {+ const a = corners[i], b = corners[(i + 1) % 4];+ const len = Math.hypot(b[0] - a[0], b[1] - a[1]);+ const rope = new Mesh(new BoxGeometry(len, 0.05, 0.05), ropeMat);+ rope.position.set((a[0] + b[0]) / 2, h, (a[1] + b[1]) / 2);+ rope.rotation.y = Math.atan2(b[1] - a[1], b[0] - a[0]);+ g.add(rope);+ }+ }+ g.position.set(c.x, 0, c.z);+ this.staticGroup.add(g);+ }++ // Moving-floor rollers (Arena): a hot conveyor tint over each strip with a flat+ // chevron on every tile pointing the way the server pushes — read the flow, ride it.+ _buildRollers(rollers) {+ if (!rollers?.length) return;+ for (const r of rollers) {+ const tiles = this._rectTiles(r);+ this._paintTiles(tiles, 0xff9a3a, 0.85);+ const [dx, dy] = this._rollerDelta(r.dir);+ const yaw = Math.atan2(-dy, dx); // map the push delta to a flat-XZ heading+ for (const t of tiles) {+ const chevron = this._rollerChevron(yaw);+ const w = this._tileToWorld(t.tx, t.ty);+ chevron.position.set(w.x, 0.07, w.z);+ this.staticGroup.add(chevron);+ }+ }+ }++ _rollerDelta(dir) {+ return dir === 'n' ? [0, -1] : dir === 's' ? [0, 1] : dir === 'e' ? [1, 0] : dir === 'w' ? [-1, 0] : [0, 0];+ }++ // A flat '>' chevron (two angled bars) lying on the ground, apex toward +X, then+ // turned by yaw so it points the roller's way.+ _rollerChevron(yaw) {+ const g = new Group();+ const mat = new MeshBasicMaterial({ color: 0x3a2410 });+ const barGeo = new BoxGeometry(0.34, 0.05, 0.1);+ const a = new Mesh(barGeo, mat); a.position.set(-0.05, 0, -0.1); a.rotation.y = -Math.PI / 4;+ const b = new Mesh(barGeo, mat); b.position.set(-0.05, 0, 0.1); b.rotation.y = Math.PI / 4;+ g.add(a, b);+ g.rotation.y = yaw;+ return g;+ }++ // Climb a raycast hit up to the player rig it belongs to, returning that player's+ // id (set on the rig in GamePlayerView) — used to resolve a PvP tap to a target.+ _playerIdOf(obj) {+ let o = obj;+ while (o) { if (o.userData && o.userData.playerId) return o.userData.playerId; o = o.parent; }+ return null;+ }+// A faint tile grid drawn once into a tiling canvas texture. `dark` swaps the// grass palette for a dim rock floor used by the cave (mine) interior._gridTexture(grid, dark = false) {@@ -648,11 +869,15 @@ export class IsoGame {// Task 01's portal traversal lands this is how a danger realm like// Wilderness is reached directly; the server still validates everything.const realm = new URLSearchParams(location.search).get('realm') || 'mainland';- this.net = new GameNet({ name, avatar: netAvatar, realm, pid: this._playerId() });+ // World instance (Task 23) chosen at the login picker — pins every realm room+ // of this session to one server. The server validates/defaults it regardless.+ const server = this._resolveServerChoice();+ this.net = new GameNet({ name, avatar: netAvatar, realm, server, pid: this._playerId(), getPresence: getPresenceTicket });if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));this.net.on('status', ({ status, error }) => this._onStatus(status, error));this.net.on('realm', (layout) => this._buildRealm(layout));this.net.on('items', (r) => this._onItems(r));+ this.net.on('commands', (c) => this._onCommands(c));this.net.on('notice', (n) => this._onNotice(n));this.net.on('cooked', (c) => this._onCooked(c));this.net.on('chat', (m) => this._onChat(m));@@ -671,8 +896,21 @@ export class IsoGame {this.net.on('tombAdd', (t, id) => this._tombAdd(t, id));this.net.on('tombChange', (t, id) => this._tombChange(t, id));this.net.on('tombRemove', (id) => this._tombRemove(id));+ this.net.on('structAdd', (s, id) => this._structAdd(s, id));+ this.net.on('structChange', (s, id) => this._structChange(s, id));+ this.net.on('structRemove', (id) => this._structRemove(id));this.net.on('died', (d) => this._onDied(d));this.net.on('quests', (q) => this._onQuests(q));+ this.net.on('cosmetics', (c) => this._onCosmetics(c));+ this.net.on('shop', (s) => this._onShop(s));+ this.net.on('market', (m) => this.q?.setMarket(m));+ this.net.on('marketDirty', () => this.q?.marketDirty());+ this.net.on('marketQuote', (qd) => this._onMarketQuote(qd));+ this.net.on('marketSettled', (s) => this._onMarketSettled(s));+ this.net.on('marketBuyFail', (f) => this._onMarketBuyFail(f));+ this.net.on('marketPayout', (p) => this._onMarketPayout(p));+ this.net.on('handoff', (info) => this._onHandoff(info));+ this.net.on('takeover', (m) => this._onTakeover(m));await this.net.connect();this.myId = this.net.sessionId;@@ -707,11 +945,189 @@ export class IsoGame {this._updateOnline();}+ // The same account just signed in on another server or tab (Task 23 single+ // active session). game-net already suppressed the auto-reconnect; pull the+ // player out of the world to the offline screen with an honest, actionable+ // reason. The Reconnect button reclaims the seat (game-net clears the flag).+ _onTakeover() {+ this.phase = 'offline';+ this._setHudPhase('offline');+ if (this.hud.offlineMsg) {+ this.hud.offlineMsg.textContent =+ 'Your account signed in on another server or tab. Only one session can be active at a time.';+ }+ if (this.hud.retryBtn) this.hud.retryBtn.textContent = 'Reconnect here';+ }++ // ---------------------------------------------------------------- server picker+ // Login-time world-instance chooser (Task 23). Lists the real roster with live+ // population from the multiplayer host's /servers endpoint; the choice is+ // remembered per browser and pins the whole session to one instance.++ // The active choice: an explicit picker selection wins, then a ?server= deep+ // link, then the remembered choice, else '' (server resolves its default).+ _resolveServerChoice() {+ if (this._chosenServer) return this._chosenServer;+ const urlS = new URLSearchParams(location.search).get('server');+ if (urlS) return urlS;+ try { return localStorage.getItem('kg-server') || ''; } catch { return ''; }+ }++ _initServerPicker() {+ this._serverList = null;+ this._serverPollTimer = null;+ this._chosenServer = this._resolveServerChoice();+ this._refreshServers();+ }++ _startServerPolling() {+ if (this._serverPollTimer || !this.hud?.serversList) return;+ // Refresh live counts every 10s while the picker is visible so the numbers+ // the player chooses from stay honest without hammering the endpoint.+ this._serverPollTimer = setInterval(() => this._refreshServers(), 10_000);+ }++ _stopServerPolling() {+ if (this._serverPollTimer) { clearInterval(this._serverPollTimer); this._serverPollTimer = null; }+ }++ async _refreshServers() {+ if (!this.hud?.serversList) return;+ let list;+ try {+ list = await fetchServers(this.net?.url);+ } catch {+ // Host unreachable: still let the player in via a single default world+ // rather than blocking on a count we can't get. Never fake a number.+ if (!this._serverList) this._renderServerFallback();+ return;+ }+ if (!Array.isArray(list) || !list.length) { this._renderServerFallback(); return; }+ this._serverList = list;+ // Pre-select the remembered/url choice if it's still a real instance, else+ // the recommended (least-full) one, else the first.+ const ids = new Set(list.map((s) => s.id));+ if (!this._chosenServer || !ids.has(this._chosenServer)) {+ this._chosenServer = (list.find((s) => s.recommended) || list[0]).id;+ }+ this._renderServers(list, false);+ }++ _renderServerFallback() {+ this._serverList = [{ id: '', name: 'Default world', blurb: '', players: null, recommended: false }];+ this._chosenServer = '';+ this._renderServers(this._serverList, true);+ }++ _renderServers(list, isFallback) {+ const host = this.hud.serversList;+ if (!host) return;+ host.setAttribute('aria-busy', 'false');+ host.textContent = '';+ for (const s of list) {+ const known = Number.isFinite(s.players);+ const selected = s.id === this._chosenServer;++ const opt = document.createElement('label');+ opt.className = 'kg-server-opt';+ opt.dataset.selected = String(selected);+ opt.dataset.empty = String(known && s.players === 0);++ const input = document.createElement('input');+ input.type = 'radio';+ input.name = 'kg-server';+ input.value = s.id;+ input.checked = selected;+ input.addEventListener('change', () => this._selectServer(s.id));+ opt.appendChild(input);++ const dot = document.createElement('span');+ dot.className = 'kg-server-dot';+ dot.setAttribute('aria-hidden', 'true');+ opt.appendChild(dot);++ const main = document.createElement('span');+ main.className = 'kg-server-main';+ const nameRow = document.createElement('span');+ nameRow.className = 'kg-server-name';+ nameRow.append(document.createTextNode(s.name || s.id || 'World'));+ if (s.recommended && !isFallback) {+ const rec = document.createElement('span');+ rec.className = 'kg-server-rec';+ rec.textContent = 'Recommended';+ nameRow.appendChild(rec);+ }+ main.appendChild(nameRow);+ if (s.blurb) {+ const blurb = document.createElement('div');+ blurb.className = 'kg-server-blurb';+ blurb.textContent = s.blurb;+ main.appendChild(blurb);+ }+ opt.appendChild(main);++ if (known) {+ const pop = document.createElement('span');+ pop.className = 'kg-server-pop';+ const b = document.createElement('b');+ b.textContent = String(s.players);+ pop.append(b, document.createTextNode(s.players === 1 ? 'player' : 'players'));+ opt.appendChild(pop);+ }++ opt.addEventListener('click', (e) => {+ // The label already toggles the radio; guard against a double-fire.+ if (e.target !== input) this._selectServer(s.id);+ });+ host.appendChild(opt);+ }+ this._updateServerChip();+ }++ _selectServer(id) {+ this._chosenServer = id;+ try { localStorage.setItem('kg-server', id); } catch {}+ // Repaint just the selection state so live counts + focus survive.+ this.hud.serversList?.querySelectorAll('.kg-server-opt').forEach((el) => {+ el.dataset.selected = String((el.querySelector('input')?.value ?? '') === id);+ });+ }++ // Topbar chip naming the world instance the player is on. Reads the synced,+ // authoritative server id; only shown when there's a real choice of instances.+ _updateServerChip() {+ const chip = this.hud.server;+ if (!chip) return;+ const id = this.net?.state?.server || this._chosenServer || '';+ const name = this._serverList?.find((s) => s.id === id)?.name || id;+ const multi = (this._serverList?.length || 0) > 1;+ if (name && multi) { chip.textContent = name; chip.hidden = false; }+ else { chip.hidden = true; }+ }++ // A portal moved us into a different realm room. The new room replays its own+ // players/nodes/mobs/tombs from scratch, so tear down every dynamic view tied+ // to the old realm (otherwise they linger as ghosts) and adopt the new session+ // id before those replays arrive. The fresh 'realm' message rebuilds the static+ // geometry; the loop's pending target is dropped so we don't chase a stale tile.+ _onHandoff({ sessionId } = {}) {+ for (const id of [...this.players.keys()]) this._playerRemove(id);+ for (const id of [...this.nodeViews.keys()]) this._nodeRemove(id);+ for (const id of [...this.mobViews.keys()]) this._mobRemove(id);+ for (const id of [...this.tombViews.keys()]) this._tombRemove(id);+ for (const id of [...this.structViews.keys()]) this._structRemove(id);+ this._exitBuildMode();+ this._target = null;+ this._lootTombId = null;+ this.myId = sessionId || this.net?.sessionId || this.myId;+ this._updateOnline();+ }+// ---------------------------------------------------------------- players_playerAdd(p, id) {if (this.players.has(id)) { this.players.get(id).apply(p); return; }const isLocal = id === this.myId;- const view = new GamePlayerView(this.scene, (tx, ty) => this._tileToWorld(tx, ty), p, isLocal);+ const view = new GamePlayerView(this.scene, (tx, ty) => this._tileToWorld(tx, ty), p, isLocal, (cid) => this._cosmeticVisual(cid));// The local player renders its own resolved avatar immediately (covers a// guest blob the server hasn't received the public URL for yet).if (isLocal && this.localAvatarUrl) view.setAvatar(this.localAvatarUrl);@@ -738,6 +1154,12 @@ export class IsoGame {const onBank = (this.realm?.bankZone || []).some((t) => t.tx === p.tx && t.ty === p.ty);this.q.setBankAvailable(onBank);this._updateMountChip(p);+ // Keep the persistent gold readout + any open shop's affordability in sync as+ // the purse changes (mob/quest rewards, a purchase).+ this.q.setGold(p.gold);+ // Affordability of buildables shifts as materials are gained/spent — keep the+ // build menu live (no-op in realms that don't permit building).+ this._refreshBuildMenu();}_playerRemove(id) {const v = this.players.get(id);@@ -767,6 +1189,114 @@ export class IsoGame {_mountDef(id) { return this.items?.[id]?.mount || null; }+ // ------------------------------------------------------------ cosmetics (Task 21)+ // The cosmetics catalogue (id → name/rarity/price/rotation/visual) arrives once+ // on join. Index it, hand it to the HUD so the shop/wardrobe render real data,+ // and re-apply every avatar's equipped look now that visuals are resolvable.+ _onCosmetics(catalog) {+ const list = catalog?.cosmetics || [];+ this.cosmetics = new Map(list.map((c) => [c.id, c]));+ this.cosmeticRarities = catalog?.rarities || {};+ this.q?.setCosmeticCatalog(list, this.cosmeticRarities);+ const players = this.net?.state?.players;+ for (const [id, v] of this.players) {+ const sp = players?.get(id);+ v.setCosmetic(sp?.cosmeticId || '');+ }+ }++ // Resolve a cosmetic id to its visual spec for the avatar renderer. Returns null+ // for the empty/default look or before the catalogue has loaded.+ _cosmeticVisual(id) {+ return id ? (this.cosmetics?.get(id)?.visual || null) : null;+ }++ // The live shop board (offers + rotation countdowns + owned + gold) — straight+ // through to the HUD's shop surface.+ _onShop(snapshot) {+ this.q?.setShop(snapshot || null);+ }++ // ---------------------------------------------------------------- marketplace (Task 20)++ // Begin an on-chain token purchase. We allow one in flight at a time so the+ // per-listing busy state and the wallet handshake stay unambiguous. The server+ // replies with a 'marketQuote' (unsigned split tx + signed quote) which+ // _onMarketQuote then drives through the wallet and back as a settle.+ async _buyTokenListing(id) {+ if (this._tokenBuy) { this._toast({ kind: 'market', text: 'Finish your current purchase first.' }); return; }+ let wallet = null;+ try {+ const { detectSolanaWallet } = await import('../erc8004/solana-deploy.js');+ wallet = detectSolanaWallet();+ } catch { wallet = null; }+ if (!wallet || !wallet.publicKey) {+ this._toast({ kind: 'market', text: 'Connect a Solana wallet to buy with tokens.' });+ return;+ }+ this._tokenBuy = { id };+ this.q?.setMarketBusy(id, 'Preparing…');+ this.net?.marketTokenQuote(id);+ }++ // The server quoted the token amount and built the split transaction. Sign it in+ // the wallet, broadcast through our same-origin RPC proxy, wait for confirmation,+ // then hand the signature back for server-side verification + gold release.+ async _onMarketQuote(qd) {+ if (!qd || !this._tokenBuy || this._tokenBuy.id !== qd.id) return; // stale/unsolicited+ const id = qd.id;+ try {+ const { detectSolanaWallet, SOLANA_RPC } = await import('../erc8004/solana-deploy.js');+ const { Transaction, Connection } = await import('@solana/web3.js');+ const wallet = detectSolanaWallet();+ if (!wallet || !wallet.publicKey) throw new Error('wallet-missing');+ this.q?.setMarketBusy(id, 'Confirm in wallet…');+ const bytes = Uint8Array.from(atob(qd.tx), (c) => c.charCodeAt(0));+ const tx = Transaction.from(bytes);+ const signed = await wallet.signTransaction(tx);+ this.q?.setMarketBusy(id, 'Confirming…');+ const conn = new Connection(SOLANA_RPC.mainnet, 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false, maxRetries: 3 });+ const latest = await conn.getLatestBlockhash('confirmed');+ await conn.confirmTransaction({ signature: sig, blockhash: latest.blockhash, lastValidBlockHeight: latest.lastValidBlockHeight }, 'confirmed');+ this.q?.setMarketBusy(id, 'Settling…');+ this.net?.marketTokenSettle(qd.quote, sig);+ } catch (err) {+ const msg = String(err?.message || err);+ const friendly = /reject|denied|cancell?ed|user/i.test(msg) ? 'Cancelled in wallet.' : 'Payment failed — no gold was charged.';+ this._tokenBuy = null;+ this.q?.clearMarketBusy(id);+ this._toast({ kind: 'market', text: friendly });+ }+ }++ // Server verified the payment and released the gold (it also sends a notice ++ // fresh board). Clear the in-flight buy + its busy spinner.+ _onMarketSettled(s) {+ const id = s?.id || this._tokenBuy?.id;+ this._tokenBuy = null;+ if (id) this.q?.clearMarketBusy(id);+ }++ // Server rejected a token quote/settle (price feed down, expired quote, failed+ // verification). The accompanying notice explains why; here we just release the+ // spinner so the card returns to a buyable state.+ _onMarketBuyFail(info) {+ const id = info?.id || this._tokenBuy?.id;+ this._tokenBuy = null;+ if (id) this.q?.clearMarketBusy(id);+ }++ // Proceeds from a sale that completed while this account was offline or in+ // another realm, delivered on login / via a live nudge.+ _onMarketPayout(p) {+ if (!p) return;+ const parts = [];+ if (p.gold) parts.push(`${(p.gold | 0).toLocaleString('en-US')} gold`);+ if (Array.isArray(p.items)) for (const it of p.items) parts.push(`${it.qty}× ${itemLabel(it.item)}`);+ if (parts.length) this._toast({ kind: 'market', text: `Sale settled: +${parts.join(', ')}.` });+ }+// Equip a hotbar slot; if it holds a mount, also ride it — the natural "tap your// steed to mount" gesture. Both are server-authoritative (equip + use intents)._equipOrRide(i) {@@ -873,8 +1403,8 @@ export class IsoGame {// Override seam for T8. Baseline: a colour-coded stand-in per mob kind._buildMobView(mob) {const g = new Group();- const color = mob.kind === 'ogre' ? 0x9c5a3c : mob.kind === 'goblin' ? 0x5a8c3c : 0x9aa0ac;- const scale = mob.kind === 'ogre' ? 1.4 : 1;+ const color = mob.kind === 'troll' ? 0x6f5b8e : mob.kind === 'ogre' ? 0x9c5a3c : mob.kind === 'goblin' ? 0x5a8c3c : 0x9aa0ac;+ const scale = mob.kind === 'troll' ? 1.7 : mob.kind === 'ogre' ? 1.4 : 1;const body = new Mesh(new CylinderGeometry(0.3 * scale, 0.35 * scale, 1.1 * scale, 10),new MeshStandardMaterial({ color, roughness: 0.9 }));body.position.y = 0.55 * scale; body.castShadow = true;@@ -941,6 +1471,294 @@ export class IsoGame {return g;}+ // ---------------------------------------------------------------- structures+ // Player-built firepits + shacks (Task 07), synced via the structures map. A+ // firepit carries a flat countdown ring that drains with its remaining lifetime+ // (read off the authoritative expiresAt); a shack is a permanent little hut.+ _structAdd(struct, id) {+ if (this.structViews.has(id)) { this._structChange(struct, id); return; }+ const view = this._buildStructView(struct, id);+ const w = this._tileToWorld(struct.tx, struct.ty);+ view.group.position.set(w.x, 0, w.z);+ view.group.traverse((o) => { o.userData.structId = id; });+ this.objectGroup.add(view.group);+ this.structViews.set(id, { ...view, struct });+ // A new structure changes which tiles are buildable + (if mine) pickup state.+ this._refreshBuildMenu();+ }+ _structChange(struct, id) {+ const v = this.structViews.get(id);+ if (!v) return;+ v.struct = struct;+ const w = this._tileToWorld(struct.tx, struct.ty);+ v.group.position.set(w.x, 0, w.z);+ }+ _structRemove(id) {+ const v = this.structViews.get(id);+ if (v) {+ this.objectGroup.remove(v.group);+ // Dispose the per-structure geometry/materials (a firepit rebuilds its+ // countdown ring each frame, so free the live one on teardown).+ v.group.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });+ this.structViews.delete(id);+ }+ this._refreshBuildMenu();+ }++ // Build the mesh for a structure. Returns { group, ring?, flame?, lifetime } so+ // the loop can animate a firepit's flame + countdown ring.+ _buildStructView(struct) {+ const g = new Group();+ if (struct.kind === 'firepit') {+ // A ring of stones, a glowing ember bed, and a flickering flame cone.+ const stoneMat = new MeshStandardMaterial({ color: 0x6b6f7a, roughness: 0.95 });+ const ringN = 8;+ for (let i = 0; i < ringN; i++) {+ const a = (i / ringN) * Math.PI * 2;+ const stone = new Mesh(new DodecahedronGeometry(0.16, 0), stoneMat);+ stone.position.set(Math.cos(a) * 0.42, 0.12, Math.sin(a) * 0.42);+ stone.castShadow = true;+ g.add(stone);+ }+ const embers = new Mesh(new CylinderGeometry(0.34, 0.34, 0.06, 12),+ new MeshStandardMaterial({ color: 0x3a1c0c, emissive: 0xff5a1e, emissiveIntensity: 0.9, roughness: 0.6 }));+ embers.position.y = 0.1;+ const flame = new Mesh(new ConeGeometry(0.26, 0.8, 10),+ new MeshStandardMaterial({ color: 0xffae3a, emissive: 0xff7a1e, emissiveIntensity: 1.3, roughness: 0.4, transparent: true, opacity: 0.92 }));+ flame.position.y = 0.62;+ // A flat countdown ring around the pit — drains from full to empty over the+ // firepit's lifetime. Rebuilt each frame via _updateStructures.+ const ring = new Mesh(+ new RingGeometry(0.5, 0.62, 28),+ new MeshBasicMaterial({ color: 0xffce5c, transparent: true, opacity: 0.85, side: DoubleSide }),+ );+ ring.rotation.x = -Math.PI / 2;+ ring.position.y = 0.06;+ g.add(embers, flame, ring);+ const lifetime = this._buildCatalog?.firepit?.lifetimeMs || 30000;+ return { group: g, ring, flame, lifetime };+ }+ // Shack: a timber cabin with a pitched roof and a dark doorway.+ const wall = new Mesh(new BoxGeometry(0.92, 0.8, 0.92),+ new MeshStandardMaterial({ color: 0x8a5a32, roughness: 0.9 }));+ wall.position.y = 0.4; wall.castShadow = true; wall.receiveShadow = true;+ const roof = new Mesh(new ConeGeometry(0.85, 0.6, 4),+ new MeshStandardMaterial({ color: 0x5a3a20, roughness: 0.9 }));+ roof.position.y = 1.1; roof.rotation.y = Math.PI / 4; roof.castShadow = true;+ const door = new Mesh(new BoxGeometry(0.26, 0.46, 0.06),+ new MeshStandardMaterial({ color: 0x2a1a0e, roughness: 1 }));+ door.position.set(0, 0.23, 0.47);+ g.add(wall, roof, door);+ return { group: g, lifetime: 0 };+ }++ // Animate firepits: flicker the flame and drain the countdown ring from its+ // remaining lifetime fraction. Shacks are static. Cheap; runs each frame.+ _updateStructures(now) {+ if (!this.structViews.size) return;+ const t = now / 1000;+ for (const [, v] of this.structViews) {+ if (!v.ring) continue;+ const exp = v.struct?.expiresAt || 0;+ const frac = exp ? Math.max(0, Math.min(1, (exp - Date.now()) / (v.lifetime || 30000))) : 1;+ // Redraw the ring as an arc covering the remaining fraction.+ v.ring.geometry.dispose();+ v.ring.geometry = new RingGeometry(0.5, 0.62, 40, 1, -Math.PI / 2, frac * Math.PI * 2);+ // Warm→red as it runs low; flame shrinks + flickers.+ v.ring.material.color.setHex(frac > 0.33 ? 0xffce5c : 0xff5a3a);+ if (v.flame) {+ const flick = 0.85 + Math.sin(t * 12 + v.group.position.x) * 0.12;+ v.flame.scale.set(1, (0.5 + frac * 0.5) * flick, 1);+ v.flame.material.opacity = 0.8 + Math.sin(t * 9) * 0.12;+ }+ }+ }++ // ---------------------------------------------------------------- build mode+ // Enter placement for `kind`: spawn a ghost the loop snaps to the hovered tile,+ // tinting green/red for valid/invalid. Tap places; right-click/Esc cancels.+ _enterBuildMode(kind) {+ if (this.phase !== 'world') return;+ if (!this._buildCatalog?.[kind]) return;+ this._exitBuildMode();+ const ghost = this._makeGhost(kind);+ this.objectGroup.add(ghost);+ this._buildMode = { kind, ghost, valid: false, tile: null };+ this.q?.closeBuild();+ this.q?.showBuildBanner(STRUCTURE_META[kind]);+ this._toast({ kind: 'build', text: `Tap a tile beside you to place the ${STRUCTURE_META[kind]?.label || kind}.` });+ }++ _exitBuildMode() {+ if (!this._buildMode) { this.q?.hideBuildBanner?.(); return; }+ this.objectGroup.remove(this._buildMode.ghost);+ this._buildMode.ghost.traverse((o) => { o.geometry?.dispose?.(); o.material?.dispose?.(); });+ this._buildMode = null;+ this.q?.hideBuildBanner();+ }++ // A translucent footprint + a faint silhouette of the structure, tinted by+ // validity. Kept light — it's built only on enter, recoloured each frame.+ _makeGhost(kind) {+ const g = new Group();+ const pad = new Mesh(new PlaneGeometry(TILE * 0.94, TILE * 0.94),+ new MeshBasicMaterial({ color: 0x55ff99, transparent: true, opacity: 0.4, side: DoubleSide }));+ pad.rotation.x = -Math.PI / 2; pad.position.y = 0.05;+ const silMat = new MeshBasicMaterial({ color: 0x55ff99, transparent: true, opacity: 0.35, depthWrite: false });+ const sil = kind === 'shack'+ ? new Mesh(new BoxGeometry(0.9, 0.8, 0.9), silMat)+ : new Mesh(new ConeGeometry(0.3, 0.7, 10), silMat);+ sil.position.y = kind === 'shack' ? 0.4 : 0.45;+ g.add(pad, sil);+ g._pad = pad; g._sil = sil; g._silMat = silMat;+ return g;+ }++ // Each frame in build mode: snap the ghost to the tile under the cursor and+ // recolour by validity. With no cursor yet, park it on the tile in front of us.+ _updateBuildGhost() {+ const bm = this._buildMode;+ if (!bm) return;+ const tile = this._buildHoverTile();+ if (!tile) { bm.ghost.visible = false; return; }+ bm.ghost.visible = true;+ const w = this._tileToWorld(tile.tx, tile.ty);+ bm.ghost.position.set(w.x, 0, w.z);+ const valid = this._buildValid(bm.kind, tile.tx, tile.ty);+ bm.valid = valid; bm.tile = tile;+ const col = valid ? 0x55ff99 : 0xff5a5a;+ bm.ghost._pad.material.color.setHex(col);+ bm.ghost._silMat.color.setHex(col);+ }++ // The tile the ghost should occupy: under the cursor if we have one, else the+ // tile directly in front of the player.+ _buildHoverTile() {+ if (this._hoverPtr) {+ this._ptr.x = (this._hoverPtr.x / window.innerWidth) * 2 - 1;+ this._ptr.y = -(this._hoverPtr.y / window.innerHeight) * 2 + 1;+ this._raycaster.setFromCamera(this._ptr, this.camera);+ const t = this._pickGroundTile();+ if (t) return t;+ }+ const me = this._localView();+ if (!me) return null;+ return { tx: me.tx, ty: me.ty - 1 };+ }++ // Client mirror of the server's build gates for instant ghost feedback: adjacent+ // (but not under the player), a free/buildable tile, and affordable. The server+ // re-checks all of it authoritatively on the actual 'build'.+ _buildValid(kind, tx, ty) {+ const ps = this.net?.state?.players?.get(this.myId);+ if (!ps) return false;+ const dx = Math.abs(tx - ps.tx), dy = Math.abs(ty - ps.ty);+ if (dx === 0 && dy === 0) return false;+ if (dx > 1 || dy > 1) return false;+ if (!this._isBuildableTile(tx, ty)) return false;+ return this._canAffordBuild(kind);+ }++ // A tile clear for building: walkable (bounds + not blocked + no node/mob/+ // structure) and not a portal/bank/fountain/fishing/cooking tile or a standing+ // player — mirrors the server's _isBuildable.+ _isBuildableTile(tx, ty) {+ if (!this._isWalkable(tx, ty)) return false;+ for (const [, v] of this.structViews) if (v.struct.tx === tx && v.struct.ty === ty) return false;+ for (const [, pv] of this.players) if (!pv.dead && pv.tx === tx && pv.ty === ty) return false;+ const r = this.realm || {};+ for (const p of r.portals || []) {+ if (tx >= p.x0 && tx <= p.x1 && ty >= p.y0 && ty <= p.y1) return false;+ }+ if ((r.bankZone || []).some((t) => t.tx === tx && t.ty === ty)) return false;+ if (r.fountain && r.fountain.tx === tx && r.fountain.ty === ty) return false;+ for (const f of r.fishing || []) if (f.tx === tx && f.ty === ty) return false;+ for (const c of r.cooking || []) if (c.tx === tx && c.ty === ty) return false;+ return true;+ }++ _canAffordBuild(kind) {+ const ps = this.net?.state?.players?.get(this.myId);+ const cost = this._buildCatalog?.[kind]?.cost;+ if (!ps || !cost) return false;+ for (const [item, qty] of Object.entries(cost)) {+ if (this._countItem(ps, item) < qty) return false;+ }+ return true;+ }++ // Place the ghost: validate client-side for instant feedback, then send the+ // authoritative 'build'. Stays honest — a red ghost explains why instead of+ // firing a doomed request. Exits build mode on a successful send.+ _attemptBuild(tile) {+ const bm = this._buildMode;+ if (!bm || !tile) return;+ const ps = this.net?.state?.players?.get(this.myId);+ const dx = Math.abs(tile.tx - (ps?.tx ?? 0)), dy = Math.abs(tile.ty - (ps?.ty ?? 0));+ if (dx === 0 && dy === 0) { this._toast({ kind: 'build', text: 'Step back a tile to place it.' }); return; }+ if (dx > 1 || dy > 1) { this._toast({ kind: 'build', text: 'Build on a tile right beside you.' }); return; }+ if (!this._isBuildableTile(tile.tx, tile.ty)) { this._toast({ kind: 'build', text: 'You can’t build there.' }); return; }+ if (!this._canAffordBuild(bm.kind)) {+ this._toast({ kind: 'build', text: `Not enough materials for a ${STRUCTURE_META[bm.kind]?.label || bm.kind}.` });+ return;+ }+ this.net?.build(bm.kind, tile.tx, tile.ty);+ this._exitBuildMode();+ }++ // Toggle the build menu (B key / toolbar). Refreshes affordability first so the+ // menu opens with live costs. In build mode, B cancels placement instead.+ _toggleBuildMenu() {+ if (this.phase !== 'world') return;+ if (this._buildMode) { this._exitBuildMode(); return; }+ this._refreshBuildMenu();+ this.q?.toggleBuild();+ }++ // Recompute the buildable list (kinds + live affordability) and hand it to the+ // HUD. Driven by the realm catalogue + the player's current materials.+ _refreshBuildMenu() {+ const kinds = Object.keys(this._buildCatalog || {});+ if (!kinds.length) { this.q?.setBuildables([]); return; }+ const ps = this.net?.state?.players?.get(this.myId);+ const items = kinds.map((kind) => {+ const def = this._buildCatalog[kind] || {};+ const meta = STRUCTURE_META[kind] || { icon: '🔨', label: kind, desc: '' };+ const costs = Object.entries(def.cost || {}).map(([item, need]) => {+ const have = ps ? this._countItem(ps, item) : 0;+ return { item, icon: MATERIAL_ICON[item] || '📦', need, have, ok: have >= need };+ });+ const owned = this._countOwnedStructures(kind);+ const capped = !!def.cap && owned >= def.cap;+ const affordable = costs.every((c) => c.ok) && !capped;+ const capNote = def.cap ? (capped ? 'placed' : `${owned}/${def.cap}`) : '';+ return { kind, icon: meta.icon, label: meta.label, desc: meta.desc, costs, affordable, capNote };+ });+ this.q?.setBuildables(items);+ }++ _countOwnedStructures(kind) {+ let n = 0;+ for (const [, v] of this.structViews) if (v.struct.kind === kind && v.struct.owner === this.myId) n++;+ return n;+ }++ // A structure of mine I'm standing beside (for the /pickup affordance), nearest+ // first. Null if none in reach.+ _adjacentOwnedStructure() {+ const ps = this.net?.state?.players?.get(this.myId);+ if (!ps) return null;+ let best = null, bd = Infinity;+ for (const [, v] of this.structViews) {+ const s = v.struct;+ if (s.owner !== this.myId) continue;+ if (Math.abs(ps.tx - s.tx) > 1 || Math.abs(ps.ty - s.ty) > 1) continue;+ const d = (ps.tx - s.tx) ** 2 + (ps.ty - s.ty) ** 2;+ if (d < bd) { bd = d; best = s; }+ }+ return best;+ }+// ---------------------------------------------------------------- death & loot// The local player died: stash the notice so the respawn overlay can describe// the drop, and close any open bag panel (you can't loot while dead).@@ -975,6 +1793,14 @@ export class IsoGame {this._ptr.y = -(clientY / window.innerHeight) * 2 + 1;this._raycaster.setFromCamera(this._ptr, this.camera);+ // Build mode (Task 07) owns the tap: a click places the structure on the+ // ghost's tile; movement/gather clicks are suppressed until we exit.+ if (this._buildMode) {+ const tile = this._pickGroundTile() || this._buildMode.tile;+ this._attemptBuild(tile);+ return;+ }+// 1) Tombstone under the cursor (dynamic objects).if (this.tombViews.size) {const hits = this._raycaster.intersectObject(this.objectGroup, true);@@ -1006,6 +1832,19 @@ export class IsoGame {if (ud.npcId && this.npcViews.has(ud.npcId)) { this._setTarget('npc', ud.npcId); return; }}+ // 2b) In a PvP realm, a tap on another living player marks them as an attack+ // target the loop closes on and strikes (the server enforces range + safe zones).+ if (this.realm?.pvp) {+ const rigs = [];+ for (const [pid, pv] of this.players) if (pid !== this.myId && !pv.dead) rigs.push(pv.rig);+ if (rigs.length) {+ for (const h of this._raycaster.intersectObjects(rigs, true)) {+ const pid = this._playerIdOf(h.object);+ if (pid && this.players.has(pid)) { this._setTarget('player', pid); return; }+ }+ }+ }+// 3) Ground pick: water / a shore spot is a cast intent; otherwise a walkable// tile is a click-to-walk move target.const tile = this._pickGroundTile();@@ -1299,7 +2138,13 @@ export class IsoGame {this._toggleAction(this.hud.castBtn, showCast, hasRod ? 'Cast line 🎣' : 'Need a rod 🎣');if (this.hud.castBtn) this.hud.castBtn.classList.toggle('kg-action--muted', showCast && !hasRod);- bar.hidden = !(showCook || showEat || showCast);+ // Pick up: standing beside a structure I placed (Task 07). Routes to /pickup;+ // a locked structure tells the player to /unlock first (server enforces it).+ const mine = this._adjacentOwnedStructure();+ const showPickup = !!mine;+ this._toggleAction(this.hud.pickupBtn, showPickup, mine ? `Pick up ${STRUCTURE_META[mine.kind]?.label || mine.kind}${mine.locked ? ' 🔒' : ''}` : 'Pick up');++ bar.hidden = !(showCook || showEat || showCast || showPickup);}_toggleAction(btn, show, label) {@@ -1487,9 +2332,13 @@ export class IsoGame {if (k === 'escape' && this._skillsOpen) { e.preventDefault(); this._toggleSkills(false); return; }// Quests panel: Q toggles, Escape closes any open quest/bank/NPC surface.if (k === 'q' && this.phase === 'world') { e.preventDefault(); this.q?.toggleQuests(); return; }+ // Build menu (Task 07): B opens it / cancels an in-progress placement.+ if (k === 'b' && this.phase === 'world') { e.preventDefault(); this._toggleBuildMenu(); return; }+ // Escape also cancels build mode before any other surface.+ if (k === 'escape' && this._buildMode) { e.preventDefault(); this._exitBuildMode(); return; }// Hotbar number keys 1–6: select that slot (and ride a mount on it).if (this.phase === 'world' && k >= '1' && k <= '6') { e.preventDefault(); this._equipOrRide(+k - 1); return; }- if (k === 'escape') { this.q?.closeQuests(); this.q?.closeBank(); this.q?.closeNpc(); }+ if (k === 'escape') { this.q?.closeQuests(); this.q?.closeBank(); this.q?.closeNpc(); this.q?.closeBuild?.(); this.q?.closeShop?.(); }// Hotbar 1–6: equip that slot (server validates + patches activeSlot back).if (this.phase === 'world' && k >= '1' && k <= '6') { e.preventDefault(); this.net?.equip(parseInt(k, 10) - 1); return; }// Chat focus: C (or Enter) opens the chat input once in the world. The@@ -1503,8 +2352,14 @@ export class IsoGame {this.canvas.addEventListener('pointerdown', (e) => {this._dragging = true; this._lastPtr = { x: e.clientX, y: e.clientY };+ this._hoverPtr = { x: e.clientX, y: e.clientY }; // build ghost follows the press pointthis._downAt = performance.now(); this._dragMoved = 0;});+ // Right-click cancels build placement (the desktop counterpart to the banner's+ // Cancel button on touch). Only swallow the context menu while building.+ this.canvas.addEventListener('contextmenu', (e) => {+ if (this._buildMode) { e.preventDefault(); this._exitBuildMode(); }+ });window.addEventListener('pointerup', (e) => {const wasDragging = this._dragging;this._dragging = false;@@ -1516,6 +2371,9 @@ export class IsoGame {}});window.addEventListener('pointermove', (e) => {+ // Track the cursor always (even without a drag) so the build ghost can+ // follow it on desktop hover.+ this._hoverPtr = { x: e.clientX, y: e.clientY };if (!this._dragging) return;const dx = e.clientX - this._lastPtr.x, dy = e.clientY - this._lastPtr.y;this._lastPtr = { x: e.clientX, y: e.clientY };@@ -1599,6 +2457,7 @@ export class IsoGame {if (t.kind === 'tile') return { tx: t.tx, ty: t.ty };if (t.kind === 'node') { const v = this.nodeViews.get(t.id); if (!v || v.node.depleted) return null; return { tx: v.node.tx, ty: v.node.ty }; }if (t.kind === 'mob') { const v = this.mobViews.get(t.id); if (!v || v.mob.dead) return null; return { tx: v.mob.tx, ty: v.mob.ty }; }+ if (t.kind === 'player') { const v = this.players.get(t.id); if (!v || v.dead) return null; return { tx: v.tx, ty: v.ty }; }if (t.kind === 'npc') { const v = this.npcViews.get(t.id); if (!v) return null; return { tx: v.npc.tx, ty: v.npc.ty }; }return null;}@@ -1662,6 +2521,11 @@ export class IsoGame {if (!v || v.mob.dead) { this._target = null; return; }this._equipTool(ps, 'sword');this.net?.attack(t.id);+ } else if (t.kind === 'player') {+ const v = this.players.get(t.id);+ if (!v || v.dead) { this._target = null; return; }+ this._equipTool(ps, 'sword');+ this.net?.attack(t.id); // PvP — server validates realm/range/safe-zone}}@@ -1706,8 +2570,10 @@ export class IsoGame {offline: document.getElementById('kg-offline'),offlineMsg: document.getElementById('kg-offline-msg'),retryBtn: document.getElementById('kg-retry'),+ serversList: document.getElementById('kg-servers-list'),topbar: document.getElementById('kg-topbar'),realm: document.getElementById('kg-realm'),+ server: document.getElementById('kg-server'),online: document.getElementById('kg-online'),status: document.getElementById('kg-status'),toasts: document.getElementById('kg-toasts'),@@ -1724,10 +2590,12 @@ export class IsoGame {cookBtn: document.getElementById('kg-cook'),eatBtn: document.getElementById('kg-eat'),castBtn: document.getElementById('kg-cast'),+ pickupBtn: document.getElementById('kg-pickup'),chat: document.getElementById('kg-chat'),chatLog: document.getElementById('kg-chat-log'),chatForm: document.getElementById('kg-chat-form'),chatInput: document.getElementById('kg-chat-input'),+ chatHint: document.getElementById('kg-chat-hint'),chatMutedBtn: document.getElementById('kg-chat-muted-btn'),chatMutedN: document.getElementById('kg-chat-muted-n'),chatMutedList: document.getElementById('kg-chat-muted'),@@ -1748,6 +2616,10 @@ export class IsoGame {if (savedName) this.hud.nameInput.value = savedName;this.hud.nameInput.placeholder = 'guest-' + Math.random().toString(36).slice(2, 6);+ // World-instance picker (Task 23): render the live roster + populations and+ // remember the player's choice. Polling starts/stops with the start screen.+ this._initServerPicker();+const begin = () => {const name = (this.hud.nameInput.value || this.hud.nameInput.placeholder).trim().slice(0, 24);localStorage.setItem('cc-name', name);@@ -1774,6 +2646,8 @@ export class IsoGame {this.hud.eatBtn?.addEventListener('click', () => { if (this._eatRef) this.net?.consume(this._eatRef); });this.hud.dismountBtn?.addEventListener('click', () => this.net?.dismount());this.hud.castBtn?.addEventListener('click', () => this._attemptCast());+ // Pick up a structure I'm standing beside — the server action is /pickup.+ this.hud.pickupBtn?.addEventListener('click', () => this.net?.command('/pickup'));this._bindChat();this._setHudPhase('start');@@ -1782,6 +2656,9 @@ export class IsoGame {_setHudPhase(phase) {this.hud.start.hidden = phase !== 'start';this.hud.offline.hidden = phase !== 'offline';+ // Poll live server populations only while the picker is on screen.+ if (phase === 'start') this._startServerPolling();+ else this._stopServerPolling();this.hud.topbar.hidden = !(phase === 'world' || phase === 'connecting');this.hud.hint.hidden = phase !== 'world';// The contextual action bar only makes sense in-world; hide it elsewhere so@@ -1812,15 +2689,28 @@ export class IsoGame {// server command system, and mute players client-side. The panel is collapsed// (click-through) until focused so it never blocks the world.+ // Storage key for the mute list — scoped to the stable account id (Task 16) so+ // each account keeps its own block list, matching how keybindings persist.+ _mutedKey() {+ return 'kg-muted:' + (this._playerId() || '_');+ }+_loadMuted() {try {- const raw = JSON.parse(localStorage.getItem('kg-muted') || '[]');- return new Set(Array.isArray(raw) ? raw.filter((n) => typeof n === 'string') : []);+ const key = this._mutedKey();+ let raw = localStorage.getItem(key);+ // Migrate the pre-account global list (kg-muted) into this account once.+ if (raw == null) {+ const legacy = localStorage.getItem('kg-muted');+ if (legacy != null) { raw = legacy; localStorage.setItem(key, legacy); localStorage.removeItem('kg-muted'); }+ }+ const parsed = JSON.parse(raw || '[]');+ return new Set(Array.isArray(parsed) ? parsed.filter((n) => typeof n === 'string') : []);} catch { return new Set(); }}_saveMuted() {- try { localStorage.setItem('kg-muted', JSON.stringify([...this.muted])); } catch { /* storage may be unavailable */ }+ try { localStorage.setItem(this._mutedKey(), JSON.stringify([...this.muted])); } catch { /* storage may be unavailable */ }}_bindChat() {@@ -1834,16 +2724,149 @@ export class IsoGame {if (this.hud.chat?.contains(e.relatedTarget)) return;if (!this.hud.chatInput.value.trim()) this._closeChat();});+ // Slash-command autocomplete: refresh the hint list on every edit.+ this.hud.chatInput?.addEventListener('input', () => this._refreshCmdHint());this.hud.chatInput?.addEventListener('keydown', (e) => {- // Esc clears + closes; everything else stays in the field (the global- // keydown bails on _typing(), so movement keys never fire while chatting).- if (e.key === 'Escape') { e.preventDefault(); this.hud.chatInput.value = ''; this._closeChat(); }+ // Esc: first dismiss an open command hint, otherwise clear + close chat.+ if (e.key === 'Escape') {+ e.preventDefault();+ if (this._cmdHint) this._hideCmdHint();+ else { this.hud.chatInput.value = ''; this._closeChat(); }+ e.stopPropagation();+ return;+ }+ // When the hint is open, the arrow/Tab keys drive it instead of the field.+ if (this._cmdHint) {+ if (e.key === 'ArrowDown') { e.preventDefault(); this._moveCmdHint(1); e.stopPropagation(); return; }+ if (e.key === 'ArrowUp') { e.preventDefault(); this._moveCmdHint(-1); e.stopPropagation(); return; }+ if (e.key === 'Tab') { e.preventDefault(); this._completeCmdHint(); e.stopPropagation(); return; }+ // Enter on a highlighted suggestion completes it, then falls through to+ // the form submit so the command sends in a single keystroke.+ if (e.key === 'Enter' && this._cmdHint.active >= 0) {+ const c = this._cmdHint.items[this._cmdHint.active];+ if (c) this.hud.chatInput.value = '/' + c.name;+ this._hideCmdHint();+ }+ }+ // Everything else stays in the field (the global keydown bails on+ // _typing(), so movement keys never fire while chatting).e.stopPropagation();});this.hud.chatMutedBtn?.addEventListener('click', () => this._toggleMutedList());this._updateMutedCount();}+ // Slash-command manifest (Task 13) — the same registry that powers /help and the+ // server router, so the autocomplete can never list a command that doesn't exist.+ _onCommands(manifest) {+ this._cmds = Array.isArray(manifest)+ ? manifest+ .map((c) => ({+ name: String(c?.name || ''),+ args: String(c?.args || ''),+ desc: String(c?.desc || ''),+ aliases: Array.isArray(c?.aliases) ? c.aliases.map(String) : [],+ }))+ .filter((c) => c.name)+ : [];+ }++ // Recompute the hint list from the current input. Suggestions show only while+ // typing a command NAME — a leading '/' with no space yet. Once a space (args)+ // or a non-command line is typed, the hint hides.+ _refreshCmdHint() {+ const input = this.hud.chatInput;+ if (!input) return;+ const m = /^\/(\S*)$/.exec(input.value);+ if (!m || !this._cmds?.length) { this._hideCmdHint(); return; }+ const frag = m[1].toLowerCase();+ const matches = this._cmds+ .filter((c) => c.name.startsWith(frag) || c.aliases.some((a) => a.startsWith(frag)))+ .slice(0, 8);+ if (!matches.length) { this._hideCmdHint(); return; }+ // Keep the highlighted command across keystrokes when it's still a match, so+ // narrowing the list doesn't reset the user's selection out from under them.+ const prev = this._cmdHint?.active >= 0 ? this._cmdHint.items[this._cmdHint.active]?.name : null;+ const active = prev ? matches.findIndex((c) => c.name === prev) : -1;+ this._cmdHint = { items: matches, active };+ this._renderCmdHint();+ }++ _renderCmdHint() {+ const hint = this.hud.chatHint;+ const input = this.hud.chatInput;+ if (!hint || !this._cmdHint) return;+ hint.replaceChildren();+ this._cmdHint.items.forEach((c, i) => {+ const li = document.createElement('li');+ const on = i === this._cmdHint.active;+ li.className = 'kg-chat-hint-item' + (on ? ' kg-chat-hint-item--active' : '');+ li.id = 'kg-chat-hint-' + i;+ li.setAttribute('role', 'option');+ li.setAttribute('aria-selected', on ? 'true' : 'false');+ const sig = document.createElement('span');+ sig.className = 'kg-chat-hint-cmd';+ sig.textContent = '/' + c.name + (c.args ? ' ' + c.args : '');+ const desc = document.createElement('span');+ desc.className = 'kg-chat-hint-desc';+ desc.textContent = c.desc;+ li.append(sig, desc);+ // mousedown (before the input's blur) so a click completes + sends without+ // the panel collapsing first.+ li.addEventListener('mousedown', (e) => { e.preventDefault(); this._chooseCmdHint(i); });+ hint.appendChild(li);+ });+ hint.hidden = false;+ input?.setAttribute('aria-expanded', 'true');+ if (this._cmdHint.active >= 0) {+ input?.setAttribute('aria-activedescendant', 'kg-chat-hint-' + this._cmdHint.active);+ hint.children[this._cmdHint.active]?.scrollIntoView({ block: 'nearest' });+ } else {+ input?.removeAttribute('aria-activedescendant');+ }+ }++ _moveCmdHint(dir) {+ if (!this._cmdHint) return;+ const n = this._cmdHint.items.length;+ const cur = this._cmdHint.active;+ this._cmdHint.active = cur < 0 ? (dir > 0 ? 0 : n - 1) : (cur + dir + n) % n;+ this._renderCmdHint();+ }++ // Tab: fill the field with the (highlighted, else first) command. Append a space+ // when it takes args so the player keeps typing; refresh then hides or re-narrows.+ _completeCmdHint() {+ if (!this._cmdHint || !this.hud.chatInput) return;+ const idx = this._cmdHint.active >= 0 ? this._cmdHint.active : 0;+ const c = this._cmdHint.items[idx];+ if (!c) return;+ // Tab fills the chosen command in full. For an arg-taking command, append a+ // space and re-narrow so the player keeps typing; for a complete no-arg+ // command there's nothing left to suggest, so dismiss the hint.+ this.hud.chatInput.value = '/' + c.name + (c.args ? ' ' : '');+ if (c.args) this._refreshCmdHint();+ else this._hideCmdHint();+ }++ // Mouse pick: complete + send in one action.+ _chooseCmdHint(i) {+ const c = this._cmdHint?.items[i];+ if (!c || !this.hud.chatInput) return;+ this.hud.chatInput.value = '/' + c.name;+ this._hideCmdHint();+ this._sendChat();+ }++ _hideCmdHint() {+ this._cmdHint = null;+ if (this.hud.chatHint) { this.hud.chatHint.hidden = true; this.hud.chatHint.replaceChildren(); }+ if (this.hud.chatInput) {+ this.hud.chatInput.setAttribute('aria-expanded', 'false');+ this.hud.chatInput.removeAttribute('aria-activedescendant');+ }+ }+_openChat() {if (!this.hud.chat || this.phase !== 'world') return;this.keys.clear(); // drop held movement keys so the avatar doesn't walk while typing@@ -1858,6 +2881,7 @@ export class IsoGame {_closeChat(force) {this._closeMuteMenu();this._toggleMutedList(false);+ this._hideCmdHint();if (!this._chatOpen && !force) return;this._chatOpen = false;this.hud.chat?.classList.remove('kg-chat--open');@@ -1869,6 +2893,7 @@ export class IsoGame {if (!input) return;const text = input.value.trim();input.value = '';+ this._hideCmdHint();if (!text) { this._closeChat(); return; }// Server is authoritative: it sanitizes, rate-limits, routes `/commands`, and// echoes accepted messages back to everyone (us included) as 'chat' events.@@ -2079,6 +3104,8 @@ export class IsoGame {this._updateLabels();this._updateNpcLabels();this._updateTombLabels();+ this._updateStructures(now);+ this._updateBuildGhost();this._updateDeathOverlay();this._updateActions();this._tickCast(now);@@ -2205,6 +3232,9 @@ export class IsoGame {this.players.clear();for (const [, tv] of this.tombViews) { this.objectGroup.remove(tv.group); tv.label.remove(); }this.tombViews.clear();+ for (const [, sv] of this.structViews) this.objectGroup.remove(sv.group);+ this.structViews.clear();+ this._exitBuildMode();this._disposeNpcs();this.q?.destroy();this._clearCast();diff --git a/src/game/play-auth.js b/src/game/play-auth.jsnew file mode 100644index 000000000..c27c64c96--- /dev/null+++ b/src/game/play-auth.js@@ -0,0 +1,187 @@+// Play auth — the browser half of wallet-first sign-in for /play.+//+// The wallet address IS the account: no email, no password, no seed phrase ever+// asked for. The flow is, all real:+// 1. Fetch the gate config + a fresh server nonce (GET /api/play/nonce).+// 2. Connect a Solana wallet (Phantom/Backpack/Solflare, or the Seeker TWA's+// on-device wallet) and read its public key.+// 3. Sign a human-readable message embedding the nonce — proves key ownership,+// moves nothing on-chain.+// 4. POST { address, signature, nonce } to /api/play/verify, which checks the+// signature server-side, reads the wallet's game-token balance from real+// RPC, and (if it clears the floor) returns a short-lived play pass.+//+// The pass + verified wallet are cached in sessionStorage so a reload inside the+// pass's lifetime doesn't re-prompt the wallet. All on-chain truth is computed+// server-side; this module only orchestrates the wallet interaction.++// Side-effect import: on a Solana Mobile (Seeker/Saga) device running inside our+// TWA, this installs an MWA-backed wallet at window.solana that signs through the+// Seed Vault. A no-op on every other platform.+import '../../solana-mobile/src/index.js';++const NONCE_URL = '/api/play/nonce';+const VERIFY_URL = '/api/play/verify';+const STORE_KEY = 'cc-play-pass';+// Refresh a little before the server's 10-min pass TTL so a reconnect never+// races expiry; the game server sweeps expired passes every minute.+const REFRESH_SKEW_MS = 90_000;++/** A coded error the gate UI can route on (err.code) without string matching. */+export class PlayAuthError extends Error {+ constructor(code, message) {+ super(message);+ this.code = code;+ this.name = 'PlayAuthError';+ }+}++/** Detect an injected Solana wallet, preferring Phantom, then Backpack/Solflare,+ * and the Seeker TWA wallet (window.solana.isThreeWs). */+export function detectProvider() {+ if (typeof window === 'undefined') return null;+ const w = window;+ if (w.phantom?.solana?.isPhantom) return w.phantom.solana;+ if (w.solana?.isPhantom || w.solana?.isThreeWs) return w.solana;+ if (w.backpack?.solana) return w.backpack.solana;+ if (w.solflare?.isSolflare) return w.solflare;+ if (w.solana) return w.solana; // generic injected provider+ return null;+}++/** True when any Solana wallet is installed/injected. */+export function hasWallet() {+ return !!detectProvider();+}++/**+ * Fetch the gate configuration and a fresh nonce.+ * @returns {Promise<{ nonce: string, expiresAt: string, required: boolean, mint: string, minBalance: number }>}+ */+export async function fetchPlayConfig() {+ const res = await fetch(NONCE_URL, { credentials: 'include', headers: { accept: 'application/json' } });+ const body = await res.json().catch(() => null);+ if (!res.ok || !body?.data?.nonce) {+ throw new PlayAuthError('nonce_unavailable', body?.error_description || 'Could not start sign-in. Try again.');+ }+ return body.data;+}++// The message the wallet signs. MUST stay byte-identical to buildPlayMessage in+// api/play/verify.js — the server reconstructs and verifies the signature over+// these exact bytes, so any drift breaks every login.+function buildPlayMessage(address, nonce) {+ return [+ 'three.ws wants you to sign in with your Solana account:',+ address,+ '',+ 'Sign in to play three.ws. This proves you own this wallet and will not move any funds or tokens.',+ '',+ `Nonce: ${nonce}`,+ ].join('\n');+}++/**+ * Run the full connect → sign → verify flow against a server-issued nonce.+ *+ * @param {object} opts+ * @param {string} opts.nonce nonce from fetchPlayConfig()+ * @param {(stage: string) => void} [opts.onStage] 'connecting' | 'signing' | 'verifying'+ * @returns {Promise<object>} the /verify result — { ok: true, wallet, balance,+ * playPass, … } when the wallet clears the floor, or { ok: false,+ * reason: 'balance_too_low', wallet, balance, minBalance, acquireUrl, … }.+ * @throws {PlayAuthError} no_wallet | rejected | nonce_invalid | bad_signature |+ * balance_unavailable | verify_failed+ */+export async function signInToPlay({ nonce, onStage = () => {} } = {}) {+ const provider = detectProvider();+ if (!provider?.connect) {+ throw new PlayAuthError('no_wallet', 'No Solana wallet found. Install Phantom to play.');+ }++ onStage('connecting');+ let address;+ try {+ const resp = await provider.connect();+ address = (resp?.publicKey || provider.publicKey)?.toString();+ } catch (err) {+ if (err?.code === 4001 || /reject|cancel|denied/i.test(String(err?.message))) {+ throw new PlayAuthError('rejected', 'Wallet connection was cancelled.');+ }+ throw new PlayAuthError('rejected', err?.message || 'Could not connect your wallet.');+ }+ if (!address) throw new PlayAuthError('rejected', 'Could not read your wallet address.');++ onStage('signing');+ const message = buildPlayMessage(address, nonce);+ let signature;+ try {+ const encoded = new TextEncoder().encode(message);+ const signed = await provider.signMessage(encoded, 'utf8');+ const sigBytes = signed?.signature ?? signed;+ const bs58 = (await import('bs58')).default;+ signature = bs58.encode(sigBytes);+ } catch (err) {+ if (err?.code === 4001 || /reject|cancel|denied/i.test(String(err?.message))) {+ throw new PlayAuthError('rejected', 'You declined the sign-in signature.');+ }+ throw new PlayAuthError('rejected', err?.message || 'Could not sign the sign-in message.');+ }++ onStage('verifying');+ let res, body;+ try {+ res = await fetch(VERIFY_URL, {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ address, signature, nonce }),+ });+ body = await res.json().catch(() => null);+ } catch {+ throw new PlayAuthError('verify_failed', 'Network error during sign-in. Check your connection and retry.');+ }+ if (!res.ok) {+ const code = body?.error || 'verify_failed';+ throw new PlayAuthError(code, body?.error_description || 'Sign-in verification failed.');+ }+ const data = body?.data;+ if (!data) throw new PlayAuthError('verify_failed', 'Sign-in returned an unexpected response.');++ if (data.ok && data.playPass) storePass(data);+ return data;+}++// ── Session cache ────────────────────────────────────────────────────────────++/** Persist a granted pass for this tab so a reload inside its TTL doesn't+ * re-prompt the wallet. */+export function storePass(data) {+ try {+ sessionStorage.setItem(+ STORE_KEY,+ JSON.stringify({ wallet: data.wallet, playPass: data.playPass, mint: data.mint, balance: data.balance, symbol: data.symbol, expiresAt: data.expiresAt }),+ );+ } catch { /* private mode / quota — sign-in just re-runs */ }+}++/** Return a cached, still-fresh pass, or null. */+export function loadStoredPass() {+ try {+ const raw = sessionStorage.getItem(STORE_KEY);+ if (!raw) return null;+ const p = JSON.parse(raw);+ if (!p?.playPass || !p?.expiresAt) return null;+ if (new Date(p.expiresAt).getTime() - Date.now() <= REFRESH_SKEW_MS) {+ clearStoredPass();+ return null;+ }+ return p;+ } catch {+ return null;+ }+}++export function clearStoredPass() {+ try { sessionStorage.removeItem(STORE_KEY); } catch { /* ignore */ }+}diff --git a/src/game/play-gate.js b/src/game/play-gate.jsnew file mode 100644index 000000000..93708b761--- /dev/null+++ b/src/game/play-gate.js@@ -0,0 +1,247 @@+// Play gate — the wallet sign-in screen that stands in front of /play.+//+// When the platform has pinned a game token, no one reaches the lobby without+// connecting a Solana wallet, signing a server nonce to prove ownership, and+// holding ≥ the required balance of the token. This module owns that screen and+// every state it can be in: checking, wallet-not-installed, ready-to-connect,+// signing, verifying, balance-too-low (with a path to acquire the token), and+// error — each honest and actionable, none a dead end. It resolves only once the+// wallet clears the gate (or immediately, with required:false, when no token is+// pinned and /play is open).++import { fetchPlayConfig, signInToPlay, loadStoredPass, hasWallet, PlayAuthError } from './play-auth.js';++const PHANTOM_INSTALL = 'https://phantom.app/download';++// Monochrome line icons (stroke = currentColor) — the gate's design language is+// strictly greyscale, so no emoji.+const SVG = {+ wallet: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 9h18"/><circle cx="16.5" cy="13" r="1.2"/></svg>',+ key: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="4.5"/><path d="M11.2 11.2 20 20"/><path d="M16.5 16.5 19 14"/></svg>',+ ticket: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 7h16v3a2 2 0 0 0 0 4v3H4v-3a2 2 0 0 0 0-4z"/><path d="M14 7v10" stroke-dasharray="1.5 2"/></svg>',+ warn: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 4 2.5 20h19z"/><path d="M12 10v4"/><circle cx="12" cy="17" r="0.6" fill="currentColor"/></svg>',+};++/**+ * Ensure the player has cleared the token gate before the lobby opens.+ * @returns {Promise<{ required: boolean, wallet?: string, playPass?: string, balance?: number, symbol?: string }>}+ */+export function ensurePlayAccess() {+ return new Gate().run();+}++class Gate {+ constructor() {+ this.root = null;+ this.cfg = null; // { nonce, mint, minBalance, required }+ this._resolve = null;+ }++ run() {+ return new Promise((resolve) => {+ this._resolve = resolve;+ this._start();+ });+ }++ async _start() {+ // Probe the gate. If we can't reach it we don't know whether sign-in is+ // required, so show a retryable error rather than guessing either way.+ this._mount();+ this._render({ state: 'checking' });+ let cfg;+ try {+ cfg = await fetchPlayConfig();+ } catch (err) {+ this._render({ state: 'error', error: err?.message || 'Could not reach sign-in.', retry: () => this._start() });+ return;+ }+ this.cfg = cfg;++ // No token pinned → /play is open. Tear the gate down and let everyone in.+ if (!cfg.required) {+ this._finish({ required: false });+ return;+ }++ // A still-fresh pass from earlier this session skips the wallet prompt.+ const cached = loadStoredPass();+ if (cached && cached.mint === cfg.mint) {+ this._finish({ required: true, wallet: cached.wallet, playPass: cached.playPass, balance: cached.balance, symbol: cached.symbol });+ return;+ }++ this._renderConnect();+ }++ _renderConnect(error = '') {+ if (!hasWallet()) {+ this._render({ state: 'no_wallet' });+ return;+ }+ this._render({ state: 'connect', error });+ }++ async _attempt() {+ // Each attempt gets a fresh nonce — they're short-lived and single-use in+ // spirit, so never reuse one across a retry.+ this._render({ state: 'working', stage: 'connecting' });+ let nonce = this.cfg?.nonce;+ try {+ const cfg = await fetchPlayConfig();+ this.cfg = cfg;+ nonce = cfg.nonce;+ } catch {+ /* fall back to the nonce we already have; verify will reject if stale */+ }++ try {+ const res = await signInToPlay({ nonce, onStage: (stage) => this._render({ state: 'working', stage }) });+ if (res.ok && res.playPass) {+ this._render({ state: 'granted', symbol: res.symbol, balance: res.balance });+ setTimeout(() => {+ this._finish({ required: true, wallet: res.wallet, playPass: res.playPass, balance: res.balance, symbol: res.symbol });+ }, 700);+ return;+ }+ // Verified ownership, but short of the floor.+ this._render({ state: 'low', data: res });+ } catch (err) {+ const code = err instanceof PlayAuthError ? err.code : 'error';+ if (code === 'no_wallet') { this._render({ state: 'no_wallet' }); return; }+ if (code === 'rejected') { this._renderConnect(err.message); return; }+ if (code === 'balance_unavailable') {+ this._render({ state: 'error', error: 'Couldn’t read your on-chain balance right now. Please try again.', retry: () => this._attempt() });+ return;+ }+ // nonce_invalid / bad_signature / verify_failed / anything else.+ this._render({ state: 'error', error: err?.message || 'Sign-in failed. Please try again.', retry: () => this._attempt() });+ }+ }++ // ── DOM ────────────────────────────────────────────────────────────────────++ _mount() {+ if (this.root) return;+ const root = document.createElement('div');+ root.className = 'pg-root';+ root.setAttribute('role', 'dialog');+ root.setAttribute('aria-modal', 'true');+ root.setAttribute('aria-label', 'Sign in to play');+ document.body.appendChild(root);+ this.root = root;+ }++ _finish(result) {+ if (this.root) {+ this.root.classList.add('pg-leaving');+ const el = this.root;+ setTimeout(() => el.remove(), 320);+ this.root = null;+ }+ this._resolve?.(result);+ this._resolve = null;+ }++ _render(view) {+ if (!this.root) return;+ this.root.innerHTML = this._html(view);+ // Wire the freshly-rendered buttons.+ const q = (sel) => this.root.querySelector(sel);+ q('[data-act="connect"]')?.addEventListener('click', () => this._attempt());+ q('[data-act="recheck"]')?.addEventListener('click', () => this._attempt());+ q('[data-act="retry"]')?.addEventListener('click', () => view.retry?.());+ const acquire = q('[data-act="acquire"]');+ if (acquire) acquire.addEventListener('click', () => window.open(acquire.dataset.url, '_blank', 'noopener'));+ // Move focus to the primary action for keyboard users.+ (q('.pg-btn-primary') || q('.pg-btn'))?.focus();+ }++ _html(view) {+ const card = (inner) => `+ <div class="pg-backdrop"></div>+ <div class="pg-card">+ <div class="pg-brand"><img src="/three.svg" alt="" width="30" height="30" /><span>COIN COMMUNITIES</span></div>+ ${inner}+ </div>`;++ const min = this.cfg?.minBalance ?? 1;+ const tokenName = (sym) => sym || this.cfg?.symbol || 'the game token';++ switch (view.state) {+ case 'checking':+ return card(`+ <div class="pg-spinner" aria-hidden="true"></div>+ <h1 class="pg-title">Checking access…</h1>+ <p class="pg-sub">One moment while we set up sign-in.</p>`);++ case 'no_wallet':+ return card(`+ <div class="pg-icon" aria-hidden="true">${SVG.wallet}</div>+ <h1 class="pg-title">Connect a Solana wallet</h1>+ <p class="pg-sub">Your wallet is your account here — no email, no password. Install a Solana wallet to sign in and play.</p>+ <a class="pg-btn pg-btn-primary" href="${PHANTOM_INSTALL}" target="_blank" rel="noopener">Get Phantom</a>+ <button class="pg-btn pg-btn-ghost" data-act="retry">I’ve installed one — retry</button>`);++ case 'connect':+ return card(`+ <div class="pg-icon" aria-hidden="true">${SVG.key}</div>+ <h1 class="pg-title">Sign in to play</h1>+ <p class="pg-sub">Connect your Solana wallet and sign a message to prove it’s yours. You’ll need to hold at least <strong>${min} ${tokenName()}</strong> to enter. This never moves your funds.</p>+ ${view.error ? `<p class="pg-error" role="alert">${esc(view.error)}</p>` : ''}+ <button class="pg-btn pg-btn-primary" data-act="connect">Connect wallet</button>+ <p class="pg-fine">We’ll never ask for your seed phrase.</p>`);++ case 'working': {+ const label = { connecting: 'Connecting your wallet…', signing: 'Approve the signature in your wallet…', verifying: 'Verifying your balance on-chain…' }[view.stage] || 'Working…';+ return card(`+ <div class="pg-spinner" aria-hidden="true"></div>+ <h1 class="pg-title">${esc(label)}</h1>+ <p class="pg-sub">${view.stage === 'signing' ? 'Check your wallet for a signature request.' : 'This only takes a moment.'}</p>`);+ }++ case 'low': {+ const d = view.data || {};+ const bal = fmt(d.balance ?? 0);+ const need = fmt(d.minBalance ?? min);+ const sym = tokenName(d.symbol);+ return card(`+ <div class="pg-icon" aria-hidden="true">${SVG.ticket}</div>+ <h1 class="pg-title">You need a little more</h1>+ <p class="pg-sub">Entry requires <strong>${need} ${esc(sym)}</strong>. Your wallet holds <strong>${bal} ${esc(sym)}</strong>. Top up, then recheck — no need to sign again.</p>+ <div class="pg-balance">+ <div><span class="pg-balance-k">You hold</span><span class="pg-balance-v">${bal}</span></div>+ <div class="pg-balance-sep">→</div>+ <div><span class="pg-balance-k">Need</span><span class="pg-balance-v pg-balance-need">${need}</span></div>+ </div>+ ${d.acquireUrl ? `<button class="pg-btn pg-btn-primary" data-act="acquire" data-url="${esc(d.acquireUrl)}">Get ${esc(sym)}</button>` : ''}+ <button class="pg-btn pg-btn-ghost" data-act="recheck">Recheck balance</button>`);+ }++ case 'granted':+ return card(`+ <div class="pg-check" aria-hidden="true">✓</div>+ <h1 class="pg-title">You’re in</h1>+ <p class="pg-sub">Wallet verified${view.balance != null ? ` — ${fmt(view.balance)} ${esc(tokenName(view.symbol))}` : ''}. Entering the world…</p>`);++ case 'error':+ default:+ return card(`+ <div class="pg-icon" aria-hidden="true">${SVG.warn}</div>+ <h1 class="pg-title">Something went wrong</h1>+ <p class="pg-sub" role="alert">${esc(view.error || 'Please try again.')}</p>+ <button class="pg-btn pg-btn-primary" data-act="retry">Try again</button>`);+ }+ }+}++function esc(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}++function fmt(n) {+ const v = Number(n) || 0;+ if (v >= 1000) return v.toLocaleString(undefined, { maximumFractionDigits: 0 });+ if (v >= 1) return v.toLocaleString(undefined, { maximumFractionDigits: 2 });+ return v.toLocaleString(undefined, { maximumFractionDigits: 6 });+}diff --git a/src/game/spin-wheel-ui.js b/src/game/spin-wheel-ui.jsnew file mode 100644index 000000000..41c6f6247--- /dev/null+++ b/src/game/spin-wheel-ui.js@@ -0,0 +1,468 @@+// Wheel of Fortune — the in-world spinner UI for /play (Task 19).+//+// 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:+// • 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+// 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.++import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';++const NETWORK = 'mainnet';+const SEG_COLORS = {+ gold: { fill: '#f5c542', edge: '#caa033', text: '#3a2c00' },+ wood: { fill: '#8a5a32', edge: '#6e4626', text: '#fbe9d4' },+ stone: { fill: '#8b94a4', edge: '#6c7585', text: '#0d1420' },+ coal: { fill: '#39404e', edge: '#262b35', text: '#dfe6f2' },+};+// Alternating tint so adjacent same-kind wedges stay distinct on the wheel.+const ALT = 'rgba(0,0,0,0.10)';++function el(tag, props = {}, kids = []) {+ 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 === 'html') n.innerHTML = v;+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);+ else if (v != null && v !== false) n.setAttribute(k, v === true ? '' : v);+ }+ for (const kid of [].concat(kids)) if (kid != null && kid !== false) n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);+ return n;+}++const kindOf = (seg) => (seg.kind === 'gold' ? 'gold' : seg.item || 'stone');++/**+ * Open the Wheel of Fortune. Idempotent — a second call focuses the existing+ * modal. Returns a controller with `.close()`.+ * @param {{ net: object, onClose?: () => void }} opts+ */+export function openSpinWheel(opts) {+ if (_open) { _open.focus(); return _open; }+ _open = new SpinWheel(opts);+ return _open;+}+let _open = null;++class SpinWheel {+ constructor({ net, onClose }) {+ this.net = net;+ this.onClose = onClose;+ this.segments = null;+ this.info = null;+ this.phase = 'loading'; // loading | ready | spinning | paying | result | error+ this.busy = false;+ this.rotation = 0; // current wheel rotation (radians)+ this._raf = null;+ this._countdownTimer = null;+ this._prep = null; // the live paid-spin prep ({tx, quote, ...})+ this._settleAttempts = 0;++ this._build();+ // The UI owns its own server subscriptions so the scene just opens/closes it.+ this._offs = [+ net.on('spinInfo', (m) => this._onInfo(m)),+ net.on('spinPrep', (m) => this._onPrep(m)),+ net.on('spinResult', (m) => this._onResult(m)),+ net.on('spinDenied', (m) => this._onDenied(m)),+ ];+ net.spinInfo();+ this._drawWheel();+ }++ // ----------------------------------------------------------------- view+ _build() {+ this.overlay = el('div', { class: 'kg-spin-overlay', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Wheel of Fortune' });+ this.overlay.addEventListener('click', (e) => { if (e.target === this.overlay) this.close(); });++ this.canvas = el('canvas', { class: 'kg-spin-canvas', width: '640', height: '640' });+ this.pointer = el('div', { class: 'kg-spin-pointer', 'aria-hidden': 'true' });+ this.hub = el('div', { class: 'kg-spin-hub', 'aria-hidden': 'true', text: '★' });+ const wheelWrap = el('div', { class: 'kg-spin-wheelwrap' }, [this.canvas, this.pointer, this.hub]);++ this.resultLine = el('div', { class: 'kg-spin-result', 'aria-live': 'polite' });++ this.freeBtn = el('button', { class: 'kg-spin-btn kg-spin-free', type: 'button', onclick: () => this._free() }, 'Free spin');+ this.freeSub = el('div', { class: 'kg-spin-sub' });+ const freeBlock = el('div', { class: 'kg-spin-action' }, [this.freeBtn, this.freeSub]);++ this.paidBtn = el('button', { class: 'kg-spin-btn kg-spin-paid', type: 'button', onclick: () => this._paid() }, 'Paid spin');+ this.paidSub = el('div', { class: 'kg-spin-sub' });+ const paidBlock = el('div', { class: 'kg-spin-action' }, [this.paidBtn, this.paidSub]);++ this.actions = el('div', { class: 'kg-spin-actions' }, [freeBlock, paidBlock]);++ this.status = el('div', { class: 'kg-spin-status' });+ this.gate = el('div', { class: 'kg-spin-gate', hidden: true });+ this.legend = el('div', { class: 'kg-spin-legend' });++ const close = el('button', { class: 'kg-spin-close', type: 'button', 'aria-label': 'Close', onclick: () => this.close() }, '✕');+ const head = el('div', { class: 'kg-spin-head' }, [+ el('div', { class: 'kg-spin-title' }, ["Wheel of Fortune", el('span', { class: 'kg-spin-sub2', text: "Fortune's Folly · Mainland" })]),+ close,+ ]);++ this.card = el('div', { class: 'kg-spin-card' }, [head, wheelWrap, this.resultLine, this.gate, this.actions, this.status, this.legend]);+ this.overlay.appendChild(this.card);+ document.body.appendChild(this.overlay);+ this._setBusy(true, 'Loading the wheel…');+ this._onKey = (e) => { if (e.key === 'Escape') this.close(); };+ window.addEventListener('keydown', this._onKey);+ }++ focus() { this.card?.classList.remove('kg-spin-flash'); requestAnimationFrame(() => this.card?.classList.add('kg-spin-flash')); }++ // ----------------------------------------------------------- server in+ _onInfo(m) {+ this.info = m;+ this._infoAt = Date.now(); // anchor the local clock to the server's `now`+ this.segments = Array.isArray(m.segments) ? m.segments : [];+ this._renderLegend();+ this._drawWheel();+ if (this.phase === 'loading') this.phase = 'ready';+ this._sync();+ this._startCountdown();+ }++ _onPrep(m) {+ if (this.phase !== 'paying') return; // a stale prep from a cancelled flow+ this._prep = m;+ this._runWalletPayment(m).catch((err) => this._payError(err));+ }++ _onResult(m) {+ // Land the wheel on the server's chosen segment, then reveal the prize.+ if (m.mode === 'free' && Number.isFinite(m.nextFreeSpinAt) && this.info) this.info.nextFreeSpinAt = m.nextFreeSpinAt;+ this._pendingResult = m;+ this._animateTo(m.index, () => this._reveal(m));+ }++ _onDenied(m) {+ if (m && Number.isFinite(m.nextFreeSpinAt) && this.info) this.info.nextFreeSpinAt = m.nextFreeSpinAt;+ if (m && Number.isFinite(m.avgLevel) && this.info) { this.info.avgLevel = m.avgLevel; this.info.eligible = m.avgLevel >= m.minLevel; }+ this.busy = false;+ this._stopSpin();+ this.phase = 'ready';+ this._prep = null;+ this._status(this._denyText(m), 'err');+ this._sync();+ }++ _denyText(m) {+ const min = m?.minLevel ?? this.info?.minLevel ?? 5;+ switch (m?.reason) {+ case 'level': return `You need an average skill level of ${min} to spin. You're at ${m?.avgLevel ?? this.info?.avgLevel ?? 0}. Train your skills and come back.`;+ case 'not_at_wheel': return 'Step up to the wheel to spin.';+ case 'no_wheel': return 'There is no wheel in this realm.';+ case 'cooldown': return 'Your free spin isn’t ready yet.';+ case 'token_unavailable': return 'Paid spins are unavailable right now.';+ case 'no_wallet': return 'Connect a Solana wallet to buy a spin.';+ case 'price_unavailable': return 'Live token price unavailable — try again in a moment.';+ case 'build_failed': return 'Could not prepare the payment. Try again.';+ case 'no_signature': return 'No transaction signature received.';+ case 'already_settled': return 'That payment was already used for a spin.';+ case 'not_found': return 'Payment not confirmed on-chain yet — give it a moment and try again.';+ case 'underpaid': return 'The payment amount didn’t match the quote. No spin was taken.';+ case 'quote_expired': return 'Your quote expired before the payment confirmed. Try again.';+ default: return 'The spin couldn’t be completed.';+ }+ }++ // --------------------------------------------------------------- spins+ _free() {+ if (this.busy || !this._levelOk()) return;+ const now = this.info?.now ?? Date.now();+ const next = this.info?.nextFreeSpinAt ?? 0;+ if (now < next) return; // not ready — button is disabled, but guard anyway+ this.busy = true;+ this.phase = 'spinning';+ this.resultLine.textContent = '';+ this._status('Rolling…', '');+ this._sync();+ this._startSpin();+ this.net.spinFree();+ }++ async _paid() {+ if (this.busy || !this._levelOk() || !this.info?.paidAvailable) return;+ const wallet = detectSolanaWallet();+ if (!wallet) { this._status('No Solana wallet found. Install Phantom (or Backpack/Solflare) to buy a spin.', 'err'); return; }+ this.busy = true;+ this.phase = 'paying';+ this._prep = null;+ this._settleAttempts = 0;+ this.resultLine.textContent = '';+ this._status('Preparing your payment…', '');+ this._sync();+ this.net.spinPaidPrep();+ }++ async _runWalletPayment(prep) {+ const wallet = detectSolanaWallet();+ if (!wallet) throw Object.assign(new Error('No Solana wallet found.'), { friendly: true });+ this._status('Approve the $3 spin in your wallet…', '');+ const { Transaction, Connection } = await import('@solana/web3.js');+ const bytes = Uint8Array.from(atob(prep.tx), (c) => c.charCodeAt(0));+ const tx = Transaction.from(bytes);+ const signed = await wallet.signTransaction(tx);++ this._status('Submitting payment on-chain…', '');+ const conn = new Connection(SOLANA_RPC[NETWORK], 'confirmed');+ const sig = await conn.sendRawTransaction(signed.serialize(), { skipPreflight: false, maxRetries: 3 });+ this._sig = sig;++ const url = solanaTxExplorerUrl(NETWORK, sig);+ this._statusNode(el('span', {}, ['Confirming payment — ', el('a', { href: url, target: '_blank', rel: 'noopener', text: 'view ↗' }), '…']), 'ok');+ await this._confirm(conn, sig);++ // Hand the signature to the server: it verifies the burn + treasury legs+ // on-chain before rolling. Start the wheel spinning for feedback.+ this.phase = 'spinning';+ this._startSpin();+ this._status('Verifying payment & rolling…', '');+ this._settleAttempts = 1;+ this.net.spinPaidSettle(prep.quote, sig);+ }++ // Poll signature status over HTTP (no WS — the public RPC refuses subscriptions).+ async _confirm(conn, sig, timeoutMs = 35_000) {+ const start = Date.now();+ while (Date.now() - start < timeoutMs) {+ try {+ const { value } = await conn.getSignatureStatuses([sig]);+ const st = value?.[0];+ if (st?.err) throw Object.assign(new Error('Payment failed on-chain.'), { friendly: true });+ if (st?.confirmationStatus === 'confirmed' || st?.confirmationStatus === 'finalized') return;+ } catch (e) {+ if (e.friendly) throw e;+ }+ await new Promise((r) => setTimeout(r, 1500));+ }+ // Timed out waiting — let the server try anyway; it may already see it.+ }++ _payError(err) {+ this.busy = false;+ this._stopSpin();+ this.phase = 'ready';+ this._prep = null;+ const msg = err?.message || 'Payment failed.';+ const friendly = /reject|denied|cancel|user/i.test(msg) ? 'Cancelled in wallet.' : msg;+ this._status(friendly, 'err');+ this._sync();+ }++ // --------------------------------------------------------------- result+ _reveal(m) {+ this.busy = false;+ this.phase = 'result';+ this._prep = null;+ const seg = this.segments?.[m.index];+ const label = m.label || seg?.label || 'a prize';+ let line = `You won ${label}!`;+ if (m.overflow > 0) line += ` (${m.overflow} waiting in a bag at your feet — your pack was full)`;+ this.resultLine.textContent = line;+ this.resultLine.dataset.kind = seg ? kindOf(seg) : 'stone';+ this._status(m.mode === 'paid' ? 'Paid spin settled on-chain.' : 'Free spin used.', 'ok');+ if (m.mode === 'free') this._startCountdown();+ this._sync();+ }++ // --------------------------------------------------------------- canvas+ _drawWheel() {+ const c = this.canvas;+ const ctx = c.getContext('2d');+ const W = c.width, R = W / 2, cx = R, cy = R, rad = R - 14;+ ctx.clearRect(0, 0, W, W);+ const segs = this.segments && this.segments.length ? this.segments : new Array(20).fill({ kind: 'item', item: 'stone', label: '' });+ const n = segs.length;+ const seg = (Math.PI * 2) / n;+ ctx.save();+ ctx.translate(cx, cy);+ ctx.rotate(this.rotation);+ for (let i = 0; i < n; i++) {+ const a0 = -Math.PI / 2 + (i - 0.5) * seg;+ const a1 = -Math.PI / 2 + (i + 0.5) * seg;+ const k = kindOf(segs[i]);+ const col = SEG_COLORS[k] || SEG_COLORS.stone;+ ctx.beginPath();+ ctx.moveTo(0, 0);+ ctx.arc(0, 0, rad, a0, a1);+ ctx.closePath();+ ctx.fillStyle = col.fill;+ ctx.fill();+ if (i % 2) { ctx.fillStyle = ALT; ctx.fill(); }+ ctx.lineWidth = 2; ctx.strokeStyle = col.edge; ctx.stroke();+ // Label: the amount, drawn along the wedge centre.+ const mid = -Math.PI / 2 + i * seg;+ ctx.save();+ ctx.rotate(mid);+ ctx.translate(rad * 0.66, 0);+ ctx.rotate(Math.PI / 2);+ ctx.fillStyle = col.text;+ ctx.font = '600 22px ui-sans-serif, system-ui, sans-serif';+ ctx.textAlign = 'center'; ctx.textBaseline = 'middle';+ const amt = segs[i].kind === 'gold' ? String(segs[i].gold ?? '') : String(segs[i].qty ?? '');+ ctx.fillText(amt, 0, -8);+ ctx.font = '600 12px ui-sans-serif, system-ui, sans-serif';+ ctx.fillText((k === 'gold' ? 'GOLD' : k.toUpperCase()), 0, 12);+ ctx.restore();+ }+ ctx.restore();+ // Outer rim.+ ctx.beginPath(); ctx.arc(cx, cy, rad + 2, 0, Math.PI * 2);+ ctx.lineWidth = 6; ctx.strokeStyle = 'rgba(255,255,255,0.14)'; ctx.stroke();+ }++ _startSpin() {+ this._stopSpin();+ this._spinVel = 0.45; // rad/frame while waiting for the server outcome+ const tick = () => {+ this.rotation = (this.rotation + this._spinVel) % (Math.PI * 2);+ this._drawWheel();+ this._raf = requestAnimationFrame(tick);+ };+ this._raf = requestAnimationFrame(tick);+ }++ _stopSpin() {+ if (this._raf) { cancelAnimationFrame(this._raf); this._raf = null; }+ }++ // Ease the wheel to a stop with segment `index` under the top pointer.+ _animateTo(index, done) {+ this._stopSpin();+ const n = this.segments?.length || 20;+ const seg = (Math.PI * 2) / n;+ const TAU = Math.PI * 2;+ const cur = ((this.rotation % TAU) + TAU) % TAU;+ // Target rotation (mod TAU) that puts segment `index` centre at the top.+ const targetMod = ((-index * seg) % TAU + TAU) % TAU;+ const spins = 5; // full turns of flourish before landing+ const delta = spins * TAU + ((targetMod - cur + TAU) % TAU);+ const from = this.rotation;+ const dur = 4200;+ const t0 = performance.now();+ const ease = (t) => 1 - Math.pow(1 - t, 3); // cubic ease-out+ const step = (now) => {+ const t = Math.min(1, (now - t0) / dur);+ this.rotation = from + delta * ease(t);+ this._drawWheel();+ if (t < 1) { this._raf = requestAnimationFrame(step); }+ else { this._raf = null; this.rotation %= TAU; done && done(); }+ };+ this._raf = requestAnimationFrame(step);+ }++ // -------------------------------------------------------------- chrome+ _renderLegend() {+ if (!this.segments) return;+ const order = ['gold', 'wood', 'stone', 'coal'];+ const odds = {};+ for (const s of this.segments) {+ const k = kindOf(s);+ odds[k] = (odds[k] || 0) + (s.oddsPct || 0);+ }+ const labels = { gold: 'Gold', wood: 'Wood', stone: 'Stone', coal: 'Coal' };+ this.legend.replaceChildren(+ el('span', { class: 'kg-spin-legend-h', text: 'Odds' }),+ ...order.filter((k) => odds[k] != null).map((k) =>+ el('span', { class: 'kg-spin-chip', 'data-kind': k }, [+ el('i', { class: 'kg-spin-dot', style: `background:${(SEG_COLORS[k] || SEG_COLORS.stone).fill}` }),+ `${labels[k]} ${Math.round(odds[k])}%`,+ ])),+ );+ }++ _startCountdown() {+ if (this._countdownTimer) clearInterval(this._countdownTimer);+ const update = () => this._syncFree();+ update();+ this._countdownTimer = setInterval(update, 1000);+ }++ _levelOk() { return !!this.info?.eligible; }++ _fmtCountdown(ms) {+ const s = Math.max(0, Math.ceil(ms / 1000));+ const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;+ if (h > 0) return `${h}h ${String(m).padStart(2, '0')}m`;+ if (m > 0) return `${m}m ${String(sec).padStart(2, '0')}s`;+ return `${sec}s`;+ }++ // Free-spin button + countdown, recomputed every second against a local clock+ // anchored to the server's `now` so the countdown is accurate without polling.+ _syncFree() {+ if (!this.info) return;+ const drift = Date.now() - (this._infoAt || Date.now());+ const now = (this.info.now ?? Date.now()) + drift;+ const next = this.info.nextFreeSpinAt ?? 0;+ const ready = now >= next;+ if (this.phase === 'spinning' || this.phase === 'paying') return;+ if (!this._levelOk()) {+ this.freeBtn.disabled = true; this.freeBtn.textContent = 'Free spin';+ this.freeSub.textContent = '';+ return;+ }+ this.freeBtn.disabled = !ready || this.busy;+ this.freeBtn.textContent = ready ? 'Free spin' : 'Free spin';+ this.freeSub.textContent = ready ? 'Ready now · 1 per 12h' : `Next free spin in ${this._fmtCountdown(next - now)}`;+ this.freeSub.dataset.ready = ready ? '1' : '0';+ }++ // Reconcile the whole UI with the current phase + eligibility.+ _sync() {+ const lvlOk = this._levelOk();+ const min = this.info?.minLevel ?? 5;+ // Level gate banner — the designed "not eligible" state with a how-to.+ if (this.info && !lvlOk) {+ this.gate.hidden = false;+ this.gate.replaceChildren(+ el('div', { class: 'kg-spin-gate-h', text: 'Locked' }),+ el('div', { class: 'kg-spin-gate-b' }, [+ `Spinning needs an average skill level of ${min}. You're at ${this.info.avgLevel ?? 0}. `,+ 'Chop, mine, fish, cook and fight to raise your skills — the wheel unlocks at level ' + min + '.',+ ]),+ );+ } else {+ this.gate.hidden = true;+ }+ // Paid button availability + label.+ const paidOk = lvlOk && !!this.info?.paidAvailable;+ this.paidBtn.disabled = this.busy || !paidOk;+ const cost = this.info?.costUsd ?? 3;+ const sym = this.info?.symbol || '$THREE';+ this.paidBtn.textContent = `Paid spin · $${cost}`;+ 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`;+ this._syncFree();+ }++ _setBusy(on, text) { if (text != null) this._status(text, ''); }+ _status(text, kind) { this.status.textContent = text || ''; this.status.dataset.kind = kind || ''; }+ _statusNode(node, kind) { this.status.replaceChildren(node); this.status.dataset.kind = kind || ''; }++ // ---------------------------------------------------------------- close+ close() {+ if (this._closed) return;+ this._closed = true;+ this._stopSpin();+ if (this._countdownTimer) clearInterval(this._countdownTimer);+ for (const off of this._offs || []) { try { off(); } catch {} }+ window.removeEventListener('keydown', this._onKey);+ this.overlay?.remove();+ if (_open === this) _open = null;+ try { this.onClose?.(); } catch {}+ }+}diff --git a/src/token-pay.js b/src/token-pay.jsnew file mode 100644index 000000000..2f0e4c63f--- /dev/null+++ b/src/token-pay.js@@ -0,0 +1,193 @@+/**+ * $THREE token payment — client helper (Task 18).+ *+ * Drives the server-authoritative quote → sign → settle flow that Task 19+ * (paid spins) and Task 20 (token-priced listings) reuse:+ *+ * 1. POST /api/token/quote → a signed quote with concrete split legs+ * 2. Build ONE transaction: an idempotent ATA-create + SPL transfer per leg+ * (burn + treasury, or seller + treasury), plus a memo carrying the nonce+ * 3. Wallet signs & sends it; we wait for confirmation+ * 4. POST /api/token/settle → server verifies on-chain and records it+ *+ * The server is the only authority on whether the payment counts — this helper+ * never reports success on its own. Usage:+ *+ * import { payWithToken } from './token-pay.js';+ * const result = await payWithToken({+ * purpose: 'spin', usd: 0.50, refType: 'spin', refId,+ * onStatus: (s) => spinner.set(s),+ * });+ * if (result.ok) grantSpin();+ */++const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';++// Lazy-load the Solana SDKs so they stay out of the initial bundle — Vite+// splits them into a chunk fetched only when a payment actually happens.+let _web3 = null;+let _spl = null;+async function loadSolana() {+ if (!_web3) _web3 = await import('@solana/web3.js');+ if (!_spl) _spl = await import('@solana/spl-token');+ return { web3: _web3, spl: _spl };+}++function rpcEndpoint() {+ return (+ (typeof window !== 'undefined' && window.__solanaRpc) ||+ `${window.location.origin}/api/solana-rpc`+ );+}++async function getProvider(explicit) {+ const wallet = explicit || (typeof window !== 'undefined' ? window.solana : null);+ if (!wallet) {+ throw Object.assign(+ new Error('No Solana wallet found. Install Phantom or connect a wallet.'),+ {+ code: 'no_wallet',+ },+ );+ }+ if (!wallet.isConnected) {+ if (typeof wallet.connect === 'function') await wallet.connect();+ else throw Object.assign(new Error('Wallet is not connected.'), { code: 'not_connected' });+ }+ return wallet;+}++function memoData(nonce) {+ return typeof Buffer !== 'undefined'+ ? Buffer.from(nonce, 'utf8')+ : new TextEncoder().encode(nonce);+}++/** GET the public token config (mint, decimals, treasury, burn, split policies). */+export async function fetchTokenConfig() {+ const r = await fetch('/api/token/config', { credentials: 'include' });+ if (!r.ok) throw new Error(`token config ${r.status}`);+ return r.json();+}++/** GET the live token price; pass `usd` to also receive a token-amount quote. */+export async function fetchTokenPrice(usd) {+ const url =+ usd != null ? `/api/token/price?usd=${encodeURIComponent(usd)}` : '/api/token/price';+ const r = await fetch(url, { credentials: 'include' });+ if (!r.ok) throw new Error(`token price ${r.status}`);+ return r.json();+}++/**+ * Run the full quote → sign → settle flow.+ * @param {{+ * purpose: 'spin'|'marketplace_sale',+ * usd: number,+ * sellerWallet?: string,+ * refType?: string,+ * refId?: string,+ * network?: 'mainnet'|'devnet',+ * wallet?: any, // override window.solana+ * onStatus?: (status: string) => void, // 'quoting'|'awaiting_signature'|'confirming'|'settling'+ * }} params+ * @returns {Promise<{ ok: boolean, payment_id: string, tx_signature: string, legs: any[], credited: object }>}+ */+export async function payWithToken({+ purpose,+ usd,+ sellerWallet,+ refType,+ refId,+ network = 'mainnet',+ wallet,+ onStatus = () => {},+}) {+ // 1. Quote+ onStatus('quoting');+ const quoteResp = await fetch('/api/token/quote', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ purpose,+ usd,+ network,+ ...(sellerWallet ? { seller_wallet: sellerWallet } : {}),+ ...(refType ? { ref_type: refType } : {}),+ ...(refId ? { ref_id: refId } : {}),+ }),+ });+ const quote = await quoteResp.json();+ if (!quoteResp.ok) {+ throw Object.assign(new Error(quote.error_description || 'quote failed'), {+ code: quote.error,+ });+ }++ // 2. Build the transaction from the quote legs+ const { web3, spl } = await loadSolana();+ const { Connection, PublicKey, Transaction, TransactionInstruction } = web3;+ const {+ getAssociatedTokenAddressSync,+ createTransferInstruction,+ createAssociatedTokenAccountIdempotentInstruction,+ } = spl;++ const provider = await getProvider(wallet);+ const payer = provider.publicKey;+ if (!payer) throw Object.assign(new Error('Wallet has no public key.'), { code: 'no_pubkey' });++ const connection = new Connection(rpcEndpoint(), 'confirmed');+ const mint = new PublicKey(quote.mint);+ const fromAta = getAssociatedTokenAddressSync(mint, payer);++ const tx = new Transaction();+ for (const leg of quote.legs) {+ const owner = new PublicKey(leg.address);+ // allowOwnerOffCurve: the burn incinerator is off-curve.+ const destAta = getAssociatedTokenAddressSync(mint, owner, true);+ // Idempotent: a no-op if the destination ATA already exists; otherwise the+ // payer funds its rent so burn/treasury/seller can receive on first use.+ tx.add(createAssociatedTokenAccountIdempotentInstruction(payer, destAta, owner, mint));+ tx.add(createTransferInstruction(fromAta, destAta, payer, BigInt(leg.atomics)));+ }+ // Memo carries the quote nonce so the server can bind this tx to the quote.+ tx.add(+ new TransactionInstruction({+ keys: [],+ programId: new PublicKey(MEMO_PROGRAM_ID),+ data: memoData(quote.memo),+ }),+ );++ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');+ tx.feePayer = payer;+ tx.recentBlockhash = blockhash;++ // 3. Sign + send + confirm+ onStatus('awaiting_signature');+ const signature = await provider.sendTransaction(tx, connection);+ onStatus('confirming');+ await connection.confirmTransaction(+ { signature, blockhash, lastValidBlockHeight },+ 'confirmed',+ );++ // 4. Settle (server verifies on-chain and records the payment)+ onStatus('settling');+ const settleResp = await fetch('/api/token/settle', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ quote_token: quote.quote_token, tx_signature: signature, network }),+ });+ const settled = await settleResp.json();+ if (!settleResp.ok) {+ throw Object.assign(new Error(settled.error_description || 'settlement failed'), {+ code: settled.error,+ tx_signature: signature,+ });+ }+ return { ...settled, tx_signature: signature };+}diff --git a/tests/cosmetics-hud.test.js b/tests/cosmetics-hud.test.jsnew file mode 100644index 000000000..7f526962a--- /dev/null+++ b/tests/cosmetics-hud.test.js@@ -0,0 +1,136 @@+// @vitest-environment jsdom+//+// Cosmetics shop HUD (Task 21) — the DOM half of the in-world shop the scene+// drives. Verifies the gold readout, the buy/wardrobe tabs, affordability ++// owned states, equip/unequip wiring, the rotation-section countdown, and the+// empty wardrobe state, so the player-facing chrome is exercised without a+// browser. Fed the same shapes the server sends (catalogue + shop board).++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++globalThis.self = globalThis;++import { GameHud } from '../src/game/game-hud.js';+import { clientCatalog, currentOffers } from '../multiplayer/src/cosmetics.js';++const CAT = clientCatalog();+const T = Date.UTC(2026, 5, 1, 12, 0, 0);++let hud;+let calls;+afterEach(() => { hud?.destroy(); hud = null; document.body.innerHTML = ''; });++function mount() {+ calls = { buy: [], equip: [], unequip: 0, shopOpen: 0 };+ hud = new GameHud({+ onShopOpen: () => calls.shopOpen++,+ onBuyCosmetic: (id) => calls.buy.push(id),+ onEquipCosmetic: (id) => calls.equip.push(id),+ onUnequipCosmetic: () => calls.unequip++,+ });+ hud.setCosmeticCatalog(CAT.cosmetics, CAT.rarities);+ return hud;+}++// A shop board for instant T with a given purse / owned / equipped.+function board({ gold = 1000, owned = [], equipped = '' } = {}) {+ return { offers: currentOffers(T), owned, equipped, gold };+}++describe('gold readout', () => {+ it('reflects setGold in the toolbar and shop header', () => {+ mount();+ hud.setGold(1234);+ expect(document.querySelector('#kq-gold-n').textContent).toBe('1,234');+ expect(document.querySelector('#kq-shop-gold').textContent).toBe('1,234');+ });+});++describe('shop tab — buy board', () => {+ it('opens, fetches a fresh board, and renders the rotating + always sections', () => {+ mount();+ hud.openShop();+ expect(calls.shopOpen).toBe(1); // open pulls a fresh board+ hud.setShop(board({ gold: 2000 }));+ const sections = document.querySelectorAll('#kq-shop-body .kq-shop-section');+ expect(sections.length).toBe(3); // daily, weekly, always+ // A live countdown is present for the rotating sections.+ expect(document.querySelector('#kq-shop-daily-reset')).toBeTruthy();+ expect(document.querySelector('#kq-shop-weekly-reset')).toBeTruthy();+ // Every offered card is rendered.+ const offers = currentOffers(T);+ const total = offers.daily.length + offers.weekly.length + offers.always.length;+ expect(document.querySelectorAll('#kq-shop-body .kq-cos-card').length).toBe(total);+ });++ it('a buy click on an affordable card routes the cosmetic id to the server', () => {+ mount();+ hud.openShop();+ hud.setShop(board({ gold: 100000 }));+ const buy = document.querySelector('#kq-shop-body .kq-cos-buy');+ expect(buy).toBeTruthy();+ buy.click();+ expect(calls.buy.length).toBe(1);+ expect(typeof calls.buy[0]).toBe('string');+ });++ it('disables buying when the purse is short and shows the shortfall', () => {+ mount();+ hud.openShop();+ hud.setShop(board({ gold: 0 }));+ const card = document.querySelector('#kq-shop-body .kq-cos-card.kq-cos--short');+ expect(card).toBeTruthy();+ const btn = card.querySelector('.kq-cos-buy');+ expect(btn.disabled).toBe(true);+ btn.click();+ expect(calls.buy.length).toBe(0); // a disabled button never fires+ });++ it('marks an owned cosmetic as Owned instead of offering a buy button', () => {+ mount();+ hud.openShop();+ const ownedId = currentOffers(T).always[0];+ hud.setShop(board({ gold: 5000, owned: [ownedId] }));+ const ownedTag = [...document.querySelectorAll('#kq-shop-body .kq-cos-owned')];+ expect(ownedTag.length).toBeGreaterThan(0);+ });+});++describe('wardrobe tab — equip / unequip', () => {+ it('shows the empty state when nothing is owned', () => {+ mount();+ hud.openShop();+ hud.setShop(board({ owned: [] }));+ hud._setShopTab('wardrobe');+ expect(document.querySelector('#kq-shop-body .kq-shop-empty')).toBeTruthy();+ });++ it('lists owned cosmetics + a Default tile and equips on click', () => {+ mount();+ hud.openShop();+ const owned = currentOffers(T).always.slice(0, 1);+ hud.setShop(board({ owned, equipped: '' }));+ hud._setShopTab('wardrobe');+ // Default tile is equipped when nothing else is.+ const equippedTag = document.querySelector('#kq-shop-body .kq-cos--equipped');+ expect(equippedTag).toBeTruthy();+ // Equip the owned cosmetic.+ const equipBtn = document.querySelector('#kq-shop-body .kq-cos-equip');+ expect(equipBtn).toBeTruthy();+ equipBtn.click();+ expect(calls.equip).toEqual(owned);+ });++ it('the Default tile unequips when a cosmetic is equipped', () => {+ mount();+ hud.openShop();+ const owned = currentOffers(T).always.slice(0, 1);+ hud.setShop(board({ owned, equipped: owned[0] }));+ hud._setShopTab('wardrobe');+ // The equipped cosmetic shows "Equipped"; the Default tile offers Equip.+ const defaultCard = document.querySelector('#kq-shop-body .kq-cos--default');+ expect(defaultCard).toBeTruthy();+ defaultCard.querySelector('.kq-cos-equip').click();+ expect(calls.unequip).toBe(1);+ });+});diff --git a/tests/cosmetics.test.js b/tests/cosmetics.test.jsnew file mode 100644index 000000000..e795c6c31--- /dev/null+++ b/tests/cosmetics.test.js@@ -0,0 +1,154 @@+// Task 21 — cosmetics shop. These cover the data-driven core the buy/equip+// handlers rest on: the catalogue's integrity (every cosmetic is purely visual,+// priced, and rotation-tagged), the deterministic daily/weekly rotation (same+// date ⇒ same offers, across processes), the next-rotation timestamps the client+// counts down to, and the `isOffered` gate the purchase handler trusts. All live+// in a dependency-free module so they assert without standing up a Colyseus room+// — mirroring fishing.test.js / cooking.test.js.+import { describe, it, expect } from 'vitest';+import {+ COSMETICS, RARITIES, DAILY_OFFER_COUNT, WEEKLY_OFFER_COUNT,+ cosmeticById, currentOffers, isOffered, clientCatalog,+ dailyKey, weekKey, nextDailyReset, nextWeeklyReset,+} from '../multiplayer/src/cosmetics.js';++// A fixed instant for deterministic assertions: Mon 2026-06-01 12:00 UTC.+const T = Date.UTC(2026, 5, 1, 12, 0, 0);+const DAY = 24 * 60 * 60 * 1000;++describe('catalogue integrity — every cosmetic is visual-only, priced, rotation-tagged', () => {+ it('has a non-empty catalogue with unique ids', () => {+ expect(COSMETICS.length).toBeGreaterThan(0);+ const ids = COSMETICS.map((c) => c.id);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('every entry has a positive price, known rarity, and a valid rotation', () => {+ for (const c of COSMETICS) {+ expect(typeof c.id).toBe('string');+ expect(c.name).toBeTruthy();+ expect(Number.isInteger(c.price)).toBe(true);+ expect(c.price).toBeGreaterThan(0);+ expect(RARITIES[c.rarity]).toBeTruthy();+ expect(['always', 'daily', 'weekly']).toContain(c.rotation);+ }+ });++ it('every visual spec is strictly cosmetic — only tint / prop / aura keys', () => {+ const allowed = new Set(['tint', 'prop', 'anchor', 'aura']);+ for (const c of COSMETICS) {+ expect(c.visual && typeof c.visual === 'object').toBe(true);+ for (const key of Object.keys(c.visual)) expect(allowed.has(key)).toBe(true);+ // At least one renderable primitive — never an empty (no-op) cosmetic.+ expect(c.visual.tint || c.visual.prop || c.visual.aura).toBeTruthy();+ }+ });++ it('has enough rotating stock that a set genuinely changes each period', () => {+ const daily = COSMETICS.filter((c) => c.rotation === 'daily').length;+ const weekly = COSMETICS.filter((c) => c.rotation === 'weekly').length;+ expect(daily).toBeGreaterThan(DAILY_OFFER_COUNT);+ expect(weekly).toBeGreaterThan(WEEKLY_OFFER_COUNT);+ });++ it('cosmeticById resolves a real entry and rejects unknowns', () => {+ expect(cosmeticById(COSMETICS[0].id)).toBe(COSMETICS[0]);+ expect(cosmeticById('does-not-exist')).toBeNull();+ expect(cosmeticById('')).toBeNull();+ });+});++describe('currentOffers — deterministic rotation, correct bucket sizes', () => {+ it('offers exactly the configured count from each rotating pool', () => {+ const o = currentOffers(T);+ expect(o.daily).toHaveLength(DAILY_OFFER_COUNT);+ expect(o.weekly).toHaveLength(WEEKLY_OFFER_COUNT);+ expect(o.always.length).toBe(COSMETICS.filter((c) => c.rotation === 'always').length);+ });++ it('offered ids are distinct and drawn from the right pool', () => {+ const o = currentOffers(T);+ expect(new Set(o.daily).size).toBe(o.daily.length);+ for (const id of o.daily) expect(cosmeticById(id).rotation).toBe('daily');+ for (const id of o.weekly) expect(cosmeticById(id).rotation).toBe('weekly');+ for (const id of o.always) expect(cosmeticById(id).rotation).toBe('always');+ });++ it('is deterministic for a given instant (same date ⇒ same offers)', () => {+ const a = currentOffers(T);+ const b = currentOffers(T + 60 * 1000); // a minute later, same UTC day/week+ expect(b.daily).toEqual(a.daily);+ expect(b.weekly).toEqual(a.weekly);+ });++ it('the daily set rolls over across a UTC-day boundary', () => {+ // Compare two days far enough apart that the seeded shuffle differs. Some+ // neighbouring days can coincide, so assert change over a span of days.+ const today = currentOffers(T).daily.join(',');+ const later = currentOffers(T + 3 * DAY).daily.join(',');+ // Either the set or its order may shift; over 3 days at least one differs.+ const anyDiff = [1, 2, 3, 4, 5].some((d) => currentOffers(T + d * DAY).daily.join(',') !== today);+ expect(anyDiff || later !== today).toBe(true);+ });+});++describe('rotation keys + next-reset timestamps drive the client countdown', () => {+ it('dailyKey is the UTC date and nextDailyReset is the next UTC midnight', () => {+ expect(dailyKey(T)).toBe('2026-06-01');+ expect(nextDailyReset(T)).toBe(Date.UTC(2026, 5, 2));+ // Idempotent within the same day; advances to the next at the boundary.+ expect(nextDailyReset(T) - T).toBeLessThanOrEqual(DAY);+ expect(nextDailyReset(T)).toBeGreaterThan(T);+ });++ it('weekKey is the ISO-week Monday and nextWeeklyReset is the next Monday', () => {+ // 2026-06-01 is itself a Monday, so the week starts that day.+ expect(weekKey(T)).toBe('2026-06-01');+ const next = nextWeeklyReset(T);+ expect(next).toBe(Date.UTC(2026, 5, 8));+ expect(new Date(next).getUTCDay()).toBe(1); // Monday+ });++ it('mid-week still resolves to the same Monday + the same next reset', () => {+ const wed = T + 2 * DAY; // Wed 2026-06-03+ expect(weekKey(wed)).toBe('2026-06-01');+ expect(nextWeeklyReset(wed)).toBe(Date.UTC(2026, 5, 8));+ });+});++describe('isOffered — the purchase gate', () => {+ it('always-cosmetics are always buyable', () => {+ const always = COSMETICS.find((c) => c.rotation === 'always');+ expect(isOffered(always.id, T)).toBe(true);+ });++ it('matches the current rotating board exactly', () => {+ const o = currentOffers(T);+ for (const id of o.daily) expect(isOffered(id, T)).toBe(true);+ for (const id of o.weekly) expect(isOffered(id, T)).toBe(true);+ // A rotating cosmetic NOT in today's set is not offered.+ const offered = new Set([...o.daily, ...o.weekly]);+ const benched = COSMETICS.find((c) => c.rotation !== 'always' && !offered.has(c.id));+ if (benched) expect(isOffered(benched.id, T)).toBe(false);+ });++ it('rejects unknown ids', () => {+ expect(isOffered('nope', T)).toBe(false);+ });+});++describe('clientCatalog — what the client renders from', () => {+ it('exposes every cosmetic with the fields the shop/wardrobe need, plus rarities', () => {+ const cat = clientCatalog();+ expect(cat.rarities).toBe(RARITIES);+ expect(cat.cosmetics).toHaveLength(COSMETICS.length);+ for (const c of cat.cosmetics) {+ expect(c).toHaveProperty('id');+ expect(c).toHaveProperty('name');+ expect(c).toHaveProperty('rarity');+ expect(c).toHaveProperty('price');+ expect(c).toHaveProperty('rotation');+ expect(c).toHaveProperty('visual');+ }+ });+});diff --git a/tests/fishing.test.js b/tests/fishing.test.jsnew file mode 100644index 000000000..c434d9b6d--- /dev/null+++ b/tests/fishing.test.js@@ -0,0 +1,124 @@+// Task 05 — fishing. These cover the data-driven core the cast handler rests on:+// the catch + double-haul curves (which the server rolls a single cast against)+// and the realm fishing-spot data + adjacency helper (which gate a cast to shore+// tiles beside water). All live in dependency-free modules so they can be+// asserted without standing up a Colyseus room — mirroring cooking.test.js.+import { describe, it, expect } from 'vitest';+import { fishCatchChance, fishDoubleChance, STACKABLE_ITEMS } from '../multiplayer/src/items.js';+import { REALMS, fishingSpotNear } from '../multiplayer/src/rooms/realms.js';++describe('fishCatchChance — rises with skill + spot quality, capped', () => {+ it('starts at 40% for a level-1 angler on average water', () => {+ expect(fishCatchChance(1, 1)).toBeCloseTo(0.4, 10);+ });++ it('improves as fishing level rises (the core progression promise)', () => {+ expect(fishCatchChance(20, 1)).toBeGreaterThan(fishCatchChance(1, 1));+ expect(fishCatchChance(99, 1)).toBeGreaterThan(fishCatchChance(20, 1));+ });++ it('richer water catches more often than poor water at the same level', () => {+ // Pond (1.3) beats Whisperwood pools (0.9) for a given angler.+ expect(fishCatchChance(10, 1.3)).toBeGreaterThan(fishCatchChance(10, 0.9));+ });++ it('is monotonically non-decreasing in level and bounded in [0, 0.95]', () => {+ let prev = -Infinity;+ for (let lvl = 1; lvl <= 99; lvl++) {+ const c = fishCatchChance(lvl, 1);+ expect(c).toBeGreaterThanOrEqual(0);+ expect(c).toBeLessThanOrEqual(0.95);+ expect(c).toBeGreaterThanOrEqual(prev - 1e-12);+ prev = c;+ }+ });++ it('never guarantees a catch even on the best water at the cap', () => {+ expect(fishCatchChance(99, 1.3)).toBeLessThanOrEqual(0.95);+ expect(fishCatchChance(99, 5)).toBe(0.95); // absurd quality still clamps+ });++ it('treats below-floor levels and bad quality as level 1 / quality 1', () => {+ expect(fishCatchChance(0, 1)).toBeCloseTo(0.4, 10);+ expect(fishCatchChance(-5, 1)).toBeCloseTo(0.4, 10);+ expect(fishCatchChance(1, 0)).toBeCloseTo(0.4, 10);+ expect(fishCatchChance(1, -2)).toBeCloseTo(0.4, 10);+ });+});++describe('fishDoubleChance — a treat that scales, never the norm', () => {+ it('is zero at level 1 (no doubles for a raw beginner)', () => {+ expect(fishDoubleChance(1, 1)).toBe(0);+ });++ it('grows with level and quality but stays clamped at 45%', () => {+ expect(fishDoubleChance(10, 1)).toBeGreaterThan(0);+ expect(fishDoubleChance(50, 1.3)).toBeGreaterThan(fishDoubleChance(10, 1));+ for (let lvl = 1; lvl <= 99; lvl++) {+ expect(fishDoubleChance(lvl, 1.3)).toBeLessThanOrEqual(0.45);+ }+ });+});++describe('catch yield is a stackable item', () => {+ it('raw fish stacks so repeated casts fill one slot', () => {+ expect(STACKABLE_ITEMS.has('fish')).toBe(true);+ });+});++describe('realm fishing data — fishable shores beside water', () => {+ it('Pond is the richest water, Whisperwood the poorest of the fishable realms', () => {+ const pondQ = REALMS.pond.fishing[0].quality;+ const woodQ = REALMS.whisperwood.fishing[0].quality;+ const landQ = REALMS.mainland.fishing[0].quality;+ expect(pondQ).toBeGreaterThan(landQ);+ expect(landQ).toBeGreaterThan(woodQ);+ });++ it('every fishing spot carries a positive quality multiplier', () => {+ for (const realm of Object.values(REALMS)) {+ for (const spot of realm.fishing) {+ expect(spot.quality).toBeGreaterThan(0);+ expect(Number.isFinite(spot.tx)).toBe(true);+ expect(Number.isFinite(spot.ty)).toBe(true);+ }+ }+ });++ it('mine and wilderness have no fishing (dry/dangerous realms)', () => {+ expect(REALMS.mine.fishing).toHaveLength(0);+ expect(REALMS.wilderness.fishing).toHaveLength(0);+ });+});++describe('fishingSpotNear — 8-way adjacency gate, picks the richest reachable water', () => {+ const pond = REALMS.pond;+ const spot = pond.fishing[0]; // { tx: 13, ty: 14, quality: 1.3 }++ it('finds the spot when standing on it', () => {+ expect(fishingSpotNear(pond, spot.tx, spot.ty)).toBeTruthy();+ });++ it('finds the spot from a diagonally adjacent tile', () => {+ expect(fishingSpotNear(pond, spot.tx - 1, spot.ty - 1)).toBeTruthy();+ expect(fishingSpotNear(pond, spot.tx + 1, spot.ty + 1)).toBeTruthy();+ });++ it('returns null when two or more tiles away from any water', () => {+ expect(fishingSpotNear(pond, spot.tx + 3, spot.ty + 3)).toBeNull();+ expect(fishingSpotNear(pond, 0, 0)).toBeNull();+ });++ it('returns null in a realm with no fishing water', () => {+ expect(fishingSpotNear(REALMS.mine, 16, 28)).toBeNull();+ });++ it('prefers the higher-quality spot when two are in reach', () => {+ // Hand-built realm stub: a poor spot and a rich spot both within one tile.+ const realm = { fishing: [+ { tx: 5, ty: 5, quality: 0.5 },+ { tx: 6, ty: 5, quality: 1.5 },+ ] };+ expect(fishingSpotNear(realm, 5, 5).quality).toBe(1.5);+ });+});diff --git a/tests/mine-realm.test.js b/tests/mine-realm.test.jsnew file mode 100644index 000000000..157a81907--- /dev/null+++ b/tests/mine-realm.test.js@@ -0,0 +1,145 @@+// Task 08 — Mainland mine interior. These cover the dependency-free core the+// mine rests on: the realm geometry + portal wiring (which the GameRoom validates+// movement and traversal against) and the realm-transfer token (which carries a+// player's haul between realm rooms without trusting the client). Both live in+// plain modules, so they assert without standing up a Colyseus room — mirroring+// fishing.test.js / cooking.test.js.+import { describe, it, expect } from 'vitest';+import { REALMS, portalAt, isBlocked, inBounds } from '../multiplayer/src/rooms/realms.js';+import { signTransfer, verifyTransfer } from '../multiplayer/src/rooms/realm-transfer.js';++const MINE = REALMS.mine;+const MAINLAND = REALMS.mainland;++describe('mine realm — an enclosed, safe cave dense with ore', () => {+ it('exists and is a safe, non-pvp, non-danger resource area', () => {+ expect(MINE).toBeTruthy();+ expect(MINE.safe).toBe(true);+ expect(MINE.pvp).toBe(false);+ expect(MINE.danger).toBe(false);+ });++ it('has no bank or fountain — you carry the haul back up to the Mainland', () => {+ expect(MINE.fountain).toBeNull();+ expect(MINE.bankZone).toEqual([]);+ });++ it('is denser in ore than the Mainland surface (the whole point of the mine)', () => {+ const count = (realm, kind) => realm.nodes.filter((n) => n.kind === kind).length;+ const mineRock = count(MINE, 'rock'), mineCoal = count(MINE, 'coal');+ const surfRock = count(MAINLAND, 'rock'), surfCoal = count(MAINLAND, 'coal');+ expect(mineRock).toBeGreaterThan(surfRock);+ expect(mineCoal).toBeGreaterThan(surfCoal);+ // Only rock and coal grow down here — no trees in a cave.+ expect(MINE.nodes.every((n) => n.kind === 'rock' || n.kind === 'coal')).toBe(true);+ });++ it('keeps every node id unique and every node on a walkable, in-bounds tile', () => {+ const ids = MINE.nodes.map((n) => n.id);+ expect(new Set(ids).size).toBe(ids.length);+ for (const n of MINE.nodes) {+ expect(inBounds(MINE, n.tx, n.ty)).toBe(true);+ // A node may not sit inside a wall/ridge/pillar (it would be unreachable).+ expect(isBlocked(MINE, n.tx, n.ty)).toBe(false);+ }+ });++ it('spawns the player on a walkable interior tile, not in a wall', () => {+ expect(inBounds(MINE, MINE.spawn.tx, MINE.spawn.ty)).toBe(true);+ expect(isBlocked(MINE, MINE.spawn.tx, MINE.spawn.ty)).toBe(false);+ });++ it('walls its entire edge except the entrance mouth', () => {+ const g = MINE.grid;+ // Corners are always wall.+ for (const [x, y] of [[0, 0], [g - 1, 0], [0, g - 1], [g - 1, g - 1]]) {+ expect(isBlocked(MINE, x, y)).toBe(true);+ }+ // The south edge has a walkable gap (the entrance/return mouth) AND wall.+ let gap = 0, wall = 0;+ for (let x = 0; x < g; x++) (isBlocked(MINE, x, g - 1) ? wall++ : gap++);+ expect(gap).toBeGreaterThan(0);+ expect(wall).toBeGreaterThan(0);+ });++ it('permits no player building down a working mine', () => {+ expect(MINE.structures).toEqual([]);+ });+});++describe('mine portals — round-trip between the Mainland entrance and the cave', () => {+ it('Mainland has a mine entrance that targets the mine spawn area', () => {+ const entrance = MAINLAND.portals.find((p) => p.to === 'mine');+ expect(entrance).toBeTruthy();+ // The entrance tile is walkable so a player can actually step onto it.+ expect(isBlocked(MAINLAND, entrance.x0, entrance.y0)).toBe(false);+ // Its destination lands inside the mine, on a walkable tile.+ expect(inBounds(MINE, entrance.toTx, entrance.toTy)).toBe(true);+ expect(isBlocked(MINE, entrance.toTx, entrance.toTy)).toBe(false);+ });++ it('the mine has exactly one portal — a return to the Mainland', () => {+ expect(MINE.portals).toHaveLength(1);+ const ret = MINE.portals[0];+ expect(ret.to).toBe('mainland');+ expect(inBounds(MAINLAND, ret.toTx, ret.toTy)).toBe(true);+ expect(isBlocked(MAINLAND, ret.toTx, ret.toTy)).toBe(false);+ });++ it('return tile is clear of the entrance rect, so stepping out never bounces back in', () => {+ const entrance = MAINLAND.portals.find((p) => p.to === 'mine');+ const ret = MINE.portals[0];+ // Landing back on the Mainland must NOT be on a portal tile.+ expect(portalAt(MAINLAND, ret.toTx, ret.toTy)).toBeNull();+ // And the entrance's own destination must not sit on the mine's return rect.+ expect(portalAt(MINE, entrance.toTx, entrance.toTy)).toBeNull();+ });++ it('portalAt resolves the entrance rect and rejects ordinary tiles', () => {+ const entrance = MAINLAND.portals.find((p) => p.to === 'mine');+ expect(portalAt(MAINLAND, entrance.x0, entrance.y0)?.to).toBe('mine');+ expect(portalAt(MAINLAND, MAINLAND.spawn.tx, MAINLAND.spawn.ty)).toBeNull();+ });+});++describe('realm-transfer token — the trust boundary for carrying a haul across realms', () => {+ const carry = {+ inv: [{ item: 'coal', qty: 17 }, { item: 'stone', qty: 9 }],+ hotbar: [{ item: 'pickaxe', qty: 1 }],+ activeSlot: 0,+ bank: [{ item: 'gold', qty: 250 }],+ gold: 1234,+ hp: 73,+ maxHp: 100,+ xp: { mining: 4200, combat: 0, woodcutting: 0, fishing: 0, cooking: 0 },+ mounted: false,+ mount: '',+ };++ it('round-trips a signed carry intact', () => {+ const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry });+ const out = verifyTransfer(token);+ expect(out).toBeTruthy();+ expect(out.to).toBe('mine');+ expect(out.tx).toBe(16);+ expect(out.ty).toBe(28);+ expect(out.carry).toEqual(carry);+ });++ it('rejects a tampered payload (forged items can never ride in)', () => {+ const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry });+ const [body, sig] = token.split('.');+ const forged = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));+ forged.carry.gold = 9_999_999;+ const rebody = Buffer.from(JSON.stringify(forged)).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');+ expect(verifyTransfer(`${rebody}.${sig}`)).toBeNull();+ });++ it('rejects garbage, empty, and structurally-invalid tokens', () => {+ expect(verifyTransfer('')).toBeNull();+ expect(verifyTransfer('not-a-token')).toBeNull();+ expect(verifyTransfer('abc.def')).toBeNull();+ expect(verifyTransfer(null)).toBeNull();+ expect(verifyTransfer(undefined)).toBeNull();+ });+});diff --git a/tests/play-pass.test.js b/tests/play-pass.test.jsnew file mode 100644index 000000000..c01cc67b9--- /dev/null+++ b/tests/play-pass.test.js@@ -0,0 +1,91 @@+// Contract tests for the wallet-first /play gate credentials.+//+// The nonce + play pass are HMAC-signed on the Vercel side (api/_lib/play-pass.js)+// and verified on the standalone game server (multiplayer/src/play-pass.js).+// These two must stay byte-compatible, and each token must reject tampering,+// expiry, and cross-use. The signature/balance flow lives in api/play/verify.js;+// here we lock down the sealing layer it depends on.++import { describe, it, expect, beforeAll } from 'vitest';++let api, mp;++beforeAll(async () => {+ process.env.NODE_ENV = 'development';+ delete process.env.HOLDER_PASS_SECRET; // both sides fall back to the same dev secret+ process.env.PLAY_GATE_MINT = 'So11111111111111111111111111111111111111112';+ process.env.PLAY_GATE_MIN = '1';+ api = await import('../api/_lib/play-pass.js');+ mp = await import('../multiplayer/src/play-pass.js');+});++describe('nonce', () => {+ it('issues a nonce that verifies', () => {+ const { nonce, exp } = api.issueNonce();+ expect(typeof nonce).toBe('string');+ expect(api.verifyNonce(nonce)).toBeTruthy();+ expect(exp).toBeGreaterThan(Date.now() / 1000);+ });++ it('rejects a tampered or garbage nonce', () => {+ const { nonce } = api.issueNonce();+ expect(api.verifyNonce(nonce + 'x')).toBeNull();+ expect(api.verifyNonce('garbage')).toBeNull();+ expect(api.verifyNonce(null)).toBeNull();+ });++ it('is namespaced apart from a play pass', () => {+ const { nonce } = api.issueNonce();+ // A nonce must never validate as a pass, nor a pass as a nonce.+ expect(mp.verifyPlayPass(nonce)).toBeNull();+ });+});++describe('play pass cross-process contract', () => {+ const mint = 'So11111111111111111111111111111111111111112';+ const wallet = '4Nd1mYbQ2YpTof3pT7nYwE2qS9p9z3v8WqHk5xQ2abcd';++ it('signs on the API side and verifies on the game server', () => {+ const token = api.signPlayPass({ wallet, mint, balance: 5 });+ const v = mp.verifyPlayPass(token);+ expect(v).toBeTruthy();+ expect(v.wallet).toBe(wallet);+ expect(v.mint).toBe(mint);+ expect(v.balance).toBe(5);+ expect(v.tier).toBe('play');+ expect(v.minBalance).toBe(1);+ });++ it('rejects a tampered pass', () => {+ const token = api.signPlayPass({ wallet, mint, balance: 5 });+ expect(mp.verifyPlayPass(token.slice(0, -2) + 'zz')).toBeNull();+ // flip a payload byte+ const [body, sig] = token.split('.');+ const flipped = body.slice(0, -1) + (body.slice(-1) === 'A' ? 'B' : 'A') + '.' + sig;+ expect(mp.verifyPlayPass(flipped)).toBeNull();+ });++ it('is not accepted as a nonce', () => {+ const token = api.signPlayPass({ wallet, mint, balance: 5 });+ expect(api.verifyNonce(token)).toBeNull();+ });++ it('rounds the balance to 6dp', () => {+ const token = api.signPlayPass({ wallet, mint, balance: 1.23456789 });+ expect(mp.verifyPlayPass(token).balance).toBe(1.234568);+ });++ it('fails closed on a negative balance (verifier rejects)', () => {+ // verify.js never produces a negative balance, but if a tampered/forged pass+ // carried one the game server must refuse it rather than admit the player.+ const bad = api.signPlayPass({ wallet, mint, balance: -3 });+ expect(mp.verifyPlayPass(bad)).toBeNull();+ });+});++describe('gate config', () => {+ it('reads the mint + min from env', () => {+ expect(api.PLAY_GATE_MINT).toBe('So11111111111111111111111111111111111111112');+ expect(api.PLAY_GATE_MIN).toBe(1);+ });+});diff --git a/tests/player-store.test.js b/tests/player-store.test.jsnew file mode 100644index 000000000..45d425d79--- /dev/null+++ b/tests/player-store.test.js@@ -0,0 +1,164 @@+// PlayerStore (Task 16) — account-keyed player persistence. Two tiers, mirroring+// block-store: a synchronous in-process cache and a durable Upstash Redis backing.+// Exercised against a mocked @upstash/redis so the durability contract is proven+// without real credentials:+// - the sync API (loadPlayer/savePlayer/hasPlayer) round-trips the full profile,+// - durability is claimed only after a real PING succeeds,+// - a profile saved + flushed by one process is rehydrated by the next (the+// cross-restart / cross-instance guarantee — the heart of Task 16),+// - a brand-new account stays null so it is never falsely resurrected,+// - an unreachable Redis degrades to memory-only without losing in-process state,+// - a sustained write outage flips `durable` off (and recovers when writes land).++import { describe, it, expect, beforeEach, vi } from 'vitest';++// Hoisted so the (hoisted) vi.mock factory can close over it. Stands in for the+// Redis server — its contents survive a simulated restart (a fresh PlayerStore).+const redis = vi.hoisted(() => ({ store: new Map(), pingFails: false, setFails: 0 }));++vi.mock('@upstash/redis', () => ({+ Redis: class {+ async ping() { if (redis.pingFails) throw new Error('unreachable'); return 'PONG'; }+ async get(k) { return redis.store.has(k) ? redis.store.get(k) : null; }+ // Accepts (and ignores) the { ex } TTL option the store passes.+ async set(k, v) { if (redis.setFails > 0) { redis.setFails--; throw new Error('write failed'); } redis.store.set(k, v); return 'OK'; }+ async del(k) { return redis.store.delete(k) ? 1 : 0; }+ },+}));++// Spin up a fresh PlayerStore module ("a new process"). With creds set it wires+// the mocked Redis; without them it is memory-only.+async function freshStore({ durable = true } = {}) {+ vi.resetModules();+ if (durable) {+ process.env.UPSTASH_REDIS_REST_URL = 'http://mock-upstash';+ process.env.UPSTASH_REDIS_REST_TOKEN = 'mock-token';+ } else {+ delete process.env.UPSTASH_REDIS_REST_URL;+ delete process.env.UPSTASH_REDIS_REST_TOKEN;+ }+ return import('../multiplayer/src/playerStore.js');+}++// A representative full profile — the exact shape GameRoom persists: gold, name,+// quests (tutorial + dailies + badges), the inventory/hotbar/bank/skills profile+// blob, and owned/equipped cosmetics.+function sampleProfile() {+ return {+ name: 'Nico',+ gold: 4242,+ quests: { tutorial: { step: 5, done: true }, daily: { date: '2026-06-01', quests: [] }, badges: ['newcomer'] },+ profile: {+ inv: [{ item: 'wood', qty: 120 }, { item: 'fish', qty: 8 }],+ hotbar: [{ item: 'axe', qty: 1 }],+ bank: [{ item: 'coal', qty: 30 }],+ activeSlot: 2,+ xp: { combat: 1500, woodcutting: 3000, mining: 200, fishing: 75, cooking: 640 },+ hp: 88, maxHp: 100, mount: 'horse', realm: 'whisperwood', tx: 12, ty: 7,+ },+ cosmetics: { owned: ['hat_red', 'cape_blue', 'crown_gold'], equipped: 'crown_gold' },+ };+}++beforeEach(() => { redis.store.clear(); redis.pingFails = false; redis.setFails = 0; });++describe('PlayerStore — synchronous cache API', () => {+ it('round-trips the full profile through save → load', async () => {+ const s = await freshStore();+ await s.playerStoreReady();+ expect(s.loadPlayer('acct')).toBeNull();+ expect(s.hasPlayer('acct')).toBe(false);++ s.savePlayer('acct', sampleProfile());+ const got = s.loadPlayer('acct');+ expect(got.gold).toBe(4242);+ expect(got.profile.inv[0].qty).toBe(120);+ expect(got.profile.xp.cooking).toBe(640);+ expect(got.cosmetics.equipped).toBe('crown_gold');+ expect(got.quests.tutorial.done).toBe(true);+ expect(typeof got.savedAt).toBe('number'); // stamped for the cache sweep+ expect(s.hasPlayer('acct')).toBe(true);+ });++ it('supports the read-merge-write the GameRoom uses to persist one slice at a time', async () => {+ const s = await freshStore();+ await s.playerStoreReady();+ s.savePlayer('acct', sampleProfile());+ const prev = s.loadPlayer('acct') || {};+ s.savePlayer('acct', { ...prev, gold: 9999 });+ expect(s.loadPlayer('acct').gold).toBe(9999);+ expect(s.loadPlayer('acct').profile.inv[0].qty).toBe(120); // other fields preserved+ });+});++describe('PlayerStore (durable / Upstash)', () => {+ it('claims durability only after a verifying PING succeeds', async () => {+ const s = await freshStore();+ await s.playerStoreReady();+ expect(s.playerStore.durable).toBe(true);+ });++ it('persists a full profile across a simulated restart', async () => {+ // Process A: a player earns progress, then the session ends (flush).+ const a = await freshStore();+ await a.playerStoreReady();+ a.savePlayer('wallet:0xABC', sampleProfile());+ await a.flushPlayer('wallet:0xABC');+ expect(redis.store.size).toBe(1); // one atomic JSON value for the account+ expect(JSON.parse(redis.store.get('player:wallet:0xABC')).gold).toBe(4242);++ // Process B (fresh store, same Redis): the returning player must NOT look+ // brand-new — the cache is empty until hydrate pulls them back.+ const b = await freshStore();+ await b.playerStoreReady();+ expect(b.loadPlayer('wallet:0xABC')).toBeNull();+ const restored = await b.hydratePlayer('wallet:0xABC');+ expect(restored.gold).toBe(4242);+ expect(b.loadPlayer('wallet:0xABC').profile.inv[0].qty).toBe(120);+ expect(b.loadPlayer('wallet:0xABC').profile.xp.cooking).toBe(640);+ expect(b.loadPlayer('wallet:0xABC').profile.realm).toBe('whisperwood');+ expect(b.loadPlayer('wallet:0xABC').cosmetics.equipped).toBe('crown_gold');+ expect(b.loadPlayer('wallet:0xABC').quests.tutorial.done).toBe(true);+ });++ it('hydrates a never-seen account to null so a new player gets the starter kit, not a reset', async () => {+ const s = await freshStore();+ await s.playerStoreReady();+ expect(await s.hydratePlayer('wallet:0xNEW')).toBeNull();+ expect(s.loadPlayer('wallet:0xNEW')).toBeNull();+ });++ it('flushAll persists every dirty account on shutdown', async () => {+ const s = await freshStore();+ await s.playerStoreReady();+ s.savePlayer('a', { gold: 1 });+ s.savePlayer('b', { gold: 2 });+ await s.flushAllPlayers();+ expect(JSON.parse(redis.store.get('player:a')).gold).toBe(1);+ expect(JSON.parse(redis.store.get('player:b')).gold).toBe(2);+ });++ it('degrades to memory-only when Redis is unreachable, without losing in-process state', async () => {+ redis.pingFails = true;+ const s = await freshStore();+ await s.playerStoreReady();+ expect(s.playerStore.durable).toBe(false);+ s.savePlayer('acct', sampleProfile());+ expect(s.loadPlayer('acct').gold).toBe(4242); // cache still serves within the process+ });++ it('flips durability off after sustained write failures, then recovers', async () => {+ const s = await freshStore();+ await s.playerStoreReady();+ expect(s.playerStore.durable).toBe(true);+ s.savePlayer('acct', sampleProfile());+ redis.setFails = 3; // next three writes throw+ await s.flushPlayer('acct');+ await s.flushPlayer('acct');+ await s.flushPlayer('acct');+ expect(s.playerStore.durable).toBe(false);+ await s.flushPlayer('acct'); // writes land again+ expect(s.playerStore.durable).toBe(true);+ expect(JSON.parse(redis.store.get('player:acct')).gold).toBe(4242);+ });+});diff --git a/tests/realms-arena.test.js b/tests/realms-arena.test.jsnew file mode 100644index 000000000..43eb10c29--- /dev/null+++ b/tests/realms-arena.test.js@@ -0,0 +1,226 @@+// Task 22 — additional realms (Wilderness North/East, the gated Cave) and the+// Arena (rollers + seating). These tests pin the realm DATA contract the server+// and client both depend on: every realm is internally walkable, every portal is a+// real two-way link that lands on solid ground (never inside a wall, a node, or a+// return portal that would bounce you), the northern cave is combat-gated, and the+// Arena's rollers + spectator stands carry the right shape + push semantics.++import { describe, it, expect } from 'vitest';+import {+ REALMS, isBlocked, inBounds, portalAt, inRect, inAnyRect,+ rollerAt, rollerDelta, inNoPvpZone, realmLayout,+} from '../multiplayer/src/rooms/realms.js';++// A tile is walkable on the server if it's in bounds, not blocked, and not sitting+// under a resource node (nodes occupy their tile — see GameRoom._isWalkable).+function nodeSet(realm) {+ return new Set((realm.nodes || []).map((n) => `${n.tx},${n.ty}`));+}+function walkable(realm, tx, ty, nodes = nodeSet(realm)) {+ return inBounds(realm, tx, ty) && !isBlocked(realm, tx, ty) && !nodes.has(`${tx},${ty}`);+}++const NEW = ['wilderness_north', 'wilderness_cave', 'wilderness_east', 'arena'];++describe('new realms exist with the right rule flags', () => {+ it('all four are registered', () => {+ for (const name of NEW) expect(REALMS[name], name).toBeTruthy();+ });++ it('Wilderness North is PvP + danger with NO safe camp', () => {+ const r = REALMS.wilderness_north;+ expect(r.pvp).toBe(true);+ expect(r.danger).toBe(true);+ expect(r.safe).toBe(false);+ expect(r.safeCamp).toBeNull();+ });++ it('the Cave is a PvP + danger cavern (rendered enclosed)', () => {+ const r = REALMS.wilderness_cave;+ expect(r.pvp).toBe(true);+ expect(r.danger).toBe(true);+ expect(r.cave).toBe(true);+ });++ it('Wilderness East is a full PvP + danger realm, no safe camp', () => {+ const r = REALMS.wilderness_east;+ expect(r.pvp).toBe(true);+ expect(r.danger).toBe(true);+ expect(r.safeCamp).toBeNull();+ expect(r.grid).toBeGreaterThanOrEqual(40); // full-size, like the main Wilderness+ });++ it('the Arena is PvP but NOT danger (a sporting bout — no item loss)', () => {+ const r = REALMS.arena;+ expect(r.pvp).toBe(true);+ expect(r.danger).toBe(false);+ expect(r.rollers?.length).toBeGreaterThan(0);+ expect(r.seating?.length).toBeGreaterThan(0);+ });++ it('Wilderness North has a LOWER mob count than the main Wilderness', () => {+ expect(REALMS.wilderness_north.mobs.length).toBeLessThan(REALMS.wilderness.mobs.length);+ });+});++describe('every realm spawn stands on walkable ground', () => {+ for (const [name, r] of Object.entries(REALMS)) {+ it(`${name} spawn (${r.spawn.tx},${r.spawn.ty}) is walkable`, () => {+ expect(walkable(r, r.spawn.tx, r.spawn.ty)).toBe(true);+ });+ }+});++describe('portals are real two-way links that land on solid ground', () => {+ for (const [name, r] of Object.entries(REALMS)) {+ for (const p of r.portals) {+ it(`${name} → ${p.to} lands cleanly and is reciprocated`, () => {+ const dest = REALMS[p.to];+ expect(dest, `destination realm ${p.to} must exist`).toBeTruthy();++ // Landing tile is in bounds, not a wall, and not under a node.+ expect(walkable(dest, p.toTx, p.toTy), `landing (${p.toTx},${p.toTy}) in ${p.to} walkable`).toBe(true);++ // Landing tile is NOT inside a portal of the destination (no instant bounce).+ const bounced = portalAt(dest, p.toTx, p.toTy);+ expect(bounced, `landing in ${p.to} must not sit on a return portal`).toBeNull();++ // Some portal in the destination points back to this realm (a real round trip).+ const back = dest.portals.some((q) => q.to === name);+ expect(back, `${p.to} should have a portal back to ${name}`).toBe(true);+ });+ }+ }+});++describe('the guide-specified connectivity is wired', () => {+ const links = (from) => new Set(REALMS[from].portals.map((p) => p.to));+ it('Wilderness connects north and east', () => {+ expect(links('wilderness').has('wilderness_north')).toBe(true);+ expect(links('wilderness').has('wilderness_east')).toBe(true);+ });+ it('the Pond also reaches Wilderness East off its north shore', () => {+ expect(links('pond').has('wilderness_east')).toBe(true);+ });+ it('Wilderness North reaches the Cave; the Cave returns to the North', () => {+ expect(links('wilderness_north').has('wilderness_cave')).toBe(true);+ expect(links('wilderness_cave').has('wilderness_north')).toBe(true);+ });+ it('the Mainland plaza opens into the Arena and the Arena returns to it', () => {+ expect(links('mainland').has('arena')).toBe(true);+ expect(links('arena').has('mainland')).toBe(true);+ });+});++describe('the northern cave is combat-LEVEL gated', () => {+ const cavePortal = REALMS.wilderness_north.portals.find((p) => p.to === 'wilderness_cave');++ it('the cave portal carries a combat gate', () => {+ expect(cavePortal.gate).toBeTruthy();+ expect(cavePortal.gate.combat).toBeGreaterThan(1);+ });++ it('no OTHER portal in the world is gated (only the cave guards entry)', () => {+ const gated = [];+ for (const [name, r] of Object.entries(REALMS)) {+ for (const p of r.portals) if (p.gate) gated.push(`${name}->${p.to}`);+ }+ expect(gated).toEqual(['wilderness_north->wilderness_cave']);+ });++ // Mirrors GameRoom._meetsGate, the server's authoritative check.+ const meetsGate = (combat, gate) => !(gate && Number.isFinite(gate.combat) && combat < gate.combat);++ it('an under-level fighter is refused and a qualified one admitted', () => {+ const gate = cavePortal.gate;+ expect(meetsGate(gate.combat - 1, gate)).toBe(false);+ expect(meetsGate(gate.combat, gate)).toBe(true);+ expect(meetsGate(gate.combat + 5, gate)).toBe(true);+ });+});++describe('Arena rollers — direction + walkable footprint', () => {+ const arena = REALMS.arena;++ it('rollerDelta maps each compass direction to a unit step', () => {+ expect(rollerDelta('n')).toEqual([0, -1]);+ expect(rollerDelta('s')).toEqual([0, 1]);+ expect(rollerDelta('e')).toEqual([1, 0]);+ expect(rollerDelta('w')).toEqual([-1, 0]);+ expect(rollerDelta('?')).toEqual([0, 0]); // unknown never moves+ });++ it('every roller tile is itself walkable and uses a known direction', () => {+ const nodes = nodeSet(arena);+ for (const r of arena.rollers) {+ expect(['n', 's', 'e', 'w']).toContain(r.dir);+ for (let tx = r.x0; tx <= r.x1; tx++) {+ for (let ty = r.y0; ty <= r.y1; ty++) {+ expect(walkable(arena, tx, ty, nodes), `roller tile (${tx},${ty})`).toBe(true);+ expect(rollerAt(arena, tx, ty)).toBeTruthy();+ }+ }+ }+ });++ it('a push never shoves a player out of bounds (the strip stays inside the bowl)', () => {+ for (const r of arena.rollers) {+ const [dx, dy] = rollerDelta(r.dir);+ for (let tx = r.x0; tx <= r.x1; tx++) {+ for (let ty = r.y0; ty <= r.y1; ty++) {+ expect(inBounds(arena, tx + dx, ty + dy)).toBe(true);+ }+ }+ }+ });++ it('rollerAt is null off the belts (the spawn floor is free)', () => {+ expect(rollerAt(arena, arena.spawn.tx, arena.spawn.ty)).toBeNull();+ });+});++describe('PvP-immune zones (safe camps + spectator stands)', () => {+ it('Arena seating is a no-PvP zone; the open floor is fair game', () => {+ const seat = REALMS.arena.seating[0];+ expect(inNoPvpZone(REALMS.arena, seat.x0, seat.y0)).toBe(true);+ expect(inNoPvpZone(REALMS.arena, REALMS.arena.spawn.tx, REALMS.arena.spawn.ty)).toBe(false);+ });++ it('the Wilderness safe camp is still a no-PvP zone', () => {+ const camp = REALMS.wilderness.safeCamp;+ expect(inNoPvpZone(REALMS.wilderness, camp.x0, camp.y0)).toBe(true);+ });++ it('seating tiles are walkable (spectators stand on them)', () => {+ for (const stand of REALMS.arena.seating) {+ expect(walkable(REALMS.arena, stand.x0, stand.y0)).toBe(true);+ }+ });+});++describe('realmLayout carries the new client-render fields', () => {+ it('the Arena layout exposes rollers (with dir), seating, and PvP flag', () => {+ const L = realmLayout(REALMS.arena);+ expect(L.pvp).toBe(true);+ expect(L.rollers.length).toBe(REALMS.arena.rollers.length);+ expect(L.rollers[0].dir).toBeTruthy();+ expect(L.seating.length).toBe(REALMS.arena.seating.length);+ });++ it('the cave layout is flagged for enclosed rendering', () => {+ expect(realmLayout(REALMS.wilderness_cave).cave).toBe(true);+ expect(realmLayout(REALMS.mainland).cave).toBe(false);+ });++ it('a gated portal forwards its gate to the client; an open one sends null', () => {+ const north = realmLayout(REALMS.wilderness_north);+ const gated = north.portals.find((p) => p.to === 'wilderness_cave');+ expect(gated.gate.combat).toBe(REALMS.wilderness_north.portals.find((p) => p.to === 'wilderness_cave').gate.combat);+ const open = realmLayout(REALMS.mainland).portals.find((p) => p.to === 'pond');+ expect(open.gate).toBeNull();+ });++ it('the Mainland layout exposes the practice boxing ring', () => {+ expect(realmLayout(REALMS.mainland).ring).toEqual(REALMS.mainland.ring);+ });+});diff --git a/vercel.json b/vercel.jsonindex 61daae43f..2785c2b12 100644--- a/vercel.json+++ b/vercel.json@@ -1959,6 +1959,10 @@"src": "/api/three-token/([^/]+)","dest": "/api/three-token/[action]?action=$1"},+ {+ "src": "/api/token/([^/]+)",+ "dest": "/api/token/[action]?action=$1"+ },{"src": "/api/developer/webhooks/([^/]+)","dest": "/api/developer/webhooks/[id]?id=$1"