我正在使用此方法将带有自定义 rpc 的自定义网络添加到我的元掩码中:
async function addMaticNetwork() {
try {
// Check if the Matic network RPC URL is already added
await window.ethereum.request({
method: "wallet_addEthereumChain",
params: [
{
chainId: "0x89",
rpcUrls: [
"https://polygon-mainnet.g.alchemy.com/v2/KEY",
],
chainName: "Matic Mainnet",
nativeCurrency: {
name: "MATIC",
symbol: "MATIC",
decimals: 18,
},
blockExplorerUrls: ["https://polygonscan.com/"],
},
],
});
} catch (error) {
console.log(error);
}
}
问题是,即使网络存在,函数也总是被调用,因此它会打开 Metamask 弹出窗口来安装网络,而不是切换到网络。所以我想通过它的 RPC 而不是 id 检查这个网络是否存在,因为我可以有另一个具有相同 id 的网络。 谢谢你
您可以使用
wallet_switchEthereumChain
方法。如果您尝试更改的网络不存在,此方法将失败,然后您可以将其添加到钱包中。