Smart contract development on Ethereum and EVM-compatible blockchains demands more than just functional correctness—it requires efficiency. One of the most critical aspects of efficient smart contracts is gas optimization, which directly impacts deployment cost, transaction fees, and user experience. In this guide, we’ll dive deep into using the Hardhat Gas Reporter plugin to analyze and optimize gas consumption in your Solidity projects.
Whether you're building DeFi protocols, NFTs, or Web3 applications, understanding how to measure and reduce gas usage can save significant costs and improve scalability. Let’s explore how to integrate, configure, and leverage hardhat-gas-reporter for maximum development efficiency.
👉 Discover how developers are cutting gas costs with real-time analytics and advanced tooling.
What Is Hardhat Gas Reporter?
The Hardhat Gas Reporter is a powerful development plugin that automatically analyzes the gas usage of your smart contract functions during testing. It provides detailed insights into:
- The minimum, maximum, and average gas consumed per function call.
- Estimated transaction costs in ETH or USD.
- Network-specific pricing based on current gas prices and ETH market value.
This data helps developers identify high-cost operations, validate optimization efforts, and make informed architectural decisions.
Core Keywords:
hardhat gas reportergas optimizationSolidity gas efficiencysmart contract testingEVM gas costcontract deployment costgas analysis tool
Why Gas Optimization Matters
On Ethereum, every operation in a smart contract has a gas cost. High gas consumption leads to:
- Expensive user transactions
- Lower adoption due to poor UX
- Higher risk of out-of-gas errors
- Increased cost for contract deployment
By using tools like Gas Reporter, developers can quantify these costs early in development and apply proven optimization strategies before going live.
Installing and Configuring Hardhat Gas Reporter
Step 1: Install the Plugin
Run the following command to add the gas reporter to your Hardhat project:
npm install --save-dev hardhat-gas-reporterThis installs the plugin locally so it doesn’t affect production environments.
Step 2: Update hardhat.config.js
Import the plugin and configure its settings:
require("hardhat-gas-reporter");
module.exports = {
solidity: "0.8.20",
gasReporter: {
enabled: true,
currency: "USD",
gasPrice: 20,
coinmarketcap: process.env.COINMARKETCAP_KEY,
outputFile: "gas-report.txt",
noColors: true,
excludeContracts: ["MockToken"]
}
};Key Configuration Options:
enabled: Toggle reporting on/off.currency: Display costs in USD, EUR, or ETH.gasPrice: Set custom gas price in Gwei (default uses live network data).coinmarketcap: Use API key for real-time ETH price (get from CoinMarketCap).outputFile: Save report to a file instead of console.excludeContracts: Skip reporting for mocks or test-only contracts.
👉 See how top teams streamline development with integrated performance tracking.
Running Gas Reports During Testing
Once configured, run your test suite as usual:
npx hardhat testAfter tests complete, the gas reporter will output a summary table like this:
·----------------------------|----------------------------|-------------|-------------|-------------·
| Contract · Method · Min (Gas) · Max (Gas) · Avg (Gas) ·
·----------------------------|----------------------------|-------------|-------------|-------------·
| MyContract · transfer · 28912 · 51234 · 43210 ·
| MyContract · approve · 2345 · 2345 · 2345 ·
·----------------------------|----------------------------|-------------|-------------|-------------·
| Network · Eth Price · Gas Price · Cost (Avg) ·
·-----------------------------|-------------|-------------·
| sepolia · $1,800 · 20 Gwei · $1.73 ·
·-----------------------------|-------------|-------------·This breakdown shows exactly how much each function costs under different scenarios.
How to Read the Gas Report
Understanding the output is crucial for effective optimization.
Core Fields Explained
- Method: Name of the function being called.
- Min/Max/Avg Gas: Range of gas used across test cases; useful for spotting variable-cost behaviors.
- Eth Price: Current ETH market price (requires CoinMarketCap API).
- Gas Price: Assumed or real-time network gas rate (in Gwei).
- Cost (USD): Estimated dollar cost per transaction—helpful for product teams and budget planning.
Key Performance Indicators
Look for these red flags in your reports:
- High storage writes (SSTORE) — among the most expensive EVM operations.
- Frequent SLOADs — reading from storage isn’t free.
- Large calldata size — impacts transaction overhead.
- Loops with unbounded iterations — risk of hitting gas limits.
Frequently Asked Questions
Q: Can I use Gas Reporter without a CoinMarketCap API key?
A: Yes. Without the key, the report will still show gas values but won't display USD/ETH prices.
Q: Does Gas Reporter work on all networks?
A: It simulates gas usage based on your configuration and works locally. You can set different gas prices to mimic mainnet, Sepolia, or other EVM chains.
Q: Why are some functions showing zero gas cost?
A: View or pure functions that don’t modify state often have lower or near-zero execution cost when called externally during tests.
Q: Can I export reports to CSV or JSON?
A: Not natively. However, you can parse the text output or use third-party tools to process outputFile.
Q: Is Gas Reporter accurate compared to actual mainnet usage?
A: It’s highly accurate for relative comparisons and identifying costly functions. Actual mainnet gas may vary slightly due to network conditions.
Q: Should I optimize every function for minimal gas?
A: Focus on frequently called functions (e.g., user-facing actions). Prioritize readability and security unless gas is a critical bottleneck.
Top 5 Gas Optimization Strategies
1. Reduce Storage Operations
Storage writes (SSTORE) are extremely expensive. Minimize them by grouping related data.
// Before: Two separate SSTOREs
uint256 public value;
uint256 public lastUpdate;
function updateValue(uint256 newValue) public {
value = newValue;
lastUpdate = block.timestamp;
}
// After: Single SSTORE using struct
struct State {
uint256 value;
uint256 lastUpdate;
}
State private state;
function updateValue(uint256 newValue) public {
state = State(newValue, block.timestamp); // One write
}2. Use Constants and Immutables
Avoid unnecessary SLOAD operations by defining fixed values at compile time.
// Before: Reads from storage
address public owner;
// After: Zero-gas read
address public constant OWNER = 0x...;3. Pack Variables Efficiently
EVM allocates 256 bits per storage slot. Pack small variables together to save space.
// Wastes space — uses two slots
uint128 a;
uint256 b;
uint128 c;
// Optimized — fits in two slots instead of three
uint128 a;
uint128 c;
uint256 b;4. Leverage unchecked Blocks
When overflow is impossible, skip safety checks:
function increment(uint256 x) public pure returns (uint256) {
unchecked { return x + 1; } // Saves ~300 gas
}Use cautiously—only where math is guaranteed safe.
5. Cache Repeated Calculations
Avoid recalculating values inside functions:
function calculate(uint256 a, uint256 b) public pure {
uint256 sum = a + b;
require(sum > 100);
return sum * 2; // Reuse sum instead of recomputing
}Caching improves both gas efficiency and code clarity.
👉 Access next-gen blockchain tools that help developers ship faster and cheaper.
Final Thoughts
Integrating Hardhat Gas Reporter into your workflow transforms gas optimization from guesswork into a data-driven process. By measuring function-level costs, visualizing trends, and applying strategic code improvements, you can significantly reduce transaction expenses and enhance contract performance.
Remember: small optimizations compound over thousands of transactions. Even saving 500 gas per call can translate to thousands of dollars saved annually on a popular dApp.
Start using the gas reporter today—measure first, optimize wisely, and deploy confidently.