Hardhat provides powerful debugging capabilities. Here are the main debugging techniques:
1. Console.log Debugging
Use console.log in Solidity contracts:
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. Transaction Tracing
Use hardhat --verbose to view detailed transaction information:
bashnpx hardhat test --verbose
Capture error stacks in tests:
javascripttry { await contract.someFunction(); } catch (error) { console.log(error); }
3. Hardhat Network Console
Start interactive console:
bashnpx hardhat console
Execute commands in the console:
javascriptconst 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:
bashnpx hardhat test --debug
5. Viewing Events
Listen to contract events:
javascriptcontract.on("EventName", (arg1, arg2, event) => { console.log("Event emitted:", arg1, arg2); });
6. State Snapshots
Use snapshot functionality to quickly reset state:
javascriptconst 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:
bashnpx 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