Last active
August 15, 2022 12:47
-
-
Save davidkathoh/b758520344d4bd29b20d22828e301b37 to your computer and use it in GitHub Desktop.
Swicthing and adding network programatically on metamask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function switchN(){ | |
const provider = window.ethereum; | |
const binanceTestChainId = '0x61'; | |
if(!provider){ | |
console.log("Metamask is not installed, please install!"); | |
}else{ | |
const chainId = await provider.request({ method: 'eth_chainId' }); | |
if(chainId === binanceTestChainId){ | |
console.log("Bravo!, you are on the correct network"); | |
}else{ | |
console.log("oulalal, switch to the correct network"); | |
try { | |
await provider.request({ | |
method: 'wallet_switchEthereumChain', | |
params: [{ chainId: binanceTestChainId}], | |
}); | |
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") | |
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', // 2-6 characters long | |
decimals: 18 | |
} | |
}], | |
}); | |
} catch (addError) { | |
// handle "add" error | |
console.log(addError); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment