乐闻世界logo
搜索文章和话题

如何在 Hardhat 中进行 Gas 优化?

2月21日 14:12

在 Hardhat 中进行 Gas 优化是智能合约开发的重要环节,以下是主要的优化策略:

1. 使用 Gas Reporter 插件

安装并配置 gas-reporter:

bash
npm install --save-dev hardhat-gas-reporter

在 hardhat.config.js 中配置:

javascript
require("hardhat-gas-reporter"); module.exports = { gasReporter: { enabled: true, currency: "USD", gasPrice: 20 } };

运行测试查看 Gas 使用:

bash
npx hardhat test --gas

2. Solidity 编译器优化

启用编译器优化:

javascript
solidity: { version: "0.8.19", settings: { optimizer: { enabled: true, runs: 200 // 根据合约调用频率调整 } } }

3. 合约代码优化技巧

  • 使用 uint256 而非较小类型:EVM 操作 32 字节最有效率
  • 批量操作:减少循环和多次调用
  • 使用事件而非存储:事件比存储便宜
  • 使用 calldata 而非 memory:对于只读参数
  • 短路求值:在 if 语句中先检查最可能为真的条件

4. 存储优化

  • 打包变量:将小类型变量打包到同一个槽位
  • 使用 mapping 而非 array:对于稀疏数据
  • 删除不需要的存储:使用 delete 关键字

5. 测试 Gas 使用

在测试中验证 Gas 消耗:

javascript
it("should use reasonable gas", async function () { const tx = await contract.someFunction(); const receipt = await tx.wait(); console.log("Gas used:", receipt.gasUsed.toString()); // 断言 Gas 使用在合理范围内 expect(receipt.gasUsed).to.be.below(100000); });

6. 使用 Hardhat Console 测试 Gas

bash
npx hardhat console
javascript
const tx = await contract.someFunction(); const receipt = await tx.wait(); console.log("Gas used:", receipt.gasUsed.toString());

最佳实践:

  • 在开发阶段持续监控 Gas 使用
  • 对关键函数进行 Gas 优化
  • 使用 gas-reporter 定期检查
  • 在测试网验证 Gas 消耗
  • 考虑 Gas 价格波动对用户体验的影响
标签:Hardhat