diff --git a/.firebaserc b/.firebaserc new file mode 100644 index 00000000..7594f4c6 --- /dev/null +++ b/.firebaserc @@ -0,0 +1,5 @@ +{ + "projects": { + "default": "mantic-markets" + } +} diff --git a/firebase.json b/firebase.json new file mode 100644 index 00000000..060c76ca --- /dev/null +++ b/firebase.json @@ -0,0 +1,5 @@ +{ + "functions": { + "predeploy": "npm --prefix \"$RESOURCE_DIR\" run build" + } +} diff --git a/functions/.gitignore b/functions/.gitignore new file mode 100644 index 00000000..e0ba0181 --- /dev/null +++ b/functions/.gitignore @@ -0,0 +1,13 @@ +# Compiled JavaScript files +lib/**/*.js +lib/**/*.js.map + +# TypeScript v1 declaration files +typings/ + +# Node.js dependency directory +node_modules/ + +package-lock.json +ui-debug.log +firebase-debug.log \ No newline at end of file diff --git a/functions/package.json b/functions/package.json new file mode 100644 index 00000000..f9fedf5b --- /dev/null +++ b/functions/package.json @@ -0,0 +1,24 @@ +{ + "name": "functions", + "scripts": { + "build": "tsc", + "serve": "npm run build && firebase emulators:start --only functions", + "shell": "npm run build && firebase functions:shell", + "start": "npm run shell", + "deploy": "firebase deploy --only functions", + "logs": "firebase functions:log" + }, + "engines": { + "node": "14" + }, + "main": "lib/index.js", + "dependencies": { + "firebase-admin": "10.0.0", + "firebase-functions": "3.16.0" + }, + "devDependencies": { + "firebase-functions-test": "0.3.3", + "typescript": "4.5.3" + }, + "private": true +} diff --git a/functions/src/index.ts b/functions/src/index.ts new file mode 100644 index 00000000..d866c043 --- /dev/null +++ b/functions/src/index.ts @@ -0,0 +1,5 @@ +import * as admin from 'firebase-admin' + +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/functions/tsconfig.json b/functions/tsconfig.json new file mode 100644 index 00000000..7ce05d03 --- /dev/null +++ b/functions/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "module": "commonjs", + "noImplicitReturns": true, + "noUnusedLocals": true, + "outDir": "lib", + "sourceMap": true, + "strict": true, + "target": "es2017" + }, + "compileOnSave": true, + "include": [ + "src" + ] +} diff --git a/web/components/bet-panel.tsx b/web/components/bet-panel.tsx index acb081a6..0dd9f722 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) @@ -132,3 +124,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 ffbd4f15..bc15e743 100644 --- a/web/pages/contract/index.tsx +++ b/web/pages/contract/index.tsx @@ -19,6 +19,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(), @@ -117,6 +118,10 @@ export default function NewContract() { ...contract.seedAmounts, YES: parseInt(e.target.value), }, + pot: { + ...contract.pot, + YES: parseInt(e.target.value), + }, }) }} /> @@ -140,6 +145,10 @@ export default function NewContract() { ...contract.seedAmounts, NO: parseInt(e.target.value), }, + pot: { + ...contract.pot, + NO: parseInt(e.target.value), + }, }) }} />