Loading...
Gas is the unit that measures the amount of computational work required to execute specific operations on the Ethereum network, different blockchain has different terms for it but function is the same.As each Ethereum transaction requires computational resources to execute, each transaction requires a fee. Gas refers to the fee required to successfully conduct a transaction on the Ethereum network.
Web3 module provides many function to work with gas fees and we will take a look into those in this Smartbook.
This function will return the current gas price and it is determined by the last few blocks median gas price.
Syntax
web3.eth.getGasPrice([callback])
Parameters
callback [ Function ] (optional) : It returns an error object as first parameter and the result as second.
Returns
It's promise returns number string of the current gas price in wei.
Example
const Web3 = require('web3');
Web3.eth.getGasPrice().then((res)=>{
console.log(res);
})
This function executes a message call or transaction and returns the amount of the gas used for that call/transaction.
Syntax
web3.eth.estimateGas( callObject [ , callback ] )
Parameters
callObject [ Transaction Object ] - Transaction or call object whose gas fees is to be estimated.
callback [ Function ] (optional) : It returns an error object as first parameter and the result as second.
Returns
Promise returns Number which is the used gas for the call/transaction.
Example
const Web3 = require("web3");
// In Simple Transaction
web3.eth.estimateGas({
to: "0x11f4d0A3c12e86B4b5F39B213F7E19D048276DAe",
data: "0xc6888fa10000000000000000000000000000000000000000000000000000000000000003"
}, function(error, estimated_gas){
console.log(estimated_gas);
});
// In Smart Contracts
myContract.methods.myMethod(123).estimateGas(function(error, estimated_gas){
console.log(estimated_gas);
});
We can use this method to get gas limit of a block in which out transaction is to be sent.
Syntax
block.gasLimit
Returns
Returns gas limit of a given block as number string in wei.
Example
const Web3 = require("web3");
var gas_limit;
Web3.eth.getBlock("latest" , (error, block) => {
gas_limit = block.gasLimit;
});
This method will return the total used gas by all transactions in this block.
Syntax
block.gasUsed
Returns
Returns gas used of a given block as number string in wei.
Example
const Web3 = require("web3");
var gas_limit;
Web3.eth.getBlock("latest" , (error, block) => {
gas_limit = block.gasUsed;
});