manifold/web/lib/firebase/contracts.ts

303 lines
7.9 KiB
TypeScript
Raw Normal View History

2021-12-10 04:54:40 +00:00
import {
collection,
deleteDoc,
doc,
getDoc,
getDocs,
limit,
orderBy,
query,
setDoc,
startAfter,
updateDoc,
where,
2021-12-10 04:54:40 +00:00
} from 'firebase/firestore'
import { sortBy, sum } from 'lodash'
2021-12-17 22:15:09 +00:00
import { coll, getValues, listenForValue, listenForValues } from './utils'
import { BinaryContract, Contract } from 'common/contract'
import { createRNG, shuffle } from 'common/util/random'
import { formatMoney, formatPercent } from 'common/util/format'
import { DAY_MS } from 'common/util/time'
import { Bet } from 'common/bet'
import { Comment } from 'common/comment'
import { ENV_CONFIG } from 'common/envs/constants'
import { getBinaryProb } from 'common/contract-details'
export const contracts = coll<Contract>('contracts')
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}`
}
Challenge Bets (#679) * Challenge bets * Store avatar url * Fix before and after probs * Check balance before creation * Calculate winning shares * pretty * Change winning value * Set shares to equal each other * Fix share challenge link * pretty * remove lib refs * Probability of bet is set to market * Remove peer pill * Cleanup * Button on contract page * don't show challenge if not binary or if resolved * challenge button (WIP) * fix accept challenge: don't change pool/probability * Opengraph preview [WIP] * elim lib * Edit og card props * Change challenge text * New card gen attempt * Get challenge on server * challenge button styling * Use env domain * Remove other window ref * Use challenge creator as avatar * Remove user name * Remove s from property, replace prob with outcome * challenge form * share text * Add in challenge parts to template and url * Challenge url params optional * Add challenge params to parse request * Parse please * Don't remove prob * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Challenge card styling * Add to readme about how to dev og-image * Add emojis * button: gradient background, 2xl size * beautify accept bet screen * update question button * Add separate challenge template * Accepted challenge sharing card, fix accept bet call * accept challenge button * challenge winner page * create challenge screen * Your outcome/cost=> acceptorOutcome/cost * New create challenge panel * Fix main merge * Add challenge slug to bet and filter by it * Center title * Add helper text * Add FAQ section * Lint * Columnize the user areas in preview link too * Absolutely position * Spacing * Orientation * Restyle challenges list, cache contract name * Make copying easy on mobile * Link spacing * Fix spacing * qr codes! * put your challenges first * eslint * Changes to contract buttons and create challenge modal * Change titles around for current bet * Add back in contract title after winning * Cleanup * Add challenge enabled flag * Spacing of switch button * Put sharing qr code in modal Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-08-04 21:27:02 +00:00
export function contractPathWithoutContract(
creatorUsername: string,
slug: string
) {
return `/${creatorUsername}/${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 contractPool(contract: Contract) {
return contract.mechanism === 'cpmm-1'
? formatMoney(contract.totalLiquidity)
: contract.mechanism === 'dpm-2'
? formatMoney(sum(Object.values(contract.pool)))
: 'Empty pool'
}
export function getBinaryProbPercent(contract: BinaryContract) {
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
// Push contract to Firestore
export async function setContract(contract: Contract) {
await setDoc(doc(contracts, contract.id), contract)
2021-12-10 04:54:40 +00:00
}
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>
) {
await updateDoc(doc(contracts, contractId), update)
2022-01-07 19:27:59 +00:00
}
2021-12-17 23:16:42 +00:00
export async function getContractFromId(contractId: string) {
const result = await getDoc(doc(contracts, contractId))
return result.exists() ? result.data() : undefined
}
2021-12-17 23:16:42 +00:00
export async function getContractFromSlug(slug: string) {
const q = query(contracts, where('slug', '==', slug))
2021-12-17 23:16:42 +00:00
const snapshot = await getDocs(q)
return snapshot.empty ? undefined : snapshot.docs[0].data()
2021-12-17 23:16:42 +00:00
}
2021-12-10 04:54:40 +00:00
export async function deleteContract(contractId: string) {
await deleteDoc(doc(contracts, contractId))
2021-12-10 04:54:40 +00:00
}
export async function listContracts(creatorId: string): Promise<Contract[]> {
2021-12-10 07:08:28 +00:00
const q = query(
contracts,
2021-12-10 07:08:28 +00:00
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())
}
export async function listContractsByGroupSlug(
slug: string
): Promise<Contract[]> {
const q = query(contracts, where('groupSlugs', 'array-contains', slug))
const snapshot = await getDocs(q)
return snapshot.docs.map((doc) => doc.data())
}
export async function listTaggedContractsCaseInsensitive(
tag: string
): Promise<Contract[]> {
const q = query(
contracts,
where('lowercaseTags', 'array-contains', tag.toLowerCase()),
orderBy('createdTime', 'desc')
)
const snapshot = await getDocs(q)
return snapshot.docs.map((doc) => doc.data())
}
export async function listAllContracts(
n: number,
before?: string
): Promise<Contract[]> {
let q = query(contracts, orderBy('createdTime', 'desc'), limit(n))
if (before != null) {
const snap = await getDoc(doc(contracts, before))
q = query(q, startAfter(snap))
}
const snapshot = await getDocs(q)
return snapshot.docs.map((doc) => doc.data())
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(contracts, orderBy('createdTime', 'desc'))
return listenForValues<Contract>(q, setContracts)
}
export function listenForUserContracts(
creatorId: string,
setContracts: (contracts: Contract[]) => void
) {
const q = query(
contracts,
where('creatorId', '==', creatorId),
orderBy('createdTime', 'desc')
)
return listenForValues<Contract>(q, setContracts)
}
const activeContractsQuery = query(
contracts,
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(
contracts,
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(
contracts,
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(contracts, 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(
contracts,
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(
2022-01-17 22:54:00 +00:00
chooseRandomSubset(contracts, 4),
(contract) => contract.volume24Hours
)
setHotContracts(hotContracts)
})
}
const trendingContractsQuery = query(
contracts,
where('isResolved', '==', false),
where('visibility', '==', 'public'),
orderBy('popularityScore', 'desc'),
limit(10)
)
export async function getTrendingContracts() {
return await getValues<Contract>(trendingContractsQuery)
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(contracts, where('slug', 'in', slugs))
2022-05-07 23:44:01 +00:00
const snapshot = await getDocs(q)
const data = snapshot.docs.map((doc) => doc.data())
return sortBy(data, (contract) => -1 * contract.volume24Hours)
2022-05-07 23:44:01 +00:00
}
2022-01-17 22:54:00 +00:00
const closingSoonQuery = query(
contracts,
2022-01-17 22:54:00 +00:00
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 data = await getValues<Contract>(closingSoonQuery)
return sortBy(chooseRandomSubset(data, 2), (contract) => contract.closeTime)
2022-01-05 06:32:52 +00:00
}
export async function getRecentBetsAndComments(contract: Contract) {
const contractDoc = doc(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,
}
}