beskay

Smart Contract Engineer

Introduction

This is the first part of a three-part series on gas optimization patterns. This guide targets developers familiar with Solidity who want to write more gas-efficient smart contracts.

Originally created for a gas optimization mentorship, it included tests and practice contracts for optimization. For more details, visit the original GitHub repository.

This part provides a general overview of gas in Ethereum. Part two covers essential background knowledge about the EVM, such as data locations. Part three offers an extensive collection of gas optimization techniques.

What is gas?

All programmable compution in Ethereum is subject to fees, which are paid in gas. The gas fees should encourage writing efficient code and discourage spamming activities.

gas

Each opcode (EVM instruction) has a fixed cost that is paid upon execution. Some opcodes have a dynamic cost on top of the fixed cost, which is dependent on several factors. Opcodes with a dynamic gas cost include instructions related to storage or memory.

Gas costs

The total transaction gas cost is the sum of

  1. The base transaction costs (21k gas).
  2. The costs for calldata (4 gas for a zero byte, 16 gas for a nonzero byte).
  3. OPTIONAL: The costs for the access list (EIP-2930)
  4. The execution costs.

The more complex your transaction is, meaning the more instructions it takes to execute, the more expensive it becomes (values taken from Ethereum Gas Tracker):

To prevent the network from being clogged up with transactions that use too much gas, there is a current block gas limit of 30 million gas. If a transaction exceeds the block gas limit, it will be rejected.

A seen above a standard ETH transfer costs 21k gas, which is the minimum amount required to execute a transaction on the Ethereum network. So in theory, you could fit 1428 ETH transfers in a block (30 million / 21k).

Gas price

Since EIP-1559, the gas price consists of a

The fee you pay in USD is calculated as follows:

(gas used x gas price (in gwei) x ether price (in USD)) / 1 billion

For example, with a gas price of 50 gwei and an ETH price of $2k a standard ETH transfer costs:

(21k x 50 x 2000) / 1 billion = $2.1

References