diff --git a/src/components/ElasticZap/ZapDetail.tsx b/src/components/ElasticZap/ZapDetail.tsx index af17ee0b78..69c9fe763d 100644 --- a/src/components/ElasticZap/ZapDetail.tsx +++ b/src/components/ElasticZap/ZapDetail.tsx @@ -11,7 +11,7 @@ import Divider from 'components/Divider' import { GasStation } from 'components/Icons' import { FeeTag } from 'components/YieldPools/ElasticFarmGroup/styleds' import { ELASTIC_BASE_FEE_UNIT } from 'constants/index' -import { useActiveWeb3React } from 'hooks' +import { useKyberChainId } from 'hooks' import { ZapResult, useZapInAction } from 'hooks/elasticZap' import useTheme from 'hooks/useTheme' import { useKyberSwapConfig } from 'state/application/hooks' @@ -77,7 +77,7 @@ export const useZapDetail = ({ tickUpper?: number previousTicks?: number[] }): ZapDetail => { - const { chainId } = useActiveWeb3React() + const chainId = useKyberChainId() const { readProvider } = useKyberSwapConfig() const equivalentQuoteAmount = diff --git a/src/components/Header/web3/SelectNetwork.tsx b/src/components/Header/web3/SelectNetwork.tsx index 9a4486f623..995c97e96a 100644 --- a/src/components/Header/web3/SelectNetwork.tsx +++ b/src/components/Header/web3/SelectNetwork.tsx @@ -70,7 +70,7 @@ function SelectNetwork(): JSX.Element | null { const { chainId, networkInfo } = useActiveWeb3React() const networkModalOpen = useModalOpen(ApplicationModal.NETWORK) const toggleNetworkModal = useNetworkModalToggle() - const userEthBalance = useNativeBalance() + const userEthBalance = useNativeBalance(chainId) const labelContent = useMemo(() => { if (!userEthBalance) return networkInfo.name const balanceFixedStr = formatDisplayNumber(userEthBalance, { significantDigits: 6 }) diff --git a/src/hooks/Tokens.ts b/src/hooks/Tokens.ts index eb0b016ecd..9624911ef9 100644 --- a/src/hooks/Tokens.ts +++ b/src/hooks/Tokens.ts @@ -11,7 +11,7 @@ import ERC20_INTERFACE, { ERC20_BYTES32_INTERFACE } from 'constants/abis/erc20' import { KS_SETTING_API } from 'constants/env' import { ETHER_ADDRESS, ZERO_ADDRESS } from 'constants/index' import { NativeCurrencies } from 'constants/tokens' -import { useActiveWeb3React } from 'hooks/index' +import { useActiveWeb3React, useKyberChainId } from 'hooks/index' import { useBytes32TokenContract, useMulticallContract, useTokenReadingContract } from 'hooks/useContract' import { AppState } from 'state' import { TokenAddressMap } from 'state/lists/reducer' @@ -175,8 +175,8 @@ export const useTokens = (addresses: string[]): TokenMap => { // null if loading // otherwise returns the token export function useToken(tokenAddress?: string): Token | NativeCurrency | undefined | null { - const { chainId } = useActiveWeb3React() - const tokens = useAllTokens() + const chainId = useKyberChainId() + const tokens = useAllTokens(true, chainId) const address = isAddress(chainId, tokenAddress) @@ -354,7 +354,7 @@ function useTokenV2( } export function useCurrency(currencyId: string | undefined): Currency | null | undefined { - const { chainId } = useActiveWeb3React() + const chainId = useKyberChainId() const isETH = useMemo( () => chainId && currencyId?.toUpperCase() === NativeCurrencies[chainId].symbol?.toUpperCase(), [chainId, currencyId], diff --git a/src/hooks/elasticZap/index.ts b/src/hooks/elasticZap/index.ts index 65c2deba0e..5e119bb739 100644 --- a/src/hooks/elasticZap/index.ts +++ b/src/hooks/elasticZap/index.ts @@ -41,6 +41,7 @@ export function useZapInPoolResult(params?: { amountIn: CurrencyAmount tickLower: number tickUpper: number + skip?: boolean }): { loading: boolean aggregatorData: RouteSummary | null @@ -67,13 +68,13 @@ export function useZapInPoolResult(params?: { const [aggregatorOutputs, setAggregatorOutputs] = useState>([]) - const { tokenIn, tokenOut, poolAddress } = params || {} + const { tokenIn, tokenOut, poolAddress, skip } = params || {} const getRoutes = useCallback(() => { if (slippage) { // added to refresh rate when slippage change, aggregator dont need this } - if (tokenIn && tokenOut && poolAddress) { + if (tokenIn && tokenOut && poolAddress && !skip) { setAggregatorOutputs([]) if (useAggregatorForZap) { setLoadingAggregator(true) @@ -101,7 +102,7 @@ export function useZapInPoolResult(params?: { }) } } - }, [tokenIn, tokenOut, poolAddress, splitedAmount, getRoute, url, useAggregatorForZap, slippage]) + }, [tokenIn, tokenOut, poolAddress, splitedAmount, getRoute, url, useAggregatorForZap, slippage, skip]) useEffect(() => { getRoutes() diff --git a/src/hooks/index.ts b/src/hooks/index.ts index ea3788fc4d..c3cb41c710 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -5,7 +5,7 @@ import { useWeb3React as useWeb3ReactCore } from '@web3-react/core' import { Connector } from '@web3-react/types' import { useMemo } from 'react' import { useSelector } from 'react-redux' -import { useSearchParams } from 'react-router-dom' +import { useParams, useSearchParams } from 'react-router-dom' import { useCheckBlackjackQuery } from 'services/blackjack' import { blocto, gnosisSafe, krystalWalletConnectV2, walletConnectV2 } from 'constants/connectors/evm' @@ -17,6 +17,7 @@ import { NETWORKS_INFO } from 'hooks/useChainsConfig' import { AppState } from 'state' import { useKyberSwapConfig } from 'state/application/hooks' import { detectInjectedType, isEVMWallet, isSolanaWallet } from 'utils' +import { getChainIdFromSlug } from 'utils/string' export function useActiveWeb3React(): { chainId: ChainId @@ -174,3 +175,16 @@ export const useWeb3Solana = () => { const { connection } = useKyberSwapConfig() return { connection } } + +export const useKyberChainId = () => { + const { network } = useParams() + const { pathname } = location + const params = pathname.split('/') + + const networkFromUrl = params.map(item => getChainIdFromSlug(item)).filter(Boolean) + + const { chainId: walletChainId } = useActiveWeb3React() + const chainId = getChainIdFromSlug(network) || networkFromUrl?.[0] || walletChainId + + return chainId +} diff --git a/src/hooks/useContract.ts b/src/hooks/useContract.ts index 8947cfea8e..0ab5c96b9b 100644 --- a/src/hooks/useContract.ts +++ b/src/hooks/useContract.ts @@ -29,7 +29,7 @@ import ZAP_ABI from 'constants/abis/zap.json' import { MULTICALL_ABI } from 'constants/multicall' import { NETWORKS_INFO, isEVM } from 'constants/networks' import { EVMNetworkInfo } from 'constants/networks/type' -import { useWeb3React } from 'hooks' +import { useKyberChainId, useWeb3React } from 'hooks' import { useKyberSwapConfig } from 'state/application/hooks' import { FairLaunchVersion, RewardLockerVersion } from 'state/farms/classic/types' import { useRewardLockerAddressesWithVersion } from 'state/vesting/hooks' @@ -61,7 +61,8 @@ export function useReadingContract( customChainId?: ChainId, ): Contract | null { const { chainId: curChainId } = useActiveWeb3React() - const chainId = customChainId || curChainId + const kyberChainId = useKyberChainId() + const chainId = customChainId || kyberChainId || curChainId const { readProvider } = useKyberSwapConfig(chainId) return useMemo(() => { @@ -166,8 +167,8 @@ export function usePairContract(pairAddress?: string): Contract | null { } export function useMulticallContract(customChainId?: ChainId): Contract | null { - const { chainId: curChainId } = useActiveWeb3React() - const chainId = customChainId || curChainId + const kyberChainId = useKyberChainId() + const chainId = customChainId || kyberChainId return useReadingContract(isEVM(chainId) ? NETWORKS_INFO[chainId].multicall : undefined, MULTICALL_ABI, chainId) } diff --git a/src/index.tsx b/src/index.tsx index 5339ccd99e..f6db13804a 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -73,7 +73,7 @@ if (window.ethereum) { window.ethereum.autoRefreshOnNetworkChange = false } -function Updaters() { +export function Updaters() { return ( <> diff --git a/src/pages/AddLiquidityV2/components/PoolSelection.tsx b/src/pages/AddLiquidityV2/components/PoolSelection.tsx new file mode 100644 index 0000000000..e925186af2 --- /dev/null +++ b/src/pages/AddLiquidityV2/components/PoolSelection.tsx @@ -0,0 +1,308 @@ +import { ChainId, Currency, Price, Token, WETH } from '@kyberswap/ks-sdk-core' +import { FeeAmount } from '@kyberswap/ks-sdk-elastic' +import { Trans, t } from '@lingui/macro' +import mixpanel from 'mixpanel-browser' +import { useCallback, useState } from 'react' +import { Repeat } from 'react-feather' +import { generatePath, useNavigate, useParams } from 'react-router-dom' +import { useMedia } from 'react-use' +import { Text } from 'rebass' +import styled from 'styled-components' + +import { ReactComponent as DropdownSVG } from 'assets/svg/down.svg' +import { ButtonLight } from 'components/Button' +import CurrencyInputPanel from 'components/CurrencyInputPanel' +import FeeSelector from 'components/FeeSelector' +import NetworkModal from 'components/Header/web3/NetworkModal' +import { Swap as SwapIcon } from 'components/Icons' +import { RowBetween } from 'components/Row' +import { APP_PATHS } from 'constants/index' +import { ELASTIC_NOT_SUPPORTED, MAINNET_NETWORKS } from 'constants/networks' +import { NativeCurrencies } from 'constants/tokens' +import { useKyberChainId } from 'hooks' +import { NETWORKS_INFO } from 'hooks/useChainsConfig' +import useTheme from 'hooks/useTheme' +import { Bound, Field } from 'state/mint/proamm/type' +import { ExternalLink, MEDIA_WIDTHS, StyledInternalLink } from 'theme' +import { currencyId } from 'utils/currencyId' +import { formatDisplayNumber } from 'utils/numbers' + +import { ArrowWrapper, DynamicSection } from '../styled' + +const SelectNetwork = styled.div` + border: 999px; + font-size: 14px; + font-weight: 500; + padding: 6px 12px; + display: flex; + align-items: center; + gap: 8px; + + color: ${({ theme }) => theme.subText}; + background: ${({ theme }) => theme.tabActive}; + border-radius: 999px; + cursor: pointer; +` + +export const PoolSelection = ({ + tokenA, + tokenB, + formattedAmounts, + onFieldAInput, + onFieldBInput, + currencies, + estimatedUsdCurrencyA, + estimatedUsdCurrencyB, + pricesAtTicks, + onLeftRangeInput, + onRightRangeInput, +}: { + tokenA: Token | undefined + tokenB: Token | undefined + formattedAmounts: { + [key: string]: string + } + pricesAtTicks: { + [bound in Bound]?: Price | undefined + } + + onFieldAInput: (val: string) => void + onFieldBInput: (val: string) => void + currencies: { [field in Field]?: Currency } + estimatedUsdCurrencyA: number + estimatedUsdCurrencyB: number + onLeftRangeInput: (typedValue: string) => void + onRightRangeInput: (typedValue: string) => void +}) => { + const chainId = useKyberChainId() + const params = useParams() + const { currencyIdA, currencyIdB, feeAmount: feeAmountFromUrl, network } = params + + // fee selection from url + const feeAmount: FeeAmount = + feeAmountFromUrl && Object.values(FeeAmount).includes(parseFloat(feeAmountFromUrl)) + ? parseFloat(feeAmountFromUrl) + : FeeAmount.MOST_PAIR + + const theme = useTheme() + + const { [Field.CURRENCY_A]: currencies_A, [Field.CURRENCY_B]: currencies_B } = currencies + const { [Bound.LOWER]: priceLower, [Bound.UPPER]: priceUpper } = pricesAtTicks + const isSorted = tokenA && tokenB && tokenA.sortsBefore(tokenB) + const leftPrice = isSorted ? priceLower : priceUpper?.invert() + const rightPrice = isSorted ? priceUpper : priceLower?.invert() + + const upToXL = useMedia(`(max-width: ${MEDIA_WIDTHS.upToXL}px)`) + const upToLarge = useMedia(`(max-width: ${MEDIA_WIDTHS.upToLarge}px)`) + const upToMedium = useMedia(`(max-width: ${MEDIA_WIDTHS.upToMedium}px)`) + const upToXXSmall = useMedia(`(max-width: ${MEDIA_WIDTHS.upToXXSmall}px)`) + const [rotate, setRotate] = useState(false) + + const tightTokenSelect = !upToMedium && upToLarge + + const navigate = useNavigate() + + const handleCurrencySelect = useCallback( + (currencyNew: Currency, currencyIdOther?: string): (string | undefined)[] => { + const currencyIdNew = currencyId(currencyNew, chainId) + + if (currencyIdNew === currencyIdOther) { + // not ideal, but for now clobber the other if the currency ids are equal + return [currencyIdNew, undefined] + } else { + // prevent weth + eth + const isETHOrWETHNew = currencyNew.isNative || (chainId && currencyIdNew === WETH[chainId]?.address) + const isETHOrWETHOther = + !!currencyIdOther && + ((chainId && currencyIdOther === NativeCurrencies[chainId].symbol) || + (chainId && currencyIdOther === WETH[chainId]?.address)) + + if (isETHOrWETHNew && isETHOrWETHOther) { + return [currencyIdNew, undefined] + } else { + return [currencyIdNew, currencyIdOther] + } + } + }, + [chainId], + ) + + const handleCurrencyASelect = useCallback( + (currencyANew: Currency) => { + const [idA, idB] = handleCurrencySelect(currencyANew, currencyIdB) + if (idB === undefined) { + navigate(`/${NETWORKS_INFO[chainId].route}${APP_PATHS.ELASTIC_CREATE_POOL}/${idA}`) + } else { + navigate(`/${NETWORKS_INFO[chainId].route}${APP_PATHS.ELASTIC_CREATE_POOL}/${idA}/${idB}`) + } + }, + [handleCurrencySelect, currencyIdB, navigate, chainId], + ) + + const handleCurrencyBSelect = useCallback( + (currencyBNew: Currency) => { + const [idB, idA] = handleCurrencySelect(currencyBNew, currencyIdA) + if (idA === undefined) { + navigate(`/${NETWORKS_INFO[chainId].route}${APP_PATHS.ELASTIC_CREATE_POOL}/${idB}`) + } else { + navigate(`/${NETWORKS_INFO[chainId].route}${APP_PATHS.ELASTIC_CREATE_POOL}/${idA}/${idB}`) + } + }, + [handleCurrencySelect, currencyIdA, navigate, chainId], + ) + + const handleFeePoolSelect = useCallback( + (newFeeAmount: FeeAmount) => { + onLeftRangeInput('') + onRightRangeInput('') + navigate( + `/${NETWORKS_INFO[chainId].route}${APP_PATHS.ELASTIC_CREATE_POOL}/${currencyIdA}/${currencyIdB}/${newFeeAmount}`, + ) + }, + [currencyIdA, currencyIdB, navigate, chainId, onLeftRangeInput, onRightRangeInput], + ) + + const [isOpenNetworkModal, setIsOpenNetworkModal] = useState(false) + const openNetworkModal = () => { + setIsOpenNetworkModal(true) + } + + const handleSelectNetwork = (chainId: ChainId) => { + const path = generatePath(`/:network${APP_PATHS.ELASTIC_CREATE_POOL}`, { + ...params, + network: NETWORKS_INFO[chainId].route, + } as any) + navigate(path, { replace: true }) + } + + const activeChainIds = MAINNET_NETWORKS.filter(item => !ELASTIC_NOT_SUPPORTED[item]) + + return ( + <> + setIsOpenNetworkModal(prev => !prev)} + disabledMsg={t`Elastic is not supported on this network`} + /> + + + Choose pool + +
+ { + if (tokenA?.symbol && tokenB?.symbol) + mixpanel.track('Elastic - Add Liquidity page - Click Swap', { + token_1: tokenA?.symbol, + token_2: tokenB?.symbol, + }) + }} + > + + + Swap + + +
+
+ + + + Choose a chain + + + + Network + {NETWORKS_INFO[chainId].name} + + + + + + + + { + if (!!rightPrice) { + onLeftRangeInput(rightPrice?.invert().toString()) + } + if (!!leftPrice) { + onRightRangeInput(leftPrice?.invert().toString()) + } + setRotate(prev => !prev) + }} + > + {!currencyIdA && !currencyIdB ? ( + + ) : ( + + + + )} + + + + + + + + Select fee tier + + + + + ) +} diff --git a/src/pages/AddLiquidityV2/components/TransactionConfirmModal.tsx b/src/pages/AddLiquidityV2/components/TransactionConfirmModal.tsx new file mode 100644 index 0000000000..d5676ed426 --- /dev/null +++ b/src/pages/AddLiquidityV2/components/TransactionConfirmModal.tsx @@ -0,0 +1,204 @@ +import { Currency, CurrencyAmount } from '@kyberswap/ks-sdk-core' +import { Position } from '@kyberswap/ks-sdk-elastic' +import { Trans, t } from '@lingui/macro' +import { ReactNode } from 'react' +import { Flex, Text } from 'rebass' + +import { ButtonError } from 'components/Button' +import { ZapDetail } from 'components/ElasticZap/ZapDetail' +import ProAmmPoolInfo from 'components/ProAmm/ProAmmPoolInfo' +import ProAmmPooledTokens from 'components/ProAmm/ProAmmPooledTokens' +import ProAmmPriceRangeConfirm from 'components/ProAmm/ProAmmPriceRangeConfirm' +import Row from 'components/Row' +import TransactionConfirmationModal, { + ConfirmationModalContent, + TransactionErrorContent, +} from 'components/TransactionConfirmationModal' +import { useActiveWeb3React } from 'hooks' +import { Bound } from 'state/mint/proamm/type' +import { getTokenSymbolWithHardcode } from 'utils/tokenInfo' +import { unwrappedToken } from 'utils/wrappedCurrency' + +export const AddLiquidityTransactionConfirmModal = ({ + warnings, + noLiquidity, + showConfirm, + handleDismissConfirmation, + attemptingTxn, + txHash, + isMultiplePosition, + modalContent, + isWarningButton, + onAdd, + pendingText, +}: { + warnings: ReactNode + noLiquidity: boolean + showConfirm: boolean + handleDismissConfirmation: () => void + attemptingTxn: boolean + txHash: string + isMultiplePosition: boolean + modalContent: () => ReactNode + isWarningButton: boolean + onAdd: () => void + pendingText: string +}) => { + return ( + ( + ( + + {warnings} + + + + Supply + + + + + )} + /> + )} + pendingText={pendingText} + /> + ) +} + +export const ZapConfirmTransactionModal = ({ + showZapConfirmation, + handleDismissConfirmation, + txHash, + attemptingTxn, + amountIn, + selectedCurrency, + newPosDraft, + zapError, + handleDissmissZap, + zapDetail, + ticksAtLimit, + warnings, + zapPriceImpactNote, + handleZap, + isWarningButton, + useWrapped, +}: { + showZapConfirmation: boolean + handleDismissConfirmation: () => void + txHash: string + attemptingTxn: boolean + amountIn: CurrencyAmount | undefined + selectedCurrency: Currency | undefined + newPosDraft: Position | undefined + zapError: string + handleDissmissZap: () => void + zapDetail: ZapDetail + ticksAtLimit: { [bound in Bound]?: boolean | undefined } + warnings: ReactNode + zapPriceImpactNote: ReactNode + handleZap: () => void + isWarningButton: boolean + useWrapped: boolean +}) => { + const { chainId } = useActiveWeb3React() + + const symbol0 = getTokenSymbolWithHardcode( + chainId, + newPosDraft?.pool?.token0?.wrapped.address, + useWrapped + ? newPosDraft?.pool?.token0?.wrapped.symbol + : (newPosDraft?.pool?.token0 ? unwrappedToken(newPosDraft.pool.token0) : newPosDraft?.pool?.token0)?.symbol, + ) + const symbol1 = getTokenSymbolWithHardcode( + chainId, + newPosDraft?.pool?.token1?.wrapped.address, + useWrapped + ? newPosDraft?.pool?.token1?.wrapped.symbol + : (newPosDraft?.pool?.token1 ? unwrappedToken(newPosDraft.pool.token1) : newPosDraft?.pool?.token1)?.symbol, + ) + + return ( + + Zapping {amountIn?.toSignificant(6)} {selectedCurrency?.symbol} into {newPosDraft?.amount0.toSignificant(6)}{' '} + {symbol0} and {newPosDraft?.amount1.toSignificant(6)} {symbol1} of liquidity to the pool + + } + content={() => ( + + {zapError ? ( + + ) : ( + ( +
+ {!!zapDetail.newPosDraft && } + + {!!zapDetail.newPosDraft && ( + + )} +
+ )} + showGridListOption={false} + bottomContent={() => ( + + {warnings} + {zapPriceImpactNote} + + + Supply + + + + )} + /> + )} +
+ )} + /> + ) +} diff --git a/src/pages/AddLiquidityV2/index.tsx b/src/pages/AddLiquidityV2/index.tsx index b26eaf62d3..1598b2a057 100644 --- a/src/pages/AddLiquidityV2/index.tsx +++ b/src/pages/AddLiquidityV2/index.tsx @@ -14,7 +14,7 @@ import { BigNumber } from 'ethers' import JSBI from 'jsbi' import mixpanel from 'mixpanel-browser' import { ReactElement, useCallback, useEffect, useMemo, useRef, useState } from 'react' -import { AlertTriangle, Repeat } from 'react-feather' +import { AlertTriangle } from 'react-feather' import { Navigate, useNavigate, useParams, useSearchParams } from 'react-router-dom' import { useMedia } from 'react-use' import { Box, Flex, Text } from 'rebass' @@ -27,9 +27,8 @@ import { AutoColumn } from 'components/Column' import CurrencyInputPanel from 'components/CurrencyInputPanel' import CurrencyLogo from 'components/CurrencyLogo' import { useZapDetail } from 'components/ElasticZap/ZapDetail' -import FeeSelector from 'components/FeeSelector' import HoverInlineText from 'components/HoverInlineText' -import { Swap as SwapIcon, TwoWayArrow } from 'components/Icons' +import { TwoWayArrow } from 'components/Icons' import LiquidityChartRangeInput from 'components/LiquidityChartRangeInput' import { AddRemoveTabs, LiquidityAction } from 'components/NavigationTabs' import ListPositions from 'components/ProAmm/ListPositions' @@ -47,14 +46,10 @@ import { SLIPPAGE_EXPLANATION_URL } from 'components/SlippageWarningNote' import PriceImpactNote, { ZapHighPriceImpact } from 'components/SwapForm/PriceImpactNote' import useParsedAmount from 'components/SwapForm/hooks/useParsedAmount' import Tooltip, { MouseoverTooltip } from 'components/Tooltip' -import TransactionConfirmationModal, { - ConfirmationModalContent, - TransactionErrorContent, -} from 'components/TransactionConfirmationModal' import { TutorialType } from 'components/Tutorial' import { Dots } from 'components/swapv2/styleds' import { APP_PATHS, ETHER_ADDRESS } from 'constants/index' -import { ELASTIC_NOT_SUPPORTED } from 'constants/networks' +import { NETWORKS_INFO } from 'constants/networks' import { EVMNetworkInfo } from 'constants/networks/type' import { NativeCurrencies } from 'constants/tokens' import { useActiveWeb3React, useWeb3React } from 'hooks' @@ -69,9 +64,10 @@ import useProAmmPoolInfo from 'hooks/useProAmmPoolInfo' import useProAmmPreviousTicks, { useProAmmMultiplePreviousTicks } from 'hooks/useProAmmPreviousTicks' import useTheme from 'hooks/useTheme' import useTransactionDeadline from 'hooks/useTransactionDeadline' +import { useChangeNetwork } from 'hooks/web3/useChangeNetwork' import { convertTickToPrice } from 'pages/Farm/ElasticFarmv2/utils' import { ApplicationModal } from 'state/application/actions' -import { useNotify, useOpenModal, useOpenNetworkModal, useWalletModalToggle } from 'state/application/hooks' +import { useNotify, useOpenModal, useWalletModalToggle } from 'state/application/hooks' import { FarmUpdater } from 'state/farms/elastic/hooks' import { useElasticFarmsV2 } from 'state/farms/elasticv2/hooks' import ElasticFarmV2Updater from 'state/farms/elasticv2/updater' @@ -92,21 +88,21 @@ import { useTransactionAdder } from 'state/transactions/hooks' import { TRANSACTION_TYPE } from 'state/transactions/type' import { useDegenModeManager, useUserSlippageTolerance } from 'state/user/hooks' import { useCurrencyBalances } from 'state/wallet/hooks' -import { ExternalLink, MEDIA_WIDTHS, StyledInternalLink, TYPE } from 'theme' +import { ExternalLink, MEDIA_WIDTHS, TYPE } from 'theme' import { basisPointsToPercent, calculateGasMargin, formattedNum } from 'utils' -import { currencyId } from 'utils/currencyId' import { friendlyError } from 'utils/errorMessage' import { maxAmountSpend } from 'utils/maxAmountSpend' import { formatDisplayNumber, toString } from 'utils/numbers' import { SLIPPAGE_STATUS, checkRangeSlippage, formatSlippage } from 'utils/slippage' -import { getTokenSymbolWithHardcode } from 'utils/tokenInfo' +import { getChainIdFromSlug } from 'utils/string' import { unwrappedToken } from 'utils/wrappedCurrency' import DisclaimerERC20 from './components/DisclaimerERC20' import NewPoolNote from './components/NewPoolNote' +import { PoolSelection } from './components/PoolSelection' +import { AddLiquidityTransactionConfirmModal, ZapConfirmTransactionModal } from './components/TransactionConfirmModal' import { RANGE_LIST, rangeData } from './constants' import { - ArrowWrapper, ChartBody, ChartWrapper, Container, @@ -138,14 +134,15 @@ const TextUnderlineTransparent = styled(Text)` ` export default function AddLiquidity() { - const { currencyIdA, currencyIdB, feeAmount: feeAmountFromUrl } = useParams() + const { currencyIdA, currencyIdB, feeAmount: feeAmountFromUrl, network } = useParams() const navigate = useNavigate() - const [rotate, setRotate] = useState(false) - const { account, chainId, isEVM, networkInfo } = useActiveWeb3React() + const { account, chainId: currentWalletChainId, isEVM } = useActiveWeb3React() + const chainId = getChainIdFromSlug(network) || currentWalletChainId + const { library } = useWeb3React() const theme = useTheme() - const openNetworkModal = useOpenNetworkModal() const toggleWalletModal = useWalletModalToggle() // toggle wallet when disconnected + const { changeNetwork } = useChangeNetwork() const [isDegenMode] = useDegenModeManager() const addTransactionWithType = useTransactionAdder() const positionManager = useProAmmNFTPositionManagerReadingContract() @@ -254,7 +251,7 @@ export default function AddLiquidity() { const defaultFId = Number(searchParams.get('fId') || '0') const range = activeRanges.find(i => i.index === activeRangeIndex && i.farm.fId === defaultFId) - const isZapAvailable = !!(networkInfo as EVMNetworkInfo).elastic.zap + const isZapAvailable = !!(NETWORKS_INFO[chainId] as EVMNetworkInfo).elastic.zap const [method, setMethod] = useState<'pair' | 'zap'>(() => (isZapAvailable ? 'zap' : 'pair')) useEffect(() => { @@ -389,7 +386,7 @@ export default function AddLiquidity() { : isMultiplePosition ? currencyAmountSum[Field.CURRENCY_A] : parsedAmounts_A, - isEVM ? (networkInfo as EVMNetworkInfo).elastic.nonfungiblePositionManager : undefined, + isEVM ? (NETWORKS_INFO[chainId] as EVMNetworkInfo).elastic.nonfungiblePositionManager : undefined, ) const [approvalB, approveBCallback] = useApproveCallback( @@ -398,7 +395,7 @@ export default function AddLiquidity() { : isMultiplePosition ? currencyAmountSum[Field.CURRENCY_B] : parsedAmounts_B, - isEVM ? (networkInfo as EVMNetworkInfo).elastic.nonfungiblePositionManager : undefined, + isEVM ? (NETWORKS_INFO[chainId] as EVMNetworkInfo).elastic.nonfungiblePositionManager : undefined, ) const tokens = useMemo( @@ -410,7 +407,10 @@ export default function AddLiquidity() { loading, fetchPrices, refetch, - } = useTokenPricesWithLoading(tokens.map(t => t?.wrapped.address || '')) + } = useTokenPricesWithLoading( + tokens.map(t => t?.wrapped.address || ''), + chainId, + ) const marketPrice = usdPrices[quoteCurrency?.wrapped.address || ''] && usdPrices[baseCurrency?.wrapped.address || ''] && @@ -444,7 +444,7 @@ export default function AddLiquidity() { const previousTicksParam = isMultiplePosition ? mutiplePreviousTicks : previousTicks - const { data: poolDatas } = useGetElasticPools([poolAddress]) + const { data: poolDatas } = useGetElasticPools([poolAddress], chainId) const onAdd = useCallback( async function () { @@ -470,7 +470,7 @@ export default function AddLiquidity() { //0.00283161 const txn: { to: string; data: string; value: string } = { - to: (networkInfo as EVMNetworkInfo).elastic.nonfungiblePositionManager, + to: (NETWORKS_INFO[chainId] as EVMNetworkInfo).elastic.nonfungiblePositionManager, data: calldata, value, } @@ -491,7 +491,7 @@ export default function AddLiquidity() { .sendTransaction(newTxn) .then((response: TransactionResponse) => { onResetMintState() - navigate(`${APP_PATHS.MY_POOLS}/${networkInfo.route}?tab=elastic`) + navigate(`${APP_PATHS.MY_POOLS}/${NETWORKS_INFO[chainId].route}?tab=elastic`) setAttemptingTxn(false) if (noLiquidity) { @@ -555,6 +555,7 @@ export default function AddLiquidity() { [ isEVM, library, + chainId, account, positionManager, baseCurrency, @@ -564,7 +565,6 @@ export default function AddLiquidity() { previousTicksParam, userSlippageTolerance, noLiquidity, - networkInfo, onResetMintState, navigate, parsedAmounts_A, @@ -577,64 +577,6 @@ export default function AddLiquidity() { ], ) - const handleCurrencySelect = useCallback( - (currencyNew: Currency, currencyIdOther?: string): (string | undefined)[] => { - const currencyIdNew = currencyId(currencyNew, chainId) - - if (currencyIdNew === currencyIdOther) { - // not ideal, but for now clobber the other if the currency ids are equal - return [currencyIdNew, undefined] - } else { - // prevent weth + eth - const isETHOrWETHNew = currencyNew.isNative || (chainId && currencyIdNew === WETH[chainId]?.address) - const isETHOrWETHOther = - !!currencyIdOther && - ((chainId && currencyIdOther === NativeCurrencies[chainId].symbol) || - (chainId && currencyIdOther === WETH[chainId]?.address)) - - if (isETHOrWETHNew && isETHOrWETHOther) { - return [currencyIdNew, undefined] - } else { - return [currencyIdNew, currencyIdOther] - } - } - }, - [chainId], - ) - - const handleCurrencyASelect = useCallback( - (currencyANew: Currency) => { - const [idA, idB] = handleCurrencySelect(currencyANew, currencyIdB) - if (idB === undefined) { - navigate(`/${networkInfo.route}${APP_PATHS.ELASTIC_CREATE_POOL}/${idA}`) - } else { - navigate(`/${networkInfo.route}${APP_PATHS.ELASTIC_CREATE_POOL}/${idA}/${idB}`) - } - }, - [handleCurrencySelect, currencyIdB, navigate, networkInfo.route], - ) - - const handleCurrencyBSelect = useCallback( - (currencyBNew: Currency) => { - const [idB, idA] = handleCurrencySelect(currencyBNew, currencyIdA) - if (idA === undefined) { - navigate(`/${networkInfo.route}${APP_PATHS.ELASTIC_CREATE_POOL}/${idB}`) - } else { - navigate(`/${networkInfo.route}${APP_PATHS.ELASTIC_CREATE_POOL}/${idA}/${idB}`) - } - }, - [handleCurrencySelect, currencyIdA, navigate, networkInfo.route], - ) - - const handleFeePoolSelect = useCallback( - (newFeeAmount: FeeAmount) => { - onLeftRangeInput('') - onRightRangeInput('') - navigate(`/${networkInfo.route}${APP_PATHS.ELASTIC_CREATE_POOL}/${currencyIdA}/${currencyIdB}/${newFeeAmount}`) - }, - [currencyIdA, currencyIdB, navigate, networkInfo.route, onLeftRangeInput, onRightRangeInput], - ) - const handleDismissConfirmation = useCallback(() => { if (method === 'zap') setShowZapConfirmation(false) else setShowConfirm(false) @@ -643,10 +585,10 @@ export default function AddLiquidity() { if (txHash) { onFieldAInput('') // dont jump to pool page if creating - navigate(`${APP_PATHS.MY_POOLS}/${networkInfo.route}?tab=elastic`) + navigate(`${APP_PATHS.MY_POOLS}/${NETWORKS_INFO[chainId].route}?tab=elastic`) } setTxHash('') - }, [navigate, networkInfo.route, onFieldAInput, txHash, method]) + }, [navigate, onFieldAInput, txHash, method, chainId]) const handleDismissConfirmationRef = useRef(handleDismissConfirmation) @@ -728,10 +670,7 @@ export default function AddLiquidity() { positions.length, ]) - const upToXL = useMedia(`(max-width: ${MEDIA_WIDTHS.upToXL}px)`) - const upToLarge = useMedia(`(max-width: ${MEDIA_WIDTHS.upToLarge}px)`) const upToMedium = useMedia(`(max-width: ${MEDIA_WIDTHS.upToMedium}px)`) - const upToXXSmall = useMedia(`(max-width: ${MEDIA_WIDTHS.upToXXSmall}px)`) const priceDiff = baseCurrency && quoteCurrency && tokenA && tokenB && price @@ -762,6 +701,14 @@ export default function AddLiquidity() { Connect + ) : currentWalletChainId !== chainId ? ( + changeNetwork(chainId)} + > + Switch to {NETWORKS_INFO[chainId].name} + ) : ( ) - const disableFeeSelect = !currencyIdA || !currencyIdB const disableRangeSelect = !feeAmount || invalidPool || (noLiquidity && !startPriceTypedValue) const hasTab = !noLiquidity && !disableRangeSelect const disableAmountSelect = disableRangeSelect || tickLower === undefined || tickUpper === undefined || invalidRange @@ -1021,7 +967,7 @@ export default function AddLiquidity() { : currencyIdB return ( chainId && - navigate(`/${networkInfo.route}${APP_PATHS.ELASTIC_CREATE_POOL}/${param1}/${param2}/${feeAmount}`, { + navigate(`/${NETWORKS_INFO[chainId].route}${APP_PATHS.ELASTIC_CREATE_POOL}/${param1}/${param2}/${feeAmount}`, { replace: true, }) ) @@ -1075,12 +1021,13 @@ export default function AddLiquidity() { amountIn, tickLower, tickUpper, + skip: method !== 'zap', } : undefined - }, [amountIn, poolAddress, selectedCurrency, quoteZapCurrency, tickLower, tickUpper]) + }, [amountIn, poolAddress, selectedCurrency, quoteZapCurrency, tickLower, tickUpper, method]) const { loading: zapLoading, result: zapResult, aggregatorData } = useZapInPoolResult(params) - const zapInContractAddress = (networkInfo as EVMNetworkInfo).elastic.zap?.router + const zapInContractAddress = (NETWORKS_INFO[chainId] as EVMNetworkInfo).elastic.zap?.router const [zapApprovalState, zapApprove] = useApproveCallback(amountIn, zapInContractAddress) const { zapIn } = useZapInAction() const [showZapConfirmation, setShowZapConfirmation] = useState(false) @@ -1677,7 +1624,9 @@ export default function AddLiquidity() { {tokenA && tokenB && } {zapPriceImpactNote} - {method === 'pair' || !account ? : ZapButton} + + {method === 'pair' || !account || currentWalletChainId !== chainId ? : ZapButton} + ) @@ -1738,8 +1687,6 @@ export default function AddLiquidity() { [account, userLiquidityPositionsQueryResult], ) - const tightTokenSelect = !upToMedium && upToLarge - const onFarmRangeSelected = useCallback( (tickLower: number, tickUpper: number) => { const tickSpacing = TICK_SPACINGS[feeAmount] @@ -1792,51 +1739,19 @@ export default function AddLiquidity() { }, [isFarmV2Available, range?.tickUpper, range?.tickLower, onFarmRangeSelected, positionsState, pIndex]) if (!isEVM) return - const symbol0 = getTokenSymbolWithHardcode( - chainId, - pool?.token0?.wrapped.address, - useWrapped ? pool?.token0?.wrapped.symbol : (pool?.token0 ? unwrappedToken(pool.token0) : pool?.token0)?.symbol, - ) - const symbol1 = getTokenSymbolWithHardcode( - chainId, - pool?.token1?.wrapped.address, - useWrapped ? pool?.token1?.wrapped.symbol : (pool?.token1 ? unwrappedToken(pool.token1) : pool?.token1)?.symbol, - ) - return ( <> - ( - ( - - {warnings} - - - - Supply - - - - - )} - /> - )} + txHash={txHash} + isMultiplePosition={isMultiplePosition} + modalContent={modalContent} + isWarningButton={isWarningButton} + onAdd={onAdd} pendingText={pendingText} /> @@ -1848,303 +1763,148 @@ export default function AddLiquidity() { onCleared={() => { onFieldAInput('0') onFieldBInput('0') - navigate(`/${networkInfo.route}${APP_PATHS.ELASTIC_CREATE_POOL}`) + navigate(`/${NETWORKS_INFO[chainId].route}${APP_PATHS.ELASTIC_CREATE_POOL}`) }} tutorialType={TutorialType.ELASTIC_ADD_LIQUIDITY} /> - {ELASTIC_NOT_SUPPORTED[chainId] ? ( - - {ELASTIC_NOT_SUPPORTED[chainId]} - - Change network - - - ) : ( - <> - - - - - Choose pool - -
- { + + + + + {noLiquidity ? ( + + + + + Set Starting Price + + + + + + To initialize this pool, select a starting price for the pool then enter your liquidity price + range. + + + + + + + + + + + + Starting Price + + + {price ? ( + + + + + + ) : ( + '-' + )} + + + fetchPrices(tokens.map(t => t?.wrapped.address || ''))} + marketPrice={marketPrice} + baseCurrency={baseCurrency} + quoteCurrency={quoteCurrency} + /> + + + ) : ( + poolStat && ( + <> + + + Pool Stats + + { if (tokenA?.symbol && tokenB?.symbol) - mixpanelHandler(MIXPANEL_TYPE.ELASTIC_ADD_LIQUIDITY_CLICK_SWAP, { + mixpanelHandler(MIXPANEL_TYPE.ELASTIC_ADD_LIQUIDITY_CLICK_POOL_ANALYTIC, { token_1: tokenA?.symbol, token_2: tokenB?.symbol, }) }} - > - - - Swap - - -
-
- - - - { - if (!!rightPrice) { - onLeftRangeInput(rightPrice?.invert().toString()) - } - if (!!leftPrice) { - onRightRangeInput(leftPrice?.invert().toString()) - } - setRotate(prev => !prev) - }} - > - {!currencyIdA && !currencyIdB ? ( - - ) : ( - - - - )} - - - - - - - Select fee tier - - +
+ - - - {noLiquidity ? ( - - - - - Set Starting Price - - - - - - To initialize this pool, select a starting price for the pool then enter your liquidity - price range. - - - - - - - - - - - - Starting Price - - - {price ? ( - - - - - - ) : ( - '-' - )} - - - fetchPrices(tokens.map(t => t?.wrapped.address || ''))} - marketPrice={marketPrice} - baseCurrency={baseCurrency} - quoteCurrency={quoteCurrency} - /> - - - ) : ( - poolStat && ( - <> - - - Pool Stats - - { - if (tokenA?.symbol && tokenB?.symbol) - mixpanelHandler(MIXPANEL_TYPE.ELASTIC_ADD_LIQUIDITY_CLICK_POOL_ANALYTIC, { - token_1: tokenA?.symbol, - token_2: tokenB?.symbol, - }) - }} - /> - - - - ) - )} - {upToMedium && chart} - - {!upToMedium && {chart}} -
- - )} + + ) + )} + {upToMedium && chart} + + {!upToMedium && {chart}} + - - Zapping {amountIn?.toSignificant(6)} {selectedCurrency?.symbol} into {newPosDraft?.amount0.toSignificant(6)}{' '} - {symbol0} and {newPosDraft?.amount1.toSignificant(6)} {symbol1} of liquidity to the pool - - } - content={() => ( - - {zapError ? ( - - ) : ( - ( -
- {!!zapDetail.newPosDraft && } - - {!!zapDetail.newPosDraft && ( - - )} -
- )} - showGridListOption={false} - bottomContent={() => ( - - {warnings} - {zapPriceImpactNote} - - - Supply - - - - )} - /> - )} -
- )} + amountIn={amountIn} + selectedCurrency={selectedCurrency} + newPosDraft={newPosDraft} + zapError={zapError} + handleDissmissZap={handleDissmissZap} + zapDetail={zapDetail} + ticksAtLimit={ticksAtLimit} + warnings={warnings} + zapPriceImpactNote={zapPriceImpactNote} + handleZap={handleZap} + isWarningButton={isWarningButton} + useWrapped={useWrapped} /> ) diff --git a/src/pages/App.tsx b/src/pages/App.tsx index 97979c73cb..07298b6078 100644 --- a/src/pages/App.tsx +++ b/src/pages/App.tsx @@ -153,6 +153,7 @@ const RoutesWithNetworkPrefix = () => { const { networkInfo, chainId } = useActiveWeb3React() const location = useLocation() + console.log('viet-nv', location.pathname) useSyncNetworkParamWithStore() if (!network) { @@ -189,10 +190,6 @@ const RoutesWithNetworkPrefix = () => { {!ELASTIC_NOT_SUPPORTED[chainId] && ( <> - } - /> } @@ -306,6 +303,11 @@ export default function App() { <> + } + /> + {/* These are old routes and will soon be deprecated - Check: RoutesWithNetworkParam */} } /> } /> diff --git a/src/state/application/hooks.ts b/src/state/application/hooks.ts index a90645719e..72f864d2b5 100644 --- a/src/state/application/hooks.ts +++ b/src/state/application/hooks.ts @@ -22,7 +22,7 @@ import ethereumInfo from 'constants/networks/ethereum' import { AppJsonRpcProvider } from 'constants/providers' import { KNC_ADDRESS } from 'constants/tokens' import { VERSION } from 'constants/v2' -import { useActiveWeb3React } from 'hooks/index' +import { useActiveWeb3React, useKyberChainId } from 'hooks/index' import { useAppSelector } from 'state/hooks' import { AppDispatch, AppState } from 'state/index' import { useTokenPricesWithLoading } from 'state/tokenPrices/hooks' @@ -42,8 +42,7 @@ import { import { ModalParams } from './types' export function useBlockNumber(): number | undefined { - const { chainId } = useActiveWeb3React() - + const chainId = useKyberChainId() return useSelector((state: AppState) => state.application.blockNumber[chainId]) } @@ -446,7 +445,8 @@ function getDefaultConfig(chainId: ChainId): KyberSwapConfigResponse { export const useKyberSwapConfig = (customChainId?: ChainId): KyberSwapConfig => { const storeChainId = useAppSelector(state => state.user.chainId) || ChainId.MAINNET - const chainId = customChainId || storeChainId + const urlChainId = useKyberChainId() + const chainId = customChainId || urlChainId || storeChainId const config = useAppSelector(state => state.application.config[chainId] || getDefaultConfig(chainId)) diff --git a/src/state/application/updater.ts b/src/state/application/updater.ts index d90d23ef20..466ecceca1 100644 --- a/src/state/application/updater.ts +++ b/src/state/application/updater.ts @@ -2,7 +2,7 @@ import { useCallback, useEffect, useState } from 'react' import { useDispatch } from 'react-redux' import { useGetKyberswapConfigurationQuery } from 'services/ksSetting' -import { useActiveWeb3React, useWeb3Solana } from 'hooks' +import { useActiveWeb3React, useKyberChainId, useWeb3Solana } from 'hooks' import useDebounce from 'hooks/useDebounce' import useIsWindowVisible from 'hooks/useIsWindowVisible' import { useKyberSwapConfig } from 'state/application/hooks' @@ -10,9 +10,10 @@ import { useKyberSwapConfig } from 'state/application/hooks' import { updateBlockNumber } from './actions' export default function Updater(): null { - const { chainId, isEVM, isSolana } = useActiveWeb3React() + const { isEVM, isSolana } = useActiveWeb3React() + const chainId = useKyberChainId() - const { readProvider } = useKyberSwapConfig() + const { readProvider } = useKyberSwapConfig(chainId) const dispatch = useDispatch() const { connection } = useWeb3Solana() diff --git a/src/state/multicall/hooks.ts b/src/state/multicall/hooks.ts index 8460ae845b..29d4188c37 100644 --- a/src/state/multicall/hooks.ts +++ b/src/state/multicall/hooks.ts @@ -6,7 +6,7 @@ import { useEffect, useMemo, useRef } from 'react' import { useDispatch, useSelector } from 'react-redux' import { EMPTY_ARRAY } from 'constants/index' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useKyberChainId } from 'hooks' import { AppDispatch, AppState } from 'state/index' import { @@ -52,8 +52,14 @@ export const NEVER_RELOAD: ListenerOptions = { } // the lowest level call for subscribing to contract data -export function useCallsData(calls: (Call | undefined)[], options?: ListenerOptions): CallResult[] { - const { chainId, isEVM } = useActiveWeb3React() +export function useCallsData( + calls: (Call | undefined)[], + options?: ListenerOptions, + customChainId?: ChainId, +): CallResult[] { + const urlChainId = useKyberChainId() + const chainId = customChainId || urlChainId + const { isEVM } = useActiveWeb3React() const callResults = useSelector( state => state.multicall.callResults?.[chainId], ) @@ -263,6 +269,7 @@ export function useSingleCallResult( methodName: string, inputs?: OptionalMethodInputs, options?: ListenerOptions, + customChainId?: ChainId, ): CallState { const { isEVM } = useActiveWeb3React() const fragment = useMemo( @@ -282,7 +289,7 @@ export function useSingleCallResult( : EMPTY_ARRAY }, [isEVM, contract, fragment, inputs, gasRequired]) - const { valid, data, blockNumber } = useCallsData(calls, options)[0] || {} + const { valid, data, blockNumber } = useCallsData(calls, options, customChainId)[0] || {} return useMemo(() => { return toCallState({ valid, data, blockNumber }, contract?.interface, fragment) diff --git a/src/state/multicall/updater.tsx b/src/state/multicall/updater.tsx index d94c25aed7..9ee9165022 100644 --- a/src/state/multicall/updater.tsx +++ b/src/state/multicall/updater.tsx @@ -3,7 +3,7 @@ import { ChainId } from '@kyberswap/ks-sdk-core' import { useEffect, useMemo, useRef } from 'react' import { useDispatch, useSelector } from 'react-redux' -import { useActiveWeb3React } from 'hooks' +import { useKyberChainId } from 'hooks' import { useMulticallContract } from 'hooks/useContract' import useDebounce from 'hooks/useDebounce' import { useBlockNumber } from 'state/application/hooks' @@ -152,7 +152,7 @@ export default function Updater(): null { // wait for listeners to settle before triggering updates const debouncedListeners = useDebounce(state.callListeners, 100) const latestBlockNumber = useBlockNumber() - const { chainId } = useActiveWeb3React() + const chainId = useKyberChainId() const multicallContract = useMulticallContract() const cancellations = useRef<{ blockNumber: number; cancellations: (() => void)[] }>() diff --git a/src/state/prommPools/useGetElasticPools/index.ts b/src/state/prommPools/useGetElasticPools/index.ts index fb5330d94b..84e467d9c7 100644 --- a/src/state/prommPools/useGetElasticPools/index.ts +++ b/src/state/prommPools/useGetElasticPools/index.ts @@ -1,11 +1,13 @@ +import { ChainId } from '@kyberswap/ks-sdk-core' + import { useKyberSwapConfig } from 'state/application/hooks' import { CommonReturn } from './type' import useGetElasticPoolsV1 from './useGetElasticPoolsV1' import useGetElasticPoolsV2 from './useGetElasticPoolsV2' -const useGetElasticPools = (poolAddresses: string[]): CommonReturn => { - const { isEnableKNProtocol } = useKyberSwapConfig() +const useGetElasticPools = (poolAddresses: string[], customChainId?: ChainId): CommonReturn => { + const { isEnableKNProtocol } = useKyberSwapConfig(customChainId) const responseV1 = useGetElasticPoolsV1(poolAddresses) const responseV2 = useGetElasticPoolsV2() diff --git a/src/state/tokenPrices/hooks.ts b/src/state/tokenPrices/hooks.ts index cd0a59ce8d..50459e186d 100644 --- a/src/state/tokenPrices/hooks.ts +++ b/src/state/tokenPrices/hooks.ts @@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react' import { PRICE_API } from 'constants/env' import { NETWORKS_INFO, isEVM as isEVMChain } from 'constants/networks' -import { useActiveWeb3React } from 'hooks' +import { useKyberChainId } from 'hooks' import { useKyberswapGlobalConfig } from 'hooks/useKyberSwapConfig' import { useAppDispatch, useAppSelector } from 'state/hooks' import { isAddressString } from 'utils' @@ -25,7 +25,7 @@ export const useTokenPricesWithLoading = ( } => { const tokenPrices = useAppSelector(state => state.tokenPrices) const dispatch = useAppDispatch() - const { chainId: currentChain } = useActiveWeb3React() + const currentChain = useKyberChainId() const chainId = customChain || currentChain const isEVM = isEVMChain(chainId) diff --git a/src/state/wallet/hooks.ts b/src/state/wallet/hooks.ts index 4e34e0e433..9483216d9a 100644 --- a/src/state/wallet/hooks.ts +++ b/src/state/wallet/hooks.ts @@ -6,7 +6,7 @@ import ERC20_INTERFACE from 'constants/abis/erc20' import { EMPTY_ARRAY, EMPTY_OBJECT } from 'constants/index' import { isEVM as isEVMChain } from 'constants/networks' import { NativeCurrencies } from 'constants/tokens' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useKyberChainId } from 'hooks' import { useAllTokens } from 'hooks/Tokens' import { useEthBalanceOfAnotherChain, useTokensBalanceOfAnotherChain } from 'hooks/bridge' import { useMulticallContract } from 'hooks/useContract' @@ -16,25 +16,24 @@ import { useTokenPrices } from 'state/tokenPrices/hooks' import { isAddress } from 'utils' import { isTokenNative } from 'utils/tokenInfo' -import { useSOLBalance, useTokensBalanceSolana } from './solanaHooks' +import { useTokensBalanceSolana } from './solanaHooks' export function useNativeBalance(customChain?: ChainId): CurrencyAmount | undefined { const { chainId: currentChain } = useActiveWeb3React() const chainId = customChain || currentChain - const isEVM = isEVMChain(chainId) const isFetchOtherChain = chainId !== currentChain const userEthBalanceAnotherChain = useEthBalanceOfAnotherChain(isFetchOtherChain ? chainId : undefined) const userEthBalance = useETHBalance() - const userSolBalance = useSOLBalance() + // const userSolBalance = useSOLBalance() const evmBalance = isFetchOtherChain ? userEthBalanceAnotherChain : userEthBalance - return isEVM ? evmBalance : userSolBalance + return evmBalance } function useETHBalance(): CurrencyAmount | undefined { const { chainId, account } = useActiveWeb3React() - const multicallContract = useMulticallContract() + const multicallContract = useMulticallContract(chainId) const addressParam: (string | undefined)[] = useMemo( () => (account && isAddress(chainId, account) ? [account] || [undefined] : [undefined]), @@ -163,7 +162,8 @@ export function useCurrencyBalances( currencies?: (Currency | undefined)[], customChain?: ChainId, ): CurrencyAmount[] { - const { account, chainId: currentChain } = useActiveWeb3React() + const { account } = useActiveWeb3React() + const currentChain = useKyberChainId() const chainId = customChain || currentChain const tokens: Token[] = useMemo(() => {