manifold/web/components/contract/contract-prob-graph.tsx

170 lines
4.8 KiB
TypeScript
Raw Normal View History

2021-12-13 01:10:28 +00:00
import { DatumValue } from '@nivo/core'
import { ResponsiveLine, SliceTooltipProps } from '@nivo/line'
import { BasicTooltip } from '@nivo/tooltip'
2021-12-13 06:55:28 +00:00
import dayjs from 'dayjs'
import { memo } from 'react'
import { Bet } from 'common/bet'
import { getInitialProbability } from 'common/calculate'
import { BinaryContract } from 'common/contract'
import { useWindowSize } from 'web/hooks/use-window-size'
2021-12-12 22:14:52 +00:00
export const ContractProbGraph = memo(function ContractProbGraph(props: {
contract: BinaryContract
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
bets: Bet[]
height?: number
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
}) {
const { contract, height } = props
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
const { resolutionTime, closeTime } = contract
2021-12-12 22:14:52 +00:00
const bets = props.bets.filter((bet) => !bet.isAnte && !bet.isRedemption)
2021-12-12 22:14:52 +00:00
Cfmm (#64) * cpmm initial commit: common logic, cloud functions * remove unnecessary property * contract type * rename 'calculate.ts' => 'calculate-dpm.ts' * rename dpm calculations * use focus hook * mechanism-agnostic calculations * bet panel: use new calculations * use new calculations * delete markets cloud function * use correct contract type in scripts / functions * calculate fixed payouts; bets list calculations * new bet: use calculateCpmmPurchase * getOutcomeProbabilityAfterBet * use deductFixedFees * fix auto-refactor * fix antes * separate logic to payouts-dpm, payouts-fixed * liquidity provision tracking * remove comment * liquidity label * create liquidity provision even if no ante bet * liquidity fee * use all bets for getFixedCancelPayouts * updateUserBalance: allow negative balances * store initialProbability in contracts * turn on liquidity fee; turn off creator fee * Include time param in tweet url, so image preview is re-fetched * share redemption * cpmm ContractBetsTable display * formatMoney: handle minus zero * filter out redemption bets * track fees on contract and bets; change fee schedule for cpmm markets; only pay out creator fees at resolution * small fixes * small fixes * Redeem shares pays back loans first * Fix initial point on graph * calculateCpmmPurchase: deduct creator fee * Filter out redemption bets from feed * set env to dev for user-testing purposes * creator fees messaging * new cfmm: k = y^(1-p) * n^p * addCpmmLiquidity * correct price function * enable fees * handle overflow * liquidity provision tracking * raise fees * Fix merge error * fix dpm free response payout for single outcome * Fix DPM payout calculation * Remove hardcoding as dev Co-authored-by: James Grugett <jahooma@gmail.com>
2022-03-15 22:27:51 +00:00
const startProb = getInitialProbability(contract)
const times = [
contract.createdTime,
...bets.map((bet) => bet.createdTime),
].map((time) => new Date(time))
const probs = [startProb, ...bets.map((bet) => bet.probAfter)]
2022-02-08 05:43:35 +00:00
const isClosed = !!closeTime && Date.now() > closeTime
const latestTime = dayjs(
2022-02-08 05:43:35 +00:00
resolutionTime && isClosed
? Math.min(resolutionTime, closeTime)
2022-02-08 05:43:35 +00:00
: isClosed
? closeTime
: resolutionTime ?? Date.now()
)
2021-12-16 06:44:04 +00:00
// Add a fake datapoint so the line continues to the right
times.push(latestTime.toDate())
probs.push(probs[probs.length - 1])
const yTickValues = [0, 25, 50, 75, 100]
2021-12-13 01:10:28 +00:00
const { width } = useWindowSize()
2021-12-16 06:44:04 +00:00
const numXTickValues = !width || width < 800 ? 2 : 5
const hoursAgo = latestTime.subtract(5, 'hours')
const startDate = dayjs(times[0]).isBefore(hoursAgo)
? times[0]
: hoursAgo.toDate()
// Minimum number of points for the graph to have. For smooth tooltip movement
// On first load, width is undefined, skip adding extra points to let page load faster
// This fn runs again once DOM is finished loading
const totalPoints = width ? (width > 800 ? 300 : 50) : 1
const timeStep: number = latestTime.diff(startDate, 'ms') / totalPoints
const points: { x: Date; y: number }[] = []
for (let i = 0; i < times.length; i++) {
points[points.length] = { x: times[i], y: probs[i] * 100 }
const numPoints: number = Math.floor(
dayjs(times[i + 1]).diff(dayjs(times[i]), 'ms') / timeStep
)
if (numPoints > 1) {
const thisTimeStep: number =
dayjs(times[i + 1]).diff(dayjs(times[i]), 'ms') / numPoints
for (let n = 1; n < numPoints; n++) {
points[points.length] = {
x: dayjs(times[i])
.add(thisTimeStep * n, 'ms')
.toDate(),
y: probs[i] * 100,
}
}
}
}
const data = [{ id: 'Yes', data: points, color: '#11b981' }]
const multiYear = !dayjs(startDate).isSame(latestTime, 'year')
const lessThanAWeek = dayjs(startDate).add(8, 'day').isAfter(latestTime)
2021-12-16 06:44:04 +00:00
2021-12-13 01:10:28 +00:00
return (
2022-01-18 23:10:21 +00:00
<div
className="w-full overflow-visible"
style={{ height: height ?? (!width || width >= 800 ? 350 : 250) }}
2022-01-18 23:10:21 +00:00
>
2021-12-13 01:10:28 +00:00
<ResponsiveLine
data={data}
yScale={{ min: 0, max: 100, type: 'linear' }}
yFormat={formatPercent}
gridYValues={yTickValues}
2021-12-13 01:10:28 +00:00
axisLeft={{
tickValues: yTickValues,
2021-12-13 01:10:28 +00:00
format: formatPercent,
}}
xScale={{
type: 'time',
min: startDate,
2021-12-16 06:44:04 +00:00
max: latestTime.toDate(),
}}
xFormat={(d) =>
formatTime(+d.valueOf(), multiYear, lessThanAWeek, lessThanAWeek)
}
2021-12-13 01:10:28 +00:00
axisBottom={{
tickValues: numXTickValues,
format: (time) => formatTime(+time, multiYear, lessThanAWeek, false),
2021-12-13 01:10:28 +00:00
}}
colors={{ datum: 'color' }}
curve="stepAfter"
enablePoints={false}
2021-12-13 06:55:28 +00:00
pointBorderWidth={1}
2021-12-13 01:10:28 +00:00
pointBorderColor="#fff"
enableSlices="x"
enableGridX={!!width && width >= 800}
2021-12-13 01:10:28 +00:00
enableArea
margin={{ top: 20, right: 20, bottom: 25, left: 40 }}
2022-06-08 15:12:33 +00:00
animate={false}
sliceTooltip={SliceTooltip}
2021-12-13 01:10:28 +00:00
/>
</div>
)
})
2021-12-12 22:14:52 +00:00
const SliceTooltip = ({ slice }: SliceTooltipProps) => {
return (
<BasicTooltip
id={slice.points.map((point) => [
<span key="date">
<strong>{point.data[`yFormatted`]}</strong> {point.data['xFormatted']}
</span>,
])}
/>
)
}
2021-12-13 01:10:28 +00:00
function formatPercent(y: DatumValue) {
return `${Math.round(+y.toString())}%`
2021-12-12 22:14:52 +00:00
}
2021-12-13 06:55:28 +00:00
function formatTime(
time: number,
includeYear: boolean,
includeHour: boolean,
includeMinute: boolean
) {
2021-12-13 06:55:28 +00:00
const d = dayjs(time)
if (d.add(1, 'minute').isAfter(Date.now())) return 'Now'
let format: string
if (d.isSame(Date.now(), 'day')) {
format = '[Today]'
} else if (d.add(1, 'day').isSame(Date.now(), 'day')) {
format = '[Yesterday]'
} else {
format = 'MMM D'
}
if (includeMinute) {
format += ', h:mma'
} else if (includeHour) {
format += ', ha'
} else if (includeYear) {
format += ', YYYY'
}
return d.format(format)
2021-12-13 06:55:28 +00:00
}