Skip to content

Commit 3a92bc6

Browse files
Merge pull request #1757 from curvefi/refactor/user-balances-tanstack-query
refactor: use tanstack query for fetching user balances
2 parents 4d4ddbc + ee6e161 commit 3a92bc6

File tree

21 files changed

+228
-168
lines changed

21 files changed

+228
-168
lines changed

apps/main/src/dao/store/createAppSlice.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { produce } from 'immer'
22
import lodash from 'lodash'
3+
import type { Config } from 'wagmi'
34
import type { StoreApi } from 'zustand'
45
import type { State } from '@/dao/store/useStore'
56
import type { CurveApi, Wallet } from '@/dao/types/dao.types'
@@ -15,7 +16,7 @@ export interface AppSlice extends SliceState {
1516
updateGlobalStoreByKey: <T>(key: DefaultStateKeys, value: T) => void
1617

1718
/** Hydrate resets states and refreshes store data from the API */
18-
hydrate(api: CurveApi | undefined, prevApi: CurveApi | undefined, wallet: Wallet | undefined): Promise<void>
19+
hydrate(config: Config, api: CurveApi | undefined, prevApi: CurveApi | undefined, wallet: Wallet | undefined): Promise<void>
1920

2021
setAppStateByActiveKey<T>(sliceKey: SliceKey, key: StateKey, activeKey: string, value: T): void
2122
setAppStateByKey<T>(sliceKey: SliceKey, key: StateKey, value: T): void
@@ -35,7 +36,7 @@ const createAppSlice = (set: StoreApi<State>['setState'], get: StoreApi<State>['
3536
)
3637
},
3738

38-
hydrate: async (api, prevApi, wallet) => {
39+
hydrate: async (config, api, prevApi, wallet) => {
3940
if (!api) return
4041

4142
const isNetworkSwitched = prevApi?.chainId != api.chainId

apps/main/src/dex/components/PageCreatePool/ConfirmModal/CreatePoolButton.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { styled } from 'styled-components'
2+
import { useConfig } from 'wagmi'
23
import InfoLinkBar from '@/dex/components/PageCreatePool/ConfirmModal/CreateInfoLinkBar'
34
import { useNetworks } from '@/dex/entities/networks'
45
import { curveProps } from '@/dex/lib/utils'
@@ -25,6 +26,7 @@ const CreatePoolButton = ({ disabled, curve }: Props) => {
2526
const poolId = useStore((state) => state.createPool.transactionState.poolId)
2627
const errorMessage = useStore((state) => state.createPool.transactionState.errorMessage)
2728
const { connectState, connect: connectWallet } = useWallet()
29+
const config = useConfig()
2830

2931
return !haveSigner ? (
3032
<StyledButton variant="filled" onClick={() => connectWallet()} loading={isLoading(connectState)}>
@@ -39,7 +41,7 @@ const CreatePoolButton = ({ disabled, curve }: Props) => {
3941
</StyledAlertBox>
4042
)}
4143
{(txStatus === '' || txStatus === 'ERROR') && (
42-
<StyledButton disabled={disabled} variant={'icon-filled'} onClick={() => deployPool(curve)}>
44+
<StyledButton disabled={disabled} variant={'icon-filled'} onClick={() => deployPool(config, curve)}>
4345
{t`Create Pool`}
4446
</StyledButton>
4547
)}

apps/main/src/dex/components/PagePool/Page.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { useEffect, useMemo, useState } from 'react'
2+
import { useConfig } from 'wagmi'
23
import Transfer from '@/dex/components/PagePool/index'
34
import { ROUTE } from '@/dex/constants'
45
import { useNetworkByChain } from '@/dex/entities/networks'
@@ -30,12 +31,13 @@ export const PagePool = () => {
3031

3132
const poolDataCacheOrApi = useMemo(() => poolData || poolDataCache, [poolData, poolDataCache])
3233

34+
const config = useConfig()
3335
useEffect(() => {
3436
if (!rChainId || !poolId || curveApi?.chainId !== rChainId || !haveAllPools || poolData) return
35-
fetchNewPool(curveApi, poolId)
37+
fetchNewPool(config, curveApi, poolId)
3638
.then((found) => setPoolNotFound(!found))
3739
.catch(() => setPoolNotFound(true))
38-
}, [curveApi, fetchNewPool, haveAllPools, network, poolId, poolData, push, rChainId])
40+
}, [config, curveApi, fetchNewPool, haveAllPools, network, poolId, poolData, push, rChainId])
3941

4042
return !rFormType || network.excludePoolsMapper[poolId ?? ''] || poolNotFound ? (
4143
<ErrorPage title="404" subtitle={t`Pool Not Found`} continueUrl={getPath(props, ROUTE.PAGE_POOLS)} />

apps/main/src/dex/components/PageRouterSwap/index.tsx

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import lodash from 'lodash'
22
import { ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
33
import { ethAddress } from 'viem'
4+
import { useConfig } from 'wagmi'
45
import ChipInpHelper from '@/dex/components/ChipInpHelper'
56
import DetailInfoEstGas from '@/dex/components/DetailInfoEstGas'
67
import FieldHelperUsdRate from '@/dex/components/FieldHelperUsdRate'
@@ -131,6 +132,7 @@ const QuickSwap = ({
131132
const fromToken = tokens.find((x) => x.address.toLocaleLowerCase() == fromAddress)
132133
const toToken = tokens.find((x) => x.address.toLocaleLowerCase() == toAddress)
133134

135+
const config = useConfig()
134136
const updateFormValues = useCallback(
135137
(
136138
updatedFormValues: Partial<FormValues>,
@@ -143,6 +145,7 @@ const QuickSwap = ({
143145
setConfirmedLoss(false)
144146

145147
void setFormValues(
148+
config,
146149
pageLoaded ? curve : null,
147150
updatedFormValues,
148151
searchedParams,
@@ -152,7 +155,7 @@ const QuickSwap = ({
152155
isRefetch,
153156
)
154157
},
155-
[curve, storeMaxSlippage, pageLoaded, searchedParams, setFormValues],
158+
[config, curve, storeMaxSlippage, pageLoaded, searchedParams, setFormValues],
156159
)
157160

158161
const handleBtnClickSwap = useCallback(
@@ -175,7 +178,7 @@ const QuickSwap = ({
175178
const { dismiss } = notify(`Please confirm ${notifyMessage}`, 'pending')
176179
setTxInfoBar(<AlertBox alertType="info">Pending {notifyMessage}</AlertBox>)
177180

178-
const resp = await fetchStepSwap(actionActiveKey, curve, formValues, searchedParams, maxSlippage)
181+
const resp = await fetchStepSwap(actionActiveKey, config, curve, formValues, searchedParams, maxSlippage)
179182

180183
if (isSubscribed.current && resp && resp.hash && resp.activeKey === activeKey && !resp.error && network) {
181184
const txMessage = t`Transaction complete. Received ${resp.swappedAmount} ${toSymbol}.`
@@ -190,7 +193,7 @@ const QuickSwap = ({
190193
if (resp?.error) setTxInfoBar(null)
191194
if (typeof dismiss === 'function') dismiss()
192195
},
193-
[activeKey, fetchStepSwap, updateFormValues, network],
196+
[activeKey, config, fetchStepSwap, updateFormValues, network],
194197
)
195198

196199
const getSteps = useCallback(
@@ -222,7 +225,7 @@ const QuickSwap = ({
222225
onClick: async () => {
223226
const notifyMessage = t`Please approve spending your ${fromSymbol}.`
224227
const { dismiss } = notify(notifyMessage, 'pending')
225-
await fetchStepApprove(activeKey, curve, formValues, searchedParams, storeMaxSlippage)
228+
await fetchStepApprove(activeKey, config, curve, formValues, searchedParams, storeMaxSlippage)
226229
if (typeof dismiss === 'function') dismiss()
227230
},
228231
},
@@ -300,7 +303,15 @@ const QuickSwap = ({
300303

301304
return stepsKey.map((key) => stepsObj[key])
302305
},
303-
[confirmedLoss, fetchStepApprove, storeMaxSlippage, handleBtnClickSwap, slippageImpact?.isExpectedToAmount, steps],
306+
[
307+
config,
308+
confirmedLoss,
309+
fetchStepApprove,
310+
storeMaxSlippage,
311+
handleBtnClickSwap,
312+
slippageImpact?.isExpectedToAmount,
313+
steps,
314+
],
304315
)
305316

306317
const fetchData = useCallback(() => {
@@ -343,9 +354,9 @@ const QuickSwap = ({
343354
useEffect(() => fetchData(), [tokensMapperStr, searchedParams.fromAddress, searchedParams.toAddress])
344355

345356
useEffect(() => {
346-
void updateTokenList(isReady ? curve : null, tokensMapper)
357+
void updateTokenList(config, isReady ? curve : null, tokensMapper)
347358
// eslint-disable-next-line react-hooks/exhaustive-deps
348-
}, [isReady, tokensMapperStr, curve?.signerAddress])
359+
}, [config, isReady, tokensMapperStr, curve?.signerAddress])
349360

350361
// re-fetch data
351362
usePageVisibleInterval(fetchData, REFRESH_INTERVAL['15s'])

apps/main/src/dex/hooks/useAutoRefresh.tsx

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { useCallback, useMemo } from 'react'
2+
import { useConfig } from 'wagmi'
23
import curvejsApi from '@/dex/lib/curvejs'
34
import useStore from '@/dex/store/useStore'
45
import { type CurveApi, useCurve } from '@ui-kit/features/connect-wallet'
@@ -32,19 +33,20 @@ export const useAutoRefresh = (chainId: number | undefined) => {
3233
[chainId, fetchPoolsTvl, fetchPoolsVolume, poolDataMapper, setTokensMapper],
3334
)
3435

36+
const config = useConfig()
3537
usePageVisibleInterval(() => {
3638
if (curveApi) {
3739
void fetchPoolsVolumeTvl(curveApi)
3840

3941
if (curveApi.signerAddress) {
40-
void fetchAllStoredBalances(curveApi)
42+
void fetchAllStoredBalances(config, curveApi)
4143
}
4244
}
4345
}, REFRESH_INTERVAL['5m'])
4446

4547
usePageVisibleInterval(async () => {
4648
if (!curveApi || !network) return console.warn('Curve API or network is not defined, cannot refetch pools')
4749
const poolIds = await curvejsApi.network.fetchAllPoolsList(curveApi, network)
48-
void fetchPools(curveApi, poolIds, null)
50+
void fetchPools(config, curveApi, poolIds, null)
4951
}, REFRESH_INTERVAL['11m'])
5052
}

apps/main/src/dex/lib/curvejs.ts

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import {
1717
RewardCrv,
1818
RewardOther,
1919
RewardsApy,
20-
UserBalancesMapper,
2120
} from '@/dex/types/main.types'
2221
import { fulfilledValue, getErrorMessage, isValidAddress } from '@/dex/utils'
2322
import {
@@ -36,7 +35,6 @@ import {
3635
} from '@/dex/utils/utilsSwap'
3736
import type { IProfit } from '@curvefi/api/lib/interfaces'
3837
import type { DateValue } from '@internationalized/date'
39-
import PromisePool from '@supercharge/promise-pool/dist'
4038
import { BN } from '@ui/utils'
4139
import dayjs from '@ui-kit/lib/dayjs'
4240
import { waitForTransaction, waitForTransactions } from '@ui-kit/lib/ethers'
@@ -1368,42 +1366,6 @@ const wallet = {
13681366
log('userPoolShare', p.name)
13691367
return p.userShare()
13701368
},
1371-
fetchUserBalances: async (curve: CurveApi, tokenAddresses: string[]) => {
1372-
const { chainId } = curve
1373-
log('fetchWalletTokensBalances', chainId, tokenAddresses.length)
1374-
1375-
const results: UserBalancesMapper = {}
1376-
const errors: string[][] = []
1377-
const chunks = chunk(tokenAddresses, 20)
1378-
await PromisePool.for(chunks)
1379-
.withConcurrency(10)
1380-
.handleError((_, chunk) => {
1381-
errors.push(chunk)
1382-
})
1383-
.process(async (addresses) => {
1384-
const balances = (await curve.getBalances(addresses)) as string[]
1385-
for (const idx in balances) {
1386-
const balance = balances[idx]
1387-
const tokenAddress = addresses[idx]
1388-
results[tokenAddress] = balance
1389-
}
1390-
})
1391-
1392-
const fattenErrors = flatten(errors)
1393-
1394-
if (fattenErrors.length) {
1395-
await PromisePool.for(fattenErrors)
1396-
.handleError((error, tokenAddress) => {
1397-
console.error(`Unable to get user balance for ${tokenAddress}`, error)
1398-
results[tokenAddress] = 'NaN'
1399-
})
1400-
.process(async (tokenAddress) => {
1401-
const [balance] = (await curve.getBalances([tokenAddress])) as string[]
1402-
results[tokenAddress] = balance
1403-
})
1404-
}
1405-
return results
1406-
},
14071369
}
14081370

14091371
const lockCrv = {

apps/main/src/dex/store/createCreatePoolSlice.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { BigNumber } from 'bignumber.js'
22
import type { ContractTransactionResponse } from 'ethers'
33
import { produce } from 'immer'
44
import { zeroAddress } from 'viem'
5+
import type { Config } from 'wagmi'
56
import type { StoreApi } from 'zustand'
67
import {
78
CRYPTOSWAP,
@@ -141,7 +142,7 @@ export type CreatePoolSlice = {
141142
updateTokensInPoolValidation: (tokensInPool: boolean) => void
142143
updateParametersValidation: (parameters: boolean) => void
143144
updatePoolInfoValidation: (poolInfo: boolean) => void
144-
deployPool: (curve: CurveApi) => void
145+
deployPool: (config: Config, curve: CurveApi) => void
145146
resetState: () => void
146147
}
147148
}
@@ -766,7 +767,7 @@ const createCreatePoolSlice = (
766767
}),
767768
)
768769
},
769-
deployPool: async (curve: CurveApi) => {
770+
deployPool: async (config: Config, curve: CurveApi) => {
770771
const chainId = curve.chainId
771772
const {
772773
pools: { fetchNewPool, basePools },
@@ -867,7 +868,7 @@ const createCreatePoolSlice = (
867868
}),
868869
)
869870

870-
const poolData = await fetchNewPool(curve, poolId)
871+
const poolData = await fetchNewPool(config, curve, poolId)
871872
if (poolData) {
872873
set(
873874
produce((state) => {
@@ -944,7 +945,7 @@ const createCreatePoolSlice = (
944945
}),
945946
)
946947

947-
const poolData = await fetchNewPool(curve, poolId)
948+
const poolData = await fetchNewPool(config, curve, poolId)
948949
if (poolData) {
949950
set(
950951
produce((state) => {
@@ -1025,7 +1026,7 @@ const createCreatePoolSlice = (
10251026
}),
10261027
)
10271028

1028-
const poolData = await fetchNewPool(curve, poolId)
1029+
const poolData = await fetchNewPool(config, curve, poolId)
10291030
if (poolData) {
10301031
set(
10311032
produce((state) => {
@@ -1123,7 +1124,7 @@ const createCreatePoolSlice = (
11231124
}),
11241125
)
11251126

1126-
const poolData = await fetchNewPool(curve, poolId)
1127+
const poolData = await fetchNewPool(config, curve, poolId)
11271128
if (poolData) {
11281129
set(
11291130
produce((state) => {
@@ -1214,7 +1215,7 @@ const createCreatePoolSlice = (
12141215
}),
12151216
)
12161217

1217-
const poolData = await fetchNewPool(curve, poolId)
1218+
const poolData = await fetchNewPool(config, curve, poolId)
12181219
if (poolData) {
12191220
set(
12201221
produce((state) => {

apps/main/src/dex/store/createGlobalSlice.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { produce } from 'immer'
22
import lodash from 'lodash'
3+
import type { Config } from 'wagmi'
34
import type { StoreApi } from 'zustand'
45
import curvejsApi from '@/dex/lib/curvejs'
56
import type { State } from '@/dex/store/useStore'
@@ -22,7 +23,12 @@ export interface GlobalSlice extends GlobalState {
2223
setNetworkConfigFromApi(curve: CurveApi): void
2324

2425
/** Hydrate resets states and refreshes store data from the API */
25-
hydrate(curveApi: CurveApi | undefined, prevCurveApi: CurveApi | undefined, wallet: Wallet | undefined): Promise<void>
26+
hydrate(
27+
config: Config,
28+
curveApi: CurveApi | undefined,
29+
prevCurveApi: CurveApi | undefined,
30+
wallet: Wallet | undefined,
31+
): Promise<void>
2632

2733
updateGlobalStoreByKey: <T>(key: DefaultStateKeys, value: T) => void
2834

@@ -63,7 +69,7 @@ const createGlobalSlice = (set: StoreApi<State>['setState'], get: StoreApi<State
6369
}),
6470
)
6571
},
66-
hydrate: async (curveApi, prevCurveApi) => {
72+
hydrate: async (config, curveApi, prevCurveApi) => {
6773
if (!curveApi) return
6874

6975
const state = get()
@@ -117,7 +123,7 @@ const createGlobalSlice = (set: StoreApi<State>['setState'], get: StoreApi<State
117123
const failedFetching24hOldVprice: { [poolAddress: string]: boolean } =
118124
chainId === 2222 ? await curvejsApi.network.getFailedFetching24hOldVprice() : {}
119125

120-
await state.pools.fetchPools(curveApi, poolIds, failedFetching24hOldVprice)
126+
await state.pools.fetchPools(config, curveApi, poolIds, failedFetching24hOldVprice)
121127

122128
if (isUserSwitched || isNetworkSwitched) {
123129
void state.pools.fetchPricesApiPools(chainId)

0 commit comments

Comments
 (0)