Created
May 12, 2022 01:27
-
-
Save anistark/95f51e17638fd8d0ccf1d69955f85b32 to your computer and use it in GitHub Desktop.
Js snippet to auto-add IOTA Smart Contracts Evm to 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
// This is an example to auto detect if the current chain is ISC EVM Testnet and if not, switch to it. | |
// If chain doesn't exist on Metamask yet, this script will also add it. | |
// A metamask pop-up will appear and you can approve after verifying the details. | |
// This config can be set for any EVM compatible chain as such. | |
const chainName = 'ISC Testnet' | |
const chainId = 1074 // ISC EVM | |
const rpcUrl = 'https://evm.wasp.sc.iota.org' | |
const blockExplorerUrl = 'https://explorer.wasp.sc.iota.org' | |
const currency = 'EIOTA' | |
const decimal = 18 | |
async function networkSync() { | |
if (window.ethereum) { | |
console.log("Metamask detected..."); | |
// Check if current chain is the required chain | |
if (window.ethereum.networkVersion !== chainId) { | |
let hexParsedChainId = parseChainId(chainId); | |
try { | |
await window.ethereum.request({ | |
method: 'wallet_switchEthereumChain', | |
params: [ | |
{ | |
chainId: hexParsedChainId | |
} | |
] | |
}); | |
} catch (err) { | |
// console.log('err:', err); | |
// This error code indicates that the chain has not been added to MetaMask | |
if (err.code === 4902) { | |
// Add chain to Metamask | |
await window.ethereum.request({ | |
method: 'wallet_addEthereumChain', | |
params: [ | |
{ | |
chainName: chainName, | |
chainId: hexParsedChainId, | |
nativeCurrency: { | |
name: currency, | |
decimals: decimal, | |
symbol: currency | |
}, | |
rpcUrls: [rpcUrl], | |
blockExplorerUrls: [blockExplorerUrl] | |
} | |
] | |
}); | |
} | |
} | |
} | |
} else { | |
console.log("Metamask extensions not detected!"); | |
} | |
} | |
function parseChainId(chainId) { | |
let hexChainId = ethers.utils.hexlify(chainId); | |
// Trim any leading 0s | |
return '0x' + hexChainId.split('0x')[1].replace(/^0+/, ''); | |
} | |
networkSync(); // Call it on button click or on page load. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment