2022-06-11 00:51:55 +00:00
|
|
|
import { sumBy } from 'lodash'
|
2022-03-29 19:56:56 +00:00
|
|
|
import * as admin from 'firebase-admin'
|
2022-06-07 20:54:58 +00:00
|
|
|
import { z } from 'zod'
|
2022-03-29 19:56:56 +00:00
|
|
|
|
2022-06-07 20:54:58 +00:00
|
|
|
import { APIError, newEndpoint, validate } from './api'
|
|
|
|
import { Contract } from '../../common/contract'
|
2022-05-15 17:39:42 +00:00
|
|
|
import { User } from '../../common/user'
|
|
|
|
import { getCpmmSellBetInfo } from '../../common/sell-bet'
|
|
|
|
import { addObjects, removeUndefinedProps } from '../../common/util/object'
|
2022-03-29 19:56:56 +00:00
|
|
|
import { getValues } from './utils'
|
2022-05-15 17:39:42 +00:00
|
|
|
import { Bet } from '../../common/bet'
|
2022-03-29 19:56:56 +00:00
|
|
|
|
2022-06-07 20:54:58 +00:00
|
|
|
const bodySchema = z.object({
|
|
|
|
contractId: z.string(),
|
|
|
|
shares: z.number(),
|
|
|
|
outcome: z.enum(['YES', 'NO']),
|
|
|
|
})
|
|
|
|
|
2022-06-11 00:51:55 +00:00
|
|
|
export const sellshares = newEndpoint(['POST'], async (req, auth) => {
|
2022-06-07 20:54:58 +00:00
|
|
|
const { contractId, shares, outcome } = validate(bodySchema, req.body)
|
|
|
|
|
|
|
|
// Run as transaction to prevent race conditions.
|
|
|
|
return await firestore.runTransaction(async (transaction) => {
|
|
|
|
const contractDoc = firestore.doc(`contracts/${contractId}`)
|
2022-06-11 00:51:55 +00:00
|
|
|
const userDoc = firestore.doc(`users/${auth.uid}`)
|
|
|
|
const betsQ = contractDoc.collection('bets').where('userId', '==', auth.uid)
|
|
|
|
const [contractSnap, userSnap, userBets] = await Promise.all([
|
|
|
|
transaction.get(contractDoc),
|
|
|
|
transaction.get(userDoc),
|
|
|
|
getValues<Bet>(betsQ), // TODO: why is this not in the transaction??
|
|
|
|
])
|
2022-06-07 20:54:58 +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-07 20:54:58 +00:00
|
|
|
const contract = contractSnap.data() as Contract
|
2022-06-11 00:51:55 +00:00
|
|
|
const user = userSnap.data() as User
|
|
|
|
|
2022-06-07 20:54:58 +00:00
|
|
|
const { closeTime, mechanism, collectedFees, volume } = contract
|
|
|
|
|
|
|
|
if (mechanism !== 'cpmm-1')
|
|
|
|
throw new APIError(400, 'You can only sell shares on CPMM-1 contracts.')
|
|
|
|
if (closeTime && Date.now() > closeTime)
|
|
|
|
throw new APIError(400, 'Trading is closed.')
|
|
|
|
|
|
|
|
const prevLoanAmount = sumBy(userBets, (bet) => bet.loanAmount ?? 0)
|
|
|
|
|
2022-06-11 00:51:55 +00:00
|
|
|
const outcomeBets = userBets.filter((bet) => bet.outcome == outcome)
|
|
|
|
const maxShares = sumBy(outcomeBets, (bet) => bet.shares)
|
2022-06-07 20:54:58 +00:00
|
|
|
|
|
|
|
if (shares > maxShares + 0.000000000001)
|
|
|
|
throw new APIError(400, `You can only sell up to ${maxShares} shares.`)
|
|
|
|
|
|
|
|
const { newBet, newPool, newP, fees } = getCpmmSellBetInfo(
|
|
|
|
shares,
|
|
|
|
outcome,
|
|
|
|
contract,
|
|
|
|
prevLoanAmount
|
|
|
|
)
|
|
|
|
|
|
|
|
if (!isFinite(newP)) {
|
|
|
|
throw new APIError(500, 'Trade rejected due to overflow error.')
|
|
|
|
}
|
|
|
|
|
|
|
|
const newBetDoc = firestore.collection(`contracts/${contractId}/bets`).doc()
|
|
|
|
const newBalance = user.balance - newBet.amount + (newBet.loanAmount ?? 0)
|
|
|
|
const userId = user.id
|
|
|
|
|
|
|
|
transaction.update(userDoc, { balance: newBalance })
|
|
|
|
transaction.create(newBetDoc, { id: newBetDoc.id, userId, ...newBet })
|
|
|
|
transaction.update(
|
|
|
|
contractDoc,
|
|
|
|
removeUndefinedProps({
|
|
|
|
pool: newPool,
|
|
|
|
p: newP,
|
|
|
|
collectedFees: addObjects(fees, collectedFees),
|
|
|
|
volume: volume + Math.abs(newBet.amount),
|
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
return { status: 'success' }
|
|
|
|
})
|
|
|
|
})
|
2022-03-29 19:56:56 +00:00
|
|
|
|
|
|
|
const firestore = admin.firestore()
|