From fc60ed3ac7ca69803bf62bd29ec5538b80d59a49 Mon Sep 17 00:00:00 2001 From: Ian Philips Date: Tue, 5 Nov 2024 06:19:28 -0800 Subject: [PATCH] Optimize cancel-bet --- backend/api/src/cancel-bet.ts | 48 ++++++++++++++++------------------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/backend/api/src/cancel-bet.ts b/backend/api/src/cancel-bet.ts index fc3501f474..13f803e5db 100644 --- a/backend/api/src/cancel-bet.ts +++ b/backend/api/src/cancel-bet.ts @@ -1,37 +1,33 @@ import { APIError, type APIHandler } from './helpers/endpoint' -import { convertBet } from 'common/supabase/bets' -import { cancelLimitOrders } from 'shared/supabase/bets' import { createSupabaseDirectClient } from 'shared/supabase/init' import { type LimitBet } from 'common/bet' -import { updateContract } from 'shared/supabase/contracts' +import { broadcastOrders } from 'shared/websockets/helpers' +import { convertBet } from 'common/supabase/bets' +import { cancelLimitOrdersQuery } from 'shared/supabase/bets' +import { runTransactionWithRetries } from 'shared/transact-with-retries' export const cancelBet: APIHandler<'bet/cancel/:betId'> = async ( { betId }, auth ) => { const pg = createSupabaseDirectClient() - return await pg.tx(async (tx) => { - const bet = await tx.oneOrNone( - `select * from contract_bets where bet_id = $1`, - [betId], - (row) => (row ? convertBet(row) : null) - ) - - if (!bet) throw new APIError(404, 'Bet not found') - if (bet.userId !== auth.uid) - throw new APIError(403, 'You can only cancel your own bets') - if (bet.limitProb === undefined) - throw new APIError(403, 'Not a limit order. Cannot cancel.') - if (bet.isCancelled) throw new APIError(403, 'Bet already cancelled') - - await cancelLimitOrders(tx, [bet as LimitBet]) - const now = Date.now() - - await updateContract(tx, bet.contractId, { - lastBetTime: now, - lastUpdatedTime: now, - }) - - return { ...(bet as LimitBet), isCancelled: true } + const bet = await pg.oneOrNone( + `select * from contract_bets where bet_id = $1`, + [betId], + convertBet + ) + if (!bet) throw new APIError(404, 'Bet not found') + if (bet.userId !== auth.uid) + throw new APIError(403, 'You can only cancel your own bets') + if (bet.limitProb === undefined) + throw new APIError(403, 'Not a limit order. Cannot cancel.') + if (bet.isCancelled) throw new APIError(403, 'Bet already cancelled') + const bets = await runTransactionWithRetries(async (tx) => { + const { query, bets } = cancelLimitOrdersQuery([bet as LimitBet]) + await tx.none(query) + return bets }) + broadcastOrders(bets) + + return bets[0] }