manifold/web/lib/firebase/contracts.ts

334 lines
9.0 KiB
TypeScript
Raw Normal View History

import dayjs from 'dayjs'
2021-12-10 04:54:40 +00:00
import {
getFirestore,
doc,
setDoc,
deleteDoc,
where,
collection,
query,
getDocs,
2021-12-10 07:08:28 +00:00
orderBy,
getDoc,
2022-01-07 19:27:59 +00:00
updateDoc,
limit,
2021-12-10 04:54:40 +00:00
} from 'firebase/firestore'
2022-01-17 22:54:00 +00:00
import _ from 'lodash'
2021-12-17 22:15:09 +00:00
import { app } from './init'
import { getValues, listenForValue, listenForValues } from './utils'
import { Binary, Contract, FullContract } from 'common/contract'
import { getDpmProbability } from 'common/calculate-dpm'
import { createRNG, shuffle } from 'common/util/random'
import { getCpmmProbability } from 'common/calculate-cpmm'
import { formatMoney, formatPercent } from 'common/util/format'
import { DAY_MS } from 'common/util/time'
import { MAX_FEED_CONTRACTS } from 'common/recommended-contracts'
import { Bet } from 'common/bet'
import { Comment } from 'common/comment'
import { ENV_CONFIG } from 'common/envs/constants'
export type { Contract }
2021-12-10 04:54:40 +00:00
export function contractPath(contract: Contract) {
2021-12-18 07:27:29 +00:00
return `/${contract.creatorUsername}/${contract.slug}`
}
2022-04-11 21:13:26 +00:00
export function homeContractPath(contract: Contract) {
return `/home?c=${contract.slug}`
}
export function contractUrl(contract: Contract) {
return `https://${ENV_CONFIG.domain}${contractPath(contract)}`
}
export function contractMetrics(contract: Contract) {
const { createdTime, resolutionTime, isResolved } = contract
const createdDate = dayjs(createdTime).format('MMM D')
2021-12-15 07:41:50 +00:00
const resolvedDate = isResolved
? dayjs(resolutionTime).format('MMM D')
: undefined
2022-05-07 14:10:25 +00:00
const volumeLabel = `${formatMoney(contract.volume)} bet`
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
return { volumeLabel, createdDate, resolvedDate }
Free response (#47) * Answer datatype and MULTI outcome type for Contract * Create free answer contract * Automatically sort Tailwind classes with Prettier (#45) * Add Prettier Tailwind plugin * Autoformat Tailwind classes with Prettier * Allow for non-binary contracts in contract page and related components * logo with white inside, transparent bg * Create answer * Some UI for showing answers * Answer bet panel * Convert rest of calcuate file to generic multi contracts * Working betting with ante'd NONE answer * Numbered answers. Layout & calculation tweaks * Can bet. More layout tweaks! * Resolve answer UI * Resolve multi market * Resolved market UI * Fix feed and cards for multi contracts * Sell bets. Various fixes * Tweaks for trades page * Always dev mode * Create answer bet has isAnte: true * Fix card showing 0% for multi contracts * Fix grouped bets feed for multi outcomes * None option converted to none of the above label at bottom of list. Button to resolve none. * Tweaks to no answers yet, resolve button layout * Show ante bets on new answers in the feed * Update placeholder text for description * Consolidate firestore rules for subcollections * Remove Contract and Bet type params. Use string type for outcomes. * Increase char limit to 10k for answers. Preserve line breaks. * Don't show resolve options after answer chosen * Fix type error in script * Remove NONE resolution option * Change outcomeType to include 'MULTI' and 'FREE_RESPONSE' * Show bet probability change and payout when creating answer * User info change: also change answers * Append answers to contract field 'answers' * sort trades by resolved * Don't include trailing !:,.; in links * Stop flooring inputs into formatMoney * Revert "Stop flooring inputs into formatMoney" This reverts commit 2f7ab1842916bc903e60231cbf45b934db2f2658. * Consistently floor user.balance * Expand create panel on focus From Richard Hanania's feedback * welcome email: include link to manifold * Fix home page in dev on branches that are not free-response * Close emails (#50) * script init for stephen dev * market close emails * order of operations * template email * sendMarketCloseEmail: handle unsubscribe * remove debugging * marketCloseEmails: every hour * sendMarketCloseEmails: check undefined * marketCloseEmails: "every hour" => "every 1 hours" * Set up a read API using Vercel serverless functions (#49) * Set up read API using Vercel serverless functions Featuring: /api/v0/markets /api/v0/market/[contractId] /api/v0/slug/[contractSlug] * Include tags in API * Tweaks. Remove filter for only binary contract * Fix bet probability change for NO bets * Put back isProd calculation Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com>
2022-02-17 23:00:19 +00:00
}
export function getBinaryProb(contract: FullContract<any, Binary>) {
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
const { totalShares, pool, p, resolutionProbability, mechanism } = contract
Free response (#47) * Answer datatype and MULTI outcome type for Contract * Create free answer contract * Automatically sort Tailwind classes with Prettier (#45) * Add Prettier Tailwind plugin * Autoformat Tailwind classes with Prettier * Allow for non-binary contracts in contract page and related components * logo with white inside, transparent bg * Create answer * Some UI for showing answers * Answer bet panel * Convert rest of calcuate file to generic multi contracts * Working betting with ante'd NONE answer * Numbered answers. Layout & calculation tweaks * Can bet. More layout tweaks! * Resolve answer UI * Resolve multi market * Resolved market UI * Fix feed and cards for multi contracts * Sell bets. Various fixes * Tweaks for trades page * Always dev mode * Create answer bet has isAnte: true * Fix card showing 0% for multi contracts * Fix grouped bets feed for multi outcomes * None option converted to none of the above label at bottom of list. Button to resolve none. * Tweaks to no answers yet, resolve button layout * Show ante bets on new answers in the feed * Update placeholder text for description * Consolidate firestore rules for subcollections * Remove Contract and Bet type params. Use string type for outcomes. * Increase char limit to 10k for answers. Preserve line breaks. * Don't show resolve options after answer chosen * Fix type error in script * Remove NONE resolution option * Change outcomeType to include 'MULTI' and 'FREE_RESPONSE' * Show bet probability change and payout when creating answer * User info change: also change answers * Append answers to contract field 'answers' * sort trades by resolved * Don't include trailing !:,.; in links * Stop flooring inputs into formatMoney * Revert "Stop flooring inputs into formatMoney" This reverts commit 2f7ab1842916bc903e60231cbf45b934db2f2658. * Consistently floor user.balance * Expand create panel on focus From Richard Hanania's feedback * welcome email: include link to manifold * Fix home page in dev on branches that are not free-response * Close emails (#50) * script init for stephen dev * market close emails * order of operations * template email * sendMarketCloseEmail: handle unsubscribe * remove debugging * marketCloseEmails: every hour * sendMarketCloseEmails: check undefined * marketCloseEmails: "every hour" => "every 1 hours" * Set up a read API using Vercel serverless functions (#49) * Set up read API using Vercel serverless functions Featuring: /api/v0/markets /api/v0/market/[contractId] /api/v0/slug/[contractSlug] * Include tags in API * Tweaks. Remove filter for only binary contract * Fix bet probability change for NO bets * Put back isProd calculation Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com>
2022-02-17 23:00:19 +00:00
return (
resolutionProbability ??
(mechanism === 'cpmm-1'
? getCpmmProbability(pool, p)
: getDpmProbability(totalShares))
)
}
Free response (#47) * Answer datatype and MULTI outcome type for Contract * Create free answer contract * Automatically sort Tailwind classes with Prettier (#45) * Add Prettier Tailwind plugin * Autoformat Tailwind classes with Prettier * Allow for non-binary contracts in contract page and related components * logo with white inside, transparent bg * Create answer * Some UI for showing answers * Answer bet panel * Convert rest of calcuate file to generic multi contracts * Working betting with ante'd NONE answer * Numbered answers. Layout & calculation tweaks * Can bet. More layout tweaks! * Resolve answer UI * Resolve multi market * Resolved market UI * Fix feed and cards for multi contracts * Sell bets. Various fixes * Tweaks for trades page * Always dev mode * Create answer bet has isAnte: true * Fix card showing 0% for multi contracts * Fix grouped bets feed for multi outcomes * None option converted to none of the above label at bottom of list. Button to resolve none. * Tweaks to no answers yet, resolve button layout * Show ante bets on new answers in the feed * Update placeholder text for description * Consolidate firestore rules for subcollections * Remove Contract and Bet type params. Use string type for outcomes. * Increase char limit to 10k for answers. Preserve line breaks. * Don't show resolve options after answer chosen * Fix type error in script * Remove NONE resolution option * Change outcomeType to include 'MULTI' and 'FREE_RESPONSE' * Show bet probability change and payout when creating answer * User info change: also change answers * Append answers to contract field 'answers' * sort trades by resolved * Don't include trailing !:,.; in links * Stop flooring inputs into formatMoney * Revert "Stop flooring inputs into formatMoney" This reverts commit 2f7ab1842916bc903e60231cbf45b934db2f2658. * Consistently floor user.balance * Expand create panel on focus From Richard Hanania's feedback * welcome email: include link to manifold * Fix home page in dev on branches that are not free-response * Close emails (#50) * script init for stephen dev * market close emails * order of operations * template email * sendMarketCloseEmail: handle unsubscribe * remove debugging * marketCloseEmails: every hour * sendMarketCloseEmails: check undefined * marketCloseEmails: "every hour" => "every 1 hours" * Set up a read API using Vercel serverless functions (#49) * Set up read API using Vercel serverless functions Featuring: /api/v0/markets /api/v0/market/[contractId] /api/v0/slug/[contractSlug] * Include tags in API * Tweaks. Remove filter for only binary contract * Fix bet probability change for NO bets * Put back isProd calculation Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com>
2022-02-17 23:00:19 +00:00
export function getBinaryProbPercent(contract: FullContract<any, Binary>) {
return formatPercent(getBinaryProb(contract))
}
export function tradingAllowed(contract: Contract) {
return (
!contract.isResolved &&
(!contract.closeTime || contract.closeTime > Date.now())
)
}
2021-12-10 04:54:40 +00:00
const db = getFirestore(app)
export const contractCollection = collection(db, 'contracts')
2021-12-10 04:54:40 +00:00
// Push contract to Firestore
export async function setContract(contract: Contract) {
const docRef = doc(db, 'contracts', contract.id)
await setDoc(docRef, contract)
}
2021-12-09 22:05:55 +00:00
2022-01-07 19:27:59 +00:00
export async function updateContract(
contractId: string,
update: Partial<Contract>
) {
const docRef = doc(db, 'contracts', contractId)
await updateDoc(docRef, update)
}
2021-12-17 23:16:42 +00:00
export async function getContractFromId(contractId: string) {
const docRef = doc(db, 'contracts', contractId)
const result = await getDoc(docRef)
return result.exists() ? (result.data() as Contract) : undefined
}
2021-12-17 23:16:42 +00:00
export async function getContractFromSlug(slug: string) {
const q = query(contractCollection, where('slug', '==', slug))
const snapshot = await getDocs(q)
return snapshot.empty ? undefined : (snapshot.docs[0].data() as Contract)
}
2021-12-10 04:54:40 +00:00
export async function deleteContract(contractId: string) {
const docRef = doc(db, 'contracts', contractId)
await deleteDoc(docRef)
}
export async function listContracts(creatorId: string): Promise<Contract[]> {
2021-12-10 07:08:28 +00:00
const q = query(
contractCollection,
where('creatorId', '==', creatorId),
orderBy('createdTime', 'desc')
)
2021-12-10 04:54:40 +00:00
const snapshot = await getDocs(q)
return snapshot.docs.map((doc) => doc.data() as Contract)
}
export async function listTaggedContractsCaseInsensitive(
tag: string
): Promise<Contract[]> {
const q = query(
contractCollection,
where('lowercaseTags', 'array-contains', tag.toLowerCase()),
orderBy('createdTime', 'desc')
)
const snapshot = await getDocs(q)
return snapshot.docs.map((doc) => doc.data() as Contract)
}
export async function listAllContracts(): Promise<Contract[]> {
const q = query(contractCollection, orderBy('createdTime', 'desc'))
const snapshot = await getDocs(q)
return snapshot.docs.map((doc) => doc.data() as Contract)
2021-12-10 04:54:40 +00:00
}
2021-12-09 22:05:55 +00:00
export function listenForContracts(
setContracts: (contracts: Contract[]) => void
) {
const q = query(contractCollection, orderBy('createdTime', 'desc'))
return listenForValues<Contract>(q, setContracts)
}
const activeContractsQuery = query(
contractCollection,
where('isResolved', '==', false),
where('visibility', '==', 'public'),
where('volume7Days', '>', 0)
)
export function getActiveContracts() {
return getValues<Contract>(activeContractsQuery)
}
export function listenForActiveContracts(
setContracts: (contracts: Contract[]) => void
) {
return listenForValues<Contract>(activeContractsQuery, setContracts)
}
const inactiveContractsQuery = query(
contractCollection,
where('isResolved', '==', false),
where('closeTime', '>', Date.now()),
where('visibility', '==', 'public'),
where('volume24Hours', '==', 0)
)
export function getInactiveContracts() {
return getValues<Contract>(inactiveContractsQuery)
}
export function listenForInactiveContracts(
setContracts: (contracts: Contract[]) => void
) {
return listenForValues<Contract>(inactiveContractsQuery, setContracts)
}
const newContractsQuery = query(
contractCollection,
where('isResolved', '==', false),
where('volume7Days', '==', 0),
where('createdTime', '>', Date.now() - 7 * DAY_MS)
)
export function listenForNewContracts(
setContracts: (contracts: Contract[]) => void
) {
return listenForValues<Contract>(newContractsQuery, setContracts)
}
2021-12-10 05:01:44 +00:00
export function listenForContract(
contractId: string,
2021-12-15 07:41:50 +00:00
setContract: (contract: Contract | null) => void
2021-12-10 05:01:44 +00:00
) {
const contractRef = doc(contractCollection, contractId)
return listenForValue<Contract>(contractRef, setContract)
2021-12-10 05:01:44 +00:00
}
2022-01-05 06:32:52 +00:00
2022-01-17 22:54:00 +00:00
function chooseRandomSubset(contracts: Contract[], count: number) {
const fiveMinutes = 5 * 60 * 1000
const seed = Math.round(Date.now() / fiveMinutes).toString()
shuffle(contracts, createRNG(seed))
return contracts.slice(0, count)
}
const hotContractsQuery = query(
contractCollection,
where('isResolved', '==', false),
where('visibility', '==', 'public'),
orderBy('volume24Hours', 'desc'),
limit(16)
)
export function listenForHotContracts(
setHotContracts: (contracts: Contract[]) => void
) {
2022-01-17 22:54:00 +00:00
return listenForValues<Contract>(hotContractsQuery, (contracts) => {
const hotContracts = _.sortBy(
chooseRandomSubset(contracts, 4),
(contract) => contract.volume24Hours
)
setHotContracts(hotContracts)
})
}
export async function getHotContracts() {
const contracts = await getValues<Contract>(hotContractsQuery)
return _.sortBy(
2022-01-27 00:21:14 +00:00
chooseRandomSubset(contracts, 10),
2022-01-17 22:54:00 +00:00
(contract) => -1 * contract.volume24Hours
)
2022-01-05 06:32:52 +00:00
}
2022-05-07 23:44:01 +00:00
export async function getContractsBySlugs(slugs: string[]) {
const q = query(contractCollection, where('slug', 'in', slugs))
const snapshot = await getDocs(q)
const contracts = snapshot.docs.map((doc) => doc.data() as Contract)
return _.sortBy(contracts, (contract) => -1 * contract.volume24Hours)
}
const topWeeklyQuery = query(
contractCollection,
where('isResolved', '==', false),
orderBy('volume7Days', 'desc'),
limit(MAX_FEED_CONTRACTS)
)
export async function getTopWeeklyContracts() {
return await getValues<Contract>(topWeeklyQuery)
}
2022-01-17 22:54:00 +00:00
const closingSoonQuery = query(
contractCollection,
where('isResolved', '==', false),
where('visibility', '==', 'public'),
2022-01-17 22:54:00 +00:00
where('closeTime', '>', Date.now()),
orderBy('closeTime', 'asc'),
limit(6)
)
export async function getClosingSoonContracts() {
const contracts = await getValues<Contract>(closingSoonQuery)
return _.sortBy(
chooseRandomSubset(contracts, 2),
(contract) => contract.closeTime
)
2022-01-05 06:32:52 +00:00
}
const getContractsQuery = (startTime: number, endTime: number) =>
query(
collection(db, 'contracts'),
where('createdTime', '>=', startTime),
where('createdTime', '<', endTime),
orderBy('createdTime', 'asc')
)
const DAY_IN_MS = 24 * 60 * 60 * 1000
export async function getDailyContracts(
startTime: number,
numberOfDays: number
) {
const query = getContractsQuery(
startTime,
startTime + DAY_IN_MS * numberOfDays
)
const contracts = await getValues<Contract>(query)
const contractsByDay = _.range(0, numberOfDays).map(() => [] as Contract[])
for (const contract of contracts) {
const dayIndex = Math.floor((contract.createdTime - startTime) / DAY_IN_MS)
contractsByDay[dayIndex].push(contract)
}
return contractsByDay
}
export async function getRecentBetsAndComments(contract: Contract) {
const contractDoc = doc(db, 'contracts', contract.id)
const [recentBets, recentComments] = await Promise.all([
getValues<Bet>(
query(
collection(contractDoc, 'bets'),
where('createdTime', '>', Date.now() - DAY_MS),
orderBy('createdTime', 'desc'),
limit(1)
)
),
getValues<Comment>(
query(
collection(contractDoc, 'comments'),
where('createdTime', '>', Date.now() - 3 * DAY_MS),
orderBy('createdTime', 'desc'),
limit(3)
)
),
])
return {
contract,
recentBets,
recentComments,
}
}