Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions apps/web/app/api/bounties/[id]/claim/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,15 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
}

// Mark bounty as claimed — atomic WHERE prevents race conditions
await db.sql`
const claimed = await db.sql`
UPDATE bounties
SET status = 'claimed', coupon_id = ${coupon_id}, claimer_did = ${did},
updated_at = ${new Date().toISOString()}
WHERE id = ${bountyId} AND status = 'funded'
RETURNING id
`;

// Verify the claim succeeded (handles concurrent claim race)
const verify = await db.sql`SELECT claimer_did FROM bounties WHERE id = ${bountyId}`;
if (verify.length && verify[0].claimer_did !== did) {
if (!claimed.length) {
return NextResponse.json({ error: 'Bounty was already claimed by another user' }, { status: 409 });
}

Expand Down
21 changes: 21 additions & 0 deletions test/bounty-claim-race.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';

const source = readFileSync(
new URL('../apps/web/app/api/bounties/[id]/claim/route.ts', import.meta.url),
'utf8'
);

test('a funded bounty is reserved atomically before payout', () => {
assert.match(
source,
/UPDATE bounties[\s\S]*WHERE id = \$\{bountyId\} AND status = 'funded'[\s\S]*RETURNING id/
);
assert.match(source, /if \(!claimed\.length\)/);
assert.doesNotMatch(source, /SELECT claimer_did FROM bounties/);

const reservation = source.indexOf('const claimed = await db.sql');
const payout = source.indexOf('prepare-tx');
assert.ok(reservation >= 0 && reservation < payout, 'reservation must happen before payout');
});
Loading