How to Add Custom Network (BNB) in MetaMask Using web3

metamasknetworkidweb3js

I am trying to add Binance Main and test net Network through web3 js. I don't want that user to setup it manually. Did you guys any idea about that how to handle it?

Best Answer

Use wallet_addEthereumChain method - https://docs.metamask.io/guide/rpc-api.html#other-rpc-methods

Example code:

window.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId: '0x38',
chainName: 'Binance Smart Chain',
nativeCurrency: {
    name: 'Binance Coin',
    symbol: 'BNB',
    decimals: 18
},
rpcUrls: ['https://bsc-dataseed.binance.org/'],
blockExplorerUrls: ['https://bscscan.com']
}]
})
.catch((error) => {
console.log(error)
})