import clsx from 'clsx' import { useState } from 'react' import Textarea from 'react-expanding-textarea' import { findBestMatch } from 'string-similarity' import { FreeResponseContract } from 'common/contract' import { BuyAmountInput } from '../amount-input' import { Col } from '../layout/col' import { createAnswer } from 'web/lib/firebase/fn-call' import { Row } from '../layout/row' import { formatMoney, formatPercent, formatWithCommas, } from 'common/util/format' import { InfoTooltip } from '../info-tooltip' import { useUser } from 'web/hooks/use-user' import { 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' export function CreateAnswerPanel(props: { contract: FreeResponseContract }) { const { contract } = props const user = useUser() const [text, setText] = useState('') const [betAmount, setBetAmount] = useState(10) const [amountError, setAmountError] = useState() const [answerError, setAnswerError] = useState() const [possibleDuplicateAnswer, setPossibleDuplicateAnswer] = useState< string | undefined >() const [isSubmitting, setIsSubmitting] = useState(false) const { answers } = contract const canSubmit = text && betAmount && !amountError && !isSubmitting && !answerError const submitAnswer = async () => { if (canSubmit) { setIsSubmitting(true) const result = await createAnswer({ contractId: contract.id, text, amount: betAmount, }).then((r) => r.data) setIsSubmitting(false) if (result.status === 'success') { setText('') setBetAmount(10) setAmountError(undefined) setPossibleDuplicateAnswer(undefined) } else setAmountError(result.message) } } 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 : '' ) } } const resultProb = getDpmOutcomeProbabilityAfterBet( contract.totalShares, 'new', betAmount ?? 0 ) const shares = calculateDpmShares(contract.totalShares, betAmount ?? 0, 'new') const currentPayout = betAmount ? calculateDpmPayoutAfterCorrectBet(contract, { outcome: 'new', amount: betAmount, shares, } as Bet) : 0 const currentReturn = betAmount ? (currentPayout - betAmount) / betAmount : 0 const currentReturnPercent = (currentReturn * 100).toFixed() + '%' return (
Add your answer