TRON
With ChainType set to TRON, the Web3 exchange object connects to a TRON node. Usage is largely the same as on Ethereum (see Ethereum (EVM)): the exchange.IO() commands for registering ABIs, calling contracts, encoding and decoding, signing and switching private keys are the same, addresses use the TRON format (starting with T), and TRX amounts are in sun (1 TRX = 1000000 sun). This page covers the configuration and the TRON-specific parts.
Configure the exchange object
ChainType: ChooseTRONPrivate Key: Wallet private key (hex string). The key can be deployed locally on the docker, seeKey SecurityRpc Address: HTTP address of a TRON full node, for example the official nodehttps://api.trongrid.io(testnets:https://nile.trongrid.io,https://api.shasta.trongrid.io)Rpc Api Key: TronGrid API key. Enter only the key itself; it is sent as theTRON-PRO-API-KEYrequest header. It works without a key, but TronGrid rate-limits keyless requests more strictly
The docker accesses TRON through the full node's HTTP API (/wallet/...) and no longer uses gRPC. The old gRPC address grpc.trongrid.io:50051 that the form fills in by default for TRON is replaced automatically with https://api.trongrid.io (grpc.nile.trongrid.io:50051 and grpc.shasta.trongrid.io:50051 likewise become the HTTP addresses of the corresponding testnets); any other gRPC address is rejected, so enter the node's HTTP address instead.
At runtime, exchange.IO("base", nodeAddress) switches nodes, exchange.IO("key", privateKey) switches wallets, and exchange.IO("address") returns the current wallet address (starting with T). The standard functions exchange.GetAccount() and exchange.GetAssets() return the wallet's TRX balance. An account that has not been activated yet (no on-chain record) reads as 0 TRX.
Calling smart contracts
As on Ethereum, use exchange.IO("api", contractAddress, method, ...args): read-only methods return results directly, write methods sign and broadcast a transaction and return the transaction ID. Standard TRC20 methods are built in; for other contracts without a registered ABI, the ABI is read from the chain automatically, and only when that fails do you need to register it with exchange.IO("abi", contractAddress, abi). The last argument of a write method can be {gasLimit: amount} to set the fee limit (feeLimit, in sun).
javascript
// USDT (TRC20) contract
var usdt = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
Log(exchange.IO("api", usdt, "balanceOf", exchange.IO("address"))) // on-chain integer, 6 decimals
Encoding and decoding work as on Ethereum; address arguments can be written directly as T addresses:
javascript
exchange.IO("encode", "address", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")
// 000000000000000000000000a614f803b6fd780986a42c78ec9c7f77e6ded13c
exchange.IO("encodePacked", "address", "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")
// a614f803b6fd780986a42c78ec9c7f77e6ded13c
exchange.IO("decode", "string",
"0000000000000000000000000000000000000000000000000000000000000020" +
"000000000000000000000000000000000000000000000000000000000000000a" +
"5465746865722055534400000000000000000000000000000000000000000000")
// Tether USD
Calling TRON node methods
exchange.IO("api", "tron", method, ...args) calls TRON node methods; method names are case-insensitive (except send, which must be lower case). Methods that need a signature (transfers, triggering contracts, etc.) are signed and broadcast automatically. Common methods:
| Method | Arguments | Description |
|---|---|---|
send | to address, amount (sun) | Send TRX from the current wallet |
Transfer | from address, to address, amount (sun) | Send TRX; the from address must be the current wallet |
GetAccount | address | Account information |
GetAccountResource | address | The account's energy and bandwidth resources |
GetContractABI | contract address | The contract's on-chain ABI |
GetAssetIssueByName | name | TRC10 asset information |
GetNowBlock | none | Current block |
GetBlockByNum | block height | A given block |
GetTransactionByID | transaction ID | Transaction content |
GetTransactionInfoByID | transaction ID | Execution result of a transaction (fees, energy used, logs, etc.) |
GetChainParameters | none | Chain parameters |
TriggerConstantContract | caller address (may be empty), contract address, method signature, argument values (see below the table) | Read-only contract call; the result is in constant_result |
TRC20ContractBalance | address, contract address | TRC20 balance (on-chain integer) |
TRC20GetName, TRC20GetSymbol, TRC20GetDecimals | contract address | Name, symbol and decimals of a TRC20 token |
TRC20Send, TRC20Approve | from address, to or spender address, contract address, amount, feeLimit | TRC20 transfer and approval |
TRC20Call | caller address (may be empty), contract address, call data, read-only flag, feeLimit | Call a contract with raw call data |
ParseTRC20NumericProperty, ParseTRC20StringProperty | hex data | Parse numbers and strings returned by TRC20 |
For TriggerConstantContract, the method signature includes the parameter types (e.g. "balanceOf(address)") and the argument values are a JSON array string (e.g. '["T..."]', an empty string for no arguments); the returned constant_result holds hex strings that can be decoded with exchange.IO("decode", ...).
Node endpoints not in the table can be called with a path and a request body: exchange.IO("api", "tron", "/wallet/endpointName", {body}).
Differences from Ethereum
The following commands only work on Ethereum (EVM) and report an error on TRON: call, multicall, logs, waitReceipt, nonce, speedUp, cancelTx, contracts and sendBase. Multiple fallback nodes also only apply to Ethereum: TRON takes a single node address, and a comma-separated list of nodes reports an error. On TRON, simulate a contract call with the node method TriggerConstantContract, and query a transaction's execution result with GetTransactionInfoByID.
toUnits, fromUnits, uniswapV3, the encoding and decoding commands and the signing commands work on TRON as well, and a TRC20 contract address can be passed as the decimals:
javascript
var usdt = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
var raw = exchange.IO("api", usdt, "balanceOf", exchange.IO("address"))
Log(exchange.IO("fromUnits", raw, usdt)) // readable amount, using the contract's decimals()
When the node rejects a contract call at validation time (for example because the contract does not exist), the error carries the node's reason, such as tron contract call rejected (CONTRACT_VALIDATE_ERROR): Smart contract is not exist.; a contract execution failure (revert) reports tron contract execution failed with the reason.
Signing
exchange.IO("hash", "sign", "hex", "hex", txHash) signs a 32-byte hash with the current private key and returns the 65-byte signature r‖s‖v (v is 0 or 1); other hash algorithms (such as sha256) compute digests, the same as the Encode() function. When r, s and v (v being 27 or 28) are needed separately for contract verification, use exchange.IO("sign", ...), see the Web3 exchange page of the syntax manual.
Examples
-
Query TRX and USDT balances and read token information.
javascriptfunction main() { var usdt = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" var wallet = exchange.IO("address") // TRX balance (standard function, in TRX) Log("account:", exchange.GetAccount()) // USDT balance: an on-chain integer, scale it by the decimals var raw = exchange.IO("api", "tron", "TRC20ContractBalance", wallet, usdt) var decimals = exchange.IO("api", "tron", "TRC20GetDecimals", usdt) Log("USDT:", raw / Math.pow(10, decimals)) // read-only call of name() (selector 0x06fdde03) with TRC20Call, then parse the returned string var ret = exchange.IO("api", "tron", "TRC20Call", "", usdt, "0x06fdde03", true, 0) // constant_result holds hex strings, parse them directly Log("name:", exchange.IO("api", "tron", "ParseTRC20StringProperty", ret.constant_result[0])) } -
Read several contract methods at once with a Multicall contract.
javascriptfunction main() { var usdt = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" var multicall = "TGXuuKAb4bnrn137u39EKbYzKNXvdCes98" var wallet = exchange.IO("address") var calls = [ [usdt, exchange.IO("encode", usdt, "name")], [usdt, exchange.IO("encode", usdt, "decimals")], [usdt, exchange.IO("encode", usdt, "balanceOf", wallet)] ] // register the aggregate method of the Multicall contract exchange.IO("abi", multicall, `[{ "inputs": [{ "components": [ {"internalType": "address", "name": "target", "type": "address"}, {"internalType": "bytes", "name": "callData", "type": "bytes"} ], "internalType": "struct TronMulticall.Call[]", "name": "calls", "type": "tuple[]" }], "name": "aggregate", "outputs": [ {"internalType": "uint256", "name": "blockNumber", "type": "uint256"}, {"internalType": "bytes[]", "name": "returnData", "type": "bytes[]"} ], "stateMutability": "view", "type": "function" }]`) var ret = exchange.IO("api", multicall, "aggregate", calls) Log("name:", exchange.IO("decode", "string", ret.returnData[0])) Log("decimals:", exchange.IO("decode", "uint8", ret.returnData[1])) Log("balanceOf:", exchange.IO("decode", "uint256", ret.returnData[2])) }
See Also