web3modal icon indicating copy to clipboard operation
web3modal copied to clipboard

"accountsChanged" event does not fire

Open RobertoDonPedro opened this issue 2 years ago • 4 comments

Hi,

how can I react to account changes in Metamask? I'm trying this with React.js and ethers.js but the "accountsChanged" event is not firing.

    const web3Modal = new Web3Modal()
    const connection = await web3Modal.connect()
    const provider = new ethers.providers.Web3Provider(connection)   

    // Subscribe to accounts change
    provider.on("accountsChanged", (accounts) => {
      console.log('ACCOUNTS CHANGED' + accounts[0]);
    });

RobertoDonPedro avatar Feb 10 '22 12:02 RobertoDonPedro

You're meant to do:

const web3Modal = new Web3Modal()
const connection = await web3Modal.connect()
const provider = new ethers.providers.Web3Provider(connection)   

// Subscribe to accounts change
connection.on("accountsChanged", (accounts) => {
  console.log('ACCOUNTS CHANGED' + accounts[0]);
});

jahvi avatar Feb 13 '22 14:02 jahvi

You're meant to do:

const web3Modal = new Web3Modal()
const connection = await web3Modal.connect()
const provider = new ethers.providers.Web3Provider(connection)   

// Subscribe to accounts change
connection.on("accountsChanged", (accounts) => {
  console.log('ACCOUNTS CHANGED' + accounts[0]);
});

Ok, but then the documentation in the README is incorrect: // Subscribe to chainId change provider.on("chainChanged", (chainId: number) => { console.log(chainId); });

RobertoDonPedro avatar Feb 13 '22 15:02 RobertoDonPedro

Yes that should be changed, I only found out from reading the source code.

jahvi avatar Feb 13 '22 17:02 jahvi

Nvm, the documentation is outdated.

pencilcheck avatar Jun 21 '22 04:06 pencilcheck

With stable version 2.0.0 of Web3Modal now released, we are officially dropping support for version 1.x Due to this this issue/pr was marked for closing. It is highly recommended to upgrade as 2.x will be receiving further updates that will enable functionality for some of our newer sdks like auth and push as well as support for WalletConnect v2 (See this post about WalletConnect v1 being deprecated https://medium.com/walletconnect/walletconnect-v1-0-sunset-notice-and-migration-schedule-8af9d3720d2e)

If you need to continue using Web3Modal 1.x and require this feature/fix implemented, we suggest adding it via forking V1 branch.

xzilja avatar Jan 21 '23 16:01 xzilja

@0xAsimetriq Hello, how can I react to account changes in Metamask with web3modal v3?

uninstalls avatar Nov 26 '23 04:11 uninstalls

@uninstalls modal should react to these automatically. If you want to do it in code yourself you can use tools that wagmi or ethers exposes (depending on which web3modal package you use)

xzilja avatar Nov 26 '23 08:11 xzilja