Gas optimization in Hardhat is an important part of smart contract development. Here are the main optimization strategies:
1. Use Gas Reporter Plugin
Install and configure gas-reporter:
bashnpm install --save-dev hardhat-gas-reporter
Configure in hardhat.config.js:
javascriptrequire("hardhat-gas-reporter"); module.exports = { gasReporter: { enabled: true, currency: "USD", gasPrice: 20 } };
Run tests to view gas usage:
bashnpx hardhat test --gas
2. Solidity Compiler Optimization
Enable compiler optimization:
javascriptsolidity: { version: "0.8.19", settings: { optimizer: { enabled: true, runs: 200 // Adjust based on contract call frequency } } }
3. Contract Code Optimization Techniques
- Use uint256 instead of smaller types: EVM operates most efficiently with 32 bytes
- Batch operations: Reduce loops and multiple calls
- Use events instead of storage: Events are cheaper than storage
- Use calldata instead of memory: For read-only parameters
- Short-circuit evaluation: Check most likely true conditions first in if statements
4. Storage Optimization
- Pack variables: Pack small type variables into the same slot
- Use mapping instead of array: For sparse data
- Delete unnecessary storage: Use delete keyword
5. Test Gas Usage
Verify gas consumption in tests:
javascriptit("should use reasonable gas", async function () { const tx = await contract.someFunction(); const receipt = await tx.wait(); console.log("Gas used:", receipt.gasUsed.toString()); // Assert gas usage is within reasonable range expect(receipt.gasUsed).to.be.below(100000); });
6. Use Hardhat Console to Test Gas
bashnpx hardhat console
javascriptconst tx = await contract.someFunction(); const receipt = await tx.wait(); console.log("Gas used:", receipt.gasUsed.toString());
Best Practices:
- Continuously monitor gas usage during development
- Optimize gas for critical functions
- Regularly check with gas-reporter
- Verify gas consumption on testnets
- Consider the impact of gas price fluctuations on user experience