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, resolvedPayout, } 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 contractsCurrentValue = _.mapValues( contractBets, (bets, contractId) => { return _.sumBy(bets, (bet) => { if (bet.isSold || bet.sale) return 0 const contract = contractsById[contractId] const payout = contract ? calculatePayout(contract, bet, 'MKT') : 0 return payout - (bet.loanAmount ?? 0) }) } ) const contractsInvestment = _.mapValues(contractBets, (bets) => { return _.sumBy(bets, (bet) => { if (bet.isSold || bet.sale) return 0 return bet.amount - (bet.loanAmount ?? 0) }) }) 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) => contractsCurrentValue[c.id] - contractsInvestment[c.id], value: (c) => contractsCurrentValue[c.id], 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 || contractsInvestment[c.id] === 0 ) const currentInvestment = _.sumBy(unsettled, (c) => contractsInvestment[c.id]) const currentBetsValue = _.sumBy( unsettled, (c) => contractsCurrentValue[c.id] ) const totalPortfolio = currentBetsValue + user.balance const totalPnl = totalPortfolio - user.totalDeposits const totalProfitPercent = (totalPnl / user.totalDeposits) * 100 const investedProfitPercent = ((currentBetsValue - currentInvestment) / currentInvestment) * 100 return (
Investment value
{formatMoney(currentBetsValue)}{' '}
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[] }) { const { bets, contract } = props const { resolution, outcomeType } = contract const [collapsed, setCollapsed] = useState(true) const isBinary = outcomeType === 'BINARY' const probPercent = getBinaryProbPercent(contract) return (
setCollapsed((collapsed) => !collapsed)} > e.stopPropagation()} > {contract.question} {/* Show carrot for collapsing. Hack the positioning. */}
{isBinary && ( <> {resolution ? (
Resolved
) : (
{probPercent}
)}
)}
) } export function MyBetsSummary(props: { contract: Contract bets: Bet[] onlyMKT?: boolean className?: string }) { const { bets, contract, onlyMKT, className } = props const { resolution, outcomeType } = contract const isBinary = outcomeType === 'BINARY' const excludeSales = bets.filter((b) => !b.isSold && !b.sale) const betsTotal = _.sumBy(excludeSales, (bet) => bet.amount) const betsPayout = resolution ? _.sumBy(excludeSales, (bet) => resolvedPayout(contract, bet)) : 0 const yesWinnings = _.sumBy(excludeSales, (bet) => calculatePayout(contract, bet, 'YES') ) const noWinnings = _.sumBy(excludeSales, (bet) => calculatePayout(contract, bet, 'NO') ) // const p = getProbability(contract.totalShares) // const expectation = p * yesWinnings + (1 - p) * noWinnings const marketWinnings = _.sumBy(excludeSales, (bet) => calculatePayout(contract, bet, 'MKT') ) const currentValue = resolution ? betsPayout : marketWinnings const pnl = currentValue - betsTotal const profit = (pnl / betsTotal) * 100 const valueCol = (
{formatMoney(currentValue)}
) const payoutCol = (
Payout
{formatMoney(betsPayout)}
) return ( {onlyMKT ? ( {valueCol} ) : (
Invested
{formatMoney(betsTotal)}
{resolution ? ( payoutCol ) : ( <> {/*
Expectation
{formatMoney(expectation)}
*/} {isBinary && ( <>
Payout if
{formatMoney(yesWinnings)}
Payout if
{formatMoney(noWinnings)}
)}
{isBinary ? ( <> Payout at{' '} {formatPercent(getProbability(contract))} ) : ( <>Current payout )}
{formatMoney(marketWinnings)}
)}
)}
) } 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) + '%'} ) }