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: cosmetics economy, world-gating, build persistence, and holder-pass updates
nirholasd7cb3330b1b9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3f352f6ed..7db33c45e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -24,7 +24,7 @@ Public feature history for [three.ws](https://three.ws), newest first. Feature d## 2026-06-03-- **three.ws on IBM watsonx** (`/ibm`) — three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.+- **three.ws on IBM watsonx — Agent Galaxy** (`/ibm/galaxy`) — three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.## 2026-05-29diff --git a/README.md b/README.mdindex daf13d56b..f8d3fc768 100644--- a/README.md+++ b/README.md@@ -375,7 +375,7 @@ three.ws is indexed in chain-ecosystem dApp directories so the community can dis## IBM watsonx & Granite-three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM Granite** foundation models served through **IBM watsonx.ai**. One IBM Cloud API key + project unlocks the whole suite; every call is real inference (no mock path — endpoints return `503` when unconfigured). Full docs: **[docs/ibm.md](docs/ibm.md)**. Live showcase: **[three.ws/ibm](https://three.ws/ibm)**.+three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM Granite** foundation models served through **IBM watsonx.ai**. One IBM Cloud API key + project unlocks the whole suite; every call is real inference (no mock path — endpoints return `503` when unconfigured). Full docs: **[docs/ibm.md](docs/ibm.md)**. Live showcase: **[three.ws/ibm/galaxy](https://three.ws/ibm/galaxy)**.> **The public showcase is not the partnership.** The demos under `/ibm/*` are independent tools three.ws built for developers to explore Granite on watsonx.ai and build their own integrations — they are not official IBM partnership deliverables, not IBM products, and not endorsed by IBM. Our formal partnership work with IBM is being built on the IBM platform and is not yet public.@@ -387,7 +387,7 @@ three.ws is an **IBM Business Partner**, and the agent runtime runs on **IBM Gra| `granite-embedding-278m-multilingual` | **Semantic** agent map + `/api/watsonx/embed` || `granite-vision-3-2-2b` | **Vision** — reads an avatar into a full agent identity |-Six showcase surfaces put it on screen, linked from the [hub](https://three.ws/ibm): the [Agent Galaxy](https://three.ws/ibm/galaxy) (semantic 3D star-map), the [Granite Oracle](https://three.ws/ibm/oracle) (narrated forecast), the [Digital Twin](https://three.ws/ibm/twin) (back-test + what-if), the [Trust Layer](https://three.ws/ibm/trust-layer) (Guardian + hash-chained audit ledger), [Granite Proof](https://three.ws/ibm/proof) (a Guardian-governed forecast notarized on Solana), and [Granite Vision](https://three.ws/ibm/vision). The standalone connector [`@three-ws/ibm-watsonx-mcp`](packages/ibm-watsonx-mcp/) exposes watsonx.ai to any MCP host — it is community-built and not an IBM product; the hosted platform integration is what runs on IBM watsonx.ai.+Six showcase surfaces put it on screen, cross-linked by an in-page suite switcher: the [Agent Galaxy](https://three.ws/ibm/galaxy) (semantic 3D star-map), the [Granite Oracle](https://three.ws/ibm/oracle) (narrated forecast), the [Digital Twin](https://three.ws/ibm/twin) (back-test + what-if), the [Trust Layer](https://three.ws/ibm/trust-layer) (Guardian + hash-chained audit ledger), [Granite Proof](https://three.ws/ibm/proof) (a Guardian-governed forecast notarized on Solana), and [Granite Vision](https://three.ws/ibm/vision). The standalone connector [`@three-ws/ibm-watsonx-mcp`](packages/ibm-watsonx-mcp/) exposes watsonx.ai to any MCP host — it is community-built and not an IBM product; the hosted platform integration is what runs on IBM watsonx.ai.---diff --git a/api/_lib/builds-store.js b/api/_lib/builds-store.jsnew file mode 100644index 000000000..07aa31f08--- /dev/null+++ b/api/_lib/builds-store.js@@ -0,0 +1,108 @@+// Featured builds store (R20) — the share-a-build half of the /play sandbox.+//+// When a player screenshots their voxel build and publishes it, it lands here:+// a small per-coin "featured builds" surface that links back into the world.+// This reuses the SAME persistence layer as the rest of /play (Upstash Redis,+// the R17 layer the multiplayer block-store writes to) — no new provider.+//+// Layout, kept small so each value stays well under Redis's per-value ceiling:+// - `featured-builds:<mint>` → a JSON array of lightweight index entries+// { id, title, author, blocks, createdAt }, newest first, capped to MAX_FEATURED.+// - `play-build:<id>` → the full record incl. the screenshot thumbnail,+// with a TTL so an entry that ages out of the index doesn't leak forever.+//+// Reads fan the index in over one mget; a build whose per-build key has expired+// is simply dropped from the result, so the index self-heals.++import { Redis } from '@upstash/redis';+import { env } from './env.js';++const INDEX_PREFIX = 'featured-builds:';+const BUILD_PREFIX = 'play-build:';+const MAX_FEATURED = 12; // builds kept per coin+const BUILD_TTL_SEC = 60 * 60 * 24 * 45; // 45 days — long-lived, but self-expiring++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;+}++function indexKey(mint) { return INDEX_PREFIX + mint; }+function buildKey(id) { return BUILD_PREFIX + id; }++function parse(v) {+ if (v == null) return null;+ if (typeof v !== 'string') return v; // Upstash may auto-parse JSON+ try { return JSON.parse(v); } catch { return null; }+}++// List a coin's featured builds, newest first, each with its screenshot. Tolerant+// of a Redis outage / missing index: returns [] rather than throwing so the+// surface always renders (its empty state covers the no-data case).+export async function listBuilds(mint) {+ const r = redis();+ if (!r || !mint) return [];+ let index;+ try {+ index = parse(await r.get(indexKey(mint)));+ } catch (err) {+ console.warn('[builds-store] index read failed:', err?.message);+ return [];+ }+ if (!Array.isArray(index) || index.length === 0) return [];+ let thumbs = [];+ try {+ thumbs = await r.mget(...index.map((e) => buildKey(e.id)));+ } catch (err) {+ console.warn('[builds-store] thumb read failed:', err?.message);+ }+ const out = [];+ index.forEach((entry, i) => {+ const full = parse(thumbs[i]);+ if (!full) return; // expired or missing — drop it (index self-heals on next publish)+ out.push({+ id: entry.id,+ mint,+ title: entry.title || full.title || '',+ author: entry.author || full.author || '',+ blocks: entry.blocks ?? full.blocks ?? 0,+ createdAt: entry.createdAt ?? full.createdAt ?? 0,+ thumb: full.thumb || '',+ coinName: full.coinName || '',+ coinSymbol: full.coinSymbol || '',+ });+ });+ return out;+}++// Publish a build to a coin's featured surface. The caller has already validated+// the payload (mint, title/author lengths, thumb format + size). Returns the+// stored index entry. Throws only on a hard Redis failure the endpoint surfaces+// as a 5xx.+export async function publishBuild(mint, { id, title, author, blocks, thumb, coinName, coinSymbol, createdAt }) {+ const r = redis();+ if (!r) throw new Error('persistence_unavailable');+ const record = { id, mint, title, author, blocks, thumb, coinName, coinSymbol, createdAt };+ await r.set(buildKey(id), JSON.stringify(record), { ex: BUILD_TTL_SEC });++ const entry = { id, title, author, blocks, createdAt };+ let index = [];+ try { index = parse(await r.get(indexKey(mint))) || []; } catch { index = []; }+ if (!Array.isArray(index)) index = [];+ index.unshift(entry);+ // Trim to the cap; drop the per-build keys of anything evicted so they don't+ // linger past their usefulness (TTL would eventually clear them anyway).+ const evicted = index.slice(MAX_FEATURED);+ index = index.slice(0, MAX_FEATURED);+ await r.set(indexKey(mint), JSON.stringify(index));+ if (evicted.length) {+ try { await r.del(...evicted.map((e) => buildKey(e.id))); } catch { /* best-effort */ }+ }+ return entry;+}diff --git a/api/_lib/cosmetics-economy.js b/api/_lib/cosmetics-economy.jsnew file mode 100644index 000000000..8b17ad896--- /dev/null+++ b/api/_lib/cosmetics-economy.js@@ -0,0 +1,523 @@+// Cosmetic creator economy (R25) — coin-tied revenue splits on top of the R22+// avatar-shop rail.+//+// Every /play world IS a pump.fun coin (keyed by its mint). When a player buys a+// premium cosmetic inside a coin's world, the sale is "tied" to that coin: a+// configurable share of the settled USDC is paid out — as a REAL on-chain USDC+// transfer from the platform settlement wallet to the coin's creator wallet+// (reusing api/_lib/solana-transfer.js, the same payout rail the club sweep uses).+// There is no simulated balance: the creator either has a confirmed payout tx or a+// pending/failed accrual a sweep retries.+//+// The split is recorded by the verified-payment handler in+// api/x402/cosmetic-purchase.js (R22), the only writer. The creator-earnings+// dashboard and the platform "rarest fits" leaderboard read the ledger back. All+// amounts are USDC atomics (6 decimals) — the asset x402 actually settles. ($THREE+// stays the only coin the shop quotes value in; it is never a settlement asset.)++import bs58 from 'bs58';++import { sql } from './db.js';+import { getCosmetic } from './cosmetics.js';+import { verifySiwsSignature } from './siws.js';+import { transferSolanaUSDC } from './solana-transfer.js';+import { SOLANA_USDC_MINT } from '../payments/_config.js';+import { loadCoinByMint } from './coin/index.js';++// The default creator share of a coin-tied cosmetic sale, in basis points. A coin+// creator can raise or lower their own share but never above MAX_CREATOR_BPS — the+// platform always keeps a slice to fund the worlds the cosmetics are worn in.+export const DEFAULT_CREATOR_BPS = 5000; // 50%+export const MAX_CREATOR_BPS = 9000; // 90% ceiling++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+// Rarity → flex weight. Drives the "rarest fits" status score: a legendary fit is+// worth far more to a wallet's flex score than a rare one.+export const RARITY_WEIGHT = Object.freeze({ common: 1, rare: 4, epic: 12, legendary: 40 });++export function isMint(mint) {+ return typeof mint === 'string' && BASE58_RE.test(mint);+}+export function isWallet(addr) {+ return typeof addr === 'string' && BASE58_RE.test(addr);+}++// True only when a durable economy DB is configured. Recording is best-effort: a+// missing DB must never block an R22 unlock the buyer already paid for.+export function economyDbConfigured() {+ return !!process.env.DATABASE_URL;+}++// ── Creator resolution ─────────────────────────────────────────────────────++// Resolve the creator wallet that earns a coin's cosmetic share. Order:+// 1. an explicit cosmetic_creator_splits override (the creator set it),+// 2. our own launch record (coin_launches.creator_wallet),+// 3. an agent identity that launched this mint (agent_identities.meta.token),+// 4. the on-chain pump.fun bonding-curve creator (arbitrary community coins).+// Returns { wallet, source }; { wallet:null, source:'none' } when none resolves —+// the sale then settles with no creator leg (full platform revenue).+export async function resolveCreatorWallet(mint, { allowOnchain = true } = {}) {+ if (!isMint(mint)) return { wallet: null, source: 'none' };+ try {+ const [cfg] = await sql`+ select creator_wallet from cosmetic_creator_splits where mint = ${mint} limit 1+ `;+ if (isWallet(cfg?.creator_wallet)) return { wallet: cfg.creator_wallet, source: 'config' };++ const coin = await loadCoinByMint(mint).catch(() => null);+ if (isWallet(coin?.creator_wallet)) return { wallet: coin.creator_wallet, source: 'coin_launches' };++ const [agent] = await sql`+ select meta->'token'->>'creator' as creator+ from agent_identities+ where deleted_at is null and meta->'token'->>'mint' = ${mint}+ limit 1+ `;+ if (isWallet(agent?.creator)) return { wallet: agent.creator, source: 'agent_identity' };+ } catch (err) {+ console.warn('[cosmetics-economy] DB creator lookup failed:', err?.message);+ }++ if (allowOnchain) {+ const onchain = await resolveOnchainPumpCreator(mint);+ if (onchain) return { wallet: onchain, source: 'pumpfun_onchain' };+ }+ return { wallet: null, source: 'none' };+}++// Best-effort on-chain creator from the pump.fun bonding curve. Heavy SDK imports+// are deferred so the common (DB-resolved) path never loads them. Returns null on+// any failure — an unresolvable creator just means "no creator leg".+async function resolveOnchainPumpCreator(mint) {+ try {+ const [{ PublicKey }, { PUMP_SDK, bondingCurvePda }, { getConnection }] = await Promise.all([+ import('@solana/web3.js'),+ import('@pump-fun/pump-sdk'),+ import('./pump.js'),+ ]);+ const conn = getConnection({ network: 'mainnet' });+ const info = await conn.getAccountInfo(bondingCurvePda(new PublicKey(mint)));+ if (!info) return null;+ const curve = typeof PUMP_SDK?.decodeBondingCurve === 'function'+ ? PUMP_SDK.decodeBondingCurve(info)+ : new PUMP_SDK().decodeBondingCurve(info);+ const creator = curve?.creator?.toBase58?.();+ return isWallet(creator) ? creator : null;+ } catch (err) {+ console.warn('[cosmetics-economy] on-chain creator lookup failed:', err?.message);+ return null;+ }+}++// ── Split config ───────────────────────────────────────────────────────────++export function clampCreatorBps(bps) {+ const n = Number(bps);+ if (!Number.isFinite(n)) return DEFAULT_CREATOR_BPS;+ return Math.max(0, Math.min(MAX_CREATOR_BPS, Math.round(n)));+}++// The effective split config for a coin: the creator wallet + share applied to its+// cosmetic sales. Reflects an explicit override when present, otherwise the+// resolved creator at the default share. `isDefault` tells the UI whether the+// creator has customized it yet.+export async function getSplitConfig(mint) {+ if (!isMint(mint)) return null;+ const [row] = await sql`+ select mint, creator_wallet, split_bps, updated_at+ from cosmetic_creator_splits where mint = ${mint} limit 1+ `;+ if (row) {+ return {+ mint: row.mint,+ creatorWallet: row.creator_wallet,+ splitBps: row.split_bps,+ source: 'config',+ isDefault: false,+ updatedAt: row.updated_at,+ maxBps: MAX_CREATOR_BPS,+ };+ }+ const { wallet, source } = await resolveCreatorWallet(mint);+ return {+ mint,+ creatorWallet: wallet,+ splitBps: wallet ? DEFAULT_CREATOR_BPS : 0,+ source,+ isDefault: true,+ updatedAt: null,+ maxBps: MAX_CREATOR_BPS,+ };+}++// The message a creator signs to authorize changing their coin's cosmetic split.+export function splitConfigMessage({ mint, bps, ts }) {+ return `three.ws cosmetic revenue split\nmint: ${mint}\nshare: ${bps} bps\nts: ${ts}`;+}++const SIGNATURE_MAX_AGE_S = 600; // a config-change signature is valid for 10 minutes++// Set a coin's cosmetic split, authorized by an ed25519 signature from the coin's+// creator wallet over splitConfigMessage(). Verifies the signer IS the resolved+// creator, the timestamp is fresh, and the bps is in range. Returns the new+// effective config. Throws { status, code, message, expose } on any failure.+export async function setSplitConfig({ mint, bps, ts, signature, signer }) {+ if (!isMint(mint)) throw fail(400, 'bad_mint', 'Invalid coin mint.');+ const bpsClamped = clampCreatorBps(bps);+ const tsNum = Number(ts);+ if (!Number.isFinite(tsNum)) throw fail(400, 'bad_timestamp', 'Missing or invalid timestamp.');+ const ageS = Math.floor(Date.now() / 1000) - tsNum;+ if (ageS < -60 || ageS > SIGNATURE_MAX_AGE_S) throw fail(400, 'stale_signature', 'Signature timestamp is too old or in the future.');+ if (!isWallet(signer)) throw fail(400, 'bad_signer', 'Invalid signer wallet.');++ const { wallet: creatorWallet } = await resolveCreatorWallet(mint);+ if (!creatorWallet) throw fail(409, 'no_creator', 'No creator wallet is established for this coin yet.');+ if (creatorWallet !== signer) throw fail(403, 'not_creator', 'Only the coin creator can set the cosmetic split.');++ let valid = false;+ try {+ valid = verifySiwsSignature(splitConfigMessage({ mint, bps: bpsClamped, ts: tsNum }), signature, signer);+ } catch { valid = false; }+ if (!valid) throw fail(401, 'bad_signature', 'Signature did not verify against the creator wallet.');++ await sql`+ insert into cosmetic_creator_splits (mint, creator_wallet, split_bps, updated_by)+ values (${mint}, ${creatorWallet}, ${bpsClamped}, ${signer})+ on conflict (mint) do update+ set creator_wallet = excluded.creator_wallet,+ split_bps = excluded.split_bps,+ updated_by = excluded.updated_by+ `;+ return getSplitConfig(mint);+}++// ── Record + pay the creator split ─────────────────────────────────────────++// Decode the platform settlement wallet that fronts creator payouts. This is the+// wallet the x402 Solana settlements land in; ops configures its 64-byte secret+// (base64) so the split can be sent back out on-chain. Returns the bs58 secret+// transferSolanaUSDC expects, or null when unconfigured (payouts then accrue).+function payoutTreasuryBs58() {+ const b64 = process.env.COSMETIC_SPLIT_TREASURY_SECRET_KEY_B64;+ if (!b64) return null;+ try {+ const raw = Buffer.from(b64, 'base64');+ if (raw.byteLength !== 64) {+ console.warn('[cosmetics-economy] COSMETIC_SPLIT_TREASURY_SECRET_KEY_B64 is not a 64-byte secret — payouts disabled.');+ return null;+ }+ return bs58.encode(raw);+ } catch {+ return null;+ }+}++// Record a settled cosmetic sale and pay the coin creator their share on-chain.+// Idempotent on (account, cosmetic): a replayed settle or SIWX re-access conflicts+// and returns the existing record without re-paying. On a fresh sale it resolves+// the creator + share, inserts the ledger row, then BEST-EFFORT pays the creator's+// USDC cut on Solana — a payout failure leaves the row 'pending'/'failed' (the+// buyer still owns the cosmetic; a sweep retries the payout). Never throws to the+// caller: recording/payout must not fail the unlock the buyer already paid for.+//+// @returns {Promise<{ recorded:boolean, alreadyRecorded?:boolean, creatorWallet?:string|null,+// creatorBps?:number, creatorCutAtomics?:string, payoutStatus?:string, payoutTx?:string|null }>}+export async function recordSaleAndSplit({ account, cosmeticId, item, payerWallet, payerNetwork, asset, priceAtomics, mint }) {+ if (!economyDbConfigured()) return { recorded: false };+ const cosmetic = item || getCosmetic(cosmeticId);+ if (!cosmetic) return { recorded: false };++ let priceRaw;+ try { priceRaw = BigInt(priceAtomics || '0'); } catch { priceRaw = 0n; }++ // Resolve the creator + share for this coin world (best-effort).+ let creatorWallet = null;+ let bps = 0;+ if (isMint(mint)) {+ try {+ const cfg = await getSplitConfig(mint);+ if (cfg?.creatorWallet && isWallet(cfg.creatorWallet)) {+ creatorWallet = cfg.creatorWallet;+ bps = clampCreatorBps(cfg.splitBps);+ }+ } catch (err) {+ console.warn('[cosmetics-economy] split config resolve failed:', err?.message);+ }+ }+ // Never pay the creator out of a payment they themselves made.+ if (creatorWallet && payerWallet && creatorWallet === payerWallet) { creatorWallet = null; bps = 0; }+ const cutRaw = creatorWallet && bps > 0 ? (priceRaw * BigInt(bps)) / 10000n : 0n;+ const initialStatus = !creatorWallet || cutRaw <= 0n ? 'none' : 'pending';++ // Insert-or-skip, idempotent on (account, cosmetic). A conflict means we already+ // recorded (and possibly paid) this unlock — return without re-paying.+ let inserted;+ try {+ [inserted] = await sql`+ insert into cosmetic_sales (+ account, payer_wallet, payer_network, mint, cosmetic_id, rarity,+ price_usdc_atomics, asset, creator_wallet, split_bps, creator_cut_atomics, payout_status+ ) values (+ ${account}, ${payerWallet || null}, ${payerNetwork || null}, ${isMint(mint) ? mint : null},+ ${cosmeticId}, ${cosmetic.rarity || 'common'}, ${priceRaw.toString()}, ${asset || null},+ ${creatorWallet}, ${bps}, ${cutRaw.toString()}, ${initialStatus}+ )+ on conflict (account, cosmetic_id) do nothing+ returning id+ `;+ } catch (err) {+ console.error('[cosmetics-economy] sale insert failed:', err?.message);+ return { recorded: false };+ }+ if (!inserted) {+ return { recorded: true, alreadyRecorded: true };+ }++ // Pay the creator their cut on-chain (best-effort). Solana-only: pump.fun+ // creators are Solana wallets, and the platform fronts the USDC on Solana+ // regardless of which network the buyer paid on.+ let payoutStatus = initialStatus;+ let payoutTx = null;+ if (initialStatus === 'pending') {+ const result = await payCreatorCut({ saleId: inserted.id, creatorWallet, cutRaw });+ payoutStatus = result.status;+ payoutTx = result.tx || null;+ }++ return {+ recorded: true,+ alreadyRecorded: false,+ creatorWallet,+ creatorBps: bps,+ creatorCutAtomics: cutRaw.toString(),+ payoutStatus,+ payoutTx,+ };+}++// Send one creator cut on-chain and reconcile the ledger row. Returns the new+// payout status + tx (or the failure). Never throws.+async function payCreatorCut({ saleId, creatorWallet, cutRaw }) {+ const fromWallet = payoutTreasuryBs58();+ if (!fromWallet) {+ await markPayout(saleId, { status: 'skipped', error: 'payout treasury not configured' });+ return { status: 'skipped' };+ }+ try {+ const tx = await transferSolanaUSDC({+ fromWallet,+ toAddress: creatorWallet,+ amount: cutRaw,+ mint: SOLANA_USDC_MINT,+ });+ await markPayout(saleId, { status: 'paid', tx, network: 'solana' });+ return { status: 'paid', tx };+ } catch (err) {+ const reason = err?.message ? String(err.message).slice(0, 300) : 'payout_failed';+ console.error('[cosmetics-economy] creator payout failed:', reason);+ await markPayout(saleId, { status: 'failed', error: reason });+ return { status: 'failed' };+ }+}++async function markPayout(saleId, { status, tx = null, network = null, error = null }) {+ try {+ await sql`+ update cosmetic_sales+ set payout_status = ${status},+ payout_tx = ${tx},+ payout_network = ${network},+ payout_error = ${error},+ paid_at = ${status === 'paid' ? new Date().toISOString() : null}+ where id = ${saleId}+ `;+ } catch (err) {+ console.error('[cosmetics-economy] payout reconcile failed:', err?.message);+ }+}++// Retry creator payouts that haven't landed on-chain (pending/failed). Bounded per+// run. Returns a per-sale outcome list. Safe to call from a cron or an admin tool.+export async function sweepPendingCreatorPayouts({ limit = 25 } = {}) {+ if (!economyDbConfigured()) return { swept: 0, results: [] };+ const rows = await sql`+ select id, creator_wallet, creator_cut_atomics+ from cosmetic_sales+ where payout_status in ('pending', 'failed')+ and creator_wallet is not null+ and creator_cut_atomics > 0+ order by settled_at asc+ limit ${limit}+ `;+ const results = [];+ for (const r of rows) {+ const out = await payCreatorCut({ saleId: r.id, creatorWallet: r.creator_wallet, cutRaw: BigInt(r.creator_cut_atomics) });+ results.push({ id: r.id, status: out.status, tx: out.tx || null });+ }+ return { swept: results.length, results };+}++// ── Creator earnings (dashboard) ───────────────────────────────────────────++const usdc = (raw) => Number(raw || 0) / 1e6;++// Real, settled cosmetic earnings for a creator wallet: lifetime + 30-day totals,+// paid vs. pending, per-coin + per-cosmetic breakdowns, and recent sales. Every+// number is summed straight from the ledger — never estimated.+export async function creatorEarnings(creatorWallet, { recentLimit = 25 } = {}) {+ if (!isWallet(creatorWallet)) return null;++ const [totals] = await sql`+ select+ count(*)::int as sales,+ count(distinct account)::int as buyers,+ coalesce(sum(creator_cut_atomics), 0)::text as earned,+ coalesce(sum(creator_cut_atomics) filter (where payout_status = 'paid'), 0)::text as paid,+ coalesce(sum(creator_cut_atomics) filter (where payout_status in ('pending','failed')), 0)::text as pending,+ coalesce(sum(creator_cut_atomics) filter (where settled_at > now() - interval '30 days'), 0)::text as earned_30d,+ coalesce(sum(price_usdc_atomics), 0)::text as gross,+ min(settled_at) as first_sale_at,+ max(settled_at) as last_sale_at+ from cosmetic_sales+ where creator_wallet = ${creatorWallet}+ `;++ const perCoin = await sql`+ select mint, count(*)::int as sales, coalesce(sum(creator_cut_atomics),0)::text as earned+ from cosmetic_sales where creator_wallet = ${creatorWallet}+ group by mint order by sum(creator_cut_atomics) desc limit 50+ `;+ const perCosmetic = await sql`+ select cosmetic_id, rarity, count(*)::int as sales, coalesce(sum(creator_cut_atomics),0)::text as earned+ from cosmetic_sales where creator_wallet = ${creatorWallet}+ group by cosmetic_id, rarity order by sum(creator_cut_atomics) desc limit 50+ `;+ const recent = await sql`+ select cosmetic_id, rarity, mint, account, price_usdc_atomics, creator_cut_atomics,+ split_bps, payout_status, payout_tx, settled_at+ from cosmetic_sales where creator_wallet = ${creatorWallet}+ order by settled_at desc limit ${recentLimit}+ `;++ return {+ creatorWallet,+ currency: 'USDC',+ totals: {+ sales: totals.sales,+ buyers: totals.buyers,+ earnedUsdc: usdc(totals.earned),+ paidUsdc: usdc(totals.paid),+ pendingUsdc: usdc(totals.pending),+ earned30dUsdc: usdc(totals.earned_30d),+ grossUsdc: usdc(totals.gross),+ firstSaleAt: totals.first_sale_at,+ lastSaleAt: totals.last_sale_at,+ },+ perCoin: perCoin.map((r) => ({ mint: r.mint, sales: r.sales, earnedUsdc: usdc(r.earned) })),+ perCosmetic: perCosmetic.map((r) => ({+ cosmeticId: r.cosmetic_id,+ name: getCosmetic(r.cosmetic_id)?.name || r.cosmetic_id,+ rarity: r.rarity,+ sales: r.sales,+ earnedUsdc: usdc(r.earned),+ })),+ recent: recent.map((r) => ({+ cosmeticId: r.cosmetic_id,+ name: getCosmetic(r.cosmetic_id)?.name || r.cosmetic_id,+ rarity: r.rarity,+ mint: r.mint,+ buyer: r.account,+ priceUsdc: usdc(r.price_usdc_atomics),+ earnedUsdc: usdc(r.creator_cut_atomics),+ splitBps: r.split_bps,+ payoutStatus: r.payout_status,+ payoutTx: r.payout_tx,+ settledAt: r.settled_at,+ })),+ };+}++// ── Leaderboard / rarest fits ──────────────────────────────────────────────++// The platform-wide flex surface, all from settled records:+// • rarestFits — premium cosmetics ranked by scarcity (fewest distinct owners),+// each with a deep link back to a world where it's been bought.+// • topCollectors — accounts ranked by a rarity-weighted flex score.+// • topCreators — creator wallets ranked by real settled cosmetic earnings.+// • recent — the latest settled sales (the live activity drip).+export async function cosmeticsLeaderboard({ limit = 12 } = {}) {+ const ownerRows = await sql`+ select cosmetic_id, account,+ (array_agg(mint) filter (where mint is not null))[1] as any_mint+ from cosmetic_sales+ group by cosmetic_id, account+ `;++ const owners = new Map(); // cosmetic_id → { owners:Set, anyMint }+ const scoreByAccount = new Map(); // account → { score, count }+ for (const row of ownerRows) {+ const c = getCosmetic(row.cosmetic_id);+ if (!c) continue;+ const weight = RARITY_WEIGHT[c.rarity] || 1;+ const o = owners.get(row.cosmetic_id) || { set: new Set(), anyMint: row.any_mint || null };+ o.set.add(row.account);+ if (!o.anyMint && row.any_mint) o.anyMint = row.any_mint;+ owners.set(row.cosmetic_id, o);++ const s = scoreByAccount.get(row.account) || { score: 0, count: 0 };+ s.score += weight; s.count += 1;+ scoreByAccount.set(row.account, s);+ }++ const rarestFits = [...owners.entries()]+ .map(([cosmeticId, o]) => {+ const c = getCosmetic(cosmeticId);+ return {+ cosmeticId,+ name: c.name,+ slot: c.slot,+ rarity: c.rarity,+ owners: o.set.size,+ weight: RARITY_WEIGHT[c.rarity] || 1,+ worldMint: o.anyMint,+ previewImage: c.previewImage || null,+ };+ })+ .sort((a, b) => a.owners - b.owners || b.weight - a.weight)+ .slice(0, limit);++ const topCollectors = [...scoreByAccount.entries()]+ .map(([account, v]) => ({ account, flexScore: v.score, fits: v.count }))+ .sort((a, b) => b.flexScore - a.flexScore || b.fits - a.fits)+ .slice(0, limit);++ const creatorRows = await sql`+ select creator_wallet, count(*)::int as sales, coalesce(sum(creator_cut_atomics),0)::text as earned+ from cosmetic_sales where creator_wallet is not null+ group by creator_wallet order by sum(creator_cut_atomics) desc limit ${limit}+ `;+ const topCreators = creatorRows.map((r) => ({ wallet: r.creator_wallet, sales: r.sales, earnedUsdc: usdc(r.earned) }));++ const recentRows = await sql`+ select cosmetic_id, rarity, mint, account, price_usdc_atomics, settled_at+ from cosmetic_sales order by settled_at desc limit ${limit}+ `;+ const recent = recentRows.map((r) => ({+ cosmeticId: r.cosmetic_id,+ name: getCosmetic(r.cosmetic_id)?.name || r.cosmetic_id,+ rarity: r.rarity,+ mint: r.mint,+ buyer: r.account,+ priceUsdc: usdc(r.price_usdc_atomics),+ settledAt: r.settled_at,+ }));++ return { currency: 'USDC', rarestFits, topCollectors, topCreators, recent };+}++// ── helpers ────────────────────────────────────────────────────────────────++function fail(status, code, message) {+ return Object.assign(new Error(message), { status, code, expose: true });+}diff --git a/api/_lib/feed.js b/api/_lib/feed.jsindex 9aff896ad..56cfe3cf5 100644--- a/api/_lib/feed.js+++ b/api/_lib/feed.js@@ -47,6 +47,7 @@ export const ALLOWED_TYPES = new Set(['jackpot','payment', // skill/service payment confirmed; { usdcAtomic, recipientLabel, txSig, explorerUrl }'mission-complete', // /play job or co-op heist finished; { mission, gold, coop, coin }+ 'member-join', // a person signed in to three.ws; { handle } (actor = display name)]);// Per-user notification types: stored in user_notifications (DB), never in thediff --git a/api/_lib/holder-pass.js b/api/_lib/holder-pass.jsindex ca8c2cc7b..982051257 100644--- a/api/_lib/holder-pass.js+++ b/api/_lib/holder-pass.js@@ -62,18 +62,28 @@ function hmac(body) {/*** Seal a verified holding into a signed pass.- * @param {{ mint: string, wallet: string, usd: number }} claims+ *+ * A coin gates on either the platform USD floor (default) or a creator-set token+ * amount (R24). Both the requirement and the verified holding are signed so the+ * game server and HUD state the real bar without trusting a client value.+ * @param {{ mint: string, wallet: string, usd: number, amount?: number, minTokens?: number }} claims* @returns {string} the compact pass token*/-export function signHolderPass({ mint, wallet, usd }) {+export function signHolderPass({ mint, wallet, usd, amount = 0, minTokens = 0 }) {const now = Math.floor(Date.now() / 1000);const payload = {mint,wallet,usd: Math.round((Number(usd) || 0) * 100) / 100,- // The floor this pass was gated on, signed so the game server can display+ // The verified on-chain token holding, so a token-gated world can show+ // "you hold N / X" instead of a dollar value.+ amount: Math.max(0, Number(amount) || 0),+ // The USD floor this pass was gated on, signed so the game server can display// the real requirement without trusting a client-supplied value.minUsd: HOLDER_MIN_USD,+ // The creator-set token threshold this coin gates on, or 0 when it uses the+ // USD floor above. Signed for the same reason.+ minTokens: Math.max(0, Number(minTokens) || 0),tier: 'holders',iat: now,exp: now + PASS_TTL_S,diff --git a/api/_lib/migrations/20260605000000_cosmetic_economy.sql b/api/_lib/migrations/20260605000000_cosmetic_economy.sqlindex 7ebd439f5..b5278fb39 100644--- a/api/_lib/migrations/20260605000000_cosmetic_economy.sql+++ b/api/_lib/migrations/20260605000000_cosmetic_economy.sql@@ -1,29 +1,26 @@--- Migration: cosmetic creator revenue splits + sales ledger + ownership (R25).+-- Migration: cosmetic creator revenue splits + settled-sale ledger (R25).-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260605000000_cosmetic_economy.sql-- (or `npm run db:migrate`). Idempotent — safe to re-run.----- The /play avatar economy sells premium cosmetics for $THREE inside coin--- communities (each /play world IS a pump.fun coin, keyed by its mint). When a--- cosmetic sells inside a coin's world the settled $THREE splits a configurable--- share to that coin's creator wallet — a REAL on-chain leg in the buyer's--- single signed transaction (see multiplayer/src/game-token.js buildTokenPurchase--- with a `creator` leg). These tables are the queryable record of:+-- Extends the R22 avatar-shop rail (api/x402/cosmetic-purchase.js): a premium+-- cosmetic bought inside a coin's /play world settles real USDC over x402, and a+-- configurable share of that settled USDC is paid out — a REAL on-chain USDC+-- transfer (api/_lib/solana-transfer.js) — to that coin's creator wallet. These+-- tables are the queryable record the creator-earnings dashboard and the platform+-- "rarest fits" leaderboard read. All amounts are USDC atomics (6 decimals), the+-- asset the x402 rail actually settles; the shop quotes value in $THREE separately.----- 1. cosmetic_creator_splits — per-coin config: the creator wallet that--- receives the share and the share itself (basis points, creator-adjustable--- within a platform-enforced ceiling). A missing row means "use the platform--- default share, resolve the creator from launch records".--- 2. cosmetic_sales — one row per settled purchase, idempotent on the on-chain--- signature. Carries every split leg so the creator-earnings dashboard and--- the platform leaderboard read only real, settled numbers.--- 3. cosmetic_ownership — (wallet, cosmetic) the buyer owns, readable by the--- boutique (owned vs. locked) and the rarest-fits flex surface.+-- 1. cosmetic_creator_splits — per-coin config: the creator wallet that earns the+-- share + the share in basis points (creator-adjustable up to a platform cap).+-- 2. cosmetic_sales — one row per settled purchase (idempotent on account++-- cosmetic), carrying the creator cut and the payout's on-chain status/tx so+-- the dashboard shows only real, settled+paid numbers and a sweep can retry a+-- failed payout.begin;--- Per-coin split configuration. `creator_wallet` is the Solana address that--- receives the creator share; `split_bps` is that share in basis points--- (0..10000). Both are clamped in application code to a sane ceiling.+-- Per-coin split configuration. A missing row means "resolve the creator from+-- launch records and apply the platform default share".create table if not exists cosmetic_creator_splits (mint text primary key, -- base58 coin mint (the /play world)creator_wallet text not null, -- base58 Solana address that earns the share@@ -34,24 +31,32 @@ create table if not exists cosmetic_creator_splits (updated_at timestamptz not null default now());--- Settled cosmetic sales. One row per confirmed on-chain purchase. `tx_signature`--- is unique so a replayed settle can never double-record (and the unlock grant is--- idempotent regardless). Every split leg is stored in $THREE base units (strings--- would lose bigint range; columns are numeric(20,0) to hold raw 6-decimal totals).+-- Settled cosmetic sales. One row per (account, cosmetic) — premium unlocks are+-- buy-once-per-account, so this natural key is the idempotency guard: a replayed+-- settle or a SIWX re-access conflicts and never double-records or double-pays.create table if not exists cosmetic_sales (- id uuid primary key default gen_random_uuid(),- tx_signature text not null unique, -- on-chain proof; idempotency key- buyer_wallet text not null, -- base58 buyer- mint text not null, -- coin world the sale was tied to- cosmetic_id text not null, -- catalog id (e.g. 'aura-gold')- rarity text not null default 'common', -- denormalized for the leaderboard- price_three_raw numeric(20,0) not null, -- total $THREE charged (base units)- creator_wallet text, -- recipient of the creator leg (null = none)- creator_raw numeric(20,0) not null default 0, -- creator leg (base units)- treasury_raw numeric(20,0) not null default 0, -- treasury leg- burn_raw numeric(20,0) not null default 0, -- burned leg- split_bps integer not null default 0, -- creator share applied at settle time- settled_at timestamptz not null default now()+ id uuid primary key default gen_random_uuid(),+ account text not null, -- account the cosmetic was granted to+ payer_wallet text, -- paying wallet (may differ from account)+ payer_network text, -- 'base' | 'solana'+ mint text, -- coin world the sale was tied to (null = untied)+ cosmetic_id text not null, -- catalog id (e.g. 'skin-midnight')+ rarity text not null default 'common', -- denormalized for the leaderboard+ price_usdc_atomics numeric(20,0) not null, -- total USDC charged (atomics, 6dp)+ asset text, -- settlement asset address+ creator_wallet text, -- recipient of the creator cut (null = none)+ split_bps integer not null default 0, -- creator share applied at settle time+ creator_cut_atomics numeric(20,0) not null default 0, -- creator cut in USDC atomics+ -- Payout lifecycle: 'none' (no creator/cut), 'pending' (accrued, not yet sent),+ -- 'paid' (on-chain), 'failed' (retriable by the sweep), 'skipped' (no treasury).+ payout_status text not null default 'none'+ check (payout_status in ('none', 'pending', 'paid', 'failed', 'skipped')),+ payout_tx text, -- on-chain signature of the creator payout+ payout_network text, -- network the payout settled on+ payout_error text, -- last failure reason (when 'failed')+ settled_at timestamptz not null default now(),+ paid_at timestamptz,+ unique (account, cosmetic_id));create index if not exists cosmetic_sales_creator@@ -61,28 +66,13 @@ create index if not exists cosmetic_sales_creatorcreate index if not exists cosmetic_sales_minton cosmetic_sales (mint, settled_at desc);-create index if not exists cosmetic_sales_buyer- on cosmetic_sales (buyer_wallet, settled_at desc);-create index if not exists cosmetic_sales_cosmeticon cosmetic_sales (cosmetic_id);--- Owned premium cosmetics. A wallet owns a cosmetic at most once; `mint` records--- the world the unlock was first bought in (so the flex surface can link a fit--- back to where it was earned). Readable by the boutique (owned state) downstream.-create table if not exists cosmetic_ownership (- buyer_wallet text not null,- cosmetic_id text not null,- mint text, -- world the unlock was first bought in- first_acquired_at timestamptz not null default now(),- primary key (buyer_wallet, cosmetic_id)-);--create index if not exists cosmetic_ownership_wallet- on cosmetic_ownership (buyer_wallet);--create index if not exists cosmetic_ownership_cosmetic- on cosmetic_ownership (cosmetic_id);+-- Sweep target: rows whose creator cut hasn't landed on-chain yet.+create index if not exists cosmetic_sales_unpaid+ on cosmetic_sales (payout_status, settled_at)+ where payout_status in ('pending', 'failed');-- Auto-bump updated_at on the config table; reuse the standard trigger fn.do $$ begindiff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 7fe3103e6..c664e18ee 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -214,6 +214,10 @@ export const limits = {snsResolve: (ip) => getLimiter('sns:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),// Generic public read endpoints (explore, showcase, public agent fetch). 60/min per IP.publicIp: (ip) => getLimiter('public:ip', { limit: 60, window: '1 m' }).limit(ip),+ // Publishing a /play build to a coin's featured surface (R20). Each write stores+ // a screenshot in Redis, so cap the burst per IP to keep that bounded; reads use+ // the generic publicIp bucket.+ buildPublishIp: (ip) => getLimiter('build:publish:ip', { limit: 10, window: '10 m' }).limit(ip),// Browser Solana JSON-RPC proxy (api/solana-rpc). Forwards to the keyed// upstream (Helius), so cap per-IP burst to keep the studio launch panel// responsive while preventing anonymous quota drain, plus a global hourlydiff --git a/api/_lib/world-gate.js b/api/_lib/world-gate.jsnew file mode 100644index 000000000..813ce54d4--- /dev/null+++ b/api/_lib/world-gate.js@@ -0,0 +1,79 @@+// Per-coin world gate config — a creator-set token threshold for entering a+// coin's Holders world (R24 token-gated worlds).+//+// By default a coin's Holders world gates on the platform's HOLDER_MIN_USD floor+// (see holder-pass.js). A coin's creator may instead pin a *token amount* —+// "hold ≥ X of the coin to enter" — that overrides the USD floor for their world+// only. Absent config = platform default, so existing worlds are unaffected+// unless a creator opts in.+//+// Storage reuses the shared KV (cache.js → Upstash in prod, in-memory in dev) —+// no new provider. The config is read by api/community/holder-pass.js when it+// prices a joining wallet, and read/written by api/community/world-gate.js (the+// creator panel). The multiplayer server never reads it directly: the signed+// holder pass carries the effective requirement, byte-verified server-side.++import { cacheGet, cacheSet, cacheDel } from './cache.js';++// The KV is durable Upstash in production. We use a long TTL and refresh it on+// every read so an actively-used gate never lapses; a year of total disuse+// expiring back to "platform default" is the safe direction to fail.+const TTL_S = 365 * 24 * 60 * 60;+const KEY = (mint) => `worldgate:${mint}`;++// Guard rails on a creator-set threshold: positive, finite, integer, and bounded+// so a fat-fingered or hostile value can't lock a world to an unreachable number+// (pump.fun supplies are ≤ 1e9 with 6 decimals → ≤ 1e15 base; cap there).+const MAX_MIN_TOKENS = 1e15;++/** Clamp an arbitrary input to a valid token threshold, or 0 when it's no gate. */+export function normalizeMinTokens(v) {+ const n = Number(v);+ if (!Number.isFinite(n) || n <= 0) return 0;+ return Math.min(Math.floor(n), MAX_MIN_TOKENS);+}++/**+ * Read a coin's gate config, or null when the creator hasn't set one (the world+ * then uses the platform USD default). Best-effort: a KV failure reads as "no+ * config" so a transient store hiccup never wrongly locks a world.+ * @param {string} mint+ * @returns {Promise<{ minTokens: number, setBy: string, updatedAt: number } | null>}+ */+export async function readWorldGate(mint) {+ if (!mint) return null;+ let cfg;+ try {+ cfg = await cacheGet(KEY(mint));+ } catch {+ return null;+ }+ if (!cfg || typeof cfg !== 'object') return null;+ const minTokens = normalizeMinTokens(cfg.minTokens);+ if (minTokens <= 0) return null;+ // Touch the TTL so a live gate doesn't expire under an active community.+ cacheSet(KEY(mint), { ...cfg, minTokens }, TTL_S).catch(() => {});+ return {+ minTokens,+ setBy: typeof cfg.setBy === 'string' ? cfg.setBy : '',+ updatedAt: Number(cfg.updatedAt) || 0,+ };+}++/**+ * Set — or clear, when minTokens ≤ 0 — a coin's gate config.+ * @param {string} mint+ * @param {{ minTokens: number }} params+ * @param {string} setBy creator wallet that set it (for display/audit)+ * @returns {Promise<{ minTokens: number, setBy: string, updatedAt: number } | null>} the stored config, or null when cleared+ */+export async function writeWorldGate(mint, { minTokens }, setBy = '') {+ const n = normalizeMinTokens(minTokens);+ if (n <= 0) {+ await cacheDel(KEY(mint));+ return null;+ }+ const cfg = { minTokens: n, setBy: setBy || '', updatedAt: Date.now() };+ await cacheSet(KEY(mint), cfg, TTL_S);+ return cfg;+}diff --git a/api/community/holder-pass.js b/api/community/holder-pass.jsindex 8cebb97cd..41a42c0ba 100644--- a/api/community/holder-pass.js+++ b/api/community/holder-pass.js@@ -22,6 +22,7 @@ import { clientIp, limits } from '../_lib/rate-limit.js';import { cc, userAuthHeaders, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';import { getBalances, solanaMintUsdPrice } from '../_lib/balances.js';import { HOLDER_MIN_USD, signHolderPass } from '../_lib/holder-pass.js';+import { readWorldGate } from '../_lib/world-gate.js';const SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -121,9 +122,16 @@ export default wrap(async (req, res) => {const wallet = primaryWallet;const minUsd = HOLDER_MIN_USD;- if (usd >= minUsd) {- const holderPass = signHolderPass({ mint: token, wallet, usd });- return json(res, 200, { data: { eligible: true, usd, amount, minUsd, wallet, holderPass } });+ // A coin's creator may pin a token-amount threshold (R24); absent that, the+ // world gates on the platform USD floor. Read it best-effort — a KV hiccup+ // falls back to the USD floor rather than wrongly locking the world.+ const gate = await readWorldGate(token);+ const minTokens = gate?.minTokens || 0;+ const eligible = minTokens > 0 ? amount >= minTokens : usd >= minUsd;++ if (eligible) {+ const holderPass = signHolderPass({ mint: token, wallet, usd, amount, minTokens });+ return json(res, 200, { data: { eligible: true, usd, amount, minUsd, minTokens, wallet, holderPass } });}- return json(res, 200, { data: { eligible: false, usd, amount, minUsd, wallet } });+ return json(res, 200, { data: { eligible: false, usd, amount, minUsd, minTokens, wallet } });});diff --git a/api/community/world-gate.js b/api/community/world-gate.jsnew file mode 100644index 000000000..22ca9c1c8--- /dev/null+++ b/api/community/world-gate.js@@ -0,0 +1,134 @@+// GET /api/community/world-gate?token=<mint> — read a coin's world gate+// POST /api/community/world-gate?token=<mint> — set it (coin creator only)+//+// R24 token-gated worlds. A coin's creator may require holding ≥ X of the coin to+// enter its Holders world, overriding the platform USD floor. The threshold is a+// token amount; setting 0 (or omitting it) clears the gate back to the default.+//+// GET is public so the lobby and gate screen can state the requirement; it adds+// `canEdit: true` only when the signed-in user's linked Solana wallet is the+// coin's on-chain creator. POST re-verifies that ownership server-side before+// writing — the browser never asserts who the creator is.+//+// Responses:+// GET { mint, gated, minTokens, canEdit }+// POST { mint, gated, minTokens } — on success+// 401 auth_required — POST without a CoinCommunities session+// 403 not_creator — signed in, but not this coin's creator+// 403 wallet_required — signed in, but no linked Solana wallet to match+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { cc, userAuthHeaders, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';+import { readWorldGate, writeWorldGate, normalizeMinTokens } from '../_lib/world-gate.js';++const PUMP_FRONTEND_BASE = process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';+const MAX_WALLETS_CHECKED = 5;++// Resolve a coin's on-chain creator from pump.fun. Returns '' when unknown (a+// non-pump mint, or pump didn't answer) so the caller fails closed (not creator).+async function resolveCoinCreator(mint) {+ try {+ const resp = await fetch(new URL(`/coins/${mint}`, PUMP_FRONTEND_BASE), {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(8000),+ });+ if (!resp.ok) return '';+ const body = await resp.json();+ const creator = typeof body?.creator === 'string' ? body.creator.trim() : '';+ return creator;+ } catch {+ return '';+ }+}++// The signed-in user's linked Solana wallets, or { error } shaped like the SDK's.+async function linkedSvmWallets(api, headers) {+ const w = await api.getWallets({ headers });+ if (w.error) return { error: w.error };+ const wallets = (w.data?.wallets ?? [])+ .filter((x) => x.chainType === 'svm')+ .map((x) => x.address)+ .filter(Boolean)+ .slice(0, MAX_WALLETS_CHECKED);+ return { wallets };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', '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');++ const mint = new URL(req.url, 'http://x').searchParams.get('token');+ if (!isValidToken(mint)) {+ return error(res, 400, 'validation_error', 'valid token query param required');+ }++ const headers = userAuthHeaders(req);++ if (req.method === 'GET') {+ const gate = await readWorldGate(mint);+ const minTokens = gate?.minTokens || 0;+ // Whether the requester may edit: signed in, with a linked wallet that is the+ // coin's creator. Best-effort — any failure just yields canEdit:false (the+ // read still succeeds), so the requirement is always visible.+ let canEdit = false;+ if (headers) {+ try {+ const api = cc();+ const [{ wallets = [] }, creator] = await Promise.all([+ linkedSvmWallets(api, headers).then((r) => r.error ? { wallets: [] } : r),+ resolveCoinCreator(mint),+ ]);+ canEdit = !!creator && wallets.includes(creator);+ } catch { /* canEdit stays false */ }+ }+ return json(res, 200, { data: { mint, gated: minTokens > 0, minTokens, canEdit } });+ }++ // POST — set the threshold. Creator-only.+ if (!headers) {+ return error(res, 401, 'auth_required', 'sign in with X to manage this world');+ }++ let api;+ try {+ api = cc();+ } catch (err) {+ if (err instanceof UnconfiguredError) {+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');+ }+ throw err;+ }++ // Parse the body before any upstream calls so a bad request fails fast.+ let minTokens = 0;+ try {+ const raw = await readJson(req);+ minTokens = normalizeMinTokens(raw?.minTokens);+ } catch {+ return error(res, 400, 'validation_error', 'body must be JSON { minTokens }');+ }++ const { wallets, error: walletErr } = await linkedSvmWallets(api, headers);+ if (walletErr) {+ if (walletErr.statusCode === 401) return error(res, 401, 'auth_required', 'session expired — sign in again');+ return error(res, 502, 'upstream_error', walletErr.message || 'failed to read wallets');+ }+ if (!wallets.length) {+ return error(res, 403, 'wallet_required', 'link the creator wallet to manage this world');+ }++ const creator = await resolveCoinCreator(mint);+ if (!creator) {+ return error(res, 502, 'creator_unresolved', 'could not resolve this coin’s creator — try again');+ }+ if (!wallets.includes(creator)) {+ return error(res, 403, 'not_creator', 'only the coin’s creator can gate this world');+ }++ const cfg = await writeWorldGate(mint, { minTokens }, creator);+ return json(res, 200, { data: { mint, gated: !!cfg, minTokens: cfg?.minTokens || 0 } });+});diff --git a/api/cosmetics/catalog.js b/api/cosmetics/catalog.jsindex a5deea8e8..8450787da 100644--- a/api/cosmetics/catalog.js+++ b/api/cosmetics/catalog.js@@ -4,15 +4,19 @@* Returns every shop item with its shop fields (id, name, slot, rarity, price,* previewImage, owned/locked) and the rig payload the live preview needs. The* base accessory pack is owned/free; premium emotes + skins are locked until- * purchased (R22 x402 flow / R23 inventory). Prices are denominated in $THREE.+ * purchased over the R22 x402 USDC rail. The item's value is quoted in $THREE+ * (`price`/`currency`); checkout charges USDC (`priceUsdc`/`priceUsdcAtomics`).** Query params:* rarity=common|rare|epic|legendary — optional filter to one tier.+ * account=<wallet|guest id> — optional; when present, premium items+ * this account has purchased read as owned.*/import { cors, json, method, wrap, error } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { buildCatalog, RARITIES } from '../_lib/cosmetics.js';+import { readOwnedCosmetics, normalizeAccountId } from '../_lib/cosmetics-ownership.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;@@ -27,13 +31,18 @@ export default wrap(async (req, res) => {return error(res, 400, 'bad_rarity', `rarity must be one of: ${RARITIES.join(', ')}`);}- // Ownership beyond the free base pack is wired in R23 (wallet-bound- // inventory). Until then every premium item reads as locked.- const items = buildCatalog({ rarity: rarity || null });+ // When the caller identifies an account, fold in the cosmetics it has bought+ // over the R22 x402 rail so premium items it owns render as owned, not locked.+ // Anonymous callers (no account) see every premium item locked.+ const account = normalizeAccountId(url.searchParams.get('account'));+ const ownedIds = account ? await readOwnedCosmetics(account) : [];- // Catalog is static content — cache hard at the edge, but let the client- // revalidate so a deploy that changes the pack propagates promptly.- return json(res, 200, { items, rarities: RARITIES }, {- 'cache-control': 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400',- });+ const items = buildCatalog({ rarity: rarity || null, ownedIds });++ // Per-account responses must not be shared at the edge; the anonymous catalog+ // is static and cacheable. Vary so a CDN never crosses the two.+ const cacheControl = account+ ? 'private, no-store'+ : 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400';+ return json(res, 200, { items, rarities: RARITIES }, { 'cache-control': cacheControl });});diff --git a/api/play/builds.js b/api/play/builds.jsnew file mode 100644index 000000000..2ec526d26--- /dev/null+++ b/api/play/builds.js@@ -0,0 +1,82 @@+// /api/play/builds — featured builds for a coin's /play world (R20).+//+// GET ?mint=<mint> → { builds: [...] } newest first+// POST { mint, title, author, blocks, thumb } → { ok, id }+//+// A "build" is a player's screenshot of their voxel creation plus a little+// metadata. Storage reuses the same Upstash Redis the rest of /play persists to+// (the R17 layer) — see api/_lib/builds-store.js. The surface that renders these+// lives in the /play client (coincommunities-ui.js); each card links back into+// the coin's world.+import { z } from 'zod';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';+import { listBuilds, publishBuild } from '../_lib/builds-store.js';++// Mirror the client/server build caps so a forged payload can't claim an+// impossible size. MAX_BLOCKS matches build-voxels.js / WalkRoom.+const MAX_BLOCKS = 6000;+// A downscaled JPEG thumbnail (~720px wide, q0.72) is tens of KB; cap the data+// URL well above that but far below Redis's per-value ceiling so one oversized+// screenshot can't bloat a coin's storage.+const MAX_THUMB_CHARS = 280_000; // ~210 KB decoded++const publishSchema = z.object({+ mint: z.string().trim().min(32).max(64),+ title: z.string().trim().max(60).optional().default(''),+ author: z.string().trim().max(32).optional().default(''),+ blocks: z.number().int().min(0).max(MAX_BLOCKS),+ thumb: z.string()+ .regex(/^data:image\/(jpeg|png|webp);base64,/, 'thumb must be a base64 image data URL')+ .max(MAX_THUMB_CHARS, 'thumb too large'),+});++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ if (req.method === 'GET') {+ res.setHeader('cache-control', 'public, max-age=15, stale-while-revalidate=60');+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ const mint = String(req.query?.mint || '').trim();+ if (!mint || mint.length < 32 || mint.length > 64) {+ return error(res, 400, 'bad_mint', 'a valid coin mint is required');+ }+ try {+ const builds = await listBuilds(mint);+ return json(res, 200, { builds });+ } catch (err) {+ console.error('[play/builds] list failed:', err?.message);+ return error(res, 502, 'list_failed', 'could not load featured builds');+ }+ }++ // POST — publish a build.+ res.setHeader('cache-control', 'no-store');+ const rl = await limits.buildPublishIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'sharing too fast — try again shortly');++ const parsed = publishSchema.safeParse(await readJson(req, MAX_THUMB_CHARS + 2048).catch(() => null));+ if (!parsed.success) {+ const tooBig = parsed.error?.issues?.some((i) => /too large/.test(i.message));+ if (tooBig) return error(res, 413, 'thumb_too_large', 'screenshot too large to share');+ return error(res, 400, 'validation_error', 'mint, blocks and a screenshot are required');+ }+ const { mint, title, author, blocks, thumb } = parsed.data;+ const id = (globalThis.crypto?.randomUUID?.() || `b_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`);+ try {+ await publishBuild(mint, {+ id, title, author, blocks, thumb,+ coinName: '', coinSymbol: '',+ createdAt: Date.now(),+ });+ return json(res, 201, { ok: true, id });+ } catch (err) {+ if (err?.message === 'persistence_unavailable') {+ return error(res, 503, 'unavailable', 'sharing is temporarily unavailable');+ }+ console.error('[play/builds] publish failed:', err?.message);+ return error(res, 502, 'publish_failed', 'could not publish build');+ }+});diff --git a/api/x402/cosmetic-purchase.js b/api/x402/cosmetic-purchase.jsindex bffcf2615..ecb4977ca 100644--- a/api/x402/cosmetic-purchase.js+++ b/api/x402/cosmetic-purchase.js@@ -25,6 +25,7 @@ import { error } from '../_lib/http.js';import { env } from '../_lib/env.js';import { getCosmetic, priceUsdcAtomicsOf } from '../_lib/cosmetics.js';import { grantCosmeticOwnership, normalizeAccountId } from '../_lib/cosmetics-ownership.js';+import { recordSaleAndSplit, isMint } from '../_lib/cosmetics-economy.js';const ROUTE = '/api/x402/cosmetic-purchase';@@ -91,6 +92,18 @@ const OUTPUT_SCHEMA = {network: { type: ['string', 'null'] },amountAtomics: { type: ['string', 'null'] },asset: { type: ['string', 'null'] },+ // Coin the sale was tied to (R25), and the creator split that paid out.+ coin: { type: ['string', 'null'] },+ split: {+ type: ['object', 'null'],+ properties: {+ creatorWallet: { type: ['string', 'null'] },+ creatorBps: { type: 'number' },+ creatorCutAtomics: { type: 'string' },+ payoutStatus: { type: 'string' },+ payoutTx: { type: ['string', 'null'] },+ },+ },},};@@ -122,6 +135,12 @@ export default async function handler(req, res) {'query parameter "account" is required (a Solana wallet or guest id)');}+ // Coin-tied sale (R25): when bought inside a coin's /play world, the optional+ // `coin` mint ties the sale to that coin so a configurable share of the settled+ // USDC pays out to the coin's creator. Untied (no/invalid coin) → full platform+ // revenue, exactly as before.+ const coin = isMint(String(req.query?.coin || '').trim()) ? String(req.query.coin).trim() : null;+const item = getCosmetic(id);if (!item) {return error(res, 404, 'cosmetic_not_found', `no cosmetic with id "${id}"`);@@ -163,6 +182,36 @@ export default async function handler(req, res) {// a charge we can't record. Idempotent: a re-paid/replayed call just// re-confirms the existing unlock.const newlyOwned = await grantCosmeticOwnership(account, item.id);++ // Coin-tied creator split (R25). Only on a fresh, genuinely-settled+ // purchase: `requirement` is null on the SIWX free-re-access path, and+ // newlyOwned is false on a re-grant — either way we never re-record or+ // re-pay. The split records the sale and pays the creator's USDC cut+ // on-chain; it's best-effort and never throws, so a recording/payout+ // hiccup can't undo the unlock the buyer already paid for.+ let split = null;+ if (requirement && newlyOwned) {+ const result = await recordSaleAndSplit({+ account,+ cosmeticId: item.id,+ item,+ payerWallet: payer ?? null,+ payerNetwork: requirement?.network ?? null,+ asset: requirement?.asset ?? null,+ priceAtomics: requirement?.amount ?? priceAtomics,+ mint: coin,+ });+ if (result?.creatorWallet) {+ split = {+ creatorWallet: result.creatorWallet,+ creatorBps: result.creatorBps,+ creatorCutAtomics: result.creatorCutAtomics,+ payoutStatus: result.payoutStatus,+ payoutTx: result.payoutTx ?? null,+ };+ }+ }+return {ok: true,id: item.id,@@ -176,6 +225,8 @@ export default async function handler(req, res) {network: requirement?.network ?? null,amountAtomics: requirement?.amount ?? null,asset: requirement?.asset ?? null,+ coin: coin ?? null,+ split,};},});diff --git a/data/pages.json b/data/pages.jsonindex e05067228..531157960 100644--- a/data/pages.json+++ b/data/pages.json@@ -80,8 +80,8 @@"added": "2026-05-25"},{- "path": "/ibm",- "title": "three.ws on IBM watsonx",+ "path": "/ibm/galaxy",+ "title": "three.ws on IBM watsonx — Agent Galaxy","description": "three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.","priority": 0.7,"changefreq": "weekly",diff --git a/multiplayer/src/block-store.js b/multiplayer/src/block-store.jsindex 2bcfc9e74..54434f718 100644--- a/multiplayer/src/block-store.js+++ b/multiplayer/src/block-store.js@@ -158,7 +158,13 @@ class BlockStore {await this._redis.del(redisKey(coin));} else {const obj = {};- for (const [k, rec] of map) obj[k] = [rec.t, rec.o || ''];+ for (const [k, rec] of map) {+ // Tolerate a raw-number value (a direct map mutation) as well as the+ // canonical { t, o } record, so the serialized form is always a+ // [type, owner] pair regardless of how the cell got into the map.+ const r = decodeCell(rec);+ if (r) obj[k] = [r.t, r.o || ''];+ }await this._redis.set(redisKey(coin), JSON.stringify(obj));}// A successful write proves durability is back; reset the failure streak.diff --git a/multiplayer/src/holder-pass.js b/multiplayer/src/holder-pass.jsindex 7dd95918f..46ebf9eb6 100644--- a/multiplayer/src/holder-pass.js+++ b/multiplayer/src/holder-pass.js@@ -51,7 +51,7 @@ function safeEqual(a, b) {* Verify a holder pass and return its payload, or null if the token is missing,* malformed, tampered with, or expired.* @param {unknown} token- * @returns {{ mint: string, wallet: string, usd: number, minUsd?: number, tier: string, iat: number, exp: number } | null}+ * @returns {{ mint: string, wallet: string, usd: number, amount?: number, minUsd?: number, minTokens?: number, tier: string, iat: number, exp: number } | null}*/export function verifyHolderPass(token) {if (typeof token !== 'string' || token.length < 16 || token.length > 4096) return null;@@ -85,5 +85,10 @@ export function verifyHolderPass(token) {// game server displays it as the gate requirement). Tolerate its absence so a// pass minted by an older signer during a rollout still verifies.if (payload.minUsd != null && (typeof payload.minUsd !== 'number' || !Number.isFinite(payload.minUsd) || payload.minUsd < 0)) return null;+ // minTokens (the creator-set threshold) and amount (the verified holding) are+ // optional — a pass from an older signer during a rollout omits them — but when+ // present must be sane numbers, since the game server displays them as the gate.+ if (payload.minTokens != null && (typeof payload.minTokens !== 'number' || !Number.isFinite(payload.minTokens) || payload.minTokens < 0)) return null;+ if (payload.amount != null && (typeof payload.amount !== 'number' || !Number.isFinite(payload.amount) || payload.amount < 0)) return null;return payload;}diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex 268c7b56b..818265e72 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -26,8 +26,12 @@ import {addItem, hasRoomFor, resolveSlot, grantXp, consumeSlot,countItem, removeItem,dropCarried, reviveProfile, bankTransfer,+ equipCosmetic, ownedCosmeticSet,HOTBAR_SIZE,} from '../economy.js';+import {+ serializeLoadout, getCosmetic, canWear,+} from '../cosmetics-catalog.js';import {itemLabel, fishCatchChance, fishDoubleChance,gatherChance, gatherDoubleChance, coalBonusChance, cookBurnChance,@@ -293,7 +297,14 @@ 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 = { ...(client.userData || {}), holderUsd: pass.usd, holderWallet: pass.wallet, holderMinUsd: pass.minUsd };+ client.userData = {+ ...(client.userData || {}),+ holderUsd: pass.usd,+ holderWallet: pass.wallet,+ holderMinUsd: pass.minUsd,+ holderMinTokens: pass.minTokens,+ holderAmount: pass.amount,+ };return true;}@@ -344,11 +355,16 @@ export class WalkRoom extends Room {// HOLDER_MIN_USD), not the client's unsigned `holderMinUsd` option which a// malicious first-joiner could otherwise use to misstate the requirement// for everyone in the room. Fall back to the server's own env, then 8.- const signed = verifyHolderPass(options?.holderPass)?.minUsd;+ const signedPass = verifyHolderPass(options?.holderPass);+ const signed = signedPass?.minUsd;const envMin = Number(process.env.HOLDER_MIN_USD);this.state.holderMinUsd = Number.isFinite(signed) && signed > 0? signed: (Number.isFinite(envMin) && envMin > 0 ? envMin : 8);+ // R24: when the creator pinned a token threshold, record it from the signed+ // pass (never the unsigned option) so the HUD states "hold N $SYM to enter".+ const signedTokens = signedPass?.minTokens;+ this.state.holderMinTokens = Number.isFinite(signedTokens) && signedTokens > 0 ? signedTokens : 0;}// Persisted-build key. General and Holders are separate worlds for the same// coin, so their voxel builds must persist independently — otherwise the two@@ -373,6 +389,10 @@ export class WalkRoom extends Room {registerActivityHandlers(this); // W06 gather/craft: chop, mine, cookthis.onMessage('equip', (client, payload) => this._handleEquip(client, payload));this.onMessage('consume', (client, payload) => this._handleConsume(client, payload));+ // Equip/unequip a cosmetic from the owned-inventory (R23). Server-authoritative:+ // validates ownership, persists the loadout to the account, re-publishes it on+ // the schema so peers re-render, and echoes the owner a fresh profile.+ this.onMessage('equip-cosmetic', (client, payload) => this._handleEquipCosmetic(client, payload));this.onMessage('profileReq', (client) => this._sendProfile(client));// Quests, jobs & heists (W05, off-schema). The board, accepting/abandoning a// mission, and acting at a quest object all flow through here; the server is the@@ -558,6 +578,9 @@ export class WalkRoom extends Room {onLeave(client) {if (client.userData?.accountUid) socialHub.unregister(client.userData.accountUid, client);+ // Resolve this owner's object key up front — _ownerKey reads the econ profile,+ // which the block below deletes, so capture it before reaping their objects.+ const ownerKey = this._ownerKey(client.sessionId);// Free any vehicle this player was driving so it parks where it was left and// becomes available again — otherwise a disconnect would lock a car forever.this._releaseVehicleOf(client.sessionId);@@ -574,9 +597,8 @@ export class WalkRoom extends Room {}// Reap this owner's transient objects (R01): balls and fx they spawned die// with their session. Their durable build props stay as part of the world- // (R17) — that's the whole point of persistence. Computed before the player- // is removed from state so _ownerKey can still read their account.- this._reapOwnerTransients(this._ownerKey(client));+ // (R17) — that's the whole point of persistence.+ this._reapOwnerTransients(ownerKey);this.state.players.delete(client.sessionId);this._moveCounters.delete(client.sessionId);this._chatCooldowns.delete(client.sessionId);@@ -874,6 +896,48 @@ export class WalkRoom extends Room {this._persistEcon(client.sessionId);}+ // Dress the player from a pre-join loadout wire (the character-creator / a+ // world hand-off in `cosmetics` join option), merged on top of their persisted+ // loadout and validated per id against what they own — free cosmetics always+ // pass, premium only when unlocked — so a join option can never put an unowned+ // cosmetic on a player. Mutates profile.cosmetics.equipped in place.+ _applyJoinCosmetics(profile, wire) {+ if (!profile.cosmetics) profile.cosmetics = { owned: [], equipped: {} };+ if (typeof wire !== 'string' || !wire) return;+ const owned = ownedCosmeticSet(profile);+ for (const raw of wire.split(',')) {+ const id = raw.trim();+ const c = getCosmetic(id);+ if (c && canWear(id, owned)) profile.cosmetics.equipped[c.slot] = id;+ }+ }++ // Equip/unequip one cosmetic into its slot (R23). The economy validates the id+ // is owned (or free) before it moves — an unowned id is rejected, never worn —+ // then we re-publish the loadout on the schema (peers re-render the fit), echo+ // the owner a fresh profile (inventory reflects the new equipped state), and+ // persist to the account so it survives logout and applies in every world.+ // Unequip is just equipping the slot's `none` default (always free).+ _handleEquipCosmetic(client, payload) {+ const profile = this.econ.get(client.sessionId);+ if (!profile) return;+ if (!this._actionOk(client.sessionId, 'equip')) return;+ const id = typeof payload?.id === 'string' ? payload.id.slice(0, 64) : '';+ if (!getCosmetic(id)) {+ client.send('notice', { kind: 'cosmetic', text: 'That cosmetic doesn’t exist.' });+ return;+ }+ const equipped = equipCosmetic(profile, id);+ if (!equipped) {+ client.send('notice', { kind: 'cosmetic', text: 'You don’t own that cosmetic yet.' });+ return;+ }+ const player = this.state.players.get(client.sessionId);+ if (player) player.cosmetics = serializeLoadout(profile.cosmetics.equipped);+ this._sendProfile(client);+ this._persistEcon(client.sessionId);+ }+// Select a hotbar slot (what the player is "holding"). -1 clears the hand._handleEquip(client, payload) {const profile = this.econ.get(client.sessionId);@@ -1259,6 +1323,187 @@ export class WalkRoom extends Room {this._sendBuildPerms(client);}+ // ── Generic world objects (R01 protocol) ────────────────────────────────────+ //+ // The shared `objects` MapSchema carries every non-player, non-voxel world+ // entity: thrown balls, placed build props, pickups, fx. Three client messages+ // drive it; the server is authoritative on ids, ownership, bounds and lifetime.+ //+ // obj:spawn { id?, type?, kind?, x, y, z, yaw?, scale?, vx?, vy?, vz? }+ // Any joined player. x/y/z required + finite. The server assigns ownerId+ // (the sender's account, else sessionId), accepts a sane unused `id` or+ // mints one, clamps position to the world bound and scale to [0.1, 10],+ // and stamps ts. Rejected (obj:reject {reason}) when the room is at+ // MAX_WORLD_OBJECTS or the player at MAX_OBJECTS_PER_PLAYER. Clients can+ // never spawn a 'server'-owned object.+ // obj:update { id, x?, y?, z?, yaw?, scale?, vx?, vy?, vz? }+ // Owner only. Server-owned objects (ownerId === 'server', e.g. the R05+ // physics ball) are moved by the server's own simulation, never a client.+ // Position re-clamped to bounds, scale to range.+ // obj:remove { id }+ // Owner, or the coin creator (world moderation). No one else can.+ //+ // Limits: each handler is rate-limited per client (OBJ_OPS_PER_SEC_LIMIT),+ // positions are bounds-clamped, NaN/Infinity payloads are dropped, and totals+ // are capped per room and per player. Lifetime: on owner disconnect their+ // transient objects are reaped (_reapOwnerTransients); durable build props stay+ // and are persisted per coin world (R17). A `kind` in TRANSIENT_OBJECT_KINDS+ // (or a 'server'-owned object) is transient and never written to storage.++ _handleObjSpawn(client, payload) {+ if (!this.state.players.has(client.sessionId)) return;+ if (!this._objOk(client.sessionId)) return;+ if (!payload || typeof payload !== 'object') return;+ // Position is mandatory and must be finite — a NaN slips past clamps.+ if (!Number.isFinite(payload.x) || !Number.isFinite(payload.y) || !Number.isFinite(payload.z)) return;+ if (this.state.objects.size >= MAX_WORLD_OBJECTS) { client.send('obj:reject', { reason: 'world_full' }); return; }++ const owner = this._ownerKey(client.sessionId);+ let owned = 0;+ for (const [, o] of this.state.objects) if (o.ownerId === owner) owned++;+ if (owned >= MAX_OBJECTS_PER_PLAYER) { client.send('obj:reject', { reason: 'player_full' }); return; }++ const obj = new WorldObject();+ // Accept a client-supplied id only if it's a sane, unused token; otherwise the+ // server mints a collision-free one. Either way ids stay server-controlled.+ let id = (typeof payload.id === 'string' && OBJ_ID_RE.test(payload.id)) ? payload.id : '';+ if (!id || this.state.objects.has(id)) id = `o_${client.sessionId.slice(0, 6)}_${++this._objSeq}`;+ obj.id = id;+ obj.type = typeof payload.type === 'string' ? payload.type.slice(0, OBJ_STR_MAX) : '';+ // Ownership is assigned here; a client can never claim the 'server' sentinel.+ obj.ownerId = owner;+ obj.kind = typeof payload.kind === 'string' ? payload.kind.slice(0, OBJ_STR_MAX) : '';+ obj.scale = objClamp(objNum(payload.scale, 1), OBJ_SCALE_MIN, OBJ_SCALE_MAX);+ obj.yaw = objNum(payload.yaw, 0);+ this._clampObjPos(obj, payload);+ obj.vx = objNum(payload.vx, 0);+ obj.vy = objNum(payload.vy, 0);+ obj.vz = objNum(payload.vz, 0);+ obj.ts = Date.now();+ this.state.objects.set(obj.id, obj);+ if (this._objectIsPersistent(obj)) this._persistObjects();+ }++ _handleObjUpdate(client, payload) {+ if (!this._objOk(client.sessionId)) return;+ if (!payload || typeof payload.id !== 'string') return;+ const obj = this.state.objects.get(payload.id);+ if (!obj) return;+ // Server-owned objects (the R05 ball) are driven by the server, never a+ // client; and only the owner may move their own object.+ if (obj.ownerId === SERVER_OBJECT_OWNER) return;+ if (obj.ownerId !== this._ownerKey(client.sessionId)) return;+ this._clampObjPos(obj, payload);+ if (Number.isFinite(payload.yaw)) obj.yaw = payload.yaw;+ if (Number.isFinite(payload.scale)) obj.scale = objClamp(payload.scale, OBJ_SCALE_MIN, OBJ_SCALE_MAX);+ obj.vx = objNum(payload.vx, obj.vx);+ obj.vy = objNum(payload.vy, obj.vy);+ obj.vz = objNum(payload.vz, obj.vz);+ obj.ts = Date.now();+ if (this._objectIsPersistent(obj)) this._persistObjects();+ }++ _handleObjRemove(client, payload) {+ if (!this._objOk(client.sessionId)) return;+ if (!payload || typeof payload.id !== 'string') return;+ const obj = this.state.objects.get(payload.id);+ if (!obj) return;+ // The owner may remove their own object; the coin creator may remove any as+ // world moderation. No one else can.+ if (obj.ownerId !== this._ownerKey(client.sessionId) && !this._isCreator(client)) return;+ const wasPersistent = this._objectIsPersistent(obj);+ this.state.objects.delete(payload.id);+ // Persist the removal too, so a deleted prop doesn't resurrect on re-entry.+ if (wasPersistent) this._persistObjects();+ }++ // Per-client token bucket for obj:* ops, mirroring the edit limiter.+ _objOk(sessionId) {+ const now = Date.now();+ let bucket = this._objCounters.get(sessionId);+ if (!bucket || now - bucket.windowStart > 1000) {+ bucket = { windowStart: now, count: 0 };+ this._objCounters.set(sessionId, bucket);+ }+ bucket.count++;+ return bucket.count <= OBJ_OPS_PER_SEC_LIMIT;+ }++ _clampObjPos(obj, payload) {+ obj.x = objClamp(objNum(payload.x, obj.x), -WORLD_BOUND_M, WORLD_BOUND_M);+ obj.y = objClamp(objNum(payload.y, obj.y), OBJ_Y_MIN, OBJ_Y_MAX);+ obj.z = objClamp(objNum(payload.z, obj.z), -WORLD_BOUND_M, WORLD_BOUND_M);+ }++ // A durable build piece (worth persisting, R17) is any object that isn't a+ // server-owned entity and isn't a transient kind (ball, fx, projectile…).+ _objectIsPersistent(obj) {+ return obj.ownerId !== SERVER_OBJECT_OWNER && !TRANSIENT_OBJECT_KINDS.has(obj.kind);+ }++ // Delete a disconnecting owner's transient objects; their persistent build props+ // remain as part of the world (R17).+ _reapOwnerTransients(owner) {+ const doomed = [];+ for (const [id, o] of this.state.objects) {+ if (o.ownerId === owner && !this._objectIsPersistent(o)) doomed.push(id);+ }+ for (const id of doomed) this.state.objects.delete(id);+ }++ // Snapshot the durable build props for storage — transient and server-owned+ // objects are excluded. Coordinates are rounded to keep the doc compact.+ _snapshotObjects() {+ const out = [];+ for (const [id, o] of this.state.objects) {+ if (!this._objectIsPersistent(o)) continue;+ out.push({+ id,+ type: o.type,+ kind: o.kind,+ ownerId: o.ownerId,+ x: round3(o.x), y: round3(o.y), z: round3(o.z),+ yaw: round3(o.yaw),+ scale: round3(o.scale),+ });+ if (out.length >= MAX_WORLD_OBJECTS) break;+ }+ return out;+ }++ // Arm a debounced durable write of this world's build props (R17). The producer+ // runs at flush time so the latest state lands; worldPersistence coalesces a+ // burst of edits into one backend write.+ _persistObjects() {+ worldPersistence.save(this._objKey, () => ({ objects: this._snapshotObjects() }));+ }++ // Rebuild the `objects` map from a persisted doc on room create. Persisted+ // objects are at rest, so velocity restores to zero and ts is re-stamped.+ _restoreObjects(doc) {+ const list = Array.isArray(doc?.objects) ? doc.objects : null;+ if (!list || !list.length) return;+ let n = 0;+ for (const o of list) {+ if (n >= MAX_WORLD_OBJECTS) break;+ if (!o || typeof o.id !== 'string' || !o.id) continue;+ const obj = new WorldObject();+ obj.id = o.id.slice(0, OBJ_STR_MAX);+ obj.type = typeof o.type === 'string' ? o.type.slice(0, OBJ_STR_MAX) : '';+ obj.kind = typeof o.kind === 'string' ? o.kind.slice(0, OBJ_STR_MAX) : '';+ obj.ownerId = typeof o.ownerId === 'string' ? o.ownerId.slice(0, OBJ_STR_MAX) : '';+ obj.x = objNum(o.x, 0);+ obj.y = objClamp(objNum(o.y, 0), OBJ_Y_MIN, OBJ_Y_MAX);+ obj.z = objNum(o.z, 0);+ obj.yaw = objNum(o.yaw, 0);+ obj.scale = objClamp(objNum(o.scale, 1), OBJ_SCALE_MIN, OBJ_SCALE_MAX);+ obj.ts = Date.now();+ this.state.objects.set(obj.id, obj);+ n++;+ }+ if (n) console.log(`[walk_world ${this.roomId} coin=${this.state.coin || 'mainland'}] restored ${n} objects`);+ }+// Creator-only moderation: clear a disc of blocks around a grid point, or the// whole world. Validated server-side — the creator identity comes from the coin's// on-chain creator matching this client's verified wallet, never a client claim.diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.jsindex b3c6d1717..71e20eb8c 100644--- a/multiplayer/src/schemas.js+++ b/multiplayer/src/schemas.js@@ -40,6 +40,12 @@ export class Player extends Schema {// are tiny and authoritative — set only by the server's combat resolution.this.dead = false;this.heat = 0; // wanted/heat stars (0–5), derived from the private heat meter+ // Equipped cosmetic loadout (R03/R23) as the compact wire string peers render+ // — the worn ids in slot order, comma-joined, `none` defaults dropped (see+ // cosmetics-catalog.serializeLoadout). Set authoritatively from the owner's+ // persisted, ownership-validated loadout so a peer can trust the look and an+ // unowned cosmetic can never appear on anyone. Empty ⇒ the bare avatar.+ this.cosmetics = '';}}// IMPORTANT: append-only. Field indices are positional in @colyseus/schema's@@ -65,6 +71,8 @@ defineTypes(Player, {// Append-only (W07): downed state + wanted stars. See the constructor note.dead: 'boolean',heat: 'uint8',+ // Append-only (R23): equipped cosmetic loadout wire string. See the constructor.+ cosmetics: 'string',});// A single placed voxel in a coin's world. Keyed in the blocks MapSchema by its@@ -245,6 +253,9 @@ export class WalkState extends Schema {// two isolated rooms — General and Holders — kept apart by filterBy.this.tier = '';this.holderMinUsd = 0; // USD floor for the holder world (0 in General)+ // Creator-set token threshold for this coin's holder world (R24): hold ≥ this+ // many of `coin` to enter. 0 = no creator threshold, so holderMinUsd applies.+ this.holderMinTokens = 0;// Collaborative voxel builds for this coin's world. Keyed by packed grid// coordinate; the value carries only the block type. Persisted per coin so// a community's build survives the room emptying and the server restarting.@@ -291,4 +302,7 @@ defineTypes(WalkState, {mobs: { map: Mob },tombstones: { map: Tombstone },objects: { map: WorldObject },+ // Append-only (R24): a new scalar at the end so a still-running older client+ // isn't shifted off the wire format mid-deploy.+ holderMinTokens: 'float32',});diff --git a/pages/agent-economy.html b/pages/agent-economy.htmlindex a0d8f56d3..473ad3dbc 100644--- a/pages/agent-economy.html+++ b/pages/agent-economy.html@@ -517,7 +517,7 @@</div><div id="bottom-bar">- <a href="/ibm">IBM showcase</a>+ <a href="/ibm/galaxy">IBM showcase</a><span class="sep">·</span><a href="/x402">x402 Bazaar</a><span class="sep">·</span>diff --git a/pages/constellation.html b/pages/constellation.htmlindex 11a064206..4e62ca7e1 100644--- a/pages/constellation.html+++ b/pages/constellation.html@@ -103,7 +103,7 @@<canvas id="c-scene"></canvas><div class="c-hud">- <a class="c-badge" href="/ibm"><span class="dot"></span><strong>three.ws</strong> × IBM watsonx</a>+ <a class="c-badge" href="/ibm/galaxy"><span class="dot"></span><strong>three.ws</strong> × IBM watsonx</a><h1>watsonx <span class="g">Constellation</span></h1><p>Live Solana tokens, positioned in 3D by IBM Granite embeddings on watsonx.ai. Nearby stars are semantically alike.</p><div class="c-status" id="c-status"><span class="s-dot"></span><span id="c-status-text">Starting…</span></div>diff --git a/pages/features.html b/pages/features.htmlindex aa48269fd..5487f748d 100644--- a/pages/features.html+++ b/pages/features.html@@ -624,7 +624,7 @@<p class="feat-card-why"><strong>Why it's better:</strong> These are real Granite API calls — not mocked — with every decision anchored to a Solana transaction as an immutable record.</p>- <a href="/ibm" class="btn-primary feat-card-cta">+ <a href="/ibm/galaxy" class="btn-primary feat-card-cta">Explore the IBM suite <span class="btn-arrow">→</span></a></div>@@ -825,7 +825,7 @@<h4 class="h-footer-link-heading">Company</h4><a href="/blog">Blog</a><a href="/community">Community</a>- <a href="/ibm">IBM · watsonx.ai</a>+ <a href="/ibm/galaxy">IBM · watsonx.ai</a><a href="/dashboard">Dashboard</a></div><div class="h-footer-link-col">diff --git a/pages/galaxy.html b/pages/galaxy.htmlindex f1e3b6d7d..7055aa4f0 100644--- a/pages/galaxy.html+++ b/pages/galaxy.html@@ -137,7 +137,7 @@<!-- Footer attribution / controls hint --><div class="gx-footnote"><span class="gx-footnote-hint" id="gxHint">Drag to orbit · scroll to zoom · click a star</span>- <a class="gx-footnote-link" href="/ibm">three.ws × IBM watsonx →</a>+ <a class="gx-footnote-link" href="/ibm/galaxy">three.ws × IBM watsonx →</a></div></main>diff --git a/pages/home.html b/pages/home.htmlindex 4fbb52972..56b5e0e16 100644--- a/pages/home.html+++ b/pages/home.html@@ -2516,7 +2516,6 @@<button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Integrations<span class="nav-caret" aria-hidden="true">▾</span></button><div class="nav-pop wide" role="menu" aria-label="Integrations"><div class="nav-pop-note">Live partner showcases — built on real platforms, running end-to-end.</div>- <a class="nav-mi" href="/ibm" role="menuitem"><span class="nav-mi-t">IBM watsonx</span><span class="nav-mi-d">Granite-powered 3D agent demos — the hub</span></a><a class="nav-mi" href="/ibm/galaxy" role="menuitem"><span class="nav-mi-t">Agent Galaxy</span><span class="nav-mi-d">Granite embeddings → 3D semantic agent map</span></a><a class="nav-mi" href="/ibm/oracle" role="menuitem"><span class="nav-mi-t">Oracle</span><span class="nav-mi-d">Granite TimeSeries forecasting in 3D</span></a><a class="nav-mi" href="/ibm/twin" role="menuitem"><span class="nav-mi-t">Digital Twin</span><span class="nav-mi-d">Living market replica + projection</span></a>@@ -2601,7 +2600,6 @@<a href="/chat">Chat</a><a href="/pay">Pay</a><div class="dr-h">Integrations</div>- <a href="/ibm">IBM watsonx</a><a href="/ibm/galaxy">Agent Galaxy</a><a href="/ibm/oracle">Oracle</a><a href="/ibm/twin">Digital Twin</a>@@ -3969,7 +3967,6 @@</div><div class="foot-col"><div class="foot-col-h">Integrations</div>- <a href="/ibm">IBM watsonx</a><a href="/ibm/galaxy">Agent Galaxy</a><a href="/ibm/trust-layer">Trust Layer</a><a href="/aws">AWS Marketplace</a>diff --git a/public/features.json b/public/features.jsonindex 16516417d..f48688a77 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-05T09:53:55.956Z",+ "generated_at": "2026-06-05T10:56:09.314Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -106,8 +106,8 @@"showcase": false},{- "path": "/ibm",- "title": "three.ws on IBM watsonx",+ "path": "/ibm/galaxy",+ "title": "three.ws on IBM watsonx — Agent Galaxy","description": "three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.","added": "2026-06-03","auth": null,diff --git a/public/llms-full.txt b/public/llms-full.txtindex 0e6bb13b8..543d94eec 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -67,9 +67,9 @@ URL: https://three.ws/charactersDiscover AI characters on three.ws. Chat, trade, and create.-### three.ws on IBM watsonx+### three.ws on IBM watsonx — Agent Galaxy-URL: https://three.ws/ibm+URL: https://three.ws/ibm/galaxythree.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.diff --git a/public/llms.txt b/public/llms.txtindex 22ed767e1..cba83eb9c 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -20,7 +20,7 @@ Entry points into the product.- [Community](https://three.ws/community): Featured creators, builds, and conversations from the three.ws community.- [Sitemap](https://three.ws/sitemap): Human-readable index of every page on three.ws.- [Characters](https://three.ws/characters): Discover AI characters on three.ws. Chat, trade, and create.-- [three.ws on IBM watsonx](https://three.ws/ibm): three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.+- [three.ws on IBM watsonx — Agent Galaxy](https://three.ws/ibm/galaxy): three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.## Builddiff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 87f29e22c..7ce24605b 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -144,9 +144,9 @@</a></li><li>- <a href="/ibm">- <span class="sm-title">three.ws on IBM watsonx</span>- <span class="sm-path">/ibm</span>+ <a href="/ibm/galaxy">+ <span class="sm-title">three.ws on IBM watsonx — Agent Galaxy</span>+ <span class="sm-path">/ibm/galaxy</span><span class="sm-desc">three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity.</span></a></li>diff --git a/src/community/town-auth.js b/src/community/town-auth.jsindex 190b62b4c..943da6b8a 100644--- a/src/community/town-auth.js+++ b/src/community/town-auth.js@@ -160,6 +160,29 @@ export function requestHolderPass(mint) {return json(`/holder-pass?token=${encodeURIComponent(mint)}`, { method: 'POST' });}+/**+ * Read a coin's world gate (R24). Public: returns the token threshold to enter+ * the Holders world (0 = uses the platform USD floor) and whether the signed-in+ * user is the creator and may edit it.+ * @returns {Promise<{ mint: string, gated: boolean, minTokens: number, canEdit: boolean }>}+ */+export function getWorldGate(mint) {+ return json(`/world-gate?token=${encodeURIComponent(mint)}`);+}++/**+ * Set (or clear, with minTokens ≤ 0) a coin's holder-world token threshold.+ * Creator-only — the server re-verifies ownership against the linked wallet.+ * Rejects with err.code on `auth_required` / `wallet_required` / `not_creator`.+ */+export function setWorldGate(mint, minTokens) {+ return json(`/world-gate?token=${encodeURIComponent(mint)}`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ minTokens: Number(minTokens) || 0 }),+ });+}+/** Post content to a coin world as the signed-in user from their linked wallet. */export function postAsUser(token, content, walletAddress) {return json(`/messages?token=${encodeURIComponent(token)}`, {diff --git a/src/constellation/main.js b/src/constellation/main.jsindex f843c0ee6..79dc9e543 100644--- a/src/constellation/main.js+++ b/src/constellation/main.js@@ -390,7 +390,7 @@ async function runGraniteAnalysis(token, neighbors) {function graniteUnavailableNotice(code) {if (code === 'provider_not_configured') {- return '<div class="c-notice">IBM Granite isn\'t enabled on this deployment yet — set <code>WATSONX_API_KEY</code> to turn on live analysis. See the <a href="/ibm">IBM Granite demos</a>.</div>';+ return '<div class="c-notice">IBM Granite isn\'t enabled on this deployment yet — set <code>WATSONX_API_KEY</code> to turn on live analysis. See the <a href="/ibm/galaxy">IBM Granite demos</a>.</div>';}if (code === 'rate_limited') {return '<div class="c-notice">Rate limit reached — wait a moment and click again.</div>';@@ -489,7 +489,7 @@ async function init() {setStatus('live', `Embedded by IBM Granite · <code>${escapeHtml(model || EMBED_MODEL_HINT)}</code> · ${dimensions || dim}d`);} catch (e) {if (e.code === 'watsonx_unconfigured') {- setStatus('off', 'IBM watsonx not configured — showing tokens by trending rank. <a href="/ibm" style="color:var(--brand-blue-light)">Enable →</a>');+ setStatus('off', 'IBM watsonx not configured — showing tokens by trending rank. <a href="/ibm/galaxy" style="color:var(--brand-blue-light)">Enable →</a>');} else if (e.status === 404) {setStatus('off', 'Granite embeddings endpoint not deployed yet — showing tokens by trending rank.');} else {diff --git a/src/game/build-voxels.js b/src/game/build-voxels.jsindex 05d779748..1089b2d38 100644--- a/src/game/build-voxels.js+++ b/src/game/build-voxels.js@@ -453,7 +453,7 @@ export class VoxelWorld {// place/break mode toggle, and an enable toggle. Returned controller lets the// scene drive selection from keys and reflect connection state. Kept here so the// build feature owns its own chrome end-to-end.-export function createBuildHud({ onToggle, onPick, onModeChange }) {+export function createBuildHud({ onToggle, onPick, onModeChange, onClearArea }) {const el = (tag, props = {}, kids = []) => {const n = document.createElement(tag);for (const [k, v] of Object.entries(props)) {@@ -516,7 +516,35 @@ export function createBuildHud({ onToggle, onPick, onModeChange }) {// saved for keeps (Redis) or only for the life of the server process.const durBadge = el('div', { class: 'cc-build-durability', role: 'status', hidden: true });- const panel = el('div', { class: 'cc-build-panel', hidden: true }, [modeBtn, hotbar, budget, durBadge, hint]);+ // Per-player allowance (R19): how many blocks YOU own here vs your personal cap,+ // separate from the world budget above. Hidden until the server reports a cap, so+ // a solo (offline) build — which has no per-player limit — never shows it.+ const mineFill = el('span', { class: 'cc-build-mine-fill' });+ const mineText = el('span', { class: 'cc-build-mine-text', text: '' });+ const mine = el('div', {+ class: 'cc-build-mine', role: 'status', 'aria-label': 'Your blocks', hidden: true,+ title: 'Blocks you have placed in this world (your personal cap)',+ }, [el('span', { class: 'cc-build-mine-bar' }, [mineFill]), mineText]);++ // Creator moderation (R19): the coin's creator can wipe griefed builds. Hidden for+ // everyone else; the server is the real authority, so revealing it is purely a UI+ // affordance — a non-creator's request is refused server-side regardless.+ const clearAreaBtn = el('button', {+ class: 'cc-build-mod-btn', type: 'button',+ title: 'Clear the blocks around where you stand',+ onclick: () => onClearArea?.('area'),+ }, ['Clear nearby']);+ const clearAllBtn = el('button', {+ class: 'cc-build-mod-btn cc-danger', type: 'button',+ title: 'Clear every block in this world',+ onclick: () => onClearArea?.('all'),+ }, ['Clear all']);+ const modRow = el('div', { class: 'cc-build-mod', hidden: true }, [+ el('span', { class: 'cc-build-mod-tag', text: '★ Creator' }),+ clearAreaBtn, clearAllBtn,+ ]);++ const panel = el('div', { class: 'cc-build-panel', hidden: true }, [modeBtn, hotbar, budget, mine, durBadge, modRow, hint]);const root = el('div', { id: 'cc-build', class: 'cc-build' }, [toggleBtn, panel]);document.body.appendChild(root);@@ -576,6 +604,21 @@ export function createBuildHud({ onToggle, onPick, onModeChange }) {? 'This world is saved to durable storage — your build is here when you return.': 'Durable storage is unavailable — this build lives only until the server restarts.';},+ // Per-player allowance meter. used/cap come from the server's build-perms+ // snapshot; passing a falsy cap (solo build) hides the meter entirely.+ setUsage(used, cap) {+ if (!cap || cap <= 0) { mine.hidden = true; return; }+ const u = Math.max(0, Math.min(used | 0, cap));+ const pct = u / cap;+ mineFill.style.transform = `scaleX(${pct})`;+ mineText.textContent = `You: ${u.toLocaleString()} / ${cap.toLocaleString()}`;+ mine.hidden = false;+ mine.classList.toggle('cc-warn', pct >= 0.8 && u < cap);+ mine.classList.toggle('cc-full', u >= cap);+ },+ // Reveal the creator-only moderation controls. Server-enforced — this only+ // surfaces the affordance to the coin's creator.+ setCreator(isCreator) { modRow.hidden = !isCreator; },dispose() { root.remove(); },};}diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex 125e88b45..0238c4ac1 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -13,8 +13,12 @@ import { renderAvatarThumb } from './avatar-thumb.js';import { resolveAvatarUrl } from './avatar-rig.js';import { validateGlb, uploadGlb } from './avatar-upload.js';import { GUEST_SENTINEL, playAs } from './play-handoff.js';+import { COMPOSITE_PIECES } from './build-voxels.js';import { log } from '../shared/log.js';+// Degrees shown on the rotate button for each quarter-turn step (0–3).+const ROT_DEG = ['0°', '90°', '180°', '270°'];+function el(tag, props = {}, kids = []) {const n = document.createElement(tag);for (const [k, v] of Object.entries(props)) {@@ -36,6 +40,26 @@ const fmtMc = (n) => {return '$' + Math.round(n);};+// Compact token-amount label ("1.5M", "12.3K", "950") for gate requirements.+const fmtCompact = (n) => {+ const v = Number(n) || 0;+ if (v >= 1e9) return (v / 1e9).toFixed(v >= 1e10 ? 0 : 1).replace(/\.0$/, '') + 'B';+ if (v >= 1e6) return (v / 1e6).toFixed(v >= 1e7 ? 0 : 1).replace(/\.0$/, '') + 'M';+ if (v >= 1e3) return (v / 1e3).toFixed(v >= 1e4 ? 0 : 1).replace(/\.0$/, '') + 'K';+ return String(Math.round(v));+};++// Compact "3h ago" / "just now" relative time from an epoch-ms timestamp.+function timeAgo(ts) {+ const t = Number(ts);+ if (!t || !isFinite(t)) return '';+ const s = Math.max(0, (Date.now() - t) / 1000);+ if (s < 60) return 'just now';+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ return `${Math.floor(s / 86400)}d ago`;+}+const DEFAULT_AVATAR = '/avatars/default.glb';export class CommunityUI {@@ -53,6 +77,7 @@ export class CommunityUI {this.avatar = localStorage.getItem('cc-avatar') || DEFAULT_AVATAR;this._buildLobby();this._buildHud();+ this._buildStructures();}// ---------------------------------------------------------------- lobby@@ -852,8 +877,16 @@ export class CommunityUI {if (!body) return;const sym = data.symbol ? '$' + String(data.symbol).replace(/^\$/, '').toUpperCase() : 'this coin';const round2 = (n) => Math.round((Number(n) || 0) * 100) / 100;- const min = '$' + (data.minUsd ? round2(data.minUsd) : 8);const usd = '$' + round2(data.usd);+ // R24: a coin's creator can gate on a *token amount* instead of the USD floor.+ // When set, state the requirement and the player's holding in tokens of the+ // coin ("hold 1M $SYM"); otherwise fall back to the dollar floor.+ const tokenGated = Number(data.minTokens) > 0;+ const fmtAmt = (n) => fmtCompact(Number(n) || 0);+ const min = tokenGated+ ? `${fmtAmt(data.minTokens)} ${sym}`+ : '$' + (data.minUsd ? round2(data.minUsd) : 8);+ const held = tokenGated ? `${fmtAmt(data.amount)} ${sym}` : usd;const btn = (label, action, variant = '') => el('button', {type: 'button', class: 'cc-gate-btn' + (variant ? ' ' + variant : ''),onclick: () => this.h.onHolderAction?.(action),@@ -873,13 +906,13 @@ export class CommunityUI {nodes = [spin(), title('One moment'), msg(data.msg || 'Working…')];break;case 'granted':- nodes = [el('div', { class: 'cc-gate-check', text: '✓' }), title('You’re in'), msg(`Verified ${usd} of ${sym}. Welcome to the holders’ world.`)];+ nodes = [el('div', { class: 'cc-gate-check', text: '✓' }), title('You’re in'), msg(`Verified ${held} of ${sym}. Welcome to the holders’ world.`)];break;case 'short':nodes = [el('div', { class: 'cc-gate-lock', text: '🔒' }),title('Holders only'),- msg(`You hold ${usd} of ${sym}. This world is for holders of ${min} or more.`),+ msg(`You hold ${held} of ${sym}. This world is for holders of ${min} or more.`),actions(btn(`Buy ${sym}`, 'buy', 'cc-gate-primary'),btn('I bought — re-check', 'recheck'),@@ -939,6 +972,14 @@ export class CommunityUI {class: 'cc-buy-btn', type: 'button', title: 'Buy this coin',onclick: () => this.h.onBuy?.(),}, [el('span', { class: 'cc-buy-btn-ico', text: '⚡' }), this.buyBtnLabel]);+ // Creator-only (R24): set the token threshold to enter this coin's Holders+ // world. Hidden until the server confirms this player is the coin's creator+ // (build-perms snapshot); shown in both the General and Holders worlds.+ this.gateBtn = el('button', {+ class: 'cc-gate-cfg-btn', type: 'button', hidden: true,+ title: 'Set who can enter the Holders world', 'aria-label': 'Configure the holders gate',+ onclick: () => this.h.onConfigureGate?.(),+ }, [el('span', { class: 'cc-gate-cfg-ico', 'aria-hidden': 'true', text: '🔑' }), el('span', { class: 'cc-gate-cfg-text', text: 'Gate' })]);// Open the cosmetics shop — browse + try cosmetics on your avatar live.this.shopBtn = el('button', {class: 'cc-shop-btn', type: 'button', title: 'Cosmetics — try looks on your avatar',@@ -956,6 +997,7 @@ export class CommunityUI {]),]),this.shopBtn,+ this.gateBtn,this.buyBtn,]);@@ -1039,6 +1081,250 @@ export class CommunityUI {document.body.appendChild(this.hud);}+ // ---------------------------------------------------------------- build structures (R20)+ // The structures toolbar that rides above the block hotbar while build mode is+ // on: pick a composite piece (wall / floor / stairs / doorway) instead of a+ // single block, rotate it, screenshot-and-share the build, or open this coin's+ // featured builds. The block hotbar itself lives in build-voxels.js; this panel+ // is the "structures" layer on top of it.+ _buildStructures() {+ this._activePiece = null;++ // "Block" is the default single-cell tool; each composite piece follows.+ const tools = [{ id: null, name: 'Block', icon: '▪', key: 'B' }, ...COMPOSITE_PIECES];+ this._pieceBtns = new Map();+ const pieceRow = el('div', { class: 'cc-st-pieces', role: 'radiogroup', 'aria-label': 'Build tool' },+ tools.map((p) => {+ const btn = el('button', {+ class: 'cc-st-piece' + (p.id === null ? ' cc-on' : ''), type: 'button',+ role: 'radio', 'aria-checked': p.id === null ? 'true' : 'false',+ title: p.id === null ? 'Single block' : `${p.name} — one-click structure (R rotates)`,+ 'aria-label': p.name,+ onclick: () => this.h.onPickPiece?.(p.id),+ }, [+ el('span', { class: 'cc-st-piece-ico', 'aria-hidden': 'true', text: p.icon || '▦' }),+ el('span', { class: 'cc-st-piece-name', text: p.name }),+ ]);+ this._pieceBtns.set(p.id, btn);+ return btn;+ }));++ this.rotateBtn = el('button', {+ class: 'cc-st-rotate', type: 'button', disabled: true,+ title: 'Rotate the piece a quarter-turn (R)', 'aria-label': 'Rotate piece',+ onclick: () => this.h.onRotateBuild?.(),+ }, [+ el('span', { class: 'cc-st-rotate-ico', 'aria-hidden': 'true', text: '⟳' }),+ el('span', { class: 'cc-st-rotate-deg', text: ROT_DEG[0] }),+ ]);++ const shareBtn = el('button', {+ class: 'cc-st-action', type: 'button', title: 'Screenshot & share this build',+ onclick: () => this.h.onShareBuild?.(),+ }, [el('span', { 'aria-hidden': 'true', text: '📸' }), document.createTextNode('Share')]);++ const featuredBtn = el('button', {+ class: 'cc-st-action', type: 'button', title: 'Featured builds in this world',+ onclick: () => this.h.onOpenFeatured?.(),+ }, [el('span', { 'aria-hidden': 'true', text: '🏛' }), document.createTextNode('Builds')]);++ this.structures = el('div', { id: 'cc-structures', hidden: true, 'aria-label': 'Build structures' }, [+ pieceRow,+ el('div', { class: 'cc-st-tools' }, [this.rotateBtn, el('span', { class: 'cc-st-sep' }), shareBtn, featuredBtn]),+ ]);+ document.body.appendChild(this.structures);+ }++ /** Show/hide the structures toolbar with build mode. */+ setBuildToolsVisible(on) { if (this.structures) this.structures.hidden = !on; }++ /** Reflect the armed composite piece (null = single block); toggles rotate. */+ setBuildPiece(id) {+ this._activePiece = id ?? null;+ for (const [pid, btn] of this._pieceBtns) {+ const on = pid === this._activePiece;+ btn.classList.toggle('cc-on', on);+ btn.setAttribute('aria-checked', on ? 'true' : 'false');+ }+ this.rotateBtn.disabled = this._activePiece == null;+ }++ /** Reflect the current quarter-turn rotation on the rotate button. */+ setBuildRotation(rot) {+ this.rotateBtn.querySelector('.cc-st-rotate-deg').textContent = ROT_DEG[((rot % 4) + 4) % 4];+ }++ // ---------------------------------------------------------------- share sheet (R20)+ // A modal that shows the captured screenshot and offers three ways to share the+ // build: copy a deep link back into this world, download the image, or publish+ // it to the coin's featured builds. The scene captures the shot and owns the+ // publish call; this only renders and routes the user's choice.+ openShareSheet({ image, link, blocks, coinName, canPublish }) {+ this.closeShareSheet();+ const titleInput = el('input', {+ type: 'text', maxlength: '60', class: 'cc-share-title',+ placeholder: 'Name your build (optional)', 'aria-label': 'Build name',+ onkeydown: (e) => { e.stopPropagation(); if (e.key === 'Enter') publish(); },+ });+ const status = el('div', { class: 'cc-share-status', role: 'status', 'aria-live': 'polite', hidden: true });+ const setStatus = (msg, kind) => {+ status.hidden = !msg;+ status.textContent = msg || '';+ status.setAttribute('data-kind', kind || '');+ };++ const copyBtn = el('button', { class: 'cc-share-btn', type: 'button' },+ [el('span', { 'aria-hidden': 'true', text: '🔗' }), document.createTextNode('Copy link')]);+ copyBtn.addEventListener('click', async () => {+ try { await navigator.clipboard.writeText(link); setStatus('Link copied to clipboard.', 'ok'); }+ catch { setStatus('Couldn’t copy — select and copy the link manually.', 'warn'); }+ });++ const dlBtn = el('a', {+ class: 'cc-share-btn', href: image, download: `threews-build-${Date.now()}.jpg`,+ }, [el('span', { 'aria-hidden': 'true', text: '⬇' }), document.createTextNode('Download')]);++ const publishBtn = el('button', {+ class: 'cc-share-btn cc-primary', type: 'button', disabled: !canPublish,+ title: canPublish ? 'Publish to this world’s featured builds' : 'Build something first',+ }, [el('span', { 'aria-hidden': 'true', text: '🏛' }), document.createTextNode('Publish to featured')]);+ const publish = async () => {+ if (publishBtn.disabled) return;+ publishBtn.disabled = true;+ setStatus('Publishing…', '');+ const res = await this.h.onPublishBuild?.({ image, title: titleInput.value });+ if (res?.ok) {+ setStatus('Published! It’s now in this world’s featured builds.', 'ok');+ publishBtn.textContent = '✓ Published';+ } else {+ setStatus(res?.error || 'Couldn’t publish — try again.', 'warn');+ publishBtn.disabled = false;+ }+ };+ publishBtn.addEventListener('click', publish);++ const closeBtn = el('button', {+ class: 'cc-share-close', type: 'button', 'aria-label': 'Close', title: 'Close',+ onclick: () => this.closeShareSheet(),+ }, ['✕']);++ const card = el('div', {+ class: 'cc-share-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Share your build',+ onclick: (e) => e.stopPropagation(),+ }, [+ closeBtn,+ el('div', { class: 'cc-share-head' }, [+ el('h3', { class: 'cc-share-h', text: 'Share your build' }),+ el('p', { class: 'cc-share-sub', text: `${coinName} · ${blocks.toLocaleString()} block${blocks === 1 ? '' : 's'}` }),+ ]),+ el('div', { class: 'cc-share-shot' }, [el('img', { src: image, alt: 'Screenshot of your build' })]),+ titleInput,+ el('div', { class: 'cc-share-actions' }, [copyBtn, dlBtn, publishBtn]),+ status,+ ]);+ this.shareSheet = el('div', { id: 'cc-share', onclick: () => this.closeShareSheet() }, [card]);+ this._shareKeydown = (e) => { if (e.key === 'Escape') this.closeShareSheet(); };+ document.addEventListener('keydown', this._shareKeydown);+ document.body.appendChild(this.shareSheet);+ requestAnimationFrame(() => this.shareSheet?.classList.add('cc-on'));+ (canPublish ? titleInput : copyBtn).focus();+ }++ closeShareSheet() {+ if (this._shareKeydown) { document.removeEventListener('keydown', this._shareKeydown); this._shareKeydown = null; }+ if (this.shareSheet) { this.shareSheet.remove(); this.shareSheet = null; }+ }++ // ---------------------------------------------------------------- featured builds (R20)+ // A per-coin surface of shared builds. Designed for every state: loading+ // (skeletons), empty (a clear call to be the first), error (retry), and a+ // populated grid whose cards link back into the world.+ openFeatured(coinLabel) {+ if (this.featuredPanel) { this.featuredPanel.remove(); this.featuredPanel = null; }+ this._featuredBody = el('div', { class: 'cc-fb-body' });+ const closeBtn = el('button', {+ class: 'cc-fb-close', type: 'button', 'aria-label': 'Close', title: 'Close',+ onclick: () => this.closeFeatured(),+ }, ['✕']);+ const card = el('div', {+ class: 'cc-fb-card', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Featured builds',+ onclick: (e) => e.stopPropagation(),+ }, [+ closeBtn,+ el('div', { class: 'cc-fb-head' }, [+ el('h3', { class: 'cc-fb-h', html: '🏛 Featured builds' }),+ el('p', { class: 'cc-fb-sub', text: `Creations shared in ${coinLabel}` }),+ ]),+ this._featuredBody,+ ]);+ this.featuredPanel = el('div', { id: 'cc-featured', onclick: () => this.closeFeatured() }, [card]);+ this._featuredKeydown = (e) => { if (e.key === 'Escape') this.closeFeatured(); };+ document.addEventListener('keydown', this._featuredKeydown);+ document.body.appendChild(this.featuredPanel);+ requestAnimationFrame(() => this.featuredPanel?.classList.add('cc-on'));+ closeBtn.focus();+ }++ closeFeatured() {+ this._featuredOpen = false;+ if (this._featuredKeydown) { document.removeEventListener('keydown', this._featuredKeydown); this._featuredKeydown = null; }+ if (this.featuredPanel) { this.featuredPanel.remove(); this.featuredPanel = null; }+ this.h.onFeaturedClosed?.();+ }++ setFeaturedLoading() {+ if (!this._featuredBody) return;+ this._featuredBody.textContent = '';+ const grid = el('div', { class: 'cc-fb-grid', 'aria-busy': 'true' },+ Array.from({ length: 4 }, () => el('div', { class: 'cc-fb-skel' })));+ this._featuredBody.appendChild(grid);+ }++ setFeaturedError(retry) {+ if (!this._featuredBody) return;+ this._featuredBody.textContent = '';+ this._featuredBody.appendChild(el('div', { class: 'cc-fb-state' }, [+ el('span', { class: 'cc-fb-state-ico', 'aria-hidden': 'true', text: '⚠️' }),+ el('p', { class: 'cc-fb-state-msg', text: 'Couldn’t load featured builds.' }),+ el('button', { class: 'cc-fb-retry', type: 'button', text: 'Try again', onclick: () => retry?.() }),+ ]));+ }++ setFeaturedBuilds(list) {+ if (!this._featuredBody) return;+ this._featuredBody.textContent = '';+ if (!list || list.length === 0) {+ this._featuredBody.appendChild(el('div', { class: 'cc-fb-state' }, [+ el('span', { class: 'cc-fb-state-ico', 'aria-hidden': 'true', text: '🏗️' }),+ el('p', { class: 'cc-fb-state-msg', text: 'No featured builds yet.' }),+ el('p', { class: 'cc-fb-state-hint', text: 'Build something, hit Share, and publish it to be the first.' }),+ ]));+ return;+ }+ const grid = el('div', { class: 'cc-fb-grid' }, list.map((b) => this._featuredCard(b)));+ this._featuredBody.appendChild(grid);+ }++ _featuredCard(b) {+ const q = new URLSearchParams({ coin: b.mint || '' });+ if (b.coinName) q.set('name', b.coinName);+ if (b.coinSymbol) q.set('symbol', b.coinSymbol);+ const href = `/play?${q.toString()}`;+ const meta = [b.author ? `by ${b.author}` : null, b.blocks ? `${Number(b.blocks).toLocaleString()} blocks` : null, timeAgo(b.createdAt)]+ .filter(Boolean).join(' · ');+ return el('a', { class: 'cc-fb-item', href, title: 'Enter this world' }, [+ el('div', { class: 'cc-fb-thumb' }, [+ b.thumb ? el('img', { src: b.thumb, alt: b.title || 'Featured build', loading: 'lazy' })+ : el('div', { class: 'cc-fb-thumb-empty', 'aria-hidden': 'true', text: '🧱' }),+ ]),+ el('div', { class: 'cc-fb-meta' }, [+ el('div', { class: 'cc-fb-title', text: b.title || 'Untitled build' }),+ el('div', { class: 'cc-fb-byline', text: meta }),+ ]),+ el('span', { class: 'cc-fb-enter', 'aria-hidden': 'true', text: 'Enter →' }),+ ]);+ }+// Reflect the voice engine's state on the mic button: label, tooltip, and the// data-state hook the CSS uses to colour the icon / show the mute slash.setVoiceState(state) {@@ -1093,7 +1379,13 @@ export class CommunityUI {else this.coinImg.style.display = 'none';const holders = coin.tier === 'holders';this.tierBadge.hidden = !holders;- this.tierBadge.textContent = holders ? `🔒 Holders · $${coin.holderMinUsd ? Math.round(coin.holderMinUsd * 100) / 100 : 8}+` : '';+ // State the real bar: a creator-set token threshold (R24) reads "1M $SYM+",+ // otherwise the USD floor reads "$8+".+ const sym = coin.symbol ? '$' + String(coin.symbol).replace(/^\$/, '').toUpperCase() : '';+ const req = coin.holderMinTokens > 0+ ? `${fmtCompact(coin.holderMinTokens)} ${sym}+`+ : `$${coin.holderMinUsd ? Math.round(coin.holderMinUsd * 100) / 100 : 8}+`;+ this.tierBadge.textContent = holders ? `🔒 Holders · ${req}` : '';this.chatLog.textContent = '';this._unread = 0;this.chatUnread.hidden = true;diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex cf54faa1f..735849871 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -1384,6 +1384,97 @@ html, body {color: #8fe9a8;}+/* Per-player allowance meter (R19) — "You: N / cap", mirrors the world budget+ bar but tracks only this player's own blocks against their personal cap. */+.cc-build-mine {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 11px;+ color: rgba(255, 255, 255, 0.55);+ font-variant-numeric: tabular-nums;+}+.cc-build-mine[hidden] {+ display: none;+}+.cc-build-mine-bar {+ position: relative;+ flex: 1;+ height: 3px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.1);+ overflow: hidden;+}+.cc-build-mine-fill {+ position: absolute;+ inset: 0;+ transform-origin: left center;+ transform: scaleX(0);+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.45);+ transition: transform 0.2s ease, background 0.2s ease;+}+.cc-build-mine-text {+ white-space: nowrap;+}+.cc-build-mine.cc-warn .cc-build-mine-fill {+ background: #ffb648;+}+.cc-build-mine.cc-full .cc-build-mine-fill {+ background: #ff5a5a;+}+.cc-build-mine.cc-full .cc-build-mine-text {+ color: #ffb3b3;+}++/* Creator moderation row (R19) — only revealed to the coin creator. */+.cc-build-mod {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+ padding-top: 6px;+ border-top: 1px solid rgba(255, 255, 255, 0.1);+}+.cc-build-mod[hidden] {+ display: none;+}+.cc-build-mod-tag {+ font-size: 10.5px;+ font-weight: 700;+ letter-spacing: 0.04em;+ color: #ffce5c;+ text-transform: uppercase;+}+.cc-build-mod-btn {+ padding: 4px 10px;+ border-radius: 999px;+ border: 1px solid rgba(255, 255, 255, 0.18);+ background: rgba(255, 255, 255, 0.06);+ color: #e8e8ea;+ font-size: 11px;+ font-weight: 600;+ cursor: pointer;+ transition: background 0.14s, border-color 0.14s, color 0.14s;+}+.cc-build-mod-btn:hover {+ background: rgba(255, 255, 255, 0.12);+ border-color: rgba(255, 255, 255, 0.34);+}+.cc-build-mod-btn:focus-visible {+ outline: 2px solid #66ff8c;+ outline-offset: 2px;+}+.cc-build-mod-btn.cc-danger {+ color: #ffd2d2;+ border-color: rgba(255, 90, 90, 0.4);+ background: rgba(255, 90, 90, 0.12);+}+.cc-build-mod-btn.cc-danger:hover {+ background: rgba(255, 90, 90, 0.22);+ border-color: rgba(255, 90, 90, 0.6);+}+@media (pointer: coarse) {.cc-build-hint {display: none;@@ -1404,6 +1495,163 @@ html, body {}}+/* ---------------- build structures toolbar (R20) ----------------+ Composite-piece palette + rotate + share + featured. Docks bottom-centre+ above the emote tray; shows only while build mode is on. Monochrome, same+ glass + light-accent language as the build HUD. */+#cc-structures {+ position: fixed; left: 50%; bottom: 84px; transform: translateX(-50%);+ z-index: 22; display: flex; flex-direction: column; align-items: center; gap: 8px;+ pointer-events: none;+ font: 13px/1.3 system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ animation: cc-build-in 0.16s ease;+}+#cc-structures[hidden] { display: none; }+#cc-structures button, #cc-structures a { pointer-events: auto; }+.cc-st-pieces, .cc-st-tools {+ display: flex; align-items: center; gap: 6px; padding: 7px;+ background: var(--cc-panel); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);+ -webkit-backdrop-filter: blur(10px); backdrop-filter: blur(10px);+}+.cc-st-piece {+ display: inline-flex; flex-direction: column; align-items: center; gap: 3px;+ min-width: 52px; padding: 6px 8px; border-radius: var(--cc-radius-sm);+ border: 1px solid transparent; background: rgba(255, 255, 255, 0.04);+ color: var(--cc-dim); cursor: pointer; font-weight: 600;+ transition: background 0.12s, border-color 0.12s, color 0.12s, transform 0.08s;+}+.cc-st-piece:hover { background: rgba(255, 255, 255, 0.1); color: var(--cc-text); transform: translateY(-2px); }+.cc-st-piece:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }+.cc-st-piece.cc-on { background: #f4f5f7; color: var(--cc-ink); border-color: #f4f5f7; }+.cc-st-piece-ico { font-size: 18px; line-height: 1; }+.cc-st-piece-name { font-size: 10.5px; letter-spacing: 0.02em; }+.cc-st-rotate, .cc-st-action {+ display: inline-flex; align-items: center; gap: 6px; padding: 8px 12px;+ border-radius: var(--cc-radius-sm); border: 1px solid var(--cc-edge);+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text);+ font-weight: 600; cursor: pointer;+ transition: background 0.12s, border-color 0.12s, color 0.12s, opacity 0.12s, transform 0.08s;+}+.cc-st-rotate:hover, .cc-st-action:hover { background: rgba(255, 255, 255, 0.12); border-color: var(--cc-edge-hi); }+.cc-st-rotate:active, .cc-st-action:active { transform: translateY(1px); }+.cc-st-rotate:focus-visible, .cc-st-action:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }+.cc-st-rotate:disabled { opacity: 0.4; cursor: not-allowed; }+.cc-st-rotate-ico { font-size: 15px; line-height: 1; }+.cc-st-rotate-deg { font-variant-numeric: tabular-nums; min-width: 34px; text-align: left; }+.cc-st-sep { width: 1px; align-self: stretch; background: var(--cc-edge-soft); margin: 0 2px; }++@media (pointer: coarse) { #cc-structures { bottom: 78px; } }+@media (max-width: 560px) {+ #cc-structures { bottom: 84px; width: 100%; padding: 0 8px; }+ .cc-st-pieces { flex-wrap: wrap; justify-content: center; max-width: 96vw; }+ .cc-st-piece { min-width: 46px; }+}++/* ---------------- share-a-build sheet (R20) ---------------- */+#cc-share, #cc-featured {+ position: fixed; inset: 0; z-index: 120; display: grid; place-items: center;+ padding: 20px; background: rgba(4, 4, 5, 0.62);+ -webkit-backdrop-filter: blur(4px); backdrop-filter: blur(4px);+ opacity: 0; transition: opacity 0.2s ease;+}+#cc-share.cc-on, #cc-featured.cc-on { opacity: 1; }+.cc-share-card, .cc-fb-card {+ position: relative; width: min(440px, 94vw); max-height: 88vh; overflow: auto;+ background: var(--cc-panel-solid); border: 1px solid var(--cc-edge);+ border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);+ padding: 20px; color: var(--cc-text);+ transform: translateY(8px) scale(0.99); transition: transform 0.2s ease;+}+#cc-share.cc-on .cc-share-card, #cc-featured.cc-on .cc-fb-card { transform: none; }+.cc-fb-card { width: min(720px, 94vw); }+.cc-share-close, .cc-fb-close {+ position: absolute; top: 12px; right: 12px; width: 30px; height: 30px;+ display: grid; place-items: center; border-radius: var(--cc-radius-sm);+ border: 1px solid var(--cc-edge); background: rgba(255, 255, 255, 0.04);+ color: var(--cc-dim); cursor: pointer; font-size: 14px; line-height: 1;+ transition: color 0.12s, background 0.12s, border-color 0.12s;+}+.cc-share-close:hover, .cc-fb-close:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.1); }+.cc-share-close:focus-visible, .cc-fb-close:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }+.cc-share-h, .cc-fb-h { margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.01em; }+.cc-share-sub, .cc-fb-sub { margin: 3px 0 0; font-size: 12.5px; color: var(--cc-dim); }+.cc-share-shot {+ margin: 14px 0; border-radius: var(--cc-radius-sm); overflow: hidden;+ border: 1px solid var(--cc-edge-soft); background: var(--cc-bg2); aspect-ratio: 16 / 9;+}+.cc-share-shot img { width: 100%; height: 100%; object-fit: cover; display: block; }+.cc-share-title {+ width: 100%; box-sizing: border-box; padding: 9px 11px; margin-bottom: 12px;+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);+ color: var(--cc-text); font-size: 13.5px;+}+.cc-share-title:focus { outline: none; border-color: var(--cc-edge-hi); }+.cc-share-actions { display: flex; flex-wrap: wrap; gap: 8px; }+.cc-share-btn {+ display: inline-flex; align-items: center; gap: 6px; padding: 9px 13px;+ border-radius: var(--cc-radius-sm); border: 1px solid var(--cc-edge);+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text); cursor: pointer;+ font-weight: 600; font-size: 13px; text-decoration: none;+ transition: background 0.12s, border-color 0.12s, opacity 0.12s, transform 0.08s;+}+.cc-share-btn:hover { background: rgba(255, 255, 255, 0.12); border-color: var(--cc-edge-hi); }+.cc-share-btn:active { transform: translateY(1px); }+.cc-share-btn:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }+.cc-share-btn.cc-primary { background: #f4f5f7; color: var(--cc-ink); border-color: #f4f5f7; margin-left: auto; }+.cc-share-btn.cc-primary:hover { background: #fff; }+.cc-share-btn:disabled { opacity: 0.45; cursor: not-allowed; transform: none; }+.cc-share-status { margin-top: 12px; font-size: 12.5px; color: var(--cc-dim); }+.cc-share-status[data-kind="ok"] { color: #cfe9d4; }+.cc-share-status[data-kind="warn"] { color: #e7cccc; }++/* ---------------- featured builds surface (R20) ---------------- */+.cc-fb-body { margin-top: 16px; }+.cc-fb-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }+.cc-fb-item {+ display: flex; flex-direction: column; text-decoration: none; color: var(--cc-text);+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius); overflow: hidden;+ background: var(--cc-bg2); transition: border-color 0.14s, transform 0.1s, box-shadow 0.14s;+}+.cc-fb-item:hover { border-color: var(--cc-edge-hi); transform: translateY(-3px); box-shadow: var(--cc-shadow); }+.cc-fb-item:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }+.cc-fb-thumb { aspect-ratio: 16 / 9; background: var(--cc-bg3); overflow: hidden; }+.cc-fb-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }+.cc-fb-thumb-empty { width: 100%; height: 100%; display: grid; place-items: center; font-size: 28px; opacity: 0.4; }+.cc-fb-meta { padding: 10px 12px; }+.cc-fb-title { font-size: 13.5px; font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+.cc-fb-byline { margin-top: 3px; font-size: 11.5px; color: var(--cc-dim); }+.cc-fb-enter {+ padding: 0 12px 11px; font-size: 12px; font-weight: 600; color: var(--cc-dim);+ transition: color 0.14s;+}+.cc-fb-item:hover .cc-fb-enter { color: var(--cc-text); }+.cc-fb-skel {+ aspect-ratio: 4 / 3; border-radius: var(--cc-radius); background: var(--cc-bg2);+ border: 1px solid var(--cc-edge-soft); position: relative; overflow: hidden;+}+.cc-fb-skel::after {+ content: ''; position: absolute; inset: 0;+ background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.06), transparent);+ transform: translateX(-100%); animation: cc-fb-shimmer 1.2s infinite;+}+@keyframes cc-fb-shimmer { to { transform: translateX(100%); } }+.cc-fb-state { padding: 40px 16px; text-align: center; color: var(--cc-dim); }+.cc-fb-state-ico { font-size: 30px; }+.cc-fb-state-msg { margin: 12px 0 4px; font-size: 14px; font-weight: 600; color: var(--cc-text); }+.cc-fb-state-hint { margin: 0; font-size: 12.5px; }+.cc-fb-retry {+ margin-top: 14px; padding: 8px 16px; border-radius: var(--cc-radius-sm);+ border: 1px solid var(--cc-edge); background: rgba(255, 255, 255, 0.04);+ color: var(--cc-text); cursor: pointer; font-weight: 600;+ transition: background 0.12s, border-color 0.12s;+}+.cc-fb-retry:hover { background: rgba(255, 255, 255, 0.12); border-color: var(--cc-edge-hi); }+.cc-fb-retry:focus-visible { outline: 2px solid #66ff8c; outline-offset: 2px; }+@media (prefers-reduced-motion: reduce) {+ #cc-structures, #cc-share, #cc-featured, .cc-share-card, .cc-fb-card, .cc-fb-skel::after { animation: none; transition: none; }+}+/* ---------------- 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@@ -1605,26 +1853,41 @@ html, body {padding: 12px 2px 8px; font-size: 11.5px; color: var(--cc-faint);letter-spacing: 0.12em; text-transform: uppercase;}+/* Purchase feedback (R22) — overrides the neutral count line while a buy resolves. */+.cc-shop-status[data-kind="pending"] { color: var(--cc-text); }+.cc-shop-status[data-kind="ok"] { color: #cfe9d4; }+.cc-shop-status[data-kind="error"] { color: #e7b3b3; }.cc-shop-grid {display: grid; gap: 12px; padding-top: 6px;grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));}.cc-shop-grid.cc-shop-empty-grid { display: block; }-/* A card is a click-to-toggle preview button. */+/* A card stacks a click-to-toggle preview button (the thumb) over its meta ++ buy action. The card itself is a container; the thumb and Buy are the two+ independent interactive controls. */.cc-shop-card {display: flex; flex-direction: column; text-align: left;padding: 0; background: var(--cc-bg2);border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius);- color: var(--cc-text); cursor: pointer; overflow: hidden;+ color: var(--cc-text); overflow: hidden;transition: transform 0.12s ease, border-color 0.12s ease, box-shadow 0.12s ease;}.cc-shop-card:hover { transform: translateY(-2px); border-color: var(--cc-edge-hi); }-.cc-shop-card:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }.cc-shop-card.cc-active {border-color: var(--cc-accent); box-shadow: var(--cc-glow);}+/* The thumb is a real button (preview toggle) — reset the UA chrome so it reads+ as the image tile it replaces. */+.cc-shop-thumb-btn {+ appearance: none; -webkit-appearance: none;+ border: 0; border-bottom: 1px solid var(--cc-edge-soft);+ margin: 0; font: inherit; color: inherit; cursor: pointer;+ width: 100%; display: block;+}+.cc-shop-thumb-btn:focus-visible { outline: 2px solid #fff; outline-offset: -2px; }+.cc-shop-thumb {position: relative; aspect-ratio: 1 / 1; width: 100%;display: grid; place-items: center; overflow: hidden;@@ -1659,6 +1922,24 @@ html, body {.cc-shop-meta { display: flex; flex-direction: column; gap: 6px; padding: 10px 11px 11px; }.cc-shop-name { font-size: 13px; font-weight: 700; letter-spacing: 0.01em; }+/* The item's value, quoted in $THREE — the only coin. */+.cc-shop-value { font-size: 11px; font-weight: 700; color: var(--cc-dim); letter-spacing: 0.02em; }++/* Buy / Owned action (R22). The action is its own focusable control, distinct+ from the preview toggle on the thumb. */+.cc-shop-action { margin-top: 2px; align-self: stretch; }+.cc-shop-buy {+ appearance: none; -webkit-appearance: none;+ width: 100%; padding: 8px 10px; border-radius: var(--cc-radius);+ border: 1px solid var(--cc-edge-hi); background: rgba(255, 255, 255, 0.92);+ color: var(--cc-ink); font-size: 12px; font-weight: 800; letter-spacing: 0.02em;+ cursor: pointer; transition: transform 0.12s ease, background 0.12s ease, opacity 0.12s ease;+}+.cc-shop-buy:hover { transform: translateY(-1px); background: #fff; }+.cc-shop-buy:active { transform: translateY(1px); }+.cc-shop-buy:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+.cc-shop-buy:disabled { opacity: 0.55; cursor: progress; transform: none; }+span.cc-shop-action.cc-owned { align-self: flex-start; }.cc-shop-badge {display: inline-flex; align-items: center; gap: 5px; align-self: flex-start;font-size: 11px; font-weight: 700; letter-spacing: 0.02em;diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 0bcc56a72..d1c23fffe 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -27,7 +27,7 @@ import { createChartScreen } from './chart-screen.js';import { mountOracleRibbon } from './oracle-ribbon.js';import { MarketReactor } from './market-reactor.js';import {- VoxelWorld, createBuildHud, parseKey, keyOf, MAX_BLOCKS,+ VoxelWorld, createBuildHud, parseKey, keyOf, MAX_BLOCKS, BLOCK,COMPOSITE_PIECES, compositeCells, MAX_COMPOSITE_CELLS,} from './build-voxels.js';import { normalizeGatewayURL } from '../ipfs.js';@@ -35,7 +35,9 @@ import {loadManifest, getEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,CLIP_IDLE, CLIP_WALK,} from './avatar-rig.js';-import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';+import { GUEST_SENTINEL, uploadPendingGuestAvatar, getPlayCosmetics, setPlayCosmetics } from './play-handoff.js';+import { applyLoadout } from './cosmetics-loadout.js';+import { serializeLoadout } from '../../multiplayer/src/cosmetics-catalog.js';import { AccessoryManager } from '../agent-accessories.js';import { CosmeticsShop } from './cosmetics-shop.js';import { HOME_TOWN, isHomeTown } from './home-town.js';@@ -109,12 +111,20 @@ class RemotePlayer {this.voice = !!player.voice;this.label.classList.toggle('cc-invoice', this.voice);+ // This peer's equipped cosmetic loadout (R23), as the wire string the server+ // publishes on the schema. Applied once the GLB measures (setAvatar), and+ // re-applied whenever they change their fit (apply()).+ this._cosWire = player.cosmetics || '';this.setAvatar(player.avatar);}setAvatar(url) {if (url === this._avatarUrl) return;this._avatarUrl = url;- // rebuild model+ // rebuild model — clearing the rig takes any worn cosmetics with it, so drop+ // the old handle and re-apply once the new GLB has measured.+ try { this.cosmetics?.dispose(); } catch {}+ this.cosmetics = null;+ this._cosApplied = null;this.rig.clear();this.anim = new AnimationManager();// Tag this load so a slower in-flight GLB can't attach to the rig after the@@ -126,8 +136,22 @@ class RemotePlayer {if (this._disposed || token !== this._avatarToken) return;this.height = height;anim.crossfadeTo(this.motion === 'walk' || this.motion === 'run' ? CLIP_WALK : CLIP_IDLE, 0);+ this.applyCosmetics();})).catch(() => {});}+ // Dress this peer in their equipped loadout. Idempotent — re-applies only when+ // the wire actually changed, and waits for the avatar to measure (setAvatar+ // calls it post-load). Reuses the same applyLoadout the local player and the+ // creator use, so one wardrobe renders identically everywhere.+ applyCosmetics(wire) {+ const next = typeof wire === 'string' ? wire : (this._cosWire || '');+ this._cosWire = next;+ if (this._disposed || !this.height) return;+ if (this.cosmetics && this._cosApplied === next) return;+ this._cosApplied = next;+ try { this.cosmetics?.dispose(); } catch {}+ this.cosmetics = applyLoadout(this.rig, this.height, next);+ }apply(player) {this.targetX = player.x; this.targetY = player.y; this.targetZ = player.z; this.targetYaw = player.yaw;if (player.name) this.label.textContent = player.name;@@ -137,6 +161,7 @@ class RemotePlayer {if (!this.voice) this.setSpeaking(false);}if (player.avatar !== this._avatarUrl) this.setAvatar(player.avatar);+ if (player.cosmetics !== undefined && player.cosmetics !== this._cosWire) this.applyCosmetics(player.cosmetics);if (player.motion !== this.motion) {this.motion = player.motion;this.anim.crossfadeTo(this.motion === 'walk' || this.motion === 'run' ? CLIP_WALK : CLIP_IDLE, 0.18);@@ -173,9 +198,11 @@ class RemotePlayer {this.rig.rotation.y = this.curYaw;if (this.anim.currentName === CLIP_WALK) this.anim.setSpeed(this.motion === 'run' ? RUN_TIMESCALE : 1);this.anim.update(dt);+ this.cosmetics?.tick(dt);}dispose() {this._disposed = true;+ try { this.cosmetics?.dispose(); } catch {}this.scene.remove(this.rig);this.label.remove();this.bubble?.remove();@@ -234,6 +261,7 @@ export class CoinCommunities {onShareBuild: () => this._shareBuild(),onOpenFeatured: () => this._openFeatured(),onPublishBuild: (meta) => this._publishBuild(meta),+ onFeaturedClosed: () => { this._featuredOpen = false; },});// Collaborative building HUD (hotbar + place/break toggle). Hidden until the@@ -247,7 +275,12 @@ export class CoinCommunities {onToggle: (on) => this._onBuildToggle(on),onPick: (i) => { this.buildType = i; this._refreshGhost(); },onModeChange: () => this._refreshGhost(),+ onClearArea: (scope) => this._onClearArea(scope),});+ // Build permissions (R19) — refreshed from the server's build-perms snapshot:+ // the player's per-world block cap + usage, and whether they're the coin creator+ // (which unlocks the clear-area moderation tool). Solo builds carry no cap.+ this._buildPerms = { creator: false, cap: 0, used: 0, clearMaxRadius: 12 };this.buildHud.root.hidden = true;this.buildHud.setEnabled(false);@@ -587,11 +620,13 @@ export class CoinCommunities {// instead. A null result means they cancelled — stay put.let holderPass = '';let holderMinUsd = 0;+ let holderMinTokens = 0;if (tier === 'holders') {const pass = await this._passHolderGate(coin);if (!pass) return;holderPass = pass.holderPass;holderMinUsd = pass.minUsd;+ holderMinTokens = pass.minTokens || 0;}this.phase = 'loading';@@ -607,7 +642,7 @@ export class CoinCommunities {official: true,};}- coin = { ...coin, tier, holderMinUsd };+ coin = { ...coin, tier, holderMinUsd, holderMinTokens };this.coin = coin;this.ui.enterWorld(coin);document.body.classList.toggle('cc-holders', tier === 'holders');@@ -679,6 +714,13 @@ export class CoinCommunities {// Backed out while the avatar GLB was loading — stop before we open a room.if (epoch !== this._enterEpoch) return;this.localHeight = localHeight;+ // Dress the local avatar in the loadout the player last equipped (carried+ // across sessions and worlds via the cc-cosmetics mirror). The server echoes+ // the authoritative, ownership-validated loadout right after join — which+ // re-applies here through _onCosmeticsProfile — but applying the cached wire+ // now means the player sees their fit immediately, not a flash of bare avatar.+ this._localCosWire = null;+ this._applyLocalCosmetics(getPlayCosmetics());// Don't silently swap a broken model for the stand-in — tell the player so// they know to pick another avatar.if (avatarFallback && avatarInput !== GUEST_SENTINEL) {@@ -715,6 +757,11 @@ export class CoinCommunities {// server binds the wallet (inside the pass) as the account id; harmless// when the server isn't gated.playPass: this.playPass, account: this.account,+ // Pre-join cosmetic loadout (R23): the fit the player last equipped, so+ // peers see it the instant we appear. The server validates each id against+ // what the account owns before publishing it, so it can't dress us in+ // anything unowned.+ cosmetics: getPlayCosmetics(),});if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));this.net.on('status', ({ status }) => {@@ -731,7 +778,7 @@ export class CoinCommunities {// Every (re)connect re-streams the server's authoritative build, so wipe// the local layer first. On a manual retry out of single-player this also// hands authority back: the solo build gives way to the shared world's.- if (status === 'connecting') { this.voxels?.clear(); this._undoStack = []; this._syncBudget(); }+ if (status === 'connecting') { this.voxels?.clear(); this._undoStack = []; this._syncBudget(); this._resetBuildPerms(); }// Building is available with a live server (synced + persisted for// everyone) and in solo single-player mode (local-only) once multiplayer// has been given up. The connecting window is the only time it's off, so@@ -778,6 +825,13 @@ export class CoinCommunities {this.net.on('blockChange', (key, t) => { const [x, y, z] = parseKey(key); this.voxels?.setBlock(x, y, z, t); });this.net.on('blockRemove', (key) => { const [x, y, z] = parseKey(key); this.voxels?.removeBlock(x, y, z); this._syncBudget(); });this.net.on('editReject', ({ reason }) => this._onEditReject(reason));+ // Build permissions: the per-player cap/usage + creator flag drive the HUD's+ // allowance meter and reveal the creator-only clear-area control. build-cleared+ // confirms a creator sweep landed.+ this.net.on('buildPerms', (p) => this._onBuildPerms(p));+ this.net.on('buildCleared', ({ count, all }) => {+ this.ui.toast(all ? `Cleared the whole world (${count|0} blocks).` : `Cleared ${count|0} block${(count|0) === 1 ? '' : 's'} nearby.`, 'info');+ });// Durability flag for this world's build — drives the HUD "Saved" badge.this.net.on('persistent', (durable) => { if (this.net?.status === 'online') this.buildHud.setPersistent(durable); });@@ -791,7 +845,7 @@ export class CoinCommunities {net: this.net,ui: this.ui,});- this.net.on('profile', (snap) => this.playSystems?.setProfile(snap));+ this.net.on('profile', (snap) => { this.playSystems?.setProfile(snap); this._onCosmeticsProfile(snap); });this.net.on('inv', (delta) => this.playSystems?.applyInv(delta));this.net.on('xpgain', (g) => this.playSystems?.onXpGain(g));this.net.on('levelup', (l) => this.playSystems?.onLevelup(l));@@ -940,14 +994,14 @@ export class CoinCommunities {try {const res = await requestHolderPass(coin.mint);if (res?.eligible && res.holderPass) {- this.ui.setHolderGate('granted', { symbol, usd: res.usd, minUsd: res.minUsd });+ this.ui.setHolderGate('granted', { symbol, usd: res.usd, amount: res.amount, minUsd: res.minUsd, minTokens: res.minTokens });// Let the "verified" state land for a beat before the world builds.await new Promise((r) => setTimeout(r, 650));this.ui.closeHolderGate();return res;}state = 'short';- data = { symbol, usd: res?.usd ?? 0, amount: res?.amount ?? 0, minUsd: res?.minUsd ?? 8 };+ data = { symbol, usd: res?.usd ?? 0, amount: res?.amount ?? 0, minUsd: res?.minUsd ?? 8, minTokens: res?.minTokens ?? 0 };} catch (err) {if (err?.code === 'auth_required') { state = 'auth'; data = { symbol, error: carryError }; }else if (err?.code === 'wallet_required') { state = 'wallet'; data = { symbol, error: carryError }; }@@ -1076,7 +1130,17 @@ export class CoinCommunities {this.buildHud.setActive(false);this.buildHud.setEnabled(false);this.buildHud.setPersistent(null);+ this._resetBuildPerms();this.buildHud.root.hidden = true;+ // Reset the structures toolbar back to single-block and close any open+ // share / featured surfaces — they're scoped to the world we're leaving.+ this.buildPiece = null; this.buildRot = 0;+ this.ui.setBuildPiece(null);+ this.ui.setBuildToolsVisible(false);+ this.ui.closeShareSheet();+ this.ui.closeFeatured();+ try { this.localCosmetics?.dispose(); } catch {}+ this.localCosmetics = null; this._localCosWire = null;if (this.localRig) { this.scene.remove(this.localRig); this.localRig = null; }if (this._nipple) { this._nipple.destroy(); this._nipple = null; }this.phase = 'lobby';@@ -1163,13 +1227,20 @@ export class CoinCommunities {return false;}- // Open/close the cosmetics shop (R21). Lazy-built; previews route to the- // local rig hooks above. Reverts any preview when it closes.+ // Open/close the cosmetics shop (R21 browse/preview + R22 buy). Lazy-built;+ // previews route to the local rig hooks above, and a settled purchase records+ // ownership server-side. Reverts any preview when it closes._toggleShop() {if (!this._shop) {this._shop = new CosmeticsShop({+ // Key ownership + purchases on the verified wallet when we have one;+ // the shop falls back to the persisted guest id otherwise.+ account: this.account || '',onPreview: (item) => this.equipCosmeticPreview(item),onEndPreview: () => this.unequipCosmeticPreview(),+ // A premium item was just bought (R22) — now owned for this account.+ // Keep it previewing so the buyer sees what they unlocked.+ onPurchased: (item) => { this._previewItem = item; },});}this._shop.toggle();@@ -1185,6 +1256,34 @@ export class CoinCommunities {this._previewItem = null;}+ // ── Owned-cosmetics: persisted equip on the LOCAL avatar (R23) ─────────────+ // Dress the local avatar in `wire` (an equipped loadout, slot→id map or wire+ // string). Idempotent — re-applies only when it actually changed — and reuses+ // the shared applyLoadout so the local body, peers and the creator preview all+ // render the same wardrobe. Separate from the R21 shop's ephemeral preview+ // above (AccessoryManager): this is the durable, equipped look.+ _applyLocalCosmetics(wire) {+ const next = typeof wire === 'string' ? wire : serializeLoadout(wire);+ if (this.localCosmetics && this._localCosWire === next) return;+ this._localCosWire = next;+ try { this.localCosmetics?.dispose(); } catch {}+ this.localCosmetics = (this.localRig && this.localHeight)+ ? applyLoadout(this.localRig, this.localHeight, next)+ : null;+ }++ // The server echoes the authoritative profile on join and after every equip.+ // Mirror the equipped loadout to the cross-world store (so /walk and the next+ // session restore the same fit) and re-dress the local avatar. This is the one+ // place equip state flows client-side, so the wardrobe panel, the 3D body and+ // the persisted mirror never drift apart.+ _onCosmeticsProfile(snap) {+ const equipped = snap?.cosmetics?.equipped;+ if (!equipped || typeof equipped !== 'object') return;+ setPlayCosmetics(equipped);+ this._applyLocalCosmetics(equipped);+ }+// Surface unread chat in the tab title when the page is backgrounded, so a// new message pulls the user back. Cleared the moment they refocus the tab._bumpTabUnread() {@@ -1528,6 +1627,7 @@ export class CoinCommunities {const action = this._undoStack?.pop();if (!action) { this.ui.toast('Nothing to undo.', 'info'); return; }if (action.kind === 'place') this._applyEdit('place', action.cell, action.type);+ else if (action.kind === 'remove-batch') for (const cell of action.cells) this._applyEdit('remove', cell);else this._applyEdit('remove', action.cell);this._refreshGhost();}@@ -1555,6 +1655,9 @@ export class CoinCommunities {column: 'That stack is too tall here — try building wider, not higher.',protected: 'That spot is protected — keep the spawn and totem clear.',player: 'You’ve hit your block limit for this world — break some to build more.',+ playercap: 'You’ve hit your block limit for this world — break some to build more.',+ dense: 'That stack is too tall here — try building wider, not higher.',+ notcreator: 'Only the coin’s creator can clear builds here.',}[reason] || 'That edit couldn’t be applied.';this.ui.toast(msg, 'warn');}@@ -1585,18 +1688,189 @@ export class CoinCommunities {if (this.buildHud.active && this._lastHover) this._updateGhost(this._lastHover.x, this._lastHover.y);}+ // Adopt the server's build-permission snapshot: drive the per-player allowance+ // meter and reveal the creator-only moderation control. Authoritative — the HUD+ // only surfaces what the server already enforces.+ _onBuildPerms(p) {+ if (!p || typeof p !== 'object') return;+ this._buildPerms = {+ creator: !!p.creator,+ cap: Number(p.cap) || 0,+ used: Number(p.used) || 0,+ clearMaxRadius: Number(p.clearMaxRadius) || 12,+ };+ this.buildHud.setCreator(this._buildPerms.creator);+ this.buildHud.setUsage(this._buildPerms.used, this._buildPerms.cap);+ }++ // Clear the per-player meter + creator tool — on leave and on every (re)connect,+ // before fresh perms arrive, so a solo build or a different world never inherits+ // the last one's allowance or moderation control.+ _resetBuildPerms() {+ this._buildPerms = { creator: false, cap: 0, used: 0, clearMaxRadius: 12 };+ this.buildHud.setCreator(false);+ this.buildHud.setUsage(0, 0);+ }++ // Creator moderation: clear a disc of blocks around where the player stands, or+ // the whole world. Both are confirmed (a clear is destructive) and validated again+ // server-side. Maps the avatar's world position to the build grid for the area+ // sweep; the radius is the server-advertised maximum so the tool's reach is honest.+ _onClearArea(scope) {+ if (!this._buildPerms.creator || this.net?.status !== 'online') {+ this.ui.toast('Clearing builds needs a live connection as the coin creator.', 'warn');+ return;+ }+ if (scope === 'all') {+ if (typeof confirm === 'function' && !confirm('Clear EVERY block in this world? This can\u2019t be undone.')) return;+ this.net.sendClearAll();+ return;+ }+ const r = this._buildPerms.clearMaxRadius || 12;+ if (typeof confirm === 'function' && !confirm(`Clear all blocks within ${r} cells of where you stand?`)) return;+ const gx = Math.round(this.localPos.x / BLOCK);+ const gz = Math.round(this.localPos.z / BLOCK);+ this.net.sendClearArea(gx, gz, r);+ }+_onBuildToggle(on) {- if (!on) { this.voxels?.hideGhost(); this.canvas.style.cursor = ''; return; }+ // The structures toolbar (composite pieces + rotate + share + featured) lives+ // or dies with build mode.+ this.ui.setBuildToolsVisible(on);+ if (!on) { this.voxels?.hideGhost(); this.voxels?.hideFootprint(); this.canvas.style.cursor = ''; return; }const touch = typeof matchMedia === 'function' && matchMedia('(hover: none), (pointer: coarse)').matches;const solo = this.net?.status !== 'online';const how = touch? 'tap to place, hold to break, pick a block, ⌘/Ctrl+Z to undo'- : 'click to place, right-click to break, 1–0 pick a block, ⌘/Ctrl+Z to undo';+ : 'click to place, right-click to break, 1–0 pick a block, R rotates pieces, ⌘/Ctrl+Z to undo';this.ui.toast(`Build mode${solo ? ' (offline — reconnect to share)' : ''} — ${how}`, 'info');this._syncBudget();if (this._lastHover) this._updateGhost(this._lastHover.x, this._lastHover.y);}+ // ---------------------------------------------------------------- share builds+ // Render the current view into an offscreen target and return a JPEG data URL ++ // dimensions, or null if capture isn't possible. Uses a render target (not the+ // live canvas) so it works regardless of preserveDrawingBuffer, and downscales+ // to keep the thumbnail small enough to persist and share.+ _captureBuildShot(maxW = 720) {+ const r = this.renderer;+ if (!r || !this.scene || !this.camera) return null;+ const size = r.getSize(new Vector2());+ if (size.x < 1 || size.y < 1) return null;+ const scale = Math.min(1, maxW / size.x);+ const w = Math.max(1, Math.round(size.x * scale));+ const h = Math.max(1, Math.round(size.y * scale));+ let rt = null;+ try {+ rt = new WebGLRenderTarget(w, h, { samples: 4 });+ rt.texture.colorSpace = SRGBColorSpace;+ const prev = r.getRenderTarget();+ r.setRenderTarget(rt);+ r.render(this.scene, this.camera);+ const buf = new Uint8Array(w * h * 4);+ r.readRenderTargetPixels(rt, 0, 0, w, h, buf);+ r.setRenderTarget(prev);+ const c = document.createElement('canvas');+ c.width = w; c.height = h;+ const ctx = c.getContext('2d');+ const img = ctx.createImageData(w, h);+ // WebGL's origin is bottom-left; flip rows so the image isn't upside down.+ for (let y = 0; y < h; y++) {+ const src = (h - 1 - y) * w * 4;+ img.data.set(buf.subarray(src, src + w * 4), y * w * 4);+ }+ ctx.putImageData(img, 0, 0);+ return { dataUrl: c.toDataURL('image/jpeg', 0.72), width: w, height: h };+ } catch (err) {+ log.warn('[coincommunities] build capture failed:', err?.message);+ return null;+ } finally {+ rt?.dispose();+ }+ }++ // Capture a screenshot of the build and open the share sheet: copy a deep link,+ // download the image, or publish it to this coin's featured builds.+ _shareBuild() {+ if (this.phase !== 'world' || !this.coin) return;+ const shot = this._captureBuildShot();+ if (!shot) { this.ui.toast('Couldn’t capture the view — try again.', 'warn'); return; }+ const link = this._coinShareLink();+ const blocks = this.voxels?.count ?? 0;+ this.ui.openShareSheet({+ image: shot.dataUrl,+ link,+ blocks,+ coinName: this.coin.symbol ? '$' + this.coin.symbol : (this.coin.name || 'this world'),+ canPublish: blocks > 0,+ });+ }++ // A shareable deep link back into this exact community.+ _coinShareLink() {+ const q = new URLSearchParams({ coin: this.coin.mint });+ if (this.coin.name) q.set('name', this.coin.name);+ if (this.coin.symbol) q.set('symbol', this.coin.symbol);+ if (this.coin.image) q.set('image', this.coin.image);+ return `${location.origin}/play?${q.toString()}`;+ }++ // Publish the captured build to this coin's featured surface via the R17+ // persistence-backed endpoint. Returns a result the share sheet renders inline.+ async _publishBuild({ image, title }) {+ if (!this.coin?.mint) return { ok: false, error: 'No world to publish to.' };+ const author = this.ui.getName() || (this.account ? this.account.slice(0, 4) + '…' + this.account.slice(-4) : 'anon');+ try {+ const res = await fetch('/api/play/builds', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ mint: this.coin.mint,+ title: (title || '').trim().slice(0, 60),+ author: author.slice(0, 32),+ blocks: this.voxels?.count ?? 0,+ thumb: image,+ }),+ });+ if (!res.ok) {+ const reason = res.status === 429 ? 'Sharing too fast — give it a minute.'+ : res.status === 413 ? 'That screenshot was too large to share.'+ : `Couldn’t publish (error ${res.status}).`;+ return { ok: false, error: reason };+ }+ // A fresh publish belongs at the top of the featured list — refresh if open.+ if (this._featuredOpen) this._loadFeatured();+ return { ok: true };+ } catch (err) {+ log.warn('[coincommunities] publish build failed:', err?.message);+ return { ok: false, error: 'Network error — check your connection and retry.' };+ }+ }++ // Open this coin's featured builds surface and load it.+ _openFeatured() {+ if (!this.coin?.mint) return;+ this._featuredOpen = true;+ this.ui.openFeatured(this.coin.symbol ? '$' + this.coin.symbol : (this.coin.name || 'this world'));+ this._loadFeatured();+ }++ async _loadFeatured() {+ const mint = this.coin?.mint;+ if (!mint) return;+ this.ui.setFeaturedLoading();+ try {+ const res = await fetch(`/api/play/builds?mint=${encodeURIComponent(mint)}`, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error('HTTP ' + res.status);+ const data = await res.json();+ this.ui.setFeaturedBuilds(Array.isArray(data?.builds) ? data.builds : []);+ } catch (err) {+ log.warn('[coincommunities] featured load failed:', err?.message);+ this.ui.setFeaturedError(() => this._loadFeatured());+ }+ }+_initJoystick() {const zone = document.getElementById('cc-joystick');if (!zone || this._joyInit) return;@@ -1665,6 +1939,7 @@ export class CoinCommunities {if (this.phase === 'world') {this._stepLocal(dt);this.localAnim?.update(dt);+ this.localCosmetics?.tick(dt);for (const [, r] of this.remotes) r.tick(dt);this._updateLabels();this._updateVoice();diff --git a/src/game/community-net.js b/src/game/community-net.jsindex f3268baf2..dea07e3bc 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -127,6 +127,8 @@ export class CommunityNet {blockChange: new Set(), // (key, type) — a voxel was repaintedblockRemove: new Set(), // (key) — a voxel was brokeneditReject: new Set(), // ({reason}) — the server refused one of our edits+ buildPerms: new Set(), // ({creator, cap, used, clearMaxRadius}) — build-permission snapshot (R19)+ buildCleared: new Set(), // ({count, all}) — creator clear-area result (R19)persistent: new Set(), // (bool) — whether this world's build is durably savedworldtime: new Set(), // (frac) — authoritative day fraction [0,1) for day/night// Off-schema economy (private to this player; delivered as targeted messages).@@ -252,6 +254,11 @@ export class CommunityNet {// The server replies here when it refuses one of our place/break edits// (budget full, rate limited, …) so the HUD can explain the no-op.this.room.onMessage('edit-reject', (msg) => this._emit('editReject', msg || {}));+ // Build permissions (R19): the per-player cap + usage, and whether we're the+ // coin creator (which unlocks the clear-area moderation tool). Sent on join and+ // whenever our tally moves. build-cleared confirms a creator clear-area sweep.+ this.room.onMessage('build-perms', (msg) => this._emit('buildPerms', msg || {}));+ this.room.onMessage('build-cleared', (msg) => this._emit('buildCleared', msg || {}));// Off-schema economy: the server streams this player's own pack/purse/skills// here (peers never see it). Drives the HUD, inventory, hotbar and toasts.this.room.onMessage('profile', (msg) => this._emit('profile', msg || {}));@@ -417,6 +424,11 @@ export class CommunityNet {// Each placed block streams back through the same blockAdd path as single edits.sendPlaceBatch(cells) { this.room?.send('place-batch', { cells }); }sendRemove(x, y, z) { this.room?.send('remove', { x, y, z }); }+ // Creator-only moderation (R19): clear a disc of blocks around a grid cell, or the+ // whole world. The server validates the creator identity + bounds and streams each+ // removal back through the usual blockRemove path.+ sendClearArea(x, z, r) { this.room?.send('build-clear', { x, z, r }); }+ sendClearAll() { this.room?.send('build-clear', { all: true }); }sendInteract(to, action) { this.room?.send('interact', { to, action }); }// Spatial voice: relay a WebRTC offer/answer/ICE candidate to one peer, and// flag ourselves in/out of voice so peers know whether to connect to us.diff --git a/src/game/cosmetics-purchase.js b/src/game/cosmetics-purchase.jsnew file mode 100644index 000000000..917195b49--- /dev/null+++ b/src/game/cosmetics-purchase.js@@ -0,0 +1,99 @@+// Cosmetics purchase rail (R22) — turn a "Buy" into a REAL USDC payment.+//+// The shop (R21) handles browsing + live preview; this module handles money.+// purchaseCosmetic() runs the x402 flow against /api/x402/cosmetic-purchase:+// window.X402.pay opens the wallet, settles the USDC on Base or Solana, and the+// endpoint records ownership of the cosmetic to the player's account in the+// durable ledger (api/_lib/cosmetics-ownership.js). It resolves only after the+// server confirms ownership — there is no optimistic unlock — and rejects with a+// wallet-accurate Error (including insufficient funds) on failure. The rail is+// idempotent (single-use on-chain proof + idempotent ownership grant), so a+// retried buy never double-charges.+//+// Ownership is keyed on the player's stable account id: their verified wallet+// when signed in, otherwise the same persisted guest id the /play economy uses+// (`cc-pid`), so a guest purchase survives a refresh on this device.+//+// $THREE is the coin the shop quotes value in; USDC is only the settlement asset+// the rail charges — never surfaced as a coin to hold.++import { loadStoredPass } from './play-auth.js';++const PURCHASE_ENDPOINT = '/api/x402/cosmetic-purchase';+const OWNED_ENDPOINT = '/api/cosmetics/owned';++// Resolve the account a purchase is attached to. Prefers an explicit verified+// wallet (the id the room already carries), then a cached play pass, then the+// persisted guest id. Returns '' only if storage is entirely unavailable.+export function resolveShopAccount(explicitWallet) {+ if (explicitWallet) return explicitWallet;+ try {+ const pass = loadStoredPass();+ if (pass?.wallet) return pass.wallet;+ } catch { /* fall through to guest id */ }+ try {+ let id = localStorage.getItem('cc-pid');+ if (!id) { id = 'guest-' + Math.random().toString(36).slice(2, 12); localStorage.setItem('cc-pid', id); }+ return id;+ } catch {+ return '';+ }+}++// Run the x402 USDC payment for one cosmetic. Resolves with the settled ticket+// ({ ok, owned, newlyOwned, payer, network, … }); rejects with an Error on+// failure or { code:'cancelled' } when the buyer dismisses the wallet.+export async function purchaseCosmetic(item, { account } = {}) {+ if (!window.X402?.pay) {+ throw new Error('Payment widget still loading — try again in a second.');+ }+ if (!item?.id) throw new Error('Pick a cosmetic to buy.');+ const acct = account || resolveShopAccount();+ if (!acct) throw new Error('No account to attach this purchase to.');++ // First-timers get the wallet/USDC explainer before the payment modal; returning+ // buyers pass straight through. Lazy-loaded so the shop only pays for it on the+ // first buy. A cancel here aborts the purchase; a load failure is non-fatal.+ try {+ const { ensureOnchainPrimer } = await import('../shared/onchain-primer.js');+ if (!(await ensureOnchainPrimer({ action: 'buy' }))) {+ const err = new Error('cancelled'); err.code = 'cancelled'; throw err;+ }+ } catch (err) {+ if (err?.code === 'cancelled') throw err;+ // primer unavailable — proceed to the payment modal anyway.+ }++ const url = `${PURCHASE_ENDPOINT}?id=${encodeURIComponent(item.id)}&account=${encodeURIComponent(acct)}`;+ const out = await window.X402.pay({+ endpoint: url,+ method: 'GET',+ merchant: 'three.ws Avatar Shop',+ action: `Unlock ${item.name} — $${item.priceUsdc} USDC`,+ });++ // SIWX re-access (a wallet that already paid) returns the settled body too;+ // either way the server is the source of truth for `owned`.+ const ticket = out?.result;+ if (!ticket?.ok || !ticket?.owned) {+ throw new Error(ticket?.error || 'purchase did not settle');+ }+ return ticket;+}++// The premium cosmetic ids an account owns, from the ledger. Degrades to [] on+// any error so a caller (shop owned-state, R23 inventory) still renders.+export async function fetchOwnedCosmetics(account) {+ const acct = account || resolveShopAccount();+ if (!acct) return [];+ try {+ const res = await fetch(`${OWNED_ENDPOINT}?account=${encodeURIComponent(acct)}`, {+ headers: { accept: 'application/json' },+ });+ if (!res.ok) return [];+ const body = await res.json();+ return Array.isArray(body?.ownedIds) ? body.ownedIds : [];+ } catch {+ return [];+ }+}diff --git a/src/game/cosmetics-shop.js b/src/game/cosmetics-shop.jsindex 7d5153b0b..d1441d503 100644--- a/src/game/cosmetics-shop.js+++ b/src/game/cosmetics-shop.js@@ -1,17 +1,22 @@-// Cosmetics Shop (R21) — in-world panel to browse the cosmetics catalog, filter-// by rarity, and preview any item LIVE on your own avatar before buying.+// Cosmetics Shop (R21 browse/preview + R22 x402 purchase) — in-world panel to+// browse the cosmetics catalog, filter by rarity, preview any item LIVE on your+// own avatar, and BUY a premium item with a real USDC payment over x402.//// The shop is pure 2D chrome: it fetches the real catalog and calls back into-// the scene (coincommunities.js) to equip/unequip a preview on the local rig.-// It never mutates the 3D scene directly and never persists a purchase — that's-// R22 (x402) / R23 (inventory). Prices are denominated in $THREE, the only coin.+// the scene (coincommunities.js) to equip/unequip a preview on the local rig. A+// "Buy" runs the x402 flow in cosmetics-purchase.js — open wallet, settle USDC,+// record ownership server-side — and flips the card to owned only once the+// server confirms it (no optimistic unlock). Owned state is read per-account+// from the R22 ledger. The item's value is quoted in $THREE (the only coin);+// USDC is the settlement asset shown on the buy button.//-// Catalog source: the real endpoint /api/cosmetics/catalog, with the static CDN-// mirror /cosmetics/catalog.json as a resilient fallback (and the dev source,-// where /api/* proxies to prod and the endpoint isn't deployed yet). Both are-// real network fetches — there is no client-side sample array.+// Catalog source: the real endpoint /api/cosmetics/catalog (with the caller's+// account, so owned items render owned), with the static CDN mirror+// /cosmetics/catalog.json as a resilient fallback (and the dev source, where+// /api/* proxies to prod). Both are real network fetches — no sample array.import { log } from '../shared/log.js';+import { purchaseCosmetic, resolveShopAccount } from './cosmetics-purchase.js';function el(tag, props = {}, kids = []) {const n = document.createElement(tag);@@ -38,8 +43,10 @@ const fmtPrice = (n) => {// Fetch the catalog from the real endpoint, falling back to the static mirror.// Throws only if neither source yields items, so the UI can show its error state.-async function fetchCatalog(rarity) {- const qs = rarity ? `?rarity=${encodeURIComponent(rarity)}` : '';+// `account` (when set) makes premium items the account already bought read as+// owned — the static mirror has no account view, so it always shows them locked.+async function fetchCatalog(account) {+ const qs = account ? `?account=${encodeURIComponent(account)}` : '';const sources = [`/api/cosmetics/catalog${qs}`, '/cosmetics/catalog.json'];for (const url of sources) {try {@@ -55,8 +62,11 @@ async function fetchCatalog(rarity) {export class CosmeticsShop {/*** @param {object} h handlers:- * onPreview(item) — equip the item live on the local avatar.- * onEndPreview() — revert the active preview.+ * onPreview(item) — equip the item live on the local avatar.+ * onEndPreview() — revert the active preview.+ * onPurchased(item) — (optional) a premium item was just bought.+ * account — (optional) verified wallet to key ownership on;+ * falls back to the persisted guest id.*/constructor(h = {}) {this.h = h;@@ -64,6 +74,10 @@ export class CosmeticsShop {this.rarity = 'all'; // active rarity filterthis.previewId = null; // id of the item currently previewing (toggle)this.state = 'idle'; // idle | loading | ready | error+ this.buyingId = null; // id of the item whose payment is in flight+ // The account ownership + purchases are keyed on. Resolved once at build;+ // re-resolved on each open() in case the player signs in between sessions.+ this.account = resolveShopAccount(h.account);this._build();}@@ -134,8 +148,14 @@ export class CosmeticsShop {requestAnimationFrame(() => this.root.classList.add('cc-shop-in'));document.addEventListener('keydown', this._onKey, true);this.closeBtn.focus();- // Load once; re-open reuses the catalog (cheap, and avoids a flash).- if (this.state !== 'ready') await this._load();+ // Re-resolve the account in case the player signed in since last open, so a+ // fresh wallet sees its owned items rather than the guest's.+ const acct = resolveShopAccount(this.h.account);+ const accountChanged = acct !== this.account;+ this.account = acct;+ // Load once; re-open reuses the catalog (cheap, and avoids a flash) — unless+ // the account changed, which flips owned/locked state and needs a refetch.+ if (this.state !== 'ready' || accountChanged) await this._load();else this._render();}@@ -161,9 +181,9 @@ export class CosmeticsShop {this.state = 'loading';this._renderSkeleton();try {- // Always fetch the full catalog; rarity filtering is client-side so- // switching tabs is instant and needs no refetch.- this.items = await fetchCatalog();+ // Always fetch the full catalog (keyed on the account so owned items read+ // owned); rarity filtering is client-side so switching tabs is instant.+ this.items = await fetchCatalog(this.account);this.state = 'ready';this._render();} catch (err) {@@ -175,9 +195,10 @@ export class CosmeticsShop {// ── rendering ───────────────────────────────────────────────────────────────- _status(text) {+ _status(text, kind = '') {this.statusEl.textContent = text || '';this.statusEl.hidden = !text;+ this.statusEl.dataset.kind = text ? kind : '';}_renderSkeleton() {@@ -243,41 +264,110 @@ export class CosmeticsShop {}): this._glyph(item);- const badge = item.owned- ? el('span', { class: 'cc-shop-badge cc-owned', text: 'Owned' })- : el('span', { class: 'cc-shop-badge cc-locked' }, [- el('span', { class: 'cc-lock-ico', 'aria-hidden': 'true', text: '🔒' }),- el('span', { text: `${fmtPrice(item.price)} $THREE` }),- ]);+ // The thumb is the live-preview toggle (R21): a button so it's keyboard- and+ // screen-reader-operable on its own, separate from the Buy button below.+ const previewBtn = el('button', {+ class: 'cc-shop-thumb cc-shop-thumb-btn',+ type: 'button',+ 'aria-pressed': active ? 'true' : 'false',+ 'aria-label': `${active ? 'Stop previewing' : 'Preview'} ${item.name} on your avatar`,+ title: active ? 'Click to stop preview' : 'Click to preview on your avatar',+ onclick: () => this._toggleItem(item),+ }, [+ thumb,+ el('span', { class: 'cc-shop-rarity', 'data-rarity': item.rarity, text: RARITY_LABEL[item.rarity] }),+ el('span', { class: 'cc-shop-preview-tag', 'aria-hidden': 'true', text: active ? 'Previewing' : 'Preview' }),+ ]);- const card = el('button', {+ const card = el('div', {class: 'cc-shop-card'+ ` cc-rarity-${item.rarity}`+ (item.owned ? ' cc-is-owned' : ' cc-is-locked')+ (active ? ' cc-active' : ''),- type: 'button',- 'aria-pressed': active ? 'true' : 'false',- 'aria-label': `${item.name} — ${RARITY_LABEL[item.rarity]}, ${item.owned ? 'owned' : `locked, ${item.price} $THREE`}. ${active ? 'Stop preview' : 'Preview on your avatar'}`,- title: active ? 'Click to stop preview' : 'Click to preview on your avatar',- onclick: () => this._toggleItem(item),+ 'data-id': item.id,}, [- el('div', { class: 'cc-shop-thumb' }, [- thumb,- el('span', { class: 'cc-shop-rarity', 'data-rarity': item.rarity, text: RARITY_LABEL[item.rarity] }),- el('span', { class: 'cc-shop-preview-tag', 'aria-hidden': 'true', text: active ? 'Previewing' : 'Preview' }),- ]),+ previewBtn,el('div', { class: 'cc-shop-meta' }, [el('span', { class: 'cc-shop-name', text: item.name }),- badge,+ // The item's value is quoted in $THREE — the only coin (R21 copy).+ el('span', { class: 'cc-shop-value', text: `${fmtPrice(item.price)} $THREE` }),+ this._action(item),]),]);return card;}+ // The owned badge or the Buy button (R22). Built separately so a settled+ // purchase can swap just this node to "Owned" without re-rendering the grid.+ _action(item) {+ if (item.owned) {+ return el('span', { class: 'cc-shop-action cc-shop-badge cc-owned', text: 'Owned' });+ }+ const pending = this.buyingId === item.id;+ const buy = el('button', {+ class: 'cc-shop-action cc-shop-buy',+ type: 'button',+ disabled: pending || undefined,+ // USDC is the settlement asset (not a coin we hold) — labelled on the CTA.+ 'aria-label': `Buy ${item.name} for ${item.priceUsdc} USDC`,+ text: pending ? 'Opening wallet…' : `Buy · $${item.priceUsdc} USDC`,+ onclick: () => this._buy(item),+ });+ return buy;+ }+_glyph(item) {return el('div', { class: 'cc-shop-glyph', 'aria-hidden': 'true', text: SLOT_GLYPH[item.slot] || '✦' });}+ // ── purchase (R22) ──────────────────────────────────────────────────────────+ // Run the real x402 USDC payment for a locked item and, on the server's+ // confirmation, flip the card to owned. Every state is honest: pending while+ // the wallet is open, owned only after the payment verifies, an actionable+ // message on failure (including insufficient funds). No optimistic unlock.+ async _buy(item) {+ if (this.buyingId || item.owned) return;+ this.buyingId = item.id;+ const card = this.grid.querySelector(`.cc-shop-card[data-id="${CSS.escape(item.id)}"]`);+ this._swapAction(card, item);+ this._status(`Settling payment for ${item.name}…`, 'pending');+ try {+ const ticket = await purchaseCosmetic(item, { account: this.account });+ this.buyingId = null;+ item.owned = true;+ if (card) {+ card.classList.remove('cc-is-locked');+ card.classList.add('cc-is-owned');+ this._swapAction(card, item);+ }+ this._status(+ ticket.newlyOwned ? `Unlocked ${item.name}.` : `${item.name} is already in your wardrobe.`,+ 'ok',+ );+ try { this.h.onPurchased?.(item, ticket); } catch (err) { log.warn('[shop] onPurchased', err?.message); }+ } catch (err) {+ this.buyingId = null;+ this._swapAction(card, item);+ if (err?.code === 'cancelled') { this._status(''); return; }+ const msg = String(err?.message || err);+ // The wallet relays an insufficient-balance error verbatim — turn it into+ // an actionable nudge instead of a raw failure string.+ const insufficient = /insufficient|balance|not enough|exceeds/i.test(msg);+ this._status(+ insufficient+ ? `Not enough USDC to buy ${item.name}. Top up your wallet and try again.`+ : `Purchase failed: ${msg}`,+ 'error',+ );+ }+ }++ // Replace just the action node of a card in place (Buy ⇄ pending ⇄ Owned).+ _swapAction(card, item) {+ const old = card?.querySelector('.cc-shop-action');+ if (old) old.replaceWith(this._action(item));+ }+// ── preview toggle ────────────────────────────────────────────────────────async _toggleItem(item) {diff --git a/src/game/play-systems.css b/src/game/play-systems.cssindex 7edd882af..622b46698 100644--- a/src/game/play-systems.css+++ b/src/game/play-systems.css@@ -267,6 +267,128 @@.ps-skill-bar { height: 5px; background: rgba(255, 255, 255, 0.08); border-radius: 99px; overflow: hidden; }.ps-skill-fill { display: block; height: 100%; background: #fff; border-radius: 99px; transition: width 0.4s ease; }+/* ---- My Cosmetics (R23) ---- */+.ps-cos { width: 320px; }+.ps-cos-body { padding: 12px 12px 6px; overflow-y: auto; }+.ps-cos-slot-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin: 10px 2px 7px;+}+.ps-cos-slot-head:first-child { margin-top: 2px; }+.ps-cos-slot-name {+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.14em;+ text-transform: uppercase;+ color: var(--cc-dim);+}+.ps-cos-remove {+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--cc-dim);+ background: transparent;+ border: 1px solid var(--cc-edge-soft);+ border-radius: var(--cc-radius-sm);+ padding: 2px 8px;+ transition: color 0.12s ease, border-color 0.12s ease, background 0.12s ease;+}+.ps-cos-remove:hover { color: var(--cc-text); border-color: var(--cc-edge); background: rgba(255, 255, 255, 0.08); }+.ps-cos-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 7px; }+.ps-cos-card {+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 6px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid var(--cc-edge-soft);+ border-radius: var(--cc-radius-sm);+ cursor: pointer;+ transition: transform 0.09s ease, background 0.12s ease, border-color 0.12s ease, box-shadow 0.14s ease;+}+.ps-cos-card[role="button"]:hover { background: rgba(255, 255, 255, 0.1); border-color: var(--cc-edge); transform: translateY(-2px); }+.ps-cos-card[role="button"]:focus-visible { outline: 2px solid #fff; outline-offset: 1px; }+.ps-cos-card.is-equipped { border-color: #fff; background: rgba(255, 255, 255, 0.14); box-shadow: var(--cc-glow); cursor: default; }+.ps-cos-card.is-locked { opacity: 0.5; cursor: default; }+.ps-cos-card.is-locked:hover { transform: none; }+.ps-cos-preview {+ position: relative;+ aspect-ratio: 1;+ display: grid;+ place-items: center;+ background: rgba(0, 0, 0, 0.25);+ border-radius: var(--cc-radius-sm);+ overflow: hidden;+}+.ps-cos-thumb { width: 100%; height: 100%; object-fit: contain; }+.ps-cos-swatch { width: 60%; height: 60%; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.25); }+.ps-cos-rarity {+ position: absolute;+ left: 3px;+ bottom: 3px;+ font-size: 8px;+ font-weight: 800;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ padding: 1px 4px;+ border-radius: 99px;+ background: rgba(0, 0, 0, 0.6);+ color: var(--cc-dim);+}+.ps-cos-rarity.is-rare { color: #7cc7ff; }+.ps-cos-rarity.is-epic { color: #d49bff; }+.ps-cos-rarity.is-legendary { color: #ffd470; }+.ps-cos-check {+ position: absolute;+ top: 3px;+ right: 3px;+ width: 16px;+ height: 16px;+ display: grid;+ place-items: center;+ font-size: 10px;+ font-weight: 900;+ color: var(--cc-ink);+ background: #fff;+ border-radius: 50%;+}+.ps-cos-name {+ font-size: 11px;+ color: var(--cc-text);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.ps-cos-status { font-size: 9px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--cc-faint); }+.ps-cos-card.is-equipped .ps-cos-status { color: var(--cc-text); }+.ps-cos-hint {+ margin: 10px 2px 6px;+ font-size: 11px;+ line-height: 1.5;+ color: var(--cc-faint);+}+.ps-cos-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 12px;+ padding: 34px 12px;+ text-align: center;+}+.ps-cos-state-text { font-size: 12px; color: var(--cc-dim); margin: 0; }+.ps-cos-spinner {+ width: 26px;+ height: 26px;+ border-radius: 50%;+ border: 2px solid var(--cc-edge);+ border-top-color: #fff;+ animation: ps-cos-spin 0.8s linear infinite;+}+@keyframes ps-cos-spin { to { transform: rotate(360deg); } }+/* ---- Floating XP + level-up ---- */.ps-xp-float {position: fixed;diff --git a/src/game/play-systems.js b/src/game/play-systems.jsindex c15589254..dc256fa7f 100644--- a/src/game/play-systems.js+++ b/src/game/play-systems.js@@ -28,8 +28,21 @@ import {FIREPITS, nearestFirepit, MOB_SPAWNS, nearestMobSpawn,} from '../../multiplayer/src/world-features.js';import { itemDisplay } from './items.js';+import {+ COSMETICS, SLOTS, SLOT_LABELS, getCosmetic, DEFAULT_LOADOUT,+} from '../../multiplayer/src/cosmetics-catalog.js';import './play-systems.css';+// Rarity → display label + accent, shared by the inventory cards. Keeps the+// wardrobe legible at a glance (a legendary aura should read differently from a+// common dye) without inventing per-item art.+const RARITY_META = {+ common: { label: 'Common', cls: 'is-common' },+ rare: { label: 'Rare', cls: 'is-rare' },+ epic: { label: 'Epic', cls: 'is-epic' },+ legendary: { label: 'Legendary', cls: 'is-legendary' },+};+// Contextual activities the world offers, beyond fishing. Each entry knows the// tool the player must hold (null = none), the nearest-node finder (shared with the// server so the range rule never drifts), and the verb shown on the action button.@@ -165,7 +178,10 @@ export class PlaySystems {// Right tool rail: inventory + skills toggles.this.invBtn = el('button', { class: 'ps-rail-btn', title: 'Inventory (backpack)', 'aria-label': 'Inventory', onclick: () => this.toggleInventory() }, [el('span', { text: '🎒' })]);this.skillsBtn = el('button', { class: 'ps-rail-btn', title: 'Skills', 'aria-label': 'Skills', onclick: () => this.toggleSkills() }, [el('span', { text: '📊' })]);- this.rail = el('div', { class: 'ps-rail' }, [this.invBtn, this.skillsBtn]);+ // My Cosmetics (R23): the owned wardrobe + equip. Equipping persists to the+ // account and re-applies in every world; peers see the fit live.+ this.cosBtn = el('button', { class: 'ps-rail-btn', title: 'My Cosmetics', 'aria-label': 'My Cosmetics', onclick: () => this.toggleCosmetics() }, [el('span', { text: '👕' })]);+ this.rail = el('div', { class: 'ps-rail' }, [this.invBtn, this.skillsBtn, this.cosBtn]);// Hotbar (bottom-center, above the emote tray).this.hotbarEl = el('div', { class: 'ps-hotbar', role: 'toolbar', 'aria-label': 'Hotbar' });@@ -194,8 +210,20 @@ export class PlaySystems {this.skillsList,]);+ // My Cosmetics panel (R23): the owned wardrobe. Body is rebuilt per open from+ // the latest profile snapshot so it always reflects the authoritative owned ++ // equipped set; states (loading/empty/error) render inside ps-cos-body.+ this.cosBody = el('div', { class: 'ps-cos-body' });+ this.cosPanel = el('div', { class: 'ps-panel ps-cos', hidden: true, role: 'dialog', 'aria-label': 'My Cosmetics' }, [+ el('div', { class: 'ps-panel-head' }, [+ el('span', { class: 'ps-panel-title', text: 'My Cosmetics' }),+ el('button', { class: 'ps-x', 'aria-label': 'Close', text: '✕', onclick: () => this.toggleCosmetics(false) }),+ ]),+ this.cosBody,+ ]);+this.root = el('div', { id: 'ps-hud' }, [- this.gold, this.rail, this.actionBtn, this.hotbarEl, this.invPanel, this.skillsPanel,+ this.gold, this.rail, this.actionBtn, this.hotbarEl, this.invPanel, this.skillsPanel, this.cosPanel,]);document.body.appendChild(this.root);@@ -216,6 +244,16 @@ export class PlaySystems {};this.cap = snap.cap || 99;this.skills = snap.skills || {};+ // Cosmetics ownership + equipped loadout (R23). The server is the source of+ // truth — owned premium ids the account has unlocked, plus the per-slot+ // equipped map (free `none` defaults for empty slots). Marked "loaded" so the+ // panel can tell a still-connecting world (loading) from a genuinely bare one.+ const cos = snap.cosmetics && typeof snap.cosmetics === 'object' ? snap.cosmetics : null;+ this.cosmetics = {+ loaded: true,+ owned: Array.isArray(cos?.owned) ? cos.owned : [],+ equipped: cos?.equipped && typeof cos.equipped === 'object' ? cos.equipped : { ...DEFAULT_LOADOUT },+ };this._renderAll();}@@ -290,6 +328,7 @@ export class PlaySystems {this._renderHotbar();this._renderSkills();if (this._invOpen) this._renderInventory();+ if (this._cosOpen) this._renderCosmetics();}_renderGold() {@@ -424,6 +463,132 @@ export class PlaySystems {if (this._skillsOpen) this._renderSkills();}+ // ---------------------------------------------------------------- cosmetics+ toggleCosmetics(force) {+ this._cosOpen = force == null ? !this._cosOpen : !!force;+ this.cosPanel.hidden = !this._cosOpen;+ this.cosBtn.classList.toggle('is-on', this._cosOpen);+ if (this._cosOpen) this._renderCosmetics();+ }++ // Render "My Cosmetics": the owned wardrobe grouped by slot, each item card+ // showing its rarity and preview, with the equipped one marked and a per-slot+ // "Remove" to unequip. Owned = every free cosmetic plus the premium ids the+ // account has unlocked; locked premium items show a hint to the shop so the+ // panel is never a dead end. Loading/empty states are designed, not blank.+ _renderCosmetics() {+ const body = this.cosBody;+ body.replaceChildren();++ // Loading: no profile snapshot has arrived yet (still joining the world).+ if (!this.cosmetics?.loaded) {+ body.appendChild(el('div', { class: 'ps-cos-state' }, [+ el('div', { class: 'ps-cos-spinner', 'aria-hidden': 'true' }),+ el('p', { class: 'ps-cos-state-text', text: 'Loading your wardrobe…' }),+ ]));+ return;+ }++ const ownedSet = new Set(this.cosmetics.owned || []);+ const equipped = this.cosmetics.equipped || DEFAULT_LOADOUT;+ const ownsAnyPremium = (this.cosmetics.owned || []).length > 0;++ for (const slot of SLOTS) {+ const items = COSMETICS.filter((c) => c.slot === slot);+ if (!items.length) continue;+ const equippedId = equipped[slot];+ // The slot's bare default (its `none` entry) — "Remove" equips it. Only+ // offer it when something non-default is actually worn in this slot.+ const noneId = DEFAULT_LOADOUT[slot];+ const wornNonDefault = equippedId && equippedId !== noneId && getCosmetic(equippedId)?.visual;++ const head = el('div', { class: 'ps-cos-slot-head' }, [+ el('span', { class: 'ps-cos-slot-name', text: SLOT_LABELS[slot] || slot }),+ ]);+ if (wornNonDefault) {+ head.appendChild(el('button', {+ class: 'ps-cos-remove', text: 'Remove', title: `Unequip ${SLOT_LABELS[slot] || slot}`,+ 'aria-label': `Unequip ${SLOT_LABELS[slot] || slot}`,+ onclick: () => this._equipCosmetic(noneId),+ }));+ }+ body.appendChild(head);++ const grid = el('div', { class: 'ps-cos-grid' });+ for (const item of items) {+ // Skip the invisible `none` placeholders — "Remove" already covers+ // clearing a slot; a card for "None" would just be noise.+ if (!item.visual) continue;+ const owned = item.tier === 'free' || ownedSet.has(item.id);+ const isEquipped = equippedId === item.id;+ grid.appendChild(this._cosmeticCard(item, { owned, isEquipped }));+ }+ body.appendChild(grid);+ }++ // Footer: an honest pointer. Everyone owns the free pack; premium pieces are+ // earned in the shop. Surface that path so the wardrobe links onward.+ if (!ownsAnyPremium) {+ body.appendChild(el('p', { class: 'ps-cos-hint', text: 'Unlock premium dyes, hats and auras in the shop — they appear here once you own them.' }));+ }+ }++ // One wardrobe card: preview (GLB thumb or colour swatch), name, rarity, and a+ // state-appropriate action — Equipped (current), Equip (owned), or Locked (a+ // premium item not yet purchased, routed to the shop).+ _cosmeticCard(item, { owned, isEquipped }) {+ const rarity = RARITY_META[item.rarity] || RARITY_META.common;+ const preview = item.thumb+ ? el('img', { class: 'ps-cos-thumb', src: item.thumb, alt: '', loading: 'lazy', draggable: 'false' })+ : el('span', { class: 'ps-cos-swatch', style: `background:${item.swatch || '#888'}`, 'aria-hidden': 'true' });++ const card = el('div', {+ class: `ps-cos-card ${rarity.cls}${isEquipped ? ' is-equipped' : ''}${owned ? '' : ' is-locked'}`,+ }, [+ el('div', { class: 'ps-cos-preview' }, [+ preview,+ el('span', { class: `ps-cos-rarity ${rarity.cls}`, text: rarity.label }),+ isEquipped ? el('span', { class: 'ps-cos-check', text: '✓', 'aria-hidden': 'true' }) : null,+ ]),+ el('span', { class: 'ps-cos-name', text: item.name }),+ el('span', { class: 'ps-cos-status', text: isEquipped ? 'Equipped' : (owned ? 'Owned' : 'Locked') }),+ ]);++ if (!owned) {+ card.setAttribute('title', 'Unlock this in the shop');+ card.setAttribute('aria-disabled', 'true');+ return card;+ }+ // Owned + not equipped → clickable to equip. Equipped → inert (use Remove).+ if (!isEquipped) {+ card.setAttribute('role', 'button');+ card.setAttribute('tabindex', '0');+ card.setAttribute('aria-label', `Equip ${item.name}`);+ const equip = () => this._equipCosmetic(item.id);+ card.addEventListener('click', equip);+ card.addEventListener('keydown', (e) => {+ if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); equip(); }+ });+ } else {+ card.setAttribute('aria-label', `${item.name}, equipped`);+ }+ return card;+ }++ // Send the equip intent. The server validates ownership, persists the loadout to+ // the account, re-broadcasts it to peers and echoes a fresh profile — which flows+ // back through setProfile and re-renders this panel, so we don't mutate optimistically+ // (an unowned id would be rejected with a 'cosmetic' notice). Unequip is the same+ // path with the slot's `none` id.+ _equipCosmetic(id) {+ if (!id) return;+ if (this.net?.status && this.net.status !== 'online') {+ this.ui?.toast?.('Reconnecting to the world — your fit will sync in a moment.', 'warn');+ return;+ }+ this.net?.equipCosmetic(id);+ }+// ---------------------------------------------------------------- cast visual_spawnCast(near) {const p = this.getPlayer();diff --git a/src/walk-net.js b/src/walk-net.jsindex 3c136d33d..5806171ba 100644--- a/src/walk-net.js+++ b/src/walk-net.js@@ -87,6 +87,10 @@ export class WalkNet {this.coinName = opts.coinName || '';this.coinSymbol = opts.coinSymbol || '';this.coinImage = opts.coinImage || '';+ // Pre-join cosmetic loadout (R23): the wire string the player last equipped,+ // so peers in this world see their fit the moment they appear. The server+ // re-validates each id against what the account owns before publishing it.+ this.cosmetics = opts.cosmetics || '';this.client = null;this.room = null;this.status = 'idle'; // 'idle' | 'connecting' | 'online' | 'offline' | 'failed'@@ -177,6 +181,7 @@ export class WalkNet {coinName: this.coinName,coinSymbol: this.coinSymbol,coinImage: this.coinImage,+ cosmetics: this.cosmetics,...(presence ? { presence } : {}),}, WalkState);if (this._destroyed || gen !== this._connectGen) {diff --git a/src/walk.js b/src/walk.jsindex 82ae21333..bbe42bae0 100644--- a/src/walk.js+++ b/src/walk.js@@ -47,6 +47,8 @@ import nipplejs from 'nipplejs';import { AnimationManager } from './animation-manager.js';import { WalkNet } from './walk-net.js';+import { applyLoadout } from './game/cosmetics-loadout.js';+import { getPlayCosmetics } from './game/play-handoff.js';import { getPresenceTicket, friendsClient } from './friends.js';import { FriendsPanel } from './game/friends-panel.js';import { PhysicsWorld } from './physics/physics-world.js';@@ -1019,6 +1021,19 @@ let avatarHeight = 1.8; // cached avatar height, updated on load/switchlet avatarTemplate = null;let animationDefs = null;+// The local avatar's equipped cosmetic loadout (R23), carried across worlds via+// the cc-cosmetics mirror. `applyLoadout` returns a handle we tick each frame+// (props re-glue to the head, the aura spins) and dispose before re-applying.+let localCosmetics = null;+let _localCosWire = null;+function applyLocalCosmetics(wire) {+ const next = typeof wire === 'string' ? wire : '';+ if (localCosmetics && _localCosWire === next) return;+ _localCosWire = next;+ try { localCosmetics?.dispose(); } catch { /* already gone */ }+ localCosmetics = applyLoadout(avatarRig, avatarHeight || 1.7, next);+}+async function loadAvatar() {setLoadingText('Resolving avatar...');const avatarUrl = await resolveAvatarUrl();@@ -1049,6 +1064,12 @@ async function loadAvatar() {avatarHeight = height;frameAvatarCamera();+ // Dress the local avatar in the loadout the player last equipped (R23). The+ // equipped fit is persisted to their account in /play and mirrored to the+ // cross-world cc-cosmetics store, so the same wardrobe rides into /walk. Reuses+ // the shared applyLoadout, so a hat or aura renders identically in both worlds.+ applyLocalCosmetics(getPlayCosmetics());+animationManager.attach(avatar);setLoadingText('Preparing animations...');@@ -1826,6 +1847,7 @@ function tick() {// 3. Tick the animation mixer.animationManager.update(dt);+ localCosmetics?.tick(dt);// 4. Broadcast our state to the server (throttled inside WalkNet) and// advance every remote player's interpolated transform + animation.diff --git a/tests/block-store-redis.test.js b/tests/block-store-redis.test.jsindex 560d42502..3d0978103 100644--- a/tests/block-store-redis.test.js+++ b/tests/block-store-redis.test.js@@ -54,11 +54,27 @@ describe('BlockStore (durable / Upstash)', () => {const b = await freshStore();await b.ready();const mapB = await b.load('Mint1111111111111111111111111111111111111111');- expect(mapB.get('0,0,0')).toBe(3);- expect(mapB.get('1,2,3')).toBe(9);+ // Reloaded cells are { t, o } records (the type round-trips; owner is '' here+ // since the build was written by a direct map mutation, not blockStore.set).+ expect(mapB.get('0,0,0').t).toBe(3);+ expect(mapB.get('1,2,3').t).toBe(9);expect(mapB.size).toBe(2);});+ it('round-trips block ownership across a simulated restart (R19)', async () => {+ const coin = 'MintOwner11111111111111111111111111111111111';+ const a = await freshStore();+ await a.ready();+ await a.load(coin);+ a.set(coin, '0,0,0', 4, 'wallet-bob');+ await a.flush(coin);++ const b = await freshStore();+ await b.ready();+ const map = await b.load(coin);+ expect(map.get('0,0,0')).toEqual({ t: 4, o: 'wallet-bob' });+ });+it('clearing a world to empty deletes its durable key', async () => {const a = await freshStore();await a.ready();diff --git a/tests/block-store.test.js b/tests/block-store.test.jsindex ac9f5acec..3e478adcc 100644--- a/tests/block-store.test.js+++ b/tests/block-store.test.js@@ -24,11 +24,12 @@ describe('BlockStore (memory-only)', () => {blockStore.set(coin, '1,0,0', 5);// A fresh load (e.g. the room disposed and was recreated) returns the SAME- // live map — the community's build is still there.+ // live map — the community's build is still there. Each cell is a { t, o }+ // record carrying the block type and the placer's id (R19 ownership).const second = await blockStore.load(coin);expect(second).toBe(first);- expect(second.get('0,0,0')).toBe(3);- expect(second.get('1,0,0')).toBe(5);+ expect(second.get('0,0,0').t).toBe(3);+ expect(second.get('1,0,0').t).toBe(5);expect(second.size).toBe(2);});@@ -51,6 +52,16 @@ describe('BlockStore (memory-only)', () => {expect(zMap.has('0,0,0')).toBe(false);});+ it('records the placer id alongside the block type (R19 ownership)', async () => {+ const coin = 'CoinOwnerEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE';+ await blockStore.load(coin);+ blockStore.set(coin, '4,0,4', 2, 'wallet-alice');+ blockStore.set(coin, '5,0,5', 7); // ownerless cell+ const map = await blockStore.load(coin);+ expect(map.get('4,0,4')).toEqual({ t: 2, o: 'wallet-alice' });+ expect(map.get('5,0,5')).toEqual({ t: 7, o: '' });+ });+it('set/delete on an unloaded coin is a safe no-op', () => {expect(() => blockStore.set('NeverLoadedCoin', '0,0,0', 1)).not.toThrow();expect(() => blockStore.delete('NeverLoadedCoin', '0,0,0')).not.toThrow();diff --git a/tests/build-hud.test.js b/tests/build-hud.test.jsindex b85a417c5..2d0087feb 100644--- a/tests/build-hud.test.js+++ b/tests/build-hud.test.js@@ -89,6 +89,47 @@ describe('build HUD', () => {expect(document.querySelectorAll('.cc-build-slot')[4].classList.contains('cc-on')).toBe(true);});+ it('per-player allowance meter hides without a cap and escalates with usage (R19)', () => {+ mount();+ const meter = document.querySelector('.cc-build-mine');+ const fill = document.querySelector('.cc-build-mine-fill');++ // Solo build (no cap) → meter stays hidden, never a phantom limit.+ hud.setUsage(0, 0);+ expect(meter.hidden).toBe(true);++ hud.setUsage(600, 1200); // half of the cap+ expect(meter.hidden).toBe(false);+ expect(fill.style.transform).toBe('scaleX(0.5)');+ expect(meter.classList.contains('cc-warn')).toBe(false);+ expect(document.querySelector('.cc-build-mine-text').textContent).toMatch(/600/);++ hud.setUsage(1100, 1200); // ≥80% → warn+ expect(meter.classList.contains('cc-warn')).toBe(true);++ hud.setUsage(1200, 1200); // at the cap → full+ expect(meter.classList.contains('cc-full')).toBe(true);+ expect(meter.classList.contains('cc-warn')).toBe(false);+ });++ it('creator moderation row is hidden until setCreator, and fires clear actions (R19)', () => {+ const scopes = [];+ mount({ onClearArea: (s) => scopes.push(s) });+ const row = document.querySelector('.cc-build-mod');+ expect(row.hidden).toBe(true); // ordinary builder never sees it++ hud.setCreator(true);+ expect(row.hidden).toBe(false);++ const [nearbyBtn, allBtn] = document.querySelectorAll('.cc-build-mod-btn');+ nearbyBtn.click();+ allBtn.click();+ expect(scopes).toEqual(['area', 'all']);++ hud.setCreator(false);+ expect(row.hidden).toBe(true);+ });+it('setEnabled disables the toggle and collapses an open panel', () => {const toggles = [];mount({ onToggle: (v) => toggles.push(v) });diff --git a/tests/cosmetics-purchase.test.js b/tests/cosmetics-purchase.test.jsnew file mode 100644index 000000000..0925e1825--- /dev/null+++ b/tests/cosmetics-purchase.test.js@@ -0,0 +1,173 @@+// Coverage for the R22 avatar-shop purchase lineage:+//+// • api/_lib/cosmetics.js — USDC pricing layer + catalog owned-merge+// • api/_lib/cosmetics-ownership.js — durable ownership ledger (fail-closed+// grant, graceful reads, idempotency)+// • api/x402/cosmetic-purchase.js — input validation + the 402 challenge+//+// The on-chain settlement itself needs a funded wallet + facilitator and is+// verified against the real rail on deploy; here we lock down the boundary+// behaviour that must hold regardless: server-owned pricing, honest validation,+// fail-closed ownership, and a correctly-priced 402.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ buildCatalog, getCosmetic, priceUsdcAtomicsOf, priceUsdcDisplayOf,+} from '../api/_lib/cosmetics.js';++describe('cosmetics USDC pricing', () => {+ afterEach(() => { delete process.env.X402_PRICE_COSMETIC_LEGENDARY; });++ it('prices premium items by rarity and frees the base pack', () => {+ expect(priceUsdcAtomicsOf(getCosmetic('skin-crimson'))).toBe('500000'); // rare $0.50+ expect(priceUsdcAtomicsOf(getCosmetic('skin-whiteout'))).toBe('1500000'); // epic $1.50+ expect(priceUsdcAtomicsOf(getCosmetic('skin-midnight'))).toBe('3000000'); // legendary $3.00+ expect(priceUsdcAtomicsOf(getCosmetic('hat-baseball'))).toBe('0'); // free base item+ expect(priceUsdcDisplayOf(getCosmetic('skin-midnight'))).toBe('3.00');+ });++ it('honours an env price override', () => {+ process.env.X402_PRICE_COSMETIC_LEGENDARY = '4200000';+ expect(priceUsdcAtomicsOf(getCosmetic('skin-midnight'))).toBe('4200000');+ });++ it('surfaces both the $THREE value and the USDC charge in the catalog', () => {+ const midnight = buildCatalog({}).find((c) => c.id === 'skin-midnight');+ expect(midnight.currency).toBe('THREE'); // coin-facing copy stays $THREE+ expect(midnight.price).toBe(750);+ expect(midnight.priceUsdc).toBe('3.00'); // USDC is the settlement asset+ expect(midnight.priceUsdcAtomics).toBe('3000000');+ expect(midnight.owned).toBe(false);+ });++ it('reads a purchased premium item as owned when merged in', () => {+ const owned = buildCatalog({ ownedIds: ['skin-midnight'] }).find((c) => c.id === 'skin-midnight');+ expect(owned.owned).toBe(true);+ expect(owned.locked).toBe(false);+ });+});++// ── ownership ledger ─────────────────────────────────────────────────────────+// A tiny in-memory stand-in for Upstash Redis so we can exercise the SET-backed+// ledger without a live instance.+class FakeRedis {+ constructor() { this.sets = new Map(); }+ async sadd(key, member) {+ const s = this.sets.get(key) || new Set();+ const had = s.has(member);+ s.add(member); this.sets.set(key, s);+ return had ? 0 : 1;+ }+ async smembers(key) { return [...(this.sets.get(key) || [])]; }+ async sismember(key, m) { return this.sets.get(key)?.has(m) ? 1 : 0; }+ async expire() { return 1; }+}++async function loadOwnership({ withRedis }) {+ vi.resetModules();+ if (withRedis) {+ process.env.UPSTASH_REDIS_REST_URL = 'https://fake.upstash.io';+ process.env.UPSTASH_REDIS_REST_TOKEN = 'fake-token';+ const fake = new FakeRedis();+ vi.doMock('@upstash/redis', () => ({ Redis: class { constructor() { return fake; } } }));+ } else {+ delete process.env.UPSTASH_REDIS_REST_URL;+ delete process.env.UPSTASH_REDIS_REST_TOKEN;+ delete process.env.three_KV_REST_API_URL;+ delete process.env.KV_REST_API_URL;+ vi.doMock('@upstash/redis', () => ({ Redis: class {} }));+ }+ return import('../api/_lib/cosmetics-ownership.js');+}++describe('cosmetics ownership ledger', () => {+ beforeEach(() => { vi.resetModules(); });+ afterEach(() => { vi.unmock('@upstash/redis'); vi.resetModules(); });++ it('normalizeAccountId accepts wallets + guest ids, rejects junk', async () => {+ const { normalizeAccountId } = await loadOwnership({ withRedis: false });+ expect(normalizeAccountId('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump'))+ .toBe('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');+ expect(normalizeAccountId('guest-ab12cd34')).toBe('guest-ab12cd34');+ expect(normalizeAccountId('a b/c')).toBe('');+ expect(normalizeAccountId('')).toBe('');+ expect(normalizeAccountId('x'.repeat(80))).toBe('');+ });++ it('grants idempotently and reads back when a store is configured', async () => {+ const lib = await loadOwnership({ withRedis: true });+ expect(lib.ownershipStoreConfigured()).toBe(true);+ expect(await lib.grantCosmeticOwnership('guest-1', 'skin-midnight')).toBe(true); // newly owned+ expect(await lib.grantCosmeticOwnership('guest-1', 'skin-midnight')).toBe(false); // idempotent+ expect(await lib.readOwnedCosmetics('guest-1')).toEqual(['skin-midnight']);+ expect(await lib.ownsCosmetic('guest-1', 'skin-midnight')).toBe(true);+ expect(await lib.ownsCosmetic('guest-1', 'skin-crimson')).toBe(false);+ });++ it('fails closed on grant and degrades gracefully on read with no store', async () => {+ const lib = await loadOwnership({ withRedis: false });+ expect(lib.ownershipStoreConfigured()).toBe(false);+ await expect(lib.grantCosmeticOwnership('guest-1', 'skin-midnight')).rejects.toMatchObject({+ status: 503, code: 'ownership_store_unavailable',+ });+ expect(await lib.readOwnedCosmetics('guest-1')).toEqual([]);+ expect(await lib.ownsCosmetic('guest-1', 'skin-midnight')).toBe(false);+ });+});++// ── purchase endpoint boundary ───────────────────────────────────────────────+function mockReq(query) {+ return {+ method: 'GET',+ url: '/api/x402/cosmetic-purchase?' + new URLSearchParams(query).toString(),+ query,+ headers: {},+ };+}++function mockRes() {+ const res = { statusCode: 0, body: '', headers: {} };+ res.setHeader = (k, v) => { res.headers[k.toLowerCase()] = v; };+ res.getHeader = (k) => res.headers[k.toLowerCase()];+ res.status = (s) => { res.statusCode = s; return res; };+ res.end = (b) => { res.body = b || ''; res.writableEnded = true; };+ return res;+}++async function call(query) {+ const { default: handler } = await import('../api/x402/cosmetic-purchase.js');+ const req = mockReq(query);+ const res = mockRes();+ await handler(req, res);+ let parsed; try { parsed = JSON.parse(res.body); } catch { parsed = res.body; }+ return { status: res.statusCode, parsed };+}++describe('cosmetic-purchase endpoint boundary', () => {+ beforeEach(() => {+ // Minimal x402 config so the 402 challenge can build a Solana accept.+ process.env.X402_PAY_TO_SOLANA = 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';+ process.env.X402_ASSET_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+ });++ it('rejects missing id / account', async () => {+ expect((await call({ account: 'guest-1' })).status).toBe(400);+ expect((await call({ id: 'skin-midnight' })).status).toBe(400);+ });++ it('404s an unknown cosmetic and 400s a free base item', async () => {+ expect((await call({ id: 'nope', account: 'guest-1' })).status).toBe(404);+ const free = await call({ id: 'hat-baseball', account: 'guest-1' });+ expect(free.status).toBe(400);+ expect(free.parsed.code).toBe('not_purchasable');+ });++ it('issues a 402 priced in USDC for a premium cosmetic', async () => {+ const r = await call({ id: 'skin-midnight', account: 'guest-1' });+ expect(r.status).toBe(402);+ const sol = (r.parsed.accepts || []).find((a) => String(a.network).startsWith('solana'));+ expect(sol).toBeTruthy();+ expect(sol.amount).toBe('3000000'); // $3.00 USDC, server-owned price+ expect(sol.asset).toBe('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v');+ });+});diff --git a/tests/e2e/galaxy.spec.js b/tests/e2e/galaxy.spec.jsindex 66ad377c0..826c9ee9b 100644--- a/tests/e2e/galaxy.spec.js+++ b/tests/e2e/galaxy.spec.js@@ -189,8 +189,8 @@ test.describe('IBM Agent Galaxy', () => {await gotoGalaxy(page, { mode: 'unavailable', expectState: 'unavailable' });await expect(page.locator('#unavailableState')).toBeVisible();await expect(page.locator('#unavailableState h2')).toContainText('not configured');- // The /ibm link is present so users know what to do.- await expect(page.locator('#unavailableState a[href="/ibm"]')).toBeVisible();+ // The IBM demos link is present so users know what to do.+ await expect(page.locator('#unavailableState a[href="/ibm/galaxy"]')).toBeVisible();});// ── State: no agents ────────────────────────────────────────────────────diff --git a/tests/walkroom-build-perms.test.js b/tests/walkroom-build-perms.test.jsnew file mode 100644index 000000000..c85db847a--- /dev/null+++ b/tests/walkroom-build-perms.test.js@@ -0,0 +1,124 @@+// R19 — build netcode hardening: ownership, per-player + density caps, protected+// zones, and creator moderation. The full WalkRoom needs the Colyseus runtime, so+// these tests drive the pure permission helpers directly against a minimal stand-in+// (Object.create avoids the Room constructor). They lock the server-authoritative+// invariants a malicious client must not be able to break.++import { describe, it, expect, beforeEach } from 'vitest';+import { WalkRoom } from '../multiplayer/src/rooms/WalkRoom.js';++// Build a WalkRoom instance without the Colyseus constructor, wiring only the state+// the permission helpers touch.+function makeRoom({ creator = '' } = {}) {+ const room = Object.create(WalkRoom.prototype);+ room.blockOwners = new Map();+ room.blockCounts = new Map();+ room.columnCounts = new Map();+ room.coinCreator = creator;+ room.econ = new Map();+ room.state = { players: new Map() };+ return room;+}++// Register a seated player with a stable owner id and (optionally) a verified wallet.+function seat(room, sessionId, { playerId = sessionId, account = '' } = {}) {+ room.econ.set(sessionId, { playerId });+ room.state.players.set(sessionId, { account });+ return { sessionId };+}++describe('WalkRoom build permissions (R19)', () => {+ let room;+ beforeEach(() => { room = makeRoom(); });++ it('protects the spawn and totem columns at every height', () => {+ expect(room._isProtectedColumn(0, 0)).toBe(true); // spawn+ expect(room._isProtectedColumn(0, -8)).toBe(true); // totem (world z=-12 → grid -8)+ expect(room._isProtectedColumn(2, -1)).toBe(true); // within the spawn disc+ expect(room._isProtectedColumn(15, 15)).toBe(false); // open plaza+ });++ it('refuses placement in a protected column', () => {+ seat(room, 's1');+ const owner = room._ownerKey('s1');+ expect(room._placementBlock(owner, 0, 0)).toBe('protected');+ expect(room._placementBlock(owner, 20, 20)).toBe(null);+ });++ it('enforces the per-player ownership cap', () => {+ seat(room, 's1');+ const owner = room._ownerKey('s1');+ room.blockCounts.set(owner, 1200); // at the cap+ expect(room._placementBlock(owner, 20, 20)).toBe('playercap');+ room.blockCounts.set(owner, 1199);+ expect(room._placementBlock(owner, 20, 20)).toBe(null);+ });++ it('enforces the per-column density cap (anti-wall)', () => {+ seat(room, 's1');+ const owner = room._ownerKey('s1');+ room.columnCounts.set('20,20', 14); // at the column cap+ expect(room._placementBlock(owner, 20, 20)).toBe('dense');+ room.columnCounts.set('20,20', 13);+ expect(room._placementBlock(owner, 20, 20)).toBe(null);+ });++ it('accounts for in-batch additions so a composite stamp cannot straddle a cap', () => {+ seat(room, 's1');+ const owner = room._ownerKey('s1');+ room.columnCounts.set('20,20', 13); // one slot left in the column+ // First cell of the batch is allowed; the second (extraColumn=1) trips 'dense'.+ expect(room._placementBlock(owner, 20, 20, 0, 0)).toBe(null);+ expect(room._placementBlock(owner, 20, 20, 0, 1)).toBe('dense');+ });++ it('lets only the placer (or the creator) modify a piece', () => {+ const alice = seat(room, 'sA', { playerId: 'alice' });+ const bob = seat(room, 'sB', { playerId: 'bob' });+ room._trackPlacement('20,0,20', 'alice');++ expect(room._mayModify(alice, '20,0,20')).toBe(true); // owner+ expect(room._mayModify(bob, '20,0,20')).toBe(false); // stranger — denied+ });++ it('treats an ownerless (restored) cell as creator-only', () => {+ const bob = seat(room, 'sB', { playerId: 'bob' });+ room._trackPlacement('20,0,20', ''); // legacy / pre-ownership restore+ expect(room._mayModify(bob, '20,0,20')).toBe(false);+ });++ it('grants the verified coin creator world-wide modify rights', () => {+ room = makeRoom({ creator: 'CREATORWALLET' });+ const creator = seat(room, 'sC', { playerId: 'cc', account: 'CREATORWALLET' });+ const someone = seat(room, 'sX', { playerId: 'xx', account: 'OTHERWALLET' });+ room._trackPlacement('20,0,20', 'yy'); // a third party's block — not someone's++ expect(room._isCreator(creator)).toBe(true);+ expect(room._isCreator(someone)).toBe(false);+ expect(room._mayModify(creator, '20,0,20')).toBe(true); // creator moderates+ expect(room._mayModify(someone, '20,0,20')).toBe(false);+ });++ it('a spoofed account cannot impersonate the creator', () => {+ room = makeRoom({ creator: 'CREATORWALLET' });+ // A player whose verified account is NOT the creator wallet — even if a client+ // claimed otherwise, the server reads the bound account, so this is false.+ const faker = seat(room, 'sF', { playerId: 'ff', account: '' });+ expect(room._isCreator(faker)).toBe(false);+ });++ it('keeps owner + column tallies consistent across place and remove', () => {+ room._trackPlacement('3,0,3', 'alice');+ room._trackPlacement('3,1,3', 'alice'); // same column, stacked+ expect(room.blockCounts.get('alice')).toBe(2);+ expect(room.columnCounts.get('3,3')).toBe(2);++ room._untrackPlacement('3,1,3', 'alice', 3, 3);+ expect(room.blockCounts.get('alice')).toBe(1);+ expect(room.columnCounts.get('3,3')).toBe(1);++ room._untrackPlacement('3,0,3', 'alice', 3, 3);+ expect(room.blockCounts.has('alice')).toBe(false); // last one removed → key dropped+ expect(room.columnCounts.has('3,3')).toBe(false);+ });+});diff --git a/vercel.json b/vercel.jsonindex fb57f0cff..c99968288 100644--- a/vercel.json+++ b/vercel.json@@ -179,11 +179,13 @@},{"src": "/ibm",- "dest": "/ibm/index.html"+ "status": 308,+ "headers": { "Location": "/ibm/galaxy" }},{"src": "/ibm/",- "dest": "/ibm/index.html"+ "status": 308,+ "headers": { "Location": "/ibm/galaxy" }},{"src": "/rss/announcements\\.xml",diff --git a/vite.config.js b/vite.config.jsindex dc20535be..5c26e03a0 100644--- a/vite.config.js+++ b/vite.config.js@@ -374,7 +374,6 @@ const appConfig = {'aws-marketplace-welcome': resolve(__dirname, 'pages/aws-marketplace/welcome.html'),'aws': resolve(__dirname, 'pages/aws/index.html'),'agent-trade': resolve(__dirname, 'pages/agent-trade.html'),- 'ibm': resolve(__dirname, 'pages/ibm/index.html'),'ibm-galaxy': resolve(__dirname, 'pages/ibm/galaxy.html'),'ibm-trust-layer': resolve(__dirname, 'pages/ibm/trust-layer.html'),'ibm-oracle': resolve(__dirname, 'pages/ibm/oracle.html'),@@ -609,8 +608,8 @@ const appConfig = {'/aws-marketplace/error/': resolve(root, 'pages/aws-marketplace/welcome.html'),'/aws': resolve(root, 'pages/aws/index.html'),'/aws/': resolve(root, 'pages/aws/index.html'),- '/ibm': resolve(root, 'pages/ibm/index.html'),- '/ibm/': resolve(root, 'pages/ibm/index.html'),+ '/ibm': resolve(root, 'pages/ibm/galaxy.html'),+ '/ibm/': resolve(root, 'pages/ibm/galaxy.html'),'/ibm/galaxy': resolve(root, 'pages/ibm/galaxy.html'),'/ibm/galaxy/': resolve(root, 'pages/ibm/galaxy.html'),'/ibm/trust-layer': resolve(root, 'pages/ibm/trust-layer.html'),