create market: use transaction

This commit is contained in:
mantikoros 2022-10-05 22:18:19 -05:00
parent cd8245fbee
commit e1f24f24a9

View File

@ -15,7 +15,7 @@ import {
import { slugify } from '../../common/util/slugify'
import { randomString } from '../../common/util/random'
import { chargeUser, getContract, isProd } from './utils'
import { isProd } from './utils'
import { APIError, AuthedUser, newEndpoint, validate, zTimestamp } from './api'
import { FIXED_ANTE, FREE_MARKETS_PER_USER_MAX } from '../../common/economy'
@ -36,7 +36,7 @@ import { getPseudoProbability } from '../../common/pseudo-numeric'
import { JSONContent } from '@tiptap/core'
import { uniq, zip } from 'lodash'
import { Bet } from '../../common/bet'
import { FieldValue } from 'firebase-admin/firestore'
import { FieldValue, Transaction } from 'firebase-admin/firestore'
const descScehma: z.ZodType<JSONContent> = z.lazy(() =>
z.intersection(
@ -107,6 +107,7 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
visibility = 'public',
} = validate(bodySchema, body)
return await firestore.runTransaction(async (trans) => {
let min, max, initialProb, isLogScale, answers
if (outcomeType === 'PSEUDO_NUMERIC' || outcomeType === 'NUMERIC') {
@ -115,7 +116,8 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
if (max - min <= 0.01 || initialValue <= min || initialValue >= max)
throw new APIError(400, 'Invalid range.')
initialProb = getPseudoProbability(initialValue, min, max, isLogScale) * 100
initialProb =
getPseudoProbability(initialValue, min, max, isLogScale) * 100
if (initialProb < 1 || initialProb > 99)
if (outcomeType === 'PSEUDO_NUMERIC')
@ -134,7 +136,7 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
;({ answers } = validate(multipleChoiceSchema, body))
}
const userDoc = await firestore.collection('users').doc(auth.uid).get()
const userDoc = await trans.get(firestore.collection('users').doc(auth.uid))
if (!userDoc.exists) {
throw new APIError(400, 'No user exists with the authenticated user ID.')
}
@ -150,15 +152,15 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
let group: Group | null = null
if (groupId) {
const groupDocRef = firestore.collection('groups').doc(groupId)
const groupDoc = await groupDocRef.get()
const groupDoc = await trans.get(groupDocRef)
if (!groupDoc.exists) {
throw new APIError(400, 'No group exists with the given group ID.')
}
group = groupDoc.data() as Group
const groupMembersSnap = await firestore
.collection(`groups/${groupId}/groupMembers`)
.get()
const groupMembersSnap = await trans.get(
firestore.collection(`groups/${groupId}/groupMembers`)
)
const groupMemberDocs = groupMembersSnap.docs.map(
(doc) => doc.data() as { userId: string; createdTime: number }
)
@ -173,7 +175,7 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
)
}
}
const slug = await getSlug(question)
const slug = await getSlug(trans, question)
const contractRef = firestore.collection('contracts').doc()
console.log(
@ -224,28 +226,36 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
: DEV_HOUSE_LIQUIDITY_PROVIDER_ID
: user.id
if (ante) await chargeUser(providerId, ante, true)
if (deservesFreeMarket)
await firestore
.collection('users')
.doc(user.id)
.update({ freeMarketsCreated: FieldValue.increment(1) })
if (ante) {
const delta = FieldValue.increment(-ante)
const providerDoc = firestore.collection('users').doc(providerId)
await trans.update(providerDoc, { balance: delta, totalDeposits: delta })
}
if (deservesFreeMarket) {
await trans.update(firestore.collection('users').doc(user.id), {
freeMarketsCreated: FieldValue.increment(1),
})
}
await contractRef.create(contract)
if (group != null) {
const groupContractsSnap = await firestore
.collection(`groups/${groupId}/groupContracts`)
.get()
const groupContractsSnap = await trans.get(
firestore.collection(`groups/${groupId}/groupContracts`)
)
const groupContracts = groupContractsSnap.docs.map(
(doc) => doc.data() as { contractId: string; createdTime: number }
)
if (!groupContracts.map((c) => c.contractId).includes(contractRef.id)) {
await createGroupLinks(group, [contractRef.id], auth.uid)
await createGroupLinks(trans, group, [contractRef.id], auth.uid)
const groupContractRef = firestore
.collection(`groups/${groupId}/groupContracts`)
.doc(contract.id)
await groupContractRef.set({
await trans.set(groupContractRef, {
contractId: contract.id,
createdTime: Date.now(),
})
@ -264,7 +274,7 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
ante
)
await liquidityDoc.set(lp)
await trans.set(liquidityDoc, lp)
} else if (outcomeType === 'MULTIPLE_CHOICE') {
const betCol = firestore.collection(`contracts/${contract.id}/bets`)
const betDocs = (answers ?? []).map(() => betCol.doc())
@ -282,21 +292,23 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
)
await Promise.all(
zip(bets, betDocs).map(([bet, doc]) => doc?.create(bet as Bet))
zip(bets, betDocs).map(([bet, doc]) =>
doc ? trans.create(doc, bet as Bet) : undefined
)
)
await Promise.all(
zip(answerObjects, answerDocs).map(([answer, doc]) =>
doc?.create(answer as Answer)
doc ? trans.create(doc, answer as Answer) : undefined
)
)
await contractRef.update({ answers: answerObjects })
await trans.update(contractRef, { answers: answerObjects })
} else if (outcomeType === 'FREE_RESPONSE') {
const noneAnswerDoc = firestore
.collection(`contracts/${contract.id}/answers`)
.doc('0')
const noneAnswer = getNoneAnswer(contract.id, user)
await noneAnswerDoc.set(noneAnswer)
await trans.set(noneAnswerDoc, noneAnswer)
const anteBetDoc = firestore
.collection(`contracts/${contract.id}/bets`)
@ -307,7 +319,7 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
contract as FreeResponseContract,
anteBetDoc.id
)
await anteBetDoc.set(anteBet)
await trans.set(anteBetDoc, anteBet)
} else if (outcomeType === 'NUMERIC') {
const anteBetDoc = firestore
.collection(`contracts/${contract.id}/bets`)
@ -320,16 +332,17 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
anteBetDoc.id
)
await anteBetDoc.set(anteBet)
await trans.set(anteBetDoc, anteBet)
}
return contract
})
}
const getSlug = async (question: string) => {
const getSlug = async (trans: Transaction, question: string) => {
const proposedSlug = slugify(question)
const preexistingContract = await getContractFromSlug(proposedSlug)
const preexistingContract = await getContractFromSlug(trans, proposedSlug)
return preexistingContract
? proposedSlug + '-' + randomString()
@ -338,35 +351,31 @@ const getSlug = async (question: string) => {
const firestore = admin.firestore()
export async function getContractFromSlug(slug: string) {
const snap = await firestore
.collection('contracts')
.where('slug', '==', slug)
.get()
async function getContractFromSlug(trans: Transaction, slug: string) {
const snap = await trans.get(
firestore.collection('contracts').where('slug', '==', slug)
)
return snap.empty ? undefined : (snap.docs[0].data() as Contract)
}
async function createGroupLinks(
trans: Transaction,
group: Group,
contractIds: string[],
userId: string
) {
for (const contractId of contractIds) {
const contract = await getContract(contractId)
const contractRef = firestore.collection('contracts').doc(contractId)
const contract = (await trans.get(contractRef)).data() as Contract
if (!contract?.groupSlugs?.includes(group.slug)) {
await firestore
.collection('contracts')
.doc(contractId)
.update({
await trans.update(contractRef, {
groupSlugs: uniq([group.slug, ...(contract?.groupSlugs ?? [])]),
})
}
if (!contract?.groupLinks?.map((gl) => gl.groupId).includes(group.id)) {
await firestore
.collection('contracts')
.doc(contractId)
.update({
await trans.update(contractRef, {
groupLinks: [
{
groupId: group.id,