文章目录
- 前言
-
- [hardhat 单元测试时如何观察gas消耗情况](#hardhat 单元测试时如何观察gas消耗情况)
-
- [1. 安装依赖与配置](#1. 安装依赖与配置)
- [2. 演示示例](#2. 演示示例)
前言
如果您觉得有用的话,记得给博主点个赞,评论,收藏一键三连啊,写作不易啊^ _ ^。
而且听说点赞的人每天的运气都不会太差,实在白嫖的话,那欢迎常来啊!!!
hardhat 单元测试时如何观察gas消耗情况
1. 安装依赖与配置
安装gas reporter 组件:
bash
yarn add -D hardhat-gas-reporter

修改hardhat.config.ts 配置中开启gas-reporter:
引入:
bash
import "hardhat-gas-reporter";
添加:
bash
gasReporter: {
enabled: true,
currency: "USD",
token: "ETH"
}

2. 演示示例
合约:
bash
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.28;
contract HelloWorld {
uint a;
uint b;
function hello() public pure returns (string memory) {
return "Hello World";
}
function test1() public {
a++;
}
function test2() public {
a++;
b++;
}
}
单元测试:
bash
import "@nomicfoundation/hardhat-ethers";
import { ethers } from "hardhat";
import { expect } from "chai";
describe("HelloWorld", function () {
it("should get the hello world", async() =>{
// 步骤如下:
// 1. setup 安装合约
// 2. import contract 引入合约
// 3. test action
//安装合约
const HW = await ethers.getContractFactory("HelloWorld");
// 部署合约,拿到合约实例
const hw = await HW.deploy();
await hw.waitForDeployment();//等待部署完成
// 测试gas
for (let index = 0; index < 10; index++) {
await hw.test1();
await hw.test2();
}
// 测试合约的方法调用结果,并输出
expect(await hw.hello()).to.equal("Hello World");
});
});
执行单元测试:
bash
npx hardhat test
可以看到下图,每个方法的gas使用都会在控制台上打印出来。

说明:
| 字段 | 含义 | 重点观察点 |
|---|---|---|
| Min | 该方法执行的最小 Gas 消耗 | 代表最优情况下的 Gas 成本 |
| Max | 该方法执行的最大 Gas 消耗 | 代表最坏情况下的 Gas 成本(比如状态变化、循环分支差异) |
| Avg | 该方法执行的平均 Gas 消耗 | 最具参考价值,反映日常调用的平均成本 |
| # calls | 该方法在测试中被调用的总次数 | 确认你的测试用例是否覆盖了足够多的调用场景 |
| usd (avg) | 按当前 ETH 价格换算的平均美元成本 | 直观感受实际部署后的经济成本(这里显示 - 是因为未配置价格) |