Skip to content

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.

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.

Terminal
# Task: Install the official TRON JavaScript SDK.
npm install tronweb

tronweb works in Node.js (CommonJS and ESM) and in the browser. TypeScript types are bundled.


init.js
// 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',
});
NetworkfullHost
Mainnethttps://api.trongrid.io
Nile testnethttps://nile.trongrid.io
Shasta testnethttps://api.shasta.trongrid.io

TronGrid requires an API key for production use above the free tier rate limit. Set it:

init_apikey.js
// 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,
});

addresses.js
// Task: Validate addresses and convert between Hex/Base58 formats.
// Check if an address is valid
tronWeb.isAddress('TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb2Jq'); // true
// Convert hex address to Base58 (T-prefix)
const base58 = tronWeb.address.fromHex('41e552f6487585c2b58bc2c9bb4492bc1f17132cd0');
// → 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb2Jq'
// Convert Base58 to hex
const hex = tronWeb.address.toHex('TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb2Jq');
// → '41e552f6487585c2b58bc2c9bb4492bc1f17132cd0'
// Derive address from private key
const address = tronWeb.address.fromPrivateKey(process.env.PRIVATE_KEY);

balance.js
// 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 available
console.log(resources.EnergyUsed); // Energy consumed so far this period
console.log(resources.NetLimit); // total Bandwidth available
console.log(resources.freeNetUsed); // free Bandwidth consumed today

send.js
// 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 hash

contract_load.js
// 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...');

View and pure functions do not cost Energy when called off-chain:

contract_call.js
// Task: Execute a view-only method call without creating a transaction.
// .call() for read-only functions — no transaction, no fee
const result = await contract.balanceOf('TUserAddress...').call();
console.log(result.toString()); // BigNumber
contract_send.js
// Task: Create and send a transaction for a state-changing method.
// .send() for state-changing functions — creates a transaction
const 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 hash
contract_deploy.js
// 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);

trc20_ops.js
// 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;
// Transfer
await usdt.transfer('TRecipient...', 5_000_000).send({
feeLimit: 1_000_000_000,
shouldPollResponse: true,
});
// Approve
await usdt.approve('TSpenderContract...', 1_000_000_000).send({
feeLimit: 100_000_000,
});

events.js
// 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 contract
contract.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,
});
});

tx_info.js
// 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 transaction
const tx = await tronWeb.trx.getTransaction('txHashHere...');

tronweb throws or rejects with error objects that include a message field. Wrap calls in try/catch:

error_handling.js
// 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);
}

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:

dapp_usage.js
// 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 connection
if (!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.