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

在beforeEach中调用hardhat_reset重置Polygon主网分叉时遇参数错误

解决Hardhat beforeEach中hardhat_reset的分叉错误

错误核心原因

报错提示jsonRpcUrl: string为undefined,主要是两个问题:

  • 你代码里的apiKey变量可能未正确赋值(比如未从环境变量读取、拼写错误),导致拼接后的分叉URL无效
  • 调用hardhat_reset时,forking配置的字段名写错了——正确字段是jsonRpcUrl,不是你用的url

修复方案

方案1:修正hardhat_reset的参数字段名

直接修改beforeEach里的调用代码,把url改成jsonRpcUrl,同时确保apiKey有效:

beforeEach(async () => {
  // 先验证apiKey是否存在,避免拼接出无效URL
  if (!apiKey) {
    throw new Error("请正确配置Alchemy API Key");
  }
  
  await network.provider.request({
    method: "hardhat_reset",
    params: [{
      forking: {
        jsonRpcUrl: `https://polygon-mainnet.g.alchemy.com/v2/${apiKey}`,
        blockNumber: 31911877
      }
    }]
  })
  
  const wallets = waffle.provider.getWallets()
  wallet = wallets[0]
  await deployContract()
})

方案2:改用官方封装的reset函数(更简洁)

使用@nomicfoundation/hardhat-network-helpers提供的reset函数,避免手动拼参数出错:

beforeEach(async () => {
  if (!apiKey) {
    throw new Error("请正确配置Alchemy API Key");
  }
  
  // 直接传入URL和区块号即可
  await helpers.reset(
    `https://polygon-mainnet.g.alchemy.com/v2/${apiKey}`,
    31911877
  )
  
  const wallets = waffle.provider.getWallets()
  wallet = wallets[0]
  await deployContract()
})

额外验证步骤

  • 在测试文件顶部添加apiKey的加载逻辑,确保从环境变量读取:
    require("dotenv").config();
    const apiKey = process.env.ALCHEMY_POLYGON_API_KEY;
    
  • 运行测试前打印apiKey和拼接后的URL,确认不是undefined

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 13:39:40