For calculating the transaction fee using web3js I am using it's gas price:


multiplied by how much gas was actually used:


Is it correct? Is there a simpler way?

  • Yes, your method is correct and it probably the simplest one available via Web3js. – Mikhail Vladimirov Nov 11 '19 at 6:26

What is Gas?

If you are unclear on what gas is, I recommend reading the answers to the StackOverflow question "what is gas?" before going any further.

Calculating the Transaction Fee

The total cost of a transaction is the product of the gas limit and gas price:

(gas limit x gas price) = transaction fee

In web3js the following methods are available:

As an example, if you want to transfer all of your ether you first need to calculate the transaction fee, subtract that from the balance, and then do the transfer:

var sender = web3.eth.accounts[0];
var receiver = web3.eth.accounts[1];
var balance = web3.eth.getBalance(sender);
var gasPrice = web3.eth.getGasPrice(); // estimate the gas price

var transactionObject = {
  from: sender,
  to: receiver,
  gasPrice: gasPrice,

var gasLimit = web3.eth.estimateGas(transactionObject); // estimate the gas limit for this transaction
var transactionFee = gasPrice * gasLimit; // calculate the transaction fee

transactionObject.gas = gasLimit;
transactionObject.value = balance - transactionFee; // set the transaction value to the entire balance, less the transaction fee

web3.eth.sendTransaction(transactionObject, myCallbackFunction);
  • ty for detailed explanation). It's all okey, when I send transactions by my own. But, when u have a payment system, which need to listen transactions for some accounts, this accounts could send transaction with another gas value (for example 30000) or this gas value could change in future, be much higher, and use all this 30000 amount of gas, and it wont be incorrect to calculate fee on already mined transactions. web3.eth.gasPrice from docs it calculates on latest blocks median gas price, it's okey, when u send it now). – DeV1doR Jul 10 '17 at 8:43
  • Wrong !!!!. the formula is gas_used x gas_price . if I have a limit of 1000 and used only 210, the fee is 210 x gas_price and NOT 1000 x gas_price – realtebo Apr 9 '20 at 9:43

You might want to look at the web3 documentation. As described there, you can get the current gas price like this:

var gasPrice = web3.eth.gasPrice;

The rest looks good.


Take for example this real transaction, a random one


Transaction Fee:
0.000284248 Ether ($0.05)
Gas Limit:
Gas Used by Transaction:
35,531 (26.03%)
Gas Price:
0.000000008 Ether (8 Gwei)

Here you can see that

Fee = Gas_Used * Gas_Price 
    = 35531 (unit) * 0.000000008 (eth)
    = 0.000284248 (eth)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.