10

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

eth.getTransaction("txhash").gasPrice

multiplied by how much gas was actually used:

eth.getTransactionReceipt("txhash").gasUsed

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 at 6:26
18

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
1

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.

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.