import Link from 'next/link' import _ from 'lodash' import dayjs from 'dayjs' import { useEffect, useState } from 'react' import clsx from 'clsx' import { useUserBets } from '../hooks/use-user-bets' import { Bet } from '../lib/firebase/bets' import { User } from '../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 '../lib/firebase/contracts' import { Row } from './layout/row' import { UserLink } from './user-page' import { sellBet } from '../lib/firebase/api-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, getProbability, getProbabilityAfterSale, getContractBetMetrics, resolvedPayout, getContractBetNullMetrics, } from '../../common/calculate' type BetSort = 'newest' | 'profit' | 'resolutionTime' | 'value' | 'closeTime' type BetFilter = 'open' | 'closed' | 'resolved' | 'all' export function BetsList(props: { user: User }) { const { user } = props const bets = useUserBets(user.id) const [contracts, setContracts] = useState() const [sort, setSort] = useState('value') 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]) 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 = _.fromPairs(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, // Pepe notes: most users want "settled", to see when their bets or sold; or "realized profit" } const SORTS: Record number> = { profit: (c) => contractsMetrics[c.id].profit, value: (c) => contractsMetrics[c.id].totalValue, newest: (c) => Math.max(...contractBets[c.id].map((bet) => bet.createdTime)), resolutionTime: (c) => -(c.resolutionTime ?? c.closeTime ?? Infinity), closeTime: (c) => -(c.closeTime ?? Infinity), } const displayedContracts = _.sortBy(contracts, SORTS[sort]) .reverse() .filter(FILTERS[filter]) 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].netInvestment ) const totalPortfolio = currentNetInvestment + user.balance const totalPnl = totalPortfolio - user.totalDeposits const totalProfitPercent = (totalPnl / user.totalDeposits) * 100 const investedProfitPercent = ((currentBetsValue - currentInvested) / currentInvested) * 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 [collapsed, setCollapsed] = useState(true) const isBinary = outcomeType === 'BINARY' const probPercent = getBinaryProbPercent(contract) const { totalValue, profit, profitPercent } = getContractBetMetrics( contract, bets ) return (
setCollapsed((collapsed) => !collapsed)} > e.stopPropagation()} > {contract.question} {/* Show carrot for collapsing. Hack the positioning. */}
{isBinary && ( <> {resolution ? (
Resolved
) : (
{probPercent}
)}
)}
{formatMoney(metric === 'profit' ? profit : totalValue)}
) } export function MyBetsSummary(props: { contract: Contract bets: Bet[] className?: string }) { const { bets, contract, className } = props const { resolution, outcomeType } = contract const isBinary = outcomeType === 'BINARY' const excludeSales = bets.filter((b) => !b.isSold && !b.sale) const yesWinnings = _.sumBy(excludeSales, (bet) => calculatePayout(contract, bet, 'YES') ) const noWinnings = _.sumBy(excludeSales, (bet) => calculatePayout(contract, bet, 'NO') ) const { invested, profitPercent, payout } = getContractBetMetrics( contract, bets ) return (
Invested
{formatMoney(invested)}
{resolution ? (
Payout
{formatMoney(payout)}{' '}
) : ( <> {isBinary && ( <>
Payout if
{formatMoney(yesWinnings)}
Payout if
{formatMoney(noWinnings)}
)}
{isBinary ? ( <> Payout at{' '} {formatPercent(getProbability(contract))} ) : ( <>Current payout )}
{formatMoney(payout)}
)}
) } export function ContractBetsTable(props: { contract: Contract bets: Bet[] className?: string }) { const { contract, bets, className } = props const [sales, buys] = _.partition(bets, (bet) => bet.sale) const salesDict = _.fromPairs( sales.map((sale) => [sale.sale?.betId ?? '', sale]) ) const [redemptions, normalBets] = _.partition(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 } = contract const isCPMM = mechanism === 'cpmm-1' 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 && } {!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 } = contract const isClosed = closeTime && Date.now() > closeTime const isCPMM = mechanism === 'cpmm-1' 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.outcome === '0' && bet.isAnte ? 'N/A' : formatMoney(calculatePayout(contract, bet, bet.outcome)) return ( {!isCPMM && !isResolved && !isClosed && !isSold && !isAnte && ( )} {isCPMM && {shares >= 0 ? 'BUY' : 'SELL'}} {formatMoney(Math.abs(amount))} {!isCPMM && {saleDisplay}} {!isCPMM && !isResolved && {payoutIfChosenDisplay}} {formatWithCommas(Math.abs(shares))} {formatPercent(probBefore)} → {formatPercent(probAfter)} {dayjs(createdTime).format('MMM D, h:mma')} ) } function SellButton(props: { contract: Contract; bet: Bet }) { useEffect(() => { // warm up cloud function sellBet({}).catch() }, []) 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) + '%'} ) }