Fixed Custom Network Chain and Network ID Values
Beginning in MetaMask 8.1, we are correcting the value that the MetaMask extension emits with the chainChanged
event for some custom networks. This could cause issues for sites that are relying on the incorrect behavior.
As a dapp developer, you should do the following to handle this change:
- Always use the
chainChanged
event to detect network changes. ThenetworkChanged
event is deprecated. - If you need to continue using the
networkChanged
event, ensure that your dapp expects it to emit with decimal string values. Previously, this event could have emitted with a hexadecimal string for some custom networks.
Explanation
The MetaMask provider emits the chainChanged
and networkChanged
events when the user switches the network in MetaMask. Due to a bug, in cases where the user added a custom network and specified its chain ID, MetaMask emitted the specified chain ID with networkChanged
, and a nonsense value with chainChanged
.
Prior to MetaMask 8.1, the specified chain ID for a custom network could be a decimal or hexadecimal string. This meant that the networkChanged
event could emit with decimal or hexadecimal string values for the affected custom networks.
For example, if the user entered a “chain ID” of 0x64
for a custom network and switched to it, the MetaMask provider would emit networkChanged
with 0x64
. Likewise, if the user entered a “chain ID” of 100
, networkChanged
would emit with 100
.
In MetaMask 8.1 and later, these two events will emit the values according to the specification for all networks:
networkChanged
will emit the network ID as a decimal stringchainChanged
will emit the chain ID as a hexadecimal string
For a list of networks and their various IDs, see chainId.network. Note that all listed values are decimal numbers.
Background
This particular bug goes back to the DAO hack and EIP-155, which added chain IDs to EVM-compatible blockchains so that wallets could ensure that a transaction was only valid on one chain, and not on both sides of a fork.
Initially, chain_id
was often identical to network_id
, and this conflation was baked into our codebase, resulting in many developers relying on our network ID values when they should have been relying on the chain ID. As a result, the networkChanged
event would sometimes emit with the chain ID. You can read more about this history in this post by Pedro Gomes.
Fixing this issue brings our provider into tighter compatibility with the spec and the broader ecosystem. We hope that the impact is minimal, but please contact us if there is anything else we can do to help your app to continue operating smoothly.