Skip to content

Commit

Permalink
perf: Don't fetch cake price when currency is not and not enabled (#1…
Browse files Browse the repository at this point in the history
…0719)

That hook instance in swap usually not directly fetching from rpc since
instance in menu component doing the fetch but disabling it still bring
some perf benefits

<!--
Before opening a pull request, please read the [contributing
guidelines](https://github.com/pancakeswap/pancake-frontend/blob/develop/CONTRIBUTING.md)
first
-->

<!-- start pr-codex -->

---

## PR-Codex overview
This PR focuses on replacing instances of `cakePriceBusd` with
`cakePrice` throughout various components. This change streamlines the
code by ensuring a consistent reference to the cake price across the
application.

### Detailed summary
- Replaced `cakePriceBusd` with `cakePrice` in multiple files.
- Updated calculations for `mcap`, `prizeInBusd`, and `balanceInBusd` to
use `cakePrice`.
- Adjusted conditions and hooks to reference the new `cakePrice`
variable.
- Ensured all related calculations maintain functionality with the new
variable.

> ✨ Ask PR-Codex anything about this PR by commenting with `/codex {your
question}`

<!-- end pr-codex -->
  • Loading branch information
memoyil authored Sep 30, 2024
1 parent 69687b2 commit d1ae861
Show file tree
Hide file tree
Showing 41 changed files with 119 additions and 119 deletions.
4 changes: 2 additions & 2 deletions apps/web/src/hooks/useStablecoinPrice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ export function useStablecoinPrice(
const chainId = currency?.chainId
const { enabled, hideIfPriceImpactTooHigh } = { ...DEFAULT_CONFIG, ...config }

const cakePrice = useCakePrice()
const isCake = Boolean(chainId && currency && CAKE[chainId] && currency.wrapped.equals(CAKE[chainId]))
const cakePrice = useCakePrice({ enabled: Boolean(isCake && enabled) })
const stableCoin = chainId && chainId in ChainId ? STABLE_COIN[chainId as ChainId] : undefined
const isCake = chainId && currency && CAKE[chainId] && currency.wrapped.equals(CAKE[chainId])

const isStableCoin = currency && stableCoin && currency.wrapped.equals(stableCoin)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,19 +88,19 @@ const chartConfig: ChartInfo[] = [

const CommissionInfo: React.FC<React.PropsWithChildren<CommissionInfoProps>> = ({ affiliate }) => {
const { t } = useTranslation()
const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()
const { totalUsers, totalEarnFeeUSD } = affiliate.metric

const totalCakeEarned = useMemo(() => {
const cakeBalance = new BigNumber(totalEarnFeeUSD).div(cakePriceBusd).toNumber()
const cakeBalance = new BigNumber(totalEarnFeeUSD).div(cakePrice).toNumber()
return formatNumber(cakeBalance)
}, [cakePriceBusd, totalEarnFeeUSD])
}, [cakePrice, totalEarnFeeUSD])

const chartData = useMemo(() => {
return chartConfig
.map((chart) => {
const usdValue: string = affiliate.metric[chart?.id] ?? '0'
const cakeBalance = new BigNumber(usdValue).div(cakePriceBusd).toNumber()
const cakeBalance = new BigNumber(usdValue).div(cakePrice).toNumber()
const valuePercentage = new BigNumber(usdValue).div(totalEarnFeeUSD)
const percentage = new BigNumber(valuePercentage.isNaN() ? '0' : valuePercentage).times(100).toNumber()
return {
Expand All @@ -112,7 +112,7 @@ const CommissionInfo: React.FC<React.PropsWithChildren<CommissionInfoProps>> = (
}
})
.sort((a, b) => b.cakeValueAsNumber - a.cakeValueAsNumber)
}, [affiliate?.metric, cakePriceBusd, totalEarnFeeUSD])
}, [affiliate?.metric, cakePrice, totalEarnFeeUSD])

return (
<Box width={['100%', '100%', '100%', '100%', '100%', '387px']}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,19 +43,19 @@ const LatestReward: React.FC<React.PropsWithChildren<LatestRewardProps>> = ({
const { isUserExist } = useUserExist()
const { toastSuccess, toastError } = useToast()
const { signMessageAsync } = useSignMessage()
const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()

const [isAffiliateClaimLoading, setIsAffiliateClaimLoading] = useState(false)
const [isUserClaimLoading, setIsUserClaimLoading] = useState(false)
const contract = useAffiliateProgramContract({ chainId: ChainId.BSC })

const affiliateTotalCakeEarned = useMemo(
() => new BigNumber(affiliateRewardFeeUSD).div(cakePriceBusd).toNumber(),
[cakePriceBusd, affiliateRewardFeeUSD],
() => new BigNumber(affiliateRewardFeeUSD).div(cakePrice).toNumber(),
[cakePrice, affiliateRewardFeeUSD],
)
const userTotalCakeEarned = useMemo(
() => new BigNumber(userRewardFeeUSD).div(cakePriceBusd).toNumber(),
[cakePriceBusd, userRewardFeeUSD],
() => new BigNumber(userRewardFeeUSD).div(cakePrice).toNumber(),
[cakePrice, userRewardFeeUSD],
)

const handleClaim = async (isAffiliateClaim: boolean) => {
Expand Down
8 changes: 4 additions & 4 deletions apps/web/src/views/AffiliatesProgram/hooks/useLeaderboard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@ interface Leaderboard {
}

const useLeaderboard = (): Leaderboard => {
const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()

const { data, isPending } = useQuery({
queryKey: ['affiliates-program', 'affiliate-program-leaderboard', cakePriceBusd],
queryKey: ['affiliates-program', 'affiliate-program-leaderboard', cakePrice],

queryFn: async () => {
const response = await fetch(`/api/affiliates-program/leader-board`)
const result = await response.json()
const list: ListType[] = result.affiliates.map((affiliate) => {
const cakeBalance = new BigNumber(affiliate.metric.totalEarnFeeUSD).div(cakePriceBusd)
const cakeBalance = new BigNumber(affiliate.metric.totalEarnFeeUSD).div(cakePrice)
return {
...affiliate,
cakeBalance: cakeBalance.isNaN() ? '0' : cakeBalance.toString(),
Expand All @@ -34,7 +34,7 @@ const useLeaderboard = (): Leaderboard => {
return list
},

enabled: cakePriceBusd.gt(0),
enabled: cakePrice.gt(0),
refetchOnWindowFocus: false,
refetchOnReconnect: false,
})
Expand Down
14 changes: 7 additions & 7 deletions apps/web/src/views/CakeStaking/components/CakeRewardsCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ export const CakeRewardsCard = ({ onDismiss }) => {
currentLanguage: { locale },
} = useTranslation()
const { isDesktop } = useMatchBreakpoints()
const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()
const { cakeUnlockTime, cakeLockedAmount } = useCakeLockStatus()
const { balanceOfAt, totalSupplyAt, nextDistributionTimestamp, lastTokenTimestamp, availableClaim } =
useRevenueSharingVeCake()
Expand All @@ -112,26 +112,26 @@ export const CakeRewardsCard = ({ onDismiss }) => {
[availableClaimFromCakePool],
)
const availableCakePoolCakeUsdValue = useMemo(
() => new BigNumber(availableCakePoolCake).times(cakePriceBusd).toNumber(),
[availableCakePoolCake, cakePriceBusd],
() => new BigNumber(availableCakePoolCake).times(cakePrice).toNumber(),
[availableCakePoolCake, cakePrice],
)

const availableRevenueSharingCake = useMemo(
() => getBalanceAmount(new BigNumber(availableClaim)).toNumber(),
[availableClaim],
)
const availableRevenueSharingCakeUsdValue = useMemo(
() => new BigNumber(availableRevenueSharingCake).times(cakePriceBusd).toNumber(),
[availableRevenueSharingCake, cakePriceBusd],
() => new BigNumber(availableRevenueSharingCake).times(cakePrice).toNumber(),
[availableRevenueSharingCake, cakePrice],
)

const totalAvailableClaim = useMemo(
() => getBalanceAmount(new BigNumber(availableClaim).plus(availableClaimFromCakePool)).toNumber(),
[availableClaim, availableClaimFromCakePool],
)
const totalAvailableClaimUsdValue = useMemo(
() => new BigNumber(totalAvailableClaim).times(cakePriceBusd).toNumber(),
[totalAvailableClaim, cakePriceBusd],
() => new BigNumber(totalAvailableClaim).times(cakePrice).toNumber(),
[totalAvailableClaim, cakePrice],
)

const showExpireSoonWarning = useMemo(() => {
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/views/CakeStaking/components/LockCakeForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ const CakeInput: React.FC<{
disabled?: boolean
}> = ({ value, onUserInput, disabled }) => {
const { t } = useTranslation()
const cakeUsdPrice = useCakePrice()
const cakePrice = useCakePrice()
const cakeUsdValue = useMemo(() => {
return cakeUsdPrice && value ? cakeUsdPrice.times(value).toNumber() : 0
}, [cakeUsdPrice, value])
return cakePrice && value ? cakePrice.times(value).toNumber() : 0
}, [cakePrice, value])
const [percent, setPercent] = useState<number | null>(null)
const _cakeBalance = useBSCCakeBalance()
const cakeBalance = BigInt(_cakeBalance.toString())
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Home/components/Banners/LotteryBanner.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ const LotteryPrice: React.FC<React.PropsWithChildren> = () => {
const { data } = useQuery<LotteryResponse>({
queryKey: ['currentLottery'],
})
const cakePriceBusd = useCakePrice()
const prizeInBusd = new BigNumber(data?.amountCollectedInCake || Number.NaN).times(cakePriceBusd)
const cakePrice = useCakePrice()
const prizeInBusd = new BigNumber(data?.amountCollectedInCake || Number.NaN).times(cakePrice)
const prizeTotal = getBalanceNumber(prizeInBusd)
const { t } = useTranslation()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ const useIsRenderUserBanner = () => {
const { account, chainId } = useActiveWeb3React()

const { earningsSum: farmEarningsSum } = useFarmsWithBalance()
const cakePriceBusd = useCakePrice()
const isEarningsBusdZero = new BigNumber(farmEarningsSum).multipliedBy(cakePriceBusd).isZero()
const cakePrice = useCakePrice()
const isEarningsBusdZero = new BigNumber(farmEarningsSum).multipliedBy(cakePrice).isZero()

const { data: shouldRenderUserBanner } = useQuery({
queryKey: ['shouldRenderUserBanner', account],
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Home/components/CakeDataRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ const CakeDataRow = () => {
enabled: Boolean(loadData),
refetchInterval: SLOW_INTERVAL,
})
const cakePriceBusd = useCakePrice()
const mcap = cakePriceBusd.times(circulatingSupply)
const cakePrice = useCakePrice()
const mcap = cakePrice.times(circulatingSupply)
const mcapString = formatLocalisedCompactNumber(mcap.toNumber(), isMobile)

useEffect(() => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const LotteryCardContent = () => {
const { t } = useTranslation()
const { observerRef, isIntersecting } = useIntersectionObserver()
const [loadData, setLoadData] = useState(false)
const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()
const { data: currentLotteryId } = useQuery({
queryKey: ['currentLotteryId'],
queryFn: fetchCurrentLotteryId,
Expand All @@ -46,10 +46,10 @@ const LotteryCardContent = () => {
refetchOnWindowFocus: false,
})

const cakePrizesText = t('%cakePrizeInUsd% in CAKE prizes this round', { cakePrizeInUsd: cakePriceBusd.toString() })
const [pretext, prizesThisRound] = cakePrizesText.split(cakePriceBusd.toString())
const cakePrizesText = t('%cakePrizeInUsd% in CAKE prizes this round', { cakePrizeInUsd: cakePrice.toString() })
const [pretext, prizesThisRound] = cakePrizesText.split(cakePrice.toString())
const amountCollectedInCake = currentLottery ? parseFloat(currentLottery.amountCollectedInCake) : null
const currentLotteryPrize = amountCollectedInCake ? cakePriceBusd.times(amountCollectedInCake) : null
const currentLotteryPrize = amountCollectedInCake ? cakePrice.times(amountCollectedInCake) : null

useEffect(() => {
if (isIntersecting) {
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Home/components/UserBanner/HarvestCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ const HarvestCard: React.FC<React.PropsWithChildren<HarvestCardProps>> = ({ onHa
const { fetchWithCatchTxError, loading: v2PendingTx } = useCatchTxError()
const { farmsWithStakedBalance, earningsSum: farmEarningsSum } = useFarmsWithBalance()

const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()
const masterChefAddress = useMasterchef()
const { isMobile } = useMatchBreakpoints()
const gasPrice = useGasPrice()
const earningsBusd = new BigNumber(farmEarningsSum).multipliedBy(cakePriceBusd)
const earningsBusd = new BigNumber(farmEarningsSum).multipliedBy(cakePrice)
const numTotalToCollect = farmsWithStakedBalance.length
const numFarmsToCollect = farmsWithStakedBalance.filter(
(value) => (value && 'pid' in value && value.pid !== 0) || (value && 'sendTx' in value && value.sendTx !== null),
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/views/Home/hooks/useGetTopFarmsByApr.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const useGetTopFarmsByApr = (isIntersecting: boolean) => {
version: 2 | 3
} | null)[]
>(() => [null, null, null, null, null])
const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()
const { chainId } = useActiveChainId()

const { status: fetchStatus, isFetching } = useQuery({
Expand Down Expand Up @@ -77,7 +77,7 @@ const useGetTopFarmsByApr = (isIntersecting: boolean) => {
const { cakeRewardsApr, lpRewardsApr } = getFarmApr(
chainId,
farm.poolWeight,
cakePriceBusd,
cakePrice,
totalLiquidity,
farm.lpAddress,
regularCakePerBlock,
Expand All @@ -102,7 +102,7 @@ const useGetTopFarmsByApr = (isIntersecting: boolean) => {
)
setTopFarms(sortedByApr.slice(0, 5))
}
}, [cakePriceBusd, chainId, farms, farmsV3.farmsWithPrice, fetchStatus, isLoading, regularCakePerBlock, farmsV3Aprs])
}, [cakePrice, chainId, farms, farmsV3.farmsWithPrice, fetchStatus, isLoading, regularCakePerBlock, farmsV3Aprs])
return { topFarms, fetched: fetchStatus === 'success' && !isFetching, chainId }
}

Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Ifos/hooks/v2/useGetPublicIfoData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ const formatPool = (pool) => ({
*/
const useGetPublicIfoData = (ifo: Ifo): PublicIfoData => {
const { address } = ifo
const cakePriceUsd = useCakePrice()
const cakePrice = useCakePrice()
const lpTokenPriceInUsd = useLpTokenPrice(ifo.currency.symbol)
const currencyPriceInUSD = ifo.currency === bscTokens.cake ? cakePriceUsd : lpTokenPriceInUsd
const currencyPriceInUSD = ifo.currency === bscTokens.cake ? cakePrice : lpTokenPriceInUsd

const [state, setState] = useState({
isInitialized: false,
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Ifos/hooks/v3/useGetPublicIfoData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ const ROUND_DIGIT = 3
*/
const useGetPublicIfoData = (ifo: Ifo): PublicIfoData => {
const { address, plannedStartTime } = ifo
const cakePriceUsd = useCakePrice()
const cakePrice = useCakePrice()
const lpTokenPriceInUsd = useLpTokenPrice(ifo.currency.symbol)
const currencyPriceInUSD = ifo.currency === bscTokens.cake ? cakePriceUsd : lpTokenPriceInUsd
const currencyPriceInUSD = ifo.currency === bscTokens.cake ? cakePrice : lpTokenPriceInUsd

const [state, setState] = useState({
isInitialized: false,
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Ifos/hooks/v7/useGetPublicIfoData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ const useGetPublicIfoData = (ifo: Ifo): PublicIfoData => {
const { address: account } = useAccount()
const { chainId } = ifo
const { address, plannedStartTime } = ifo
const cakePriceUsd = useCakePrice()
const cakePrice = useCakePrice()
const lpTokenPriceInUsd = useLpTokenPrice(ifo.currency.symbol)
const currencyPriceInUSD = ifo.currency === CAKE[ifo.chainId] ? cakePriceUsd : lpTokenPriceInUsd
const currencyPriceInUSD = ifo.currency === CAKE[ifo.chainId] ? cakePrice : lpTokenPriceInUsd

const [state, setState] = useState(INITIAL_STATE)

Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Ifos/hooks/v8/useGetPublicIfoData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ const useGetPublicIfoData = (ifo: Ifo): PublicIfoData => {
const { address: account } = useAccount()
const { chainId } = ifo
const { address, plannedStartTime } = ifo
const cakePriceUsd = useCakePrice()
const cakePrice = useCakePrice()
const lpTokenPriceInUsd = useLpTokenPrice(ifo.currency.symbol)
const currencyPriceInUSD = ifo.currency === CAKE[ifo.chainId] ? cakePriceUsd : lpTokenPriceInUsd
const currencyPriceInUSD = ifo.currency === CAKE[ifo.chainId] ? cakePrice : lpTokenPriceInUsd

const [state, setState] = useState(INITIAL_STATE)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const BuyTicketsModal: React.FC<React.PropsWithChildren<BuyTicketsModalProps>> =
const stringifiedUserCake = userCake.toJSON()
const memoisedUserCake = useMemo(() => new BigNumber(stringifiedUserCake), [stringifiedUserCake])

const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()
const dispatch = useAppDispatch()
const hasFetchedBalance = fetchStatus === FetchStatus.Fetched
const userCakeDisplayBalance = getFullDisplayBalance(userCake, 18, 3)
Expand Down Expand Up @@ -321,7 +321,7 @@ const BuyTicketsModal: React.FC<React.PropsWithChildren<BuyTicketsModalProps>> =
value={ticketsToBuy}
onUserInput={handleInputChange}
currencyValue={
cakePriceBusd.gt(0) &&
cakePrice.gt(0) &&
`~${ticketsToBuy ? getFullDisplayBalance(priceTicketInCake.times(new BigNumber(ticketsToBuy))) : '0.00'} CAKE`
}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ const ClaimInnerContainer: React.FC<React.PropsWithChildren<ClaimInnerProps>> =
const lotteryContract = useLotteryV2Contract()
const activeClaimData = roundsToClaim[activeClaimIndex]

const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()
const cakeReward = activeClaimData.cakeTotal
const dollarReward = cakeReward.times(cakePriceBusd)
const dollarReward = cakeReward.times(cakePrice)
const rewardAsBalance = getBalanceAmount(cakeReward).toNumber()
const dollarRewardAsBalance = getBalanceAmount(dollarReward).toNumber()

Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Lottery/components/Hero.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,8 @@ const Hero = () => {
isTransitioning,
} = useLottery()

const cakePriceBusd = useCakePrice()
const prizeInBusd = amountCollectedInCake.times(cakePriceBusd)
const cakePrice = useCakePrice()
const prizeInBusd = amountCollectedInCake.times(cakePrice)
const prizeTotal = getBalanceNumber(prizeInBusd)
const ticketBuyIsDisabled = status !== LotteryStatus.OPEN || isTransitioning

Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Lottery/components/NextDrawCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ const NextDrawCard = () => {
const [isExpanded, setIsExpanded] = useState(false)
const ticketBuyIsDisabled = status !== LotteryStatus.OPEN || isTransitioning

const cakePriceBusd = useCakePrice()
const prizeInBusd = amountCollectedInCake.times(cakePriceBusd)
const cakePrice = useCakePrice()
const prizeInBusd = amountCollectedInCake.times(cakePrice)
const endTimeMs = parseInt(endTime, 10) * 1000
const endDate = new Date(endTimeMs)
const isLotteryOpen = status === LotteryStatus.OPEN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const PreviousRoundCardFooter: React.FC<
const { t } = useTranslation()
const [fetchedLotteryGraphData, setFetchedLotteryGraphData] = useState<LotteryRoundGraphEntity>()
const lotteryGraphDataFromState = useGetLotteryGraphDataById(lotteryId)
const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()

useEffect(() => {
if (!lotteryId) return
Expand All @@ -43,7 +43,7 @@ const PreviousRoundCardFooter: React.FC<
let prizeInBusd = new BigNumber(NaN)
if (lotteryNodeData) {
const { amountCollectedInCake } = lotteryNodeData
prizeInBusd = amountCollectedInCake.times(cakePriceBusd)
prizeInBusd = amountCollectedInCake.times(cakePrice)
}

const getTotalUsers = (): string | null => {
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/views/Lottery/components/RewardBracketDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ const RewardBracketDetail: React.FC<React.PropsWithChildren<RewardBracketDetailP
isLoading,
}) => {
const { t } = useTranslation()
const cakePriceBusd = useCakePrice()
const cakePrice = useCakePrice()

const getRewardText = () => {
const numberMatch = rewardBracket + 1
Expand Down Expand Up @@ -59,7 +59,7 @@ const RewardBracketDetail: React.FC<React.PropsWithChildren<RewardBracketDetailP
fontSize="12px"
color="textSubtle"
prefix="~$"
value={getBalanceNumber(cakeAmount.times(cakePriceBusd))}
value={getBalanceNumber(cakeAmount.times(cakePrice))}
decimals={0}
/>
)}
Expand Down
Loading

0 comments on commit d1ae861

Please sign in to comment.