Getting into the world of Ethereum one of the learning curve has been about gas.
Gas is essentially how you track and then compute the cost you need to pay for the transaction you submit to the Etheruem network and is collected by the miners.
gasLimit, startGas, gasUsed, gasRemaining and gasPrice.
The fuel analogy is good but what helps me understand is the unit of measure for each.
I think of all these attributes except
gasPrice in the unit “cycle” (thinking about CPU cycles per instruction) while
gasPrice is “ETH/cycle”. The gasPrice is usally in WEI or GWEI (which is like cents to a dollar so GWEI/cycle).
Let us look at two important values:
gasPrice (the other attributes help compute
This is the number of cycles it takes to compute/store the transaction you submitted to the network. The number of cycles per instruction is predefined (in the the Yellow paper but this question has easier to understand links). This depends on the complexity of the contract you are using so how you write your code and what you execute will determine how many cycles you use. Note that both successful and failed transactions use gas.
This is the cost per cycle that you are willing to pay.
Analogy time! When you are driving around the gas statations prominently display the price. But what if gas stations stopped displaying their price, instead you get to ask “will you sell me gas for $X/gallon?” Then wait until you find a station that is willing to accept your offer. For example, at $1/gallon you will likely not be able to buy gas, while if you offer $10/gallon you will be taken for a sucker.
Similarly in the Ethereum world, you set the price you are willing to pay per cycle to the miners. Too low and your transaction may not be included in the next block (or take a long time). Also a very high price cannot process it faster than the next block anyway. Eth Gas Station provides good information on what you should set.
The total cost you pay is the number of cycles you consume (
gasUsed) multiplied by the price per cycle (
gasLimit are essentially synonyms in the context of submitting a transaction and is the maximum amount of gas you authorize the miners to use. If your code exceeds this then you get an out of gas error and you pay for this amount of gas. the
gasRemaining is an in progress balance as gas gets consumed and
gasUsed = startGas — gasRemaining. You always pre-pay the
startGas * gasPrice amount so anything remaining is refunded to you.
There are also some unknown heuristics that different miners employ on which transaction to pick based on these values so optimizing these could be critical to operations. I hope to learn more about this in the future.