Skip to content

Commit

Permalink
perf: Remove isaddressequal usage and Call update cake apr once inste…
Browse files Browse the repository at this point in the history
…ad of per farm when initial load (#10774)

<!--
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 primarily focuses on code refactoring and optimization,
particularly around the usage of `isAddressEqual` and reducing array
operations for improved readability and performance.

### Detailed summary
- Removed `refetchInterval` from several hooks.
- Changed array reduction methods to use `push` instead of spreading.
- Standardized import of `isAddressEqual` from `utils` instead of
`viem`.
- Updated various components and hooks to improve code clarity and
performance.
- Enhanced error handling in asynchronous functions.

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

<!-- end pr-codex -->
  • Loading branch information
memoyil authored Oct 18, 2024
1 parent 9d0e560 commit e8744cf
Show file tree
Hide file tree
Showing 38 changed files with 280 additions and 188 deletions.
3 changes: 2 additions & 1 deletion apps/web/src/hooks/usePermit2Requires.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { CurrencyAmount, Token } from '@pancakeswap/swap-sdk-core'
import { bscTestnetTokens, ethereumTokens, goerliTestnetTokens } from '@pancakeswap/tokens'
import { useMemo } from 'react'
import { Address, isAddressEqual } from 'viem'
import { isAddressEqual } from 'utils'
import { Address } from 'viem'
import useAccountActiveChain from './useAccountActiveChain'
import useCurrentBlockTimestamp from './useCurrentBlockTimestamp'
import { usePermit2Allowance } from './usePermit2Allowance'
Expand Down
49 changes: 28 additions & 21 deletions apps/web/src/state/farmsV4/state/accountPositions/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AppState } from 'state'
import { safeGetAddress } from 'utils'
import { publicClient } from 'utils/viem'
import { Address, erc20Abi, zeroAddress } from 'viem'
import { getBalanceNumber } from '@pancakeswap/utils/formatBalance'
import { StablePoolInfo, V2PoolInfo } from '../type'
import { StableLPDetail, V2LPDetail } from './type'

Expand Down Expand Up @@ -136,10 +137,7 @@ export const getAccountV2LpDetails = async (

const validLpTokens = lpTokens.filter((token) => token.chainId === chainId)

const bCakeWrapperAddresses = validReserveTokens.map((tokens) => {
const lpAddress = getV2LiquidityToken(tokens).address
return getBCakeWrapperAddress(lpAddress, chainId)
})
const bCakeWrapperAddresses = validLpTokens.map((token) => getBCakeWrapperAddress(token.address, chainId))

const balanceCalls = validLpTokens.map((token) => {
return {
Expand All @@ -152,15 +150,13 @@ export const getAccountV2LpDetails = async (
const farmingCalls = bCakeWrapperAddresses.reduce(
(acc, address) => {
if (!address || address === '0x') return acc
return [
...acc,
{
abi: v2BCakeWrapperABI,
address,
functionName: 'userInfo',
args: [account] as const,
} as const,
]
acc.push({
abi: v2BCakeWrapperABI,
address,
functionName: 'userInfo',
args: [account] as const,
})
return acc
},
[] as Array<{
abi: typeof v2BCakeWrapperABI
Expand Down Expand Up @@ -203,16 +199,26 @@ export const getAccountV2LpDetails = async (
])

const farming = bCakeWrapperAddresses.reduce((acc, address) => {
if (!address || address === '0x') return [...acc, undefined]
const { result } = _farming.shift() ?? { result: undefined }
return [...acc, result]
if (!address || address === '0x') {
acc.push(undefined)
} else {
const { result } = _farming.shift() ?? { result: undefined }
acc.push(result)
}
return acc
}, [] as Array<readonly [bigint, bigint, bigint, bigint, bigint] | undefined>)

return balances
.map((result, index) => {
const { result: _balance = 0n, status } = result
// LP not exist
if (status === 'failure') return undefined
if (status === 'failure') {
if (reserves[index].status === 'failure' && totalSupplies[index].status === 'failure') {
return undefined
}
throw new Error(
`Mismatch between balances, reserves, and supplies: Token: ${validLpTokens[index].address} Balance (${status}), Reserve (${reserves[index].status}), Supply (${totalSupplies[index].status})`,
)
}

const nativeBalance = CurrencyAmount.fromRawAmount(validLpTokens[index], _balance)
const farmingInfo = farming[index]
Expand All @@ -221,7 +227,7 @@ export const getAccountV2LpDetails = async (
let farmingBoostedAmount = CurrencyAmount.fromRawAmount(validLpTokens[index], '0')
if (farmingInfo) {
farmingBalance = CurrencyAmount.fromRawAmount(validLpTokens[index], farmingInfo[0].toString())
farmingBoosterMultiplier = new BigNumber(Number(farmingInfo[2])).div(1000000000000).toNumber()
farmingBoosterMultiplier = getBalanceNumber(new BigNumber(Number(farmingInfo[2])), 12)
farmingBoostedAmount = CurrencyAmount.fromRawAmount(validLpTokens[index], farmingInfo[3].toString())
}
const tokens = validReserveTokens[index]
Expand Down Expand Up @@ -256,7 +262,7 @@ export const getAccountV2LpDetails = async (
protocol: Protocol.V2,
}
})
.filter((r) => typeof r !== 'undefined') as V2LPDetail[]
.filter(Boolean) as V2LPDetail[]
}

export const getStablePairDetails = async (
Expand All @@ -270,7 +276,8 @@ export const getStablePairDetails = async (
if (!account || !client || !validStablePairs.length) return []

const bCakeWrapperAddresses = validStablePairs.reduce((acc, pair) => {
return [...acc, getBCakeWrapperAddress(pair.lpAddress, chainId)]
acc.push(getBCakeWrapperAddress(pair.lpAddress, chainId))
return acc
}, [] as Array<Address>)

const balanceCalls = validStablePairs.map((pair) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { Protocol } from '@pancakeswap/farms'
import { LegacyRouter } from '@pancakeswap/smart-router/legacy-router'
import { useQuery, UseQueryResult } from '@tanstack/react-query'
import { useCallback, useMemo } from 'react'
import { Address, isAddressEqual } from 'viem'
import { isAddressEqual } from 'utils'
import { Address } from 'viem'
import { PoolInfo } from '../../type'
import { getAccountV2LpDetails, getStablePairDetails } from '../fetcher'
import { getAccountV3Positions } from '../fetcher/v3'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ export const useAccountV2LpDetails = (chainIds: number[], account?: Address | nu
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchInterval: false,
// Prevents re-fetching while the data is still fresh
staleTime: SLOW_INTERVAL,
} satisfies UseQueryOptions<V2LPDetail[]>
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/state/farmsV4/state/extendPools/atom.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { ChainId } from '@pancakeswap/chains'
import { Protocol, supportedChainIdV4 } from '@pancakeswap/farms'
import { atom } from 'jotai'
import { isAddressEqual, type Address } from 'viem'
import { isAddressEqual } from 'utils'
import { type Address } from 'viem'
import { farmPoolsAtom } from '../farmPools/atom'
import { ChainIdAddressKey, PoolInfo } from '../type'

Expand Down
15 changes: 13 additions & 2 deletions apps/web/src/state/farmsV4/state/farmPools/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import groupBy from 'lodash/groupBy'
import { explorerApiClient } from 'state/info/api/client'
import { v3Clients } from 'utils/graphql'
import { publicClient } from 'utils/viem'
import { isAddressEqual, type Address } from 'viem'
import { isAddressEqual } from 'utils'
import { type Address } from 'viem'
import { PoolInfo } from '../type'
import { parseFarmPools } from '../utils'

Expand Down Expand Up @@ -146,7 +147,12 @@ export const fetchExplorerFarmPools = async (
params: {
query: {
protocols: args.protocols ?? DEFAULT_PROTOCOLS,
chains: chains.reduce((acc, cur) => (cur ? [...acc, getChainNameInKebabCase(cur)] : acc), [] as any[]),
chains: chains.reduce((acc, cur) => {
if (cur) {
acc.push(getChainNameInKebabCase(cur))
}
return acc
}, [] as any[]),
},
},
})
Expand Down Expand Up @@ -184,6 +190,11 @@ export const fetchFarmPools = async (
try {
remotePools = await fetchExplorerFarmPools(args, signal)
} catch (error) {
if (error instanceof Error) {
if (error.name === 'AbortError') {
throw error
}
}
console.error('Failed to fetch remote pools', error)
}
const localPools = UNIVERSAL_FARMS.filter((farm) => {
Expand Down
45 changes: 19 additions & 26 deletions apps/web/src/state/farmsV4/state/farmPools/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import dayjs from 'dayjs'
import { useAtom } from 'jotai'
import groupBy from 'lodash/groupBy'
import keyBy from 'lodash/keyBy'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { useCallback, useMemo } from 'react'
import { publicClient } from 'utils/viem'
import { zeroAddress } from 'viem'
import { Address } from 'viem/accounts'
Expand All @@ -22,18 +22,18 @@ type UnwrapPromise<T> = T extends Promise<infer U> ? U : T
type ArrayItemType<T> = T extends Array<infer U> ? U : T

export const useFarmPools = () => {
const [loaded, setLoaded] = useState(false)
const [pools, setPools] = useAtom(farmPoolsAtom)

useEffect(() => {
if (!loaded) {
fetchFarmPools()
.then(setPools)
.finally(() => setLoaded(true))
}
// only fetch once when mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const { isLoading } = useQuery({
queryKey: ['fetchFarmPools'],
queryFn: async ({ signal }) => {
const data = await fetchFarmPools(undefined, signal)
setPools(data)
},
refetchOnMount: false,
refetchOnReconnect: false,
refetchOnWindowFocus: false,
})

const { data: poolsStatus, pending: isPoolStatusPending } = useMultiChainV3PoolsStatus(UNIVERSAL_FARMS)
const { data: poolsTimeFrame, pending: isPoolsTimeFramePending } = useMultiChainPoolsTimeFrame(UNIVERSAL_FARMS)
Expand All @@ -60,7 +60,7 @@ export const useFarmPools = () => {
})
}, [pools, poolsStatus, isPoolStatusPending, poolsTimeFrame, isPoolsTimeFramePending])

return { loaded, data: poolsWithStatus }
return { loaded: !isLoading, data: poolsWithStatus }
}

export const useV3PoolsLength = (chainIds: number[]) => {
Expand Down Expand Up @@ -88,10 +88,8 @@ export const useV3PoolsLength = (chainIds: number[]) => {
(results: UseQueryResult<bigint, Error>[]) => {
return {
data: results.reduce((acc, result, idx) => {
return {
...acc,
[chainIds[idx]]: Number(result.data ?? 0),
}
Object.assign(acc, { [chainIds[idx]]: Number(result.data ?? 0) })
return acc
}, {} as { [key: `${number}`]: number }),
pending: results.some((result) => result.isPending),
}
Expand Down Expand Up @@ -130,10 +128,7 @@ export const useV2PoolsLength = (chainIds: number[]) => {
(results: UseQueryResult<bigint, Error>[]) => {
return {
data: results.reduce((acc, result, idx) => {
return {
...acc,
[chainIds[idx]]: Number(result.data ?? 0),
}
return Object.assign(acc, { [chainIds[idx]]: Number(result.data ?? 0) })
}, {} as { [key: `${number}`]: number }),
pending: results.some((result) => result.isPending),
}
Expand Down Expand Up @@ -172,10 +167,9 @@ export const useMultiChainV3PoolsStatus = (pools: UniversalFarmConfig[]) => {
(results: UseQueryResult<UnwrapPromise<ReturnType<typeof fetchV3PoolsStatusByChainId>>, Error>[]) => {
return {
data: results.reduce((acc, result, idx) => {
return {
...acc,
return Object.assign(acc, {
[poolsEntries[idx][0]]: keyBy(result.data ?? [], ([, lpAddress]) => lpAddress),
}
})
}, {} as IPoolsStatusType),
pending: results.some((result) => result.isPending),
}
Expand Down Expand Up @@ -259,12 +253,11 @@ export const useMultiChainPoolsTimeFrame = (pools: UniversalFarmConfig[]) => {
return {
data: results.reduce((acc, result, idx) => {
let dataIdx = 0
return {
...acc,
return Object.assign(acc, {
[poolsEntries[idx][0]]: keyBy(result.data ?? [], () => {
return poolsEntries[idx][1][dataIdx++].lpAddress
}),
}
})
}, {} as IPoolsTimeFrameType),
pending: results.some((result) => result.isPending),
}
Expand Down
25 changes: 11 additions & 14 deletions apps/web/src/state/farmsV4/state/poolApr/atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,9 @@ export type LpApr = AprValue
export const lpAprAtom = atom<LpApr>((get) => {
const pools = get(poolsAtom)
return pools.reduce((acc, pool) => {
return {
...acc,
[`${pool.chainId}:${pool.lpAddress}`]: pool.lpApr ?? '0',
}
// eslint-disable-next-line no-param-reassign
acc[`${pool.chainId}:${pool.lpAddress}`] = pool.lpApr ?? '0'
return acc
}, {} as LpApr)
})

Expand All @@ -43,7 +42,6 @@ export type CakeApr = Record<
>
export const cakeAprAtom = atom<CakeApr>({})

export const cakeAprGetterAtom = atom
export const cakeAprSetterAtom = atom(null, (get, set, newApr: CakeApr) => {
const cakeApr = get(cakeAprAtom)
set(cakeAprAtom, { ...cakeApr, ...newApr })
Expand All @@ -63,21 +61,20 @@ export const poolAprAtom = atom<PoolApr>((get) => {
const cakeAprs = get(cakeAprAtom)
const merklAprs = get(merklAprAtom)

return Object.keys(lpAprs).reduce((acc, key) => {
return {
...acc,
[key]: {
lpApr: lpAprs[key],
cakeApr: cakeAprs[key],
merklApr: merklAprs[key],
},
return Object.entries(lpAprs).reduce((acc, [key, lpApr]) => {
// eslint-disable-next-line no-param-reassign
acc[key] = {
lpApr,
cakeApr: cakeAprs[key],
merklApr: merklAprs[key],
}
return acc
}, {} as PoolApr)
})

export const emptyCakeAprPoolsAtom = atom((get) => {
const pools = get(poolsAtom)
const aprs = get(cakeAprAtom)

return pools.filter((pool) => !aprs[`${pool.chainId}:${pool.lpAddress}`])
return pools.filter((pool) => !(`${pool.chainId}:${pool.lpAddress}` in aprs))
})
Loading

0 comments on commit e8744cf

Please sign in to comment.