Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: Remove isaddressequal usage and Call update cake apr once instead of per farm when initial load #10774

Open
wants to merge 50 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
f0417a7
perf: Call update cake apr once instead of per farm when initial load
memoyil Oct 2, 2024
8df78c4
fix: Caches and remove poolinfo from masterchef cache
memoyil Oct 2, 2024
1990185
perf: Use string key
memoyil Oct 2, 2024
234808c
perf: Use string instead of function for query key
memoyil Oct 3, 2024
167fb52
fix: Inline functions and avoid fetching pools again when cakeapr und…
memoyil Oct 3, 2024
2323a5b
chore: Remove async and braces
memoyil Oct 3, 2024
a50695a
perf: Dont fetch masterchef sanity check if there is no valid pool
memoyil Oct 3, 2024
d8f8e83
chore: Remove unused unset cache
memoyil Oct 3, 2024
31c0387
perf: Use native assign
memoyil Oct 4, 2024
a0f1ceb
fix: Make v2 calls retryable
memoyil Oct 12, 2024
2310a16
chore: Use getbalance
memoyil Oct 12, 2024
2ce557e
perf: Use hash
memoyil Oct 16, 2024
ae25cc7
perf: Make reduce efficent
memoyil Oct 16, 2024
e4add90
perf: Make reduce efficent
memoyil Oct 16, 2024
7d9aa5d
perf: Make account fetcher reduce more efficent
memoyil Oct 16, 2024
d2ba580
perf: Make fetchers reduce efficient
memoyil Oct 16, 2024
d3c872a
perf: Make chain reduce efficent
memoyil Oct 16, 2024
81d1098
chore: Upgrade jotai
memoyil Oct 16, 2024
b1d0964
fix: Build
memoyil Oct 16, 2024
eb331fa
fix: Recursive update
memoyil Oct 16, 2024
a3616c6
chore: Remove redundant getter
memoyil Oct 16, 2024
1034925
chore: Comment out update
memoyil Oct 16, 2024
799b6b0
fix: Atom update
memoyil Oct 17, 2024
2e514a5
fix: Atom update
memoyil Oct 17, 2024
b1cd3eb
fix: Give precedence to poolapr
memoyil Oct 17, 2024
d7aaedd
fix: Add Check
memoyil Oct 17, 2024
cd8d483
fix: Remove condition
memoyil Oct 17, 2024
641d4c1
fix: Add back condition
memoyil Oct 17, 2024
0978d7e
chore: Disable data fetch
memoyil Oct 17, 2024
ece6e80
chore: Use entries
memoyil Oct 17, 2024
6d5a5bb
fix: Build
memoyil Oct 17, 2024
022d409
fix: Wait
memoyil Oct 17, 2024
aacf3ef
chore: Remove query
memoyil Oct 17, 2024
36ddc68
chore: Upgrade nextjs
memoyil Oct 17, 2024
70bd226
chore: Remove farm fetch
memoyil Oct 17, 2024
0732737
fix: Use query
memoyil Oct 17, 2024
c5a1e13
chore: Upgrade tanstack query
memoyil Oct 17, 2024
56db390
chore: Experiment mock
memoyil Oct 17, 2024
d7cd8ad
fix: Revert query
memoyil Oct 17, 2024
0d91a2b
Revert "chore: Upgrade tanstack query"
memoyil Oct 17, 2024
3ccb51d
fix: Add back fetch
memoyil Oct 17, 2024
399d4f8
fix: mock response
memoyil Oct 17, 2024
d45c490
fix: Mock explorer result
memoyil Oct 17, 2024
eb83e6e
fix: mock with timeout
memoyil Oct 17, 2024
f24b000
fix: Dont use isaddress equal
memoyil Oct 17, 2024
23a0aa1
fix: Revert
memoyil Oct 17, 2024
73d80bf
fix: Use safeget instead of address equal
memoyil Oct 17, 2024
6223614
refactor: Use own isaddressequal
memoyil Oct 17, 2024
1281cf5
perf: Custom function
memoyil Oct 17, 2024
aa03fc3
perf: Use push and remove data.json
memoyil Oct 17, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion apps/aptos/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@
"@vanilla-extract/recipes": "^0.5.0",
"bignumber.js": "^9.0.0",
"dayjs": "^1.11.10",
"jotai": "^2.4.3",
"jotai": "^2.10.1",
"lodash": "^4.17.21",
"next": "catalog:",
"next-seo": "^5.15.0",
Expand Down
2 changes: 1 addition & 1 deletion apps/bridge/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"@wagmi/core": "^0.10.11",
"@wormhole-foundation/wormhole-connect": "0.1.7",
"ethers": "^5.0.0",
"jotai": "^2.4.3",
"jotai": "^2.10.1",
"lodash": "^4.17.21",
"next": "catalog:",
"next-themes": "^0.2.1",
Expand Down
2 changes: 1 addition & 1 deletion apps/gamification/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
"easymde": "2.16.1",
"graphql": "^16.8.1",
"graphql-request": "5.0.0",
"jotai": "^2.4.3",
"jotai": "^2.10.1",
"js-cookie": "^3.0.5",
"lodash": "^4.17.21",
"next": "catalog:",
Expand Down
4 changes: 2 additions & 2 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
"fast-json-stable-stringify": "^2.1.0",
"graphql": "^16.8.1",
"graphql-request": "5.0.0",
"jotai": "^2.4.3",
"jotai": "^2.10.1",
"js-cookie": "^3.0.1",
"lightweight-charts": "^4.0.1",
"local-storage": "^2.0.0",
Expand All @@ -120,7 +120,7 @@
"next-seo": "^5.15.0",
"next-themes": "^0.2.1",
"nuqs": "^1.17.4",
"openapi-fetch": "^0.9.7",
"openapi-fetch": "^0.12.2",
"polished": "^4.2.2",
"qs": "^6.0.0",
"react": "^18.2.0",
Expand Down
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
2 changes: 1 addition & 1 deletion apps/web/src/hooks/useUserAcknowledgement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { useAccount } from 'wagmi'
export function useUserAcknowledgement(id: string) {
const { address } = useAccount()
const atom = useMemo(
() => atomWithStorage(`pcs_user_ack_${id}_${address}`, false, undefined, { unstable_getOnInit: true }),
() => atomWithStorage(`pcs_user_ack_${id}_${address}`, false, undefined, { getOnInit: true }),
[id, address],
)
const [userACK, setUserACK] = useAtom(atom)
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/hooks/useZksyncAirDropAutoPopup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const zksyncAutoPopup = atomWithStorage<{ [account: string]: boolean }>(
'pcs:zksync-airdrop-auto-popup-v2',
{},
undefined,
{ unstable_getOnInit: true },
{ getOnInit: true },
)

const useAutoPopup = (): [boolean, (value: boolean) => void] => {
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/pages/usdv.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import styled from 'styled-components'

import DisclaimerModal from 'components/DisclaimerModal'

const usdvDisclaimer = atomWithStorage('pcs:usdv-disclaimer-accept', false, undefined, { unstable_getOnInit: true })
const usdvDisclaimer = atomWithStorage('pcs:usdv-disclaimer-accept', false, undefined, { getOnInit: true })

let initialized = false

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
12 changes: 8 additions & 4 deletions 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 Expand Up @@ -33,14 +34,17 @@ export const DEFAULT_QUERIES = {

export const extendPoolsQueryAtom = atom<ExtendPoolsQuery>(DEFAULT_QUERIES)

export const extendPoolsAtom = atom([] as PoolInfo[], (get, set, values: PoolInfo[]) => {
// remove duplicates pools with farmPoolsAtom
export const extendPoolsAtom = atom<PoolInfo[]>([])

export const updateExtendPoolsAtom = atom(null, (get, set, values: PoolInfo[]) => {
const farms = get(farmPoolsAtom)
const currentPools = get(extendPoolsAtom)

const newData = values.filter(
(pool) => !farms.some((farm) => isAddressEqual(farm.lpAddress, pool.lpAddress) && farm.protocol === pool.protocol),
)

set(extendPoolsAtom, [...get(extendPoolsAtom), ...newData])
set(extendPoolsAtom, [...currentPools, ...newData])
})

interface PoolsOfPositionType {
Expand Down
7 changes: 4 additions & 3 deletions apps/web/src/state/farmsV4/state/extendPools/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import { Token } from '@pancakeswap/swap-sdk-core'
import { computePoolAddress, DEPLOYER_ADDRESSES, FeeAmount } from '@pancakeswap/v3-sdk'
import { useQuery } from '@tanstack/react-query'
import { useAtom } from 'jotai'
import { useAtom, useAtomValue, useSetAtom } from 'jotai'
import memoize from 'lodash/memoize'
import { useCallback, useState } from 'react'
import { Address } from 'viem/accounts'
import type { PoolInfo } from '../type'
import { DEFAULT_QUERIES, extendPoolsAtom, ExtendPoolsQuery, extendPoolsQueryAtom } from './atom'
import { DEFAULT_QUERIES, extendPoolsAtom, ExtendPoolsQuery, extendPoolsQueryAtom, updateExtendPoolsAtom } from './atom'
import { fetchExplorerPoolInfo, fetchExplorerPoolsList } from './fetcher'

const RESET_QUERY_KEYS = ['protocols', 'orderBy', 'chains', 'pools', 'tokens'] as Array<keyof ExtendPoolsQuery>

export const useExtendPools = () => {
const [query, _setQuery] = useAtom(extendPoolsQueryAtom)
const [extendPools, updateExtendPools] = useAtom(extendPoolsAtom)
const updateExtendPools = useSetAtom(updateExtendPoolsAtom)
const extendPools = useAtomValue(extendPoolsAtom)
const [pageEnd, setPageEnd] = useState(false)
const fetchPoolList = useCallback(
async (newQuery: Partial<ExtendPoolsQuery>) => {
Expand Down
10 changes: 8 additions & 2 deletions apps/web/src/state/farmsV4/state/farmPools/fetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import { getStableSwapPools } from '@pancakeswap/stable-swap-sdk'
import { FeeAmount, masterChefV3ABI } from '@pancakeswap/v3-sdk'
import { explorerApiClient } from 'state/info/api/client'
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 All @@ -36,7 +37,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
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 () => {
const data = await fetchFarmPools()
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
Loading
Loading