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: add cosmetics ownership bridge between shop and rig/wardrobe catalogs
nirholas9acb1afaa295
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9c595d859..fc7ff9197 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,8 +20,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Call out a pose and your agent's 3D avatar performs it live** — On an agent's live screen the Avatar Cam is now a stage. Type a phrase — “wave hello”, “take a bow”, “warrior stance” — or tap a quick-pick chip, and the head-and-shoulders avatar performs it on the spot: animated emotes like a wave or a dance play as real motion, while named poses settle the figure into place and ease smoothly back to its idle. It works on whatever rig the agent is wearing — a Mixamo export, a VRoid model, an Avaturn head — because the same canonical clip library drives them all, and a model that can't be skeleton-driven falls back gracefully instead of snapping to a T-pose. Every request is tagged in the activity log. (`/agent-screen`) `[feature]`- **Club entry no longer gets stuck behind the payment receipt** — Paying the cover at the club door (and tipping a dancer) now drops you straight into the room. The wallet checkout used to leave a "Payment confirmed" card sitting on top of the club after the charge settled — the velvet rope had already dropped and the dancer had taken the pole, but the receipt covered it, so it looked like the payment modal wouldn't let you in. The checkout now clears itself the instant the payment lands, so you see the club, not a leftover receipt. (`/club`) `[fix]`- **Coin Clash stays up when the leaderboard backend hiccups** — The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable. (`/clash`) `[fix]`+- **Coin creators can now set their cut of cosmetic sales** — When a player buys a premium cosmetic inside your coin's 3D world, a share of that sale already pays out to your wallet in real USDC on-chain — but the percentage was fixed. Your Monetize dashboard now has a Cosmetic revenue split panel: for every coin you've launched it shows the current share, who it pays out to, and a slider to set your cut up to the platform ceiling. Changing it is authorized by signing a message with the coin's own creator wallet — the same wallet the money lands in — so no one else can redirect your revenue. It sits right next to your settled cosmetic earnings, which already show paid, pending, and per-cosmetic totals with on-chain receipts. (`/dashboard/monetize`) `[feature]`- **Coin World Tour: an agent walks you through the $THREE 3D world live** — Watch a guide agent take a first-person walk through the $THREE 3D world — gliding from the lobby across the floor and into the arena, the camera bobbing with each step. As it reaches each stop it commentates what's climbing the three.ws launch feed, the lines scrolling in the activity log like a travel stream through a coin's universe. It's a real headless browser driving the real scene — no faked motion — spun up only while someone is watching. Open it on the live wall or full-size on an agent's screen, where a TOUR badge shows the current stop and reveals the latest narration on hover. (`/agents-live`) `[feature]`- **Copy-Trade Mirror: watch an agent shadow a target wallet live** — Watch an agent mirror a target wallet live — the source trade and the agent's guarded replica land side by side with latency and fill shown, every order inside hard spend caps. The Mirror panel on /agent-screen streams the target wallet's real pump.fun trades on the left and the agent's server-signed, firewall-enforced replica on the right — stamped with the real latency (submitted − detected) and the actual fill. Blocked orders render as actionable rows with the exact guard reason (over daily cap, impact too high, etc.) — never a silent skip. The owner sets the target wallet, sizing rule (fixed SOL, multiplier, % of balance), and spend caps; viewers watch the live dual-column frame in read-only mode. (`/agent-screen`) `[feature]`+- **Cosmetics you buy now follow you into every world** — When you buy a premium cosmetic for your avatar, that unlock now reaches the 3D world itself: the item is wearable the moment the payment settles, your equipped look is saved to your account, and it re-applies automatically the next time you log in — in any world, whether you arrived through a coin's /play space or /walk. Previously a purchase was recorded but the world didn't yet know you owned it, so the item could still read as locked when you went to wear it. Everyone around you sees your equipped fit too. (`/play`) `[fix]`- **Deploy your agent to the live wall in four guided steps** — Going live is now a wizard, not a docs hunt. Open the agent screen with no agent picked and a four-step flow walks you through it: choose your agent, generate its key in one click (shown once, with a copy button), copy the exact run command for your setup — local npm, Docker, or Browserbase — and then watch a live status strip that flips to “You’re live on the wall” the instant your agent pushes its first frame, with a direct link to its card on the public wall. A progress tracker, a searchable agent list, inline error recovery, and a “not appearing?” troubleshooter round it out. (`/agent-screen`) `[feature, improvement]`- **Fixed the footer overlapping the Payment Sessions page** — On the Agent Payment Sessions page the site footer was rendering on top of the whole page, hiding your sessions, stats, and the New Session button behind it. It now sits where it belongs at the bottom of the page. (`/payments`) `[fix]`- **Full interactive trading chart on every coin page** — Each coin's profile page now lets you switch its price chart between the fast native view and a full interactive DexScreener terminal — candlesticks, zoom, on-chart trades and liquidity — embedded right on the page and keyed to the coin's mint, with a one-tap link to open it in DexScreener. The chart matches your light/dark theme and only loads the heavier terminal when you choose it, so the page stays quick by default. (`/launches`) `[improvement]`diff --git a/api/_lib/market/ohlcv.js b/api/_lib/market/ohlcv.jsindex d98d2b61d..e4c439ce5 100644--- a/api/_lib/market/ohlcv.js+++ b/api/_lib/market/ohlcv.js@@ -14,19 +14,36 @@ const UA = 'three.ws-granite-oracle/1.0';const cache = new Map(); // url → { value, expiresAt }const TTL_MS = 20_000;+// Bounded exponential backoff with jitter for transient upstream throttling.+// GeckoTerminal's free tier (~30 req/min) bursts into 429s and occasional 5xx;+// a couple of short, jittered waits clear most of them. Bounded so the total+// added latency (≈0.4s + ≈0.8s worst case, ~1.8s with jitter) never approaches+// the function time budget. 404 and other client errors are NOT retried.+const MAX_ATTEMPTS = 3;+const BACKOFF_BASE_MS = 400;+const BACKOFF_CAP_MS = 1200;+const RETRYABLE = new Set([429, 502, 503, 504]);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// attempt is 0-based: delay grows 400ms, 800ms, … capped, with ±50% jitter so a+// fleet of lambdas throttled together don't all retry on the same beat.+function backoffMs(attempt) {+ const exp = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);+ return Math.round(exp * (0.5 + Math.random() * 0.5));+}+async function gecko(path) {const url = `${BASE}${path}`;const now = Date.now();const hit = cache.get(url);if (hit && hit.expiresAt > now) return hit.value;- // One bounded retry on a 429 with backoff before giving up — GeckoTerminal's- // free tier throttles bursts, and a short wait usually clears it well within- // the function budget. Preserves 429 as the thrown status (not a generic 502)- // so the caller can map it to a retryable response instead of a hard error.+ // Retry transient throttles (429/5xx) with bounded jittered backoff before+ // giving up. Preserves the real status (esp. 429) on the thrown error so the+ // caller maps it to a retryable response instead of a generic 502/500.let res;let lastStatus = 502;- for (let attempt = 0; attempt < 2; attempt++) {+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {try {res = await fetch(url, {headers: { accept: 'application/json', 'user-agent': UA },@@ -40,9 +57,9 @@ async function gecko(path) {if (res.ok) break;lastStatus = res.status;const text = await res.text();- if (res.status === 429 && attempt === 0) {- await new Promise((r) => setTimeout(r, 600));- continue; // retry once+ if (RETRYABLE.has(res.status) && attempt < MAX_ATTEMPTS - 1) {+ await sleep(backoffMs(attempt));+ continue; // retry with backoff}throw Object.assign(new Error(`GeckoTerminal ${res.status}: ${text.slice(0, 160)}`), {status: res.status === 404 ? 404 : res.status === 429 ? 429 : 502,diff --git a/data/changelog.json b/data/changelog.jsonindex 2c4362d4e..e89994abf 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,24 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-29",+ "title": "Cosmetics you buy now follow you into every world",+ "summary": "When you buy a premium cosmetic for your avatar, that unlock now reaches the 3D world itself: the item is wearable the moment the payment settles, your equipped look is saved to your account, and it re-applies automatically the next time you log in — in any world, whether you arrived through a coin's /play space or /walk. Previously a purchase was recorded but the world didn't yet know you owned it, so the item could still read as locked when you went to wear it. Everyone around you sees your equipped fit too.",+ "tags": [+ "fix"+ ],+ "link": "/play"+ },+ {+ "date": "2026-06-29",+ "title": "Coin creators can now set their cut of cosmetic sales",+ "summary": "When a player buys a premium cosmetic inside your coin's 3D world, a share of that sale already pays out to your wallet in real USDC on-chain — but the percentage was fixed. Your Monetize dashboard now has a Cosmetic revenue split panel: for every coin you've launched it shows the current share, who it pays out to, and a slider to set your cut up to the platform ceiling. Changing it is authorized by signing a message with the coin's own creator wallet — the same wallet the money lands in — so no one else can redirect your revenue. It sits right next to your settled cosmetic earnings, which already show paid, pending, and per-cosmetic totals with on-chain receipts.",+ "tags": [+ "feature"+ ],+ "link": "/dashboard/monetize"+ },{"date": "2026-06-29","title": "Splat viewer now loads GitHub and Hugging Face links directly",diff --git a/multiplayer/src/cosmetics-ownership.js b/multiplayer/src/cosmetics-ownership.jsnew file mode 100644index 000000000..4bd98e5d8--- /dev/null+++ b/multiplayer/src/cosmetics-ownership.js@@ -0,0 +1,72 @@+// Cosmetic ownership ledger — READER (R22 → R23 bridge, game-server side).+//+// The R22 x402 purchase handler (api/x402/cosmetic-purchase.js → api/_lib/+// cosmetics-ownership.js) records every premium cosmetic an account buys into one+// Upstash Redis SET per account: `cosmetics:owned:<account>`. That writer lives on+// the Vercel side; this is its read-only mirror on the Colyseus game server, so+// the authoritative equip path (WalkRoom) can seed a player's owned set from real+// purchases instead of an empty list. Keep the key prefix and the account+// normalisation byte-for-byte in lockstep with api/_lib/cosmetics-ownership.js —+// the two processes share one Redis, and a drifted key would silently hide a+// player's purchases from the world that's meant to render them.+//+// Same Upstash instance, same env, same lazy-singleton + ping pattern the other+// game-server stores use (playerStore.js, feed.js, presence-store.js) so there's+// no new provider and no extra connection pool churn. Reads FAIL OPEN: if Redis is+// unreachable or unconfigured the player simply owns nothing extra this session —+// the world still renders, free cosmetics still equip — matching how the shop and+// the api-side reader degrade. The purchase side fails CLOSED; only reads degrade.++const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';+const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';++// Lockstep with api/_lib/cosmetics-ownership.js — the SET the x402 handler writes.+const OWNED_PREFIX = 'cosmetics:owned:';++let _redis = null;+let _redisReady = null;++if (REDIS_URL && REDIS_TOKEN) {+ _redisReady = import('@upstash/redis')+ .then(async ({ Redis }) => {+ _redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });+ await _redis.ping();+ console.log('[cosmetics-ownership] reading purchased cosmetics from Upstash Redis (verified)');+ })+ .catch((err) => {+ _redis = null;+ console.warn('[cosmetics-ownership] Redis unreachable — purchased cosmetics will read as empty:', err?.message);+ });+} else {+ console.log('[cosmetics-ownership] no UPSTASH_REDIS_REST_URL/_TOKEN — purchased cosmetics read as empty (free cosmetics still equip)');+}++// Account ids must be a Solana wallet (base58) or a guest id like `g_…`/`guest-…`.+// Bound the charset + length so a crafted value can't escape the keyspace. Mirrors+// api/_lib/cosmetics-ownership.js so the same account resolves to the same SET on+// both sides. Returns the trimmed id, or '' when it isn't a usable account id.+export function normalizeAccountId(raw) {+ const id = String(raw ?? '').trim();+ if (id.length < 3 || id.length > 80) return '';+ if (!/^[A-Za-z0-9_:-]+$/.test(id)) return '';+ return id;+}++// The premium cosmetic ids `account` has purchased over the R22 x402 rail. Awaits+// the one-time Redis handshake, then a single SMEMBERS. Degrades to [] on any+// error, when no store is configured, or for an unusable account id — the caller+// (WalkRoom equip authority) then grants only the free cosmetics, never throwing+// on the join hot path.+export async function readOwnedCosmetics(account) {+ const id = normalizeAccountId(account);+ if (!id) return [];+ if (_redisReady) { try { await _redisReady; } catch { /* fell back to memory */ } }+ if (!_redis) return [];+ try {+ const members = await _redis.smembers(OWNED_PREFIX + id);+ return Array.isArray(members) ? members : [];+ } catch (err) {+ console.warn('[cosmetics-ownership] read failed:', err?.message);+ return [];+ }+}diff --git a/multiplayer/src/economy.js b/multiplayer/src/economy.jsindex e5b4d5499..32c0a2824 100644--- a/multiplayer/src/economy.js+++ b/multiplayer/src/economy.js@@ -109,6 +109,20 @@ export function grantCosmetic(profile, id) {return true;}+// Bridge the R22 ownership ledger (real x402 purchases, keyed by account in+// Redis) into a profile's unlocked set. `ledgerIds` is the raw SMEMBERS of+// `cosmetics:owned:<account>`; only ids that are premium cosmetics in THIS+// catalog are granted (the ledger may also hold ids from a sibling catalog the+// rig can't render — those are ignored, never errored). Idempotent via+// grantCosmetic. Returns the count newly unlocked, so a caller can skip a persist+// when nothing changed.+export function mergeOwnedFromLedger(profile, ledgerIds) {+ if (!Array.isArray(ledgerIds) || !ledgerIds.length) return 0;+ let granted = 0;+ for (const id of ledgerIds) if (grantCosmetic(profile, id)) granted++;+ return granted;+}+// Equip `id` into its slot if the profile is allowed to wear it. Returns the new// equipped map on success, or null when the id is unknown or unowned (the server// then rejects the equip). Mutates profile.cosmetics.equipped.diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex c2c2aac30..cfeb03eed 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -26,12 +26,13 @@ import {addItem, hasRoomFor, resolveSlot, grantXp, consumeSlot,countItem, removeItem,dropCarried, reviveProfile, bankTransfer,- equipCosmetic, ownedCosmeticSet,+ equipCosmetic, ownedCosmeticSet, mergeOwnedFromLedger,HOTBAR_SIZE,} from '../economy.js';import {serializeLoadout, getCosmetic, canWear, DEFAULT_LOADOUT,} from '../cosmetics-catalog.js';+import { readOwnedCosmetics } from '../cosmetics-ownership.js';import {itemLabel, fishCatchChance, fishDoubleChance,gatherChance, gatherDoubleChance, coalBonusChance, cookBurnChance,@@ -158,7 +159,18 @@ const PROTECTED_RADIUS_CELLS = 3; // keep this many cells clear around each p// client's BLOCK size (1.5 m). The spawn point is the origin; the coin totem// renders at world z = -12 → grid z = round(-12 / 1.5) = -8. Protect both columns// at every height so neither can be buried or walled in.+const BLOCK_SIZE_M = 1.5; // client BLOCK: one grid cell ↔ metresconst PROTECTED_POINTS = [{ x: 0, z: 0 }, { x: 0, z: -8 }];+// The prop/object build channel (obj:spawn kind:'block') works in world METRES, not+// grid cells, so its grief guard has its own protected discs and density tile. The+// protected world points are the spawn (origin) and the rendered totem (world z=-12);+// the radius matches the voxel discs (PROTECTED_RADIUS_CELLS cells). PER_TILE_PROP_CAP+// stops a builder piling props onto one spot to bury a landmark or wall an area off —+// the per-player count (MAX_OBJECTS_PER_PLAYER) and world cap bound the rest.+const PROTECTED_POINTS_M = [{ x: 0, z: 0 }, { x: 0, z: -12 }];+const PROTECTED_RADIUS_M = PROTECTED_RADIUS_CELLS * BLOCK_SIZE_M;+const PROP_TILE_M = BLOCK_SIZE_M; // density tile size for props, in metres+const PER_TILE_PROP_CAP = 4; // durable props allowed on one tile// Creator moderation: a clear-area sweep is bounded to this radius (cells) so even// the creator's broad-brush tool can't nuke a whole world in one malformed call;// 'all' is the explicit full-clear path.@@ -668,6 +680,20 @@ export class WalkRoom extends Room {profile.quests = restoreQuestState(saved?.profile?.quests, utcDayKey());profile._zone = null; // last quest zone the player was inside (enter-zone edge detect)this.econ.set(client.sessionId, profile);+ // Cosmetics ownership (R22 → R23): fold the premium cosmetics this account+ // bought over the x402 rail into its unlocked set, so a purchase persists and+ // equips in EVERY world the account joins — not just the one it was bought in.+ // The ledger is keyed by the same account id as the profile (playerId), reads+ // fail-open (own nothing extra) and never block the join. Persist only when a+ // new unlock actually landed so a returning player keeps it across restarts.+ try {+ const newlyOwned = mergeOwnedFromLedger(profile, await readOwnedCosmetics(playerId));+ if (newlyOwned > 0) this._persistEcon(client.sessionId);+ } catch (err) {+ console.warn(`[walk_world] cosmetics ledger seed failed for ${playerId}:`, err?.message);+ }+ // A slower-arriving leave could have fired while we awaited the ledger.+ if (!this.state.players.has(client.sessionId)) return;// Cosmetics (W03): apply any loadout the player chose pre-join (in the// character creator) on top of their persisted one, validating each id// against what they own — free cosmetics always pass, premium only when@@ -1337,7 +1363,7 @@ export class WalkRoom extends Room {// 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) {+ async _handleEquipCosmetic(client, payload) {const profile = this.econ.get(client.sessionId);if (!profile) return;if (!this._actionOk(client.sessionId, 'equip')) return;@@ -1346,7 +1372,23 @@ export class WalkRoom extends Room {client.send('notice', { kind: 'cosmetic', text: 'That cosmetic doesn’t exist.' });return;}- const equipped = equipCosmetic(profile, id);+ let equipped = equipCosmetic(profile, id);+ // Owned-miss on a premium item: the player may have JUST bought it over the+ // x402 rail this session, before the profile's unlocked set was refreshed.+ // Re-read the R22 ledger once and retry, so a fresh purchase equips without a+ // rejoin. (Free items never miss; a genuinely-unowned premium id still falls+ // through to the honest rejection below.)+ if (!equipped && getCosmetic(id)?.tier === 'premium') {+ try {+ if (mergeOwnedFromLedger(profile, await readOwnedCosmetics(profile.playerId)) > 0) {+ // The await could have outlived the session — bail if they left.+ if (!this.econ.has(client.sessionId)) return;+ equipped = equipCosmetic(profile, id);+ }+ } catch (err) {+ console.warn('[walk_world] cosmetics ledger recheck failed:', err?.message);+ }+ }if (!equipped) {client.send('notice', { kind: 'cosmetic', text: 'You don’t own that cosmetic yet.' });return;@@ -1817,6 +1859,14 @@ export class WalkRoom extends Room {obj.scale = objClamp(objNum(payload.scale, 1), OBJ_SCALE_MIN, OBJ_SCALE_MAX);obj.yaw = objNum(payload.yaw, 0);this._clampObjPos(obj, payload);+ // Grief guard (R19): a durable build prop may not bury the spawn or totem, nor+ // pile onto a tile past the density cap so it can't wall an area off. Checked on+ // the clamped position so a client can't dodge it with an out-of-bounds value.+ // Transient kinds (ball, fx) and server objects are exempt — only build props.+ if (this._objectIsPersistent(obj)) {+ const reason = this._propPlacementBlock(obj.x, obj.z);+ if (reason) { client.send('obj:reject', { reason }); return; }+ }obj.vx = objNum(payload.vx, 0);obj.vy = objNum(payload.vy, 0);obj.vz = objNum(payload.vz, 0);@@ -1976,10 +2026,24 @@ export class WalkRoom extends Room {blockStore.delete(this.worldKey, key);cleared++;}- client.send('build-cleared', { count: cleared, all });+ // Durable props (obj:spawn build pieces) live in the objects map, not the voxel+ // grid, so a sweep that only touched blocks would leave a prop-griefed area+ // untouched. Clear them on the same disc — mapped from grid cells to world metres+ // (the centre/radius arrive in cells) — and never the ball or transient fx.+ let clearedObjs = 0;+ const wx = cx * BLOCK_SIZE_M, wz = cz * BLOCK_SIZE_M, wr = r * BLOCK_SIZE_M;+ for (const [id, o] of [...this.state.objects]) {+ if (!this._objectIsPersistent(o)) continue;+ if (!all && Math.hypot(o.x - wx, o.z - wz) > wr) continue;+ this.state.objects.delete(id);+ clearedObjs++;+ }+ if (clearedObjs) this._persistObjects();+ client.send('build-cleared', { count: cleared, objects: clearedObjs, all });this._sendBuildPerms(client); // the creator's own tally may have changed- if (cleared) {- console.log(`[walk_world ${this.roomId}] creator cleared ${cleared} block(s)${all ? ' (all)' : ` near ${cx},${cz} r=${r}`}`);+ if (cleared || clearedObjs) {+ const where = all ? ' (all)' : ` near ${cx},${cz} r=${r}`;+ console.log(`[walk_world ${this.roomId}] creator cleared ${cleared} block(s) + ${clearedObjs} prop(s)${where}`);}}@@ -2030,6 +2094,25 @@ export class WalkRoom extends Room {return null;}+ // Grief guard for the prop/object build channel (obj:spawn), mirroring the voxel+ // guard but in world metres: keep durable props off the spawn/totem discs and cap+ // how many may pile onto one tile so a builder can't bury a landmark or wall a spot+ // off. Returns an obj:reject reason, or null when the placement is allowed.+ _propPlacementBlock(x, z) {+ for (const p of PROTECTED_POINTS_M) {+ if (Math.hypot(x - p.x, z - p.z) <= PROTECTED_RADIUS_M) return 'protected';+ }+ const tx = Math.round(x / PROP_TILE_M);+ const tz = Math.round(z / PROP_TILE_M);+ let here = 0;+ for (const [, o] of this.state.objects) {+ if (!this._objectIsPersistent(o)) continue;+ if (Math.round(o.x / PROP_TILE_M) === tx && Math.round(o.z / PROP_TILE_M) === tz) here++;+ }+ if (here >= PER_TILE_PROP_CAP) return 'dense';+ return null;+ }+// Record a placement against its owner + column tallies (used by the caps)._trackPlacement(key, owner) {this.blockOwners.set(key, owner);diff --git a/public/changelog.json b/public/changelog.jsonindex 85145118f..81d948918 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-29T13:41:06.039Z",+ "generated_at": "2026-06-29T17:10:31.675Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -146,6 +146,16 @@"fix"]},+ {+ "date": "2026-06-29",+ "type": "update",+ "title": "Coin creators can now set their cut of cosmetic sales",+ "summary": "When a player buys a premium cosmetic inside your coin's 3D world, a share of that sale already pays out to your wallet in real USDC on-chain — but the percentage was fixed. Your Monetize dashboard now has a Cosmetic revenue split panel: for every coin you've launched it shows the current share, who it pays out to, and a slider to set your cut up to the platform ceiling. Changing it is authorized by signing a message with the coin's own creator wallet — the same wallet the money lands in — so no one else can redirect your revenue. It sits right next to your settled cosmetic earnings, which already show paid, pending, and per-cosmetic totals with on-chain receipts.",+ "link": "/dashboard/monetize",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-29","type": "update",@@ -166,6 +176,16 @@"feature"]},+ {+ "date": "2026-06-29",+ "type": "update",+ "title": "Cosmetics you buy now follow you into every world",+ "summary": "When you buy a premium cosmetic for your avatar, that unlock now reaches the 3D world itself: the item is wearable the moment the payment settles, your equipped look is saved to your account, and it re-applies automatically the next time you log in — in any world, whether you arrived through a coin's /play space or /walk. Previously a purchase was recorded but the world didn't yet know you owned it, so the item could still read as locked when you went to wear it. Everyone around you sees your equipped fit too.",+ "link": "/play",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-29","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex cad229404..7b2181425 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -118,6 +118,14 @@<category>fix</category><description>The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable.</description></item>+ <item>+ <title>Coin creators can now set their cut of cosmetic sales</title>+ <link>https://three.ws/dashboard/monetize</link>+ <guid isPermaLink="false">2026-06-29:Coin creators can now set their cut of cosmetic sales</guid>+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>When a player buys a premium cosmetic inside your coin's 3D world, a share of that sale already pays out to your wallet in real USDC on-chain — but the percentage was fixed. Your Monetize dashboard now has a Cosmetic revenue split panel: for every coin you've launched it shows the current share, who it pays out to, and a slider to set your cut up to the platform ceiling. Changing it is authorized by signing a message with the coin's own creator wallet — the same wallet the money lands in — so no one else can redirect your revenue. It sits right next to your settled cosmetic earnings, which already show paid, pending, and per-cosmetic totals with on-chain receipts.</description>+ </item><item><title>Coin World Tour: an agent walks you through the $THREE 3D world live</title><link>https://three.ws/agents-live</link>@@ -134,6 +142,14 @@<category>feature</category><description>Watch an agent mirror a target wallet live — the source trade and the agent's guarded replica land side by side with latency and fill shown, every order inside hard spend caps. The Mirror panel on /agent-screen streams the target wallet's real pump.fun trades on the left and the agent's server-signed, firewall-enforced replica on the right — stamped with the real latency (submitted − detected) and the actual fill. Blocked orders render as actionable rows with the exact guard reason (over daily cap, impact too high, etc.) — never a silent skip. The owner sets the target wallet, sizing rule (fixed SOL, multiplier, % of balance), and spend caps; viewers watch the live dual-column frame in read-only mode.</description></item>+ <item>+ <title>Cosmetics you buy now follow you into every world</title>+ <link>https://three.ws/play</link>+ <guid isPermaLink="false">2026-06-29:Cosmetics you buy now follow you into every world</guid>+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>When you buy a premium cosmetic for your avatar, that unlock now reaches the 3D world itself: the item is wearable the moment the payment settles, your equipped look is saved to your account, and it re-applies automatically the next time you log in — in any world, whether you arrived through a coin's /play space or /walk. Previously a purchase was recorded but the world didn't yet know you owned it, so the item could still read as locked when you went to wear it. Everyone around you sees your equipped fit too.</description>+ </item><item><title>Deploy your agent to the live wall in four guided steps</title><link>https://three.ws/agent-screen</link>diff --git a/public/features.json b/public/features.jsonindex 850fddbb9..3204b608a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-29T13:41:06.022Z",+ "generated_at": "2026-06-29T17:10:31.648Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-screen.js b/src/agent-screen.jsindex 78143ccb5..cd963936a 100644--- a/src/agent-screen.js+++ b/src/agent-screen.js@@ -575,6 +575,25 @@ function loadLayout() {return base;}+// Detect a Team Task command in the task bar. A lead agent splits the goal,+// delegates sub-tasks and hires teammates over x402 (api/agent-collab). Matches+// an explicit `team:` prefix or natural phrasings; returns the cleaned goal or+// null. The owner gate and hard spend cap live server-side — this only routes.+export function parseTeamCommand(raw) {+ const text = String(raw == null ? '' : raw).trim();+ if (!text) return null;+ // Explicit prefix: "team: <goal>" / "team task: <goal>".+ const prefix = text.match(/^team(?:\s+task)?\s*[:\-—]\s*(.+)$/is);+ if (prefix && prefix[1].trim()) return prefix[1].trim();+ // Natural phrasing: "assemble a team to …", "lead a team to …",+ // "delegate to your team: …", "with your team, …".+ const natural = text.match(+ /^(?:assemble|lead|gather|rally|build)\s+(?:a|your|the)?\s*team\b[\s,:to-]*([\s\S]+)$/i,+ ) || text.match(/^delegate\s+to\s+(?:your|the)\s+team\b[\s,:-]*([\s\S]+)$/i);+ if (natural && natural[1].trim()) return natural[1].trim();+ return null;+}+// ─────────────────────────────────────────────────────────────────────────────async function boot(id) {@@ -1778,6 +1797,7 @@ async function boot(id) {const forgeHit = parseForgeFrame(frame);if (forgeHit) loadForgedAvatar(forgeHit);if (frame.meta?.kind === 'a2a_hire') hireViz?.ingest(frame.meta, { live: true });+ if (frame.meta?.collab) teamTask.ingest(frame.meta.collab);if (frame.type === 'trade') {const delta = ingestTrade(frame);if (delta) emoteForTrade(delta);@@ -1802,6 +1822,9 @@ async function boot(id) {// Replay any hire phases in order so a reconnect re-syncs to the latest// phase (no coin animation — this is history, not a fresh settle).entries.forEach((e) => { if (e.meta?.kind === 'a2a_hire') hireViz?.ingest(e.meta, { live: false }); });+ // Resync the Team Task graph to the latest pushed snapshot on reconnect.+ const lastCollab = [...entries].reverse().find((e) => e?.meta?.collab);+ if (lastCollab) teamTask.ingest(lastCollab.meta.collab);},onDark() { setDark(); },onError() {diff --git a/src/dashboard-next/pages/monetize.js b/src/dashboard-next/pages/monetize.jsindex f869dfd23..02f7764e8 100644--- a/src/dashboard-next/pages/monetize.js+++ b/src/dashboard-next/pages/monetize.js@@ -179,6 +179,7 @@ async function loadAndRender(host, me, agents) {host.appendChild(renderWithdrawals({ withdrawals, wallets, available, host, me, agents }));host.appendChild(renderLegacyPayoutWallets({ wallets, host, me, agents }));host.appendChild(renderCosmeticEarnings({ wallets }));+ host.appendChild(renderCosmeticSplit({ agents }));host.appendChild(renderPlanUsage(summary));host.appendChild(renderTokensPanel(agents));}@@ -1750,6 +1751,225 @@ async function loadCosmeticEarnings(body, wallet) {`;}+// -- Cosmetic revenue split (R25) --+//+// Set how much of each premium-cosmetic sale tied to one of your coins pays out to+// your wallet. The share is real: it's the % of the settled USDC sent on-chain to+// the coin's creator wallet at sale time (the rest funds the worlds the cosmetic is+// worn in). Changing it is authorized by signing a message with the coin's creator+// wallet — the same wallet the payout goes to — so no one else can redirect it.++/** The creator's launched coins, from their agents' token metadata (mint+symbol). */+function launchedCoins(agents) {+ const seen = new Set();+ const coins = [];+ for (const a of agents || []) {+ const m = a?.meta?.pumpfun || a?.meta?.token;+ const mint = m?.mint || m?.address || m?.ca;+ if (!mint || !SOLANA_ADDR_RE.test(String(mint)) || seen.has(String(mint))) continue;+ seen.add(String(mint));+ const sym = String(m.symbol || m.ticker || a.name || 'COIN').toUpperCase().replace(/^\$+/, '');+ coins.push({ mint: String(mint), symbol: sym });+ }+ return coins;+}++/** Connect a Solana wallet and sign `message`, returning { signer, signature }.+ * Mirrors the link/sign flow in community/town-auth.js — ed25519 over the UTF-8+ * bytes, base58-encoded, exactly how the server (verifySiwsSignature) expects. */+async function signSolanaMessage(message) {+ const provider = window.phantom?.solana || window.solana;+ if (!provider?.connect) throw new Error('No Solana wallet found — install Phantom to sign.');+ const resp = await provider.connect();+ const signer = (resp?.publicKey || provider.publicKey)?.toString();+ if (!signer) throw new Error('Could not read wallet address.');+ const encoded = new TextEncoder().encode(message);+ const signed = await provider.signMessage(encoded, 'utf8');+ const sigBytes = signed?.signature ?? signed;+ const bs58 = (await import('bs58')).default;+ return { signer, signature: bs58.encode(sigBytes) };+}++function renderCosmeticSplit({ agents }) {+ const panel = document.createElement('div');+ panel.className = 'dn-panel';++ const coins = launchedCoins(agents);++ panel.innerHTML = `+ <div style="margin-bottom:6px">+ <div class="dn-panel-title">Cosmetic revenue split</div>+ <div class="dn-panel-sub" style="margin:2px 0 0">+ Your share of premium cosmetics sold inside your coins’ worlds — paid out in USDC+ on-chain. The platform keeps the rest to fund the worlds they’re worn in.+ </div>+ </div>+ <div data-slot="split-list"></div>+ `;++ const list = panel.querySelector('[data-slot="split-list"]');++ if (!coins.length) {+ list.innerHTML = `+ <div style="text-align:center;padding:24px 12px;color:var(--nxt-ink-fade)">+ <div style="font-size:28px;opacity:.5" aria-hidden="true">✦</div>+ <div style="font-weight:600;color:var(--nxt-ink);margin-top:6px">No coins launched yet</div>+ <div style="font-size:13px;margin-top:6px;max-width:48ch;margin-inline:auto;line-height:1.5">+ Launch a coin from one of your agents to open its 3D world. You’ll then set+ your share of every premium cosmetic players buy inside it.+ </div>+ <a class="dn-btn primary" href="/dashboard/agents" style="margin-top:14px;display:inline-block">Go to Agents</a>+ </div>`;+ return panel;+ }++ list.innerHTML = coins.map((c) => `+ <div data-mint="${esc(c.mint)}" style="border:1px solid var(--nxt-stroke);border-radius:12px;padding:14px 16px;margin-bottom:10px">+ <div style="display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap">+ <div style="display:flex;align-items:center;gap:8px;min-width:0">+ <span style="font-weight:700">$${esc(c.symbol)}</span>+ <a href="/play?coin=${encodeURIComponent(c.mint)}" target="_blank" rel="noopener"+ style="font-size:11.5px;color:var(--nxt-ink-fade);text-decoration:none">+ ${esc(c.mint.slice(0, 4) + '…' + c.mint.slice(-4))} ↗</a>+ </div>+ </div>+ <div data-slot="split-body" style="margin-top:10px">+ <div style="color:var(--nxt-ink-fade);font-size:13px">Loading split…</div>+ </div>+ </div>`).join('');++ for (const c of coins) {+ const row = list.querySelector(`[data-mint="${CSS.escape(c.mint)}"] [data-slot="split-body"]`);+ loadSplitRow(row, c.mint, c.symbol);+ }++ return panel;+}++async function loadSplitRow(body, mint, symbol) {+ body.innerHTML = `<div style="color:var(--nxt-ink-fade);font-size:13px">Loading split…</div>`;+ let cfg;+ try {+ cfg = await get(`/api/cosmetics/split?mint=${encodeURIComponent(mint)}`);+ } catch {+ body.innerHTML = `<div style="color:var(--nxt-danger);font-size:13px">+ Couldn’t load split. <button class="dn-btn" data-slot="sp-retry" style="margin-left:8px;padding:4px 10px;font-size:12px">Retry</button></div>`;+ body.querySelector('[data-slot="sp-retry"]')?.addEventListener('click', () => loadSplitRow(body, mint, symbol));+ return;+ }+ renderSplitRow(body, mint, symbol, cfg);+}++function renderSplitRow(body, mint, symbol, cfg) {+ const maxBps = Number.isFinite(Number(cfg?.maxBps)) ? Number(cfg.maxBps) : 9000;+ const maxPct = Math.round(maxBps / 100);+ const curBps = Math.max(0, Math.min(maxBps, Math.round(Number(cfg?.splitBps) || 0)));+ const curPct = Math.round(curBps / 100);+ const creator = cfg?.creatorWallet || null;++ // No resolvable creator wallet → nothing to pay out to yet. Honest, designed state.+ if (!creator) {+ body.innerHTML = `+ <div style="font-size:13px;color:var(--nxt-ink-fade);line-height:1.5">+ We couldn’t resolve this coin’s creator wallet on-chain yet, so there’s no+ payout target to split to. Once the coin’s creator is established, set your+ share here.+ </div>`;+ return;+ }++ const creatorShort = creator.slice(0, 4) + '…' + creator.slice(-4);+ const defaultTag = cfg?.isDefault+ ? `<span class="dn-tag" style="margin-left:8px">Default</span>`+ : `<span class="dn-tag success" style="margin-left:8px">Custom</span>`;++ body.innerHTML = `+ <div style="display:flex;align-items:flex-end;gap:14px;flex-wrap:wrap">+ <div style="flex:1 1 260px;min-width:220px">+ <label style="display:flex;align-items:center;font-size:12px;color:var(--nxt-ink-fade);margin-bottom:6px">+ Your share ${defaultTag}+ </label>+ <div style="display:flex;align-items:center;gap:10px">+ <input type="range" data-slot="sp-range" min="0" max="${maxPct}" step="1" value="${curPct}"+ aria-label="Your share of cosmetic sales (percent)" style="flex:1;accent-color:var(--nxt-accent,#8aa0ff)">+ <div style="display:flex;align-items:center;gap:4px">+ <input type="number" data-slot="sp-num" min="0" max="${maxPct}" step="1" value="${curPct}"+ class="mon-select" style="width:70px;text-align:right" aria-label="Your share percent">+ <span style="color:var(--nxt-ink-fade);font-size:13px">%</span>+ </div>+ </div>+ <div data-slot="sp-hint" style="font-size:11.5px;color:var(--nxt-ink-fade);margin-top:6px"></div>+ </div>+ <div style="display:flex;flex-direction:column;gap:6px;align-items:flex-end">+ <button class="dn-btn primary" data-slot="sp-save" style="padding:7px 16px" disabled>Save share</button>+ <div style="font-size:11px;color:var(--nxt-ink-fade)">Pays to ${esc(creatorShort)}</div>+ </div>+ </div>+ <div data-slot="sp-status" role="status" style="font-size:12.5px;margin-top:10px;min-height:16px"></div>+ `;++ const range = body.querySelector('[data-slot="sp-range"]');+ const num = body.querySelector('[data-slot="sp-num"]');+ const hint = body.querySelector('[data-slot="sp-hint"]');+ const saveBtn = body.querySelector('[data-slot="sp-save"]');+ const status = body.querySelector('[data-slot="sp-status"]');++ const clampPct = (v) => Math.max(0, Math.min(maxPct, Math.round(Number(v) || 0)));+ const paint = (pct) => {+ hint.textContent = `Platform keeps ${100 - pct}% · max your share ${maxPct}%`;+ saveBtn.disabled = pct === curPct;+ };+ const sync = (pct, from) => {+ const v = clampPct(pct);+ if (from !== 'range') range.value = String(v);+ if (from !== 'num') num.value = String(v);+ paint(v);+ };++ range.addEventListener('input', () => sync(range.value, 'range'));+ num.addEventListener('input', () => sync(num.value, 'num'));+ sync(curPct);++ saveBtn.addEventListener('click', async () => {+ const pct = clampPct(num.value);+ const bps = pct * 100;+ saveBtn.disabled = true;+ status.style.color = 'var(--nxt-ink-fade)';+ status.textContent = 'Approve the signature in your wallet…';+ const ts = Math.floor(Date.now() / 1000);+ // Rebuild the exact message the server re-derives + verifies (see+ // splitConfigMessage in api/_lib/cosmetics-economy.js). bps is already clamped.+ const message = `three.ws cosmetic revenue split\nmint: ${mint}\nshare: ${bps} bps\nts: ${ts}`;+ let signer, signature;+ try {+ ({ signer, signature } = await signSolanaMessage(message));+ } catch (err) {+ status.style.color = 'var(--nxt-danger)';+ status.textContent = err?.message || 'Could not sign with your wallet.';+ saveBtn.disabled = false;+ return;+ }+ status.textContent = 'Saving…';+ try {+ const next = await post('/api/cosmetics/split', { mint, bps, ts, signature, signer });+ renderSplitRow(body, mint, symbol, next);+ const ok = body.querySelector('[data-slot="sp-status"]');+ if (ok) { ok.style.color = 'var(--nxt-success)'; ok.textContent = `Saved — you now take ${Math.round((next.splitBps || 0) / 100)}% of $${symbol} cosmetic sales.`; }+ } catch (err) {+ status.style.color = 'var(--nxt-danger)';+ status.textContent =+ err?.code === 'not_creator'+ ? `This coin pays out to ${creatorShort}. Connect that wallet to change the split.`+ : err?.code === 'bad_signature'+ ? 'Signature didn’t verify — make sure you signed with the creator wallet, then try again.'+ : err?.code === 'no_creator'+ ? 'No creator wallet is established for this coin yet.'+ : err?.message || 'Couldn’t save the split. Try again.';+ saveBtn.disabled = false;+ }+ });+}+// -- Token earnings --function renderTokensPanel(agents) {diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 2333b02f5..0aa271852 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -29,9 +29,9 @@ import { mountOracleRibbon } from './oracle-ribbon.js';import { MarketReactor } from './market-reactor.js';import {VoxelWorld, createBuildHud, parseKey, keyOf, MAX_BLOCKS, BLOCK,- COMPOSITE_PIECES, compositeCells, MAX_COMPOSITE_CELLS,+ COMPOSITE_PIECES, compositeCells,} from './build-voxels.js';-import { WorldObjects, PropGhost, PROP_CATALOG, DEFAULT_PROP, propDef } from './world-objects.js';+import { WorldObjects, PropGhost, propDef } from './world-objects.js';import { normalizeGatewayURL } from '../ipfs.js';import {loadManifest, getEmoteDefs, getAllEmoteDefs, resolveAvatarUrl, buildAvatar, playEmoteClip,@@ -39,7 +39,7 @@ import {} from './avatar-rig.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 { serializeLoadout, getCosmetic } from '../../multiplayer/src/cosmetics-catalog.js';import { AccessoryManager } from '../agent-accessories.js';import { CosmeticsShop } from './cosmetics-shop.js';import { CosmeticsWardrobe } from './cosmetics-wardrobe.js';@@ -1591,8 +1591,11 @@ export class CoinCommunities {// Equip `id` durably: send to the server (authoritative validation + persistence)// so the fit survives logout, world switches, and is visible to peers immediately.// The server echoes a fresh profile which updates the wardrobe and local avatar.+ // Only forward ids the rig can actually wear — a purchase of an item outside the+ // worn-cosmetics catalog (its ownership still records server-side) must not fire+ // a spurious "that cosmetic doesn't exist" notice from the equip authority._equipCosmeticDurable(id) {- if (this.net) this.net.equipCosmetic(id);+ if (this.net && getCosmetic(id)) this.net.equipCosmetic(id);}// Revert the active preview, leaving the avatar exactly as it was.diff --git a/tests/api/granite-oracle-libs.test.js b/tests/api/granite-oracle-libs.test.jsindex 0ae1fc0bf..5f7d6e9c9 100644--- a/tests/api/granite-oracle-libs.test.js+++ b/tests/api/granite-oracle-libs.test.js@@ -90,4 +90,36 @@ describe('GeckoTerminal OHLCV lib', () => {it('resolves a token to its top pool', async () => {expect(await topPoolForToken('MINTX')).toBe('TOPPOOL');});++ it('retries a transient 429 with backoff, then succeeds', async () => {+ let calls = 0;+ global.fetch = vi.fn(async () => {+ calls += 1;+ if (calls === 1) return mres({ status: { error_code: 429 } }, false, 429);+ return mres({ data: [{ id: 'solana_TOPPOOL', attributes: { address: 'TOPPOOL' } }] });+ });+ // Use a fresh pool id so the in-module 20s cache can't serve a prior value.+ expect(await topPoolForToken('MINTX-429-once')).toBe('TOPPOOL');+ expect(calls).toBe(2); // first 429 retried, second call served+ });++ it('throws a 429-tagged error once retries are exhausted', async () => {+ let calls = 0;+ global.fetch = vi.fn(async () => {+ calls += 1;+ return mres({ status: { error_code: 429 } }, false, 429);+ });+ await expect(topPoolForToken('MINTX-429-always')).rejects.toMatchObject({ status: 429 });+ expect(calls).toBe(3); // MAX_ATTEMPTS exhausted, status preserved as 429+ });++ it('does not retry a 404 (fail fast)', async () => {+ let calls = 0;+ global.fetch = vi.fn(async () => {+ calls += 1;+ return mres({}, false, 404);+ });+ await expect(topPoolForToken('MINTX-404')).rejects.toMatchObject({ status: 404 });+ expect(calls).toBe(1); // client error is not retried+ });});diff --git a/tests/cosmetics-ownership-bridge.test.js b/tests/cosmetics-ownership-bridge.test.jsnew file mode 100644index 000000000..3330655e2--- /dev/null+++ b/tests/cosmetics-ownership-bridge.test.js@@ -0,0 +1,82 @@+// R22 → R23 ownership bridge: a cosmetic bought over the x402 rail (recorded in+// the Redis ownership ledger) must fold into a player's profile so the worn-rig+// equip authority lets them wear it — in every world, across logins.+//+// Covers the pure server-side seam:+// • mergeOwnedFromLedger: grants only ids that are premium in THIS worn catalog,+// ignores free/unknown/foreign-catalog ids, is idempotent, returns the count+// • equipCosmetic after a merge: a previously-unowned premium id becomes wearable+// • the ledger reader degrades to [] when Redis isn't configured (fail-open read)+//+// The Redis round-trip itself is exercised against the real Upstash rail on+// deploy; here the reader runs unconfigured so the seam is deterministic.++import { describe, it, expect } from 'vitest';++import {+ newProfile, mergeOwnedFromLedger, equipCosmetic, ownedCosmeticSet,+} from '../multiplayer/src/economy.js';+import { COSMETICS } from '../multiplayer/src/cosmetics-catalog.js';+import { readOwnedCosmetics, normalizeAccountId } from '../multiplayer/src/cosmetics-ownership.js';++// A premium worn cosmetic that exists in BOTH the shop and the rig catalog — the+// real overlap a purchase unlocks. (Picked from the catalog so the test tracks it.)+const PREMIUM = COSMETICS.find((c) => c.tier === 'premium');+const FREE = COSMETICS.find((c) => c.tier === 'free' && c.visual); // a free wearable++describe('mergeOwnedFromLedger — R22 ledger → profile unlock', () => {+ it('grants a premium id from the ledger and makes it wearable', () => {+ const p = newProfile('acct-1');+ expect(ownedCosmeticSet(p).has(PREMIUM.id)).toBe(false);+ expect(equipCosmetic(p, PREMIUM.id)).toBeNull(); // unowned → rejected++ const granted = mergeOwnedFromLedger(p, [PREMIUM.id]);+ expect(granted).toBe(1);+ expect(ownedCosmeticSet(p).has(PREMIUM.id)).toBe(true);+ const equipped = equipCosmetic(p, PREMIUM.id);+ expect(equipped).not.toBeNull();+ expect(equipped[PREMIUM.slot]).toBe(PREMIUM.id);+ });++ it('is idempotent — a second merge of the same id grants nothing new', () => {+ const p = newProfile('acct-2');+ expect(mergeOwnedFromLedger(p, [PREMIUM.id])).toBe(1);+ expect(mergeOwnedFromLedger(p, [PREMIUM.id])).toBe(0);+ expect(p.cosmetics.owned.filter((id) => id === PREMIUM.id)).toHaveLength(1);+ });++ it('ignores free, unknown, and foreign-catalog ledger ids (no error, no grant)', () => {+ const p = newProfile('acct-3');+ // `skin-crimson` is a real shop SKU in the sibling catalog but not a worn-rig+ // cosmetic here — it must be silently ignored, never stored or errored.+ const granted = mergeOwnedFromLedger(p, [FREE.id, 'skin-crimson', 'totally-made-up', PREMIUM.id]);+ expect(granted).toBe(1); // only PREMIUM.id is a premium worn cosmetic+ expect(p.cosmetics.owned).toEqual([PREMIUM.id]);+ expect(equipCosmetic(p, 'skin-crimson')).toBeNull();+ });++ it('handles empty / non-array input without throwing', () => {+ const p = newProfile('acct-4');+ expect(mergeOwnedFromLedger(p, [])).toBe(0);+ expect(mergeOwnedFromLedger(p, null)).toBe(0);+ expect(mergeOwnedFromLedger(p, undefined)).toBe(0);+ expect(p.cosmetics.owned).toEqual([]);+ });+});++describe('cosmetics-ownership reader — fail-open when unconfigured', () => {+ it('normalizeAccountId accepts wallets/guest ids, rejects junk', () => {+ expect(normalizeAccountId(' WwW9dwK7iY5cT9aZ8h6n3v2Q1rT4uYpL5mN6oP7qR8s '))+ .toBe('WwW9dwK7iY5cT9aZ8h6n3v2Q1rT4uYpL5mN6oP7qR8s');+ expect(normalizeAccountId('guest-abc123')).toBe('guest-abc123');+ expect(normalizeAccountId('a')).toBe(''); // too short+ expect(normalizeAccountId('bad id!')).toBe(''); // illegal chars+ expect(normalizeAccountId(null)).toBe('');+ });++ it('reads [] for any account when Redis is not configured', async () => {+ // No UPSTASH_REDIS_REST_URL/_TOKEN in the test env → fail-open empty read.+ await expect(readOwnedCosmetics('WwW9dwK7iY5cT9aZ8h6n3v2Q1rT4uYpL5mN6oP7qR8s')).resolves.toEqual([]);+ await expect(readOwnedCosmetics('')).resolves.toEqual([]);+ });+});