From f10f7bbaea9dba776a3ce46934ceb2fde12ccdc3 Mon Sep 17 00:00:00 2001 From: mantikoros Date: Tue, 11 Jan 2022 13:30:18 -0600 Subject: [PATCH] market data cloud function --- functions/src/index.ts | 1 + functions/src/markets.ts | 59 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 functions/src/markets.ts diff --git a/functions/src/index.ts b/functions/src/index.ts index 7d58f8a0..f61e49b7 100644 --- a/functions/src/index.ts +++ b/functions/src/index.ts @@ -3,6 +3,7 @@ import * as admin from 'firebase-admin' admin.initializeApp() // export * from './keep-awake' +export * from './markets' export * from './place-bet' export * from './resolve-market' export * from './stripe' diff --git a/functions/src/markets.ts b/functions/src/markets.ts new file mode 100644 index 00000000..aaa6db06 --- /dev/null +++ b/functions/src/markets.ts @@ -0,0 +1,59 @@ +import * as functions from 'firebase-functions' +import * as admin from 'firebase-admin' +import * as _ from 'lodash' + +import { getValues } from './utils' +import { Contract } from '../../common/contract' +import { getProbability } from '../../common/calculate' + +const cache = { lastUpdated: 0, data: '' } + +export const markets = functions + .runWith({ minInstances: 1 }) + .https.onRequest(async (req, res) => { + const contracts: Contract[] = await getValues( + firestore.collection('contracts').orderBy('volume24Hours', 'desc') + ) + + if (!cache.data || Date.now() - cache.lastUpdated > 120 * 1000) { + const contractsInfo = contracts.map(getContractInfo) + cache.data = JSON.stringify(contractsInfo) + cache.lastUpdated = Date.now() + } + + res.status(200).send(cache.data) + }) + +const getContractInfo = ({ + creatorUsername, + creatorName, + createdTime, + closeTime, + question, + description, + slug, + pool, + startPool, + volume7Days, + volume24Hours, + isResolved, + resolution, +}: Contract) => { + return { + creatorUsername, + creatorName, + createdTime, + closeTime, + question, + description, + url: `https://manifold.markets/${creatorUsername}/${slug}`, + pool: pool.YES + pool.NO - startPool.YES - startPool.NO, + probability: getProbability(pool), + volume7Days, + volume24Hours, + isResolved, + resolution, + } +} + +const firestore = admin.firestore()