Skip to content

Instantly share code, notes, and snippets.

@o-az
Last active December 16, 2021 18:30
Show Gist options
  • Save o-az/7747508487caa60b3ec9fcc967ad8742 to your computer and use it in GitHub Desktop.
Save o-az/7747508487caa60b3ec9fcc967ad8742 to your computer and use it in GitHub Desktop.
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