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 './types/contract'
|
|
|
|
import { User } from './types/user'
|
|
|
|
import { Bet } from './types/bet'
|
2022-01-02 00:08:52 +00:00
|
|
|
import { getUser } from './utils'
|
|
|
|
import { sendMarketResolutionEmail } from './emails'
|
2021-12-14 07:02:50 +00:00
|
|
|
|
|
|
|
export const PLATFORM_FEE = 0.01 // 1%
|
|
|
|
export const CREATOR_FEE = 0.01 // 1%
|
|
|
|
|
|
|
|
export const resolveMarket = functions
|
|
|
|
.runWith({ minInstances: 1 })
|
2021-12-17 22:15:09 +00:00
|
|
|
.https.onCall(
|
|
|
|
async (
|
|
|
|
data: {
|
2022-01-02 01:13:30 +00:00
|
|
|
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', 'CANCEL'].includes(outcome))
|
|
|
|
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' }
|
|
|
|
|
2022-01-02 00:08:52 +00:00
|
|
|
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()
|
2022-01-02 01:03:18 +00:00
|
|
|
|
2021-12-17 22:15:09 +00:00
|
|
|
const bets = betsSnap.docs.map((doc) => doc.data() as Bet)
|
2022-01-02 01:03:18 +00:00
|
|
|
const openBets = bets.filter((b) => !b.isSold && !b.sale)
|
|
|
|
|
|
|
|
const startPool = contract.startPool.YES + contract.startPool.NO
|
|
|
|
const truePool = contract.pool.YES + contract.pool.NO - startPool
|
2021-12-17 22:15:09 +00:00
|
|
|
|
|
|
|
const payouts =
|
|
|
|
outcome === 'CANCEL'
|
2022-01-02 01:03:18 +00:00
|
|
|
? 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)
|
|
|
|
)
|
|
|
|
|
|
|
|
const payoutPromises = Object.entries(userPayouts).map(payUser)
|
|
|
|
|
2022-01-02 00:08:52 +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' }))
|
2022-01-02 00:08:52 +00:00
|
|
|
|
2022-01-02 01:13:30 +00:00
|
|
|
await sendResolutionEmails(
|
|
|
|
openBets,
|
|
|
|
userPayouts,
|
|
|
|
creator,
|
|
|
|
contract,
|
|
|
|
outcome
|
2022-01-02 00:08:52 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
return result
|
2021-12-17 22:15:09 +00:00
|
|
|
}
|
|
|
|
)
|
2021-12-14 07:02:50 +00:00
|
|
|
|
2022-01-02 01:13:30 +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()
|
|
|
|
|
2022-01-02 01:03:18 +00:00
|
|
|
const getCancelPayouts = (truePool: number, bets: Bet[]) => {
|
|
|
|
console.log('resolved N/A, pool M$', truePool)
|
2021-12-29 05:49:10 +00:00
|
|
|
|
2022-01-02 01:03:18 +00:00
|
|
|
const betSum = _.sumBy(bets, (b) => b.amount)
|
2021-12-29 05:49:10 +00:00
|
|
|
|
2022-01-02 01:03:18 +00:00
|
|
|
return bets.map((bet) => ({
|
2021-12-29 05:49:10 +00:00
|
|
|
userId: bet.userId,
|
|
|
|
payout: (bet.amount / betSum) * truePool,
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
|
2022-01-02 01:03:18 +00:00
|
|
|
const getStandardPayouts = (
|
|
|
|
outcome: string,
|
|
|
|
truePool: number,
|
|
|
|
contract: Contract,
|
|
|
|
bets: Bet[]
|
|
|
|
) => {
|
|
|
|
const [yesBets, noBets] = _.partition(bets, (bet) => bet.outcome === 'YES')
|
|
|
|
const winningBets = outcome === 'YES' ? yesBets : noBets
|
2021-12-24 21:06:01 +00:00
|
|
|
|
2022-01-02 01:03:18 +00:00
|
|
|
const betSum = _.sumBy(winningBets, (b) => b.amount)
|
2021-12-14 07:02:50 +00:00
|
|
|
|
2022-01-02 01:03:18 +00:00
|
|
|
if (betSum >= truePool) return getCancelPayouts(truePool, winningBets)
|
2021-12-14 07:02:50 +00:00
|
|
|
|
2021-12-24 21:06:01 +00:00
|
|
|
const creatorPayout = CREATOR_FEE * truePool
|
2022-01-02 01:03:18 +00:00
|
|
|
console.log(
|
|
|
|
'resolved',
|
|
|
|
outcome,
|
|
|
|
'pool: M$',
|
|
|
|
truePool,
|
|
|
|
'creator fee: M$',
|
|
|
|
creatorPayout
|
|
|
|
)
|
|
|
|
|
|
|
|
const shareDifferenceSum = _.sumBy(winningBets, (b) => b.shares - b.amount)
|
|
|
|
|
|
|
|
const winningsPool = truePool - betSum
|
|
|
|
const fees = PLATFORM_FEE + CREATOR_FEE
|
2021-12-14 07:02:50 +00:00
|
|
|
|
2021-12-17 22:15:09 +00:00
|
|
|
const winnerPayouts = winningBets.map((bet) => ({
|
2021-12-14 07:02:50 +00:00
|
|
|
userId: bet.userId,
|
2022-01-02 01:03:18 +00:00
|
|
|
payout:
|
|
|
|
(1 - fees) *
|
|
|
|
(bet.amount +
|
|
|
|
((bet.shares - bet.amount) / shareDifferenceSum) * winningsPool),
|
2021-12-14 07:02:50 +00:00
|
|
|
}))
|
|
|
|
|
2021-12-17 22:15:09 +00:00
|
|
|
return winnerPayouts.concat([
|
|
|
|
{ userId: contract.creatorId, payout: creatorPayout },
|
|
|
|
]) // add creator fee
|
2021-12-14 07:02:50 +00:00
|
|
|
}
|
|
|
|
|
2022-01-02 01:03:18 +00:00
|
|
|
const getMktPayouts = (truePool: number, contract: Contract, bets: Bet[]) => {
|
|
|
|
const p =
|
|
|
|
contract.pool.YES ** 2 / (contract.pool.YES ** 2 + contract.pool.NO ** 2)
|
|
|
|
console.log('Resolved MKT at p=', p)
|
|
|
|
|
|
|
|
return [
|
|
|
|
...getStandardPayouts('YES', p * truePool, contract, bets),
|
|
|
|
...getStandardPayouts('NO', (1 - p) * truePool, contract, bets),
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
2021-12-14 07:02:50 +00:00
|
|
|
const payUser = ([userId, payout]: [string, number]) => {
|
2021-12-17 22:15:09 +00:00
|
|
|
return firestore.runTransaction(async (transaction) => {
|
2021-12-14 07:02:50 +00:00
|
|
|
const userDoc = firestore.doc(`users/${userId}`)
|
|
|
|
const userSnap = await transaction.get(userDoc)
|
|
|
|
if (!userSnap.exists) return
|
|
|
|
const user = userSnap.data() as User
|
|
|
|
|
|
|
|
const newUserBalance = user.balance + payout
|
|
|
|
transaction.update(userDoc, { balance: newUserBalance })
|
|
|
|
})
|
|
|
|
}
|