From d95bef8ab3f0f3e9a2fc477b5406fff8e1b3bb68 Mon Sep 17 00:00:00 2001 From: mantikoros Date: Fri, 10 Dec 2021 18:06:17 -0600 Subject: [PATCH] placeBet --- functions/package.json | 8 ++-- functions/src/index.ts | 9 ++-- functions/src/place-bet.ts | 75 +++++++++++++++++++++++++++++++++ functions/src/types/bet.ts | 11 +++++ functions/src/types/contract.ts | 22 ++++++++++ functions/src/types/user.ts | 10 +++++ functions/src/utils.ts | 23 ++++++++++ web/components/bet-panel.tsx | 28 ++++++------ web/lib/firebase/contracts.ts | 1 + web/pages/contract/index.tsx | 9 ++++ 10 files changed, 171 insertions(+), 25 deletions(-) create mode 100644 functions/src/place-bet.ts create mode 100644 functions/src/types/bet.ts create mode 100644 functions/src/types/contract.ts create mode 100644 functions/src/types/user.ts create mode 100644 functions/src/utils.ts diff --git a/functions/package.json b/functions/package.json index 2738eb80..f9fedf5b 100644 --- a/functions/package.json +++ b/functions/package.json @@ -13,12 +13,12 @@ }, "main": "lib/index.js", "dependencies": { - "firebase-admin": "9.8.0", - "firebase-functions": "3.14.1" + "firebase-admin": "10.0.0", + "firebase-functions": "3.16.0" }, "devDependencies": { - "firebase-functions-test": "0.2.0", - "typescript": "3.8.0" + "firebase-functions-test": "0.3.3", + "typescript": "4.5.3" }, "private": true } diff --git a/functions/src/index.ts b/functions/src/index.ts index 113a4f9e..d866c043 100644 --- a/functions/src/index.ts +++ b/functions/src/index.ts @@ -1,6 +1,5 @@ -import * as functions from "firebase-functions" +import * as admin from 'firebase-admin' -export const helloWorld = functions.https.onRequest((request, response) => { - functions.logger.info("Hello logs!", { structuredData: true }) - response.send("Hello from Firebase!") -}) +admin.initializeApp() + +export * from './place-bet' \ No newline at end of file diff --git a/functions/src/place-bet.ts b/functions/src/place-bet.ts new file mode 100644 index 00000000..9a0a2cc0 --- /dev/null +++ b/functions/src/place-bet.ts @@ -0,0 +1,75 @@ +import * as functions from 'firebase-functions' +import * as admin from 'firebase-admin' + +import { Contract } from './types/contract' +import { User } from './types/user' +import { Bet } from './types/bet' + +export const placeBet = functions.https.onCall(async (data: { + amount: number + outcome: string + contractId: string +}, context) => { + const userId = context?.auth?.uid + if (!userId) + return { status: 'error', message: 'Not authorized' } + + const { amount, outcome, contractId } = data + + if (outcome !== 'YES' && outcome !== 'NO') + return { status: 'error', message: 'Invalid outcome' } + + // run as transaction to prevent race conditions + return await firestore.runTransaction(async transaction => { + const userDoc = firestore.doc(`users/${userId}`) + const userSnap = await transaction.get(userDoc) + if (!userSnap.exists) return { status: 'error', message: 'User not found' } + const user = userSnap.data() as User + + if (user.balanceUsd < amount) + return { status: 'error', message: 'Insufficient balance' } + + const contractDoc = firestore.doc(`contracts/${contractId}`) + const contractSnap = await transaction.get(contractDoc) + if (!contractSnap.exists) return { status: 'error', message: 'Invalid contract' } + const contract = contractSnap.data() as Contract + + const newBetDoc = firestore.collection(`contracts/${contractId}/bets`).doc() + + const { newBet, newPot, newBalance } = getNewBetInfo(user, outcome, amount, contract, newBetDoc.id) + + transaction.create(newBetDoc, newBet) + transaction.update(contractDoc, { pot: newPot }) + transaction.update(userDoc, { balanceUsd: newBalance }) + + return { status: 'success' } + }) +}) + +const firestore = admin.firestore() + +const getNewBetInfo = (user: User, outcome: 'YES' | 'NO', amount: number, contract: Contract, newBetId: string) => { + const { YES: yesPot, NO: noPot } = contract.pot + + const dpmWeight = outcome === 'YES' + ? amount * Math.pow(noPot, 2) / (Math.pow(yesPot, 2) + amount * yesPot) + : amount * Math.pow(yesPot, 2) / (Math.pow(noPot, 2) + amount * noPot) + + const newBet: Bet = { + id: newBetId, + userId: user.id, + contractId: contract.id, + amount, + dpmWeight, + outcome, + createdTime: Date.now() + } + + const newPot = outcome === 'YES' + ? { YES: yesPot + amount, NO: noPot } + : { YES: yesPot, NO: noPot + amount } + + const newBalance = user.balanceUsd - amount + + return { newBet, newPot, newBalance } +} \ No newline at end of file diff --git a/functions/src/types/bet.ts b/functions/src/types/bet.ts new file mode 100644 index 00000000..327f3822 --- /dev/null +++ b/functions/src/types/bet.ts @@ -0,0 +1,11 @@ +export type Bet = { + id: string + userId: string + contractId: string + + amount: number // Amount of USD bid + outcome: 'YES' | 'NO' // Chosen outcome + + createdTime: number + dpmWeight: number // Dynamic Parimutuel weight +} \ No newline at end of file diff --git a/functions/src/types/contract.ts b/functions/src/types/contract.ts new file mode 100644 index 00000000..68e74186 --- /dev/null +++ b/functions/src/types/contract.ts @@ -0,0 +1,22 @@ + +export type Contract = { + id: string // Chosen by creator; must be unique + creatorId: string + creatorName: string + + question: string + description: string // More info about what the contract is about + + outcomeType: 'BINARY' // | 'MULTI' | 'interval' | 'date' + // outcomes: ['YES', 'NO'] + seedAmounts: { YES: number; NO: number } + pot: { YES: number; NO: number } + + createdTime: number // Milliseconds since epoch + lastUpdatedTime: number // If the question or description was changed + closeTime?: number // When no more trading is allowed + + // isResolved: boolean + resolutionTime?: 10293849 // When the contract creator resolved the market; 0 if unresolved + resolution?: 'YES' | 'NO' | 'CANCEL' // Chosen by creator; must be one of outcomes +} \ No newline at end of file diff --git a/functions/src/types/user.ts b/functions/src/types/user.ts new file mode 100644 index 00000000..ad3a84b1 --- /dev/null +++ b/functions/src/types/user.ts @@ -0,0 +1,10 @@ +export type User = { + id: string + email: string + name: string + username: string + avatarUrl: string + balanceUsd: number + createdTime: number + lastUpdatedTime: number +} \ No newline at end of file diff --git a/functions/src/utils.ts b/functions/src/utils.ts new file mode 100644 index 00000000..ff3e8fb3 --- /dev/null +++ b/functions/src/utils.ts @@ -0,0 +1,23 @@ +import * as admin from 'firebase-admin' + +import { Contract } from './types/contract' +import { User } from './types/user' + +export const getValue = async (collection: string, doc: string) => { + const snap = await admin.firestore() + .collection(collection) + .doc(doc) + .get() + + return snap.exists + ? snap.data() as T + : undefined +} + +export const getContract = (contractId: string) => { + return getValue('contracts', contractId) +} + +export const getUser = (userId: string) => { + return getValue('users', userId) +} \ No newline at end of file diff --git a/web/components/bet-panel.tsx b/web/components/bet-panel.tsx index 8a403077..b5796e4a 100644 --- a/web/components/bet-panel.tsx +++ b/web/components/bet-panel.tsx @@ -1,7 +1,8 @@ +import { getFunctions, httpsCallable } from "firebase/functions" import clsx from 'clsx' import React, { useState } from 'react' + import { useUser } from '../hooks/use-user' -import { Bet, saveBet } from '../lib/firebase/bets' import { Contract } from '../lib/firebase/contracts' import { Col } from './layout/col' import { Row } from './layout/row' @@ -27,23 +28,14 @@ export function BetPanel(props: { contract: Contract; className?: string }) { async function submitBet() { if (!user || !betAmount) return - const now = Date.now() - - const bet: Bet = { - id: `${now}-${user.id}`, - userId: user.id, - contractId: contract.id, - createdTime: now, - outcome: betChoice, - amount: betAmount, - - // Placeholder. - dpmWeight: betAmount, - } - setIsSubmitting(true) - await saveBet(bet) + const result = await placeBet({ + amount: betAmount, + outcome: betChoice, + contractId: contract.id + }) + console.log('placed bet. Result:', result) setIsSubmitting(false) setWasSubmitted(true) @@ -126,3 +118,7 @@ export function BetPanel(props: { contract: Contract; className?: string }) { ) } + + +const functions = getFunctions() +export const placeBet = httpsCallable(functions, 'placeBet') diff --git a/web/lib/firebase/contracts.ts b/web/lib/firebase/contracts.ts index 519fdb5a..0d74bb18 100644 --- a/web/lib/firebase/contracts.ts +++ b/web/lib/firebase/contracts.ts @@ -22,6 +22,7 @@ export type Contract = { outcomeType: 'BINARY' // | 'MULTI' | 'interval' | 'date' // outcomes: ['YES', 'NO'] seedAmounts: { YES: number; NO: number } // seedBets: [number, number] + pot: { YES: number; NO: number } createdTime: number // Milliseconds since epoch lastUpdatedTime: number // If the question or description was changed diff --git a/web/pages/contract/index.tsx b/web/pages/contract/index.tsx index b164f6d0..372d8cbc 100644 --- a/web/pages/contract/index.tsx +++ b/web/pages/contract/index.tsx @@ -80,6 +80,7 @@ export default function NewContract() { question: '', description: '', seedAmounts: { YES: 100, NO: 100 }, + pot: { YES: 100, NO: 100 }, // TODO: Set create time to Firestore timestamp createdTime: Date.now(), @@ -178,6 +179,10 @@ export default function NewContract() { ...contract.seedAmounts, YES: parseInt(e.target.value), }, + pot: { + ...contract.pot, + YES: parseInt(e.target.value), + }, }) }} /> @@ -201,6 +206,10 @@ export default function NewContract() { ...contract.seedAmounts, NO: parseInt(e.target.value), }, + pot: { + ...contract.pot, + NO: parseInt(e.target.value), + }, }) }} />