How to switch network on Metamask programmatically

David Kathoh
4 min readDec 10, 2021

--

In this article, we are going to learn how to initiate a network switch on Metamask from a website. A website will only work on the network the smart contract it will be interacting with is deployed. A great user experience is to alert users when they are on a wrong network and allow them to switch automatically to the correct network when they are connecting their wallet or when interacting with a smart contract.

Switching network

Step 1: Before switching to a network, we first check if Metamask is installed in our browser by verifying if window.ethereum, a global API that MetaMask injects into websites is available. We do it like this

const provider = window.ethereum;
if(!provider){
console.log("Metamask is not installed, please install!");
}

Step 2: Now that we can confirm if Metamask is installed, let’s check if it is connected to the network we want by looking at the chainId, for this example, we are going to check if we are connected to the Binance Smart chain Test network it’s chainId is 0x61 (97 in decimal). The code looks like this

const chainId = await provider.request({ method: ‘eth_chainId’ });
const binanceTestChainId = '0x61'
if(chainId === binanceTestChainId){
console.log("Bravo!, you are on the correct network");
}else{
console.log("oulalal, switch to the correct network")
}

ChainIds of different networks can be found here

step 3: We know how to check the network we are currently connected to, let switch to our preferred network if it is not the one we are currently connected to by putting the network chainId in the request below

try {
await provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: binanaceTestChainId}],
});
console.log("You have succefully switched to Binance Test network")
} catch (switchError) {
// This error code indicates that the chain has not been added to MetaMask.
if (switchError.code === 4902) {
console.log("This network is not available in your metamask, please add it")
}
console.log("Failed to switch to the network")
}

When the above code is called a popup from Metamask should appear, asking the user to allow the website to switch the network. If the request returns null it is successful and the website should be connected to the Binance Smart chain test network otherwise an error is returned. If the error code (error.code) is 4902, then the requested network is not available in our Metamask Wallet.

Bonus 🎁, let’s see how to add a network programmatically on Metamask in the last part of this article

Adding a network in Metamask

To programmatically add a network in Metamask, we need to call the wallet_addEthereumChain method, exposed by window.ethereum and pass the network parameters to it. The parameters have this format

chainId: string; // A 0x-prefixed hexadecimal string
chainName: string;
nativeCurrency: {
name: string;
symbol: string; // 2-6 characters long
decimals: 18;
};
rpcUrls: string[];
blockExplorerUrls?: string[];
iconUrls?: string[]; // Currently ignored.(optional)

For Binance smart chain test network the parameter's values are:

Network Name: Smart Chain — Testnet

New RPC URL: https://data-seed-prebsc-1-s1.binance.org:8545/

ChainID: 0x61

Symbol: BNB

Block Explorer URL: https://testnet.bscscan.com

let's switch to the Binance chain test network finally

try {
await provider.request({
method: 'wallet_addEthereumChain',
params: [
{ chainId: '0x61',
chainName:'Smart Chain - Testnet',
rpcUrls:['https://data-seed-prebsc-1-s1.binance.org:8545'], blockExplorerUrls:['https://testnet.bscscan.com'],
nativeCurrency: {
symbol:'BNB',
decimals: 18}
});
} catch (addError) {
console.log(addError);
}

The method returns null if the request was successful and the user may choose to switch to the network once it has been added otherwise an error is returned. The full code can be found here

Voila, in this article we have just seen how to programmatically switch and add a network in Metamask.

Let’s connect on Twitter, Bye ✌️.

--

--

David Kathoh
David Kathoh

Responses (3)