2021-12-14 07:02:50 +00:00
|
|
|
import * as functions from 'firebase-functions'
|
|
|
|
import * as admin from 'firebase-admin'
|
2022-06-14 20:01:32 +00:00
|
|
|
import { difference, uniq, mapValues, groupBy, sum, sumBy } from 'lodash'
|
2021-12-14 07:02:50 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
import {
|
|
|
|
AUTO_RESOLUTION,
|
|
|
|
Contract,
|
|
|
|
FreeResponse,
|
|
|
|
resolution,
|
|
|
|
RESOLUTIONS,
|
|
|
|
} from '../../common/contract'
|
2022-05-15 17:39:42 +00:00
|
|
|
import { User } from '../../common/user'
|
|
|
|
import { Bet } from '../../common/bet'
|
2022-03-15 22:27:51 +00:00
|
|
|
import { getUser, isProd, payUser } from './utils'
|
2022-01-02 00:08:52 +00:00
|
|
|
import { sendMarketResolutionEmail } from './emails'
|
2022-05-09 21:04:40 +00:00
|
|
|
import {
|
|
|
|
getLoanPayouts,
|
|
|
|
getPayouts,
|
|
|
|
groupPayoutsByUser,
|
|
|
|
Payout,
|
2022-05-15 17:39:42 +00:00
|
|
|
} from '../../common/payouts'
|
|
|
|
import { removeUndefinedProps } from '../../common/util/object'
|
|
|
|
import { LiquidityProvision } from '../../common/liquidity-provision'
|
2022-06-14 20:01:32 +00:00
|
|
|
import { getDpmOutcomeProbability } from '../../common/calculate-dpm'
|
|
|
|
import { getValues } from './utils'
|
|
|
|
import { batchedWaitAll } from '../../common/util/promise'
|
|
|
|
import { getProbability } from '../../common/calculate'
|
2021-12-14 07:02:50 +00:00
|
|
|
|
|
|
|
export const resolveMarket = functions
|
2022-06-04 21:39:25 +00:00
|
|
|
.runWith({ minInstances: 1, secrets: ['MAILGUN_KEY'] })
|
2021-12-17 22:15:09 +00:00
|
|
|
.https.onCall(
|
|
|
|
async (
|
|
|
|
data: {
|
2022-06-03 00:30:34 +00:00
|
|
|
outcome: resolution
|
2022-05-19 17:42:03 +00:00
|
|
|
value?: number
|
2021-12-17 22:15:09 +00:00
|
|
|
contractId: string
|
2022-01-30 21:51:30 +00:00
|
|
|
probabilityInt?: number
|
2022-02-20 07:26:26 +00:00
|
|
|
resolutions?: { [outcome: string]: number }
|
2021-12-17 22:15:09 +00:00
|
|
|
},
|
|
|
|
context
|
|
|
|
) => {
|
|
|
|
const userId = context?.auth?.uid
|
|
|
|
if (!userId) return { status: 'error', message: 'Not authorized' }
|
2022-06-14 20:01:32 +00:00
|
|
|
const contractDoc = firestore.doc(`contracts/${data.contractId}`)
|
2022-02-17 23:00:19 +00:00
|
|
|
const contractSnap = await contractDoc.get()
|
|
|
|
if (!contractSnap.exists)
|
|
|
|
return { status: 'error', message: 'Invalid contract' }
|
|
|
|
const contract = contractSnap.data() as Contract
|
2022-06-14 20:01:32 +00:00
|
|
|
if (contract.creatorId !== userId)
|
|
|
|
return { status: 'error', message: 'User not creator of contract' }
|
|
|
|
|
|
|
|
return privateResolveMarket(contract, data)
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
export const autoResolveMarkets = functions.pubsub
|
|
|
|
.schedule('every 1 minutes')
|
|
|
|
.onRun(async () => {
|
|
|
|
const contracts = await getValues<Contract>(
|
|
|
|
firestore
|
|
|
|
.collection('contracts')
|
|
|
|
.where('isResolved', '==', false)
|
|
|
|
.where('autoResolutionTime', '<', Date.now())
|
|
|
|
)
|
2022-06-15 04:16:02 +00:00
|
|
|
const closedContracts = contracts.filter(
|
|
|
|
(c) => c.closeTime && c.closeTime < Date.now()
|
|
|
|
)
|
2022-06-14 20:01:32 +00:00
|
|
|
|
|
|
|
await batchedWaitAll(
|
2022-06-15 04:16:02 +00:00
|
|
|
closedContracts.map((contract) => async () => {
|
2022-06-14 20:01:32 +00:00
|
|
|
const result = await autoResolve(contract)
|
|
|
|
|
|
|
|
console.log('resolved', contract.slug, 'result:', result)
|
|
|
|
})
|
|
|
|
)
|
|
|
|
})
|
|
|
|
|
|
|
|
const autoResolve = async (contract: Contract) => {
|
|
|
|
const data = {
|
|
|
|
outcome: AUTO_RESOLUTION,
|
|
|
|
value: undefined, // numeric
|
|
|
|
probabilityInt:
|
|
|
|
contract.outcomeType == 'BINARY'
|
|
|
|
? getProbability(contract) * 100
|
|
|
|
: undefined,
|
|
|
|
resolutions:
|
|
|
|
contract.outcomeType == 'FREE_RESPONSE'
|
|
|
|
? getFreeResponseResolutions(contract)
|
|
|
|
: undefined,
|
|
|
|
}
|
|
|
|
contract.description = contract.description.concat(
|
|
|
|
`\n\n\nContract resolved automatically.`
|
|
|
|
)
|
|
|
|
|
|
|
|
return await privateResolveMarket(contract, data)
|
|
|
|
}
|
|
|
|
|
|
|
|
const getFreeResponseResolutions = (contract: Contract & FreeResponse) => {
|
|
|
|
const answersWithProbs = getAnswersWithProbs(contract)
|
|
|
|
const totalProb = sum(Object.values(answersWithProbs))
|
|
|
|
return mapValues(answersWithProbs, (prob) => (100 * prob) / totalProb)
|
|
|
|
}
|
|
|
|
|
|
|
|
const getAnswersWithProbs = (contract: Contract & FreeResponse) => {
|
|
|
|
const answers: { [id: string]: number } = {}
|
|
|
|
for (const answer of contract.answers) {
|
|
|
|
answers[answer.id] = getDpmOutcomeProbability(
|
|
|
|
contract.totalShares,
|
|
|
|
answer.id
|
|
|
|
)
|
|
|
|
}
|
|
|
|
return answers
|
|
|
|
}
|
2022-05-19 17:42:03 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const privateResolveMarket = async (
|
|
|
|
contract: Contract,
|
|
|
|
data: {
|
|
|
|
outcome: resolution
|
|
|
|
value?: number
|
|
|
|
probabilityInt?: number
|
|
|
|
resolutions?: { [outcome: string]: number }
|
|
|
|
}
|
|
|
|
) => {
|
|
|
|
const { creatorId, id, outcomeType, closeTime } = contract
|
|
|
|
const { outcome, probabilityInt, resolutions, value } = data
|
|
|
|
switch (outcomeType) {
|
|
|
|
case 'FREE_RESPONSE':
|
|
|
|
if (
|
|
|
|
isNaN(+outcome) &&
|
|
|
|
!(outcome === 'MKT' && resolutions) &&
|
|
|
|
outcome !== 'CANCEL'
|
|
|
|
)
|
|
|
|
return { status: 'error', message: 'Invalid outcome' }
|
|
|
|
break
|
|
|
|
case 'NUMERIC':
|
|
|
|
if (isNaN(+outcome) && outcome !== 'CANCEL')
|
|
|
|
return { status: 'error', message: 'Invalid outcome' }
|
|
|
|
break
|
|
|
|
case 'BINARY':
|
|
|
|
if (!RESOLUTIONS.includes(outcome))
|
|
|
|
return { status: 'error', message: 'Invalid outcome' }
|
2022-01-30 21:51:30 +00:00
|
|
|
if (
|
|
|
|
probabilityInt !== undefined &&
|
2022-02-12 06:19:45 +00:00
|
|
|
(probabilityInt < 0 ||
|
|
|
|
probabilityInt > 100 ||
|
|
|
|
!isFinite(probabilityInt))
|
2022-01-30 21:51:30 +00:00
|
|
|
)
|
|
|
|
return { status: 'error', message: 'Invalid probability' }
|
2022-06-14 20:01:32 +00:00
|
|
|
}
|
2022-01-30 21:51:30 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
if (value && !isFinite(value))
|
|
|
|
return { status: 'error', message: 'Invalid value' }
|
2021-12-17 22:15:09 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
if (contract.resolution)
|
|
|
|
return { status: 'error', message: 'Contract already resolved' }
|
2021-12-17 22:15:09 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const creator = await getUser(creatorId)
|
|
|
|
if (!creator) return { status: 'error', message: 'Creator not found' }
|
2022-01-02 00:08:52 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const resolutionProbability =
|
|
|
|
probabilityInt !== undefined ? probabilityInt / 100 : undefined
|
2022-01-30 21:51:30 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const resolutionTime = Date.now()
|
|
|
|
const newCloseTime = closeTime
|
|
|
|
? Math.min(closeTime, resolutionTime)
|
|
|
|
: closeTime
|
2022-03-01 00:19:47 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const betsSnap = await firestore.collection(`contracts/${id}/bets`).get()
|
2022-03-15 22:27:51 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const bets = betsSnap.docs.map((doc) => doc.data() as Bet)
|
2022-03-15 22:27:51 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const liquiditiesSnap = await firestore
|
|
|
|
.collection(`contracts/${id}/liquidity`)
|
|
|
|
.get()
|
2022-03-15 22:27:51 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const liquidities = liquiditiesSnap.docs.map(
|
|
|
|
(doc) => doc.data() as LiquidityProvision
|
|
|
|
)
|
2022-03-15 22:27:51 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const { payouts, creatorPayout, liquidityPayouts, collectedFees } =
|
|
|
|
getPayouts(
|
|
|
|
outcome,
|
|
|
|
resolutions ?? {},
|
|
|
|
contract,
|
|
|
|
bets,
|
|
|
|
liquidities,
|
|
|
|
resolutionProbability
|
|
|
|
)
|
|
|
|
|
|
|
|
const contractDoc = firestore.doc(`contracts/${contract.id}`)
|
|
|
|
|
|
|
|
await contractDoc.update(
|
|
|
|
removeUndefinedProps({
|
|
|
|
isResolved: true,
|
|
|
|
resolution: outcome,
|
|
|
|
resolutionValue: value,
|
|
|
|
resolutionTime,
|
|
|
|
description: contract.description,
|
|
|
|
closeTime: newCloseTime,
|
|
|
|
resolutionProbability,
|
|
|
|
resolutions,
|
|
|
|
collectedFees,
|
|
|
|
})
|
|
|
|
)
|
2021-12-17 22:15:09 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
console.log('contract ', id, 'resolved to:', outcome)
|
2022-01-02 00:08:52 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
const openBets = bets.filter((b) => !b.isSold && !b.sale)
|
|
|
|
const loanPayouts = getLoanPayouts(openBets)
|
|
|
|
|
|
|
|
if (!isProd)
|
|
|
|
console.log(
|
|
|
|
'payouts:',
|
|
|
|
payouts,
|
|
|
|
'creator payout:',
|
|
|
|
creatorPayout,
|
|
|
|
'liquidity payout:'
|
|
|
|
)
|
|
|
|
|
|
|
|
if (creatorPayout)
|
|
|
|
await processPayouts([{ userId: creatorId, payout: creatorPayout }], true)
|
|
|
|
|
|
|
|
await processPayouts(liquidityPayouts, true)
|
|
|
|
|
|
|
|
const result = await processPayouts([...payouts, ...loanPayouts])
|
|
|
|
|
|
|
|
const userPayoutsWithoutLoans = groupPayoutsByUser(payouts)
|
|
|
|
|
|
|
|
await sendResolutionEmails(
|
|
|
|
openBets,
|
|
|
|
userPayoutsWithoutLoans,
|
|
|
|
creator,
|
|
|
|
creatorPayout,
|
|
|
|
contract,
|
|
|
|
outcome,
|
|
|
|
resolutionProbability,
|
|
|
|
resolutions
|
2021-12-17 22:15:09 +00:00
|
|
|
)
|
2021-12-14 07:02:50 +00:00
|
|
|
|
2022-06-14 20:01:32 +00:00
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
2022-05-09 21:04:40 +00:00
|
|
|
const processPayouts = async (payouts: Payout[], isDeposit = false) => {
|
|
|
|
const userPayouts = groupPayoutsByUser(payouts)
|
|
|
|
|
|
|
|
const payoutPromises = Object.entries(userPayouts).map(([userId, payout]) =>
|
|
|
|
payUser(userId, payout, isDeposit)
|
|
|
|
)
|
|
|
|
|
|
|
|
return await Promise.all(payoutPromises)
|
|
|
|
.catch((e) => ({ status: 'error', message: e }))
|
|
|
|
.then(() => ({ status: 'success' }))
|
|
|
|
}
|
|
|
|
|
2022-01-02 01:13:30 +00:00
|
|
|
const sendResolutionEmails = async (
|
|
|
|
openBets: Bet[],
|
|
|
|
userPayouts: { [userId: string]: number },
|
|
|
|
creator: User,
|
2022-05-10 13:49:14 +00:00
|
|
|
creatorPayout: number,
|
2022-01-02 01:13:30 +00:00
|
|
|
contract: Contract,
|
2022-02-20 07:26:26 +00:00
|
|
|
outcome: string,
|
|
|
|
resolutionProbability?: number,
|
|
|
|
resolutions?: { [outcome: string]: number }
|
2022-01-02 01:13:30 +00:00
|
|
|
) => {
|
2022-05-22 08:36:05 +00:00
|
|
|
const nonWinners = difference(
|
|
|
|
uniq(openBets.map(({ userId }) => userId)),
|
2022-01-02 01:13:30 +00:00
|
|
|
Object.keys(userPayouts)
|
|
|
|
)
|
2022-05-22 08:36:05 +00:00
|
|
|
const investedByUser = mapValues(
|
|
|
|
groupBy(openBets, (bet) => bet.userId),
|
|
|
|
(bets) => sumBy(bets, (bet) => bet.amount)
|
2022-02-24 07:04:24 +00:00
|
|
|
)
|
2022-01-02 01:13:30 +00:00
|
|
|
const emailPayouts = [
|
|
|
|
...Object.entries(userPayouts),
|
|
|
|
...nonWinners.map((userId) => [userId, 0] as const),
|
2022-02-24 07:04:24 +00:00
|
|
|
].map(([userId, payout]) => ({
|
|
|
|
userId,
|
2022-03-17 04:56:59 +00:00
|
|
|
investment: investedByUser[userId] ?? 0,
|
2022-02-24 07:04:24 +00:00
|
|
|
payout,
|
|
|
|
}))
|
|
|
|
|
2022-01-02 01:13:30 +00:00
|
|
|
await Promise.all(
|
2022-02-24 07:04:24 +00:00
|
|
|
emailPayouts.map(({ userId, investment, payout }) =>
|
2022-01-30 21:51:30 +00:00
|
|
|
sendMarketResolutionEmail(
|
|
|
|
userId,
|
2022-02-24 07:04:24 +00:00
|
|
|
investment,
|
2022-01-30 21:51:30 +00:00
|
|
|
payout,
|
|
|
|
creator,
|
2022-05-10 13:49:14 +00:00
|
|
|
creatorPayout,
|
2022-01-30 21:51:30 +00:00
|
|
|
contract,
|
|
|
|
outcome,
|
2022-02-20 07:26:26 +00:00
|
|
|
resolutionProbability,
|
|
|
|
resolutions
|
2022-01-30 21:51:30 +00:00
|
|
|
)
|
2022-01-02 01:13:30 +00:00
|
|
|
)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2021-12-14 07:02:50 +00:00
|
|
|
const firestore = admin.firestore()
|