Skip to content

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.

feat: game-hud/iso-game/walk/friends/play-gate/spin-wheel refinements, marketplace-store test

nirholas741714bb76ce
diff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.js
index 4f885725e..8eee14f3d 100644
--- a/multiplayer/src/rooms/GameRoom.js
+++ b/multiplayer/src/rooms/GameRoom.js
@@ -1809,7 +1809,7 @@ export class GameRoom extends Room {
if (priv.cosmetics) {
next.cosmetics = { owned: [...priv.cosmetics.owned], equipped: priv.cosmetics.equipped };
}
- if (priv.spin) next.spin = { nextFreeSpinAt: priv.spin.nextFreeSpinAt | 0 };
+ if (priv.spin) next.spin = { nextFreeSpinAt: priv.spin.nextFreeSpinAt || 0 };
savePlayer(priv.playerId, next);
}
@@ -2109,25 +2109,22 @@ export class GameRoom extends Room {
const priv = this.priv.get(client.sessionId);
if (!p || !priv) return;
if (!this._rateOk(client.sessionId, 'mkt')) return;
- if (!tokenConfigured()) { client.send('notice', { kind: 'market', text: 'Token payments are unavailable.' }); return; }
+ const id = String(payload?.id ?? '');
+ // Every rejection clears the client's per-listing "Preparing…" spinner.
+ const fail = (text) => { client.send('notice', { kind: 'market', text }); client.send('marketBuyFail', { id }); };
+ if (!tokenConfigured()) { fail('Token payments are unavailable.'); return; }
const buyerWallet = priv.playerId;
- if (!isWalletAddress(buyerWallet)) {
- client.send('notice', { kind: 'market', text: 'Connect a Solana wallet to pay with tokens.' });
- return;
- }
- const l = marketplaceStore.get(String(payload?.id ?? ''));
- if (!l || l.type !== 'goldForToken' || l.status !== 'active') {
- client.send('notice', { kind: 'market', text: 'That listing is no longer available.' });
- return;
- }
- if (l.seller === buyerWallet) { client.send('notice', { kind: 'market', text: "You can't buy your own listing." }); return; }
+ if (!isWalletAddress(buyerWallet)) { fail('Connect a Solana wallet to pay with tokens.'); return; }
+ const l = marketplaceStore.get(id);
+ if (!l || l.type !== 'goldForToken' || l.status !== 'active') { fail('That listing is no longer available.'); return; }
+ if (l.seller === buyerWallet) { fail("You can't buy your own listing."); return; }
const quote = await quoteTokenForUsd(l.priceUsd);
- if (!quote) { client.send('notice', { kind: 'market', text: 'Live price unavailable — try again in a moment.' }); return; }
+ if (!quote) { fail('Live price unavailable — try again in a moment.'); return; }
// Re-check the listing survived the awaited quote (it could have been bought
// or cancelled while we fetched the price).
const still = marketplaceStore.get(l.id);
- if (!still || still.status !== 'active') { client.send('notice', { kind: 'market', text: 'That listing is no longer available.' }); return; }
+ if (!still || still.status !== 'active') { fail('That listing is no longer available.'); return; }
const { seller: sellerRaw, treasury: treasuryRaw } = splitAmount(quote.raw, MARKET_TREASURY_BPS);
let txB64;
@@ -2138,7 +2135,7 @@ export class GameRoom extends Room {
});
} catch (err) {
console.warn('[market] build split tx failed:', err?.message);
- client.send('notice', { kind: 'market', text: 'Could not prepare the payment. Try again.' });
+ fail('Could not prepare the payment. Try again.');
return;
}
const signed = signQuote({
@@ -2170,18 +2167,17 @@ export class GameRoom extends Room {
if (!p || !priv) return;
if (!this._rateOk(client.sessionId, 'mkt')) return;
const q = verifyQuote(payload?.quote);
- if (!q) { client.send('notice', { kind: 'market', text: 'Your quote expired — get a fresh one.' }); return; }
- if (q.buyer !== priv.playerId) { client.send('notice', { kind: 'market', text: 'That quote was issued to a different wallet.' }); return; }
+ const failId = q?.listingId || String(payload?.id ?? '');
+ const fail = (text) => { client.send('notice', { kind: 'market', text }); client.send('marketBuyFail', { id: failId }); };
+ if (!q) { fail('Your quote expired — get a fresh one.'); return; }
+ if (q.buyer !== priv.playerId) { fail('That quote was issued to a different wallet.'); return; }
const txSig = typeof payload?.txSig === 'string' ? payload.txSig.trim() : '';
- if (!txSig) { client.send('notice', { kind: 'market', text: 'Missing transaction signature.' }); return; }
- if (marketplaceStore.isSettled(txSig)) { client.send('notice', { kind: 'market', text: 'That payment was already settled.' }); return; }
+ if (!txSig) { fail('Missing transaction signature.'); return; }
+ if (marketplaceStore.isSettled(txSig)) { fail('That payment was already settled.'); return; }
const l = marketplaceStore.get(q.listingId);
- if (!l || l.type !== 'goldForToken' || l.sellerWallet !== q.sellerWallet) {
- client.send('notice', { kind: 'market', text: 'That listing is no longer available.' });
- return;
- }
- if (l.status !== 'active') { client.send('notice', { kind: 'market', text: 'That listing is no longer available.' }); return; }
+ if (!l || l.type !== 'goldForToken' || l.sellerWallet !== q.sellerWallet) { fail('That listing is no longer available.'); return; }
+ if (l.status !== 'active') { fail('That listing is no longer available.'); return; }
// Claim it synchronously before the async verify so a second settle can't
// double-release the same gold. Reverted to active if verification fails.
marketplaceStore.update(l.id, { status: 'settling' });
@@ -2192,7 +2188,7 @@ export class GameRoom extends Room {
const current = marketplaceStore.get(l.id);
if (!current || current.status !== 'settling') {
// Cancelled/evicted out from under us mid-verify — don't release.
- client.send('notice', { kind: 'market', text: 'That listing is no longer available.' });
+ fail('That listing is no longer available.');
return;
}
if (!verify.ok) {
@@ -2200,7 +2196,7 @@ export class GameRoom extends Room {
const why = verify.reason === 'not_found' ? 'Payment not found on-chain yet — wait for confirmation and retry.'
: verify.reason?.includes('underpaid') ? 'The payment amount did not match the quote.'
: 'Could not verify the payment. No gold was released.';
- client.send('notice', { kind: 'market', text: why });
+ fail(why);
return;
}
// Verified. Consume the signature, close the listing, deliver the gold.
@@ -2251,7 +2247,7 @@ export class GameRoom extends Room {
reason,
avgLevel: Math.round(this._averageLevel(p) * 10) / 10,
minLevel: SPIN_MIN_AVG_LEVEL,
- nextFreeSpinAt: priv.spin.nextFreeSpinAt | 0,
+ nextFreeSpinAt: priv.spin.nextFreeSpinAt || 0,
now: Date.now(),
});
}
@@ -2271,7 +2267,7 @@ export class GameRoom extends Room {
minLevel: SPIN_MIN_AVG_LEVEL,
eligible: avg >= SPIN_MIN_AVG_LEVEL,
atWheel: this._atWheel(p),
- nextFreeSpinAt: priv.spin.nextFreeSpinAt | 0,
+ nextFreeSpinAt: priv.spin.nextFreeSpinAt || 0,
now: Date.now(),
costUsd: PAID_SPIN_USD,
symbol: TOKEN_SYMBOL,
@@ -2315,7 +2311,7 @@ export class GameRoom extends Room {
const reason = this._spinBlockReason(p);
if (reason) { this._sendSpinDenied(client, p, priv, 'free', reason); return; }
const now = Date.now();
- if (now < (priv.spin.nextFreeSpinAt | 0)) {
+ if (now < (priv.spin.nextFreeSpinAt || 0)) {
this._sendSpinDenied(client, p, priv, 'free', 'cooldown');
return;
}
@@ -2395,7 +2391,7 @@ export class GameRoom extends Room {
markSpinSettled(txSig);
const result = this._rollAndAward(client, p);
this._persistPlayer(client.sessionId);
- client.send('spinResult', { mode: 'paid', ...result, txSig, nextFreeSpinAt: priv.spin.nextFreeSpinAt | 0, now: Date.now() });
+ client.send('spinResult', { mode: 'paid', ...result, txSig, nextFreeSpinAt: priv.spin.nextFreeSpinAt || 0, now: Date.now() });
}
// Credit a seller their gold proceeds. If they're online (in this room or any
@@ -2460,13 +2456,6 @@ export class GameRoom extends Room {
// ----- marketplace item helpers ----------------------------------------
- // Total quantity of `item` the player holds in their backpack (not hotbar).
- _countInvItem(p, item) {
- let n = 0;
- for (const s of p.inv) if (s.item === item) n += s.qty;
- return n;
- }
-
// Remove up to `qty` of `item` from the backpack, emptying slots as they drain.
// Returns the quantity actually removed (< qty if the player didn't have enough).
_removeInvItem(p, item, qty) {
diff --git a/public/features.json b/public/features.json
index 99f9009c5..d8f6a2c8d 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-01T03:35:16.249Z",
+ "generated_at": "2026-06-01T04:14:50.101Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/friends.js b/src/friends.js
index 3cd3ad449..e62dc5b6d 100644
--- a/src/friends.js
+++ b/src/friends.js
@@ -122,11 +122,21 @@ export class FriendsClient {
}
if (!res.ok) throw new Error(`friends ${res.status}`);
const { data } = await res.json();
+ const sig = graphSignature(data);
+ const first = !this.loaded;
this.friends = data.friends || [];
this.incoming = data.incoming || [];
this.outgoing = data.outgoing || [];
this.loaded = true;
this.loadError = null;
+ // Only repaint when something actually changed — a 20s presence/unread
+ // poll that returns identical state must not rebuild the panel (and reset
+ // a half-typed search / DM caret).
+ if (first || sig !== this._graphSig) {
+ this._graphSig = sig;
+ this._emit();
+ }
+ return;
} catch (err) {
this.loadError = 'network';
this.loaded = true;
@@ -215,8 +225,13 @@ export class FriendsClient {
});
if (!res.ok) throw new Error(`thread ${res.status}`);
const { data } = await res.json();
- this.threads.set(friendId, data.messages || []);
- if (!quiet || this.openWith === friendId) this._emit();
+ const next = data.messages || [];
+ const prev = this.threads.get(friendId) || [];
+ const changed = next.length !== prev.length || next[next.length - 1]?.id !== prev[prev.length - 1]?.id;
+ this.threads.set(friendId, next);
+ // A quiet poll that found no new messages must not repaint — otherwise the
+ // open composer rebuilds every few seconds and steals the caret.
+ if (changed || !quiet) this._emit();
} catch (err) {
if (!quiet) console.warn('[friends] thread load failed:', err?.message);
}
@@ -286,6 +301,15 @@ export class FriendsClient {
}
}
+// Compact fingerprint of the graph payload so refresh() can skip a repaint when
+// a poll returns identical state (presence, realm, unread, and membership).
+function graphSignature(data) {
+ const f = (data.friends || []).map((x) => `${x.id}:${x.online ? 1 : 0}:${x.realm || ''}:${x.unread || 0}`).join('|');
+ const i = (data.incoming || []).map((x) => x.id).join('|');
+ const o = (data.outgoing || []).map((x) => x.id).join('|');
+ return `${f}#${i}#${o}`;
+}
+
// One shared client per page — the panel and the net wiring both reference it.
let _client = null;
export function friendsClient() {
diff --git a/src/game/game-hud.js b/src/game/game-hud.js
index 6f340625b..be7cc3ed3 100644
--- a/src/game/game-hud.js
+++ b/src/game/game-hud.js
@@ -1088,7 +1088,7 @@ export class GameHud {
row.append(qtyWrap, priceWrap);
pane.appendChild(row);
- const btn = el('button', 'kq-btn kq-btn-primary kq-market-list', `List ${m.label} for gold`);
+ const btn = el('button', 'kq-btn kq-btn-primary 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));
@@ -1132,7 +1132,7 @@ export class GameHud {
row.append(goldWrap, usdWrap);
pane.appendChild(row);
- const btn = el('button', 'kq-btn kq-btn-primary kq-market-list', `List gold for ${this.market.token.symbol}`);
+ const btn = el('button', 'kq-btn kq-btn-primary 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));
diff --git a/src/game/iso-controls.js b/src/game/iso-controls.js
index 34ee09bf8..f06cb4b1d 100644
--- a/src/game/iso-controls.js
+++ b/src/game/iso-controls.js
@@ -96,10 +96,16 @@ export class IsoControls {
this._mounted = true;
this._buildGear();
+ this._buildFriendsButton();
window.addEventListener('keydown', this._onKeyDown, true);
this._unsub = this.kb.subscribe(() => this._onBindingsChanged());
+ // Keep the HUD unread badge live whether or not the panel is open. A single
+ // background load seeds existing unread; live DM events keep it current.
+ this._friendsUnsub = this._friends.subscribe(() => this._updateFriendsBadge());
+ this._friends.refresh();
+
// Poll for the network connection + phase changes. Cheap (5Hz) and only
// needs to wire the net bus once; visibility follows game.phase.
this._syncTimer = setInterval(this._sync, 200);
@@ -113,6 +119,10 @@ export class IsoControls {
this.kb.setAccount(localStorage.getItem('cc-name') || '');
game.net.on('playerAdd', (p, id) => this._onPlayer(p, id));
game.net.on('playerChange', (p, id) => this._onPlayer(p, id));
+ // Friends realtime (Task 15): live DMs + request/accept events arrive on
+ // whatever realm room this account is connected to; hand them to the
+ // shared friends client so the panel + unread badge update instantly.
+ game.net.on('social', (m) => this._friends.handleSocial(m));
}
// A reconnect builds a fresh GameNet; rebind against the new bus.
if (game.net && this._boundNet && this._boundNet !== game.net) {
@@ -125,6 +135,7 @@ export class IsoControls {
_applyPhase(phase) {
const world = phase === 'world';
if (this._gearEl) this._gearEl.hidden = !world;
+ if (this._friendsBtn) this._friendsBtn.hidden = !world;
if (world && !this._hintDone) {
this._updateHint();
this._hintDone = true;
@@ -188,6 +199,40 @@ export class IsoControls {
else document.body.appendChild(this._gearEl);
}
+ // -------------------------------------------------------------- friends button
+ // A topbar entry point for the friends panel (Task 15), alongside the F hotkey.
+ // Carries a live unread badge so a new DM is noticeable without opening it.
+ _buildFriendsButton() {
+ this._friendsBadge = el('span', { class: 'kg-fr-hudbadge', hidden: true, 'aria-hidden': 'true' });
+ this._friendsBtn = el(
+ 'button',
+ {
+ id: 'kg-friends-btn',
+ class: 'kg-iconbtn',
+ type: 'button',
+ hidden: true,
+ 'aria-haspopup': 'dialog',
+ 'aria-controls': 'kg-ov-friends',
+ 'aria-label': 'Friends',
+ title: 'Friends (F)',
+ onclick: () => this._toggle('friends'),
+ },
+ ['👥', this._friendsBadge],
+ );
+ const bar = document.getElementById('kg-topbar');
+ if (this._gearEl && this._gearEl.parentNode) this._gearEl.parentNode.insertBefore(this._friendsBtn, this._gearEl);
+ else if (bar) bar.appendChild(this._friendsBtn);
+ else document.body.appendChild(this._friendsBtn);
+ }
+
+ _updateFriendsBadge() {
+ if (!this._friendsBadge) return;
+ const n = this._friends.totalUnread;
+ this._friendsBadge.textContent = n > 9 ? '9+' : String(n);
+ this._friendsBadge.hidden = n <= 0;
+ this._friendsBtn?.classList.toggle('kg-iconbtn--alert', n > 0);
+ }
+
// -------------------------------------------------------------- keyboard
_onKeyDown(e) {
if (this._capture) {
@@ -330,6 +375,10 @@ export class IsoControls {
clearInterval(this._mapTimer);
this._mapTimer = null;
}
+ if (key === 'friends' && this._friendsPanel) {
+ this._friendsPanel.unmount();
+ this._friendsPanel = null;
+ }
if (this._capture && key === 'settings') this._capture = null;
const back = this._lastFocus;
if (back && document.contains(back)) back.focus();
@@ -351,7 +400,7 @@ export class IsoControls {
_ensureSurface(key) {
if (this._surfaces[key]) return this._surfaces[key];
- const titles = { inv: 'Inventory', map: 'Map', settings: 'Controls' };
+ const titles = { inv: 'Inventory', map: 'Map', settings: 'Controls', friends: 'Friends' };
const title = titles[key] || PLACEHOLDERS[key]?.title || key;
const closeBtn = el(
'button',
@@ -400,6 +449,7 @@ export class IsoControls {
if (key === 'inv') this._renderInv();
else if (key === 'map') this._renderMap();
else if (key === 'settings') this._renderControls();
+ else if (key === 'friends') this._mountFriends();
else this._renderPlaceholder(key);
}
@@ -524,6 +574,20 @@ export class IsoControls {
}
}
+ // -------------------------------------------------------------- friends
+ // Lazily mount the friends panel into its surface body on first open; reuse it
+ // thereafter. The panel owns its own polling/realtime lifecycle via mount()/
+ // unmount() (the latter fires from _close).
+ _mountFriends() {
+ const body = this._surfaces.friends?.body;
+ if (!body) return;
+ if (!this._friendsPanel) {
+ body.innerHTML = '';
+ this._friendsPanel = new FriendsPanel(body);
+ }
+ this._friendsPanel.mount();
+ }
+
// -------------------------------------------------------------- placeholder
_renderPlaceholder(key) {
const meta = PLACEHOLDERS[key];
@@ -739,7 +803,11 @@ export class IsoControls {
clearInterval(this._syncTimer);
if (this._mapTimer) clearInterval(this._mapTimer);
this._unsub?.();
+ this._friendsUnsub?.();
+ this._friendsPanel?.unmount();
+ this._friendsPanel = null;
this._gearEl?.remove();
+ this._friendsBtn?.remove();
for (const k of Object.keys(this._surfaces)) this._surfaces[k].overlay.remove();
this._surfaces = {};
this._mounted = false;
diff --git a/src/game/iso-game.css b/src/game/iso-game.css
index 3ee9768ca..740264172 100644
--- a/src/game/iso-game.css
+++ b/src/game/iso-game.css
@@ -2435,10 +2435,118 @@ body.kg-loading-cursor {
.kq-gold .kq-gold-ic + b { display: inline; }
}
+/* Marketplace (Task 20) — player-to-player trading: Buy / Sell / My Listings. */
+.kq-market-card { max-width: 640px; }
+.kq-market-head { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; padding-right: 34px; }
+.kq-market-head h2 { margin: 0; font-size: 17px; font-weight: 800; }
+.kq-market-tabs { display: flex; gap: 6px; margin-bottom: 14px; }
+.kq-market-tab {
+ flex: 1; cursor: pointer; font: inherit; font-size: 13px; font-weight: 700; padding: 8px 10px;
+ color: var(--kg-dim); background: rgba(255,255,255,0.04); border: 1px solid var(--kg-line);
+ border-radius: 10px; transition: color .15s, border-color .15s, background .15s;
+}
+.kq-market-tab:hover { color: var(--kg-text); border-color: var(--kg-accent); }
+.kq-market-tab:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
+.kq-market-tab--on { color: #0d1420; background: var(--kg-text); border-color: var(--kg-text); }
+.kq-market-body { min-height: 240px; }
+.kq-market-pane { display: flex; flex-direction: column; gap: 12px; }
+
+/* Buy controls */
+.kq-market-controls { display: flex; gap: 8px; }
+.kq-market-search {
+ flex: 1; font: inherit; font-size: 13px; padding: 8px 11px; color: var(--kg-text);
+ background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 9px;
+}
+.kq-market-search::placeholder { color: var(--kg-dim); }
+.kq-market-search:focus-visible, .kq-market-input:focus-visible, .kq-market-sort:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 1px; }
+.kq-market-sort {
+ font: inherit; font-size: 13px; padding: 8px 10px; color: var(--kg-text);
+ background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 9px; cursor: pointer;
+}
+
+/* Listing list + rows */
+.kq-market-list { display: flex; flex-direction: column; gap: 8px; }
+.kq-market-card-row {
+ display: flex; align-items: center; gap: 12px; padding: 10px 12px;
+ background: rgba(255,255,255,0.035); border: 1px solid var(--kg-line); border-radius: 12px;
+ transition: border-color .15s, background .15s;
+}
+.kq-market-card-row:hover { border-color: rgba(255,255,255,0.22); }
+.kq-market-mine { opacity: 0.82; }
+.kq-market-ic {
+ flex: 0 0 auto; width: 40px; height: 40px; display: grid; place-items: center; font-size: 22px;
+ background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 10px;
+}
+.kq-market-info { flex: 1 1 auto; min-width: 0; }
+.kq-market-title { font-size: 14px; font-weight: 800; color: var(--kg-text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.kq-market-sub { font-size: 11px; color: var(--kg-dim); margin-top: 2px; }
+.kq-market-seller { font-variant-numeric: tabular-nums; }
+.kq-market-right { flex: 0 0 auto; display: flex; flex-direction: column; align-items: flex-end; gap: 6px; }
+.kq-market-price { font-size: 14px; font-weight: 800; color: #ffce5c; font-variant-numeric: tabular-nums; display: flex; align-items: baseline; gap: 5px; }
+.kq-market-coin { font-size: 12px; }
+.kq-market-usd { color: #6ee7b0; }
+.kq-market-token { font-size: 10px; font-weight: 700; color: var(--kg-dim); text-transform: uppercase; letter-spacing: .05em; }
+.kq-market-buy { background: #6ee7b0; color: #062017; padding: 6px 14px; white-space: nowrap; }
+.kq-market-buy.kq-btn-disabled { background: rgba(255,255,255,0.08); color: var(--kg-dim); }
+.kq-market-badge { font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: .08em; color: var(--kg-dim); }
+.kq-market-note { font-size: 11px; color: var(--kg-dim); max-width: 120px; text-align: right; line-height: 1.35; }
+.kq-market-busy { display: inline-flex; align-items: center; gap: 7px; font-size: 12px; font-weight: 700; color: #ffce5c; }
+.kq-spin { width: 12px; height: 12px; border: 2px solid rgba(255,206,92,0.35); border-top-color: #ffce5c; border-radius: 50%; animation: kq-spin 0.7s linear infinite; }
+@keyframes kq-spin { to { transform: rotate(360deg); } }
+
+/* Status labels (My Listings) */
+.kq-market-statlbl { font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .06em; color: var(--kg-dim); }
+.kq-market-statlbl--active { color: #6ee7b0; }
+.kq-market-statlbl--sold { color: #ffce5c; text-transform: none; letter-spacing: 0; }
+.kq-market-statlbl--cancelled { color: #ff9a9a; }
+.kq-market-cancel { margin-top: 0; width: auto; padding: 5px 12px; }
+.kq-market-status-sold, .kq-market-status-cancelled { opacity: 0.7; }
+
+/* Sell form */
+.kq-market-modes { display: flex; gap: 6px; }
+.kq-market-mode {
+ flex: 1; cursor: pointer; font: inherit; font-size: 12px; font-weight: 700; padding: 8px;
+ color: var(--kg-dim); background: rgba(255,255,255,0.04); border: 1px solid var(--kg-line); border-radius: 9px;
+ transition: color .15s, border-color .15s, background .15s;
+}
+.kq-market-mode:hover { color: var(--kg-text); border-color: var(--kg-accent); }
+.kq-market-mode--on { color: #0d1420; background: var(--kg-text); border-color: var(--kg-text); }
+.kq-market-sellform { display: flex; flex-direction: column; gap: 12px; }
+.kq-market-label { font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .1em; color: var(--kg-dim); }
+.kq-market-pick { display: grid; grid-template-columns: repeat(6, 1fr); gap: 6px; }
+.kq-market-pickcell.kq-cell--on { border-color: #6ee7b0; background: rgba(110,231,176,0.12); }
+.kq-market-fields { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
+.kq-market-field { display: flex; flex-direction: column; gap: 5px; }
+.kq-market-field-lbl { font-size: 11px; font-weight: 700; color: var(--kg-dim); }
+.kq-market-input {
+ font: inherit; font-size: 14px; padding: 9px 11px; color: var(--kg-text);
+ background: rgba(255,255,255,0.05); border: 1px solid var(--kg-line); border-radius: 9px; width: 100%;
+}
+.kq-market-input.kq-input-bad { border-color: #ff9a9a; }
+.kq-market-listbtn { width: 100%; padding: 11px; font-size: 13px; background: #6ee7b0; color: #062017; }
+.kq-market-hint { font-size: 12px; color: var(--kg-dim); line-height: 1.5; text-align: center; padding: 18px 8px; }
+.kq-market-fineprint { font-size: 11px; color: var(--kg-dim); line-height: 1.45; margin: 0; text-align: center; }
+
+/* Empty / error / skeleton states */
+.kq-market-empty { display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; padding: 36px 16px; color: var(--kg-dim); }
+.kq-market-empty p { margin: 0; font-size: 14px; color: var(--kg-text); }
+.kq-market-empty span { font-size: 12px; color: var(--kg-dim); max-width: 320px; line-height: 1.5; }
+.kq-market-empty-ic { font-size: 38px; opacity: 0.85; }
+.kq-market-empty .kq-btn-ghost { margin-top: 4px; width: auto; }
+.kq-market-err p { color: #ffb4b4; }
+.kq-market-skel { height: 60px; background: linear-gradient(90deg, rgba(255,255,255,0.04), rgba(255,255,255,0.08), rgba(255,255,255,0.04)); background-size: 200% 100%; animation: kq-shimmer 1.2s ease-in-out infinite; border-color: transparent; }
+@keyframes kq-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+
+@media (max-width: 480px) {
+ .kq-market-pick { grid-template-columns: repeat(5, 1fr); }
+ .kq-market-fields { grid-template-columns: 1fr; }
+ .kq-market-card-row { gap: 9px; padding: 9px 10px; }
+}
+
@media (prefers-reduced-motion: reduce) {
- .kq-panel, .kq-progress i, .kq-tool-btn, .kq-slot, .kq-cell, .kq-build-menu, .kq-shop-tab, .kq-cos-card { transition: none; }
+ .kq-panel, .kq-progress i, .kq-tool-btn, .kq-slot, .kq-cell, .kq-build-menu, .kq-shop-tab, .kq-cos-card, .kq-market-tab, .kq-market-mode { transition: none; }
.kq-modal-card, .kq-build-banner { animation: none; }
- .kq-npc-marker, .kq-dot { animation: none; }
+ .kq-npc-marker, .kq-dot, .kq-spin, .kq-market-skel { animation: none; }
}
/* Loot + mount toasts (Task 09). Mount drops get a celebratory violet accent;
@@ -2516,3 +2624,650 @@ body.kg-loading-cursor {
outline: 2px solid var(--kg-accent);
outline-offset: 2px;
}
+
+/* ----- Wheel of Fortune (Task 19) ----------------------------------------- */
+.kg-wheel-label .kg-npc-tag {
+ background: rgba(245, 197, 66, 0.22); border-color: rgba(245, 197, 66, 0.55); color: #ffe6ad;
+}
+.kg-casino-label .kg-npc-tag {
+ background: rgba(150, 50, 110, 0.5); border-color: rgba(255, 180, 220, 0.45); color: #ffd9ee;
+ letter-spacing: 0.04em; text-transform: uppercase; font-size: 11px;
+}
+
+.kg-spin-overlay {
+ position: fixed; inset: 0; z-index: 40; display: flex; align-items: center; justify-content: center;
+ background: rgba(6, 9, 16, 0.72); backdrop-filter: blur(4px); padding: 16px;
+ animation: kg-spin-fade .18s ease-out;
+}
+@keyframes kg-spin-fade { from { opacity: 0; } to { opacity: 1; } }
+
+.kg-spin-card {
+ width: min(440px, 96vw); max-height: 94vh; overflow: auto;
+ background: linear-gradient(180deg, rgba(22, 28, 42, 0.98), rgba(13, 18, 30, 0.98));
+ border: 1px solid var(--kg-line); border-radius: 18px; color: var(--kg-text);
+ box-shadow: 0 24px 70px rgba(0,0,0,0.6), inset 0 1px 0 rgba(255,255,255,0.05);
+ padding: 18px 18px 20px; display: flex; flex-direction: column; gap: 14px;
+}
+.kg-spin-card.kg-spin-flash { animation: kg-spin-flash .4s ease-out; }
+@keyframes kg-spin-flash { 0% { box-shadow: 0 0 0 2px var(--kg-accent); } 100% { box-shadow: 0 24px 70px rgba(0,0,0,0.6); } }
+
+.kg-spin-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
+.kg-spin-title { font-size: 18px; font-weight: 800; display: flex; flex-direction: column; gap: 2px; }
+.kg-spin-sub2 { font-size: 11px; font-weight: 600; color: var(--kg-dim); letter-spacing: 0.03em; text-transform: uppercase; }
+.kg-spin-close {
+ flex: 0 0 auto; width: 30px; height: 30px; border-radius: 8px; cursor: pointer;
+ background: rgba(255,255,255,0.06); border: 1px solid var(--kg-line); color: var(--kg-dim);
+ font-size: 15px; line-height: 1; transition: background .15s, color .15s, border-color .15s;
+}
+.kg-spin-close:hover { background: rgba(255,255,255,0.14); color: var(--kg-text); border-color: var(--kg-accent); }
+.kg-spin-close:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
+
+.kg-spin-wheelwrap { position: relative; align-self: center; width: 300px; height: 300px; }
+.kg-spin-canvas { width: 300px; height: 300px; display: block; filter: drop-shadow(0 10px 26px rgba(0,0,0,0.5)); }
+.kg-spin-pointer {
+ position: absolute; top: -4px; left: 50%; transform: translateX(-50%);
+ width: 0; height: 0; border-left: 13px solid transparent; border-right: 13px solid transparent;
+ border-top: 22px solid #ff5a3a; filter: drop-shadow(0 2px 3px rgba(0,0,0,0.6)); z-index: 2;
+}
+.kg-spin-hub {
+ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);
+ width: 44px; height: 44px; border-radius: 50%; display: flex; align-items: center; justify-content: center;
+ background: radial-gradient(circle at 35% 30%, #fff6da, #e0b54a); color: #6b4e00; font-size: 18px;
+ border: 3px solid rgba(0,0,0,0.35); box-shadow: 0 2px 8px rgba(0,0,0,0.45); z-index: 1;
+}
+
+.kg-spin-result {
+ min-height: 22px; text-align: center; font-size: 16px; font-weight: 800;
+ transition: color .2s;
+}
+.kg-spin-result[data-kind="gold"] { color: #f5c542; text-shadow: 0 0 14px rgba(245,197,66,0.5); }
+.kg-spin-result[data-kind="wood"] { color: #d9a36a; }
+.kg-spin-result[data-kind="stone"] { color: #c2cbda; }
+.kg-spin-result[data-kind="coal"] { color: #aeb6c4; }
+
+.kg-spin-gate {
+ border: 1px solid rgba(255, 184, 92, 0.4); background: rgba(255, 184, 92, 0.08);
+ border-radius: 12px; padding: 10px 12px;
+}
+.kg-spin-gate[hidden] { display: none; }
+.kg-spin-gate-h { font-size: 11px; font-weight: 800; letter-spacing: 0.06em; text-transform: uppercase; color: #ffce5c; margin-bottom: 4px; }
+.kg-spin-gate-b { font-size: 13px; line-height: 1.45; color: var(--kg-text); }
+
+.kg-spin-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
+.kg-spin-action { display: flex; flex-direction: column; gap: 5px; }
+.kg-spin-btn {
+ width: 100%; padding: 12px 10px; border-radius: 12px; cursor: pointer; font: inherit;
+ font-size: 14px; font-weight: 800; color: var(--kg-text); border: 1px solid var(--kg-line);
+ transition: transform .08s, filter .15s, background .15s, border-color .15s; text-align: center;
+}
+.kg-spin-btn:active:not(:disabled) { transform: translateY(1px); }
+.kg-spin-btn:focus-visible { outline: 2px solid var(--kg-accent); outline-offset: 2px; }
+.kg-spin-btn:disabled { opacity: 0.45; cursor: not-allowed; }
+.kg-spin-free {
+ background: linear-gradient(180deg, rgba(110, 231, 135, 0.22), rgba(110, 231, 135, 0.1));
+ border-color: rgba(110, 231, 135, 0.5);
+}
+.kg-spin-free:hover:not(:disabled) { filter: brightness(1.12); border-color: rgba(110, 231, 135, 0.85); }
+.kg-spin-paid {
+ background: linear-gradient(180deg, rgba(245, 197, 66, 0.22), rgba(245, 197, 66, 0.1));
+ border-color: rgba(245, 197, 66, 0.5);
+}
+.kg-spin-paid:hover:not(:disabled) { filter: brightness(1.12); border-color: rgba(245, 197, 66, 0.85); }
+.kg-spin-sub { font-size: 11px; line-height: 1.35; color: var(--kg-dim); text-align: center; min-height: 15px; }
+.kg-spin-sub[data-ready="1"] { color: #6ee787; }
+
+.kg-spin-status { min-height: 18px; text-align: center; font-size: 13px; color: var(--kg-dim); }
+.kg-spin-status[data-kind="ok"] { color: #6ee787; }
+.kg-spin-status[data-kind="err"] { color: #ff8d7a; }
+.kg-spin-status a { color: inherit; text-decoration: underline; }
+
+.kg-spin-legend { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; justify-content: center; }
+.kg-spin-legend-h { font-size: 11px; font-weight: 800; letter-spacing: 0.06em; text-transform: uppercase; color: var(--kg-dim); }
+.kg-spin-chip { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 600; color: var(--kg-accent); }
+.kg-spin-dot { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
+
+@media (max-width: 380px) {
+ .kg-spin-wheelwrap, .kg-spin-canvas { width: 260px; height: 260px; }
+ .kg-spin-actions { grid-template-columns: 1fr; }
+}
+
+/* ───────────────────────────── Friends panel (Task 15) ─────────────────────
+ Rendered into the shared kg-ov surface body. Reuses the realm palette so it
+ feels native: same panel/line/text tokens, the green accent for "online" and
+ primary actions, amber for pending, red for destructive. */
+.kg-fr {
+ display: flex;
+ flex-direction: column;
+ min-height: 360px;
+}
+.kg-fr-hudbadge {
+ position: absolute;
+ top: -4px;
+ right: -4px;
+ min-width: 16px;
+ height: 16px;
+ padding: 0 4px;
+ border-radius: 999px;
+ background: #ff7a3a;
+ color: #1a0f08;
+ font-size: 10px;
+ font-weight: 800;
+ line-height: 16px;
+ text-align: center;
+ box-shadow: 0 0 0 2px var(--kg-bg);
+}
+.kg-iconbtn--alert {
+ border-color: rgba(255, 122, 58, 0.6);
+}
+
+/* tabs */
+.kg-fr-tabs {
+ display: flex;
+ gap: 6px;
+ margin-bottom: 14px;
+}
+.kg-fr-tab {
+ flex: 1;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: 8px 6px;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ color: var(--kg-dim);
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--kg-line);
+ border-radius: 10px;
+ cursor: pointer;
+ transition: color 0.15s, background 0.15s, border-color 0.15s;
+}
+.kg-fr-tab:hover {
+ color: var(--kg-text);
+ border-color: rgba(255, 255, 255, 0.22);
+}
+.kg-fr-tab.is-active {
+ color: #0d1420;
+ background: var(--kg-accent);
+ border-color: var(--kg-accent);
+}
+.kg-fr-pill {
+ min-width: 16px;
+ padding: 0 5px;
+ border-radius: 999px;
+ background: rgba(255, 122, 58, 0.95);
+ color: #1a0f08;
+ font-size: 10px;
+ font-weight: 800;
+ line-height: 16px;
+}
+.kg-fr-tab.is-active .kg-fr-pill {
+ background: #1a2030;
+ color: var(--kg-accent);
+}
+
+/* lists + rows */
+.kg-fr-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+.kg-fr-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 7px 8px;
+ border: 1px solid var(--kg-line);
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.03);
+}
+.kg-fr-rowmain {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0;
+ font: inherit;
+ color: inherit;
+ text-align: left;
+ background: transparent;
+ border: 0;
+ cursor: pointer;
+ border-radius: 8px;
+}
+.kg-fr-rowmain--static {
+ cursor: default;
+}
+.kg-fr-rowmain:not(.kg-fr-rowmain--static):hover .kg-fr-name {
+ color: #fff;
+}
+.kg-fr-meta {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ min-width: 0;
+}
+.kg-fr-name {
+ font-size: 13.5px;
+ font-weight: 700;
+ color: var(--kg-text);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 200px;
+ transition: color 0.15s;
+}
+.kg-fr-status {
+ font-size: 11.5px;
+ color: var(--kg-dim);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 220px;
+}
+.kg-fr-status--on {
+ color: #6ee787;
+}
+.kg-fr-status--off {
+ color: var(--kg-dim);
+}
+
+/* avatar + presence dot */
+.kg-fr-av {
+ position: relative;
+ flex: none;
+ width: 34px;
+ height: 34px;
+ border-radius: 50%;
+}
+.kg-fr-av-img {
+ width: 34px;
+ height: 34px;
+ border-radius: 50%;
+ object-fit: cover;
+ background: rgba(255, 255, 255, 0.06);
+}
+.kg-fr-av--mono {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: linear-gradient(150deg, #2a3550, #1a2233);
+ border: 1px solid var(--kg-line);
+}
+.kg-fr-av-ini {
+ font-size: 12.5px;
+ font-weight: 800;
+ color: var(--kg-accent);
+}
+.kg-fr-dot {
+ position: absolute;
+ bottom: -1px;
+ right: -1px;
+ width: 11px;
+ height: 11px;
+ border-radius: 50%;
+ box-shadow: 0 0 0 2px var(--kg-panel);
+}
+.kg-fr-dot--on {
+ background: #6ee787;
+}
+.kg-fr-dot--off {
+ background: #56627a;
+}
+
+/* unread + row actions */
+.kg-fr-unread {
+ flex: none;
+ min-width: 18px;
+ height: 18px;
+ padding: 0 5px;
+ border-radius: 999px;
+ background: #ff7a3a;
+ color: #1a0f08;
+ font-size: 11px;
+ font-weight: 800;
+ line-height: 18px;
+ text-align: center;
+}
+.kg-fr-rowactions {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex: none;
+}
+.kg-fr-icon {
+ width: 28px;
+ height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 13px;
+ color: var(--kg-dim);
+ background: transparent;
+ border: 1px solid transparent;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: color 0.15s, background 0.15s, border-color 0.15s;
+}
+.kg-fr-icon:hover {
+ color: var(--kg-text);
+ background: rgba(255, 255, 255, 0.06);
+ border-color: var(--kg-line);
+}
+.kg-fr-icon--danger:hover {
+ color: #ff8a8a;
+ border-color: rgba(255, 138, 138, 0.4);
+}
+.kg-fr-icon:disabled {
+ opacity: 0.4;
+ cursor: default;
+}
+
+/* buttons */
+.kg-fr-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: 8px 14px;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 700;
+ border-radius: 10px;
+ border: 1px solid var(--kg-line);
+ background: rgba(255, 255, 255, 0.05);
+ color: var(--kg-text);
+ cursor: pointer;
+ transition: transform 0.12s, background 0.15s, border-color 0.15s, opacity 0.15s;
+ text-decoration: none;
+}
+.kg-fr-btn:hover {
+ border-color: rgba(255, 255, 255, 0.26);
+}
+.kg-fr-btn:active {
+ transform: scale(0.97);
+}
+.kg-fr-btn:disabled {
+ opacity: 0.45;
+ cursor: default;
+}
+.kg-fr-btn--sm {
+ padding: 6px 11px;
+ font-size: 12px;
+}
+.kg-fr-btn--primary {
+ background: #6ee787;
+ border-color: #6ee787;
+ color: #0d1420;
+}
+.kg-fr-btn--primary:hover {
+ background: #82ed97;
+ border-color: #82ed97;
+}
+.kg-fr-btn--ghost {
+ background: transparent;
+}
+.kg-fr-tagpending {
+ font-size: 12px;
+ font-weight: 700;
+ color: #ffce5c;
+ padding: 5px 8px;
+}
+.kg-fr-tagpending--ok {
+ color: #6ee787;
+}
+
+/* requests subheads */
+.kg-fr-subhead {
+ margin: 16px 0 8px;
+ font-size: 11px;
+ font-weight: 800;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--kg-dim);
+}
+.kg-fr-reqs > .kg-fr-subhead:first-child {
+ margin-top: 0;
+}
+
+/* search */
+.kg-fr-searchwrap {
+ position: relative;
+ margin-bottom: 12px;
+}
+.kg-fr-search-ico {
+ position: absolute;
+ left: 11px;
+ top: 50%;
+ transform: translateY(-50%);
+ font-size: 13px;
+ opacity: 0.6;
+ pointer-events: none;
+}
+.kg-fr-search {
+ width: 100%;
+ padding: 10px 12px 10px 32px;
+ font: inherit;
+ font-size: 13.5px;
+ color: var(--kg-text);
+ background: rgba(13, 20, 32, 0.6);
+ border: 1px solid var(--kg-line);
+ border-radius: 10px;
+ outline: none;
+ transition: border-color 0.15s;
+}
+.kg-fr-search:focus {
+ border-color: var(--kg-accent);
+}
+.kg-fr-hint {
+ margin: 14px 4px;
+ font-size: 12.5px;
+ color: var(--kg-dim);
+ text-align: center;
+ line-height: 1.5;
+}
+
+/* empty + skeleton + banner */
+.kg-fr-empty {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ gap: 6px;
+ padding: 28px 16px;
+}
+.kg-fr-empty-glyph {
+ font-size: 34px;
+ opacity: 0.9;
+ margin-bottom: 4px;
+}
+.kg-fr-empty-title {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 800;
+ color: var(--kg-text);
+}
+.kg-fr-empty-sub {
+ margin: 0 0 8px;
+ font-size: 12.5px;
+ color: var(--kg-dim);
+ line-height: 1.5;
+ max-width: 280px;
+}
+.kg-fr-skel {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding-top: 4px;
+}
+.kg-fr-skel-row {
+ height: 50px;
+ border-radius: 12px;
+ background: linear-gradient(90deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.09), rgba(255, 255, 255, 0.04));
+ background-size: 200% 100%;
+ animation: kg-fr-shimmer 1.3s ease-in-out infinite;
+}
+@keyframes kg-fr-shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+}
+.kg-fr-banner {
+ margin: 0 0 12px;
+ padding: 9px 12px;
+ font-size: 12.5px;
+ color: #ff8a8a;
+ background: rgba(255, 122, 58, 0.1);
+ border: 1px solid rgba(255, 138, 138, 0.35);
+ border-radius: 10px;
+}
+
+/* DM thread */
+.kg-fr-thread {
+ display: flex;
+ flex-direction: column;
+ min-height: 380px;
+ height: min(62vh, 480px);
+}
+.kg-fr-thread-head {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding-bottom: 10px;
+ margin-bottom: 6px;
+ border-bottom: 1px solid var(--kg-line);
+}
+.kg-fr-back {
+ flex: none;
+ width: 30px;
+ height: 30px;
+ font-size: 20px;
+ line-height: 1;
+ color: var(--kg-dim);
+ background: transparent;
+ border: 1px solid var(--kg-line);
+ border-radius: 8px;
+ cursor: pointer;
+ transition: color 0.15s, border-color 0.15s;
+}
+.kg-fr-back:hover {
+ color: var(--kg-text);
+ border-color: var(--kg-accent);
+}
+.kg-fr-thread-msgs {
+ flex: 1;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ padding: 6px 2px;
+}
+.kg-fr-thread-empty {
+ margin: auto;
+ text-align: center;
+ padding: 24px 12px;
+}
+.kg-fr-daysep {
+ align-self: center;
+ margin: 8px 0 4px;
+ font-size: 10.5px;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--kg-dim);
+}
+.kg-fr-msg {
+ max-width: 78%;
+ padding: 7px 11px;
+ border-radius: 14px;
+ font-size: 13.5px;
+ line-height: 1.4;
+ word-wrap: break-word;
+ overflow-wrap: anywhere;
+ display: flex;
+ align-items: flex-end;
+ gap: 8px;
+}
+.kg-fr-msg--theirs {
+ align-self: flex-start;
+ background: rgba(255, 255, 255, 0.07);
+ color: var(--kg-text);
+ border-bottom-left-radius: 5px;
+}
+.kg-fr-msg--mine {
+ align-self: flex-end;
+ background: #2f6b8a;
+ color: #f1f7fb;
+ border-bottom-right-radius: 5px;
+}
+.kg-fr-msg-body {
+ min-width: 0;
+}
+.kg-fr-msg-time {
+ flex: none;
+ font-size: 9.5px;
+ opacity: 0.6;
+ margin-bottom: 1px;
+}
+.kg-fr-dm-bar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-top: 10px;
+ margin-top: 6px;
+ border-top: 1px solid var(--kg-line);
+}
+.kg-fr-dm-input {
+ flex: 1;
+ min-width: 0;
+ padding: 10px 14px;
+ font: inherit;
+ font-size: 13.5px;
+ color: var(--kg-text);
+ background: rgba(13, 20, 32, 0.6);
+ border: 1px solid var(--kg-line);
+ border-radius: 999px;
+ outline: none;
+ transition: border-color 0.15s;
+}
+.kg-fr-dm-input:focus {
+ border-color: var(--kg-accent);
+}
+.kg-fr-dm-send {
+ flex: none;
+ width: 38px;
+ height: 38px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 15px;
+ color: #0d1420;
+ background: #6ee787;
+ border: 0;
+ border-radius: 50%;
+ cursor: pointer;
+ transition: transform 0.12s, background 0.15s;
+}
+.kg-fr-dm-send:hover {
+ background: #82ed97;
+}
+.kg-fr-dm-send:active {
+ transform: scale(0.92);
+}
+.kg-fr-btn:focus-visible,
+.kg-fr-tab:focus-visible,
+.kg-fr-icon:focus-visible,
+.kg-fr-rowmain:focus-visible,
+.kg-fr-back:focus-visible,
+.kg-fr-dm-send:focus-visible,
+.kg-fr-search:focus-visible,
+.kg-fr-dm-input:focus-visible {
+ outline: 2px solid var(--kg-accent);
+ outline-offset: 2px;
+}
diff --git a/src/game/iso-game.js b/src/game/iso-game.js
index c616c56a5..c1dd42908 100644
--- a/src/game/iso-game.js
+++ b/src/game/iso-game.js
@@ -338,6 +338,9 @@ export class IsoGame {
this.nodeViews = new Map(); // id -> { group, node }
this.mobViews = new Map(); // id -> { group, mob }
this.npcViews = new Map(); // id -> { group, npc, label, markerEl }
+ this.wheelViews = new Map(); // id -> { group, landmark } — interactable wheels (Task 19)
+ this._landmarkGroups = []; // decorative landmark meshes (casino), cleared per realm
+ this._casinoLabels = []; // [{ label, x, z, height }] — decorative landmark nameplates
this.tombViews = new Map(); // id -> { group, tomb, label, nameEl, ttlEl }
this.structViews = new Map(); // id -> { group, struct, ring, flame } (Task 07)
this.keys = new Set();
@@ -591,6 +594,11 @@ export class IsoGame {
// quest marker. Rebuilt with the realm since they ride in the realm layout.
this._buildNpcs(layout);
+ // Fixed landmarks (Task 19): the casino building + its Wheel of Fortune.
+ // The wheel is interactable — clicking it walks the player adjacent and opens
+ // the spinner; the casino is decorative (its footprint is blocked server-side).
+ this._buildLandmarks(layout);
+
// Frame the camera on the spawn before the local player exists.
const sp = this._tileToWorld(layout.spawn?.tx ?? grid / 2, layout.spawn?.ty ?? grid / 2);
this._camTarget.set(sp.x, 0, sp.z);
@@ -674,6 +682,127 @@ export class IsoGame {
this.npcViews.clear();
}
+ // ---------------------------------------------------------------- landmarks
+ // Fixed world landmarks (Task 19). The casino is a decorative building; the
+ // wheel is an interactable object (tagged for raycast → walk-and-spin). Rebuilt
+ // with the realm since they ride in the realm layout.
+ _buildLandmarks(layout) {
+ this._disposeLandmarks();
+ for (const lm of layout.landmarks || []) {
+ if (lm.kind === 'wheel') {
+ const group = this._buildWheelView();
+ const w = this._tileToWorld(lm.tx, lm.ty);
+ group.position.set(w.x, 0, w.z);
+ group.traverse((o) => { o.userData.wheelId = lm.id; }); // raycast → spin target
+ this.objectGroup.add(group);
+
+ const label = document.createElement('div');
+ label.className = 'kg-npc-label kg-wheel-label';
+ label.innerHTML = `<span class="kg-npc-tag"></span>`;
+ label.querySelector('.kg-npc-tag').textContent = lm.label || 'Wheel of Fortune';
+ document.getElementById('kg-labels')?.appendChild(label);
+
+ this.wheelViews.set(lm.id, { group, landmark: lm, label, height: 2.2, spin: 0 });
+ } else if (lm.kind === 'casino') {
+ const group = this._buildCasinoView();
+ const w = this._tileToWorld(lm.tx, lm.ty);
+ group.position.set(w.x, 0, w.z);
+ this.staticGroup.add(group);
+ this._landmarkGroups.push(group);
+
+ const label = document.createElement('div');
+ label.className = 'kg-npc-label kg-casino-label';
+ label.innerHTML = `<span class="kg-npc-tag"></span>`;
+ label.querySelector('.kg-npc-tag').textContent = lm.label || 'Casino';
+ document.getElementById('kg-labels')?.appendChild(label);
+ this._casinoLabels.push({ label, x: w.x, z: w.z, height: 3.0 });
+ }
+ }
+ }
+
+ // A carnival prize wheel: an upright disc with alternating gold/teal sectors, a
+ // hub, and a top pointer. Low-poly, no asset load. Slowly idles via _updateLandmarks.
+ _buildWheelView() {
+ const g = new Group();
+ const post = new Mesh(new CylinderGeometry(0.12, 0.16, 1.5, 10),
+ new MeshStandardMaterial({ color: 0x5a4632, roughness: 0.9 }));
+ post.position.y = 0.75; post.castShadow = true;
+ const disc = new Group();
+ disc.position.y = 1.7;
+ const n = 12, seg = (Math.PI * 2) / n;
+ for (let i = 0; i < n; i++) {
+ const wedge = new Mesh(
+ new CylinderGeometry(0.78, 0.78, 0.12, 24, 1, false, i * seg, seg),
+ new MeshStandardMaterial({
+ color: i % 2 ? 0xf5c542 : 0x2b9fa8,
+ emissive: i % 2 ? 0x4a3a08 : 0x0a3034, emissiveIntensity: 0.5, roughness: 0.5,
+ }),
+ );
+ wedge.rotation.x = Math.PI / 2;
+ disc.add(wedge);
+ }
+ const hub = new Mesh(new SphereGeometry(0.16, 16, 12),
+ new MeshStandardMaterial({ color: 0xfff1c0, emissive: 0x6b5410, emissiveIntensity: 0.9, roughness: 0.3 }));
+ hub.position.z = 0.08;
+ disc.add(hub);
+ disc.rotation.y = 0; // faces +Z; idles around Z in _updateLandmarks
+ const pointer = new Mesh(new ConeGeometry(0.12, 0.28, 4),
+ new MeshStandardMaterial({ color: 0xff5a3a, roughness: 0.5 }));
+ pointer.position.set(0, 2.56, 0.06); pointer.rotation.x = Math.PI;
+ g.add(post, disc, pointer);
+ g.userData.disc = disc;
+ g.castShadow = true;
+ return g;
+ }
+
+ // A small casino pavilion: a warm-lit body with a striped awning and a glowing
+ // sign cube, so the wheel reads as part of a venue, not a stray object.
+ _buildCasinoView() {
+ const g = new Group();
+ const body = new Mesh(new BoxGeometry(3.2, 2.0, 2.4),
+ new MeshStandardMaterial({ color: 0x6a2b4a, roughness: 0.85 }));
+ body.position.y = 1.0; body.castShadow = true; body.receiveShadow = true;
+ const roof = new Mesh(new CylinderGeometry(1.9, 1.9, 0.5, 6),
+ new MeshStandardMaterial({ color: 0x3a1830, roughness: 0.8 }));
+ roof.position.y = 2.25; roof.rotation.y = Math.PI / 6; roof.castShadow = true;
+ const sign = new Mesh(new BoxGeometry(1.4, 0.5, 0.18),
+ new MeshStandardMaterial({ color: 0xffce5c, emissive: 0xffae3a, emissiveIntensity: 1.1, roughness: 0.4 }));
+ sign.position.set(0, 2.0, 1.25);
+ const doorway = new Mesh(new BoxGeometry(0.9, 1.3, 0.12),
+ new MeshStandardMaterial({ color: 0x140a12, roughness: 1 }));
+ doorway.position.set(0, 0.65, 1.21);
+ g.add(body, roof, sign, doorway);
+ return g;
+ }
+
+ _disposeLandmarks() {
+ for (const [, v] of this.wheelViews) { this.objectGroup.remove(v.group); v.label?.remove(); }
+ this.wheelViews.clear();
+ for (const group of this._landmarkGroups) this.staticGroup.remove(group);
+ this._landmarkGroups = [];
+ for (const cl of this._casinoLabels) cl.label?.remove();
+ this._casinoLabels = [];
+ }
+
+ // Open the Wheel of Fortune (Task 19). The heavy Solana signing path lives in a
+ // lazy chunk, so it only loads the first time a player reaches the wheel. The UI
+ // owns its own server subscriptions; we just hand it the net and clear our handle
+ // when it closes.
+ async _openSpinWheel() {
+ if (this._spinUI) { this._spinUI.focus(); return; }
+ if (this._spinUILoading) return;
+ this._spinUILoading = true;
+ try {
+ const { openSpinWheel } = await import('./spin-wheel-ui.js');
+ this._spinUI = openSpinWheel({ net: this.net, onClose: () => { this._spinUI = null; } });
+ } catch (err) {
+ console.warn('[spin] failed to open wheel:', err?.message);
+ this._toast({ kind: 'spin', text: 'Could not open the wheel. Try again.' });
+ } finally {
+ this._spinUILoading = false;
+ }
+ }
+
_rectTiles(r) {
const out = [];
for (let tx = r.x0; tx <= r.x1; tx++) for (let ty = r.y0; ty <= r.y1; ty++) out.push({ tx, ty });
@@ -1117,6 +1246,8 @@ export class IsoGame {
for (const id of [...this.tombViews.keys()]) this._tombRemove(id);
for (const id of [...this.structViews.keys()]) this._structRemove(id);
this._exitBuildMode();
+ // The wheel lives only on the Mainland — close an open spinner on a realm hop.
+ this._spinUI?.close();
this._target = null;
this._lootTombId = null;
this.myId = sessionId || this.net?.sessionId || this.myId;
@@ -1830,6 +1961,7 @@ export class IsoGame {
if (ud.nodeId && this.nodeViews.has(ud.nodeId)) { this._setTarget('node', ud.nodeId); return; }
if (ud.mobId && this.mobViews.has(ud.mobId)) { this._setTarget('mob', ud.mobId); return; }
if (ud.npcId && this.npcViews.has(ud.npcId)) { this._setTarget('npc', ud.npcId); return; }
+ if (ud.wheelId && this.wheelViews.has(ud.wheelId)) { this._setTarget('wheel', ud.wheelId); return; }
}
// 2b) In a PvP realm, a tap on another living player marks them as an attack
@@ -2334,11 +2466,13 @@ export class IsoGame {
if (k === 'q' && this.phase === 'world') { e.preventDefault(); this.q?.toggleQuests(); return; }
// Build menu (Task 07): B opens it / cancels an in-progress placement.
if (k === 'b' && this.phase === 'world') { e.preventDefault(); this._toggleBuildMenu(); return; }
+ // Marketplace (Task 20): M opens/closes the cart from anywhere in-world.
+ if (k === 'm' && this.phase === 'world') { e.preventDefault(); this.q?.toggleMarket(); return; }
// Escape also cancels build mode before any other surface.
if (k === 'escape' && this._buildMode) { e.preventDefault(); this._exitBuildMode(); return; }
// Hotbar number keys 1–6: select that slot (and ride a mount on it).
if (this.phase === 'world' && k >= '1' && k <= '6') { e.preventDefault(); this._equipOrRide(+k - 1); return; }
- if (k === 'escape') { this.q?.closeQuests(); this.q?.closeBank(); this.q?.closeNpc(); this.q?.closeBuild?.(); this.q?.closeShop?.(); }
+ if (k === 'escape') { this.q?.closeQuests(); this.q?.closeBank(); this.q?.closeNpc(); this.q?.closeBuild?.(); this.q?.closeShop?.(); this.q?.closeMarket?.(); }
// Hotbar 1–6: equip that slot (server validates + patches activeSlot back).
if (this.phase === 'world' && k >= '1' && k <= '6') { e.preventDefault(); this.net?.equip(parseInt(k, 10) - 1); return; }
// Chat focus: C (or Enter) opens the chat input once in the world. The
@@ -2459,6 +2593,7 @@ export class IsoGame {
if (t.kind === 'mob') { const v = this.mobViews.get(t.id); if (!v || v.mob.dead) return null; return { tx: v.mob.tx, ty: v.mob.ty }; }
if (t.kind === 'player') { const v = this.players.get(t.id); if (!v || v.dead) return null; return { tx: v.tx, ty: v.ty }; }
if (t.kind === 'npc') { const v = this.npcViews.get(t.id); if (!v) return null; return { tx: v.npc.tx, ty: v.npc.ty }; }
+ if (t.kind === 'wheel') { const v = this.wheelViews.get(t.id); if (!v) return null; return { tx: v.landmark.tx, ty: v.landmark.ty }; }
return null;
}
@@ -2507,6 +2642,7 @@ export class IsoGame {
if (Math.abs(me.tx - tile.tx) > 1 || Math.abs(me.ty - tile.ty) > 1) return; // not there yet
if (t.kind === 'npc') { this.net?.npcTalk(t.id); this._target = null; return; }
+ if (t.kind === 'wheel') { this._openSpinWheel(); this._target = null; return; }
this._interactAccum += dt * 1000;
if (this._interactAccum < INTERACT_ACTION_MS) return;
@@ -3103,6 +3239,7 @@ export class IsoGame {
this._updateCamera();
this._updateLabels();
this._updateNpcLabels();
+ this._updateLandmarks(dt);
this._updateTombLabels();
this._updateStructures(now);
this._updateBuildGhost();
@@ -3174,6 +3311,29 @@ export class IsoGame {
}
}
+ // Idle-spin each wheel disc for a touch of life, and project the wheel + casino
+ // nameplates to screen space (Task 19).
+ _updateLandmarks(dt) {
+ const w = window.innerWidth, h = window.innerHeight;
+ const v = new Vector3();
+ for (const [, wv] of this.wheelViews) {
+ const disc = wv.group.userData.disc;
+ if (disc) disc.rotation.z += dt * 0.6;
+ v.set(wv.group.position.x, wv.height + 0.6, wv.group.position.z).project(this.camera);
+ if (v.z > 1) { wv.label.style.display = 'none'; continue; }
+ wv.label.style.display = '';
+ const sx = (v.x * 0.5 + 0.5) * w, sy = (-v.y * 0.5 + 0.5) * h;
+ wv.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
+ }
+ for (const cl of this._casinoLabels) {
+ v.set(cl.x, cl.height, cl.z).project(this.camera);
+ if (v.z > 1) { cl.label.style.display = 'none'; continue; }
+ cl.label.style.display = '';
+ const sx = (v.x * 0.5 + 0.5) * w, sy = (-v.y * 0.5 + 0.5) * h;
+ cl.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
+ }
+ }
+
// Project each tombstone's headstone to screen space, place its DOM label, and
// tick the live "expires in Xs" countdown straight off the synced expiresAt.
_updateTombLabels() {
@@ -3236,6 +3396,8 @@ export class IsoGame {
this.structViews.clear();
this._exitBuildMode();
this._disposeNpcs();
+ this._disposeLandmarks();
+ this._spinUI?.close();
this.q?.destroy();
this._clearCast();
this._nipple?.destroy();
diff --git a/src/game/play-gate.js b/src/game/play-gate.js
index 93708b761..a42aab117 100644
--- a/src/game/play-gate.js
+++ b/src/game/play-gate.js
@@ -45,20 +45,22 @@ class Gate {
}
async _start() {
- // Probe the gate. If we can't reach it we don't know whether sign-in is
- // required, so show a retryable error rather than guessing either way.
- this._mount();
- this._render({ state: 'checking' });
+ // Probe the gate before mounting anything — when /play is open (no token
+ // pinned) or a fresh pass is already cached, the player never sees an overlay
+ // at all. We only paint a screen when sign-in is genuinely needed, or when
+ // we can't reach the gate (a retryable error — we don't guess access either
+ // way, since the server is the real authority).
let cfg;
try {
cfg = await fetchPlayConfig();
} catch (err) {
+ this._mount();
this._render({ state: 'error', error: err?.message || 'Could not reach sign-in.', retry: () => this._start() });
return;
}
this.cfg = cfg;
- // No token pinned → /play is open. Tear the gate down and let everyone in.
+ // No token pinned → /play is open. Let everyone in without a flash.
if (!cfg.required) {
this._finish({ required: false });
return;
@@ -71,6 +73,7 @@ class Gate {
return;
}
+ this._mount();
this._renderConnect();
}
@@ -169,12 +172,6 @@ class Gate {
const tokenName = (sym) => sym || this.cfg?.symbol || 'the game token';
switch (view.state) {
- case 'checking':
- return card(`
- <div class="pg-spinner" aria-hidden="true"></div>
- <h1 class="pg-title">Checking access…</h1>
- <p class="pg-sub">One moment while we set up sign-in.</p>`);
-
case 'no_wallet':
return card(`
<div class="pg-icon" aria-hidden="true">${SVG.wallet}</div>
diff --git a/src/game/spin-wheel-ui.js b/src/game/spin-wheel-ui.js
index 41c6f6247..3bb65850e 100644
--- a/src/game/spin-wheel-ui.js
+++ b/src/game/spin-wheel-ui.js
@@ -148,10 +148,20 @@ class SpinWheel {
_onDenied(m) {
if (m && Number.isFinite(m.nextFreeSpinAt) && this.info) this.info.nextFreeSpinAt = m.nextFreeSpinAt;
if (m && Number.isFinite(m.avgLevel) && this.info) { this.info.avgLevel = m.avgLevel; this.info.eligible = m.avgLevel >= m.minLevel; }
+ // A paid spin whose payment isn't visible to the server yet: it landed
+ // on-chain (we waited for confirmation) but the RPC's parsed view can lag a
+ // beat. Retry the settle a few times before giving up so a confirmed payment
+ // is never lost to a timing race. The signature is consumed only on success.
+ if (m?.mode === 'paid' && m.reason === 'not_found' && this._prep && this._sig && (this._settleAttempts || 0) < 5) {
+ this._status('Waiting for the payment to confirm…', '');
+ setTimeout(() => { if (!this._closed && this.phase === 'spinning') this._settle(); }, 2500);
+ return;
+ }
this.busy = false;
this._stopSpin();
this.phase = 'ready';
this._prep = null;
+ this._sig = null;
this._status(this._denyText(m), 'err');
this._sync();
}
@@ -228,8 +238,14 @@ class SpinWheel {
this.phase = 'spinning';
this._startSpin();
this._status('Verifying payment & rolling…', '');
- this._settleAttempts = 1;
- this.net.spinPaidSettle(prep.quote, sig);
+ this._settle();
+ }
+
+ // Ask the server to verify the broadcast payment and roll. Kept as its own step
+ // so a transient "not confirmed yet" can retry without re-signing.
+ _settle() {
+ this._settleAttempts = (this._settleAttempts || 0) + 1;
+ this.net.spinPaidSettle(this._prep.quote, this._sig);
}
// Poll signature status over HTTP (no WS — the public RPC refuses subscriptions).
@@ -265,6 +281,7 @@ class SpinWheel {
this.busy = false;
this.phase = 'result';
this._prep = null;
+ this._sig = null;
const seg = this.segments?.[m.index];
const label = m.label || seg?.label || 'a prize';
let line = `You won ${label}!`;
@@ -407,7 +424,10 @@ class SpinWheel {
const now = (this.info.now ?? Date.now()) + drift;
const next = this.info.nextFreeSpinAt ?? 0;
const ready = now >= next;
- if (this.phase === 'spinning' || this.phase === 'paying') return;
+ if (this.busy || this.phase === 'spinning' || this.phase === 'paying') {
+ this.freeBtn.disabled = true;
+ return;
+ }
if (!this._levelOk()) {
this.freeBtn.disabled = true; this.freeBtn.textContent = 'Free spin';
this.freeSub.textContent = '';
diff --git a/src/walk-net.js b/src/walk-net.js
index 8268d86a2..67f91b204 100644
--- a/src/walk-net.js
+++ b/src/walk-net.js
@@ -81,7 +81,12 @@ export class WalkNet {
remove: new Set(), // (sessionId)
change: new Set(), // (player, sessionId)
chat: new Set(), // ({ id, name, text, ts })
+ social: new Set(), // ({ type, ... }) — friends events: live DM, request/accept (Task 15)
};
+ // Optional async presence-ticket supplier (Task 15). When provided, its
+ // resolved token rides the join so this coin world publishes the player's
+ // account presence to friends and can deliver DMs here live.
+ this.getPresence = typeof opts.getPresence === 'function' ? opts.getPresence : null;
this._lastSent = null; // { x, y, z, yaw, motion } we last broadcast
this._lastSentAt = 0;
this._reconnectTimer = null;
@@ -136,6 +141,7 @@ export class WalkNet {
// `token` is the server's filterBy key (matchmaking): clients with the
// same coin mint join one room instance. `coin`/`coinName`/… seed that
// room's identity the first time it's created. Empty coin → mainland.
+ const presence = this.getPresence ? await this.getPresence().catch(() => null) : null;
const room = await this.client.joinOrCreate(ROOM_NAME, {
name: this.name,
avatar: this.avatar,
@@ -145,6 +151,7 @@ export class WalkNet {
coinName: this.coinName,
coinSymbol: this.coinSymbol,
coinImage: this.coinImage,
+ ...(presence ? { presence } : {}),
});
if (this._destroyed || gen !== this._connectGen) {
try { room.leave(); } catch {}
@@ -169,6 +176,8 @@ export class WalkNet {
// We relay it through our own event API; walk.js renders the bubble +
// log line and routes it to the right remote player.
this.room.onMessage('chat', (msg) => this._emit('chat', msg));
+ // Friends (Task 15): live DM + request/accept events pushed by the social hub.
+ this.room.onMessage('social', (msg) => this._emit('social', msg));
this.room.onLeave((code) => {
this._setStatus('offline');
diff --git a/src/walk.js b/src/walk.js
index 04f5696f3..f7d8b3cf3 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -47,6 +47,7 @@ import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
import { WalkNet } from './walk-net.js';
+import { getPresenceTicket, friendsClient } from './friends.js';
const AVATAR_URL_DEFAULT = '/avatars/default.glb';
@@ -1953,8 +1954,15 @@ function startNet() {
coinName: COIN_PARAMS.name,
coinSymbol: COIN_PARAMS.symbol,
coinImage: COIN_PARAMS.image,
+ // Publish account presence (Task 15) so friends see this player online in
+ // this coin world, and so DMs can deliver here live. No-op when signed out.
+ getPresence: getPresenceTicket,
});
+ // Friends realtime (Task 15): keep the shared friends client's threads + unread
+ // warm with any live DM / request events delivered to this coin world.
+ net.on('social', (m) => friendsClient().handleSocial(m));
+
net.on('status', ({ status }) => {
netConnected = status === 'online';
setOnlineStatus(status);
diff --git a/tests/marketplace-store.test.js b/tests/marketplace-store.test.js
new file mode 100644
index 000000000..1aaec1b9e
--- /dev/null
+++ b/tests/marketplace-store.test.js
@@ -0,0 +1,123 @@
+// Marketplace (Task 20) — the durable listing/payout store and the token quote
+// primitives the on-chain settlement depends on. The store is exercised against a
+// mocked @upstash/redis (same harness as player-store.test) so the durability +
+// no-dupe invariants are proven without real credentials, and the token layer's
+// quote sign/verify + 95/5 split are unit-checked.
+//
+// What matters for the task:
+// - a listing's escrow lives on the store, survives a simulated restart, and a
+// drained payout is removed atomically (delivered exactly once — no dupe/loss),
+// - a consumed on-chain signature is remembered so a token payment can't replay,
+// - a USD price quotes to a tamper-proof, expiring signed quote,
+// - the 95/5 split always sums back to the exact total.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const redis = vi.hoisted(() => ({ store: new Map(), pingFails: false }));
+
+vi.mock('@upstash/redis', () => ({
+ Redis: class {
+ async ping() { if (redis.pingFails) throw new Error('unreachable'); return 'PONG'; }
+ async get(k) { return redis.store.has(k) ? redis.store.get(k) : null; }
+ async set(k, v) { redis.store.set(k, v); return 'OK'; }
+ async del(k) { return redis.store.delete(k) ? 1 : 0; }
+ },
+}));
+
+async function freshStore({ durable = true } = {}) {
+ vi.resetModules();
+ if (durable) {
+ process.env.UPSTASH_REDIS_REST_URL = 'http://mock-upstash';
+ process.env.UPSTASH_REDIS_REST_TOKEN = 'mock-token';
+ } else {
+ delete process.env.UPSTASH_REDIS_REST_URL;
+ delete process.env.UPSTASH_REDIS_REST_TOKEN;
+ }
+ return import('../multiplayer/src/marketplaceStore.js');
+}
+
+beforeEach(() => { redis.store.clear(); redis.pingFails = false; });
+
+describe('MarketplaceStore — listings + escrow', () => {
+ it('creates active listings and surfaces them by recency + by seller', async () => {
+ const { marketplaceStore: m } = await freshStore({ durable: false });
+ const a = m.create({ seller: 'alice', sellerName: 'Alice', type: 'gold', item: 'wood', qty: 50, priceGold: 100 });
+ const b = m.create({ seller: 'bob', sellerName: 'Bob', type: 'goldForToken', goldAmount: 1000, priceUsd: 1.5, sellerWallet: 'bob' });
+ expect(a.status).toBe('active');
+ expect(m.activeListings().map((l) => l.id)).toContain(a.id);
+ expect(m.listingsBySeller('alice')).toHaveLength(1);
+ // Closing one drops it from the active board but keeps it on the seller's list.
+ m.update(a.id, { status: 'cancelled', closedAt: Date.now() });
+ expect(m.activeListings().map((l) => l.id)).not.toContain(a.id);
+ expect(m.listingsBySeller('alice')).toHaveLength(1);
+ expect(m.get(b.id).status).toBe('active');
+ });
+
+ it('delivers a queued payout exactly once (no dupe, no loss)', async () => {
+ const { marketplaceStore: m } = await freshStore({ durable: false });
+ m.enqueuePayout('alice', { gold: 250, reason: 'sold wood' });
+ m.enqueuePayout('alice', { gold: 50, reason: 'sold fish' });
+ expect(m.hasPendingPayouts('alice')).toBe(true);
+ const first = m.drainPayouts('alice');
+ expect(first.reduce((s, p) => s + p.gold, 0)).toBe(300);
+ // A second drain (e.g. a presence nudge racing the login) yields nothing.
+ expect(m.drainPayouts('alice')).toEqual([]);
+ expect(m.hasPendingPayouts('alice')).toBe(false);
+ });
+
+ it('remembers a consumed tx signature so a token payment cannot replay', async () => {
+ const { marketplaceStore: m } = await freshStore({ durable: false });
+ expect(m.isSettled('sigABC')).toBe(false);
+ m.markSettled('sigABC');
+ expect(m.isSettled('sigABC')).toBe(true);
+ });
+});
+
+describe('MarketplaceStore (durable / Upstash)', () => {
+ it('persists active listings + payouts across a simulated restart', async () => {
+ const a = await freshStore();
+ await a.marketplaceStore.ready();
+ const rec = a.marketplaceStore.create({ seller: 'alice', sellerName: 'Alice', type: 'gold', item: 'coal', qty: 12, priceGold: 80 });
+ a.marketplaceStore.enqueuePayout('bob', { gold: 999, reason: 'sale' });
+ a.marketplaceStore.markSettled('sig1');
+ await a.marketplaceStore.flushAll();
+ expect(redis.store.has('market:listings')).toBe(true);
+
+ // Process B (fresh store, same Redis) hydrates the board on boot.
+ const b = await freshStore();
+ await b.marketplaceStore.ready();
+ expect(b.marketplaceStore.get(rec.id)?.priceGold).toBe(80);
+ expect(b.marketplaceStore.activeListings().map((l) => l.id)).toContain(rec.id);
+ expect(b.marketplaceStore.hasPendingPayouts('bob')).toBe(true);
+ expect(b.marketplaceStore.isSettled('sig1')).toBe(true);
+ });
+});
+
+describe('Game token — quote sign/verify + split', () => {
+ it('splits a total 95/5 with no remainder lost', async () => {
+ const { splitAmount } = await import('../multiplayer/src/game-token.js');
+ for (const total of [1_000_000n, 999_999n, 7n, 123_456_789n]) {
+ const { seller, treasury } = splitAmount(total, 500);
+ expect(seller + treasury).toBe(total); // nothing created or lost
+ expect(treasury).toBe((total * 500n) / 10000n); // exact 5%
+ }
+ });
+
+ it('signs a quote that verifies and rejects tampering', async () => {
+ const { signQuote, verifyQuote } = await import('../multiplayer/src/game-token.js');
+ const token = signQuote({ listingId: 'lst_1', buyer: 'B', sellerWallet: 'S', usd: 2, total: '1000000', sellerRaw: '950000', treasuryRaw: '50000' });
+ const ok = verifyQuote(token);
+ expect(ok?.listingId).toBe('lst_1');
+ expect(ok?.sellerRaw).toBe('950000');
+ // Any byte flipped in the body or signature fails the HMAC.
+ expect(verifyQuote(token.slice(0, -1) + (token.slice(-1) === 'a' ? 'b' : 'a'))).toBeNull();
+ expect(verifyQuote('not-a-token')).toBeNull();
+ });
+
+ it('classifies wallet vs guest account ids', async () => {
+ const { isWalletAddress } = await import('../multiplayer/src/game-token.js');
+ expect(isWalletAddress('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).toBe(true);
+ expect(isWalletAddress('g_abc123')).toBe(false);
+ expect(isWalletAddress('')).toBe(false);
+ });
+});