manifold/functions/src/utils.ts

156 lines
4.2 KiB
TypeScript
Raw Normal View History

2021-12-11 00:06:17 +00:00
import * as admin from 'firebase-admin'
import { chunk } from 'lodash'
import { Contract } from '../../common/contract'
import { PrivateUser, User } from '../../common/user'
import { Group } from '../../common/group'
import { Post } from 'common/post'
2021-12-11 00:06:17 +00:00
export const log = (...args: unknown[]) => {
console.log(`[${new Date().toISOString()}]`, ...args)
}
export const logMemory = () => {
const used = process.memoryUsage()
for (const [k, v] of Object.entries(used)) {
log(`${k} ${Math.round((v / 1024 / 1024) * 100) / 100} MB`)
}
}
export type UpdateSpec = {
doc: admin.firestore.DocumentReference
fields: { [k: string]: unknown }
}
export const writeAsync = async (
db: admin.firestore.Firestore,
updates: UpdateSpec[],
operationType: 'update' | 'set' = 'update',
batchSize = 500 // 500 = Firestore batch limit
) => {
const chunks = chunk(updates, batchSize)
for (let i = 0; i < chunks.length; i++) {
log(`${i * batchSize}/${updates.length} updates written...`)
const batch = db.batch()
for (const { doc, fields } of chunks[i]) {
if (operationType === 'update') {
batch.update(doc, fields)
} else {
batch.set(doc, fields)
}
}
await batch.commit()
}
}
export const tryOrLogError = async <T>(task: Promise<T>) => {
try {
return await task
} catch (e) {
console.error(e)
return null
}
}
export const isProd = () => {
return 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 getGroup = (groupId: string) => {
return getDoc<Group>('groups', groupId)
}
export const getPost = (postId: string) => {
return getDoc<Post>('posts', postId)
}
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 getAllPrivateUsers = async () => {
const firestore = admin.firestore()
const users = await firestore.collection('private-users').get()
return users.docs.map((doc) => doc.data() as PrivateUser)
}
export const getUserByUsername = async (username: string) => {
const firestore = admin.firestore()
const snap = await firestore
.collection('users')
.where('username', '==', username)
.get()
return snap.empty ? undefined : (snap.docs[0].data() as User)
}
const updateUserBalance = (
userId: string,
delta: number,
isDeposit = false
) => {
const firestore = admin.firestore()
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
}