Gas Cost in Ethereum

Published by Mario Oettler on

Since Ethereum offers an (almost) Turing complete scripting language for its Smart Contracts, it faces the so-called halting problem. It means it is impossible to determine whether a script terminates in a finite time before running it. This would allow denial of service attacks by creating transactions that run infinitely (or very long). Nodes executing these transactions would not be able to build a block in a timely manner, and hence the blockchain would not be alive anymore.

Hence, Ethereum introduced its “gas concept”. Gas are the transaction fees that the transaction sender is paying. They have the following purposes:

  1. avoid transactional spam
  2. avoid the halting problem
  3. reimburse/pay the block producers for their computing efforts

The halting problem is avoided by assigning every operation (OP-code) a certain amount of fees (gas) to be paid. In each transaction, the sender has to state how much gas he wants to submit in total. If the total used gas is larger than the allowed gas, the execution of the transaction stops, and all so far made changes are rolled back to the original state. The gas, however, is lost.

OP codes have different gas costs to address the different computation and memory requirements. A KECCAK256-operation, for example, costs 30 gas.

The exact gas cost per OP-code is given in the yellow paper: https://ethereum.github.io/yellowpaper/paper.pdf

The sender tells the network how many units of gas he wants to spend at maximum. This protects the sender from losing all its funds with a faulty transaction. If the transaction costs less gas than the maximum allowed amount, the remaining gas is returned to the sender.

Example: Bob creates a transaction and allows 10,000 units of gas to be spent, but the transaction costs only 7,500 gas. Then, he gets 2,500 back.

Each block has a certain maximum space of how much gas all transactions in it can cost in total. Therefore, the block producer needs to select the most profitable transactions. One indicator is the gas price (see below). But another indicator is the ratio between a transaction’s maximally allowed gas and the actually used gas.

If a block has space of 15 million gas and a transaction reserves a maximum of 15 million gas, then there is no space for other transactions. If this transaction has an actual gas consumption of only 1 million gas, then space of 14 million gas would be wasted. As we know, unused gas is returned to the sender. Hence, it is crucial to set the maximally allowed gas amount just a little higher than the expected actual gas consumption.

Red is the gas reserved and consumed by the transaction. Yellow is the reserved but not consumed gas of a transaction. Green is the total block space in gas.

Categories: