Ultimate Guide for Gas Optimization on Ethereum

Ultimate Guide for Gas Optimization on Ethereum

Reduce gas fees in Solidity Smart Contracts

·

10 min read

Introduction

We carry on the progressive learning curve of this Welcome to Web3 series.

As you already know, money is the common thread of our series 🤑. So let's discuss the biggest challenge we face in the Web3 space. Whether as an Ethereum Developer or DeFi/NFT user. It's** gas fees**.

gasfeesprices.png

To answer the problem of gas fees optimization we will understand more about how blockchain technology works and discover the edge cases and limits of Ethereum development. It’s also the occasion to get some interesting Solidity basics and best practices before diving into more code-oriented articles next time.

The biggest concern of Crypto and Blockchain Development is gas fees getting higher and higher, especially on the Ethereum network.

So, let’s understand first why there is gas to pay.

Transactions

The Blockchain World is based on Transactions. When you buy or sell a Coin/Token of course, but not only. To mint an NFT, to Deploy an App on Ethereum’s mainnet is also a transaction. The same goes for modifying a variable in a smart contract or executing a function. Every interaction with the blockchain is called a transaction.

Gas & Gas Fees

Gas is the unit (in GWei) that measures the amount of computational power needed to execute an operation on the Blockchain network. It also helps to keep the network secure.

Gas price is the fee paid to the miners for providing this computational effort. It’s based on supply and demand between the miners and users of the network.

If the network is busy and the miners struggle to maintain it, the price of gas increases. Otherwise, when the network's activity is slower with excess mining capacity the price drop.

Without more boring details - for now- this is what we call the Proof-of-Work consensus mechanism.

So 'thanks' to the current crash of crypto market, we can expect low gas fees right?

Nop! Gas costs aren't affected at all.

On the opposite.

Ethereum's popularity is growing and Web3 is going mainstream.

We notice an all-time high demand on transactions for NFTs trading and DeFi users.

The amount of computational effort is huge. Thus, more expensive gas fees.

But don't worry!

There's good news.

We know how to reduce these fees and spend less money. Start by adopting the following techniques:

1- Plan Ahead to optimize Timing

As gas fees fluctuate over time, it would be smart to choose the right moment to make a transaction by checking Ethereum Gas Charts.

Start with ethereumprice.org/gas for heatmaps.

Keep an eye on traffic to avoid Network congestion.

Define a schedule for your transactions (dApp deployment, DeFi or NFT trading).

Usually, non-working hours on weekends are when gas prices are the lowest.

One popular, alternative way to do this is to use Alchemy's gas-optimized transactions APIs. For example, someone can send a bundle of identical transactions with varying gas costs via alchemy_sendGasOptimizedTransaction to save on gas costs.

Screenshot 2022-01-02 153914.png

2- Calculate Gas Fees Accurately

Before going live in a public Ethereum network, you must use Testnests first. Ropsten, Rinkeby, and Kovan all clone the real mainnet to give you a preview before deployment.

With Tools such Remix, Truffle and Etherscan you’ll get each transaction’s cost. It’s a good estimation of your gas fees.

But you can get a more accurate evaluation.

Instead of relying on gas price estimation. Select the Gas Used by a Transaction **(in gwei) **and get live gas prices at etherscan.io/gastracker

Then apply this formula

Cost = Gas Price x Amount of Gas Consumed

3- Share the fees with Users

This is one of the most important aspects of Web 3.0 and I personally love it.

When designing and developing a dApp you can let the users pay (some or all of ) the gas of their transactions.

When you buy an NFT, you pay for the gas needed for minting.

It can be the same for publishing an article on a decentralized Blogging Platform where the writer pays a part of the gas fees for storing the article on the Ethereum network.

The cost of gas is incurred by users.

4- Optimize Solidity Smart Contracts

This is the most effective way to reduce gas fees along with choosing the best timing. It's above all something that we can control totally.

Here are some of the best approaches to writing performant and low-cost smart contracts in Solidity:

Don’t initialize variables.

Every operation on a variable costs gas in Solidity. If the default value of a variable will never be used, don't initialize it. Just declare it and don't waste gas.

// OK 
uint256 hellovariable;

//Avoid if possible

uint256 hellovariable= 0;.

Store data on memory not storage.

Choosing the perfect Data location is essential. You must know these:

  • **storage **- variable is stored on the blockchain. It's a persistent state variable. Costs Gas to define it and change it.

  • **memory **- temporary variable declared inside a function. No gas for declaring. But costs gas for changing memory variable (less than storage)

  • **calldata **- like memory but non-modifiable and only available as an argument of external functions

/* If not specified data location is storage by default */

uint[] x;

Order your variables the right way

The order of your variables matters in Smart contracts. Solidity stores data in a single slot of 256 bits. If your variable is smaller than one slot, it is packed with another variable to be put in a single slot. But to do so, we need to make these variables next to each other. Just like in Tetris.

// Gas Wasting
uint128 a;
uint256 b;
uint128 c;

//Better
uint128 a;
uint128 b;
uint256 c;

Single-Line Swap

This is some Solidity magic. Using one line to swap two variables without writing a function or temporary variable that needs more gas.

(hello, world) = (world, hello)

Delete your variables to get a gas refund.

This is also a great Solidity feature. Since there's no garbage collection, you have to throw away unused data yourself. The goal here is to save space on the blockchain. The good news is that you'll get 75% of your storing costs back.

// Give me 15000 gas refund

//Using delete keyword
delete myVariable;

//Or assigning the value 0 if integer
myInt = 0;

Short circuit operations.

This technique can be used in any programming language but it’s more important if you write smart contracts. The goal is to reduce the number and cost of operations performed. When using logical operators like || or &&, we have 2 operations to compare. We should order the operations in a way to avoid checking the second value that needs more computation.

// f(x) is low cost
// g(y) is expensive

// Order this way
f(x) || g(y)
f(x) && g(y)

Avoid loop mistakes

Using loops needs a lot of computational power. In Solidity that means you should be very careful and precise with loop expensive operations and errors. Otherwise, gas fees can grow exponentially.

For example, use a temporary variable inside of loops and then affect it to a global variable outside the loops.

// DON'T
uint mynumber = 0;

function BadLoop(uint x) public {
  for(uint k = 0; k< x; k++) {
    mynumber  += 1;
  }
}


// DO
uint mynumber = 0;

function BetterLoop(uint x) public {
  uint temp = mynumber;

  for(uint k = 0; k< x; k++) {
    temp += 1;
  }

  mynumber = temp;
}

Make fewer external calls.

This one is different and even against coding best practices in other languages 😆 Usually we define a function to execute or retrieve a specified piece of data.

Don't do it with Solidity! Each call to an external contract costs gas. Instead, make one call to a function that returns all the data you need.

Avoid dead code

Dead code means Solidity code will never be executed. For example, two contradictory conditions are just a waste of gas.

function deadCode(uint x) public pure {
  if(x <1) {
    if(x> 2) {
      return x;
    }
  }
}

Minimize on-chain data

Globally the idea is to send the least persistent data on the blockchain and reduce unnecessary operations as possible. It starts when you design the architecture of your dApp.

One of the most used- yet not recommended tips- is using Events to store data. It costs less than storing them in variables. But remember that you can't use data in events on-chain.

All the complex computations and non-relevant data must be off-chain. It's important to define what will be put on-chain or not before diving into the code.

Don't forget Solidity Optimizer

Whether you're using Truffle, HardHat or Remix IDE. They all include a Solidity optimizer feature. You can avoid it during development but never in production.

/* Truffle */

module.exports = {
  solc: {
    optimizer: {
      enabled: true,
      runs: 1000
    }
  }
};


/*  HardHat */
module.exports = {
  solidity: {
    version: "0.8.9",
    settings: {
      optimizer: {
        enabled: true,
        runs: 1000,
      },
    },
  },
};

In Remix IDE.

Screenshot 2022-01-05 211751.png

These are just some tips to make your code better. There is several more techniques.

Gas Tokens Refund

GasToken helps you tokenize gas.

This means you can store gas.

Mint gas tokens when gas prices are cheap and deploy/use them when the prices are high to get a refund in ETH.

Smart contracts like GasToken.io take advantage of gas refunds when deleting storage variables. Just like we saw it in the code optimization part.

Fee = (GasUsed - GasRefunded) x gasPrice

Optimizing gas cost in Solidity smart contracts is probably the most difficult and crucial part of a Web3/Blockchain Developer. It requires a precise understanding of Ethereum and Solidity concepts in addition to a lot of practice.

Besides improving your smart contracts, you can "change" the Ethereum network to reduce gas fees without any modification to your code thanks to L2 and sidechains.

5- Adopt Layer 2 and Sidechains

polygon-2.png

Until Ethereum 2.0 upgrade, gas fees on the Mainnet (Layer1) will probably stay pricey due to traffic. Layer 2 and Sidechains are two scaling solutions. Both are built on the Ethereum network to make transactions faster and cheaper.

Examples are xDai , Polygon and Optimism or Arbitrum .

The main difference between L2 and sidechains is that Layer 2 scaling solutions don't have their own consensus mechanism (or protocol) but rely on the security of Ethereum. Meanwhile, sidechains have their own Ethereum-compatible consensus mechanism.

To understand the concept of consensus protocols, you can read the amazing thread by Oliver Jumpertz.

6- Try other Blockchains

otherbc.png

Ethereum isn’t the only network in the Web3 space. The most popular yes, but several other blockchains can be used to build Apps.

**Cardano **for example is the third most used crypto. Considered as a good mix between Bitcoin and Ethereum, Cardano is a proof-of-stake blockchain (PoS) network.

This guarantees low gas fees and more climate-friendly technology.

**Polkadot **is a PoS blockchain created by Gavin Wood. He is well-known for being the co-founder of Ethereum. Besides having very low gas fees, Polkadot enables cross-blockchain transfers.

This interoperability could be the future of Web3 development. Just like hybrid cloud storage is now getting adopted widely.

**Solana **is the new outsider. It's a blockchain that uses a different consensus mechanism. A combination of PoS and a new technology called Proof-of-History.

Solana's low gas fees and speed explains its popularity. More and more NFTs and dApps are now available on Solana.

**Binance Smart Chain **(BSC) is also very famous among DeFi Traders for its low cost.

When developing to a different blockchain make sure to check the documentation of each platform. Some big changes in your code might be necessary. Some use Solidity language others Rust and **Go **.

All these alternatives offer lower transaction costs and an improved suite of tools for developers.

Dapps for Traders

These dApps are useful for NFTs traders and DeFi users.

They offer tools to simulate and/or bundle transactions.

You can also benefit from low (or no) gas fees than the market.

DeFiSaver: All-in-one platform for DeFi management. Useful for real-life simulating transactions and minimizing gas fees.

FTX: Very popular crypto exchange platform. Allow you to trade cryptocurrencies for free. It also doesn't charge you for deposits.

Keeper_DAO DeFi trading with reduced gas fees

Balancer a platform known as Automated Market Maker. Has improved gas efficiency to reduce trading costs.

Dapper Enables fee-free transactions with CryptoKitties or NBA Top Shots

Conclusion

Thank you for reading me.

Optimizing gas fees isn't an optional concept to know.

It's a core consideration in the web3 space if you're looking for a job.

It involves many important blockchain fundamentals like Proof-of-Work or Proof-of-Stake consensus mechanisms.

If you liked this article, let's connect:

Twitter @marmooznet

Hashnode @marmooz

Â