initial commit

This commit is contained in:
mantikoros 2021-12-17 19:47:46 -06:00
parent b5761baeaf
commit 0b1d59a2ac
5 changed files with 81 additions and 50 deletions

16
functions/src/api-call.ts Normal file
View File

@ -0,0 +1,16 @@
import * as functions from 'firebase-functions'
import { placeBetLogic } from '.'
const apiFunctions = {
'place-bet': placeBetLogic,
}
export const apiCall = functions.firestore
.document('api-calls/{apiCallId}')
.onCreate(async (snap, context) => {
const data = snap.data() as any
console.log('data:', data)
const apiFunction = apiFunctions[data.name as keyof typeof apiFunctions]
await apiFunction(data)
})

View File

@ -3,4 +3,5 @@ import * as admin from 'firebase-admin'
admin.initializeApp() admin.initializeApp()
export * from './place-bet' export * from './place-bet'
export * from './resolve-market' export * from './resolve-market'
export * from './api-call'

View File

@ -5,63 +5,62 @@ import { Contract } from './types/contract'
import { User } from './types/user' import { User } from './types/user'
import { Bet } from './types/bet' import { Bet } from './types/bet'
export const placeBet = functions.runWith({ minInstances: 1 }).https.onCall( export const placeBet = functions
async ( .runWith({ minInstances: 1 })
data: { .https.onCall((data, context) => {
amount: number placeBetLogic({ ...data, userId: context?.auth?.uid })
outcome: string })
contractId: string
},
context
) => {
const userId = context?.auth?.uid
if (!userId) return { status: 'error', message: 'Not authorized' }
const { amount, outcome, contractId } = data export const placeBetLogic = async (data: {
amount: number
outcome: string
contractId: string
userId: string
}) => {
console.log('placeBet called')
// if (!userId) return { status: 'error', message: 'Not authorized' }
if (outcome !== 'YES' && outcome !== 'NO') const { amount, outcome, contractId, userId } = data
return { status: 'error', message: 'Invalid outcome' }
// run as transaction to prevent race conditions if (outcome !== 'YES' && outcome !== 'NO')
return await firestore.runTransaction(async (transaction) => { return { status: 'error', message: 'Invalid outcome' }
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.balance < amount) // run as transaction to prevent race conditions
return { status: 'error', message: 'Insufficient balance' } 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
const contractDoc = firestore.doc(`contracts/${contractId}`) if (user.balance < amount)
const contractSnap = await transaction.get(contractDoc) return { status: 'error', message: 'Insufficient balance' }
if (!contractSnap.exists)
return { status: 'error', message: 'Invalid contract' }
const contract = contractSnap.data() as Contract
const newBetDoc = firestore const contractDoc = firestore.doc(`contracts/${contractId}`)
.collection(`contracts/${contractId}/bets`) const contractSnap = await transaction.get(contractDoc)
.doc() if (!contractSnap.exists)
return { status: 'error', message: 'Invalid contract' }
const contract = contractSnap.data() as Contract
const { newBet, newPool, newDpmWeights, newBalance } = getNewBetInfo( const newBetDoc = firestore.collection(`contracts/${contractId}/bets`).doc()
user,
outcome,
amount,
contract,
newBetDoc.id
)
transaction.create(newBetDoc, newBet) const { newBet, newPool, newDpmWeights, newBalance } = getNewBetInfo(
transaction.update(contractDoc, { user,
pool: newPool, outcome,
dpmWeights: newDpmWeights, amount,
}) contract,
transaction.update(userDoc, { balance: newBalance }) newBetDoc.id
)
return { status: 'success' } transaction.create(newBetDoc, newBet)
transaction.update(contractDoc, {
pool: newPool,
dpmWeights: newDpmWeights,
}) })
} transaction.update(userDoc, { balance: newBalance })
)
return { status: 'success' }
})
}
const firestore = admin.firestore() const firestore = admin.firestore()

View File

@ -15,6 +15,7 @@ import {
getDpmWeight, getDpmWeight,
getProbabilityAfterBet, getProbabilityAfterBet,
} from '../lib/calculation/contract' } from '../lib/calculation/contract'
import { apiCall } from '../lib/firebase/api-call'
export function BetPanel(props: { contract: Contract; className?: string }) { export function BetPanel(props: { contract: Contract; className?: string }) {
const { contract, className } = props const { contract, className } = props
@ -61,6 +62,7 @@ export function BetPanel(props: { contract: Contract; className?: string }) {
amount: betAmount, amount: betAmount,
outcome: betChoice, outcome: betChoice,
contractId: contract.id, contractId: contract.id,
userId: user.id,
}).then((r) => r.data as any) }).then((r) => r.data as any)
console.log('placed bet. Result:', result) console.log('placed bet. Result:', result)
@ -171,5 +173,9 @@ export function BetPanel(props: { contract: Contract; className?: string }) {
) )
} }
const functions = getFunctions() // const functions = getFunctions()
export const placeBet = httpsCallable(functions, 'placeBet') // export const placeBet = httpsCallable(functions, 'placeBet')
export const placeBet = async (bet: any) => {
await apiCall({ ...bet, name: 'place-bet' })
return { data: { success: true } }
}

View File

@ -0,0 +1,9 @@
import { app } from './init'
import { doc, collection, getFirestore, setDoc } from 'firebase/firestore'
const db = getFirestore(app)
export async function apiCall(apiCallDoc: any) {
const apiCallRef = doc(collection(db, 'api-calls'))
await setDoc(apiCallRef, apiCallDoc)
}