Skip to content

Commit

Permalink
fix: update web3-react (#1858)
Browse files Browse the repository at this point in the history
  • Loading branch information
berteotti authored Aug 21, 2023
1 parent 6310945 commit 7fe5115
Show file tree
Hide file tree
Showing 38 changed files with 1,391 additions and 949 deletions.
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"dependencies": {
"@apollo/client": "^3.7.5",
"@arbitrum/sdk": "3.0.0-beta.12",
"@coinbase/wallet-sdk": "3.7.1",
"@lifi/sdk": "1.7.2",
"@lifi/types": "2.1.1",
"@popperjs/core": "^2.11.6",
Expand All @@ -50,11 +51,11 @@
"@tanstack/react-query": "4.24.6",
"@uniswap/token-lists": "^1.0.0-beta.27",
"@uniswap/v3-periphery": "1.4.1",
"@web3-react/core": "^6.1.9",
"@web3-react/injected-connector": "^6.0.7",
"@web3-react/network-connector": "^6.2.9",
"@web3-react/walletconnect-connector": "^6.2.13",
"@web3-react/walletlink-connector": "^6.2.14",
"@web3-react/coinbase-wallet": "8.2.2",
"@web3-react/core": "8.2.2",
"@web3-react/metamask": "8.2.3",
"@web3-react/network": "8.2.2",
"@web3-react/walletconnect-v2": "8.5.0",
"ajv": "^8.12.0",
"ajv-formats": "^2.1.1",
"aos": "^2.3.4",
Expand Down
3 changes: 1 addition & 2 deletions src/analytics/trackers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ export async function trackEcoRouterTradeVolume(
debug('tracking EcoRouter trade USD volume', { trade, chartOption, site })
// Get use value for input amount
const tradeUSDValue = await getTradeUSDValue(trade)
//const data = await queryClient.fetchQuery({ queryKey, queryFn })

if (tradeUSDValue === null) {
throw new Error('Could not get trade USD value', {
Expand Down Expand Up @@ -73,7 +72,7 @@ export async function trackEcoBridgeTradeVolume(trade: BridgeTransactionSummary,
if (rawTokenPriceInfo === null) {
throw new Error('Could not get token price')
}
console.log(Object.values(rawTokenPriceInfo))

const tokenUSDPrice = Object.values(rawTokenPriceInfo)[0].usd
const usdValue = (tokenUSDPrice * parseFloat(trade.fromValue)).toFixed(2)
const tradeUSDValueInCents = (parseFloat(parseFloat(usdValue).toFixed(2)) * 100).toString() // convert to cents because fathom requires it
Expand Down
4 changes: 2 additions & 2 deletions src/components/Claim/ActionButton/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CurrencyAmount } from '@swapr/sdk'

import { InjectedConnector } from '@web3-react/injected-connector'
import { MetaMask } from '@web3-react/metamask'
import { useCallback, useEffect, useState } from 'react'
import styled from 'styled-components'

Expand Down Expand Up @@ -63,7 +63,7 @@ export function ActionButton({

const handleLocalClick = useCallback(() => {
if (!account) onConnectWallet()
else if (!correctNetwork && connector instanceof InjectedConnector) onSwitchToArbitrum()
else if (!correctNetwork && connector instanceof MetaMask) onSwitchToArbitrum()
else if (isOldSwaprLp) {
const anchor = document.createElement('a')
Object.assign(anchor, {
Expand Down
6 changes: 2 additions & 4 deletions src/components/NetworkSwitcherPopover/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ interface NetworkSwitcherPopoverProps {

export default function NetworkSwitcherPopover({ children, modal, placement }: NetworkSwitcherPopoverProps) {
const closeModals = useCloseModals()
const { connector, chainId: activeChainId } = useActiveWeb3React()
const { chainId: activeChainId } = useActiveWeb3React()
const networkSwitcherPopoverOpen = useModalOpen(modal)
const unsupportedChainIdError = useUnsupportedChainIdError()

Expand All @@ -28,9 +28,7 @@ export default function NetworkSwitcherPopover({ children, modal, placement }: N
})

const isNetworkDisabled = (chainId: ChainId) => {
return (
connector?.supportedChainIds?.indexOf(chainId) === -1 || (!unsupportedChainIdError && activeChainId === chainId)
)
return !unsupportedChainIdError && activeChainId === chainId
}

if (!activeChainId) {
Expand Down
10 changes: 5 additions & 5 deletions src/components/WalletModal/PendingView.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { AbstractConnector } from '@web3-react/abstract-connector'
import { Connector } from '@web3-react/types'
import { Box, Flex } from 'rebass'
import styled from 'styled-components'

import { injected } from '../../connectors'
import { metaMask } from '../../connectors'
import { SUPPORTED_WALLETS } from '../../constants'
import { TYPE } from '../../theme'
import { ButtonPrimary } from '../Button'
Expand Down Expand Up @@ -55,10 +55,10 @@ export default function PendingView({
setPendingError,
tryActivation,
}: {
connector?: AbstractConnector
connector?: Connector
error?: boolean
setPendingError: (error: boolean) => void
tryActivation: (connector: AbstractConnector) => void
tryActivation: (connector: Connector) => void
}) {
const isMetamask = window?.ethereum?.isMetaMask

Expand All @@ -67,7 +67,7 @@ export default function PendingView({
{Object.keys(SUPPORTED_WALLETS).map(key => {
const option = SUPPORTED_WALLETS[key]
if (option.connector === connector) {
if (option.connector === injected) {
if (option.connector === metaMask) {
if (isMetamask && option.name !== 'MetaMask') {
return null
}
Expand Down
29 changes: 14 additions & 15 deletions src/components/WalletModal/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AbstractConnector } from '@web3-react/abstract-connector'
import { useWeb3React } from '@web3-react/core'
import { Connector } from '@web3-react/types'
import { useCallback, useEffect } from 'react'
import { AlertTriangle } from 'react-feather'
import { usePrevious } from 'react-use'
Expand Down Expand Up @@ -86,10 +86,10 @@ const HoverText = styled.div`
interface WalletModalProps {
modal: ModalView | null
setModal: (modal: ModalView | null) => void
tryActivation: (connector: AbstractConnector | undefined) => void
tryActivation: (connector: Connector | undefined) => void
pendingError: boolean | undefined
setPendingError: (value: boolean) => void
pendingWallet: AbstractConnector | undefined
pendingWallet: Connector | undefined
}

export default function WalletModal({
Expand All @@ -100,7 +100,8 @@ export default function WalletModal({
setPendingError,
pendingWallet,
}: WalletModalProps) {
const { active, account, connector, error } = useWeb3React()
const { isActive, account, connector } = useWeb3React()
const isUnsupportedChainIdError = useUnsupportedChainIdError()

const closeModal = useCallback(() => setModal(null), [setModal])

Expand All @@ -122,24 +123,26 @@ export default function WalletModal({
}
}, [account, previousAccount, closeModal, isModalVisible])

const activePrevious = usePrevious(active)
const activePrevious = usePrevious(isActive)
const connectorPrevious = usePrevious(connector)
useEffect(() => {
if (!!modal && ((active && !activePrevious) || (connector && connector !== connectorPrevious && !error))) {
if (
!!modal &&
((isActive && !activePrevious) || (connector && connector !== connectorPrevious && !isUnsupportedChainIdError))
) {
setModal(null)
}
}, [setModal, active, error, connector, modal, activePrevious, connectorPrevious])
}, [setModal, isActive, connector, modal, activePrevious, connectorPrevious, isUnsupportedChainIdError])

const toggleWalletSwitcherPopover = useWalletSwitcherPopoverToggle()
const onBackButtonClick = () => {
setPendingError(false)
setModal(null)
toggleWalletSwitcherPopover()
}
const unsupportedChainIdError = useUnsupportedChainIdError()

function getModalContent() {
if (error) {
if (isUnsupportedChainIdError) {
return (
<UpperSection>
<CloseIcon onClick={closeModal}>
Expand All @@ -149,17 +152,13 @@ export default function WalletModal({
<AutoRow gap="6px">
<StyledWarningIcon size="20px" />
<TYPE.Main fontSize="16px" lineHeight="22px" color={'text3'}>
{unsupportedChainIdError ? 'Wrong Network' : 'Error connecting'}
Wrong Network
</TYPE.Main>
</AutoRow>
</HeaderRow>
<ContentWrapper>
<TYPE.Yellow color="text4">
<h5>
{unsupportedChainIdError
? 'Please connect to the appropriate network.'
: 'Error connecting. Try refreshing the page.'}
</h5>
<h5>Please connect to the appropriate network.</h5>
</TYPE.Yellow>
</ContentWrapper>
</UpperSection>
Expand Down
37 changes: 25 additions & 12 deletions src/components/Web3ReactManager/index.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { ChainId } from '@swapr/sdk'

import { useWeb3React } from '@web3-react/core'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import styled from 'styled-components'

import { network } from '../../connectors'
import { NetworkContextName } from '../../constants'
import { useEagerConnect, useInactiveListener } from '../../hooks'
import { useEagerConnect, useInactiveListener, useUnsupportedChainIdError } from '../../hooks'
import { useTargetedChainIdFromUrl } from '../../hooks/useTargetedChainIdFromUrl'
import { Loader } from '../Loader'

Expand All @@ -22,22 +23,34 @@ const Message = styled.h2`

export default function Web3ReactManager({ children }: { children: JSX.Element }) {
const { t } = useTranslation('common')
const { active } = useWeb3React()
const { active: networkActive, error: networkError, activate: activateNetwork } = useWeb3React(NetworkContextName)
const { isActive, connector, hooks, chainId } = useWeb3React()
const { useSelectedIsActive, usePriorityChainId } = hooks
const networkIsActive = useSelectedIsActive(network)
const ativeChainId = usePriorityChainId()
const targetedChainId = useTargetedChainIdFromUrl()
const isUnsupportedChainIdError = useUnsupportedChainIdError()

// try to eagerly connect to an injected provider, if it exists and has granted access already
const triedEager = useEagerConnect()

// after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
//after eagerly trying injected, if the network connect ever isn't active or in an error state, activate itd
useEffect(() => {
if (triedEager && !networkActive && !networkError && !active) {
if (targetedChainId && network.supportedChainIds && network.supportedChainIds.indexOf(targetedChainId) >= 0) {
network.changeChainId(targetedChainId)
if (triedEager && !networkIsActive && !isActive && !isUnsupportedChainIdError) {
if (targetedChainId && Boolean(ChainId[targetedChainId])) {
network.activate(targetedChainId)
}
activateNetwork(network)
network.activate()
}
}, [triedEager, networkActive, networkError, activateNetwork, active, targetedChainId])
}, [
triedEager,
targetedChainId,
isActive,
isUnsupportedChainIdError,
connector,
networkIsActive,
chainId,
ativeChainId,
])

// when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
useInactiveListener(!triedEager)
Expand All @@ -60,7 +73,7 @@ export default function Web3ReactManager({ children }: { children: JSX.Element }
}

// if the account context isn't active, and there's an error on the network context, it's an irrecoverable error
if (!active && networkError) {
if (!isActive && isUnsupportedChainIdError) {
return (
<MessageWrapper>
<Message>{t('unknownError')}</Message>
Expand All @@ -69,7 +82,7 @@ export default function Web3ReactManager({ children }: { children: JSX.Element }
}

// if neither context is active, spin
if (!active && !networkActive) {
if (!isActive && !networkIsActive) {
return showLoader ? (
<MessageWrapper>
<Loader />
Expand Down
19 changes: 10 additions & 9 deletions src/components/Web3Status/AccountStatus.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { ChainId } from '@swapr/sdk'

import { AbstractConnector } from '@web3-react/abstract-connector'
import { InjectedConnector } from '@web3-react/injected-connector'
import { CoinbaseWallet } from '@web3-react/coinbase-wallet'
import { MetaMask } from '@web3-react/metamask'
import { Network } from '@web3-react/network'
import { Connector } from '@web3-react/types'
import { WalletConnect } from '@web3-react/walletconnect-v2'
import { useEffect, useState } from 'react'
import { Text } from 'rebass'
import styled from 'styled-components'
Expand All @@ -13,8 +16,6 @@ import GnosisLogo from '../../assets/images/gnosis-chain-logo.svg'
import OptimismLogo from '../../assets/images/optimism-logo.svg'
import PolygonMaticLogo from '../../assets/images/polygon-matic-logo.svg'
import ZkSyncEraLogo from '../../assets/images/zk-sync-era-logo.svg'
import { CustomNetworkConnector } from '../../connectors/CustomNetworkConnector'
import { CustomWalletLinkConnector } from '../../connectors/CustomWalletLinkConnector'
import { ENSAvatarData } from '../../hooks/useENSAvatar'
import { ApplicationModal } from '../../state/application/actions'
import { useNetworkSwitcherPopoverToggle } from '../../state/application/hooks'
Expand Down Expand Up @@ -143,7 +144,7 @@ interface AccountStatusProps {
ENSName?: string
avatar?: ENSAvatarData
account: string | undefined | null
connector: AbstractConnector | undefined
connector: Connector | undefined
networkConnectorChainId: ChainId | undefined
onAddressClick: () => void
}
Expand All @@ -163,10 +164,10 @@ export function AccountStatus({

useEffect(() => {
setNetworkSwitchingActive(
connector instanceof CustomNetworkConnector ||
connector instanceof InjectedConnector ||
connector instanceof CustomWalletLinkConnector ||
connector instanceof AbstractConnector
connector instanceof Network ||
connector instanceof MetaMask ||
connector instanceof WalletConnect ||
connector instanceof CoinbaseWallet
)
}, [connector])

Expand Down
27 changes: 18 additions & 9 deletions src/components/Web3Status/ConnectWalletPopover.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { AbstractConnector } from '@web3-react/abstract-connector'
import { useWeb3React } from '@web3-react/core'
import { Connector } from '@web3-react/types'
import { ReactNode, useRef } from 'react'
import { isMobile } from 'react-device-detect'
import styled from 'styled-components'

import MetamaskIcon from '../../assets/images/metamask.png'
import { injected } from '../../connectors'
import { metaMask } from '../../connectors'
import { SUPPORTED_WALLETS } from '../../constants'
import { useOnClickOutside } from '../../hooks/useOnClickOutside'
import { ApplicationModal } from '../../state/application/actions'
Expand Down Expand Up @@ -98,12 +98,15 @@ const StyledPopover = styled(Popover)<{ isActive?: boolean }>`
`

interface ConnectWalletProps {
tryActivation: (connector: AbstractConnector | undefined) => void
tryActivation: (connector: Connector | undefined) => void
children: ReactNode
}

export const ConnectWalletPopover = ({ tryActivation, children }: ConnectWalletProps) => {
const { connector, active, deactivate } = useWeb3React()
const { connector, isActive, hooks } = useWeb3React()
const { useSelectedIsActive } = hooks
const selectedIsActive = useSelectedIsActive(connector)

const popoverRef = useRef<HTMLDivElement | null>(null)
const walletSwitcherPopoverOpen = useModalOpen(ApplicationModal.WALLET_SWITCHER)
const closeModals = useCloseModals()
Expand Down Expand Up @@ -136,7 +139,7 @@ export const ConnectWalletPopover = ({ tryActivation, children }: ConnectWalletP
}

// overwrite injected when needed
if (option.connector === injected) {
if (option.connector === metaMask) {
// don't show injected if there's no injected provider
if (!(window.web3 || window.ethereum) || ((window.web3 || window.ethereum) && !isMetamask)) {
if (option.name === 'MetaMask') {
Expand Down Expand Up @@ -173,11 +176,11 @@ export const ConnectWalletPopover = ({ tryActivation, children }: ConnectWalletP
id={`connect-${key}`}
onClick={() => {
closeModals()
option.connector !== connector && !option.href && tryActivation(option.connector)
if (!selectedIsActive || option.connector !== connector) tryActivation(option.connector)
}}
name={option.name}
icon={option.iconName}
isActive={option.connector && option.connector === connector}
isActive={selectedIsActive && option.connector === connector}
/>
)
)
Expand All @@ -191,11 +194,17 @@ export const ConnectWalletPopover = ({ tryActivation, children }: ConnectWalletP
content={
<List data-testid="wallet-connect-list">
{getOptions()}
{active && <DisconnectButton onClick={deactivate}>Disconnect Wallet</DisconnectButton>}
{isActive && (
<DisconnectButton
onClick={() => connector && (connector.deactivate ? connector.deactivate() : connector.resetState())}
>
Disconnect Wallet
</DisconnectButton>
)}
</List>
}
show={walletSwitcherPopoverOpen}
isActive={active}
isActive={isActive}
placement="bottom-end"
>
{children}
Expand Down
Loading

0 comments on commit 7fe5115

Please sign in to comment.