Serious business API validation & big cleanup of createContract, placeBet (#302)

* Add the great Zod as a dependency to help us

* Tweak eslint

* Rewrite a ton of stuff in createContract and placeBet

* Clean up error reporting in API

* Make sure the UI is enforcing validated limits on lengths

* Remove unnecessary Math.abs

* Better type on `BetInfo`

* Kill `manaLimitPerUser`

* Clean up hacky parameters on bet info functions

* Validate `closeTime` as a valid timestamp in the future
This commit is contained in:
Marshall Polaris 2022-05-26 14:37:51 -07:00 committed by GitHub
parent 09e93779fb
commit 5217270073
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 221 additions and 272 deletions

View File

@ -21,6 +21,8 @@ module.exports = {
}, },
], ],
rules: { rules: {
'no-extra-semi': 'off',
'no-unused-vars': 'off',
'no-constant-condition': ['error', { checkLoops: false }], 'no-constant-condition': ['error', { checkLoops: false }],
'lodash/import-scope': [2, 'member'], 'lodash/import-scope': [2, 'member'],
}, },

View File

@ -31,8 +31,6 @@ export type FullContract<
closeEmailsSent?: number closeEmailsSent?: number
manaLimitPerUser?: number
volume: number volume: number
volume24Hours: number volume24Hours: number
volume7Days: number volume7Days: number
@ -97,8 +95,12 @@ export type Numeric = {
} }
export type outcomeType = 'BINARY' | 'MULTI' | 'FREE_RESPONSE' | 'NUMERIC' export type outcomeType = 'BINARY' | 'MULTI' | 'FREE_RESPONSE' | 'NUMERIC'
export const OUTCOME_TYPES = ['BINARY', 'MULTI', 'FREE_RESPONSE', 'NUMERIC'] export const OUTCOME_TYPES = [
'BINARY',
'MULTI',
'FREE_RESPONSE',
'NUMERIC',
] as const
export const MAX_QUESTION_LENGTH = 480 export const MAX_QUESTION_LENGTH = 480
export const MAX_DESCRIPTION_LENGTH = 10000 export const MAX_DESCRIPTION_LENGTH = 10000
export const MAX_TAG_LENGTH = 60 export const MAX_TAG_LENGTH = 60

View File

@ -18,18 +18,25 @@ import {
Multi, Multi,
NumericContract, NumericContract,
} from './contract' } from './contract'
import { User } from './user'
import { noFees } from './fees' import { noFees } from './fees'
import { addObjects } from './util/object' import { addObjects } from './util/object'
import { NUMERIC_FIXED_VAR } from './numeric-constants' import { NUMERIC_FIXED_VAR } from './numeric-constants'
export type CandidateBet<T extends Bet> = Omit<T, 'id' | 'userId'>
export type BetInfo = {
newBet: CandidateBet<Bet>
newPool?: { [outcome: string]: number }
newTotalShares?: { [outcome: string]: number }
newTotalBets?: { [outcome: string]: number }
newTotalLiquidity?: number
newP?: number
}
export const getNewBinaryCpmmBetInfo = ( export const getNewBinaryCpmmBetInfo = (
user: User,
outcome: 'YES' | 'NO', outcome: 'YES' | 'NO',
amount: number, amount: number,
contract: FullContract<CPMM, Binary>, contract: FullContract<CPMM, Binary>,
loanAmount: number, loanAmount: number
newBetId: string
) => { ) => {
const { shares, newPool, newP, fees } = calculateCpmmPurchase( const { shares, newPool, newP, fees } = calculateCpmmPurchase(
contract, contract,
@ -37,15 +44,11 @@ export const getNewBinaryCpmmBetInfo = (
outcome outcome
) )
const newBalance = user.balance - (amount - loanAmount)
const { pool, p, totalLiquidity } = contract const { pool, p, totalLiquidity } = contract
const probBefore = getCpmmProbability(pool, p) const probBefore = getCpmmProbability(pool, p)
const probAfter = getCpmmProbability(newPool, newP) const probAfter = getCpmmProbability(newPool, newP)
const newBet: Bet = { const newBet: CandidateBet<Bet> = {
id: newBetId,
userId: user.id,
contractId: contract.id, contractId: contract.id,
amount, amount,
shares, shares,
@ -60,16 +63,14 @@ export const getNewBinaryCpmmBetInfo = (
const { liquidityFee } = fees const { liquidityFee } = fees
const newTotalLiquidity = (totalLiquidity ?? 0) + liquidityFee const newTotalLiquidity = (totalLiquidity ?? 0) + liquidityFee
return { newBet, newPool, newP, newBalance, newTotalLiquidity, fees } return { newBet, newPool, newP, newTotalLiquidity }
} }
export const getNewBinaryDpmBetInfo = ( export const getNewBinaryDpmBetInfo = (
user: User,
outcome: 'YES' | 'NO', outcome: 'YES' | 'NO',
amount: number, amount: number,
contract: FullContract<DPM, Binary>, contract: FullContract<DPM, Binary>,
loanAmount: number, loanAmount: number
newBetId: string
) => { ) => {
const { YES: yesPool, NO: noPool } = contract.pool const { YES: yesPool, NO: noPool } = contract.pool
@ -97,9 +98,7 @@ export const getNewBinaryDpmBetInfo = (
const probBefore = getDpmProbability(contract.totalShares) const probBefore = getDpmProbability(contract.totalShares)
const probAfter = getDpmProbability(newTotalShares) const probAfter = getDpmProbability(newTotalShares)
const newBet: Bet = { const newBet: CandidateBet<Bet> = {
id: newBetId,
userId: user.id,
contractId: contract.id, contractId: contract.id,
amount, amount,
loanAmount, loanAmount,
@ -111,18 +110,14 @@ export const getNewBinaryDpmBetInfo = (
fees: noFees, fees: noFees,
} }
const newBalance = user.balance - (amount - loanAmount) return { newBet, newPool, newTotalShares, newTotalBets }
return { newBet, newPool, newTotalShares, newTotalBets, newBalance }
} }
export const getNewMultiBetInfo = ( export const getNewMultiBetInfo = (
user: User,
outcome: string, outcome: string,
amount: number, amount: number,
contract: FullContract<DPM, Multi | FreeResponse>, contract: FullContract<DPM, Multi | FreeResponse>,
loanAmount: number, loanAmount: number
newBetId: string
) => { ) => {
const { pool, totalShares, totalBets } = contract const { pool, totalShares, totalBets } = contract
@ -140,9 +135,7 @@ export const getNewMultiBetInfo = (
const probBefore = getDpmOutcomeProbability(totalShares, outcome) const probBefore = getDpmOutcomeProbability(totalShares, outcome)
const probAfter = getDpmOutcomeProbability(newTotalShares, outcome) const probAfter = getDpmOutcomeProbability(newTotalShares, outcome)
const newBet: Bet = { const newBet: CandidateBet<Bet> = {
id: newBetId,
userId: user.id,
contractId: contract.id, contractId: contract.id,
amount, amount,
loanAmount, loanAmount,
@ -154,18 +147,14 @@ export const getNewMultiBetInfo = (
fees: noFees, fees: noFees,
} }
const newBalance = user.balance - (amount - loanAmount) return { newBet, newPool, newTotalShares, newTotalBets }
return { newBet, newPool, newTotalShares, newTotalBets, newBalance }
} }
export const getNumericBetsInfo = ( export const getNumericBetsInfo = (
user: User,
value: number, value: number,
outcome: string, outcome: string,
amount: number, amount: number,
contract: NumericContract, contract: NumericContract
newBetId: string
) => { ) => {
const { pool, totalShares, totalBets } = contract const { pool, totalShares, totalBets } = contract
@ -187,9 +176,7 @@ export const getNumericBetsInfo = (
const probBefore = getDpmOutcomeProbability(totalShares, outcome) const probBefore = getDpmOutcomeProbability(totalShares, outcome)
const probAfter = getDpmOutcomeProbability(newTotalShares, outcome) const probAfter = getDpmOutcomeProbability(newTotalShares, outcome)
const newBet: NumericBet = { const newBet: CandidateBet<NumericBet> = {
id: newBetId,
userId: user.id,
contractId: contract.id, contractId: contract.id,
value, value,
amount, amount,
@ -203,9 +190,7 @@ export const getNumericBetsInfo = (
fees: noFees, fees: noFees,
} }
const newBalance = user.balance - amount return { newBet, newPool, newTotalShares, newTotalBets }
return { newBet, newPool, newTotalShares, newTotalBets, newBalance }
} }
export const getLoanAmount = (yourBets: Bet[], newBetAmount: number) => { export const getLoanAmount = (yourBets: Bet[], newBetAmount: number) => {

View File

@ -27,8 +27,7 @@ export function getNewContract(
// used for numeric markets // used for numeric markets
bucketCount: number, bucketCount: number,
min: number, min: number,
max: number, max: number
manaLimitPerUser: number
) { ) {
const tags = parseTags( const tags = parseTags(
`${question} ${description} ${extraTags.map((tag) => `#${tag}`).join(' ')}` `${question} ${description} ${extraTags.map((tag) => `#${tag}`).join(' ')}`
@ -70,7 +69,6 @@ export function getNewContract(
liquidityFee: 0, liquidityFee: 0,
platformFee: 0, platformFee: 0,
}, },
manaLimitPerUser,
}) })
return contract as Contract return contract as Contract

View File

@ -17,6 +17,7 @@ module.exports = {
}, },
], ],
rules: { rules: {
'no-extra-semi': 'off',
'no-unused-vars': 'off', 'no-unused-vars': 'off',
'no-constant-condition': ['error', { checkLoops: false }], 'no-constant-condition': ['error', { checkLoops: false }],
'lodash/import-scope': [2, 'member'], 'lodash/import-scope': [2, 'member'],

View File

@ -28,7 +28,8 @@
"mailgun-js": "0.22.0", "mailgun-js": "0.22.0",
"module-alias": "2.2.2", "module-alias": "2.2.2",
"react-query": "3.39.0", "react-query": "3.39.0",
"stripe": "8.194.0" "stripe": "8.194.0",
"zod": "3.17.2"
}, },
"devDependencies": { "devDependencies": {
"@types/mailgun-js": "0.22.12", "@types/mailgun-js": "0.22.12",

View File

@ -1,6 +1,7 @@
import * as admin from 'firebase-admin' import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions' import * as functions from 'firebase-functions'
import * as Cors from 'cors' import * as Cors from 'cors'
import { z } from 'zod'
import { User, PrivateUser } from '../../common/user' import { User, PrivateUser } from '../../common/user'
import { import {
@ -8,10 +9,11 @@ import {
CORS_ORIGIN_LOCALHOST, CORS_ORIGIN_LOCALHOST,
} from '../../common/envs/constants' } from '../../common/envs/constants'
type Output = Record<string, unknown>
type Request = functions.https.Request type Request = functions.https.Request
type Response = functions.Response type Response = functions.Response
type Handler = (req: Request, res: Response) => Promise<any>
type AuthedUser = [User, PrivateUser] type AuthedUser = [User, PrivateUser]
type Handler = (req: Request, user: AuthedUser) => Promise<Output>
type JwtCredentials = { kind: 'jwt'; data: admin.auth.DecodedIdToken } type JwtCredentials = { kind: 'jwt'; data: admin.auth.DecodedIdToken }
type KeyCredentials = { kind: 'key'; data: string } type KeyCredentials = { kind: 'key'; data: string }
type Credentials = JwtCredentials | KeyCredentials type Credentials = JwtCredentials | KeyCredentials
@ -19,10 +21,13 @@ type Credentials = JwtCredentials | KeyCredentials
export class APIError { export class APIError {
code: number code: number
msg: string msg: string
constructor(code: number, msg: string) { details: unknown
constructor(code: number, msg: string, details?: unknown) {
this.code = code this.code = code
this.msg = msg this.msg = msg
this.details = details
} }
toJson() {}
} }
export const parseCredentials = async (req: Request): Promise<Credentials> => { export const parseCredentials = async (req: Request): Promise<Credentials> => {
@ -40,14 +45,11 @@ export const parseCredentials = async (req: Request): Promise<Credentials> => {
case 'Bearer': case 'Bearer':
try { try {
const jwt = await admin.auth().verifyIdToken(payload) const jwt = await admin.auth().verifyIdToken(payload)
if (!jwt.user_id) {
throw new APIError(403, 'JWT must contain Manifold user ID.')
}
return { kind: 'jwt', data: jwt } return { kind: 'jwt', data: jwt }
} catch (err) { } catch (err) {
// This is somewhat suspicious, so get it into the firebase console // This is somewhat suspicious, so get it into the firebase console
functions.logger.error('Error verifying Firebase JWT: ', err) functions.logger.error('Error verifying Firebase JWT: ', err)
throw new APIError(403, `Error validating token: ${err}.`) throw new APIError(403, 'Error validating token.')
} }
case 'Key': case 'Key':
return { kind: 'key', data: payload } return { kind: 'key', data: payload }
@ -63,6 +65,9 @@ export const lookupUser = async (creds: Credentials): Promise<AuthedUser> => {
switch (creds.kind) { switch (creds.kind) {
case 'jwt': { case 'jwt': {
const { user_id } = creds.data const { user_id } = creds.data
if (typeof user_id !== 'string') {
throw new APIError(403, 'JWT must contain Manifold user ID.')
}
const [userSnap, privateUserSnap] = await Promise.all([ const [userSnap, privateUserSnap] = await Promise.all([
users.doc(user_id).get(), users.doc(user_id).get(),
privateUsers.doc(user_id).get(), privateUsers.doc(user_id).get(),
@ -109,6 +114,27 @@ export const applyCors = (
}) })
} }
export const zTimestamp = () => {
return z.preprocess((arg) => {
return typeof arg == 'number' ? new Date(arg) : undefined
}, z.date())
}
export const validate = <T extends z.ZodTypeAny>(schema: T, val: unknown) => {
const result = schema.safeParse(val)
if (!result.success) {
const issues = result.error.issues.map((i) => {
return {
field: i.path.join('.') || null,
error: i.message,
}
})
throw new APIError(400, 'Error validating request.', issues)
} else {
return result.data as z.infer<T>
}
}
export const newEndpoint = (methods: [string], fn: Handler) => export const newEndpoint = (methods: [string], fn: Handler) =>
functions.runWith({ minInstances: 1 }).https.onRequest(async (req, res) => { functions.runWith({ minInstances: 1 }).https.onRequest(async (req, res) => {
await applyCors(req, res, { await applyCors(req, res, {
@ -120,12 +146,17 @@ export const newEndpoint = (methods: [string], fn: Handler) =>
const allowed = methods.join(', ') const allowed = methods.join(', ')
throw new APIError(405, `This endpoint supports only ${allowed}.`) throw new APIError(405, `This endpoint supports only ${allowed}.`)
} }
res.status(200).json(await fn(req, res)) const authedUser = await lookupUser(await parseCredentials(req))
res.status(200).json(await fn(req, authedUser))
} catch (e) { } catch (e) {
if (e instanceof APIError) { if (e instanceof APIError) {
// Emit a 200 anyway here for now, for backwards compatibility const output: { [k: string]: unknown } = { message: e.msg }
res.status(e.code).json({ message: e.msg }) if (e.details != null) {
output.details = e.details
}
res.status(e.code).json(output)
} else { } else {
functions.logger.error(e)
res.status(500).json({ message: 'An unknown error occurred.' }) res.status(500).json({ message: 'An unknown error occurred.' })
} }
} }

View File

@ -12,7 +12,6 @@ import { getNewMultiBetInfo } from '../../common/new-bet'
import { Answer, MAX_ANSWER_LENGTH } from '../../common/answer' import { Answer, MAX_ANSWER_LENGTH } from '../../common/answer'
import { getContract, getValues } from './utils' import { getContract, getValues } from './utils'
import { sendNewAnswerEmail } from './emails' import { sendNewAnswerEmail } from './emails'
import { Bet } from '../../common/bet'
export const createAnswer = functions.runWith({ minInstances: 1 }).https.onCall( export const createAnswer = functions.runWith({ minInstances: 1 }).https.onCall(
async ( async (
@ -61,11 +60,6 @@ export const createAnswer = functions.runWith({ minInstances: 1 }).https.onCall(
if (closeTime && Date.now() > closeTime) if (closeTime && Date.now() > closeTime)
return { status: 'error', message: 'Trading is closed' } return { status: 'error', message: 'Trading is closed' }
const yourBetsSnap = await transaction.get(
contractDoc.collection('bets').where('userId', '==', userId)
)
const yourBets = yourBetsSnap.docs.map((doc) => doc.data() as Bet)
const [lastAnswer] = await getValues<Answer>( const [lastAnswer] = await getValues<Answer>(
firestore firestore
.collection(`contracts/${contractId}/answers`) .collection(`contracts/${contractId}/answers`)
@ -99,23 +93,20 @@ export const createAnswer = functions.runWith({ minInstances: 1 }).https.onCall(
} }
transaction.create(newAnswerDoc, answer) transaction.create(newAnswerDoc, answer)
const newBetDoc = firestore const loanAmount = 0
.collection(`contracts/${contractId}/bets`)
.doc()
const loanAmount = 0 // getLoanAmount(yourBets, amount) const { newBet, newPool, newTotalShares, newTotalBets } =
const { newBet, newPool, newTotalShares, newTotalBets, newBalance } =
getNewMultiBetInfo( getNewMultiBetInfo(
user,
answerId, answerId,
amount, amount,
contract as FullContract<DPM, FreeResponse>, contract as FullContract<DPM, FreeResponse>,
loanAmount, loanAmount
newBetDoc.id
) )
transaction.create(newBetDoc, newBet) const newBalance = user.balance - amount
const betDoc = firestore.collection(`contracts/${contractId}/bets`).doc()
transaction.create(betDoc, { id: betDoc.id, userId: user.id, ...newBet })
transaction.update(userDoc, { balance: newBalance })
transaction.update(contractDoc, { transaction.update(contractDoc, {
pool: newPool, pool: newPool,
totalShares: newTotalShares, totalShares: newTotalShares,
@ -124,13 +115,7 @@ export const createAnswer = functions.runWith({ minInstances: 1 }).https.onCall(
volume: volume + amount, volume: volume + amount,
}) })
if (!isFinite(newBalance)) { return { status: 'success', answerId, betId: betDoc.id, answer }
throw new Error('Invalid user balance for ' + user.username)
}
transaction.update(userDoc, { balance: newBalance })
return { status: 'success', answerId, betId: newBetDoc.id, answer }
}) })
const { answer } = result const { answer } = result

View File

@ -1,4 +1,5 @@
import * as admin from 'firebase-admin' import * as admin from 'firebase-admin'
import { z } from 'zod'
import { import {
Binary, Binary,
@ -17,7 +18,7 @@ import { slugify } from '../../common/util/slugify'
import { randomString } from '../../common/util/random' import { randomString } from '../../common/util/random'
import { chargeUser } from './utils' import { chargeUser } from './utils'
import { APIError, newEndpoint, parseCredentials, lookupUser } from './api' import { APIError, newEndpoint, validate, zTimestamp } from './api'
import { import {
FIXED_ANTE, FIXED_ANTE,
@ -26,66 +27,45 @@ import {
getFreeAnswerAnte, getFreeAnswerAnte,
getNumericAnte, getNumericAnte,
HOUSE_LIQUIDITY_PROVIDER_ID, HOUSE_LIQUIDITY_PROVIDER_ID,
MINIMUM_ANTE,
} from '../../common/antes' } from '../../common/antes'
import { getNoneAnswer } from '../../common/answer' import { getNoneAnswer } from '../../common/answer'
import { getNewContract } from '../../common/new-contract' import { getNewContract } from '../../common/new-contract'
import { NUMERIC_BUCKET_COUNT } from '../../common/numeric-constants' import { NUMERIC_BUCKET_COUNT } from '../../common/numeric-constants'
export const createContract = newEndpoint(['POST'], async (req, _res) => { const bodySchema = z.object({
const [creator, _privateUser] = await lookupUser(await parseCredentials(req)) question: z.string().min(1).max(MAX_QUESTION_LENGTH),
let { description: z.string().max(MAX_DESCRIPTION_LENGTH),
question, tags: z.array(z.string().min(1).max(MAX_TAG_LENGTH)).optional(),
outcomeType, closeTime: zTimestamp().refine(
description, (date) => date.getTime() > new Date().getTime(),
initialProb, 'Close time must be in the future.'
closeTime, ),
tags, outcomeType: z.enum(OUTCOME_TYPES),
min, })
max,
manaLimitPerUser,
} = req.body || {}
if (!question || typeof question != 'string') const binarySchema = z.object({
throw new APIError(400, 'Missing or invalid question field') initialProb: z.number().min(1).max(99),
})
question = question.slice(0, MAX_QUESTION_LENGTH) const numericSchema = z.object({
min: z.number(),
max: z.number(),
})
if (typeof description !== 'string') export const createContract = newEndpoint(['POST'], async (req, [user, _]) => {
throw new APIError(400, 'Invalid description field') const { question, description, tags, closeTime, outcomeType } = validate(
bodySchema,
description = description.slice(0, MAX_DESCRIPTION_LENGTH) req.body
if (tags !== undefined && !Array.isArray(tags))
throw new APIError(400, 'Invalid tags field')
tags = (tags || []).map((tag: string) =>
tag.toString().slice(0, MAX_TAG_LENGTH)
) )
outcomeType = outcomeType ?? 'BINARY' let min, max, initialProb
if (outcomeType === 'NUMERIC') {
if (!OUTCOME_TYPES.includes(outcomeType)) ;({ min, max } = validate(numericSchema, req.body))
throw new APIError(400, 'Invalid outcomeType') if (max - min <= 0.01) throw new APIError(400, 'Invalid range.')
}
if ( if (outcomeType === 'BINARY') {
outcomeType === 'NUMERIC' && ;({ initialProb } = validate(binarySchema, req.body))
!( }
min !== undefined &&
max !== undefined &&
isFinite(min) &&
isFinite(max) &&
min < max &&
max - min > 0.01
)
)
throw new APIError(400, 'Invalid range')
if (
outcomeType === 'BINARY' &&
(!initialProb || initialProb < 1 || initialProb > 99)
)
throw new APIError(400, 'Invalid initial probability')
// Uses utc time on server: // Uses utc time on server:
const today = new Date() const today = new Date()
@ -96,7 +76,7 @@ export const createContract = newEndpoint(['POST'], async (req, _res) => {
const userContractsCreatedTodaySnapshot = await firestore const userContractsCreatedTodaySnapshot = await firestore
.collection(`contracts`) .collection(`contracts`)
.where('creatorId', '==', creator.id) .where('creatorId', '==', user.id)
.where('createdTime', '>=', freeMarketResetTime) .where('createdTime', '>=', freeMarketResetTime)
.get() .get()
console.log('free market reset time: ', freeMarketResetTime) console.log('free market reset time: ', freeMarketResetTime)
@ -104,18 +84,9 @@ export const createContract = newEndpoint(['POST'], async (req, _res) => {
const ante = FIXED_ANTE const ante = FIXED_ANTE
if (
ante === undefined ||
ante < MINIMUM_ANTE ||
(ante > creator.balance && !isFree) ||
isNaN(ante) ||
!isFinite(ante)
)
throw new APIError(400, 'Invalid ante')
console.log( console.log(
'creating contract for', 'creating contract for',
creator.username, user.username,
'on', 'on',
question, question,
'ante:', 'ante:',
@ -123,31 +94,28 @@ export const createContract = newEndpoint(['POST'], async (req, _res) => {
) )
const slug = await getSlug(question) const slug = await getSlug(question)
const contractRef = firestore.collection('contracts').doc() const contractRef = firestore.collection('contracts').doc()
const contract = getNewContract( const contract = getNewContract(
contractRef.id, contractRef.id,
slug, slug,
creator, user,
question, question,
outcomeType, outcomeType,
description, description,
initialProb, initialProb ?? 0,
ante, ante,
closeTime, closeTime.getTime(),
tags ?? [], tags ?? [],
NUMERIC_BUCKET_COUNT, NUMERIC_BUCKET_COUNT,
min ?? 0, min ?? 0,
max ?? 0, max ?? 0
manaLimitPerUser ?? 0
) )
if (!isFree && ante) await chargeUser(creator.id, ante, true) if (!isFree && ante) await chargeUser(user.id, ante, true)
await contractRef.create(contract) await contractRef.create(contract)
const providerId = isFree ? HOUSE_LIQUIDITY_PROVIDER_ID : creator.id const providerId = isFree ? HOUSE_LIQUIDITY_PROVIDER_ID : user.id
if (outcomeType === 'BINARY' && contract.mechanism === 'dpm-2') { if (outcomeType === 'BINARY' && contract.mechanism === 'dpm-2') {
const yesBetDoc = firestore const yesBetDoc = firestore
@ -157,7 +125,7 @@ export const createContract = newEndpoint(['POST'], async (req, _res) => {
const noBetDoc = firestore.collection(`contracts/${contract.id}/bets`).doc() const noBetDoc = firestore.collection(`contracts/${contract.id}/bets`).doc()
const { yesBet, noBet } = getAnteBets( const { yesBet, noBet } = getAnteBets(
creator, user,
contract as FullContract<DPM, Binary>, contract as FullContract<DPM, Binary>,
yesBetDoc.id, yesBetDoc.id,
noBetDoc.id noBetDoc.id
@ -183,7 +151,7 @@ export const createContract = newEndpoint(['POST'], async (req, _res) => {
.collection(`contracts/${contract.id}/answers`) .collection(`contracts/${contract.id}/answers`)
.doc('0') .doc('0')
const noneAnswer = getNoneAnswer(contract.id, creator) const noneAnswer = getNoneAnswer(contract.id, user)
await noneAnswerDoc.set(noneAnswer) await noneAnswerDoc.set(noneAnswer)
const anteBetDoc = firestore const anteBetDoc = firestore
@ -202,7 +170,7 @@ export const createContract = newEndpoint(['POST'], async (req, _res) => {
.doc() .doc()
const anteBet = getNumericAnte( const anteBet = getNumericAnte(
creator, user,
contract as FullContract<DPM, Numeric>, contract as FullContract<DPM, Numeric>,
ante, ante,
anteBetDoc.id anteBetDoc.id

View File

@ -1,122 +1,95 @@
import * as admin from 'firebase-admin' import * as admin from 'firebase-admin'
import { z } from 'zod'
import { APIError, newEndpoint, parseCredentials, lookupUser } from './api' import { APIError, newEndpoint, validate } from './api'
import { Contract } from '../../common/contract' import { Contract } from '../../common/contract'
import { User } from '../../common/user' import { User } from '../../common/user'
import { import {
BetInfo,
getNewBinaryCpmmBetInfo, getNewBinaryCpmmBetInfo,
getNewBinaryDpmBetInfo, getNewBinaryDpmBetInfo,
getNewMultiBetInfo, getNewMultiBetInfo,
getNumericBetsInfo, getNumericBetsInfo,
} from '../../common/new-bet' } from '../../common/new-bet'
import { addObjects, removeUndefinedProps } from '../../common/util/object' import { addObjects, removeUndefinedProps } from '../../common/util/object'
import { Bet } from '../../common/bet'
import { redeemShares } from './redeem-shares' import { redeemShares } from './redeem-shares'
import { Fees } from '../../common/fees'
export const placeBet = newEndpoint(['POST'], async (req, _res) => { const bodySchema = z.object({
const [bettor, _privateUser] = await lookupUser(await parseCredentials(req)) contractId: z.string(),
const { amount, outcome, contractId, value } = req.body || {} amount: z.number().gte(1),
})
if (amount < 1 || isNaN(amount) || !isFinite(amount)) const binarySchema = z.object({
throw new APIError(400, 'Invalid amount') outcome: z.enum(['YES', 'NO']),
})
if (outcome !== 'YES' && outcome !== 'NO' && isNaN(+outcome)) const freeResponseSchema = z.object({
throw new APIError(400, 'Invalid outcome') outcome: z.string(),
})
if (value !== undefined && !isFinite(value)) const numericSchema = z.object({
throw new APIError(400, 'Invalid value') outcome: z.string(),
value: z.number(),
})
// run as transaction to prevent race conditions export const placeBet = newEndpoint(['POST'], async (req, [bettor, _]) => {
return await firestore const { amount, contractId } = validate(bodySchema, req.body)
.runTransaction(async (transaction) => {
const result = await firestore.runTransaction(async (trans) => {
const userDoc = firestore.doc(`users/${bettor.id}`) const userDoc = firestore.doc(`users/${bettor.id}`)
const userSnap = await transaction.get(userDoc) const userSnap = await trans.get(userDoc)
if (!userSnap.exists) throw new APIError(400, 'User not found') if (!userSnap.exists) throw new APIError(400, 'User not found.')
const user = userSnap.data() as User const user = userSnap.data() as User
if (user.balance < amount) throw new APIError(400, 'Insufficient balance.')
const contractDoc = firestore.doc(`contracts/${contractId}`) const contractDoc = firestore.doc(`contracts/${contractId}`)
const contractSnap = await transaction.get(contractDoc) const contractSnap = await trans.get(contractDoc)
if (!contractSnap.exists) throw new APIError(400, 'Invalid contract') if (!contractSnap.exists) throw new APIError(400, 'Contract not found.')
const contract = contractSnap.data() as Contract const contract = contractSnap.data() as Contract
const loanAmount = 0
const { closeTime, outcomeType, mechanism, collectedFees, volume } = const { closeTime, outcomeType, mechanism, collectedFees, volume } =
contract contract
if (closeTime && Date.now() > closeTime) if (closeTime && Date.now() > closeTime)
throw new APIError(400, 'Trading is closed') throw new APIError(400, 'Trading is closed.')
const yourBetsSnap = await transaction.get(
contractDoc.collection('bets').where('userId', '==', bettor.id)
)
const yourBets = yourBetsSnap.docs.map((doc) => doc.data() as Bet)
const loanAmount = 0 // getLoanAmount(yourBets, amount)
if (user.balance < amount) throw new APIError(400, 'Insufficient balance')
if (outcomeType === 'FREE_RESPONSE') {
const answerSnap = await transaction.get(
contractDoc.collection('answers').doc(outcome)
)
if (!answerSnap.exists) throw new APIError(400, 'Invalid contract')
}
const newBetDoc = firestore
.collection(`contracts/${contractId}/bets`)
.doc()
const { const {
newBet, newBet,
newPool, newPool,
newTotalShares, newTotalShares,
newTotalBets, newTotalBets,
newBalance,
newTotalLiquidity, newTotalLiquidity,
fees,
newP, newP,
} = } = await (async (): Promise<BetInfo> => {
outcomeType === 'BINARY' if (outcomeType == 'BINARY' && mechanism == 'dpm-2') {
? mechanism === 'dpm-2' const { outcome } = validate(binarySchema, req.body)
? getNewBinaryDpmBetInfo( return getNewBinaryDpmBetInfo(outcome, amount, contract, loanAmount)
user, } else if (outcomeType == 'BINARY' && mechanism == 'cpmm-1') {
outcome as 'YES' | 'NO', const { outcome } = validate(binarySchema, req.body)
amount, return getNewBinaryCpmmBetInfo(outcome, amount, contract, loanAmount)
contract, } else if (outcomeType == 'FREE_RESPONSE' && mechanism == 'dpm-2') {
loanAmount, const { outcome } = validate(freeResponseSchema, req.body)
newBetDoc.id const answerDoc = contractDoc.collection('answers').doc(outcome)
) const answerSnap = await trans.get(answerDoc)
: (getNewBinaryCpmmBetInfo( if (!answerSnap.exists) throw new APIError(400, 'Invalid answer')
user, return getNewMultiBetInfo(outcome, amount, contract, loanAmount)
outcome as 'YES' | 'NO', } else if (outcomeType == 'NUMERIC' && mechanism == 'dpm-2') {
amount, const { outcome, value } = validate(numericSchema, req.body)
contract, return getNumericBetsInfo(value, outcome, amount, contract)
loanAmount, } else {
newBetDoc.id throw new APIError(500, 'Contract has invalid type/mechanism.')
) as any) }
: outcomeType === 'NUMERIC' && mechanism === 'dpm-2' })()
? getNumericBetsInfo(
user,
value,
outcome,
amount,
contract,
newBetDoc.id
)
: getNewMultiBetInfo(
user,
outcome,
amount,
contract as any,
loanAmount,
newBetDoc.id
)
if (newP !== undefined && !isFinite(newP)) { if (newP != null && !isFinite(newP)) {
throw new APIError(400, 'Trade rejected due to overflow error.') throw new APIError(400, 'Trade rejected due to overflow error.')
} }
transaction.create(newBetDoc, newBet) const newBalance = user.balance - amount - loanAmount
const betDoc = contractDoc.collection('bets').doc()
transaction.update( trans.create(betDoc, { id: betDoc.id, userId: user.id, ...newBet })
trans.update(userDoc, { balance: newBalance })
trans.update(
contractDoc, contractDoc,
removeUndefinedProps({ removeUndefinedProps({
pool: newPool, pool: newPool,
@ -124,23 +97,16 @@ export const placeBet = newEndpoint(['POST'], async (req, _res) => {
totalShares: newTotalShares, totalShares: newTotalShares,
totalBets: newTotalBets, totalBets: newTotalBets,
totalLiquidity: newTotalLiquidity, totalLiquidity: newTotalLiquidity,
collectedFees: addObjects<Fees>(fees ?? {}, collectedFees ?? {}), collectedFees: addObjects(newBet.fees, collectedFees),
volume: volume + Math.abs(amount), volume: volume + amount,
}) })
) )
if (!isFinite(newBalance)) { return { betId: betDoc.id }
throw new APIError(500, 'Invalid user balance for ' + user.username)
}
transaction.update(userDoc, { balance: newBalance })
return { betId: newBetDoc.id }
}) })
.then(async (result) => {
await redeemShares(bettor.id, contractId) await redeemShares(bettor.id, contractId)
return result return result
}) })
})
const firestore = admin.firestore() const firestore = admin.firestore()

View File

@ -102,12 +102,10 @@ function NumericBuyPanel(props: {
const betDisabled = isSubmitting || !betAmount || !bucketChoice || error const betDisabled = isSubmitting || !betAmount || !bucketChoice || error
const { newBet, newPool, newTotalShares, newTotalBets } = getNumericBetsInfo( const { newBet, newPool, newTotalShares, newTotalBets } = getNumericBetsInfo(
{ id: 'dummy', balance: 0 } as User, // a little hackish
value ?? 0, value ?? 0,
bucketChoice ?? 'NaN', bucketChoice ?? 'NaN',
betAmount ?? 0, betAmount ?? 0,
contract, contract
'dummy id'
) )
const { probAfter: outcomeProb, shares } = newBet const { probAfter: outcomeProb, shares } = newBet

View File

@ -5,6 +5,7 @@ import { Contract, updateContract } from 'web/lib/firebase/contracts'
import { Col } from './layout/col' import { Col } from './layout/col'
import { Row } from './layout/row' import { Row } from './layout/row'
import { TagsList } from './tags-list' import { TagsList } from './tags-list'
import { MAX_TAG_LENGTH } from 'common/contract'
export function TagsInput(props: { contract: Contract; className?: string }) { export function TagsInput(props: { contract: Contract; className?: string }) {
const { contract, className } = props const { contract, className } = props
@ -36,6 +37,7 @@ export function TagsInput(props: { contract: Contract; className?: string }) {
className="input input-sm input-bordered resize-none" className="input input-sm input-bordered resize-none"
disabled={isSubmitting} disabled={isSubmitting}
value={tagText} value={tagText}
maxLength={MAX_TAG_LENGTH}
onChange={(e) => setTagText(e.target.value || '')} onChange={(e) => setTagText(e.target.value || '')}
onKeyDown={(e) => { onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) { if (e.key === 'Enter' && !e.shiftKey) {

View File

@ -11,7 +11,11 @@ import { FIXED_ANTE, MINIMUM_ANTE } from 'common/antes'
import { InfoTooltip } from 'web/components/info-tooltip' import { InfoTooltip } from 'web/components/info-tooltip'
import { Page } from 'web/components/page' import { Page } from 'web/components/page'
import { Row } from 'web/components/layout/row' import { Row } from 'web/components/layout/row'
import { MAX_DESCRIPTION_LENGTH, outcomeType } from 'common/contract' import {
MAX_DESCRIPTION_LENGTH,
MAX_QUESTION_LENGTH,
outcomeType,
} from 'common/contract'
import { formatMoney } from 'common/util/format' import { formatMoney } from 'common/util/format'
import { useHasCreatedContractToday } from 'web/hooks/use-has-created-contract-today' import { useHasCreatedContractToday } from 'web/hooks/use-has-created-contract-today'
import { removeUndefinedProps } from 'common/util/object' import { removeUndefinedProps } from 'common/util/object'
@ -37,6 +41,7 @@ export default function Create() {
placeholder="e.g. Will the Democrats win the 2024 US presidential election?" placeholder="e.g. Will the Democrats win the 2024 US presidential election?"
className="input input-bordered resize-none" className="input input-bordered resize-none"
autoFocus autoFocus
maxLength={MAX_QUESTION_LENGTH}
value={question} value={question}
onChange={(e) => setQuestion(e.target.value || '')} onChange={(e) => setQuestion(e.target.value || '')}
/> />

View File

@ -5410,3 +5410,8 @@ yocto-queue@^0.1.0:
version "0.1.0" version "0.1.0"
resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b"
integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==
zod@3.17.2:
version "3.17.2"
resolved "https://registry.yarnpkg.com/zod/-/zod-3.17.2.tgz#d20b32146a3b5068f8f71768b4f9a4bfe52cddb0"
integrity sha512-L8UPS2J/F3dIA8gsPTvGjd8wSRuwR1Td4AqR2Nw8r8BgcLIbZZ5/tCII7hbTLXTQDhxUnnsFdHwpETGajt5i3A==