Last active
December 16, 2021 18:30
-
-
Save o-az/7747508487caa60b3ec9fcc967ad8742 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
declare const window: any | |
const chainIds: { | |
[chainId: string]: string | |
} = { | |
ethereum: '0x1', | |
bsc: '0x38', | |
} | |
const rpcUrls: { | |
[chainId: string]: string | |
} = { | |
ethereum: 'https://mainnet.infura.io/ocCdekUYwOyLn7h7OlJM', | |
bsc: 'https://bsc-dataseed.binance.org', | |
} | |
/** | |
* by default it switches to Ethereum. Update parameters for bsc or add more chainIds and rpcUrls for other networks. | |
* chainid has to be a hex string | |
*/ | |
// Tries to switch network first then if network is not added, it tries to add network | |
export const switchNetwork = async ( | |
hexChainId = chainIds.ethereum, | |
rpcUrl = rpcUrls.ethereum | |
) => { | |
const { ethereum } = window | |
if (!ethereum) return | |
try { | |
await window?.ethereum?.request({ | |
method: 'wallet_switchEthereumChain', | |
params: [{ chainId: hexChainId }], | |
}) | |
} catch (error) { | |
if ((error as any).code !== 4902) return | |
try { | |
await window.ethereum.request({ | |
method: 'wallet_addEthereumChain', | |
params: [ | |
{ | |
chainId: hexChainId, | |
rpcUrl, | |
}, | |
], | |
}) | |
} catch (error) { | |
console.error(error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment