TronWeb JavaScript SDK
TronWeb is the official JavaScript SDK for interacting with the TRON blockchain, providing a comprehensive encapsulation of the TRON HTTP API. As of version 6.2.2, it continues to be actively maintained with frequent minor and patch releases, incorporating new TRON features and API quality-of-life improvements. Unlike a direct fork of Ethereum's Web3.js, TronWeb is specifically tailored to unlock TRON's unique feature set and offers distinct tools for DApp integration across browsers, Node.js environments (v16+), and IoT devices. It ships with TypeScript types, enhancing developer experience for strongly typed projects. Key features include deterministic contract address computation (CREATE2), robust transaction deserialization, and methods for retrieving real-time witness lists and transaction building parameters.
Common errors
-
TypeError: TronWeb is not a constructor
cause Attempting to instantiate TronWeb using incorrect import syntax (e.g., CommonJS `require` for an ESM module, or `import { TronWeb } from 'tronweb'` instead of `import TronWeb from 'tronweb'`).fixFor ESM, use `import TronWeb from 'tronweb';`. For CommonJS, use `const TronWeb = require('tronweb');`. Ensure your project's module system is correctly configured. -
Error: Invalid private key provided
cause The private key passed to the TronWeb constructor is not in a valid format or is incorrect for the network being connected to.fixDouble-check your private key for typos, ensure it's a valid hexadecimal string, and confirm it's associated with the correct network (e.g., Shasta testnet key for Shasta). -
Error: Failed to connect to fullHost: https://api.trongrid.io
cause TronWeb instance failed to establish a connection to the specified full node. This can be due to network issues, an invalid `fullHost` URL, or missing/incorrect `TRON-PRO-API-KEY` headers for services like TronGrid.fixVerify your `fullHost` URL is correct and accessible. Ensure `TRON-PRO-API-KEY` is provided and valid if connecting to TronGrid. Check your internet connection and any firewall settings. -
Error: This feature requires JAVA-TRON v4.8.1 or above
cause Attempting to use a TronWeb method (e.g., `trx.getNowWitnessList`) that relies on a specific TRON full node feature only available in newer JAVA-TRON versions, while connected to an older node.fixEnsure the TRON full node you are connected to (e.g., your local quickstart instance or a public gateway) is running JAVA-TRON v4.8.1 or a newer compatible version.
Warnings
- breaking The behavior of `contract.new()` method was changed in v6.0.4. Previously, it mutated the current TronWeb instance; now, it returns a new contract instance and infers method signatures from the provided ABI. ABIs should be defined using `as const` or passed directly to `tronWeb.contract()` for accurate type inference.
- gotcha TronWeb requires Node.js v16 or above. Older Node.js versions are not officially supported and may lead to unexpected behavior or security vulnerabilities.
- gotcha Versions prior to v6.2.2 had potential prototype pollution vulnerabilities in `decodeParams` and `encodeArgs`. This was fixed by replacing `{}` with `Object.create(null)` to prevent malicious property injection.
- gotcha The `trx.getNowWitnessList` method, introduced in v6.2.0, requires the underlying JAVA-TRON full node to be running version v4.8.1 or above. Using it with older node versions will result in errors.
- deprecated The `jsonwebtoken` dependency was removed in v6.1.1 due to audit issues. While this improves the package's security posture, applications directly relying on `jsonwebtoken` through TronWeb might need to adjust.
Install
-
npm install tronweb -
yarn add tronweb -
pnpm add tronweb
Imports
- TronWeb
import { TronWeb } from 'tronweb';import TronWeb from 'tronweb';
- TronWeb (CommonJS)
const TronWeb = require('tronweb'); - Utilities (instance method)
import { getCreate2Address } from 'tronweb/utils';const create2Address = tronWeb.utils.address.getCreate2Address(creatorAddress, salt, bytecodeHash);
Quickstart
import TronWeb from 'tronweb';
// Replace with your actual TRON Grid API key and a test private key for Shasta
// NEVER use production private keys directly in code. Use environment variables for security.
const TRON_GRID_API_KEY = process.env.TRON_GRID_API_KEY ?? 'YOUR_TRONGRID_API_KEY';
const TEST_PRIVATE_KEY = process.env.TEST_PRIVATE_KEY ?? 'YOUR_SHASTA_PRIVATE_KEY_HERE'; // e.g., for a test account on Shasta
if (TRON_GRID_API_KEY === 'YOUR_TRONGRID_API_KEY' || TEST_PRIVATE_KEY === 'YOUR_SHASTA_PRIVATE_KEY_HERE') {
console.warn('Please provide a valid TRON_GRID_API_KEY and TEST_PRIVATE_KEY in your environment variables or replace placeholders.');
// In a real application, you might throw an error or exit.
}
const tronWeb = new TronWeb({
fullHost: 'https://api.shasta.trongrid.io', // Official Tron testnet endpoint
headers: { "TRON-PRO-API-KEY": TRON_GRID_API_KEY },
privateKey: TEST_PRIVATE_KEY
});
async function getAccountInfo() {
try {
const address = tronWeb.defaultAddress.base58;
if (!address) {
console.error("No default address set. Ensure your private key is valid and connected.");
return;
}
console.log(`Connected to Shasta Testnet with address: ${address}`);
const balanceSun = await tronWeb.trx.getBalance(address);
const balanceTrx = tronWeb.trx.fromSun(balanceSun);
console.log(`Account Balance: ${balanceTrx} TRX`);
// Example of using a new utility method (v6.2.2+)
const creatorAddress = 'TXwU1rY5Gj89P4g45v3C6M5427K8K1YJ8M'; // Example creator address
const salt = '0x1234567890abcdef1234567890abcdef'; // Example salt
const bytecodeHash = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; // Example bytecode hash
const create2Address = tronWeb.utils.address.getCreate2Address(creatorAddress, salt, bytecodeHash);
console.log(`CREATE2 Address for example: ${create2Address}`);
} catch (error) {
console.error("Error fetching account info or using utilities:", error);
}
}
getAccountInfo();