Para calcular la tarifa de transacción utilizando web3js
el precio del gas:
eth.getTransaction("txhash").gasPrice
multiplicado por la cantidad de gas que se usó realmente:
eth.getTransactionReceipt("txhash").gasUsed
¿Es correcto? ¿Hay una manera más sencilla?
Si no tiene claro qué es el gas, le recomiendo leer las respuestas a la pregunta de StackOverflow "¿qué es el gas?" antes de ir más lejos.
El costo total de una transacción es el producto del límite de gas y el precio del gas :
(gas limit x gas price) = transaction fee
En web3js
los siguientes métodos están disponibles:
web3.eth.estimateGas
para estimar el límite de gasweb3.eth.getGasPrice
para estimar el precio del gasComo ejemplo, si desea transferir todo su ether, primero debe calcular la tarifa de transacción, restarla del saldo y luego realizar la transferencia:
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);
web3.eth.gasPrice
de los documentos, calcula el precio medio de la gasolina en los últimos bloques, está bien, cuando lo envíe ahora).Tomemos como ejemplo esta transacción real, una aleatoria
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)
Aquí puedes ver que
Fee = Gas_Used * Gas_Price
= 35531 (unit) * 0.000000008 (eth)
= 0.000284248 (eth)
Es posible que desee consultar la documentación de web3 . Como se describe allí, puede obtener el precio actual del gas de esta manera:
const gasPrice = web3.eth.getGasPrice();
El resto se ve bien.
mijail vladimirov