Back

blockchain - metamask 自动切换网络

发布时间: 2022-08-03 00:56:00

refer to:
https://docs.metamask.io/guide/rpc-api.html#unrestricted-methods

1. switchEthereumChain 只能切换内置网络

2. addEthereumChain 用来新增外部网络,并且切换。(不能用于内置网络)

下面是完整代码 (记得替换里面的erb tag)

    window.onload = async function(){
      if(window.ethereum) {
        window.ethereum.request({method: 'eth_requestAccounts'})
        let network_id = <%= @contract.network.chain_id rescue 0 %>

        // 对于内置网络,直接切换
        if([1,3,4,5,42].includes(network_id)) {
          await ethereum.request({
            method: 'wallet_switchEthereumChain',
            params: [{ chainId: "0x" + network_id.toString(16) }]
          })

        // 否则就添加
        }else{
          await window.ethereum.request({
            method: 'wallet_addEthereumChain',
              params: [{
                chainId: '0x<%= @contract.network.try(:chain_id).to_s(16) %>',
                chainName: "<%= @contract.network.try(:name) %>",
                nativeCurrency: {
                  name: "<%= @contract.network.try(:native_currency_name) %>",
                  symbol: "<%= @contract.network.try(:native_currency_symbol) %>",
                  decimals: <%= @contract.network.try(:native_currency_decimals) %>
                },
                rpcUrls: ['<%= @contract.network.try(:rpc_server) %>'],
              }]
          })
        }
      }
    }

Back