React-Native钱包中Wallet Connect V2如何仅连接部分链?
问题解决:Wallet Connect V2 仅连接指定链的实现方案
你遇到的错误核心原因是传入了无效的账户格式,并且错误保留了不需要连接的链的条目。Wallet Connect V2 要求账户必须是链标识:钱包地址的有效格式,不允许空地址的账户项(比如${chain}:这种写法)。以下是修正后的实现方案:
修正思路
- 过滤掉不需要连接的链,只保留你想连接的链(
availableNetwork?.isConnect为true的条目) - 仅为保留的链生成有效格式的账户字符串
- 避免添加空的命名空间(namespace),如果某个命名空间下没有要连接的链,直接跳过
修正后的代码
const { id, params } = this.proposal; const { requiredNamespaces, relays } = params; const namespaces: SessionTypes.Namespaces = {}; Object.keys(requiredNamespaces).forEach(key => { // 过滤出用户允许连接的链 const allowedChains = requiredNamespaces[key].chains?.filter(chain => { const availableNetwork = availableNetworkList.find( ({ chainId }) => chainId === this.getEIP155ChainId(chain), ); return availableNetwork?.isConnect; }) || []; // 生成符合规范的账户数组 const accounts = allowedChains.map(chain => `${chain}:${this.currentETHAddress}`); // 仅当有有效账户时,才添加该命名空间 if (accounts.length > 0) { namespaces[key] = { accounts, methods: requiredNamespaces[key].methods, events: requiredNamespaces[key].events, }; } }); // 处理无有效链的情况:拒绝会话请求 if (Object.keys(namespaces).length === 0) { await this.web3wallet.rejectSession({ id, reason: { code: 5001, message: "用户拒绝部分链的连接请求" } }); } else { // 批准会话,仅连接指定的链 await this.web3wallet.approveSession({ id, relayProtocol: relays[0].protocol, namespaces, }); }
关键说明
- 移除了
${chain}:这种无效的空地址写法,确保所有账户条目都是符合Wallet Connect规范的有效格式 - 通过
filter而非map过滤不需要的链,避免生成无效条目 - 增加了空命名空间的判断,防止因无有效链而触发批准会话的错误
内容的提问来源于stack exchange,提问作者noheadthink
相关产品推荐
相关产品推荐

