连接浏览器插件钱包

切换网络#

wallet_switchEthereumChain

EIP-3326
此方法由 EIP-3326 指定。

描述

此方法询问用户是否要切换到具有指定 chainId 的链上,并返回一个确认值。

与任何确认值出现的场景一样,wallet_switchEthereumChain 只能作为直接用户操作的结果调用,例如用户单击按钮的时候。

欧易会在以下情况下自动拒绝请求:

  • 链 ID 格式错误
  • 指定链 ID 所属的链尚未添加到欧易

我们建议你与 wallet_addEthereumChain 一起使用:

try {
  await okxwallet.request({
    method: 'wallet_switchEthereumChain',
    params: [{ chainId: '0xf00' }],
  });
} catch (switchError) {
  // This error code indicates that the chain has not been added to OKX.
  if (switchError.code === 4902) {
    try {
      await okxwallet.request({
        method: 'wallet_addEthereumChain',
        params: [
          {
            chainId: '0xf00',
            chainName: '...',
            rpcUrls: ['https://...'] /* ... */,
          },
        ],
      });
    } catch (addError) {
      // handle "add" error
    }
  }
  // handle other "switch" errors
}

参数

  • Array

    SwitchEthereumChainParameter

interface SwitchEthereumChainParameter {
  chainId: string; // A 0x-prefixed hexadecimal string
}

链 IDs

这些是欧易默认支持的以太坊链的 ID。 更多信息请咨询 chainid.network

十六进制十进制网络
0x11Ethereum Main Network (Mainnet)
0x271110001ETHW
0x4266OKT Chain Mainnet
0x3856Binance Smart Chain Mainnet
0x89137Matic Mainnet
0xa86a43114Avax Mainnet
0xfa250Fantom Mainnet
0xa4b142161Arbitrum Mainnet
0xa10Optimism Mainnet
0x1925Cronos Mainnet
0x20198217Klaytn Mainnet
0x141321KCC Mainnet
0x4401088Metis Mainnet
0x120288Boba Mainnet
0x64100Gnosis Mainnet
0x5051285Moonriver Mainnet
0x5041284Moonbeam Mainnet
0x4061030Conflux eSpace

返回值

null - 如果此方法请求成功,该方法会返回 null,否则将会返回一个错误值。

如果错误码(error.code)为 4902,说明请求的链没有被欧易添加,另需要通过 wallet_addEthereumChain 请求添加。

例子

codeopen中打开。

HTML
JavaScript
<button class="connectEthereumButton btn">Connect Ethereum</button>
<button class="switchChainButton btn">Switch Chain</button>
const connectEthereumButton = document.querySelector('.connectEthereumButton');
const switchChainButton = document.querySelector('.switchChainButton');

let accounts = [];

//Sending Ethereum to an address
switchChainButton.addEventListener('click', () => {
  try {
    const chainId = okxwallet.chainId === "0x42" ? "0x38" : "0x42";
    await okxwallet.request({
      method: "wallet_switchEthereumChain",
      params: [{ chainId: chainId }]
    });
  } catch (switchError) {
    // This error code indicates that the chain has not been added to OKX Wallet.
    if (error.code === 4902) {
      try {
        await okxwallet.request({
          method: "wallet_addEthereumChain",
          params: [{ chainId: "0xf00", rpcUrl: "https://..." /* ... */ }]
        });
      } catch (addError) {
        // handle "add" error
      }
    }
    // handle other "switch" errors
  }
});

connectEthereumButton.addEventListener('click', () => {
  getAccount();
});

async function getAccount() {
  try{
    accounts = await okxwallet.request({ method: 'eth_requestAccounts' });
  }catch(error){
    console.log(error);
  }
}