Last active
July 15, 2022 16:17
-
-
Save httpJunkie/a056c0f120c5916b637498de61f6117a to your computer and use it in GitHub Desktop.
Switch and or Add a network in 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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.