manifold/functions/src/resolve-market.ts

139 lines
3.9 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-22 23:59:50 +00:00
import { getPayouts } 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
probabilityInt?: number
2021-12-17 22:15:09 +00:00
},
context
) => {
const userId = context?.auth?.uid
if (!userId) return { status: 'error', message: 'Not authorized' }
const { outcome, contractId, probabilityInt } = data
2021-12-17 22:15:09 +00:00
if (!['YES', 'NO', 'MKT', 'CANCEL'].includes(outcome))
2021-12-17 22:15:09 +00:00
return { status: 'error', message: 'Invalid outcome' }
if (
probabilityInt !== undefined &&
(probabilityInt < 1 || probabilityInt > 99 || !isFinite(probabilityInt))
)
return { status: 'error', message: 'Invalid probability' }
2021-12-17 22:15:09 +00:00
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' }
const resolutionProbability =
probabilityInt !== undefined ? probabilityInt / 100 : undefined
2021-12-17 22:15:09 +00:00
await contractDoc.update({
isResolved: true,
resolution: outcome,
resolutionTime: Date.now(),
...(resolutionProbability === undefined
? {}
: { resolutionProbability }),
2021-12-17 22:15:09 +00:00
})
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 payouts = getPayouts(
outcome,
contract,
openBets,
resolutionProbability
)
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,
resolutionProbability
)
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',
resolutionProbability?: number
) => {
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,
resolutionProbability
)
)
)
}
2021-12-14 07:02:50 +00:00
const firestore = admin.firestore()