Hardhat 提供了强大的调试功能,以下是主要的调试技巧:
1. Console.log 调试
在 Solidity 合约中使用 console.log:
solidityimport "hardhat/console.sol"; contract MyContract { function setValue(uint256 _value) public { console.log("Setting value to:", _value); value = _value; console.log("Value set successfully"); } }
2. 交易回溯
使用 hardhat --verbose 查看详细交易信息:
bashnpx hardhat test --verbose
在测试中捕获错误堆栈:
javascripttry { await contract.someFunction(); } catch (error) { console.log(error); }
3. Hardhat Network 控制台
启动交互式控制台:
bashnpx hardhat console
在控制台中执行命令:
javascriptconst Contract = await ethers.getContractFactory("MyContract"); const contract = await Contract.deploy(); await contract.setValue(42); console.log(await contract.value());
4. 调试测试
使用 --debug 标志运行测试:
bashnpx hardhat test --debug
5. 查看事件
监听合约事件:
javascriptcontract.on("EventName", (arg1, arg2, event) => { console.log("Event emitted:", arg1, arg2); });
6. 状态快照
使用快照功能快速重置状态:
javascriptconst snapshot = await ethers.provider.send("evm_snapshot", []); // 执行操作 await ethers.provider.send("evm_revert", [snapshot]);
7. Gas 分析
使用 gas-reporter 插件分析 Gas 使用:
bashnpx hardhat test --gas
最佳实践:
- 在开发阶段大量使用 console.log
- 生产环境移除 console.sol 导入
- 使用有意义的日志信息
- 结合事件和日志进行调试
- 利用快照功能提高测试效率