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, getProbability, 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' type BetSort = 'newest' | 'profit' | 'resolved' | '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(() => { const loadedBets = bets ? bets : [] const contractIds = _.uniq(loadedBets.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) { return <> } if (bets.length === 0) return (
You have not made any bets yet.{' '} Find a prediction market!
) // 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]) } const [resolved, unresolved] = _.partition( sortedContracts, (c) => c.isResolved ) const displayedContracts = sort === 'resolved' ? resolved : unresolved const currentInvestment = _.sumBy( unresolved, (c) => contractsInvestment[c.id] ) const currentBetsValue = _.sumBy( unresolved, (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)}{' '}
Balance
{formatMoney(Math.floor(user.balance))}{' '}
Total portfolio
{formatMoney(totalPortfolio)}{' '}
{displayedContracts.map((contract) => ( ))} ) } 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)}
*/}
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 (
{buys.map((bet) => ( ))}
Date Outcome Amount Probability Shares {isResolved ? <>Payout : <>Sale price}
) } 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 } = contract const isClosed = closeTime && Date.now() > closeTime const saleAmount = saleBet?.sale?.amount const saleDisplay = bet.isAnte ? ( 'ANTE' ) : saleAmount !== undefined ? ( <>{formatMoney(saleAmount)} (sold) ) : ( formatMoney( isResolved ? resolvedPayout(contract, bet) : calculateSaleAmount(contract, bet) ) ) return ( {dayjs(createdTime).format('MMM D, h:mma')} {formatMoney(amount)} {formatPercent(probBefore)} → {formatPercent(probAfter)} {formatWithCommas(shares)} {saleDisplay} {!isResolved && !isClosed && !isSold && !isAnte && ( )} ) } function SellButton(props: { contract: Contract; bet: Bet }) { useEffect(() => { // warm up cloud function sellBet({}).catch() }, []) const { contract, bet } = props const [isSubmitting, setIsSubmitting] = useState(false) return ( { setIsSubmitting(true) await sellBet({ contractId: contract.id, betId: bet.id }) setIsSubmitting(false) }} >
Sell
Do you want to sell {formatWithCommas(bet.shares)} shares of{' '} for{' '} {formatMoney(calculateSaleAmount(contract, bet))}?
) } 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) + '%'} ) }