Skip to content

Commit

Permalink
Optimize cancel-bet
Browse files Browse the repository at this point in the history
  • Loading branch information
IanPhilips committed Nov 5, 2024
1 parent bdcc9dd commit fc60ed3
Showing 1 changed file with 22 additions and 26 deletions.
48 changes: 22 additions & 26 deletions backend/api/src/cancel-bet.ts
Original file line number Diff line number Diff line change
@@ -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]
}

0 comments on commit fc60ed3

Please sign in to comment.