manifold/functions/src/utils.ts

92 lines
2.5 KiB
TypeScript
Raw Normal View History

2021-12-11 00:06:17 +00:00
import * as admin from 'firebase-admin'
import { Contract } from 'common/contract'
import { PrivateUser, User } from 'common/user'
2021-12-11 00:06:17 +00:00
export const isProd =
admin.instanceId().app.options.projectId === 'mantic-markets'
export const getDoc = async <T>(collection: string, doc: string) => {
2022-01-07 00:05:48 +00:00
const snap = await admin.firestore().collection(collection).doc(doc).get()
2021-12-11 00:06:17 +00:00
2022-01-07 00:05:48 +00:00
return snap.exists ? (snap.data() as T) : undefined
}
export const getValue = async <T>(ref: admin.firestore.DocumentReference) => {
const snap = await ref.get()
return snap.exists ? (snap.data() as T) : undefined
}
2022-01-07 00:05:48 +00:00
export const getValues = async <T>(query: admin.firestore.Query) => {
const snap = await query.get()
return snap.docs.map((doc) => doc.data() as T)
2021-12-11 00:06:17 +00:00
}
export const getContract = (contractId: string) => {
return getDoc<Contract>('contracts', contractId)
2021-12-11 00:06:17 +00:00
}
export const getUser = (userId: string) => {
return getDoc<User>('users', userId)
2022-01-07 00:05:48 +00:00
}
2022-01-10 22:48:48 +00:00
export const getPrivateUser = (userId: string) => {
return getDoc<PrivateUser>('private-users', userId)
}
export const getUserByUsername = async (username: string) => {
const snap = await firestore
.collection('users')
.where('username', '==', username)
.get()
return snap.empty ? undefined : (snap.docs[0].data() as User)
}
2022-01-10 22:48:48 +00:00
const firestore = admin.firestore()
const updateUserBalance = (
userId: string,
delta: number,
isDeposit = false
) => {
2022-01-10 22:48:48 +00:00
return firestore.runTransaction(async (transaction) => {
const userDoc = firestore.doc(`users/${userId}`)
const userSnap = await transaction.get(userDoc)
if (!userSnap.exists) return
const user = userSnap.data() as User
const newUserBalance = user.balance + delta
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
// if (newUserBalance < 0)
// throw new Error(
// `User (${userId}) balance cannot be negative: ${newUserBalance}`
// )
if (isDeposit) {
const newTotalDeposits = (user.totalDeposits || 0) + delta
transaction.update(userDoc, { totalDeposits: newTotalDeposits })
}
2022-01-10 22:48:48 +00:00
transaction.update(userDoc, { balance: newUserBalance })
})
}
export const payUser = (userId: string, payout: number, isDeposit = false) => {
if (!isFinite(payout)) throw new Error('Payout is not finite: ' + payout)
2022-01-10 22:48:48 +00:00
return updateUserBalance(userId, payout, isDeposit)
2022-01-10 22:48:48 +00:00
}
export const chargeUser = (
userId: string,
charge: number,
isAnte?: boolean
) => {
2022-01-10 22:48:48 +00:00
if (!isFinite(charge) || charge <= 0)
throw new Error('User charge is not positive: ' + charge)
return updateUserBalance(userId, -charge, isAnte)
2022-01-10 22:48:48 +00:00
}