<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[TRONILEND]]></title><description><![CDATA[TRONILEND]]></description><link>https://tronilend.hashnode.dev</link><image><url>https://cdn.hashnode.com/uploads/logos/6afda8069b733cda87c281d5/3823f8ed-6328-4427-ba03-6dadabc875f9.png</url><title>TRONILEND</title><link>https://tronilend.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 21 Nov 2026 19:04:19 GMT</lastBuildDate><atom:link href="https://tronilend.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Building a Pre-Transfer Energy Check for USDT on TRON]]></title><description><![CDATA[A TypeScript preflight that estimates Energy, Bandwidth and fee_limit before signing a USDT TRC-20 transfer on TRON.]]></description><link>https://tronilend.hashnode.dev/building-a-pre-transfer-energy-check-for-usdt-on-tron</link><guid isPermaLink="true">https://tronilend.hashnode.dev/building-a-pre-transfer-energy-check-for-usdt-on-tron</guid><category><![CDATA[tron]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[Blockchain]]></category><category><![CDATA[Web3]]></category><category><![CDATA[api]]></category><dc:creator><![CDATA[TRONILEND]]></dc:creator><pubDate>Wed, 18 Nov 2026 13:57:06 GMT</pubDate><content:encoded><![CDATA[<p>A USDT transfer on TRON that runs out of Energy rolls back the token transfer, but can still consume Energy and burn TRX. A preflight can reduce failed attempts for an app, bot or payout service. This example estimates the current execution needs, fee_limit budget and Bandwidth costs before signing; it is not a guarantee of execution.</p>
<h2>What the preflight has to know</h2>
<p>Three numbers decide whether the call will finish:</p>
<ol>
<li><strong>How much Energy this exact transfer needs.</strong> For USDT it depends mostly on the recipient: about 65,000 Energy if the recipient already holds USDT, about 131,000 if their balance is zero. These are orientation figures; TRON's <a href="https://developers.tron.network/docs/paying-for-resources">Dynamic Energy Model</a> moves the real cost over time.</li>
<li><strong>How much the sender can cover.</strong> Available staked or delegated Energy, plus TRX the network may burn at the current price (the <code>getEnergyFee</code> chain parameter, 100 sun per Energy at the time of writing), all capped by the transaction's <code>fee_limit</code> - see <a href="https://developers.tron.network/docs/set-feelimit">FeeLimit &amp; Energy cost</a>.</li>
<li><strong>Whether something else will fail anyway.</strong> Not enough USDT, an unactivated address or missing Bandwidth are not solved by Energy.</li>
</ol>
<p>We will get these from two independent sources and take the more conservative answer.</p>
<h2>Source 1: Tronilend's public address check</h2>
<p>Tronilend publishes an open endpoint documented on its <a href="https://tronilend.com/developers">developer page</a>: <code>GET https://tronilend.com/api/check</code>. It needs no key and is limited to 30 requests per minute per IP. Pass the sender as <code>address</code> and, when you know it, the recipient as <code>recipient</code> - the requirement doubles for a recipient without USDT.</p>
<pre><code class="language-bash">curl "https://tronilend.com/api/check?address=&lt;SENDER&gt;&amp;recipient=&lt;RECIPIENT&gt;"
</code></pre>
<p>The documented response contains the sender's state (<code>activated</code>, <code>trx</code>, <code>usdt</code>, <code>energy</code>, <code>bandwidth</code>), the recipient's <code>hasUsdt</code>, plus <code>energyNeeded</code>, <code>energyMissing</code>, <code>bandwidthMissing</code>, <code>needsActivation</code> and <code>ready</code> (true when nothing has to be bought). It also returns <code>pack</code> and <code>canPayInstant</code>, which relate to Tronilend's own Energy packages; the preflight below ignores them and keeps only the neutral resource data. Errors come back as <code>{ "error": { "code": ... } }</code>, for example <code>invalid_address</code> with HTTP 400 or <code>rate_limited</code> with 429.</p>
<h2>Source 2: the TRON node itself</h2>
<p>The node can answer the same questions from first principles:</p>
<table>
<thead>
<tr>
<th><strong>Endpoint</strong></th>
<th><strong>What we take from it</strong></th>
</tr>
</thead>
<tbody><tr>
<td><a href="https://developers.tron.network/reference/triggerconstantcontract">wallet/triggerconstantcontract</a></td>
<td>Dry run of <code>transfer(address,uint256)</code> as the sender: <code>energy_used</code> (total, including the Dynamic Energy penalty), <code>energy_penalty</code>, and whether the call would succeed</td>
</tr>
<tr>
<td><a href="https://developers.tron.network/reference/getaccountresource">wallet/getaccountresource</a></td>
<td>EnergyLimit - EnergyUsed = available Energy; check NetLimit - NetUsed and freeNetLimit - freeNetUsed independently, never add them for a transaction</td>
</tr>
<tr>
<td>wallet/getaccount</td>
<td>TRX <code>balance</code> in sun</td>
</tr>
<tr>
<td><a href="https://developers.tron.network/reference/wallet-getchainparameters">wallet/getchainparameters</a></td>
<td>getEnergyFee and getTransactionFee: current Energy/Bandwidth burn rates; getMaxFeeLimit: maximum fee_limit</td>
</tr>
</tbody></table>
<p>The dry run is the most precise signal because it executes the real call against current contract state. <a href="https://developers.tron.network/reference/estimateenergy">estimateenergy</a> is an alternative, but it is optional on full nodes and public endpoints may answer <code>this node does not support estimate energy</code>; the TRON docs recommend <code>triggerconstantcontract</code> as the default. Also note that zero-valued fields are omitted from these JSON responses, so a fresh account returns no <code>EnergyLimit</code> at all.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6afda8069b733cda87c281d5/2500b760-81e5-490c-a1a0-cac6c24e0b86.png" alt="Flowchart showing how to validate a TRON address, check Energy and Bandwidth, estimate resources, verify TRX and fee_limit, and determine whether a USDT transfer is ready." style="display:block;margin:0 auto" />

<h2>The preflight in TypeScript</h2>
<p>No external SDK: this example uses built-in fetch and node:crypto to validate TRON Base58Check addresses before ABI-encoding them. Save it as preflight.mts and run it with Node 22.6+ (type stripping) or compile with TypeScript and Node type definitions.</p>
<pre><code class="language-ts">// preflight.mts - estimate USDT transfer readiness; do NOT treat this as a guarantee
// Node 22.6+: node --experimental-strip-types preflight.mts &lt;sender&gt; &lt;recipient&gt; &lt;amountUSDT&gt;
// Or compile with TypeScript and run the JavaScript output.

import { createHash } from "node:crypto";

const TRONILEND = "https://tronilend.com";
const NODE = process.env.TRON_NODE ?? "https://api.trongrid.io";
const USDT = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"; // Mainnet TRC-20 USDT
const MARGIN = 0.1; // 10% Energy buffer; state and network parameters can change
const ESTIMATED_BANDWIDTH = 400; // planning allowance, NOT an exact transaction size
const headers: Record&lt;string, string&gt; = { "Content-Type": "application/json" };
if (process.env.TRONGRID_API_KEY) headers["TRON-PRO-API-KEY"] = process.env.TRONGRID_API_KEY;

async function rpc&lt;T&gt;(path: string, body: unknown): Promise&lt;T&gt; {
  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 as T;
}

async function chainParameters(): Promise&lt;Record&lt;string, number&gt;&gt; {
  // This endpoint is documented as GET, unlike the transaction RPC endpoints.
  const res = await fetch(`${NODE}/wallet/getchainparameters`, { headers });
  if (!res.ok) throw new Error(`getchainparameters: HTTP ${res.status}`);
  const json = await res.json();
  const values: Record&lt;string, number&gt; = {};
  for (const p of json.chainParameter ?? []) values[p.key] = p.value;
  return values;
}

// Base58Check TRON address -&gt; 20-byte EVM address -&gt; 32-byte ABI argument.
// Check both the 0x41 Mainnet prefix and the double-SHA256 checksum.
const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
function abiAddress(address: string): string {
  if (!/^T[1-9A-HJ-NP-Za-km-z]{33}$/.test(address)) throw new Error("Invalid TRON address format");
  let n = 0n;
  for (const c of address) n = n * 58n + BigInt(ALPHABET.indexOf(c));
  const rawHex = n.toString(16);
  if (rawHex.length &gt; 50) throw new Error("Invalid TRON address length");
  const bytes = Buffer.from(rawHex.padStart(50, "0"), "hex");
  if (bytes[0] !== 0x41) throw new Error("Not a Mainnet TRON address");
  const payload = bytes.subarray(0, 21);
  const firstHash = createHash("sha256").update(payload).digest();
  const check = createHash("sha256").update(firstHash).digest().subarray(0, 4);
  if (!check.equals(bytes.subarray(21))) throw new Error("Invalid TRON address checksum");
  return bytes.subarray(1, 21).toString("hex").padStart(64, "0");
}
const abiUint = (v: bigint) =&gt; v.toString(16).padStart(64, "0");
function toUnits(amount: string): bigint {
  const m = /^(\d+)(?:\.(\d{1,6}))?$/.exec(amount);
  if (!m) throw new Error("USDT amount must have at most six decimals");
  const units = BigInt(m[1] + (m[2] ?? "").padEnd(6, "0"));
  if (units &lt;= 0n) throw new Error("USDT amount must be positive");
  return units;
}

// Public, read-only address check; 30 requests/minute per IP.
type ServiceCheck = {
  sender: { activated: boolean; trx: number; usdt: number; energy: number; bandwidth: number };
  recipient?: { activated: boolean; hasUsdt: boolean };
  energyNeeded: number; bandwidthMissing: number; needsActivation: boolean;
};
async function serviceCheck(sender: string, recipient: string): Promise&lt;ServiceCheck&gt; {
  const qs = new URLSearchParams({ address: sender, recipient });
  const res = await fetch(`${TRONILEND}/api/check?${qs}`);
  const json = await res.json();
  if (!res.ok || !json.data) throw new Error(`Tronilend /api/check: ${json.error?.code ?? res.status}`);
  return json.data as ServiceCheck;
}

// Simulate exactly this sender, recipient and amount without spending resources.
type Simulation = { ok: boolean; energyUsed: number; energyPenalty: number; message: string };
async function simulate(sender: string, recipient: string, units: bigint): Promise&lt;Simulation&gt; {
  const r = await rpc&lt;any&gt;("/wallet/triggerconstantcontract", {
    owner_address: sender, contract_address: USDT,
    function_selector: "transfer(address,uint256)",
    parameter: abiAddress(recipient) + abiUint(units), visible: true,
  });
  const execution = r.transaction?.ret?.[0]?.ret;
  const returnedFalse = /^0{64}$/i.test(r.constant_result?.[0] ?? "");
  const ok = r.result?.result === true &amp;&amp;
    (!execution || execution === "SUCCESS") &amp;&amp; !returnedFalse &amp;&amp; (r.energy_used ?? 0) &gt; 0;
  return {
    ok, energyUsed: r.energy_used ?? 0, energyPenalty: r.energy_penalty ?? 0,
    message: r.result?.message ?? execution ?? (returnedFalse ? "Token returned false" : ""),
  };
}

async function resources(address: string) {
  const [res, acc, params] = await Promise.all([
    rpc&lt;any&gt;("/wallet/getaccountresource", { address, visible: true }),
    rpc&lt;any&gt;("/wallet/getaccount", { address, visible: true }),
    chainParameters(),
  ]);
  const energyPrice = params.getEnergyFee;
  const bandwidthPrice = params.getTransactionFee;
  if (!energyPrice || !bandwidthPrice) throw new Error("Network resource prices unavailable: stop, do not broadcast");
  return {
    energy: Math.max(0, (res.EnergyLimit ?? 0) - (res.EnergyUsed ?? 0)),
    stakedBandwidth: Math.max(0, (res.NetLimit ?? 0) - (res.NetUsed ?? 0)),
    freeBandwidth: Math.max(0, (res.freeNetLimit ?? 0) - (res.freeNetUsed ?? 0)),
    trxSun: acc.balance ?? 0,
    energyPrice, bandwidthPrice,
    maxFeeLimitSun: params.getMaxFeeLimit ?? Infinity,
  };
}

export async function preflight(sender: string, recipient: string, amountUsdt: string) {
  abiAddress(sender); // validate both addresses and their Base58Check checksums
  abiAddress(recipient);
  const units = toUnits(amountUsdt);
  const [svc, sim, own] = await Promise.all([
    serviceCheck(sender, recipient), simulate(sender, recipient, units), resources(sender),
  ]);

  const reasons: string[] = [];
  if (!sim.ok) reasons.push(`Simulation failed (${sim.message || "unknown"}); fix the call before sending`);
  if (svc.needsActivation || !svc.sender.activated) reasons.push("Sender is not activated");
  const needed = Math.ceil(Math.max(svc.energyNeeded ?? 0, sim.energyUsed) * (1 + MARGIN));
  const missingEnergy = Math.max(0, needed - own.energy);
  const energyBurnSun = missingEnergy * own.energyPrice;
  const suggestedFeeLimitSun = Math.ceil(needed * own.energyPrice);
  if (suggestedFeeLimitSun &gt; own.maxFeeLimitSun) reasons.push("Calculated fee_limit exceeds the network maximum");

  // TRON does NOT combine staked and free Bandwidth for one transaction.
  // If neither alone covers the estimated bytes, TRX pays the FULL byte cost.
  const enoughStakedBW = own.stakedBandwidth &gt;= ESTIMATED_BANDWIDTH;
  const enoughFreeBW = own.freeBandwidth &gt;= ESTIMATED_BANDWIDTH;
  const bandwidthBurnSun = enoughStakedBW || enoughFreeBW ? 0 :
    ESTIMATED_BANDWIDTH * own.bandwidthPrice;
  const totalBurnSun = energyBurnSun + bandwidthBurnSun;

  let decision: "send" | "send_burns_trx" | "top_up_resources" | "blocked" = "send";
  if (reasons.length) decision = "blocked";
  else if (own.trxSun &lt; totalBurnSun) decision = "top_up_resources";
  else if (totalBurnSun &gt; 0) decision = "send_burns_trx";

  return {
    decision, reasons,
    energy: { available: own.energy, needed, missing: missingEnergy,
      simulated: sim.energyUsed, penalty: sim.energyPenalty, service: svc.energyNeeded },
    bandwidth: { estimatedBytes: ESTIMATED_BANDWIDTH,
      stakedAvailable: own.stakedBandwidth, freeAvailable: own.freeBandwidth,
      burnEstimatedTRX: bandwidthBurnSun / 1e6 },
    trx: { balance: own.trxSun / 1e6, burnEstimatedTRX: totalBurnSun / 1e6,
      canCoverEstimate: own.trxSun &gt;= totalBurnSun },
    suggestedFeeLimitSun,
    recipientHoldsUsdt: svc.recipient?.hasUsdt,
    caveat: "Estimate only: actual signed size, network-wide free Bandwidth and contract state may change",
  };
}

// After staking or receiving a delegation, verify that the balance is really available.
export async function waitForEnergy(addr: string, needed: number, timeoutMs = 120_000) {
  abiAddress(addr);
  const start = Date.now();
  while (Date.now() - start &lt; timeoutMs) {
    const { energy } = await resources(addr);
    if (energy &gt;= needed) return energy;
    await new Promise((resolve) =&gt; setTimeout(resolve, 5_000));
  }
  throw new Error(`Energy still below ${needed}; do not broadcast`);
}

const [sender, recipient, amount] = process.argv.slice(2);
if (sender &amp;&amp; recipient &amp;&amp; amount) {
  console.log(JSON.stringify(await preflight(sender, recipient, amount), null, 2));
}
</code></pre>
<h2>How the decision is made</h2>
<ul>
<li><strong>blocked</strong> - the dry run failed, the sender is not activated, or the suggested fee_limit exceeds the chain maximum. Fix the cause before building a transaction.</li>
<li><strong>send</strong> - current Energy covers the buffered estimate and either free or staked/delegated Bandwidth appears sufficient on its own; still re-check immediately before signing.</li>
<li><strong>send_burns_trx</strong> - estimated Energy and/or Bandwidth shortfall can be paid by the current TRX balance. Network state and the final signed byte size can still change the actual cost.</li>
<li><strong>top_up_resources</strong> - the TRX balance does not cover the estimated combined Energy and Bandwidth burn. Obtain Energy/Bandwidth or add TRX before sending, then run the preflight again.</li>
</ul>
<p>The function returns <code>suggestedFeeLimitSun</code> (buffered Energy requirement multiplied by live <code>getEnergyFee</code>). It checks the current maximum permitted fee_limit. Configure the real transaction with an appropriate fee_limit; this function does not sign or broadcast.</p>
<p>Why take the maximum of two estimates? The simulated call sees the current contract state, while the public checker adds a recipient-focused estimate. A 10% buffer helps with small changes but does not guarantee future state or network conditions. Bandwidth is handled separately because TRON does not sum free and staked Bandwidth allowances for a single transaction.</p>
<h2>Wiring it into a send flow</h2>
<pre><code class="language-ts">import { preflight, waitForEnergy } from "./preflight.mts";

const check = await preflight(sender, recipient, "250");

switch (check.decision) {
  case "send":
  case "send_burns_trx":
    // Your own signer: use check.suggestedFeeLimitSun, then confirm the receipt.
    await buildSignAndBroadcast({ feeLimit: check.suggestedFeeLimitSun });
    break;
  case "top_up_resources":
    // Your own funding/delegation logic; Bandwidth may also need TRX.
    if (check.energy.missing &gt; 0) {
      await requestEnergy(sender, check.energy.missing);
      await waitForEnergy(sender, check.energy.needed);
    }
    // Re-run preflight; do not broadcast automatically after a top-up.
    break;
  case "blocked":
    throw new Error(check.reasons.join("; "));
}
</code></pre>
<p><strong>IMPORTANT:</strong> these names are placeholders for your own application, not executable imports; the example does not sign or broadcast transactions. Re-run preflight after changes in Energy, Bandwidth or TRX. <code>buildSignAndBroadcast</code> and <code>requestEnergy</code> are placeholders for your own code. Energy can come from staking TRX, a delegation from another account you control, or a rental service; <code>waitForEnergy</code> simply polls the node until <code>EnergyLimit - EnergyUsed</code> reaches the target, so the broadcast never races a delegation that has not landed yet. If you use Tronilend's Energy by Transfer, its docs also describe an open <code>GET /api/order-status</code> endpoint to follow the order; a key-based API with <code>/api/energy/v1/quote</code> and <code>/api/energy/v1/orders</code> exists for accounts. Check the current price through the quote endpoint or the <a href="https://tronilend.com/price">pricing page</a> rather than hard-coding it.</p>
<h2>Things the preflight cannot see</h2>
<ul>
<li><strong>Time between check and send.</strong> The contract state and Dynamic Energy factor can change; re-run the check immediately before signing, and after any top-up.</li>
<li><strong>Actual signed size and Bandwidth payment.</strong> This example uses a 400-unit planning allowance, not the final serialized byte size. TRON uses either staked/delegated OR free Bandwidth when one covers the entire transaction; otherwise it burns TRX for the entire byte cost. Network-wide free Bandwidth may also be exhausted.</li>
<li><strong>Wallet-side rules.</strong> Some wallets require a minimum TRX balance or use a gas-free USDT fee mode that bypasses delegated Energy. The estimate does not override wallet policy.</li>
<li><strong>Custodial addresses.</strong> Energy is per address. Exchange deposit and withdrawal addresses are not yours to configure.</li>
<li><strong>Contracts other than USDT.</strong> The Tronilend endpoint is USDT-specific; for other TRC-20 tokens rely on the dry run.</li>
</ul>
<h2>Recap</h2>
<p>Ask the chain before you sign: simulate the exact transfer, read the available resource budgets, check Bandwidth independently, compare with the public USDT-specific estimate and re-run immediately before broadcast. This reduces avoidable failures but does not replace checking the confirmed on-chain receipt.</p>
]]></content:encoded></item></channel></rss>