Ethereum "Gas" - How it Works

in #ethereum7 years ago (edited)

Purpose


Understanding how gas works is crucial for Ethereum users interested in participating in ICOs, using smart contracts, and even making simple transfers between wallets. In this post, I hope to explain what gas is and how it works. Skip to the end for a simple summary of things. To start off, we need to understand some basics about the Ethereum Virtual Machine.

Ethereum Virtual Machine and Gas


The Ethereum Virtual Machine (EVM) is a major part of the Ethereum ecosystem, but I'll be heavily glossing over this so we can focus on how it relates to gas. In short, the EVM is an environment where arbitrary code of smart contracts and other operations can be executed. Every node in the Ethereum network executes operations within the EVM to ensure redundantly correct execution and relies on consensus to agree on the answer.

All transactions, from simple transfers to ICO smart contracts, require some amount of operations to perform. Each of these operations has an associated cost in gas. Thus, simple transactions like transfers will require less gas to perform than more intense smart contracts.

For example, a simple operation like if(var > 1) may cost 1 gas, but a more complex operation to store a variable could cost 100 gas. The cumulative sum of all the operations is the total gas cost for the transaction.

Gas Limit


When on a site like MyEtherWallet, you're going to see a field called Gas Limit. This corresponds the the MAXIMUM amount of gas you are willing to spend on the transaction.
Important to note:

  • Different types of transactions will require different amounts of gas to complete
  • Providing too little gas will result in a failed transaction, the fees are kept by the miner
  • Extra, unspent gas is refunded automatically

What happens if I specify too little gas?

Your transaction will start to be executed, but will eventually run out of gas and be stopped. When this happens, you will not get back ether spend on the gas used, but since the transaction did not complete, the blockchain does not reflect a transfer, so the main funds essentially never left the wallet.

So I should always specify a large gas limit since I'll be refunded?

No. The minimum gas limit for transaction is 21000 + the amount to execute any fallback functions if it's sent to a contract, but the actual blocks also have a gas limit that specifies the maximum amount of gas all transactions in the block can consume. This is comparable to Bitcoin's block size in bytes, but ether miners have the option to increase or decrease the gas limit of blocks so that they are propagated quickly. You cannot exceed this amount if you wish for your transaction to be processed. Also, miners only get paid for the actual gas consumed by a transaction, so putting a high value for the gas limit fills up the block gas limit, but isn't computationally-dense enough for miners to want.

Gas Price


Gas price is the amount of ether you are willing to spend on every unit of gas. Yes, you determine the price of gas AND maximum amount of gas you want to spend on performing a transaction on the Ethereum network. Although gas limit is just a simple quantity, gas price is measured in ether (specifically some amount of wei, usually gwei). The value of gas is driven by the market and the nodes that prioritize higher gas prices when mining transactions. The current gas price can be seen on Etherscan or EthGasStation. As I mentioned, gas price is usually some amount of gwei. Wei is the smallest unit of ether, and gwei is simply 1000000000 wei. To put this in perspective, check out this code below:

var unitMap = {
    'wei':          '1',
    'kwei':         '1000',
    'ada':          '1000',
    'femtoether':   '1000',
    'mwei':         '1000000',
    'babbage':      '1000000',
    'picoether':    '1000000',
    'gwei':         '1000000000',
    'shannon':      '1000000000',
    'nanoether':    '1000000000',
    'nano':         '1000000000',
    'szabo':        '1000000000000',
    'microether':   '1000000000000',
    'micro':        '1000000000000',
    'finney':       '1000000000000000',
    'milliether':   '1000000000000000',
    'milli':        '1000000000000000',
    'ether':        '1000000000000000000',
    'kether':       '1000000000000000000000',
    'grand':        '1000000000000000000000',
    'einstein':     '1000000000000000000000',
    'mether':       '1000000000000000000000000',
    'gether':       '1000000000000000000000000000',
    'tether':       '1000000000000000000000000000000'
};

from https://github.com/ethereum/web3.js/blob/0.15.0/lib/utils/utils.js#L40

Setting Gas Limit and Gas Price


If you're using MetaMask, you will see something like this when trying to send Ether:

Here you can see that the gas limit has been set to 31500 and the gas price at 20 gwei. This means we are only willing to spend a maximum on 31500 gas at the price of 20 gwei / gas on the transaction. 31500 x 20 gwei = .000630 ether.

MyEtherWallet has the Gas Limit field, but no Gas Price for their transactions.
*I assume they calculate Gas Price depending on the market value

Edit- MEW has a slider at the bottom right of the site for adjusting gas price.

Summary


  • Transactions on the Ethereum network require fees in the form of gas. The amount of gas depends on the amount of computation required to complete the transaction.
  • Gas Limit is the maximum amount of gas allotted to the transaction, 21000 being sufficient for simple transfers and much higher amounts for transfers to smart contracts like those in ICOs.
  • Insufficient gas in the Gas Limit will result in a failed transaction, the fee paid will be lost, but the ether transferred never leaves the wallet since the blockchain was never updated.
  • Gas Price is the price of each gas unit measured in a fractional amount of ether, typically gwei. Gas price varies, but 20-30 gwei is average as of writing this.
  • Current Gas Price can be checked online ( Etherscan or EthGasStation ), and the Gas Limit for things other than simple transfers can only be known by looking at the smart contract code or by looking at what the organization behind the ICO / smart contract says is appropriate for their smart contract.

Handy Sites

EthStats
Etherscan
EthGasStation
Ethereum and ERC20 token wallet, MyEtherWallet
MetaMask Chrome Plugin

Consider leaving a like or even resteem if you found this helpful! If you're really crazy, my MEW address is 0x5B13430b6D2E327DFCDB93D7430FC6e9a2E63E74. Please feel free to leave corrections and comments below :)

Sort:  

Hey, very helpful, but what's the MINIMUM amount of gwei to put to let the transaction does not fail? i mean, if i set 0.1 gwei, the transaction may go into "limbo" and never execute? if yes, what is the minimum price?( don't care if it will be slow)

There isn't one. You can do 0 gwei and miners can accept it if they want. It may never actually be accepted, but it can be.

Thanks, but do you think that with 0.1 or 0.5 gwei might be accepted or there are some chances to never be accepted? i must do thousands of transactions, so i'm trying to spend as low as possible..

If you're asking about chance, then sure, there's a chance they may never be mined.. It depends on the transaction pool, how long you want to wait, and what miners are willing to accept.

I've done 0 gwei free transactions before, and I've had problems with 20 gwei transactions never being mined. It depends.

If you're sending thousands of separate transactions, you're not really using cryptocurrency very intelligently. There are better, and cheaper ways.

Thanks a bunch man! I have multiple MEW accounts and this helped a lot in loading my ETH wallets for transfer fees. :D

thank you. No one has explained it properly like you did in this post. Thanx again!!

Glad it was helpful!

I have 1 question. What would it be the highest gas posible? And how would it cost? THX

As I mention in the post, there is a limit to the amount of gas a block can have, so the maximum gas a transaction could have and still be accepted is limited by this block size. See https://ethstats.net/ "gas limit" section to see the block gas limit (it's dynamic).

There is no maximum gas price, but it's bounded by the largest number you can put into that field. IIRC, every number is 128 bits, so it would be 2^128 - 1.

If this is how ethereum works, then that's some bullshit right there. A failed contract took an $18.00 fee in ethereum from me. If there is any error error then kiss your fee goodbye. Sounds like bad business to me.

I doubt the contract was written incorrectly, so it's likely that you either executed it improperly or executed it properly but you didn't know what it would do and it turned out different than what you expected.

In either case, you set the gas price and agreed to "lose" your money. It's your fault, not the Ethereum Networks, and almost certainly not the contract's.

@tomshwom Do you know how it feels like when all of your hard earned money were gradually evaporating into oblivion just because of this apparent bulshit called GAS?

It's your fault, not the Ethereum Networks

Wow! You must be kidding me. There is nowhere you can find any upfront information on the amount of bulshit they'll be needing in order to process your transaction with ease. It smells fishy right there, isn't it?

As a result, I needed to do the guesswork and lost all my money in the process because there was no refund whatsoever. WTF!

Tried doubling my initial attempt, tripled and so on. They all failed. This is a total garbage. I am new to all this crypto activities but this I can tell you. I have never been into this type of crap.

You don't experience this in BTC, DASH, STEEM, this is only in Shithereum.

Things like this should not be tolerated. This is money grabbing in-your-face! Anyway, the days of Shithereum are counted. Enjoy the crypto robbery while you still can. The moment EOS runs fully operational, it's over for this nonsense.

EOS will soon send Shithereum to the place where it belongs---to the GARBAGE LANDFILL.

This has been really helpful. I'm already in BTC, LTC and a few alts but recently purchased some Ether to play around with CryptoKitties and the Gas/Gwei thing was a little confusing from the outside. Not as worried about being overcharged now. Thanks! :)

This is a great explanation of ETH transaction fees, I have always steered away from ETH because of this learning curve. Thank you so much for taking the time to make this more clear for the ones newer in the crypto space like myself.

thank you so much!

Excellent explanation !!
Compliments. Thanks for sharing.

This post has helped me to understand gas and gwei. thanks.

So I came here expecting to learn about gas price and gas limit but it still seems confusing. Why the separation of the two? Why not have just one fee? I can add much gas and pay little for it or add little gas and pay a fortune for it. What is the difference exactly?

Gas itself exists to accurately represent computational work. Ether, and thus value, is not a good measurement of this work because the value is so volatile. Can you imagine if there was a flat fee in Ether that you paid for transactions, and it was set when Ether was $10? Why would you pay 50x more for the same work just because Ether is worth more?

You need gas so that somebody doesn't write code to execute an infinite loop that would stall the blockchain. You need gas so that each individual opcode in the EVM can be accurately weighted proportionally to electrical costs (or other costs such as storage) of performing the operation.

The actual fee is up to the free market to determine via gas price, but the computation is a set amount and needs a separate unit to be represented in.

A quick question arose from "So I should always specify a large gas limit since I'll be refunded?" phrase from your article.

A function takes 40,000 Gas Units to execute. Which one of the following function calls will miner prefer to take?

  1. Call with 100,000 Gas Units.
  2. Call with 50,000 Gas Units.

Provided that the miner is paid for just 40,000 gas unit operations, they will prefer 2nd function call as it takes less total block size limit compared to 1st call.

Does the algorithm for tx selection from txpool work like this?

Preferring the call with 50k is better for the miner since it frees up 50k in the block for additional transactions hat will actually result in fees.

However, I had a conversation with the person behind a lot of the ethgasstation.info site programming and we found that this is not how actual miners are working. Looking at historical transactions, miners are pretty dumb. They almost always prefer higher gas price and don't look at gas limit, regardless of whether it's high or low.

Miners don't usually account for gas limit until it exceeds 1M or so, in which case they simply ignore it regardless of gas price.

For a demographic that thrives on cost optimization, this was a strange result to find. I'd expect it to change in the future, but who knows.

Coin Marketplace

STEEM 0.31
TRX 0.11
JST 0.034
BTC 66765.98
ETH 3234.00
USDT 1.00
SBD 4.23