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(play): server-side Coin Wars, event scoring, and quest zones

nirholas2207a06f90bd
diff --git a/api/_lib/event-config.js b/api/_lib/event-config.js
index ad554bc29..438073e71 100644
--- a/api/_lib/event-config.js
+++ b/api/_lib/event-config.js
@@ -4,7 +4,7 @@
// countdown pill, the in-world meetup layer, the game server's quest gate
// (multiplayer/src/event-window.js, which reads the same file over HTTP because its
// container ships without public/) and now the leaderboard endpoints. The API
-// process serves that file from disk, so it reads it from disk — no HTTP hop to
+// process serves that file from disk, so it reads it from disk, no HTTP hop to
// itself, and no second copy of the times anywhere.
//
// Parsing is delegated to parseEventWindow so the API and the game server agree on
diff --git a/api/_lib/event-leaderboard-store.js b/api/_lib/event-leaderboard-store.js
index d59bfc6f4..9e15d78b4 100644
--- a/api/_lib/event-leaderboard-store.js
+++ b/api/_lib/event-leaderboard-store.js
@@ -1,15 +1,15 @@
-// Event leaderboard — durable storage for the live event quest line's standing.
+// Event leaderboard, durable storage for the live event quest line's standing.
//
// The authoritative game server (multiplayer WalkRoom) reports every finished event
// quest here through api/internal/event-score.js; api/play/event-leaderboard.js and
// the in-world panel read the ranked table back. The ranking itself lives in
-// multiplayer/src/event-leaderboard.js so both sides sort identically — this module
+// multiplayer/src/event-leaderboard.js so both sides sort identically, this module
// is purely the store.
//
// Shape: one Redis HASH per event (`event:lb:<eventId>`), field = the player's
// account key, value = the JSON record. A HASH (rather than the ZSET clash-store
-// uses) because a row carries more than a score — display name, cash earned, the
-// per-mission breakdown, the timestamp that breaks ties — and the population is one
+// uses) because a row carries more than a score, display name, cash earned, the
+// per-mission breakdown, the timestamp that breaks ties, and the population is one
// event's worth of players, small enough that HGETALL plus an in-process sort is a
// single cheap round-trip. Distinct accounts write distinct fields, and one account
// can only be in one live session (playerStore enforces that upstream), so a per-
@@ -28,7 +28,7 @@ import { applyEventRun, emptyEventRecord, normalizeEventRecord } from '../../mul
const redis = getRedis();
-// Keep a finished event's standing around for a week — long enough for the owner to
+// Keep a finished event's standing around for a week, long enough for the owner to
// read the winners off it and settle prizes by hand.
export const BOARD_TTL_S = 7 * 24 * 60 * 60;
@@ -61,7 +61,7 @@ function redisDegraded(err) {
const now = Date.now();
if (now - _degradedAt > 60_000) {
_degradedAt = now;
- console.warn('[event-leaderboard] redis degraded — serving from in-memory fallback:', err?.message || err);
+ console.warn('[event-leaderboard] redis degraded, serving from in-memory fallback:', err?.message || err);
}
}
diff --git a/api/_lib/feed.js b/api/_lib/feed.js
index f245dabbe..010dd3d23 100644
--- a/api/_lib/feed.js
+++ b/api/_lib/feed.js
@@ -1,9 +1,9 @@
-// Live activity feed store — the cross-surface "something is always happening
+// Live activity feed store, the cross-surface "something is always happening
// here" ticker that makes three.ws feel alive on every page.
//
-// Events are produced from many places — a coin buy confirmed in api/pump, an
+// Events are produced from many places, a coin buy confirmed in api/pump, an
// agent deployed in api/agents, a level-up or a world-join in the standalone
-// multiplayer server — and read by the site-wide widget (public/feed.js) via
+// multiplayer server, and read by the site-wide widget (public/feed.js) via
// GET /api/feed. Storage is a single capped Redis list `feed:events` ordered
// newest-first.
//
@@ -14,33 +14,33 @@
//
// ── Event shape ──────────────────────────────────────────────────────────────
// { id, type, ts, actor, ...typeSpecific }
-// id — opaque unique key; the widget de-dupes and uses it as a render key
-// type — one of ALLOWED_TYPES
-// ts — epoch ms
-// actor — short, already-sanitized display label (truncated wallet, player
+// id, opaque unique key; the widget de-dupes and uses it as a render key
+// type, one of ALLOWED_TYPES
+// ts, epoch ms
+// actor, short, already-sanitized display label (truncated wallet, player
// name, agent name). NEVER a raw secret or full address we wouldn't
-// show publicly — this list is world-readable.
+// show publicly, this list is world-readable.
// coin-buy → { mint, sol, network }
-// agent-deploy → { agentId, name } — new agent joined the registry (off-chain)
-// agent-onchain → { agentId, name, chain } — agent verified on-chain
+// agent-deploy → { agentId, name }, new agent joined the registry (off-chain)
+// agent-onchain → { agentId, name, chain }, agent verified on-chain
// level-up → { skill, level, coin }
// world-join → { coin, coinName }
// jackpot → { reward, coin }
-// mission-complete → { mission, gold, coop, coin } — /play job or heist finished
-// war-result → { winner, reason, a, b, matchKey, network } — a Coin Wars battle ended; actor is the winning community
-// agora-registered → { citizenId, agentPda, profession, narrative } — a citizen joined Agora (AgenC registerAgent)
-// agora-task-posted → { actor, taskPda, profession, rewardLabel, minReputation, cluster } — a bounty was escrowed on the board (createTask)
-// agora-hired → { actor, taskPda, profession, rewardLabel, cluster } — a citizen hired a sub-agent (agent-to-agent)
-// agora-task-claimed → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } — claimed an on-chain task
-// agora-task-completed→ { citizenId, agentPda, profession, taskPda, proofHash, txSig, explorerUrl, narrative } — proof accepted
-// agora-earned → { citizenId, agentPda, profession, rewardLabel, txSig, explorerUrl, narrative } — escrow released to the worker
+// mission-complete → { mission, gold, coop, coin }, /play job or heist finished
+// war-result → { winner, reason, a, b, matchKey, network }, a Coin Wars battle ended; actor is the winning community
+// agora-registered → { citizenId, agentPda, profession, narrative }, a citizen joined Agora (AgenC registerAgent)
+// agora-task-posted → { actor, taskPda, profession, rewardLabel, minReputation, cluster }, a bounty was escrowed on the board (createTask)
+// agora-hired → { actor, taskPda, profession, rewardLabel, cluster }, a citizen hired a sub-agent (agent-to-agent)
+// agora-task-claimed → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative }, claimed an on-chain task
+// agora-task-completed→ { citizenId, agentPda, profession, taskPda, proofHash, txSig, explorerUrl, narrative }, proof accepted
+// agora-earned → { citizenId, agentPda, profession, rewardLabel, txSig, explorerUrl, narrative }, escrow released to the worker
// agora-arena-entered → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } : joined a Competitive task; first valid proof takes the purse
// agora-arena-won → { citizenId, agentPda, profession, taskPda, rewardLabel, txSig, explorerUrl, narrative } : won an Arena race
// agora-arena-lost → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } : another racer proved it first
// agora-guild-joined → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } : joined a Collaborative task alongside other citizens
// agora-guild-contributed → { citizenId, agentPda, profession, taskPda, rewardLabel, txSig, explorerUrl, narrative } : contributed a proof to a Guild; the pool splits across contributors
-// agora-vouched → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } — a Verifier re-derived a proof and it held
-// agora-flagged → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative } — a Verifier re-derived a proof and it did NOT match
+// agora-vouched → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative }, a Verifier re-derived a proof and it held
+// agora-flagged → { citizenId, agentPda, profession, taskPda, txSig, explorerUrl, narrative }, a Verifier re-derived a proof and it did NOT match
//
// All writes are best-effort. The feed is a delight layer, never on a critical
// path: a Redis outage degrades to an empty feed, never a thrown error.
@@ -50,7 +50,7 @@ import { getRedis } from './redis.js';
import { insertNotification } from './notify.js';
const FEED_KEY = 'feed:events';
-const MAX_EVENTS = 200; // capped list — the widget shows ~30; we keep headroom
+const MAX_EVENTS = 200; // capped list, the widget shows ~30; we keep headroom
export const ALLOWED_TYPES = new Set([
'coin-buy',
@@ -62,9 +62,9 @@ export const ALLOWED_TYPES = new Set([
'payment', // skill/service payment confirmed; { usdcAtomic, recipientLabel, txSig, explorerUrl }
'mission-complete', // /play job or co-op heist finished; { mission, gold, coop, coin }
'member-join', // a person signed in to three.ws; { handle } (actor = display name)
- 'agent-guard', // an autonomous buy was REFUSED by a safety rule; { agentId, mint, reason, label } — trust made visible
+ 'agent-guard', // an autonomous buy was REFUSED by a safety rule; { agentId, mint, reason, label }, trust made visible
'war-result', // a Coin Wars battle ended; { winner, reason, a:{mint,name,symbol,score}, b:{…}, matchKey, network }
- // Agora — the living agent economy (workers/agora-citizens). Each is a real
+ // Agora, the living agent economy (workers/agora-citizens). Each is a real
// on-chain AgenC action projected onto the ticker; see docs/agora.md.
'agora-registered', // a citizen registered on AgenC
'agora-task-posted', // a bounty was escrowed on the board (createTask)
@@ -77,7 +77,7 @@ export const ALLOWED_TYPES = new Set([
'agora-arena-lost', // another racer proved the Arena task first
'agora-guild-joined', // joined a Collaborative task (Guild)
'agora-guild-contributed',// contributed a proof to a Guild; the pool splits
- 'agora-vouched', // a Verifier re-derived a deliverable's proof — it holds
+ 'agora-vouched', // a Verifier re-derived a deliverable's proof, it holds
'agora-flagged', // a Verifier re-derived a proof and it did NOT match
]);
@@ -121,8 +121,8 @@ function eventId(ts) {
// { id, type, ts, actor, ...typeSpecific } plus `read` flag and a `link` for
// click-through. Fire-and-forget: never throws.
//
-// @param {string} userId — recipient's user id
-// @param {object} event — { type (USER_EVENT_TYPES), actor, link, ...rest }
+// @param {string} userId, recipient's user id
+// @param {object} event, { type (USER_EVENT_TYPES), actor, link, ...rest }
export function publishUserEvent(userId, event) {
if (!userId || !event || !USER_EVENT_TYPES.has(event.type)) return;
const ts = Number.isFinite(event.ts) ? event.ts : Date.now();
@@ -137,7 +137,7 @@ export function publishUserEvent(userId, event) {
// Append an event to the feed. Returns the stored record (with id + ts filled
// in) or null on a no-op (unknown type, Redis down, malformed input). Never
-// throws — every caller is fire-and-forget on a non-critical path.
+// throws, every caller is fire-and-forget on a non-critical path.
export async function publishFeedEvent(event) {
const r = redis();
if (!r || !event || !ALLOWED_TYPES.has(event.type)) return null;
@@ -208,7 +208,7 @@ const MEMBER_JOIN_TTL_S = 6 * 60 * 60; // 6h
/**
* Publish a 'member-join' feed event when someone signs in, throttled to once
* per `userKey` per MEMBER_JOIN_TTL_S so re-logins don't spam the ticker.
- * Best-effort and fire-and-forget — never throws, returns the stored record or
+ * Best-effort and fire-and-forget, never throws, returns the stored record or
* null (throttled / Redis down / no display name).
*
* @param {object} opts
@@ -238,9 +238,9 @@ export async function publishMemberJoin({ userKey, actor, handle } = {}) {
// Short-lived in-process read cache. The widget is mounted on every page and
// polls this endpoint continuously, so without dedup each poll becomes a Redis
-// command — at platform scale that alone can exhaust the Upstash request quota.
+// command, at platform scale that alone can exhaust the Upstash request quota.
// A warm serverless instance serving a burst of polls reuses one underlying
-// read for READ_CACHE_MS; we always fetch the top CACHE_N (cheap — one command
+// read for READ_CACHE_MS; we always fetch the top CACHE_N (cheap, one command
// regardless of count) and slice per caller, so every limit ≤ CACHE_N is served
// from the same cached array. This bounds Redis reads to ~one per instance per
// window instead of one per client poll. The feed is a delight layer, so a few
diff --git a/api/_lib/migrations/20260807120000_stage_coin_mint.sql b/api/_lib/migrations/20260807120000_stage_coin_mint.sql
index 428c7047b..4626ab6e3 100644
--- a/api/_lib/migrations/20260807120000_stage_coin_mint.sql
+++ b/api/_lib/migrations/20260807120000_stage_coin_mint.sql
@@ -2,7 +2,7 @@
-- stands in.
--
-- The stage's id is already derived from the mint (uuidv5, see
--- multiplayer/src/plaza-stage.js), so this column stores no new authority — it
+-- multiplayer/src/plaza-stage.js), so this column stores no new authority, it
-- records the binding in a readable, queryable form so the /stage directory can
-- link a show back to the world you can walk into, and so a plaza claim can be
-- verified against the row it is about to write.
diff --git a/api/_lib/presence-store.js b/api/_lib/presence-store.js
index 7cbcd89d3..b0ada145c 100644
--- a/api/_lib/presence-store.js
+++ b/api/_lib/presence-store.js
@@ -1,4 +1,4 @@
-// Presence store — the volatile half of the friends system. Who is online and
+// Presence store, the volatile half of the friends system. Who is online and
// which realm they're in changes by the second and is shared across every
// realm-room instance, so it lives in Redis (Upstash REST), not Postgres.
//
@@ -6,7 +6,7 @@
// player joins a realm room it verifies their presence ticket (minted here),
// then writes `presence:<userId>` with a short TTL and refreshes it on a
// heartbeat; on leave it deletes the key. This API only ever READS presence
-// (to annotate the friends list) and MINTS the tickets — it never writes
+// (to annotate the friends list) and MINTS the tickets, it never writes
// presence itself, so a stale process can't claim a user is online forever.
//
// This module also signs the tickets and fires the internal notify webhook the
@@ -17,7 +17,7 @@ import { getRedis } from './redis.js';
import { hmacSha256, constantTimeEquals, sha256Base64Url } from './crypto.js';
const PRESENCE_PREFIX = 'presence:';
-const TICKET_TTL_SEC = 600; // 10 min — the client refreshes well before expiry
+const TICKET_TTL_SEC = 600; // 10 min, the client refreshes well before expiry
function redis() { return getRedis(); }
@@ -68,13 +68,13 @@ function safeParse(s) {
// the avatar without a DB of its own and without trusting a client option.
// The bearer's public profile handle (username + display name) rides the same
// way: it is what lets a realm room publish a VERIFIED three.ws identity on the
-// player schema, so peers can open the real profile, follow, and DM — a client
+// player schema, so peers can open the real profile, follow, and DM, a client
// option could claim anyone's handle, a signed ticket cannot.
// Format: base64url(JSON{uid,exp,crew,crewName,u,dn}).base64url(hmac).
export async function signPresenceTicket(userId) {
const exp = Math.floor(Date.now() / 1000) + TICKET_TTL_SEC;
// Fold in the bearer's crew tag if they're in one. Defensive: a missing crews
- // table (pre-migration) or any lookup error must never break ticket minting —
+ // table (pre-migration) or any lookup error must never break ticket minting,
// friends presence has to keep working regardless of the crew feature.
let crew = '';
let crewName = '';
@@ -107,7 +107,7 @@ export async function signPresenceTicket(userId) {
// Verify a ticket and return { uid, crew, crewName, username, displayName }, or
// null. Mirrored byte-for-byte on the multiplayer side
// (multiplayer/src/presence-token.js); keep the two in sync. (No API caller
-// today — the multiplayer server is the verifier; this stays here as the
+// today, the multiplayer server is the verifier; this stays here as the
// canonical reference implementation.)
export async function verifyPresenceTicket(token) {
if (typeof token !== 'string' || !token.includes('.')) return null;
diff --git a/api/_lib/war-ticket.js b/api/_lib/war-ticket.js
index c8624a2ca..c3fb28361 100644
--- a/api/_lib/war-ticket.js
+++ b/api/_lib/war-ticket.js
@@ -1,4 +1,4 @@
-// War ticket — a short-lived, HMAC-signed pairing the Coin Wars arena trusts.
+// War ticket, a short-lived, HMAC-signed pairing the Coin Wars arena trusts.
//
// Why this exists: ClashRoom is defined with filterBy(['matchKey']), so whoever
// joins a key FIRST also creates the room, and the room reads the two competing
@@ -37,13 +37,13 @@ function secret() {
if (s) return s;
if (process.env.NODE_ENV === 'production') {
throw new Error(
- '[war-ticket] WAR_TICKET_SECRET (or WAR_RESULT_SECRET / HOLDER_PASS_SECRET) is required in production — refusing to mint tickets with the dev secret.',
+ '[war-ticket] WAR_TICKET_SECRET (or WAR_RESULT_SECRET / HOLDER_PASS_SECRET) is required in production, refusing to mint tickets with the dev secret.',
);
}
if (!_warned) {
_warned = true;
console.warn(
- '[war-ticket] no ticket secret set — using the insecure dev secret. ' +
+ '[war-ticket] no ticket secret set, using the insecure dev secret. ' +
'Set WAR_TICKET_SECRET in production or a war pairing can be forged.',
);
}
diff --git a/api/_lib/wars-store.js b/api/_lib/wars-store.js
index 9baa9eab3..06665bae4 100644
--- a/api/_lib/wars-store.js
+++ b/api/_lib/wars-store.js
@@ -1,4 +1,4 @@
-// Coin Wars store — the read/write half of the war league.
+// Coin Wars store, the read/write half of the war league.
//
// Three surfaces live here, all serving /api/wars:
//
@@ -33,7 +33,7 @@ const STANDINGS_WINDOW = 2000;
const RECENT_DEFAULT = 12;
const RECENT_MAX = 50;
-// Redis keys. Shared verbatim with multiplayer/src/war-live.js — the game server
+// Redis keys. Shared verbatim with multiplayer/src/war-live.js, the game server
// writes these, this module reads them, exactly like feed.js / presence-store.js.
const LIVE_KEY = (matchKey) => `wars:live:${matchKey}`;
const LIVE_INDEX = 'wars:live:index';
@@ -140,7 +140,7 @@ export async function readStandings({ network = 'mainnet' } = {}) {
/**
* Every battle currently running, newest heartbeat first. `mint` narrows to wars
* one community is fighting in, which is what the portal board asks for.
- * Returns [] (never throws) when Redis is unavailable — a missing spectator feed
+ * Returns [] (never throws) when Redis is unavailable, a missing spectator feed
* must not take down the standings board it sits beside.
*/
export async function readLiveMatches({ network = 'mainnet', mint = '' } = {}) {
@@ -236,7 +236,7 @@ function requireRedis() {
// A best-effort mutex. Upstash SET NX PX is atomic, so at most one writer holds
// the queue at a time; if the lock cannot be taken within the retry budget we
-// proceed anyway rather than refusing the player — the worst case is the same
+// proceed anyway rather than refusing the player, the worst case is the same
// unpaired-this-poll outcome they would get from an empty queue, and the next
// poll pairs them.
async function acquireQueueLock(redis, network) {
diff --git a/api/cron/treasury-topup.js b/api/cron/treasury-topup.js
index 1853baad4..550fc447e 100644
--- a/api/cron/treasury-topup.js
+++ b/api/cron/treasury-topup.js
@@ -1,14 +1,14 @@
// @ts-check
-// GET /api/cron/treasury-topup — economy funding-root auto-refill.
+// GET /api/cron/treasury-topup, economy funding-root auto-refill.
//
// The companion to relayer-balance-check (which only ALERTS). This cron reads
// every configured engine signer's mainnet SOL balance and, for any that has
// dropped below its `minSol` floor, tops it up from the ONE economy master
-// wallet (api/_lib/economy-master.js) — the "masters fund engines, engines do
+// wallet (api/_lib/economy-master.js), the "masters fund engines, engines do
// the work" model applied platform-wide.
//
// Safe by construction:
-// • Inert until ECONOMY_MASTER_SECRET_BASE58 is set — with no master it does
+// • Inert until ECONOMY_MASTER_SECRET_BASE58 is set, with no master it does
// nothing (relayer-balance-check keeps alerting), so shipping it is a no-op
// until the operator funds WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW.
// • Only ever pays pubkeys derived from SOLANA_SIGNERS (the registry is the
@@ -16,15 +16,15 @@
// • Reserve floor + per-engine cap + per-run cap (see economy-master.js) bound
// every sweep; the reserve floor is an on-chain read, so it holds with no DB.
//
-// Runs every 30 min — fast enough that no engine dries out between sweeps, cheap
+// Runs every 30 min, fast enough that no engine dries out between sweeps, cheap
// enough (one getBalance per signer + at most a handful of transfers) to stay
// well inside the RPC/Upstash budgets.
//
// Env (reuses existing infra):
-// CRON_SECRET — Vercel cron bearer auth (shared with other crons)
-// SOLANA_RPC_URL — mainnet RPC (defaults to api.mainnet-beta)
-// ECONOMY_MASTER_SECRET_BASE58 — the funding-root key (unset ⇒ inert)
-// ECONOMY_MASTER_RESERVE_SOL / _PER_TOPUP_MAX_SOL / _RUN_CAP_SOL — guard caps
+// CRON_SECRET, Vercel cron bearer auth (shared with other crons)
+// SOLANA_RPC_URL, mainnet RPC (defaults to api.mainnet-beta)
+// ECONOMY_MASTER_SECRET_BASE58, the funding-root key (unset ⇒ inert)
+// ECONOMY_MASTER_RESERVE_SOL / _PER_TOPUP_MAX_SOL / _RUN_CAP_SOL, guard caps
import { randomUUID } from 'node:crypto';
import { error, json, method, wrapCron } from '../_lib/http.js';
@@ -60,7 +60,7 @@ export default wrapCron(async (req, res) => {
const errors = [];
// A non-master signer whose SECRET resolves to the master's own wallet (env
// aliasing, e.g. THREE_BUYBACK_SECRET_KEY_B64 set to the master key). Its
- // balance IS the master's balance, so it can never be a refill target — before
+ // balance IS the master's balance, so it can never be a refill target, before
// this check, every sweep listed it as underfunded, filterToRegistry rejected
// the master-to-itself transfer, and the pair of alerts re-fired forever
// (~10k repeats each) while misreporting the count of genuinely dry engines.
@@ -129,7 +129,7 @@ export default wrapCron(async (req, res) => {
// Self-healing fuel: before the master distributes, if it cannot cover the
// engines' real SOL deficit, convert a small bounded slice of its own idle
// USDC into native SOL. The circulation loop leaks SOL to fees every tick, so
- // without a source the funding root drains to zero and /pulse goes quiet —
+ // without a source the funding root drains to zero and /pulse goes quiet,
// this keeps the tank full from revenue instead of waiting on a human. No-op
// unless there is a genuine shortage AND spare USDC (see economy-fuel.js).
const engineDeficitSol = targets.reduce((s, t) => s + Math.max(0, t.refillToSol - t.currentSol), 0);
@@ -185,11 +185,11 @@ export default wrapCron(async (req, res) => {
// Self-healing, step 1b (the other half of the fleet's SOL): the engine reclaim
// above only walks the SOLANA_SIGNERS registry. Most of the platform's SOL lives
// one layer down, in PLATFORM-OWNED agent custody wallets, which had no return
- // path at all — master → agent funding is one-way and snipe proceeds settle back
+ // path at all, master → agent funding is one-way and snipe proceeds settle back
// into the agent, never the master. Without this the fleet can hold plenty of SOL
// while the fee wallet starves under its settle floor (audited 2026-07-28: 7.2 of
// 7.53 SOL stranded in agent wallets, engines at 0.31, rail fully 503). Customer
- // agents are never touched — see reclaimIdleAgentSol's ownership gate.
+ // agents are never touched, see reclaimIdleAgentSol's ownership gate.
let agentReclaim = { reclaimedSol: 0, moves: [], skipped: [], failed: [] };
if (totalDeficitSol > 0 && reclaim.reclaimedSol < totalDeficitSol) {
try {
@@ -298,7 +298,7 @@ export default wrapCron(async (req, res) => {
// Self-healing, step 2 (revenue): if reclaim did not close the gap, convert a
// small bounded slice of the master's own idle USDC into native SOL. The
// circulation loop leaks SOL to fees every tick, so without a source the funding
- // root drains to zero and /pulse goes quiet — this keeps the tank full from
+ // root drains to zero and /pulse goes quiet, this keeps the tank full from
// revenue instead of waiting on a human. No-op unless a genuine shortage remains
// AND there is spare USDC (see economy-fuel.js).
let fuel = { acted: false, reason: 'not_needed' };
@@ -358,7 +358,7 @@ export default wrapCron(async (req, res) => {
// The sweep is the only leg that both reads AND moves SOL, so it is the one
// that dies when every RPC lane is cooling at once. Letting it throw took the
- // whole cron down with a 500 (2026-08-07: ~1 in 15 ticks) — and this cron IS
+ // whole cron down with a 500 (2026-08-07: ~1 in 15 ticks), and this cron IS
// the self-heal for a starved engine, so the outage disabled its own remedy
// exactly when the ring needed it. An exhausted lane chain is upstream
// weather, not a bug: report it as a skipped sweep the same way wrapCron
@@ -371,7 +371,7 @@ export default wrapCron(async (req, res) => {
} catch (e) {
if (!isTransientRpcError(e)) throw e;
const reason = e?.message || 'rpc_unavailable';
- console.warn(`[cron] treasury-topup sweep skipped — solana rpc unavailable: ${reason}`);
+ console.warn(`[cron] treasury-topup sweep skipped, solana rpc unavailable: ${reason}`);
return json(res, 200, {
ok: false,
reason: 'rpc_unavailable',
@@ -414,7 +414,7 @@ export default wrapCron(async (req, res) => {
// Record the sweep to the tamper-evident accounting ledger. Every transfer,
// block, and failure becomes a hash-chained row; the heartbeat row proves the
- // monitor ran even on a no-op sweep. The write never fails the response — but
+ // monitor ran even on a no-op sweep. The write never fails the response, but
// if SOL moved and the record was dropped, that is a monitoring gap an operator
// must know about (the reconcile cron would flag the tx as unrecorded).
let ledger = { written: 0 };
@@ -433,7 +433,7 @@ export default wrapCron(async (req, res) => {
if (ledger.skippedWrite && result.funded.length > 0) {
await sendOpsAlert(
`🧾 Economy ledger did NOT record a real transfer`,
- `sweep ${runId} moved ${result.spentSol} SOL across ${result.funded.length} transfer(s) but the ledger write failed (${ledger.skippedWrite}). The money moved; the book is behind. economy-reconcile will flag these as unrecorded — reconcile manually.`,
+ `sweep ${runId} moved ${result.spentSol} SOL across ${result.funded.length} transfer(s) but the ledger write failed (${ledger.skippedWrite}). The money moved; the book is behind. economy-reconcile will flag these as unrecorded, reconcile manually.`,
{ signature: `economy-ledger-miss:${runId}` },
);
}
@@ -441,7 +441,7 @@ export default wrapCron(async (req, res) => {
// Alert when the master is configured but too drained to cover a real deficit
// AND self-healing could not rescue it (USDC exhausted, daily cap hit, or fuel
- // disabled) — that is the one condition a human must act on (fund the root).
+ // disabled), that is the one condition a human must act on (fund the root).
// When the refuel swap DID act, the shortage is being handled autonomously, so
// suppress the page: the next tick distributes the freshly-bought SOL.
if (result.configured && targets.length > 0 && result.spentSol === 0 && result.funded.length === 0 && !fuel.acted) {
diff --git a/api/internal/event-score.js b/api/internal/event-score.js
index f1787b980..1d47bfad3 100644
--- a/api/internal/event-score.js
+++ b/api/internal/event-score.js
@@ -1,10 +1,10 @@
-// POST /api/internal/event-score — the multiplayer server → API bridge for the live
+// POST /api/internal/event-score, the multiplayer server → API bridge for the live
// event leaderboard.
//
// When a player finishes one of the event quest line's jobs (multiplayer/src/
// quests.js, `event: true`), the authoritative Colyseus room reports it here. Only
// completions that the room's own quest engine granted ever reach this endpoint, and
-// only inside the event window that the room re-derives server-side — a client can
+// only inside the event window that the room re-derives server-side, a client can
// neither claim a run nor forge one for another player.
//
// Trust model mirrors api/internal/quest-notify.js: a valid world-service token
@@ -25,7 +25,7 @@ import { isEventLive } from '../../multiplayer/src/event-window.js';
import { isEventMission } from '../../multiplayer/src/quests.js';
export default wrap(async (req, res) => {
- // Server-to-server only — no browser origin ever calls this directly.
+ // Server-to-server only, no browser origin ever calls this directly.
if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['POST'])) return;
diff --git a/api/play/event-leaderboard.js b/api/play/event-leaderboard.js
index 67c7baa09..7426d4a85 100644
--- a/api/play/event-leaderboard.js
+++ b/api/play/event-leaderboard.js
@@ -2,22 +2,22 @@
//
// The live standing for the platform event's in-world quest line: who has completed
// the most event jobs inside the window, tiebroken by the event gold they earned.
-// One read, two consumers — the in-world panel (the multiplayer room proxies this
-// call for its clients) and the web event page — so the ranking a player sees at the
+// One read, two consumers, the in-world panel (the multiplayer room proxies this
+// call for its clients) and the web event page, so the ranking a player sees at the
// jobs board is byte-for-byte the ranking the site shows.
//
// Query:
-// account optional — a player's account key; pins their own row in `you`, even
+// account optional, a player's account key; pins their own row in `you`, even
// when they are outside the top N. Omitted for an anonymous
// web read.
-// limit optional — how many rows to return (default 10, max 100).
+// limit optional, how many rows to return (default 10, max 100).
//
// Scores are written only by the authoritative game server through
// api/internal/event-score.js; this endpoint is read-only and never grants anything.
// Prizes are NOT settled here: the board ranks, and the owner pays the winners
// manually after the event. Nothing in this path touches a wallet or a chain.
//
-// Shape (always 200 when an event is configured — an event nobody has played yet is
+// Shape (always 200 when an event is configured, an event nobody has played yet is
// an empty board, not an error):
// {
// event: { id, name, startsAt, endsAt, live },
diff --git a/api/stage/index.js b/api/stage/index.js
index 9258a26e8..db5028fdd 100644
--- a/api/stage/index.js
+++ b/api/stage/index.js
@@ -1,5 +1,5 @@
/**
- * Living Stages — stage + show lifecycle (Moonshot 04).
+ * Living Stages, stage + show lifecycle (Moonshot 04).
*
* A "stage" is a venue where an embodied AI agent hosts live, monetized shows.
* A "show" is one live session against that stage; "show_tips" is the per-show
@@ -78,7 +78,7 @@ async function ensureTables() {
)
`;
await sql`CREATE INDEX IF NOT EXISTS shows_stage ON shows (stage_id, started_at DESC)`;
- // Exactly one open show per stage — a partial unique index makes "go live twice"
+ // Exactly one open show per stage, a partial unique index makes "go live twice"
// a no-op rather than a second open row the tips would split across.
await sql`CREATE UNIQUE INDEX IF NOT EXISTS shows_one_open ON shows (stage_id) WHERE ended_at IS NULL`;
await sql`
@@ -115,7 +115,7 @@ async function ensureTables() {
}
// Resolve the host agent's Solana wallet (the tip target) without provisioning on
-// a public read — only return an address that already exists. Provisioning
+// a public read, only return an address that already exists. Provisioning
// happens at stage creation, when the owner is authenticated.
async function readHostWallet(agentId) {
const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1`;
@@ -216,7 +216,7 @@ async function handleGet(req, res) {
// ── the stage standing in a coin world's plaza (F17) ──────────────────────
// The /play client derives this id itself (multiplayer/src/plaza-stage.js) and
- // only needs the show state, so an UNCLAIMED plaza is a 200 with stage:null —
+ // only needs the show state, so an UNCLAIMED plaza is a 200 with stage:null,
// the quiet-landmark case is normal, not an error.
if (req.query.coin) {
const mint = cleanStr(req.query.coin, MAX_MINT);
@@ -345,13 +345,13 @@ async function claimPlaza(req, res, session, body) {
});
}
// One stage per agent (stages_agent_uniq). An agent that already has a stage
- // elsewhere cannot also take a plaza — say so with the id they already own
+ // elsewhere cannot also take a plaza, say so with the id they already own
// rather than failing on a constraint the caller can't see.
const [existing] = await sql`SELECT id FROM stages WHERE agent_id = ${agent.id} LIMIT 1`;
if (existing && existing.id !== stageId) {
return json(res, 409, {
error: 'agent_has_stage',
- message: 'this agent already hosts another stage — use a different agent for the plaza',
+ message: 'this agent already hosts another stage, use a different agent for the plaza',
stageId: existing.id,
});
}
@@ -391,7 +391,7 @@ async function goLive(req, res, session, body) {
const stage = await ownedStage(body.stageId, session.id);
if (!stage) return json(res, 403, { error: 'you do not own this stage' });
- // Open a show (idempotent via the partial unique index — a second go-live
+ // Open a show (idempotent via the partial unique index, a second go-live
// returns the already-open show rather than a duplicate).
const [show] = await sql`
INSERT INTO shows (stage_id) VALUES (${stage.id})
@@ -400,7 +400,7 @@ async function goLive(req, res, session, body) {
`;
await sql`UPDATE stages SET status = 'live', updated_at = NOW() WHERE id = ${stage.id}`;
- // Tell holders the show is starting — in-app bell + a best-effort Telegram ping.
+ // Tell holders the show is starting, in-app bell + a best-effort Telegram ping.
insertNotification(session.id, 'stage_live', {
stage_id: stage.id,
agent_id: stage.agent_id,
@@ -451,7 +451,7 @@ function shapeStage(s) {
next_show_at: s.next_show_at ? Date.parse(s.next_show_at) : null,
host_name: s.agent_name,
host_avatar: s.avatar_url || s.profile_image_url || null,
- // The /play world this stage stands in, when it is a plaza stage — lets the
+ // The /play world this stage stands in, when it is a plaza stage, lets the
// directory card offer "attend in-world" alongside the /stage venue link.
coin_mint: s.coin_mint || null,
};
diff --git a/api/wars.js b/api/wars.js
index b7a423a66..77d8e28d9 100644
--- a/api/wars.js
+++ b/api/wars.js
@@ -1,4 +1,4 @@
-// /api/wars — the public face of Coin Wars.
+// /api/wars, the public face of Coin Wars.
//
// One endpoint serves everything the war portal in /play and the arena page at
// /play/war need, plus the write the game server makes when a battle ends:
@@ -51,7 +51,7 @@ export default wrap(async (req, res) => {
if (action === 'report') return handleReport(req, res);
if (action === 'queue') return handleQueue(req, res, url);
if (action === 'leave') return handleLeave(req, res, url);
- return error(res, 400, 'validation_error', 'unknown action — expected report, queue or leave');
+ return error(res, 400, 'validation_error', 'unknown action, expected report, queue or leave');
}
const rl = await limits.publicIp(clientIp(req));
@@ -70,7 +70,7 @@ async function handleBoard(res, url) {
// Each surface degrades on its own. A cold database must not blank the live
// war a player is standing in front of, and a Redis outage must not hide the
- // league table — so failures resolve to an explicit availability flag rather
+ // league table, so failures resolve to an explicit availability flag rather
// than to a 500 or, worse, to a silently empty board that reads as "no wars".
const [standings, recent, live, queue] = await Promise.all([
readStandings({ network }).catch((err) => ({ error: err, standings: [], battlesRead: 0, windowFull: false })),
@@ -88,7 +88,7 @@ async function handleBoard(res, url) {
network,
coin: coin || null,
// The requesting community's league row, or null when it has never
- // fought — the portal renders a designed "unranked" state from that.
+ // fought, the portal renders a designed "unranked" state from that.
standing: row,
standings: table,
ledgerAvailable: !standings.error,
diff --git a/multiplayer/src/combat-handlers.js b/multiplayer/src/combat-handlers.js
index b288a218a..a1df33a32 100644
--- a/multiplayer/src/combat-handlers.js
+++ b/multiplayer/src/combat-handlers.js
@@ -1,18 +1,18 @@
-// Combat handlers for the /play coin worlds (W07) — the network-and-AI half of
+// Combat handlers for the /play coin worlds (W07), the network-and-AI half of
// combat.js's pure math. Mirrors activities.js's split: the room registers a
// couple of message handlers and two ticks here, and this file reaches back into
// the room's authoritative helpers (`_actionOk`, `_grantXp`, `_sendInv`,
// `_questEvent`, `_persistEcon`, `econ`, `clients`) rather than duplicating them.
//
// Three things live here:
-// 1. Mob AI — roaming PvE enemies confined to the named DANGER_ZONES, chasing
+// 1. Mob AI, roaming PvE enemies confined to the named DANGER_ZONES, chasing
// and attacking the nearest player through the SAME damage path an 'attack'
// intent uses, so a mob hit and a player hit are one code path
// (combat.js applyDamage), not two.
-// 2. The 'attack' intent — validate weapon/ammo/cooldown/zone, pick a target
+// 2. The 'attack' intent, validate weapon/ammo/cooldown/zone, pick a target
// with combat.selectTarget, roll damage, apply it, and (on a kill) spill a
// lootable tombstone.
-// 3. The 'loot' intent — claim a tombstone's cash + items when standing beside
+// 3. The 'loot' intent, claim a tombstone's cash + items when standing beside
// it.
//
// Authority model mirrors _handleFish/activities.js: the client only ever sends
@@ -32,7 +32,7 @@ import {
} from './combat.js';
import { Mob, Tombstone } from './schemas.js';
-// How often the mob AI advances (ms). Coarser than the 15 Hz move rate — mobs
+// How often the mob AI advances (ms). Coarser than the 15 Hz move rate, mobs
// don't need move-grade smoothness, and the client interpolates between ticks.
export const MOB_TICK_MS = 200;
// Wanted/heat decay cadence (ms). Independent of the mob tick so tuning one
@@ -48,7 +48,7 @@ export const TOMBSTONE_TTL_MS = 180_000;
// How close a player must stand to a tombstone to loot it.
export const LOOT_REACH_M = 3.2;
-// This zone's PvE roster, by DANGER_ZONES id — a difficulty gradient across the
+// This zone's PvE roster, by DANGER_ZONES id, a difficulty gradient across the
// three named wilds so a player has somewhere easier to start and something to
// grow into, matching the loot tables' own "richer than an ogre" framing for the
// troll. Kept here (not in world-features.js) since it's a combat-only concern.
@@ -230,7 +230,7 @@ function spillTombstone(room, x, z, ownerName, drop) {
}
// Kill a player: drop their carried gold + pack into a tombstone (banked cash
-// and equipped hotbar tools/weapons are untouched — dropCarried's own risk/
+// and equipped hotbar tools/weapons are untouched, dropCarried's own risk/
// reward contract), flag them downed on the shared schema so peers stop
// targeting them and render the ragdoll, and schedule a clean respawn at the
// safe spawn point.
@@ -302,7 +302,7 @@ export function handleAttack(room, client) {
return;
}
if (!isDangerZone(player.x, player.z)) {
- client.send('notice', { kind: 'attack', ok: false, text: 'The wilds are past the edge of town — fights only break out there.' });
+ client.send('notice', { kind: 'attack', ok: false, text: 'The wilds are past the edge of town, fights only break out there.' });
return;
}
const now = Date.now();
diff --git a/multiplayer/src/cosmetics-catalog.js b/multiplayer/src/cosmetics-catalog.js
index ad2f60856..ec8c2d5b6 100644
--- a/multiplayer/src/cosmetics-catalog.js
+++ b/multiplayer/src/cosmetics-catalog.js
@@ -1,19 +1,19 @@
-// Cosmetics catalog — the single source of truth for every wearable in the
+// Cosmetics catalog, the single source of truth for every wearable in the
// world, shared verbatim by the authoritative server (WalkRoom validates equips
// and ownership against it) and the client (the creator wardrobe renders it, and
// every player's rig applies it). Keep it dependency-free so both the Node server
-// and the Vite client import the exact same table — a cosmetic that exists on one
+// and the Vite client import the exact same table, a cosmetic that exists on one
// side but not the other would let a player wear something peers can't render.
//
// A cosmetic is purely visual (see cosmetics-visual.js): it never touches a
// gameplay value. Each entry carries a `visual` spec the renderer turns into
// Three.js objects:
-// tint — recolour the body (a dye), { tint:'#rrggbb' }
-// prop — a GLB worn on the head/face, { prop:'/url.glb', anchor:'head'|'face' }
-// aura — a glowing ground ring, { aura:'#rrggbb' }
+// tint, recolour the body (a dye), { tint:'#rrggbb' }
+// prop, a GLB worn on the head/face, { prop:'/url.glb', anchor:'head'|'face' }
+// aura, a glowing ground ring, { aura:'#rrggbb' }
//
// Slots are exclusive: a player wears at most one cosmetic per slot. The `none`
-// entry in each slot is the bare default everyone owns — equipping it clears the
+// entry in each slot is the bare default everyone owns, equipping it clears the
// slot. Props reference the real GLBs already shipped in public/accessories/, so
// nothing here points at an asset that 404s.
@@ -30,7 +30,7 @@ export const SLOT_LABELS = {
// tier: 'free' is owned by everyone implicitly; 'premium' must be unlocked
// (W04's shop grants it into the account's owned list). `price` is the $THREE
-// cost the shop will charge — surfaced here so the wardrobe can show it, but W03
+// cost the shop will charge, surfaced here so the wardrobe can show it, but W03
// never sells (it only exposes the unlock hook).
//
// A third tier, 'event', is a souvenir: it is GRANTED, never sold. The server
@@ -96,7 +96,7 @@ export function isFreeCosmetic(id) {
return !!c && c.tier === 'free';
}
-// Is this id an event souvenir — granted for being somewhere at some time, never
+// Is this id an event souvenir, granted for being somewhere at some time, never
// purchasable? The grant path (event-drop.js → WalkRoom) checks this so a
// misconfigured event can never hand out a boutique item for nothing, and the
// wardrobe checks it so a locked souvenir offers no "buy it" shortcut.
@@ -106,7 +106,7 @@ export function isEventCosmetic(id) {
}
// Is this id one an account has to explicitly own to wear (premium or event)?
-// The inverse of isFreeCosmetic for known ids — used by the persistence layer,
+// The inverse of isFreeCosmetic for known ids, used by the persistence layer,
// which must keep every unlocked id regardless of how it was unlocked.
export function isUnlockableCosmetic(id) {
const c = getCosmetic(id);
@@ -125,7 +125,7 @@ export function canWear(id, owned) {
// Coerce an arbitrary equipped map (from a client or a persisted blob) into a
// valid, slot-correct loadout the wearer is actually allowed to use. Anything
-// invalid, in the wrong slot, or unowned falls back to that slot's default — so a
+// invalid, in the wrong slot, or unowned falls back to that slot's default, so a
// tampered payload can never put an unowned cosmetic on a player.
export function sanitizeLoadout(equipped, owned) {
const out = { ...DEFAULT_LOADOUT };
@@ -153,7 +153,7 @@ export function serializeLoadout(equipped) {
}
// Parse the wire string back into the list of catalog entries to render. Tolerant
-// of unknown/empty ids (a peer on a newer catalog) — they're simply skipped.
+// of unknown/empty ids (a peer on a newer catalog), they're simply skipped.
export function parseLoadout(str) {
if (!str || typeof str !== 'string') return [];
return str.split(',').map((id) => getCosmetic(id.trim())).filter((c) => c && c.visual);
diff --git a/multiplayer/src/economy.js b/multiplayer/src/economy.js
index 7f3ada4dd..8ca0725f4 100644
--- a/multiplayer/src/economy.js
+++ b/multiplayer/src/economy.js
@@ -1,7 +1,7 @@
// Economy & progression for the /play coin worlds.
//
// /play is a free-roam, per-coin social world where a player's pack and purse are
-// PRIVATE — no peer needs to see them — so we keep all of it OFF the shared
+// PRIVATE, no peer needs to see them, so we keep all of it OFF the shared
// WalkState schema and stream each owner only their own state via targeted
// messages.
//
@@ -9,7 +9,7 @@
// peers zero extra wire bytes, and lets the economy grow (cooking, gathering,
// commerce) without ever repricing the movement-critical position deltas.
//
-// A "profile" here is a plain JS object — not a Schema — so these helpers operate
+// A "profile" here is a plain JS object, not a Schema, so these helpers operate
// on ordinary arrays. The shapes mirror items.js/playerStore.js so a fish caught on
// /play means the same thing it does in /game, and a profile persists through the
// same account-keyed playerStore.
@@ -27,20 +27,20 @@ export const HOTBAR_SIZE = 6;
export const MAX_STACK = 999;
export const LEVEL_CAP = 99;
export const SKILLS = ['combat', 'woodcutting', 'mining', 'fishing', 'cooking'];
-// The armor layer's ceiling — a vest tops you up to here, and incoming damage eats
+// The armor layer's ceiling, a vest tops you up to here, and incoming damage eats
// armor before HP (see combat.js applyDamage). One capped bar, so it reads cleanly.
export const MAX_ARMOR = 100;
// Starter kit handed to a brand-new player so the loop is exercisable the moment
// they land: a fishing rod (cast at any pond), the gathering tools, and BOTH a
-// melee (sword) and ranged (pistol) weapon so the W07 combat loop — swing, shoot,
-// heal, re-armor — is playable on arrival. Tools occupy the hotbar.
+// melee (sword) and ranged (pistol) weapon so the W07 combat loop, swing, shoot,
+// heal, re-armor, is playable on arrival. Tools occupy the hotbar.
const STARTER_HOTBAR = ['rod', 'axe', 'pickaxe', 'sword', 'pistol'];
// Backpack seed so a new player can fire and survive their first fight without a
// shop run: a clip of pistol ammo and one body-armor vest.
const STARTER_INV = [{ item: 'ammo', qty: 24 }, { item: 'vest', qty: 1 }];
-// XP curve — the canonical progression for the platform: level n needs
+// XP curve, the canonical progression for the platform: level n needs
// 50 * n^1.8 cumulative XP, capped at LEVEL_CAP.
export function levelForXp(xp) {
let lvl = 1;
@@ -70,19 +70,19 @@ export function newProfile(playerId = '') {
return {
playerId,
gold: 0,
- bank: 0, // banked cash — protected on death (carried `gold` drops). W04 extends.
+ bank: 0, // banked cash, protected on death (carried `gold` drops). W04 extends.
hp: 100,
maxHp: 100,
armor: 0, // armor layer that absorbs damage before HP; refilled by a vest.
maxArmor: MAX_ARMOR,
- heat: 0, // wanted/heat meter (0..MAX_HEAT) — raised by crimes, decays over time.
+ heat: 0, // wanted/heat meter (0..MAX_HEAT), raised by crimes, decays over time.
inv,
hotbar,
activeSlot: 0, // the rod, ready to cast
xp: Object.fromEntries(SKILLS.map((s) => [s, 0])),
levels: Object.fromEntries(SKILLS.map((s) => [s, 1])),
// Wheel of Fortune (W09/Task 19): epoch ms the next free spin unlocks. Unlike
- // the ephemeral per-action `cd` map (WalkRoom.js, reset every reconnect —
+ // the ephemeral per-action `cd` map (WalkRoom.js, reset every reconnect,
// fine for a sub-second gather cooldown), this MUST survive a disconnect: a
// 12h cooldown that resets on reconnect would be free to farm. Persisted
// through serializeProfile/restoreProfile below.
@@ -106,7 +106,7 @@ export function ownedCosmeticSet(profile) {
// Grant an unlockable cosmetic into an account's owned list. Two callers: the
// W04 boutique after a $THREE payment settles (premium tier), and the event-drop
// grant when a player is in the world during a live meetup (event tier).
-// Idempotent; ignores free or unknown ids — a free cosmetic is implicitly owned
+// Idempotent; ignores free or unknown ids, a free cosmetic is implicitly owned
// and storing it would bloat every save with nothing. Returns true when it newly
// unlocked something, so the caller can skip a persist that would change nothing.
export function grantCosmetic(profile, id) {
@@ -123,7 +123,7 @@ export function grantCosmetic(profile, id) {
// Redis) into a profile's unlocked set. `ledgerIds` is the raw SMEMBERS of
// `cosmetics:owned:<account>`; only ids that are premium cosmetics in THIS
// catalog are granted (the ledger may also hold ids from a sibling catalog the
-// rig can't render — those are ignored, never errored). Idempotent via
+// rig can't render, those are ignored, never errored). Idempotent via
// grantCosmetic. Returns the count newly unlocked, so a caller can skip a persist
// when nothing changed.
//
@@ -154,7 +154,7 @@ export function equipCosmetic(profile, id) {
}
// Rebuild a profile from a persisted blob (playerStore `profile` field). Tolerant
-// of partial/legacy/missing data — every field is clamped and defaulted so a
+// of partial/legacy/missing data, every field is clamped and defaulted so a
// corrupt save can never crash a join; missing → a fresh starter profile.
export function restoreProfile(saved, playerId = '') {
if (!saved || typeof saved !== 'object') return newProfile(playerId);
@@ -269,7 +269,7 @@ export function addItem(profile, item, qty) {
return left;
}
-// Total quantity of `item` held across the backpack (hotbar tools aren't counted —
+// Total quantity of `item` held across the backpack (hotbar tools aren't counted,
// resources and food live in the pack). Used to gate cooking ("any raw fish?").
export function countItem(profile, item) {
let n = 0;
@@ -305,7 +305,7 @@ export function resolveSlot(profile, ref) {
}
// Grant XP in a skill. Mutates the profile and returns the detail the owner's
-// client needs to animate the gain and (when crossed) the level-up — including the
+// client needs to animate the gain and (when crossed) the level-up, including the
// current level's XP boundaries so the bar is exact without a round-trip.
export function grantXp(profile, skill, amount) {
if (!SKILLS.includes(skill)) return null;
@@ -364,7 +364,7 @@ export function profileSnapshot(profile) {
export function consumeSlot(profile, slot) {
if (!slot || !slot.item) return { ok: false, reason: 'inedible' };
- // Body armor — refill the armor bar instead of HP.
+ // Body armor, refill the armor bar instead of HP.
const armorPts = armorValue(slot.item);
if (armorPts > 0) {
const cap = profile.maxArmor || MAX_ARMOR;
@@ -391,7 +391,7 @@ export function consumeSlot(profile, slot) {
// Strip the carried valuables a tombstone inherits when this player dies: all
// carried cash (`gold`) plus everything in the BACKPACK. Equipped hotbar tools and
-// weapons are kept so a respawn isn't toothless, and BANKED cash is untouched —
+// weapons are kept so a respawn isn't toothless, and BANKED cash is untouched,
// that's the whole risk/reward point of banking. Mutates the profile (zeroing the
// dropped slice) and returns { gold, items:[{item,qty}] } for the tombstone.
export function dropCarried(profile) {
@@ -415,7 +415,7 @@ export function creditGold(profile, amount) {
}
// Restore a player to fighting shape after respawn: full HP and a cleared armor bar
-// (you lose your vest on death — re-armor from the pack or a vendor).
+// (you lose your vest on death, re-armor from the pack or a vendor).
export function reviveProfile(profile) {
profile.hp = profile.maxHp;
profile.armor = 0;
diff --git a/multiplayer/src/event-leaderboard.js b/multiplayer/src/event-leaderboard.js
index ce45517f1..40ee6fa5d 100644
--- a/multiplayer/src/event-leaderboard.js
+++ b/multiplayer/src/event-leaderboard.js
@@ -1,4 +1,4 @@
-// Event leaderboard — the pure ranking math behind the live event quest line.
+// Event leaderboard, the pure ranking math behind the live event quest line.
//
// The event jobs (quests.js, `event: true`) pay in ordinary in-world gold; this is
// the standing that says who ran the most of them inside the window. Like
@@ -9,11 +9,11 @@
// never rank the same data two different ways.
//
// Ranking, in order:
-// 1. runs — event quests completed inside the window (the headline)
-// 2. cash — total event gold earned (the tiebreak: harder jobs pay more)
-// 3. lastAt — earliest to reach that score wins (a tie broken by the clock is
+// 1. runs, event quests completed inside the window (the headline)
+// 2. cash, total event gold earned (the tiebreak: harder jobs pay more)
+// 3. lastAt, earliest to reach that score wins (a tie broken by the clock is
// fairer than one broken by an id, and it rewards finishing early)
-// 4. account — a stable last resort so the order is total and reproducible
+// 4. account, a stable last resort so the order is total and reproducible
//
// Prizes are NOT paid here or anywhere in code. The board ranks; the owner settles
// after the event.
@@ -58,7 +58,7 @@ function nonNegInt(v) {
}
// 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
+// 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 || '');
@@ -104,7 +104,7 @@ function publicRow(row) {
// The payload the in-world panel and the read endpoint both serve: the top N, the
// requesting player's own row (pinned, whatever their rank), and the totals that let
// a UI say "12 of 41 runners" without a second call. `account` may be omitted for an
-// anonymous read (the web page) — `you` is then null.
+// anonymous read (the web page), `you` is then null.
export function eventBoardView(records = [], { account = '', limit = TOP_LIMIT } = {}) {
const ranked = rankEventBoard(records);
const cap = Math.max(1, Math.min(100, limit | 0 || TOP_LIMIT));
diff --git a/multiplayer/src/event-score.js b/multiplayer/src/event-score.js
index 0e7fa6af1..910fc52cd 100644
--- a/multiplayer/src/event-score.js
+++ b/multiplayer/src/event-score.js
@@ -1,4 +1,4 @@
-// Event leaderboard bridge — the game server's client for the event standing.
+// Event leaderboard bridge, the game server's client for the event standing.
//
// The board is stored on the API side (api/_lib/event-leaderboard-store.js) rather
// than in this process because a player's runs have to survive a room disposal, a
@@ -42,7 +42,7 @@ function secret() {
/**
* Report one finished event quest. Returns the player's updated totals, or null if
- * the report did not land (offline API, closed window, unconfigured secret) — the
+ * the report did not land (offline API, closed window, unconfigured secret), the
* caller has already paid the player their in-world gold either way.
*
* @param {{ eventId: string, account: string, name?: string, missionId: string, gold?: number }} run
@@ -77,7 +77,7 @@ const _cache = new Map(); // `${eventId}|${account}` → { at, body }
/**
* Read the ranked board (top rows plus this account's own row). Returns the API's
- * payload, or null when it is unreachable — the client renders its error state
+ * payload, or null when it is unreachable, the client renders its error state
* rather than a stale or invented ranking.
*/
export async function fetchEventBoard({ account = '', limit = 10 } = {}) {
diff --git a/multiplayer/src/event-window.js b/multiplayer/src/event-window.js
index 123ac02a8..09eb41386 100644
--- a/multiplayer/src/event-window.js
+++ b/multiplayer/src/event-window.js
@@ -1,4 +1,4 @@
-// Live-event window — the server's own read of public/event.json.
+// Live-event window, the server's own read of public/event.json.
//
// The countdown pill, the in-world meetup layer and the /play agenda all derive
// their timing from ONE config file (public/event.json). The event quest line and
@@ -7,7 +7,7 @@
//
// This process ships without the repo's `public/` directory (multiplayer/Dockerfile
// copies only src/), so the config is read over HTTP from the site that serves it
-// — the same origin persistence.js and quest-notify.js already talk to. The times
+//, the same origin persistence.js and quest-notify.js already talk to. The times
// are never transcribed into code here: parse what the file says, or run nothing.
//
// Failure is CLOSED. A missing, unreachable or malformed config means "there is no
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index 8b4e1271c..c02346a15 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -1,8 +1,8 @@
// Entry point for the three.ws multiplayer server.
//
-// This is a standalone Colyseus process — Vercel can't host long-lived
+// This is a standalone Colyseus process, Vercel can't host long-lived
// WebSocket servers, so this runs separately (Fly.io, Railway, Render, or a
-// $5 VPS — see ../README.md). The Vite app at three.ws/walk and three.ws/play
+// $5 VPS, see ../README.md). The Vite app at three.ws/walk and three.ws/play
// connect to it over WebSocket and exchange state via the rooms defined below.
//
// We mount an Express app as the HTTP request handler. Colyseus 0.16 detects
@@ -10,7 +10,7 @@
// matchmaking + seat-reservation routes go to Colyseus's own router, and
// everything else (/health, /colyseus monitor) falls through to Express. This
// is the supported way to expose custom HTTP routes alongside Colyseus on one
-// port — a hand-rolled raw request listener double-responds and throws
+// port, a hand-rolled raw request listener double-responds and throws
// ERR_HTTP_HEADERS_SENT against the matchmaker's prepended listener.
import http from 'node:http';
@@ -35,7 +35,7 @@ import { liveWalkRooms } from './walk-registry.js';
const PORT = Number(process.env.PORT || 2567);
const HOST = process.env.HOST || '0.0.0.0';
-// Origins permitted to upgrade to WebSocket — comma-separated list. Default
+// Origins permitted to upgrade to WebSocket, comma-separated list. Default
// covers local dev + the production three.ws origin. Anything outside this
// set gets a 403 before the WS handshake completes.
const ALLOWED_ORIGINS = (
@@ -52,7 +52,7 @@ const ALLOWED_ORIGINS = (
// rather than silently shipping a bypassable gate.
if (process.env.NODE_ENV === 'production' && !process.env.HOLDER_PASS_SECRET) {
console.error(
- '[multiplayer] FATAL: HOLDER_PASS_SECRET is required in production — the holder gate would be forgeable. Refusing to start.',
+ '[multiplayer] FATAL: HOLDER_PASS_SECRET is required in production, the holder gate would be forgeable. Refusing to start.',
);
process.exit(1);
}
@@ -63,7 +63,7 @@ if (process.env.NODE_ENV === 'production' && !process.env.HOLDER_PASS_SECRET) {
const PLAY_GATE_MINT = (process.env.PLAY_GATE_MINT || process.env.THREE_MINT || '').trim();
if (PLAY_GATE_MINT) {
const min = Number(process.env.PLAY_GATE_MIN) > 0 ? Number(process.env.PLAY_GATE_MIN) : 1;
- console.log(`[multiplayer] play gate ENABLED — require ≥ ${min} of ${PLAY_GATE_MINT} (wallet sign-in)`);
+ console.log(`[multiplayer] play gate ENABLED, require ≥ ${min} of ${PLAY_GATE_MINT} (wallet sign-in)`);
} else {
console.log('[multiplayer] play gate OFF (set PLAY_GATE_MINT or THREE_MINT to require wallet sign-in + token balance)');
}
@@ -101,11 +101,11 @@ app.post('/internal/notify', express.json({ limit: '16kb' }), (req, res) => {
// Living Stages tip/event bridge (Moonshot 04). The three.ws API calls this the
// instant a real $THREE tip settles on-chain (after it has verified the
// settlement signature + mint and deduped per signature) so the live StageRoom
-// can react within ~1s — broadcast the tip ticker, update the leaderboard, and
+// can react within ~1s, broadcast the tip ticker, update the leaderboard, and
// pre-empt the host's next beat with a shoutout. HMAC-signed with the shared
// secret bound to the exact body + a fresh timestamp, so only the API can inject
// a tip; an unsigned or stale request is rejected before it reaches a room. The
-// money already settled to the host wallet on-chain — this only drives the live
+// money already settled to the host wallet on-chain, this only drives the live
// reaction, so a `not_found` (room not hosted on this instance) loses nothing but
// the in-room flourish.
app.post('/internal/stage', express.json({ limit: '16kb' }), (req, res) => {
@@ -134,7 +134,7 @@ app.post('/internal/stage', express.json({ limit: '16kb' }), (req, res) => {
// Live-event announcement webhook. An operator (scripts/announce-play.mjs in
// the main repo, holding the same shared secret) broadcasts a message to every
-// player in every live walk_world room on this instance — optionally narrowed
+// player in every live walk_world room on this instance, optionally narrowed
// to one coin's world. Delivery rides the existing 'notice' channel, which every
// deployed client already renders as a toast (and newer clients as a banner
// when a title is present), so announcements need no client version to land.
@@ -204,13 +204,13 @@ app.get('/population', async (req, res) => {
}
});
-// The IRL world (irl_world) is a presence + reaction room only — it is NOT a pin
+// The IRL world (irl_world) is a presence + reaction room only, it is NOT a pin
// transport. Placed agents are private by location and reach a viewer solely via
// the per-viewer /api/irl/pins proximity read when they are physically near one,
// so there is no pin-publish webhook here: nothing fans pin coordinates into a
// room to be broadcast to every client. See rooms/IrlRoom.js.
-// Admin monitor UI — exposes live room/client state, so it must NOT be open to
+// Admin monitor UI, exposes live room/client state, so it must NOT be open to
// the world in production. Mount it only when protected by basic-auth creds
// (MONITOR_USER + MONITOR_PASS), or, outside production, openly for local dev.
const MONITOR_USER = process.env.MONITOR_USER;
@@ -230,7 +230,7 @@ if (MONITOR_USER && MONITOR_PASS) {
console.log('[multiplayer] monitor mounted at /colyseus (basic auth)');
} else if (!IS_PROD) {
app.use('/colyseus', monitor());
- console.log('[multiplayer] monitor mounted at /colyseus (open — dev only)');
+ console.log('[multiplayer] monitor mounted at /colyseus (open, dev only)');
} else {
console.log('[multiplayer] monitor disabled (set MONITOR_USER/MONITOR_PASS to enable in prod)');
}
@@ -263,7 +263,7 @@ const transport = new WebSocketTransport({
// the allowlist entirely. The real access boundary is each room's onAuth (a
// signed play pass / presence ticket, or a server-issued guest token), so the
// origin allowlist is only a browser-facing CSRF-style filter. We still reject
- // origin-less handshakes in production — there is no legitimate origin-less
+ // origin-less handshakes in production, there is no legitimate origin-less
// browser client, and the signed-token gate, not a spoofable header, is what
// protects the rooms. Non-prod keeps them open for local curl/native dev probes.
if (!origin) {
@@ -272,7 +272,7 @@ const transport = new WebSocketTransport({
return next(false, 403, 'origin required');
}
if (ALLOWED_ORIGINS.includes(origin)) return next(true);
- // Allow any Vercel preview deploy that targets the same project — these
+ // Allow any Vercel preview deploy that targets the same project, these
// have origins like https://three-ws-<hash>-<team>.vercel.app. We match
// by hostname suffix so we don't have to maintain an allow-list per
// preview URL.
@@ -292,7 +292,7 @@ const transport = new WebSocketTransport({
// Horizontal scaling across Cloud Run instances. Colyseus rooms live in one
// process, so to run more than one instance the room registry (driver) and
-// pub/sub (presence) must be shared — otherwise matchmaking on instance A can't
+// pub/sub (presence) must be shared, otherwise matchmaking on instance A can't
// see a room hosted on instance B and players for the same coin split apart.
// Setting REDIS_URI (e.g. a Memorystore instance) wires both; without it the
// server runs single-instance exactly as before (zero new behaviour, the deps
@@ -309,7 +309,7 @@ if (REDIS_URI) {
presence = new RedisPresence(REDIS_URI);
console.log('[multiplayer] horizontal scaling ENABLED (Redis driver + presence)');
} catch (err) {
- console.error('[multiplayer] REDIS_URI set but Redis deps unavailable — staying single-instance:', err?.message);
+ console.error('[multiplayer] REDIS_URI set but Redis deps unavailable, staying single-instance:', err?.message);
}
} else {
console.log('[multiplayer] single-instance mode (set REDIS_URI to scale horizontally)');
@@ -324,7 +324,7 @@ const gameServer = new Server({ transport, ...(driver && { driver }), ...(presen
// WalkRoom.onCreate / onAuth / schemas.js).
gameServer.define('walk_world', WalkRoom).filterBy(['coin', 'tier']);
// The playable Agora Commons (/agora): ONE shared city-scale square for human
-// presence only — the AI-citizen NPCs and their on-chain economy are driven by
+// presence only, the AI-citizen NPCs and their on-chain economy are driven by
// the three.ws projection APIs, not this room. No filterBy: every visitor lands
// in the same Commons. See rooms/AgoraRoom.js for why it isn't a walk_world
// coin shard (city-scale movement clamps).
@@ -336,19 +336,19 @@ gameServer.define('agora_world', AgoraRoom);
// inside the nearby radius are never missed (see rooms/IrlRoom.js).
gameServer.define('irl_world', IrlRoom).filterBy(['geocell']);
// Coin Wars (community-vs-community battles). One arena instance per matchKey, so
-// every fighter the /wars lobby hands the same matchKey lands in the same battle —
+// every fighter the /wars lobby hands the same matchKey lands in the same battle,
// the two coin communities, their score, and the round clock all live in that one
// room. A fighter must hold the coin they fight for (ClashRoom.onAuth verifies a
// holder pass for their declared faction). See rooms/ClashRoom.js + clash.js.
gameServer.define('clash_arena', ClashRoom).filterBy(['matchKey']);
// Living Stages (Moonshot 04). One room instance per stageId, so every audience
-// member who joins a given stage lands in the same live show — the host, the
+// member who joins a given stage lands in the same live show, the host, the
// crowd, the tip ticker, and the leaderboard all live in that one room. The room
// loads its host/title/format from /api/stage and reacts to real $THREE tips the
// API injects over /internal/stage. See rooms/StageRoom.js + src/stage.js.
gameServer.define('stage_world', StageRoom).filterBy(['stageId']);
-// Shared AR Studio (/ar/studio "Shared room"). One instance per roomKey — a
-// shared code or a QR-marker id — so everyone holding the same key builds one
+// Shared AR Studio (/ar/studio "Shared room"). One instance per roomKey, a
+// shared code or a QR-marker id, so everyone holding the same key builds one
// live scene together: placed models delta-sync and a late joiner receives the
// whole scene on join. An opted-into collaborative world (WalkRoom side of the
// privacy line), never a broadcast of private irl pins. See rooms/StudioRoom.js.
@@ -369,7 +369,7 @@ gameServer
// Keep the single instance alive through an isolated fault. A throw inside one
// onMessage handler, or an unawaited rejection deep in a dependency, would
// otherwise take down the whole process (min=1/max=1) and every connected
-// player with it. We log loudly and keep serving — the offending message/room
+// player with it. We log loudly and keep serving, the offending message/room
// is lost, the server is not. (A crash-loop on a corrupt state would still be
// caught by the host's health check.)
process.on('uncaughtException', (err) => {
@@ -381,7 +381,7 @@ process.on('unhandledRejection', (reason) => {
// Clean shutdown on SIGTERM/SIGINT so deploys don't drop sessions abruptly.
const shutdown = async (signal) => {
- console.log(`[multiplayer] ${signal} received — shutting down`);
+ console.log(`[multiplayer] ${signal} received, shutting down`);
try {
await gameServer.gracefullyShutdown(true);
} catch (err) {
diff --git a/multiplayer/src/plaza-stage.js b/multiplayer/src/plaza-stage.js
index e8487f0be..590d96ebb 100644
--- a/multiplayer/src/plaza-stage.js
+++ b/multiplayer/src/plaza-stage.js
@@ -1,4 +1,4 @@
-// Plaza stage identity — the deterministic bridge between a /play coin world and
+// Plaza stage identity, the deterministic bridge between a /play coin world and
// its Living Stage (stage_world room + the /api/stage record).
//
// A coin world has no stage column to look up and no directory to search: the
@@ -16,7 +16,7 @@
//
// Imported by the browser client (src/game/plaza-stage.js) and the three.ws API
// (api/stage/index.js), both of which resolve `uuid` from the repo root. The
-// Colyseus server never derives an id — it is handed one on join — so this file
+// Colyseus server never derives an id, it is handed one on join, so this file
// deliberately adds no dependency to the multiplayer workspace. It lives here,
// beside world-features.js, because it is the same kind of thing: one source of
// truth that the world and the platform must agree on exactly.
@@ -41,7 +41,7 @@ export function plazaStageKey(mint) {
/**
* The stage id for a coin world's plaza. Deterministic, isomorphic, and a valid
- * UUID — the same value on the client, in the API, and in the database.
+ * UUID, the same value on the client, in the API, and in the database.
* @param {string} mint the world's coin mint ('' / null ⇒ the mainland world)
* @returns {string} UUIDv5
*/
diff --git a/multiplayer/src/quest-zones.js b/multiplayer/src/quest-zones.js
index 60027d9a0..e88abffa5 100644
--- a/multiplayer/src/quest-zones.js
+++ b/multiplayer/src/quest-zones.js
@@ -1,17 +1,17 @@
-// Quest zones (W05) — the named world locations missions reference for goto /
+// Quest zones (W05), the named world locations missions reference for goto /
// interact objectives, waypoints, and the heist district.
//
// This is the ONE source of truth for those positions, imported by BOTH the server
-// (WalkRoom — validates "are you actually at the dock / vault?") and the client
-// (quest-systems — renders the markers and gates the interact prompt), so the
+// (WalkRoom, validates "are you actually at the dock / vault?") and the client
+// (quest-systems, renders the markers and gates the interact prompt), so the
// playable world and the authoritative world can never drift. It sits alongside
// world-features.js (fishing/gather positions) rather than inside it so the quest
// layer stays self-contained and conflict-free. Coordinates are world metres in the
// XZ plane; the ground sits at y = 0.
//
// `kind` tags how a zone is used:
-// 'goto' — a survey/patrol point you reach (drives an enter-zone objective)
-// 'interact' — a quest object you act at (pickup/dropoff/terminal/crack)
+// 'goto', a survey/patrol point you reach (drives an enter-zone objective)
+// 'interact', a quest object you act at (pickup/dropoff/terminal/crack)
// `r` is the trigger radius. Two survey points reuse the pond centres (see
// world-features.FISHING_SPOTS) so a survey also reveals where the fishing is. The
// vault district sits out east, clear of the spawn ring, the totem (0,0,-12) and the
@@ -36,9 +36,9 @@ export const QUEST_ZONES = [
{ id: 'depot-west', kind: 'goto', x: -90, z: -6, r: 8, label: 'West Depot', glyph: '🚚' },
// Event landmarks (the Meetup Grand Tour). Deliberately sited ON the three
- // places the event agenda already sends people — the totem the showdown is
+ // places the event agenda already sends people, the totem the showdown is
// held at, the Fortune's Folly wheel (world-features.WHEEL) and the trading
- // screen — so the tour walks the party route instead of inventing empty
+ // screen, so the tour walks the party route instead of inventing empty
// waypoints. Generous radii: these are crowded during the event and a marker
// you have to thread a crowd to hit is a bad objective.
{ id: 'event-totem', kind: 'goto', x: 0, z: -12, r: 6, label: 'The Totem', glyph: '🎉' },
@@ -53,7 +53,7 @@ export const QUEST_ZONES = [
const QUEST_ZONE_BY_ID = new Map(QUEST_ZONES.map((z) => [z.id, z]));
-// Reach beyond a zone's radius that still counts as "at" it — a little margin so the
+// Reach beyond a zone's radius that still counts as "at" it, a little margin so the
// prompt feels reliable as you walk up (mirrors FISH_REACH for activities).
export const ZONE_REACH = 1.6;
@@ -64,7 +64,7 @@ export function questZone(id) {
// Which quest zone (if any) the point (x,z) is inside, including the reach margin.
// Nearest centre wins on overlap. The single check the server trusts for both
// zone-entry (goto) and the interact gate, mirrored by the client for waypoints and
-// the interact prompt — same function, no drift.
+// the interact prompt, same function, no drift.
export function zoneAt(x, z) {
let best = null;
let bestD = Infinity;
diff --git a/multiplayer/src/quests.js b/multiplayer/src/quests.js
index b4e602fed..1e7aa19e4 100644
--- a/multiplayer/src/quests.js
+++ b/multiplayer/src/quests.js
@@ -1,8 +1,8 @@
-// Quest engine — jobs, missions & heists for the /play coin worlds (W05).
+// Quest engine, jobs, missions & heists for the /play coin worlds (W05).
//
// A mission is DATA, not code: a spec of ordered objectives + a reward. The same
// engine drives one-tap daily jobs, repeatable courier runs, and multi-stage
-// co-op heists — authoring new content is adding an entry to MISSIONS, never
+// co-op heists, authoring new content is adding an entry to MISSIONS, never
// writing a new handler. This mirrors how items.js is the one source of truth for
// items and economy.js for the pack/purse: rooms read THIS instead of branching on
// mission ids inline.
@@ -10,28 +10,28 @@
// Authority is server-side. The WalkRoom owns a player's quest state OFF the synced
// WalkState schema (it's private, like the pack/purse), feeds real gameplay events
// (a fish caught, a zone entered, a terminal activated) into applyEvent(), and grants
-// rewards only when the engine — not the client — says an objective is done. A client
+// rewards only when the engine, not the client, says an objective is done. A client
// claiming "I finished" advances nothing; only the event it actually produced does.
//
// Objective vocabulary (every mission is expressible in these, all backed by a REAL
-// server handler that emits the matching event — no objective is un-completable):
-// collect — gather N of an item (emitted by the fishing handler)
-// goto — enter a named world zone (emitted by movement zone-entry)
-// interact — act at a quest object/zone (emitted by the questInteract handler)
-// defeat — kill N foes in the wilds (emitted by the combat handler on a kill)
+// server handler that emits the matching event, no objective is un-completable):
+// collect, gather N of an item (emitted by the fishing handler)
+// goto, enter a named world zone (emitted by movement zone-entry)
+// interact, act at a quest object/zone (emitted by the questInteract handler)
+// defeat, kill N foes in the wilds (emitted by the combat handler on a kill)
// Heists compose these as a SHARED instance (see WalkRoom): the same objective shape,
// advanced by any crew member, finishing only when the party is assembled at the finale.
//
// A mission flagged `event: true` only exists inside the live window of the platform
// event (public/event.json, read server-side by event-window.js). The gate is applied
-// HERE — in the offer/accept/prune rules every caller already goes through — so no
+// HERE, in the offer/accept/prune rules every caller already goes through, so no
// surface can accidentally serve an event job out of window: outside it, the job is
// not on the board, cannot be accepted, and any stale run is dropped unpaid.
import { SKILLS } from './economy.js';
// ---------------------------------------------------------------------------
-// Mission registry — the single source of truth for what missions exist.
+// Mission registry, the single source of truth for what missions exist.
// ---------------------------------------------------------------------------
//
// Fields:
@@ -43,16 +43,16 @@ import { SKILLS } from './economy.js';
// repeat 'daily' (once per UTC day, rotated) | 'repeatable' (any time) |
// 'once' (a one-shot the account completes a single time, ever).
// party minimum crew size to FINISH (1 for solo; ≥2 for a heist finale).
-// objectives ordered list — complete one to advance to the next.
+// objectives ordered list, complete one to advance to the next.
// reward { gold, xp?: { skill, amount } } granted server-side on completion.
// Heist gold is the TOTAL pot, split evenly among the crew at payout.
// prereq mission ids that must be completed before this one is offered.
//
-// In-world spendable currency is "gold" (a game resource, per the program rules) —
+// In-world spendable currency is "gold" (a game resource, per the program rules),
// never an on-chain token. The only coin that ever exists is $THREE, and missions
// never mint or reference it.
export const MISSIONS = {
- // — Daily collect job (the Kintara retention mechanic): cheap, once/day, fishing. —
+ //, Daily collect job (the Kintara retention mechanic): cheap, once/day, fishing.,
'daily-anglers-haul': {
id: 'daily-anglers-haul',
title: "Angler's Daily Haul",
@@ -67,8 +67,8 @@ export const MISSIONS = {
reward: { gold: 140, xp: { skill: 'fishing', amount: 120 } },
},
- // — Daily survey job: a movement loop that teaches the map. One tap to accept,
- // finished by simply touring the landmarks. —
+ //, Daily survey job: a movement loop that teaches the map. One tap to accept,
+ // finished by simply touring the landmarks.,
'daily-grounds-survey': {
id: 'daily-grounds-survey',
title: 'Grounds Survey',
@@ -85,12 +85,12 @@ export const MISSIONS = {
reward: { gold: 90 },
},
- // — Repeatable collect: a bigger fishing contract for grinders. —
+ //, Repeatable collect: a bigger fishing contract for grinders.,
'stock-the-kitchen': {
id: 'stock-the-kitchen',
title: 'Stock the Kitchen',
giver: 'Cook Mara',
- summary: 'The roast pit is running low — bring in 12 fresh fish.',
+ summary: 'The roast pit is running low, bring in 12 fresh fish.',
kind: 'job',
repeat: 'repeatable',
party: 1,
@@ -100,10 +100,10 @@ export const MISSIONS = {
reward: { gold: 260, xp: { skill: 'fishing', amount: 220 } },
},
- // — Repeatable courier run: pick up at the dock, deliver to the market. A
- // two-stage go-there / act, then go-there / act loop — the spine of every
+ //, Repeatable courier run: pick up at the dock, deliver to the market. A
+ // two-stage go-there / act, then go-there / act loop, the spine of every
// GTA-style delivery mission. (Vehicles, W02, will make the legs faster; on
- // foot it already plays.) —
+ // foot it already plays.),
'harbor-courier': {
id: 'harbor-courier',
title: 'Harbor Courier',
@@ -119,8 +119,8 @@ export const MISSIONS = {
reward: { gold: 180 },
},
- // — One-shot intro mission: first taste of the loop, unlocks nothing but pays a
- // welcome purse and points the player at the board. —
+ //, One-shot intro mission: first taste of the loop, unlocks nothing but pays a
+ // welcome purse and points the player at the board.,
'welcome-to-work': {
id: 'welcome-to-work',
title: 'First Day on the Job',
@@ -135,12 +135,12 @@ export const MISSIONS = {
reward: { gold: 60, xp: { skill: 'fishing', amount: 40 } },
},
- // — Vehicle deliveries: the actual "drive around, go on missions" loop. Both
+ //, Vehicle deliveries: the actual "drive around, go on missions" loop. Both
// legs are `goto` objectives flagged `vehicle: true`, so entering the depot
- // zone on foot doesn't count — you have to actually be behind the wheel
+ // zone on foot doesn't count, you have to actually be behind the wheel
// (validated server-side off the authoritative vehicle-driver map, never the
// client). Depots sit at the four avenue vehicle spawns (vehicles.js
- // VEHICLE_SPAWNS), so a real car is always parked right where the job starts. —
+ // VEHICLE_SPAWNS), so a real car is always parked right where the job starts.,
'cross-town-delivery': {
id: 'cross-town-delivery',
title: 'Cross-Town Delivery',
@@ -150,8 +150,8 @@ export const MISSIONS = {
repeat: 'repeatable',
party: 1,
objectives: [
- { type: 'goto', zone: 'depot-north', vehicle: true, label: '🚗 Load the order — drive to the North Depot' },
- { type: 'goto', zone: 'depot-south', vehicle: true, label: '🚗 Drop it off — drive to the South Depot' },
+ { type: 'goto', zone: 'depot-north', vehicle: true, label: '🚗 Load the order, drive to the North Depot' },
+ { type: 'goto', zone: 'depot-south', vehicle: true, label: '🚗 Drop it off, drive to the South Depot' },
],
reward: { gold: 220 },
},
@@ -164,17 +164,17 @@ export const MISSIONS = {
repeat: 'repeatable',
party: 1,
objectives: [
- { type: 'goto', zone: 'depot-east', vehicle: true, label: '🚗 Load the order — drive to the East Depot' },
- { type: 'goto', zone: 'depot-west', vehicle: true, label: '🚗 Drop it off — drive to the West Depot' },
+ { type: 'goto', zone: 'depot-east', vehicle: true, label: '🚗 Load the order, drive to the East Depot' },
+ { type: 'goto', zone: 'depot-west', vehicle: true, label: '🚗 Drop it off, drive to the West Depot' },
],
reward: { gold: 220 },
},
- // — Co-op heist: the flagship multi-stage crew job. Stage 1 disables both alarm
- // terminals (either crew member can tap either terminal — SHARED progress);
- // the finale cracks the vault and only completes with the full crew assembled
- // at the door. The pot is split evenly at payout. Repeatable so a crew can run
- // it again. —
+ // Co-op heist: the flagship multi-stage crew job. Stage 1 disables both alarm
+ // terminals. Either crew member can tap either terminal, since progress is
+ // SHARED. The finale cracks the vault and only completes with the full crew
+ // assembled at the door. The pot is split evenly at payout, and the job is
+ // repeatable so a crew can run it again.
'vault-job': {
id: 'vault-job',
title: 'The Vault Job',
@@ -191,18 +191,18 @@ export const MISSIONS = {
},
{
type: 'interact', action: 'crack', zone: 'vault-door', shared: true, finale: true,
- label: 'Crack the vault — full crew at the door',
+ label: 'Crack the vault, full crew at the door',
},
],
// 900 gold total, split among the crew (e.g. 450 each for a duo).
reward: { gold: 900, xp: { skill: 'combat', amount: 200 } },
},
- // — Event quest line —————————————————————————————————————————————————————
+ //, Event quest line -----------------------------------------------------
// Four jobs that only exist while the platform event is live, one per thing the
// world already does well: gather, drive, fight, tour. All repeatable, because
// the event leaderboard ranks players by how many of these they finish inside
- // the window — a closed-ended set would decide the ranking in the first ten
+ // the window, a closed-ended set would decide the ranking in the first ten
// minutes. Payouts are richer than the everyday board (it's a two-hour window,
// not an all-day grind) but still ordinary in-world gold: the leaderboard's
// prizes are settled by the owner after the event, never paid on-chain by code.
@@ -210,7 +210,7 @@ export const MISSIONS = {
id: 'event-plaza-catch',
title: 'Meetup Fish Fry',
giver: 'Cook Mara',
- summary: 'The plaza pit is feeding the whole meetup — land 8 fish before the doors close.',
+ summary: 'The plaza pit is feeding the whole meetup, land 8 fish before the doors close.',
kind: 'job',
repeat: 'repeatable',
party: 1,
@@ -270,7 +270,7 @@ export const MISSIONS = {
},
};
-// The event quest line, in board order — the ids the leaderboard counts and the
+// The event quest line, in board order, the ids the leaderboard counts and the
// only missions the event window gates.
export const EVENT_MISSION_IDS = Object.values(MISSIONS)
.filter((m) => m.event)
@@ -304,7 +304,7 @@ function objCount(obj) {
}
// ---------------------------------------------------------------------------
-// Daily rotation — deterministic per UTC day, so every player and every room
+// Daily rotation, deterministic per UTC day, so every player and every room
// instance offers the same daily set, and it changes exactly at the UTC midnight
// boundary with no scheduler.
// ---------------------------------------------------------------------------
@@ -326,14 +326,14 @@ function hashStr(s) {
return h >>> 0;
}
-// The daily job ids for a given UTC day — a stable shuffle of DAILY_POOL seeded by
+// The daily job ids for a given UTC day, a stable shuffle of DAILY_POOL seeded by
// the day, then the first DAILY_COUNT. Pure: same day in → same ids out, anywhere.
export function dailyJobIds(dayKey, count = DAILY_COUNT) {
const pool = [...DAILY_POOL];
if (pool.length <= count) return pool;
let seed = hashStr(String(dayKey)) || 1;
const rng = () => {
- // LCG (Numerical Recipes constants) — deterministic, no Math.random.
+ // LCG (Numerical Recipes constants), deterministic, no Math.random.
seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;
return seed / 0x100000000;
};
@@ -345,7 +345,7 @@ export function dailyJobIds(dayKey, count = DAILY_COUNT) {
}
// ---------------------------------------------------------------------------
-// Per-player quest state — lives on the player's profile (off-schema), persisted
+// Per-player quest state, lives on the player's profile (off-schema), persisted
// through the account-keyed player store alongside the pack/purse.
// active: { [missionId]: run } in-progress missions
// completed: { [missionId]: { count, ts } } lifetime completions (for one-shots
@@ -362,7 +362,7 @@ export function newQuestState(dayKey = utcDayKey()) {
};
}
-// Rebuild from a persisted blob, tolerant of partial/legacy/missing data — a
+// Rebuild from a persisted blob, tolerant of partial/legacy/missing data, a
// corrupt save can never crash a join; it degrades to a fresh quest log. Stale
// daily state is rolled over to the current day on load (yesterday's completions
// don't block today's offers).
@@ -374,7 +374,7 @@ export function restoreQuestState(saved, dayKey = utcDayKey()) {
for (const [id, run] of Object.entries(saved.active)) {
const mission = MISSIONS[id];
if (!mission || !run || typeof run !== 'object') continue;
- // Heists are ephemeral, room-scoped shared instances — never restored as a
+ // Heists are ephemeral, room-scoped shared instances, never restored as a
// solo active run (you re-join the crew live), so drop any persisted heist.
if (mission.kind === 'heist') continue;
const stage = Math.max(0, Math.min(mission.objectives.length - 1, run.stage | 0));
@@ -434,7 +434,7 @@ export function rolloverDaily(state, dayKey = utcDayKey()) {
}
// ---------------------------------------------------------------------------
-// Offers — which missions the board may show this player right now.
+// Offers, which missions the board may show this player right now.
// ---------------------------------------------------------------------------
function prereqMet(state, mission) {
@@ -472,7 +472,7 @@ export function boardOffers(state, dayKey = utcDayKey(), ctx = {}) {
if (!canAccept(state, mission, dayKey, ctx)) continue;
offers.push(offerView(mission, state));
}
- // Event jobs lead the board while the window is open — they expire with it, the
+ // Event jobs lead the board while the window is open, they expire with it, the
// everyday work does not.
offers.sort((a, b) => (b.event ? 1 : 0) - (a.event ? 1 : 0));
return offers;
@@ -537,7 +537,7 @@ export function abandonMission(state, id) {
}
// ---------------------------------------------------------------------------
-// Progress — feed a real gameplay event into a run.
+// Progress, feed a real gameplay event into a run.
// ---------------------------------------------------------------------------
// Does objective `obj` match gameplay `event`?
@@ -553,7 +553,7 @@ export function objectiveMatches(obj, event) {
}
if (obj.type === 'goto') {
if (event.type !== 'enter-zone' || event.zone !== obj.zone) return false;
- // A `vehicle: true` goto is a driving leg — walking through the zone doesn't
+ // A `vehicle: true` goto is a driving leg, walking through the zone doesn't
// count, only crossing it in the driver's seat (event.inVehicle, set by the
// room from the authoritative vehicle-driver map).
if (obj.vehicle && !event.inVehicle) return false;
@@ -579,7 +579,7 @@ export function objectiveMatches(obj, event) {
return false;
}
-// Apply an event to a run (or a shared heist instance — same shape). Mutates the
+// Apply an event to a run (or a shared heist instance, same shape). Mutates the
// run's stage/counts. Returns:
// { matched, objComplete, missionComplete, stage }
// `progressed` runs carry an optional `seen` Set on shared multi-zone objectives so
@@ -643,7 +643,7 @@ export function missionReward(mission) {
return out;
}
-// Split a heist pot across `n` crew members — even split, remainder to the first
+// Split a heist pot across `n` crew members, even split, remainder to the first
// member so no gold is lost to rounding. Returns an array of per-member gold.
export function splitPot(totalGold, n) {
const count = Math.max(1, n | 0);
diff --git a/multiplayer/src/rooms/ClashRoom.js b/multiplayer/src/rooms/ClashRoom.js
index 2b8fd6412..b438735a2 100644
--- a/multiplayer/src/rooms/ClashRoom.js
+++ b/multiplayer/src/rooms/ClashRoom.js
@@ -1,18 +1,18 @@
-// ClashRoom — the live arena for Coin Wars (community-vs-community battles).
+// ClashRoom, the live arena for Coin Wars (community-vs-community battles).
//
// Two coin communities meet here. A fighter joins FOR the coin they hold (proven by
// the same holder pass that gates that coin's Holders world), is seated on that
// faction, and fights the other community in a shared 3D arena. The room is a thin
// validator-and-replicator over two pure cores:
-// • combat.js — picks which enemy a swing lands on, from authoritative positions.
-// • clash.js — the match: friendly-fire rules, kill scoring, respawns, the round
+// • combat.js, picks which enemy a swing lands on, from authoritative positions.
+// • clash.js, the match: friendly-fire rules, kill scoring, respawns, the round
// clock, sudden death, and the final result.
// Neither core touches the network or the schema, so the rules are unit-tested in
// isolation (tests/clash-match.test.js); this file just feeds them validated input
// and mirrors their state onto the wire.
//
// Matchmaking: rooms are defined with filterBy(['matchKey']) so every fighter who
-// passes the same matchKey lands in the same arena instance — the /wars lobby mints a
+// passes the same matchKey lands in the same arena instance, the /wars lobby mints a
// matchKey for a challenge and hands it to both communities.
import { Room } from '@colyseus/core';
@@ -41,7 +41,7 @@ const ARENA_BOUND_M = 60; // square arena half-extent
const SPAWN_OFFSET = 22; // each faction spawns this far up/down the z axis
const MOTION_VALUES = new Set(['idle', 'walk', 'run']);
-// The arena weapon. Everyone fights with the same kit in v1 — a mid-range blaster —
+// The arena weapon. Everyone fights with the same kit in v1, a mid-range blaster,
// so a clash is decided by positioning and teamwork, not gear. Real game constant
// (not a placeholder): the same {kind,dmg,range,aimTol} shape combat.js expects.
const CLASH_WEAPON = Object.freeze({ kind: 'ranged', dmg: 34, range: 26, aimTol: 0.32 });
@@ -59,7 +59,7 @@ export class ClashRoom extends Room {
// Admission. The platform play gate (if a game token is pinned) applies exactly as
// in WalkRoom. Then the fighter must prove they hold the coin they want to fight
// for: a holder pass whose mint equals their declared `coin`. That single check is
- // what makes a clash a battle BETWEEN communities — you can only wear a community's
+ // what makes a clash a battle BETWEEN communities, you can only wear a community's
// colours if you actually hold its coin. The faction must also be one of the two in
// this match. Throw on refusal so the client routes back to its gate.
//
@@ -296,7 +296,7 @@ export class ClashRoom extends Room {
}
// The spectator's view of this battle: text and numbers only, everything the
- // portal board renders without joining the room. Deliberately small — it is
+ // portal board renders without joining the room. Deliberately small, it is
// written every couple of seconds for the whole length of a war.
_liveSnapshot(now = Date.now()) {
const s = this.state;
@@ -360,7 +360,7 @@ export class ClashRoom extends Room {
// (with the winner set) instead of the last live tick before the end.
this._publishLive(true);
// Echo the outcome into the site-wide activity feed, which is what carries
- // the result back into BOTH communities' worlds — the portal board reads the
+ // the result back into BOTH communities' worlds, the portal board reads the
// ledger, the ticker reads this. Best-effort like every feed write.
const winnerName = result.winner === this.state.aMint ? this.state.aName
: result.winner === this.state.bMint ? this.state.bName : 'Draw';
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 694359117..5efc9fa73 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -1,4 +1,4 @@
-// WalkRoom — authoritative state for the three.ws /walk experience.
+// WalkRoom, authoritative state for the three.ws /walk experience.
//
// Players send 'move' messages 15× per second. The server validates each
// update (max-step clamp, world bounds, name length, message rate) and
@@ -6,12 +6,12 @@
// protocol broadcasts only fields that actually changed to every other
// client in the same room, at the configured patch rate.
//
-// Generic world objects (R01) — balls, placed props, pickups — ride the same
+// Generic world objects (R01), balls, placed props, pickups, ride the same
// pattern on their own `objects` map (see schemas.js WorldObject). The full
// obj:spawn / obj:update / obj:remove wire contract (payload shape, who's
// authorized, rate limits and caps) is documented at the
// "── Generic world objects (R01 protocol) ──" comment block below, right
-// above _handleObjSpawn — read that before adding a new object-driven
+// above _handleObjSpawn, read that before adding a new object-driven
// feature (R02 client manager, R05 ball physics, R17 persistence and later
// briefs all build on that single channel).
@@ -94,7 +94,7 @@ import { reportQuestComplete } from '../quest-notify.js';
// Platform entry gate (wallet-first sign-in + game-token balance). When a game
// token is pinned (PLAY_GATE_MINT, falling back to THREE_MINT) every join must
-// carry a valid play pass — minted by api/play/verify after proving wallet
+// carry a valid play pass, minted by api/play/verify after proving wallet
// ownership and a balance ≥ PLAY_GATE_MIN of that token. An unset mint leaves
// walk_world open exactly as before, so /walk and un-pinned deploys are
// unaffected. Read at boot: gate config doesn't change without a redeploy.
@@ -167,7 +167,7 @@ const BATCHES_PER_SEC_LIMIT = 4;
// ball:kick { vx, vy, vz }
// Any joined player, BALL_KICKS_PER_SEC rate limit. The server caps impulse
// magnitude and ensures a minimum upward component, then adds it to the
-// authoritative velocity. Ball id is fixed (BALL_ID) — one per room.
+// authoritative velocity. Ball id is fixed (BALL_ID), one per room.
//
// Velocity kept in _ballVx/y/z server vars, written to the WorldObject schema
// each tick. A settled ball (speed < BALL_IDLE_SPEED_SQ on ground) skips
@@ -180,8 +180,8 @@ const BALL_BOUNCE = 0.55; // vertical energy retained on ground bounc
const BALL_WALL_BOUNCE = 0.80; // energy retained on world-edge bounce
const BALL_ROLLING_FRICTION = 2.0; // per-second horizontal speed decay on ground
const BALL_AIR_DRAG = 0.12; // per-second speed decay while airborne
-const BALL_MAX_IMPULSE = 12; // m/s — cap on a single client kick
-const BALL_POST_KICK_CAP = 18; // m/s — absolute total velocity cap post-kick
+const BALL_MAX_IMPULSE = 12; // m/s, cap on a single client kick
+const BALL_POST_KICK_CAP = 18; // m/s, absolute total velocity cap post-kick
const BALL_MIN_UPY = 0.8; // minimum upward component on any kick
const BALL_KICK_REACH_M = 3.5; // must stand beside the ball to kick it (mirrors LOOT_REACH_M-style gates)
const BALL_WORLD_RADIUS = 54; // keep inside the visible arena
@@ -189,7 +189,7 @@ const BALL_SPAWN_X = 0;
const BALL_SPAWN_Y = BALL_RADIUS;
const BALL_SPAWN_Z = 5;
const BALL_OOB_Y = -10; // respawn below this y
-const BALL_IDLE_SPEED_SQ = 0.04; // (m/s)^2 — skip integration when settled
+const BALL_IDLE_SPEED_SQ = 0.04; // (m/s)^2, skip integration when settled
const BALL_KICKS_PER_SEC = 3;
// --- Build permissions & anti-grief (R19) ---------------------------------
@@ -223,7 +223,7 @@ const PROTECTED_POINTS = [
// grid cells, so its grief guard has its own protected discs and density tile. The
// protected world points are the spawn (origin) and the rendered totem (world z=-12);
// the radius matches the voxel discs (PROTECTED_RADIUS_CELLS cells). PER_TILE_PROP_CAP
-// stops a builder piling props onto one spot to bury a landmark or wall an area off —
+// stops a builder piling props onto one spot to bury a landmark or wall an area off,
// the per-player count (MAX_OBJECTS_PER_PLAYER) and world cap bound the rest.
const PROTECTED_RADIUS_M = PROTECTED_RADIUS_CELLS * BLOCK_SIZE_M;
const PROTECTED_POINTS_M = [
@@ -263,7 +263,7 @@ const TAG_LB_INTERVAL_MS = 8000;
// occupant of the king-zone at the totem base earns points each tick; two or more
// inside is "contested" and nobody scores. Rounds run on a fixed timer with a
// short intermission between them. The zone is centred on the totem (rendered at
-// world (0, -12) — see PROTECTED_POINTS) so its radius matches the client ring.
+// world (0, -12), see PROTECTED_POINTS) so its radius matches the client ring.
// Occupancy is judged from the server's authoritative player positions, so a
// client can never score from outside the zone. KING_TICK_MS is the scoring +
// timer cadence; KING_POINTS_PER_SEC is awarded scaled by real elapsed time so a
@@ -279,7 +279,7 @@ const KING_MIN_PLAYERS = 1;
// Open-world district bounds (W01). The /play world is no longer the 60 m disc:
// it's a square district the client renders streets/buildings across. These
-// mirror DISTRICT.half in src/game/world-zones.js — keep the two in sync so the
+// mirror DISTRICT.half in src/game/world-zones.js, keep the two in sync so the
// authoritative bounds and the rendered ground agree. The anti-teleport MAX_STEP
// clamp above is independent and still applies on every move.
const WORLD_HALF_M = 200;
@@ -299,8 +299,8 @@ const MOVE_WINDOW_MS = 1000;
const MOTION_VALUES = new Set(['idle', 'walk', 'run']);
// --- Economy & activities (off-schema) ------------------------------------
-// A player's pack, purse and skills are PRIVATE to them — peers never render
-// them in this free-roam world — so they live off the synced WalkState schema
+// A player's pack, purse and skills are PRIVATE to them, peers never render
+// them in this free-roam world, so they live off the synced WalkState schema
// (kept in this.econ) and stream to the owning client via targeted messages.
// This keeps the shared /walk schema untouched and peers' wire cost at zero.
// Per-cast reel time. Read from the shared cadence table in activities.js (which the
@@ -308,7 +308,7 @@ const MOTION_VALUES = new Set(['idle', 'walk', 'run']);
// gather cadence in the codebase.
const FISH_COOLDOWN_MS = ACTIVITY_COOLDOWN_MS.fish;
const CONSUME_COOLDOWN_MS = 1100; // pace between bites, no instant heal-spam
-// Per-action rate ceilings (messages/sec/client) — a flooding client is dropped.
+// Per-action rate ceilings (messages/sec/client), a flooding client is dropped.
// vsync rides at the same 15Hz the move netcode uses; allow 2× for jitter, like
// MOVES_PER_SEC_LIMIT. enter/exit are deliberate, rare actions.
const ACTION_RATES = {
@@ -318,13 +318,13 @@ const ACTION_RATES = {
// The room caches the upstream read (event-score.js), so this ceiling bounds the
// per-client chatter, not the API load.
eventBoard: 4,
- // General store, bank/ATM, and the $THREE boutique (W04) — low-frequency,
+ // General store, bank/ATM, and the $THREE boutique (W04), low-frequency,
// currency-mutating actions, throttled tighter than the gather loop.
store: 6, storeBuy: 6, storeSell: 6, bank: 6, boutique: 4, boutiqueQuote: 3, boutiqueSettle: 3,
// Combat (W07): attack rides at a swing/shot cadence a touch above the fastest
// weapon's cooldown (pistol ~430ms); loot is a deliberate, rare action.
attack: 5, loot: 4,
- // Wheel of Fortune (W09) — deliberate, low-frequency, currency/payment-mutating
+ // Wheel of Fortune (W09), deliberate, low-frequency, currency/payment-mutating
// actions, throttled like the boutique's above.
spinInfo: 4, spinFree: 3, spinPaidPrep: 3, spinPaidSettle: 3,
// Read-only snapshot requests. profile is cheap but unbounded outbound;
@@ -345,7 +345,7 @@ const ACTION_RATES = {
const VOICE_SIGNALS_PER_SEC_LIMIT = 60;
const MAX_VOICE_SIGNAL_BYTES = 16_000;
-// Solana mint addresses are base58, 32–44 chars. Anything else (including '')
+// Solana mint addresses are base58, 32, 44 chars. Anything else (including '')
// collapses to the default mainland world.
const MINT_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
function cleanCoin(v) {
@@ -355,7 +355,7 @@ function cleanCoin(v) {
// Access tier. Only 'holders' is gated; anything else (including '') is the open
// General world. A coin's General and Holders worlds are kept in separate room
-// instances by filterBy(['coin','tier']) — see multiplayer/src/index.js.
+// instances by filterBy(['coin','tier']), see multiplayer/src/index.js.
function cleanTier(v) {
return v === 'holders' ? 'holders' : '';
}
@@ -383,7 +383,7 @@ function round3(n) {
}
function pickPlayerColor(sessionId) {
- // Deterministic pleasant hue from sessionId — every client renders the
+ // Deterministic pleasant hue from sessionId, every client renders the
// same player in the same color without us needing to sync it explicitly.
let h = 0;
for (let i = 0; i < sessionId.length; i++) {
@@ -406,12 +406,12 @@ function hslToHex(h, s, l) {
export class WalkRoom extends Room {
// Players are matched into the same room instance only when their `coin`
- // join option matches — so each coin community is an isolated world while a
+ // join option matches, so each coin community is an isolated world while a
// single room definition serves them all. Coin-less players share the
// default mainland instance.
//
// Tier gate: the General world ('') is open to everyone. The Holders world
- // ('holders') admits a client only with a valid holder pass — an HMAC-signed
+ // ('holders') admits a client only with a valid holder pass, an HMAC-signed
// token the API mints after pricing the user's authenticated wallet against
// HOLDER_MIN_USD of this exact coin. We verify the pass here, before onJoin,
// and reject otherwise. Returning false makes Colyseus answer the
@@ -426,7 +426,7 @@ export class WalkRoom extends Room {
// time and its return value is stored as client.auth.
onAuth(client, options) {
// Platform token gate (orthogonal to the per-coin holder tier below). When a
- // game token is pinned, no client reaches any world — General or Holders —
+ // game token is pinned, no client reaches any world, General or Holders,
// without a play pass proving a signed-in wallet holds ≥ the floor. Throw
// (not return false) so a refusal arrives as a `play_pass`-prefixed error the
// client routes back to its sign-in gate. The verified wallet is bound to the
@@ -434,15 +434,15 @@ export class WalkRoom extends Room {
//
// KNOWN LANDMINE (2026-07-10): this gate is enforced against every client of
// this shared room, but only `/play` (src/game/community-net.js) actually
- // carries a `playPass` in its join options — it has the whole wallet
+ // carries a `playPass` in its join options, it has the whole wallet
// sign-in + pass-minting flow. `/walk` (src/walk-net.js) has never had that
// UI and sends no `playPass` field at all. As long as PLAY_GATE_MINT is unset
- // (the default today) this is inert — every join sails past the `if` below.
+ // (the default today) this is inert, every join sails past the `if` below.
// The moment an operator sets PLAY_GATE_MINT/THREE_MINT, every `/walk` join
// and reconnect will throw `play_pass_required` and the page will look
// completely offline, while `/play` keeps working. Fixing this properly means
// porting real sign-in UI into `/walk` (or extracting the pass-minting flow
- // out of coincommunities.js into a shared module both pages call) — a
+ // out of coincommunities.js into a shared module both pages call), a
// deliberate product decision about whether `/walk` stays a simpler,
// no-sign-in surface, not a one-line wiring fix. Do this BEFORE flipping the
// platform gate on in production, not after someone reports `/walk` is dead.
@@ -461,7 +461,7 @@ export class WalkRoom extends Room {
// A holder world must name a real coin. Throw (rather than return false) so
// every holder-gate refusal reaches the client as a `holder_pass`-prefixed
- // error its gate UI routes on — a uniform denial contract.
+ // error its gate UI routes on, a uniform denial contract.
const coin = cleanCoin(options?.coin);
if (!coin) throw new Error('holder_pass_required');
@@ -469,7 +469,7 @@ export class WalkRoom extends Room {
if (!pass) {
throw new Error('holder_pass_required');
}
- // The pass is for this exact coin's holder tier — a pass minted for coin A
+ // The pass is for this exact coin's holder tier, a pass minted for coin A
// can't unlock coin B's holder world.
if (pass.mint !== coin || pass.tier !== 'holders') {
throw new Error('holder_pass_mismatch');
@@ -501,7 +501,7 @@ export class WalkRoom extends Room {
// stable persistence id + per-action cooldowns). Never synced to peers.
this.econ = new Map();
this._actionCounters = new Map(); // sessionId → { [action]: { windowStart, count } }
- // On-chain settlement replay protection lives in settlement-guard.js — one
+ // On-chain settlement replay protection lives in settlement-guard.js, one
// durable, process-wide (and Redis-backed, when configured) consumption
// ledger shared by the boutique and the paid wheel, replacing the per-room
// nonce Maps that let one payment re-grant across rooms and restarts.
@@ -518,7 +518,7 @@ export class WalkRoom extends Room {
this.coinCreator = '';
// Co-op heist instances live on the room, not on a profile: a SHARED run a
// crew advances together. Keyed by mission id (one live instance per heist per
- // world). Each value: { missionId, members:Set<sessionId>, run } — the run
+ // world). Each value: { missionId, members:Set<sessionId>, run }, the run
// carries its own per-stage seen-zone dedupe (quests.js applyEvent).
this.heists = new Map();
// Tag mini-game (R08): off-schema state. _tagImmunity tracks who is immune
@@ -588,7 +588,7 @@ export class WalkRoom extends Room {
this.state.holderMinTokens = Number.isFinite(signedTokens) && signedTokens > 0 ? signedTokens : 0;
}
// Persisted-build key. General and Holders are separate worlds for the same
- // coin, so their voxel builds must persist independently — otherwise the two
+ // coin, so their voxel builds must persist independently, otherwise the two
// rooms would load and flush over each other's creation.
this.worldKey = this.state.tier === 'holders' ? `${this.state.coin}#holders` : this.state.coin;
@@ -627,7 +627,7 @@ export class WalkRoom extends Room {
// the schema so peers re-render, and echoes the owner a fresh profile.
this.onMessage('equip-cosmetic', (client, payload) => this._handleEquipCosmetic(client, payload));
// Full-loadout broadcast (R03): replaces the player's entire equipped state in
- // one shot, re-validated against ownership — mirrors how `avatar` is sent.
+ // one shot, re-validated against ownership, mirrors how `avatar` is sent.
this.onMessage('set-cosmetics', (client, payload) => this._handleSetCosmetics(client, payload));
this.onMessage('profileReq', (client) => { if (this._actionOk(client.sessionId, 'profile')) this._sendProfile(client); });
// Quests, jobs & heists (W05, off-schema). The board, accepting/abandoning a
@@ -654,7 +654,7 @@ export class WalkRoom extends Room {
this.onMessage('obj:remove', (client, payload) => this._handleObjRemove(client, payload));
// R05 physics ball: client sends kick intent with impulse; server validates,
// applies velocity, and integrates physics on its own tick. Clients never move
- // the ball directly — ownerId is 'server', blocking obj:update from them.
+ // the ball directly, ownerId is 'server', blocking obj:update from them.
this.onMessage('ball:kick', (client, payload) => this._handleBallKick(client, payload));
// Broadcast reactions (R04): a client sends an emoji; the server rate-limits
// and rebroadcasts to all clients in the room (including the sender).
@@ -687,8 +687,8 @@ export class WalkRoom extends Room {
console.warn(`[walk_world ${this.roomId}] block restore failed:`, err?.message);
}
- // Rehydrate this coin's durable placed objects (R17) — the build props the
- // community left behind — from the per-world persistence store before the
+ // Rehydrate this coin's durable placed objects (R17), the build props the
+ // community left behind, from the per-world persistence store before the
// first client renders, mirroring how blocks are restored above. The store is
// keyed by world id; mainland (empty coin) gets a stable fallback key. Blocks
// and objects share the world key but live in separate backends, so they
@@ -714,7 +714,7 @@ export class WalkRoom extends Room {
// Seed this world's drivable fleet. Vehicles are world entities (everyone sees
// them) so they ride on the synced state, parked until someone takes the wheel.
- // Spawned for every coin world — driving is a core verb, not a flagship-only
+ // Spawned for every coin world, driving is a core verb, not a flagship-only
// affordance. v1 fleet is ephemeral per room (re-spawned fresh each time the
// room is created); persistence of parked vehicles is a later concern.
this._seedVehicles();
@@ -742,7 +742,7 @@ export class WalkRoom extends Room {
// Re-check policy for the token gate. The game server has no RPC of its own,
// so "still holding the token" is re-proven by the client minting a fresh
// play pass (which re-reads the chain) before the current one's 10-min TTL
- // runs out and reconnecting — onAuth then re-validates. To actively evict a
+ // runs out and reconnecting, onAuth then re-validates. To actively evict a
// wallet that offloaded below the floor mid-session, we sweep once a minute
// and disconnect any client whose bound pass has expired without a refresh.
// The client refreshes ahead of expiry, so a holder never sees this; only a
@@ -766,7 +766,7 @@ export class WalkRoom extends Room {
if (this._itPlayer()) this._broadcastTagState();
}, TAG_LB_INTERVAL_MS);
- // Dance floor beat — every 4 s, aligned across all clients in the room so
+ // Dance floor beat, every 4 s, aligned across all clients in the room so
// avatars standing on the disco pad start the same crossfade at the same
// wall-clock moment. Clip rotates through the four dance animations.
const DANCE_FLOOR_CLIPS = ['av-dance-shuffle', 'av-rap-dance', 'av-headbang', 'dance'];
@@ -776,7 +776,7 @@ export class WalkRoom extends Room {
}, 4000);
// King of the Totem (R07): the single authoritative clock that runs the round
- // machine — awards points to a sole zone occupant, ends a round on time, and
+ // machine, awards points to a sole zone occupant, ends a round on time, and
// schedules the next one. One interval drives scoring, the countdown, and the
// idle→active→intermission transitions so the timing can never drift apart.
this.clock.setInterval(() => this._kingTick(), KING_TICK_MS);
@@ -799,7 +799,7 @@ export class WalkRoom extends Room {
player.motion = 'idle';
player.avatar = cleanAvatarUrl(options?.avatar);
player.agent = clean(options?.agent, 64);
- // The account id is the wallet verified in onAuth — bound server-side, never
+ // The account id is the wallet verified in onAuth, bound server-side, never
// from a client option, so it's a trustworthy persistence + social-graph key.
player.account = clean(client.userData?.account, 64);
player.tsServer = Date.now();
@@ -808,7 +808,7 @@ export class WalkRoom extends Room {
// Friends presence (Task 15): a presence ticket signed by the three.ws API
// proves which account this socket belongs to, independent of the wallet
// holder gate. Register it so friends see this player as online in this
- // coin world and can DM them live. Spoof-proof — the account id comes from
+ // coin world and can DM them live. Spoof-proof, the account id comes from
// the verified ticket, never a raw client option.
const presence = verifyPresenceTicket(options?.presence);
if (presence?.uid) {
@@ -816,7 +816,7 @@ export class WalkRoom extends Room {
socialHub.register(presence.uid, client, this.state.coinName || 'Mainland');
// Verified three.ws profile (W10): publish the ticket's username on the
// schema so every peer can open this player's real profile, follow them,
- // and DM them. Trustworthy by construction — it came out of the signed
+ // and DM them. Trustworthy by construction, it came out of the signed
// ticket, so nobody can wear a handle they don't own. A signed-in player
// who never picked a nameplate gets their account display name instead of
// an anonymous guest-xxxx handle.
@@ -830,7 +830,7 @@ export class WalkRoom extends Room {
// from onAuth when the platform gate is on, else a wallet proven by a signed
// play pass the client volunteered, else a server-minted guest id sealed in
// an HMAC guest token (guest-token.js). A raw `pid` join option is never an
- // account key anymore — it let any client load, spend, and overwrite any
+ // account key anymore, it let any client load, spend, and overwrite any
// victim's saved profile (gold, bank, items, cosmetics) just by asserting
// their id. Legacy `guest-…` pids migrate once (see _resolveIdentity).
const identity = await this._resolveIdentity(client, options);
@@ -842,7 +842,7 @@ export class WalkRoom extends Room {
client.userData = { ...(client.userData || {}), playerKey: playerId };
this._evictPriorSession(client, playerId, clean(options?.prevSession, 32));
if (identity.wallet && !client.userData?.account) {
- // The play pass proved this wallet even though the platform gate is off —
+ // The play pass proved this wallet even though the platform gate is off,
// bind it as the session account so ownership + moderation checks and the
// on-schema account field agree with the persistence key.
client.userData = { ...(client.userData || {}), account: identity.wallet };
@@ -872,7 +872,7 @@ export class WalkRoom extends Room {
this.econ.set(client.sessionId, profile);
// Cosmetics ownership (R22 → R23): fold the premium cosmetics this account
// bought over the x402 rail into its unlocked set, so a purchase persists and
- // equips in EVERY world the account joins — not just the one it was bought in.
+ // equips in EVERY world the account joins, not just the one it was bought in.
// The ledger is keyed by the same account id as the profile (playerId), reads
// fail-open (own nothing extra) and never block the join. Persist only when a
// new unlock actually landed so a returning player keeps it across restarts.
@@ -892,7 +892,7 @@ export class WalkRoom extends Room {
if (!this.state.players.has(client.sessionId)) return;
// Cosmetics (W03): apply any loadout the player chose pre-join (in the
// character creator) on top of their persisted one, validating each id
- // against what they own — free cosmetics always pass, premium only when
+ // against what they own, free cosmetics always pass, premium only when
// unlocked, so a join option can never put an unowned cosmetic on a player.
// Then publish the equipped loadout on the schema so peers render the look.
this._applyJoinCosmetics(profile, options?.cosmetics);
@@ -912,7 +912,7 @@ export class WalkRoom extends Room {
`[walk_world ${this.roomId} coin=${this.state.coin || 'mainland'}${tierTag}] +join ${client.sessionId} ${name} (n=${this.state.players.size})`,
);
- // "Someone is hanging out in <world>" — social proof + FOMO on the site-wide
+ // "Someone is hanging out in <world>", social proof + FOMO on the site-wide
// ticker. Throttled per world so a popular coin emits at most once a minute,
// not once per arrival. Mainland falls back to a friendly label.
publishFeedEvent(
@@ -951,7 +951,7 @@ export class WalkRoom extends Room {
// A socket that dies uncleanly (phone slept, tab froze, wifi handover) stays
// half-open: the transport still reads it as OPEN and only reaps it when its
// ping retries expire, several seconds later. The client reconnects well inside
- // that window, so the room briefly holds two sessions for one person — the
+ // that window, so the room briefly holds two sessions for one person, the
// returning player sees a frozen ghost of themselves at spawn, and so does
// everyone else. Liveness cannot be probed synchronously here (that is exactly
// what the half-open socket hides), so the reconnecting client tells us which
@@ -959,7 +959,7 @@ export class WalkRoom extends Room {
//
// `prevSession` alone would be a kick primitive: session ids are published on
// the player schema, so anyone could name a stranger's. It is only honoured
- // together with a matching persistent player key — the wallet the server itself
+ // together with a matching persistent player key, the wallet the server itself
// verified in onAuth, or a guest id that is never broadcast to peers. A second
// tab or a second device is untouched: each carries its own prior session id.
_evictPriorSession(client, playerKey, prevSession) {
@@ -978,11 +978,11 @@ export class WalkRoom extends Room {
// Tag mini-game (R08): capture wasIt BEFORE state.players.delete below, so
// we know if someone needs reassigning. Cleanup runs after the delete.
const _tagWasIt = this.state.players.get(client.sessionId)?.it ?? false;
- // Resolve this owner's object key up front — _ownerKey reads the econ profile,
+ // Resolve this owner's object key up front, _ownerKey reads the econ profile,
// which the block below deletes, so capture it before reaping their objects.
const ownerKey = this._ownerKey(client.sessionId);
// Free any vehicle this player was driving so it parks where it was left and
- // becomes available again — otherwise a disconnect would lock a car forever.
+ // becomes available again, otherwise a disconnect would lock a car forever.
this._releaseVehicleOf(client.sessionId);
// Drop the player from any co-op heist instance they were in, so the shared run
// doesn't hold a phantom crew member (and disposes when the last one leaves).
@@ -997,7 +997,7 @@ export class WalkRoom extends Room {
}
// Reap this owner's transient objects (R01): balls and fx they spawned die
// with their session. Their durable build props stay as part of the world
- // (R17) — that's the whole point of persistence.
+ // (R17), that's the whole point of persistence.
this._reapOwnerTransients(ownerKey);
this.state.players.delete(client.sessionId);
// Tag mini-game (R08): finalize this player's tracked time, purge immunity,
@@ -1041,14 +1041,14 @@ export class WalkRoom extends Room {
unregisterWalkRoom(this);
// Persist the final build so the community's creation survives the room
// being torn down when the last player leaves. Awaited (Colyseus waits on
- // the returned promise) so the Redis write lands before the room is gone —
+ // the returned promise) so the Redis write lands before the room is gone,
// fire-and-forget here would race the process exiting on a redeploy.
try {
await blockStore.flush(this.worldKey);
} catch (err) {
console.warn(`[walk_world ${this.roomId}] final flush failed:`, err?.message);
}
- // Flush the durable placed objects (R17) the same way — any spawn/move/remove
+ // Flush the durable placed objects (R17) the same way, any spawn/move/remove
// whose debounce hadn't fired lands before the room is gone, so leaving and
// re-entering (or a redeploy) shows the same build.
try {
@@ -1070,7 +1070,7 @@ export class WalkRoom extends Room {
const player = this.state.players.get(client.sessionId);
if (!player) return;
// W07: a downed player is off their feet until the respawn timer clears
- // them (killPlayer teleports to SPAWN_POINT itself) — reject stray moves so
+ // them (killPlayer teleports to SPAWN_POINT itself), reject stray moves so
// a "ragdolled" peer can't be walked around mid-death.
if (player.dead) return;
@@ -1091,7 +1091,7 @@ export class WalkRoom extends Room {
return;
}
- // Max-step clamp — reject teleports.
+ // Max-step clamp, reject teleports.
const dx = x - player.x;
const dz = z - player.z;
if (Math.hypot(dx, dz) > MAX_STEP_M) {
@@ -1103,7 +1103,7 @@ export class WalkRoom extends Room {
return;
}
- // World bounds clamp — the square open-world district (W01).
+ // World bounds clamp, the square open-world district (W01).
player.x = Math.max(-WORLD_BOUND_M, Math.min(WORLD_BOUND_M, x));
player.z = Math.max(-WORLD_BOUND_M, Math.min(WORLD_BOUND_M, z));
player.y = Math.max(-10, Math.min(10, y)); // keep avatars near the ground plane
@@ -1117,13 +1117,13 @@ export class WalkRoom extends Room {
// Tag mini-game (R08): if this mover is "it", check whether they've caught
// an adjacent player. All proximity math uses the server's authoritative
- // positions — the client can never claim a tag.
+ // positions, the client can never claim a tag.
if (player.it) this._checkTag(client.sessionId, player);
}
// Edge-detect quest-zone entry on the server's authoritative position. Emits a
// single 'enter-zone' event when the player crosses into a zone they weren't in
- // last tick — never per-frame while standing in it — so survey/patrol objectives
+ // last tick, never per-frame while standing in it, so survey/patrol objectives
// advance exactly once per visit. Cheap (a handful of zones); only does work when
// the current zone actually changed.
@@ -1252,7 +1252,7 @@ export class WalkRoom extends Room {
}
/** One authoritative beat: drives scoring, the countdown, and every phase
- * transition. Idempotent per second — safe even if a tick is delayed. */
+ * transition. Idempotent per second, safe even if a tick is delayed. */
_kingTick() {
const now = Date.now();
const k = this._king;
@@ -1308,7 +1308,7 @@ export class WalkRoom extends Room {
}
/** End the active round: pick the highest-scoring PRESENT player as winner
- * (a score of 0 across the board ⇒ no winner — an honest "nobody held it"),
+ * (a score of 0 across the board ⇒ no winner, an honest "nobody held it"),
* enter the intermission, and announce the result so clients celebrate. */
_endKingRound() {
const now = Date.now();
@@ -1387,7 +1387,7 @@ export class WalkRoom extends Room {
}
// Send the owning client its jobs board + active runs ({offers, active, day,
- // eventLive} — the shape community-net.js documents). Solo runs come straight from
+ // eventLive}, the shape community-net.js documents). Solo runs come straight from
// the engine's snapshot (which also rolls stale daily state over to today); a heist
// run is overlaid with the crew's SHARED instance so every member's tracker
// shows the same live progress, plus the current crew size.
@@ -1403,7 +1403,7 @@ export class WalkRoom extends Room {
this._persistEcon(client.sessionId);
client.send('notice', {
kind: 'quest', ok: false,
- text: 'The event has ended — its jobs have closed for now.',
+ text: 'The event has ended, its jobs have closed for now.',
});
}
const snap = questSnapshot(profile.quests, utcDayKey(), ctx);
@@ -1419,7 +1419,7 @@ export class WalkRoom extends Room {
// Accept a mission off the board. The engine owns the eligibility rules (already
// active, prereqs, daily/once repeats); a refusal is surfaced as a notice, never
// a silent no-op. Accepting a heist joins (or founds) this world's one shared
- // instance — the crew advances a single run together and splits the pot at payout.
+ // instance, the crew advances a single run together and splits the pot at payout.
_handleQuestAccept(client, payload) {
const profile = this.econ.get(client.sessionId);
if (!profile) return;
@@ -1430,7 +1430,7 @@ export class WalkRoom extends Room {
const res = acceptMission(profile.quests, id, utcDayKey(), this._questCtx());
if (!res.ok) {
const text = res.reason === 'active' ? 'You already took that job.'
- : res.reason === 'daily-done' ? 'That job is done for today — check back tomorrow.'
+ : res.reason === 'daily-done' ? 'That job is done for today, check back tomorrow.'
: res.reason === 'done' ? 'You’ve already completed that job.'
: res.reason === 'event-closed' ? 'That job only runs during the live event.'
: 'That job isn’t available to you yet.';
@@ -1441,12 +1441,12 @@ export class WalkRoom extends Room {
let inst = this.heists.get(id);
if (!inst) {
// First accept founds the instance; the founder's fresh run IS the shared
- // run every later member advances (it's never persisted — see quests.js).
+ // run every later member advances (it's never persisted, see quests.js).
inst = { missionId: id, members: new Set(), run: res.run };
this.heists.set(id, inst);
}
inst.members.add(client.sessionId);
- // The crew grew — every member's tracker shows the new headcount.
+ // The crew grew, every member's tracker shows the new headcount.
this._sendQuestsToCrew(inst, client.sessionId);
}
this._persistEcon(client.sessionId);
@@ -1456,7 +1456,7 @@ export class WalkRoom extends Room {
// Abandon an active mission. Solo progress is simply dropped (a daily can be
// re-accepted the same day); leaving a heist removes this member from the shared
- // crew — the rest keep the run, and the instance dissolves with its last member.
+ // crew, the rest keep the run, and the instance dissolves with its last member.
_handleQuestAbandon(client, payload) {
const profile = this.econ.get(client.sessionId);
if (!profile) return;
@@ -1470,7 +1470,7 @@ export class WalkRoom extends Room {
// Act at the quest object the player is standing at (courier pickup/dropoff, a
// heist terminal, the vault door). The zone comes from the SERVER's authoritative
- // position — the client's prompt is a hint, never the authority — and the event
+ // position, the client's prompt is a hint, never the authority, and the event
// carries the zone's action so objectiveMatches can tell a pickup from a dropoff.
_handleQuestInteract(client) {
const player = this.state.players.get(client.sessionId);
@@ -1490,7 +1490,7 @@ export class WalkRoom extends Room {
// run it could advance. Called from the move path, so it stays cheap: a player
// has a handful of active runs at most, and live heist instances are bounded by
// the mission registry. Solo runs live on the profile; heists advance the crew's
- // shared run — any member's action moves everyone, and the finale gates on
+ // shared run, any member's action moves everyone, and the finale gates on
// assembly (the whole crew at the door, judged from server positions).
_questEvent(client, profile, event) {
const dayKey = utcDayKey();
@@ -1511,7 +1511,7 @@ export class WalkRoom extends Room {
if (!inst.members.has(client.sessionId)) continue;
const mission = missionDef(inst.missionId);
if (!mission) continue;
- // The finale only lands with the whole crew assembled at its zone — checked
+ // The finale only lands with the whole crew assembled at its zone, checked
// BEFORE applying, so a lone cracker gets a hint instead of a silent miss.
const obj = mission.objectives[inst.run.stage];
if (obj?.finale && objectiveMatches(obj, event) && !this._heistFinaleReady(client, inst, mission, obj)) continue;
@@ -1549,9 +1549,9 @@ export class WalkRoom extends Room {
}
// Pay out a finished heist to the LIVE crew: the pot splits evenly (remainder to
- // the first member — splitPot loses no gold to rounding), each member's own
+ // the first member, splitPot loses no gold to rounding), each member's own
// completion log records it, and each gets their share + XP through their own
- // client. The instance is consumed — a crew founds a fresh one to run it again.
+ // client. The instance is consumed, a crew founds a fresh one to run it again.
_completeHeist(client, inst, mission, dayKey) {
const members = [...inst.members];
const reward = missionReward(mission);
@@ -1582,12 +1582,12 @@ export class WalkRoom extends Room {
}
// The finale gate: a heist only finishes with a big-enough crew ALL standing at
- // the finale zone — server positions, never client claims. A failed gate tells
+ // the finale zone, server positions, never client claims. A failed gate tells
// the actor why, so "nothing happened" is never the answer at the vault door.
_heistFinaleReady(client, inst, mission, obj) {
const need = Math.max(1, mission.party | 0 || 1);
if (inst.members.size < need) {
- client.send('notice', { kind: 'quest', ok: false, text: `This job needs a crew of ${need} — recruit before the finale.` });
+ client.send('notice', { kind: 'quest', ok: false, text: `This job needs a crew of ${need}, recruit before the finale.` });
return false;
}
for (const sid of inst.members) {
@@ -1602,7 +1602,7 @@ export class WalkRoom extends Room {
}
// Re-send the quest snapshot to every member of a heist crew (optionally skipping
- // one — the actor, whose re-send rides on the caller). Best-effort per client so
+ // one, the actor, whose re-send rides on the caller). Best-effort per client so
// a mid-send disconnect can't break the loop for the rest of the crew.
_sendQuestsToCrew(inst, exceptSessionId = null) {
for (const sid of inst.members) {
@@ -1626,7 +1626,7 @@ export class WalkRoom extends Room {
}
// Drop a departing session from EVERY heist crew (onLeave) so no shared run holds
- // a phantom member. Never throws — it runs inside the leave teardown.
+ // a phantom member. Never throws, it runs inside the leave teardown.
_leaveHeists(sessionId) {
for (const id of [...this.heists.keys()]) {
try { this._leaveHeistCrew(id, sessionId); } catch { /* best-effort */ }
@@ -1650,7 +1650,7 @@ export class WalkRoom extends Room {
},
`${player?.account || client.sessionId}:${mission.id}`,
);
- // Per-user bell notification, distinct from the anonymous ticker above —
+ // Per-user bell notification, distinct from the anonymous ticker above,
// only fires for a player whose presence ticket verified a real account.
const accountUid = client.userData?.accountUid;
if (accountUid) {
@@ -1752,7 +1752,7 @@ export class WalkRoom extends Room {
// NOT a profanity filter (crypto chat is crude by nature), but a slur is
// never relayed to fifty screens with our nameplate UI around it.
if (containsHateSlur(text)) return;
- // One message per 700ms per client — enough for conversation, not spam.
+ // One message per 700ms per client, enough for conversation, not spam.
const now = Date.now();
const last = this._chatCooldowns.get(client.sessionId) || 0;
if (now - last < 700) return;
@@ -1823,7 +1823,7 @@ export class WalkRoom extends Room {
}
// Send just the mutable economy slice after a change the client can't infer
- // (a catch, an eat, a purse change) — lighter than a full profile resend.
+ // (a catch, an eat, a purse change), lighter than a full profile resend.
_sendInv(client, profile) {
client.send('inv', {
inv: profile.inv.map((s) => ({ item: s.item, qty: s.qty })),
@@ -1926,7 +1926,7 @@ export class WalkRoom extends Room {
}
// Event souvenir grant. When a community event is live in THIS world, every
- // player who joins keeps a free commemorative wearable — a souvenir, not a
+ // player who joins keeps a free commemorative wearable, a souvenir, not a
// sale: there is no purchase path for it before, during or after.
//
// Server-authoritative and idempotent by construction. The window and the
@@ -1934,7 +1934,7 @@ export class WalkRoom extends Room {
// reading /event.json), never from a client option, and the grant itself is
// grantCosmetic(), which is a no-op on an account that already owns the item.
// So a reconnect, a room hop, or ten rejoins produce exactly one unlock and
- // exactly one announcement — the `souvenir` message only goes out on the
+ // exactly one announcement, the `souvenir` message only goes out on the
// transition from not-owned to owned.
//
// Fail-open on every axis: no config, an unreachable config, a closed window,
@@ -1968,8 +1968,8 @@ export class WalkRoom extends Room {
// Dress the player from a pre-join loadout wire (the character-creator / a
// world hand-off in `cosmetics` join option), merged on top of their persisted
- // loadout and validated per id against what they own — free cosmetics always
- // pass, premium only when unlocked — so a join option can never put an unowned
+ // loadout and validated per id against what they own, free cosmetics always
+ // pass, premium only when unlocked, so a join option can never put an unowned
// cosmetic on a player. Mutates profile.cosmetics.equipped in place.
_applyJoinCosmetics(profile, wire) {
if (!profile.cosmetics) profile.cosmetics = { owned: [], equipped: {} };
@@ -1983,7 +1983,7 @@ export class WalkRoom extends Room {
}
// Equip/unequip one cosmetic into its slot (R23). The economy validates the id
- // is owned (or free) before it moves — an unowned id is rejected, never worn —
+ // is owned (or free) before it moves, an unowned id is rejected, never worn,
// then we re-publish the loadout on the schema (peers re-render the fit), echo
// the owner a fresh profile (inventory reflects the new equipped state), and
// persist to the account so it survives logout and applies in every world.
@@ -2006,7 +2006,7 @@ export class WalkRoom extends Room {
if (!equipped && getCosmetic(id)?.tier === 'premium') {
try {
if (mergeOwnedFromLedger(profile, await readOwnedCosmetics(profile.playerId)) > 0) {
- // The await could have outlived the session — bail if they left.
+ // The await could have outlived the session, bail if they left.
if (!this.econ.has(client.sessionId)) return;
equipped = equipCosmetic(profile, id);
}
@@ -2025,7 +2025,7 @@ export class WalkRoom extends Room {
}
// Replace the player's entire equipped loadout in one shot (R03). The wire
- // is re-validated against the catalog and account ownership before applying —
+ // is re-validated against the catalog and account ownership before applying,
// any unknown id, any id in the wrong slot, and any unowned premium id are
// silently dropped to the slot default. This is the full-loadout counterpart to
// equip-cosmetic (which changes one slot); the schema update and persist follow
@@ -2084,14 +2084,14 @@ export class WalkRoom extends Room {
// server prices every trade from shop.js (never a client-supplied number),
// mutates the profile, and echoes the owner a fresh inv/profile snapshot.
- // The general store's catalog — sell prices + the buy list — so the client
+ // The general store's catalog, sell prices + the buy list, so the client
// renders exactly what the server will charge/pay, no drift possible.
_sendStore(client) {
client.send('store', clientStoreCatalog());
}
// Buy `item` from the general store for cash. Validates the catalog entry,
- // the purse, and pack room before moving anything — a rejected buy costs
+ // the purse, and pack room before moving anything, a rejected buy costs
// nothing and leaves the pack untouched.
// Is this session standing at a counter? Trading and banking are walk-up
// actions like every other station in the world, and the check has to live
@@ -2124,7 +2124,7 @@ export class WalkRoom extends Room {
return;
}
if (profile.gold < entry.price) {
- client.send('notice', { kind: 'store', ok: false, text: `Not enough cash — ${entry.price} needed.` });
+ client.send('notice', { kind: 'store', ok: false, text: `Not enough cash, ${entry.price} needed.` });
return;
}
if (!hasRoomFor(profile, entry.item)) {
@@ -2174,7 +2174,7 @@ export class WalkRoom extends Room {
// Move cash between the carried purse and the protected bank (the ATM).
// Positive amounts deposit, negative withdraw; bankTransfer clamps to
// what's actually available so it can never mint or strand cash. Banked
- // cash is untouched by a death drop (economy.js dropCarried) — the whole
+ // cash is untouched by a death drop (economy.js dropCarried), the whole
// risk/reward point of using the bank.
_handleBank(client, payload) {
const profile = this.econ.get(client.sessionId);
@@ -2192,7 +2192,7 @@ export class WalkRoom extends Room {
client.send('notice', {
kind: 'bank',
ok: true,
- text: moved > 0 ? `Deposited ${moved} cash — protected from drops.` : `Withdrew ${-moved} cash.`,
+ text: moved > 0 ? `Deposited ${moved} cash, protected from drops.` : `Withdrew ${-moved} cash.`,
});
this._persistEcon(client.sessionId);
}
@@ -2200,12 +2200,12 @@ export class WalkRoom extends Room {
// --- $THREE boutique (W04) -------------------------------------------------
//
// Premium in-game cosmetics (multiplayer/src/cosmetics-catalog.js), priced
- // and unlocked entirely separately from the R21–25 avatar-shop/x402 rail
+ // and unlocked entirely separately from the R21, 25 avatar-shop/x402 rail
// (which sells a different catalog, settled in USDC, for the standalone
// character creator). This is the purpose-built W04 rail: the buyer's own
// Solana wallet sends ONE real $THREE transaction (game-token.js), split
// between the holder-rewards pool and the treasury, and the server re-reads
- // that transaction from RPC before granting anything — never trusting a
+ // that transaction from RPC before granting anything, never trusting a
// client "it worked" claim.
// The boutique catalog (priced in $THREE) + this account's owned ids.
@@ -2220,10 +2220,10 @@ export class WalkRoom extends Room {
// Price + build the unsigned $THREE purchase transaction for one boutique
// item. `wallet` is whichever Solana wallet the player has connected in the
- // browser — it pays; the unlock always lands on THIS session's profile
+ // browser, it pays; the unlock always lands on THIS session's profile
// regardless of who fronts the tokens (the same "anyone can settle a quote"
// model buildSpinPayment already uses). The price is read from the server
- // catalog only — a client can never move it.
+ // catalog only, a client can never move it.
async _handleBoutiqueQuote(client, payload) {
const profile = this.econ.get(client.sessionId);
if (!profile) return;
@@ -2263,7 +2263,7 @@ export class WalkRoom extends Room {
console.warn('[walk_world] boutique quote failed:', err?.message);
}
if (!built) {
- client.send('notice', { kind: 'boutique', ok: false, text: 'Could not price that purchase — try again in a moment.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'Could not price that purchase, try again in a moment.' });
return;
}
client.send('boutiqueQuote', { id, price, quoteToken: built.quoteToken, txBase64: built.txBase64 });
@@ -2285,7 +2285,7 @@ export class WalkRoom extends Room {
result = await verifyTokenPurchase({ quoteToken, txSig, purpose: 'boutique', forAccount: profile.playerId });
} catch (err) {
console.warn('[walk_world] boutique settle failed:', err?.message);
- client.send('notice', { kind: 'boutique', ok: false, text: 'Could not verify that payment — try again.' });
+ client.send('notice', { kind: 'boutique', ok: false, text: 'Could not verify that payment, try again.' });
return;
}
if (!result?.ok) {
@@ -2303,7 +2303,7 @@ export class WalkRoom extends Room {
}
const cosmeticId = result.quote?.cosmeticId;
if (ownedCosmeticSet(profile).has(cosmeticId)) {
- client.send('notice', { kind: 'boutique', ok: true, text: 'Payment verified — you already owned this.' });
+ client.send('notice', { kind: 'boutique', ok: true, text: 'Payment verified, you already owned this.' });
return;
}
const granted = cosmeticId ? grantCosmetic(profile, cosmeticId) : false;
@@ -2312,13 +2312,13 @@ export class WalkRoom extends Room {
return;
}
this._sendProfile(client);
- client.send('notice', { kind: 'boutique', ok: true, text: `Unlocked ${getCosmetic(cosmeticId)?.name || 'the item'} — check your wardrobe.` });
+ client.send('notice', { kind: 'boutique', ok: true, text: `Unlocked ${getCosmetic(cosmeticId)?.name || 'the item'}, check your wardrobe.` });
this._persistEcon(client.sessionId);
}
// Resolve the stable persistence identity for a joining session. Trust order:
// 1. The wallet onAuth verified (platform gate on).
- // 2. A wallet sealed in a valid play pass the client sent voluntarily —
+ // 2. A wallet sealed in a valid play pass the client sent voluntarily,
// possession of the HMAC-signed pass proves the wallet even when the
// gate is off, so signed-in players keep one profile across deploys.
// 3. A guest id sealed in a signed guest token (minted below on a prior
@@ -2385,7 +2385,7 @@ export class WalkRoom extends Room {
v.type = spawn.type;
v.color = Number.isInteger(spawn.color) ? spawn.color : spec.color;
v.x = spawn.x;
- // Rest the chassis on its suspension, not embedded in the asphalt — see
+ // Rest the chassis on its suspension, not embedded in the asphalt, see
// vehicleRestHeight's doc for the geometry this mirrors.
v.y = vehicleRestHeight(spawn.type);
v.z = spawn.z;
@@ -2403,7 +2403,7 @@ export class WalkRoom extends Room {
// Take the wheel of a parked vehicle. Gated by: the vehicle exists, it isn't
// already occupied, and the player is standing within range of it. A player can
// only drive one vehicle, so any prior one is released first. The grant is the
- // authoritative `driver` field flipping to this session — the client waits for
+ // authoritative `driver` field flipping to this session, the client waits for
// that echo (plus a targeted ack) before it starts simulating.
_handleVehicleEnter(client, payload) {
const player = this.state.players.get(client.sessionId);
@@ -2416,7 +2416,7 @@ export class WalkRoom extends Room {
client.send('vehicle', { event: 'deny', id, reason: 'occupied' });
return;
}
- // Proximity gate — can't claim a car from across the map.
+ // Proximity gate, can't claim a car from across the map.
const dist = Math.hypot(player.x - v.x, player.z - v.z);
if (dist > VEHICLE_ENTER_RANGE_M) {
client.send('vehicle', { event: 'deny', id, reason: 'range' });
@@ -2431,7 +2431,7 @@ export class WalkRoom extends Room {
// Leave the wheel. The client sends its final resting transform; the server
// parks the car there, clears the driver, and authors the player's drop point
// beside the door so the next ordinary 'move' is continuous (no teleport
- // rejection). The drop is server-computed and bounds-clamped — a client can't
+ // rejection). The drop is server-computed and bounds-clamped, a client can't
// use exit to warp.
_handleVehicleExit(client, payload) {
const player = this.state.players.get(client.sessionId);
@@ -2463,7 +2463,7 @@ export class WalkRoom extends Room {
// Adopt the driver's streamed transform. Server-authoritative validation: only
// the seated driver may write; reject NaNs; reject a jump larger than the type's
// top speed allows over the send window (teleport) and an implausible reported
- // speed (speed hack). A rejected position is simply not applied — the car holds
+ // speed (speed hack). A rejected position is simply not applied, the car holds
// its last authoritative transform, which the cheating client then sees snap back.
_handleVehicleSync(client, payload) {
if (!this._actionOk(client.sessionId, 'vsync')) return;
@@ -2483,7 +2483,7 @@ export class WalkRoom extends Room {
player.motion = 'idle';
player.tsServer = v.tsServer;
// The ordinary 'move' handler drives zone-entry detection, but a seated
- // driver never sends 'move' — they stream 'vsync' instead. Without this, a
+ // driver never sends 'move', they stream 'vsync' instead. Without this, a
// vehicle-flagged goto objective could never be reached by driving through
// it. Check here too so cross-town delivery jobs actually progress.
this._checkZoneEntry(client);
@@ -2514,7 +2514,7 @@ export class WalkRoom extends Room {
const sp = typeof speed === 'number' && Number.isFinite(speed) ? speed : 0;
if (Math.abs(sp) > vehicleMaxSpeedMps(v.type)) return false;
- // World bounds — the same square district clamp ordinary movement uses, so a
+ // World bounds, the same square district clamp ordinary movement uses, so a
// car can reach the avenue spawns at x/z=±90 without being pulled toward the
// centre by a stale circular radius.
v.x = Math.max(-VEHICLE_WORLD_BOUND_M, Math.min(VEHICLE_WORLD_BOUND_M, x));
@@ -2587,11 +2587,11 @@ export class WalkRoom extends Room {
// Adopt a mid-session play-pass refresh. The client re-mints a pass (re-reading
// the chain) ahead of the 10-min TTL and pushes it here so this live session's
- // bound expiry tracks the fresh credential — without this, the once-a-minute
+ // bound expiry tracks the fresh credential, without this, the once-a-minute
// expiry sweep evicts a still-qualifying player at the original TTL, which is
// what kicked anyone in a long building session. We re-verify exactly as onAuth
// does: a valid pass for this gate's mint, at or above the floor, bound to the
- // same wallet. Anything else is silently ignored — the stale expiry stands and
+ // same wallet. Anything else is silently ignored, the stale expiry stands and
// the sweep handles it, so a forged refresh can't extend or hijack a session.
_handlePlayPassRefresh(client, payload) {
if (!PLAY_GATE_MINT) return;
@@ -2616,7 +2616,7 @@ export class WalkRoom extends Room {
const existing = this.state.blocks.get(key);
if (existing) {
// Re-painting an existing cell. It doesn't grow the world, but it DOES
- // rewrite someone's build — only the piece's owner (or the coin creator)
+ // rewrite someone's build, only the piece's owner (or the coin creator)
// may change it, so a passer-by can't recolour another player's work.
if (existing.t === t) return; // no-op
if (!this._mayModify(client, key)) { this._rejectEdit(client, 'owned'); return; }
@@ -2626,7 +2626,7 @@ export class WalkRoom extends Room {
}
// New cell. Enforce, in order: the per-world budget, the protected spawn/totem
// discs, the per-player ownership cap, and the per-column density cap. Each is
- // surfaced to the builder with its own reason — never a silent drop.
+ // surfaced to the builder with its own reason, never a silent drop.
if (this.state.blocks.size >= MAX_BLOCKS) { this._rejectEdit(client, 'budget'); return; }
const reason = this._placementBlock(owner, payload.x, payload.z);
if (reason) { this._rejectEdit(client, reason); return; }
@@ -2638,7 +2638,7 @@ export class WalkRoom extends Room {
this._sendBuildPerms(client);
}
- // Place a composite piece — a handful of cells in one atomic, all-or-nothing
+ // Place a composite piece, a handful of cells in one atomic, all-or-nothing
// stamp. Validated exactly like a single place (in-bounds integer cell, real
// type) for EVERY cell before anything lands, plus a whole-batch budget check,
// so a wall never half-appears and the per-world cap can't be straddled. Rate
@@ -2654,7 +2654,7 @@ export class WalkRoom extends Room {
}
// First pass: validate every cell and count how many are new, so the budget,
// per-player cap, per-column density, protected-zone, and ownership checks all
- // cover the WHOLE stamp before anything lands — a single bad cell rejects the
+ // cover the WHOLE stamp before anything lands, a single bad cell rejects the
// lot. Cumulative tallies (ownerAdds, per-column) are tracked across the batch
// so a single stamp can't straddle a cap the same way a sequence of singles can't.
const owner = this._ownerKey(client.sessionId);
@@ -2749,7 +2749,7 @@ export class WalkRoom extends Room {
if (!this.state.players.has(client.sessionId)) return;
if (!this._objOk(client.sessionId)) return;
if (!payload || typeof payload !== 'object') return;
- // Position is mandatory and must be finite — a NaN slips past clamps.
+ // Position is mandatory and must be finite, a NaN slips past clamps.
if (!Number.isFinite(payload.x) || !Number.isFinite(payload.y) || !Number.isFinite(payload.z)) return;
if (this.state.objects.size >= MAX_WORLD_OBJECTS) { client.send('obj:reject', { reason: 'world_full' }); return; }
@@ -2783,7 +2783,7 @@ export class WalkRoom extends Room {
// Grief guard (R19): a durable build prop may not bury the spawn or totem, nor
// pile onto a tile past the density cap so it can't wall an area off. Checked on
// the clamped position so a client can't dodge it with an out-of-bounds value.
- // Transient kinds (ball, fx) and server objects are exempt — only build props.
+ // Transient kinds (ball, fx) and server objects are exempt, only build props.
if (this._objectIsPersistent(obj)) {
const reason = this._propPlacementBlock(obj.x, obj.z);
if (reason) { client.send('obj:reject', { reason }); return; }
@@ -2864,7 +2864,7 @@ export class WalkRoom extends Room {
for (const id of doomed) this.state.objects.delete(id);
}
- // Snapshot the durable build props for storage — transient and server-owned
+ // Snapshot the durable build props for storage, transient and server-owned
// objects are excluded. Coordinates are rounded to keep the doc compact.
_snapshotObjects() {
const out = [];
@@ -2926,7 +2926,7 @@ export class WalkRoom extends Room {
}
// Creator-only moderation: clear a disc of blocks around a grid point, or the
- // whole world. Validated server-side — the creator identity comes from the coin's
+ // whole world. Validated server-side, the creator identity comes from the coin's
// on-chain creator matching this client's verified wallet, never a client claim.
// Bounded radius keeps even a malformed call from over-reaching; 'all' is the
// explicit full wipe. Every removed cell streams out via the blocks state, so all
@@ -2943,14 +2943,14 @@ export class WalkRoom extends Room {
cx = Number(payload.x); cz = Number(payload.z); r = Number(payload.r);
if (!Number.isFinite(cx) || !Number.isFinite(cz) || !Number.isFinite(r)) return;
// Clamp to the tier this caller earned (P3.2), then to the absolute
- // ceiling — a client asking for more gets the honest maximum, never more.
+ // ceiling, a client asking for more gets the honest maximum, never more.
const earned = Math.min(this._clearRadiusFor(client), BUILD_CLEAR_RADIUS_MAX);
r = Math.max(1, Math.min(earned, Math.round(r)));
}
let cleared = 0;
for (const key of [...this.state.blocks.keys()]) {
- const [bx, , bz] = key.split(',').map(Number);
+ const [bx, bz] = key.split(',').map(Number);
if (!all && Math.hypot(bx - cx, bz - cz) > r) continue;
const owner = this.blockOwners.get(key) || '';
this.state.blocks.delete(key);
@@ -2960,8 +2960,8 @@ export class WalkRoom extends Room {
}
// Durable props (obj:spawn build pieces) live in the objects map, not the voxel
// grid, so a sweep that only touched blocks would leave a prop-griefed area
- // untouched. Clear them on the same disc — mapped from grid cells to world metres
- // (the centre/radius arrive in cells) — and never the ball or transient fx.
+ // untouched. Clear them on the same disc, mapped from grid cells to world metres
+ // (the centre/radius arrive in cells), and never the ball or transient fx.
let clearedObjs = 0;
const wx = cx * BLOCK_SIZE_M, wz = cz * BLOCK_SIZE_M, wr = r * BLOCK_SIZE_M;
for (const [id, o] of [...this.state.objects]) {
@@ -2989,7 +2989,7 @@ export class WalkRoom extends Room {
return this.econ.get(sessionId)?.playerId || sessionId;
}
- // Whether this client may modify the block at `key` — its owner, or the creator.
+ // Whether this client may modify the block at `key`, its owner, or the creator.
// An ownerless cell (a legacy/pre-ownership restore) is creator-only, so restored
// builds stay protected from griefing while the creator can still moderate them.
_mayModify(client, key) {
@@ -3006,7 +3006,7 @@ export class WalkRoom extends Room {
return !!player && !!player.account && player.account === this.coinCreator;
}
- // True if (x,z) is inside a protected disc (spawn, totem, or the plaza stage) —
+ // True if (x,z) is inside a protected disc (spawn, totem, or the plaza stage),
// placement there is refused at every height so no landmark can be buried or
// fenced in.
_isProtectedColumn(x, z) {
@@ -3069,7 +3069,7 @@ export class WalkRoom extends Room {
// Tell one client what they're allowed to do and how much of their build budget
// they've used, so the HUD can surface the per-player cap and reveal the creator
- // moderation control — no silent limits. Sent on join and after their tally moves.
+ // moderation control, no silent limits. Sent on join and after their tally moves.
_sendBuildPerms(client) {
const owner = this._ownerKey(client.sessionId);
const creator = this._isCreator(client);
@@ -3079,7 +3079,7 @@ export class WalkRoom extends Room {
used: this.blockCounts.get(owner) || 0,
// P3.2: the radius this caller has actually earned, not a flat constant.
// The client renders this number in the confirm prompt, and
- // _handleBuildClear clamps to the same call — one source of truth, so the
+ // _handleBuildClear clamps to the same call, one source of truth, so the
// HUD can never promise reach the server would refuse.
clearMaxRadius: this._clearRadiusFor(client),
holderWorld: this.state.tier === 'holders',
@@ -3104,7 +3104,7 @@ export class WalkRoom extends Room {
// their moderation control the moment it resolves.
async _resolveCoinCreator() {
const mint = this.state.coin;
- if (!mint) return; // mainland — no coin, no creator
+ if (!mint) return; // mainland, no coin, no creator
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 6000);
@@ -3196,7 +3196,7 @@ export class WalkRoom extends Room {
// Respawn if out of bounds
const rSq = ball.x * ball.x + ball.z * ball.z;
if (ball.y < BALL_OOB_Y || rSq > (BALL_WORLD_RADIUS + 6) * (BALL_WORLD_RADIUS + 6)) {
- console.log(`[walk_world ${this.roomId}] ball out of bounds — respawning`);
+ console.log(`[walk_world ${this.roomId}] ball out of bounds, respawning`);
this._spawnBall();
return;
}
@@ -3260,7 +3260,7 @@ export class WalkRoom extends Room {
// Handle a kick intent from a client. Server validates and caps the impulse,
// then applies it to the authoritative ball velocity. Never trusts the client's
- // raw values — only direction + a capped magnitude survive.
+ // raw values, only direction + a capped magnitude survive.
_handleBallKick(client, payload) {
if (!this.state.players.has(client.sessionId)) return;
if (!this._kickOk(client.sessionId)) return;
diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.js
index 84e770398..e3af44ff0 100644
--- a/multiplayer/src/schemas.js
+++ b/multiplayer/src/schemas.js
@@ -1,7 +1,7 @@
// Schema definitions shared between the WalkRoom (server) and the client.
//
// @colyseus/schema uses delta encoding: only fields that changed since the
-// last patch are sent over the wire. Keep this schema small and primitive —
+// last patch are sent over the wire. Keep this schema small and primitive,
// every field here is paid for on every state diff.
import { Schema, MapSchema, defineTypes } from '@colyseus/schema';
@@ -29,19 +29,19 @@ export class Player extends Schema {
// WebRTC connection to them and the UI can mark their nameplate.
this.voice = false;
this.tsServer = 0; // server-side last-update epoch ms (for interpolation)
- // Verified Solana wallet address bound at sign-in — the account id this
+ // Verified Solana wallet address bound at sign-in, the account id this
// player persists under and is known by in the social graph. Empty in the
// open (un-gated) world; set from the play pass when the token gate is on.
this.account = '';
// Combat (W07). HP/armor stay PRIVATE (off-schema, streamed only to the
// owner) so peers can't read exact vitals, but two states MUST be visible to
// everyone: whether you're downed (peers render the ragdoll + skip you as a
- // target) and your wanted level (0–5 stars peers can see to bounty you). Both
- // are tiny and authoritative — set only by the server's combat resolution.
+ // target) and your wanted level (0, 5 stars peers can see to bounty you). Both
+ // are tiny and authoritative, set only by the server's combat resolution.
this.dead = false;
- this.heat = 0; // wanted/heat stars (0–5), derived from the private heat meter
+ this.heat = 0; // wanted/heat stars (0, 5), derived from the private heat meter
// Equipped cosmetic loadout (R03/R23) as the compact wire string peers render
- // — the worn ids in slot order, comma-joined, `none` defaults dropped (see
+ //, the worn ids in slot order, comma-joined, `none` defaults dropped (see
// cosmetics-catalog.serializeLoadout). Set authoritatively from the owner's
// persisted, ownership-validated loadout so a peer can trust the look and an
// unowned cosmetic can never appear on anyone. Empty ⇒ the bare avatar.
@@ -52,7 +52,7 @@ export class Player extends Schema {
// type would lose precision past 2^53 but float64 covers epoch ms safely.
this.it = false;
this.itSince = 0;
- // Verified three.ws username (W10) — set only from a signed presence
+ // Verified three.ws username (W10), set only from a signed presence
// ticket, never from a raw client option, so peers can trust it enough to
// open the real /u/<username> profile, follow, and DM this player. Empty
// for guests and wallet-only sessions.
@@ -95,7 +95,7 @@ defineTypes(Player, {
// A single placed voxel in a coin's world. Keyed in the blocks MapSchema by its
// packed grid coordinate ("gx,gy,gz"), so the position never has to ride on the
-// wire — only the block type does. Delta encoding then makes a place/break a
+// wire, only the block type does. Delta encoding then makes a place/break a
// one-entry patch. `t` is the palette index (see build-voxels.js BLOCK_TYPES).
export class Block extends Schema {
constructor() {
@@ -110,7 +110,7 @@ defineTypes(Block, {
// A drivable vehicle living in the shared world. Unlike a player's private
// economy (off-schema), a vehicle is a world entity everyone must see, so it
// rides on the synced state. The driver's client simulates it with Rapier and
-// streams the authoritative transform (full quaternion — cars pitch/roll over
+// streams the authoritative transform (full quaternion, cars pitch/roll over
// the ground, a single yaw can't express that); the server validates per-type
// speed/bounds and relays. `driver` is the sessionId at the wheel ('' = parked),
// the field that gates who is allowed to write this vehicle's transform.
@@ -118,7 +118,7 @@ export class Vehicle extends Schema {
constructor() {
super();
this.id = '';
- this.type = 'sedan'; // VEHICLE_TYPES key — picks the mesh + handling profile
+ this.type = 'sedan'; // VEHICLE_TYPES key, picks the mesh + handling profile
this.color = 0xffffff;
this.x = 0;
this.y = 0;
@@ -128,7 +128,7 @@ export class Vehicle extends Schema {
this.qy = 0;
this.qz = 0;
this.qw = 1;
- this.speed = 0; // signed forward speed (m/s) — drives wheel spin + audio
+ this.speed = 0; // signed forward speed (m/s), drives wheel spin + audio
this.driver = ''; // sessionId at the wheel; '' when parked
this.health = 100; // damage hooks for W07 (combat); full here
this.tsServer = 0; // last authoritative update (epoch ms) for interpolation
@@ -153,14 +153,14 @@ defineTypes(Vehicle, {
// A PvE enemy in the shared world (W07). Unlike a player's private vitals, a mob
// is a world entity everyone must see and fight, so it rides on the synced state.
-// The SERVER owns every field — spawns it, runs its AI, applies damage — so a
+// The SERVER owns every field, spawns it, runs its AI, applies damage, so a
// client can never move, heal, or kill a mob by writing state; it only renders
// what the room replicates. Keyed in the mobs MapSchema by its id.
export class Mob extends Schema {
constructor() {
super();
this.id = '';
- this.kind = 'goblin'; // MOB_STATS key — picks stats, mesh, loot table
+ this.kind = 'goblin'; // MOB_STATS key, picks stats, mesh, loot table
this.x = 0;
this.y = 0;
this.z = 0;
@@ -212,13 +212,13 @@ defineTypes(Tombstone, {
ts: 'float64',
});
-// A generic networked world object (R01) — the single shared channel every later
+// A generic networked world object (R01), the single shared channel every later
// object feature reuses: thrown balls, placed build props, pickups, confetti.
// Unlike a player's private economy (off-schema), an object is a world entity
// everyone must see, so it rides on the synced state. Keyed in the `objects`
// MapSchema by its id. `ownerId` is the account/session allowed to move or remove
// it; the sentinel 'server' means the room owns it (clients can't write it, e.g.
-// the R05 physics ball). `kind` is the category — build props persist across a
+// the R05 physics ball). `kind` is the category, build props persist across a
// server restart (R17); transient kinds like 'ball' are never saved.
export class WorldObject extends Schema {
constructor() {
@@ -274,7 +274,7 @@ export class WalkState extends Schema {
// Access tier for this instance. '' = the open General world anyone can
// enter; 'holders' = a gated world only wallets holding ≥ holderMinUsd of
// `coin` can join (enforced in WalkRoom.onAuth). The same coin therefore has
- // two isolated rooms — General and Holders — kept apart by filterBy.
+ // two isolated rooms, General and Holders, kept apart by filterBy.
this.tier = '';
this.holderMinUsd = 0; // USD floor for the holder world (0 in General)
// Creator-set token threshold for this coin's holder world (R24): hold ≥ this
@@ -303,7 +303,7 @@ export class WalkState extends Schema {
// the schema (append-only) so an older client isn't shifted off the format.
this.mobs = new MapSchema();
this.tombstones = new MapSchema();
- // Generic placed/networked world objects (R01) — balls, props, pickups —
+ // Generic placed/networked world objects (R01), balls, props, pickups,
// keyed by object id. Durable build props in here are persisted per coin
// world (R17); transient ones (the R05 ball) are not. Append-only at the end.
this.objects = new MapSchema();
diff --git a/multiplayer/src/settlement-guard.js b/multiplayer/src/settlement-guard.js
index 78b10b1c9..8bf703328 100644
--- a/multiplayer/src/settlement-guard.js
+++ b/multiplayer/src/settlement-guard.js
@@ -41,7 +41,7 @@ class SettlementGuard {
})
.catch((err) => {
this._redis = null;
- console.error('[settlement-guard] Redis unreachable — replay guard is per-process only:', err?.message);
+ console.error('[settlement-guard] Redis unreachable, replay guard is per-process only:', err?.message);
});
} else {
console.log('[settlement-guard] replay guard: memory-only (set UPSTASH_REDIS_REST_URL/_TOKEN to span instances + restarts)');
@@ -69,7 +69,7 @@ class SettlementGuard {
if (res === null) return false;
}
} catch (err) {
- console.error(`[settlement-guard] Redis consume failed for ${key} — continuing on the in-process guard:`, err?.message);
+ console.error(`[settlement-guard] Redis consume failed for ${key}, continuing on the in-process guard:`, err?.message);
}
}
return true;
diff --git a/multiplayer/src/walk-registry.js b/multiplayer/src/walk-registry.js
index 6f67996c4..c70298aab 100644
--- a/multiplayer/src/walk-registry.js
+++ b/multiplayer/src/walk-registry.js
@@ -1,4 +1,4 @@
-// Walk-room registry — the in-process lookup that lets the internal
+// Walk-room registry, the in-process lookup that lets the internal
// /internal/announce webhook (called by an operator during a live event, signed
// with the shared secret) reach every live walk_world room on this instance and
// broadcast an announcement to the players in it.
@@ -9,7 +9,7 @@
// at broadcast time) is therefore the right shape, not a Map keyed by coin.
// Under horizontal scaling (Redis driver) an announce only reaches the rooms
// hosted on the instance that received the webhook; the caller fans out to
-// every instance or accepts partial delivery — nothing here breaks.
+// every instance or accepts partial delivery, nothing here breaks.
const _rooms = new Set(); // live WalkRoom instances on this process
diff --git a/multiplayer/src/war-live.js b/multiplayer/src/war-live.js
index cb5b3c3eb..5d2c8d2e3 100644
--- a/multiplayer/src/war-live.js
+++ b/multiplayer/src/war-live.js
@@ -1,4 +1,4 @@
-// Live war registry — the multiplayer server's spectator half of Coin Wars.
+// Live war registry, the multiplayer server's spectator half of Coin Wars.
//
// A battle runs inside a ClashRoom, which only its fighters are connected to.
// Players standing in either community's world want to watch it without joining
@@ -10,7 +10,7 @@
//
// Same writer/reader split as feed.js and presence-store.js: Redis is the bus
// between the long-running game server and the serverless API. Every write is
-// best-effort — spectating is a delight layer, never on the battle's critical
+// best-effort, spectating is a delight layer, never on the battle's critical
// path, so an unreachable Redis means no spectators, never a thrown error inside
// a room handler.
@@ -47,7 +47,7 @@ if (REDIS_URL && REDIS_TOKEN) {
})
.catch((err) => {
_redis = null;
- console.warn('[war-live] Redis unreachable — wars will not be spectatable:', err?.message);
+ console.warn('[war-live] Redis unreachable, wars will not be spectatable:', err?.message);
});
} else {
console.log('[war-live] live war registry disabled (no UPSTASH_REDIS_REST_URL/_TOKEN)');
diff --git a/multiplayer/src/war-matchmaking.js b/multiplayer/src/war-matchmaking.js
index 07cd74e80..53fd14a01 100644
--- a/multiplayer/src/war-matchmaking.js
+++ b/multiplayer/src/war-matchmaking.js
@@ -1,4 +1,4 @@
-// War matchmaking — the pure pairing math behind the Coin Wars portal.
+// War matchmaking, the pure pairing math behind the Coin Wars portal.
//
// A player standing in their coin's world presses "Enter the war". That queues
// their community. When a SECOND community is waiting, the two are paired and
@@ -106,12 +106,12 @@ export function entryLive(entry, now) {
* fight, return the next queue and what to tell the caller.
*
* Four outcomes, in the order they are checked:
- * 'paired' — this community was already matched by an earlier call (the
+ * 'paired', this community was already matched by an earlier call (the
* other side queued first and paired with us); hand back the key.
- * 'matched' — we just paired with a waiting community; both entries are
+ * 'matched', we just paired with a waiting community; both entries are
* stamped with the new key.
- * 'waiting' — nobody else is queued; we are now the one waiting.
- * 'invalid' — the community is not a coin we can seat.
+ * 'waiting', nobody else is queued; we are now the one waiting.
+ * 'invalid', the community is not a coin we can seat.
*
* @param {object} args
* @param {Array<object>} args.queue stored entries (any staleness)
@@ -131,7 +131,7 @@ export function joinQueue({ queue = [], coin, network = 'mainnet', now = 0 }) {
const live = liveOnly(queue, now).filter((e) => e.network === net || !e.network);
const mine = live.find((e) => e.mint === mint) || null;
- // Already paired by whoever queued second — nothing to do but report it.
+ // Already paired by whoever queued second, nothing to do but report it.
if (mine?.matchKey) {
const rest = live.filter((e) => e.mint !== mint);
return {
@@ -152,7 +152,7 @@ export function joinQueue({ queue = [], coin, network = 'mainnet', now = 0 }) {
image: str(coin?.image, 400),
};
- // The oldest unpaired community that is not us — first come, first fought.
+ // The oldest unpaired community that is not us, first come, first fought.
const rival = live
.filter((e) => e.mint !== mint && !e.matchKey)
.sort((x, y) => (x.at || 0) - (y.at || 0))[0] || null;
diff --git a/multiplayer/src/war-ticket.js b/multiplayer/src/war-ticket.js
index 8ac7b2773..2804c2760 100644
--- a/multiplayer/src/war-ticket.js
+++ b/multiplayer/src/war-ticket.js
@@ -1,4 +1,4 @@
-// War ticket verification — the game-server half of Coin Wars matchmaking.
+// War ticket verification, the game-server half of Coin Wars matchmaking.
//
// The API's matchmaker (api/wars.js over war-matchmaking.js) pairs two coin
// communities and seals the pairing into an HMAC-signed ticket
@@ -23,12 +23,12 @@ function secret() {
// let anyone open an arena naming any two communities.
if (process.env.NODE_ENV === 'production') {
throw new Error(
- '[war-ticket] WAR_TICKET_SECRET (or WAR_RESULT_SECRET / HOLDER_PASS_SECRET) is required in production — refusing to verify tickets with the dev secret.',
+ '[war-ticket] WAR_TICKET_SECRET (or WAR_RESULT_SECRET / HOLDER_PASS_SECRET) is required in production, refusing to verify tickets with the dev secret.',
);
}
if (!_warned) {
_warned = true;
- console.warn('[war-ticket] no ticket secret set — verifying with the insecure dev secret (development only).');
+ console.warn('[war-ticket] no ticket secret set, verifying with the insecure dev secret (development only).');
}
return DEV_SECRET;
}
diff --git a/multiplayer/src/world-features.js b/multiplayer/src/world-features.js
index eee839d83..8b4afd72d 100644
--- a/multiplayer/src/world-features.js
+++ b/multiplayer/src/world-features.js
@@ -5,8 +5,8 @@
// gather nodes) are re-anchored here to fixed positions in continuous world space.
//
// This module is the ONE source of truth for those positions, imported by BOTH the
-// server (WalkRoom — validates "are you actually beside the water?") and the client
-// (coincommunities/play-systems — renders the pond and gates the Cast button), so
+// server (WalkRoom, validates "are you actually beside the water?") and the client
+// (coincommunities/play-systems, renders the pond and gates the Cast button), so
// the playable world and the authoritative world can never drift apart. Coordinates
// are world metres in the XZ plane; the ground sits at y = 0.
//
@@ -22,7 +22,7 @@ export const FISHING_SPOTS = [
{ id: 'pond-west', x: -28, z: 16, r: 4.6, quality: 1.4 },
];
-// How far BEYOND a pond's water edge a player may stand and still cast — you fish
+// How far BEYOND a pond's water edge a player may stand and still cast, you fish
// from the bank, not from the middle of the water. Generous enough that the Cast
// button feels reliable as you walk up, tight enough that it's clearly "at" the pond.
export const FISH_REACH = 3.4;
@@ -42,19 +42,19 @@ export function nearestFishingSpot(x, z) {
// Server-side gate: is the player standing close enough to a pond to cast? Returns
// the spot (with its quality) or null. The single check both the server trusts and
-// the client mirrors for the button — same function, no drift.
+// the client mirrors for the button, same function, no drift.
export function fishingSpotInRange(x, z) {
const near = nearestFishingSpot(x, z);
return near && near.gap <= 0 ? near.spot : null;
}
// ---------------------------------------------------------------------------
-// Gather & craft stations — woodcutting, mining, cooking (W06)
+// Gather & craft stations, woodcutting, mining, cooking (W06)
// ---------------------------------------------------------------------------
//
// The gather→craft loop's fixed world stations, the chop/mine/cook counterpart to
// the fishing ponds above. All sited in the SAFE town (clear of the W07 danger
-// zones), so the gather economy stays peaceful — you fight foes in the wilds, you
+// zones), so the gather economy stays peaceful, you fight foes in the wilds, you
// gather and cook at home. Generalised over `nearestNode` so the range rule the
// server trusts and the client renders the button from is byte-identical to fishing.
@@ -103,7 +103,7 @@ export const MINE_REACH = 2.8;
export function nearestRock(x, z) { return nearestNode(x, z, ROCKS, MINE_REACH); }
export function rockInRange(x, z) { return nodeInRange(x, z, ROCKS, MINE_REACH); }
-// Roast pits — cook raw fish into edible cooked fish. Sited beside the ponds so the
+// Roast pits, cook raw fish into edible cooked fish. Sited beside the ponds so the
// catch→cook→eat loop is a short walk, not a trek.
export const FIREPITS = [
{ id: 'fire-east', x: 23, z: 13, r: 1.0 },
@@ -113,9 +113,9 @@ export const COOK_REACH = 2.6;
export function nearestFirepit(x, z) { return nearestNode(x, z, FIREPITS, COOK_REACH); }
export function firepitInRange(x, z) { return nodeInRange(x, z, FIREPITS, COOK_REACH); }
-// The Wheel of Fortune — "Fortune's Folly" (W09/Task 19). One per world, in the
-// open plaza north of the totem: clear of both ponds (~29–33m away), both
-// firepits (~22–25m), and the plaza rod pickup (~16m) — a landmark on its own,
+// The Wheel of Fortune, "Fortune's Folly" (W09/Task 19). One per world, in the
+// open plaza north of the totem: clear of both ponds (~29, 33m away), both
+// firepits (~22, 25m), and the plaza rod pickup (~16m), a landmark on its own,
// not crowded against another station.
export const WHEEL = [
{ id: 'wheel-plaza', x: 0, z: 22, r: 2.0 },
@@ -153,15 +153,15 @@ export function vendorInRange(x, z) { return nodeInRange(x, z, VENDOR_STALLS, CO
export function nearestAtm(x, z) { return nearestNode(x, z, ATMS, COUNTER_REACH); }
export function atmInRange(x, z) { return nodeInRange(x, z, ATMS, COUNTER_REACH); }
-// The Plaza Stage — the Living Stages venue standing in every coin world's plaza
+// The Plaza Stage, the Living Stages venue standing in every coin world's plaza
// (F17). `r` is the footprint of the built structure (platform + backdrop), which
// is what the client renders and what WalkRoom protects from being buried or
// walled in (its protected discs are derived from this point, so the landmark and
// the grief guard can never drift apart).
//
// Sited in the north-east plaza: a short walk from the wheel at (0,22) and clear
-// of every other feature — the east pond (~22 m), the east firepit (~14 m), the
-// plaza rod pickup (~15 m) — and well outside all three danger zones, so the
+// of every other feature, the east pond (~22 m), the east firepit (~14 m), the
+// plaza rod pickup (~15 m), and well outside all three danger zones, so the
// crowd that gathers for a show is standing in safe town.
export const PLAZA_STAGE = { id: 'plaza-stage', x: 18, z: 26, r: 5 };
@@ -180,7 +180,7 @@ export function nearestStage(x, z) { return nearestNode(x, z, [PLAZA_STAGE], STA
export function stageInRange(x, z) { return nodeInRange(x, z, [PLAZA_STAGE], STAGE_ATTEND_REACH); }
export function stageMarqueeInRange(x, z) { return nodeInRange(x, z, [PLAZA_STAGE], STAGE_MARQUEE_REACH); }
-// The War Portal — the Coin Wars door standing in every coin world's plaza
+// The War Portal, the Coin Wars door standing in every coin world's plaza
// (F18). Walking up to it shows this community's league standing, the last
// battles fought, and any war running right now; interacting with it queues the
// community for a battle and hands the player through to the arena at /play/war.
@@ -192,7 +192,7 @@ export function stageMarqueeInRange(x, z) { return nodeInRange(x, z, [PLAZA_STAG
// the northern wilds (0,42,r10), so the crowd reading the board is in safe town.
export const WAR_PORTAL = { id: 'war-portal', x: -20, z: 30, r: 3 };
-// How close a player must stand to use the portal (the "E — Enter the war"
+// How close a player must stand to use the portal (the "E, Enter the war"
// prompt). Matches the other landmark reaches so every plaza interaction has the
// same feel underfoot.
export const WAR_PORTAL_REACH = 3.5;
@@ -206,7 +206,7 @@ export function nearestWarPortal(x, z) { return nearestNode(x, z, [WAR_PORTAL],
export function warPortalInRange(x, z) { return nodeInRange(x, z, [WAR_PORTAL], WAR_PORTAL_REACH); }
export function warPortalBoardInRange(x, z) { return nodeInRange(x, z, [WAR_PORTAL], WAR_PORTAL_BOARD_REACH); }
-// Fishing-rod pickups — a spare rod waiting on the bank for anyone without one
+// Fishing-rod pickups, a spare rod waiting on the bank for anyone without one
// (or anyone who wants a backup to store). Every player already starts with a
// rod in the hotbar and it's never lost on death, so these exist for
// discoverability and flavour, not survival: sited just past each pond's cast
@@ -222,7 +222,7 @@ export const PICKUP_REACH = 2.4;
export function nearestRodPickup(x, z) { return nearestNode(x, z, ROD_PICKUPS, PICKUP_REACH); }
export function rodPickupInRange(x, z) { return nodeInRange(x, z, ROD_PICKUPS, PICKUP_REACH); }
-// Mob spawn points — used by W07 combat and the ACTIVITIES dispatch in play-systems.
+// Mob spawn points, used by W07 combat and the ACTIVITIES dispatch in play-systems.
export const MOB_SPAWNS = [
{ id: 'mob-danger-n', x: 0, z: -60, r: 1.5 },
{ id: 'mob-danger-e', x: 60, z: 0, r: 1.5 },
@@ -233,11 +233,11 @@ export const MOB_REACH = 4.0;
export function nearestMobSpawn(x, z) { return nearestNode(x, z, MOB_SPAWNS, MOB_REACH); }
// ---------------------------------------------------------------------------
-// Safe vs danger zones — opt-in PvP by location (W07)
+// Safe vs danger zones, opt-in PvP by location (W07)
// ---------------------------------------------------------------------------
//
// GTA / Kintara-style risk geography: the whole built-up town (spawn, totem,
-// trading screen, and the gather/fish stations) is SAFE — no player may damage
+// trading screen, and the gather/fish stations) is SAFE, no player may damage
// another there and no roaming mob enters it. Combat tension is confined to a
// handful of named WILDERNESS pockets sited in the open ground away from those
// landmarks: inside one, PvP is on and PvE mobs roam and drop the better loot.
@@ -246,8 +246,8 @@ export function nearestMobSpawn(x, z) { return nearestNode(x, z, MOB_SPAWNS, MOB
// the gather economy undisturbed.
//
// This is the ONE source of truth for the boundary, imported by BOTH the server
-// (WalkRoom — gates every attack, confines + seeds mobs, picks death-drop rules)
-// and the client (PlayCombat — paints the danger ground ring, signposts the
+// (WalkRoom, gates every attack, confines + seeds mobs, picks death-drop rules)
+// and the client (PlayCombat, paints the danger ground ring, signposts the
// crossing, gates the attack button). A circle test is exact, cheap and trivially
// unit-testable; W01 can later refine these into full districts.
// Sited within the area players actually roam today (the ~58 m central plaza the
@@ -261,7 +261,7 @@ export const DANGER_ZONES = [
];
export const WORLD_RADIUS = 60; // matches WalkRoom's authoritative clamp
-export const SPAWN_POINT = { x: 0, z: 0 }; // where the dead respawn — always safe
+export const SPAWN_POINT = { x: 0, z: 0 }; // where the dead respawn, always safe
// The danger zone a world point sits inside, or null when it's in safe town.
export function dangerZoneAt(x, z) {
diff --git a/pages/play.html b/pages/play.html
index f4b797795..f2746ae10 100644
--- a/pages/play.html
+++ b/pages/play.html
@@ -1,22 +1,22 @@
<!doctype html>
<html lang="en">
<head>
- <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
- <script>/* embed bg — ?bg=transparent composites the world onto the host page (e.g. the IBM x402 showcase) instead of a black box. Set before first paint so there is no dark flash. */(function(){try{if(new URLSearchParams(location.search).get('bg')==='transparent')document.documentElement.setAttribute('data-bg','transparent');}catch(e){}})();</script>
+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <script>/* embed bg, ?bg=transparent composites the world onto the host page (e.g. the IBM x402 showcase) instead of a black box. Set before first paint so there is no dark flash. */(function(){try{if(new URLSearchParams(location.search).get('bg')==='transparent')document.documentElement.setAttribute('data-bg','transparent');}catch(e){}})();</script>
<meta charset="utf-8" />
- <title data-i18n="play.meta_title">Play · Coin Communities — three.ws</title>
+ <title data-i18n="play.meta_title">Play · Coin Communities, three.ws</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1, viewport-fit=cover"
/>
<meta
name="description"
- content="Coin Communities — a browser isometric MMO on three.ws. Join coin communities, gather, fight, trade, and explore a shared world. Sign in with your wallet and play."
+ content="Coin Communities, a browser isometric MMO on three.ws. Join coin communities, gather, fight, trade, and explore a shared world. Sign in with your wallet and play."
data-i18n-attr="content:play.meta_description"/>
<meta name="theme-color" content="#060607" />
<!--
- Multiplayer server URL — the deployed Colyseus host (Cloud Run).
+ Multiplayer server URL, the deployed Colyseus host (Cloud Run).
Local dev ignores this and uses ws://localhost:2567 automatically
(see defaultServerUrl in src/game/community-net.js), so
`npm run dev:walk-all` still works out of the box.
@@ -33,14 +33,14 @@
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
<meta property="og:title" content="Play · Coin Communities" data-i18n-attr="content:play.meta_og_title"/>
- <meta property="og:description" content="A browser isometric MMO on three.ws — join coin communities, gather, fight, trade, explore." data-i18n-attr="content:play.meta_og_description"/>
+ <meta property="og:description" content="A browser isometric MMO on three.ws, join coin communities, gather, fight, trade, explore." data-i18n-attr="content:play.meta_og_description"/>
<meta property="og:url" content="https://three.ws/play" />
<meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Play&amp;d=Jump+into+a+live+coin+community+world+and+explore+it+with+your+avatar.&amp;p=%2Fplay" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@trythreews" />
- <meta name="twitter:title" content="Play · Coin Communities — three.ws" data-i18n-attr="content:play.meta_twitter_title"/>
+ <meta name="twitter:title" content="Play · Coin Communities, three.ws" data-i18n-attr="content:play.meta_twitter_title"/>
<meta name="twitter:description" content="Play in your coin's 3D community world. Walk, chat, and hang out with fellow holders." data-i18n-attr="content:play.meta_twitter_description"/>
<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Play&amp;d=Jump+into+a+live+coin+community+world+and+explore+it+with+your+avatar.&amp;p=%2Fplay" />
@@ -49,7 +49,7 @@
page never loaded a face for it, so the whole surface (including the boot
wordmark) silently rendered in the OS default. Preload the latin subset so
the loader's first paint is already on-brand, no FOUT.
- See docs/DESIGN-TOKENS.md — standalone pages must load /fonts/fonts.css.
+ See docs/DESIGN-TOKENS.md, standalone pages must load /fonts/fonts.css.
-->
<link rel="preload" href="/fonts/inter-latin.woff2" as="font" type="font/woff2" crossorigin />
<link rel="stylesheet" href="/fonts/fonts.css" />
@@ -58,7 +58,7 @@
<link rel="canonical" href="https://three.ws/play">
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
<meta property="og:locale" content="en_US">
- <meta property="og:image:alt" content="Play — three.ws">
+ <meta property="og:image:alt" content="Play, three.ws">
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Play","description":"Jump into a live coin community world and explore it with your avatar.","url":"https://three.ws/play","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&amp;t=Play&amp;d=Jump+into+a+live+coin+community+world+and+explore+it+with+your+avatar.&amp;p=%2Fplay"}]}</script>
</head>
<body>
@@ -194,11 +194,19 @@
msg.style.cssText = 'opacity:.8;font-size:14px;line-height:1.5;margin:0 0 18px;';
var actions = document.createElement('div');
actions.className = 'kx-boot-error-actions';
+ /* This card exists because a stylesheet may be exactly what failed, so
+ the two things a stranded player needs, a thumb-sized target and a
+ visible focus ring, cannot be left to coincommunities.css. Inline
+ style attributes cannot express :focus-visible, so the rules ride
+ along in their own <style> element. */
+ var ring = document.createElement('style');
+ ring.textContent = '.kx-boot-error-btn:focus-visible,.kx-boot-error-link:focus-visible{outline:2px solid #fff;outline-offset:2px;}';
+ card.appendChild(ring);
var retry = document.createElement('button');
retry.type = 'button';
retry.className = 'kx-boot-error-btn';
retry.textContent = 'Try again';
- retry.style.cssText = 'padding:10px 22px;border-radius:8px;border:1px solid #555;background:#191a1c;color:#fff;cursor:pointer;font-size:14px;';
+ retry.style.cssText = 'min-height:44px;padding:12px 22px;border-radius:8px;border:1px solid #555;background:#191a1c;color:#fff;cursor:pointer;font-size:14px;';
retry.addEventListener('click', function () {
/* Hard reload: a stale cached HTML referencing dead chunks needs a
revalidated document, not a memory-cache replay. */
@@ -208,7 +216,7 @@
home.className = 'kx-boot-error-link';
home.href = '/';
home.textContent = 'Back to three.ws';
- home.style.cssText = 'display:inline-block;margin-left:14px;color:#9ab;font-size:14px;';
+ home.style.cssText = 'display:inline-flex;align-items:center;min-height:44px;padding:0 10px;margin-left:14px;color:#9ab;font-size:14px;';
actions.appendChild(retry);
actions.appendChild(home);
card.appendChild(mark);
diff --git a/public/event.json b/public/event.json
index 41b54b053..9bb119a98 100644
--- a/public/event.json
+++ b/public/event.json
@@ -9,7 +9,7 @@
"linkLabel": "Join the $THREE world",
"souvenir": {
"cosmeticId": "laurel-meetup",
- "$comment": "Free commemorative wearable granted once to every player in the world named by `link` between startsAt and endsAt. Must be an id in multiplayer/src/cosmetics-catalog.js with tier 'event' — the server refuses to grant anything else, so this field can never hand out a boutique item. Drop the field to run an event with no souvenir."
+ "$comment": "Free commemorative wearable granted once to every player in the world named by `link` between startsAt and endsAt. Must be an id in multiplayer/src/cosmetics-catalog.js with tier 'event', the server refuses to grant anything else, so this field can never hand out a boutique item. Drop the field to run an event with no souvenir."
},
"agenda": [
{ "atMin": 0, "title": "Doors open in the plaza", "detail": "Say hi in chat, show off your fit, grab a commemorative photo", "icon": "👋" },
diff --git a/src/event-page.js b/src/event-page.js
index bd0703694..a2163ee93 100644
--- a/src/event-page.js
+++ b/src/event-page.js
@@ -52,6 +52,23 @@ const els = {
};
// ── config ──────────────────────────────────────────────────────────────────
+// The config is a repo file, but it arrives over the network and its `link`
+// becomes an href and an .ics URL. Accept only a same-origin http(s) target, so
+// a swapped or tampered event.json cannot turn the page's one big button into a
+// `javascript:` payload or an off-site redirect. Anything else falls back to
+// /play, which is always the right door.
+function safeLink(raw) {
+ if (!raw) return '/play';
+ try {
+ const u = new URL(String(raw), location.origin);
+ if (u.origin !== location.origin) return '/play';
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') return '/play';
+ return u.pathname + u.search + u.hash;
+ } catch {
+ return '/play';
+ }
+}
+
// Deliberately the same shape and the same fallbacks as event-countdown.js: an
// event with no usable end time is treated as six hours long by both surfaces.
function parseConfig(raw) {
@@ -65,7 +82,7 @@ function parseConfig(raw) {
tagline: raw.tagline ? String(raw.tagline) : '',
startsAt,
endsAt: Number.isFinite(endsAt) ? endsAt : startsAt + 6 * 3600 * 1000,
- link: raw.link ? String(raw.link) : '/play',
+ link: safeLink(raw.link),
linkLabel: raw.linkLabel ? String(raw.linkLabel) : 'Join the event',
agenda: Array.isArray(raw.agenda)
? raw.agenda
diff --git a/src/game/coin-buy.js b/src/game/coin-buy.js
index ac1f14acf..2380d1def 100644
--- a/src/game/coin-buy.js
+++ b/src/game/coin-buy.js
@@ -759,6 +759,33 @@ class TradeModal {
}
}
+ // The quote endpoint is advisory: the swap is priced server-side at execution,
+ // so a failed quote never blocks the trade. It does have to be honest about WHY
+ // there is no number. "Priced at buy" is true when the server answered and had
+ // no pre-quote to give (a coin still on the bonding curve) and a lie when the
+ // quote service itself is down, and a bare `.then(r => r.json())` collapsed
+ // the two, so a 429 or a 502 rendered the reassuring on-curve copy and fed the
+ // error body to _captureFee. Surface the status so the caller can tell them
+ // apart, exactly like _quoteSolBuy already does for the on-chain lane.
+ async _fetchQuote(params) {
+ const r = await fetch(`/api/pump/quote?${params}`);
+ if (!r.ok) {
+ const err = new Error(`HTTP ${r.status}`);
+ err.status = r.status;
+ throw err;
+ }
+ return r.json();
+ }
+
+ // What to tell the player when no price could be fetched at all. Rate limiting
+ // is transient and worth naming (retrying in a moment works); anything else is
+ // an outage. Either way the trade itself still prices at execution.
+ _quoteUnavailable(status) {
+ return status === 429
+ ? 'Pricing is busy right now, retry in a moment.'
+ : 'Price check unavailable, this still prices at execution.';
+ }
+
async _quoteServer() {
const seq = ++this._quoteSeq;
this.quoteLine.classList.remove('cc-buy-quote-warn');
@@ -768,7 +795,7 @@ class TradeModal {
this.quoteLine.textContent = 'Fetching price…';
const u = new URLSearchParams({ mint: this.coin.mint, network: NETWORK, direction: 'buy', usdc: String(this.amount), slippage_bps: String(this.slippageBps) });
try {
- const data = await fetch(`/api/pump/quote?${u}`).then((r) => r.json());
+ const data = await this._fetchQuote(u);
if (seq !== this._quoteSeq) return;
if (typeof data?.graduated === 'boolean') { this.graduated = data.graduated; this._renderStage(); }
this._captureFee(data);
@@ -779,13 +806,14 @@ class TradeModal {
this.quoteLine.append(el('span', { class: 'cc-buy-quote-out', text: tokens ? `≈ ${tokens} ${this.symTokens}` : 'Quoted at market' }));
this.quoteLine.append(el('span', { class: 'cc-buy-quote-impact', text: ` · for ${this.amount} USDC` }));
} else {
+ // The server answered and had no pre-quote: genuinely on-curve.
this.quoteLine.classList.add('cc-buy-quote-warn');
this.quoteLine.textContent = `Priced at buy — you'll receive ${this.sym} for ${this.amount} USDC.`;
}
- } catch {
+ } catch (err) {
if (seq !== this._quoteSeq) return;
this.quoteLine.classList.add('cc-buy-quote-warn');
- this.quoteLine.textContent = `Priced at buy — you'll receive ${this.sym} for ${this.amount} USDC.`;
+ this.quoteLine.textContent = this._quoteUnavailable(err?.status);
}
return;
}
@@ -796,7 +824,7 @@ class TradeModal {
this.quoteLine.textContent = 'Fetching price…';
const u = new URLSearchParams({ mint: this.coin.mint, network: NETWORK, direction: 'sell', token: tokens, slippage_bps: String(this.slippageBps) });
try {
- const data = await fetch(`/api/pump/quote?${u}`).then((r) => r.json());
+ const data = await this._fetchQuote(u);
if (seq !== this._quoteSeq) return;
if (typeof data?.graduated === 'boolean') { this.graduated = data.graduated; this._renderStage(); }
this._captureFee(data);
@@ -807,13 +835,14 @@ class TradeModal {
this.quoteLine.append(el('span', { class: 'cc-buy-quote-out', text: `≈ ${fmtQuote(out, this.denom)} ${this.denom.label}` }));
this.quoteLine.append(el('span', { class: 'cc-buy-quote-impact', text: ` · you receive` }));
} else {
+ // The server answered and had no pre-quote: genuinely on-curve.
this.quoteLine.classList.add('cc-buy-quote-warn');
this.quoteLine.textContent = `Priced at sale — you'll receive ${this.denom.label}.`;
}
- } catch {
+ } catch (err) {
if (seq !== this._quoteSeq) return;
this.quoteLine.classList.add('cc-buy-quote-warn');
- this.quoteLine.textContent = `Priced at sale — you'll receive ${this.denom.label}.`;
+ this.quoteLine.textContent = this._quoteUnavailable(err?.status);
}
}