import Link from 'next/link' import { uniq, groupBy, mapValues, sortBy, partition, sumBy, throttle, } from 'lodash' import dayjs from 'dayjs' import { useEffect, useState } from 'react' import clsx from 'clsx' import { useUserBets } from 'web/hooks/use-user-bets' import { Bet } from 'web/lib/firebase/bets' import { User } from 'web/lib/firebase/users' import { formatMoney, formatPercent, formatWithCommas, } from 'common/util/format' import { Col } from './layout/col' import { Spacer } from './layout/spacer' import { Contract, getContractFromId, contractPath, getBinaryProbPercent, } from 'web/lib/firebase/contracts' import { Row } from './layout/row' import { UserLink } from './user-page' import { sellBet } from 'web/lib/firebase/fn-call' import { ConfirmationButton } from './confirmation-button' import { OutcomeLabel, YesLabel, NoLabel } from './outcome-label' import { filterDefined } from 'common/util/array' 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' type BetSort = 'newest' | 'profit' | 'closeTime' | 'value' type BetFilter = 'open' | 'sold' | 'closed' | 'resolved' | 'all' export function BetsList(props: { user: User }) { const { user } = props const bets = useUserBets(user.id, { includeRedemptions: true }) const [contracts, setContracts] = useState() const [sort, setSort] = useState('newest') const [filter, setFilter] = useState('open') useEffect(() => { if (bets) { const contractIds = uniq(bets.map((bet) => bet.contractId)) let disposed = false Promise.all(contractIds.map((id) => getContractFromId(id))).then( (contracts) => { if (!disposed) setContracts(filterDefined(contracts)) } ) return () => { disposed = true } } }, [bets]) const getTime = useTimeSinceFirstRender() useEffect(() => { if (bets && contracts) { trackLatency('portfolio', getTime()) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [!!bets, !!contracts]) if (!bets || !contracts) { return } if (bets.length === 0) return // Decending creation time. bets.sort((bet1, bet2) => bet2.createdTime - bet1.createdTime) const contractBets = groupBy(bets, 'contractId') const contractsById = Object.fromEntries(contracts.map((c) => [c.id, c])) 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, } 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 displayedContracts = sortBy(contracts, SORTS[sort]) .reverse() .filter(FILTERS[filter]) .filter((c) => { if (filter === 'all') return true const { totalShares } = contractsMetrics[c.id] const hasSoldAll = Object.values(totalShares).every( (shares) => shares === 0 ) if (filter === 'sold') return hasSoldAll return !hasSoldAll }) const [settled, unsettled] = partition( contracts, (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 totalPortfolio = currentNetInvestment + user.balance const totalPnl = totalPortfolio - user.totalDeposits 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 = () => { return (
You have not made any bets yet.{' '} Find a prediction market!
) } function MyContractBets(props: { contract: Contract bets: Bet[] metric: 'profit' | 'value' }) { const { bets, contract, metric } = props const { resolution, outcomeType } = contract const resolutionValue = (contract as NumericContract).resolutionValue const [collapsed, setCollapsed] = useState(true) const isBinary = outcomeType === 'BINARY' const probPercent = getBinaryProbPercent(contract) const { payout, profit, profitPercent, invested } = getContractBetMetrics( contract, bets ) return (
setCollapsed((collapsed) => !collapsed)} > e.stopPropagation()} > {contract.question} {/* Show carrot for collapsing. Hack the positioning. */}
{(isBinary || resolution) && ( <> {resolution ? (
Resolved{' '}
) : (
{probPercent}
)}
)}
{formatMoney(metric === 'profit' ? profit : payout)}
) } export function MyBetsSummary(props: { contract: Contract bets: Bet[] className?: string }) { const { contract, className } = props const { resolution, outcomeType, mechanism } = contract const isBinary = outcomeType === 'BINARY' const isCpmm = mechanism === 'cpmm-1' const bets = props.bets.filter((b) => !b.isAnte) 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 } = getContractBetMetrics( contract, bets ) return ( {!isCpmm && (
Invested
{formatMoney(invested)}
)} {resolution ? (
Payout
{formatMoney(payout)}{' '}
) : ( <> {isBinary ? ( <>
Payout if
{formatMoney(yesWinnings)}
Payout if
{formatMoney(noWinnings)}
) : (
Current value
{formatMoney(payout)}
)} )}
Profit
{formatMoney(profit)}
) } export function ContractBetsTable(props: { contract: Contract bets: Bet[] className?: string }) { const { contract, className } = props const bets = props.bets.filter((b) => !b.isAnte) 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' return (
{amountRedeemed > 0 && ( <>
{amountRedeemed} YES shares and {amountRedeemed} NO shares automatically redeemed for {formatMoney(amountRedeemed)}.
)} {!isResolved && amountLoaned > 0 && ( <>
You currently have a loan of {formatMoney(amountLoaned)}.
)} {isCPMM && } {!isCPMM && !isNumeric && ( )} {!isCPMM && !isResolved && } {normalBets.map((bet) => ( ))}
TypeOutcome Amount{isResolved ? <>Payout : <>Sale price}Payout if chosenShares Probability Date
) } function BetRow(props: { bet: Bet; contract: Contract; saleBet?: Bet }) { const { bet, saleBet, contract } = 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 saleAmount = saleBet?.sale?.amount const saleDisplay = isAnte ? ( 'ANTE' ) : saleAmount !== undefined ? ( <>{formatMoney(saleAmount)} (sold) ) : ( formatMoney( isResolved ? resolvedPayout(contract, bet) : calculateSaleAmount(contract, bet) ) ) const payoutIfChosenDisplay = bet.isAnte && outcomeType === 'FREE_RESPONSE' && bet.outcome === '0' ? 'N/A' : formatMoney(calculatePayout(contract, bet, bet.outcome)) return ( {!isCPMM && !isResolved && !isClosed && !isSold && !isAnte && !isNumeric && } {isCPMM && {shares >= 0 ? 'BUY' : 'SELL'}} {bet.isAnte ? ( 'ANTE' ) : ( )} {formatMoney(Math.abs(amount))} {!isCPMM && !isNumeric && {saleDisplay}} {!isCPMM && !isResolved && {payoutIfChosenDisplay}} {formatWithCommas(Math.abs(shares))} {formatPercent(probBefore)} → {formatPercent(probAfter)} {dayjs(createdTime).format('MMM D, h:mma')} ) } const warmUpSellBet = throttle(() => sellBet({}).catch(() => {}), 5000 /* ms */) function SellButton(props: { contract: Contract; bet: Bet }) { useEffect(() => { warmUpSellBet() }, []) const { contract, bet } = 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) const saleAmount = calculateSaleAmount(contract, bet) 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 }) { const { profitPercent } = 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) + '%'} ) }