Web3js

如何計算交易費用?

  • March 21, 2022

使用web3js我使用它的 gas 價格計算交易費用:

eth.getTransaction("txhash").gasPrice

乘以實際使用的氣體量:

eth.getTransactionReceipt("txhash").gasUsed

這是正確的嗎?有沒有更簡單的方法?

什麼是氣體?

如果您不清楚什麼是氣體,我建議您閱讀 StackOverflow 問題“什麼是氣體?”的答案。在繼續之前。

計算交易費用

交易的總成本是gas 限制和 gas 價格的乘積

(gas limit x gas price) = transaction fee

web3js以下方法中可用:

例如,如果你想轉移所有的乙太幣,你首先需要計算交易費用,從餘額中減去,然後進行轉移:

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

以這個真實的交易為例,一個隨機的

https://etherscan.io/tx/0xcb1e3530950cf2c43a307bcb5645ae71a12c76a60831617badd04aea3efe68aa

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

在這裡你可以看到

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

引用自:https://ethereum.stackexchange.com/questions/19665