Skip to content

Commit

Permalink
fix: metamask auto reconnect after change account
Browse files Browse the repository at this point in the history
  • Loading branch information
namgold committed Sep 14, 2023
1 parent 0f929f4 commit 12e5036
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 44 deletions.
4 changes: 1 addition & 3 deletions src/components/Web3ReactManager/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'

import LocalLoader from 'components/LocalLoader'
import { useActiveWeb3React, useInactiveListener, useWeb3React } from 'hooks'
import { useActiveWeb3React, useWeb3React } from 'hooks'
import { useEagerConnect } from 'hooks/web3/useEagerConnect'
import { AppState } from 'state'
import { updateChainId } from 'state/user/actions'
Expand All @@ -16,8 +16,6 @@ export default function Web3ReactManager({ children }: { children: JSX.Element }
// try to eagerly connect to an injected provider, if it exists and has granted access already
const triedEager = useEagerConnect()

// when there's no account connected, react to logins (broadly speaking) on the injected provider, if it exists
useInactiveListener(!triedEager.current)
const dispatch = useDispatch()
/** On user change network from wallet, update chainId in store, only work on EVM wallet */
useEffect(() => {
Expand Down
41 changes: 0 additions & 41 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,44 +136,3 @@ export const useWeb3Solana = () => {
const { connection } = useKyberSwapConfig()
return { connection }
}

/**
* Use for network and injected - logs user in
* and out after checking what network they're on
*/
export function useInactiveListener(suppress = false) {
const { isEVM } = useActiveWeb3React()
const { active } = useWeb3React() // specifically using useWeb3React because of what this hook does

useEffect(() => {
const { ethereum } = window
if (isEVM && ethereum?.on && !active && !suppress) {
const handleChainChanged = () => {
// eat errors
metaMask.activate().catch(error => {
console.error('Failed to activate after chain changed', error)
})
}

const handleAccountsChanged = (accounts: string[]) => {
if (accounts.length > 0) {
// eat errors
metaMask.activate().catch(error => {
console.error('Failed to activate after accounts changed', error)
})
}
}

ethereum.on('chainChanged', handleChainChanged)
ethereum.on('accountsChanged', handleAccountsChanged)

return () => {
if (ethereum.removeListener) {
ethereum.removeListener('chainChanged', handleChainChanged)
ethereum.removeListener('accountsChanged', handleAccountsChanged)
}
}
}
return undefined
}, [active, suppress, isEVM])
}

0 comments on commit 12e5036

Please sign in to comment.