Every 15 minutes, compute contract volume in last 24 hours and 7 days

This commit is contained in:
jahooma 2022-01-09 13:34:42 -06:00
parent 6d4554e9ef
commit 6b4417d8b8
5 changed files with 50 additions and 0 deletions

View File

@ -114,6 +114,9 @@ function getNewContract(
createdTime: Date.now(),
lastUpdatedTime: Date.now(),
volume24Hours: 0,
volume7Days: 0,
}
if (closeTime) contract.closeTime = closeTime

View File

@ -8,3 +8,4 @@ export * from './resolve-market'
export * from './stripe'
export * from './sell-bet'
export * from './create-contract'
export * from './update-contract-metrics'

View File

@ -23,4 +23,7 @@ export type Contract = {
isResolved: boolean
resolutionTime?: number // When the contract creator resolved the market
resolution?: 'YES' | 'NO' | 'CANCEL' // Chosen by creator; must be one of outcomes
volume24Hours: number
volume7Days: number
}

View File

@ -0,0 +1,40 @@
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
import * as _ from 'lodash'
import { Contract } from './types/contract'
import { getValues } from './utils'
import { Bet } from './types/bet'
const firestore = admin.firestore()
const oneDay = 1000 * 60 * 60 * 24
export const updateContractMetrics = functions.pubsub
.schedule('every 15 minutes')
.onRun(async () => {
const contracts = await getValues<Contract>(
firestore.collection('contracts')
)
await Promise.all(
contracts.map(async (contract) => {
const volume24Hours = await computeVolumeFrom(contract, oneDay)
const volume7Days = await computeVolumeFrom(contract, oneDay * 7)
const contractRef = firestore.doc(`contracts/${contract.id}`)
return contractRef.update({
volume24Hours,
volume7Days,
})
})
)
})
const computeVolumeFrom = async (contract: Contract, timeAgoMs: number) => {
const bets = await getValues<Bet>(
firestore
.collection(`contracts/${contract.id}/bets`)
.where('createdTime', '>', Date.now() - timeAgoMs)
)
return _.sumBy(bets, (bet) => Math.abs(bet.amount))
}

View File

@ -42,6 +42,9 @@ export type Contract = {
isResolved: boolean
resolutionTime?: number // When the contract creator resolved the market
resolution?: 'YES' | 'NO' | 'CANCEL' // Chosen by creator; must be one of outcomes
volume24Hours: number
volume7Days: number
}
export function path(contract: Contract) {