manifold/functions/src/scripts/pay-out-contract-again.ts

105 lines
3.0 KiB
TypeScript
Raw Normal View History

2022-03-09 23:02:57 +00:00
import * as admin from 'firebase-admin'
import { flatten, groupBy, sumBy, mapValues } from 'lodash'
2022-03-09 23:02:57 +00:00
import { initAdmin } from './script-init'
initAdmin()
2022-03-09 23:02:57 +00:00
import { Bet } from '../../../common/bet'
import { Contract } from '../../../common/contract'
import { getLoanPayouts, getPayouts } from '../../../common/payouts'
import { filterDefined } from '../../../common/util/array'
2022-03-09 23:02:57 +00:00
type DocRef = admin.firestore.DocumentReference
const firestore = admin.firestore()
async function checkIfPayOutAgain(contractRef: DocRef, contract: Contract) {
const bets = await contractRef
.collection('bets')
.get()
.then((snap) => snap.docs.map((bet) => bet.data() as Bet))
const openBets = bets.filter((b) => !b.isSold && !b.sale)
const loanedBets = openBets.filter((bet) => bet.loanAmount)
if (loanedBets.length && contract.resolution) {
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
const { resolution, resolutions, resolutionProbability } = contract as any
const { payouts } = getPayouts(
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
resolution,
resolutions,
contract,
openBets,
[],
resolutionProbability
)
2022-03-09 23:02:57 +00:00
const loanPayouts = getLoanPayouts(openBets)
const groups = groupBy(
2022-03-09 23:02:57 +00:00
[...payouts, ...loanPayouts],
(payout) => payout.userId
)
const userPayouts = mapValues(groups, (group) =>
sumBy(group, (g) => g.payout)
2022-03-09 23:02:57 +00:00
)
const entries = Object.entries(userPayouts)
const firstNegative = entries.findIndex(([_, payout]) => payout < 0)
const toBePaidOut = firstNegative === -1 ? [] : entries.slice(firstNegative)
if (toBePaidOut.length) {
console.log(
'to be paid out',
toBePaidOut.length,
'already paid out',
entries.length - toBePaidOut.length
)
const positivePayouts = toBePaidOut.filter(([_, payout]) => payout > 0)
if (positivePayouts.length)
return { contract, toBePaidOut: positivePayouts }
}
}
return undefined
}
async function payOutContractAgain() {
console.log('Recalculating contract info')
const snapshot = await firestore.collection('contracts').get()
const [startTime, endTime] = [
new Date('2022-03-02'),
new Date('2022-03-07'),
].map((date) => date.getTime())
const contracts = snapshot.docs
.map((doc) => doc.data() as Contract)
.filter((contract) => {
const { resolutionTime } = contract
return (
resolutionTime && resolutionTime > startTime && resolutionTime < endTime
)
})
console.log('Loaded', contracts.length, 'contracts')
const toPayOutAgain = filterDefined(
await Promise.all(
contracts.map(async (contract) => {
const contractRef = firestore.doc(`contracts/${contract.id}`)
return await checkIfPayOutAgain(contractRef, contract)
})
)
)
const flattened = flatten(toPayOutAgain.map((d) => d.toBePaidOut))
2022-03-09 23:02:57 +00:00
for (const [userId, payout] of flattened) {
console.log('Paying out', userId, payout)
// await payUser(userId, payout)
}
}
if (require.main === module) payOutContractAgain().then(() => process.exit())