manifold/web/components/bets-list.tsx

602 lines
17 KiB
TypeScript
Raw Normal View History

2021-12-15 07:41:50 +00:00
import Link from 'next/link'
import _ from 'lodash'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import clsx from 'clsx'
2021-12-15 07:41:50 +00:00
import { useUserBets } from '../hooks/use-user-bets'
import { Bet } from '../lib/firebase/bets'
import { User } from '../lib/firebase/users'
2021-12-31 20:13:06 +00:00
import {
formatMoney,
formatPercent,
formatWithCommas,
} from '../../common/util/format'
2021-12-15 07:41:50 +00:00
import { Col } from './layout/col'
2021-12-15 18:41:18 +00:00
import { Spacer } from './layout/spacer'
import {
Contract,
getContractFromId,
contractPath,
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
getBinaryProbPercent,
} from '../lib/firebase/contracts'
import { Row } from './layout/row'
2021-12-16 02:11:29 +00:00
import { UserLink } from './user-page'
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
import { sellBet } from '../lib/firebase/api-call'
import { ConfirmationButton } from './confirmation-button'
import { OutcomeLabel, YesLabel, NoLabel } from './outcome-label'
import { filterDefined } from '../../common/util/array'
import { LoadingIndicator } from './loading-indicator'
import { SiteLink } from './site-link'
import {
calculatePayout,
calculateSaleAmount,
getOutcomeProbability,
getProbabilityAfterSale,
getContractBetMetrics,
resolvedPayout,
getContractBetNullMetrics,
} from '../../common/calculate'
2021-12-15 07:41:50 +00:00
2022-04-13 23:56:28 +00:00
type BetSort = 'newest' | 'profit' | 'closeTime' | 'value'
2022-03-13 20:55:42 +00:00
type BetFilter = 'open' | 'closed' | 'resolved' | 'all'
2021-12-15 07:41:50 +00:00
export function BetsList(props: { user: User }) {
const { user } = props
const bets = useUserBets(user.id)
2021-12-15 07:41:50 +00:00
const [contracts, setContracts] = useState<Contract[] | undefined>()
const [sort, setSort] = useState<BetSort>('newest')
2022-03-13 20:55:42 +00:00
const [filter, setFilter] = useState<BetFilter>('open')
useEffect(() => {
if (bets) {
const contractIds = _.uniq(bets.map((bet) => bet.contractId))
let disposed = false
Promise.all(contractIds.map((id) => getContractFromId(id))).then(
(contracts) => {
if (!disposed) setContracts(filterDefined(contracts))
}
)
return () => {
disposed = true
}
}
}, [bets])
if (!bets || !contracts) {
return <LoadingIndicator />
2021-12-15 07:41:50 +00:00
}
if (bets.length === 0) return <NoBets />
2021-12-16 04:40:48 +00:00
// Decending creation time.
bets.sort((bet1, bet2) => bet2.createdTime - bet1.createdTime)
2021-12-15 07:41:50 +00:00
const contractBets = _.groupBy(bets, 'contractId')
2022-03-13 20:55:42 +00:00
const contractsById = _.fromPairs(contracts.map((c) => [c.id, c]))
2021-12-15 07:41:50 +00:00
const contractsMetrics = _.mapValues(contractBets, (bets, contractId) => {
const contract = contractsById[contractId]
if (!contract) return getContractBetNullMetrics()
return getContractBetMetrics(contract, bets)
})
2022-03-13 20:55:42 +00:00
const FILTERS: Record<BetFilter, (c: Contract) => boolean> = {
resolved: (c) => !!c.resolutionTime,
closed: (c) =>
!FILTERS.resolved(c) && (c.closeTime ?? Infinity) < Date.now(),
open: (c) => !(FILTERS.closed(c) || FILTERS.resolved(c)),
all: () => true,
}
const SORTS: Record<BetSort, (c: Contract) => number> = {
profit: (c) => contractsMetrics[c.id].profit,
value: (c) => contractsMetrics[c.id].payout,
2022-03-13 20:55:42 +00:00
newest: (c) =>
Math.max(...contractBets[c.id].map((bet) => bet.createdTime)),
2022-04-13 23:56:28 +00:00
closeTime: (c) =>
// This is in fact the intuitive sort direction.
(filter === 'open' ? -1 : 1) *
(c.resolutionTime ?? c.closeTime ?? Infinity),
2022-03-13 20:55:42 +00:00
}
const displayedContracts = _.sortBy(contracts, SORTS[sort])
.reverse()
.filter(FILTERS[filter])
2022-02-26 00:57:28 +00:00
const [settled, unsettled] = _.partition(
2022-03-13 20:55:42 +00:00
contracts,
(c) => c.isResolved || contractsMetrics[c.id].invested === 0
)
const currentInvested = _.sumBy(
unsettled,
(c) => contractsMetrics[c.id].invested
)
const currentBetsValue = _.sumBy(
2022-02-26 00:57:28 +00:00
unsettled,
(c) => contractsMetrics[c.id].payout
)
const currentNetInvestment = _.sumBy(
unsettled,
2022-04-14 03:28:29 +00:00
(c) => contractsMetrics[c.id].netPayout
)
const totalPortfolio = currentNetInvestment + user.balance
2022-02-14 19:00:20 +00:00
2022-02-14 23:29:29 +00:00
const totalPnl = totalPortfolio - user.totalDeposits
const totalProfitPercent = (totalPnl / user.totalDeposits) * 100
const investedProfitPercent =
2022-04-14 03:28:29 +00:00
((currentBetsValue - currentInvested) / (currentInvested + 0.1)) * 100
2022-02-14 22:00:35 +00:00
2021-12-15 07:41:50 +00:00
return (
2022-04-14 05:06:13 +00:00
<Col className="mt-6">
<Col className="mx-4 gap-4 sm:flex-row sm:justify-between md:mx-0">
<Row className="gap-8">
2022-02-14 19:00:20 +00:00
<Col>
2022-03-02 23:48:38 +00:00
<div className="text-sm text-gray-500">Investment value</div>
2022-02-14 23:29:29 +00:00
<div className="text-lg">
{formatMoney(currentNetInvestment)}{' '}
<ProfitBadge profitPercent={investedProfitPercent} />
2022-02-14 19:00:20 +00:00
</div>
</Col>
<Col>
<div className="text-sm text-gray-500">Total profit</div>
2022-02-14 23:29:29 +00:00
<div className="text-lg">
{formatMoney(totalPnl)}{' '}
<ProfitBadge profitPercent={totalProfitPercent} />
2022-02-14 23:29:29 +00:00
</div>
</Col>
</Row>
2022-03-13 20:55:42 +00:00
<Row className="gap-8">
<select
className="select select-bordered self-start"
value={filter}
onChange={(e) => setFilter(e.target.value as BetFilter)}
>
<option value="open">Open</option>
<option value="closed">Closed</option>
<option value="resolved">Resolved</option>
<option value="all">All</option>
</select>
<select
className="select select-bordered self-start"
value={sort}
onChange={(e) => setSort(e.target.value as BetSort)}
>
2022-04-15 22:55:26 +00:00
<option value="newest">Recent</option>
2022-04-13 23:56:28 +00:00
<option value="value">Value</option>
<option value="profit">Profit</option>
<option value="closeTime">Close date</option>
2022-03-13 20:55:42 +00:00
</select>
</Row>
</Col>
2022-04-14 05:06:13 +00:00
<Col className="mt-6 divide-y">
{displayedContracts.length === 0 ? (
<NoBets />
) : (
displayedContracts.map((contract) => (
<MyContractBets
key={contract.id}
contract={contract}
bets={contractBets[contract.id] ?? []}
metric={sort === 'profit' ? 'profit' : 'value'}
/>
))
)}
</Col>
2021-12-15 07:41:50 +00:00
</Col>
)
}
const NoBets = () => {
return (
<div className="mx-4 text-gray-500">
You have not made any bets yet.{' '}
<SiteLink href="/" className="underline">
Find a prediction market!
</SiteLink>
</div>
)
}
function MyContractBets(props: {
contract: Contract
bets: Bet[]
metric: 'profit' | 'value'
}) {
const { bets, contract, metric } = props
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 { resolution, outcomeType } = contract
const [collapsed, setCollapsed] = useState(true)
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 isBinary = outcomeType === 'BINARY'
const probPercent = getBinaryProbPercent(contract)
const { payout, profit, profitPercent } = getContractBetMetrics(
contract,
bets
)
2021-12-15 07:41:50 +00:00
return (
<div
tabIndex={0}
className={clsx(
2022-04-14 05:06:13 +00:00
'collapse collapse-arrow relative cursor-pointer bg-white p-4 pr-6',
collapsed ? 'collapse-close' : 'collapse-open pb-2'
)}
onClick={() => setCollapsed((collapsed) => !collapsed)}
>
2022-02-14 23:39:59 +00:00
<Row className="flex-wrap gap-2">
<Col className="flex-[2] gap-1">
2022-02-14 23:39:59 +00:00
<Row className="mr-2 max-w-lg">
<Link href={contractPath(contract)}>
2021-12-16 21:28:56 +00:00
<a
className="font-medium text-indigo-700 hover:underline hover:decoration-indigo-400 hover:decoration-2"
onClick={(e) => e.stopPropagation()}
>
{contract.question}
</a>
</Link>
2021-12-18 23:40:39 +00:00
{/* Show carrot for collapsing. Hack the positioning. */}
<div
className="collapse-title absolute h-0 min-h-0 w-0 p-0"
2022-04-14 05:06:13 +00:00
style={{ top: -10, right: 0 }}
2021-12-18 23:40:39 +00:00
/>
</Row>
2022-02-26 00:57:28 +00:00
<Row className="flex-1 items-center gap-2 text-sm text-gray-500">
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
{isBinary && (
<>
{resolution ? (
<div>
Resolved <OutcomeLabel outcome={resolution} />
</div>
) : (
<div className="text-primary text-lg">{probPercent}</div>
)}
<div></div>
</>
2022-02-09 04:52:09 +00:00
)}
<UserLink
name={contract.creatorName}
username={contract.creatorUsername}
/>
</Row>
</Col>
<Row className="mr-5 justify-end sm:mr-8">
<Col>
<div className="whitespace-nowrap text-right text-lg">
{formatMoney(metric === 'profit' ? profit : payout)}
</div>
<div className="text-right">
<ProfitBadge profitPercent={profitPercent} />
</div>
</Col>
</Row>
</Row>
<div
className="collapse-content !px-0"
style={{ backgroundColor: 'white' }}
>
<Spacer h={8} />
2022-02-14 22:00:35 +00:00
<MyBetsSummary
className="mr-5 flex-1 sm:mr-8"
contract={contract}
bets={bets}
/>
<Spacer h={8} />
<ContractBetsTable contract={contract} bets={bets} />
</div>
2021-12-15 07:41:50 +00:00
</div>
)
}
2021-12-16 04:30:24 +00:00
export function MyBetsSummary(props: {
contract: Contract
bets: Bet[]
className?: string
}) {
const { bets, contract, className } = props
const { resolution, outcomeType, mechanism } = contract
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 isBinary = outcomeType === 'BINARY'
const isCpmm = mechanism === 'cpmm-1'
2021-12-16 04:30:24 +00:00
const excludeSales = bets.filter((b) => !b.isSold && !b.sale)
const yesWinnings = _.sumBy(excludeSales, (bet) =>
2021-12-16 04:30:24 +00:00
calculatePayout(contract, bet, 'YES')
)
const noWinnings = _.sumBy(excludeSales, (bet) =>
2021-12-16 04:30:24 +00:00
calculatePayout(contract, bet, 'NO')
)
const { invested, profitPercent, payout, profit } = getContractBetMetrics(
contract,
bets
2022-02-14 22:00:35 +00:00
)
2021-12-16 04:30:24 +00:00
return (
<Row className={clsx('flex-wrap gap-4 sm:flex-nowrap sm:gap-6', className)}>
<Row className="gap-4 sm:gap-6">
{!isCpmm && (
<Col>
<div className="whitespace-nowrap text-sm text-gray-500">
Invested
</div>
<div className="whitespace-nowrap">{formatMoney(invested)}</div>
</Col>
)}
{resolution ? (
2021-12-16 04:30:24 +00:00
<Col>
<div className="text-sm text-gray-500">Payout</div>
<div className="whitespace-nowrap">
{formatMoney(payout)}{' '}
<ProfitBadge profitPercent={profitPercent} />
2021-12-16 04:30:24 +00:00
</div>
</Col>
) : (
<>
{isBinary ? (
<>
<Col>
<div className="whitespace-nowrap text-sm text-gray-500">
Payout if <YesLabel />
</div>
<div className="whitespace-nowrap">
{formatMoney(yesWinnings)}
</div>
</Col>
<Col>
<div className="whitespace-nowrap text-sm text-gray-500">
Payout if <NoLabel />
</div>
<div className="whitespace-nowrap">
{formatMoney(noWinnings)}
</div>
</Col>
</>
) : (
<Col>
<div className="whitespace-nowrap text-sm text-gray-500">
Current value
</div>
<div className="whitespace-nowrap">{formatMoney(payout)}</div>
</Col>
)}
</>
)}
<Col>
<div className="whitespace-nowrap text-sm text-gray-500">Profit</div>
<div className="whitespace-nowrap">
{formatMoney(profit)} <ProfitBadge profitPercent={profitPercent} />
</div>
</Col>
</Row>
2021-12-16 04:30:24 +00:00
</Row>
)
}
export function ContractBetsTable(props: {
contract: Contract
bets: Bet[]
className?: string
}) {
const { contract, bets, className } = props
const [sales, buys] = _.partition(bets, (bet) => bet.sale)
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 salesDict = _.fromPairs(
sales.map((sale) => [sale.sale?.betId ?? '', sale])
)
const [redemptions, normalBets] = _.partition(
contract.mechanism === 'cpmm-1' ? bets : buys,
(b) => b.isRedemption
)
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 amountRedeemed = Math.floor(
-0.5 * _.sumBy(redemptions, (b) => b.shares)
)
const amountLoaned = _.sumBy(
bets.filter((bet) => !bet.isSold && !bet.sale),
(bet) => bet.loanAmount ?? 0
)
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 { isResolved, mechanism } = contract
const isCPMM = mechanism === 'cpmm-1'
return (
<div className={clsx('overflow-x-auto', className)}>
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
{amountRedeemed > 0 && (
<>
2022-03-21 02:30:04 +00:00
<div className="pl-2 text-sm text-gray-500">
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
{amountRedeemed} YES shares and {amountRedeemed} NO shares
automatically redeemed for {formatMoney(amountRedeemed)}.
</div>
<Spacer h={4} />
</>
)}
{!isResolved && amountLoaned > 0 && (
<>
2022-03-21 02:30:04 +00:00
<div className="pl-2 text-sm text-gray-500">
You currently have a loan of {formatMoney(amountLoaned)}.
</div>
<Spacer h={4} />
</>
)}
<table className="table-zebra table-compact table w-full text-gray-500">
<thead>
<tr className="p-2">
<th></th>
{isCPMM && <th>Type</th>}
<th>Outcome</th>
<th>Amount</th>
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
{!isCPMM && <th>{isResolved ? <>Payout</> : <>Sale price</>}</th>}
{!isCPMM && !isResolved && <th>Payout if chosen</th>}
2021-12-31 20:13:06 +00:00
<th>Shares</th>
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
<th>Probability</th>
<th>Date</th>
</tr>
</thead>
<tbody>
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
{normalBets.map((bet) => (
<BetRow
key={bet.id}
bet={bet}
2022-01-15 22:51:09 +00:00
saleBet={salesDict[bet.id]}
contract={contract}
/>
))}
</tbody>
</table>
</div>
)
}
2022-01-15 22:51:09 +00:00
function BetRow(props: { bet: Bet; contract: Contract; saleBet?: Bet }) {
const { bet, saleBet, contract } = props
const {
amount,
outcome,
createdTime,
probBefore,
probAfter,
shares,
isSold,
2022-01-19 22:36:55 +00:00
isAnte,
} = bet
2022-01-19 22:36:55 +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 { isResolved, closeTime, mechanism } = contract
const isClosed = closeTime && Date.now() > closeTime
2021-12-15 07:41:50 +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 isCPMM = mechanism === 'cpmm-1'
2022-01-19 22:36:55 +00:00
const saleAmount = saleBet?.sale?.amount
const saleDisplay = isAnte ? (
2022-01-19 22:36:55 +00:00
'ANTE'
) : saleAmount !== undefined ? (
<>{formatMoney(saleAmount)} (sold)</>
) : (
formatMoney(
isResolved
? resolvedPayout(contract, bet)
: calculateSaleAmount(contract, bet)
)
)
const payoutIfChosenDisplay =
bet.outcome === '0' && bet.isAnte
? 'N/A'
: formatMoney(calculatePayout(contract, bet, bet.outcome))
2021-12-15 07:41:50 +00:00
return (
2021-12-15 18:41:18 +00:00
<tr>
<td className="text-neutral">
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
{!isCPMM && !isResolved && !isClosed && !isSold && !isAnte && (
<SellButton contract={contract} bet={bet} />
)}
</td>
{isCPMM && <td>{shares >= 0 ? 'BUY' : 'SELL'}</td>}
<td>
<OutcomeLabel outcome={outcome} />
</td>
<td>{formatMoney(Math.abs(amount))}</td>
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
{!isCPMM && <td>{saleDisplay}</td>}
{!isCPMM && !isResolved && <td>{payoutIfChosenDisplay}</td>}
<td>{formatWithCommas(Math.abs(shares))}</td>
2021-12-15 18:41:18 +00:00
<td>
{formatPercent(probBefore)} {formatPercent(probAfter)}
</td>
<td>{dayjs(createdTime).format('MMM D, h:mma')}</td>
2021-12-15 18:41:18 +00:00
</tr>
2021-12-15 07:41:50 +00:00
)
}
function SellButton(props: { contract: Contract; bet: Bet }) {
useEffect(() => {
// warm up cloud function
sellBet({}).catch()
}, [])
const { contract, bet } = props
const { outcome, shares, loanAmount } = bet
const [isSubmitting, setIsSubmitting] = useState(false)
const initialProb = getOutcomeProbability(
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
contract,
outcome === 'NO' ? 'YES' : outcome
)
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 outcomeProb = getProbabilityAfterSale(contract, outcome, shares)
const saleAmount = calculateSaleAmount(contract, bet)
2022-03-03 10:10:20 +00:00
const profit = saleAmount - bet.amount
return (
<ConfirmationButton
id={`sell-${bet.id}`}
2022-03-31 08:38:57 +00:00
openModalBtn={{
className: clsx('btn-sm', isSubmitting && 'btn-disabled loading'),
label: 'Sell',
}}
submitBtn={{ className: 'btn-primary', label: 'Sell' }}
onSubmit={async () => {
setIsSubmitting(true)
await sellBet({ contractId: contract.id, betId: bet.id })
setIsSubmitting(false)
}}
>
<div className="mb-4 text-2xl">
Sell {formatWithCommas(shares)} shares of{' '}
<OutcomeLabel outcome={outcome} /> for {formatMoney(saleAmount)}?
</div>
{!!loanAmount && (
<div className="mt-2">
You will also pay back {formatMoney(loanAmount)} of your loan, for a
net of {formatMoney(saleAmount - loanAmount)}.
</div>
)}
<div className="mt-2 mb-1 text-sm">
2022-03-03 10:10:20 +00:00
{profit > 0 ? 'Profit' : 'Loss'}: {formatMoney(profit).replace('-', '')}
<br />
Market probability: {formatPercent(initialProb)} {' '}
{formatPercent(outcomeProb)}
</div>
</ConfirmationButton>
)
}
2022-02-14 23:29:29 +00:00
function ProfitBadge(props: { profitPercent: number }) {
const { profitPercent } = props
if (!profitPercent) return null
const colors =
profitPercent > 0
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
return (
<span
className={clsx(
'ml-1 inline-flex items-center rounded-full px-3 py-0.5 text-sm font-medium',
colors
)}
>
{(profitPercent > 0 ? '+' : '') + profitPercent.toFixed(1) + '%'}
</span>
)
}