[Ethereum] Detecting `accountsChanged` and `chainChanged` with ethersjs

clientsethers.jsevents

I'm not sure if this question makes sense or if I'm looking at things correctly but it's coming from my understanding that ethersjs is an abstraction on top of MetaMask (and other providers)…

I've been able to get events from ethereum.on('chainChanged') and ethereum.on('accountsChanged') but I'm wondering if there is a way to do this through the ethersjs events or interface.

Best Answer

You can initialize ethers and set a provider variable

const provider = new ethers.providers.Web3Provider(window.ethereum);

then you add/remove events by

const { provider: ethereum } = provider;
ethereum.on('accountsChanged', someFunction}; 
ethereum.off('accountsChanged', someFunction};
Related Topic