import { track } from '@amplitude/analytics-browser' import clsx from 'clsx' import { CPMMBinaryContract, PseudoNumericContract } from 'common/contract' import { getBinaryCpmmBetInfo } from 'common/new-bet' import { APIError } from 'web/lib/firebase/api' import { useEffect, useState } from 'react' import { useMutation } from 'react-query' import { placeBet } from 'web/lib/firebase/api' import { BuyAmountInput } from './amount-input' import { Button } from './button' import { Row } from './layout/row' import { YesNoSelector } from './yes-no-selector' import { useUnfilledBetsAndBalanceByUserId } from 'web/hooks/use-bets' import { useUser } from 'web/hooks/use-user' import { BetSignUpPrompt } from './sign-up-prompt' import { getCpmmProbability } from 'common/calculate-cpmm' import { Col } from './layout/col' import { XIcon } from '@heroicons/react/solid' import { formatMoney } from 'common/util/format' // adapted from bet-panel.ts export function BetInline(props: { contract: CPMMBinaryContract | PseudoNumericContract className?: string setProbAfter: (probAfter: number | undefined) => void onClose: () => void }) { const { contract, className, setProbAfter, onClose } = props const user = useUser() const [outcome, setOutcome] = useState<'YES' | 'NO'>('YES') const [amount, setAmount] = useState() const [error, setError] = useState() const isPseudoNumeric = contract.outcomeType === 'PSEUDO_NUMERIC' const { unfilledBets, balanceByUserId } = useUnfilledBetsAndBalanceByUserId( contract.id ) const { newPool, newP } = getBinaryCpmmBetInfo( outcome ?? 'YES', amount ?? 0, contract, undefined, unfilledBets, balanceByUserId ) const resultProb = getCpmmProbability(newPool, newP) useEffect(() => setProbAfter(resultProb), [setProbAfter, resultProb]) const submitBet = useMutation( () => placeBet({ outcome, amount, contractId: contract.id }), { onError: (e) => setError(e instanceof APIError ? e.toString() : 'Error placing bet'), onSuccess: () => { track('bet', { location: 'embed', outcomeType: contract.outcomeType, slug: contract.slug, contractId: contract.id, amount, outcome, isLimitOrder: false, }) setAmount(undefined) }, } ) // reset error / success state on user change useEffect(() => { amount && submitBet.reset() // eslint-disable-next-line react-hooks/exhaustive-deps }, [outcome, amount]) const tooFewFunds = error === 'Insufficient balance' const betDisabled = submitBet.isLoading || tooFewFunds || !amount return (
Predict
{user && ( )}
{error && (
{error} {tooFewFunds && `(${formatMoney(user?.balance ?? 0)})`}
)} ) }