Skip to content

Commit

Permalink
Rename runTxn to runTxnInBetQueue
Browse files Browse the repository at this point in the history
  • Loading branch information
IanPhilips committed Nov 5, 2024
1 parent 1a19ab7 commit 024c55f
Show file tree
Hide file tree
Showing 16 changed files with 70 additions and 59 deletions.
4 changes: 2 additions & 2 deletions backend/api/src/add-liquidity.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getNewLiquidityProvision } from 'common/add-liquidity'
import { APIError, type APIHandler } from './helpers/endpoint'
import { SUBSIDY_FEE } from 'common/economy'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { getContract, getUser } from 'shared/utils'
import { onCreateLiquidityProvision } from './on-update-liquidity-provision'
Expand Down Expand Up @@ -44,7 +44,7 @@ export const addContractLiquidity = async (

if (user.balance < amount) throw new APIError(403, 'Insufficient balance')

await runTxn(tx, {
await runTxnInBetQueue(tx, {
fromId: userId,
amount: amount,
toId: contractId,
Expand Down
4 changes: 2 additions & 2 deletions backend/api/src/boost-market.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { APIError, authEndpoint, validate } from './helpers/endpoint'
import { MarketAdCreateTxn } from 'common/txn'
import { log, getContractSupabase } from 'shared/utils'
import { MIN_AD_COST_PER_VIEW } from 'common/boost'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { generateContractEmbeddings } from 'shared/supabase/contracts'

const schema = z
Expand Down Expand Up @@ -57,7 +57,7 @@ export const boostmarket = authEndpoint(async (req, auth) => {
// use supabase to add txn from user to the ad. deducts from user
log('starting transaction to deduct funds.')

await runTxn(tx, {
await runTxnInBetQueue(tx, {
category: 'MARKET_BOOST_CREATE',
fromType: 'USER',
fromId: auth.uid,
Expand Down
4 changes: 2 additions & 2 deletions backend/api/src/claim-manalink.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { z } from 'zod'
import { canSendMana } from 'common/can-send-mana'
import { APIError, authEndpoint, validate } from './helpers/endpoint'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { Row, tsToMillis } from 'common/supabase/utils'
import { getUserPortfolioInternal } from 'shared/get-user-portfolio-internal'
Expand Down Expand Up @@ -88,7 +88,7 @@ export const claimmanalink = authEndpoint(async (req, auth) => {
description: `Manalink ${slug} claimed: ${amount} from ${toUser.username} to ${auth.uid}`,
} as const

const txn = await runTxn(tx, data)
const txn = await runTxnInBetQueue(tx, data)
await tx.none(
`insert into manalink_claims (txn_id, manalink_id) values ($1, $2)`,
[txn.id, slug]
Expand Down
6 changes: 3 additions & 3 deletions backend/api/src/convert-cash-to-mana.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { APIError, APIHandler } from './helpers/endpoint'
import { type TxnData, runTxn } from 'shared/txn/run-txn'
import { type TxnData, runTxnInBetQueue } from 'shared/txn/run-txn'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { CASH_TO_MANA_CONVERSION_RATE } from 'common/envs/constants'
import { calculateRedeemablePrizeCash } from 'shared/calculate-redeemable-prize-cash'
Expand Down Expand Up @@ -31,7 +31,7 @@ export const convertCashToMana: APIHandler<'convert-cash-to-mana'> = async (
description: 'Convert cash to mana',
data: { insertTime },
}
await runTxn(tx, toBank)
await runTxnInBetQueue(tx, toBank)

const toYou: TxnData = {
category: 'CONVERT_CASH_DONE',
Expand All @@ -44,6 +44,6 @@ export const convertCashToMana: APIHandler<'convert-cash-to-mana'> = async (
description: 'Convert cash to mana',
data: { insertTime },
}
await runTxn(tx, toYou)
await runTxnInBetQueue(tx, toYou)
})
}
4 changes: 2 additions & 2 deletions backend/api/src/create-comment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { onCreateCommentOnContract } from './on-create-comment-on-contract'
import { millisToTs } from 'common/supabase/utils'
import { convertBet } from 'common/supabase/bets'
import { Bet } from 'common/bet'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { broadcastNewComment } from 'shared/websockets/helpers'
import { buildArray } from 'common/util/array'
import { type Contract } from 'common/contract'
Expand Down Expand Up @@ -124,7 +124,7 @@ export const createCommentOnContractInternal = async (
continue: async () => {
if (isApi) {
await pg.tx((tx) =>
runTxn(tx, {
runTxnInBetQueue(tx, {
category: 'BOT_COMMENT_FEE',
token: 'M$',
fromId: creator.id,
Expand Down
20 changes: 13 additions & 7 deletions backend/api/src/create-market.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import {
} from 'shared/supabase/init'
import { insertLiquidity } from 'shared/supabase/liquidity'
import { anythingToRichText } from 'shared/tiptap'
import { runTxn, runTxnFromBank } from 'shared/txn/run-txn'
import { runTxnInBetQueue, runTxnFromBank } from 'shared/txn/run-txn'
import {
addGroupToContract,
canUserAddGroupToMarket,
Expand Down Expand Up @@ -134,9 +134,15 @@ export async function createMarketHelper(body: Body, auth: AuthedUser) {
: unmodifiedAnte
const ante = Math.min(unmodifiedAnte, totalMarketCost)

const duplicateSubmissionUrl = await getDuplicateSubmissionUrl(idempotencyKey, pg)
const duplicateSubmissionUrl = await getDuplicateSubmissionUrl(
idempotencyKey,
pg
)
if (duplicateSubmissionUrl) {
throw new APIError(400, 'Contract has already been created at ' + duplicateSubmissionUrl)
throw new APIError(
400,
'Contract has already been created at ' + duplicateSubmissionUrl
)
}

return await pg.tx(async (tx) => {
Expand Down Expand Up @@ -244,7 +250,7 @@ const runCreateMarketTxn = async (args: {
} = args

if (amountSuppliedByUser > 0) {
await runTxn(transaction, {
await runTxnInBetQueue(transaction, {
fromId: userId,
fromType: 'USER',
toId: contractId,
Expand All @@ -271,12 +277,12 @@ async function getDuplicateSubmissionUrl(
idempotencyKey: string | undefined,
pg: SupabaseDirectClient
): Promise<string | undefined> {
if (!idempotencyKey) return undefined;
if (!idempotencyKey) return undefined
const contracts = await getContractsDirect([idempotencyKey], pg)
if (contracts.length > 0) {
return contractUrl(contracts[0])
}
return undefined;
return undefined
}

async function getCloseTimestamp(
Expand Down Expand Up @@ -583,7 +589,7 @@ export async function generateAntes(
(contract.mechanism === 'cpmm-1' || contract.mechanism === 'cpmm-multi-1')
) {
return await pg.txIf(async (tx) => {
await runTxn(tx, {
await runTxnInBetQueue(tx, {
fromId: providerId,
amount: drizzledAmount,
toId: contract.id,
Expand Down
4 changes: 2 additions & 2 deletions backend/api/src/donate.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { type APIHandler } from './helpers/endpoint'
import { charities } from 'common/charity'
import { APIError } from 'api/helpers/endpoint'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { MIN_CASH_DONATION } from 'common/envs/constants'
import { calculateRedeemablePrizeCash } from 'shared/calculate-redeemable-prize-cash'
Expand Down Expand Up @@ -64,6 +64,6 @@ export const donate: APIHandler<'donate'> = async ({ amount, to }, auth) => {
token: 'CASH',
} as const

await runTxn(tx, donationTxn)
await runTxnInBetQueue(tx, donationTxn)
})
}
4 changes: 2 additions & 2 deletions backend/api/src/gidx/complete-cashout-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { APIError, APIHandler } from 'api/helpers/endpoint'
import { PaymentMethod } from 'common/gidx/gidx'
import { log } from 'shared/monitoring/log'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { getIp, track } from 'shared/analytics'
import { TWOMBA_ENABLED } from 'common/envs/constants'
import { getUser } from 'shared/utils'
Expand Down Expand Up @@ -113,7 +113,7 @@ const debitCoins = async (
{ response: props }
)
}
const txn = await runTxn(tx, manaCashoutTxn)
const txn = await runTxnInBetQueue(tx, manaCashoutTxn)
await tx.none(
`
insert into redemption_status (user_id, status, session_id, transaction_id, txn_id) values ($1, $2, $3, $4, $5)
Expand Down
6 changes: 3 additions & 3 deletions backend/api/src/gidx/complete-checkout-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
import { log } from 'shared/monitoring/log'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { getReferrerInfo, updateUser } from 'shared/supabase/users'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { getUser, LOCAL_DEV } from 'shared/utils'
import { distributeReferralBonusIfNoneGiven } from 'shared/distribute-referral-bonus'

Expand Down Expand Up @@ -256,9 +256,9 @@ const sendCoins = async (
} as const

await pg.tx(async (tx) => {
await runTxn(tx, manaPurchaseTxn)
await runTxnInBetQueue(tx, manaPurchaseTxn)
if (isSweepsVerified) {
await runTxn(tx, cashBonusTxn)
await runTxnInBetQueue(tx, cashBonusTxn)
}
await updateUser(tx, userId, {
purchasedMana: true,
Expand Down
4 changes: 2 additions & 2 deletions backend/api/src/manachan-tweet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { postTweet } from 'shared/twitter'
import { MANACHAN_TWEET_COST } from 'common/economy'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { getUser } from 'shared/utils'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { insert } from 'shared/supabase/utils'

const bodySchema = z
Expand All @@ -22,7 +22,7 @@ export const manachantweet = authEndpoint(async (req, auth) => {
if (!user) throw new APIError(401, 'Your account was not found')

const result = await pg.tx(async (tx) => {
await runTxn(tx, {
await runTxnInBetQueue(tx, {
category: 'MANACHAN_TWEET',
token: 'M$',
fromType: 'USER',
Expand Down
4 changes: 2 additions & 2 deletions backend/api/src/remove-liquidity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { formatMoneyWithDecimals } from 'common/util/format'
import { runTransactionWithRetries } from 'shared/transact-with-retries'
import { updateContract } from 'shared/supabase/contracts'
import { FieldVal } from 'shared/supabase/utils'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { getContract, log } from 'shared/utils'
import { APIError, type APIHandler } from './helpers/endpoint'
import { getNewLiquidityProvision } from 'common/add-liquidity'
Expand Down Expand Up @@ -73,7 +73,7 @@ export const removeLiquidity: APIHandler<
),
})

await runTxn(pgTrans, {
await runTxnInBetQueue(pgTrans, {
fromType: 'CONTRACT',
fromId: contract.id,
toType: 'USER',
Expand Down
4 changes: 2 additions & 2 deletions backend/api/src/stripe-endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getPrivateUser, getUser, isProd, log } from 'shared/utils'
import { sendThankYouEmail } from 'shared/emails'
import { trackPublicEvent } from 'shared/analytics'
import { APIError } from 'common/api/utils'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { updateUser } from 'shared/supabase/users'
import { WEB_PRICES } from 'common/economy'
Expand Down Expand Up @@ -163,7 +163,7 @@ const issueMoneys = async (session: StripeSession) => {
let success = false
try {
await pg.tx(async (tx) => {
await runTxn(tx, manaPurchaseTxn)
await runTxnInBetQueue(tx, manaPurchaseTxn)
await updateUser(tx, userId, {
purchasedMana: true,
})
Expand Down
41 changes: 21 additions & 20 deletions backend/api/src/validate-iap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as admin from 'firebase-admin'
import { IapTransaction, PurchaseData } from 'common/iap'
import { ManaPurchaseTxn } from 'common/txn'
import { sendThankYouEmail } from 'shared/emails'
import { runTxn } from 'shared/txn/run-txn'
import { runTxnInBetQueue } from 'shared/txn/run-txn'
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { IOS_PRICES } from 'common/economy'
import { TWOMBA_ENABLED } from 'common/envs/constants'
Expand Down Expand Up @@ -119,31 +119,32 @@ export const validateiap = authEndpoint(async (req, auth) => {

const isBonusEligible = TWOMBA_ENABLED && user.sweepstakesVerified

const bonusPurchaseTxn = isBonusEligible && bonusInDollars
? ({
fromId: 'EXTERNAL',
fromType: 'BANK',
toId: userId,
toType: 'USER',
amount: bonusInDollars,
token: 'CASH',
category: 'CASH_BONUS',
data: {
iapTransactionId: iapTransRef.id,
type: IAP_TYPES_PROCESSED,
paidInCents: priceInDollars * 100 * quantity,
},
description: `Deposit ${bonusInDollars} mana cash from BANK for mana purchase bonus`,
} as const)
: null
const bonusPurchaseTxn =
isBonusEligible && bonusInDollars
? ({
fromId: 'EXTERNAL',
fromType: 'BANK',
toId: userId,
toType: 'USER',
amount: bonusInDollars,
token: 'CASH',
category: 'CASH_BONUS',
data: {
iapTransactionId: iapTransRef.id,
type: IAP_TYPES_PROCESSED,
paidInCents: priceInDollars * 100 * quantity,
},
description: `Deposit ${bonusInDollars} mana cash from BANK for mana purchase bonus`,
} as const)
: null

const pg = createSupabaseDirectClient()
// TODO: retry transactions on failure!
await pg
.tx(async (tx) => {
await runTxn(tx, manaPurchaseTxn)
await runTxnInBetQueue(tx, manaPurchaseTxn)
if (bonusPurchaseTxn) {
await runTxn(tx, bonusPurchaseTxn)
await runTxnInBetQueue(tx, bonusPurchaseTxn)
}
})
.catch((e) => {
Expand Down
4 changes: 2 additions & 2 deletions backend/shared/src/resolve-market-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import { User } from 'common/user'
import { removeUndefinedProps } from 'common/util/object'
import { createContractResolvedNotifications } from './create-notification'
import { updateContractMetricsForUsers } from './helpers/user-contract-metrics'
import { TxnData, runTxn, txnToRow } from './txn/run-txn'
import { TxnData, runTxnInBetQueue, txnToRow } from './txn/run-txn'
import {
revalidateStaticProps,
isProd,
Expand Down Expand Up @@ -372,7 +372,7 @@ async function undoUniqueBettorRewardsIfCancelResolution(
} as Omit<CancelUniqueBettorBonusTxn, 'id' | 'createdTime'>

try {
const txn = await pg.tx((tx) => runTxn(tx, bonusTxn))
const txn = await pg.tx((tx) => runTxnInBetQueue(tx, bonusTxn))
log(`Cancel Bonus txn for user: ${contract.creatorId} completed: ${txn.id}`)
} catch (e) {
log.error(
Expand Down
8 changes: 4 additions & 4 deletions backend/shared/src/txn/run-bounty-txn.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BountyAddedTxn, BountyAwardedTxn, BountyCanceledTxn } from 'common/txn'
import { APIError } from 'common//api/utils'
import { runTxn } from './run-txn'
import { runTxnInBetQueue } from './run-txn'
import {
SupabaseTransaction,
createSupabaseDirectClient,
Expand All @@ -26,7 +26,7 @@ export async function runAddBountyTxn(
}

const txn = await pg.tx(async (tx) => {
const txn = await runTxn(tx, txnData)
const txn = await runTxnInBetQueue(tx, txnData)

// update bountied contract
await updateContract(tx, toId, {
Expand All @@ -53,7 +53,7 @@ export async function runAwardBountyTxn(
)
}

const txn = await runTxn(tx, txnData)
const txn = await runTxnInBetQueue(tx, txnData)
const { bountyLeft } = contract
if (bountyLeft < amount) {
throw new APIError(
Expand Down Expand Up @@ -94,7 +94,7 @@ export async function runCancelBountyTxn(
totalDeposits: txnData.amount,
})

const txn = await runTxn(tx, txnData)
const txn = await runTxnInBetQueue(tx, txnData)

const amount = contract.bountyLeft
if (amount != txnData.amount) {
Expand Down
Loading

0 comments on commit 024c55f

Please sign in to comment.