Skip to content

Commit

Permalink
chore: Remove nigeria meetup banner, dont fetch farms length when no …
Browse files Browse the repository at this point in the history
…account and callback on select query (#10814)

According to
https://tanstack.com/query/latest/docs/framework/react/reference/useQuery

"The select function will only run if data changed, or if the reference
to the select function itself changes. To optimize, wrap the function in
useCallback."


<!--
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 improving type safety and code readability in various
hooks and components by updating TypeScript types, enhancing query
selections with `useCallback`, and removing unused hooks.

### Detailed summary
- Updated type of `proxyAddress` to `Address | undefined`.
- Enhanced query selections with `useCallback` in multiple hooks.
- Modified `useFarmsLength` to accept an `enabled` parameter.
- Removed unused hook `useIsRenderTgPredictionBotBanner`.
- Ensured default values in queries to prevent undefined states.

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

<!-- end pr-codex -->
  • Loading branch information
memoyil authored Oct 14, 2024
1 parent ed5e430 commit 3ee4a96
Show file tree
Hide file tree
Showing 17 changed files with 57 additions and 54 deletions.
2 changes: 1 addition & 1 deletion apps/web/src/hooks/useBCakeProxyContractAddress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const useBCakeProxyContractAddress = (account?: Address, chainId?: number
const isLoading = isSupportedChain ? status !== 'success' : false

return {
proxyAddress: data as Address,
proxyAddress: data as Address | undefined,
isLoading,
proxyCreated: data && data !== NO_PROXY_CONTRACT,
refreshProxyAddress: refetch,
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/hooks/useContract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ export function useBCakeFarmBoosterProxyFactoryContract() {
return useMemo(() => getBCakeFarmBoosterProxyFactoryContract(signer ?? undefined), [signer])
}

export function useBCakeProxyContract(proxyContractAddress: Address) {
export function useBCakeProxyContract(proxyContractAddress: Address | undefined) {
const { data: signer } = useWalletClient()
return useMemo(
() => proxyContractAddress && getBCakeProxyContract(proxyContractAddress, signer ?? undefined),
Expand Down
13 changes: 8 additions & 5 deletions apps/web/src/hooks/useMerkl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,14 @@ export function useMerklInfo(poolAddress: string | null): {
enabled: Boolean(chainId && poolAddress),
staleTime: FAST_INTERVAL,
retryDelay: (attemptIndex) => Math.min(2000 * 2 ** attemptIndex, 30000),
select: (data) => {
return data?.[chainId ?? 0]?.pools?.[poolAddress ?? '']?.aprs?.['Average APR (rewards / pool TVL)'] as
| number
| undefined
},
select: useCallback(
(data) => {
return data?.[chainId ?? 0]?.pools?.[poolAddress ?? '']?.aprs?.['Average APR (rewards / pool TVL)'] as
| number
| undefined
},
[chainId, poolAddress],
),
})

const { data, isPending, refetch } = useQuery({
Expand Down
23 changes: 13 additions & 10 deletions apps/web/src/hooks/usePermit2Details.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Permit2ABI, getPermit2Address } from '@pancakeswap/permit2-sdk'
import { CurrencyAmount, Token } from '@pancakeswap/swap-sdk-core'
import { useQuery } from '@tanstack/react-query'
import { FAST_INTERVAL } from 'config/constants'
import { useMemo } from 'react'
import { useCallback, useMemo } from 'react'
import { publicClient } from 'utils/wagmi'
import { Address, zeroAddress } from 'viem'
import { useActiveChainId } from './useActiveChainId'
Expand Down Expand Up @@ -50,14 +50,17 @@ export const usePermit2Details = (
retry: true,
refetchOnWindowFocus: false,
enabled: Boolean(chainId && token && !token.isNative && spender && owner),
select: (data): Permit2Details | undefined => {
if (!data || token?.isNative) return undefined
const [amount, expiration, nonce] = data
return {
amount: CurrencyAmount.fromRawAmount(token!, amount),
expiration: Number(expiration),
nonce: Number(nonce),
}
},
select: useCallback(
(data: readonly [bigint, number, number]): Permit2Details | undefined => {
if (!data || token?.isNative) return undefined
const [amount, expiration, nonce] = data
return {
amount: CurrencyAmount.fromRawAmount(token!, amount),
expiration: Number(expiration),
nonce: Number(nonce),
}
},
[token],
),
})
}
3 changes: 2 additions & 1 deletion apps/web/src/state/block/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
} from '@pancakeswap/wagmi'

import { useActiveChainId } from 'hooks/useActiveChainId'
import { useCallback } from 'react'

export const usePollBlockNumber = () => {
const { chainId } = useActiveChainId()
Expand Down Expand Up @@ -65,7 +66,7 @@ export const useChainCurrentBlock = (chainId: number) => {
watch: true,
query: {
enabled: isTargetDifferent,
select: (data) => (data !== undefined ? Number(data) : undefined),
select: useCallback((data: bigint) => (data !== undefined ? Number(data) : undefined), []),
},
})

Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/state/farms/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
makeUserFarmFromPidSelector,
} from './selectors'

export function useFarmsLength() {
export function useFarmsLength({ enabled = true } = {}) {
const { chainId } = useActiveChainId()
return useQuery({
queryKey: ['farmsLength', chainId],
Expand All @@ -44,7 +44,7 @@ export function useFarmsLength() {
return Number(await mc.read.poolLength())
},

enabled: Boolean(chainId && supportedChainIdV2.includes(chainId)),
enabled: Boolean(enabled && chainId && supportedChainIdV2.includes(chainId)),
refetchOnReconnect: false,
refetchOnWindowFocus: false,
refetchOnMount: false,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BCakeWrapperFarmConfig } from '@pancakeswap/farms'
import { useQuery } from '@tanstack/react-query'
import { Address } from 'viem'
import { useCallback } from 'react'
import { getAccountV2FarmingBCakeWrapperEarning } from '../fetcher'

export const useAccountV2PendingCakeReward = (
Expand All @@ -19,6 +20,6 @@ export const useAccountV2PendingCakeReward = (
bCakeWrapperConfig as BCakeWrapperFarmConfig,
]),
enabled: Boolean(account && bCakeWrapperConfig.chainId && bCakeWrapperConfig.bCakeWrapperAddress),
select: (data) => data?.[0],
select: useCallback((data: string[]) => data?.[0], []),
})
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import { useQuery } from '@tanstack/react-query'
import { SLOW_INTERVAL } from 'config/constants'
import { useCallback } from 'react'
import { readPositions } from '../fetcher/v3'
import { PositionDetail } from '../type'

export const useAccountV3Position = (chainId?: number, tokenId?: bigint) => {
return useQuery({
queryKey: ['accountV3Position', chainId, tokenId?.toString()],
queryFn: () => readPositions(chainId!, [tokenId!]),
select: (data) => data[0],
select: useCallback((data: PositionDetail[]) => data[0], []),
enabled: !!tokenId && !!chainId,
refetchOnMount: false,
refetchOnWindowFocus: false,
Expand Down
6 changes: 3 additions & 3 deletions apps/web/src/views/CakeStaking/hooks/useVeCakeUserInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useReadContract } from '@pancakeswap/wagmi'
import dayjs from 'dayjs'
import useAccountActiveChain from 'hooks/useAccountActiveChain'
import { useVeCakeContract } from 'hooks/useContract'
import { useMemo } from 'react'
import { useCallback, useMemo } from 'react'
import { Address } from 'viem'
import { CakeLockStatus, CakePoolType } from '../types'
import { useCakePoolLockInfo } from './useCakePoolLockInfo'
Expand Down Expand Up @@ -55,7 +55,7 @@ export const useVeCakeUserInfo = (
functionName: 'getUserInfo',
query: {
enabled: Boolean(veCakeContract?.address && account),
select: (d) => {
select: useCallback((d: readonly [bigint, bigint, `0x${string}`, bigint, number, number, number, number]) => {
if (!d) return undefined
const [amount, end, cakePoolProxy, cakeAmount, lockEndTime, migrationTime, cakePoolType, withdrawFlag] = d
return {
Expand All @@ -68,7 +68,7 @@ export const useVeCakeUserInfo = (
cakePoolType,
withdrawFlag,
} as VeCakeUserInfo
},
}, []),
},
args: [account!],
watch: true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,31 @@ import useAccountActiveChain from 'hooks/useAccountActiveChain'
import { getCakeContract } from 'utils/contractHelpers'
import { useBCakeProxyContractAddress } from 'hooks/useBCakeProxyContractAddress'
import { useReadContract } from '@pancakeswap/wagmi'
import { useCallback } from 'react'

const useProxyCAKEBalance = () => {
const { account, chainId } = useAccountActiveChain()
const { proxyAddress } = useBCakeProxyContractAddress(account, chainId)
const cakeContract = getCakeContract()

const { data, refetch } = useReadContract({
const { data = 0, refetch } = useReadContract({
chainId,
address: cakeContract.address,
abi: cakeContract.abi,
query: {
enabled: Boolean(account && proxyAddress),
select: useCallback(
(cakeBalance: bigint) => (cakeBalance ? getBalanceNumber(new BigNumber(cakeBalance.toString())) : 0),
[],
),
},
functionName: 'balanceOf',
args: [proxyAddress],
args: proxyAddress && [proxyAddress],
})

return {
refreshProxyCakeBalance: refetch,
proxyCakeBalance: data ? getBalanceNumber(new BigNumber(data.toString())) : 0,
proxyCakeBalance: data,
}
}

Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/views/Farms/hooks/useBCakeProxyBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const useBCakeProxyBalance = () => {
queryKey: ['bCakeProxyBalance', account],

queryFn: async () => {
const rawBalance = await cakeContract?.read.balanceOf([bCakeProxy.address])
const rawBalance = await cakeContract?.read.balanceOf([bCakeProxy!.address])
return rawBalance ? new BigNumber(rawBalance.toString()) : new BigNumber(0)
},

Expand Down

This file was deleted.

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

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

const { data: shouldRenderUserBanner } = useQuery({
const { data: shouldRenderUserBanner = false } = useQuery({
queryKey: ['shouldRenderUserBanner', account],
queryFn: async () => {
const v2FarmsConfigSize = (await getLegacyFarmConfig(chainId))?.length || 0
Expand All @@ -25,9 +23,12 @@ const useIsRenderUserBanner = () => {
enabled: Boolean(account),
})

const cakePrice = useCakePrice({ enabled: shouldRenderUserBanner })

return useMemo(() => {
return { shouldRender: Boolean(shouldRenderUserBanner), isEarningsBusdZero }
}, [isEarningsBusdZero, shouldRenderUserBanner])
const isEarningsBusdZero = new BigNumber(farmEarningsSum).multipliedBy(cakePrice).isZero()
return { shouldRender: shouldRenderUserBanner, isEarningsBusdZero }
}, [shouldRenderUserBanner, farmEarningsSum, cakePrice])
}

export default useIsRenderUserBanner
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { TurkeyMeetupBanner } from 'views/Home/components/Banners/TurkeyMeetupBa
import CompetitionBanner from '../CompetitionBanner'
import { EigenpieIFOBanner } from '../EigenpieIFOBanner'
import { FourMemeBanner } from '../FourMemeBanner'
import { NigeriaMeetupBanner } from '../NigeriaMeetupBanner'
import { OptionsBanner } from '../OptionsBanner'
import { QuestBanner } from '../QuestBanner'
import { TgPredictionBotBanner } from '../TgPredictionBotBanner'
Expand All @@ -14,7 +13,6 @@ import { VeCakeBanner } from '../VeCakeBanner'
import WebNotificationBanner from '../WebNotificationBanner'
import useIsRenderCompetitionBanner from './useIsRenderCompetitionBanner'
import { useIsRenderIfoBannerFromConfig } from './useIsRenderIFOBanner'
import { useIsRenderTgPredictionBotBanner } from './useIsRenderTgPredictionBotBanner'
import useIsRenderUserBanner from './useIsRenderUserBanner'

interface IBannerConfig {
Expand All @@ -38,7 +36,6 @@ interface IBannerConfig {
export const useMultipleBannerConfig = () => {
const isRenderCompetitionBanner = useIsRenderCompetitionBanner()
const isRenderUserBanner = useIsRenderUserBanner()
const isRenderTgPredictionBotBanner = useIsRenderTgPredictionBotBanner()
const isRenderIFOBannerFromConfig = useIsRenderIfoBannerFromConfig()

return useMemo(() => {
Expand All @@ -47,10 +44,6 @@ export const useMultipleBannerConfig = () => {
shouldRender: true,
banner: <TurkeyMeetupBanner />,
},
{
shouldRender: true,
banner: <NigeriaMeetupBanner />,
},
{
shouldRender: isRenderIFOBannerFromConfig,
banner: <EigenpieIFOBanner />,
Expand All @@ -60,7 +53,7 @@ export const useMultipleBannerConfig = () => {
banner: <UserBanner />,
},
{
shouldRender: isRenderTgPredictionBotBanner,
shouldRender: true,
banner: <TgPredictionBotBanner />,
},
{
Expand Down Expand Up @@ -105,7 +98,6 @@ export const useMultipleBannerConfig = () => {
.map((bannerConfig: IBannerConfig) => bannerConfig.banner)
}, [
isRenderCompetitionBanner,
isRenderTgPredictionBotBanner,
isRenderUserBanner.isEarningsBusdZero,
isRenderUserBanner.shouldRender,
isRenderIFOBannerFromConfig,
Expand Down
5 changes: 3 additions & 2 deletions apps/web/src/views/Home/hooks/useCakeEmissionPerBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { masterChefV2ABI } from 'config/abi/masterchefV2'
import { getMasterChefV2Address } from 'utils/addressHelpers'
import { formatEther } from 'viem'
import { useReadContract } from '@pancakeswap/wagmi'
import { useCallback } from 'react'

const CAKE_PER_BLOCK = 40
const masterChefAddress = getMasterChefV2Address(ChainId.BSC)!
Expand All @@ -16,10 +17,10 @@ export const useCakeEmissionPerBlock = (inView?: boolean) => {
functionName: 'cakePerBlockToBurn',
query: {
enabled: inView,
select: (d) => {
select: useCallback((d: bigint) => {
const burn = formatEther(d)
return new BigNumber(CAKE_PER_BLOCK).minus(burn).toNumber()
},
}, []),
},
})

Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/views/Home/hooks/useFarmsWithBalance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export type FarmWithBalance = {

const useFarmsWithBalance = () => {
const { account, chainId } = useAccountActiveChain()
const { data: poolLength } = useFarmsLength()
const { data: poolLength } = useFarmsLength({ enabled: Boolean(account) })
const { proxyAddress, isLoading: isProxyContractAddressLoading } = useBCakeProxyContractAddress(account, chainId)
const bCakeProxy = useBCakeProxyContract(proxyAddress)
const masterChefContract = useMasterchef()
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/views/PoolDetail/hooks/usePoolTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import dayjs from 'dayjs'
import { chainIdToExplorerInfoChainName, explorerApiClient } from 'state/info/api/client'
import { components } from 'state/info/api/schema'
import { Address, Hash } from 'viem'
import { useCallback } from 'react'
import { Transaction, TransactionType } from '../components/Transactions/type'

const urlMap = {
Expand Down Expand Up @@ -67,6 +68,6 @@ export const usePoolTransactions = (address?: string, protocol?: Protocol, chain
queryFn: () =>
fetchPoolTransactions(address!, protocol!, chainName! as components['schemas']['ChainName'], chainId!),
enabled: !!address && !!protocol && !!chainName && !!chainId,
select: (data) => data.filter((tx) => tx.amountUSD > 0),
select: useCallback((data: Transaction[]) => data.filter((tx) => tx.amountUSD > 0), []),
})
}

0 comments on commit 3ee4a96

Please sign in to comment.