manifold/functions/src/resolve-market.ts

123 lines
3.5 KiB
TypeScript
Raw Normal View History

2021-12-14 07:02:50 +00:00
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as _ from 'lodash'
import { Contract } from '../../common/contract'
import { User } from '../../common/user'
import { Bet } from '../../common/bet'
2022-01-10 22:48:48 +00:00
import { getUser, payUser } from './utils'
import { sendMarketResolutionEmail } from './emails'
2022-01-10 22:48:48 +00:00
import {
getCancelPayouts,
getMktPayouts,
getStandardPayouts,
} from '../../common/payouts'
2021-12-14 07:02:50 +00:00
export const resolveMarket = functions
.runWith({ minInstances: 1 })
2021-12-17 22:15:09 +00:00
.https.onCall(
async (
data: {
outcome: 'YES' | 'NO' | 'CANCEL' | 'MKT'
2021-12-17 22:15:09 +00:00
contractId: string
},
context
) => {
const userId = context?.auth?.uid
if (!userId) return { status: 'error', message: 'Not authorized' }
const { outcome, contractId } = data
if (!['YES', 'NO', 'MKT', 'CANCEL'].includes(outcome))
2021-12-17 22:15:09 +00:00
return { status: 'error', message: 'Invalid outcome' }
const contractDoc = firestore.doc(`contracts/${contractId}`)
const contractSnap = await contractDoc.get()
if (!contractSnap.exists)
return { status: 'error', message: 'Invalid contract' }
const contract = contractSnap.data() as Contract
if (contract.creatorId !== userId)
return { status: 'error', message: 'User not creator of contract' }
if (contract.resolution)
return { status: 'error', message: 'Contract already resolved' }
const creator = await getUser(contract.creatorId)
if (!creator) return { status: 'error', message: 'Creator not found' }
2021-12-17 22:15:09 +00:00
await contractDoc.update({
isResolved: true,
resolution: outcome,
resolutionTime: Date.now(),
})
console.log('contract ', contractId, 'resolved to:', outcome)
const betsSnap = await firestore
.collection(`contracts/${contractId}/bets`)
.get()
2021-12-17 22:15:09 +00:00
const bets = betsSnap.docs.map((doc) => doc.data() as Bet)
const openBets = bets.filter((b) => !b.isSold && !b.sale)
const truePool = contract.pool.YES + contract.pool.NO
2021-12-17 22:15:09 +00:00
const payouts =
outcome === 'CANCEL'
? getCancelPayouts(truePool, openBets)
: outcome === 'MKT'
? getMktPayouts(truePool, contract, openBets)
: getStandardPayouts(outcome, truePool, contract, openBets)
2021-12-17 22:15:09 +00:00
console.log('payouts:', payouts)
const groups = _.groupBy(payouts, (payout) => payout.userId)
const userPayouts = _.mapValues(groups, (group) =>
_.sumBy(group, (g) => g.payout)
)
2022-01-10 22:48:48 +00:00
const payoutPromises = Object.entries(userPayouts).map(
([userId, payout]) => payUser(userId, payout)
)
2021-12-17 22:15:09 +00:00
const result = await Promise.all(payoutPromises)
2021-12-17 22:15:09 +00:00
.catch((e) => ({ status: 'error', message: e }))
.then(() => ({ status: 'success' }))
await sendResolutionEmails(
openBets,
userPayouts,
creator,
contract,
outcome
)
return result
2021-12-17 22:15:09 +00:00
}
)
2021-12-14 07:02:50 +00:00
const sendResolutionEmails = async (
openBets: Bet[],
userPayouts: { [userId: string]: number },
creator: User,
contract: Contract,
outcome: 'YES' | 'NO' | 'CANCEL' | 'MKT'
) => {
const nonWinners = _.difference(
_.uniq(openBets.map(({ userId }) => userId)),
Object.keys(userPayouts)
)
const emailPayouts = [
...Object.entries(userPayouts),
...nonWinners.map((userId) => [userId, 0] as const),
]
await Promise.all(
emailPayouts.map(([userId, payout]) =>
sendMarketResolutionEmail(userId, payout, creator, contract, outcome)
)
)
}
2021-12-14 07:02:50 +00:00
const firestore = admin.firestore()