2022-03-15 22:27:51 +00:00
|
|
|
import * as admin from 'firebase-admin'
|
|
|
|
|
2022-05-15 17:39:42 +00:00
|
|
|
import { Bet } from '../../common/bet'
|
2022-07-05 19:35:39 +00:00
|
|
|
import { getRedeemableAmount, getRedemptionBets } from '../../common/redeem'
|
2022-03-15 22:27:51 +00:00
|
|
|
|
2022-06-01 02:42:35 +00:00
|
|
|
import { Contract } from '../../common/contract'
|
2022-05-15 17:39:42 +00:00
|
|
|
import { User } from '../../common/user'
|
2022-03-15 22:27:51 +00:00
|
|
|
|
|
|
|
export const redeemShares = async (userId: string, contractId: string) => {
|
2022-07-05 19:35:39 +00:00
|
|
|
return await firestore.runTransaction(async (trans) => {
|
2022-03-15 22:27:51 +00:00
|
|
|
const contractDoc = firestore.doc(`contracts/${contractId}`)
|
2022-07-05 19:35:39 +00:00
|
|
|
const contractSnap = await trans.get(contractDoc)
|
2022-03-15 22:27:51 +00:00
|
|
|
if (!contractSnap.exists)
|
|
|
|
return { status: 'error', message: 'Invalid contract' }
|
|
|
|
|
2022-06-01 02:42:35 +00:00
|
|
|
const contract = contractSnap.data() as Contract
|
2022-07-05 19:35:39 +00:00
|
|
|
const { mechanism } = contract
|
|
|
|
if (mechanism !== 'cpmm-1') return { status: 'success' }
|
2022-03-15 22:27:51 +00:00
|
|
|
|
2022-07-05 19:35:39 +00:00
|
|
|
const betsColl = firestore.collection(`contracts/${contract.id}/bets`)
|
|
|
|
const betsSnap = await trans.get(betsColl.where('userId', '==', userId))
|
2022-03-15 22:27:51 +00:00
|
|
|
const bets = betsSnap.docs.map((doc) => doc.data() as Bet)
|
2022-07-05 19:35:39 +00:00
|
|
|
const { shares, loanPayment, netAmount } = getRedeemableAmount(bets)
|
2022-07-05 21:01:57 +00:00
|
|
|
if (netAmount === 0) {
|
|
|
|
return { status: 'success' }
|
|
|
|
}
|
2022-07-05 19:35:39 +00:00
|
|
|
const [yesBet, noBet] = getRedemptionBets(shares, loanPayment, contract)
|
2022-03-15 22:27:51 +00:00
|
|
|
|
|
|
|
const userDoc = firestore.doc(`users/${userId}`)
|
2022-07-05 19:35:39 +00:00
|
|
|
const userSnap = await trans.get(userDoc)
|
2022-03-15 22:27:51 +00:00
|
|
|
if (!userSnap.exists) return { status: 'error', message: 'User not found' }
|
|
|
|
const user = userSnap.data() as User
|
|
|
|
const newBalance = user.balance + netAmount
|
2022-03-16 03:05:08 +00:00
|
|
|
|
|
|
|
if (!isFinite(newBalance)) {
|
|
|
|
throw new Error('Invalid user balance for ' + user.username)
|
|
|
|
}
|
|
|
|
|
2022-07-05 19:35:39 +00:00
|
|
|
const yesDoc = betsColl.doc()
|
|
|
|
const noDoc = betsColl.doc()
|
|
|
|
trans.update(userDoc, { balance: newBalance })
|
|
|
|
trans.create(yesDoc, { id: yesDoc.id, userId, ...yesBet })
|
|
|
|
trans.create(noDoc, { id: noDoc.id, userId, ...noBet })
|
2022-03-15 22:27:51 +00:00
|
|
|
|
|
|
|
return { status: 'success' }
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
const firestore = admin.firestore()
|