首页 > 解决方案 > 将 Metamask 网络切换到链 1(以太坊主网)

问题描述

上周 Metamask 引入了一个名为“wallet_addEthereumChain”的新功能,允许用户在收到提示时自动将新的 Etheruem RPC 添加到他们的钱包中。此功能还允许用户更改他们连接的网络,例如,如果我已经将 Binance Smart Chain 连接到 metamask,则调用 wallet_addEthereumChain 会将活动网络更改为 BSC。但是,在以太坊链上尝试此操作时,会出现无法添加主网 RPC 的错误。我使用以下代码将以太坊主网更改为币安智能链,并且运行良好:switchToBinance: async function () {

        let ethereum = window.ethereum;
        const data = [{
            chainId: '0x38',
            chainName: 'Binance Smart Chain',
            nativeCurrency:
                {
                    name: 'BNB',
                    symbol: 'BNB',
                    decimals: 18
                },
            rpcUrls: ['https://bsc-dataseed.binance.org/'],
            blockExplorerUrls: ['https://bscscan.com/'],
        }]
        /* eslint-disable */
        const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:data}).catch()
        if (tx) {
            console.log(tx)
        }
    },

但是,当我尝试 Exact 时,metamask 会抛出异常,说我无法添加主网 RPC:switchToEthereum: async function () {

        let ethereum = window.ethereum;
        const data = [{
      chainId: '0x1',
      chainName: 'Ethereum',
      nativeCurrency: {
        name: 'Ethereum',
        symbol: 'ETH',
        decimals: 18,
      },
      rpcUrls: ['https://mainnet.infura.io/v3/undefined'],
      blockExplorerUrls: ['https://etherscan.io'],
    }]
        /* eslint-disable */
        const tx = await ethereum.request({method: 'wallet_addEthereumChain', params:data}).catch()
        if (tx) {
            console.log(tx)
        }
    },

但是,添加新的 RPC 连接和更改活动的 RPC 连接的请求是相同的。那么有没有办法将活跃的以太坊提供商从自定义链更改为主网(链 ID-1)

标签: ethereumweb3metamask

解决方案


作为这个问题评论点,出于安全原因wallet_addEthereumChain不支持主网。但是有一个新的 EIP 可以解决这个问题,请按照EIP-3326查找发布信息,并讨论以查看草案进度。


推荐阅读