# Tron (TRX / USDT TRC-20) Toolchain

Tron has no plain JSON-RPC like Ethereum; use the free keyless TronGrid HTTP API. Same secp256k1 keys as Ethereum — only the address encoding differs.

## Constants

- USDT (TRC-20) contract: `TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` — the canonical mainnet USDT issuer; any other "USDT" contract is a fake.
- Decimals on Tron are 6 (both TRX "sun" and USDT): divide raw integers by 1_000_000.

## Reading an account (deposit watch)

```
GET https://api.trongrid.io/v1/accounts/{address}
```
Response `data[0]`:
- `balance` → TRX in sun (÷1e6)
- `trc20` → list of dicts `{contract_address: raw_amount}`; match the USDT contract above
- Empty `data: []` → address has never received anything (normal for fresh wallets, NOT an error)

Always send a browser-like `User-Agent`; retry on HTTP 429 with a few seconds sleep — TronGrid rate-limits anonymous clients aggressively.

## Generating a Tron address from a private key

`tronpy` may fail to install (its `coincurve` dependency has no wheels on some Python versions — do not fight the build; derive manually):

```python
import secrets, base58
from eth_keys import keys as ekeys
from eth_utils import keccak

priv = secrets.token_hex(32)
pub = ekeys.PrivateKey(bytes.fromhex(priv)).public_key.to_bytes()   # 65 bytes, 04-prefix
addr = base58.b58encode_check(b"\x41" + keccak(pub)[12:]).decode()   # T... base58check
```

Store the hex key in `~/.secrets/<name>_tron.key` (chmod 600), address is public. Never write keys to the vault.

## Sending USDT TRC-20 (PROVEN PATH: tronpy on the system Python)

`tronpy` runs on `/usr/bin/python3` (3.12) — install once:
```
curl -sS https://bootstrap.pypa.io/get-pip.py -o /tmp/get-pip.py
/usr/bin/python3 /tmp/get-pip.py --user --break-system-packages
/usr/bin/python3 -m pip install --user --break-system-packages tronpy
```
Do NOT use the Hermes Python (~3.14) for this — `coincurve` has no wheels there and the source build fails. Verify the key→address pair before signing (`PrivateKey(...).public_key.to_base58check_address() == FROM_WALLET`).

Working example: `~/send_tron_usdt.py` (Tron client + `ContractBuilder` from `client.get_contract(USDT).functions.transfer(to, amount_sun).with_owner(from).fee_limit(60_000_000)`, then `.build().sign(priv)`, `.broadcast().wait(timeout=180)`).

- Amounts are raw 6-decimal integers: `int(round(amount * 1e6))`. When the owner names an EXACT amount (services often credit deposits by exact-amount match), send it to the unit, no rounding to nice numbers.
- A USDT transfer burns Energy or ~13-30 TRX in fees — keep TRX on the sending wallet.
- Verify on-chain after broadcast: receipt `result: SUCCESS`, and the Transfer log's `to` topic must equal the 20-byte hex of the recipient (`base58.b58decode_check(addr).hex()[2:]`) — a copied address that transposed a character otherwise sends funds into the void.
- TronGrid rate-limits hard under sustained use (429, later even 401). Fallback full-node RPC with the same `wallet/*` API: `https://api.tronstack.io` — swap it into the provider URL and retry; also wrap every client call in a retry-with-sleep(15) helper.
- Sind TronGrid UND Tronstack gleichzeitig im 429-Sturm (typisch bei vielen parallelen Agenten), antwortet noch `https://tron-rpc.publicnode.com` — via tronpy `Tron(provider=HTTPProvider('https://tron-rpc.publicnode.com'))` verwenden. Achtung: dort liefert `/wallet/getaccount` KEIN TRC-20 (`assetV2` zeigt USDT nicht → falsche 0) — USDT dort NUR über den Contract-Call `client.get_contract(USDT).functions.balanceOf(addr)` lesen (löst auch das Hex-Parameter-Problem automatisch).

## Balance reads — which endpoint shows which tokens

- `POST /wallet/getaccount` returns `assetV2` = TRC-10 tokens ONLY (numeric asset IDs); TRC-20 balances like USDT are INVISIBLE there — reading that array as "the wallet's tokens" reports USDT=0 while the wallet holds six figures. Use `GET /v1/accounts/{address}` and read the `trc20` array instead (or `POST /wallet/triggerconstantcontract` with `function_selector: balanceOf(address)` and the zero-padded hex address).
- For `balanceOf`, build the parameter as 24 zeros + the hex address without `0x41` prefix: get it via `tronpy` (`Tron().to_hex_address(addr)` or `tronpy.keys.address_to_hex`) — hand-encoding the base58 address produced a valid-looking but WRONG parameter and a silent 0.

## Native TRX transfer (gas/top-ups)

`client.trx.transfer(FROM, TO, sun).fee_limit(30_000_000).build().sign(priv)` — same tronpy path as USDT, minus the contract. The address check method is `to_base58check_address` (one "check", no underscore between base58 and check) — `to_base58_check_address` raises AttributeError. USDT transfer energy (~65k) burned ≈6.4 TRX in fees; keep ≥30 TRX on the sending wallet.

## Manual signing fallback (UNVERIFIED — last resort only)

Build via `POST /wallet/triggersmartcontract`, sign the `txID`, broadcast via `/wallet/broadcasttransaction`. The `txID` is a SINGLE `sha256` of `raw_data_hex` (verified on-chain), NOT sha256d. Signing it with `eth_keys.sign_msg_hash` + 65-byte `(r,s,v)` should work in theory but has never produced a verified accepted transaction here — prefer tronpy above.

## Incoming-payment verification ("Geldeingangskontrolle")

For "did the owner's payment arrive" checks on a deposit/service address:

- Verify incoming payments via HISTORY, never via balance: `GET /v1/accounts/{addr}/transactions/trc20?limit=50&only_to=true&contract_address=TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t` returns each deposit with `value`, `block_timestamp`, `transaction_id`, `from`. Exchange/service deposit addresses (e.g. NanoGPT) sweep funds out within minutes — balance 0 with a confirmed history is NORMAL and does not mean the payment vanished; the credit shows up in the service's own balance API instead.
- Run Tron scripts through the TERMINAL tool as `/usr/bin/python3 /tmp/script.py`, not via execute_code subprocess — the kernel environment shadows even an absolute `/usr/bin/python3` with a broken Hermes venv (pydantic import error). Grep constants like the USDT contract from a proven script (`~/send_tron_usdt.py`) instead of typing them from memory — a one-character base58 typo raises `BadAddress` or, worse, silently targets a fake token.
- Report to the owner: amount, UTC timestamp, short TX id, sender address, and the NEW resulting balance of every checked wallet (he usually sends to several in one batch).

## Cron deposit-watch pattern

Script prints one deterministic line per address (`"name: X TRX, USDT Y"`, no timestamps). Use it as a `cronjob_manage` `monitor=` source on a 10-15m schedule, `deliver='origin'`: unchanged output = silence; a changed line wakes the agent, which reports address + amount to the owner.
