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(play): extend war-portal leaderboard and guard thresholds
nirholas62e3ae4f1749
diff --git a/data/guards.json b/data/guards.jsonindex bd107a8f0..6546ec3ef 100644--- a/data/guards.json+++ b/data/guards.json@@ -837,6 +837,34 @@"expect": "guard-proof"}},+ {+ "id": "check-event-window",+ "script": "scripts/check-event-window.mjs",+ "npm": "check:event",+ "title": "Live event window",+ "protects": "public/event.json describes an event that will actually happen, on every surface that reads it.",+ "why": "One file drives the /play lobby banner, the in-world countdown and meetup layer, the game server's quest gate, the leaderboard endpoints and the souvenir grant. Every one of them treats a bad or expired window as 'there is no event' and mounts nothing, so the failure is silent and total: the page loads, the world runs, and the entire event is simply absent with no error to say why. That has already happened once, when a rehearsal window was left in the file.",+ "stages": [+ "manual"+ ],+ "needs": "none",+ "proof": {+ "summary": "An event window whose end has already passed, which every surface reads as 'no event' and mounts nothing.",+ "violation": {+ "json": [+ {+ "file": "public/event.json",+ "pointer": "",+ "set": {+ "startsAt": "2020-01-01T00:00:00.000Z",+ "endsAt": "2020-01-01T02:00:00.000Z"+ }+ }+ ]+ },+ "expect": "event.json"+ }+ },{"id": "audit-tour-atlas","script": "scripts/build-tour-atlas.mjs",diff --git a/multiplayer/src/event-leaderboard.js b/multiplayer/src/event-leaderboard.jsindex a4793d9fb..ce45517f1 100644--- a/multiplayer/src/event-leaderboard.js+++ b/multiplayer/src/event-leaderboard.js@@ -38,27 +38,36 @@ export function emptyEventRecord(account, name = '') {// value is clamped here rather than at the call sites, so a malformed report can// dirty a row but never poison the ranking with NaN or a negative score.export function applyEventRun(rec, { missionId = '', gold = 0, at = 0, name = '' } = {}) {- rec.runs = Math.max(0, (rec.runs | 0) + 1);- rec.cash = Math.max(0, (rec.cash | 0) + Math.max(0, Math.round(Number(gold) || 0)));- const ts = Math.max(0, Math.round(Number(at) || 0));+ rec.runs = nonNegInt(rec.runs) + 1;+ rec.cash = nonNegInt(rec.cash) + nonNegInt(gold);+ const ts = nonNegInt(at);if (ts > rec.lastAt) rec.lastAt = ts;if (name) rec.name = String(name).slice(0, 24);const id = String(missionId || '').slice(0, 64);- if (id) rec.missions[id] = (rec.missions[id] | 0) + 1;+ if (id) rec.missions[id] = nonNegInt(rec.missions[id]) + 1;return rec;}+// Coerce an untrusted field to a non-negative integer. Deliberately NOT `| 0`:+// that truncates to 32 bits, and an epoch-ms timestamp is far past 2^31, so a+// bitwise coercion silently zeroed every `lastAt` and with it the tiebreak that+// puts the earlier finisher ahead.+function nonNegInt(v) {+ const n = Math.floor(Number(v));+ return Number.isFinite(n) && n > 0 ? n : 0;+}+// Normalize a persisted/transported row back into a full record. Tolerant of// partial and legacy blobs — a corrupt row degrades to a zeroed one rather than// throwing inside a read that the whole panel depends on.export function normalizeEventRecord(row, account = '') {const rec = emptyEventRecord(row?.account || account, row?.name || '');- rec.runs = Math.max(0, Number(row?.runs) | 0);- rec.cash = Math.max(0, Number(row?.cash) | 0);- rec.lastAt = Math.max(0, Number(row?.lastAt) | 0);+ rec.runs = nonNegInt(row?.runs);+ rec.cash = nonNegInt(row?.cash);+ rec.lastAt = nonNegInt(row?.lastAt);if (row?.missions && typeof row.missions === 'object') {for (const [id, n] of Object.entries(row.missions)) {- const count = Number(n) | 0;+ const count = nonNegInt(n);if (count > 0) rec.missions[String(id).slice(0, 64)] = count;}}diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.jsindex d795fa92b..694359117 100644--- a/multiplayer/src/rooms/WalkRoom.js+++ b/multiplayer/src/rooms/WalkRoom.js@@ -2150,6 +2150,7 @@ export class WalkRoom extends Room {const profile = this.econ.get(client.sessionId);if (!profile) return;if (!this._actionOk(client.sessionId, 'storeSell')) return;+ if (!this._atCounter(client, 'store')) return;const slot = resolveSlot(profile, payload?.slot);if (!slot || !slot.item) {client.send('notice', { kind: 'store', ok: false, text: 'Nothing there to sell.' });@@ -2179,6 +2180,7 @@ export class WalkRoom extends Room {const profile = this.econ.get(client.sessionId);if (!profile) return;if (!this._actionOk(client.sessionId, 'bank')) return;+ if (!this._atCounter(client, 'bank')) return;const amount = Number.isFinite(payload?.amount) ? payload.amount | 0 : 0;if (!amount) return;const moved = bankTransfer(profile, amount);diff --git a/page-agent-sdk/src/stage.js b/page-agent-sdk/src/stage.jsindex 390fcc445..51b1b1b8e 100644--- a/page-agent-sdk/src/stage.js+++ b/page-agent-sdk/src/stage.js@@ -45,7 +45,7 @@ const HDRI_ORIGIN = new URL(DEFAULT_ASSET_BASE).origin;let _hdriPromise = null;function getHdriTexture() {if (!_hdriPromise) {- // RGBELoader on purpose, not HDRLoader — same reasoning as+ // RGBELoader on purpose, not HDRLoader. Same reasoning as// avatar-sdk/src/viewer.js: three renamed the class in r180, but this// package's peer range is `three >= 0.150.0` and the ESM build leaves// three external, so the specifier resolves against the CONSUMER'sdiff --git a/scripts/play-desktop-audit.mjs b/scripts/play-desktop-audit.mjsindex a068e2c30..bc7bc4480 100644--- a/scripts/play-desktop-audit.mjs+++ b/scripts/play-desktop-audit.mjs@@ -21,7 +21,11 @@ const t0 = Date.now();const at = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;const issues = [];-const note = (line) => { issues.push(line); console.log(at(), line); };+// Vite's dev-only HMR socket cannot reach a Codespaces-forwarded port, so it+// always fails there. It is a harness artifact with no production equivalent+// (the built site ships no HMR client), so it must not drown out real findings.+const HARNESS_NOISE = /\[vite\]|vite.*websocket|WebSocket closed without opened|app\.github\.dev/i;+const note = (line) => { if (HARNESS_NOISE.test(line)) return; issues.push(line); console.log(at(), line); };page.on('console', (m) => {if (m.type() === 'error' || m.type() === 'warning') note(`[console.${m.type()}] ${m.text().slice(0, 300)}`);});@@ -32,7 +36,7 @@ page.on('requestfailed', (r) => {});page.on('response', (r) => { if (r.status() >= 400) note(`[http ${r.status()}] ${r.url().slice(0, 140)}`); });-await page.goto(TARGET, { waitUntil: 'domcontentloaded', timeout: 60000 });+await page.goto(TARGET, { waitUntil: "domcontentloaded", timeout: 180000 });console.log(at(), 'domcontentloaded');let loaderCleared = true;@@ -100,7 +104,7 @@ if (/position|inset|z-index|content/.test(checks.cardStyleProps)) note(`[css-inj// A malformed mint must land in the lobby with an explanation, not a world.const bad = new URL(TARGET);bad.search = '?coin=notarealmint';-await page.goto(bad.toString(), { waitUntil: 'domcontentloaded', timeout: 60000 });+await page.goto(bad.toString(), { waitUntil: "domcontentloaded", timeout: 180000 });await page.waitForTimeout(6000);const badMint = await page.evaluate(() => ({phase: window.__CC__?.phase ?? null,diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.jsindex cdb90e065..088483dfe 100644--- a/src/game/coincommunities-ui.js+++ b/src/game/coincommunities-ui.js@@ -1322,19 +1322,21 @@ export class CommunityUI {this.tierBadge = el('span', { class: 'cc-tier-badge', hidden: true });// Buy this coin from inside its own world — the most natural action in a// pump.fun community. Opens the native on-chain buy modal (lazy chunk).- this.buyBtnLabel = el('span', { class: 'cc-buy-btn-text', text: 'Buy' });+ this.buyBtnLabel = el('span', { class: 'cc-buy-btn-text', text: 'Buy', 'data-i18n': 'play.buy' });this.buyBtn = el('button', {class: 'cc-buy-btn', type: 'button', title: 'Buy this coin',+ 'data-i18n-attr': 'title:play.buy_title',onclick: () => this.h.onBuy?.(),- }, [el('span', { class: 'cc-buy-btn-ico', text: '⚡' }), this.buyBtnLabel]);+ }, [el('span', { class: 'cc-buy-btn-ico', 'aria-hidden': 'true', text: '⚡' }), this.buyBtnLabel]);// Creator-only (R24): set the token threshold to enter this coin's Holders// world. Hidden until the server confirms this player is the coin's creator// (build-perms snapshot); shown in both the General and Holders worlds.this.gateBtn = el('button', {class: 'cc-gate-cfg-btn', type: 'button', hidden: true,title: 'Set who can enter the Holders world', 'aria-label': 'Configure the holders gate',+ 'data-i18n-attr': 'title:play.gate_title;aria-label:play.gate_aria',onclick: () => this.h.onConfigureGate?.(),- }, [el('span', { class: 'cc-gate-cfg-ico', 'aria-hidden': 'true', text: '🔑' }), el('span', { class: 'cc-gate-cfg-text', text: 'Gate' })]);+ }, [el('span', { class: 'cc-gate-cfg-ico', 'aria-hidden': 'true', text: '🔑' }), el('span', { class: 'cc-gate-cfg-text', text: 'Gate', 'data-i18n': 'play.gate' })]);// Open the cosmetics shop — browse + try cosmetics on your avatar live.this.shopBtn = el('button', {class: 'cc-shop-btn', type: 'button', title: 'Cosmetics — try looks on your avatar',@@ -1347,8 +1349,9 @@ export class CommunityUI {this.avatarBtn = el('button', {class: 'cc-avatarbtn', type: 'button', title: 'Change your avatar (V)','aria-label': 'Change your avatar', 'aria-expanded': 'false',+ 'data-i18n-attr': 'title:play.avatar_title;aria-label:play.avatar_aria',onclick: () => this.h.onAvatarPanel?.(),- }, [el('span', { class: 'cc-avatarbtn-ico', 'aria-hidden': 'true', text: '🧍' }), el('span', { class: 'cc-avatarbtn-text', text: 'Avatar' })]);+ }, [el('span', { class: 'cc-avatarbtn-ico', 'aria-hidden': 'true', text: '🧍' }), el('span', { class: 'cc-avatarbtn-text', text: 'Avatar', 'data-i18n': 'play.avatar' })]);// Open the "My Cosmetics" wardrobe — equip owned items, persists across worlds.this.wardrobeBtn = el('button', {class: 'cc-wardrobe-btn', type: 'button', title: 'My Cosmetics — equip your owned looks',@@ -1360,8 +1363,9 @@ export class CommunityUI {this.jobsBtn = el('button', {class: 'cc-jobs-btn', type: 'button', title: 'Jobs Board — dailies, courier runs, and the vault heist','aria-label': 'Open the jobs board',+ 'data-i18n-attr': 'title:play.jobs_title;aria-label:play.jobs_aria',onclick: () => this.h.onJobs?.(),- }, [el('span', { class: 'cc-jobs-btn-ico', 'aria-hidden': 'true', text: '🎯' }), el('span', { class: 'cc-jobs-btn-text', text: 'Jobs' })]);+ }, [el('span', { class: 'cc-jobs-btn-ico', 'aria-hidden': 'true', text: '🎯' }), el('span', { class: 'cc-jobs-btn-text', text: 'Jobs', 'data-i18n': 'play.jobs' })]);// Friends panel (W09) — the account-level social graph: requests, live// presence across every coin world, and DM threads. The badge carries the// unread-DM count so a message landing while the panel is closed stilldiff --git a/src/play/war.js b/src/play/war.jsnew file mode 100644index 000000000..61d52a6d6--- /dev/null+++ b/src/play/war.js@@ -0,0 +1,504 @@+// war.js — the Coin Wars arena page (/play/war).+//+// A player presses "Enter the war" at the portal in their coin's world; the+// matchmaker pairs their community with another and hands both sides the same+// signed pairing. This page is where that battle is actually fought: it joins+// ClashRoom under the shared matchKey, renders every fighter, sends movement and+// swing INTENT (the server decides what lands), and walks the player back into+// the world they came from when the round is over.+//+// Everything on screen is real room state. There is no demo mode, no local+// simulation: with no valid pairing the page says so and offers the way back.+//+// URL contract, produced by src/game/war-portal.js:+// /play/war?match=<matchKey>&ticket=<signed pairing>&side=a|b+// &coin=<mint>&name=&symbol=&image=&network=+// &holderPass=<signed holding>&return=<url back into the coin world>++import { Client, getStateCallbacks } from 'colyseus.js';+import { joinRoomWithTimeout } from '../shared/colyseus-connect.js';+import { defaultGameServerUrl } from '../shared/game-server-url.js';+import { ensurePlayAccess } from '../game/play-gate.js';+import { requestHolderPass } from '../community/town-auth.js';+import { createLogger } from '../shared/log.js';+import { WarWorld } from './war-world.js';+import './war.css';++const log = createLogger('war');++const ROOM = 'clash_arena';+const SEND_HZ = 15;+const AVATAR_KEY = 'cc-avatar'; // the avatar the player picked in /play+const FALLBACK_AVATAR = '/avatars/default.glb';++const $ = (id) => document.getElementById(id);+const params = new URLSearchParams(location.search);++const cfg = {+ matchKey: (params.get('match') || '').trim(),+ ticket: (params.get('ticket') || '').trim(),+ side: params.get('side') === 'b' ? 'b' : 'a',+ coin: (params.get('coin') || '').trim(),+ name: (params.get('name') || '').slice(0, 48),+ symbol: (params.get('symbol') || '').slice(0, 16),+ image: (params.get('image') || '').slice(0, 400),+ network: (params.get('network') || 'mainnet').toLowerCase().replace(/[^a-z]/g, '') || 'mainnet',+ holderPass: (params.get('holderPass') || '').trim(),+ // Only ever a same-origin path, so a crafted link cannot use the arena as an+ // open redirect off the site.+ returnTo: safeReturn(params.get('return')),+};++function safeReturn(v) {+ const s = String(v || '');+ return /^\/[^/\\]/.test(s) ? s : '/play';+}++let world = null;+let room = null;+let localId = '';+let phase = 'lobby';+let ended = null; // { winner, reason, scoreA, scoreB, mvp }+let labelEls = new Map();+let sendTimer = 0;+let lastSent = { x: NaN, z: NaN, yaw: NaN, motion: '' };+let attackCooldownUntil = 0;++// ── boot ─────────────────────────────────────────────────────────────────────++(async function boot() {+ wireChrome();++ if (!cfg.matchKey || !cfg.ticket || !cfg.coin) {+ return fail(+ 'No battle to join',+ 'This link is missing its pairing, so there is no arena to open. Walk up to the war portal in your coin world and press E to queue for a war.',+ );+ }++ const serverUrl = defaultGameServerUrl();+ if (!serverUrl) {+ return fail(+ 'The arena server is unreachable',+ 'No game server is configured for this deployment, so a battle cannot be hosted right now. Your place in the league is unaffected.',+ );+ }++ setStatus('Building the arena…');+ world = new WarWorld($('scene'));+ world.setFactions({ a: '', b: '' });+ world.start();+ world.setLabelUpdater(updateLabels);++ try {+ await world.loadAnimations();+ } catch (err) {+ log.warn('animations failed to load', err);+ }++ // The platform play gate, exactly as /play runs it. Open deployments resolve+ // instantly with no overlay.+ let access = { required: false };+ try {+ access = await ensurePlayAccess();+ } catch (err) {+ log.warn('play gate failed, continuing to the room gate', err);+ }++ // The holder pass. The portal usually hands one over; a shared or refreshed+ // link mints its own, which is also what makes this page work as a direct+ // destination rather than only as a hand-off target.+ setStatus('Verifying your holding…');+ let holderPass = cfg.holderPass;+ if (!holderPass) {+ try {+ const res = await requestHolderPass(cfg.coin);+ if (!res?.eligible || !res.holderPass) {+ return fail(+ `You do not hold enough ${coinLabel()} to fight for it`,+ `A war is fought BY a community, so the arena only seats holders of the coin. You hold ${fmtUsd(res?.usd)} of ${coinLabel()}; the floor is ${fmtUsd(res?.minUsd)}.`,+ 'Back to the world',+ );+ }+ holderPass = res.holderPass;+ } catch (err) {+ const msg = err?.code === 'auth_required'+ ? 'Sign in on the coin world first, then walk back to the war portal.'+ : err?.code === 'wallet_required'+ ? 'Link a Solana wallet on the coin world, then walk back to the war portal.'+ : err?.message || 'Your holding could not be verified right now.';+ return fail('Could not verify your holding', msg, 'Back to the world');+ }+ }++ setStatus('Joining the battle…');+ try {+ const client = new Client(serverUrl);+ room = await joinRoomWithTimeout(client, ROOM, {+ matchKey: cfg.matchKey,+ warTicket: cfg.ticket,+ coin: cfg.coin,+ holderPass,+ playPass: access?.playPass || '',+ name: displayName(),+ avatar: savedAvatar(),+ });+ } catch (err) {+ return fail('Could not join the battle', joinErrorText(err), 'Back to the world');+ }++ localId = room.sessionId;+ wireRoom(room);+ setStatus(null);+ $('hud').hidden = false;+ $('controls').hidden = false;++ sendTimer = setInterval(sendPose, 1000 / SEND_HZ);+ addEventListener('beforeunload', () => { try { room?.leave(); } catch { /* closing anyway */ } });+})();++// ── room wiring ──────────────────────────────────────────────────────────────++function wireRoom(r) {+ const $$ = getStateCallbacks(r);+ const s = r.state;++ $$(s).fighters.onAdd((f, id) => {+ world.spawnFighter(id, {+ avatarUrl: f.avatar || FALLBACK_AVATAR,+ faction: f.faction,+ name: f.name,+ x: f.x, y: f.y, z: f.z, yaw: f.yaw,+ }).then((avatar) => {+ if (!avatar) return;+ if (id === localId) world.setLocal(id);+ addLabel(id, f);+ });+ $$(f).onChange(() => {+ world.updateFighter(id, { x: f.x, y: f.y, z: f.z, yaw: f.yaw, motion: f.motion, dead: f.dead });+ if (id === localId) renderVitals(f);+ renderRoster();+ });+ });++ $$(s).fighters.onRemove((f, id) => {+ world.removeFighter(id);+ removeLabel(id);+ renderRoster();+ });++ $$(s).onChange(() => {+ world.setFactions({ a: s.aMint, b: s.bMint });+ if (s.phase !== phase) onPhase(s.phase, s);+ phase = s.phase;+ renderScore(s);+ });++ // The server resolved a swing. A hit shows where it landed; a whiff still+ // shows the shot, so a miss reads as a miss and not as a dropped input.+ r.onMessage('clash:swing', (m) => {+ world.swing(m.id, m.target, { hit: !!m.hit, killed: !!m.killed });+ if (m.killed && m.id === localId) world.celebrate(localId);+ });++ r.onMessage('clash:end', (m) => {+ ended = m;+ showResult(m);+ });++ r.onLeave((code) => {+ if (ended) return; // the result screen already owns the page+ fail(+ 'You left the battle',+ code === 1000+ ? 'The connection to the arena closed. The result, if the battle finished, is already in the league.'+ : 'The connection to the arena dropped. The result, if the battle finished, is already in the league.',+ 'Back to the world',+ );+ });+}++function onPhase(next, s) {+ // Movement is only legal while the fight is on; the countdown and the aftermath+ // hold everyone in place, matching what the server will accept.+ world.setLocked(next !== 'live' && next !== 'sudden_death');+ const banner = $('phase');+ const text = {+ lobby: 'Waiting for the other community',+ countdown: 'Get ready',+ live: 'Fight',+ sudden_death: 'Sudden death — next kill takes it',+ ended: 'Battle over',+ }[next] || next;+ banner.textContent = text;+ banner.dataset.phase = next;+ banner.hidden = false;+ if (next === 'live') setTimeout(() => { if (phase === 'live') banner.hidden = true; }, 1800);+ if (next === 'lobby') {+ $('lobby-note').hidden = false;+ $('lobby-note').textContent = `Holding the line for ${factionLabel(s, cfg.side)} — the battle starts when ${factionLabel(s, cfg.side === 'a' ? 'b' : 'a')} fields a fighter.`;+ } else {+ $('lobby-note').hidden = true;+ }+}++// ── sending ──────────────────────────────────────────────────────────────────++// Position updates are rate-limited server-side (20/s) and rejected outright as+// teleports past 3 m, so we send at 15 Hz and only when something actually moved.+function sendPose() {+ if (!room) return;+ const pose = world?.localPose();+ if (!pose) return;+ if (Math.abs(pose.x - lastSent.x) < 0.01+ && Math.abs(pose.z - lastSent.z) < 0.01+ && Math.abs(pose.yaw - lastSent.yaw) < 0.01+ && pose.motion === lastSent.motion) return;+ lastSent = pose;+ room.send('move', pose);+}++function attack() {+ if (!room || (phase !== 'live' && phase !== 'sudden_death')) return;+ const now = Date.now();+ // Mirrors ClashRoom's ATTACK_COOLDOWN_MS so the button reflects the real rule+ // rather than firing messages the server silently drops.+ if (now < attackCooldownUntil) return;+ attackCooldownUntil = now + 450;+ room.send('attack');+ const btn = $('attack');+ btn.classList.add('is-cooling');+ setTimeout(() => btn.classList.remove('is-cooling'), 450);+}++// ── HUD ──────────────────────────────────────────────────────────────────────++function renderScore(s) {+ const mine = cfg.side === 'a' ? s.aScore : s.bScore;+ const theirs = cfg.side === 'a' ? s.bScore : s.aScore;+ $('score-us').textContent = String(mine);+ $('score-them').textContent = String(theirs);+ $('name-us').textContent = factionLabel(s, cfg.side);+ $('name-them').textContent = factionLabel(s, cfg.side === 'a' ? 'b' : 'a');+ $('cap').textContent = s.scoreCap ? `first to ${s.scoreCap}` : '';++ const target = s.phase === 'countdown' ? s.countdownEndsAt : s.endsAt;+ $('clock').textContent = s.phase === 'sudden_death' ? 'OT' : clock(target - Date.now());+}++function renderVitals(f) {+ $('kills').textContent = String(f.kills || 0);+ $('deaths').textContent = String(f.deaths || 0);+ $('downed').hidden = !f.dead;+ $('attack').disabled = !!f.dead;+}++function renderRoster() {+ if (!room) return;+ let us = 0, them = 0;+ for (const [, f] of room.state.fighters) {+ if (f.faction === (cfg.side === 'a' ? room.state.aMint : room.state.bMint)) us++;+ else them++;+ }+ $('roster-us').textContent = `${us} fighting`;+ $('roster-them').textContent = `${them} fighting`;+}++// Name tags pinned over each fighter's head, coloured by faction so a crowded+// midfield still reads. DOM, not sprites: crisp at any resolution and free.+function addLabel(id, f) {+ if (labelEls.has(id)) return;+ const el = document.createElement('div');+ el.className = `war-tag ${f.faction === room.state.aMint ? 'war-tag-a' : 'war-tag-b'}${id === localId ? ' war-tag-me' : ''}`;+ el.textContent = f.name || 'fighter';+ $('labels').appendChild(el);+ labelEls.set(id, el);+}++function removeLabel(id) {+ labelEls.get(id)?.remove();+ labelEls.delete(id);+}++const _pt = { x: 0, y: 0 };+function updateLabels() {+ for (const [id, el] of labelEls) {+ const p = world.projectHead(id, _pt);+ if (!p) { el.style.opacity = '0'; continue; }+ el.style.opacity = '1';+ el.style.transform = `translate(-50%, -100%) translate(${p.x}px, ${p.y}px)`;+ }+}++// ── result ───────────────────────────────────────────────────────────────────++function showResult(m) {+ const s = room.state;+ const myMint = cfg.side === 'a' ? s.aMint : s.bMint;+ const won = m.winner === myMint;+ const drew = m.winner === 'draw' || !m.winner;+ const mine = cfg.side === 'a' ? m.scoreA : m.scoreB;+ const theirs = cfg.side === 'a' ? m.scoreB : m.scoreA;++ $('result-title').textContent = drew ? 'Draw' : won ? 'Victory' : 'Defeat';+ $('result-title').dataset.outcome = drew ? 'draw' : won ? 'win' : 'loss';+ $('result-score').textContent = `${mine} — ${theirs}`;+ $('result-reason').textContent = reasonLine(m.reason);+ $('result-mvp').textContent = m.mvp+ ? `MVP: ${m.mvp.kills} kills, ${m.mvp.deaths} deaths, ${m.mvp.damage} damage${m.mvp.id === localId ? ' — that was you' : ''}`+ : 'No knockdowns were scored.';+ $('result').hidden = false;+ $('controls').hidden = true;+ world?.setLocked(true);+ // The league write happens as the room ends, so the world we return to can+ // read this battle straight out of the ledger.+ $('result-back').textContent = `Back to ${coinLabel()}`;+}++function goBack() {+ // The return link carries the match key, so the portal board echoes THIS+ // result the moment the world finishes loading.+ const url = new URL(cfg.returnTo, location.origin);+ if (cfg.matchKey && !url.searchParams.get('war')) url.searchParams.set('war', cfg.matchKey);+ try { room?.leave(); } catch { /* leaving anyway */ }+ location.href = url.pathname + url.search;+}++// ── chrome, states, helpers ──────────────────────────────────────────────────++function wireChrome() {+ $('attack').addEventListener('click', attack);+ $('leave').addEventListener('click', goBack);+ $('result-back').addEventListener('click', goBack);+ $('fail-back').addEventListener('click', goBack);+ addEventListener('keydown', (e) => {+ if (e.repeat) return;+ const k = e.key.toLowerCase();+ if (k === ' ' || k === 'f') { e.preventDefault(); attack(); }+ if (k === 'escape' && !$('result').hidden) goBack();+ });+ mountJoystick();+ // The coin the player fights for, painted into the page chrome the moment it+ // loads — before any room state arrives — so the page is never anonymous.+ $('coin-label').textContent = coinLabel();+ if (cfg.image) {+ const img = $('coin-img');+ img.src = cfg.image;+ img.alt = '';+ img.hidden = false;+ }+}++// A thumb stick for phones. Pointer events only — no library, no dependency, and+// it releases cleanly if the finger leaves the screen mid-drag.+function mountJoystick() {+ const pad = $('stick');+ const nub = $('stick-nub');+ let active = null;+ const R = 46;+ const set = (dx, dy) => {+ const d = Math.min(1, Math.hypot(dx, dy) / R);+ const a = Math.atan2(dy, dx);+ const x = Math.cos(a) * d;+ const y = -Math.sin(a) * d;+ nub.style.transform = `translate(${Math.cos(a) * d * R}px, ${Math.sin(a) * d * R}px)`;+ world?.setJoystick(x, y);+ };+ const release = () => {+ active = null;+ nub.style.transform = 'translate(0,0)';+ world?.setJoystick(0, 0);+ };+ pad.addEventListener('pointerdown', (e) => {+ active = { id: e.pointerId, cx: e.clientX, cy: e.clientY };+ pad.setPointerCapture?.(e.pointerId);+ e.preventDefault();+ });+ pad.addEventListener('pointermove', (e) => {+ if (active?.id !== e.pointerId) return;+ set(e.clientX - active.cx, e.clientY - active.cy);+ });+ pad.addEventListener('pointerup', release);+ pad.addEventListener('pointercancel', release);+ pad.addEventListener('lostpointercapture', release);+}++function setStatus(text) {+ const el = $('status');+ if (!text) { el.hidden = true; return; }+ el.hidden = false;+ $('status-text').textContent = text;+}++// Every terminal state is a designed card with a way out, never a blank screen+// or a console error.+function fail(title, detail, action = 'Back to the world') {+ setStatus(null);+ $('hud').hidden = true;+ $('controls').hidden = true;+ $('fail-title').textContent = title;+ $('fail-detail').textContent = detail;+ $('fail-back').textContent = action;+ $('fail').hidden = false;+ clearInterval(sendTimer);+}++// The room throws named errors; each one has a player-readable cause.+function joinErrorText(err) {+ const msg = String(err?.message || '');+ if (msg.includes('war_ticket')) return 'This pairing has expired. Walk back to the war portal and queue again — it only takes a moment.';+ if (msg.includes('holder_pass_mismatch')) return 'Your holding was verified for a different coin than the one this battle seats you under.';+ if (msg.includes('holder_pass_required')) return 'The arena needs a fresh proof that you hold this coin. Queue again from the portal.';+ if (msg.includes('play_pass')) return 'This deployment gates play on a token balance and yours did not clear it.';+ if (msg.includes('clash_faction_full')) return 'This community has already fielded a full roster for the battle. Try the next one.';+ if (msg.includes('clash_faction_mismatch')) return 'You hold a coin that is not one of the two communities in this battle.';+ if (msg.includes('timed out')) return 'The arena server did not answer in time. It may be restarting; try again in a moment.';+ return msg || 'The arena refused the join.';+}++function factionLabel(s, side) {+ const symbol = side === 'a' ? s.aSymbol : s.bSymbol;+ const name = side === 'a' ? s.aName : s.bName;+ return symbol ? `$${symbol}` : (name || 'Community');+}++function coinLabel() {+ return cfg.symbol ? `$${cfg.symbol}` : (cfg.name || 'your community');+}++function displayName() {+ try {+ const stored = localStorage.getItem('cc-name');+ if (stored) return stored.slice(0, 24);+ } catch { /* storage disabled */ }+ return '';+}++function savedAvatar() {+ try {+ return localStorage.getItem(AVATAR_KEY) || FALLBACK_AVATAR;+ } catch {+ return FALLBACK_AVATAR;+ }+}++function clock(ms) {+ const s = Math.max(0, Math.round((Number(ms) || 0) / 1000));+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;+}++function fmtUsd(n) {+ const v = Number(n);+ if (!Number.isFinite(v)) return '$0';+ return v >= 1 ? `$${v.toFixed(2)}` : `$${v.toFixed(4)}`;+}++function reasonLine(reason) {+ switch (reason) {+ case 'score_cap': return 'The kill cap was reached.';+ case 'timeout': return 'The round clock ran out.';+ case 'sudden_death': return 'Taken in sudden death.';+ case 'forfeit': return 'The other side withdrew.';+ default: return 'The battle ended.';+ }+}