ethers-io / ethers.js

Complete Ethereum library and wallet implementation in JavaScript.
https://ethers.org/
MIT License
8k stars 1.87k forks source link

BrowserProvider network change event is not fired #4880

Open kubarenatioN opened 3 weeks ago

kubarenatioN commented 3 weeks ago

Ethers Version

6.13.4

Search Terms

network event listening

Describe the Problem

Well, I'm just subscribing to provider network change event (using .on('network')) and nothing is emitting when I change network in my Metamask wallet interface. When subscribing via window.ethereum.on('chainChanged', () => {}) and switching network, the callback is executed.

I'm using hardhat localhost network and Sepolia test network with deployed contract, but as I see, the issue is in provider itself.

Please, help me to understand the issue and resolve it.

Repo with source code (App.tsx, initWeb3 function) - https://github.com/kubarenatioN/dElection/commit/e1efb2c8c4e6bda8e4df2099e7ede2cb8385aca2#diff-e56cb91573ddb6a97ecd071925fe26504bb5a65f921dc64c63e534162950e1ebR53

Code Snippet

// Provider initialization
provider = new ethers.BrowserProvider(window.ethereum as any, 'any');

// Later in code when subscribe to events
// This just ignores network change.
      provider.provider.on('network', (...args) => {
        console.log(123, args);
      });

      // This will work and log in console.
      (window.ethereum as any).on('chainChanged', (...args: any[]) => {
        console.log(222, args);
      })

Contract ABI

No response

Errors

No response

Environment

Browser (Chrome, Safari, etc)

Environment (Other)

Metamask Wallet

kubarenatioN commented 2 weeks ago

Moreover, similar issue have already happened to another dev. He asked about it here, but get no response - https://github.com/ethers-io/ethers.js/issues/2842#issuecomment-1126837212

Also, I found this issue - https://github.com/ethers-io/ethers.js/issues/1396 There we have some explanation on usage of .on('network', () => {}), but still, my original question is about that it doesn't work as intended, or I'm missing some details...

Waiting for some help. By the way, thanks for your great work!

alejoloaiza commented 1 week ago

Having this issue too with version 6.13.4