This commit is contained in:
mantikoros 2021-12-10 18:06:17 -06:00
parent 083e5c506b
commit d95bef8ab3
10 changed files with 171 additions and 25 deletions

View File

@ -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
}

View File

@ -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'

View File

@ -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 }
}

View File

@ -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
}

View File

@ -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
}

View File

@ -0,0 +1,10 @@
export type User = {
id: string
email: string
name: string
username: string
avatarUrl: string
balanceUsd: number
createdTime: number
lastUpdatedTime: number
}

23
functions/src/utils.ts Normal file
View File

@ -0,0 +1,23 @@
import * as admin from 'firebase-admin'
import { Contract } from './types/contract'
import { User } from './types/user'
export const getValue = async <T>(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<Contract>('contracts', contractId)
}
export const getUser = (userId: string) => {
return getValue<User>('users', userId)
}

View File

@ -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 }) {
</Col>
)
}
const functions = getFunctions()
export const placeBet = httpsCallable(functions, 'placeBet')

View File

@ -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

View File

@ -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),
},
})
}}
/>