diff --git a/functions/src/resolve-market.ts b/functions/src/resolve-market.ts index 44293898..b99b5c87 100644 --- a/functions/src/resolve-market.ts +++ b/functions/src/resolve-market.ts @@ -9,7 +9,7 @@ import { RESOLUTIONS, } from '../../common/contract' import { Bet } from '../../common/bet' -import { getUser, isProd, payUser } from './utils' +import { getUser, getValues, isProd, log, payUser } from './utils' import { getLoanPayouts, getPayouts, @@ -22,6 +22,12 @@ import { LiquidityProvision } from '../../common/liquidity-provision' import { APIError, newEndpoint, validate } from './api' import { getContractBetMetrics } from '../../common/calculate' import { createCommentOrAnswerOrUpdatedContractNotification } from './create-notification' +import { CancelUniqueBettorBonusTxn, Txn } from '../../common/txn' +import { runTxn, TxnData } from './transact' +import { + DEV_HOUSE_LIQUIDITY_PROVIDER_ID, + HOUSE_LIQUIDITY_PROVIDER_ID, +} from '../../common/antes' const bodySchema = z.object({ contractId: z.string(), @@ -163,6 +169,7 @@ export const resolvemarket = newEndpoint(opts, async (req, auth) => { await processPayouts(liquidityPayouts, true) await processPayouts([...payouts, ...loanPayouts]) + await undoUniqueBettorRewardsIfCancelResolution(contract, outcome) const userPayoutsWithoutLoans = groupPayoutsByUser(payouts) @@ -299,4 +306,55 @@ function validateAnswer( } } +async function undoUniqueBettorRewardsIfCancelResolution( + contract: Contract, + outcome: string +) { + if (outcome === 'CANCEL') { + const creatorsBonusTxns = await getValues<Txn>( + firestore + .collection('txns') + .where('category', '==', 'UNIQUE_BETTOR_BONUS') + .where('toId', '==', contract.creatorId) + ) + + const bonusTxnsOnThisContract = creatorsBonusTxns.filter( + (txn) => txn.data && txn.data.contractId === contract.id + ) + log('total bonusTxnsOnThisContract', bonusTxnsOnThisContract.length) + const totalBonusAmount = sumBy(bonusTxnsOnThisContract, (txn) => txn.amount) + log('totalBonusAmount to be withdrawn', totalBonusAmount) + const result = await firestore.runTransaction(async (trans) => { + const bonusTxn: TxnData = { + fromId: contract.creatorId, + fromType: 'USER', + toId: isProd() + ? HOUSE_LIQUIDITY_PROVIDER_ID + : DEV_HOUSE_LIQUIDITY_PROVIDER_ID, + toType: 'BANK', + amount: totalBonusAmount, + token: 'M$', + category: 'CANCEL_UNIQUE_BETTOR_BONUS', + data: { + contractId: contract.id, + }, + } as Omit<CancelUniqueBettorBonusTxn, 'id' | 'createdTime'> + return await runTxn(trans, bonusTxn) + }) + + if (result.status != 'success' || !result.txn) { + log( + `Couldn't cancel bonus for user: ${contract.creatorId} - status:`, + result.status + ) + log('message:', result.message) + } else { + log( + `Cancel Bonus txn for user: ${contract.creatorId} completed:`, + result.txn?.id + ) + } + } +} + const firestore = admin.firestore()