Skip to content

Commit

Permalink
Batch useLiveContract and include answers in api call
Browse files Browse the repository at this point in the history
  • Loading branch information
IanPhilips committed Nov 12, 2024
1 parent 5ec831b commit 29953e0
Show file tree
Hide file tree
Showing 21 changed files with 260 additions and 194 deletions.
25 changes: 25 additions & 0 deletions backend/api/src/get-markets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createSupabaseDirectClient } from 'shared/supabase/init'
import { convertAnswer, convertContract } from 'common/supabase/contracts'
import { contractColumnsToSelect } from 'shared/utils'
import { CPMMMultiContract } from 'common/contract'
import { APIHandler } from './helpers/endpoint'

export const getMarketsByIds: APIHandler<'markets-by-ids'> = async (props) => {
const pg = createSupabaseDirectClient()
const results = await pg.multi(
`select ${contractColumnsToSelect} from contracts
where id in ($1:list);
select * from answers where contract_id in ($1:list);
`,
[props.ids]
)
const contracts = results[0].map(convertContract)
const answers = results[1].map(convertAnswer)
const multiContracts = contracts.filter((c) => c.mechanism === 'cpmm-multi-1')
for (const contract of multiContracts) {
;(contract as CPMMMultiContract).answers = answers.filter(
(a) => a.contractId === contract.id
)
}
return contracts
}
2 changes: 2 additions & 0 deletions backend/api/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ import { getLeaderboard } from './get-leaderboard'
import { toggleSystemTradingStatus } from './toggle-system-status'
import { completeCashoutRequest } from './gidx/complete-cashout-request'
import { getDailyChangedMetricsAndContracts } from './get-daily-changed-metrics-and-contracts'
import { getMarketsByIds } from './get-markets'

// we define the handlers in this object in order to typecheck that every API has a handler
export const handlers: { [k in APIPath]: APIHandler<k> } = {
Expand Down Expand Up @@ -167,6 +168,7 @@ export const handlers: { [k in APIPath]: APIHandler<k> } = {
groups: getGroups,
'market/:id': getMarket,
'market/:id/lite': ({ id }) => getMarket({ id, lite: true }),
'markets-by-ids': getMarketsByIds,
'slug/:slug': getMarket,
'market/:contractId/update': updateMarket,
'market/:contractId/close': closeMarket,
Expand Down
1 change: 1 addition & 0 deletions backend/api/url-map-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,4 @@ pathMatchers:
- pathTemplateMatch: /v0/leagues
- pathTemplateMatch: /v0/get-mod-reports
- pathTemplateMatch: /get-notifications
- pathTemplateMatch: /markets-by-ids
11 changes: 11 additions & 0 deletions common/src/api/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -497,6 +497,17 @@ export const API = (_apiTypeCheck = {
cache: DEFAULT_CACHE_STRATEGY,
props: z.object({ id: z.string(), lite: coerceBoolean.optional() }),
},
'markets-by-ids': {
method: 'GET',
visibility: 'undocumented',
authed: false,
returns: [] as Contract[],
props: z
.object({
ids: z.array(z.string()).max(100),
})
.strict(),
},
// deprecated. use /market/:id?lite=true instead
'market/:id/lite': {
method: 'GET',
Expand Down
3 changes: 1 addition & 2 deletions web/components/answers/answer-resolve-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ import { useAdmin } from 'web/hooks/use-admin'
import { GradientContainer } from '../widgets/gradient-container'
import { AmountInput } from '../widgets/amount-input'
import { getAnswerColor } from '../charts/contract/choice'
import { useAnswersCpmm } from 'web/hooks/use-answers'

function getAnswerResolveButtonColor(
resolveOption: string | undefined,
Expand Down Expand Up @@ -217,7 +216,7 @@ export const AnswersResolvePanel = (props: {
inModal?: boolean
}) => {
const { contract, onClose, inModal } = props
const answers = useAnswersCpmm(contract.id) ?? contract.answers
const answers = contract.answers

const user = useUser()

Expand Down
3 changes: 1 addition & 2 deletions web/components/answers/binary-multi-answers-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,13 @@ import { BuyPanelBody } from 'web/components/bet/bet-panel'
import { getAnswerColor } from '../charts/contract/choice'
import { useUser } from 'web/hooks/use-user'
import { PencilIcon } from '@heroicons/react/solid'
import { useAnswersCpmm } from 'web/hooks/use-answers'

export function BinaryMultiAnswersPanel(props: {
contract: CPMMMultiContract
feedReason?: string
}) {
const { feedReason, contract } = props
const answers = useAnswersCpmm(contract.id) ?? contract.answers
const answers = contract.answers

const [outcome, setOutcome] = useState<'YES' | 'NO' | undefined>(undefined)

Expand Down
4 changes: 2 additions & 2 deletions web/components/answers/numeric-bet-panel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import { SizedContainer } from 'web/components/sized-container'
import { getFeeTotal, noFees } from 'common/fees'
import { FeeDisplay } from '../bet/fees'
import { XIcon } from '@heroicons/react/solid'
import { useLiveContractWithAnswers } from 'web/hooks/use-contract'
import { useLiveContract } from 'web/hooks/use-contract'
import { getTierFromLiquidity } from 'common/tier'
import { MoneyDisplay } from '../bet/money-display'
import { TRADE_TERM } from 'common/envs/constants'
Expand All @@ -55,7 +55,7 @@ export const NumericBetPanel = (props: {
higher: 'Higher',
},
} = props
const contract = useLiveContractWithAnswers(props.contract)
const contract = useLiveContract(props.contract)
const { answers, min: minimum, max: maximum } = contract
const [expectedValue, setExpectedValue] = useState(getExpectedValue(contract))
const [betAmount, setBetAmount] = useState<number | undefined>(10)
Expand Down
4 changes: 2 additions & 2 deletions web/components/contract/contract-overview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import {
import { SizedContainer } from 'web/components/sized-container'
import { useAnnotateChartTools } from 'web/hooks/use-chart-annotations'
import { useChartPositions } from 'web/hooks/use-chart-positions'
import { useLiveContractWithAnswers } from 'web/hooks/use-contract'
import { useLiveContract } from 'web/hooks/use-contract'
import { usePersistentInMemoryState } from 'web/hooks/use-persistent-in-memory-state'
import { useUser } from 'web/hooks/use-user'
import {
Expand Down Expand Up @@ -775,7 +775,7 @@ const BinaryChoiceOverview = (props: {
}

export const SimpleMultiOverview = (props: { contract: CPMMMultiContract }) => {
const contract = useLiveContractWithAnswers(props.contract)
const contract = useLiveContract(props.contract)
const user = useUser()
const defaultSort = getDefaultSort(contract)

Expand Down
6 changes: 3 additions & 3 deletions web/components/contract/contract-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ import { GradientContainer } from 'web/components/widgets/gradient-container'
import { Tooltip } from 'web/components/widgets/tooltip'
import { useAdmin, useTrusted } from 'web/hooks/use-admin'
import { useContractBets } from 'web/hooks/use-bets'
import { useLiveContractWithAnswers } from 'web/hooks/use-contract'
import { useLiveContract } from 'web/hooks/use-contract'
import { useHeaderIsStuck } from 'web/hooks/use-header-is-stuck'
import { useRelatedMarkets } from 'web/hooks/use-related-contracts'
import { useReview } from 'web/hooks/use-review'
Expand Down Expand Up @@ -92,12 +92,12 @@ export function ContractPageContent(props: ContractParams) {
// sync query state with context
const { prefersPlay } = useSweepstakes()
const router = useRouter()
const livePlayContract = useLiveContractWithAnswers(props.contract)
const livePlayContract = useLiveContract(props.contract)
const sweepsIsPossible = !!livePlayContract.siblingContractId
const [isPlay, setIsPlay] = useState<boolean | undefined>(prefersPlay)
const liveCashContract = props.cash
? // eslint-disable-next-line react-hooks/rules-of-hooks
useLiveContractWithAnswers(props.cash.contract)
useLiveContract(props.cash.contract)
: null

const liveContract =
Expand Down
4 changes: 2 additions & 2 deletions web/components/contract/contracts-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { ContractMinibar } from '../charts/minibar'
import { Row } from '../layout/row'
import { BinaryContractOutcomeLabel } from '../outcome-label'
import { Avatar } from '../widgets/avatar'
import { useLiveContractWithAnswers } from 'web/hooks/use-contract'
import { useLiveContract } from 'web/hooks/use-contract'
import { Col } from '../layout/col'
import {
actionColumn,
Expand Down Expand Up @@ -80,7 +80,7 @@ function ContractRow(props: {
onClick?: () => void
hideAvatar?: boolean
}) {
const contract = useLiveContractWithAnswers(props.contract)
const contract = useLiveContract(props.contract)

const { columns, hideAvatar, highlighted, faded, onClick } = props
return (
Expand Down
2 changes: 1 addition & 1 deletion web/components/contract/trades-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { Avatar } from '../widgets/avatar'
import { UserLink } from '../widgets/user-link'
import { track } from 'web/lib/service/analytics'
import { Answer } from 'common/answer'
import { useUniqueBettorCountOnAnswer } from 'web/hooks/use-answers'
import { useUniqueBettorCountOnAnswer } from 'web/hooks/use-unique-bettor-count-on-answer'
import { Button, ColorType } from 'web/components/buttons/button'
import { UserHovercard } from '../user/user-hovercard'
import { useBountyAwardCount } from 'web/hooks/use-bounties'
Expand Down
4 changes: 2 additions & 2 deletions web/components/us-elections/contracts/politics-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { Row } from 'web/components/layout/row'
import { Spacer } from 'web/components/layout/spacer'
import { SweepsToggle } from 'web/components/sweeps/sweeps-toggle'
import { ClickFrame } from 'web/components/widgets/click-frame'
import { useLiveContractWithAnswers } from 'web/hooks/use-contract'
import { useLiveContract } from 'web/hooks/use-contract'
import { track } from 'web/lib/service/analytics'
import { CandidatePanel } from './candidates-panel/candidates-panel'
import { SmallCandidatePanel } from './candidates-panel/small-candidate-panel'
Expand Down Expand Up @@ -49,7 +49,7 @@ export function PoliticsCard(props: {
includeHead,
} = props

const contract = useLiveContractWithAnswers(props.contract)
const contract = useLiveContract(props.contract)

const path = contractPath(contract)

Expand Down
10 changes: 5 additions & 5 deletions web/components/usa-map/homepage-map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { ReactNode, useState } from 'react'
import { Col } from 'web/components/layout/col'
import { Row } from 'web/components/layout/row'
import { Spacer } from 'web/components/layout/spacer'
import { useLiveContractWithAnswers } from 'web/hooks/use-contract'
import { useLiveContract } from 'web/hooks/use-contract'
import {
ElectoralCollegeVisual,
sortByDemocraticDiff,
Expand Down Expand Up @@ -61,7 +61,7 @@ export function HomepageMap(props: {
? rawPresidencySwingCashContracts[key]
: rawPresidencyStateContracts[key]
// eslint-disable-next-line react-hooks/rules-of-hooks
acc[key] = useLiveContractWithAnswers(currentContract!)
acc[key] = useLiveContract(currentContract!)

return acc
}, {} as MapContractsDictionary)
Expand All @@ -73,7 +73,7 @@ export function HomepageMap(props: {
const senateContractsDictionary = Object.keys(rawSenateStateContracts).reduce(
(acc, key) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
acc[key] = useLiveContractWithAnswers(rawSenateStateContracts[key]!)
acc[key] = useLiveContract(rawSenateStateContracts[key]!)
return acc
},
{} as MapContractsDictionary
Expand All @@ -83,11 +83,11 @@ export function HomepageMap(props: {
rawGovernorStateContracts
).reduce((acc, key) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
acc[key] = useLiveContractWithAnswers(rawGovernorStateContracts[key]!)
acc[key] = useLiveContract(rawGovernorStateContracts[key]!)
return acc
}, {} as MapContractsDictionary)

const liveHouseContract = useLiveContractWithAnswers(houseContract)
const liveHouseContract = useLiveContract(houseContract)

const [mode, setMode] = useState<MapMode>('presidency')

Expand Down
69 changes: 0 additions & 69 deletions web/hooks/use-answers.ts

This file was deleted.

Loading

0 comments on commit 29953e0

Please sign in to comment.