Skip to content

Instantly share code, notes, and snippets.

@httpJunkie
Last active July 15, 2022 16:17
Show Gist options
  • Save httpJunkie/a056c0f120c5916b637498de61f6117a to your computer and use it in GitHub Desktop.
Save httpJunkie/a056c0f120c5916b637498de61f6117a to your computer and use it in GitHub Desktop.
Switch and or Add a network in MetaMask
try {
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0xf00' }],
});
} catch (switchError) {
// This error code indicates that the chain has not been added to MetaMask.
if (switchError.code === 4902 || switchError?.data?.orginalError?.code === 4902) {
try {
await ethereum.request({
method: 'wallet_addEthereumChain',
params: [
{
chainId: '0xf00',
chainName: '...',
rpcUrls: ['https://...'] /* ... */,
},
],
});
} catch (addError) {
// handle "add" error
}
}
// handle other "switch" errors
}
@httpJunkie
Copy link
Author

We are working on getting a fix in so that we can suggest removing the || switchError?.data?.orginalError?.code === 4902 this is a known bug but currently is required to ensure it will work on mobile. If you add this OR statement, it should not break once we fix it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment