Disclosure: written by the Tronilend team, which runs a TRON Energy rental service.
Your service sent a USDT TRC-20 transfer, the explorer says FAILED, support tickets are coming in and someone asks the obvious question: "Do we just send it again?" Not yet. A TRON transaction receipt tells you exactly why the call failed, how much it cost and what has to change before a new attempt. This post walks through reading that receipt from the HTTP API, telling OUT_OF_ENERGY apart from REVERT, finding out whether fee_limit or the account's resources were the binding limit, and estimating the replacement correctly.
Everything here uses documented endpoints from the TRON developer docs. Examples use TronGrid's public Mainnet endpoint; any java-tron full node works the same way.
1. Where did it fail: broadcast or execution?
The TRON errors guide splits failures into three categories, and they need different handling:
- HTTP-level — the request never got a JSON answer. For a broadcast, the outcome is unknown: check the original txID before doing anything else.
- Validation — the node rejected the transaction before execution. The broadcast response carries a code such as CONTRACT_VALIDATE_ERROR, SIGERROR or BANDWITH_ERROR (protocol spelling). Nothing went on-chain.
- Execution — the transaction was included in a block, but the TVM run failed. This is where OUT_OF_ENERGY lives, and it is reported in the transaction info, not in the broadcast response.
If your logs show a successful broadcast and a FAILED explorer status, you are in category 3. Resources may already have been charged, and the same signed payload can never run again.
2. Pull the receipt
Two calls give you the full picture: the post-execution receipt and the transaction body (which holds fee_limit). Use the walletsolidity path to read solidified data:
TXID=<64-hex txid>
# Execution receipt
curl -s -X POST https://api.trongrid.io/walletsolidity/gettransactioninfobyid \
-H 'Content-Type: application/json' \
-d "{\"value\":\"$TXID\"}"
# Transaction body: raw_data.fee_limit and ret[0].contractRet
curl -s -X POST https://api.trongrid.io/walletsolidity/gettransactionbyid \
-H 'Content-Type: application/json' \
-d "{\"value\":\"$TXID\"}" | jq '{fee_limit: .raw_data.fee_limit, ret: .ret}'
An empty object {} from gettransactioninfobyid means the node has no solidified receipt yet. It does not mean the transaction failed. Wait and query again.
The fields that matter for Energy debugging:
| Field | Meaning |
|---|---|
| result (top level) | Present as FAILED when execution failed; omitted on success |
| resMessage | Error text, usually hex-encoded — decode it before reading |
| receipt.result | TVM outcome: SUCCESS, REVERT, OUT_OF_ENERGY, OUT_OF_TIME and others (16 enum values) |
| receipt.energy_usage_total | All Energy counted for the execution |
| receipt.energy_usage | Part covered by the caller's staked or delegated Energy |
| receipt.origin_energy_usage | Part covered by the contract deployer, if the contract shares costs |
| receipt.energy_fee | Sun burned to pay for Energy |
| receipt.net_usage / net_fee | Bandwidth consumed / sun burned for Bandwidth |
| fee | Total sun charged for the transaction |
| raw_data.fee_limit (tx body) | Caller-side cap, in sun |
One gotcha: the HTTP API serialises protobuf, so zero-valued fields are omitted. A receipt without energy_fee means zero sun was burned for Energy, not that the field is unknown. Default every numeric field to 0 in code.
3. OUT_OF_ENERGY vs REVERT: different failures, different bills
Both roll back state changes, so in both cases the USDT does not move. The difference is accounting, and the VM exception handling page spells it out:
| receipt.result | What happened | Energy charged |
|---|---|---|
| OUT_OF_ENERGY | The next operation needed more Energy than remained in the budget | All Energy available to the execution, including the unused remainder |
| REVERT | The contract stopped itself: require, revert, Solidity 0.8 Panic, failed inner call | Only the Energy used up to the failure point |
| OUT_OF_TIME | CPU time limit for one transaction exceeded, or a specific protocol check fired | The whole Energy allowance, like OUT_OF_ENERGY |
This matters for the fix. Adding Energy to a REVERT will not address the revert condition: inspect contractResult[0] (an Error(string) payload begins with 08c379a0). For OUT_OF_ENERGY, check both the available Energy/TRX and fee_limit before signing a new transaction.
4. Which limit stopped the call?
Per the FeeLimit & Energy cost page, the caller's usable Energy is the minimum of two numbers:
callerEnergyLimit = min(
callerStakedEnergy + (balance - callValue) / sunPerEnergy,
fee_limit / sunPerEnergy
)
Because an OUT_OF_ENERGY execution consumes the available allowance, the receipt and fee_limit can suggest which constraint was tightest, but they do not prove which one bound at the historical execution time:
- If the caller's share of energy_usage_total approaches fee_limit / sunPerEnergy, fee_limit may have been the binding cap. Recalculate using the Energy price in effect at execution time, examine resMessage, and verify available Energy/TRX.
- If it is below that cap, the account may have run out of staked/delegated Energy and burnable TRX. Raising fee_limit alone will not solve a genuine resource shortage.
- If energy_usage_total is 0, the receipt alone does not establish why. Inspect fee_limit and the full error message instead of assuming that the account had zero resources.
resMessage usually confirms it. Decoded OUT_OF_ENERGY messages follow the pattern Not enough energy for '<OPCODE>' operation executing: curInvokeEnergyLimit[...], curOpEnergy[...], penaltyEnergy[...], usedEnergy[...]. A curInvokeEnergyLimit[0] means the budget was zero from the first opcode.
Keep in mind that the price you query today may differ from the price at execution time, and for contracts that share costs with the deployer you have to subtract origin_energy_usage. Treat the comparison as a strong hint, not a proof.
5. A small diagnostic script
The script below puts the steps together. It needs Node 18+ (built-in fetch) and no dependencies. Set TRONGRID_API_KEY if you have one; public TronGrid works without it at a lower rate limit.
// diagnose-tx.mjs — inspect a confirmed TRON smart-contract execution receipt
// Usage: node diagnose-tx.mjs <64-hex txid>; Node 18+; optional TRON_NODE, TRONGRID_API_KEY.
const NODE = process.env.TRON_NODE ?? "https://api.trongrid.io";
const headers = { "Content-Type": "application/json" };
if (process.env.TRONGRID_API_KEY) headers["TRON-PRO-API-KEY"] = process.env.TRONGRID_API_KEY;
async function post(path, body = {}) {
const res = await fetch(`${NODE}${path}`, { method: "POST", headers, body: JSON.stringify(body) });
if (!res.ok) throw new Error(`${path}: HTTP ${res.status}`);
const data = await res.json();
if (data.Error) throw new Error(`${path}: ${data.Error}`);
return data;
}
async function currentEnergyPrice() {
const res = await fetch(`${NODE}/wallet/getchainparameters`, { headers });
if (!res.ok) throw new Error(`getchainparameters: HTTP ${res.status}`);
const { chainParameter = [] } = await res.json();
return chainParameter.find((p) => p.key === "getEnergyFee")?.value;
}
const decode = (s) => s && /^(?:[0-9a-fA-F]{2})+$/.test(s)
? Buffer.from(s, "hex").toString("utf8") : s;
const txid = process.argv[2];
if (!/^[0-9a-fA-F]{64}$/.test(txid ?? "")) {
console.error("Usage: node diagnose-tx.mjs <64-hex txid>");
process.exit(1);
}
const info = await post("/walletsolidity/gettransactioninfobyid", { value: txid });
if (!info.id) {
console.log("No solidified receipt yet. An empty response does NOT prove failure or absence.");
console.log("Track the original txID; do not build a replacement based on this response.");
process.exit(0);
}
const tx = await post("/walletsolidity/gettransactionbyid", { value: txid });
const energyPrice = await currentEnergyPrice(); // today, possibly NOT the execution-time price
const r = info.receipt ?? {};
const energyTotal = r.energy_usage_total ?? 0;
const energyStaked = r.energy_usage ?? 0;
const originEnergy = r.origin_energy_usage ?? 0;
const energyFee = r.energy_fee ?? 0;
const netFee = r.net_fee ?? 0;
const feeLimit = tx.raw_data?.fee_limit ?? 0;
console.log({
receiptResult: r.result ?? "(missing)",
topLevelResult: info.result ?? "(omitted)",
contractRet: tx.ret?.[0]?.contractRet ?? "(missing)",
resMessage: decode(info.resMessage) ?? "",
energyTotal, energyStaked, originEnergy,
energyFeeTRX: energyFee / 1e6,
netFeeTRX: netFee / 1e6,
bandwidthUsed: r.net_usage ?? 0,
totalFeeTRX: (info.fee ?? 0) / 1e6,
feeLimitTRX: feeLimit / 1e6,
currentEnergyPriceSun: energyPrice ?? "unavailable",
});
switch (r.result) {
case "SUCCESS":
console.log("Execution says SUCCESS; also check the top-level result and token event logs.");
break;
case "OUT_OF_ENERGY": {
if (!energyPrice || !feeLimit || !energyTotal) {
console.log("Inspect resMessage and fee_limit; budget cause cannot be inferred from these fields alone.");
break;
}
const callerShare = Math.max(0, energyTotal - originEnergy);
const feeLimitCap = Math.floor(feeLimit / energyPrice);
if (callerShare >= feeLimitCap) {
console.log("fee_limit MAY have been binding. Compare against the execution-time energy price and error message.");
} else {
console.log("Available Energy/TRX MAY have been exhausted first. Check the historic account balance and error message.");
}
console.log("Correct the cause, then create a NEW transaction; a confirmed failed txID cannot execute again.");
break;
}
case "REVERT":
console.log("Read contractResult[0] and decode the ABI revert reason when present; more Energy alone will not fix it.");
break;
case "OUT_OF_TIME":
console.log("Check resMessage: the cause may be an execution timeout or a protocol check.");
break;
default:
console.log("Check the receipt enum and the top-level result in the TRON documentation.");
}
Run it with node diagnose-tx.mjs <txid>. It prints the solidified receipt, execution outcome and a cautious diagnosis. The fee_limit comparison uses the CURRENT network rate, so confirm it against the rate and account state at the time of execution before treating it as the root cause.
6. Estimate the replacement — per recipient
For USDT, the replacement must be estimated against the actual recipient. Writing to an empty balance slot costs more, so a transfer to an address with no USDT needs roughly twice the Energy of a transfer to a holder — around 131,000 vs 65,000 as orientation figures, not guarantees. Re-using an estimate made for another address is a common way to fail twice.
triggerconstantcontract dry-runs the exact call on the node without creating a transaction:
curl -s -X POST https://api.trongrid.io/wallet/triggerconstantcontract \
-H 'Content-Type: application/json' \
-d '{
"owner_address": "<sender base58>",
"contract_address": "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t",
"function_selector": "transfer(address,uint256)",
"parameter": "<32-byte recipient><32-byte amount>",
"visible": true
}' | jq '{ok: .result.result, energy_used, energy_penalty, msg: .result.message}'
parameter is ABI-encoded: the recipient as its 20-byte hex address (Base58Check-decoded, without the 41 prefix) left-padded to 64 hex characters, followed by the amount in base units (USDT has 6 decimals) as a 64-character hex number. energy_used is the total Energy and energy_penalty the Dynamic Energy Model share inside it. Two things to watch:
- The simulation runs as the sender. If the sender does not hold the amount, the dry run reverts — that is a balance problem, not an Energy problem.
- estimateenergy has the same interface and returns energy_required, but it is optional on full nodes. A node without it answers this node does not support estimate energy; the docs recommend falling back to triggerconstantcontract.
7. Size fee_limit with the Dynamic Energy Model in mind
The Dynamic Energy Model raises a busy contract's cost via an energy_factor that is recalculated every maintenance period (currently 6 hours on Mainnet). The fee_limit page lists three sizing strategies:
- max_factor: fee_limit = floor(base_estimate × (1 + max_factor)) × EnergyPrice. The chain parameter getDynamicEnergyMaxFactor currently returns 34,000, i.e. max_factor = 3.4. Simple, but over-budgets.
- Per-contract energy_factor: read contract_state.energy_factor from wallet/getcontractinfo each period. Tighter, needs refreshing.
- Estimate before every call: fee_limit = estimated_total_energy × EnergyPrice, plus a buffer. Most accurate, one extra round-trip.
Whichever you pick, remember the min() above: a generous fee_limit is only a ceiling. The account still needs Energy or TRX to fill it.
8. Retry rules that prevent a second OUT_OF_ENERGY
- Never re-broadcast a transaction that has an execution receipt. The txID already executed; diagnose and sign a new one.
- Never sign a replacement while the original broadcast outcome is unknown. Query the original txID first, or you risk two successful transfers.
- Re-check the token balance. After a rollback it should be unchanged.
- Re-estimate for the current recipient and the current maintenance period.
- Make the account able to cover the estimate: staked or delegated Energy first, TRX for the rest. If Energy is delegated by a third party, poll wallet/getaccountresource until EnergyLimit - EnergyUsed covers the estimate before building the transaction.
- Set fee_limit explicitly and check raw_data.fee_limit before signing.
Wrap-up
FAILED is a summary; the receipt is the diagnosis. Read receipt.result and resMessage, check both fee_limit and available Energy/TRX, then re-estimate for the actual recipient. The comparison to today's getEnergyFee is a diagnostic clue rather than proof of the historical constraint.
Top comments (0)