manifold/web/lib/service/create-contract.ts

63 lines
1.5 KiB
TypeScript
Raw Normal View History

2021-12-17 23:16:42 +00:00
import {
Contract,
getContractFromSlug,
pushNewContract,
setContract,
} from '../firebase/contracts'
import { User } from '../firebase/users'
import { randomString } from '../util/random-string'
import { slugify } from '../util/slugify'
// consider moving to cloud function for security
export async function createContract(
question: string,
description: string,
initialProb: number,
creator: User
) {
2021-12-17 23:16:42 +00:00
const proposedSlug = slugify(question).substring(0, 35)
2021-12-17 23:16:42 +00:00
const preexistingContract = await getContractFromSlug(proposedSlug)
2021-12-17 23:16:42 +00:00
const slug = preexistingContract
? proposedSlug + '-' + randomString()
: proposedSlug
2021-12-17 22:15:09 +00:00
const { startYes, startNo } = calcStartPool(initialProb)
2021-12-17 23:16:42 +00:00
const contract: Omit<Contract, 'id'> = {
slug,
outcomeType: 'BINARY',
creatorId: creator.id,
creatorName: creator.name,
question: question.trim(),
description: description.trim(),
2021-12-17 22:15:09 +00:00
startPool: { YES: startYes, NO: startNo },
pool: { YES: startYes, NO: startNo },
2021-12-15 22:44:22 +00:00
dpmWeights: { YES: 0, NO: 0 },
isResolved: false,
// TODO: Set create time to Firestore timestamp
createdTime: Date.now(),
lastUpdatedTime: Date.now(),
}
2021-12-17 23:16:42 +00:00
return await pushNewContract(contract)
}
2021-12-17 22:15:09 +00:00
export function calcStartPool(initialProb: number, initialCapital = 100) {
const p = initialProb / 100.0
2021-12-17 22:15:09 +00:00
const startYes =
p === 0.5
? p * initialCapital
: -(initialCapital * (-p + Math.sqrt((-1 + p) * -p))) / (-1 + 2 * p)
2021-12-17 22:15:09 +00:00
const startNo = initialCapital - startYes
2021-12-17 22:15:09 +00:00
return { startYes, startNo }
}