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

如何在Hardhat脚本中从命令行读取RSK网络代币地址

实现Hardhat脚本通过命令行指定代币地址查询余额

完全可以实现,只需修改脚本代码解析命令行传入的--token参数,具体方案如下:

修改后的脚本代码

async function main() {
  // 解析命令行中的--token参数
  const tokenArgIndex = process.argv.indexOf('--token');
  let rifTokenAddress;

  if (tokenArgIndex !== -1 && tokenArgIndex + 1 < process.argv.length) {
    rifTokenAddress = process.argv[tokenArgIndex + 1];
  } else {
    // 可选:设置默认代币地址,避免无参数时出错
    rifTokenAddress = '0x2aCc95758f8b5F583470bA265Eb685a8f45fC9D5';
    console.log('未指定--token参数,使用默认RIF地址:', rifTokenAddress);
  }

  // 验证地址格式(可选但推荐)
  if (!ethers.utils.isAddress(rifTokenAddress)) {
    throw new Error('传入的代币地址格式无效');
  }

  const erc20 = await ethers.getContractAt(
    ['function balanceOf(address owner) view returns (uint)'],
    rifTokenAddress.toLowerCase(),
  );
  const walletAddress = (await ethers.getSigner(0)).address;
  const rifBalance = await erc20.balanceOf(walletAddress);
  console.log(`钱包 ${walletAddress} 的代币余额: ${ethers.utils.formatEther(rifBalance)}`);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

关键修改说明

  • 通过process.argv遍历命令行参数,定位--token的位置并提取后续的地址值
  • 添加地址格式验证,避免传入无效地址导致脚本报错
  • 可选设置默认代币地址,保证未传参数时脚本也能正常运行
  • 优化日志输出,明确显示钱包地址和对应的余额信息

运行命令

直接使用你期望的命令执行即可:

npx hardhat run scripts/balances.js --network rskmainnet --token 0x2d919f19D4892381d58EdEbEcA66D5642ceF1A1F

若不指定--token参数,脚本会自动使用默认的RIF地址执行查询。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 19:20:30