如何用Polkadot.js API检查Collator意图并兼容Validator校验代码
用@polkadotjs/api同时监控Collator和Validator的参选意图
你之前的代码仅适配Polkadot/Kusama等中继链的Validator(依赖staking模块),而Collator属于Parachain的节点角色,对应的存储模块和逻辑完全不同,直接复用会返回undefined。以下是修改后的代码,可同时支持两种节点类型:
修改要点
- 新增参数指定节点类型(
validator/collator),区分处理逻辑 - 针对Collator,使用Parachain对应的存储模块(主流用
parachainStaking,部分链用collatorSelection) - 统一判断参选意图的逻辑,适配两种节点的绑定规则
完整代码
const { WsProvider, ApiPromise } = require('@polkadot/api'); async function checkNodeIntent(url, address, nodeType = 'validator') { try { // 连接节点API const provider = new WsProvider(url); const api = await ApiPromise.create({ provider }); let hasIntent = false; let commission = '0'; if (nodeType === 'validator') { // 中继链Validator逻辑(复用原代码核心逻辑) const validator = await api.query.staking.validators(address); const stashAccount = await api.query.staking.bonded(address); hasIntent = !!stashAccount && !stashAccount.isEmpty; commission = validator.commission.toString(); } else if (nodeType === 'collator') { // Parachain Collator逻辑(以主流的parachainStaking模块为例) const collatorInfo = await api.query.parachainStaking.collators(address); const stashAccount = await api.query.parachainStaking.bonded(address); // 存在Collator信息且绑定了Stash账户,视为有参选意图 hasIntent = !!collatorInfo && !collatorInfo.isEmpty && !!stashAccount && !stashAccount.isEmpty; // 提取佣金(不同链的结构可能略有差异,需根据目标链调整) commission = collatorInfo?.commission?.toString() || '0'; // 若目标链使用collatorSelection模块,替换为以下逻辑: // const candidates = await api.query.collatorSelection.candidates(); // const targetCandidate = candidates.find(c => c.accountId.toString() === address); // const stash = await api.query.collatorSelection.stash(address); // hasIntent = !!targetCandidate && !!stash && !stash.isEmpty; // commission = targetCandidate?.commission.toString() || '0'; } // 计算百分比(Polkadot生态佣金精度为1e7) const commissionPercent = commission / Math.pow(10, 7); if (!hasIntent || commission === '0') { console.log(`${nodeType === 'validator' ? 'Validator' : 'Collator'} ${address} 无参选意图!`); } else { console.log(`${nodeType === 'validator' ? 'Validator' : 'Collator'} ${address} 有参选意图,佣金为 ${commissionPercent}%`); } // 断开连接 await provider.disconnect(); } catch (error) { console.error('查询失败:', error); } } // 调用示例 // checkNodeIntent('wss://rpc.polkadot.io', '你的Validator地址', 'validator'); // checkNodeIntent('wss://rpc.moonbeam.network', '你的Collator地址', 'collator');
注意事项
- 不同Parachain的Collator管理模块可能不同:比如Moonbeam、Astar使用
parachainStaking,部分自定义链可能使用collatorSelection,需根据目标链的实际模块调整代码。 - 确保API实例加载了目标链的类型定义,避免出现存储项找不到的错误。
- 调用函数时需明确指定节点类型,或根据链的特性扩展逻辑实现自动检测。
内容的提问来源于stack exchange,提问作者Salisu Bako
相关产品推荐
相关产品推荐

