Gas is the unit used to measure the fees required for a particular computation on the Ethereum Network. In Bancor, token conversions require computations on the Ethereum Network which incur fees paid in gas to Ethereum "miners" (explained below).
Before we delve into how gas works, it's important to understand why it is necessary. Ethereum is a Turing complete language that can simulate any computer algorithm, including loops. If there were no gas fees, a malicious actor could easily try to disrupt the Ethereum Network by executing an infinite loop within a transaction, without any repercussions. Thus, fees protect the network from deliberate attacks.
Now let's define some terms:
Gas represents the relative complexity of operations. For example, adding two integers is less computationally intensive than multiplying them together, so addition uses less gas than multiplication.
Gas price is the amount of Ether a user is willing to spend on every unit of gas, and is measured in “gwei.” “Wei” is the smallest unit of Ether, where 1⁰¹⁸ Wei represents 1 Ether. One gwei is 1,000,000,000 Wei.
Gas limit represents the maximum gas the user is willing to spend on a transaction. If the user has enough Ether in their account balance to cover this maximum, the user is refunded for any unused gas at the end of the transaction, exchanged at the original rate. In the case that the user does not provide the necessary gas to execute the transaction, the transaction "runs out of gas" and is considered invalid. Additionally, a record of the transaction failing gets recorded, showing what transaction was attempted and where it failed. Since the machine already expended effort to run the calculations before running out of gas, none of the gas is refunded to the user.
With every transaction, a user sets a gas limit and gas price. The product of gas price and gas limit represents the maximum amount of Wei that the user is willing to pay for executing a transaction. For example, let’s say the user sets the gas limit to 50,000 and a gas price to 20 gwei. This implies that the user is willing to spend at most 50,000 x 20 gwei = 1,000,000,000,000,000 Wei = 0.001 Ether to execute that transaction.
While gas is fixed per operation, the amount a user pays per gas — gas price — is dynamic and dictated by market conditions. When a user sends a transaction, they specify the gas price in Gwei/Gas, and the total fee that they pay is equal to gas_price * gas_used.
Since miners expend the effort to run computations and validate transactions, miners receive the gas fee as a reward. Miners prioritize transactions with a higher gas price, so the higher gas price a user is willing to pay, the faster their transaction will be processed.