使用此方法,应用程序将侦听链变化:
ethereum.on('chainChanged', (chainId) => {
})
但是如果用户要去的链还没有添加到元掩码中,它会抛出:
inpage.js:1 MetaMask - RPC Error: Unrecognized chain ID "0x89".
Try adding the chain using wallet_addEthereumChain first. Object
当然,有一种方法可以添加一个新的链到元掩码,但是如何捕获这个元掩码错误?尝试在以太坊之外捕获。在给什么谢谢!
为元掩码网络写一个映射:
const NETWORKS = {
1: "Ethereum Main Network",
3: "Ropsten Test Network",
4: "Rinkeby Test Network",
5: "Goerli Test Network",
42: "Kovan Test Network",
56: "Binance Smart Chain",
1337: "Ganache",
};
const getChainId= async () => {
const chainId = await web3.eth.getChainId();
// handle the error here
if (!chainId) {
throw new Error(
"Cannot retrieve an account. Please refresh the browser"
);
}
return NETWORKS[chainId];
}
);
对我来说最简单的方法似乎是在切换之前先添加链,在成功添加Metamask后将要求用户切换到新添加的网络,这里添加BSC网络的示例代码:
export async function addBSCToMetamask() {
if (typeof window !== 'undefined') {
window.ethereum.request({
jsonrpc: '2.0',
method: 'wallet_addEthereumChain',
params: [
{
chainId: '0x38',
chainName: 'Binance Smart Chain Mainnet',
rpcUrls: ['https://bsc-dataseed.binance.org/'],
nativeCurrency: {
name: 'BNB',
symbol: 'BNB',
decimals: 18
},
blockExplorerUrls: ['https://bscscan.com']
}
],
id: 0
})
}
}