manifold/web/components/bet-inline.tsx

133 lines
4.1 KiB
TypeScript
Raw Permalink Normal View History

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'
Verify balance of limit order "makers" (#1007) * Fetch balance of users with open limit orders & cancel orders with insufficient balance * Fix imports * Fix bugs * Fix a bug * Remove redundant cast * buttons overlaying content fix (#1005) * buttons overlaying content fix * stats: round DAU number * made set width for portfolio/profit fields (#1006) * tournaments: included resolved markets * made delete red, moved button for regular posts (#1008) * Fix localstorage saved user being overwritten on every page load * Market page: Show no right panel while user loading * Don't flash sign in button if user is loading * election map coloring * market group modal scroll fix (#1009) * midterms: posititoning, make mobile friendly * Un-daisy share buttons (#1010) * Make embed and challenge buttons non-daisyui * Allow link Buttons. Change tweet, dupe buttons. * lint * don't insert extra lines when upload photos * Map fixes (#1011) * usa map: fix sizing * useSetIframeBackbroundColor * preload contracts * seo * remove hook * turn off sprig on dev * Render timestamp only on client to prevent error of server not matching client * Make sized container have default height so graph doesn't jump * midterms: use null in static props * Create common card component (#1012) * Create common card component * lint * add key prop to pills * redirect to /home after login * create market: use transaction * card: reduce border size * Update groupContracts in db trigger * Default sort to best * Save comment sort per user rather than per contract * Refactor Pinned Items into a reusable component * Revert "create market: use transaction" This reverts commit e1f24f24a96fa8d811ebcaa3b10b19d9b67cb282. * Mark @v with a (Bot) label * fix padding on daily movers * fix type errors * Wrap sprig init in check for window * unindex date-docs from search engines * Auto-prettification * compute elasticity * change dpm elasticity * Fix google lighthouse issues (#1013) * don't hide free response panel on open resolve * liquidity sort * Limit order trade log: '/' to 'of'. Remove 'of' in 'of YES'. * Date doc: Toggle to disable creating a prediction market * Listen for date doc changes * Fix merge error * Don't cancel all a users limit orders if they go negative Co-authored-by: ingawei <46611122+ingawei@users.noreply.github.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: Sinclair Chen <abc.sinclair@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com> Co-authored-by: Ian Philips <iansphilips@gmail.com> Co-authored-by: Pico2x <pico2x@gmail.com> Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: sipec <sipec@users.noreply.github.com>
2022-10-07 03:16:49 +00:00
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<number>()
const [error, setError] = useState<string>()
const isPseudoNumeric = contract.outcomeType === 'PSEUDO_NUMERIC'
Verify balance of limit order "makers" (#1007) * Fetch balance of users with open limit orders & cancel orders with insufficient balance * Fix imports * Fix bugs * Fix a bug * Remove redundant cast * buttons overlaying content fix (#1005) * buttons overlaying content fix * stats: round DAU number * made set width for portfolio/profit fields (#1006) * tournaments: included resolved markets * made delete red, moved button for regular posts (#1008) * Fix localstorage saved user being overwritten on every page load * Market page: Show no right panel while user loading * Don't flash sign in button if user is loading * election map coloring * market group modal scroll fix (#1009) * midterms: posititoning, make mobile friendly * Un-daisy share buttons (#1010) * Make embed and challenge buttons non-daisyui * Allow link Buttons. Change tweet, dupe buttons. * lint * don't insert extra lines when upload photos * Map fixes (#1011) * usa map: fix sizing * useSetIframeBackbroundColor * preload contracts * seo * remove hook * turn off sprig on dev * Render timestamp only on client to prevent error of server not matching client * Make sized container have default height so graph doesn't jump * midterms: use null in static props * Create common card component (#1012) * Create common card component * lint * add key prop to pills * redirect to /home after login * create market: use transaction * card: reduce border size * Update groupContracts in db trigger * Default sort to best * Save comment sort per user rather than per contract * Refactor Pinned Items into a reusable component * Revert "create market: use transaction" This reverts commit e1f24f24a96fa8d811ebcaa3b10b19d9b67cb282. * Mark @v with a (Bot) label * fix padding on daily movers * fix type errors * Wrap sprig init in check for window * unindex date-docs from search engines * Auto-prettification * compute elasticity * change dpm elasticity * Fix google lighthouse issues (#1013) * don't hide free response panel on open resolve * liquidity sort * Limit order trade log: '/' to 'of'. Remove 'of' in 'of YES'. * Date doc: Toggle to disable creating a prediction market * Listen for date doc changes * Fix merge error * Don't cancel all a users limit orders if they go negative Co-authored-by: ingawei <46611122+ingawei@users.noreply.github.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: Sinclair Chen <abc.sinclair@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com> Co-authored-by: Ian Philips <iansphilips@gmail.com> Co-authored-by: Pico2x <pico2x@gmail.com> Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: sipec <sipec@users.noreply.github.com>
2022-10-07 03:16:49 +00:00
const { unfilledBets, balanceByUserId } = useUnfilledBetsAndBalanceByUserId(
contract.id
)
const { newPool, newP } = getBinaryCpmmBetInfo(
outcome ?? 'YES',
amount ?? 0,
contract,
undefined,
Verify balance of limit order "makers" (#1007) * Fetch balance of users with open limit orders & cancel orders with insufficient balance * Fix imports * Fix bugs * Fix a bug * Remove redundant cast * buttons overlaying content fix (#1005) * buttons overlaying content fix * stats: round DAU number * made set width for portfolio/profit fields (#1006) * tournaments: included resolved markets * made delete red, moved button for regular posts (#1008) * Fix localstorage saved user being overwritten on every page load * Market page: Show no right panel while user loading * Don't flash sign in button if user is loading * election map coloring * market group modal scroll fix (#1009) * midterms: posititoning, make mobile friendly * Un-daisy share buttons (#1010) * Make embed and challenge buttons non-daisyui * Allow link Buttons. Change tweet, dupe buttons. * lint * don't insert extra lines when upload photos * Map fixes (#1011) * usa map: fix sizing * useSetIframeBackbroundColor * preload contracts * seo * remove hook * turn off sprig on dev * Render timestamp only on client to prevent error of server not matching client * Make sized container have default height so graph doesn't jump * midterms: use null in static props * Create common card component (#1012) * Create common card component * lint * add key prop to pills * redirect to /home after login * create market: use transaction * card: reduce border size * Update groupContracts in db trigger * Default sort to best * Save comment sort per user rather than per contract * Refactor Pinned Items into a reusable component * Revert "create market: use transaction" This reverts commit e1f24f24a96fa8d811ebcaa3b10b19d9b67cb282. * Mark @v with a (Bot) label * fix padding on daily movers * fix type errors * Wrap sprig init in check for window * unindex date-docs from search engines * Auto-prettification * compute elasticity * change dpm elasticity * Fix google lighthouse issues (#1013) * don't hide free response panel on open resolve * liquidity sort * Limit order trade log: '/' to 'of'. Remove 'of' in 'of YES'. * Date doc: Toggle to disable creating a prediction market * Listen for date doc changes * Fix merge error * Don't cancel all a users limit orders if they go negative Co-authored-by: ingawei <46611122+ingawei@users.noreply.github.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: Sinclair Chen <abc.sinclair@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com> Co-authored-by: Ian Philips <iansphilips@gmail.com> Co-authored-by: Pico2x <pico2x@gmail.com> Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: sipec <sipec@users.noreply.github.com>
2022-10-07 03:16:49 +00:00
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 (
<Col className={clsx('items-center', className)}>
<Row className="h-12 items-stretch gap-3 rounded bg-indigo-200 py-2 px-3">
2022-09-15 14:51:14 +00:00
<div className="text-xl">Predict</div>
<YesNoSelector
className="space-x-0"
btnClassName="rounded-l-none rounded-r-none first:rounded-l-2xl last:rounded-r-2xl"
selected={outcome}
onSelect={setOutcome}
isPseudoNumeric={isPseudoNumeric}
/>
<BuyAmountInput
className="-mb-4"
inputClassName="w-20 !text-base"
amount={amount}
onChange={setAmount}
error="" // handle error ourselves
setError={setError}
/>
{user && (
<Button
color={({ YES: 'green', NO: 'red' } as const)[outcome]}
size="xs"
disabled={betDisabled}
onClick={() => submitBet.mutate()}
>
{submitBet.isLoading
? 'Submitting'
: submitBet.isSuccess
? 'Success!'
: 'Submit'}
</Button>
)}
<BetSignUpPrompt size="xs" />
<button
onClick={() => {
setProbAfter(undefined)
onClose()
}}
>
<XIcon className="ml-1 h-6 w-6" />
</button>
</Row>
{error && (
<div className="text-error my-1 text-sm">
{error} {tooFewFunds && `(${formatMoney(user?.balance ?? 0)})`}
</div>
)}
</Col>
)
}