Skip to content

Commit

Permalink
chore: use alternate source
Browse files Browse the repository at this point in the history
  • Loading branch information
thechefpenguin committed Aug 14, 2024
1 parent ce66521 commit 05d6cbb
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { BetPosition } from '@pancakeswap/prediction'
import { Card, CardBody, Flex, PlayCircleOutlineIcon, Text, useTooltip } from '@pancakeswap/uikit'
import { formatBigInt, formatNumber } from '@pancakeswap/utils/formatBalance'
import RoundProgress from 'components/RoundProgress'
import { useEffect, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { getHasRoundFailed } from 'state/predictions/helpers'
import { useGetBufferSeconds } from 'state/predictions/hooks'
import { NodeLedger, NodeRound } from 'state/types'
import styled from 'styled-components'
import { getNowInSeconds } from 'utils/getNowInSeconds'
import { usePredictionPrice, usePredictionPriceUpdate } from 'views/Predictions/hooks/usePredictionPrice'
import { usePredictionPrice } from 'views/Predictions/hooks/usePredictionPrice'
import { useConfig } from '../../../context/ConfigProvider'
import PositionTag from '../../PositionTag'
import { LockPriceRow, PrizePoolRow, RoundResultBox } from '../../RoundResult'
Expand Down Expand Up @@ -39,7 +39,7 @@ interface AILiveRoundCardProps {
formattedBearMultiplier: string
}

const REFRESH_PRICE_BEFORE_SECONDS_TO_CLOSE = 2
const REFRESH_PRICE_BEFORE_SECONDS_TO_CLOSE = 3

export const AILiveRoundCard: React.FC<React.PropsWithChildren<AILiveRoundCardProps>> = ({
round,
Expand All @@ -54,13 +54,15 @@ export const AILiveRoundCard: React.FC<React.PropsWithChildren<AILiveRoundCardPr
const bufferSeconds = useGetBufferSeconds()
const config = useConfig()

const [fetchAlternate, setFetchAlternate] = useState(false)

// Fetch Live Price for AI Predictions Open and Live Round Cards
const {
data: { price },
} = usePredictionPrice({
currencyA: config?.token.symbol,
useAlternateSource: fetchAlternate,
})
const { updatePriceFromSource } = usePredictionPriceUpdate()

const [isCalculatingPhase, setIsCalculatingPhase] = useState(false)

Expand Down Expand Up @@ -107,13 +109,19 @@ export const AILiveRoundCard: React.FC<React.PropsWithChildren<AILiveRoundCardPr
const bullMultiplier = aiPosition === 'UP' ? formattedBullMultiplier : formattedBearMultiplier
const bearMultiplier = aiPosition === 'DOWN' ? formattedBullMultiplier : formattedBearMultiplier

const refreshLivePrice = useCallback(() => {
// Fetch live price before round ends
setFetchAlternate(true)
setTimeout(() => {
setFetchAlternate(false)
}, REFRESH_PRICE_BEFORE_SECONDS_TO_CLOSE * 1000)
}, [])

useEffect(() => {
const secondsToClose = closeTimestamp ? closeTimestamp - getNowInSeconds() : 0
if (secondsToClose > 0) {
const refreshPriceTimeout = setTimeout(() => {
updatePriceFromSource({
currencyA: config?.token.symbol,
})
refreshLivePrice()
}, (secondsToClose - REFRESH_PRICE_BEFORE_SECONDS_TO_CLOSE) * 1000)

const calculatingPhaseTimeout = setTimeout(() => {
Expand All @@ -126,7 +134,7 @@ export const AILiveRoundCard: React.FC<React.PropsWithChildren<AILiveRoundCardPr
}
}
return undefined
}, [closeTimestamp, config?.token.symbol, updatePriceFromSource])
}, [closeTimestamp, config?.token.symbol, refreshLivePrice])

if (hasRoundFailed) {
return <CanceledRoundCard round={round} />
Expand Down
49 changes: 18 additions & 31 deletions apps/web/src/views/Predictions/hooks/usePredictionPrice.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { useQuery } from '@tanstack/react-query'
import { BINANCE_DATA_API, PREDICTION_PRICE_API } from 'config/constants/endpoints'
import { PriceApiWhitelistedCurrency } from 'config/constants/prediction/price'
import { useCallback } from 'react'

interface UsePredictionPriceParameters {
/** Default: ETH */
Expand All @@ -14,6 +13,8 @@ interface UsePredictionPriceParameters {
pollingInterval?: number

enabled?: boolean

useAlternateSource?: boolean
}

interface PriceResponse {
Expand All @@ -27,43 +28,29 @@ const DEFAULT_CURRENCY_A: PriceApiWhitelistedCurrency = 'ETH'
const DEFAULT_CURRENCY_B: PriceApiWhitelistedCurrency = 'USDT'
const DEFAULT_POLLING_INTERVAL = 5_000

/**
* Fetch the price directly from the source API if
* Live Price is needed urgently
*/
export const usePredictionPriceUpdate = () => {
const queryClient = useQueryClient()

const updatePriceFromSource = useCallback(
async ({ currencyA = DEFAULT_CURRENCY_A, currencyB = DEFAULT_CURRENCY_B }: UsePredictionPriceParameters) =>
fetch(`${BINANCE_DATA_API}/v3/ticker/price?symbol=${currencyA}${currencyB}`)
.then((res) => res.json())
.then((result) => ({
price: parseFloat(result.price),
currencyA,
currencyB,
}))
.then((data) => {
queryClient.setQueryData(['price', currencyA, currencyB], data)
return data
}),
[queryClient],
)

return { updatePriceFromSource }
}

export const usePredictionPrice = ({
currencyA = DEFAULT_CURRENCY_A,
currencyB = DEFAULT_CURRENCY_B,
pollingInterval = DEFAULT_POLLING_INTERVAL,
enabled = true,
useAlternateSource = false,
}: UsePredictionPriceParameters = {}) => {
return useQuery<PriceResponse>({
queryKey: ['price', currencyA, currencyB],
queryKey: ['price', currencyA, currencyB, useAlternateSource],
queryFn: async () =>
fetch(`${PREDICTION_PRICE_API}/?currencyA=${currencyA}&currencyB=${currencyB}`).then((res) => res.json()),
refetchInterval: pollingInterval,
useAlternateSource
? fetch(`${BINANCE_DATA_API}/v3/ticker/price?symbol=${currencyA}${currencyB}`)
.then((res) => res.json())
.then((result) => ({
price: parseFloat(result.price),
currencyA,
currencyB,
}))
: fetch(`${PREDICTION_PRICE_API}/?currencyA=${currencyA}&currencyB=${currencyB}`).then((res) => res.json()),
refetchInterval: () => {
if (useAlternateSource) return false
return pollingInterval
},
retry: 2,
initialData: {
price: 0,
Expand Down

0 comments on commit 05d6cbb

Please sign in to comment.