import router, { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import dayjs from 'dayjs'
import { Spacer } from 'web/components/layout/spacer'
import { getUserAndPrivateUser } from 'web/lib/firebase/users'
import { Contract, contractPath } from 'web/lib/firebase/contracts'
import { createMarket } from 'web/lib/firebase/api'
import { FIXED_ANTE, FREE_MARKETS_PER_USER_MAX } from 'common/economy'
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,
visibility,
} 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, groupPath } from 'web/lib/firebase/groups'
import { Group } from 'common/group'
import { useTracking } from 'web/hooks/use-tracking'
import { track } from 'web/lib/service/analytics'
import { GroupSelector } from 'web/components/groups/group-selector'
import { User } from 'common/user'
import { TextEditor, useTextEditor } from 'web/components/editor'
import { Checkbox } from 'web/components/checkbox'
import { redirectIfLoggedOut } from 'web/lib/firebase/server-auth'
import { Title } from 'web/components/title'
import { SEO } from 'web/components/SEO'
import { MultipleChoiceAnswers } from 'web/components/answers/multiple-choice-answers'
import { MINUTE_MS } from 'common/util/time'
import { ExternalLinkIcon } from '@heroicons/react/outline'
import { SiteLink } from 'web/components/site-link'
import { Button } from 'web/components/button'
import { AddFundsModal } from 'web/components/add-funds-modal'
import ShortToggle from 'web/components/widgets/short-toggle'
import { Input } from 'web/components/input'
import { ExpandingInput } from 'web/components/expanding-input'
export const getServerSideProps = redirectIfLoggedOut('/', async (_, creds) => {
return { props: { auth: await getUserAndPrivateUser(creds.uid) } }
})
type NewQuestionParams = {
groupId?: string
q: string
type: string
description: string
closeTime: string
outcomeType: string
visibility: string
// Params for PSEUDO_NUMERIC outcomeType
min?: string
max?: string
isLogScale?: string
initValue?: string
}
export default function Create(props: { auth: { user: User } }) {
useTracking('view create page')
const { user } = props.auth
const router = useRouter()
const params = router.query as NewQuestionParams
// TODO: Not sure why Question is pulled out as its own component;
// Maybe merge into newContract and then we don't need useEffect here.
const [question, setQuestion] = useState('')
useEffect(() => {
setQuestion(params.q ?? '')
}, [params.q])
if (!router.isReady) return
if (user.isBannedFromPosting)
return (
Sorry, you are currently banned from creating a market.
)
return (
)
}
// Allow user to create a new contract
export function NewContract(props: {
creator: User
question: string
params?: NewQuestionParams
}) {
const { creator, question, params } = props
const { groupId, initValue } = params ?? {}
const [outcomeType, setOutcomeType] = useState(
(params?.outcomeType as outcomeType) ?? 'BINARY'
)
const [initialProb] = useState(50)
const [minString, setMinString] = useState(params?.min ?? '')
const [maxString, setMaxString] = useState(params?.max ?? '')
const [isLogScale, setIsLogScale] = useState(!!params?.isLogScale)
const [initialValueString, setInitialValueString] = useState(initValue)
const [visibility, setVisibility] = useState(
(params?.visibility as visibility) ?? 'public'
)
// for multiple choice, init to 3 empty answers
const [answers, setAnswers] = useState(['', '', ''])
useEffect(() => {
if (groupId)
getGroup(groupId).then((group) => {
if (group) {
setSelectedGroup(group)
setShowGroupSelector(false)
}
})
}, [creator.id, groupId])
const [ante, _setAnte] = useState(FIXED_ANTE)
// If params.closeTime is set, extract out the specified date and time
// By default, close the market a week from today
const weekFromToday = dayjs().add(7, 'day').format('YYYY-MM-DD')
const timeInMs = Number(params?.closeTime ?? 0)
const initDate = timeInMs
? dayjs(timeInMs).format('YYYY-MM-DD')
: weekFromToday
const initTime = timeInMs ? dayjs(timeInMs).format('HH:mm') : '23:59'
const [closeDate, setCloseDate] = useState(initDate)
const [closeHoursMinutes, setCloseHoursMinutes] = useState(initTime)
const [marketInfoText, setMarketInfoText] = useState('')
const [isSubmitting, setIsSubmitting] = useState(false)
const [selectedGroup, setSelectedGroup] = useState(
undefined
)
const [showGroupSelector, setShowGroupSelector] = useState(true)
const [fundsModalOpen, setFundsModalOpen] = useState(false)
const closeTime = closeDate
? dayjs(`${closeDate}T${closeHoursMinutes}`).valueOf()
: undefined
const balance = creator.balance || 0
const deservesFreeMarket =
(creator.freeMarketsCreated ?? 0) < FREE_MARKETS_PER_USER_MAX
const min = minString ? parseFloat(minString) : undefined
const max = maxString ? parseFloat(maxString) : undefined
const initialValue = initialValueString
? parseFloat(initialValueString)
: undefined
// get days from today until the end of this year:
const daysLeftInTheYear = dayjs().endOf('year').diff(dayjs(), 'day')
const isValidMultipleChoice = answers.every(
(answer) => answer.trim().length > 0
)
const isValid =
(outcomeType === 'BINARY' ? initialProb >= 5 && initialProb <= 95 : true) &&
question.length > 0 &&
ante !== undefined &&
ante !== null &&
(ante <= balance || deservesFreeMarket) &&
// closeTime must be in the future
closeTime &&
closeTime > Date.now() &&
(outcomeType !== 'PSEUDO_NUMERIC' ||
(min !== undefined &&
max !== undefined &&
initialValue !== undefined &&
isFinite(min) &&
isFinite(max) &&
min < max &&
max - min > 0.01 &&
min < initialValue &&
initialValue < max)) &&
(outcomeType !== 'MULTIPLE_CHOICE' || isValidMultipleChoice)
const [errorText, setErrorText] = useState('')
useEffect(() => {
setErrorText('')
}, [isValid])
const descriptionPlaceholder =
outcomeType === 'BINARY'
? `e.g. This question resolves to "YES" if they receive the majority of votes...`
: `e.g. I will choose the answer according to...`
const { editor, upload } = useTextEditor({
key: 'create market',
max: MAX_DESCRIPTION_LENGTH,
placeholder: descriptionPlaceholder,
defaultValue: params?.description
? JSON.parse(params.description)
: undefined,
})
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 (!isValid) return
setIsSubmitting(true)
try {
const result = await createMarket(
removeUndefinedProps({
question,
outcomeType,
description: editor?.getJSON(),
initialProb,
ante,
closeTime,
min,
max,
initialValue,
isLogScale,
answers,
groupId: selectedGroup?.id,
visibility,
})
)
track('create market', {
slug: result.slug,
initialProb,
selectedGroup: selectedGroup?.id,
isFree: false,
})
editor?.commands.clearContent(true)
await router.push(contractPath(result as Contract))
} catch (e) {
console.error('error creating contract', e, (e as any).details)
setErrorText(
(e as any).details || (e as any).message || 'Error creating contract'
)
setIsSubmitting(false)
}
}
return (
{
if (choice === 'FREE_RESPONSE')
setMarketInfoText(
'Users can submit their own answers to this market.'
)
else setMarketInfoText('')
setOutcomeType(choice as outcomeType)
}}
choicesMap={{
'Yes / No': 'BINARY',
// 'Multiple choice': 'MULTIPLE_CHOICE',
'Free response': 'FREE_RESPONSE',
// Numeric: 'PSEUDO_NUMERIC',
}}
isSubmitting={isSubmitting}
className={'col-span-4'}
/>
{marketInfoText && (
{marketInfoText}
)}
{outcomeType === 'MULTIPLE_CHOICE' && (
)}
{outcomeType === 'PSEUDO_NUMERIC' && (
<>
e.stopPropagation()}
onChange={(e) => setInitialValueString(e.target.value)}
max={Number.MAX_SAFE_INTEGER}
disabled={isSubmitting}
value={initialValueString ?? ''}
/>
{initialValue !== undefined &&
min !== undefined &&
max !== undefined &&
min < max &&
(initialValue <= min || initialValue >= max) && (
Initial value must be in between {min} and {max}.{' '}
)}
>
)}
{showGroupSelector && selectedGroup && (
)}
Display this market on homepage
setVisibility(on ? 'public' : 'unlisted')}
/>
{
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'}
/>
e.stopPropagation()}
onChange={(e) => setCloseDate(e.target.value)}
min={Math.round(Date.now() / MINUTE_MS) * MINUTE_MS}
disabled={isSubmitting}
value={closeDate}
/>
e.stopPropagation()}
onChange={(e) => setCloseHoursMinutes(e.target.value)}
min={'00:00'}
disabled={isSubmitting}
value={closeHoursMinutes}
/>
{errorText}
{!deservesFreeMarket ? (
{formatMoney(ante)}
) : (
{formatMoney(ante)}
FREE
(You have{' '}
{FREE_MARKETS_PER_USER_MAX - (creator?.freeMarketsCreated ?? 0)}{' '}
free markets left)
)}
{ante > balance && !deservesFreeMarket && (
Insufficient balance
)}
)
}