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 { calculatePayout, calculateSaleAmount, getOutcomeProbability, getProbability, getProbabilityAfterSale, resolvedPayout, } from '../../common/calculate' 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' type BetSort = 'newest' | 'profit' | 'settled' | 'value' export function BetsList(props: { user: User }) { const { user } = props const bets = useUserBets(user.id) const [contracts, setContracts] = useState() const [sort, setSort] = useState('value') 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 contractsCurrentValue = _.mapValues( contractBets, (bets, contractId) => { return _.sumBy(bets, (bet) => { if (bet.isSold || bet.sale) return 0 const contract = contracts.find((c) => c.id === contractId) return contract ? calculatePayout(contract, bet, 'MKT') : 0 }) } ) const contractsInvestment = _.mapValues(contractBets, (bets) => { return _.sumBy(bets, (bet) => { if (bet.isSold || bet.sale) return 0 return bet.amount }) }) let sortedContracts = contracts if (sort === 'profit') { sortedContracts = _.sortBy( contracts, (c) => -1 * (contractsCurrentValue[c.id] - contractsInvestment[c.id]) ) } else if (sort === 'value') { sortedContracts = _.sortBy(contracts, (c) => -contractsCurrentValue[c.id]) } else if (sort === 'newest') sortedContracts = _.sortBy( contracts, (c) => -1 * Math.max(...contractBets[c.id].map((bet) => bet.createdTime)) ) else if (sort === 'settled') sortedContracts = _.sortBy(contracts, (c) => -1 * (c.resolutionTime ?? 0)) const [settled, unsettled] = _.partition( sortedContracts, (c) => c.isResolved || contractsInvestment[c.id] === 0 ) const displayedContracts = sort === 'settled' ? settled : unsettled 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 totalProfit = (totalPnl / user.totalDeposits) * 100 const investedProfit = ((currentBetsValue - currentInvestment) / currentInvestment) * 100 return (
Invested
{formatMoney(currentBetsValue)}{' '}
Total portfolio
{formatMoney(totalPortfolio)}{' '}
{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.totalShares))} ) : ( <>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 { isResolved } = contract return (
{!isResolved && } {buys.map((bet) => ( ))}
Outcome Amount {isResolved ? <>Payout : <>Sale price}Payout if chosenProbability Shares Date
) } function BetRow(props: { bet: Bet; contract: Contract; saleBet?: Bet }) { const { bet, saleBet, contract } = props const { amount, outcome, createdTime, probBefore, probAfter, shares, isSold, isAnte, loanAmount, } = bet const { isResolved, closeTime } = contract const isClosed = closeTime && Date.now() > closeTime 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 ( {!isResolved && !isClosed && !isSold && !isAnte && ( )} {formatMoney(amount)} {loanAmount ? ` (${formatMoney(loanAmount ?? 0)} loan)` : ''} {saleDisplay} {!isResolved && {payoutIfChosenDisplay}} {formatPercent(probBefore)} → {formatPercent(probAfter)} {formatWithCommas(shares)} {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.totalShares, outcome === 'NO' ? 'YES' : outcome ) const outcomeProb = getProbabilityAfterSale( contract.totalShares, outcome, shares ) const saleAmount = calculateSaleAmount(contract, bet) return ( { setIsSubmitting(true) await sellBet({ contractId: contract.id, betId: bet.id }) setIsSubmitting(false) }} >
Sell
Do you want to 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)}.
)}
(Updated 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) + '%'} ) }