Understanding Gas in Ethereum

WalkingTree Technologies
Coinmonks
7 min readJul 16, 2018

--

In Ethereum, Gas is a measurement unit of computational effort that is needed to be paid to the Ethereum Client to commit the transaction to the blockchain network. The senders of the message/transactions pay this cost. At the very high level, gas is the number of instructions used to execute a transaction in the Ethereum Virtual Machine. In Ethereum architecture, it ensures that an appropriate fee is being paid by transactions submitted to the network. By requiring that a transaction pays for each operation it performs, Ethereum ensures that the network doesn’t get misused.

The transactions could be as small as setting a message in the HelloWorld greetings contract, a contract deployment, a billion dollar business contract, payment (value) transfer, an ICO or anything which is not just a read only query on the network.

While there is a direct mapping between operations performed vs the gas, in the real world, we pay this cost in terms of Ether (the built-in token on the Ethereum network). The gas exists only inside of the EVM (Ethereum Virtual Machine) as a count of how much work is being performed. When it comes to paying for the gas, the transaction fee is charged in terms of Ether, which gets calculated based on the gas price.

There are primarily two ways to earn Ether, which can be used to perform any transaction/operation on the network

  • To mine yourself
  • To procure Ethereum from a third party

In this article, we will look at the different aspects of cost calculation and how it gets mapped to gas.

Gas as the CryptoFuel

As the transaction costs on the blockchain network, need to be paid by the sender in the form of Gas, which is a fuel in physical life, the Gas is also known as CryptoFuel.

Being a CryptoFuel, Gas is helpful is driving the smart contracts. The senders exchange gas for the currency known as Ether. The wallet sets a default minimum value for one unit of a gas. For example, the default could be 20 Shannon (0.02 Szabos, or 0.00000002 Ether). The sender (typically wallet developers) can change the cost to optimize the wait time of the transaction.

Influencing miners to pick your transaction

As you are aware that gas is used on the Ethereum network to facilitate the broadcasting and confirmation of transactions on the network. Every gas amount included in a network block serves as an extra incentive for miners to pick up a transaction. And hence, increasing the gas price allows users to attract miner towards this transaction and have their transfers confirmed quicker.

Hence, as a Wallet developers, the goal is to

  • Ensure that users’ transactions will be confirmed as quickly as possible
  • Users don’t have to overspend fees for transactions

Hence, when the transaction processing time becomes critical (e.g. in the case of crypto ICO), the developers inflate the gas price to get their transactions accepted ahead of other wallet’s users.

Measurement unit for gas and their conversion

The following table shows the conversion of different ether units:

**Credit**: https://etherconverter.online/

Ethereum Transaction Fee Schedule

Since every operation (i.e. every line of solidity code) in Ethereum would require some gas, it is important to understand the Ethereum Fee Schedule.

The following diagram from the whitepaper, shows the various measurements:

Also, the following are the subsets of instructions:

  • Wzero = {STOP, RETURN}
  • Wbase = {ADDRESS, ORIGIN, CALLER, CALLVALUE, CALLDATASIZE, CODESIZE, GASPRICE, COINBASE, TIMESTAMP, NUMBER, DIFFICULTY, GASLIMIT, POP, PC, MSIZE, GAS}
  • Wverylow = {ADD, SUB, NOT, LT, GT, SLT, SGT, EQ, ISZERO, AND, OR, XOR, BYTE, CALLDATALOAD, MLOAD, MSTORE, MSTORE8, PUSH*, DUP*, SWAP*}
  • Wlow = {MUL, DIV, SDIV, MOD, SMOD, SIGNEXTEND}
  • Wmid = {ADDMOD, MULMOD, JUMP}
  • Whigh = {JUMPI}
  • Wextcode = {EXTCODESIZE}

You may like to note the following:

  • Stop and returns cost zero gas
  • A minimum of 21000 gas is paid for a given transaction
  • A minimum of 32000 gas is paid for a contract creation

Gas Estimation vs Actual Gas Used

The Ethereum protocol charges a fee per computational step that is executed in a transaction. Every transaction is required to include a gas limit and a fee that it is willing to pay per gas and miners have the choice of including the transaction.

Assuming that the user is sending a valid transaction, if the total amount of gas used by the computational operations in the transaction is less than or equal to the gas limit, then the transaction is processed. However, if the total gas needed by the transaction exceeds the gas limit, then all changes are reverted. The transaction stays to be valid, however, the fee can still be collected by the miner for partially processing the transaction. All excess gas not used by the transaction execution is reimbursed to the sender as Ether. Hence, it is always suggested that you shall send transactions with a gas limit well above the estimates.

The API, web3.eth.estimateGas, gives you a rough idea about the gas you would need to execute a transaction. Here is a sample example of how to calculate the gas estimate:

When you make a real transaction, you get an output like following, which shows that 34476 gas were used.

The estimateGas API pretends as if this specific transaction is included in the Blockchain and its operations will be executed on the network. With this pretention, it uses the same mechanism that any miner will use to calculate the actual transaction fee.

While executing the transaction, a bit of overestimation is good. You don’t want to fall short on gas during the execution. Also, even with a bit of overestimation, there is no guarantee that the gas needed will not exceed the gas estimate that you have come up with.

Cost of a Transaction

The total cost of a transaction in the Ethereum network is based on two factors:

  • gasUsed is the total gas that is consumed
  • gasPrice specified in the transaction

Notes

  • Any reference to gas price in Ethereum network, specifically in the context of Ether, currency, a balance or a payment, should be assumed to be counted in Wei
  • Each operation in the EVM needs a certain amount of gas. For a valid transaction, based on the transaction code (e.g. solidity code), the operations get decided and hence the need of gas for each operation also get decided. gasUsed is the sum of all the gas for all the operations executed
  • When a user constructs and signs a transaction, he/she may specify whatever gasPrice they feel appropriate. Often they do transactions using a wallet and generally, wallet developer tries to optimize gas price for them to give them the best experience
  • Using the unit conversion table shown in the previous section, you can calculate the price in Ether, whose fiat currency value keeps on changing.

Example of Gas Usage and Cost Calculation using Ganache

Assuming that you have been using Ganache network for the deployment and testing of your contract, a basic HelloWorld kind of greetings contract will have following transactions:

Above image shows that the contract deployment and updating the version of the contracts put together cost around

By default, Ganache set the value of gas price as 100000000000. Currently, its UI value is not being picked up (a bug perhaps).

So, the total price = Total Gas * Default Price = 653001 * 100000000000 = 6.53 * 10 to power 16 = 6.5 / 100 Ether = .0653 ether

In above image, you can see that the initial balance of 100 ether gets reduced to 99.93 ether, which basically indicates that .0653 ether was already spent by this account on deploying the contracts.

We noticed 4-transactions corresponding to the contract deployment. If you want to further deep dive into this then let’s look at the transaction data and decode them into bytecode, called Opcodes, which is understood by the Ethereum EVM. Using the following website you can try to decode the same to see the exact operations that were performed during a given transaction:
https://etherscan.io/opcode-tool

Influences of transaction fuel and transaction fee on the transaction

The following table summarizes the influence of transaction fees and its influence on the transaction:

At the start of a transaction, the Ether required for the startGas is set aside, and the remainingGas is set to startGas. With each operation of the transaction, gas is consumed and remainingGas is lowered. If there’s an Out of Gas exception, all operations are reverted and all the Ether that was initially set aside is given to the miner. If the transaction completes successfully, all the remainingGas is refunded to the originator and the rest is paid to the miner.

You can refer to below URL for more details about gas information and recommendations:
https://ethgasstation.info/index.php

Source : https://walkingtree.tech/understanding-gas-in-ethereum/

--

--

WalkingTree Technologies
Coinmonks

WalkingTree is an IT software and service provider recognized for its passion for technology.