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.

fix(multiplayer): make one payment grant once, across rooms and restarts

nirholas3b0d23fbd29e
diff --git a/multiplayer/src/game-token.js b/multiplayer/src/game-token.js
index e430538ff..ee6a08b7e 100644
--- a/multiplayer/src/game-token.js
+++ b/multiplayer/src/game-token.js
@@ -40,6 +40,13 @@ export const REWARDS_SINK =
'';
const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+// Commitment level settlement verification reads at. 'confirmed' answers in a
+// couple of seconds, which is what keeps the in-wallet spin/boutique flow
+// responsive; the residual risk (a confirmed tx dropped on a fork after the
+// grant) is bounded to single-digit dollars per settlement and further pinned
+// by the memo + durable nonce guard. Operators who prefer certainty over
+// latency can set GAME_TOKEN_VERIFY_COMMITMENT=finalized.
+const VERIFY_COMMITMENT = process.env.GAME_TOKEN_VERIFY_COMMITMENT === 'finalized' ? 'finalized' : 'confirmed';
const BIRDEYE_BASE = 'https://public-api.birdeye.so';
// SPL memo program — a memo carrying the quote nonce binds the on-chain tx to
// one specific quote so an unrelated transfer of the right size can't settle it.
@@ -241,10 +248,10 @@ export async function buildSplitTransaction({ buyerWallet, sellerWallet, sellerR
// however the wallet assembled the transfer. Returns { ok, reason }.
export async function verifySplitPayment({ txSig, sellerWallet, sellerRaw, treasuryRaw }) {
if (typeof txSig !== 'string' || txSig.length < 32 || txSig.length > 128) return { ok: false, reason: 'bad_signature' };
- const conn = new Connection(SOLANA_RPC, 'confirmed');
+ const conn = new Connection(SOLANA_RPC, VERIFY_COMMITMENT);
let tx;
try {
- tx = await conn.getParsedTransaction(txSig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });
+ tx = await conn.getParsedTransaction(txSig, { commitment: VERIFY_COMMITMENT, maxSupportedTransactionVersion: 0 });
} catch (err) {
return { ok: false, reason: 'rpc_error' };
}
@@ -331,7 +338,7 @@ function memoInstruction(nonce) {
* @param {{ buyerWallet: string, usd: number }} params
* @returns {Promise<null | { quoteToken: string, txBase64: string, quote: object }>}
*/
-export async function buildSpinPayment({ buyerWallet, usd }) {
+export async function buildSpinPayment({ buyerWallet, usd, forAccount = '' }) {
if (!tokenConfigured()) return null;
const priced = await quoteTokenForUsd(usd);
if (!priced || !(priced.raw > 0n)) return null;
@@ -380,6 +387,9 @@ export async function buildSpinPayment({ buyerWallet, usd }) {
rewardsRaw: rewardsRaw.toString(),
treasuryAddr,
treasuryRaw: treasuryRaw.toString(),
+ // Session binding: the quote can only settle onto the profile that asked
+ // for it (see verifySpinPayment). Empty when the caller has no stable id.
+ ...(forAccount ? { forAccount } : {}),
nonce,
};
const quoteToken = signQuote(quotePayload);
@@ -394,16 +404,20 @@ export async function buildSpinPayment({ buyerWallet, usd }) {
* @param {{ quoteToken: string, txSig: string, buyerWallet?: string }} params
* @returns {Promise<{ ok: boolean, reason?: string, nonce?: string, quote?: object }>}
*/
-export async function verifySpinPayment({ quoteToken, txSig, buyerWallet }) {
+export async function verifySpinPayment({ quoteToken, txSig, buyerWallet, forAccount }) {
const q = verifyQuote(quoteToken);
if (!q || q.purpose !== 'spin') return { ok: false, reason: 'bad_quote' };
if (buyerWallet && q.buyer && q.buyer !== buyerWallet) return { ok: false, reason: 'buyer_mismatch' };
+ // The quote is sealed to the session account that requested it (forAccount),
+ // so a leaked { quoteToken, txSig } pair can't be redeemed onto a different
+ // profile. Quotes minted before this field existed verify as before.
+ if (q.forAccount && forAccount && q.forAccount !== forAccount) return { ok: false, reason: 'wrong_session' };
if (typeof txSig !== 'string' || txSig.length < 32 || txSig.length > 128) return { ok: false, reason: 'bad_signature' };
- const conn = new Connection(SOLANA_RPC, 'confirmed');
+ const conn = new Connection(SOLANA_RPC, VERIFY_COMMITMENT);
let tx;
try {
- tx = await conn.getParsedTransaction(txSig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });
+ tx = await conn.getParsedTransaction(txSig, { commitment: VERIFY_COMMITMENT, maxSupportedTransactionVersion: 0 });
} catch {
return { ok: false, reason: 'rpc_error' };
}
@@ -522,7 +536,13 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, rewa
tx.recentBlockhash = blockhash;
const txBase64 = tx.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64');
+ // `extra` is sealed for the caller's own settle-time context (e.g. the
+ // boutique listing id), but it must never be able to overwrite the payment
+ // terms: spread it FIRST so every sealed settlement field below wins, and a
+ // hostile extra.nonce/total/treasuryRaw can never rewrite what verification
+ // checks against.
const quotePayload = {
+ ...extra,
purpose,
mint: TOKEN_MINT,
decimals: TOKEN_DECIMALS,
@@ -539,7 +559,6 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, rewa
// or omit it. Absent keys mean "no creator leg" (plain two-way split).
...(creatorActive ? { creatorAddr: creatorWallet, creatorRaw: creatorRaw.toString(), creatorBps: effectiveCreatorBps } : {}),
nonce,
- ...extra,
};
const quoteToken = signQuote(quotePayload);
return { quoteToken, txBase64, quote: { ...quotePayload, ttlSeconds: QUOTE_TTL_SECONDS } };
@@ -553,16 +572,19 @@ export async function buildTokenPurchase({ buyerWallet, amountRaw, purpose, rewa
* @param {{ quoteToken: string, txSig: string, buyerWallet?: string, purpose?: string }} params
* @returns {Promise<{ ok: boolean, reason?: string, nonce?: string, quote?: object }>}
*/
-export async function verifyTokenPurchase({ quoteToken, txSig, buyerWallet, purpose }) {
+export async function verifyTokenPurchase({ quoteToken, txSig, buyerWallet, purpose, forAccount }) {
const q = verifyQuote(quoteToken);
if (!q || (purpose && q.purpose !== purpose)) return { ok: false, reason: 'bad_quote' };
if (buyerWallet && q.buyer && q.buyer !== buyerWallet) return { ok: false, reason: 'buyer_mismatch' };
+ // Sealed session binding, mirroring verifySpinPayment: a stolen settled quote
+ // can only ever land on the profile that requested it.
+ if (q.forAccount && forAccount && q.forAccount !== forAccount) return { ok: false, reason: 'wrong_session' };
if (typeof txSig !== 'string' || txSig.length < 32 || txSig.length > 128) return { ok: false, reason: 'bad_signature' };
- const conn = new Connection(SOLANA_RPC, 'confirmed');
+ const conn = new Connection(SOLANA_RPC, VERIFY_COMMITMENT);
let tx;
try {
- tx = await conn.getParsedTransaction(txSig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });
+ tx = await conn.getParsedTransaction(txSig, { commitment: VERIFY_COMMITMENT, maxSupportedTransactionVersion: 0 });
} catch {
return { ok: false, reason: 'rpc_error' };
}
diff --git a/multiplayer/src/settlement-guard.js b/multiplayer/src/settlement-guard.js
new file mode 100644
index 000000000..78b10b1c9
--- /dev/null
+++ b/multiplayer/src/settlement-guard.js
@@ -0,0 +1,99 @@
+// Durable, process-wide replay guard for on-chain settlements (paid spins, the
+// $THREE boutique, and any future token sink).
+//
+// The old guard was a Map on each WalkRoom instance, which made "one payment,
+// one grant" true only within a single room: the same { quoteToken, txSig }
+// pair replayed into N different coin worlds (or after a restart, or against a
+// second Cloud Run instance) verified on-chain N times and granted N times.
+// This module gives every room in the process one shared consumption ledger,
+// and rides Upstash Redis (the same store playerStore uses) when configured so
+// consumption also survives restarts and spans instances. SET NX is atomic, so
+// two rooms racing the same nonce resolve to exactly one winner.
+//
+// Both the quote nonce AND the transaction signature are consumed: the nonce
+// binds one quote to one grant, and the signature stops a second quote from
+// being settled by the same on-chain transfer.
+//
+// Fail-open on Redis errors, fail-closed on replays: if Redis is unreachable
+// the in-process set still blocks every replay this process can see (exactly
+// the guarantee the per-room Map thought it had), and we log loudly so the
+// degraded window is visible in ops.
+
+const REDIS_URL = process.env.UPSTASH_REDIS_REST_URL || '';
+const REDIS_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || '';
+
+// Consumed keys only need to outlive the 90s quote TTL plus generous clock
+// skew; a day bounds Redis growth while making same-day replays impossible
+// even against archived transactions.
+const CONSUMED_TTL_S = 60 * 60 * 24;
+const MEM_TTL_MS = CONSUMED_TTL_S * 1000;
+
+class SettlementGuard {
+ constructor() {
+ this._mem = new Map(); // key → consumedAt (ms)
+ this._redis = null;
+ this._redisReady = null;
+ if (REDIS_URL && REDIS_TOKEN) {
+ this._redisReady = import('@upstash/redis')
+ .then(({ Redis }) => {
+ this._redis = new Redis({ url: REDIS_URL, token: REDIS_TOKEN });
+ console.log('[settlement-guard] replay guard: memory + Upstash Redis');
+ })
+ .catch((err) => {
+ this._redis = null;
+ 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)');
+ }
+ const sweep = setInterval(() => {
+ const cutoff = Date.now() - MEM_TTL_MS;
+ for (const [k, at] of this._mem) if (at < cutoff) this._mem.delete(k);
+ }, 60_000);
+ if (typeof sweep.unref === 'function') sweep.unref();
+ }
+
+ // Atomically consume one settlement key. Returns true exactly once per key
+ // per TTL window; false means "already settled somewhere" and the caller
+ // must refuse the grant. The in-process set is written first so a Redis
+ // outage can never widen the window within this process.
+ async _consume(key) {
+ if (this._mem.has(key)) return false;
+ this._mem.set(key, Date.now());
+ if (this._redisReady) {
+ try {
+ await this._redisReady;
+ if (this._redis) {
+ const res = await this._redis.set(key, '1', { nx: true, ex: CONSUMED_TTL_S });
+ // Upstash returns 'OK' when NX won, null when the key already existed.
+ if (res === null) return false;
+ }
+ } catch (err) {
+ console.error(`[settlement-guard] Redis consume failed for ${key} — continuing on the in-process guard:`, err?.message);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Consume a settlement's nonce + tx signature. True exactly once per
+ * (nonce, txSig) pair across every room in the process, and across
+ * restarts/instances when Redis is configured.
+ * @param {{ nonce: string, txSig: string, purpose?: string }} params
+ * @returns {Promise<boolean>} whether this settlement is fresh and now consumed
+ */
+ async consumeSettlement({ nonce, txSig, purpose = 'settle' }) {
+ if (typeof nonce !== 'string' || !nonce || typeof txSig !== 'string' || !txSig) return false;
+ const nonceOk = await this._consume(`settle:nonce:${purpose}:${nonce}`);
+ if (!nonceOk) return false;
+ // The signature is consumed unscoped by purpose on purpose: one on-chain
+ // transfer settles one grant, ever, regardless of which sink claims it.
+ const sigOk = await this._consume(`settle:tx:${txSig}`);
+ if (!sigOk) return false;
+ return true;
+ }
+}
+
+// One guard shared by every room in the process.
+export const settlementGuard = new SettlementGuard();
+export function consumeSettlement(params) { return settlementGuard.consumeSettlement(params); }
diff --git a/multiplayer/src/spin-wheel.js b/multiplayer/src/spin-wheel.js
index cadf417e5..a77013edd 100644
--- a/multiplayer/src/spin-wheel.js
+++ b/multiplayer/src/spin-wheel.js
@@ -60,12 +60,19 @@ function avgLevel(profile) {
return levels.reduce((a, b) => a + b, 0) / levels.length;
}
+// Every distinct item a wedge can award, derived from the paytable itself so a
+// new prize kind upstream is covered here without a second list to maintain.
+const PRIZE_ITEMS = [...new Set(WHEEL_SEGMENTS.filter((s) => s.kind === 'item').map((s) => s.item))];
+
// Is there room for at least one of EVERY possible item-type prize this wheel
-// can award? Checked before a spin is even offered (free) or paid for (paid) —
-// never after rolling — so a completed spin can never have nowhere to put its
-// prize. Gold prizes never need this (gold is a scalar balance, not pack space).
-function hasRoomForAnyPrize(profile) {
- return hasRoomFor(profile, 'wood') || hasRoomFor(profile, 'stone') || hasRoomFor(profile, 'coal');
+// can award? Checked before a spin is even offered (free) or paid for (paid) -
+// never after rolling - so a completed spin can never have nowhere to put its
+// prize. It has to be EVERY prize, not any: a pack whose only free space is a
+// half-full wood stack has room for wood and nowhere to put stone, and the roll
+// that follows is uniform over both. Gold prizes never need this (gold is a
+// scalar balance, not pack space).
+function hasRoomForEveryPrize(profile) {
+ return PRIZE_ITEMS.every((item) => hasRoomFor(profile, item));
}
function pickSegment() {
@@ -74,22 +81,25 @@ function pickSegment() {
}
// Grant a rolled segment's prize to the profile. Room was already guaranteed by
-// hasRoomForAnyPrize() before the roll, so addItem's leftover is expected to be
-// 0 — but a defensive fallback still refunds any leftover as its rough gold
+// hasRoomForEveryPrize() before the roll, so addItem's leftover is expected to
+// be 0 - but a defensive fallback still refunds any leftover as its rough gold
// value rather than silently discarding a prize a player (possibly a PAYING
-// player) already won.
+// player) already won. The refund is REPORTED back in the result so the client
+// can say what happened; a prize that quietly turned into a few cash reads as a
+// broken wheel.
const ITEM_GOLD_VALUE = { wood: 1, stone: 1, coal: 2 };
function grantSegment(profile, seg) {
if (seg.kind === 'gold') {
profile.gold = Math.min(0xffffffff, (profile.gold || 0) + seg.gold);
- return { got: seg.gold, overflow: 0 };
+ return { got: seg.gold, lost: 0, refunded: 0 };
}
const leftover = addItem(profile, seg.item, seg.qty);
+ let refunded = 0;
if (leftover > 0) {
- const refund = leftover * (ITEM_GOLD_VALUE[seg.item] || 1);
- profile.gold = Math.min(0xffffffff, (profile.gold || 0) + refund);
+ refunded = leftover * (ITEM_GOLD_VALUE[seg.item] || 1);
+ profile.gold = Math.min(0xffffffff, (profile.gold || 0) + refunded);
}
- return { got: seg.qty - leftover, overflow: 0 };
+ return { got: seg.qty - leftover, lost: leftover, refunded };
}
function infoPayload(room, client, profile) {
@@ -131,14 +141,14 @@ export function handleSpinFree(room, client) {
client.send('spinDenied', { reason: 'cooldown', nextFreeSpinAt: profile.nextFreeSpinAt });
return;
}
- if (!hasRoomForAnyPrize(profile)) { client.send('spinDenied', { reason: 'pack_full' }); return; }
+ if (!hasRoomForEveryPrize(profile)) { client.send('spinDenied', { reason: 'pack_full' }); return; }
profile.nextFreeSpinAt = now + FREE_SPIN_COOLDOWN_MS;
const { index, seg } = pickSegment();
- const { got, overflow } = grantSegment(profile, seg);
+ const { got, lost, refunded } = grantSegment(profile, seg);
room._sendInv(client, profile);
client.send('spinResult', {
- mode: 'free', index, label: seg.label, got, overflow, nextFreeSpinAt: profile.nextFreeSpinAt,
+ mode: 'free', index, label: seg.label, got, lost, refunded, nextFreeSpinAt: profile.nextFreeSpinAt,
});
room._questEvent?.(client, profile, { type: 'spin' });
room._persistEcon(client.sessionId);
@@ -153,7 +163,7 @@ export async function handleSpinPaidPrep(room, client, payload) {
if (!wheelInRange(player.x, player.z)) { client.send('spinDenied', { reason: 'not_at_wheel' }); return; }
const lvl = avgLevel(profile);
if (lvl < MIN_AVG_LEVEL) { client.send('spinDenied', { reason: 'level', avgLevel: lvl, minLevel: MIN_AVG_LEVEL }); return; }
- if (!hasRoomForAnyPrize(profile)) { client.send('spinDenied', { reason: 'pack_full' }); return; }
+ if (!hasRoomForEveryPrize(profile)) { client.send('spinDenied', { reason: 'pack_full' }); return; }
if (!tokenConfigured()) { client.send('spinDenied', { reason: 'token_unavailable' }); return; }
// Same "whoever's wallet fronts it, the unlock lands on this session" model
@@ -164,7 +174,9 @@ export async function handleSpinPaidPrep(room, client, payload) {
let built;
try {
- built = await buildSpinPayment({ buyerWallet: wallet, usd: SPIN_COST_USD });
+ // forAccount seals the quote to this session's profile so a leaked
+ // { quote, txSig } pair can't be redeemed onto a different account.
+ built = await buildSpinPayment({ buyerWallet: wallet, usd: SPIN_COST_USD, forAccount: profile.playerId });
} catch (err) {
console.warn('[walk_world] spin prep failed:', err?.message);
}
@@ -188,7 +200,7 @@ export async function handleSpinPaidSettle(room, client, payload) {
let result;
try {
- result = await verifySpinPayment({ quoteToken, txSig });
+ result = await verifySpinPayment({ quoteToken, txSig, forAccount: profile.playerId });
} catch (err) {
console.warn('[walk_world] spin settle failed:', err?.message);
client.send('spinDenied', { reason: 'not_found' });
@@ -196,19 +208,23 @@ export async function handleSpinPaidSettle(room, client, payload) {
}
if (!result?.ok) { client.send('spinDenied', { reason: result?.reason || 'not_found' }); return; }
- room._pruneSpinNonces?.();
- if (room._spinNonces.has(result.nonce)) { client.send('spinDenied', { reason: 'already_settled' }); return; }
- room._spinNonces.set(result.nonce, Date.now());
-
- // Room precheck at prep time already guaranteed pack space for an item
- // prize; re-check here too since real time passed while the player was in
- // their wallet approving the transaction — a paid spin must never lose a
- // won prize to a pack that filled up in the meantime (grantSegment's own
- // gold-value fallback is the last-resort backstop if it somehow still does).
+ // Durable, process-wide replay guard (settlement-guard.js): one payment rolls
+ // exactly one prize, across every coin world, restart, and instance. The old
+ // per-room Map let the same settled tx re-roll in N different rooms.
+ const fresh = await consumeSettlement({ nonce: result.nonce, txSig, purpose: 'spin' });
+ if (!fresh) { client.send('spinDenied', { reason: 'already_settled' }); return; }
+
+ // The prep-time precheck guaranteed pack space for every item prize, but real
+ // time passed while the player was in their wallet approving the transfer, so
+ // the pack can have filled since. The payment has ALREADY settled by now, so a
+ // denial here would be theft: roll and grant regardless, and let grantSegment's
+ // gold-value fallback catch anything that no longer fits. `refunded` rides back
+ // on the result so the client states plainly what became of the prize instead of
+ // showing a win the pack never received.
const { index, seg } = pickSegment();
- const { got, overflow } = grantSegment(profile, seg);
+ const { got, lost, refunded } = grantSegment(profile, seg);
room._sendInv(client, profile);
- client.send('spinResult', { mode: 'paid', index, label: seg.label, got, overflow });
+ client.send('spinResult', { mode: 'paid', index, label: seg.label, got, lost, refunded });
room._questEvent?.(client, profile, { type: 'spin' });
room._persistEcon(client.sessionId);
}