TRON 上的 USDT 派款:如何在發送前測量 Energy(Python,無 SDK)
USDT payouts on TRON: measure the Energy before you send (Python, no SDK)
文章示範如何以 Python 標準庫呼叫 TRON 公開節點,在發送 USDT 前模擬轉帳並查出所需 Energy,無需 SDK。
If your service sends USDT on TRON (payouts, withdrawals, refunds), every transfer needs Energy. If the sending wallet has none, the network burns TRX from it instead. The good news: you can find out exactly how much Energy a transfer will use, and what it would cost, before you send it, with three calls to a public node.
All numbers below were measured on TRON mainnet on 22 November 2026 through TronGrid.
Two transfers, two very different costs
A USDT transfer does not always cost the same. We dry-ran the same 1 USDT transfer from one wallet to two addresses:
| Recipient | Energy used | Burned if the sender has no Energy |
|---|---|---|
| Already holds USDT | 64,285 | 6.43 TRX |
| USDT balance is zero | 130,285 | 13.03 TRX |
The second one costs twice as much because the USDT contract has to write a new storage slot for the recipient's balance. Receipts of real mainnet transfers from the same day show the same two numbers.
Two more details:
-
Most of that Energy is a "popularity" surcharge. On the receipts, 49,635 of the 64,285 Energy (and 100,635 of the 130,285) is
energy_penalty_total— TRON's dynamic energy model charges busy contracts more (chain parametergetAllowDynamicEnergy= 1). That factor can change, so re-measure instead of hard-coding "65k". - Bandwidth too. Each transfer also needs 345 bytes of Bandwidth. Every account gets 600 free bytes a day; past that, 345 bytes cost 0.345 TRX.
The burn price itself is a chain parameter: getEnergyFee = 100 sun per Energy today (1 TRX = 1,000,000 sun).
The code: dry-run, check, wait
No SDK needed — just the node's HTTP API and Python's standard library.
import hashlib, json, os, time, urllib.request
TRONGRID = "https://api.trongrid.io"
USDT = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
HEADERS = {"Content-Type": "application/json", "User-Agent": "payout-bot/1.0"}
if os.getenv("TRONGRID_API_KEY"):
HEADERS["TRON-PRO-API-KEY"] = os.environ["TRONGRID_API_KEY"]
B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def to_hex20(address):
"""Base58 TRON address -> 20-byte hex (what ABI parameters need)."""
n = 0
for c in address:
n = n * 58 + B58.index(c)
raw = n.to_bytes(25, "big")
body, checksum = raw[:-4], raw[-4:]
if hashlib.sha256(hashlib.sha256(body).digest()).digest()[:4] != checksum:
raise ValueError(f"bad address: {address}")
return body[1:].hex()
def post(path, body):
req = urllib.request.Request(TRONGRID + path, data=json.dumps(body).encode(), headers=HEADERS)
with urllib.request.urlopen(req, timeout=20) as r:
return json.load(r)
def energy_for_usdt_transfer(sender, to, amount_usdt=1):
"""Dry-run the transfer on a node (nothing is broadcast or paid)."""
param = to_hex20(to).rjust(64, "0") + hex(int(amount_usdt * 1_000_000))[2:].rjust(64, "0")
res = post("/wallet/triggerconstantcontract", {
"owner_address": sender,
"contract_address": USDT,
"function_selector": "transfer(address,uint256)",
"parameter": param,
"visible": True,
})
# "result": true only means the node ran it; a reverted transfer
# (e.g. sender lacks the USDT) shows up as transaction.ret == FAILED
ret = res.get("transaction", {}).get("ret", [{}])[0].get("ret")
if not res.get("result", {}).get("result") or ret == "FAILED":
raise RuntimeError(res.get("result"))
return res["energy_used"]
def free_energy(address):
"""Energy the wallet can spend right now (own stake + delegated to it - used)."""
r = post("/wallet/getaccountresource", {"address": address, "visible": True})
return r.get("EnergyLimit", 0) - r.get("EnergyUsed", 0)
def energy_fee_sun():
"""What one burned Energy costs now, in sun (1 TRX = 1,000,000 sun)."""
params = post("/wallet/getchainparameters", {})["chainParameter"]
return next(p["value"] for p in params if p["key"] == "getEnergyFee")
def wait_for_energy(address, need, timeout_s=60):
"""After renting: poll until the delegated Energy shows up on chain."""
deadline = time.time() + timeout_s
while time.time() < deadline:
if free_energy(address) >= need:
return True
time.sleep(3)
return False
if __name__ == "__main__":
sender = "TLaGjwhvA8XQYSxFAcAXy7Dvuue9eGYitv" # any wallet that holds USDT
holder = "TT3fy5iHYcphtEJTA6nKkNLbd88Yw8kUTX" # already holds USDT
fresh = "TAYmLrLrJy9g6LLRVFQ7TVnBQEvp8bDES8" # zero USDT balance
fee = energy_fee_sun()
for name, to in (("holder", holder), ("fresh", fresh)):
e = energy_for_usdt_transfer(sender, to)
print(f"{name}: {e:,} Energy = {e * fee / 1e6:.2f} TRX if burned")
Output on 22 Nov 2026:
holder: 64,285 Energy = 6.43 TRX if burned
fresh: 130,285 Energy = 13.03 TRX if burned
Notes:
-
triggerconstantcontractonly simulates. Nothing is signed, broadcast or paid, so you can call it for every payout in your queue. - Dry-run with your real sending wallet. If it doesn't hold the USDT, the node still answers
"result": true— withREVERT opcode executedand only ~8,600 Energy. That is why the code checkstransaction.ret; a naive check would price a failing payout as cheap. -
"visible": truelets you pass Base58 addresses (T...); the ABI parameter still needs the 20-byte hex, henceto_hex20. - Some Cloudflare-fronted APIs answer 403 to Python's default
Python-urllibuser agent, so set your own. - The public TronGrid endpoint is rate-limited; a free API key goes in the
TRON-PRO-API-KEYheader.
Then decide: own stake, rent, or burn
Before each transfer (or each batch), free_energy(sender) >= need tells you whether you are covered. If not, there are three ways to get the Energy:
-
Stake TRX yourself (Stake 2.0). The network hands out 180,000,000,000 Energy a day, split by stake. With 18,628,467,213 TRX staked network-wide today, that is about 9.66 Energy per staked TRX per day — so one 64,285-Energy transfer a day needs about 6,650 TRX staked (about 13,500 TRX for a zero-balance recipient). Used Energy refills gradually over 24 hours, and unstaking takes 14 days (
getUnfreezeDelayDays= 14). - Rent it. Someone who staked delegates Energy to your sending address for a set time. You pay per Energy per period and keep your TRX liquid.
- Burn. No setup, but the most expensive per transfer: 100 sun per Energy.
A simple rule in code: covered → send; not covered and the rental (incl. fees) is cheaper than need * energy_fee_sun() → rent, wait_for_energy(), send; otherwise burn.
What renting looks like from code
Rental APIs tend to follow the same shape: read the market settings, place an order for need Energy with your sending address as the target, wait until the Energy is on chain, send.
As one example (we run TronBoost, a peer-to-peer Energy market), its market settings are public:
def market_settings(symbol="TRON_ENERGY-TRX"):
url = f"https://tronboost.io/api/v1/Markets/{symbol}"
req = urllib.request.Request(url, headers={"User-Agent": "payout-bot/1.0"})
with urllib.request.urlopen(req, timeout=20) as r:
return json.load(r)["data"]
s = market_settings()
print(s["minPrice"], s["maxPrice"], s["minTradeAmount"], [d["value"] for d in s["durations"]])
# 3.5e-05 8e-05 10000 [1800, 3600, 7200, 21600, 43200, 86400, 259200, 604800, 1209600, 2592000]
Prices are in TRX per Energy per day, so at the floor price 64,285 Energy for a day costs about 2.25 TRX before fees (makerFee / takerFee in the same response), against 6.43 TRX burned. Placing an order needs a signed transaction from your key; the request format is in the API reference. Whichever provider you use, confirm on chain with wait_for_energy() before you send — never trust an "order placed" response alone.
Checklist for a payout service
- Dry-run every transfer; group payouts by
energy_used(64k vs 130k recipients). - Re-measure regularly: the dynamic energy factor moves.
- Check
free_energy()of the sending wallet before the batch, not after. - Watch Bandwidth as well as Energy on high-volume wallets.
- Log
energy_usedand the receipt'senergy_feeper transfer, so you can see what you actually paid.
AI assistance was used in writing this article.
來源:DEV Community · dev.to