Mastering Gas Optimization in Hardhat: A Complete Guide to Using Gas Reporter

Efficient smart contract development on Ethereum and EVM-compatible blockchains demands more than just functional correctness鈥攊t requires gas optimization. Every line of Solidity code impacts transaction costs, and inefficient contracts can lead to high user fees and reduced adoption. One of the most powerful tools for identifying and reducing gas consumption is the Hardhat Gas Reporter.

This guide walks you through the complete usage of hardhat-gas-reporter, from installation to advanced optimization strategies, helping you build leaner, faster, and more cost-effective smart contracts.


What Is Gas Reporter?

馃憠 Discover how real-time gas analytics can transform your development workflow.

The Hardhat Gas Reporter is a plugin that automatically analyzes gas usage during test execution. It provides detailed insights into how much gas each function consumes, enabling developers to:

By integrating this tool into your development cycle, you gain visibility into performance bottlenecks before deployment鈥攕aving time, money, and improving user experience.


Installing and Configuring Hardhat Gas Reporter

Step 1: Install the Plugin

Run the following command in your Hardhat project:

npm install --save-dev hardhat-gas-reporter

This adds the gas reporter as a development dependency.

Step 2: Update hardhat.config.js

Import the plugin and configure its options:

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

OptionDescription
enabledTurns the reporter on/off
currencyOutput cost in USD, ETH, EUR, etc.
gasPriceSets gas price in Gwei (defaults to network average if not set)
coinmarketcapUses API key for real-time ETH price (requires environment variable)
outputFileSaves report to a file instead of console
excludeContractsSkips reporting for test-only contracts like mocks
馃挕 Pro Tip: Store your CoinMarketCap API key securely using dotenv to avoid exposing secrets.

Generating and Reading the Gas Report

Run Tests with Gas Reporting

Execute your test suite normally:

npx hardhat test

After tests complete, the gas reporter outputs a table like this:

路----------------------------|----------------------------|-------------|-------------|-------------路
| Solidity Contract          路 Method                     路 Min (Gas)   路 Max (Gas)   路 Avg (Gas)   路
路----------------------------|----------------------------|-------------|-------------|-------------路
| MyContract                 路 transfer                   路 28912       路 51234       路 43210       路
| MyContract                 路 approve                    路 2345        路 2345        路 2345        路
路----------------------------|----------------------------|-------------|-------------|-------------路
路-------------------------|---------------------------|-------------路
| Network                 路 Eth Price (USD)           路 Gas Price   路
路-------------------------|---------------------------|-------------路
| sepolia                 路 $1,800                    路 20 Gwei     路
路-------------------------|---------------------------|-------------路

Interpreting the Results

馃憠 See how top teams reduce gas costs by over 30% using automated analysis tools.

This data allows you to compare versions, track regressions, and validate optimizations.


Core Gas Optimization Strategies

Understanding where gas is spent is only half the battle. Here are proven techniques to cut costs significantly.

1. Minimize Storage Operations

Storage operations (SSTORE, SLOAD) are among the most expensive in Ethereum. Reduce them whenever possible.

Before: Multiple SSTOREs

function updateValue(uint256 newValue) public {
    value = newValue;           // First SSTORE
    lastUpdate = block.timestamp; // Second SSTORE (costly)
}

After: Single Struct Write

struct State {
    uint256 value;
    uint256 lastUpdate;
}
State private state;

function updateValue(uint256 newValue) public {
    state = State(newValue, block.timestamp); // One SSTORE
}

Result: Up to 50% reduction in storage-related gas.


2. Use Constants and Immutables

Variables declared constant or immutable avoid runtime storage reads.

Before: Dynamic Read (SLOAD)

address public owner; // Costs gas to read from storage

After: Compile-Time Value

address public constant OWNER = 0x...; // Zero gas at runtime

Use immutable for values set in the constructor but constant afterward.


3. Pack Variables Efficiently

Ethereum allocates 256 bits per storage slot, so poorly ordered variables waste space.

Inefficient Packing

uint128 a;
uint256 b; // Forces new slot even though 128 bits remain
uint128 c;

Optimized Packing

uint128 a;
uint128 c; // Shares same slot with 'a'
uint256 b; // Uses full slot

This reduces the number of storage slots accessed, lowering both SSTORE and SLOAD costs.


4. Leverage unchecked Blocks

When overflow/underflow is impossible, skip safety checks.

With Checks (Default)

function increment(uint256 x) public pure returns (uint256) {
    return x + 1; // Includes overflow check
}

Without Checks (Optimized)

function increment(uint256 x) public pure returns (uint256) {
    unchecked { return x + 1; } // Saves ~30-50 gas per operation
}

Use cautiously鈥攐nly when logic guarantees safety.


5. Cache Repeated Calculations

Avoid recalculating values within a function.

Before: Redundant Logic

require(a + b > 100);
return (a + b) * 2;

After: Cache Intermediate Result

uint256 sum = a + b;
require(sum > 100);
return sum * 2;

Saves gas by reusing computed values instead of recalculating.


Frequently Asked Questions (FAQ)

Q: Can I use Gas Reporter on local networks?
A: Yes. The reporter works on Hardhat Network, Ganache, and any EVM testnet or mainnet fork.

Q: Does it support other currencies besides USD?
A: Yes. You can set currency: "ETH", "EUR", "JPY", etc., depending on your preference.

Q: Why are my gas numbers different between runs?
A: Variability comes from dynamic state changes, branching logic, or network conditions. Use average values for comparison.

Q: Can I run it without CoinMarketCap API?
A: Yes. Without the API, it will still report gas usage but won鈥檛 show USD/ETH conversion rates.

Q: Is it safe to optimize aggressively in production?
A: Always balance optimization with readability and auditability. Over-optimization can introduce bugs.

Q: How often should I run gas reports?
A: Integrate it into CI/CD pipelines鈥攔un on every pull request or before major releases.


Final Thoughts

Gas efficiency isn鈥檛 an afterthought鈥攊t鈥檚 a core part of modern smart contract engineering. With Hardhat Gas Reporter, you gain actionable insights into your contract鈥檚 economic footprint.

Combine this tool with disciplined coding practices like variable packing, immutable usage, and unchecked math to achieve significant savings. As blockchain usage grows, every unit of gas saved translates directly into better scalability and user adoption.

馃憠 Start optimizing your next contract with real-time gas insights today.