Architecture : Stox Architecture Overview — Part 2: Optimizing Gas Costs
Understanding Gas Costs
To better understand the concept of transactions gas, imagine a transaction as a car trip. A car needs fuel to reach its destination, and that fuel costs money. Car trip fuel costs are measured in price (Dollar / Euro / Other currency) per Litre / Gallon.
Just like fuel for a car trip, transactions need gas units to complete, and that gas costs Ether. When we send a transaction we specify the price we are willing to pay for a single gas unit. Gas units price specified in Gwei. A single Gwei equals 0.000000001 Ether.
In addition, the car has a fuel tank. If we don’t have enough fuel in the tank, we can’t finish the trip.
In a similar way, when we send a transaction we specify a gas limit. When the gas limit is not high enough, we can’t finish the transaction and it fails. Just like car fuel, If you haven’t used all of your gas limit you can use the leftover for the next transaction / car trip. It doesn’t get spent.
For convenience, here is a table comparing the different terms:
The total cost of the Car Trip / Transaction will be:
Total Cost = [Gas Amount] × [Price Currency]
Who gets the fees?
In the case of a car trip, the total cost of fuel will be paid to the gas station. In the case of an Ethereum transaction the gas fees go to the Ethereum miners. The miners determine if they are willing to mine this transaction according to the specified gas price. If the price is high enough they’ll include this transaction in the next block they are mining.
How do we know if the price is high enough?
The simplest answer is that it depends on market economics. Every minute there are dozens of pending transactions competing for the right to be included in the next block. Those which offer the higher price have a better chance to be mined.
Transactions with low gas price might wait a while before miners pick them up, and if the price is very low they might never get mined at all.
To fully understand the mechanism, we need to better understand how blockchain works, which I won’t go into in this blog post. It is enough to know that the price should be high enough to compete with other pending transactions.
For example let’s look at the following transaction on Etherscan:
This transaction transfers 0.5 ether for the price of 10 Gwei and a gas limit of 21,000. The gas used by the transaction was 21,000, which is the exact amount of gas limit the transaction sender specified, so we had just enough gas to complete it.
The total transaction cost is:
[21,000 Units of Gas] × [10 Gwei price for a single unit of gas] =
210,000 Gwei = 0.00021 Ether