2022-08-02 06:53:12 +00:00
|
|
|
import { mapValues, groupBy, sumBy, uniq } 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'
|
2022-06-14 02:14:52 +00:00
|
|
|
import { Contract, CPMM_MIN_POOL_QTY } 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-08-22 05:22:49 +00:00
|
|
|
import { log } from './utils'
|
2022-05-15 17:39:42 +00:00
|
|
|
import { Bet } from '../../common/bet'
|
2022-08-02 06:53:12 +00:00
|
|
|
import { floatingEqual, floatingLesserEqual } from '../../common/util/math'
|
2022-07-10 18:05:44 +00:00
|
|
|
import { getUnfilledBetsQuery, updateMakers } from './place-bet'
|
|
|
|
import { FieldValue } from 'firebase-admin/firestore'
|
2022-07-16 18:10:59 +00:00
|
|
|
import { redeemShares } from './redeem-shares'
|
2022-08-24 16:51:21 +00:00
|
|
|
import { removeUserFromContractFollowers } from './follow-market'
|
2022-03-29 19:56:56 +00:00
|
|
|
|
2022-06-07 20:54:58 +00:00
|
|
|
const bodySchema = z.object({
|
|
|
|
contractId: z.string(),
|
2022-07-26 19:47:19 +00:00
|
|
|
shares: z.number().optional(), // leave it out to sell all shares
|
2022-08-02 06:53:12 +00:00
|
|
|
outcome: z.enum(['YES', 'NO']).optional(), // leave it out to sell whichever you have
|
2022-06-07 20:54:58 +00:00
|
|
|
})
|
|
|
|
|
2022-06-29 23:47:06 +00:00
|
|
|
export const sellshares = newEndpoint({}, 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.
|
2022-07-16 18:10:59 +00:00
|
|
|
const result = await firestore.runTransaction(async (transaction) => {
|
2022-06-07 20:54:58 +00:00
|
|
|
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)
|
2022-08-22 05:22:49 +00:00
|
|
|
const [[contractSnap, userSnap], userBetsSnap, unfilledBetsSnap] =
|
|
|
|
await Promise.all([
|
|
|
|
transaction.getAll(contractDoc, userDoc),
|
|
|
|
transaction.get(betsQ),
|
|
|
|
transaction.get(getUnfilledBetsQuery(contractDoc)),
|
|
|
|
])
|
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-08-22 05:22:49 +00:00
|
|
|
const userBets = userBetsSnap.docs.map((doc) => doc.data() as Bet)
|
|
|
|
const unfilledBets = unfilledBetsSnap.docs.map((doc) => doc.data())
|
2022-06-11 00:51:55 +00:00
|
|
|
|
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.')
|
|
|
|
|
2022-08-22 05:22:49 +00:00
|
|
|
const loanAmount = sumBy(userBets, (bet) => bet.loanAmount ?? 0)
|
2022-08-02 06:53:12 +00:00
|
|
|
const betsByOutcome = groupBy(userBets, (bet) => bet.outcome)
|
|
|
|
const sharesByOutcome = mapValues(betsByOutcome, (bets) =>
|
|
|
|
sumBy(bets, (b) => b.shares)
|
|
|
|
)
|
|
|
|
|
|
|
|
let chosenOutcome: 'YES' | 'NO'
|
|
|
|
if (outcome != null) {
|
|
|
|
chosenOutcome = outcome
|
|
|
|
} else {
|
|
|
|
const nonzeroShares = Object.entries(sharesByOutcome).filter(
|
|
|
|
([_k, v]) => !floatingEqual(0, v)
|
|
|
|
)
|
|
|
|
if (nonzeroShares.length == 0) {
|
|
|
|
throw new APIError(400, "You don't own any shares in this market.")
|
|
|
|
}
|
|
|
|
if (nonzeroShares.length > 1) {
|
|
|
|
throw new APIError(
|
|
|
|
400,
|
|
|
|
`You own multiple kinds of shares, but did not specify which to sell.`
|
|
|
|
)
|
|
|
|
}
|
|
|
|
chosenOutcome = nonzeroShares[0][0] as 'YES' | 'NO'
|
|
|
|
}
|
2022-06-07 20:54:58 +00:00
|
|
|
|
2022-08-02 06:53:12 +00:00
|
|
|
const maxShares = sharesByOutcome[chosenOutcome]
|
2022-07-26 19:47:19 +00:00
|
|
|
const sharesToSell = shares ?? maxShares
|
2022-06-07 20:54:58 +00:00
|
|
|
|
2022-07-26 19:47:19 +00:00
|
|
|
if (!floatingLesserEqual(sharesToSell, maxShares))
|
2022-06-07 20:54:58 +00:00
|
|
|
throw new APIError(400, `You can only sell up to ${maxShares} shares.`)
|
|
|
|
|
2022-07-26 19:47:19 +00:00
|
|
|
const soldShares = Math.min(sharesToSell, maxShares)
|
2022-08-22 05:22:49 +00:00
|
|
|
const saleFrac = soldShares / maxShares
|
|
|
|
let loanPaid = saleFrac * loanAmount
|
|
|
|
if (!isFinite(loanPaid)) loanPaid = 0
|
2022-07-10 18:05:44 +00:00
|
|
|
|
|
|
|
const { newBet, newPool, newP, fees, makers } = getCpmmSellBetInfo(
|
|
|
|
soldShares,
|
2022-08-02 06:53:12 +00:00
|
|
|
chosenOutcome,
|
2022-06-07 20:54:58 +00:00
|
|
|
contract,
|
2022-08-22 05:22:49 +00:00
|
|
|
unfilledBets,
|
|
|
|
loanPaid
|
2022-06-07 20:54:58 +00:00
|
|
|
)
|
|
|
|
|
2022-06-14 02:14:52 +00:00
|
|
|
if (
|
|
|
|
!newP ||
|
|
|
|
!isFinite(newP) ||
|
|
|
|
Math.min(...Object.values(newPool ?? {})) < CPMM_MIN_POOL_QTY
|
|
|
|
) {
|
|
|
|
throw new APIError(400, 'Sale too large for current liquidity pool.')
|
2022-06-07 20:54:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const newBetDoc = firestore.collection(`contracts/${contractId}/bets`).doc()
|
|
|
|
|
2022-07-10 18:05:44 +00:00
|
|
|
updateMakers(makers, newBetDoc.id, contractDoc, transaction)
|
|
|
|
|
|
|
|
transaction.update(userDoc, {
|
2022-08-22 05:22:49 +00:00
|
|
|
balance: FieldValue.increment(-newBet.amount + (newBet.loanAmount ?? 0)),
|
2022-07-10 18:05:44 +00:00
|
|
|
})
|
|
|
|
transaction.create(newBetDoc, {
|
|
|
|
id: newBetDoc.id,
|
|
|
|
userId: user.id,
|
|
|
|
...newBet,
|
|
|
|
})
|
2022-06-07 20:54:58 +00:00
|
|
|
transaction.update(
|
|
|
|
contractDoc,
|
|
|
|
removeUndefinedProps({
|
|
|
|
pool: newPool,
|
|
|
|
p: newP,
|
|
|
|
collectedFees: addObjects(fees, collectedFees),
|
|
|
|
volume: volume + Math.abs(newBet.amount),
|
|
|
|
})
|
|
|
|
)
|
|
|
|
|
2022-08-24 16:49:53 +00:00
|
|
|
return { newBet, makers, maxShares, soldShares }
|
2022-06-07 20:54:58 +00:00
|
|
|
})
|
2022-07-16 18:10:59 +00:00
|
|
|
|
2022-08-24 16:49:53 +00:00
|
|
|
if (result.maxShares === result.soldShares) {
|
|
|
|
await removeUserFromContractFollowers(contractId, auth.uid)
|
|
|
|
}
|
2022-07-16 18:10:59 +00:00
|
|
|
const userIds = uniq(result.makers.map((maker) => maker.bet.userId))
|
|
|
|
await Promise.all(userIds.map((userId) => redeemShares(userId, contractId)))
|
|
|
|
log('Share redemption transaction finished.')
|
|
|
|
|
|
|
|
return { status: 'success' }
|
2022-06-07 20:54:58 +00:00
|
|
|
})
|
2022-03-29 19:56:56 +00:00
|
|
|
|
|
|
|
const firestore = admin.firestore()
|