如何通过代码在MetaMask中自动添加并切换至Rootstock网络?
解决方案
当然可以实现!MetaMask支持通过EIP-3085(wallet_addEthereumChain)和EIP-1193规范的API自动添加并切换网络,无需用户手动复制配置。以下是完整的实现方案:
1. 定义Rootstock网络配置
先整理好Rootstock主网和测试网的官方参数:
// Rootstock主网配置 const ROOTSTOCK_MAINNET = { chainId: '0x1E', // 对应十进制30 chainName: 'Rootstock Mainnet', nativeCurrency: { name: 'Rootstock Bitcoin', symbol: 'RBTC', decimals: 18 }, rpcUrls: ['https://public-node.rsk.co'], blockExplorerUrls: ['https://explorer.rsk.co/'] }; // Rootstock测试网配置 const ROOTSTOCK_TESTNET = { chainId: '0x1F', // 对应十进制31 chainName: 'Rootstock Testnet', nativeCurrency: { name: 'Testnet Rootstock Bitcoin', symbol: 'tRBTC', decimals: 18 }, rpcUrls: ['https://public-node.testnet.rsk.co'], blockExplorerUrls: ['https://explorer.testnet.rsk.co/'] };
2. 完整连接与网络切换代码
修改你的点击事件逻辑,先尝试切换网络,若网络未添加则自动触发添加请求:
document.getElementById('connect-to-metamask-button').addEventListener('click', async () => { try { // 第一步:请求连接MetaMask账户 await window.ethereum.request({ method: 'eth_requestAccounts' }); // 第二步:尝试切换到目标网络(这里以主网为例,测试网替换为ROOTSTOCK_TESTNET即可) await window.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: ROOTSTOCK_MAINNET.chainId }] }); } catch (switchError) { // 错误码4902表示当前钱包未添加该网络,触发添加流程 if (switchError.code === 4902) { try { // 请求用户添加Rootstock网络 await window.ethereum.request({ method: 'wallet_addEthereumChain', params: [ROOTSTOCK_MAINNET] }); // 添加成功后再次切换网络 await window.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: ROOTSTOCK_MAINNET.chainId }] }); } catch (addError) { // 用户拒绝添加网络或其他异常 console.error('添加/切换网络失败:', addError); alert('请手动添加Rootstock网络以继续使用DApp'); } } else { // 其他切换失败场景(如用户拒绝切换) console.error('切换网络失败:', switchError); } } });
关键注意事项
- 确保用户MetaMask版本≥10.0.0,旧版本不支持
wallet_addEthereumChain和wallet_switchEthereumChainAPI - 所有网络操作都会触发MetaMask弹窗,需要用户手动确认授权
- 可根据业务需求自由切换主网/测试网配置,只需替换对应的常量即可
内容的提问来源于stack exchange,提问作者Jeremy Then
相关产品推荐
相关产品推荐

