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

What are the debugging techniques in Hardhat?

2月21日 15:58

Hardhat provides powerful debugging capabilities. Here are the main debugging techniques:

1. Console.log Debugging

Use console.log in Solidity contracts:

solidity
import "hardhat/console.sol"; contract MyContract { function setValue(uint256 _value) public { console.log("Setting value to:", _value); value = _value; console.log("Value set successfully"); } }

2. Transaction Tracing

Use hardhat --verbose to view detailed transaction information:

bash
npx hardhat test --verbose

Capture error stacks in tests:

javascript
try { await contract.someFunction(); } catch (error) { console.log(error); }

3. Hardhat Network Console

Start interactive console:

bash
npx hardhat console

Execute commands in the console:

javascript
const Contract = await ethers.getContractFactory("MyContract"); const contract = await Contract.deploy(); await contract.setValue(42); console.log(await contract.value());

4. Debugging Tests

Run tests with --debug flag:

bash
npx hardhat test --debug

5. Viewing Events

Listen to contract events:

javascript
contract.on("EventName", (arg1, arg2, event) => { console.log("Event emitted:", arg1, arg2); });

6. State Snapshots

Use snapshot functionality to quickly reset state:

javascript
const snapshot = await ethers.provider.send("evm_snapshot", []); // Perform operations await ethers.provider.send("evm_revert", [snapshot]);

7. Gas Analysis

Use gas-reporter plugin to analyze gas usage:

bash
npx hardhat test --gas

Best Practices:

  • Use console.log extensively during development
  • Remove console.sol import in production
  • Use meaningful log messages
  • Combine events and logs for debugging
  • Utilize snapshot functionality to improve testing efficiency
标签:Hardhat