import clsx from 'clsx' import { getOutcomeProbability, getOutcomeProbabilityAfterBet, getProbability, getTopAnswer, } from 'common/calculate' import { getExpectedValue } from 'common/calculate-dpm' import { User } from 'common/user' import { Contract, NumericContract, resolution } from 'common/contract' import { formatLargeNumber, formatMoney, formatPercent, } from 'common/util/format' import { useState } from 'react' import toast from 'react-hot-toast' import { useUserContractBets } from 'web/hooks/use-user-bets' import { placeBet } from 'web/lib/firebase/api-call' import { getBinaryProb, getBinaryProbPercent } from 'web/lib/firebase/contracts' import TriangleDownFillIcon from 'web/lib/icons/triangle-down-fill-icon' import TriangleFillIcon from 'web/lib/icons/triangle-fill-icon' import { Col } from '../layout/col' import { OUTCOME_TO_COLOR } from '../outcome-label' import { useSaveShares } from '../use-save-shares' import { sellShares } from 'web/lib/firebase/api-call' import { calculateCpmmSale, getCpmmProbability } from 'common/calculate-cpmm' import { track } from 'web/lib/service/analytics' import { formatNumericProbability } from 'common/pseudo-numeric' const BET_SIZE = 10 export function QuickBet(props: { contract: Contract; user: User }) { const { contract, user } = props const { mechanism, outcomeType } = contract const isCpmm = mechanism === 'cpmm-1' const userBets = useUserContractBets(user.id, contract.id) const topAnswer = outcomeType === 'FREE_RESPONSE' ? getTopAnswer(contract) : undefined // TODO: yes/no from useSaveShares doesn't work on numeric contracts const { yesFloorShares, noFloorShares, yesShares, noShares } = useSaveShares( contract, userBets, topAnswer?.number.toString() || undefined ) const hasUpShares = yesFloorShares || (noFloorShares && outcomeType === 'NUMERIC') const hasDownShares = noFloorShares && yesFloorShares <= 0 && outcomeType !== 'NUMERIC' const [upHover, setUpHover] = useState(false) const [downHover, setDownHover] = useState(false) let previewProb = undefined try { previewProb = upHover ? getOutcomeProbabilityAfterBet( contract, quickOutcome(contract, 'UP') || '', BET_SIZE ) : downHover ? 1 - getOutcomeProbabilityAfterBet( contract, quickOutcome(contract, 'DOWN') || '', BET_SIZE ) : undefined } catch (e) { // Catch any errors from hovering on an invalid option } let sharesSold: number | undefined let sellOutcome: 'YES' | 'NO' | undefined let saleAmount: number | undefined if (isCpmm && (upHover || downHover)) { const oppositeShares = upHover ? noShares : yesShares if (oppositeShares) { sellOutcome = upHover ? 'NO' : 'YES' const prob = getProb(contract) const maxSharesSold = BET_SIZE / (sellOutcome === 'YES' ? prob : 1 - prob) sharesSold = Math.min(oppositeShares, maxSharesSold) const { newPool, saleValue } = calculateCpmmSale( contract, sharesSold, sellOutcome ) saleAmount = saleValue previewProb = getCpmmProbability(newPool, contract.p) } } async function placeQuickBet(direction: 'UP' | 'DOWN') { const betPromise = async () => { if (sharesSold && sellOutcome) { return await sellShares({ shares: sharesSold, outcome: sellOutcome, contractId: contract.id, }) } const outcome = quickOutcome(contract, direction) return await placeBet({ amount: BET_SIZE, outcome, contractId: contract.id, }) } const shortQ = contract.question.slice(0, 20) const message = sellOutcome && saleAmount ? `${formatMoney(saleAmount)} sold of "${shortQ}"...` : `${formatMoney(BET_SIZE)} on "${shortQ}"...` toast.promise(betPromise(), { loading: message, success: message, error: (err) => `${err.message}`, }) track('quick bet', { slug: contract.slug, direction, contractId: contract.id, }) } return ( {/* Up bet triangle */}
setUpHover(true)} onMouseLeave={() => setUpHover(false)} onClick={() => placeQuickBet('UP')} />
{formatMoney(10)}
{hasUpShares > 0 ? ( ) : ( )}
{/* Down bet triangle */} {outcomeType !== 'BINARY' && outcomeType !== 'PSEUDO_NUMERIC' ? (
) : (
setDownHover(true)} onMouseLeave={() => setDownHover(false)} onClick={() => placeQuickBet('DOWN')} >
{hasDownShares > 0 ? ( ) : ( )}
{formatMoney(10)}
)} ) } export function ProbBar(props: { contract: Contract; previewProb?: number }) { const { contract, previewProb } = props const color = getColor(contract) const prob = previewProb ?? getProb(contract) return ( <>
) } function quickOutcome(contract: Contract, direction: 'UP' | 'DOWN') { const { outcomeType } = contract if (outcomeType === 'BINARY' || outcomeType === 'PSEUDO_NUMERIC') { return direction === 'UP' ? 'YES' : 'NO' } if (outcomeType === 'FREE_RESPONSE') { // TODO: Implement shorting of free response answers if (direction === 'DOWN') { throw new Error("Can't bet against free response answers") } return getTopAnswer(contract)?.id } if (outcomeType === 'NUMERIC') { // TODO: Ideally an 'UP' bet would be a uniform bet between [current, max] throw new Error("Can't quick bet on numeric markets") } } function QuickOutcomeView(props: { contract: Contract previewProb?: number caption?: 'chance' | 'expected' }) { const { contract, previewProb, caption } = props const { outcomeType } = contract const isPseudoNumeric = outcomeType === 'PSEUDO_NUMERIC' // If there's a preview prob, display that instead of the current prob const override = previewProb === undefined ? undefined : isPseudoNumeric ? formatNumericProbability(previewProb, contract) : formatPercent(previewProb) const textColor = `text-${getColor(contract)}` let display: string | undefined switch (outcomeType) { case 'BINARY': display = getBinaryProbPercent(contract) break case 'PSEUDO_NUMERIC': display = formatNumericProbability(getProbability(contract), contract) break case 'NUMERIC': display = formatLargeNumber(getExpectedValue(contract)) break case 'FREE_RESPONSE': { const topAnswer = getTopAnswer(contract) display = topAnswer && formatPercent(getOutcomeProbability(contract, topAnswer.id)) break } } return ( {override ?? display} {caption &&
{caption}
} ) } // Return a number from 0 to 1 for this contract // Resolved contracts are set to 1, for coloring purposes (even if NO) function getProb(contract: Contract) { const { outcomeType, resolution, resolutionProbability } = contract return resolutionProbability ? resolutionProbability : resolution ? 1 : outcomeType === 'BINARY' ? getBinaryProb(contract) : outcomeType === 'PSEUDO_NUMERIC' ? getProbability(contract) : outcomeType === 'FREE_RESPONSE' ? getOutcomeProbability(contract, getTopAnswer(contract)?.id || '') : outcomeType === 'NUMERIC' ? getNumericScale(contract) : 1 // Should not happen } function getNumericScale(contract: NumericContract) { const { min, max } = contract const ev = getExpectedValue(contract) return (ev - min) / (max - min) } export function getColor(contract: Contract) { // TODO: Try injecting a gradient here // return 'primary' const { resolution, outcomeType } = contract if (resolution) { return ( OUTCOME_TO_COLOR[resolution as resolution] ?? // If resolved to a FR answer, use 'primary' 'primary' ) } if (outcomeType === 'PSEUDO_NUMERIC') return 'blue-400' if ((contract.closeTime ?? Infinity) < Date.now()) { return 'gray-400' } // TODO: Not sure why eg green-400 doesn't work here; try upgrading Tailwind return 'primary' }