From dd59a4d5dc2267946b91a5a4142a1646424e07ff Mon Sep 17 00:00:00 2001 From: jahooma Date: Fri, 24 Dec 2021 14:10:32 -0500 Subject: [PATCH] Migrate contracts and bets script --- functions/package.json | 1 + functions/src/scripts/migrate-contract.ts | 55 +++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 functions/src/scripts/migrate-contract.ts diff --git a/functions/package.json b/functions/package.json index baaac0b4..62dd0c58 100644 --- a/functions/package.json +++ b/functions/package.json @@ -2,6 +2,7 @@ "name": "functions", "scripts": { "build": "tsc", + "watch": "tsc -w", "serve": "yarn build && firebase emulators:start --only functions", "shell": "yarn build && firebase functions:shell", "start": "yarn shell", diff --git a/functions/src/scripts/migrate-contract.ts b/functions/src/scripts/migrate-contract.ts new file mode 100644 index 00000000..0fc93979 --- /dev/null +++ b/functions/src/scripts/migrate-contract.ts @@ -0,0 +1,55 @@ +import * as admin from 'firebase-admin' +import * as _ from 'lodash' +import { Bet } from '../types/bet' +import { Contract } from '../types/contract' + +type DocRef = admin.firestore.DocumentReference + +const serviceAccount = require('../../../../Downloads/mantic-markets-firebase-adminsdk-1ep46-820891bb87.json') +admin.initializeApp({ + credential: admin.credential.cert(serviceAccount), +}) +const firestore = admin.firestore() + +async function migrateBet(contractRef: DocRef, bet: Bet) { + const { dpmWeight, amount, id } = bet as Bet & { dpmWeight: number } + const shares = dpmWeight + amount + + await contractRef.collection('bets').doc(id).update({ shares }) +} + +async function migrateContract(contractRef: DocRef, contract: Contract) { + const bets = await contractRef + .collection('bets') + .get() + .then((snap) => snap.docs.map((bet) => bet.data() as Bet)) + + const totalShares = { + YES: _.sumBy(bets, (bet) => (bet.outcome === 'YES' ? bet.shares : 0)), + NO: _.sumBy(bets, (bet) => (bet.outcome === 'NO' ? bet.shares : 0)), + } + + await contractRef.update({ totalShares }) +} + +async function migrateContracts() { + console.log('Migrating contracts') + + const snapshot = await firestore.collection('contracts').get() + const contracts = snapshot.docs.map((doc) => doc.data() as Contract) + + console.log('Loaded contracts', contracts.length) + + for (const contract of contracts) { + const contractRef = firestore.doc(`contracts/${contract.id}`) + const betsSnapshot = await contractRef.collection('bets').get() + const bets = betsSnapshot.docs.map((bet) => bet.data() as Bet) + + console.log('contract', contract.question, 'bets', bets.length) + + for (const bet of bets) await migrateBet(contractRef, bet) + await migrateContract(contractRef, contract) + } +} + +if (require.main === module) migrateContracts().then(() => process.exit())