
Tronweb
- 3 installs
- 4 repo stars
- Updated February 25, 2026
- hairyf/blockchain-skills
Integrate TRON into JavaScript/TypeScript apps with TronWeb: HTTP API, contract calls, transactions, and event handling.
About
Reference for TronWeb, the JavaScript/TypeScript SDK for TRON covering the HTTP API, contracts, transactions, and events. A developer uses it when building client or server integrations against the TRON network.
- HTTP API, contract, and transaction handling
- Includes event querying and subscriptions
Tronweb by the numbers
- 3 all-time installs (skills.sh)
- Ranked #390 of 479 Web3 & Blockchain skills by installs in the Skillselion catalog
- Data as of Jul 13, 2026 (Skillselion catalog sync)
npx skills add https://github.com/hairyf/blockchain-skills --skill tronwebAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3 |
|---|---|
| repo stars | ★ 4 |
| Last updated | February 25, 2026 |
| Repository | hairyf/blockchain-skills ↗ |
What it does
Integrate TRON into JavaScript/TypeScript apps with TronWeb: HTTP API, contract calls, transactions, and event handling.
Files
Skill is based on TronWeb v6.2.0, generated at 2026-02-25.
TronWeb is the official JavaScript/TypeScript SDK for the TRON network. It wraps the TRON HTTP API and provides a consistent API for accounts, blocks, transactions, smart contracts, and events. Use it in Node.js or the browser to build DApps, sign and broadcast transactions, and call contracts.
Core References
| Topic | Description | Reference |
|---|---|---|
| Instance setup | fullHost, nodes, headers, privateKey, setPrivateKey/setAddress | core-instance-setup |
| Address, units, encoding | hex/base58/checksum, toSun/fromSun, fromUtf8/toUtf8, sha3 | core-address-units |
| Trx | Blocks, transactions, accounts, bandwidth, sign, broadcast, getCurrentRefBlockParams, signTypedData, ecRecover | core-trx |
| Utils | ABI, transaction, deserializeTx, accounts, address, validations | core-utils |
| Providers | HttpProvider, request, isConnected, timeout, headers, setStatusPage | core-providers |
| Constants | ADDRESS_PREFIX, SUN/TRX, default feeLimit, BIP44 path | core-constants |
Features
Transactions and contracts
| Topic | Description | Reference |
|---|---|---|
| TransactionBuilder | sendTrx, sendToken, freeze/unfreeze, triggerSmartContract, createSmartContract, deployConstantContract | features-transaction-builder |
| Contract | contract(abi, address), methods.call/send, decodeInput, new(), at() | features-contract |
| Events | getEventsByContractAddress, getEventsByTransactionID, getEventsByBlockNumber, setServer | features-events |
| Plugin | register(PluginClass), pluginInterface (requires, components, fullClass) | features-plugin |
| Message and typed data | signMessage/verifyMessage, signTypedData/verifyTypedData, EIP-712 TypedDataEncoder | features-message-typed-data |
| Connection and version | isConnected(), fullnodeSatisfies(version), getFullnodeVersion() | features-connection-version |
| Trx tokens and chain | getTokenFromID, getTokensIssuedByAddress, getAccountResources, getChainParameters | features-trx-tokens-resources |
Best practices
| Topic | Description | Reference |
|---|---|---|
| Errors and typing | Error instances (e.message), ABI as const for contract inference | best-practices-errors-typing |
| Param validation | Validator, notValid(params), param types (address, integer, resource, url, hex, etc.) | best-practices-param-validation |
| Multi-signature | getSignWeight, getApprovedList, multiSign, permissionId | best-practices-multisig |
| Transaction lifecycle | Sign → broadcast → getTransactionInfo, handling receipt and FAILED | best-practices-transaction-lifecycle |
Generation Info
- Source:
sources/tronweb - Git SHA:
d9460de131f87d5a7e8101ccd925f8fae0aca2aa - Generated: 2026-02-25
Errors and Typing
Errors
TronWeb v6+ throws Error instances only. Always use e.message to read error text (e.g. in catch blocks or logs). Do not rely on thrown strings.
try {
await tronWeb.trx.sendRawTransaction(signed);
} catch (e) {
console.error((e as Error).message);
}Contract TypeScript inference
For accurate method types from ABI, pass the ABI so TypeScript can infer it:
const abi = [/* ... */] as const;
const contract = tronWeb.contract(abi, address);
const result = await contract.methods.balanceOf(addr).call();
// result typed from ABIOr pass the ABI object directly into tronWeb.contract(). Avoid passing a loosely typed any ABI if you want inference.
Key Points
- Parameter order and types for Trx and TransactionBuilder are strictly validated; wrong types throw.
contract.new()returns a new contract instance using the ABI from the options parameter, not the chain-stored ABI.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (CHANGELOG 6.0.0, 6.0.4)
- https://tronweb.network/docu/docs/intro/
-->
Multi-signature
TRON supports multi-sig accounts via permissions. Use getSignWeight, getApprovedList, and multiSign to build or complete multi-sig transactions.
Check sign weight and approved list
Before signing, check whether the transaction is valid for the permission and who has already signed:
const weight = await tronWeb.trx.getSignWeight(transaction, permissionId?);
// weight.result.code === 'PERMISSION_ERROR' → error message in weight.result.message
// weight.permission.keys, weight.approved_list, weight.transaction
const { approved_list } = await tronWeb.trx.getApprovedList(transaction);
// approved_list: hex addresses that have signedSign with a permission
Use multiSign(transaction, privateKey?, permissionId?) to add the signature for the given permission. If the transaction does not yet have Permission_id and you pass permissionId > 0, TronWeb will set it and may replace the transaction with the server-returned version (from getSignWeight) before signing.
const signed = await tronWeb.trx.multiSign(tx, privateKey, permissionId);
// Then broadcast: tronWeb.trx.sendRawTransaction(signed)Rules:
- The private key must belong to a key in the permission (getSignWeight checks this).
- If the key has already signed (in approved_list), multiSign throws.
- For owner permission or when the tx already has Permission_id, signing proceeds directly.
Flow
1. Build the transaction (e.g. via transactionBuilder or contract.methods.send). 2. Call getSignWeight(tx, permissionId) to validate and optionally get an updated tx. 3. Optionally call getApprovedList(tx) to show who has signed. 4. Each signer calls multiSign(tx, theirPrivateKey, permissionId). 5. When the permission threshold is met, broadcast the final signed tx with sendRawTransaction.
Key points
- permissionId identifies which permission (e.g. owner vs active) is used; 0 is owner.
- getSignWeight can return a modified transaction (e.g. with Permission_id set); use that for subsequent multiSign if returned.
- Always handle PERMISSION_ERROR and "already sign" errors in UI or agents.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/trx.ts)
-->
Param validation
TronWeb uses an internal Validator to validate arguments in Trx and TransactionBuilder. When building wrappers or agents that accept user/API input, apply the same patterns so invalid params throw clear errors before calling RPC. The Validator class is not part of the public package API.
Usage pattern
notValid(params) takes an array of { name, type, value, msg?, optional?, gt?, lt?, gte?, lte?, names? }. If any param fails, it throws. Use optional: true to skip validation when value is undefined/null or (for non-boolean) false. Custom message: set msg on the param.
Param types
| type | meaning |
|---|---|
address | Valid TRON address (base58 or hex); throws "Invalid … address provided" if invalid. |
integer | Integer; optional gt, lt, gte, lte for range. |
positive-integer | Integer > 0; throws "… must be a positive integer". |
tokenId | Non-empty string. |
resource | Must be 'BANDWIDTH' or 'ENERGY'. |
url | Valid URL (isValidURL). |
hex | Hex string. |
array | Array.isArray. |
string | String; optional gt/lt/gte/lte for length. |
not-empty-string | Non-empty string. |
boolean | Boolean. |
notEmptyObject | Object with at least one key. |
notEqual | Uses names: two param names must not be equal (throws with notEqual message). |
- notEqual — Uses
names: two param names must not be equal (throws with notEqual message).
Key points
- Use
optional: truefor params that may be omitted. - For
notEqual, passnames: ['from', 'to']and ensure both appear earlier in the params array. - When building agents, validate inputs against these types before calling TronWeb APIs.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/paramValidator/index.ts)
-->
Transaction lifecycle
After building and signing a transaction, broadcast it and poll for the result. Handle success, FAILED, and timeouts so agents and UIs give clear feedback.
Flow
const tx = await tronWeb.transactionBuilder.triggerSmartContract(...);
const signed = await tronWeb.trx.sign(tx);
const result = await tronWeb.trx.sendRawTransaction(signed);
// result: { result: true, txid: '...' } or { result: false, code: '...', message: '...' }Then wait for confirmation and inspect the receipt:
const info = await tronWeb.trx.getTransactionInfo(result.txid);
// info.receipt.result === 'SUCCESS' | 'FAILED' | undefined (pending)
// info.receipt.energy_usage_total, contractResult, etc.Handling result
- Broadcast result.result === false — Node rejected (e.g. invalid tx, duplicate); use result.code and result.message.
- info.receipt.result === 'SUCCESS' — Transaction confirmed and succeeded.
- info.receipt.result === 'FAILED' — Transaction confirmed but reverted (e.g. contract revert, out of energy). Check contractResult for revert reason when available.
- info not found or receipt.result undefined — Still pending; poll getTransactionInfo until confirmed or timeout.
Polling: wait a few seconds between calls; stop after N attempts or when receipt.result is defined. Use getConfirmedCurrentBlock to align with "confirmed" view if needed.
Key points
- Always check broadcast result before assuming the tx was submitted; then use getTransactionInfo for on-chain outcome.
- For contract calls, FAILED usually means revert or resource limit; surface receipt and contractResult to the user or agent.
- Ref block expiration (e.g. 60s) means the tx can become invalid if not broadcast in time; build with getCurrentRefBlockParams when building manually.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/trx.ts)
- https://tronweb.network/docu/docs/intro/
-->
Address, Units, and Encoding
TronWeb static helpers for addresses, TRX/SUN conversion, and hex/UTF-8.
Address (static)
import { TronWeb } from 'tronweb';
TronWeb.address.fromHex(address); // hex → base58
TronWeb.address.toHex(address); // base58 → hex (41...)
TronWeb.address.toChecksumAddress(address);
TronWeb.address.isChecksumAddress(address);
TronWeb.address.fromPrivateKey(privateKey, strict?);
TronWeb.isAddress(address); // base58 or 42-char hexInstance mirrors: tronWeb.address.*, tronWeb.isAddress(...).
TRX / SUN
TronWeb.toSun(trx); // TRX → SUN (string or BigNumber)
TronWeb.fromSun(sun); // SUN → TRXEncoding / hashing
TronWeb.fromUtf8(str); // UTF-8 string → '0x...' hex
TronWeb.toUtf8(hex); // hex → UTF-8 string
TronWeb.toHex(val); // number|boolean|object|string → hex (throws if invalid)
TronWeb.toBigNumber(amount);
TronWeb.toDecimal(value);
TronWeb.fromDecimal(value);
TronWeb.sha3(string, prefix?); // keccak256, prefix default true ('0x')Key Points
- TRON hex addresses use 41-prefix (not 0x);
toHexreturns 42-char with41.... - Use
toSun/fromSunfor TRX amounts in contract/transfer APIs (amounts in SUN). - Checksum is EIP-55 style over hex; use for display/storage when you need canonical form.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/tronweb.ts, src/utils/address.ts)
- https://tronweb.network/docu/docs/intro/
-->
Constants
Common constants used by TronWeb and TRON conventions.
Address and chain
- ADDRESS_PREFIX —
'41'(hex); TRON addresses in hex form start with 41 (not 0x). 34 chars total with prefix. - SUN per TRX — 1 TRX = 1_000_000 SUN. Use
TronWeb.toSun(trx)/TronWeb.fromSun(sun)for conversion.
Fee limit
- Default feeLimit — Instance default for contract calls is
150_000_000(150 TRX in SUN units). Set per call viaoptions.feeLimitor changetronWeb.feeLimit.
BIP44 path
- TRON path —
m/44'/195'/0'/0/0(constantTRON_BIP39_PATH_INDEX_0). Use forTronWeb.fromMnemonic(mnemonic, path)andcreateRandom(..., path); path must match^m/44'/195'.
Key points
- All amounts in TRX for contract/transfer APIs are in SUN; convert with toSun/fromSun.
- Address hex is 42 chars (41 + 40 hex digits); base58 is typically 34 chars.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/utils/constants.ts, src/tronweb.ts)
-->
TronWeb Instance Setup
How to instantiate TronWeb and set node endpoints, API headers, and default signer.
Usage
import { TronWeb } from 'tronweb';
// Single host (e.g. TronGrid) — fullNode, solidityNode, eventServer all use it
const tronWeb = new TronWeb({
fullHost: 'https://api.trongrid.io',
headers: { 'TRON-PRO-API-KEY': 'your-api-key' },
privateKey: 'your-private-key',
});
// Separate event server
const tronWeb = new TronWeb({
fullHost: 'https://api.trongrid.io',
eventServer: 'https://api.someotherevent.io',
privateKey: 'your-private-key',
});
// Explicit full / solidity / event nodes
const tronWeb = new TronWeb({
fullNode: 'https://some-node.tld',
solidityNode: 'https://some-other-node.tld',
eventServer: 'https://some-event-server.tld',
privateKey: 'your-private-key',
});Legacy constructor (retro-compat): new TronWeb(fullNode, solidityNode, eventServer, privateKey). Then tronWeb.setHeader({ 'TRON-PRO-API-KEY': 'key' }).
Key APIs
- setPrivateKey(privateKey) — Set default signer; emits
privateKeyChanged. - setAddress(address) — Set default address (base58 or hex); emits
addressChanged. - setFullNode / setSolidityNode / setEventServer — Swap node providers.
- setHeader(headers) — Apply headers to full, solidity, and event providers.
- setFullNodeHeader(headers) / setEventHeader(headers) — Per-endpoint headers.
- defaultBlock — Set via
setDefaultBlock(blockID)(false|'latest'|'earliest'| number). - feeLimit — Instance default for contract calls (default
150000000).
Key Points
fullHostis a joker: used for full + solidity when set; more specificfullNode/solidityNode/eventServeroverride.- Event server is required for
tronWeb.eventandgetEventResult/getEventByTransactionID. - All methods throw
Errorinstances; usee.messagefor error text.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (README.md, src/tronweb.ts)
- https://tronweb.network/docu/docs/intro/
-->
Providers
TronWeb talks to nodes via HttpProvider. The instance uses three providers: fullNode, solidityNode, and eventServer (optional). You can replace them with setFullNode / setSolidityNode / setEventServer or by constructing providers yourself.
HttpProvider
import { providers } from 'tronweb';
const p = new providers.HttpProvider(
'https://api.trongrid.io',
30000, // timeout ms
'', // user (basic auth)
'', // password
{ 'TRON-PRO-API-KEY': 'your-key' },
'/' // statusPage (default '/')
);- host — Base URL (trailing slashes removed).
- timeout — Request timeout in ms.
- headers — Object sent with every request.
- request(url, payload?, method?) —
method'get'(payload as query) or'post'(payload as body). ReturnsPromise<response data>. - isConnected(statusPage?) — Hits
statusPage(default/or the one set); returns true if response hasblockIDandblock_header. - setStatusPage(path) — Set path used by
isConnected().
How TronWeb uses providers
- Full node: status page
wallet/getnowblock; used for live chain and wallet APIs. - Solidity node: status page
walletsolidity/getnowblock; used for confirmed state. - Event server: used by
tronWeb.event; can use a different host/headers viasetEventServer(provider, healthcheck?)andsetEventHeader(headers).
Creating a provider with custom timeout/headers and passing to tronWeb.setFullNode(provider) is valid.
Key points
- All provider constructors validate URL, timeout, and headers; invalid values throw.
- Use
isConnected()for health checks; TronWeb uses it intronWeb.isConnected()for all three nodes.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/providers/HttpProvider.ts, src/tronweb.ts)
- https://tronweb.network/docu/docs/intro/
-->
Trx API
tronWeb.trx provides block/transaction/account RPC, signing, and broadcast. Use for reading chain state and sending signed transactions.
Blocks and transactions
const block = await tronWeb.trx.getCurrentBlock();
const blockByNum = await tronWeb.trx.getBlock(12345);
const blockByHash = await tronWeb.trx.getBlockByHash(blockId);
const tx = await tronWeb.trx.getTransaction(txId);
const txInfo = await tronWeb.trx.getTransactionInfo(txId);getBlock(block) accepts 'latest', 'earliest', block number, or block hash. Uses tronWeb.defaultBlock when no argument.
Accounts and resources
const account = await tronWeb.trx.getAccount(address);
const net = await tronWeb.trx.getAccountNet(address);
const bandwidth = await tronWeb.trx.getBandwidth(address);Signing and broadcast
- sign(transaction, privateKey?) — Sign a transaction; uses
tronWeb.defaultPrivateKeyif omitted. Returns signed transaction (signature array). - signMessageV2(message, privateKey?) — Personal sign (TRON message prefix); returns hex signature.
- signTypedData(domain, types, value, privateKey?) — EIP-712 typed data sign; returns hex signature.
- multiSign(transaction, privateKey?, permissionId?) — Multi-sig sign; use after getSignWeight/getApprovedList when needed.
Broadcast:
- sendRawTransaction(signedTx) — Broadcast signed transaction object.
- sendHexTransaction(hex) — Broadcast hex-encoded signed transaction.
Aliases: broadcast = sendRawTransaction, broadcastHex = sendHexTransaction, signTransaction = sign.
Ref block params
When building transactions manually you need current ref block params:
const ref = await tronWeb.trx.getCurrentRefBlockParams();
// { ref_block_bytes, ref_block_hash, expiration, timestamp }Use these in raw_data so the node accepts the transaction.
ecRecover
Recover signer address from signed digest and signature (hex):
import { utils } from 'tronweb';
const addressHex = utils.crypto.ecRecover(signedDataHex, signatureHex);
// Returns 41-prefix hex addressKey points
- Use fullNode for latest state, solidityNode for confirmed state (e.g. getConfirmedCurrentBlock).
- Signing methods accept optional privateKey; otherwise use setPrivateKey/default.
- getSignWeight / getApprovedList support multi-sig flows before multiSign.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/trx.ts, src/utils/crypto.ts)
- https://tronweb.network/docu/docs/intro/
-->
Utils
tronWeb.utils (and static import { utils } from 'tronweb') exposes helpers for ABI, transactions, accounts, address/code, validations, and signing utilities.
ABI and transaction
utils.abi.encodeParams(types, values); // ABI-encode params
utils.abi.decodeParams(types, data); // Decode hex data
utils.transaction.* // Transaction building/checks
utils.deserializeTx(hexOrBuffer); // Deserialize serialized txUse txCheck(transaction) from utils.transaction to validate before sign/broadcast.
Accounts
const account = await TronWeb.createAccount();
// { privateKey, publicKey, address: { base58, hex } }
const random = TronWeb.createRandom(password?, path?, wordlist?);
// { mnemonic, privateKey, publicKey, address, path }
const fromMnemonic = TronWeb.fromMnemonic(mnemonic, path?, password?, wordlist?);
// path must match ^m/44'/195'/... (TRON BIP44)Also available as utils.accounts.generateAccount(), generateRandom(), generateAccountWithMnemonic().
Address and validations
utils.address.* // toHex, fromHex, isAddress, etc. (see core-address-units)
utils.validations.* // isString, isInteger, isHex, isAddress, isBigNumber, etc.Use validations when validating user or API inputs before calling Trx/Contract/TransactionBuilder.
Message and typed data
utils.message.signMessage(message, privateKey);
utils.message.verifyMessage(message, signature);
utils.message.hashMessage(message);
utils.typedData.signTypedData(domain, types, value, privateKey);
utils.typedData.verifyTypedData(domain, types, value, signature);
// TypedDataEncoder, hashStruct, hashDomain, getPayload — EIP-712Key points
- Prefer
TronWeb.createAccount/createRandom/fromMnemonicfor wallet creation; utils.accounts mirrors them. - Use ABI encode/decode for contract call data when not using contract(abi, address).methods.
- deserializeTx useful for inspecting or re-signing serialized transactions.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/utils/index.ts, accounts.ts, abi, transaction, message, typedData)
- https://tronweb.network/docu/docs/intro/
-->
Connection and version
Check that the TronWeb instance can reach the nodes and whether the full node version meets a required range. Use before sending transactions or when building agents that need a minimum API.
isConnected()
const status = await tronWeb.isConnected();
// { fullNode: true|false, solidityNode: true|false, eventServer: true|false }Each provider calls its status page (e.g. wallet/getnowblock for full node) and returns true if the response has expected fields (blockID, block_header). Use to detect network or node issues.
Node version
await tronWeb.getFullnodeVersion();
// Sets tronWeb.fullnodeVersion (e.g. '4.7.1'); called implicitly when needed
const ok = tronWeb.fullnodeSatisfies('>=4.1.1');
// semver.satisfies(fullnodeVersion, '>=4.1.1')Use fullnodeSatisfies when a feature requires a minimum node version (e.g. certain RPC or behavior). Default fullnodeVersion is '4.7.1' until getFullnodeVersion() runs.
Key points
- isConnected() is async and checks all three providers; eventServer can be undefined if not set.
- fullnodeVersion is set by getFullnodeVersion() from node info; call it once after construction if you rely on fullnodeSatisfies.
- TronWeb.version is the SDK version (e.g. '6.2.0'); fullnodeVersion is the node’s code version.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/tronweb.ts, src/lib/providers/HttpProvider.ts)
-->
Contract Module
Create contract instances from ABI (and optional address), call view methods, send transactions, decode input, deploy, or attach to an existing contract.
Create instance
const contract = tronWeb.contract(abi, address?);
// address omitted → undeployed instance for contract.new()Call and send
// View (constant) call
const result = await contract.methods.methodName(...args).call(options?);
// options: feeLimit, callValue, tokenValue, tokenId, from
// State-changing send
const tx = await contract.methods.methodName(...args).send(options?, privateKey?);
// options: from, feeLimit, callValue, shouldPollResponse, pollTimes, rawResponse, keepTxIDMethods are also callable by function selector or full signature. Overloaded functions are supported.
Decode input
const { name, params } = contract.decodeInput(data);
// data = 8-char selector + hex-encoded paramsDeploy and attach
// Deploy: options must include abi, bytecode, and constructor parameters
const newInstance = await contract.new(options, privateKey?);
// Returns new contract instance with ABI from options (not from chain).
await contract.at(contractAddress);
// Fetches contract from chain, sets address/bytecode/abi, returns this.Key Points
- For TypeScript inference, pass ABI with
as constor inline; thencontract.methodsand call/send return types are inferred. contract.new()in v6 returns a new instance using the ABI from options; it no longer mutates the current instance or relies on chain ABI for the returned instance.- Export types:
GetEventResultOptions,EventResponsefrom the package for event result typing.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/contract/index.ts, method.ts, tronweb.ts)
- https://tronweb.network/docu/docs/intro/
-->
Events
Query contract events via the event server. Requires eventServer to be set on the TronWeb instance.
By contract address
const res = await tronWeb.event.getEventsByContractAddress(contractAddress, options);
// or tronWeb.getEventResult(contractAddress, options)
// options: eventName, blockNumber, onlyUnconfirmed, onlyConfirmed,
// minBlockTimestamp, maxBlockTimestamp, orderBy, fingerprint, limit (default 20, max 200)By transaction or block
const res = await tronWeb.event.getEventsByTransactionID(txId, { only_unconfirmed?, only_confirmed? });
// or tronWeb.getEventByTransactionID(txId, options)
await tronWeb.event.getEventsByBlockNumber(blockNumber, { only_confirmed?, limit?, fingerprint? });
await tronWeb.event.getEventsOfLatestBlock({ only_confirmed? });Event server
tronWeb.event.setServer(eventServer, healthcheck?);
// Call when configuring a separate event server or changing URL.Response shape: { success, data?, error? }; on success use data; on failure the API throws with res.error.
Key Points
- Event server is separate from full/solidity nodes; set via constructor or
setEventServer/setEventHeader. - Limit for contract events is capped at 200.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/event.ts, tronweb.ts)
- https://tronweb.network/docu/docs/intro/
-->
Message and typed data signing
TronWeb supports two signing flows: personal message (TRON prefix) and EIP-712 typed data. Use for login, attestations, or contract-compatible structured signing.
Personal message (signMessage / verifyMessage)
TRON uses the prefix \x19TRON Signed Message:\n + message length before hashing (EIP-191 style).
// Sign (prefer signMessageV2 on Trx for correct header)
const sig = tronWeb.trx.signMessageV2('Hello', privateKey);
// or: utils.message.signMessage('Hello', privateKey)
// Verify — recovers base58 address
const base58 = utils.message.verifyMessage('Hello', sig);Hash only: utils.message.hashMessage(message) (message can be string, Uint8Array, or number array).
EIP-712 typed data
For structured data (domain + types + message) use the same API as Ethereum EIP-712.
import { utils } from 'tronweb';
const domain = {
name: 'MyDApp',
version: '1',
chainId: 1,
verifyingContract: contractAddressHex // 41... or 0x...
};
const types = {
Permit: [
{ name: 'owner', type: 'address' },
{ name: 'value', type: 'uint256' }
]
};
const value = { owner: 'T...', value: 100 };
const sig = utils.typedData.signTypedData(domain, types, value, privateKey);
const recoveredHex = utils.typedData.verifyTypedData(domain, types, value, sig);Instance API: tronWeb.trx.signTypedData(domain, types, value, privateKey?).
TypedDataEncoder (EIP-712 encoding):
TypedDataEncoder.from(types)— build encoder.TypedDataEncoder.hashDomain(domain)— domain hash.TypedDataEncoder.hashStruct(name, types, value)— struct hash.TypedDataEncoder.hash(domain, types, value)— full EIP-712 hash.TypedDataEncoder.getPayload(domain, types, value)— JSON payload foreth_signTypedData_v4.
TRON supports type trcToken (encoded as uint256).
Key points
- Personal sign: use
signMessageV2/utils.message.signMessageso header length is correct; verify withutils.message.verifyMessage. - Typed data: use TRON address (41... or 0x41...) in
verifyingContractand in structs; sign/verify via utils.typedData or tronWeb.trx.signTypedData.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/utils/message.ts, src/utils/typedData.ts, src/lib/trx.ts)
- https://tronweb.network/docu/docs/intro/
-->
Plugin system
TronWeb supports plugging extra behavior via tronWeb.plugin.register(PluginClass, options?). Use for custom modules (e.g. TronLink-style helpers) without modifying core.
Registering a plugin
class MyPlugin {
constructor(tronWeb) {
this.tronWeb = tronWeb;
}
pluginInterface(options) {
return {
requires: '>=6.0.0', // semver range for TronWeb.version
components: {
trx: {
myMethod() { return this.tronWeb.trx.getCurrentBlock(); }
}
}
};
}
}
const result = tronWeb.plugin.register(MyPlugin);
// result: { libs: [], plugged: ['myMethod'], skipped: [], error?: string }After registration, tronWeb.trx.myMethod() is available. Methods are bound to the target component (e.g. trx).
fullClass mode
To attach a whole class at the same level as trx (e.g. tronWeb.myHelper):
pluginInterface() {
return { requires: '>=6.0.0', fullClass: true };
}Then the plugin instance is set as tronWeb.<lowercaseClassName> and the class on TronWeb.<ClassName>.
Rules
- Blacklist: Methods named
constructoror starting with_, or listed in the component’spluginNoOverride, are skipped (not overridden). - Version: If
semver.satisfies(TronWeb.version, pluginInterface.requires)is false, registration throws. - Disabled: If TronWeb was built with
disablePlugins: true,registerreturns{ error: '...' }and does not plug.
Key points
- Use
componentsto add or replace methods on existing modules (trx, etc.); usefullClassto add a new top-level module. - Plugins receive the TronWeb instance and can call any API; keep
requiresaligned with the TronWeb version you depend on.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/plugin.ts)
- https://tronweb.network/docu/docs/intro/
-->
TransactionBuilder
Build and return unsigned transactions for TRX/token transfers, resources, and smart contracts.
Transfers and tokens
const txBuilder = tronWeb.transactionBuilder;
const tx = await txBuilder.sendTrx(to, amount, from?, options?);
const txToken = await txBuilder.sendToken(to, amount, tokenId, from?, options?);
await txBuilder.purchaseToken(issuerAddress, tokenId, amount, buyer?, options?);Options: permissionId, and (via helper) custom ref_block_bytes, ref_block_hash, expiration, timestamp when building with custom block header.
Resources (freeze / delegate / withdraw)
await txBuilder.freezeBalance(amount?, duration?, resource?, owner?, options?);
await txBuilder.unfreezeBalance(amount?, resource?, owner?, options?);
await txBuilder.freezeBalanceV2(amount?, resource?, owner?, options?);
await txBuilder.unfreezeBalanceV2(amount?, resource?, owner?, options?);
await txBuilder.delegateResource(amount, resource, receiver, owner?, options?);
await txBuilder.undelegateResource(amount, resource, receiver, owner?, options?);
await txBuilder.withdrawExpireUnfreeze(owner?, options?);
await txBuilder.cancelAllUnfreezeV2(owner?, options?);Smart contract
// Create contract (returns unsigned tx; sign + broadcast separately)
const createTx = await txBuilder.createSmartContract(options, issuerAddress?);
// options: abi, bytecode, name, parameters, feeLimit, callValue, originEnergyLimit, userFeePercentage, tokenValue, tokenId
// Trigger (state-changing) — returns transaction wrapper
const triggerTx = await txBuilder.triggerSmartContract(
contractAddress,
functionSelector,
options?, // { feeLimit, callValue, from?, txLocal?, ... }
parameters?,
issuerAddress?
);
// Constant call (read-only, no broadcast)
const result = await txBuilder.triggerConstantContract(
contractAddress, functionSelector, options?, parameters?, issuerAddress?
);
await txBuilder.triggerConfirmedConstantContract(...);
// Energy estimation
const { energy_required } = await txBuilder.estimateEnergy(
contractAddress, functionSelector, options?, parameters?, issuerAddress?
);
// Deploy constant contract (estimate energy for deployment)
await txBuilder.deployConstantContract({ input, ownerAddress, tokenId?, tokenValue?, callValue?, confirmed? });Custom block header
Pass ref block params from trx.getCurrentRefBlockParams() into transaction options so the builder uses your chosen block reference and expiration instead of fetching automatically.
Key Points
- All builder methods return transaction objects (or wrappers); use
tronWeb.trx.sign()thentronWeb.trx.sendRawTransaction()to send. triggerSmartContractwithoptions.txLocal: trueuses local execution path.- Multi-dimension address arrays (e.g.
address[][]) are supported in contract parameters.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/TransactionBuilder/TransactionBuilder.ts, helper.ts)
- https://tronweb.network/docu/docs/intro/
-->
Trx tokens and chain params
tronWeb.trx exposes token metadata and account resource/chain parameter APIs. Use for TRC-10 token info, bandwidth/energy balances, and chain configuration.
Token metadata
const token = await tronWeb.trx.getTokenFromID(tokenId);
// or getTokenByID(tokenId)
// { name, abbr, description, url, total_supply, ... } (decoded UTF-8 where applicable)
const tokens = await tronWeb.trx.getTokensIssuedByAddress(address);
// Record<tokenId, Token>
const list = await tronWeb.trx.getTokenListByName(tokenId);
// Token or Token[] by name searchAccount resources
const res = await tronWeb.trx.getAccountResources(address?);
// { freeNetLimit, freeNetUsed, NetLimit, NetUsed, EnergyLimit, EnergyUsed, ... }Use with getAccountNet(address) for bandwidth and energy details. For energy price (sun per unit): tronWeb.trx.getEnergyPrices().
Chain parameters
const params = await tronWeb.trx.getChainParameters();
// Array of { key, value } for chain configKey points
- Token IDs are strings; getTokenFromID/getTokenByID accept string or number.
- getAccountResources uses default address when omitted; getTokensIssuedByAddress uses default address hex when omitted.
- Energy and bandwidth are used for contract execution and transaction bandwidth; check getAccountNet and getEnergyPrices when estimating fees.
<!-- Source references:
- https://github.com/tronprotocol/tronweb (src/lib/trx.ts)
-->