Metamask: How to change the network configuration by code
User experience is one of the main challenges of any blockchain-based app. Generate keypairs, keep them safe, call smart function transactions, all of this are far from familiar tasks for most people.
This is a huge challenge, but I hope this article helps a little. One of the most popular Ethereum wallets is Metamask: it’s realiable, it’s simple, it’s wide adopted, and the animated fox is quite cute…
Metamask was designed primary for Ethereum usage. So, it came with Ethereum Mainnet, and some testnet preconfigured to help users work in the Mainnet and play around with the testnets.
Many Ethereum based networks are available now. For use them with Metamask, the user must enter some params to configure the wallet to enable this network. This isn’t a very hard task, but it makes the experience even more weird for novice users.
The following code can help DAPPS devs to make this connection more user friendly. I’m not a React expert, so please forgive any imprecision and error the may content: I’m just trying to explain the idea.
if(window.ethereum) {
window.web3 = new Web3(window.ethereum)
window.ethereum.request({method: 'eth_requestAccounts'})
window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{chainId: '0xa869',
chainName: "Fuji Testnet",
nativeCurrency: {
name: "AVAX",
symbol: "AVAX",
decimals: 18
},
rpcUrls: ['https://api.avax-test.network/ext/bc/C/rpc'], blockExplorerUrls: ['https://cchain.explorer.avax-test.network/']
}]
})
}
By calling this code, Metamask will ask the user to switch the network to Avalanche Fuji Testnet, and will create the network configuration if the user hasn’t previously done.
Here’s a Github repo of the code
Here’s a running demo of the app