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);