diff --git a/src/components/AddToMetamask/index.tsx b/src/components/AddToMetamask/index.tsx index 9dc039d60a..e3c9462afe 100644 --- a/src/components/AddToMetamask/index.tsx +++ b/src/components/AddToMetamask/index.tsx @@ -1,10 +1,10 @@ import { Token } from '@kyberswap/ks-sdk-core' +import { getConnection } from 'connection' import styled from 'styled-components' import { ButtonEmpty } from 'components/Button' import { RowFixed } from 'components/Row' -import { SUPPORTED_WALLETS } from 'constants/wallets' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useWeb3React } from 'hooks' import { getTokenLogoURL } from 'utils' const StyledLogo = styled.img` @@ -14,6 +14,8 @@ const StyledLogo = styled.img` export default function AddTokenToMetaMask({ token }: { token: Token }) { const { chainId, walletKey } = useActiveWeb3React() + const { connector } = useWeb3React() + const connection = getConnection(connector) async function addToMetaMask() { const tokenAddress = token.address @@ -44,7 +46,7 @@ export default function AddTokenToMetaMask({ token }: { token: Token }) { return ( - + ) diff --git a/src/components/Header/web3/NetworkModal/components/DraggableNetworkButton.tsx b/src/components/Header/web3/NetworkModal/components/DraggableNetworkButton.tsx index c0843dd2ba..157bf33c0b 100644 --- a/src/components/Header/web3/NetworkModal/components/DraggableNetworkButton.tsx +++ b/src/components/Header/web3/NetworkModal/components/DraggableNetworkButton.tsx @@ -1,5 +1,6 @@ import { ChainId } from '@kyberswap/ks-sdk-core' import { Trans, t } from '@lingui/macro' +import { getConnection } from 'connection' import { motion, useAnimationControls, useDragControls } from 'framer-motion' import { rgba } from 'polished' import { stringify } from 'querystring' @@ -14,8 +15,7 @@ import Row from 'components/Row' import { MouseoverTooltip } from 'components/Tooltip' import { NetworkInfo } from 'constants/networks/type' import { Z_INDEXS } from 'constants/styles' -import { SUPPORTED_WALLETS } from 'constants/wallets' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useWeb3React } from 'hooks' import { ChainState } from 'hooks/useChainsConfig' import useParsedQueryString from 'hooks/useParsedQueryString' import useTheme from 'hooks/useTheme' @@ -135,6 +135,8 @@ const DraggableNetworkButton = ({ const theme = useTheme() const { isWrongNetwork, wallet } = useActiveWeb3React() const { changeNetwork } = useChangeNetwork() + const { connector } = useWeb3React() + const connection = getConnection(connector) const [dragging, setDragging] = useState(false) const ref = useRef(null) const dragControls = useDragControls() @@ -290,7 +292,7 @@ const DraggableNetworkButton = ({ {selected && !walletKey && } {walletKey && ( - {SUPPORTED_WALLETS[walletKey].name + )} diff --git a/src/components/Header/web3/SelectWallet.tsx b/src/components/Header/web3/SelectWallet.tsx index 38c32eba78..1cbd84e0e4 100644 --- a/src/components/Header/web3/SelectWallet.tsx +++ b/src/components/Header/web3/SelectWallet.tsx @@ -14,7 +14,6 @@ import Loader from 'components/Loader' import { RowBetween } from 'components/Row' import { MouseoverTooltip } from 'components/Tooltip' import { TutorialIds } from 'components/Tutorial/TutorialSwap/constant' -import { SUPPORTED_WALLETS } from 'constants/wallets' import { useActiveWeb3React, useWeb3React } from 'hooks' import useENSName from 'hooks/useENSName' import useLogin from 'hooks/useLogin' @@ -197,7 +196,7 @@ function Web3StatusInner() { ) : ( walletKey && ( - {SUPPORTED_WALLETS[walletKey].name + ) )} diff --git a/src/components/Header/web3/WalletModal/Option.tsx b/src/components/Header/web3/WalletModal/Option.tsx index 1570199537..47b25aba65 100644 --- a/src/components/Header/web3/WalletModal/Option.tsx +++ b/src/components/Header/web3/WalletModal/Option.tsx @@ -5,7 +5,6 @@ import React from 'react' import styled, { css } from 'styled-components' // import { MouseoverTooltip } from 'components/Tooltip' -// import { SUPPORTED_WALLET, SUPPORTED_WALLETS, WalletReadyState } from 'constants/wallets' import { useWeb3React } from 'hooks' import { useCloseModal } from 'state/application/hooks' import { ApplicationModal } from 'state/application/types' diff --git a/src/components/TransactionConfirmationModal/index.tsx b/src/components/TransactionConfirmationModal/index.tsx index 9b4caf8374..db1932c361 100644 --- a/src/components/TransactionConfirmationModal/index.tsx +++ b/src/components/TransactionConfirmationModal/index.tsx @@ -1,5 +1,7 @@ import { ChainId, Currency, Token } from '@kyberswap/ks-sdk-core' import { Trans } from '@lingui/macro' +import { getConnection } from 'connection' +import { ConnectionType } from 'connection/types' import React, { useState } from 'react' import { ArrowUpCircle, BarChart2 } from 'react-feather' import { Flex, Text } from 'rebass' @@ -13,8 +15,7 @@ import Loader from 'components/Loader' import Modal from 'components/Modal' import { RowBetween, RowFixed } from 'components/Row' import ListGridViewGroup from 'components/YieldPools/ListGridViewGroup' -import { SUPPORTED_WALLETS } from 'constants/wallets' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useWeb3React } from 'hooks' import useTheme from 'hooks/useTheme' import { VIEW_MODE } from 'state/user/reducer' import { ExternalLink } from 'theme' @@ -85,7 +86,8 @@ export function ConfirmationPendingContent({ } function AddTokenToInjectedWallet({ token, chainId }: { token: Token; chainId: ChainId }) { - const { walletKey } = useActiveWeb3React() + const { connector } = useWeb3React() + const connection = getConnection(connector) const handleClick = async () => { const tokenAddress = token.address const tokenSymbol = token.symbol @@ -113,18 +115,16 @@ function AddTokenToInjectedWallet({ token, chainId }: { token: Token; chainId: C } } - if (!walletKey) return null - if (walletKey === 'WALLET_CONNECT') return null - if (walletKey === 'KRYSTAL_WC') return null - const walletConfig = SUPPORTED_WALLETS[walletKey] + if (!connection || connection.type === ConnectionType.WALLET_CONNECT_V2) return null + const { name, icon } = connection.getProviderInfo() return ( - Add {token.symbol} to {walletConfig.name} + Add {token.symbol} to {name} {' '} - + ) diff --git a/src/components/WalletPopup/WalletView.tsx b/src/components/WalletPopup/WalletView.tsx index 41f05496b4..20533a5387 100644 --- a/src/components/WalletPopup/WalletView.tsx +++ b/src/components/WalletPopup/WalletView.tsx @@ -1,4 +1,5 @@ import { Trans, t } from '@lingui/macro' +import { getConnection } from 'connection' import { rgba } from 'polished' import { useEffect, useLayoutEffect, useRef, useState } from 'react' import { ChevronLeft, FileText, LogOut, StopCircle, X } from 'react-feather' @@ -16,8 +17,7 @@ import MyAssets from 'components/WalletPopup/MyAssets' import PinButton from 'components/WalletPopup/PinButton' import SendToken from 'components/WalletPopup/SendToken' import { APP_PATHS } from 'constants/index' -import { SUPPORTED_WALLETS } from 'constants/wallets' -import { useActiveWeb3React } from 'hooks' +import { useActiveWeb3React, useWeb3React } from 'hooks' import useMixpanel, { MIXPANEL_TYPE } from 'hooks/useMixpanel' import useTheme from 'hooks/useTheme' import useDisconnectWallet from 'hooks/web3/useDisconnectWallet' @@ -132,6 +132,8 @@ export default function WalletView({ const nodeRef = useRef(null) const [isMinimal, setMinimal] = useState(false) const { chainId, account = '', walletKey } = useActiveWeb3React() + const { connector } = useWeb3React() + const connection = getConnection(connector) const disconnectWallet = useDisconnectWallet() const { @@ -327,11 +329,7 @@ export default function WalletView({ {walletKey && ( - {SUPPORTED_WALLETS[walletKey].name + )} diff --git a/src/components/Web3ReactManager/index.tsx b/src/components/Web3ReactManager/index.tsx deleted file mode 100644 index 1ee1654a2a..0000000000 --- a/src/components/Web3ReactManager/index.tsx +++ /dev/null @@ -1,34 +0,0 @@ -import { ChainId } from '@kyberswap/ks-sdk-core' -import { useEffect } from 'react' -import { useDispatch, useSelector } from 'react-redux' - -import LocalLoader from 'components/LocalLoader' -import { useWeb3React } from 'hooks' -import { useEagerConnect } from 'hooks/web3/useEagerConnect' -import { AppState } from 'state' -import { updateChainId } from 'state/user/actions' - -export default function Web3ReactManager({ children }: { children: JSX.Element }) { - const chainIdState = useSelector(state => state.user.chainId) || ChainId.MAINNET - const { active, chainId: chainIdEVM } = useWeb3React() - - // try to eagerly connect to an injected provider, if it exists and has granted access already - const triedEager = useEagerConnect() - - const dispatch = useDispatch() - /** On user change network from wallet, update chainId in store, only work on EVM wallet */ - useEffect(() => { - if (triedEager.current && chainIdEVM && chainIdState !== chainIdEVM && active) { - dispatch(updateChainId(chainIdEVM)) - } - // Only run on change network from wallet - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [chainIdEVM, triedEager.current, active]) - - // on page load, do nothing until we've tried to connect to the injected connector - if (!triedEager.current) { - return - } - - return children -} diff --git a/src/hooks/web3/useActivationWallet.ts b/src/hooks/web3/useActivationWallet.ts deleted file mode 100644 index 0947d77f29..0000000000 --- a/src/hooks/web3/useActivationWallet.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { captureException } from '@sentry/react' -import { useCallback } from 'react' - -import { LOCALSTORAGE_LAST_WALLETKEY_EVM, SUPPORTED_WALLETS } from 'constants/wallets' - -export const useActivationWallet: () => { - tryActivation: (walletKey: string, isEagerly?: boolean) => Promise -} = () => { - const tryActivationEVM: (walletKey: string, isEagerly?: boolean) => Promise = useCallback( - async (walletKey: string, isEagerly = false) => { - const wallet = (SUPPORTED_WALLETS as any)[walletKey] - try { - console.info('Activate EVM start', { walletKey, isEagerly }) - if (isEagerly) { - if (wallet.connector.connectEagerly) { - await wallet.connector.connectEagerly() - console.info('Activate EVM success with .connectEagerly()', { - walletKey, - isEagerly, - 'wallet.connector': wallet.connector, - }) - } else { - await wallet.connector.activate() - console.info('Activate EVM success with .activate()', { walletKey, isEagerly }) - } - } else { - await wallet.connector.activate() - console.info('Activate EVM success with .activate()', { walletKey, isEagerly }) - } - localStorage.setItem(LOCALSTORAGE_LAST_WALLETKEY_EVM, walletKey) - } catch (error) { - console.error('Activate EVM failed:', { walletKey, wallet, error, isEagerly }) - localStorage.removeItem(LOCALSTORAGE_LAST_WALLETKEY_EVM) - const e = new Error(`[Wallet] ${error.message}`) - e.name = 'Activate EVM failed' - e.stack = '' - captureException(e, { - level: 'warning', - extra: { error, walletKey, isEagerly }, - }) - throw error - } - }, - [], - ) - - const tryActivation: (walletKey: string, isEagerly?: boolean) => Promise = useCallback( - async (walletKey: string, isEagerly = false) => { - const wallet = (SUPPORTED_WALLETS as any)[walletKey] - if (!wallet.href) { - await tryActivationEVM(walletKey, isEagerly) - } - }, - [tryActivationEVM], - ) - - return { - tryActivation, - } -} diff --git a/src/hooks/web3/useDisconnectWallet.ts b/src/hooks/web3/useDisconnectWallet.ts index d4eb973e45..0dbc57d64c 100644 --- a/src/hooks/web3/useDisconnectWallet.ts +++ b/src/hooks/web3/useDisconnectWallet.ts @@ -1,42 +1,18 @@ -import { Connector } from '@web3-react/types' import { useCallback } from 'react' -import { coinbaseWallet, krystalWalletConnectV2, walletConnectV2 } from 'constants/connectors' -import { LOCALSTORAGE_LAST_WALLETKEY_EVM, SUPPORTED_WALLETS } from 'constants/wallets' -import { useActiveWeb3React, useWeb3React } from 'hooks' - -const disconnectEvmConnector: (connector: Connector | undefined) => void | Promise = ( - connector: Connector | undefined, -) => { - if (connector) { - if (connector === coinbaseWallet) { - return connector.resetState() - } - connector.deactivate?.() - connector.resetState?.() - if (connector === walletConnectV2 || connector === krystalWalletConnectV2) { - // This key should be deleted when disconnected by walletconnect library - // But it was deleted slowly, if user call connector.active() again before this key cleared, bug will appear - // So we force remove it right after disconnected to preventing bug - // todo: deep dive rootcause why it slowly delete - localStorage.removeItem('wc@2:client:0.3//session') - } - } -} +import { useWeb3React } from 'hooks' +import { useAppDispatch } from 'state/hooks' +import { setRecentConnectionDisconnected } from 'state/user/actions' const useDisconnectWallet = () => { - const { walletKey } = useActiveWeb3React() + const dispatch = useAppDispatch() const { connector } = useWeb3React() - return useCallback(async () => { - const wallet = walletKey && SUPPORTED_WALLETS[walletKey] - // If wallet support both network, disconnect to both - if (wallet) { - await disconnectEvmConnector(connector) - localStorage.removeItem(LOCALSTORAGE_LAST_WALLETKEY_EVM) - } else { - await disconnectEvmConnector(connector) - localStorage.removeItem(LOCALSTORAGE_LAST_WALLETKEY_EVM) - } - }, [connector, walletKey]) + const disconnect = useCallback(() => { + connector.deactivate?.() + connector.resetState() + dispatch(setRecentConnectionDisconnected()) + }, [connector, dispatch]) + + return disconnect } export default useDisconnectWallet diff --git a/src/hooks/web3/useEagerConnect.ts b/src/hooks/web3/useEagerConnect.ts deleted file mode 100644 index e6a56ae3a1..0000000000 --- a/src/hooks/web3/useEagerConnect.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { useEffect, useState } from 'react' -import { isMobile } from 'react-device-detect' - -import { LOCALSTORAGE_LAST_WALLETKEY_EVM } from 'constants/wallets' -import { useWeb3React } from 'hooks' -import { useIsAcceptedTerm } from 'state/user/hooks' - -import { useActivationWallet } from './useActivationWallet' -import useDisconnectWallet from './useDisconnectWallet' - -// make sure this hook will be ran only once globally -let trying = false -const tried = { current: false } // global ref -export function useEagerConnect() { - const { active } = useWeb3React() - const disconnect = useDisconnectWallet() - const [, reRender] = useState({}) - const [isAcceptedTerm] = useIsAcceptedTerm() - const { tryActivation } = useActivationWallet() - - const setTried = () => { - try { - tried.current = true - Object.freeze(tried) - } catch {} - reRender({}) - } - - useEffect(() => { - const func = async () => { - // If not accepted Terms or Terms changed: block eager connect for EVM wallets - if (!isAcceptedTerm) { - setTried() - disconnect() - return - } - try { - if (trying || tried.current) return - trying = true - let activatedSuccess = false - // must retrieve this before activate safe, or will be overriden to SAFE - const lastWalletKeyEVM = localStorage.getItem(LOCALSTORAGE_LAST_WALLETKEY_EVM) - - try { - await tryActivation('SAFE', true) - activatedSuccess = true - setTried() - } catch {} - - await Promise.all([ - (async () => { - if (lastWalletKeyEVM) { - await tryActivation(lastWalletKeyEVM, true) - activatedSuccess = true - } - })(), - ]) - if (!activatedSuccess) { - if (isMobile && window.ethereum) { - await tryActivation('INJECTED', true) - } - } - } catch (e) { - console.log('Eagerly connect: authorize error', e) - } finally { - setTried() - } - } - func() - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) // intentionally only running on mount - - // if the connection worked, wait until we get confirmation of that to flip the flag - useEffect(() => { - if (active) { - setTried() - } - }, [active]) - - return tried -} diff --git a/src/hooks/web3/useSyncNetworkParamWithStore.ts b/src/hooks/web3/useSyncNetworkParamWithStore.ts index b6ab8d067b..edbe3f0515 100644 --- a/src/hooks/web3/useSyncNetworkParamWithStore.ts +++ b/src/hooks/web3/useSyncNetworkParamWithStore.ts @@ -3,7 +3,6 @@ import { useLocation, useNavigate, useParams } from 'react-router-dom' import { NETWORKS_INFO } from 'constants/networks' import { useActiveWeb3React } from 'hooks' -import { useEagerConnect } from 'hooks/web3/useEagerConnect' import { getChainIdFromSlug } from 'utils/string' import { useChangeNetwork } from './useChangeNetwork' @@ -14,20 +13,15 @@ export function useSyncNetworkParamWithStore() { const { changeNetwork } = useChangeNetwork() const { networkInfo, chainId } = useActiveWeb3React() const navigate = useNavigate() - const triedEager = useEagerConnect() const location = useLocation() const [requestingNetwork, setRequestingNetwork] = useState() const triedSync = useRef(false) - const tried = triedEager.current useEffect(() => { if (!networkParam || !paramChainId) { triedSync.current = true return } - if (!tried) { - return - } /** * Try to change to network on route param on init. Exp: /swap/ethereum => try to connect to ethereum on init @@ -45,7 +39,7 @@ export function useSyncNetworkParamWithStore() { }) triedSync.current = true })() - }, [changeNetwork, location, navigate, networkInfo.route, networkParam, paramChainId, tried]) + }, [changeNetwork, location, navigate, networkInfo.route, networkParam, paramChainId]) useEffect(() => { if (NETWORKS_INFO[chainId].route === requestingNetwork) setRequestingNetwork(undefined) @@ -59,13 +53,12 @@ export function useSyncNetworkParamWithStore() { ((requestingNetwork && requestingNetwork !== networkParam) || !requestingNetwork) && networkParam && networkInfo.route !== networkParam && - triedSync.current && - tried + triedSync.current ) { navigate( { ...location, pathname: location.pathname.replace(encodeURIComponent(networkParam), networkInfo.route) }, { replace: true }, ) } - }, [location, networkInfo.route, navigate, tried, networkParam, requestingNetwork]) + }, [location, networkInfo.route, navigate, networkParam, requestingNetwork]) } diff --git a/src/pages/App.tsx b/src/pages/App.tsx index aee23262ec..51d2c8ffe5 100644 --- a/src/pages/App.tsx +++ b/src/pages/App.tsx @@ -17,7 +17,6 @@ import ModalsGlobal from 'components/ModalsGlobal' import ProtectedRoute from 'components/ProtectedRoute' import Snowfall from 'components/Snowflake/Snowfall' import SupportButton from 'components/SupportButton' -import Web3ReactManager from 'components/Web3ReactManager' import { APP_PATHS, CHAINS_SUPPORT_CROSS_CHAIN } from 'constants/index' import { CLASSIC_NOT_SUPPORTED, ELASTIC_NOT_SUPPORTED, NETWORKS_INFO, SUPPORTED_NETWORKS } from 'constants/networks' import { useActiveWeb3React } from 'hooks' @@ -245,90 +244,88 @@ export default function App() { - - - {/* From react-router-dom@6.5.0, :fromCurrency-to-:toCurrency no long works, need to manually parse the params */} - } /> - } /> - {CHAINS_SUPPORT_CROSS_CHAIN.includes(chainId) && ( - } /> - )} - - {isSupportLimitOrder(chainId) && ( - } /> - )} - - } /> - <> - {/* Farms Routes */} - } /> - } /> - - - <> - {/* My Pools Routes */} - } /> - } /> - - - <> - {/* These are old routes and will soon be deprecated - Check: RoutesWithNetworkParam */} - {/* + + {/* From react-router-dom@6.5.0, :fromCurrency-to-:toCurrency no long works, need to manually parse the params */} + } /> + } /> + {CHAINS_SUPPORT_CROSS_CHAIN.includes(chainId) && ( + } /> + )} + + {isSupportLimitOrder(chainId) && ( + } /> + )} + + } /> + <> + {/* Farms Routes */} + } /> + } /> + + + <> + {/* My Pools Routes */} + } /> + } /> + + + <> + {/* These are old routes and will soon be deprecated - Check: RoutesWithNetworkParam */} + {/* } /> } /> */} - } /> - - } /> - - - } /> - } /> - } /> - } /> - } /> - } /> - {/* } /> */} - - - - } - /> - - - - } - /> - - - - } - /> - - } /> - - } /> - - } /> - } /> - } /> - } /> - - } /> - - } /> - - + } /> + + } /> + + + } /> + } /> + } /> + } /> + } /> + } /> + {/* } /> */} + + + + } + /> + + + + } + /> + + + + } + /> + + } /> + + } /> + + } /> + } /> + } /> + } /> + + } /> + + } /> + {showFooter &&