manifold/web/lib/calculation/contract.ts

73 lines
2.1 KiB
TypeScript
Raw Normal View History

import { Bet } from '../firebase/bets'
import { Contract } from '../firebase/contracts'
2021-12-15 23:27:02 +00:00
const fees = 0.02
2021-12-17 22:15:09 +00:00
export function getProbability(pool: { YES: number; NO: number }) {
const [yesPool, noPool] = [pool.YES, pool.NO]
const numerator = Math.pow(yesPool, 2)
const denominator = Math.pow(yesPool, 2) + Math.pow(noPool, 2)
return numerator / denominator
}
export function getProbabilityAfterBet(
2021-12-17 22:15:09 +00:00
pool: { YES: number; NO: number },
outcome: 'YES' | 'NO',
bet: number
) {
const [YES, NO] = [
2021-12-17 22:15:09 +00:00
pool.YES + (outcome === 'YES' ? bet : 0),
pool.NO + (outcome === 'NO' ? bet : 0),
]
return getProbability({ YES, NO })
}
export function getDpmWeight(
2021-12-17 22:15:09 +00:00
pool: { YES: number; NO: number },
bet: number,
betChoice: 'YES' | 'NO'
) {
2021-12-17 22:15:09 +00:00
const [yesPool, noPool] = [pool.YES, pool.NO]
return betChoice === 'YES'
2021-12-17 22:15:09 +00:00
? (bet * Math.pow(noPool, 2)) / (Math.pow(yesPool, 2) + bet * yesPool)
: (bet * Math.pow(yesPool, 2)) / (Math.pow(noPool, 2) + bet * noPool)
}
export function calculatePayout(
contract: Contract,
bet: Bet,
outcome: 'YES' | 'NO' | 'CANCEL'
) {
const { amount, outcome: betOutcome, dpmWeight } = bet
if (outcome === 'CANCEL') return amount
2021-12-15 23:27:02 +00:00
if (betOutcome !== outcome) return 0
2021-12-17 22:15:09 +00:00
let { dpmWeights, pool, startPool } = contract
2021-12-15 23:27:02 +00:00
// Fake data if not set.
if (!dpmWeights) dpmWeights = { YES: 100, NO: 100 }
// Fake data if not set.
2021-12-17 22:15:09 +00:00
if (!pool) pool = { YES: 100, NO: 100 }
2021-12-15 23:27:02 +00:00
const otherOutcome = outcome === 'YES' ? 'NO' : 'YES'
2021-12-17 22:15:09 +00:00
const poolSize = pool[otherOutcome] - startPool[otherOutcome]
2021-12-15 23:27:02 +00:00
2021-12-17 22:15:09 +00:00
return (1 - fees) * (dpmWeight / dpmWeights[outcome]) * poolSize + amount
}
export function resolvedPayout(contract: Contract, bet: Bet) {
if (contract.resolution)
return calculatePayout(contract, bet, contract.resolution)
throw new Error('Contract was not resolved')
}
export function currentValue(contract: Contract, bet: Bet) {
2021-12-17 22:15:09 +00:00
const prob = getProbability(contract.pool)
const yesPayout = calculatePayout(contract, bet, 'YES')
const noPayout = calculatePayout(contract, bet, 'NO')
return prob * yesPayout + (1 - prob) * noPayout
}