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

WalletConnect每次连接生成新配对:如何仅保留单个配对?

解决WalletConnect重复生成配对的问题

你的核心问题在于手动管理配对(Pairing)和会话(Session)的逻辑有误,没有利用UniversalProvider内置的存储机制来复用已有的配对,导致每次连接都创建新配对。以下是正确的处理方式:

问题根源

WalletConnect中,配对是持久化的双向连接关系,会话是基于配对的临时交互会话。你之前手动存储topic但没有让Provider加载已有的配对上下文,且断开会话时的处理逻辑不符合规范,导致无法复用旧配对。

正确实现步骤

1. 初始化Provider时启用内置存储

UniversalProvider本身支持自动管理配对和会话的持久化,无需手动存储topic或session。初始化时配置storageOptions让它使用localStorage:

import UniversalProvider from "@walletconnect/universal-provider";

const ethereumProvider = await UniversalProvider.init({
  projectId: projectId,
  storageOptions: {
    database: window.localStorage // 让Provider自动存储配对、会话数据
  }
});

2. 连接时优先复用已有配对/会话

用户再次访问时,先检查是否有已保留的会话或配对,避免重复创建:

// 优先恢复已有会话
const existingSession = ethereumProvider.session;
if (existingSession) {
  // 会话已存在,直接使用即可
  console.log("已恢复会话:", existingSession);
} else {
  // 检查是否有已有的配对
  const pairings = await ethereumProvider.pairing.getPairings();
  if (pairings.length > 0) {
    // 使用已有的配对创建新会话
    const requiredNamespaces = {
      namespaces: {
        eip155: {
          methods: [
            "eth_sendTransaction",
            "eth_signTransaction",
            "eth_sign",
            "personal_sign",
            "eth_signTypedData",
          ],
          chains: [chainId],
          events: ["chainChanged", "accountsChanged"],
        }
      },
      pairingTopic: pairings[0].topic // 指定已有的配对topic
    };
    const session = await ethereumProvider.connect(requiredNamespaces);
  } else {
    // 无配对时创建新连接(首次访问场景)
    const requiredNamespaces = {
      namespaces: {
        eip155: {
          methods: [
            "eth_sendTransaction",
            "eth_signTransaction",
            "eth_sign",
            "personal_sign",
            "eth_signTypedData",
          ],
          chains: [chainId],
          events: ["chainChanged", "accountsChanged"],
        }
      }
    };
    const session = await ethereumProvider.connect(requiredNamespaces);
  }
}

3. 断开会话的规范处理

断开会话时只需调用disconnect并传入合法原因,无需手动删除本地存储的session,Provider会自动更新存储状态,同时保留配对以便后续复用:

await ethereumProvider.disconnect({
  reason: {
    code: 1000,
    message: "用户主动断开连接"
  }
});
// 无需手动删除session或保留topic,Provider会自动管理

关键注意事项

  • 不要手动存储配对topic或session,依赖Provider的内置存储即可,否则会出现上下文不一致的问题。
  • 配对是双向的,如果用户在钱包中删除了配对,dapp这边无法复用,此时需要重新创建配对。
  • 确保使用的WalletConnect SDK版本是最新的,旧版本可能存在配对复用的bug。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:37:49