Fix before and after probs

This commit is contained in:
Ian Philips 2022-07-21 12:01:33 -06:00
parent 6051d436b8
commit ac4964f058
6 changed files with 44 additions and 51 deletions

View File

@ -37,15 +37,18 @@ export type Challenge = {
// Successful redemptions of the link // Successful redemptions of the link
acceptances: Acceptance[] acceptances: Acceptance[]
// TODO: will have to fill this on resolve contract
isResolved: boolean isResolved: boolean
resolutionOutcome?: string resolutionOutcome?: string
} }
export type Acceptance = { export type Acceptance = {
// User that accepted the challenge
userId: string userId: string
userUsername: string userUsername: string
userName: string userName: string
userAvatarUrl: string userAvatarUrl: string
// The ID of the successful bet that tracks the money moved // The ID of the successful bet that tracks the money moved
betId: string betId: string

View File

@ -8,10 +8,7 @@ import { FieldValue } from 'firebase-admin/firestore'
import { removeUndefinedProps } from '../../common/util/object' import { removeUndefinedProps } from '../../common/util/object'
import { Acceptance, Challenge } from '../../common/challenge' import { Acceptance, Challenge } from '../../common/challenge'
import { CandidateBet } from '../../common/new-bet' import { CandidateBet } from '../../common/new-bet'
import { import { getCpmmProbability } from '../../common/calculate-cpmm'
calculateCpmmPurchase,
getCpmmProbability,
} from '../../common/calculate-cpmm'
import { createChallengeAcceptedNotification } from './create-notification' import { createChallengeAcceptedNotification } from './create-notification'
const bodySchema = z.object({ const bodySchema = z.object({
@ -63,11 +60,19 @@ export const acceptchallenge = newEndpoint({}, async (req, auth) => {
throw new APIError(400, 'Challenges only accepted for binary markets.') throw new APIError(400, 'Challenges only accepted for binary markets.')
const contract = anyContract as CPMMBinaryContract const contract = anyContract as CPMMBinaryContract
log('contract stats:', contract.pool, contract.p) const { YES: y, NO: n } = contract.pool
const probs = getCpmmProbability(contract.pool, contract.p)
log('probs:', probs)
const yourShares = (1 / (1 - creatorsOutcomeProb)) * amount const yourShares = (1 / (1 - creatorsOutcomeProb)) * amount
const creatorShares = (1 / creatorsOutcomeProb) * amount
const newYesShares = creatorsOutcome === 'YES' ? creatorShares : yourShares
const newNoShares = creatorsOutcome === 'NO' ? creatorShares : yourShares
const newPool = {
YES: y + newYesShares,
NO: n + newNoShares,
}
const probBefore = getCpmmProbability(contract.pool, contract.p)
const probAfter = getCpmmProbability(newPool, contract.p)
const yourNewBet: CandidateBet = removeUndefinedProps({ const yourNewBet: CandidateBet = removeUndefinedProps({
orderAmount: amount, orderAmount: amount,
amount: amount, amount: amount,
@ -75,8 +80,8 @@ export const acceptchallenge = newEndpoint({}, async (req, auth) => {
isCancelled: false, isCancelled: false,
contractId: contract.id, contractId: contract.id,
outcome: yourOutcome, outcome: yourOutcome,
probBefore: probs, probBefore,
probAfter: probs, probAfter,
loanAmount: 0, loanAmount: 0,
createdTime: Date.now(), createdTime: Date.now(),
fees: { creatorFee: 0, platformFee: 0, liquidityFee: 0 }, fees: { creatorFee: 0, platformFee: 0, liquidityFee: 0 },
@ -92,15 +97,6 @@ export const acceptchallenge = newEndpoint({}, async (req, auth) => {
trans.update(userDoc, { balance: FieldValue.increment(-yourNewBet.amount) }) trans.update(userDoc, { balance: FieldValue.increment(-yourNewBet.amount) })
log('Updated user balance.') log('Updated user balance.')
let cpmmState = { pool: contract.pool, p: contract.p }
const { newPool, newP } = calculateCpmmPurchase(
cpmmState,
yourNewBet.amount,
yourNewBet.outcome
)
cpmmState = { pool: newPool, p: newP }
const creatorShares = (1 / creatorsOutcomeProb) * amount
const creatorNewBet: CandidateBet = removeUndefinedProps({ const creatorNewBet: CandidateBet = removeUndefinedProps({
orderAmount: amount, orderAmount: amount,
amount: amount, amount: amount,
@ -108,8 +104,8 @@ export const acceptchallenge = newEndpoint({}, async (req, auth) => {
isCancelled: false, isCancelled: false,
contractId: contract.id, contractId: contract.id,
outcome: creatorsOutcome, outcome: creatorsOutcome,
probBefore: probs, probBefore,
probAfter: probs, probAfter,
loanAmount: 0, loanAmount: 0,
createdTime: Date.now(), createdTime: Date.now(),
fees: { creatorFee: 0, platformFee: 0, liquidityFee: 0 }, fees: { creatorFee: 0, platformFee: 0, liquidityFee: 0 },
@ -126,19 +122,11 @@ export const acceptchallenge = newEndpoint({}, async (req, auth) => {
balance: FieldValue.increment(-creatorNewBet.amount), balance: FieldValue.increment(-creatorNewBet.amount),
}) })
log('Updated user balance.') log('Updated user balance.')
const newPurchaseStats = calculateCpmmPurchase(
cpmmState,
creatorNewBet.amount,
creatorNewBet.outcome
)
cpmmState = { pool: newPurchaseStats.newPool, p: newPurchaseStats.newP }
trans.update( trans.update(
contractDoc, contractDoc,
removeUndefinedProps({ removeUndefinedProps({
pool: cpmmState.pool, pool: newPool,
// p shouldn't have changed
p: contract.p,
volume: contract.volume + yourNewBet.amount + creatorNewBet.amount, volume: contract.volume + yourNewBet.amount + creatorNewBet.amount,
}) })
) )
@ -160,6 +148,7 @@ export const acceptchallenge = newEndpoint({}, async (req, auth) => {
], ],
}) })
) )
log('Updated challenge properties with new acceptance.')
await createChallengeAcceptedNotification( await createChallengeAcceptedNotification(
user, user,
@ -167,6 +156,7 @@ export const acceptchallenge = newEndpoint({}, async (req, auth) => {
challenge, challenge,
contract contract
) )
log('Created notification.')
return yourNewBetDoc return yourNewBetDoc
}) })

View File

@ -8,7 +8,6 @@ import { useUser } from 'web/hooks/use-user'
import { useUserContractBets } from 'web/hooks/use-user-bets' import { useUserContractBets } from 'web/hooks/use-user-bets'
import { useSaveBinaryShares } from './use-save-binary-shares' import { useSaveBinaryShares } from './use-save-binary-shares'
import { Col } from './layout/col' import { Col } from './layout/col'
import { CreateChallengeButton } from 'web/components/challenges/create-challenge-button'
// Inline version of a bet panel. Opens BetPanel in a new modal. // Inline version of a bet panel. Opens BetPanel in a new modal.
export default function BetRow(props: { export default function BetRow(props: {
@ -49,10 +48,6 @@ export default function BetRow(props: {
: ''} : ''}
</div> </div>
</Col> </Col>
<Col className={clsx('items-center', className)}>
<CreateChallengeButton user={user} contract={contract} />
</Col>
<Modal open={open} setOpen={setOpen}> <Modal open={open} setOpen={setOpen}>
<SimpleBetPanel <SimpleBetPanel
className={betPanelClassName} className={betPanelClassName}

View File

@ -1,4 +1,4 @@
import React, { Fragment } from 'react' import React, { Fragment, useEffect } from 'react'
import { LinkIcon } from '@heroicons/react/outline' import { LinkIcon } from '@heroicons/react/outline'
import { Menu, Transition } from '@headlessui/react' import { Menu, Transition } from '@headlessui/react'
import clsx from 'clsx' import clsx from 'clsx'

View File

@ -46,8 +46,6 @@ import { CommentTipMap, useTipTxns } from 'web/hooks/use-tip-txns'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import { useLiquidity } from 'web/hooks/use-liquidity' import { useLiquidity } from 'web/hooks/use-liquidity'
import { richTextToString } from 'common/util/parse' import { richTextToString } from 'common/util/parse'
import { CreateChallengeButton } from 'web/components/challenges/create-challenge-button'
import { Row } from 'web/components/layout/row'
export const getStaticProps = fromPropz(getStaticPropz) export const getStaticProps = fromPropz(getStaticPropz)
export async function getStaticPropz(props: { export async function getStaticPropz(props: {
@ -176,9 +174,6 @@ export function ContractPageContent(
<NumericBetPanel className="hidden xl:flex" contract={contract} /> <NumericBetPanel className="hidden xl:flex" contract={contract} />
) : ( ) : (
<div> <div>
<Row className={'my-4 hidden justify-end xl:flex'}>
<CreateChallengeButton user={user} contract={contract} />
</Row>
<BetPanel <BetPanel
className="hidden xl:flex" className="hidden xl:flex"
contract={contract as CPMMBinaryContract} contract={contract as CPMMBinaryContract}

View File

@ -103,6 +103,7 @@ export default function ChallengePage(props: {
contract={contract} contract={contract}
challenge={challenge} challenge={challenge}
creator={user} creator={user}
bets={bets}
/> />
) )
} }
@ -282,7 +283,7 @@ function ChallengeContract(props: { contract: Contract; bets: Bet[] }) {
const isBinary = contract.outcomeType === 'BINARY' const isBinary = contract.outcomeType === 'BINARY'
const isPseudoNumeric = contract.outcomeType === 'PSEUDO_NUMERIC' const isPseudoNumeric = contract.outcomeType === 'PSEUDO_NUMERIC'
return ( return (
<Col className="w-full flex-1 bg-white"> <Col className="mt-5 w-full flex-1 bg-white px-10">
<div className="relative flex flex-col pt-2"> <div className="relative flex flex-col pt-2">
<Row className="justify-between px-3 text-xl text-indigo-700 md:text-2xl"> <Row className="justify-between px-3 text-xl text-indigo-700 md:text-2xl">
<SiteLink href={href}>{question}</SiteLink> <SiteLink href={href}>{question}</SiteLink>
@ -292,13 +293,9 @@ function ChallengeContract(props: { contract: Contract; bets: Bet[] }) {
)} )}
</Row> </Row>
<Spacer h={3} /> {(isBinary || isPseudoNumeric) && (
<ContractProbGraph contract={contract} bets={bets} height={400} />
<div className="mx-1" style={{ paddingBottom: 50 }}> )}
{(isBinary || isPseudoNumeric) && (
<ContractProbGraph contract={contract} bets={bets} height={500} />
)}
</div>
</div> </div>
</Col> </Col>
) )
@ -309,8 +306,9 @@ function OpenChallengeContent(props: {
challenge: Challenge challenge: Challenge
creator: User creator: User
user: User | null | undefined user: User | null | undefined
bets: Bet[]
}) { }) {
const { contract, challenge, creator, user } = props const { contract, challenge, creator, user, bets } = props
const { question } = contract const { question } = contract
const [creatorPortfolioHistory, setUsersCreatorPortfolioHistory] = useState< const [creatorPortfolioHistory, setUsersCreatorPortfolioHistory] = useState<
PortfolioMetrics[] PortfolioMetrics[]
@ -332,6 +330,9 @@ function OpenChallengeContent(props: {
(containerRef?.offsetTop ?? 0) - (containerRef?.offsetTop ?? 0) -
bottomBarHeight bottomBarHeight
const isBinary = contract.outcomeType === 'BINARY'
const isPseudoNumeric = contract.outcomeType === 'PSEUDO_NUMERIC'
const userColumn = ( const userColumn = (
challenger: User | null | undefined, challenger: User | null | undefined,
portfolioHistory: PortfolioMetrics[], portfolioHistory: PortfolioMetrics[],
@ -389,8 +390,17 @@ function OpenChallengeContent(props: {
<Col <Col
ref={setContainerRef} ref={setContainerRef}
style={{ height: remainingHeight }} style={{ height: remainingHeight }}
className=" w-full justify-between rounded border-0 border-gray-100 bg-white py-6 pl-1 pr-2 sm:px-2 md:px-6 md:py-8" className=" relative w-full justify-between rounded border-0 border-gray-100 bg-white py-6 pl-1 pr-2 sm:px-2 md:px-6 md:py-8"
> >
{(isBinary || isPseudoNumeric) && (
<div
className={`absolute top-52 flex h-[${
remainingHeight / 2
}] w-full flex-row opacity-40`}
>
<ContractProbGraph contract={contract} bets={bets} height={400} />
</div>
)}
<Row className="px-3 pb-4 text-xl text-indigo-700 md:text-2xl"> <Row className="px-3 pb-4 text-xl text-indigo-700 md:text-2xl">
<SiteLink href={href}>{question}</SiteLink> <SiteLink href={href}>{question}</SiteLink>
</Row> </Row>