To calculate the energy used by a contract invocation with TronWeb I'm using this snippet of code
const { required_energy } = await tron.current.transactionBuilder.estimateEnergy(
contractAddress,
"transfer(address,uint256)",
{},
[
{ type: "address", value: address },
{ type: "uint256", value: tokenAmount }
]
)
or you can also use the equvalent calling triggerConstantContract (the results are similar)
const { energy_used } = await tron.current.transactionBuilder.triggerConstantContract(
contract,
"transfer(address,uint256)",
{},
[
{ type: "address", value: address },
{ type: "uint256", value: tokenAmount }
]
)
In my case I'm trying to estimate the energy required to send USDT TRC20 TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
In the vast majority of the cases the energy obtained is roughly equivalent to 14 TRX. So I can safely set the feeLimit to broadcast the transaction to 14 TRX + a little safety margin.
But then when the contract usage spikes the transaction requires like double the energy than usual, the strange thing is that the results obtained from estimateEnergy and triggerConstantContract do not follow the energy spike.
transaction working as expected with 14 trx as fee https://tronscan.org/#/transaction/f62cf944a51803951817790fd4aeb44c85e0c5a0f101ba9d4fb9021f29bd4656
transaction that consumed twice the trx amount https://tronscan.org/#/transaction/20a8df98b6695aeee73764efcb25ec4c313fdd56a56c60265d767c88833ac929
transaction that went out of gas due to the unexpected behaviour https://tronscan.org/#/transaction/ea83db2e220c22530358495dfc26f9adf671de731408cfbfd51d4d6205280556
So how can I get the correct fee preview?