caelum0x 2b68bde5d5 Predikt: full Polymarket-style prediction market — web + mobile + on-chain + bots
Working tree is now the canonical repo. Off-chain play-money + trustless on-chain
(FPMM AMM + CLOB via UMA settlement), AI market factory, creator/social/distribution,
mobile shell + push, one-command demo + deploy-kit. Secrets excluded (see ENV-AND-KEYS.md).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-06 23:29:50 +03:00

173 lines
5.1 KiB
TypeScript

import { useMemo } from 'react'
import { last, map, sum, zip, keyBy, sortBy } from 'lodash'
import { scaleLinear, scaleTime } from 'd3-scale'
import { MultiNumericContract } from 'common/contract'
import { NUMERIC_GRAPH_COLOR } from 'common/numeric-constants'
import { ValueKind } from 'common/chart'
import {
getEndDate,
getRightmostVisibleDate,
getVisibleNumericYRange,
ZoomParams,
} from '../helpers'
import { SingleValueHistoryChart } from '../generic-charts'
import { SingleContractChartTooltip } from './single-value'
import { MultiPoints } from 'common/chart'
import {
formatExpectedValue,
getExpectedValue,
getMinMax,
} from 'common/src/multi-numeric'
import { getAnswerProbAtEveryBetTime } from 'common/contract-params'
const getBetPoints = (contract: MultiNumericContract, bets: MultiPoints) => {
const { shouldAnswersSumToOne } = contract
const answers = sortBy(contract.answers, 'index')
const answersById = keyBy(answers, 'id')
const filledInBetPoints = getAnswerProbAtEveryBetTime(bets, contract)
if (shouldAnswersSumToOne) {
// multiply the prob value by the value of the bucket
const expectedValues = Object.entries(filledInBetPoints).map(
([answerId, pts]) =>
pts.map((pt) => ({
x: pt.x,
y: pt.y * answersById[answerId].midpoint!,
}))
)
return map(
zip(...expectedValues) as Array<{ x: number; y: number }[]>,
(group) => ({
y: sum(group.map((pt) => pt.y)) ?? 0,
x: group[0].x,
})
)
} else {
// Handle threshold-style expected value calculation
// First, organize points by timestamp
const pointsByTimestamp: Record<number, Record<string, number>> = {}
// Group all probabilities by timestamp
Object.entries(filledInBetPoints).forEach(([answerId, pts]) => {
pts.forEach((pt) => {
const timestamp = pt.x
if (!pointsByTimestamp[timestamp]) {
pointsByTimestamp[timestamp] = {}
}
pointsByTimestamp[timestamp][answerId] = pt.y
})
})
// Calculate expected value at each timestamp
return Object.entries(pointsByTimestamp)
.map(([timestamp, probsByAnswer]) => {
const answerIds = answers.map((a) => a.id)
const probabilities = answerIds.map((id) => probsByAnswer[id] || 0)
// Calculate expected value using threshold method
let expectedValue = 0
// For each threshold except the last one
for (let i = 0; i < probabilities.length - 1; i++) {
// Calculate the probability of being in this "bucket" between thresholds
const bucketProbability = probabilities[i] - probabilities[i + 1]
// Add the contribution to the expected value
expectedValue +=
answersById[answerIds[i]].midpoint! * bucketProbability
}
// Add the contribution from the last threshold
const lastIndex = probabilities.length - 1
expectedValue +=
answersById[answerIds[lastIndex]].midpoint! * probabilities[lastIndex]
return {
x: parseInt(timestamp),
y: expectedValue,
}
})
.sort((a, b) => a.x - b.x) // Sort by timestamp
}
}
export const MultiNumericContractChart = (props: {
contract: MultiNumericContract
multiPoints: MultiPoints
width: number
height: number
zoomParams?: ZoomParams
showZoomer?: boolean
zoomY?: boolean
noWatermark?: boolean
yKind?: ValueKind
}) => {
const {
contract,
width,
multiPoints,
height,
zoomParams,
showZoomer,
zoomY,
noWatermark,
yKind,
} = props
const start = contract.createdTime
const end = getEndDate(contract)
const endP = getExpectedValue(contract)
const stringifiedMultiPoints = JSON.stringify(multiPoints)
const betPoints = useMemo(
() => getBetPoints(contract, multiPoints),
[stringifiedMultiPoints]
)
const now = useMemo(() => Date.now(), [stringifiedMultiPoints, endP])
const singlePointData = useMemo(
() => [
...(betPoints || []),
{
x: end ?? now,
y: endP,
},
],
[betPoints, end, endP, now]
)
const { min: answerMin, max: answerMax } = getMinMax(contract)
const [minY, maxY] = getVisibleNumericYRange({
data: singlePointData,
contractMin: answerMin,
contractMax: answerMax,
zoomY,
zoomParams,
})
const isYZoomed = minY !== answerMin || maxY !== answerMax
const rightmostDate = getRightmostVisibleDate(end, last(betPoints)?.x, now)
const xScale = scaleTime([start, rightmostDate], [0, width])
const yScale = scaleLinear([minY, maxY], [height, 0])
if (isYZoomed) yScale.nice()
return (
<SingleValueHistoryChart
w={width}
h={height}
xScale={xScale}
yScale={yScale}
rightmostDate={rightmostDate}
negativeThreshold={minY}
zoomParams={zoomParams}
showZoomer={showZoomer}
data={singlePointData}
Tooltip={(props) => (
<SingleContractChartTooltip
ttProps={props}
xScale={zoomParams?.viewXScale ?? xScale}
formatY={(y) => formatExpectedValue(y, contract)}
/>
)}
color={NUMERIC_GRAPH_COLOR}
noWatermark={noWatermark}
yKind={yKind}
/>
)
}