Calculating Ethereum or Binance Smart Chain gas...

in #ethereum2 years ago (edited)

Legacy transactions

Previously calculating gas was easy, as you could just specify gas amount, gas price and gas limit.

Gas amount is fee to compensate the computing power that a smart contract method execution or transferring either Ether or BNB costs.
Gas price is the amount of gwei (1/1000000000 Ether or BNB) the user is willing to pay for the each gas unit. This varies depending on network conditions.
Gas limit is the amount of gas that is reserved for the execution, this is usually more than the actual required amount of gas to execute the action.

Type 2 transactions

Priority fee is given to miner to encourage adding the transaction faster. It is limited by base fee and maximum fee.
Base fee is calculated based on number of transactions in previous block. Maximum fee is specified by sender of the transaction

Calculating gas

The current way of calculating gas amount is to ignore the suggested gas amount and rely solely on the gas limit. This skips the "estimateGas" function of the contract as it wasn't always accurate due to not having access to metadata of the full transaction. Now, a contract call will never run out of gas unless it throws an exception. Instead the effects of the call are reverted before the transaction is added to blockchain. Normal Ether and BNB transfers will always use 21000 gas even if the destination address is a contract.

To get the gas limit, it is required to fetch the metadata of the latest block. The metadata contains both the block gas limit and number of the transactions. By dividing the block gas limit by number of transactions, you will get approximate for maximum amount of gas that any transaction can spend. If the latest block has no transactions, and you have enough balance, you can skip the division step. Otherwise you still need to use the "estimateGas" method and add some extra to compensate the missing metadata. More you add, more likely your transaction will get added to blockchain in next few blocks. This also applies to increasing gas price. Block explorer will tell minimum gas price, selected gas price and maximum gas price for the specific transaction after it has been added to blockchain.