Gas in Ethereum is the number of ethers required to execute a smart contract or transaction on the blockchain network. Viewing data on the blockchain is free, but to alter the state of data or perform some calculations, we need a transaction. And to perform a transaction, we need to pay this amount. It is basically used by the miner to perform calculations on your behalf.
Smart contracts in Ethereum are written in a programming language known as Solidity. Unlike Bitcoin Scripting Language, solidity is a Turing complete language. This means smart contracts are Turing complete. They can potentially run/execute forever and make the entire network unavailable.
Note: A language is Turing complete if, before running a program, we can tell whether it will halt/terminate or not.
Further, this can be used to perform a DDoS attack on the network. To solve this limitation, the concept of gas price was introduced.
In simple terms, we can consider gas as the price we pay someone, such as a miner, to execute our code. This price depends on the number and type of operations in the code.
Gas price for some of the common operations is given below:
Operation | Gas Used |
Addition | 3 |
Subtraction | 3 |
Multiplication | 5 |
Divison | 5 |
Equal | 3 |
Let's say we have this function that performs some basic calculations. We can use the above table to calculate the gas price:
function doMath(int a, int b) {a + b; // Gas Used = 3b - a; // Gas Used = 3a * b; // Gas Used = 5a == b; // Gas Used = 3}
+
uses 3 gas.-
uses 3 gas. *
uses 5 gas.==
uses 3 gasSo, to execute doMath
function on blockchain we need 3 + 3 + 5 + 3 = 14 Gas.
We have talked about gas in generic terms. Now, let's look at different terms associated with gas on a technical level.
It is the amount of Wei the sender of the transaction is willing to pay per unit of gas to get the transaction processed. So, if we offer a gas price of 10, that means we are willing to pay 10 * 3 = 30
to add two numbers.
Note: Wei is the smallest unit of ether.
It is the maximum units of gas that the sender is willing to pay to perform the transaction.
For example, we say that we need 14 gas limit or start gas for the above code. However, we can't always compute the gas limit ahead of time. An example would be a for
loop over a collection of records that grow or shrink in size over time. So, the purpose of the gas limit is to say we are willing to pay at most this many units of gas to call this function.
The important thing to note here is that if our gas limit is more than the actual gas used, we'll be returned the remaining amount. But, if the gas limit is less than the actual gas needed to execute the code, we'll lose our gas, and the transaction will fail.