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

求助:如何将web3-react与WalletConnect V1迁移至WalletConnect V2?

迁移web3-react WalletConnect V1到V2的可行方案

原环境依赖

  • @web3-react/core: ^6.1.9
  • @web3-react/walletconnect-connector: ^6.2.13

原代码片段

connector.js

import { WalletConnectConnector } from "@web3-react/walletconnect-connector";

export const WalletConnect = new WalletConnectConnector({
  rpcUrl: `${process.env.REACT_APP_INFURA}`,
  bridge: "https://bridge.walletconnect.org",
  qrcode: true,
  supportedChainIds: [1],
});

walletconnect.js

import { useWeb3React } from "@web3-react/core";
import { WalletConnect } from "../../../lib/connectors";

const { activate } = useWeb3React();

async function connectWalletHandler() {
    const provider = WalletConnect;
    }
    try {
      await activate(provider);
    } catch (error) {
      console.log(error);
    }
  }

迁移步骤

  1. 安装V2专用连接器包
    卸载旧的V1连接器,安装V2版本:

    npm uninstall @web3-react/walletconnect-connector
    npm install @web3-react/walletconnect-v2-connector
    

    或使用yarn:

    yarn remove @web3-react/walletconnect-connector
    yarn add @web3-react/walletconnect-v2-connector
    
  2. 重构connector.js配置
    V2要求使用Project ID(需前往WalletConnect控制台申请),移除原有的bridge参数,改用projectId、chains和rpcMap配置:

    import { WalletConnectV2Connector } from "@web3-react/walletconnect-v2-connector";
    
    // 从环境变量读取Project ID,需提前申请
    const PROJECT_ID = process.env.REACT_APP_WALLETCONNECT_PROJECT_ID;
    
    export const WalletConnect = new WalletConnectV2Connector({
      projectId: PROJECT_ID,
      chains: [1], // 支持的链ID集合,示例为以太坊主网
      showQrModal: true, // 替代原V1的qrcode参数
      rpcMap: {
        1: process.env.REACT_APP_INFURA // 对应链ID的RPC地址
      }
    });
    
  3. 调整连接逻辑
    连接逻辑基本沿用原有结构,注意直接使用新的Connector实例即可:

    import { useWeb3React } from "@web3-react/core";
    import { WalletConnect } from "../../../lib/connectors";
    
    const { activate } = useWeb3React();
    
    async function connectWalletHandler() {
      try {
        await activate(WalletConnect);
      } catch (error) {
        console.error("WalletConnect连接失败:", error);
      }
    }
    

关键注意事项

  • 必须申请Project ID:V2不再依赖公共bridge,所有Dapp需使用自己的Project ID,可在WalletConnect官方控制台免费申请
  • 配置参数变更:supportedChainIds替换为chains,rpcUrl替换为rpcMap(支持多链时可配置多个链的RPC地址)
  • 多链支持扩展:如需支持其他链,只需在chains数组添加对应链ID,并在rpcMap中补充对应RPC地址即可
  • 版本兼容性:当前使用的@web3-react/core@6.1.9完全兼容@web3-react/walletconnect-v2-connector,无需升级core包

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 14:16:24