tronweb SDK
TronWeb is the definitive JavaScript SDK for interacting with the TRON blockchain, providing a unified interface for account management, transaction signing, and contract interaction. This comprehensive reference covers initialization, core utilities, and advanced patterns for building robust frontend and backend applications.
SDK Architecture
Section titled “SDK Architecture”TronWeb is the official, canonical JavaScript SDK for the TRON blockchain. While developers coming from Ethereum will find the Solidity syntax familiar, the network’s underlying state and resource models are unique. TronWeb is architected specifically to leverage the TRON engine, providing native interfaces for managing Energy and Bandwidth, interacting with both TRC-10 and EVM-compatible tokens, and deriving T-prefixed addresses.
Whether you are building a browser-based DApp with TronLink or a high-performance backend service on Node.js, TronWeb serves as the primary bridge between your application logic and the network nodes.
Installation
Section titled “Installation”# Task: Install the official TRON JavaScript SDK.npm install tronwebtronweb works in Node.js (CommonJS and ESM) and in the browser. TypeScript types are bundled.
Initialization
Section titled “Initialization”// Task: Instantiate TronWeb for mainnet using a private key.import TronWeb from "tronweb"
// With a private key (server-side / scripts)const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io', // mainnet privateKey: process.env.PRIVATE_KEY,});
// Read-only (no private key — for querying only)const tronWebReadOnly = new TronWeb({ fullHost: 'https://api.trongrid.io',});TronGrid Endpoints
Section titled “TronGrid Endpoints”| Network | fullHost |
|---|---|
| Mainnet | https://api.trongrid.io |
| Nile testnet | https://nile.trongrid.io |
| Shasta testnet | https://api.shasta.trongrid.io |
TronGrid requires an API key for production use above the free tier rate limit. Set it:
// Task: Configure TronWeb with a TronGrid Pro API Key.const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io', headers: { 'TRON-PRO-API-KEY': process.env.TRONGRID_API_KEY }, privateKey: process.env.PRIVATE_KEY,});Address Utilities
Section titled “Address Utilities”// Task: Validate addresses and convert between Hex/Base58 formats.// Check if an address is validtronWeb.isAddress('TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb2Jq'); // true
// Convert hex address to Base58 (T-prefix)const base58 = tronWeb.address.fromHex('41e552f6487585c2b58bc2c9bb4492bc1f17132cd0');// → 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb2Jq'
// Convert Base58 to hexconst hex = tronWeb.address.toHex('TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb2Jq');// → '41e552f6487585c2b58bc2c9bb4492bc1f17132cd0'
// Derive address from private keyconst address = tronWeb.address.fromPrivateKey(process.env.PRIVATE_KEY);Account and Balance
Section titled “Account and Balance”// Task: Query account TRX balance and Energy/Bandwidth resources.// TRX balance (returned in Sun — divide by 1_000_000 for TRX)const balanceSun = await tronWeb.trx.getBalance('TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb2Jq');const balanceTRX = balanceSun / 1_000_000;
// Full account info (balance, resources, frozen amounts, permissions)const account = await tronWeb.trx.getAccount('TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb2Jq');
// Account resource info (Energy, Bandwidth balances and limits)const resources = await tronWeb.trx.getAccountResources('TN3W4H6rK2...');console.log(resources.EnergyLimit); // total Energy availableconsole.log(resources.EnergyUsed); // Energy consumed so far this periodconsole.log(resources.NetLimit); // total Bandwidth availableconsole.log(resources.freeNetUsed); // free Bandwidth consumed todaySending TRX
Section titled “Sending TRX”// Task: Transfer native TRX tokens to another address.// Send TRX — amount is in Sun (1 TRX = 1,000,000 Sun)const tx = await tronWeb.trx.sendTransaction( 'TRecipientAddress...', // to 10_000_000, // amount: 10 TRX);console.log(tx.txid); // transaction hashContract Interaction
Section titled “Contract Interaction”Loading a Deployed Contract
Section titled “Loading a Deployed Contract”// Task: Load a contract instance using its address and optional ABI.// Load a contract by address (fetches ABI from the chain if verified)const contract = await tronWeb.contract().at('TContractAddress...');
// Or provide the ABI explicitly (faster, works for unverified contracts)const abi = [ /* ABI array */ ];const contractExplicit = tronWeb.contract(abi, 'TContractAddress...');Calling View Functions (free)
Section titled “Calling View Functions (free)”View and pure functions do not cost Energy when called off-chain:
// Task: Execute a view-only method call without creating a transaction.// .call() for read-only functions — no transaction, no feeconst result = await contract.balanceOf('TUserAddress...').call();console.log(result.toString()); // BigNumberSending Transactions (state-changing)
Section titled “Sending Transactions (state-changing)”// Task: Create and send a transaction for a state-changing method.// .send() for state-changing functions — creates a transactionconst txId = await contract.transfer('TRecipient...', 1_000_000).send({ feeLimit: 1_000_000_000, // max TRX to burn if no Energy (in Sun) callValue: 0, // TRX to send with the call (in Sun), usually 0 shouldPollResponse: true, // wait for confirmation before returning});console.log(txId); // transaction hashPassing Constructor Arguments on Deploy
Section titled “Passing Constructor Arguments on Deploy”// Task: Deploy a new smart contract using ABI and bytecode.const deployed = await tronWeb.contract().new({ abi: compiledAbi, bytecode: compiledBytecode, feeLimit: 1_000_000_000, parameters: [constructorArg1, constructorArg2],});console.log(deployed.address);TRC-20 Token Operations
Section titled “TRC-20 Token Operations”// Task: Perform standard TRC-20 balance checks and transfers.const usdtAddress = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t'; // mainnet USDT
const usdt = await tronWeb.contract().at(usdtAddress);
// Balance (returned in token's smallest unit — USDT uses 6 decimals)const balance = await usdt.balanceOf('TYourAddress...').call();const usdtAmount = balance / 1_000_000;
// Transferawait usdt.transfer('TRecipient...', 5_000_000).send({ feeLimit: 1_000_000_000, shouldPollResponse: true,});
// Approveawait usdt.approve('TSpenderContract...', 1_000_000_000).send({ feeLimit: 100_000_000,});Listening to Events
Section titled “Listening to Events”// Task: Watch for real-time Transfer events on a contract.const contract = await tronWeb.contract().at('TContractAddress...');
// Watch all Transfer events on a TRC-20 contractcontract.Transfer().watch((err, event) => { if (err) return console.error(err); console.log('Transfer:', { from: event.result.from, to: event.result.to, value: event.result.value.toString(), txId: event.transaction, });});Transaction Status
Section titled “Transaction Status”// Task: Retrieve transaction receipts and Energy consumption data.// Get transaction info (includes Energy consumed, result, block)const info = await tronWeb.trx.getTransactionInfo('txHashHere...');console.log(info.receipt.result); // 'SUCCESS' or 'FAILED'console.log(info.receipt.energy_usage); // Energy consumed
// Get raw transactionconst tx = await tronWeb.trx.getTransaction('txHashHere...');Error Handling
Section titled “Error Handling”tronweb throws or rejects with error objects that include a message field. Wrap calls in try/catch:
// Task: Catch and analyze SDK errors and contract reverts.try { const tx = await contract.someMethod().send({ feeLimit: 100_000_000 });} catch (err) { if (err.includes('REVERT')) { // Contract reverted — check your inputs and Energy limit } if (err.includes('bandwith')) { // note: tronweb spells it without 'd' // Insufficient Bandwidth } console.error(err);}Using tronweb in a Browser DApp
Section titled “Using tronweb in a Browser DApp”When building a browser DApp, use the window.tronWeb injected by TronLink rather than instantiating tronweb yourself. This automatically uses the user’s connected wallet without exposing a private key:
// Task: Connect to the user's injected TronLink instance.if (typeof window.tronWeb === 'undefined') { alert('TronLink is not installed.'); return;}
const tronWeb = window.tronWeb;
// Check if user has approved the connectionif (!tronWeb.defaultAddress.base58) { // User has not connected their wallet to your DApp yet}
const userAddress = tronWeb.defaultAddress.base58;const contract = await tronWeb.contract().at('TContractAddress...');The injected window.tronWeb is pre-configured with the user’s account and signs transactions via the TronLink extension without your DApp ever seeing the private key.