import Link from 'next/link' import { Dictionary, keyBy, groupBy, mapValues, sortBy, partition, sumBy, uniq, } from 'lodash' import dayjs from 'dayjs' import { useEffect, useMemo, useState } from 'react' import clsx from 'clsx' import { ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/solid' import { Bet } from 'web/lib/firebase/bets' import { User } from 'web/lib/firebase/users' import { formatLargeNumber, formatMoney, formatPercent, formatWithCommas, } from 'common/util/format' import { Col } from './layout/col' import { Spacer } from './layout/spacer' import { Contract, contractPath, getBinaryProbPercent, getContractFromId, } from 'web/lib/firebase/contracts' import { Row } from './layout/row' import { UserLink } from './user-page' import { sellBet } from 'web/lib/firebase/api' import { ConfirmationButton } from './confirmation-button' import { OutcomeLabel, YesLabel, NoLabel } from './outcome-label' import { LoadingIndicator } from './loading-indicator' import { SiteLink } from './site-link' import { calculatePayout, calculateSaleAmount, getOutcomeProbability, getProbabilityAfterSale, getContractBetMetrics, resolvedPayout, getContractBetNullMetrics, } from 'common/calculate' import { useTimeSinceFirstRender } from 'web/hooks/use-time-since-first-render' import { trackLatency } from 'web/lib/firebase/tracking' import { NumericContract } from 'common/contract' import { formatNumericProbability } from 'common/pseudo-numeric' import { useUser } from 'web/hooks/use-user' import { useUserBets } from 'web/hooks/use-user-bets' import { SellSharesModal } from './sell-modal' import { useUnfilledBets } from 'web/hooks/use-bets' import { LimitBet } from 'common/bet' import { floatingEqual } from 'common/util/math' import { filterDefined } from 'common/util/array' import { Pagination } from './pagination' import { LimitOrderTable } from './limit-bets' type BetSort = 'newest' | 'profit' | 'closeTime' | 'value' type BetFilter = 'open' | 'limit_bet' | 'sold' | 'closed' | 'resolved' | 'all' const CONTRACTS_PER_PAGE = 50 const JUNE_1_2022 = new Date('2022-06-01T00:00:00.000Z').valueOf() export function BetsList(props: { user: User }) { const { user } = props const signedInUser = useUser() const isYourBets = user.id === signedInUser?.id const hideBetsBefore = isYourBets ? 0 : JUNE_1_2022 const userBets = useUserBets(user.id, { includeRedemptions: true }) const [contractsById, setContractsById] = useState< Dictionary | undefined >() // Hide bets before 06-01-2022 if this isn't your own profile // NOTE: This means public profits also begin on 06-01-2022 as well. const bets = useMemo( () => userBets?.filter((bet) => bet.createdTime >= (hideBetsBefore ?? 0)), [userBets, hideBetsBefore] ) useEffect(() => { if (bets) { const contractIds = uniq(bets.map((b) => b.contractId)) Promise.all(contractIds.map(getContractFromId)).then((contracts) => { setContractsById(keyBy(filterDefined(contracts), 'id')) }) } }, [bets]) const [sort, setSort] = useState('newest') const [filter, setFilter] = useState('open') const [page, setPage] = useState(0) const start = page * CONTRACTS_PER_PAGE const end = start + CONTRACTS_PER_PAGE const getTime = useTimeSinceFirstRender() useEffect(() => { if (bets && contractsById && signedInUser) { trackLatency(signedInUser.id, 'portfolio', getTime()) } }, [signedInUser, bets, contractsById, getTime]) if (!bets || !contractsById) { return } if (bets.length === 0) return // Decending creation time. bets.sort((bet1, bet2) => bet2.createdTime - bet1.createdTime) const contractBets = groupBy(bets, 'contractId') // Keep only contracts that have bets. const contracts = Object.values(contractsById).filter( (c) => contractBets[c.id] ) const contractsMetrics = mapValues(contractBets, (bets, contractId) => { const contract = contractsById[contractId] if (!contract) return getContractBetNullMetrics() return getContractBetMetrics(contract, bets) }) const FILTERS: Record boolean> = { resolved: (c) => !!c.resolutionTime, closed: (c) => !FILTERS.resolved(c) && (c.closeTime ?? Infinity) < Date.now(), open: (c) => !(FILTERS.closed(c) || FILTERS.resolved(c)), all: () => true, sold: () => true, limit_bet: (c) => FILTERS.open(c), } const SORTS: Record number> = { profit: (c) => contractsMetrics[c.id].profit, value: (c) => contractsMetrics[c.id].payout, newest: (c) => Math.max(...contractBets[c.id].map((bet) => bet.createdTime)), closeTime: (c) => // This is in fact the intuitive sort direction. (filter === 'open' ? -1 : 1) * (c.resolutionTime ?? c.closeTime ?? Infinity), } const filteredContracts = sortBy(contracts, SORTS[sort]) .reverse() .filter(FILTERS[filter]) .filter((c) => { if (filter === 'all') return true const { hasShares } = contractsMetrics[c.id] if (filter === 'sold') return !hasShares if (filter === 'limit_bet') return (contractBets[c.id] ?? []).some( (b) => b.limitProb !== undefined && !b.isCancelled && !b.isFilled ) return hasShares }) const displayedContracts = filteredContracts.slice(start, end) const unsettled = contracts.filter( (c) => !c.isResolved && contractsMetrics[c.id].invested !== 0 ) const currentInvested = sumBy( unsettled, (c) => contractsMetrics[c.id].invested ) const currentBetsValue = sumBy( unsettled, (c) => contractsMetrics[c.id].payout ) const currentNetInvestment = sumBy( unsettled, (c) => contractsMetrics[c.id].netPayout ) const totalPnl = user.profitCached.allTime const totalProfitPercent = (totalPnl / user.totalDeposits) * 100 const investedProfitPercent = ((currentBetsValue - currentInvested) / (currentInvested + 0.1)) * 100 return (
Investment value
{formatMoney(currentNetInvestment)}{' '}
Total profit
{formatMoney(totalPnl)}{' '}
{displayedContracts.length === 0 ? ( ) : ( displayedContracts.map((contract) => ( )) )} ) } const NoBets = ({ user }: { user: User }) => { const me = useUser() return (
{user.id === me?.id ? ( <> You have not made any bets yet.{' '} Find a prediction market! ) : ( <>{user.name} has not made any public bets yet. )}
) } function ContractBets(props: { contract: Contract bets: Bet[] metric: 'profit' | 'value' isYourBets: boolean }) { const { bets, contract, metric, isYourBets } = props const { resolution, outcomeType } = contract const limitBets = bets.filter( (bet) => bet.limitProb !== undefined && !bet.isCancelled && !bet.isFilled ) as LimitBet[] const resolutionValue = (contract as NumericContract).resolutionValue const [collapsed, setCollapsed] = useState(true) const isBinary = outcomeType === 'BINARY' const { payout, profit, profitPercent } = getContractBetMetrics( contract, bets ) return (
setCollapsed((collapsed) => !collapsed)} > e.stopPropagation()} > {contract.question} {/* Show carrot for collapsing. Hack the positioning. */} {collapsed ? ( ) : ( )} {resolution ? ( <>
Resolved{' '}
) : isBinary ? ( <>
{getBinaryProbPercent(contract)}
) : null}
{formatMoney(metric === 'profit' ? profit : payout)}
{!collapsed && (
{contract.mechanism === 'cpmm-1' && limitBets.length > 0 && (
Limit orders
)}
Bets
)}
) } export function BetsSummary(props: { contract: Contract bets: Bet[] isYourBets: boolean className?: string }) { const { contract, isYourBets, className } = props const { resolution, closeTime, outcomeType, mechanism } = contract const isBinary = outcomeType === 'BINARY' const isPseudoNumeric = outcomeType === 'PSEUDO_NUMERIC' const isCpmm = mechanism === 'cpmm-1' const isClosed = closeTime && Date.now() > closeTime const bets = props.bets.filter((b) => !b.isAnte) const { hasShares } = getContractBetMetrics(contract, bets) const excludeSalesAndAntes = bets.filter( (b) => !b.isAnte && !b.isSold && !b.sale ) const yesWinnings = sumBy(excludeSalesAndAntes, (bet) => calculatePayout(contract, bet, 'YES') ) const noWinnings = sumBy(excludeSalesAndAntes, (bet) => calculatePayout(contract, bet, 'NO') ) const { invested, profitPercent, payout, profit, totalShares } = getContractBetMetrics(contract, bets) const [showSellModal, setShowSellModal] = useState(false) const user = useUser() const sharesOutcome = floatingEqual(totalShares.YES ?? 0, 0) ? floatingEqual(totalShares.NO ?? 0, 0) ? undefined : 'NO' : 'YES' const canSell = isYourBets && isCpmm && (isBinary || isPseudoNumeric) && !isClosed && !resolution && hasShares && sharesOutcome && user return (
Invested
{formatMoney(invested)}
Profit
{formatMoney(profit)}
{canSell && ( <> {showSellModal && ( )} )}
{resolution ? (
Payout
{formatMoney(payout)}{' '}
) : isBinary ? ( <>
Payout if
{formatMoney(yesWinnings)}
Payout if
{formatMoney(noWinnings)}
) : isPseudoNumeric ? ( <>
Payout if {'>='} {formatLargeNumber(contract.max)}
{formatMoney(yesWinnings)}
Payout if {'<='} {formatLargeNumber(contract.min)}
{formatMoney(noWinnings)}
) : (
Current value
{formatMoney(payout)}
)}
) } export function ContractBetsTable(props: { contract: Contract bets: Bet[] isYourBets: boolean }) { const { contract, isYourBets } = props const bets = sortBy( props.bets.filter((b) => !b.isAnte && b.amount !== 0), (bet) => bet.createdTime ).reverse() const [sales, buys] = partition(bets, (bet) => bet.sale) const salesDict = Object.fromEntries( sales.map((sale) => [sale.sale?.betId ?? '', sale]) ) const [redemptions, normalBets] = partition( contract.mechanism === 'cpmm-1' ? bets : buys, (b) => b.isRedemption ) const amountRedeemed = Math.floor(-0.5 * sumBy(redemptions, (b) => b.shares)) const amountLoaned = sumBy( bets.filter((bet) => !bet.isSold && !bet.sale), (bet) => bet.loanAmount ?? 0 ) const { isResolved, mechanism, outcomeType } = contract const isCPMM = mechanism === 'cpmm-1' const isNumeric = outcomeType === 'NUMERIC' const isPseudoNumeric = outcomeType === 'PSEUDO_NUMERIC' const unfilledBets = useUnfilledBets(contract.id) ?? [] return (
{amountRedeemed > 0 && ( <>
{amountRedeemed} {isPseudoNumeric ? 'HIGHER' : 'YES'} shares and{' '} {amountRedeemed} {isPseudoNumeric ? 'LOWER' : 'NO'} shares automatically redeemed for {formatMoney(amountRedeemed)}.
)} {!isResolved && amountLoaned > 0 && ( <>
You currently have a loan of {formatMoney(amountLoaned)}.
)} {isCPMM && } {!isCPMM && !isNumeric && ( )} {!isCPMM && !isResolved && } {!isPseudoNumeric && } {normalBets.map((bet) => ( ))}
TypeOutcome Amount{isResolved ? <>Payout : <>Sale price}Payout if chosenSharesProbabilityDate
) } function BetRow(props: { bet: Bet contract: Contract saleBet?: Bet isYourBet: boolean unfilledBets: LimitBet[] }) { const { bet, saleBet, contract, isYourBet, unfilledBets } = props const { amount, outcome, createdTime, probBefore, probAfter, shares, isSold, isAnte, } = bet const { isResolved, closeTime, mechanism, outcomeType } = contract const isClosed = closeTime && Date.now() > closeTime const isCPMM = mechanism === 'cpmm-1' const isNumeric = outcomeType === 'NUMERIC' const isPseudoNumeric = outcomeType === 'PSEUDO_NUMERIC' const saleAmount = saleBet?.sale?.amount const saleDisplay = isAnte ? ( 'ANTE' ) : saleAmount !== undefined ? ( <>{formatMoney(saleAmount)} (sold) ) : ( formatMoney( isResolved ? resolvedPayout(contract, bet) : calculateSaleAmount(contract, bet, unfilledBets) ) ) const payoutIfChosenDisplay = bet.isAnte && outcomeType === 'FREE_RESPONSE' && bet.outcome === '0' ? 'N/A' : formatMoney(calculatePayout(contract, bet, bet.outcome)) const hadPoolMatch = (bet.limitProb === undefined || bet.fills?.some((fill) => fill.matchedBetId === null)) ?? false const ofTotalAmount = bet.limitProb === undefined || bet.orderAmount === undefined ? '' : ` / ${formatMoney(bet.orderAmount)}` return ( {isYourBet && !isCPMM && !isResolved && !isClosed && !isSold && !isAnte && !isNumeric && ( )} {isCPMM && {shares >= 0 ? 'BUY' : 'SELL'}} {bet.isAnte ? ( 'ANTE' ) : ( )} {isPseudoNumeric && ' than ' + formatNumericProbability(bet.probAfter, contract)} {formatMoney(Math.abs(amount))} {ofTotalAmount} {!isCPMM && !isNumeric && {saleDisplay}} {!isCPMM && !isResolved && {payoutIfChosenDisplay}} {formatWithCommas(Math.abs(shares))} {!isPseudoNumeric && ( {outcomeType === 'FREE_RESPONSE' || hadPoolMatch ? ( <> {formatPercent(probBefore)} → {formatPercent(probAfter)} ) : ( formatPercent(bet.limitProb ?? 0) )} )} {dayjs(createdTime).format('MMM D, h:mma')} ) } function SellButton(props: { contract: Contract bet: Bet unfilledBets: LimitBet[] }) { const { contract, bet, unfilledBets } = props const { outcome, shares, loanAmount } = bet const [isSubmitting, setIsSubmitting] = useState(false) const initialProb = getOutcomeProbability( contract, outcome === 'NO' ? 'YES' : outcome ) const outcomeProb = getProbabilityAfterSale( contract, outcome, shares, unfilledBets ) const saleAmount = calculateSaleAmount(contract, bet, unfilledBets) const profit = saleAmount - bet.amount return ( { setIsSubmitting(true) await sellBet({ contractId: contract.id, betId: bet.id }) setIsSubmitting(false) }} >
Sell {formatWithCommas(shares)} shares of{' '} {' '} for {formatMoney(saleAmount)}?
{!!loanAmount && (
You will also pay back {formatMoney(loanAmount)} of your loan, for a net of {formatMoney(saleAmount - loanAmount)}.
)}
{profit > 0 ? 'Profit' : 'Loss'}: {formatMoney(profit).replace('-', '')}
Market probability: {formatPercent(initialProb)} →{' '} {formatPercent(outcomeProb)}
) } function ProfitBadge(props: { profitPercent: number; className?: string }) { const { profitPercent, className } = props if (!profitPercent) return null const colors = profitPercent > 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' return ( {(profitPercent > 0 ? '+' : '') + profitPercent.toFixed(1) + '%'} ) }