Metapunk Web3 Community 🦙

Cover image for How I optimized gas costs by 75%
Michael Stivala
Michael Stivala

Posted on

How I optimized gas costs by 75%

On the Ethereum blockchain, each transaction costs an amount of money in “gas fees”. As developers, our goal is to keep transaction costs as low as possible.

In this article I’ll discuss how to configure hardhat to report gas costs, and how to configure Solidity’s built-in optimizer to reduce gas costs.

I’ll be optimizing a sample NFT project from my upcoming book “A developer’s guide to launching an NFT collection”.

Gas Reporter

Before we turn on the optimizer, let’s start by measuring our current gas costs to give us a benchmark to compare against. We’ll need to first install and configure the hardhat-gas-reporter plugin.

The hardhat-gas-reporter plugin overrides hardhat’s npx hardhat test command and tracks the average gas price of every function that is called within your tests.

You may have guessed it — having automated tests for your project is required to use the gas reporter!

Install the plugin by running npm install hardhat-gas-reporter.

In your hardhat config file import the plugin at the top of the file by adding require("hardhat-gas-reporter")

Add the following block to the settings exported from that file:

gasReporter: {
  outputFile: "gas-report.txt",
  enabled: process.env.REPORT_GAS !== undefined,
  currency: "USD",
  noColors: true,
  coinmarketcap: process.env.COIN_MARKETCAP_API_KEY || "",
  token: "ETH"
}
Enter fullscreen mode Exit fullscreen mode

In order for the gas reporter to give us the monetary cost of each transaction, we’ll need a CoinMarketCap API key, which can be acquired for free from their website.

Go ahead and add the following lines to your .env file:

REPORT_GAS=true
COIN_MARKETCAP_API_KEY=[YOUR-API-KEY]
Enter fullscreen mode Exit fullscreen mode

Let’s run our tests again via npx hardhat test. The gas reporter plugin will take over and will log the gas used in every function call and will output the results to the gas-report-txt file.

Gas report (unoptimized)

This report is really useful in estimating how much your contract will cost to deploy to production, and how much each transaction will cost once deployed.

It also gives us a benchmark that we can use to measure our gas optimization efforts!

Solidity Optimizer

Let’s configure the solidity compiler to optimize our code for us by adjusting the solidity line in our hardhat configuration in hardhat.config.js:

solidity: {
    version: "0.8.9",
    settings: {
        optimizer: {
            // Toggles whether the optimizer is on or off. 
            // It's good to keep it off for development 
            // and turn on for when getting ready to launch.
            enabled: true,
            // The number of runs specifies roughly how often 
            // the deployed code will be executed across the 
            // life-time of the contract.
            runs: 300,
        }
    },
}
Enter fullscreen mode Exit fullscreen mode

Apart from turning the optimizer on, the only configuration option we have is the runs parameter.

From the solidity documentation:

The number of runs specifies roughly how often each opcode of the deployed code will be executed across the life-time of the contract. This means it is a trade-off parameter between code size (deploy cost) and code execution cost (cost after deployment).

200 or 300 runs is a sensible default, but I encourage you to experiment with different values to see how it effects deployment and transaction costs, and pick the most appropriate value for your project.

Here’s the same report again, but with the optimizer turned on. Notice the reduction in gas prices:

Gas report (after optimization)

What’s next?

Follow me on twitter for more blockchain-related tips and tricks, and to keep in the loop about my upcoming book launch: “A developer’s guide to launching an NFT collection”.

Top comments (0)