In Web3, Almost Every Dapps were connected to a Particular Network. For Example, Beginners and Learning based projects are mostly connected to a Test Network.
When a Transaction triggered by the user, the Metamask will be connected and Perform the Transaction.In this, the user needs to manually Switch to a Particular Network to perform the Transaction.
Suppose, if the user is new to web3, he doesn't know! What network he need to switch.
So for that Coming up with the solution. Switch Network/chain in Metamask.
Here is a JavaScript Program to Switch from one Network or chain to other:
const SwitchNetwork = async (_chainId) => {
let chainId = _chainId;
await window.ethereum
.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: chainId }],
})
.then(() => console.log("Successfully! Connected to the requested Network"))
.catch((err) => {
if (err.message.startsWith("Unrecognized chain ID")) {
addNewNetwork();
}
});
};
From the above in catch() block, you can find addNetwork(). This will help the user to add Automatically connected to the Network,Which doesn't exist in his Metamask.
To know addNetwork(), Follow this!
https://dev.to/0x24karthick/how-to-add-custom-network-in-metamask-using-windowethereum-3mg
Happy Coding!
Top comments (0)