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

fix: farm stale data #2263

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 4 additions & 4 deletions src/pages/ElasticSwap/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ function useElasticAllRoutes(
const { chainId } = useActiveWeb3React()
const { pools, loading: poolsLoading } = useProAmmSwapPools(currencyIn, currencyOut)
return useMemo(() => {
if (poolsLoading || !chainId || !pools || !currencyIn || !currencyOut) return { loading: true, routes: [] }
if (poolsLoading || !pools || !currencyIn || !currencyOut) return { loading: true, routes: [] }

const routes = computeAllRoutes(currencyIn, currencyOut, pools, chainId, [], [], currencyIn, 1)

Expand Down Expand Up @@ -592,13 +592,13 @@ function useSwapCallArguments(
trade: Trade<Currency, Currency, TradeType> | undefined,
allowedSlippage = INITIAL_ALLOWED_SLIPPAGE,
): SwapCall[] {
const { account, chainId, networkInfo } = useActiveWeb3React()
const { account, networkInfo } = useActiveWeb3React()
const { library } = useWeb3React()

const deadline = useTransactionDeadline()

return useMemo(() => {
if (!trade || !account || !library || !account || !chainId || !deadline) return []
if (!trade || !account || !library || !account || !deadline) return []

const routerProAmmContract: Contract | null = getContract(
(networkInfo as EVMNetworkInfo).elastic.routers,
Expand All @@ -621,5 +621,5 @@ function useSwapCallArguments(
value,
},
]
}, [networkInfo, allowedSlippage, chainId, deadline, library, account, trade])
}, [networkInfo, allowedSlippage, deadline, library, account, trade])
}
1 change: 0 additions & 1 deletion src/pages/RemoveLiquidityProAmm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,6 @@ function Remove({ tokenId }: { tokenId: BigNumber }) {
!liquidityValue1 ||
!deadline ||
!account ||
!chainId ||
!feeValue0 ||
!feeValue1 ||
!positionSDK ||
Expand Down
6 changes: 2 additions & 4 deletions src/state/farms/elastic/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import { useSearchParams } from 'react-router-dom'
import ELASTIC_FARM_ABI from 'constants/abis/v2/farm.json'
import { ELASTIC_FARM_TYPE, FARM_TAB } from 'constants/index'
import { CONTRACT_NOT_FOUND_MSG } from 'constants/messages'
import { isEVM as isEVMNetwork } from 'constants/networks'
import { EVMNetworkInfo } from 'constants/networks/type'
import { useActiveWeb3React } from 'hooks'
import { useTokens } from 'hooks/Tokens'
Expand All @@ -36,9 +35,8 @@ export { default as FarmUpdater } from './updaters'

export const useElasticFarms = () => {
const { chainId } = useActiveWeb3React()
const isEVM = isEVMNetwork(chainId)
const elasticFarm = useAppSelector(state => state.elasticFarm[chainId])
return useMemo(() => (isEVM ? elasticFarm || defaultChainData : defaultChainData), [isEVM, elasticFarm])
const elasticFarm = useAppSelector(state => state.elasticFarm[chainId] || defaultChainData)
return elasticFarm
}

export const useFilteredFarms = () => {
Expand Down
7 changes: 4 additions & 3 deletions src/state/farms/elastic/updaters/v1.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ const defaultChainData = {
const FarmUpdaterV1: React.FC<CommonProps> = ({ interval }) => {
const dispatch = useAppDispatch()
const { chainId } = useActiveWeb3React()
const elasticFarm = useAppSelector(state => state.elasticFarm)[chainId || 1] || defaultChainData
const elasticFarm = useAppSelector(state => state.elasticFarm[chainId] || defaultChainData)
const { elasticClient } = useKyberSwapConfig()

const [getElasticFarms, { data, error }] = useLazyQuery(ELASTIC_FARM_QUERY, {
Expand Down Expand Up @@ -179,8 +179,9 @@ const FarmUpdaterV1: React.FC<CommonProps> = ({ interval }) => {
}
}, [error, dispatch, chainId])

const hasFarm = !!elasticFarm?.farms?.length
useEffect(() => {
if (data?.farms && chainId && !elasticFarm?.farms?.length) {
if (data?.farms && chainId && !hasFarm) {
// transform farm data
const formattedData: ElasticFarm[] = data.farms.map((farm: SubgraphFarm) => {
return {
Expand Down Expand Up @@ -268,7 +269,7 @@ const FarmUpdaterV1: React.FC<CommonProps> = ({ interval }) => {
})
dispatch(setFarms({ chainId, farms: formattedData }))
}
}, [data, dispatch, chainId, elasticFarm])
}, [data, dispatch, chainId, hasFarm])

return null
}
Expand Down
137 changes: 68 additions & 69 deletions src/state/farms/elasticv2/updater.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { CurrencyAmount, Token, WETH } from '@kyberswap/ks-sdk-core'
import { FeeAmount, Pool, Position } from '@kyberswap/ks-sdk-elastic'
import { BigNumber } from 'ethers'
import { Interface } from 'ethers/lib/utils'
import { useEffect, useMemo, useRef } from 'react'
import { useEffect, useRef } from 'react'
import { useLazyGetFarmV2Query } from 'services/knprotocol'

import FarmV2QuoterABI from 'constants/abis/farmv2Quoter.json'
Expand All @@ -17,11 +17,12 @@ import { NativeCurrencies } from 'constants/tokens'
import { useActiveWeb3React } from 'hooks'
import { useContract, useMulticallContract } from 'hooks/useContract'
import { useKyberSwapConfig } from 'state/application/hooks'
import { useAppDispatch, useAppSelector } from 'state/hooks'
import { useAppDispatch } from 'state/hooks'
import { useTokenPricesWithLoading } from 'state/tokenPrices/hooks'
import { isAddressString } from 'utils'
import { timeout } from 'utils/retry'

import { defaultChainData, setFarms, setLoading, setUserFarmInfo } from '.'
import { setFarms, setLoading, setUserFarmInfo } from '.'
import { ElasticFarmV2, SubgraphFarmV2, SubgraphToken, UserFarmV2Info } from './types'

const positionManagerInterface = new Interface(NFTPositionManagerABI.abi)
Expand Down Expand Up @@ -106,7 +107,6 @@ const queryFarms = gql`
export default function ElasticFarmV2Updater({ interval = true }: { interval?: boolean }) {
const dispatch = useAppDispatch()
const { networkInfo, isEVM, chainId, account } = useActiveWeb3React()
const elasticFarm = useAppSelector(state => state.elasticFarmV2[chainId] || defaultChainData)
const { elasticClient, isEnableKNProtocol } = useKyberSwapConfig()

const multicallContract = useMulticallContract()
Expand All @@ -115,82 +115,56 @@ export default function ElasticFarmV2Updater({ interval = true }: { interval?: b
FarmV2QuoterABI,
)

const [getElasticFarmV2, { data: subgraphData, error: subgraphError }] = useLazyQuery(queryFarms, {
const [getElasticFarmV2] = useLazyQuery<{ farmV2S: SubgraphFarmV2[] }>(queryFarms, {
client: elasticClient,
fetchPolicy: 'network-only',
})

const [getElasticFarmV2FromKnProtocol, { data: knProtocolData, error: knProtocolError }] = useLazyGetFarmV2Query()
const [getElasticFarmV2FromKnProtocol] = useLazyGetFarmV2Query()

const latestKnProtocolData = useRef(knProtocolData)

const data = useMemo(() => {
if (isEnableKNProtocol) {
return {
farmV2S: knProtocolData?.data?.data || latestKnProtocolData.current?.data?.data || [],
}
} else return subgraphData
}, [isEnableKNProtocol, knProtocolData, subgraphData])

const error = useMemo(() => {
if (isEnableKNProtocol) return knProtocolError
return subgraphError
}, [isEnableKNProtocol, subgraphError, knProtocolError])
const isLoadingElasticFarm = useRef(elasticFarm.loading)
isLoadingElasticFarm.current = elasticFarm.loading
const { fetchPrices } = useTokenPricesWithLoading([])
const tokensRef = useRef<string[]>([])
const pricesRef = useRef<{ [key: string]: number | undefined }>({})

useEffect(() => {
if (isEVM && !elasticFarm?.farms && !isLoadingElasticFarm.current) {
dispatch(setLoading({ chainId, loading: true }))
if (isEnableKNProtocol) {
getElasticFarmV2FromKnProtocol(chainId).finally(() => {
dispatch(setLoading({ chainId, loading: false }))
})
} else
getElasticFarmV2().finally(() => {
dispatch(setLoading({ chainId, loading: false }))
})
const controller = new AbortController()
const fetchData = async (): Promise<{ farmV2S: SubgraphFarmV2[]; error?: Error }> => {
if (isEVM) {
if (isEnableKNProtocol) {
try {
return { farmV2S: (await getElasticFarmV2FromKnProtocol(chainId))?.data?.data?.data || [] }
} catch (error) {
return { farmV2S: [], error }
}
} else {
try {
// Somehow, getElasticFarmV2() doesn't resolve nor reject so we might got an infinity await here
// Hence, we have to add an additional timeout to handle case it won't resolved
const result = (await timeout(getElasticFarmV2(), 5000)).data
return {
farmV2S: result?.farmV2S || [],
}
} catch (error) {
return { farmV2S: [], error }
}
}
}
return { farmV2S: [] }
}
}, [
isEVM,
chainId,
dispatch,
getElasticFarmV2,
elasticFarm?.farms,
getElasticFarmV2FromKnProtocol,
isEnableKNProtocol,
])

useEffect(() => {
const i = interval
? setInterval(() => {
if (isEnableKNProtocol) getElasticFarmV2FromKnProtocol(chainId)
else getElasticFarmV2()
}, 10_000)
: undefined
return () => {
i && clearInterval(i)
}
}, [interval, chainId, dispatch, getElasticFarmV2, getElasticFarmV2FromKnProtocol, isEnableKNProtocol])
const run = async () => {
dispatch(setLoading({ chainId, loading: true }))
const { farmV2S, error } = await fetchData()

useEffect(() => {
if (error && chainId) {
dispatch(setFarms({ chainId, farms: [] }))
if (controller.signal.aborted) return
dispatch(setLoading({ chainId, loading: false }))
}
}, [error, dispatch, chainId])

const { fetchPrices } = useTokenPricesWithLoading([])

const tokensRef = useRef<string[]>([])
const pricesRef = useRef<{ [key: string]: number | undefined }>({})

useEffect(() => {
const getData = async () => {
if (data?.farmV2S.length && chainId) {
if (error) {
dispatch(setFarms({ chainId, farms: [] }))
} else if (farmV2S.length) {
const tokens = [
...new Set(
data.farmV2S
farmV2S
.map((item: SubgraphFarmV2) => [
item.pool.token0.id,
item.pool.token1.id,
Expand All @@ -211,7 +185,7 @@ export default function ElasticFarmV2Updater({ interval = true }: { interval?: b
pricesRef.current = prices
}

const formattedData: ElasticFarmV2[] = data.farmV2S.map((farm: SubgraphFarmV2) => {
const formattedData: ElasticFarmV2[] = farmV2S.map((farm: SubgraphFarmV2) => {
const getToken = (t: SubgraphToken, keepWrapped = false) => {
const address = isAddressString(chainId, t.id)
return (keepWrapped ? false : address === WETH[chainId].address) || address === ZERO_ADDRESS
Expand Down Expand Up @@ -322,6 +296,7 @@ export default function ElasticFarmV2Updater({ interval = true }: { interval?: b
}
})

if (controller.signal.aborted) return
dispatch(setFarms({ chainId, farms: formattedData }))

const farmAddresses = [...new Set(formattedData.map(item => item.farmAddress))]
Expand Down Expand Up @@ -463,15 +438,39 @@ export default function ElasticFarmV2Updater({ interval = true }: { interval?: b
}),
)

if (controller.signal.aborted) return
dispatch(setUserFarmInfo({ chainId, userInfo: userFarmInfos.flat() }))
} else {
if (controller.signal.aborted) return
dispatch(setUserFarmInfo({ chainId, userInfo: [] }))
}
} else {
dispatch(setFarms({ chainId, farms: [] }))
dispatch(setUserFarmInfo({ chainId, userInfo: [] }))
}
}

getData()
}, [fetchPrices, networkInfo, chainId, dispatch, data, account, farmv2QuoterContract, multicallContract])
run()
const i = interval ? setInterval(run, 10_000) : undefined

return () => {
controller.abort()
i && clearInterval(i)
}
}, [
account,
chainId,
dispatch,
farmv2QuoterContract,
fetchPrices,
getElasticFarmV2,
getElasticFarmV2FromKnProtocol,
interval,
isEVM,
isEnableKNProtocol,
multicallContract,
networkInfo,
])

return null
}
4 changes: 4 additions & 0 deletions src/utils/retry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,7 @@ export const timeoutReject = (ms: number, msg = 'timeout') => {
}, ms)
})
}

export const timeout = <T>(promise: Promise<T>, ms: number): Promise<T> => {
return Promise.race([promise, timeoutReject(ms)]) as Promise<T>
}
Loading