From 07d9a75f67dacf272ca7591cefb8b3c3b429808a Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Wed, 21 Oct 2026 20:45:20 -0400 Subject: [PATCH 01/10] fix(backend): recheck pet progress after locking pets on battle accept --- .../features/battle/ledger/accept.service.ts | 28 ++++++++-- .../src/features/battle/ledger/transitions.ts | 49 +++++++++++++++++ .../battle/ledger/accept.service.test.ts | 17 ++++++ .../battle/ledger/transitions.test.ts | 52 +++++++++++++++++++ 4 files changed, 142 insertions(+), 4 deletions(-) diff --git a/backend/src/features/battle/ledger/accept.service.ts b/backend/src/features/battle/ledger/accept.service.ts index bd3b6d25..6791466f 100644 --- a/backend/src/features/battle/ledger/accept.service.ts +++ b/backend/src/features/battle/ledger/accept.service.ts @@ -29,7 +29,7 @@ import { servedDeploymentId } from './domain'; import { OUTBOX_TOPICS } from './outbox'; import { buildPetSnapshot } from './snapshot.builder'; import { servedRuleset, servedRulesetHash } from './ruleset.builder'; -import { applyTransition, openBattle } from './transitions'; +import { applyTransition, type ExpectedProgress, openBattle } from './transitions'; /** * The accept flow (§E, §J). @@ -563,6 +563,7 @@ async function openAcceptedBattle(args: { const opened = await openBattle({ consumeIntentHash: args.intentHash, petIds: [attacker.petId.toString(), defender.petId.toString()], + expectedProgress: [progressOf(attacker), progressOf(defender)], ledger: { battleId: args.battleId, chainId: args.domain.chainId, @@ -590,7 +591,26 @@ async function openAcceptedBattle(args: { if (opened.ok) { return proceed(null); } - return opened.reason === 'pet-locked' - ? refuse('pet-locked', `pet ${opened.petId} already has an open battle`) - : refuse('intent-already-consumed', 'this intent already produced a battle'); + switch (opened.reason) { + case 'pet-locked': + return refuse('pet-locked', `pet ${opened.petId} already has an open battle`); + case 'pet-progress-changed': + // Reported as pet-locked: to the caller it is the same event, a battle for this + // pet that was still open when the snapshot was taken. A retry builds a fresh one. + return refuse('pet-locked', `pet ${opened.petId} finished another battle during this accept; try again`); + case 'intent-already-consumed': + return refuse('intent-already-consumed', 'this intent already produced a battle'); + } +} + +/** The progress fields a snapshot froze, in the shape `pet_battle_progress` stores them. */ +function progressOf(pet: BattleSnapshot['attacker']): ExpectedProgress { + return { + petId: pet.petId.toString(), + level: pet.level, + xp: pet.xp, + streak: pet.streak, + lastOpponentId: pet.lastOpponentId.toString(), + readyAt: BigInt(pet.readyAt), + }; } diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index 18ddb832..20269193 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -119,11 +119,32 @@ export interface OpenBattleRequest { * whichever loses this guard gets `intentAlreadyConsumed`, never a second ledger row. */ consumeIntentHash?: string; + /** + * The progress each pet's snapshot was built from, rechecked after the locks are taken. + * + * The snapshot is read before this transaction, so a pet still finishing another battle + * can be photographed mid-way: its lock is released when that battle signs, this + * transaction then takes the lock, and the snapshot holds progress from before that + * battle. Fighting on it would skip that battle's cooldown, and signing it would write + * progression computed from the old values over that battle's result. Read here, the + * other battle's write is either visible (and differs) or its lock is still held. + */ + expectedProgress?: readonly ExpectedProgress[]; +} + +export interface ExpectedProgress { + petId: string; + level: number; + xp: number; + streak: number; + lastOpponentId: string; + readyAt: bigint; } export type OpenBattleResult = | { ok: true; battleId: string } | { ok: false; reason: 'pet-locked'; petId: string } + | { ok: false; reason: 'pet-progress-changed'; petId: string } | { ok: false; reason: 'intent-already-consumed' }; /** @@ -181,6 +202,9 @@ export async function openBattle(request: OpenBattleRequest): Promise 0) { await enqueueOutbox(tx, request.outbox); } @@ -196,6 +220,31 @@ export async function openBattle(request: OpenBattleRequest): Promise { + const rows = await tx.petBattleProgress.findMany({ + where: { chainId, deploymentId, petId: { in: expected.map((pet) => pet.petId) } }, + select: { petId: true, level: true, xp: true, streak: true, lastOpponentId: true, readyAt: true }, + }); + for (const pet of expected) { + const row = rows.find((candidate) => candidate.petId === pet.petId); + const unchanged = + row !== undefined && + row.level === pet.level && + row.xp === pet.xp && + row.streak === pet.streak && + row.lastOpponentId === pet.lastOpponentId && + row.readyAt === pet.readyAt; + if (!unchanged) { + throw new OpenBattleAbort({ ok: false, reason: 'pet-progress-changed', petId: pet.petId }); + } + } +} + /** Ascending numeric order, which is the lock-acquisition order. */ export function sortPetIds(petIds: readonly string[]): string[] { return [...petIds].sort((a, b) => { diff --git a/backend/tests/features/battle/ledger/accept.service.test.ts b/backend/tests/features/battle/ledger/accept.service.test.ts index b3c1200c..67d3a3f0 100644 --- a/backend/tests/features/battle/ledger/accept.service.test.ts +++ b/backend/tests/features/battle/ledger/accept.service.test.ts @@ -372,6 +372,23 @@ describe('opening the ledger', () => { expect(sign).not.toHaveBeenCalled(); }); + it('has the progress each snapshot froze rechecked once the pets are locked', async () => { + await acceptBattle({ intentHash: INTENT.intentHash, nowSeconds: NOW }); + expect(vi.mocked(openBattle).mock.calls[0]![0].expectedProgress).toEqual([ + { petId: '1', level: 10, xp: 120, streak: 0, lastOpponentId: '0', readyAt: BigInt(NOW - 100) }, + { petId: '2', level: 10, xp: 120, streak: 2, lastOpponentId: '1', readyAt: BigInt(NOW - 100) }, + ]); + }); + + it('refuses as pet-locked when a pet finished another battle while this one was being accepted', async () => { + vi.mocked(openBattle).mockResolvedValue({ ok: false, reason: 'pet-progress-changed', petId: '1' }); + expect(await acceptBattle({ intentHash: INTENT.intentHash, nowSeconds: NOW })).toMatchObject({ + ok: false, + reason: 'pet-locked', + }); + expect(sign).not.toHaveBeenCalled(); + }); + it('locks both pets, in numeric order, and consumes the originating intent atomically', async () => { await acceptBattle({ intentHash: INTENT.intentHash, nowSeconds: NOW }); const call = vi.mocked(openBattle).mock.calls[0]![0]; diff --git a/backend/tests/features/battle/ledger/transitions.test.ts b/backend/tests/features/battle/ledger/transitions.test.ts index 76164888..f049e03e 100644 --- a/backend/tests/features/battle/ledger/transitions.test.ts +++ b/backend/tests/features/battle/ledger/transitions.test.ts @@ -12,6 +12,7 @@ const tx = { battleOutbox: { createMany: vi.fn() }, petBattleLock: { create: vi.fn(), deleteMany: vi.fn() }, battleIntent: { updateMany: vi.fn() }, + petBattleProgress: { findMany: vi.fn() }, }; vi.mock('@config/prisma', () => ({ @@ -219,6 +220,57 @@ describe('openBattle', () => { openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), ).rejects.toThrow(/connection reset/); }); + + describe('with the progress the snapshots froze', () => { + const PROGRESS_9 = { petId: '9', level: 5, xp: 40, streak: 1, lastOpponentId: '10', readyAt: 1_000n }; + const PROGRESS_10 = { petId: '10', level: 7, xp: 90, streak: 0, lastOpponentId: '0', readyAt: 900n }; + const request = () => ({ + ledger: { chainId: 'eip155:84532' } as never, + petIds: ['9', '10'], + expectedProgress: [PROGRESS_9, PROGRESS_10], + }); + + beforeEach(() => { + tx.battleLedger.create.mockResolvedValue({ + battleId: 'btl_1', + chainId: 'eip155:84532', + deploymentId: 'base-sepolia-v2', + }); + }); + + it('opens the battle when neither pet changed', async () => { + tx.petBattleProgress.findMany.mockResolvedValue([PROGRESS_10, PROGRESS_9]); + expect(await openBattle(request())).toEqual({ ok: true, battleId: 'btl_1' }); + expect(tx.petBattleProgress.findMany).toHaveBeenCalledWith( + expect.objectContaining({ + where: { chainId: 'eip155:84532', deploymentId: 'base-sepolia-v2', petId: { in: ['9', '10'] } }, + }), + ); + }); + + it('rechecks after taking the locks, so a finished battle is visible', async () => { + tx.petBattleProgress.findMany.mockResolvedValue([PROGRESS_9, PROGRESS_10]); + await openBattle(request()); + const lastLock = Math.max(...tx.petBattleLock.create.mock.invocationCallOrder); + expect(tx.petBattleProgress.findMany.mock.invocationCallOrder[0]!).toBeGreaterThan(lastLock); + }); + + it('aborts when another battle moved a pet on after its snapshot was taken', async () => { + // The other battle signed and released its lock in between: same pet, a later + // cooldown and more XP than the snapshot holds. + tx.petBattleProgress.findMany.mockResolvedValue([ + PROGRESS_9, + { ...PROGRESS_10, xp: 130, readyAt: 1_600n }, + ]); + expect(await openBattle(request())).toEqual({ ok: false, reason: 'pet-progress-changed', petId: '10' }); + expect(tx.battleOutbox.createMany).not.toHaveBeenCalled(); + }); + + it('aborts when a pet has no progress row at all', async () => { + tx.petBattleProgress.findMany.mockResolvedValue([PROGRESS_10]); + expect(await openBattle(request())).toEqual({ ok: false, reason: 'pet-progress-changed', petId: '9' }); + }); + }); }); describe('sortPetIds', () => { From 2dabd6e14e3c49e2d23afee7b25b1ba966e0f5a2 Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Wed, 21 Oct 2026 21:20:42 -0400 Subject: [PATCH 02/10] fix(backend): guard the accept progress recheck with an update, not a read --- .../src/features/battle/ledger/transitions.ts | 47 ++++++++++------- .../battle/ledger/transitions.test.ts | 50 +++++++++++-------- 2 files changed, 59 insertions(+), 38 deletions(-) diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index 20269193..14b21821 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -126,8 +126,7 @@ export interface OpenBattleRequest { * can be photographed mid-way: its lock is released when that battle signs, this * transaction then takes the lock, and the snapshot holds progress from before that * battle. Fighting on it would skip that battle's cooldown, and signing it would write - * progression computed from the old values over that battle's result. Read here, the - * other battle's write is either visible (and differs) or its lock is still held. + * progression computed from the old values over that battle's result. */ expectedProgress?: readonly ExpectedProgress[]; } @@ -220,27 +219,41 @@ export async function openBattle(request: OpenBattleRequest): Promise { - const rows = await tx.petBattleProgress.findMany({ - where: { chainId, deploymentId, petId: { in: expected.map((pet) => pet.petId) } }, - select: { petId: true, level: true, xp: true, streak: true, lastOpponentId: true, readyAt: true }, - }); - for (const pet of expected) { - const row = rows.find((candidate) => candidate.petId === pet.petId); - const unchanged = - row !== undefined && - row.level === pet.level && - row.xp === pet.xp && - row.streak === pet.streak && - row.lastOpponentId === pet.lastOpponentId && - row.readyAt === pet.readyAt; - if (!unchanged) { - throw new OpenBattleAbort({ ok: false, reason: 'pet-progress-changed', petId: pet.petId }); + const byPetId = new Map(expected.map((pet) => [pet.petId, pet])); + for (const petId of sortPetIds([...byPetId.keys()])) { + const pet = byPetId.get(petId)!; + const { count } = await tx.petBattleProgress.updateMany({ + where: { + chainId, + deploymentId, + petId, + level: pet.level, + xp: pet.xp, + streak: pet.streak, + lastOpponentId: pet.lastOpponentId, + readyAt: pet.readyAt, + }, + // Writes back the value it matched on: the point is the row lock and the + // conflict check, not a change. + data: { level: pet.level }, + }); + if (count === 0) { + throw new OpenBattleAbort({ ok: false, reason: 'pet-progress-changed', petId }); } } } diff --git a/backend/tests/features/battle/ledger/transitions.test.ts b/backend/tests/features/battle/ledger/transitions.test.ts index f049e03e..c44b63a3 100644 --- a/backend/tests/features/battle/ledger/transitions.test.ts +++ b/backend/tests/features/battle/ledger/transitions.test.ts @@ -12,7 +12,7 @@ const tx = { battleOutbox: { createMany: vi.fn() }, petBattleLock: { create: vi.fn(), deleteMany: vi.fn() }, battleIntent: { updateMany: vi.fn() }, - petBattleProgress: { findMany: vi.fn() }, + petBattleProgress: { updateMany: vi.fn() }, }; vi.mock('@config/prisma', () => ({ @@ -238,38 +238,46 @@ describe('openBattle', () => { }); }); + beforeEach(() => { + tx.petBattleProgress.updateMany.mockResolvedValue({ count: 1 }); + }); + it('opens the battle when neither pet changed', async () => { - tx.petBattleProgress.findMany.mockResolvedValue([PROGRESS_10, PROGRESS_9]); expect(await openBattle(request())).toEqual({ ok: true, battleId: 'btl_1' }); - expect(tx.petBattleProgress.findMany).toHaveBeenCalledWith( - expect.objectContaining({ - where: { chainId: 'eip155:84532', deploymentId: 'base-sepolia-v2', petId: { in: ['9', '10'] } }, - }), - ); }); - it('rechecks after taking the locks, so a finished battle is visible', async () => { - tx.petBattleProgress.findMany.mockResolvedValue([PROGRESS_9, PROGRESS_10]); + it('guards each row on every frozen value, so any change matches nothing', async () => { await openBattle(request()); + expect(tx.petBattleProgress.updateMany).toHaveBeenCalledWith({ + where: { + chainId: 'eip155:84532', + deploymentId: 'base-sepolia-v2', + petId: '9', + level: 5, + xp: 40, + streak: 1, + lastOpponentId: '10', + readyAt: 1_000n, + }, + data: { level: 5 }, + }); + }); + + it('rechecks after taking the locks, in the same numeric order', async () => { + await openBattle({ ...request(), expectedProgress: [PROGRESS_10, PROGRESS_9] }); const lastLock = Math.max(...tx.petBattleLock.create.mock.invocationCallOrder); - expect(tx.petBattleProgress.findMany.mock.invocationCallOrder[0]!).toBeGreaterThan(lastLock); + expect(tx.petBattleProgress.updateMany.mock.invocationCallOrder[0]!).toBeGreaterThan(lastLock); + const order = tx.petBattleProgress.updateMany.mock.calls.map((call) => call[0].where.petId); + expect(order).toEqual(['9', '10']); }); it('aborts when another battle moved a pet on after its snapshot was taken', async () => { - // The other battle signed and released its lock in between: same pet, a later - // cooldown and more XP than the snapshot holds. - tx.petBattleProgress.findMany.mockResolvedValue([ - PROGRESS_9, - { ...PROGRESS_10, xp: 130, readyAt: 1_600n }, - ]); + // The other battle signed and released its lock in between, so pet 10's row no + // longer holds the values its snapshot froze. + tx.petBattleProgress.updateMany.mockResolvedValueOnce({ count: 1 }).mockResolvedValueOnce({ count: 0 }); expect(await openBattle(request())).toEqual({ ok: false, reason: 'pet-progress-changed', petId: '10' }); expect(tx.battleOutbox.createMany).not.toHaveBeenCalled(); }); - - it('aborts when a pet has no progress row at all', async () => { - tx.petBattleProgress.findMany.mockResolvedValue([PROGRESS_10]); - expect(await openBattle(request())).toEqual({ ok: false, reason: 'pet-progress-changed', petId: '9' }); - }); }); }); From fb31b7b739dc6aec379db5e08ad77032dfbd8a88 Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Wed, 21 Oct 2026 21:30:37 -0400 Subject: [PATCH 03/10] fix(backend): retry openBattle on a serialization failure --- .../src/features/battle/ledger/transitions.ts | 21 +++++++++++ .../battle/ledger/transitions.test.ts | 36 +++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index 14b21821..a1dea08a 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -160,6 +160,9 @@ class OpenBattleAbort extends Error { } } +/** One conflict is expected and resolved by the second attempt; the third is headroom. */ +const OPEN_BATTLE_ATTEMPTS = 3; + /** * Creates a ledger row, locks both pets, consumes the originating intent, and enqueues the * first message, all atomically. @@ -169,8 +172,26 @@ class OpenBattleAbort extends Error { * them fails cleanly on the primary key instead of the two deadlocking against each other * (threat T11). Numeric rather than lexicographic, because pet ids are decimal strings and * `"10" < "9"` as text. + * + * A serialization failure (`P2034`) is retried. Under Serializable, Postgres refuses this + * transaction when another one changed a row it touched after its snapshot was taken: a + * battle that signed while this one waited on its lock, or a second accept of the same + * intent. The retry runs on a fresh snapshot, sees that write, and ends in the matching + * refusal (`pet-progress-changed`, `pet-locked`, `intent-already-consumed`) instead of a 500. */ export async function openBattle(request: OpenBattleRequest): Promise { + for (let attempt = 1; ; attempt++) { + try { + return await openBattleOnce(request); + } catch (error) { + if ((error as { code?: string }).code !== 'P2034' || attempt >= OPEN_BATTLE_ATTEMPTS) { + throw error; + } + } + } +} + +async function openBattleOnce(request: OpenBattleRequest): Promise { const petIds = sortPetIds(request.petIds); try { diff --git a/backend/tests/features/battle/ledger/transitions.test.ts b/backend/tests/features/battle/ledger/transitions.test.ts index c44b63a3..f53522b4 100644 --- a/backend/tests/features/battle/ledger/transitions.test.ts +++ b/backend/tests/features/battle/ledger/transitions.test.ts @@ -221,6 +221,42 @@ describe('openBattle', () => { ).rejects.toThrow(/connection reset/); }); + describe('on a serialization failure', () => { + const conflict = () => Object.assign(new Error('write conflict'), { code: 'P2034' }); + + it('retries on a fresh transaction and returns that attempt\'s refusal', async () => { + // First attempt: Postgres refuses the commit. Second attempt sees the other + // transaction's write, here as an intent the other accept already consumed. + vi.mocked(prisma.$transaction).mockRejectedValueOnce(conflict()); + tx.battleIntent.updateMany.mockResolvedValue({ count: 0 }); + + const result = await openBattle({ + ledger: { chainId: 'eip155:84532' } as never, + petIds: ['9', '10'], + consumeIntentHash: '0xabc', + }); + + expect(result).toEqual({ ok: false, reason: 'intent-already-consumed' }); + expect(prisma.$transaction).toHaveBeenCalledTimes(2); + }); + + it('gives up after three attempts and rethrows', async () => { + vi.mocked(prisma.$transaction).mockRejectedValue(conflict()); + await expect( + openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), + ).rejects.toMatchObject({ code: 'P2034' }); + expect(prisma.$transaction).toHaveBeenCalledTimes(3); + }); + + it('does not retry any other error', async () => { + vi.mocked(prisma.$transaction).mockRejectedValueOnce(new Error('connection reset')); + await expect( + openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), + ).rejects.toThrow(/connection reset/); + expect(prisma.$transaction).toHaveBeenCalledTimes(1); + }); + }); + describe('with the progress the snapshots froze', () => { const PROGRESS_9 = { petId: '9', level: 5, xp: 40, streak: 1, lastOpponentId: '10', readyAt: 1_000n }; const PROGRESS_10 = { petId: '10', level: 7, xp: 90, streak: 0, lastOpponentId: '0', readyAt: 900n }; From 46aa64357a947bfda69b8a85ea618d4509f641f0 Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Thu, 22 Oct 2026 09:30:44 -0400 Subject: [PATCH 04/10] refactor(backend): bound the openBattle retry loop in its condition --- backend/src/features/battle/ledger/transitions.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index a1dea08a..461efc30 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -180,15 +180,18 @@ const OPEN_BATTLE_ATTEMPTS = 3; * refusal (`pet-progress-changed`, `pet-locked`, `intent-already-consumed`) instead of a 500. */ export async function openBattle(request: OpenBattleRequest): Promise { - for (let attempt = 1; ; attempt++) { + let lastConflict: unknown; + for (let attempt = 1; attempt <= OPEN_BATTLE_ATTEMPTS; attempt++) { try { return await openBattleOnce(request); } catch (error) { - if ((error as { code?: string }).code !== 'P2034' || attempt >= OPEN_BATTLE_ATTEMPTS) { + if ((error as { code?: string }).code !== 'P2034') { throw error; } + lastConflict = error; } } + throw lastConflict; } async function openBattleOnce(request: OpenBattleRequest): Promise { From 6f20a88912ab01633b57765d0d6ebed9c36397ff Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Thu, 22 Oct 2026 10:07:36 -0400 Subject: [PATCH 05/10] refactor(backend): address review on the openBattle retry and refusals --- .../features/battle/ledger/accept.service.ts | 8 +++---- .../src/features/battle/ledger/transitions.ts | 22 ++++++++++++++----- .../battle/ledger/accept.service.test.ts | 5 ++++- 3 files changed, 24 insertions(+), 11 deletions(-) diff --git a/backend/src/features/battle/ledger/accept.service.ts b/backend/src/features/battle/ledger/accept.service.ts index 6791466f..3066996e 100644 --- a/backend/src/features/battle/ledger/accept.service.ts +++ b/backend/src/features/battle/ledger/accept.service.ts @@ -29,7 +29,7 @@ import { servedDeploymentId } from './domain'; import { OUTBOX_TOPICS } from './outbox'; import { buildPetSnapshot } from './snapshot.builder'; import { servedRuleset, servedRulesetHash } from './ruleset.builder'; -import { applyTransition, type ExpectedProgress, openBattle } from './transitions'; +import { applyTransition, type ExpectedProgress, OPEN_BATTLE_REFUSALS, openBattle } from './transitions'; /** * The accept flow (§E, §J). @@ -592,13 +592,13 @@ async function openAcceptedBattle(args: { return proceed(null); } switch (opened.reason) { - case 'pet-locked': + case OPEN_BATTLE_REFUSALS.petLocked: return refuse('pet-locked', `pet ${opened.petId} already has an open battle`); - case 'pet-progress-changed': + case OPEN_BATTLE_REFUSALS.petProgressChanged: // Reported as pet-locked: to the caller it is the same event, a battle for this // pet that was still open when the snapshot was taken. A retry builds a fresh one. return refuse('pet-locked', `pet ${opened.petId} finished another battle during this accept; try again`); - case 'intent-already-consumed': + case OPEN_BATTLE_REFUSALS.intentAlreadyConsumed: return refuse('intent-already-consumed', 'this intent already produced a battle'); } } diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index 461efc30..3560fde6 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -140,11 +140,21 @@ export interface ExpectedProgress { readyAt: bigint; } +/** Why `openBattle` refused. Accept maps each one onto its own refusal reason. */ +export const OPEN_BATTLE_REFUSALS = { + /** A pet already has an open battle. */ + petLocked: 'pet-locked', + /** A pet's progress changed after its snapshot was taken. */ + petProgressChanged: 'pet-progress-changed', + /** The originating intent already produced a battle. */ + intentAlreadyConsumed: 'intent-already-consumed', +} as const; + export type OpenBattleResult = | { ok: true; battleId: string } - | { ok: false; reason: 'pet-locked'; petId: string } - | { ok: false; reason: 'pet-progress-changed'; petId: string } - | { ok: false; reason: 'intent-already-consumed' }; + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.petLocked; petId: string } + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.petProgressChanged; petId: string } + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.intentAlreadyConsumed }; /** * Signals a clean, expected abort of the `openBattle` transaction. @@ -206,7 +216,7 @@ async function openBattleOnce(request: OpenBattleRequest): Promise ({ }, })); -vi.mock('../../../../src/features/battle/ledger/transitions', () => ({ +vi.mock('../../../../src/features/battle/ledger/transitions', async (importOriginal) => ({ + // The real refusal names, so the mocked results below and accept's switch agree. + OPEN_BATTLE_REFUSALS: (await importOriginal()) + .OPEN_BATTLE_REFUSALS, openBattle: vi.fn(), applyTransition: vi.fn(), })); From 7d62db296b44378cc93524dd45ffd089a67ef319 Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Thu, 22 Oct 2026 17:53:12 -0400 Subject: [PATCH 06/10] refactor(backend): move battle ledger constants into constants.ts --- .../features/battle/ledger/accept.service.ts | 4 +- .../src/features/battle/ledger/constants.ts | 44 +++++++++++++++++++ backend/src/features/battle/ledger/index.ts | 3 +- backend/src/features/battle/ledger/outbox.ts | 30 +------------ .../src/features/battle/ledger/transitions.ts | 11 +---- .../battle/ledger/accept.service.test.ts | 5 +-- .../features/battle/ledger/outbox.test.ts | 2 +- 7 files changed, 52 insertions(+), 47 deletions(-) create mode 100644 backend/src/features/battle/ledger/constants.ts diff --git a/backend/src/features/battle/ledger/accept.service.ts b/backend/src/features/battle/ledger/accept.service.ts index 3066996e..8cfb26bb 100644 --- a/backend/src/features/battle/ledger/accept.service.ts +++ b/backend/src/features/battle/ledger/accept.service.ts @@ -26,10 +26,10 @@ import { chooseCommitmentRound, roundPublishTime } from '../randomness'; import { type ConsentFailure, consumeDailyBudget, findCoveringAuthorization } from './consent.service'; import { servedDeploymentId } from './domain'; -import { OUTBOX_TOPICS } from './outbox'; +import { OPEN_BATTLE_REFUSALS, OUTBOX_TOPICS } from './constants'; import { buildPetSnapshot } from './snapshot.builder'; import { servedRuleset, servedRulesetHash } from './ruleset.builder'; -import { applyTransition, type ExpectedProgress, OPEN_BATTLE_REFUSALS, openBattle } from './transitions'; +import { applyTransition, type ExpectedProgress, openBattle } from './transitions'; /** * The accept flow (§E, §J). diff --git a/backend/src/features/battle/ledger/constants.ts b/backend/src/features/battle/ledger/constants.ts new file mode 100644 index 00000000..c6804836 --- /dev/null +++ b/backend/src/features/battle/ledger/constants.ts @@ -0,0 +1,44 @@ +/** + * Constants shared across the battle ledger: outbox topics and limits, and the reasons + * `openBattle` refuses. + */ + +/** What the message tells a worker to do next. */ +export const OUTBOX_TOPICS = { + /** Wait for the committed drand round, then verify it and derive the seed. */ + awaitBeacon: 'await-beacon', + /** Run the fight through the canonical engine. */ + compute: 'compute', + /** Ask the independent Go verifier to recompute the result. */ + verify: 'verify', + /** Sign the receipt with the KMS key. */ + sign: 'sign', + /** Publish the receipt to the public corpus. */ + publish: 'publish', +} as const; + +/** + * Publishing is the last per-battle step. Batching and anchoring (§I) deliberately have no + * topic here: they aggregate across every publishable receipt on their own timer + * (`startBatchAnchor`), so there is no per-battle message to send. A `batch` topic was + * declared here for a while and never enqueued or handled, which was worse than absent — + * `claimOutbox` only claims topics `HANDLERS` lists, so anyone who took the declaration at + * face value would have enqueued a message no worker could ever claim, stranding the battle + * in a non-terminal state with both pets locked and nothing to dead-letter it. + */ + +/** Retries before an outbox message is dead-lettered. */ +export const MAX_OUTBOX_ATTEMPTS = 8; + +/** Age after which a claimed outbox message's lock is taken over. See `claimOutbox`. */ +export const STALE_LOCK_MS = 5 * 60 * 1000; + +/** Why `openBattle` refused. Accept maps each one onto its own refusal reason. */ +export const OPEN_BATTLE_REFUSALS = { + /** A pet already has an open battle. */ + petLocked: 'pet-locked', + /** A pet's progress changed after its snapshot was taken. */ + petProgressChanged: 'pet-progress-changed', + /** The originating intent already produced a battle. */ + intentAlreadyConsumed: 'intent-already-consumed', +} as const; diff --git a/backend/src/features/battle/ledger/index.ts b/backend/src/features/battle/ledger/index.ts index 0d061b66..8be2b704 100644 --- a/backend/src/features/battle/ledger/index.ts +++ b/backend/src/features/battle/ledger/index.ts @@ -67,6 +67,7 @@ export { toProtocolAuthorization, verifyAuthorizationSignature, } from './consent.service'; +export { MAX_OUTBOX_ATTEMPTS, OPEN_BATTLE_REFUSALS, OUTBOX_TOPICS, STALE_LOCK_MS } from './constants'; export { assertServedDomain, servedChainIds, servedDeploymentId, servedDomain } from './domain'; export { deleteSessionDelegations, postSessionDelegation } from './session.controller'; export { @@ -101,8 +102,6 @@ export { listDeadLetters, nextOutboxDueAt, requeueDeadLetter, - MAX_OUTBOX_ATTEMPTS, - OUTBOX_TOPICS, type OutboxMessage, type OutboxTopic, rescheduleOutbox, diff --git a/backend/src/features/battle/ledger/outbox.ts b/backend/src/features/battle/ledger/outbox.ts index 33d1d881..5735caf9 100644 --- a/backend/src/features/battle/ledger/outbox.ts +++ b/backend/src/features/battle/ledger/outbox.ts @@ -2,6 +2,8 @@ import type { Prisma } from '@generated/prisma/client'; import { prisma } from '@config/prisma'; +import { MAX_OUTBOX_ATTEMPTS, OUTBOX_TOPICS, STALE_LOCK_MS } from './constants'; + /** * Transactional outbox for the battle workflow (§J). * @@ -14,34 +16,8 @@ import { prisma } from '@config/prisma'; * which is what `classifyTransition`'s `noop` case is for. */ -/** What the message tells a worker to do next. */ -export const OUTBOX_TOPICS = { - /** Wait for the committed drand round, then verify it and derive the seed. */ - awaitBeacon: 'await-beacon', - /** Run the fight through the canonical engine. */ - compute: 'compute', - /** Ask the independent Go verifier to recompute the result. */ - verify: 'verify', - /** Sign the receipt with the KMS key. */ - sign: 'sign', - /** Publish the receipt to the public corpus. */ - publish: 'publish', -} as const; - -/** - * Publishing is the last per-battle step. Batching and anchoring (§I) deliberately have no - * topic here: they aggregate across every publishable receipt on their own timer - * (`startBatchAnchor`), so there is no per-battle message to send. A `batch` topic was - * declared here for a while and never enqueued or handled, which was worse than absent — - * `claimOutbox` only claims topics `HANDLERS` lists, so anyone who took the declaration at - * face value would have enqueued a message no worker could ever claim, stranding the battle - * in a non-terminal state with both pets locked and nothing to dead-letter it. - */ - export type OutboxTopic = (typeof OUTBOX_TOPICS)[keyof typeof OUTBOX_TOPICS]; -/** Retries before a message is dead-lettered. */ -export const MAX_OUTBOX_ATTEMPTS = 8; /** First retry delay; doubles each attempt up to the cap. */ const BASE_RETRY_SECONDS = 2; const MAX_RETRY_SECONDS = 300; @@ -101,8 +77,6 @@ export async function enqueueOutbox(client: OutboxClient, messages: readonly Out * A takeover counts as an attempt, so a message that keeps killing its worker still ends * in the dead-letter path. */ -export const STALE_LOCK_MS = 5 * 60 * 1000; - export async function claimOutbox( topics: readonly OutboxTopic[], workerId: string, diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index 3560fde6..a4bcc806 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -3,6 +3,7 @@ import type { Prisma } from '@generated/prisma/client'; import { prisma } from '@config/prisma'; +import { OPEN_BATTLE_REFUSALS } from './constants'; import { enqueueOutbox, type OutboxMessage } from './outbox'; import { canForfeitFrom, @@ -140,16 +141,6 @@ export interface ExpectedProgress { readyAt: bigint; } -/** Why `openBattle` refused. Accept maps each one onto its own refusal reason. */ -export const OPEN_BATTLE_REFUSALS = { - /** A pet already has an open battle. */ - petLocked: 'pet-locked', - /** A pet's progress changed after its snapshot was taken. */ - petProgressChanged: 'pet-progress-changed', - /** The originating intent already produced a battle. */ - intentAlreadyConsumed: 'intent-already-consumed', -} as const; - export type OpenBattleResult = | { ok: true; battleId: string } | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.petLocked; petId: string } diff --git a/backend/tests/features/battle/ledger/accept.service.test.ts b/backend/tests/features/battle/ledger/accept.service.test.ts index b195e7bc..67d3a3f0 100644 --- a/backend/tests/features/battle/ledger/accept.service.test.ts +++ b/backend/tests/features/battle/ledger/accept.service.test.ts @@ -55,10 +55,7 @@ vi.mock('../../../../src/features/battle/signer', () => ({ }, })); -vi.mock('../../../../src/features/battle/ledger/transitions', async (importOriginal) => ({ - // The real refusal names, so the mocked results below and accept's switch agree. - OPEN_BATTLE_REFUSALS: (await importOriginal()) - .OPEN_BATTLE_REFUSALS, +vi.mock('../../../../src/features/battle/ledger/transitions', () => ({ openBattle: vi.fn(), applyTransition: vi.fn(), })); diff --git a/backend/tests/features/battle/ledger/outbox.test.ts b/backend/tests/features/battle/ledger/outbox.test.ts index 3069d8e9..5424e473 100644 --- a/backend/tests/features/battle/ledger/outbox.test.ts +++ b/backend/tests/features/battle/ledger/outbox.test.ts @@ -25,7 +25,7 @@ import { OUTBOX_TOPICS, retryDelaySeconds, } from '@features/battle/ledger'; -import { STALE_LOCK_MS } from '@features/battle/ledger/outbox'; +import { STALE_LOCK_MS } from '@features/battle/ledger/constants'; const NOW = new Date('2026-07-26T09:00:00.000Z'); From 87485c0055e0f6fc10370e7324f63a23fcc69883 Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Thu, 22 Oct 2026 18:10:57 -0400 Subject: [PATCH 07/10] refactor(backend): open battles at read committed without a retry loop --- .../src/features/battle/ledger/transitions.ts | 43 ++++++------------- .../battle/ledger/transitions.test.ts | 42 +++--------------- 2 files changed, 19 insertions(+), 66 deletions(-) diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index a4bcc806..34280404 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -161,9 +161,6 @@ class OpenBattleAbort extends Error { } } -/** One conflict is expected and resolved by the second attempt; the third is headroom. */ -const OPEN_BATTLE_ATTEMPTS = 3; - /** * Creates a ledger row, locks both pets, consumes the originating intent, and enqueues the * first message, all atomically. @@ -174,28 +171,13 @@ const OPEN_BATTLE_ATTEMPTS = 3; * (threat T11). Numeric rather than lexicographic, because pet ids are decimal strings and * `"10" < "9"` as text. * - * A serialization failure (`P2034`) is retried. Under Serializable, Postgres refuses this - * transaction when another one changed a row it touched after its snapshot was taken: a - * battle that signed while this one waited on its lock, or a second accept of the same - * intent. The retry runs on a fresh snapshot, sees that write, and ends in the matching - * refusal (`pet-progress-changed`, `pet-locked`, `intent-already-consumed`) instead of a 500. + * Read Committed, not Serializable. Every check here is a write that Postgres resolves + * against the latest committed row: the intent and progress guards are guarded updates, which + * re-evaluate their `where` once a concurrent writer commits, and the pet locks are inserts + * against a primary key. So a concurrent accept or a battle that signed meanwhile ends in its + * matching refusal rather than a serialization failure that would need a retry. */ export async function openBattle(request: OpenBattleRequest): Promise { - let lastConflict: unknown; - for (let attempt = 1; attempt <= OPEN_BATTLE_ATTEMPTS; attempt++) { - try { - return await openBattleOnce(request); - } catch (error) { - if ((error as { code?: string }).code !== 'P2034') { - throw error; - } - lastConflict = error; - } - } - throw lastConflict; -} - -async function openBattleOnce(request: OpenBattleRequest): Promise { const petIds = sortPetIds(request.petIds); try { @@ -234,7 +216,7 @@ async function openBattleOnce(request: OpenBattleRequest): Promise { expect(tx.battleLedger.create).toHaveBeenCalledTimes(1); expect(tx.petBattleLock.create).toHaveBeenCalledTimes(2); expect(tx.battleOutbox.createMany).toHaveBeenCalledTimes(1); - expect(vi.mocked(prisma.$transaction).mock.calls[0]![1]).toEqual({ isolationLevel: 'Serializable' }); + expect(vi.mocked(prisma.$transaction).mock.calls[0]![1]).toEqual({ isolationLevel: 'ReadCommitted' }); }); it('takes locks in ascending numeric pet-id order', async () => { @@ -221,40 +221,12 @@ describe('openBattle', () => { ).rejects.toThrow(/connection reset/); }); - describe('on a serialization failure', () => { - const conflict = () => Object.assign(new Error('write conflict'), { code: 'P2034' }); - - it('retries on a fresh transaction and returns that attempt\'s refusal', async () => { - // First attempt: Postgres refuses the commit. Second attempt sees the other - // transaction's write, here as an intent the other accept already consumed. - vi.mocked(prisma.$transaction).mockRejectedValueOnce(conflict()); - tx.battleIntent.updateMany.mockResolvedValue({ count: 0 }); - - const result = await openBattle({ - ledger: { chainId: 'eip155:84532' } as never, - petIds: ['9', '10'], - consumeIntentHash: '0xabc', - }); - - expect(result).toEqual({ ok: false, reason: 'intent-already-consumed' }); - expect(prisma.$transaction).toHaveBeenCalledTimes(2); - }); - - it('gives up after three attempts and rethrows', async () => { - vi.mocked(prisma.$transaction).mockRejectedValue(conflict()); - await expect( - openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), - ).rejects.toMatchObject({ code: 'P2034' }); - expect(prisma.$transaction).toHaveBeenCalledTimes(3); - }); - - it('does not retry any other error', async () => { - vi.mocked(prisma.$transaction).mockRejectedValueOnce(new Error('connection reset')); - await expect( - openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), - ).rejects.toThrow(/connection reset/); - expect(prisma.$transaction).toHaveBeenCalledTimes(1); - }); + it('runs once and rethrows a failed transaction rather than retrying it', async () => { + vi.mocked(prisma.$transaction).mockRejectedValueOnce(new Error('connection reset')); + await expect( + openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), + ).rejects.toThrow(/connection reset/); + expect(prisma.$transaction).toHaveBeenCalledTimes(1); }); describe('with the progress the snapshots froze', () => { From 3ad5cec7df3c6d5b2665e6289c4bb83a452b689e Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Thu, 22 Oct 2026 20:15:16 -0400 Subject: [PATCH 08/10] fix(backend): correct the daily budget comment in battle accept --- .../src/features/battle/ledger/accept.service.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/backend/src/features/battle/ledger/accept.service.ts b/backend/src/features/battle/ledger/accept.service.ts index 8cfb26bb..061c0174 100644 --- a/backend/src/features/battle/ledger/accept.service.ts +++ b/backend/src/features/battle/ledger/accept.service.ts @@ -152,12 +152,13 @@ export async function acceptBattle(request: AcceptBattleRequest): Promise Date: Thu, 22 Oct 2026 20:17:04 -0400 Subject: [PATCH 09/10] fix(backend): make the progress-changed refusal message accurate --- .../src/features/battle/ledger/accept.service.ts | 7 ++++--- .../features/battle/ledger/accept.service.test.ts | 3 ++- .../features/battle/ledger/transitions.test.ts | 15 +++------------ 3 files changed, 9 insertions(+), 16 deletions(-) diff --git a/backend/src/features/battle/ledger/accept.service.ts b/backend/src/features/battle/ledger/accept.service.ts index 061c0174..2cf54430 100644 --- a/backend/src/features/battle/ledger/accept.service.ts +++ b/backend/src/features/battle/ledger/accept.service.ts @@ -596,9 +596,10 @@ async function openAcceptedBattle(args: { case OPEN_BATTLE_REFUSALS.petLocked: return refuse('pet-locked', `pet ${opened.petId} already has an open battle`); case OPEN_BATTLE_REFUSALS.petProgressChanged: - // Reported as pet-locked: to the caller it is the same event, a battle for this - // pet that was still open when the snapshot was taken. A retry builds a fresh one. - return refuse('pet-locked', `pet ${opened.petId} finished another battle during this accept; try again`); + // Reported as pet-locked, so the API keeps one code for "this pet is busy". The detail + // stays neutral: a signing battle is the usual cause, but an item can change progress + // too, and a battle that signed has also started a cooldown, so retrying at once fails. + return refuse('pet-locked', `pet ${opened.petId}'s progress changed during this accept`); case OPEN_BATTLE_REFUSALS.intentAlreadyConsumed: return refuse('intent-already-consumed', 'this intent already produced a battle'); } diff --git a/backend/tests/features/battle/ledger/accept.service.test.ts b/backend/tests/features/battle/ledger/accept.service.test.ts index 67d3a3f0..2c5d4e26 100644 --- a/backend/tests/features/battle/ledger/accept.service.test.ts +++ b/backend/tests/features/battle/ledger/accept.service.test.ts @@ -380,11 +380,12 @@ describe('opening the ledger', () => { ]); }); - it('refuses as pet-locked when a pet finished another battle while this one was being accepted', async () => { + it('refuses as pet-locked when a pet\'s progress changed while this one was being accepted', async () => { vi.mocked(openBattle).mockResolvedValue({ ok: false, reason: 'pet-progress-changed', petId: '1' }); expect(await acceptBattle({ intentHash: INTENT.intentHash, nowSeconds: NOW })).toMatchObject({ ok: false, reason: 'pet-locked', + detail: "pet 1's progress changed during this accept", }); expect(sign).not.toHaveBeenCalled(); }); diff --git a/backend/tests/features/battle/ledger/transitions.test.ts b/backend/tests/features/battle/ledger/transitions.test.ts index a58142b5..53b3a37f 100644 --- a/backend/tests/features/battle/ledger/transitions.test.ts +++ b/backend/tests/features/battle/ledger/transitions.test.ts @@ -38,8 +38,8 @@ import { beforeEach(() => { vi.clearAllMocks(); - // Run the callback inline with the fake client, and record the isolation level so the - // serializable requirement is testable. + // Run the callback inline with the fake client, and record the isolation level so each + // transaction's level is testable. vi.mocked(prisma.$transaction).mockImplementation(((callback: (client: typeof tx) => unknown) => Promise.resolve(callback(tx))) as never); tx.battleLedger.updateMany.mockResolvedValue({ count: 1 }); @@ -219,13 +219,7 @@ describe('openBattle', () => { await expect( openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), ).rejects.toThrow(/connection reset/); - }); - - it('runs once and rethrows a failed transaction rather than retrying it', async () => { - vi.mocked(prisma.$transaction).mockRejectedValueOnce(new Error('connection reset')); - await expect( - openBattle({ ledger: { chainId: 'eip155:84532' } as never, petIds: ['9', '10'] }), - ).rejects.toThrow(/connection reset/); + // Once: a failed transaction is rethrown, not retried. expect(prisma.$transaction).toHaveBeenCalledTimes(1); }); @@ -244,9 +238,6 @@ describe('openBattle', () => { chainId: 'eip155:84532', deploymentId: 'base-sepolia-v2', }); - }); - - beforeEach(() => { tx.petBattleProgress.updateMany.mockResolvedValue({ count: 1 }); }); From c9d9d0c36f46cde8f5cdb6ecb47f2b72cfd07c06 Mon Sep 17 00:00:00 2001 From: suryaswain612 Date: Thu, 22 Oct 2026 20:28:12 -0400 Subject: [PATCH 10/10] refactor(backend): use constants for battle accept refusal reasons --- .../battle/ledger/accept.controller.ts | 33 +++++---- .../features/battle/ledger/accept.service.ts | 70 ++++++------------- .../features/battle/ledger/consent.service.ts | 9 +-- .../src/features/battle/ledger/constants.ts | 55 +++++++++++++-- backend/src/features/battle/ledger/index.ts | 9 ++- .../src/features/battle/ledger/transitions.ts | 12 ++-- 6 files changed, 108 insertions(+), 80 deletions(-) diff --git a/backend/src/features/battle/ledger/accept.controller.ts b/backend/src/features/battle/ledger/accept.controller.ts index 081ad048..5d5e8755 100644 --- a/backend/src/features/battle/ledger/accept.controller.ts +++ b/backend/src/features/battle/ledger/accept.controller.ts @@ -3,6 +3,7 @@ import type { Response } from 'express'; import type { AuthenticatedRequest } from '@middleware/auth'; import { acceptBattle, type AcceptRejection } from './accept.service'; +import { BATTLE_REFUSALS, CONSENT_REFUSALS } from './constants'; /** * 409 for "someone already acted on this", 404/403/422 for the client's own fault, and 503 for @@ -15,27 +16,29 @@ import { acceptBattle, type AcceptRejection } from './accept.service'; * and a client that backs off and retries is behaving correctly either way. */ export const STATUS_BY_REASON: Record = { - 'intent-not-found': 404, - 'intent-already-consumed': 409, - 'intent-expired': 422, - 'attacker-pet-missing': 404, - 'defender-pet-missing': 404, - 'attacker-not-ready': 409, - 'defender-not-ready': 409, + [BATTLE_REFUSALS.INTENT_NOT_FOUND]: 404, + [BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED]: 409, + [BATTLE_REFUSALS.INTENT_EXPIRED]: 422, + [BATTLE_REFUSALS.ATTACKER_PET_MISSING]: 404, + [BATTLE_REFUSALS.DEFENDER_PET_MISSING]: 404, + [BATTLE_REFUSALS.ATTACKER_NOT_READY]: 409, + [BATTLE_REFUSALS.DEFENDER_NOT_READY]: 409, + // Coverage failures. `@cryptopets/protocol` owns these as its `CoverageFailure` type, and + // it exports no constants for them, so they are spelled here as the protocol spells them. 'not-yet-valid': 409, expired: 409, 'pet-not-covered': 403, 'attacker-level-below-band': 403, 'attacker-level-above-band': 403, 'ruleset-mismatch': 403, - 'no-authorization': 403, - revoked: 403, - 'daily-cap-reached': 429, - 'pet-locked': 409, - 'drand-unavailable': 503, - 'signer-unavailable': 503, - 'item-catalog-stale': 503, - 'equipment-catalog-mismatch': 503, + [CONSENT_REFUSALS.NO_AUTHORIZATION]: 403, + [CONSENT_REFUSALS.REVOKED]: 403, + [CONSENT_REFUSALS.DAILY_CAP_REACHED]: 429, + [BATTLE_REFUSALS.PET_LOCKED]: 409, + [BATTLE_REFUSALS.DRAND_UNAVAILABLE]: 503, + [BATTLE_REFUSALS.SIGNER_UNAVAILABLE]: 503, + [BATTLE_REFUSALS.ITEM_CATALOG_STALE]: 503, + [BATTLE_REFUSALS.EQUIPMENT_CATALOG_MISMATCH]: 503, }; interface AcceptBody { diff --git a/backend/src/features/battle/ledger/accept.service.ts b/backend/src/features/battle/ledger/accept.service.ts index 2cf54430..cdf4a40c 100644 --- a/backend/src/features/battle/ledger/accept.service.ts +++ b/backend/src/features/battle/ledger/accept.service.ts @@ -26,7 +26,7 @@ import { chooseCommitmentRound, roundPublishTime } from '../randomness'; import { type ConsentFailure, consumeDailyBudget, findCoveringAuthorization } from './consent.service'; import { servedDeploymentId } from './domain'; -import { OPEN_BATTLE_REFUSALS, OUTBOX_TOPICS } from './constants'; +import { BATTLE_REFUSALS, CONSENT_REFUSALS, OPEN_BATTLE_REFUSALS, OUTBOX_TOPICS } from './constants'; import { buildPetSnapshot } from './snapshot.builder'; import { servedRuleset, servedRulesetHash } from './ruleset.builder'; import { applyTransition, type ExpectedProgress, openBattle } from './transitions'; @@ -68,37 +68,7 @@ export interface AcceptBattleRequest { roomId?: string; } -export type AcceptRejection = - | 'intent-not-found' - | 'intent-already-consumed' - | 'intent-expired' - | 'attacker-pet-missing' - | 'defender-pet-missing' - | 'attacker-not-ready' - | 'defender-not-ready' - | ConsentFailure - | 'pet-locked' - | 'drand-unavailable' - | 'signer-unavailable' - /** - * The item catalog cannot price something this battle needs priced: a pet wears an - * item with no catalog row, or an equipment row's modifier will not parse (roadmap §4). - * - * Its own reason rather than a 500, because it is an operational fault with an obvious - * remedy (run the seeder) and no fault of the player's. Refusing is the conservative - * end: the alternative is a fight under rules this deployment cannot state, recorded in - * a signed receipt that contradicts chain state. - */ - | 'item-catalog-stale' - /** - * The frozen gear disagrees with what the ruleset this battle names prices it at - * (roadmap §4, threat T13). Reachable when the catalog changes between resolving the - * snapshot and building the ruleset, and otherwise a bug. - * - * Refused rather than fought, because the verifier makes the same comparison on the - * finished receipt: accepting would produce a battle guaranteed to fail verification. - */ - | 'equipment-catalog-mismatch'; +export type AcceptRejection = (typeof BATTLE_REFUSALS)[keyof typeof BATTLE_REFUSALS] | ConsentFailure; export interface AcceptedBattle { battleId: string; @@ -149,7 +119,7 @@ export async function acceptBattle(request: AcceptBattleRequest): Promise> { const intent = await prisma.battleIntent.findUnique({ where: { intentHash: request.intentHash } }); if (!intent) { - return refuse('intent-not-found', `no intent ${request.intentHash}`); + return refuse(BATTLE_REFUSALS.INTENT_NOT_FOUND, `no intent ${request.intentHash}`); } if (intent.consumedAt) { - return refuse('intent-already-consumed', 'this intent already produced a battle'); + return refuse(BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED, 'this intent already produced a battle'); } if (BigInt(request.nowSeconds) >= intent.expiresAt) { - return refuse('intent-expired', `intent expired at ${intent.expiresAt}`); + return refuse(BATTLE_REFUSALS.INTENT_EXPIRED, `intent expired at ${intent.expiresAt}`); } return proceed(intent); } @@ -484,18 +454,18 @@ async function freezeFighters( } if (!attacker) { - return refuse('attacker-pet-missing', `pet ${intent.attackerPetId} is not in the roster`); + return refuse(BATTLE_REFUSALS.ATTACKER_PET_MISSING, `pet ${intent.attackerPetId} is not in the roster`); } if (!defender) { - return refuse('defender-pet-missing', `pet ${intent.defenderPetId} is not in the roster`); + return refuse(BATTLE_REFUSALS.DEFENDER_PET_MISSING, `pet ${intent.defenderPetId} is not in the roster`); } // Both pets must be off cooldown, mirroring GameLogic.sol's requirement that neither side // of an on-chain battle is mid-recovery. if (!isBattleReady(attacker, nowSeconds)) { - return refuse('attacker-not-ready', `attacker ready at ${attacker.readyAt}`); + return refuse(BATTLE_REFUSALS.ATTACKER_NOT_READY, `attacker ready at ${attacker.readyAt}`); } if (!isBattleReady(defender, nowSeconds)) { - return refuse('defender-not-ready', `defender ready at ${defender.readyAt}`); + return refuse(BATTLE_REFUSALS.DEFENDER_NOT_READY, `defender ready at ${defender.readyAt}`); } return proceed({ attacker, defender }); } @@ -535,7 +505,7 @@ async function priceUnderServedRuleset( ruleset, ); if (mismatches.length > 0) { - return refuse('equipment-catalog-mismatch', mismatches.join('; ')); + return refuse(BATTLE_REFUSALS.EQUIPMENT_CATALOG_MISMATCH, mismatches.join('; ')); } const rulesetHash = await servedRulesetHash(); @@ -593,15 +563,15 @@ async function openAcceptedBattle(args: { return proceed(null); } switch (opened.reason) { - case OPEN_BATTLE_REFUSALS.petLocked: - return refuse('pet-locked', `pet ${opened.petId} already has an open battle`); - case OPEN_BATTLE_REFUSALS.petProgressChanged: + case OPEN_BATTLE_REFUSALS.PET_LOCKED: + return refuse(BATTLE_REFUSALS.PET_LOCKED, `pet ${opened.petId} already has an open battle`); + case OPEN_BATTLE_REFUSALS.PET_PROGRESS_CHANGED: // Reported as pet-locked, so the API keeps one code for "this pet is busy". The detail // stays neutral: a signing battle is the usual cause, but an item can change progress // too, and a battle that signed has also started a cooldown, so retrying at once fails. - return refuse('pet-locked', `pet ${opened.petId}'s progress changed during this accept`); - case OPEN_BATTLE_REFUSALS.intentAlreadyConsumed: - return refuse('intent-already-consumed', 'this intent already produced a battle'); + return refuse(BATTLE_REFUSALS.PET_LOCKED, `pet ${opened.petId}'s progress changed during this accept`); + case OPEN_BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED: + return refuse(BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED, 'this intent already produced a battle'); } } diff --git a/backend/src/features/battle/ledger/consent.service.ts b/backend/src/features/battle/ledger/consent.service.ts index 2c3dc83e..a0e0b4b1 100644 --- a/backend/src/features/battle/ledger/consent.service.ts +++ b/backend/src/features/battle/ledger/consent.service.ts @@ -15,6 +15,7 @@ import { ethers } from 'ethers'; import { prisma } from '@config/prisma'; import { verifySolanaSignature } from '@features/auth/solana'; +import { CONSENT_REFUSALS } from './constants'; import { assertServedDomain, servedDeploymentId } from './domain'; import type { SignatureFormat } from './intent.service'; @@ -264,7 +265,7 @@ export interface CoverageRequest { nowSeconds: number; } -export type ConsentFailure = CoverageFailure | 'no-authorization' | 'daily-cap-reached' | 'revoked'; +export type ConsentFailure = CoverageFailure | (typeof CONSENT_REFUSALS)[keyof typeof CONSENT_REFUSALS]; export type ConsentResult = | { ok: true; authorizationHash: string; maxBattlesPerDay: number } @@ -294,7 +295,7 @@ export async function findCoveringAuthorization(request: CoverageRequest): Promi }); if (candidates.length === 0) { - return { ok: false, reason: 'no-authorization', detail: 'this defender has no live authorization' }; + return { ok: false, reason: CONSENT_REFUSALS.NO_AUTHORIZATION, detail: 'this defender has no live authorization' }; } let lastFailure: CoverageFailure = 'pet-not-covered'; @@ -339,7 +340,7 @@ export async function consumeDailyBudget( authorizationHash: string, maxBattlesPerDay: number, nowSeconds: number, -): Promise<{ ok: true; used: number } | { ok: false; reason: 'daily-cap-reached' }> { +): Promise<{ ok: true; used: number } | { ok: false; reason: typeof CONSENT_REFUSALS.DAILY_CAP_REACHED }> { const dayBucket = epochDay(nowSeconds); const bump = async () => @@ -362,7 +363,7 @@ export async function consumeDailyBudget( } } if (result.count === 0) { - return { ok: false, reason: 'daily-cap-reached' }; + return { ok: false, reason: CONSENT_REFUSALS.DAILY_CAP_REACHED }; } const row = await prisma.defenseUsage.findUnique({ where: { authorizationHash_dayBucket: { authorizationHash, dayBucket } }, diff --git a/backend/src/features/battle/ledger/constants.ts b/backend/src/features/battle/ledger/constants.ts index c6804836..b0a04d95 100644 --- a/backend/src/features/battle/ledger/constants.ts +++ b/backend/src/features/battle/ledger/constants.ts @@ -1,6 +1,6 @@ /** * Constants shared across the battle ledger: outbox topics and limits, and the reasons - * `openBattle` refuses. + * `openBattle`, accept and consent refuse. */ /** What the message tells a worker to do next. */ @@ -36,9 +36,56 @@ export const STALE_LOCK_MS = 5 * 60 * 1000; /** Why `openBattle` refused. Accept maps each one onto its own refusal reason. */ export const OPEN_BATTLE_REFUSALS = { /** A pet already has an open battle. */ - petLocked: 'pet-locked', + PET_LOCKED: 'pet-locked', /** A pet's progress changed after its snapshot was taken. */ - petProgressChanged: 'pet-progress-changed', + PET_PROGRESS_CHANGED: 'pet-progress-changed', /** The originating intent already produced a battle. */ - intentAlreadyConsumed: 'intent-already-consumed', + INTENT_ALREADY_CONSUMED: 'intent-already-consumed', +} as const; + +/** + * Why accept refused a battle, as the API reports it. `accept.controller.ts` maps each one to + * an HTTP status, and clients map each one to player-facing text, so a value is part of the + * API and must not change. + * + * Consent refusals are not listed here: the backend's own are in `CONSENT_REFUSALS`, and the + * coverage ones are `CoverageFailure` in `@cryptopets/protocol`, which owns them. + */ +export const BATTLE_REFUSALS = { + INTENT_NOT_FOUND: 'intent-not-found', + INTENT_ALREADY_CONSUMED: 'intent-already-consumed', + INTENT_EXPIRED: 'intent-expired', + ATTACKER_PET_MISSING: 'attacker-pet-missing', + DEFENDER_PET_MISSING: 'defender-pet-missing', + ATTACKER_NOT_READY: 'attacker-not-ready', + DEFENDER_NOT_READY: 'defender-not-ready', + PET_LOCKED: 'pet-locked', + DRAND_UNAVAILABLE: 'drand-unavailable', + SIGNER_UNAVAILABLE: 'signer-unavailable', + /** + * The item catalog cannot price something this battle needs priced: a pet wears an + * item with no catalog row, or an equipment row's modifier will not parse (roadmap §4). + * + * Its own reason rather than a 500, because it is an operational fault with an obvious + * remedy (run the seeder) and no fault of the player's. Refusing is the conservative + * end: the alternative is a fight under rules this deployment cannot state, recorded in + * a signed receipt that contradicts chain state. + */ + ITEM_CATALOG_STALE: 'item-catalog-stale', + /** + * The frozen gear disagrees with what the ruleset this battle names prices it at + * (roadmap §4, threat T13). Reachable when the catalog changes between resolving the + * snapshot and building the ruleset, and otherwise a bug. + * + * Refused rather than fought, because the verifier makes the same comparison on the + * finished receipt: accepting would produce a battle guaranteed to fail verification. + */ + EQUIPMENT_CATALOG_MISMATCH: 'equipment-catalog-mismatch', +} as const; + +/** Consent refusals the backend decides itself, rather than the protocol's coverage rule. */ +export const CONSENT_REFUSALS = { + NO_AUTHORIZATION: 'no-authorization', + DAILY_CAP_REACHED: 'daily-cap-reached', + REVOKED: 'revoked', } as const; diff --git a/backend/src/features/battle/ledger/index.ts b/backend/src/features/battle/ledger/index.ts index 8be2b704..d4635c2c 100644 --- a/backend/src/features/battle/ledger/index.ts +++ b/backend/src/features/battle/ledger/index.ts @@ -67,7 +67,14 @@ export { toProtocolAuthorization, verifyAuthorizationSignature, } from './consent.service'; -export { MAX_OUTBOX_ATTEMPTS, OPEN_BATTLE_REFUSALS, OUTBOX_TOPICS, STALE_LOCK_MS } from './constants'; +export { + BATTLE_REFUSALS, + CONSENT_REFUSALS, + MAX_OUTBOX_ATTEMPTS, + OPEN_BATTLE_REFUSALS, + OUTBOX_TOPICS, + STALE_LOCK_MS, +} from './constants'; export { assertServedDomain, servedChainIds, servedDeploymentId, servedDomain } from './domain'; export { deleteSessionDelegations, postSessionDelegation } from './session.controller'; export { diff --git a/backend/src/features/battle/ledger/transitions.ts b/backend/src/features/battle/ledger/transitions.ts index 34280404..161e02d1 100644 --- a/backend/src/features/battle/ledger/transitions.ts +++ b/backend/src/features/battle/ledger/transitions.ts @@ -143,9 +143,9 @@ export interface ExpectedProgress { export type OpenBattleResult = | { ok: true; battleId: string } - | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.petLocked; petId: string } - | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.petProgressChanged; petId: string } - | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.intentAlreadyConsumed }; + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.PET_LOCKED; petId: string } + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.PET_PROGRESS_CHANGED; petId: string } + | { ok: false; reason: typeof OPEN_BATTLE_REFUSALS.INTENT_ALREADY_CONSUMED }; /** * Signals a clean, expected abort of the `openBattle` transaction. @@ -189,7 +189,7 @@ export async function openBattle(request: OpenBattleRequest): Promise