React JS中通过RPC判断MetaMask是否已安装指定网络
解决方案
要实现通过RPC地址判断网络是否存在,再决定切换或添加,你可以借助MetaMask的wallet_getEthereumChains API获取用户已配置的所有网络,对比目标RPC后执行对应操作,代码示例如下:
async function addOrSwitchMaticNetwork() { const targetRpc = "https://polygon-mainnet.g.alchemy.com/v2/KEY"; const targetChainConfig = { chainId: "0x89", rpcUrls: [targetRpc], chainName: "Matic Mainnet", nativeCurrency: { name: "MATIC", symbol: "MATIC", decimals: 18, }, blockExplorerUrls: ["https://polygonscan.com/"], }; try { // 获取用户已添加的所有网络 const existingChains = await window.ethereum.request({ method: "wallet_getEthereumChains" }); // 检查目标RPC是否存在于已有的网络中 const targetChainExists = existingChains.some(chain => chain.rpcUrls.some(rpc => rpc === targetRpc) ); if (targetChainExists) { // 切换到目标网络 await window.ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId: targetChainConfig.chainId }] }); } else { // 添加新网络 await window.ethereum.request({ method: "wallet_addEthereumChain", params: [targetChainConfig] }); } } catch (error) { // 处理用户拒绝操作、网络不存在等错误 console.error("操作失败:", error); } }
关键说明
wallet_getEthereumChains:该API会返回用户MetaMask中已添加的所有链的完整配置,包含每个链的rpcUrls数组,我们可以通过对比其中的地址判断目标网络是否已存在。- 对比逻辑:使用
some方法遍历已有网络,只要某条链的RPC列表中包含目标RPC,就判定该网络已存在,直接执行切换操作。 - 错误处理:捕获切换或添加过程中的异常,比如用户点击拒绝、链ID格式错误等情况。
内容的提问来源于stack exchange,提问作者Ghost
相关产品推荐
相关产品推荐

