You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过@walletconnect/react-native-dapp获取MetaMask当前连接ChainID

通过@walletconnect/react-native-dapp获取MetaMask当前ChainID

可以通过该包实现获取ChainID的需求,以下是两种实用方案:

1. 直接调用以太坊RPC方法eth_chainId

利用WalletConnect的connector实例发送RPC请求,直接获取当前钱包的ChainID:

const getCurrentChainId = async () => {
  try {
    // 请求返回的是十六进制字符串
    const hexChainId = await connector.request({ method: 'eth_chainId' });
    // 转为十进制数值使用
    const decimalChainId = parseInt(hexChainId, 16);
    console.log('当前钱包ChainID:', decimalChainId);
    return decimalChainId;
  } catch (err) {
    console.error('获取ChainID失败:', err);
    return null;
  }
};

2. 从连接会话或事件监听中获取

  • 连接成功时直接获取:调用connector.connect()返回的会话对象包含chainId字段
  • 监听网络切换:通过chainChanged事件实时捕获网络变更

代码示例:

// 连接钱包时获取初始ChainID
const connectWallet = async () => {
  const session = await connector.connect();
  console.log('钱包连接成功,当前ChainID:', session.chainId);
};

// 监听网络切换事件
connector.on('chainChanged', (hexChainId) => {
  const newChainId = parseInt(hexChainId, 16);
  console.log('钱包网络已切换,新ChainID:', newChainId);
  // 这里可以加入网络切换后的业务逻辑,比如提示用户或重新加载数据
});

结合你的交易代码使用

建议在执行交易前先校验ChainID,避免在错误网络上发起交易:

try {
  // 先获取并校验ChainID
  const currentChainId = await getCurrentChainId();
  // 示例:假设预期ChainID为以太坊主网(1)
  const targetChainId = 1;
  if (currentChainId !== targetChainId) {
    Toast.show({
      autoHide: true,
      text1: '请切换到以太坊主网',
      type: 'error',
    });
    return;
  }

  // 原交易代码
  let dataa = await contract.methods
    .transfer(toAddress, value.toString())
    .encodeABI();
  let txObj = {
    data: Web3js.utils.toHex(dataa),
    from: userWallet,
    to: POZ_TOKEN, // Contractor token address
  };
  const transactionHash = await connector
    .sendTransaction(txObj)
    .catch((_err: any) => {
      Toast.show({
        autoHide: true,
        text1: t('topUpPoz.transactionFailed'),
        type: 'error',
      });
    });
  console.log('transactionHash is =', transactionHash);
} catch (err) {
  console.error('交易流程出错:', err);
}

内容的提问来源于stack exchange,提问作者Pankaj Sonava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 21:20:59