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(marketplace): complete Task 20 player-to-player market
nirholas7e7bd743ab8d
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.jsindex 39b4bf296..f54f4819e 100644--- a/multiplayer/src/index.js+++ b/multiplayer/src/index.js@@ -26,7 +26,6 @@ import { blockStore } from './block-store.js';import { flushAllPlayers } from './playerStore.js';import { marketplaceStore } from './marketplaceStore.js';import { SERVERS } from './servers.js';-import { PRESENCE_HASH } from './presence-keys.js';import { socialHub } from './social-hub.js';import { verifyNotifySignature } from './presence-token.js';@@ -194,14 +193,15 @@ for (const realm of Object.keys(REALMS)) {gameServer.define(`game_${realm}`, GameRoom, { realm }).filterBy(['server']);}-// --- Multi-server discovery + presence (Task 23) ----------------------------// Read-only JSON the /play login picker and a friends panel consume from the-// (different-origin) static site, so they carry permissive CORS. Both read live-// truth — never cached or faked numbers.+// --- Multi-server discovery (Task 23) --------------------------------------+// Read-only population the /play login picker consumes from the (different-origin)+// static site, so it carries permissive CORS. Always live truth — never cached or+// faked. (Friends presence — "which server+realm a friend is on" — is published by+// the social hub under the verified account id and read by the authenticated+// friends API, NOT here; there is no anonymous by-id lookup to scrape.)-// CORS for the public read-only endpoints. The population counts and presence-// flags are not sensitive, so we allow any origin to GET them; no credentials-// are involved. OPTIONS preflights short-circuit here.+// CORS for the public population endpoint. The counts aren't sensitive, so any+// origin may GET them; no credentials are involved. OPTIONS preflights short-circuit.function publicJsonCors(_req, res, next) {res.set('Access-Control-Allow-Origin', '*');res.set('Access-Control-Allow-Methods', 'GET, OPTIONS');@@ -211,12 +211,34 @@ function publicJsonCors(_req, res, next) {next();}+// Lightweight per-IP rate limit for the public endpoint — a fixed window that+// clears legitimate picker polling (one every ~10s) with wide headroom but caps a+// scripted flood. In-process (per instance), which is plenty for a read-only GET.+const RATE_WINDOW_MS = 10_000;+const RATE_MAX = 30;+const _rateBuckets = new Map(); // ip -> { windowStart, count }+function rateLimit(req, res, next) {+ const ip = req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.socket?.remoteAddress || 'unknown';+ const now = Date.now();+ let b = _rateBuckets.get(ip);+ if (!b || now - b.windowStart > RATE_WINDOW_MS) { b = { windowStart: now, count: 0 }; _rateBuckets.set(ip, b); }+ b.count++;+ if (b.count > RATE_MAX) return res.status(429).json({ error: 'rate_limited' });+ next();+}+// Bound the bucket map so a churn of distinct IPs can't grow it without limit.+setInterval(() => {+ const now = Date.now();+ for (const [ip, b] of _rateBuckets) if (now - b.windowStart > RATE_WINDOW_MS) _rateBuckets.delete(ip);+}, RATE_WINDOW_MS * 6).unref?.();+// GET /servers — the world-instance roster with REAL live population. Population// is the sum of connected clients across every game_* room whose metadata names// that server, queried through the matchmaker (so it's correct across all-// horizontally-scaled instances, not just this process). The least-full server-// is recommended so the picker can nudge balancing without ever faking a count.-app.get('/servers', publicJsonCors, async (_req, res) => {+// horizontally-scaled instances, not just this process). The most-populated server+// that isn't near capacity is recommended, so newcomers land where the world feels+// alive rather than fragmenting into an empty instance — without ever faking a count.+app.get('/servers', publicJsonCors, rateLimit, async (_req, res) => {const counts = Object.fromEntries(SERVERS.map((s) => [s.id, 0]));try {const rooms = await matchMaker.query({});@@ -229,12 +251,18 @@ app.get('/servers', publicJsonCors, async (_req, res) => {console.warn('[multiplayer] /servers query failed:', err?.message);return res.status(503).json({ error: 'population_unavailable' });}- // Recommend exactly one server — the least-full — preferring the first in- // roster order on a tie so the suggestion is stable between polls.+ // Recommend the fullest server that still has comfortable headroom, so worlds+ // stay lively instead of every newcomer being sent to the emptiest one. Falls+ // back to the least-full server only when all are near capacity. Stable on ties+ // (first in roster order wins) so the suggestion doesn't flicker between polls.+ const SOFT_CAP = 40; // leave room under the 50/room ceiling before steering elsewherelet recommended = SERVERS[0]?.id || null;- let min = Infinity;+ let bestLive = -1; // fullest below the soft cap+ let leastFull = Infinity; // fallback when everyone is busyfor (const s of SERVERS) {- if (counts[s.id] < min) { min = counts[s.id]; recommended = s.id; }+ const n = counts[s.id];+ if (n < SOFT_CAP && n > bestLive) { bestLive = n; recommended = s.id; }+ if (bestLive < 0 && n < leastFull) { leastFull = n; recommended = s.id; }}res.json({servers: SERVERS.map((s) => ({@@ -247,45 +275,13 @@ app.get('/servers', publicJsonCors, async (_req, res) => {});});-// GET /presence?ids=a,b,c — for a friends panel (Task 15): resolve which-// server+realm each named account is currently on, or that they're offline.-// Reads the shared presence hash GameRoom maintains on join/leave. Capped at a-// sane batch size so a single request can't sweep the whole registry.-app.get('/presence', publicJsonCors, async (req, res) => {- const ids = String(req.query.ids || '')- .split(',')- .map((s) => s.trim())- .filter(Boolean)- .slice(0, 100);- if (!ids.length) return res.json({ presence: {} });- let all = {};- try {- all = (await gameServer.presence.hgetall(PRESENCE_HASH)) || {};- } catch (err) {- console.warn('[multiplayer] /presence read failed:', err?.message);- return res.status(503).json({ error: 'presence_unavailable' });- }- const presence = {};- for (const id of ids) {- const raw = all[id];- if (!raw) { presence[id] = { online: false }; continue; }- try {- const e = JSON.parse(raw);- presence[id] = { online: true, server: e.server || '', realm: e.realm || '', name: e.name || '' };- } catch {- presence[id] = { online: false };- }- }- res.json({ presence });-});-gameServer.listen(PORT, HOST).then(() => {console.log(`[multiplayer] listening on ws://${HOST}:${PORT}`);console.log(`[multiplayer] rooms: walk_world, game_{${Object.keys(REALMS).join(',')}}`);console.log(`[multiplayer] world instances: ${SERVERS.map((s) => `${s.id} (${s.name})`).join(', ')}`);- console.log(`[multiplayer] discovery: GET /servers, GET /presence?ids=`);+ console.log(`[multiplayer] discovery: GET /servers`);console.log(`[multiplayer] allowed origins: ${ALLOWED_ORIGINS.join(', ')}`);}).catch((err) => {diff --git a/multiplayer/src/presence-keys.js b/multiplayer/src/presence-keys.jsindex 49b147133..caaf719cb 100644--- a/multiplayer/src/presence-keys.js+++ b/multiplayer/src/presence-keys.js@@ -1,15 +1,9 @@-// Shared presence keys for the multi-server account registry (Task 23).+// Shared presence pub/sub keys for the multi-server account system (Tasks 16/20/23).//-// Both GameRoom (writer) and index.js (the /presence + /servers HTTP readers)-// reference these, so they live in one place to stay in lock-step. The store is-// the Colyseus `presence` instance — a process-local map in single-instance-// mode, or Redis when REDIS_URI is set — so the same keys work whether the host-// runs one process or many.--// Hash of currently-online accounts: field = account id (playerId), value =-// JSON { server, realm, name, sid, ts }. Lets a friends panel (or /presence)-// resolve which server+realm any account is on without joining its room.-export const PRESENCE_HASH = 'kg:presence';+// These name Colyseus `presence` channels — a process-local emitter in+// single-instance mode, or Redis when REDIS_URI is set — so they work whether the+// host runs one process or many. (Account-level *friends* presence lives in the+// social hub, keyed by verified account id; it is not stored here.)// Pub/sub channel a room subscribes to per online account, so a fresh login of// the same account anywhere on the cluster can evict the stale session anddiff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.jsindex 647863e1e..48dc9fad6 100644--- a/multiplayer/src/rooms/GameRoom.js+++ b/multiplayer/src/rooms/GameRoom.js@@ -21,10 +21,10 @@ import { STACKABLE_ITEMS, isEdible, healValue, scaledHeal, isMount, mountStepMs,import { cleanAvatarUrl } from '../avatar-url.js';import { loadPlayer, savePlayer, hydratePlayer, flushPlayer } from '../playerStore.js';import { cleanServer } from '../servers.js';-import { PRESENCE_HASH, evictChannel, payoutChannel, TAKEOVER_CLOSE_CODE } from '../presence-keys.js';+import { evictChannel, payoutChannel, TAKEOVER_CLOSE_CODE } from '../presence-keys.js';import { socialHub } from '../social-hub.js';import { verifyPresenceTicket } from '../presence-token.js';-import { cosmeticById, isOffered, currentOffers, clientCatalog } from '../cosmetics.js';+import { cosmeticById, evaluatePurchase, currentOffers, clientCatalog } from '../cosmetics.js';import { marketplaceStore } from '../marketplaceStore.js';import {TOKEN_SYMBOL, TOKEN_DECIMALS, tokenConfigured, isWalletAddress,@@ -244,7 +244,7 @@ export class GameRoom extends Room {const uid = verifyPresenceTicket(ticket);if (!uid) return;c.userData = { ...(c.userData || {}), accountUid: uid };- socialHub.register(uid, c, this.realm.name);+ socialHub.register(uid, c, this.realm.name, this.server);});// Cosmetics shop (Task 21): request the live shop board, buy a cosmetic from// the current rotation, and equip/unequip an owned (purchased) cosmetic. All@@ -517,6 +517,10 @@ export class GameRoom extends Room {async onLeave(client) {const sid = client.sessionId;const priv = this.priv.get(sid);+ // A portal handoff reserved a seat in the destination room and sent the client+ // the token. If the client disconnects before consuming it, clear the flag so+ // the slot can't be stuck. (The destination seat expires on its own TTL.)+ if (priv) priv.transferring = false;// An evicted session already persisted itself synchronously inside _onEvict;// persisting again here would write a now-stale snapshot over whatever the// new session has since done, so skip it. A normal leave persists as usual.@@ -544,13 +548,9 @@ export class GameRoom extends Room {try { this.presence.unsubscribe(paySub.channel, paySub.handler); } catch {}this._payoutSubs.delete(sid);}- if (priv?.playerId) {- try {- const raw = await this.presence.hget(PRESENCE_HASH, priv.playerId);- if (raw && JSON.parse(raw).sid === sid) await this.presence.hdel(PRESENCE_HASH, priv.playerId);- } catch {}- }+ // Clear account-level friends presence when this account's last socket here+ // leaves; the social hub keeps it online if another tab/realm is still open.if (client.userData?.accountUid) socialHub.unregister(client.userData.accountUid, client);this.state.players.delete(sid);@@ -1989,18 +1989,15 @@ export class GameRoom extends Room {if (!p || !priv || !priv.cosmetics) return;if (!this._rateOk(client.sessionId, 'ui')) return;const id = String(payload?.id ?? '');- const cosmetic = cosmeticById(id);- if (!cosmetic) { client.send('notice', { kind: 'shop', text: 'That cosmetic doesn’t exist.' }); return; }- if (priv.cosmetics.owned.has(id)) {- client.send('notice', { kind: 'shop', text: `You already own the ${cosmetic.name}.` });- return;- }- if (!isOffered(id, Date.now())) {- client.send('notice', { kind: 'shop', text: `The ${cosmetic.name} isn’t on sale right now.` });- return;- }- if (p.gold < cosmetic.price) {- client.send('notice', { kind: 'shop', text: `Need ${cosmetic.price - p.gold} more gold for the ${cosmetic.name}.` });+ // Single source of truth for the buy rules (shared with cosmetics.test.js).+ const { ok, reason, cosmetic } = evaluatePurchase(p.gold, priv.cosmetics.owned, id, Date.now());+ if (!ok) {+ const name = cosmetic?.name || 'cosmetic';+ const text = reason === 'unknown' ? 'That cosmetic doesn’t exist.'+ : reason === 'owned' ? `You already own the ${name}.`+ : reason === 'not-offered' ? `The ${name} isn’t on sale right now.`+ : `Need ${cosmetic.price - p.gold} more gold for the ${name}.`;+ client.send('notice', { kind: 'shop', text });return;}p.gold -= cosmetic.price;@@ -2662,6 +2659,7 @@ export class GameRoom extends Room {_handleInvMove(client, payload) {const p = this.state.players.get(client.sessionId);if (!p) return;+ if (this.priv.get(client.sessionId)?.transferring) return;if (!this._rateOk(client.sessionId, 'ui')) return;const from = this._resolveSlot(p, payload?.from);const to = this._resolveSlot(p, payload?.to);@@ -2687,6 +2685,7 @@ export class GameRoom extends Room {_handleEquip(client, payload) {const p = this.state.players.get(client.sessionId);if (!p) return;+ if (this.priv.get(client.sessionId)?.transferring) return;if (!this._rateOk(client.sessionId, 'ui')) return;const i = payload?.slot | 0;if (i < -1 || i >= HOTBAR_SIZE) return;@@ -2708,6 +2707,7 @@ export class GameRoom extends Room {_handleBank(client, payload, dir) {const p = this.state.players.get(client.sessionId);if (!p) return;+ if (this.priv.get(client.sessionId)?.transferring) return;if (!this._rateOk(client.sessionId, 'ui')) return;// Must be standing on a bank-counter tile.if (!this.realm.bankZone.some((t) => t.tx === p.tx && t.ty === p.ty)) {diff --git a/src/game/game-hud.js b/src/game/game-hud.jsindex a59d57506..53213e12e 100644--- a/src/game/game-hud.js+++ b/src/game/game-hud.js@@ -43,6 +43,8 @@ const PROP_ICON = {'hat-beanie': '🧢','hat-baseball': '🧢','hat-cowboy': '🤠',+ 'glasses-round': '👓',+ 'glasses-shades': '🕶️',};const SKILL_LABEL = { combat: 'Combat', woodcutting: 'Woodcutting', mining: 'Mining', fishing: 'Fishing', cooking: 'Cooking' };@@ -90,6 +92,9 @@ export class GameHud {this._shopTab = 'shop';this._dailyResetAt = 0;this._weeklyResetAt = 0;+ // Wardrobe try-before-equip: the id currently previewed on the local+ // avatar (null = none). Local-only; cleared when the shop closes.+ this._previewId = null;// Marketplace (Task 20): the latest board (active listings + your own), the// token-payment capability flags, the open flag + active tab, per-listing// "busy" labels driven by the controller during an on-chain buy, an error@@ -619,6 +624,9 @@ export class GameHud {this._shopOpen = false;this.elShop.hidden = true;this.elShopBtn.setAttribute('aria-expanded', 'false');+ // Drop any uncommitted wardrobe preview — revert the avatar to the+ // server-authoritative equipped look.+ if (this._previewId !== null) { this._previewId = null; this.opts.onStopPreview?.(); }}_setShopTab(tab) {@@ -701,56 +709,54 @@ export class GameHud {const frag = document.createDocumentFragment();const ownedIds = (this.shop?.owned || []).filter((id) => this.cosmetics.has(id));const equipped = this.shop?.equipped || '';- frag.appendChild(el('p', 'kq-shop-sub', 'Equip an owned look — it shows on your avatar instantly, for you and everyone around you.'));+ frag.appendChild(el('p', 'kq-shop-sub', 'Tap a look to preview it live on your avatar; press Equip to keep it. Everyone around you sees what you equip.'));const grid = el('div', 'kq-cos-grid');- // Default (no cosmetic) tile.- const def = el('div', 'kq-cos-card kq-cos--default' + (equipped ? '' : ' kq-cos--equipped'));- def.appendChild(el('span', 'kq-cos-swatch kq-cos-swatch--default', '🙂'));- const dmeta = el('div', 'kq-cos-meta');- dmeta.appendChild(el('div', 'kq-cos-name', 'Default look'));- dmeta.appendChild(el('div', 'kq-cos-rarity', 'No cosmetic'));- def.appendChild(dmeta);- const dfoot = el('div', 'kq-cos-foot');- if (equipped) {- const b = el('button', 'kq-btn kq-cos-equip', 'Equip');- b.type = 'button';- b.addEventListener('click', () => this.opts.onUnequipCosmetic?.());- dfoot.appendChild(b);- } else {- dfoot.appendChild(el('span', 'kq-cos-equipped', '✓ Equipped'));- }- def.appendChild(dfoot);- grid.appendChild(def);-- for (const id of ownedIds) {- const c = this.cosmetics.get(id);+ // Build one wardrobe tile. `id` is '' for the Default-look tile. A click on the+ // tile body previews the look locally (no server round-trip); Equip commits it.+ const tile = (id) => {+ const c = id ? this.cosmetics.get(id) : null;const isEq = id === equipped;- const card = el('div', `kq-cos-card kq-cos--${c.rarity}${isEq ? ' kq-cos--equipped' : ''}`);- card.style.setProperty('--cos-accent', this._rarityColor(c.rarity));- card.appendChild(this._cosSwatch(c));+ const isPreview = this._previewId === id && !isEq;+ const rarityCls = c ? ` kq-cos--${c.rarity}` : ' kq-cos--default';+ // A div (not a button) so the real Equip button can nest inside it without+ // invalid button-in-button markup; role+tabindex+keydown keep it keyboard-usable.+ const card = el('div', 'kq-cos-card kq-cos-card--pick' + rarityCls+ + (isEq ? ' kq-cos--equipped' : '') + (isPreview ? ' kq-cos--preview' : ''));+ if (c) card.style.setProperty('--cos-accent', this._rarityColor(c.rarity));+ card.setAttribute('role', 'button');+ card.tabIndex = 0;+ card.setAttribute('aria-pressed', String(isEq));+ card.setAttribute('aria-label', `Preview ${c ? c.name : 'default look'}`);+ card.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this._previewCosmetic(id); } });+ if (c) card.appendChild(this._cosSwatch(c));+ else card.appendChild(el('span', 'kq-cos-swatch kq-cos-swatch--default', '🙂'));const meta = el('div', 'kq-cos-meta');- meta.appendChild(el('div', 'kq-cos-name', c.name));- meta.appendChild(el('div', 'kq-cos-rarity', this._rarityLabel(c.rarity)));+ meta.appendChild(el('div', 'kq-cos-name', c ? c.name : 'Default look'));+ meta.appendChild(el('div', 'kq-cos-rarity', c ? this._rarityLabel(c.rarity) : 'No cosmetic'));card.appendChild(meta);const foot = el('div', 'kq-cos-foot');if (isEq) {foot.appendChild(el('span', 'kq-cos-equipped', '✓ Equipped'));} else {- const b = el('button', 'kq-btn kq-cos-equip', 'Equip');+ const b = el('button', 'kq-btn kq-cos-equip', isPreview ? 'Equip ✓' : 'Equip');b.type = 'button';- b.addEventListener('click', () => this.opts.onEquipCosmetic?.(id));+ b.addEventListener('click', (e) => { e.stopPropagation(); this._commitCosmetic(id); });foot.appendChild(b);}card.appendChild(foot);- grid.appendChild(card);- }+ card.addEventListener('click', () => this._previewCosmetic(id));+ return card;+ };++ grid.appendChild(tile(''));+ for (const id of ownedIds) grid.appendChild(tile(id));frag.appendChild(grid);if (!ownedIds.length) {const empty = el('div', 'kq-empty kq-shop-empty');- empty.innerHTML = 'You don’t own any cosmetics yet.';- const go = el('button', 'kq-btn kq-btn-ghost', 'Browse the shop →');+ empty.innerHTML = 'You don\u2019t own any cosmetics yet.';+ const go = el('button', 'kq-btn kq-btn-ghost', 'Browse the shop \u2192');go.type = 'button';go.addEventListener('click', () => this._setShopTab('shop'));empty.appendChild(go);@@ -759,6 +765,23 @@ export class GameHud {return frag;}+ // Preview a wardrobe look on the local avatar (no server round-trip). Re-renders+ // so the previewed tile reads as selected.+ _previewCosmetic(id) {+ if (this._previewId === id) return;+ this._previewId = id;+ this.opts.onPreviewCosmetic?.(id);+ if (this._shopOpen && this._shopTab === 'wardrobe') this._renderShop();+ }++ // Commit the previewed look to the server (equip an id, or unequip for '').+ _commitCosmetic(id) {+ this._previewId = id;+ this.opts.onPreviewCosmetic?.(id); // keep the avatar showing it through the round-trip+ if (id) this.opts.onEquipCosmetic?.(id);+ else this.opts.onUnequipCosmetic?.();+ }+// A small visual chip for a cosmetic: auras glow, tints fill, props show their// emoji over a neutral chip — enough to tell looks apart at a glance._cosSwatch(c) {@@ -1030,19 +1053,19 @@ export class GameHud {const b = el('span', 'kq-market-busy'); b.innerHTML = `<span class="kq-spin"></span>${busy}`;right.appendChild(b);} else if (l.type === 'gold') {- const buy = el('button', 'kq-btn kq-btn-primary kq-market-buy', 'Buy');- buy.type = 'button';const afford = this.gold >= l.priceGold;- if (!afford) { buy.disabled = true; buy.classList.add('kq-btn-disabled'); buy.title = 'Not enough gold'; }+ const buy = el('button', 'kq-btn kq-market-buy' + (afford ? '' : ' kq-btn-disabled'), 'Buy');+ buy.type = 'button';+ buy.disabled = !afford;+ if (!afford) buy.title = `Need ${this._fmtGold(l.priceGold - this.gold)} more gold`;buy.addEventListener('click', () => this.opts.onMarketBuyGold?.(l.id));right.appendChild(buy);} else {// Token listing.if (!this.market.canToken) {- const note = el('span', 'kq-market-note', 'Connect a wallet to buy');- right.appendChild(note);+ right.appendChild(el('span', 'kq-market-note', 'Connect a wallet to buy'));} else {- const buy = el('button', 'kq-btn kq-btn-primary kq-market-buy', `Buy with ${this.market.token.symbol}`);+ const buy = el('button', 'kq-btn kq-market-buy', `Buy with ${this.market.token.symbol}`);buy.type = 'button';buy.addEventListener('click', () => this.opts.onMarketBuyToken?.(l.id));right.appendChild(buy);@@ -1114,14 +1137,17 @@ export class GameHud {row.append(qtyWrap, priceWrap);pane.appendChild(row);- const btn = el('button', 'kq-btn kq-btn-primary kq-market-listbtn', `List ${m.label} for gold`);+ const btn = el('button', 'kq-btn kq-market-listbtn', `List ${m.label} for gold`);btn.type = 'button';btn.addEventListener('click', () => {const qty = Math.max(1, Math.min(held, qtyInput.value | 0));const price = priceInput.value | 0;if (!(price >= 1)) { priceInput.focus(); priceInput.classList.add('kq-input-bad'); return; }+ if (!(qty >= 1)) { qtyInput.focus(); qtyInput.classList.add('kq-input-bad'); return; }this.opts.onMarketListGold?.(this._sellItem, qty, price);this._sellItem = '';+ // Switch to My Listings so they see the new listing immediately.+ this._setMarketTab('mine');});pane.appendChild(btn);pane.appendChild(el('p', 'kq-market-fineprint', 'Gold sales have no fee — you receive the full price.'));@@ -1158,7 +1184,7 @@ export class GameHud {row.append(goldWrap, usdWrap);pane.appendChild(row);- const btn = el('button', 'kq-btn kq-btn-primary kq-market-listbtn', `List gold for ${this.market.token.symbol}`);+ const btn = el('button', 'kq-btn kq-market-listbtn', `List gold for ${this.market.token.symbol}`);btn.type = 'button';btn.addEventListener('click', () => {const goldAmount = Math.max(1, Math.min(this.gold, goldInput.value | 0));@@ -1166,6 +1192,8 @@ export class GameHud {if (!(goldAmount >= 1)) { goldInput.focus(); goldInput.classList.add('kq-input-bad'); return; }if (!(usd >= 0.01)) { usdInput.focus(); usdInput.classList.add('kq-input-bad'); return; }this.opts.onMarketListToken?.(goldAmount, usd);+ // Switch to My Listings so they see the new listing immediately.+ this._setMarketTab('mine');});pane.appendChild(btn);pane.appendChild(el('p', 'kq-market-fineprint', `Buyers pay in ${this.market.token.symbol}. You receive ${100 - Number(feePct)}% to your wallet; ${feePct}% goes to the treasury.`));diff --git a/src/game/game-net.js b/src/game/game-net.jsindex 7cdb97279..e220f315c 100644--- a/src/game/game-net.js+++ b/src/game/game-net.js@@ -277,11 +277,18 @@ export class GameNet {// leaving the old means the old room's onLeave sees `room !== this.room` and// stays quiet, so the UI never flickers offline mid-portal. On failure we keep// the old room rather than stranding the player.+ //+ // onBeforeHandoff / onAfterHandoff are optional callbacks the scene injects for+ // the portal fade overlay — they are awaited so the blackout is solid before+ // the geometry swap and the fade-in starts only after the scene is rebuilt.async _handlePortal(to, reservation) {if (this._destroyed || this._transferring || !this.client) return;this._transferring = true;const old = this.room;try {+ // Fade out first, then do the room swap — so the player never sees a+ // half-rebuilt world flash.+ if (this.onBeforeHandoff) await this.onBeforeHandoff();const next = await this.client.consumeSeatReservation(reservation);this.room = next;this.sessionId = next.sessionId;@@ -298,6 +305,7 @@ export class GameNet {} catch (err) {console.warn('[game-net] portal handoff failed:', err?.message ?? err);this.room = old; // never left it — stay put+ if (this.onAfterHandoff) this.onAfterHandoff(); // always lift the fade} finally {this._transferring = false;}diff --git a/src/game/iso-game.css b/src/game/iso-game.cssindex 1a0486e23..80a58ed22 100644--- a/src/game/iso-game.css+++ b/src/game/iso-game.css@@ -41,6 +41,25 @@ body.kg-loading-cursor {cursor: progress;}+/* Portal fade-to-black overlay — covers the full viewport during realm handoffs+ so the geometry swap is invisible and the transition reads as intentional travel.+ Fades in on portal trigger (opacity 0→1), stays opaque while the new room loads,+ then fades out once _onHandoff fires (opacity 1→0). pointer-events auto blocks+ accidental clicks during the swap. */+#kg-portal-fade {+ position: fixed;+ inset: 0;+ z-index: 50;+ background: #000;+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.35s ease;+}+#kg-portal-fade.kg-fading-out {+ opacity: 1;+ pointer-events: auto;+}+/* DOM layer for projected nameplates (pointer-transparent). */#kg-labels {position: fixed;@@ -257,6 +276,9 @@ body.kg-loading-cursor {.kg-toast--fish {border-color: rgba(92, 182, 230, 0.5);}+.kg-toast--market {+ border-color: rgba(110, 231, 176, 0.5);+}/* Contextual action bar (cook at a Roast Pit, eat to heal). Buttons reveal onlywhen the action is actually possible; see _updateActions in iso-game.js. */@@ -1435,12 +1457,54 @@ body.kg-loading-cursor {font-weight: 800;}+/* XP drop chips — "+N XP" floaters that rise and fade on each XP earn.+ Anchored just below the topbar so they don't obscure the level-up cards. */+#kg-xpdrops {+ position: fixed;+ top: 54px;+ right: 20px;+ display: flex;+ flex-direction: column;+ align-items: flex-end;+ gap: 4px;+ pointer-events: none;+ z-index: 320;+}++.kg-xpdrop {+ padding: 3px 9px;+ border-radius: 20px;+ background: color-mix(in srgb, var(--kg-hue, #cdd6e6) 18%, rgba(13, 20, 32, 0.88));+ border: 1px solid color-mix(in srgb, var(--kg-hue, #cdd6e6) 35%, transparent);+ color: var(--kg-hue, #cdd6e6);+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.02em;+ white-space: nowrap;+ opacity: 0;+ transform: translateY(6px);+ transition: opacity 0.18s ease, transform 0.18s ease;+}++.kg-xpdrop--in {+ opacity: 1;+ transform: translateY(0);+ animation: kg-xpdrop-rise 1.2s ease forwards;+}++@keyframes kg-xpdrop-rise {+ 0% { opacity: 1; transform: translateY(0); }+ 70% { opacity: 1; transform: translateY(-14px); }+ 100% { opacity: 0; transform: translateY(-20px); }+}+@media (prefers-reduced-motion: reduce) {.kg-skills,.kg-skill,.kg-skill-bar i,.kg-levelup,- .kg-levelup-ico {+ .kg-levelup-ico,+ .kg-xpdrop {transition: none;animation: none;}@@ -2341,6 +2405,7 @@ body.kg-loading-cursor {.kq-btn-disabled, .kq-btn:disabled { background: rgba(255,255,255,0.08); color: var(--kg-dim); cursor: not-allowed; }.kq-btn-ghost { background: transparent; color: var(--kg-text); border: 1px solid var(--kg-line); margin-top: 12px; width: 100%; padding: 9px; }.kq-btn-ghost:hover { border-color: var(--kg-accent); opacity: 1; }+.kq-btn-primary { /* alias — .kq-btn already uses the primary fill */ }.kq-empty { font-size: 12px; color: var(--kg-dim); line-height: 1.5; padding: 8px 2px; }.kq-empty-good { color: var(--kg-text); background: rgba(110, 231, 135, 0.08); border: 1px solid rgba(110,231,135,0.3); border-radius: 10px; padding: 12px 14px; text-align: center; }@@ -2492,6 +2557,10 @@ body.kg-loading-cursor {transition: border-color .15s, transform .08s, background .15s;}.kq-cos-card.kq-cos--equipped { background: rgba(110,231,135,0.08); border-color: rgba(110,231,135,0.5); }+.kq-cos-card--pick { cursor: pointer; font: inherit; color: inherit; text-align: center; -webkit-appearance: none; appearance: none; }+.kq-cos-card--pick:hover { border-color: var(--cos-accent); transform: translateY(-1px); }+.kq-cos-card--pick:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }+.kq-cos-card.kq-cos--preview { border-color: var(--cos-accent); box-shadow: 0 0 0 1px var(--cos-accent) inset, 0 0 16px -4px var(--cos-accent); }.kq-cos-card.kq-cos--short { opacity: 0.78; }.kq-cos-swatch {width: 58px; height: 58px; border-radius: 50%; display: grid; place-items: center;diff --git a/src/game/iso-game.js b/src/game/iso-game.jsindex e2f161c54..f69b59858 100644--- a/src/game/iso-game.js+++ b/src/game/iso-game.js@@ -460,6 +460,10 @@ export class IsoGame {onBuyCosmetic: (id) => this.net?.buyCosmetic(id),onEquipCosmetic: (id) => this.net?.equipCosmetic(id),onUnequipCosmetic: () => this.net?.unequipCosmetic(),+ // Wardrobe try-before-equip: preview a look on the local avatar with no+ // server round-trip; null reverts to the server-authoritative equipped look.+ onPreviewCosmetic: (id) => this._previewLocalCosmetic(id),+ onStopPreview: () => this._previewLocalCosmetic(null),// Marketplace (Task 20): open fetches the live board; list/cancel/buy-gold// route straight to the authoritative server. A token buy is a multi-step// on-chain flow the controller drives (_buyTokenListing): quote → wallet@@ -551,6 +555,35 @@ export class IsoGame {this.scene.fog.near = isCave ? 16 : 48;this.scene.fog.far = isCave ? 70 : 120;+ // Scene lighting: underground the sun doesn't reach. Dim the directional+ // and hemi lights to near-zero, deepen the ambient, and scatter warm torch+ // PointLights around the cave so dark corners read as firelit rather than+ // just black. Restoring surface values on exit means the Mainland always+ // looks like open daylight again, never the cave's warmth.+ this._sun.intensity = isCave ? 0.0 : 1.25;+ this._hemi.intensity = isCave ? 0.06 : 1.0;+ this._ambient.intensity = isCave ? 0.18 : 0.28;+ this._ambient.color.set(isCave ? 0x4a3020 : 0xffffff);+ // Remove previous cave lights before adding new ones (handles realm→realm hop).+ for (const l of this._caveLights) this.scene.remove(l);+ this._caveLights = [];+ if (isCave) {+ // Torch positions: corners of each chamber + one near the entrance.+ // Colours alternate between deep orange and warm amber for visual variety.+ const torchTiles = [+ [4, 3, 0xff6a1a], [27, 3, 0xffaa30], [4, 9, 0xffaa30], [27, 9, 0xff6a1a],+ [4, 18, 0xff6a1a], [27, 18, 0xffaa30], [5, 27, 0xffaa30], [27, 27, 0xff6a1a],+ [16, 28, 0xffcc55], // entrance torch — brightest, marks the way out+ ];+ for (const [tx, ty, color] of torchTiles) {+ const pt = new PointLight(color, 2.8, 8.0, 1.4);+ const wp = this._tileToWorld(tx, ty);+ pt.position.set(wp.x, 1.6, wp.z);+ this.scene.add(pt);+ this._caveLights.push(pt);+ }+ }+// Ground plane with a subtle tile grid so movement is legible. The cave// uses a dark rock floor instead of grass.const ground = new Mesh(@@ -617,12 +650,16 @@ export class IsoGame {// Fishing + cooking spots, if the realm has them.this._paintTiles(layout.fishing, 0x3aa0d0, 0.6);this._paintTiles(layout.cooking, 0xff7a3a, 0.6);- // Portals. An open portal glows violet; a combat-gated one (e.g. the northern- // cave) is barred with a red archway so its locked state reads before you step on.+ // Portals. An open portal glows violet; a combat-gated one is barred with a+ // red archway. The mine entrance on the Mainland gets a cave-mouth arch so+ // it reads as a tunnel opening rather than a plain glowing tile.for (const p of layout.portals || []) {const tiles = this._rectTiles(p);if (p.gate) { this._paintTiles(tiles, 0xd0455a, 0.75); this._buildGateArch(p); }- else this._paintTiles(tiles, 0xae7bff, 0.7);+ else {+ this._paintTiles(tiles, 0xae7bff, 0.7);+ if (p.to === 'mine') this._buildMineEntrance(p);+ }}// Arena fittings: spectator stands (no-PvP), the practice boxing ring, and the// moving floor rollers — drawn with directional chevrons so the flow is legible.@@ -885,6 +922,38 @@ export class IsoGame {this.staticGroup.add(g);}+ // A jagged cave-mouth arch over the Mainland mine entrance so the portal reads+ // as a tunnel opening rather than a plain glowing tile. Rock-textured posts,+ // rough lintel, and a warm torch glow at the apex.+ _buildMineEntrance(p) {+ const cx = (p.x0 + p.x1) / 2, cy = (p.y0 + p.y1) / 2;+ const c = this._tileToWorld(cx, cy);+ const g = new Group();+ const rockMat = new MeshStandardMaterial({ map: this._rockTexture(), color: 0x5a4f40, roughness: 1 });+ const w = (p.x1 - p.x0 + 1) * TILE;+ // Posts — flanking pillars, slightly wider than a gate arch for a tunnel feel.+ const postGeo = new CylinderGeometry(0.22, 0.3, 2.6, 7);+ const left = new Mesh(postGeo, rockMat); left.position.set(-w / 2 - 0.1, 1.3, 0);+ const right = new Mesh(postGeo, rockMat); right.position.set(w / 2 + 0.1, 1.3, 0);+ // Keystone lintel — a chunky rock span across the top.+ const lintel = new Mesh(new BoxGeometry(w + 0.9, 0.55, 0.6), rockMat);+ lintel.position.set(0, 2.7, 0);+ // Rough cap stones on each post.+ const capGeo = new DodecahedronGeometry(0.32, 0);+ const capL = new Mesh(capGeo, rockMat); capL.position.set(-w / 2 - 0.1, 2.7, 0);+ const capR = new Mesh(capGeo, rockMat); capR.position.set(w / 2 + 0.1, 2.7, 0);+ for (const m of [left, right, lintel, capL, capR]) { m.castShadow = true; m.receiveShadow = true; }+ g.add(left, right, lintel, capL, capR);+ g.position.set(c.x, 0, c.z);+ this.staticGroup.add(g);+ // A warm torch-point at the keystone so the entrance glow reads even at+ // a distance — the mine is dark; this is the last light before you go in.+ const torch = new PointLight(0xff8c30, 2.2, 6.5, 1.6);+ torch.position.set(c.x, 3.1, c.z);+ this.scene.add(torch);+ this._caveLights.push(torch); // reuse the cave-lights list so it's cleaned on next _buildRealm+ }+// Spectator stands: a cool slate tint over the walkable seating tiles plus a corner// post at each end, so the stands read as off-floor (and the server keeps them PvP-free)._buildSeating(rects) {@@ -1043,6 +1112,31 @@ export class IsoGame {const server = this._resolveServerChoice();this.net = new GameNet({ name, avatar: netAvatar, realm, server, pid: this._playerId(), getPresence: getPresenceTicket });if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));++ // Fade-to-black during portal room swaps so the geometry rebuild is hidden.+ // onBeforeHandoff is awaited by _handlePortal, so the overlay is fully opaque+ // before the old room tears down. onAfterHandoff is called once _onHandoff+ // has cleared the dynamic views and the new realm is on its way in.+ this._portalFadeEl = document.getElementById('kg-portal-fade');+ this.net.onBeforeHandoff = () => new Promise((resolve) => {+ const el = this._portalFadeEl;+ if (!el) { resolve(); return; }+ el.classList.add('kg-fading-out');+ const done = () => { el.removeEventListener('transitionend', done); resolve(); };+ el.addEventListener('transitionend', done, { once: true });+ // Safety: resolve after transition duration + slack even if event misfires.+ setTimeout(resolve, 500);+ });+ this.net.onAfterHandoff = () => {+ // Brief pause so the scene has one frame to finish the geometry rebuild+ // before we reveal it, avoiding a half-populated flash.+ setTimeout(() => {+ const el = this._portalFadeEl;+ if (!el) return;+ el.classList.remove('kg-fading-out');+ }, 80);+ };+this.net.on('status', ({ status, error }) => this._onStatus(status, error));this.net.on('realm', (layout) => this._buildRealm(layout));this.net.on('items', (r) => this._onItems(r));@@ -1293,6 +1387,9 @@ export class IsoGame {this._lootTombId = null;this.myId = sessionId || this.net?.sessionId || this.myId;this._updateOnline();+ // Lift the blackout overlay once views are cleared — the new realm layout+ // arrives via the 'realm' message moments later and rebuilds the geometry.+ if (this.net?.onAfterHandoff) this.net.onAfterHandoff();}// ---------------------------------------------------------------- players@@ -1389,6 +1486,13 @@ export class IsoGame {this.q?.setShop(snapshot || null);}+ // Preview a cosmetic on the local avatar (wardrobe try-before-equip). `id` is+ // a cosmetic id or '' (default look); null clears the preview. Local-only —+ // peers see nothing until the player actually equips (server-authoritative).+ _previewLocalCosmetic(id) {+ this.players.get(this.myId)?.previewCosmetic(id);+ }+// ---------------------------------------------------------------- marketplace (Task 20)// Begin an on-chain token purchase. We allow one in flight at a time so the@@ -2396,12 +2500,65 @@ export class IsoGame {if (this._skillsOpen) this._renderSkills();}- // A real server 'levelup' event: refresh the panel snapshot (so its bar/level- // jump immediately) and fire a celebratory toast with the skill's icon.+ // Server pushes xpgain after every XP grant. Delta-patch the cached snapshot so+ // the panel stays live without a round-trip, then show a "+N XP" float chip.+ _onXpGain({ skill, amount, xp, level, levelXp, nextXp } = {}) {+ const meta = SKILL_META[skill];+ if (!meta || !Number.isFinite(amount)) return;+ if (this._skills?.skills?.[skill]) {+ const s = this._skills.skills[skill];+ s.xp = xp; s.level = level; s.levelXp = levelXp; s.nextXp = nextXp ?? null;+ } else if (!this._skills) {+ // Seed a minimal snapshot so the panel paints immediately on first open.+ this._skills = {+ cap: 99, total: null, average: null,+ skills: Object.fromEntries(SKILL_ORDER.map((sk) => [+ sk, { level: 1, xp: 0, levelXp: 0, nextXp: null },+ ])),+ };+ this._skills.skills[skill] = { xp, level, levelXp, nextXp: nextXp ?? null };+ }+ if (this._skillsOpen) this._renderSkills();+ this._showXpDrop(meta, amount);+ }++ // Float a "+N XP" chip near the Skills button. Rapid same-skill hits within 400ms+ // merge into the live chip instead of spawning a new one.+ _showXpDrop(meta, amount) {+ if (!this.hud.xpdrops) return;+ if (!this._xpDropQueue) this._xpDropQueue = new Map();+ const key = meta.label;+ const now = Date.now();+ const pending = this._xpDropQueue.get(key);+ if (pending && now - pending.ts < 400) {+ pending.amount += amount;+ pending.ts = now;+ if (pending.el) pending.el.textContent = `+${fmtXp(pending.amount)} XP`;+ return;+ }+ const el = document.createElement('div');+ el.className = 'kg-xpdrop';+ el.style.setProperty('--kg-hue', meta.hue);+ el.textContent = `+${fmtXp(amount)} XP`;+ this.hud.xpdrops.appendChild(el);+ const entry = { amount, ts: now, el };+ this._xpDropQueue.set(key, entry);+ requestAnimationFrame(() => el.classList.add('kg-xpdrop--in'));+ setTimeout(() => {+ this._xpDropQueue?.delete(key);+ entry.el = null;+ el.classList.remove('kg-xpdrop--in');+ setTimeout(() => el.remove(), 350);+ }, 1200);+ }++ // A real server 'levelup' event: patch the cached snapshot level and celebrate.+ // No longer needs a round-trip skills() request — xpgain keeps bars current._onLevelup({ skill, level } = {}) {const meta = SKILL_META[skill];if (!meta || !Number.isFinite(level)) return;- this.net?.skills(); // pull fresh XP so an open panel reflects the new level+ if (this._skills?.skills?.[skill]) this._skills.skills[skill].level = level;+ if (this._skillsOpen) this._renderSkills();const cap = this._skills?.cap || 99;const maxed = level >= cap;@@ -2419,13 +2576,11 @@ export class IsoGame {setTimeout(() => { el.classList.remove('kg-levelup--in'); setTimeout(() => el.remove(), 420); }, 3400);}- // Open/close the skills drawer. `force` (true/false) sets an explicit state;- // omitting it toggles. On open we pull a fresh snapshot and start a light poll- // so XP bars fill in real time as the player gathers/fights.+ // Open/close the skills drawer. Panel is event-driven via xpgain — one snapshot+ // request on open seeds it; no poll needed._toggleSkills(force) {const next = force === undefined ? !this._skillsOpen : !!force;if (next === this._skillsOpen) return;- // Only meaningful in the world; ignore opens from the start/offline screens.if (next && this.phase !== 'world') return;this._skillsOpen = next;@@ -2435,19 +2590,14 @@ export class IsoGame {if (next) {panel.hidden = false;- void panel.offsetWidth; // reflow so the slide-in transition runs+ void panel.offsetWidth;panel.classList.add('kg-skills--open');- this._renderSkills(); // paint cached data (or the loading row)- this.net?.skills(); // and request the freshest snapshot- clearInterval(this._skillsTimer);- this._skillsTimer = setInterval(() => this.net?.skills(), 1500);+ this._renderSkills();+ this.net?.skills();this.hud.skillsClose?.focus();} else {panel.classList.remove('kg-skills--open');- clearInterval(this._skillsTimer);- this._skillsTimer = null;if (document.activeElement && panel.contains(document.activeElement)) this.hud.skillsBtn?.focus();- // Hide after the slide-out so it isn't focusable mid-transition.setTimeout(() => { if (!this._skillsOpen) panel.hidden = true; }, 220);}}@@ -2764,6 +2914,7 @@ export class IsoGame {skillsAvg: document.getElementById('kg-skills-avg'),skillsCap: document.getElementById('kg-skills-cap'),levelups: document.getElementById('kg-levelups'),+ xpdrops: document.getElementById('kg-xpdrops'),actions: document.getElementById('kg-actions'),cookBtn: document.getElementById('kg-cook'),eatBtn: document.getElementById('kg-eat'),