2021-12-11 00:06:17 +00:00
|
|
|
import * as admin from 'firebase-admin'
|
2022-05-26 21:37:51 +00:00
|
|
|
import { z } from 'zod'
|
2022-07-10 18:05:44 +00:00
|
|
|
import {
|
|
|
|
DocumentReference,
|
|
|
|
FieldValue,
|
|
|
|
Query,
|
|
|
|
Transaction,
|
|
|
|
} from 'firebase-admin/firestore'
|
|
|
|
import { groupBy, mapValues, sumBy } from 'lodash'
|
2021-12-11 00:06:17 +00:00
|
|
|
|
2022-05-26 21:37:51 +00:00
|
|
|
import { APIError, newEndpoint, validate } from './api'
|
2022-06-10 01:25:05 +00:00
|
|
|
import { Contract, CPMM_MIN_POOL_QTY } from '../../common/contract'
|
2022-05-15 17:39:42 +00:00
|
|
|
import { User } from '../../common/user'
|
2022-03-02 03:31:48 +00:00
|
|
|
import {
|
2022-05-26 21:37:51 +00:00
|
|
|
BetInfo,
|
2022-07-10 18:05:44 +00:00
|
|
|
getBinaryCpmmBetInfo,
|
2022-03-02 03:31:48 +00:00
|
|
|
getNewMultiBetInfo,
|
2022-05-19 17:42:03 +00:00
|
|
|
getNumericBetsInfo,
|
2022-05-15 17:39:42 +00:00
|
|
|
} from '../../common/new-bet'
|
|
|
|
import { addObjects, removeUndefinedProps } from '../../common/util/object'
|
2022-07-10 18:05:44 +00:00
|
|
|
import { LimitBet } from '../../common/bet'
|
|
|
|
import { floatingEqual } from '../../common/util/math'
|
2022-03-15 22:27:51 +00:00
|
|
|
import { redeemShares } from './redeem-shares'
|
2022-06-17 03:57:03 +00:00
|
|
|
import { log } from './utils'
|
2021-12-11 00:06:17 +00:00
|
|
|
|
2022-05-26 21:37:51 +00:00
|
|
|
const bodySchema = z.object({
|
|
|
|
contractId: z.string(),
|
|
|
|
amount: z.number().gte(1),
|
|
|
|
})
|
2022-05-17 04:43:40 +00:00
|
|
|
|
2022-05-26 21:37:51 +00:00
|
|
|
const binarySchema = z.object({
|
|
|
|
outcome: z.enum(['YES', 'NO']),
|
2022-07-10 18:05:44 +00:00
|
|
|
limitProb: z.number().gte(0.001).lte(0.999).optional(),
|
2022-05-26 21:37:51 +00:00
|
|
|
})
|
2022-05-17 04:43:40 +00:00
|
|
|
|
2022-05-26 21:37:51 +00:00
|
|
|
const freeResponseSchema = z.object({
|
|
|
|
outcome: z.string(),
|
|
|
|
})
|
2022-05-17 04:43:40 +00:00
|
|
|
|
2022-05-26 21:37:51 +00:00
|
|
|
const numericSchema = z.object({
|
|
|
|
outcome: z.string(),
|
|
|
|
value: z.number(),
|
|
|
|
})
|
2022-05-17 04:43:40 +00:00
|
|
|
|
2022-06-29 23:47:06 +00:00
|
|
|
export const placebet = newEndpoint({}, async (req, auth) => {
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Inside endpoint handler.')
|
2022-05-26 21:37:51 +00:00
|
|
|
const { amount, contractId } = validate(bodySchema, req.body)
|
|
|
|
|
|
|
|
const result = await firestore.runTransaction(async (trans) => {
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Inside main transaction.')
|
2022-05-26 21:37:51 +00:00
|
|
|
const contractDoc = firestore.doc(`contracts/${contractId}`)
|
2022-06-11 00:51:55 +00:00
|
|
|
const userDoc = firestore.doc(`users/${auth.uid}`)
|
2022-07-02 23:24:03 +00:00
|
|
|
const [contractSnap, userSnap] = await trans.getAll(contractDoc, userDoc)
|
2022-05-26 21:37:51 +00:00
|
|
|
if (!contractSnap.exists) throw new APIError(400, 'Contract not found.')
|
2022-06-11 00:51:55 +00:00
|
|
|
if (!userSnap.exists) throw new APIError(400, 'User not found.')
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Loaded user and contract snapshots.')
|
2022-06-11 00:51:55 +00:00
|
|
|
|
2022-05-26 21:37:51 +00:00
|
|
|
const contract = contractSnap.data() as Contract
|
2022-06-11 00:51:55 +00:00
|
|
|
const user = userSnap.data() as User
|
|
|
|
if (user.balance < amount) throw new APIError(400, 'Insufficient balance.')
|
2022-05-26 21:37:51 +00:00
|
|
|
|
|
|
|
const loanAmount = 0
|
|
|
|
const { closeTime, outcomeType, mechanism, collectedFees, volume } =
|
|
|
|
contract
|
|
|
|
if (closeTime && Date.now() > closeTime)
|
|
|
|
throw new APIError(400, 'Trading is closed.')
|
|
|
|
|
|
|
|
const {
|
|
|
|
newBet,
|
|
|
|
newPool,
|
|
|
|
newTotalShares,
|
|
|
|
newTotalBets,
|
|
|
|
newTotalLiquidity,
|
|
|
|
newP,
|
2022-07-10 18:05:44 +00:00
|
|
|
makers,
|
|
|
|
} = await (async (): Promise<
|
|
|
|
BetInfo & {
|
|
|
|
makers?: maker[]
|
|
|
|
}
|
|
|
|
> => {
|
|
|
|
if (
|
|
|
|
(outcomeType == 'BINARY' || outcomeType === 'PSEUDO_NUMERIC') &&
|
2022-07-02 19:37:59 +00:00
|
|
|
mechanism == 'cpmm-1'
|
|
|
|
) {
|
2022-07-10 18:05:44 +00:00
|
|
|
const { outcome, limitProb } = validate(binarySchema, req.body)
|
|
|
|
|
|
|
|
const unfilledBetsSnap = await trans.get(
|
|
|
|
getUnfilledBetsQuery(contractDoc)
|
|
|
|
)
|
|
|
|
const unfilledBets = unfilledBetsSnap.docs.map((doc) => doc.data())
|
|
|
|
|
|
|
|
return getBinaryCpmmBetInfo(
|
|
|
|
outcome,
|
|
|
|
amount,
|
|
|
|
contract,
|
|
|
|
limitProb,
|
|
|
|
unfilledBets
|
|
|
|
)
|
2022-05-26 21:37:51 +00:00
|
|
|
} else if (outcomeType == 'FREE_RESPONSE' && mechanism == 'dpm-2') {
|
|
|
|
const { outcome } = validate(freeResponseSchema, req.body)
|
|
|
|
const answerDoc = contractDoc.collection('answers').doc(outcome)
|
|
|
|
const answerSnap = await trans.get(answerDoc)
|
|
|
|
if (!answerSnap.exists) throw new APIError(400, 'Invalid answer')
|
|
|
|
return getNewMultiBetInfo(outcome, amount, contract, loanAmount)
|
|
|
|
} else if (outcomeType == 'NUMERIC' && mechanism == 'dpm-2') {
|
|
|
|
const { outcome, value } = validate(numericSchema, req.body)
|
|
|
|
return getNumericBetsInfo(value, outcome, amount, contract)
|
|
|
|
} else {
|
|
|
|
throw new APIError(500, 'Contract has invalid type/mechanism.')
|
2022-05-17 04:43:40 +00:00
|
|
|
}
|
2022-05-26 21:37:51 +00:00
|
|
|
})()
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Calculated new bet information.')
|
2022-05-26 21:37:51 +00:00
|
|
|
|
2022-06-10 01:25:05 +00:00
|
|
|
if (
|
|
|
|
mechanism == 'cpmm-1' &&
|
|
|
|
(!newP ||
|
|
|
|
!isFinite(newP) ||
|
|
|
|
Math.min(...Object.values(newPool ?? {})) < CPMM_MIN_POOL_QTY)
|
|
|
|
) {
|
|
|
|
throw new APIError(400, 'Bet too large for current liquidity pool.')
|
2022-05-26 21:37:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const betDoc = contractDoc.collection('bets').doc()
|
|
|
|
trans.create(betDoc, { id: betDoc.id, userId: user.id, ...newBet })
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Created new bet document.')
|
2022-07-10 18:05:44 +00:00
|
|
|
|
|
|
|
if (makers) {
|
|
|
|
updateMakers(makers, betDoc.id, contractDoc, trans)
|
|
|
|
}
|
|
|
|
|
|
|
|
trans.update(userDoc, { balance: FieldValue.increment(-newBet.amount) })
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Updated user balance.')
|
2022-05-26 21:37:51 +00:00
|
|
|
trans.update(
|
|
|
|
contractDoc,
|
|
|
|
removeUndefinedProps({
|
|
|
|
pool: newPool,
|
|
|
|
p: newP,
|
|
|
|
totalShares: newTotalShares,
|
|
|
|
totalBets: newTotalBets,
|
|
|
|
totalLiquidity: newTotalLiquidity,
|
|
|
|
collectedFees: addObjects(newBet.fees, collectedFees),
|
2022-07-10 18:05:44 +00:00
|
|
|
volume: volume + newBet.amount,
|
2022-05-26 21:37:51 +00:00
|
|
|
})
|
|
|
|
)
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Updated contract properties.')
|
2022-05-26 21:37:51 +00:00
|
|
|
|
|
|
|
return { betId: betDoc.id }
|
|
|
|
})
|
|
|
|
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Main transaction finished.')
|
2022-06-11 00:51:55 +00:00
|
|
|
await redeemShares(auth.uid, contractId)
|
2022-06-17 03:57:03 +00:00
|
|
|
log('Share redemption transaction finished.')
|
2022-05-26 21:37:51 +00:00
|
|
|
return result
|
2022-05-17 04:43:40 +00:00
|
|
|
})
|
2021-12-11 00:06:17 +00:00
|
|
|
|
|
|
|
const firestore = admin.firestore()
|
2022-07-10 18:05:44 +00:00
|
|
|
|
|
|
|
export const getUnfilledBetsQuery = (contractDoc: DocumentReference) => {
|
|
|
|
return contractDoc
|
|
|
|
.collection('bets')
|
|
|
|
.where('isFilled', '==', false)
|
|
|
|
.where('isCancelled', '==', false) as Query<LimitBet>
|
|
|
|
}
|
|
|
|
|
|
|
|
type maker = {
|
|
|
|
bet: LimitBet
|
|
|
|
amount: number
|
|
|
|
shares: number
|
|
|
|
timestamp: number
|
|
|
|
}
|
|
|
|
export const updateMakers = (
|
|
|
|
makers: maker[],
|
|
|
|
takerBetId: string,
|
|
|
|
contractDoc: DocumentReference,
|
|
|
|
trans: Transaction
|
|
|
|
) => {
|
|
|
|
const makersByBet = groupBy(makers, (maker) => maker.bet.id)
|
|
|
|
for (const makers of Object.values(makersByBet)) {
|
|
|
|
const bet = makers[0].bet
|
|
|
|
const newFills = makers.map((maker) => {
|
|
|
|
const { amount, shares, timestamp } = maker
|
|
|
|
return { amount, shares, matchedBetId: takerBetId, timestamp }
|
|
|
|
})
|
|
|
|
const fills = [...bet.fills, ...newFills]
|
|
|
|
const totalShares = sumBy(fills, 'shares')
|
|
|
|
const totalAmount = sumBy(fills, 'amount')
|
|
|
|
const isFilled = floatingEqual(totalAmount, bet.orderAmount)
|
|
|
|
|
2022-07-12 21:46:03 +00:00
|
|
|
log('Updated a matched limit order.')
|
2022-07-10 18:05:44 +00:00
|
|
|
trans.update(contractDoc.collection('bets').doc(bet.id), {
|
|
|
|
fills,
|
|
|
|
isFilled,
|
|
|
|
amount: totalAmount,
|
|
|
|
shares: totalShares,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Deduct balance of makers.
|
|
|
|
const spentByUser = mapValues(
|
|
|
|
groupBy(makers, (maker) => maker.bet.userId),
|
|
|
|
(makers) => sumBy(makers, (maker) => maker.amount)
|
|
|
|
)
|
|
|
|
for (const [userId, spent] of Object.entries(spentByUser)) {
|
|
|
|
const userDoc = firestore.collection('users').doc(userId)
|
|
|
|
trans.update(userDoc, { balance: FieldValue.increment(-spent) })
|
|
|
|
}
|
|
|
|
}
|