manifold/web/pages/make-predictions.tsx

303 lines
9.3 KiB
TypeScript
Raw Normal View History

import clsx from 'clsx'
import dayjs from 'dayjs'
import Link from 'next/link'
import { useState } from 'react'
import Textarea from 'react-expanding-textarea'
import { getProbability } from '../../common/calculate-dpm'
import { parseWordsAsTags } from '../../common/util/parse'
import { AmountInput } from '../components/amount-input'
import { InfoTooltip } from '../components/info-tooltip'
import { Col } from '../components/layout/col'
import { Row } from '../components/layout/row'
import { Spacer } from '../components/layout/spacer'
import { Linkify } from '../components/linkify'
import { Page } from '../components/page'
import { Title } from '../components/title'
import { useUser } from '../hooks/use-user'
import { createContract } from '../lib/firebase/api-call'
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
import { Contract, contractPath } from '../lib/firebase/contracts'
2022-01-05 06:07:36 +00:00
type Prediction = {
question: string
description: string
initialProb: number
createdUrl?: string
}
function toPrediction(contract: Contract): Prediction {
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 startProb = getProbability(contract.totalShares)
return {
question: contract.question,
description: contract.description,
initialProb: startProb * 100,
createdUrl: contractPath(contract),
}
}
function PredictionRow(props: { prediction: Prediction }) {
const { prediction } = props
return (
<Row className="justify-between gap-4 p-4 hover:bg-gray-300">
<Col className="justify-between">
<div className="mb-2 font-medium text-indigo-700">
<Linkify text={prediction.question} />
</div>
<div className="text-sm text-gray-500">{prediction.description}</div>
</Col>
{/* Initial probability */}
<div className="ml-auto">
<div className="text-3xl">
<div className="text-primary">
{prediction.initialProb.toFixed(0)}%
<div className="text-lg">chance</div>
</div>
</div>
</div>
{/* Current probability; hidden for now */}
{/* <div>
<div className="text-3xl">
<div className="text-primary">
{prediction.initialProb}%<div className="text-lg">chance</div>
</div>
</div>
</div> */}
</Row>
)
}
function PredictionList(props: { predictions: Prediction[] }) {
const { predictions } = props
return (
<Col className="divide-y divide-gray-300 rounded-md border border-gray-300">
{predictions.map((prediction) =>
prediction.createdUrl ? (
<Link href={prediction.createdUrl}>
<a>
<PredictionRow
key={prediction.question}
prediction={prediction}
/>
</a>
</Link>
) : (
<PredictionRow key={prediction.question} prediction={prediction} />
)
)}
</Col>
)
}
const TEST_VALUE = `1. Biden approval rating (as per 538) is greater than 50%: 80%
2. Court packing is clearly going to happen (new justices don't have to be appointed by end of year): 5%
3. Yang is New York mayor: 80%
4. Newsom recalled as CA governor: 5%
5. At least $250 million in damage from BLM protests this year: 30%
6. Significant capital gains tax hike (above 30% for highest bracket): 20%`
export default function MakePredictions() {
const user = useUser()
const [predictionsString, setPredictionsString] = useState('')
const [description, setDescription] = useState('')
2022-02-01 03:13:37 +00:00
const [tags, setTags] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [createdContracts, setCreatedContracts] = useState<Contract[]>([])
const [ante, setAnte] = useState<number | undefined>(100)
const [anteError, setAnteError] = useState<string | undefined>()
// By default, close the market a week from today
const weekFromToday = dayjs().add(7, 'day').format('YYYY-MM-DDT23:59')
const [closeDate, setCloseDate] = useState<undefined | string>(weekFromToday)
const closeTime = closeDate ? dayjs(closeDate).valueOf() : undefined
const bulkPlaceholder = `e.g.
${TEST_VALUE}
...
`
const predictions: Prediction[] = []
// Parse bulkContracts, then run createContract for each
const lines = predictionsString ? predictionsString.split('\n') : []
for (const line of lines) {
// Parse line with regex
const matches = line.match(/^(.*):\s*(\d+)%\s*$/) || ['', '', '']
const [_, question, prob] = matches
if (!question || !prob) {
console.error('Invalid prediction: ', line)
continue
}
predictions.push({
question,
description,
initialProb: parseInt(prob),
})
}
async function createContracts() {
if (!user) {
// TODO: Convey error with snackbar/toast
console.error('You need to be signed in!')
return
}
setIsSubmitting(true)
for (const prediction of predictions) {
2022-01-05 06:07:36 +00:00
const contract = await createContract({
question: prediction.question,
description: prediction.description,
initialProb: prediction.initialProb,
ante,
closeTime,
2022-02-01 03:13:37 +00:00
tags: parseWordsAsTags(tags),
2022-01-05 06:07:36 +00:00
}).then((r) => (r.data as any).contract)
setCreatedContracts((prev) => [...prev, contract])
}
setPredictionsString('')
setIsSubmitting(false)
}
return (
<Page>
<Title text="Make Predictions" />
<div className="w-full rounded-lg bg-gray-100 px-6 py-4 shadow-xl">
<form>
<div className="form-control">
<label className="label">
<span className="label-text">Prediction</span>
<div className="ml-1 text-sm text-gray-500">
One prediction per line, each formatted like "The sun will rise
tomorrow: 99%"
</div>
</label>
<textarea
className="textarea textarea-bordered h-60"
placeholder={bulkPlaceholder}
value={predictionsString}
onChange={(e) => setPredictionsString(e.target.value || '')}
></textarea>
</div>
</form>
<Spacer h={4} />
<div className="form-control w-full">
<label className="label">
<span className="label-text">Description</span>
</label>
<Textarea
2022-02-01 03:13:37 +00:00
placeholder="e.g. This market is part of the ACX predictions for 2022..."
className="input"
value={description}
onChange={(e) => setDescription(e.target.value || '')}
/>
</div>
2022-02-01 03:13:37 +00:00
<div className="form-control w-full">
<label className="label">
<span className="label-text">Tags</span>
</label>
<input
type="text"
placeholder="e.g. ACX2021 World"
className="input"
value={tags}
onChange={(e) => setTags(e.target.value || '')}
/>
</div>
<div className="form-control mb-1 items-start">
<label className="label mb-1 gap-2">
<span>Market close</span>
<InfoTooltip text="Trading will be halted after this time (local timezone)." />
</label>
<input
type="datetime-local"
className="input input-bordered"
onClick={(e) => e.stopPropagation()}
onChange={(e) => setCloseDate(e.target.value || '')}
min={Date.now()}
disabled={isSubmitting}
value={closeDate}
/>
</div>
<Spacer h={4} />
<div className="form-control mb-1 items-start">
<label className="label mb-1 gap-2">
<span>Market ante</span>
<InfoTooltip
text={`Subsidize your market to encourage trading. Ante bets are set to match your initial probability.
You earn ${0.01 * 100}% of trading volume.`}
/>
</label>
<AmountInput
amount={ante}
minimumAmount={10}
onChange={setAnte}
error={anteError}
setError={setAnteError}
disabled={isSubmitting}
contractId={undefined}
/>
</div>
{predictions.length > 0 && (
<div>
<Spacer h={4} />
<label className="label">
<span className="label-text">Preview</span>
</label>
<PredictionList predictions={predictions} />
</div>
)}
<Spacer h={4} />
<div className="my-4 flex justify-end">
<button
type="submit"
className={clsx('btn btn-primary', {
loading: isSubmitting,
})}
disabled={predictions.length === 0 || isSubmitting}
onClick={(e) => {
e.preventDefault()
createContracts()
}}
>
Create all
</button>
</div>
</div>
{createdContracts.length > 0 && (
<>
<Spacer h={16} />
<Title text="Created Predictions" />
<div className="w-full rounded-lg bg-gray-100 px-6 py-4 shadow-xl">
<PredictionList predictions={createdContracts.map(toPrediction)} />
</div>
</>
)}
</Page>
)
}
// Given a date string like '2022-04-02',
// return the time just before midnight on that date (in the user's local time), as millis since epoch
function dateToMillis(date: string) {
return dayjs(date)
.set('hour', 23)
.set('minute', 59)
.set('second', 59)
.valueOf()
}