This commit is contained in:
Pico2x 2022-10-06 17:04:32 +01:00
commit edbd0feb37

View File

@ -15,7 +15,7 @@ import {
import { slugify } from '../../common/util/slugify' import { slugify } from '../../common/util/slugify'
import { randomString } from '../../common/util/random' import { randomString } from '../../common/util/random'
import { isProd } from './utils' import { chargeUser, getContract, isProd } from './utils'
import { APIError, AuthedUser, newEndpoint, validate, zTimestamp } from './api' import { APIError, AuthedUser, newEndpoint, validate, zTimestamp } from './api'
import { FIXED_ANTE, FREE_MARKETS_PER_USER_MAX } from '../../common/economy' 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 { JSONContent } from '@tiptap/core'
import { uniq, zip } from 'lodash' import { uniq, zip } from 'lodash'
import { Bet } from '../../common/bet' import { Bet } from '../../common/bet'
import { FieldValue, Transaction } from 'firebase-admin/firestore' import { FieldValue } from 'firebase-admin/firestore'
const descScehma: z.ZodType<JSONContent> = z.lazy(() => const descScehma: z.ZodType<JSONContent> = z.lazy(() =>
z.intersection( z.intersection(
@ -107,242 +107,229 @@ export async function createMarketHelper(body: any, auth: AuthedUser) {
visibility = 'public', visibility = 'public',
} = validate(bodySchema, body) } = validate(bodySchema, body)
return await firestore.runTransaction(async (trans) => { let min, max, initialProb, isLogScale, answers
let min, max, initialProb, isLogScale, answers
if (outcomeType === 'PSEUDO_NUMERIC' || outcomeType === 'NUMERIC') { if (outcomeType === 'PSEUDO_NUMERIC' || outcomeType === 'NUMERIC') {
let initialValue let initialValue
;({ min, max, initialValue, isLogScale } = validate(numericSchema, body)) ;({ min, max, initialValue, isLogScale } = validate(numericSchema, body))
if (max - min <= 0.01 || initialValue <= min || initialValue >= max) if (max - min <= 0.01 || initialValue <= min || initialValue >= max)
throw new APIError(400, 'Invalid range.') throw new APIError(400, 'Invalid range.')
initialProb = initialProb = getPseudoProbability(initialValue, min, max, isLogScale) * 100
getPseudoProbability(initialValue, min, max, isLogScale) * 100
if (initialProb < 1 || initialProb > 99) if (initialProb < 1 || initialProb > 99)
if (outcomeType === 'PSEUDO_NUMERIC') if (outcomeType === 'PSEUDO_NUMERIC')
throw new APIError(
400,
`Initial value is too ${initialProb < 1 ? 'low' : 'high'}`
)
else throw new APIError(400, 'Invalid initial probability.')
}
if (outcomeType === 'BINARY') {
;({ initialProb } = validate(binarySchema, body))
}
if (outcomeType === 'MULTIPLE_CHOICE') {
;({ answers } = validate(multipleChoiceSchema, body))
}
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.')
}
const user = userDoc.data() as User
const ante = FIXED_ANTE
const deservesFreeMarket =
(user?.freeMarketsCreated ?? 0) < FREE_MARKETS_PER_USER_MAX
// TODO: this is broken because it's not in a transaction
if (ante > user.balance && !deservesFreeMarket)
throw new APIError(400, `Balance must be at least ${ante}.`)
let group: Group | null = null
if (groupId) {
const groupDocRef = firestore.collection('groups').doc(groupId)
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 trans.get(
firestore.collection(`groups/${groupId}/groupMembers`)
)
const groupMemberDocs = groupMembersSnap.docs.map(
(doc) => doc.data() as { userId: string; createdTime: number }
)
if (
!groupMemberDocs.map((m) => m.userId).includes(user.id) &&
!group.anyoneCanJoin &&
group.creatorId !== user.id
) {
throw new APIError( throw new APIError(
400, 400,
'User must be a member/creator of the group or group must be open to add markets to it.' `Initial value is too ${initialProb < 1 ? 'low' : 'high'}`
) )
} else throw new APIError(400, 'Invalid initial probability.')
} }
const slug = await getSlug(trans, question)
const contractRef = firestore.collection('contracts').doc()
console.log( if (outcomeType === 'BINARY') {
'creating contract for', ;({ initialProb } = validate(binarySchema, body))
user.username, }
'on',
question,
'ante:',
ante || 0
)
// convert string descriptions into JSONContent if (outcomeType === 'MULTIPLE_CHOICE') {
const newDescription = ;({ answers } = validate(multipleChoiceSchema, body))
!description || typeof description === 'string' }
? {
type: 'doc',
content: [
{
type: 'paragraph',
content: [{ type: 'text', text: description || ' ' }],
},
],
}
: description
const contract = getNewContract( const userDoc = await firestore.collection('users').doc(auth.uid).get()
contractRef.id, if (!userDoc.exists) {
slug, throw new APIError(400, 'No user exists with the authenticated user ID.')
user, }
question, const user = userDoc.data() as User
outcomeType,
newDescription,
initialProb ?? 0,
ante,
closeTime.getTime(),
tags ?? [],
NUMERIC_BUCKET_COUNT,
min ?? 0,
max ?? 0,
isLogScale ?? false,
answers ?? [],
visibility
)
const providerId = deservesFreeMarket const ante = FIXED_ANTE
? isProd() const deservesFreeMarket =
? HOUSE_LIQUIDITY_PROVIDER_ID (user?.freeMarketsCreated ?? 0) < FREE_MARKETS_PER_USER_MAX
: DEV_HOUSE_LIQUIDITY_PROVIDER_ID // TODO: this is broken because it's not in a transaction
: user.id if (ante > user.balance && !deservesFreeMarket)
throw new APIError(400, `Balance must be at least ${ante}.`)
if (ante) { let group: Group | null = null
const delta = FieldValue.increment(-ante) if (groupId) {
const providerDoc = firestore.collection('users').doc(providerId) const groupDocRef = firestore.collection('groups').doc(groupId)
await trans.update(providerDoc, { balance: delta, totalDeposits: delta }) const groupDoc = await groupDocRef.get()
if (!groupDoc.exists) {
throw new APIError(400, 'No group exists with the given group ID.')
} }
if (deservesFreeMarket) { group = groupDoc.data() as Group
await trans.update(firestore.collection('users').doc(user.id), { const groupMembersSnap = await firestore
freeMarketsCreated: FieldValue.increment(1), .collection(`groups/${groupId}/groupMembers`)
.get()
const groupMemberDocs = groupMembersSnap.docs.map(
(doc) => doc.data() as { userId: string; createdTime: number }
)
if (
!groupMemberDocs.map((m) => m.userId).includes(user.id) &&
!group.anyoneCanJoin &&
group.creatorId !== user.id
) {
throw new APIError(
400,
'User must be a member/creator of the group or group must be open to add markets to it.'
)
}
}
const slug = await getSlug(question)
const contractRef = firestore.collection('contracts').doc()
console.log(
'creating contract for',
user.username,
'on',
question,
'ante:',
ante || 0
)
// convert string descriptions into JSONContent
const newDescription =
!description || typeof description === 'string'
? {
type: 'doc',
content: [
{
type: 'paragraph',
content: [{ type: 'text', text: description || ' ' }],
},
],
}
: description
const contract = getNewContract(
contractRef.id,
slug,
user,
question,
outcomeType,
newDescription,
initialProb ?? 0,
ante,
closeTime.getTime(),
tags ?? [],
NUMERIC_BUCKET_COUNT,
min ?? 0,
max ?? 0,
isLogScale ?? false,
answers ?? [],
visibility
)
const providerId = deservesFreeMarket
? isProd()
? HOUSE_LIQUIDITY_PROVIDER_ID
: 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) })
await contractRef.create(contract)
if (group != null) {
const groupContractsSnap = await firestore
.collection(`groups/${groupId}/groupContracts`)
.get()
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)
const groupContractRef = firestore
.collection(`groups/${groupId}/groupContracts`)
.doc(contract.id)
await groupContractRef.set({
contractId: contract.id,
createdTime: Date.now(),
}) })
} }
}
await contractRef.create(contract) if (outcomeType === 'BINARY' || outcomeType === 'PSEUDO_NUMERIC') {
const liquidityDoc = firestore
.collection(`contracts/${contract.id}/liquidity`)
.doc()
if (group != null) { const lp = getCpmmInitialLiquidity(
const groupContractsSnap = await trans.get( providerId,
firestore.collection(`groups/${groupId}/groupContracts`) contract as CPMMBinaryContract,
) liquidityDoc.id,
const groupContracts = groupContractsSnap.docs.map( ante
(doc) => doc.data() as { contractId: string; createdTime: number } )
await liquidityDoc.set(lp)
} else if (outcomeType === 'MULTIPLE_CHOICE') {
const betCol = firestore.collection(`contracts/${contract.id}/bets`)
const betDocs = (answers ?? []).map(() => betCol.doc())
const answerCol = firestore.collection(`contracts/${contract.id}/answers`)
const answerDocs = (answers ?? []).map((_, i) =>
answerCol.doc(i.toString())
)
const { bets, answerObjects } = getMultipleChoiceAntes(
user,
contract as MultipleChoiceContract,
answers ?? [],
betDocs.map((bd) => bd.id)
)
await Promise.all(
zip(bets, betDocs).map(([bet, doc]) => doc?.create(bet as Bet))
)
await Promise.all(
zip(answerObjects, answerDocs).map(([answer, doc]) =>
doc?.create(answer as Answer)
) )
)
await contractRef.update({ answers: answerObjects })
} else if (outcomeType === 'FREE_RESPONSE') {
const noneAnswerDoc = firestore
.collection(`contracts/${contract.id}/answers`)
.doc('0')
if (!groupContracts.map((c) => c.contractId).includes(contractRef.id)) { const noneAnswer = getNoneAnswer(contract.id, user)
await createGroupLinks(trans, group, [contractRef.id], auth.uid) await noneAnswerDoc.set(noneAnswer)
const groupContractRef = firestore const anteBetDoc = firestore
.collection(`groups/${groupId}/groupContracts`) .collection(`contracts/${contract.id}/bets`)
.doc(contract.id) .doc()
await trans.set(groupContractRef, { const anteBet = getFreeAnswerAnte(
contractId: contract.id, providerId,
createdTime: Date.now(), contract as FreeResponseContract,
}) anteBetDoc.id
} )
} await anteBetDoc.set(anteBet)
} else if (outcomeType === 'NUMERIC') {
const anteBetDoc = firestore
.collection(`contracts/${contract.id}/bets`)
.doc()
if (outcomeType === 'BINARY' || outcomeType === 'PSEUDO_NUMERIC') { const anteBet = getNumericAnte(
const liquidityDoc = firestore providerId,
.collection(`contracts/${contract.id}/liquidity`) contract as NumericContract,
.doc() ante,
anteBetDoc.id
)
const lp = getCpmmInitialLiquidity( await anteBetDoc.set(anteBet)
providerId, }
contract as CPMMBinaryContract,
liquidityDoc.id,
ante
)
await trans.set(liquidityDoc, lp) return contract
} else if (outcomeType === 'MULTIPLE_CHOICE') {
const betCol = firestore.collection(`contracts/${contract.id}/bets`)
const betDocs = (answers ?? []).map(() => betCol.doc())
const answerCol = firestore.collection(`contracts/${contract.id}/answers`)
const answerDocs = (answers ?? []).map((_, i) =>
answerCol.doc(i.toString())
)
const { bets, answerObjects } = getMultipleChoiceAntes(
user,
contract as MultipleChoiceContract,
answers ?? [],
betDocs.map((bd) => bd.id)
)
await Promise.all(
zip(bets, betDocs).map(([bet, doc]) =>
doc ? trans.create(doc, bet as Bet) : undefined
)
)
await Promise.all(
zip(answerObjects, answerDocs).map(([answer, doc]) =>
doc ? trans.create(doc, answer as Answer) : undefined
)
)
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 trans.set(noneAnswerDoc, noneAnswer)
const anteBetDoc = firestore
.collection(`contracts/${contract.id}/bets`)
.doc()
const anteBet = getFreeAnswerAnte(
providerId,
contract as FreeResponseContract,
anteBetDoc.id
)
await trans.set(anteBetDoc, anteBet)
} else if (outcomeType === 'NUMERIC') {
const anteBetDoc = firestore
.collection(`contracts/${contract.id}/bets`)
.doc()
const anteBet = getNumericAnte(
providerId,
contract as NumericContract,
ante,
anteBetDoc.id
)
await trans.set(anteBetDoc, anteBet)
}
return contract
})
} }
const getSlug = async (trans: Transaction, question: string) => { const getSlug = async (question: string) => {
const proposedSlug = slugify(question) const proposedSlug = slugify(question)
const preexistingContract = await getContractFromSlug(trans, proposedSlug) const preexistingContract = await getContractFromSlug(proposedSlug)
return preexistingContract return preexistingContract
? proposedSlug + '-' + randomString() ? proposedSlug + '-' + randomString()
@ -351,42 +338,46 @@ const getSlug = async (trans: Transaction, question: string) => {
const firestore = admin.firestore() const firestore = admin.firestore()
async function getContractFromSlug(trans: Transaction, slug: string) { export async function getContractFromSlug(slug: string) {
const snap = await trans.get( const snap = await firestore
firestore.collection('contracts').where('slug', '==', slug) .collection('contracts')
) .where('slug', '==', slug)
.get()
return snap.empty ? undefined : (snap.docs[0].data() as Contract) return snap.empty ? undefined : (snap.docs[0].data() as Contract)
} }
async function createGroupLinks( async function createGroupLinks(
trans: Transaction,
group: Group, group: Group,
contractIds: string[], contractIds: string[],
userId: string userId: string
) { ) {
for (const contractId of contractIds) { for (const contractId of contractIds) {
const contractRef = firestore.collection('contracts').doc(contractId) const contract = await getContract(contractId)
const contract = (await trans.get(contractRef)).data() as Contract
if (!contract?.groupSlugs?.includes(group.slug)) { if (!contract?.groupSlugs?.includes(group.slug)) {
await trans.update(contractRef, { await firestore
groupSlugs: uniq([group.slug, ...(contract?.groupSlugs ?? [])]), .collection('contracts')
}) .doc(contractId)
.update({
groupSlugs: uniq([group.slug, ...(contract?.groupSlugs ?? [])]),
})
} }
if (!contract?.groupLinks?.map((gl) => gl.groupId).includes(group.id)) { if (!contract?.groupLinks?.map((gl) => gl.groupId).includes(group.id)) {
await trans.update(contractRef, { await firestore
groupLinks: [ .collection('contracts')
{ .doc(contractId)
groupId: group.id, .update({
name: group.name, groupLinks: [
slug: group.slug, {
userId, groupId: group.id,
createdTime: Date.now(), name: group.name,
} as GroupLink, slug: group.slug,
...(contract?.groupLinks ?? []), userId,
], createdTime: Date.now(),
}) } as GroupLink,
...(contract?.groupLinks ?? []),
],
})
} }
} }
} }