Those events are EIP-1193 specific. An ethers Provider is not related to an EIP-1193 compliant Provider. An ethers Provider is a higher-level interface compared to an EIP-1193-compliant Provider. They don't necessarily have those events that are defined in the EIP-1193 standard. The ethers library creates a strong division between the operation a Provider can perform and those of a Signer, which for example Web3.js lumps together. A Provider in ethers is a read-only abstraction to access blockchain data. They should have named it something else to avoid confusion.
See the common terminology in ethers' documentation.
That all said, there are of course ways to listen to events.
- These are the supported events on an ethers Provider, and in addition, you can use the
network
event that is pretty much the same as the chainChanged
EIP-1193 event.
const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
provider.on("network", (newNetwork, oldNetwork) => {
// When a provider makes its initial connection, it emits a "network"
// event with a null oldNetwork along with the newNetwork. So, if the
// oldNetwork exists, it represents a changing network
if (oldNetwork) {
// chain has changed
}
});
You could also try to access the EIP-1193-compliant provider that is usually injected into the website by your wallet. So, as long as you have a wallet installed, set up, and connected and it supports such events, then you can listen to them using the following code.
Note that provider.provider
might not be available on certain ethers providers (i.e.: Web3Provider
).
provider?.provider?.on("chainChanged", (chainId) => {
// Handle the new chain
});
This is what you already mentioned in your question. You also have direct access to the global EIP-1193-compliant-provider that your wallet injects. This injected global API is available via window.ethereum
. See how MetaMask does it.
You could directly listen to the event on this provider but I guess my preference would be to use ethers and you asked about the other solutions anyway.
window.ethereum.on('chainChanged', (chainId) => {
// Handle the new chain.
});
References