By Rosario Borgesi

Translation: Huo Huo, vernacular blockchain

The Ethereum blockchain has revolutionized decentralized applications and smart contracts, but every transaction incurs Ethereum gas fees. In this guide, we will demystify Ethereum gas fees and learn about their basic principles, how to calculate them, factors that affect costs, and effective strategies for optimizing transactions while controlling costs.

1. Understand Ethereum Gas

Gas is the fuel that powers transactions and smart contract executions on the Ethereum blockchain. It represents the computational work required to process these operations and is priced in small denominations of Ether called gwei (1 gwei = 10^-9 ETH).

In other words, gas is a unit of measurement for computational work, equivalent to a certain amount of Ether.

This is why gas fees are crucial in the Ethereum ecosystem:

1) Resource allocation: Gas fees act as a mechanism for allocating network resources. By requiring users to pay for the computing power and storage space they use, the network ensures fair access and prevents resource abuse.

2) Preventing network spam: Without gas fees, malicious actors could flood the network with spam transactions, overloading the system and slowing down legitimate transactions. Gas fees make spamming the network costly and economically impractical.

3) Incentivizing miners: Gas fees incentivize miners to include transactions in blocks. Miners prioritize transactions with higher gas fees, encouraging users to offer competitive fees for timely transaction processing.

4) Network Security: Gas fees contribute to the security of the Ethereum network. They ensure the correct execution of transactions and smart contracts by requiring users to pay for the computational steps involved. This deters potential attacks and vulnerabilities.

5) Scalability and efficiency: By attaching a cost to each operation, gas fees encourage developers to write efficient and optimized code. A focus on efficiency is critical to scaling the network because it encourages best practices and reduces pressure on the blockchain.

6) Economic Model: Gas fees are an integral part of Ethereum’s economic model. They promote a sustainable ecosystem, allowing miners to be compensated for their efforts and promoting the growth and stability of the network.

2. Components of Gas Fees

Understand the main components that make up Ethereum gas fees:

1) Base Fee: Set by the protocol, you must pay at least this amount for your transaction to be considered valid.

2) Priority Fee: is a tip added to the base fee to make your transaction attractive to validators so that they choose to include it in the next block.

A transaction that only pays the base fee is technically valid, but is unlikely to be included because it has no incentive for validators to choose it.

The priority fee depends on the network usage when you send the transaction: if there is a lot of demand then you might want to set the priority fee higher, but when there is less demand you can pay less.

3. Transaction Fee Calculation

For example, let's say Jordan has to pay Taylor 1 ETH. An ETH transfer requires 21,000 units of gas, with a base fee of 10 gwei. Jordan includes a 2 gwei tip.

The total cost is now equal to:

units of gas used * (base fee + priority fee)

The base fee is the value set by the protocol, and the priority fee is the value set by the user as a prompt for the validator.

即21,000 * (10 + 2) = 252,000 wei(0.000252 ETH).

When Jordan sends the money, 1.000252 ETH will be deducted from Jordan's account. Taylor will receive 1.0000 ETH. The validator receives a tip of 0.000042 ETH. The 0.00021 ETH base fee is burned, which means it will be removed from circulation.

4. Read and write data

The Ethereum network makes a distinction between writing data to the network and reading data from the network, and this distinction plays an important role in how you write your applications. Generally speaking, writing data is called a transaction, while reading data is called a call.

1) Transactions: Transactions change the state of the network when they write or change data. It can be as simple as sending ether to another account or as complex as executing a contract function or adding a new contract to the network. In order to make transactions, we have to pay gas fees, and they take time to process.

2) Calls: Calls can be used to execute code on the network, but do not permanently change data. They are basically used to read data, so they can be run for free (no gas). When you execute a contract function through a call, you will receive the return value immediately.

5. Transaction Object

You can set the amount of gas you are willing to pay when submitting a transaction by setting the following parameters in the transaction object:

1) GasLimit: The maximum amount of Gas units that a transaction can consume. The EVM specifies the gas units required for each computation step.

2) maxPriorityFeePerGas: The maximum price of consumed Gas included as a validator tip.

3) maxFeePerGas: The maximum fee per unit of Gas that you are willing to pay for the transaction (including baseFeePerGas and maxPriorityFeePerGas)

6. London Upgrade (EIP-1559)

Prior to the London upgrade, fees were calculated without distinguishing between basic and priority fees.

In the transaction object we can set:

1) GasLimit/startGas: The maximum amount of Gas units that a transaction can consume. Same as before.

2) GasPrice: The amount in wei we are willing to pay per unit of Gas.

Assume Alice has to pay Bob 1 ETH. In the transaction, the gas limit is 21,000 units and the gas price is 200 gwei.

The total cost is: Gas units (limit) * Gas ​​price per unit, which is 21,000 * 200 = 4,200,000 gwei0.0042 ETH

7. Fee calculation in complex transactions

To get a better idea of ​​transaction costs, we can look at the EVM opcodes. So let's calculate the cost of executing this function:

Function doMath ( uint a, uint b ) { a + b; b - a; a * b; a==0; }

a + b (ADD) costs 3 gas units b - a (SUB) costs 3 gas units a * b (MUL) costs 5 gas units a == 0 (EQ) costs 3 gas units

So the total cost of this transaction is 14 gas units.

The important thing to understand is that if in the transaction object we specify a gasLimit equal to 6, only the first two operations will be executed, then the transaction will be stopped and the gasFee paid will not be recovered because we have to pay for the work done.

Therefore, if we have to set the parameter gasLimit to a sufficient value so that our transaction can be executed and not lose our ether.

In this particular example, calculating the gas fee is relatively simple. However, for more complex functions, especially those involving loops over variables of varying sizes, determining the gas fee in advance can be challenging.

In this case, we can take advantage of the estimateGas function provided by two of the most famous development libraries: ethers.js and web3.js. This function allows us to estimate the gas costs associated with executing a specific function on the Ethereum blockchain.

However, it is worth reminding that it is always a good habit to set gasLimit and maxFeePerGas to avoid executing transactions that consume too much Ether.

8. Strategies to reduce gas fees 1) Utilize Layer 2

Layer-2 is a secondary framework or protocol built on top of the Ethereum blockchain. These solutions aim to enhance scalability and optimize transaction speed by processing most transactions outside of the Ethereum main chain, known as Layer 1. Layer-1 involves the base Ethereum blockchain, where transaction costs are high and can face scalability issues due to high demand.

Among the various Layer-2 approaches are Rollups adopted by Arbitrum and Optimism.

Rollups aggregate multiple transactions into a single transaction, compress the data and store it on the Ethereum mainnet. This significantly reduces gas fees and improves scalability, as a single mainnet transaction can represent a large number of off-chain transactions.

2) Run during periods of reduced network congestion

If we want to operate on layer 1, the solution to saving fees seems obvious: we must issue transactions when the network is less congested.

In fact, the Ethereum blockchain only allows about 20-40 transactions per second (TPS) (this is the total number of all Ethereum users); when the limit is reached, users are forced to compete with each other to get their transactions, which causes fees to rise.

To check the network load, we can use Etherscan.

3) Minimize transactions

Every transaction on the Ethereum blockchain incurs a cost, called a gas fee. In order to reduce these fees, it is necessary to combine multiple operations into a single transaction whenever possible. For example, bundling multiple token transfers or interactions with smart contracts into a single transaction can significantly reduce the overall cost.

4) Optimize code complexity

Ethereum transactions involve executing code stored on the blockchain. Complex and inefficient code requires more computational resources, resulting in higher gas fees. By optimizing and simplifying your code, you can reduce the gas required for execution. This involves efficient coding practices, minimizing redundant computations, and utilizing efficient programming techniques.

5) Energy-saving smart contracts

When developing smart contracts, it is critical to design them in a way that minimizes gas consumption. This includes avoiding unnecessary storage operations, optimizing loops, and reducing the complexity of contract logic. Gas optimization tools and best practices should be utilized during development.

9. Conclusion

In summary, gas fees are an important component of Ethereum, maintaining network integrity, incentivizing correct usage, ensuring security, and supporting scalability, all of which together help build an efficient and sustainable blockchain network.

In this article, we explored the calculation and estimation of gas fees, and gained insight into various strategies to mitigate their impact. By adopting optimization techniques, leveraging Layer2 solutions, and implementing gas-efficient smart contract code, users and developers can effectively reduce transaction costs and improve the overall efficiency of applications on the Ethereum network.

With a deeper understanding of gas fees and practical strategies for managing them, you are now ready to navigate the Ethereum landscape and optimize your coding efforts. Happy coding, and may your Ethereum interactions be both cost-effective and innovative!