Skip to content
Merged
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
5 changes: 3 additions & 2 deletions apps/main/src/dao/store/createAppSlice.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { produce } from 'immer'
import lodash from 'lodash'
import type { Config } from 'wagmi'
import type { StoreApi } from 'zustand'
import type { State } from '@/dao/store/useStore'
import type { CurveApi, Wallet } from '@/dao/types/dao.types'
Expand All @@ -15,7 +16,7 @@ export interface AppSlice extends SliceState {
updateGlobalStoreByKey: <T>(key: DefaultStateKeys, value: T) => void

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

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

hydrate: async (api, prevApi, wallet) => {
hydrate: async (config, api, prevApi, wallet) => {
if (!api) return

const isNetworkSwitched = prevApi?.chainId != api.chainId
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { styled } from 'styled-components'
import { useConfig } from 'wagmi'
import InfoLinkBar from '@/dex/components/PageCreatePool/ConfirmModal/CreateInfoLinkBar'
import { useNetworks } from '@/dex/entities/networks'
import { curveProps } from '@/dex/lib/utils'
Expand All @@ -25,6 +26,7 @@ const CreatePoolButton = ({ disabled, curve }: Props) => {
const poolId = useStore((state) => state.createPool.transactionState.poolId)
const errorMessage = useStore((state) => state.createPool.transactionState.errorMessage)
const { connectState, connect: connectWallet } = useWallet()
const config = useConfig()

return !haveSigner ? (
<StyledButton variant="filled" onClick={() => connectWallet()} loading={isLoading(connectState)}>
Expand All @@ -39,7 +41,7 @@ const CreatePoolButton = ({ disabled, curve }: Props) => {
</StyledAlertBox>
)}
{(txStatus === '' || txStatus === 'ERROR') && (
<StyledButton disabled={disabled} variant={'icon-filled'} onClick={() => deployPool(curve)}>
<StyledButton disabled={disabled} variant={'icon-filled'} onClick={() => deployPool(config, curve)}>
{t`Create Pool`}
</StyledButton>
)}
Expand Down
6 changes: 4 additions & 2 deletions apps/main/src/dex/components/PagePool/Page.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useState } from 'react'
import { useConfig } from 'wagmi'
import Transfer from '@/dex/components/PagePool/index'
import { ROUTE } from '@/dex/constants'
import { useNetworkByChain } from '@/dex/entities/networks'
Expand Down Expand Up @@ -30,12 +31,13 @@ export const PagePool = () => {

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

const config = useConfig()
useEffect(() => {
if (!rChainId || !poolId || curveApi?.chainId !== rChainId || !haveAllPools || poolData) return
fetchNewPool(curveApi, poolId)
fetchNewPool(config, curveApi, poolId)
.then((found) => setPoolNotFound(!found))
.catch(() => setPoolNotFound(true))
}, [curveApi, fetchNewPool, haveAllPools, network, poolId, poolData, push, rChainId])
}, [config, curveApi, fetchNewPool, haveAllPools, network, poolId, poolData, push, rChainId])

return !rFormType || network.excludePoolsMapper[poolId ?? ''] || poolNotFound ? (
<ErrorPage title="404" subtitle={t`Pool Not Found`} continueUrl={getPath(props, ROUTE.PAGE_POOLS)} />
Expand Down
25 changes: 18 additions & 7 deletions apps/main/src/dex/components/PageRouterSwap/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import lodash from 'lodash'
import { ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ethAddress } from 'viem'
import { useConfig } from 'wagmi'
import ChipInpHelper from '@/dex/components/ChipInpHelper'
import DetailInfoEstGas from '@/dex/components/DetailInfoEstGas'
import FieldHelperUsdRate from '@/dex/components/FieldHelperUsdRate'
Expand Down Expand Up @@ -131,6 +132,7 @@ const QuickSwap = ({
const fromToken = tokens.find((x) => x.address.toLocaleLowerCase() == fromAddress)
const toToken = tokens.find((x) => x.address.toLocaleLowerCase() == toAddress)

const config = useConfig()
const updateFormValues = useCallback(
(
updatedFormValues: Partial<FormValues>,
Expand All @@ -143,6 +145,7 @@ const QuickSwap = ({
setConfirmedLoss(false)

void setFormValues(
config,
pageLoaded ? curve : null,
updatedFormValues,
searchedParams,
Expand All @@ -152,7 +155,7 @@ const QuickSwap = ({
isRefetch,
)
},
[curve, storeMaxSlippage, pageLoaded, searchedParams, setFormValues],
[config, curve, storeMaxSlippage, pageLoaded, searchedParams, setFormValues],
)

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

const resp = await fetchStepSwap(actionActiveKey, curve, formValues, searchedParams, maxSlippage)
const resp = await fetchStepSwap(actionActiveKey, config, curve, formValues, searchedParams, maxSlippage)

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

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

return stepsKey.map((key) => stepsObj[key])
},
[confirmedLoss, fetchStepApprove, storeMaxSlippage, handleBtnClickSwap, slippageImpact?.isExpectedToAmount, steps],
[
config,
confirmedLoss,
fetchStepApprove,
storeMaxSlippage,
handleBtnClickSwap,
slippageImpact?.isExpectedToAmount,
steps,
],
)

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

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

// re-fetch data
usePageVisibleInterval(fetchData, REFRESH_INTERVAL['15s'])
Expand Down
6 changes: 4 additions & 2 deletions apps/main/src/dex/hooks/useAutoRefresh.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useMemo } from 'react'
import { useConfig } from 'wagmi'
import curvejsApi from '@/dex/lib/curvejs'
import useStore from '@/dex/store/useStore'
import { type CurveApi, useCurve } from '@ui-kit/features/connect-wallet'
Expand Down Expand Up @@ -32,19 +33,20 @@ export const useAutoRefresh = (chainId: number | undefined) => {
[chainId, fetchPoolsTvl, fetchPoolsVolume, poolDataMapper, setTokensMapper],
)

const config = useConfig()
usePageVisibleInterval(() => {
if (curveApi) {
void fetchPoolsVolumeTvl(curveApi)

if (curveApi.signerAddress) {
void fetchAllStoredBalances(curveApi)
void fetchAllStoredBalances(config, curveApi)
}
}
}, REFRESH_INTERVAL['5m'])

usePageVisibleInterval(async () => {
if (!curveApi || !network) return console.warn('Curve API or network is not defined, cannot refetch pools')
const poolIds = await curvejsApi.network.fetchAllPoolsList(curveApi, network)
void fetchPools(curveApi, poolIds, null)
void fetchPools(config, curveApi, poolIds, null)
}, REFRESH_INTERVAL['11m'])
}
38 changes: 0 additions & 38 deletions apps/main/src/dex/lib/curvejs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import {
RewardCrv,
RewardOther,
RewardsApy,
UserBalancesMapper,
} from '@/dex/types/main.types'
import { fulfilledValue, getErrorMessage, isValidAddress } from '@/dex/utils'
import {
Expand All @@ -36,7 +35,6 @@ import {
} from '@/dex/utils/utilsSwap'
import type { IProfit } from '@curvefi/api/lib/interfaces'
import type { DateValue } from '@internationalized/date'
import PromisePool from '@supercharge/promise-pool/dist'
import { BN } from '@ui/utils'
import dayjs from '@ui-kit/lib/dayjs'
import { waitForTransaction, waitForTransactions } from '@ui-kit/lib/ethers'
Expand Down Expand Up @@ -1368,42 +1366,6 @@ const wallet = {
log('userPoolShare', p.name)
return p.userShare()
},
fetchUserBalances: async (curve: CurveApi, tokenAddresses: string[]) => {
const { chainId } = curve
log('fetchWalletTokensBalances', chainId, tokenAddresses.length)

const results: UserBalancesMapper = {}
const errors: string[][] = []
const chunks = chunk(tokenAddresses, 20)
await PromisePool.for(chunks)
.withConcurrency(10)
.handleError((_, chunk) => {
errors.push(chunk)
})
.process(async (addresses) => {
const balances = (await curve.getBalances(addresses)) as string[]
for (const idx in balances) {
const balance = balances[idx]
const tokenAddress = addresses[idx]
results[tokenAddress] = balance
}
})

const fattenErrors = flatten(errors)

if (fattenErrors.length) {
await PromisePool.for(fattenErrors)
.handleError((error, tokenAddress) => {
console.error(`Unable to get user balance for ${tokenAddress}`, error)
results[tokenAddress] = 'NaN'
})
.process(async (tokenAddress) => {
const [balance] = (await curve.getBalances([tokenAddress])) as string[]
results[tokenAddress] = balance
})
}
return results
},
}

const lockCrv = {
Expand Down
15 changes: 8 additions & 7 deletions apps/main/src/dex/store/createCreatePoolSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { BigNumber } from 'bignumber.js'
import type { ContractTransactionResponse } from 'ethers'
import { produce } from 'immer'
import { zeroAddress } from 'viem'
import type { Config } from 'wagmi'
import type { StoreApi } from 'zustand'
import {
CRYPTOSWAP,
Expand Down Expand Up @@ -141,7 +142,7 @@ export type CreatePoolSlice = {
updateTokensInPoolValidation: (tokensInPool: boolean) => void
updateParametersValidation: (parameters: boolean) => void
updatePoolInfoValidation: (poolInfo: boolean) => void
deployPool: (curve: CurveApi) => void
deployPool: (config: Config, curve: CurveApi) => void
resetState: () => void
}
}
Expand Down Expand Up @@ -766,7 +767,7 @@ const createCreatePoolSlice = (
}),
)
},
deployPool: async (curve: CurveApi) => {
deployPool: async (config: Config, curve: CurveApi) => {
const chainId = curve.chainId
const {
pools: { fetchNewPool, basePools },
Expand Down Expand Up @@ -867,7 +868,7 @@ const createCreatePoolSlice = (
}),
)

const poolData = await fetchNewPool(curve, poolId)
const poolData = await fetchNewPool(config, curve, poolId)
if (poolData) {
set(
produce((state) => {
Expand Down Expand Up @@ -944,7 +945,7 @@ const createCreatePoolSlice = (
}),
)

const poolData = await fetchNewPool(curve, poolId)
const poolData = await fetchNewPool(config, curve, poolId)
if (poolData) {
set(
produce((state) => {
Expand Down Expand Up @@ -1025,7 +1026,7 @@ const createCreatePoolSlice = (
}),
)

const poolData = await fetchNewPool(curve, poolId)
const poolData = await fetchNewPool(config, curve, poolId)
if (poolData) {
set(
produce((state) => {
Expand Down Expand Up @@ -1123,7 +1124,7 @@ const createCreatePoolSlice = (
}),
)

const poolData = await fetchNewPool(curve, poolId)
const poolData = await fetchNewPool(config, curve, poolId)
if (poolData) {
set(
produce((state) => {
Expand Down Expand Up @@ -1214,7 +1215,7 @@ const createCreatePoolSlice = (
}),
)

const poolData = await fetchNewPool(curve, poolId)
const poolData = await fetchNewPool(config, curve, poolId)
if (poolData) {
set(
produce((state) => {
Expand Down
12 changes: 9 additions & 3 deletions apps/main/src/dex/store/createGlobalSlice.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { produce } from 'immer'
import lodash from 'lodash'
import type { Config } from 'wagmi'
import type { StoreApi } from 'zustand'
import curvejsApi from '@/dex/lib/curvejs'
import type { State } from '@/dex/store/useStore'
Expand All @@ -22,7 +23,12 @@ export interface GlobalSlice extends GlobalState {
setNetworkConfigFromApi(curve: CurveApi): void

/** Hydrate resets states and refreshes store data from the API */
hydrate(curveApi: CurveApi | undefined, prevCurveApi: CurveApi | undefined, wallet: Wallet | undefined): Promise<void>
hydrate(
config: Config,
curveApi: CurveApi | undefined,
prevCurveApi: CurveApi | undefined,
wallet: Wallet | undefined,
): Promise<void>

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

Expand Down Expand Up @@ -63,7 +69,7 @@ const createGlobalSlice = (set: StoreApi<State>['setState'], get: StoreApi<State
}),
)
},
hydrate: async (curveApi, prevCurveApi) => {
hydrate: async (config, curveApi, prevCurveApi) => {
if (!curveApi) return

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

await state.pools.fetchPools(curveApi, poolIds, failedFetching24hOldVprice)
await state.pools.fetchPools(config, curveApi, poolIds, failedFetching24hOldVprice)

if (isUserSwitched || isNetworkSwitched) {
void state.pools.fetchPricesApiPools(chainId)
Expand Down
Loading