manifold/web/components/answers/create-answer-panel.tsx

237 lines
7.1 KiB
TypeScript
Raw Normal View History

2022-02-20 22:25:58 +00:00
import clsx from 'clsx'
import { useState } from 'react'
import Textarea from 'react-expanding-textarea'
import { findBestMatch } from 'string-similarity'
2022-02-20 22:25:58 +00:00
import { BountyContract, FreeResponseContract } from 'common/contract'
import { BuyAmountInput } from '../amount-input'
2022-02-20 22:25:58 +00:00
import { Col } from '../layout/col'
import { APIError, createAnswer } from 'web/lib/firebase/api'
2022-02-20 22:25:58 +00:00
import { Row } from '../layout/row'
import {
formatMoney,
formatPercent,
formatWithCommas,
} from 'common/util/format'
2022-02-20 22:25:58 +00:00
import { InfoTooltip } from '../info-tooltip'
import { useUser } from 'web/hooks/use-user'
2022-02-20 22:25:58 +00:00
import {
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
calculateDpmShares,
calculateDpmPayoutAfterCorrectBet,
getDpmOutcomeProbabilityAfterBet,
} from 'common/calculate-dpm'
import { firebaseLogin } from 'web/lib/firebase/users'
import { Bet } from 'common/bet'
import { MAX_ANSWER_LENGTH } from 'common/answer'
import { withTracking } from 'web/lib/service/analytics'
import { lowerCase } from 'lodash'
2022-02-20 22:25:58 +00:00
export function CreateAnswerPanel(props: {
contract: FreeResponseContract | BountyContract
}) {
2022-02-20 22:25:58 +00:00
const { contract } = props
const user = useUser()
const [text, setText] = useState('')
const [betAmount, setBetAmount] = useState<number | undefined>(10)
const [amountError, setAmountError] = useState<string | undefined>()
const [answerError, setAnswerError] = useState<string | undefined>()
const [possibleDuplicateAnswer, setPossibleDuplicateAnswer] = useState<
string | undefined
>()
2022-02-20 22:25:58 +00:00
const [isSubmitting, setIsSubmitting] = useState(false)
const { answers } = contract
2022-02-20 22:25:58 +00:00
const canSubmit =
text && betAmount && !amountError && !isSubmitting && !answerError
2022-02-20 22:25:58 +00:00
const submitAnswer = async () => {
if (canSubmit) {
setIsSubmitting(true)
try {
await createAnswer({
contractId: contract.id,
text,
amount: betAmount,
})
2022-02-20 22:25:58 +00:00
setText('')
setBetAmount(10)
setAmountError(undefined)
setPossibleDuplicateAnswer(undefined)
} catch (e) {
if (e instanceof APIError) {
setAmountError(e.toString())
}
}
setIsSubmitting(false)
2022-02-20 22:25:58 +00:00
}
}
const changeAnswer = (text: string) => {
setText(text)
const existingAnswer = answers.find(
(a) => lowerCase(a.text) === lowerCase(text)
)
if (existingAnswer) {
setAnswerError(
existingAnswer
? `"${existingAnswer.text}" already exists as an answer`
: ''
)
return
} else {
setAnswerError('')
}
if (answers.length && text) {
const matches = findBestMatch(
lowerCase(text),
answers.map((a) => lowerCase(a.text))
)
setPossibleDuplicateAnswer(
matches.bestMatch.rating > 0.8
? answers[matches.bestMatchIndex].text
: ''
)
}
}
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
const resultProb = getDpmOutcomeProbabilityAfterBet(
2022-02-20 22:25:58 +00:00
contract.totalShares,
'new',
betAmount ?? 0
)
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
const shares = calculateDpmShares(contract.totalShares, betAmount ?? 0, 'new')
2022-02-20 22:25:58 +00:00
const currentPayout = betAmount
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
? calculateDpmPayoutAfterCorrectBet(contract, {
2022-02-20 22:25:58 +00:00
outcome: 'new',
amount: betAmount,
shares,
} as Bet)
: 0
const currentReturn = betAmount ? (currentPayout - betAmount) / betAmount : 0
const currentReturnPercent = (currentReturn * 100).toFixed() + '%'
return (
<Col className="gap-4 rounded">
2022-02-20 22:25:58 +00:00
<Col className="flex-1 gap-2">
<div className="mb-1">Add your answer</div>
<Textarea
value={text}
onChange={(e) => changeAnswer(e.target.value)}
className="textarea textarea-bordered w-full resize-none"
2022-02-20 22:25:58 +00:00
placeholder="Type your answer..."
rows={1}
maxLength={MAX_ANSWER_LENGTH}
2022-02-20 22:25:58 +00:00
/>
{answerError ? (
<AnswerError key={1} level="error" text={answerError} />
) : possibleDuplicateAnswer ? (
<AnswerError
key={2}
level="warning"
text={`Did you mean to bet on "${possibleDuplicateAnswer}"?`}
/>
) : undefined}
2022-02-20 22:25:58 +00:00
<div />
<Col
className={clsx(
'gap-4 sm:flex-row sm:items-end',
2022-02-20 22:25:58 +00:00
text ? 'justify-between' : 'self-end'
)}
>
{text && (
<>
<Col className="mt-1 gap-2">
2022-04-09 21:13:36 +00:00
<div className="text-sm text-gray-500">Bet amount</div>
<BuyAmountInput
2022-02-20 22:25:58 +00:00
amount={betAmount}
onChange={setBetAmount}
error={amountError}
setError={setAmountError}
minimumAmount={1}
2022-02-20 22:25:58 +00:00
disabled={isSubmitting}
/>
</Col>
<Col className="gap-3">
<Row className="items-center justify-between text-sm">
<div className="text-gray-500">Probability</div>
<Row>
<div>{formatPercent(0)}</div>
<div className="mx-2"></div>
<div>{formatPercent(resultProb)}</div>
</Row>
2022-02-20 22:25:58 +00:00
</Row>
<Row className="items-center justify-between gap-4 text-sm">
<Row className="flex-nowrap items-center gap-2 whitespace-nowrap text-gray-500">
<div>
Estimated <br /> payout if chosen
</div>
<InfoTooltip
text={`Current payout for ${formatWithCommas(
shares
)} / ${formatWithCommas(shares)} shares`}
/>
</Row>
<Row className="flex-wrap items-end justify-end gap-2">
<span className="whitespace-nowrap">
{formatMoney(currentPayout)}
</span>
<span>(+{currentReturnPercent})</span>
</Row>
2022-02-20 22:25:58 +00:00
</Row>
</Col>
</>
)}
{user ? (
<button
className={clsx(
'btn mt-2',
2022-02-20 22:25:58 +00:00
canSubmit ? 'btn-outline' : 'btn-disabled',
isSubmitting && 'loading'
)}
disabled={!canSubmit}
onClick={withTracking(submitAnswer, 'submit answer')}
2022-02-20 22:25:58 +00:00
>
Submit answer & buy
2022-02-20 22:25:58 +00:00
</button>
) : (
text && (
<button
className="btn self-end whitespace-nowrap border-none bg-gradient-to-r from-teal-500 to-green-500 px-10 text-lg font-medium normal-case hover:from-teal-600 hover:to-green-600"
onClick={withTracking(firebaseLogin, 'answer panel sign in')}
2022-02-20 22:25:58 +00:00
>
Sign in
</button>
)
)}
</Col>
</Col>
</Col>
)
}
type answerErrorLevel = 'warning' | 'error'
const AnswerError = (props: { text: string; level: answerErrorLevel }) => {
const { text, level } = props
const colorClass =
{
error: 'text-red-500',
warning: 'text-orange-500',
}[level] ?? ''
return (
<div
className={`${colorClass} mb-2 mr-auto self-center whitespace-nowrap text-xs font-medium tracking-wide`}
>
{text}
</div>
)
}