使用Hardhat 2.22.2主网分叉测试时遇429错误的求助
Hardhat主网分叉测试429请求超限错误解决方案
遇到的错误信息:
[Error: The response reported error `429`: `Your app has exceeded its compute units per second capacity. If you have retries enabled, you can safely ignore this message. If not, check out https://docs.alchemy.com/reference/throughput`. (optional data: None). Request: [{"id":8,"jsonrpc":"2.0","method":"eth_getBalance","params":["0x90f79bf6eb2c4f870365e785982e1f101e93b906","0x12bb9c5"]},{"id":9,"jsonrpc":"2.0","method":"eth_getTransactionCount","params":["0x90f79bf6eb2c4f870365e785982e1f101e93b906","0x12bb9c5"]},{"id":10,"jsonrpc":"2.0","method":"eth_getCode","params":["0x90f79bf6eb2c4f870365e785982e1f101e93b906","0x12bb9c5"]}]] { code: 'GenericFailure' }
这个错误是因为Alchemy的API请求超出了每秒计算单元(CU)的限流阈值,重试后恢复是因为限流会在短时间内自动解除。以下是几种解决办法:
开启Hardhat自动重试
在hardhat.config.js的forking配置中添加重试参数,让Hardhat自动处理超限请求:module.exports = { networks: { hardhat: { forking: { url: "你的Alchemy RPC地址", timeout: 10000, retries: 3, // 重试次数 retryInterval: 1000 // 每次重试间隔(毫秒) } } } };优化请求频率
减少批量请求的数量,或者在测试代码中添加延迟,避免短时间内发送大量请求。比如在测试步骤之间插入:await new Promise(resolve => setTimeout(resolve, 500));缓存重复请求数据
对于测试中重复查询的地址余额、合约代码等数据,在本地缓存结果,避免重复调用RPC接口。比如用对象存储缓存:const balanceCache = {}; async function getCachedBalance(address, blockNumber) { const key = `${address}-${blockNumber}`; if (!balanceCache[key]) { balanceCache[key] = await ethers.provider.getBalance(address, blockNumber); } return balanceCache[key]; }升级Alchemy套餐
如果测试需求需要更高的流量额度,可升级Alchemy的付费套餐,获得更高的CU限额。
内容的提问来源于stack exchange,提问作者Matt Jaf
相关产品推荐
相关产品推荐

