Gas in Ethereum Blockchain Network: A Friendly Guide

Fawole JoshuaFawole Joshua
8 min read

Whether you use crypto applications or you are a smart contract developer, you must have had occasions to pay gas fees. If you have ever paid delivery riders to help you deliver something from one location to another, then you should know that the concept of gas is not actually foreign.

This article will offer to you a brief but informative guide into the world of gas, its uses, calculation and process of utilisation.

What is Gas?

In the context of the Ethereum blockchain network, gas is the fee or cost required to conduct transactions on the ethereum blockchain. It is denominated in small fractions of the cryptocurrency, Ether (ETH) called gwei (10⁹).

What is Gas used for?

Gas is used to pay validations for the resources to conduct transactions.

After the introduction of the proof-of-stake mechanism in 2012. It becomes essential that Validators who helped in the processing of transactions and building against data breaches and attacks from malicious nodes are given a little incentive for their hard work.

An Uber driver is paid in fiat currency for his labour, in the same sense, a Validator is also paid for the labour he exerts during the process of validating transactions on the ethereum blockchain ecosystem.

How is the price of gas determined?

The exact price of gas is usually determined by the forces of demand and supply and also the network capacity at the time of the transaction.

If I want to make a transaction at a particular time where the network is choked with other incoming transactions, the gas fee will be slightly higher because the law of demand states that The higher the demand, the higher the price and the lower the demand, the lower the price.

To prevent overlogging of transactions, people normally add a little more incentive on the original amount in order to ensure that Validators are fascinated towards their transaction.

This is just like a tip that is given to a Waiter at a restaurant.

The total amount of gas required for a particular transaction is calculated, thus:

The total amount of gas consumed by a smart contract multiplied by the current gas price (a value set by you) the transaction sender. Here is a mathematical representation:

Total gas Gas price Transaction fee

42,300. × 80 gwei. = 0.00338 ether

The higher your gas price the faster it will be processed. This leads us to another important term you should know: gas limit. It simply means the maximum amount you are willing to spend on your transaction

The multiplication of gas price and gas limit will give the total amount of Ether you are willing and allowing ethereum to spend on gas fees or any other particular transaction.

Gas limit Gas price MaxTransactionFee

50,000. × 100 gwei = 0.005 ether

It is essential to note that if a gas is issued but it is not enough for the transaction, the gas will run, the transaction will not be completed and there will be no refund.

Hence, you should be careful in setting realistic gas limits so your transactions will not be lost. In some cases, it is even better not to set a gas limit because if there is an excess amount of gas, the transaction will be completed and the excess gas will be refunded to the owner.

What are the benefits of gas to the ethereum blockchain ecosystem?

The main reason why gas is used is that smart contracts are turing complete. i.e they can potentially execute forever, locking up every single node (private computer on the ecosystem) on the blockchain.

Meaning that it can solve any mathematical problem given the required time and resources. This can create an infinite loop or bigger problems.

Since smart contract programs can run forever, gas has become the practical way in ethereum to manage the impact of a blockchain program.

Every computation or transaction costs some fees. These fees prevent expensive (or endless) contract executions and ensure miners are fairly compensated for their works.

Tips to Save Gas As a Crypto User

The expensive nature of gas fee has prompted different crypto Enthusiasts to figure different ways in which the cost of transacting can be lowered to a comfortable level

Here are some of the ways gas fees can be drastically lowered,

Layer2 scalability

One of the major problems encountered in the princess of transacting in the ethereum network is the problem of congestion and exhaustion of network capacity.

However, with the introduction of layer2 apps, there has been a tremendous increase in scalability and easy path for every transaction without the normal exorbitant gas fees.

With the use of layer2 apps like Optimum, Arbitrum, polygon and others, high gas fees have been greatly avoided.

Transaction aggregation

Another impressive way of being scrupulous about the use of gas is when transactions and other activities that are to be conducted are combined as a whole, this way, the Individual only pays the equivalent gas fee of only one transaction.

Tactical transactions

Individuals on the ethereum blockchain are advised to conduct their transactions when there are lesser transactions going on the ecosystem.

With the use of applications like Etherscan, people are able to know when the network is not being choked with transactions and they will also have access to planned structure that would be provided by the app.

This will foster easy transactions on the ethereum blockchain ecosystem.

How to Monitor Gas with EtherScan GasTracker

The etherscan gas tracker is one indispensable tool as it provides all the information required on gas fee for the particular transaction intended and it would tailor the gas fee down to the complexity of the transaction and also the bulkiness.

The etherscan gas tracker does not only gives tips on gas fees but also keeps a highly structured and detailed information about everything i.e transactions, tokens etc. Etherscan is like the google of ethereum.

How to Get Gas Report on Your Smart Contracts with Foundry (for Devs)

Here is an easy step-by-step on how to get a gas report on your smart contracts with foundry. The first step is to initialize Foundry

forge init

When you do this, you will find a Counter.sol contract in your src folder:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

contract Counter {
    uint256 public number;

    function setNumber(uint256 newNumber) public {
        number = newNumber;
    }

    function increment() public {
        number++;
    }
}

Then you will see a corresponding Counter.t.sol in your told folder:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;

import {Test, console} from "forge-std/Test.sol";
import {Counter} from "../src/Counter.sol";

contract CounterTest is Test {
    Counter public counter;

    function setUp() public {
        counter = new Counter();
        counter.setNumber(0);
    }

    function test_Increment() public {
        counter.increment();
        assertEq(counter.number(), 1);
    }

    function testFuzz_SetNumber(uint256 x) public {
        counter.setNumber(x);
        assertEq(counter.number(), x);
    }
}

The first step is to work on your foundry configuration, enable gas report by adding the name of the contract to which you would like to generate a gas report, add the names to the foundry.toml file. This is an example;

gas_reports = ["MyContract1", "MyContract2"]

Having done that, the second and last step is to generate the reports by running the forge test command with the gas report.

forge test --gas-report

You will get this gas report in your terminal:

[⠊] Compiling...
[⠃] Compiling 24 files with Solc 0.8.26
[⠊] Solc 0.8.26 finished in 7.58s
Compiler run successful!

Ran 2 tests for test/Counter.t.sol:CounterTest
[PASS] testFuzz_SetNumber(uint256) (runs: 256, μ: 52292, ~: 52540)
[PASS] test_Increment() (gas: 52367)
Suite result: ok. 2 passed; 0 failed; 0 skipped; finished in 153.60ms (150.59ms CPU time)
| src/Counter.sol:Counter contract |                 |       |        |       |         |
|----------------------------------|-----------------|-------|--------|-------|---------|
| Deployment Cost                  | Deployment Size |       |        |       |         |
| 106703                           | 277             |       |        |       |         |
| Function Name                    | min             | avg   | median | max   | # calls |
| increment                        | 43404           | 43404 | 43404  | 43404 | 1       |
| number                           | 283             | 283   | 283    | 283   | 257     |
| setNumber                        | 23582           | 43141 | 43542  | 43866 | 258     |

Concluding remarks

Here are the most important things discussed so far in this article.

  • Gas is the fee that is used to process a transaction or any other activity on the ethereum blockchain network.

  • Gas is calculated in gwei and wei.

  • Gas is used to pay Validators. There is a gas limit and gas fee. It is important to calculate the amount of gas one needs, as insufficient gas won’t get the transaction done neither will the money be refunded.

  • Exorbitant gas prices can be caused by a high demand and network capacity. High gas fee can be avoided by combining transactions, making use of etherscan, layer2 scalability etc.

  • Gas reports can always be found on the foundry through a set of commands.

0
Subscribe to my newsletter

Read articles from Fawole Joshua directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Fawole Joshua
Fawole Joshua

I am a Web3 technical writer who loves to educate developers and crypto users. I work with Web3 protocols to update their technical content marketing game!