manifold/web/pages/create.tsx

404 lines
13 KiB
TypeScript
Raw Normal View History

import router, { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import clsx from 'clsx'
import dayjs from 'dayjs'
import Textarea from 'react-expanding-textarea'
import { Spacer } from 'web/components/layout/spacer'
import { useUser } from 'web/hooks/use-user'
import { Contract, contractPath } from 'web/lib/firebase/contracts'
import { createMarket } from 'web/lib/firebase/api-call'
import { FIXED_ANTE, MINIMUM_ANTE } from 'common/antes'
import { InfoTooltip } from 'web/components/info-tooltip'
import { Page } from 'web/components/page'
import { Row } from 'web/components/layout/row'
import {
MAX_DESCRIPTION_LENGTH,
MAX_QUESTION_LENGTH,
outcomeType,
} from 'common/contract'
import { formatMoney } from 'common/util/format'
import { removeUndefinedProps } from 'common/util/object'
import { ChoicesToggleGroup } from 'web/components/choices-toggle-group'
import { getGroup, updateGroup } from 'web/lib/firebase/groups'
import { Group } from 'common/group'
import { useTracking } from 'web/hooks/use-tracking'
import { useWarnUnsavedChanges } from 'web/hooks/use-warn-unsaved-changes'
import { track } from 'web/lib/service/analytics'
import { GroupSelector } from 'web/components/groups/group-selector'
import { CATEGORIES } from 'common/categories'
export default function Create() {
const [question, setQuestion] = useState('')
// get query params:
const router = useRouter()
const { groupId } = router.query as { groupId: string }
useTracking('view create page')
if (!router.isReady) return <div />
return (
<Page>
<div className="mx-auto w-full max-w-2xl">
2022-06-05 02:28:27 +00:00
<div className="rounded-lg px-6 py-4 sm:py-0">
<form>
<div className="form-control w-full">
<label className="label">
<span className="mb-1">
Question<span className={'text-red-700'}>*</span>
</span>
</label>
<Textarea
placeholder="e.g. Will the Democrats win the 2024 US presidential election?"
className="input input-bordered resize-none"
autoFocus
maxLength={MAX_QUESTION_LENGTH}
value={question}
onChange={(e) => setQuestion(e.target.value || '')}
/>
</div>
</form>
2022-06-05 02:28:27 +00:00
<Spacer h={6} />
<NewContract question={question} groupId={groupId} />
</div>
</div>
</Page>
)
}
// Allow user to create a new contract
export function NewContract(props: { question: string; groupId?: string }) {
const { question, groupId } = props
const creator = useUser()
useEffect(() => {
2021-12-16 07:00:35 +00:00
if (creator === null) router.push('/')
}, [creator])
Free response (#47) * Answer datatype and MULTI outcome type for Contract * Create free answer contract * Automatically sort Tailwind classes with Prettier (#45) * Add Prettier Tailwind plugin * Autoformat Tailwind classes with Prettier * Allow for non-binary contracts in contract page and related components * logo with white inside, transparent bg * Create answer * Some UI for showing answers * Answer bet panel * Convert rest of calcuate file to generic multi contracts * Working betting with ante'd NONE answer * Numbered answers. Layout & calculation tweaks * Can bet. More layout tweaks! * Resolve answer UI * Resolve multi market * Resolved market UI * Fix feed and cards for multi contracts * Sell bets. Various fixes * Tweaks for trades page * Always dev mode * Create answer bet has isAnte: true * Fix card showing 0% for multi contracts * Fix grouped bets feed for multi outcomes * None option converted to none of the above label at bottom of list. Button to resolve none. * Tweaks to no answers yet, resolve button layout * Show ante bets on new answers in the feed * Update placeholder text for description * Consolidate firestore rules for subcollections * Remove Contract and Bet type params. Use string type for outcomes. * Increase char limit to 10k for answers. Preserve line breaks. * Don't show resolve options after answer chosen * Fix type error in script * Remove NONE resolution option * Change outcomeType to include 'MULTI' and 'FREE_RESPONSE' * Show bet probability change and payout when creating answer * User info change: also change answers * Append answers to contract field 'answers' * sort trades by resolved * Don't include trailing !:,.; in links * Stop flooring inputs into formatMoney * Revert "Stop flooring inputs into formatMoney" This reverts commit 2f7ab1842916bc903e60231cbf45b934db2f2658. * Consistently floor user.balance * Expand create panel on focus From Richard Hanania's feedback * welcome email: include link to manifold * Fix home page in dev on branches that are not free-response * Close emails (#50) * script init for stephen dev * market close emails * order of operations * template email * sendMarketCloseEmail: handle unsubscribe * remove debugging * marketCloseEmails: every hour * sendMarketCloseEmails: check undefined * marketCloseEmails: "every hour" => "every 1 hours" * Set up a read API using Vercel serverless functions (#49) * Set up read API using Vercel serverless functions Featuring: /api/v0/markets /api/v0/market/[contractId] /api/v0/slug/[contractSlug] * Include tags in API * Tweaks. Remove filter for only binary contract * Fix bet probability change for NO bets * Put back isProd calculation Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com>
2022-02-17 23:00:19 +00:00
const [outcomeType, setOutcomeType] = useState<outcomeType>('BINARY')
2022-06-09 20:26:46 +00:00
const [initialProb] = useState(50)
Numeric range markets!! (#146) * Numeric contract type * Create market numeric type * Add numeric graph (coded without testing) * Outline of numeric bet panel * Update bet panel logic * create numeric contracts * remove batching for antes for numeric markets * Remove focus * numeric market range [1, 100] * Zoom graph * Hide bet panels * getNumericBets * Add numeric resolution panel * Use getNumericBets in bet panel calc * Switch bucket count to 100 * Parallelize ante creation * placeBet for numeric markets * halve std of numeric bets * Update resolveMarket with numeric type * Set min and max for contract * lower std for numeric bets * calculateNumericDpmShares: use sorted order * Use min and max to map the input * Fix probability calc * normpdf variance mislabeled * range input * merge * change numeric graph color * fix getNewContract params * bet panel labels * validation * number input * fix bucketing * bucket input, numeric resolution panel * outcome label * merge * numeric bet panel on mobile * Make text underneath filled green answer bar selectable * Default to 'all' feed category when loading page. * fix numeric resolution panel * fix numeric bet panel calculations * display numeric resolution * don't render NumericBetPanel for non numeric markets * numeric bets: store shares, bet amounts across buckets in each bet object * restore your bets for numeric markets * numeric pnl calculations * remove hasUserHitManaLimit * contrain contract type * handle undefined allOutcomeShares * numeric ante bet amount * use correct amount for numeric dpm payouts * change numeric graph/outcome color * numeric constants * hack to show correct numeric payout in calculateDpmPayoutAfterCorrectBet * remove comment * fix ante display in bet list * halve bucket count * cast to NumericContract * fix merge imports * OUTCOME_TYPES * typo * lower bucket count to 200 * store raw numeric value with bet * store raw numeric resolution value * number input max length * create page: min, max to undefined if not numeric market * numeric resolution formatting * expected value for numeric markets * expected value for numeric markets * rearrange lines for readability * move normalpdf to util/math * show bets tab * check if outcomeMode is undefined * remove extraneous auto-merge cruft * hide comment status for numeric markets * import Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-05-19 17:42:03 +00:00
const [minString, setMinString] = useState('')
const [maxString, setMaxString] = useState('')
const [description, setDescription] = useState('')
// const [tagText, setTagText] = useState<string>(tag ?? '')
// const tags = parseWordsAsTags(tagText)
useEffect(() => {
if (groupId && creator)
getGroup(groupId).then((group) => {
if (group && group.memberIds.includes(creator.id)) {
setSelectedGroup(group)
setShowGroupSelector(false)
}
})
}, [creator, groupId])
const [ante, _setAnte] = useState(FIXED_ANTE)
2022-04-09 18:51:22 +00:00
// useEffect(() => {
// if (ante === null && creator) {
// const initialAnte = creator.balance < 100 ? MINIMUM_ANTE : 100
// setAnte(initialAnte)
// }
// }, [ante, creator])
2022-04-09 18:51:22 +00:00
// const [anteError, setAnteError] = useState<string | undefined>()
// By default, close the market a week from today
const weekFromToday = dayjs().add(7, 'day').format('YYYY-MM-DD')
2022-01-31 05:20:27 +00:00
const [closeDate, setCloseDate] = useState<undefined | string>(weekFromToday)
const [closeHoursMinutes, setCloseHoursMinutes] = useState<string>('23:59')
const [marketInfoText, setMarketInfoText] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [selectedGroup, setSelectedGroup] = useState<Group | undefined>(
undefined
)
const [showGroupSelector, setShowGroupSelector] = useState(true)
const [category, setCategory] = useState<string>('')
const closeTime = closeDate
? dayjs(`${closeDate}T${closeHoursMinutes}`).valueOf()
: undefined
const balance = creator?.balance || 0
Numeric range markets!! (#146) * Numeric contract type * Create market numeric type * Add numeric graph (coded without testing) * Outline of numeric bet panel * Update bet panel logic * create numeric contracts * remove batching for antes for numeric markets * Remove focus * numeric market range [1, 100] * Zoom graph * Hide bet panels * getNumericBets * Add numeric resolution panel * Use getNumericBets in bet panel calc * Switch bucket count to 100 * Parallelize ante creation * placeBet for numeric markets * halve std of numeric bets * Update resolveMarket with numeric type * Set min and max for contract * lower std for numeric bets * calculateNumericDpmShares: use sorted order * Use min and max to map the input * Fix probability calc * normpdf variance mislabeled * range input * merge * change numeric graph color * fix getNewContract params * bet panel labels * validation * number input * fix bucketing * bucket input, numeric resolution panel * outcome label * merge * numeric bet panel on mobile * Make text underneath filled green answer bar selectable * Default to 'all' feed category when loading page. * fix numeric resolution panel * fix numeric bet panel calculations * display numeric resolution * don't render NumericBetPanel for non numeric markets * numeric bets: store shares, bet amounts across buckets in each bet object * restore your bets for numeric markets * numeric pnl calculations * remove hasUserHitManaLimit * contrain contract type * handle undefined allOutcomeShares * numeric ante bet amount * use correct amount for numeric dpm payouts * change numeric graph/outcome color * numeric constants * hack to show correct numeric payout in calculateDpmPayoutAfterCorrectBet * remove comment * fix ante display in bet list * halve bucket count * cast to NumericContract * fix merge imports * OUTCOME_TYPES * typo * lower bucket count to 200 * store raw numeric value with bet * store raw numeric resolution value * number input max length * create page: min, max to undefined if not numeric market * numeric resolution formatting * expected value for numeric markets * expected value for numeric markets * rearrange lines for readability * move normalpdf to util/math * show bets tab * check if outcomeMode is undefined * remove extraneous auto-merge cruft * hide comment status for numeric markets * import Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-05-19 17:42:03 +00:00
const min = minString ? parseFloat(minString) : undefined
const max = maxString ? parseFloat(maxString) : undefined
// get days from today until the end of this year:
const daysLeftInTheYear = dayjs().endOf('year').diff(dayjs(), 'day')
Numeric range markets!! (#146) * Numeric contract type * Create market numeric type * Add numeric graph (coded without testing) * Outline of numeric bet panel * Update bet panel logic * create numeric contracts * remove batching for antes for numeric markets * Remove focus * numeric market range [1, 100] * Zoom graph * Hide bet panels * getNumericBets * Add numeric resolution panel * Use getNumericBets in bet panel calc * Switch bucket count to 100 * Parallelize ante creation * placeBet for numeric markets * halve std of numeric bets * Update resolveMarket with numeric type * Set min and max for contract * lower std for numeric bets * calculateNumericDpmShares: use sorted order * Use min and max to map the input * Fix probability calc * normpdf variance mislabeled * range input * merge * change numeric graph color * fix getNewContract params * bet panel labels * validation * number input * fix bucketing * bucket input, numeric resolution panel * outcome label * merge * numeric bet panel on mobile * Make text underneath filled green answer bar selectable * Default to 'all' feed category when loading page. * fix numeric resolution panel * fix numeric bet panel calculations * display numeric resolution * don't render NumericBetPanel for non numeric markets * numeric bets: store shares, bet amounts across buckets in each bet object * restore your bets for numeric markets * numeric pnl calculations * remove hasUserHitManaLimit * contrain contract type * handle undefined allOutcomeShares * numeric ante bet amount * use correct amount for numeric dpm payouts * change numeric graph/outcome color * numeric constants * hack to show correct numeric payout in calculateDpmPayoutAfterCorrectBet * remove comment * fix ante display in bet list * halve bucket count * cast to NumericContract * fix merge imports * OUTCOME_TYPES * typo * lower bucket count to 200 * store raw numeric value with bet * store raw numeric resolution value * number input max length * create page: min, max to undefined if not numeric market * numeric resolution formatting * expected value for numeric markets * expected value for numeric markets * rearrange lines for readability * move normalpdf to util/math * show bets tab * check if outcomeMode is undefined * remove extraneous auto-merge cruft * hide comment status for numeric markets * import Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-05-19 17:42:03 +00:00
const hasUnsavedChanges = !isSubmitting && Boolean(question || description)
useWarnUnsavedChanges(hasUnsavedChanges)
const isValid =
(outcomeType === 'BINARY' ? initialProb >= 5 && initialProb <= 95 : true) &&
question.length > 0 &&
ante !== undefined &&
2022-02-06 01:02:13 +00:00
ante !== null &&
ante >= MINIMUM_ANTE &&
2022-06-23 18:00:14 +00:00
ante <= balance &&
// closeTime must be in the future
closeTime &&
Numeric range markets!! (#146) * Numeric contract type * Create market numeric type * Add numeric graph (coded without testing) * Outline of numeric bet panel * Update bet panel logic * create numeric contracts * remove batching for antes for numeric markets * Remove focus * numeric market range [1, 100] * Zoom graph * Hide bet panels * getNumericBets * Add numeric resolution panel * Use getNumericBets in bet panel calc * Switch bucket count to 100 * Parallelize ante creation * placeBet for numeric markets * halve std of numeric bets * Update resolveMarket with numeric type * Set min and max for contract * lower std for numeric bets * calculateNumericDpmShares: use sorted order * Use min and max to map the input * Fix probability calc * normpdf variance mislabeled * range input * merge * change numeric graph color * fix getNewContract params * bet panel labels * validation * number input * fix bucketing * bucket input, numeric resolution panel * outcome label * merge * numeric bet panel on mobile * Make text underneath filled green answer bar selectable * Default to 'all' feed category when loading page. * fix numeric resolution panel * fix numeric bet panel calculations * display numeric resolution * don't render NumericBetPanel for non numeric markets * numeric bets: store shares, bet amounts across buckets in each bet object * restore your bets for numeric markets * numeric pnl calculations * remove hasUserHitManaLimit * contrain contract type * handle undefined allOutcomeShares * numeric ante bet amount * use correct amount for numeric dpm payouts * change numeric graph/outcome color * numeric constants * hack to show correct numeric payout in calculateDpmPayoutAfterCorrectBet * remove comment * fix ante display in bet list * halve bucket count * cast to NumericContract * fix merge imports * OUTCOME_TYPES * typo * lower bucket count to 200 * store raw numeric value with bet * store raw numeric resolution value * number input max length * create page: min, max to undefined if not numeric market * numeric resolution formatting * expected value for numeric markets * expected value for numeric markets * rearrange lines for readability * move normalpdf to util/math * show bets tab * check if outcomeMode is undefined * remove extraneous auto-merge cruft * hide comment status for numeric markets * import Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-05-19 17:42:03 +00:00
closeTime > Date.now() &&
(outcomeType !== 'NUMERIC' ||
(min !== undefined &&
max !== undefined &&
isFinite(min) &&
isFinite(max) &&
min < max &&
max - min > 0.01))
function setCloseDateInDays(days: number) {
const newCloseDate = dayjs().add(days, 'day').format('YYYY-MM-DD')
setCloseDate(newCloseDate)
}
async function submit() {
// TODO: Tell users why their contract is invalid
if (!creator || !isValid) return
setIsSubmitting(true)
// TODO: add contract id to the group contractIds
try {
const result = await createMarket(
removeUndefinedProps({
question,
outcomeType,
description,
initialProb,
ante,
closeTime,
min,
max,
groupId: selectedGroup?.id,
})
)
track('create market', {
slug: result.slug,
initialProb,
selectedGroup: selectedGroup?.id,
2022-06-23 18:00:14 +00:00
isFree: false,
})
if (result && selectedGroup) {
await updateGroup(selectedGroup, {
contractIds: [...selectedGroup.contractIds, result.id],
})
}
await router.push(contractPath(result as Contract))
} catch (e) {
console.log('error creating contract', e)
}
}
Free response (#47) * Answer datatype and MULTI outcome type for Contract * Create free answer contract * Automatically sort Tailwind classes with Prettier (#45) * Add Prettier Tailwind plugin * Autoformat Tailwind classes with Prettier * Allow for non-binary contracts in contract page and related components * logo with white inside, transparent bg * Create answer * Some UI for showing answers * Answer bet panel * Convert rest of calcuate file to generic multi contracts * Working betting with ante'd NONE answer * Numbered answers. Layout & calculation tweaks * Can bet. More layout tweaks! * Resolve answer UI * Resolve multi market * Resolved market UI * Fix feed and cards for multi contracts * Sell bets. Various fixes * Tweaks for trades page * Always dev mode * Create answer bet has isAnte: true * Fix card showing 0% for multi contracts * Fix grouped bets feed for multi outcomes * None option converted to none of the above label at bottom of list. Button to resolve none. * Tweaks to no answers yet, resolve button layout * Show ante bets on new answers in the feed * Update placeholder text for description * Consolidate firestore rules for subcollections * Remove Contract and Bet type params. Use string type for outcomes. * Increase char limit to 10k for answers. Preserve line breaks. * Don't show resolve options after answer chosen * Fix type error in script * Remove NONE resolution option * Change outcomeType to include 'MULTI' and 'FREE_RESPONSE' * Show bet probability change and payout when creating answer * User info change: also change answers * Append answers to contract field 'answers' * sort trades by resolved * Don't include trailing !:,.; in links * Stop flooring inputs into formatMoney * Revert "Stop flooring inputs into formatMoney" This reverts commit 2f7ab1842916bc903e60231cbf45b934db2f2658. * Consistently floor user.balance * Expand create panel on focus From Richard Hanania's feedback * welcome email: include link to manifold * Fix home page in dev on branches that are not free-response * Close emails (#50) * script init for stephen dev * market close emails * order of operations * template email * sendMarketCloseEmail: handle unsubscribe * remove debugging * marketCloseEmails: every hour * sendMarketCloseEmails: check undefined * marketCloseEmails: "every hour" => "every 1 hours" * Set up a read API using Vercel serverless functions (#49) * Set up read API using Vercel serverless functions Featuring: /api/v0/markets /api/v0/market/[contractId] /api/v0/slug/[contractSlug] * Include tags in API * Tweaks. Remove filter for only binary contract * Fix bet probability change for NO bets * Put back isProd calculation Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com>
2022-02-17 23:00:19 +00:00
const descriptionPlaceholder =
outcomeType === 'BINARY'
? `e.g. This question resolves to "YES" if they receive the majority of votes...`
Free response (#47) * Answer datatype and MULTI outcome type for Contract * Create free answer contract * Automatically sort Tailwind classes with Prettier (#45) * Add Prettier Tailwind plugin * Autoformat Tailwind classes with Prettier * Allow for non-binary contracts in contract page and related components * logo with white inside, transparent bg * Create answer * Some UI for showing answers * Answer bet panel * Convert rest of calcuate file to generic multi contracts * Working betting with ante'd NONE answer * Numbered answers. Layout & calculation tweaks * Can bet. More layout tweaks! * Resolve answer UI * Resolve multi market * Resolved market UI * Fix feed and cards for multi contracts * Sell bets. Various fixes * Tweaks for trades page * Always dev mode * Create answer bet has isAnte: true * Fix card showing 0% for multi contracts * Fix grouped bets feed for multi outcomes * None option converted to none of the above label at bottom of list. Button to resolve none. * Tweaks to no answers yet, resolve button layout * Show ante bets on new answers in the feed * Update placeholder text for description * Consolidate firestore rules for subcollections * Remove Contract and Bet type params. Use string type for outcomes. * Increase char limit to 10k for answers. Preserve line breaks. * Don't show resolve options after answer chosen * Fix type error in script * Remove NONE resolution option * Change outcomeType to include 'MULTI' and 'FREE_RESPONSE' * Show bet probability change and payout when creating answer * User info change: also change answers * Append answers to contract field 'answers' * sort trades by resolved * Don't include trailing !:,.; in links * Stop flooring inputs into formatMoney * Revert "Stop flooring inputs into formatMoney" This reverts commit 2f7ab1842916bc903e60231cbf45b934db2f2658. * Consistently floor user.balance * Expand create panel on focus From Richard Hanania's feedback * welcome email: include link to manifold * Fix home page in dev on branches that are not free-response * Close emails (#50) * script init for stephen dev * market close emails * order of operations * template email * sendMarketCloseEmail: handle unsubscribe * remove debugging * marketCloseEmails: every hour * sendMarketCloseEmails: check undefined * marketCloseEmails: "every hour" => "every 1 hours" * Set up a read API using Vercel serverless functions (#49) * Set up read API using Vercel serverless functions Featuring: /api/v0/markets /api/v0/market/[contractId] /api/v0/slug/[contractSlug] * Include tags in API * Tweaks. Remove filter for only binary contract * Fix bet probability change for NO bets * Put back isProd calculation Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com>
2022-02-17 23:00:19 +00:00
: `e.g. I will choose the answer according to...`
if (!creator) return <></>
return (
2022-01-23 00:38:34 +00:00
<div>
2022-06-05 02:28:27 +00:00
<label className="label">
<span className="mb-1">Answer type</span>
Free response (#47) * Answer datatype and MULTI outcome type for Contract * Create free answer contract * Automatically sort Tailwind classes with Prettier (#45) * Add Prettier Tailwind plugin * Autoformat Tailwind classes with Prettier * Allow for non-binary contracts in contract page and related components * logo with white inside, transparent bg * Create answer * Some UI for showing answers * Answer bet panel * Convert rest of calcuate file to generic multi contracts * Working betting with ante'd NONE answer * Numbered answers. Layout & calculation tweaks * Can bet. More layout tweaks! * Resolve answer UI * Resolve multi market * Resolved market UI * Fix feed and cards for multi contracts * Sell bets. Various fixes * Tweaks for trades page * Always dev mode * Create answer bet has isAnte: true * Fix card showing 0% for multi contracts * Fix grouped bets feed for multi outcomes * None option converted to none of the above label at bottom of list. Button to resolve none. * Tweaks to no answers yet, resolve button layout * Show ante bets on new answers in the feed * Update placeholder text for description * Consolidate firestore rules for subcollections * Remove Contract and Bet type params. Use string type for outcomes. * Increase char limit to 10k for answers. Preserve line breaks. * Don't show resolve options after answer chosen * Fix type error in script * Remove NONE resolution option * Change outcomeType to include 'MULTI' and 'FREE_RESPONSE' * Show bet probability change and payout when creating answer * User info change: also change answers * Append answers to contract field 'answers' * sort trades by resolved * Don't include trailing !:,.; in links * Stop flooring inputs into formatMoney * Revert "Stop flooring inputs into formatMoney" This reverts commit 2f7ab1842916bc903e60231cbf45b934db2f2658. * Consistently floor user.balance * Expand create panel on focus From Richard Hanania's feedback * welcome email: include link to manifold * Fix home page in dev on branches that are not free-response * Close emails (#50) * script init for stephen dev * market close emails * order of operations * template email * sendMarketCloseEmail: handle unsubscribe * remove debugging * marketCloseEmails: every hour * sendMarketCloseEmails: check undefined * marketCloseEmails: "every hour" => "every 1 hours" * Set up a read API using Vercel serverless functions (#49) * Set up read API using Vercel serverless functions Featuring: /api/v0/markets /api/v0/market/[contractId] /api/v0/slug/[contractSlug] * Include tags in API * Tweaks. Remove filter for only binary contract * Fix bet probability change for NO bets * Put back isProd calculation Co-authored-by: Austin Chen <akrolsmir@gmail.com> Co-authored-by: mantikoros <sgrugett@gmail.com> Co-authored-by: mantikoros <95266179+mantikoros@users.noreply.github.com>
2022-02-17 23:00:19 +00:00
</label>
<ChoicesToggleGroup
currentChoice={outcomeType}
setChoice={(choice) => {
2022-06-02 19:27:01 +00:00
if (choice === 'FREE_RESPONSE')
setMarketInfoText(
'Users can submit their own answers to this market.'
)
else setMarketInfoText('')
2022-06-02 19:27:01 +00:00
setOutcomeType(choice as 'BINARY' | 'FREE_RESPONSE')
}}
choicesMap={{
'Yes / No': 'BINARY',
'Free response': 'FREE_RESPONSE',
}}
isSubmitting={isSubmitting}
className={'col-span-4'}
/>
{marketInfoText && (
2022-06-05 02:28:27 +00:00
<div className="mt-3 ml-1 text-sm text-indigo-700">
{marketInfoText}
</div>
)}
2022-06-05 02:28:27 +00:00
<Spacer h={6} />
Numeric range markets!! (#146) * Numeric contract type * Create market numeric type * Add numeric graph (coded without testing) * Outline of numeric bet panel * Update bet panel logic * create numeric contracts * remove batching for antes for numeric markets * Remove focus * numeric market range [1, 100] * Zoom graph * Hide bet panels * getNumericBets * Add numeric resolution panel * Use getNumericBets in bet panel calc * Switch bucket count to 100 * Parallelize ante creation * placeBet for numeric markets * halve std of numeric bets * Update resolveMarket with numeric type * Set min and max for contract * lower std for numeric bets * calculateNumericDpmShares: use sorted order * Use min and max to map the input * Fix probability calc * normpdf variance mislabeled * range input * merge * change numeric graph color * fix getNewContract params * bet panel labels * validation * number input * fix bucketing * bucket input, numeric resolution panel * outcome label * merge * numeric bet panel on mobile * Make text underneath filled green answer bar selectable * Default to 'all' feed category when loading page. * fix numeric resolution panel * fix numeric bet panel calculations * display numeric resolution * don't render NumericBetPanel for non numeric markets * numeric bets: store shares, bet amounts across buckets in each bet object * restore your bets for numeric markets * numeric pnl calculations * remove hasUserHitManaLimit * contrain contract type * handle undefined allOutcomeShares * numeric ante bet amount * use correct amount for numeric dpm payouts * change numeric graph/outcome color * numeric constants * hack to show correct numeric payout in calculateDpmPayoutAfterCorrectBet * remove comment * fix ante display in bet list * halve bucket count * cast to NumericContract * fix merge imports * OUTCOME_TYPES * typo * lower bucket count to 200 * store raw numeric value with bet * store raw numeric resolution value * number input max length * create page: min, max to undefined if not numeric market * numeric resolution formatting * expected value for numeric markets * expected value for numeric markets * rearrange lines for readability * move normalpdf to util/math * show bets tab * check if outcomeMode is undefined * remove extraneous auto-merge cruft * hide comment status for numeric markets * import Co-authored-by: mantikoros <sgrugett@gmail.com>
2022-05-19 17:42:03 +00:00
{outcomeType === 'NUMERIC' && (
<div className="form-control items-start">
<label className="label gap-2">
<span className="mb-1">Range</span>
<InfoTooltip text="The minimum and maximum numbers across the numeric range." />
</label>
<Row className="gap-2">
<input
type="number"
className="input input-bordered"
placeholder="MIN"
onClick={(e) => e.stopPropagation()}
onChange={(e) => setMinString(e.target.value)}
min={Number.MIN_SAFE_INTEGER}
max={Number.MAX_SAFE_INTEGER}
disabled={isSubmitting}
value={minString ?? ''}
/>
<input
type="number"
className="input input-bordered"
placeholder="MAX"
onClick={(e) => e.stopPropagation()}
onChange={(e) => setMaxString(e.target.value)}
min={Number.MIN_SAFE_INTEGER}
max={Number.MAX_SAFE_INTEGER}
disabled={isSubmitting}
value={maxString}
/>
</Row>
</div>
)}
<div className="form-control max-w-[265px] items-start">
2022-02-06 23:14:07 +00:00
<label className="label gap-2">
<span className="mb-1">Category</span>
2022-02-06 23:14:07 +00:00
</label>
<select
className={clsx(
'select select-bordered w-full text-sm',
category === '' ? 'font-normal text-gray-500' : ''
)}
value={category}
onChange={(e) => setCategory(e.currentTarget.value ?? '')}
>
<option value={''}>None</option>
{Object.entries(CATEGORIES).map(([id, name]) => (
<option key={id} value={id}>
{name}
</option>
))}
</select>
</div>
2022-02-06 23:14:07 +00:00
<div className={'mt-2'}>
<GroupSelector
selectedGroup={selectedGroup}
setSelectedGroup={setSelectedGroup}
creator={creator}
showSelector={showGroupSelector}
/>
</div>
2022-06-05 02:28:27 +00:00
<Spacer h={6} />
2022-02-06 23:14:07 +00:00
<div className="form-control mb-1 items-start">
<label className="label mb-1 gap-2">
2022-06-05 02:28:27 +00:00
<span>Question closes in</span>
<InfoTooltip text="Betting will be halted after this time (local timezone)." />
</label>
<Row className={'w-full items-center gap-2'}>
<ChoicesToggleGroup
currentChoice={dayjs(`${closeDate}T23:59`).diff(dayjs(), 'day')}
setChoice={(choice) => {
setCloseDateInDays(choice as number)
}}
choicesMap={{
'A day': 1,
'A week': 7,
'30 days': 30,
'This year': daysLeftInTheYear,
}}
isSubmitting={isSubmitting}
className={'col-span-4 sm:col-span-2'}
/>
</Row>
<Row>
<input
type={'date'}
className="input input-bordered mt-4"
onClick={(e) => e.stopPropagation()}
onChange={(e) =>
setCloseDate(dayjs(e.target.value).format('YYYY-MM-DD') || '')
}
min={Date.now()}
disabled={isSubmitting}
value={dayjs(closeDate).format('YYYY-MM-DD')}
/>
<input
type={'time'}
className="input input-bordered mt-4 ml-2"
onClick={(e) => e.stopPropagation()}
onChange={(e) => setCloseHoursMinutes(e.target.value)}
min={'00:00'}
disabled={isSubmitting}
value={closeHoursMinutes}
/>
</Row>
</div>
2022-06-05 02:28:27 +00:00
<Spacer h={6} />
<div className="form-control mb-1 items-start">
<label className="label mb-1 gap-2">
2022-06-05 02:28:27 +00:00
<span className="mb-1">Description</span>
<InfoTooltip text="Optional. Describe how you will resolve this question." />
</label>
2022-06-05 02:28:27 +00:00
<Textarea
className="textarea textarea-bordered w-full resize-none"
rows={3}
maxLength={MAX_DESCRIPTION_LENGTH}
placeholder={descriptionPlaceholder}
value={description}
disabled={isSubmitting}
2022-06-05 02:28:27 +00:00
onClick={(e) => e.stopPropagation()}
onChange={(e) => setDescription(e.target.value || '')}
/>
</div>
2022-06-05 02:28:27 +00:00
<Spacer h={6} />
<Row className="items-end justify-between">
<div className="form-control mb-1 items-start">
<label className="label mb-1 gap-2">
<span>Cost</span>
2022-06-23 18:00:14 +00:00
<InfoTooltip
text={`Cost to create your question. This amount is used to subsidize betting.`}
/>
2022-06-05 02:28:27 +00:00
</label>
2022-06-23 18:00:14 +00:00
<div className="label-text text-neutral pl-1">
{formatMoney(ante)}
</div>
{ante > balance && (
<div className="mb-2 mt-2 mr-auto self-center whitespace-nowrap text-xs font-medium tracking-wide">
<span className="mr-2 text-red-500">Insufficient balance</span>
<button
className="btn btn-xs btn-primary"
onClick={() => (window.location.href = '/add-funds')}
>
Get M$
</button>
2022-06-05 02:28:27 +00:00
</div>
)}
</div>
<button
type="submit"
className={clsx(
2022-06-05 02:28:27 +00:00
'btn btn-primary normal-case',
isSubmitting && 'loading disabled'
)}
disabled={isSubmitting || !isValid}
onClick={(e) => {
e.preventDefault()
submit()
}}
>
{isSubmitting ? 'Creating...' : 'Create question'}
</button>
2022-06-05 02:28:27 +00:00
</Row>
2022-01-23 00:38:34 +00:00
</div>
)
}