Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Gas Estimation for Mainnet Deployment and Transactions

Hello! In our previous lesson, we took a crucial step towards launching your project by securely configuring your Hardhat project for the Ethereum mainnet. We focused on the importance of protecting your private key using methods like .env files and the more secure hardhat-keystore.

Now that we have the how of deployment sorted, we need to address the how much. Before sending any real Ether to the network, it's essential to understand the potential costs. Today's lesson is dedicated to exactly that. We will learn how to estimate mainnet deployment and transaction costs using gas estimation tools. This skill is vital for financial planning, funding your deployer wallet correctly, and ensuring the long-term economic viability of your project for both you and your users.

We'll explore three distinct methods, moving from a straightforward manual approach to more automated and programmatic techniques that will feel familiar given your background in backend development.

The Anatomy of a Transaction Fee

First, let's break down what determines the cost of any on-chain action, whether it's deploying a contract or calling one of its functions. The total fee is a product of two factors:

  1. Gas Units (or Gas Used): This measures the amount of computational work required for the operation. Every single instruction in your smart contract (e.g., writing to storage, performing arithmetic) has a specific gas cost. The total gas units for a transaction is the sum of all its instruction costs. This value is relatively constant for a given operation on a specific contract.

  2. Gas Price: This is what you pay per unit of gas. It's a dynamic value determined by network demand at the time of your transaction. You can think of it as a bid to have your transaction included in a block. Gas Price is typically measured in Gwei, where 1 Gwei = 0.000000001 ETH.

    • Since the EIP-1559 update, the Gas Price is composed of a Base Fee (which is burned by the network) and a Priority Fee (a tip paid to the validator). The total effective gas price is Base Fee + Priority Fee.

The final cost calculation is:

To get the cost in a fiat currency like USD, you simply multiply the ETH fee by the current ETH/USD exchange rate.

Method 1: Manual Estimation with a Testnet and Gas Tracker

The most direct way to estimate cost is to perform the action on a testnet and use that data to project the mainnet cost. The logic is that the gas units required to deploy your contract or call a function will be nearly identical on a testnet (like Sepolia) and on the mainnet. The only difference is the highly variable gas price.

This video provides an excellent walkthrough of this exact process.

How to estimate smart contract costs (deployment and functions)

The video "How to estimate smart contract costs" by Artur Chmaro clearly demonstrates the manual estimation process. We'll watch it to see how to find the gas units used on a testnet and combine that with mainnet gas prices.

Watch the video from the beginning to the end (00:00 - 05:39). The first part covers deployment cost, and the second covers function call cost. Pay attention to the three key pieces of information he uses: Gas Units from the testnet transaction, Gas Price from a mainnet gas tracker, and the ETH/USD exchange rate.

Let's summarize the steps from the video:

  1. Deploy to a Testnet: Deploy your contract to a testnet like Sepolia, as you've done before.

  2. Find Gas Units on a Block Explorer: View the successful deployment transaction on a block explorer (e.g., Sepolia Etherscan). Find the value for "Gas Usage by Transaction". This is your Gas Units Used.

  3. Find the Current Mainnet Gas Price: Go to a mainnet gas tracker, such as the one on Etherscan. This will show you the current gas prices in Gwei for low, average, and high-priority transactions.

    Etherscan Gas Tracker
    This is an example of an Ethereum Gas Tracker. It provides real-time estimates for the Base and Priority fees in Gwei for different transaction speeds, which is crucial for calculating mainnet costs.

  4. Calculate the Cost: Multiply the Gas Units Used from your testnet transaction by the current Gas Price from the mainnet tracker to get the estimated cost in Gwei. Convert this to ETH and then to USD.

This same process applies to estimating the cost of any function call (e.g., transfer, mint, stake). Simply perform the transaction on the testnet, find the gas units used, and multiply by the current mainnet gas price.

Method 2: Automated Reporting with hardhat-gas-reporter

While the manual method is great for a one-off check, it's not efficient for continuous development. A much better approach, especially for a developer, is to integrate cost estimation directly into your testing workflow. The hardhat-gas-reporter plugin does exactly this.

This plugin automatically calculates the gas used by your smart contract functions during your test runs and presents a detailed report, including estimated costs in a fiat currency.

The article "How to Test Gas Usage in Ethereum Smart Contracts" provides a great overview of setting this up.

How to Test Gas Usage in Ethereum Smart Contracts

This article explains the importance of gas testing and introduces the hardhat-gas-reporter plugin. We will focus on how to configure and use it within our Hardhat project.

Read the sections "Using eth-gas-reporter for Detailed Reports" and the FAQ "How does the hardhat-gas-reporter plugin help optimize gas usage in smart contracts?". Focus on the installation and configuration steps in hardhat.config.js. Note that the article uses the name eth-gas-reporter, which is the underlying package; the plugin for Hardhat is hardhat-gas-reporter.

The great news is that hardhat-gas-reporter is already included in the hardhat-toolbox you installed in Module 2. So, you only need to configure it in your hardhat.config.js file.

Here's a typical configuration:

// in hardhat.config.js

module.exports = {
  solidity: "0.8.20",
  // ... your networks configuration
  gasReporter: {
    enabled: true, // Set to true to enable the reporter
    currency: "USD", // The currency to display costs in
    coinmarketcap: "YOUR_COINMARKETCAP_API_KEY", // Optional: for accurate ETH/USD conversion
    gasPrice: 20, // You can set a gas price (in gwei) for the report
    token: "ETH",
  },
};

To make this work effectively:

  1. Enable the reporter: Add the gasReporter object to your hardhat.config.js as shown above.
  2. (Optional but Recommended) Get a free API key from CoinMarketCap and add it to the coinmarketcap field. This allows the reporter to fetch the live ETH price for accurate USD cost estimates.
  3. Run your tests: Simply run your test suite as usual:
    npx hardhat test
    

After your tests complete, you will see a detailed table in your console. It will show the gas usage for the deployment of each contract and for each function call executed in your tests (min, max, and average). This provides immediate feedback on how code changes impact transaction costs.

Method 3: Programmatic Estimation with estimateGas

For maximum flexibility, you can estimate gas programmatically using a script. This leverages the estimateGas function available in libraries like ethers.js. This function simulates a transaction without broadcasting it and returns the estimated gas units required. This approach is perfect for building custom tools, such as a deployment cost calculator.

The following resource provides a ready-made Node.js script that automates this process.

How To Calculate Gas Costs For Solidity Contracts

The article "How To Calculate Gas Costs For Solidity Contracts" by James Bachini includes a fantastic estimate.js script that programmatically calculates deployment cost. As a backend developer, you'll appreciate this approach.

Read the entire article. Pay close attention to the estimate.js code. Notice how it uses provider.estimateGas() to get the gas units, provider.getFeeData() to get the current gas price, and an external API (CoinGecko) to get the ETH price.

The script in the article elegantly combines several steps:

  1. It reads and compiles your smart contract.
  2. It uses provider.estimateGas() on the deployment transaction data to get the estimated gas units.
  3. It fetches the current gas price (feeData) from the Ethereum node.
  4. It fetches the current ETH/USD price from an API.
  5. It calculates and logs the final estimated cost in both ETH and USD.

This method provides the most up-to-the-minute estimate because it pulls all variables (gas price, ETH price) in real-time.

Test your understanding!

Your hardhat-gas-reporter output shows that your token's transfer() function consumes an average of 50,000 gas units. You check Etherscan's Gas Tracker and see the average gas price is 25 Gwei. The current price of ETH is $3,000. What is the estimated cost of a single token transfer in USD?

Show answer
  1. Calculate cost in Gwei:
    50,000 Gas Units * 25 Gwei/Unit = 1,250,000 Gwei

  2. Convert Gwei to ETH:
    1,250,000 Gwei / 1,000,000,000 Gwei/ETH = 0.00125 ETH

  3. Convert ETH to USD:
    0.00125 ETH * $3,000/ETH = $3.75

The estimated cost for a transfer is $3.75.

Conclusion

You now have a powerful toolkit for understanding and predicting the costs associated with your smart contracts. This is not just a technical exercise; it's a fundamental part of running a successful and user-friendly blockchain application.

Key Takeaways:

  • Transaction cost is determined by Gas Units (work done) and Gas Price (network fee).
  • Manual estimation via testnets is simple and effective for quick checks.
  • hardhat-gas-reporter is the ideal developer tool for integrating cost analysis directly into your testing and development cycle.
  • Programmatic estimation with estimateGas offers the most flexibility and is perfect for building custom, real-time cost calculation tools.

Preview of the Next Lesson:

Now that you know how to measure costs, the next logical question is: how can we reduce them? In our next lesson, we will explore practical and effective techniques to make your contracts more efficient. We will apply basic gas optimization techniques to your Solidity code, a skill that directly translates to lower fees and a better experience for your users.

Can't find a good explanation? Sign up and we'll make it for you

Sign up