Switching networks in MetaMask is essential for interacting with different blockchain networks. This guide will walk you through the steps to switch networks programmatically using JavaScript.

Step 1: Check if MetaMask is Installed

Before attempting to switch networks, ensure that MetaMask is installed in the user's browser. You can check this by verifying the presence of the window.ethereum object.


if (typeof window.ethereum === 'undefined') {
console.log("Please install MetaMask!");
}

Step 2: Define Network Parameters

You need to define the network parameters for the networks you want to switch to. Below is an example for the Rootstock Testnet and Mainnet.


const rskTestnet = {
chainName: 'Rootstock Testnet',
chainId: '0x1f',
rpcUrls: ['https://rpc.testnet.rootstock.io/{YOUR_APIKEY}'],
blockExplorerUrls: ['https://explorer.testnet.rootstock.io/'],
nativeCurrency: {
symbol: 'tRBTC',
decimals: 18,
},
};

const rskMainnet = {
chainName: 'Rootstock Mainnet',
chainId: '0x1e',
rpcUrls: ['https://rpc.rootstock.io/{YOUR_APIKEY}'],
blockExplorerUrls: ['https://explorer.rootstock.io/'],
nativeCurrency: {
symbol: 'RBTC',
decimals: 18,
},
};

Step 3: Switch to the Desired Network

Use the wallet_switchEthereumChain method to switch to the desired network. If the network is not added, you can use wallet_addEthereumChain to add it.


async function switchToNetwork(network) {
try {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: network.chainId }],
});
} catch (error) {
if (error.code === 4902) {
await window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [network],
});
} else {
console.error("Failed to switch network:", error);
}
}
}

Step 4: Connect to the Network

After switching networks, you can connect to the network and perform transactions. Here’s how to connect and display the current network.


async function connectProviderTo(network) {
if (typeof window.ethereum === 'undefined') {
console.log("Please install MetaMask!");
return;
}

const [address] = await window.ethereum.request({ method: 'eth_requestAccounts' });
await switchToNetwork(network);
console.log(`Connected to ${network.chainName} with address: ${address}`);
}

Conclusion

By following these steps, you can programmatically switch networks in MetaMask, enhancing the user experience of your decentralized application (DApp). Make sure to handle errors gracefully and provide feedback to users.