使用此方法,应用程序正在侦听链更改:
ethereum.on('chainChanged', (chainId) => {
})
但是如果用户要去的链尚未添加到元掩码中,则会抛出:
inpage.js:1 MetaMask - RPC Error: Unrecognized chain ID "0x89".
Try adding the chain using wallet_addEthereumChain first. Object
当然,有一种方法可以将新链添加到元掩码中,但是如何捕获这个元掩码错误呢?尝试在以太坊之外捕获。on 没有给出任何结果
谢谢!
为元掩码网络编写映射:
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
})
}
}
尝试添加超过 1 个 rpcUrl,这样如果某个 rpc 失败,可以尝试另一个。例如,对于 ETH 主网,我们可以有 4 个 RPC。像这样
{ 链ID:“0x1”, rpcUrls: [ “https://mainnet.infura.io/v3/”, “https://eth.llamarpc.com”, “https://eth-pokt.nodies.app”, “wss://ethereum.publicnode.com”, ], chainName: "以太坊主网", 本地货币:{ 名称:“ETH”, 符号:“ETH”, 小数位数:18, }, blockExplorerUrls: ["https://etherscan.io"], }