### Basic TronWeb Setup Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Initialize TronWeb with your preferred node provider, API key, and private key. This setup is required before interacting with the TRON blockchain. ```typescript import { TronWeb } from 'tronweb'; const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io', headers: { 'TRON-PRO-API-KEY': 'your-api-key' }, privateKey: '0x...' }); ``` -------------------------------- ### Basic Setup Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Demonstrates how to initialize TronWeb with a full host, API key, and private key. ```APIDOC ## Basic Setup ### Description Initializes TronWeb with connection details and authentication. ### Code ```typescript import { TronWeb } from 'tronweb'; const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io', headers: { 'TRON-PRO-API-KEY': 'your-api-key' }, privateKey: '0x...' }); ``` ``` -------------------------------- ### Install TronWeb with npm Source: https://github.com/tronprotocol/tronweb/blob/master/README.md Use this command to install TronWeb in your Node.js project. ```bash npm install tronweb ``` -------------------------------- ### Install TronWeb with yarn Source: https://github.com/tronprotocol/tronweb/blob/master/README.md Use this command to install TronWeb in your Node.js project using yarn. ```bash yarn add tronweb ``` -------------------------------- ### TronWeb Account Creation Example Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Shows how to generate a new random Tron account, including its private key, public key, and addresses. ```typescript const newAccount = TronWeb.createAccount(); console.log(newAccount.address.base58); ``` -------------------------------- ### TronWeb Constructor (Options Object) Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Initializes TronWeb with a configuration object, allowing for flexible setup of nodes, event servers, and private keys. ```APIDOC ## Constructor (Options Object) ### Description Initialize TronWeb with configuration options. ### Parameters #### Options Object - **options.fullNode** (string | HttpProvider) - Optional - Full node provider URL or instance - **options.solidityNode** (string | HttpProvider) - Optional - Solidity node provider URL or instance - **options.fullHost** (string | HttpProvider) - Optional - Convenient jolly for both full and solidity node - **options.eventServer** (string | HttpProvider) - Optional - Event server URL or instance - **options.headers** (Record) - Optional - HTTP headers for all requests - **options.eventHeaders** (AxiosRequestHeaders) - Optional - HTTP headers for event server only - **options.privateKey** (string) - Optional - Private key for transaction signing - **options.disablePlugins** (boolean) - Optional - Disable plugin loading ### Example ```typescript const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io', privateKey: '0x...', headers: { 'TRON-PRO-API-KEY': 'your-api-key' } }); ``` ``` -------------------------------- ### Instantiate TronWeb with Full Host Source: https://github.com/tronprotocol/tronweb/blob/master/README.md Configure TronWeb using a fullHost, which simplifies setup when a single server provides all necessary services. Requires an API key for TRONGRID. ```javascript const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io', headers: { "TRON-PRO-API-KEY": 'your api key' }, privateKey: 'your private key' }) ``` -------------------------------- ### Query Account Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Example of retrieving account information, including balance and frozen balance. ```APIDOC ## Query Account ### Description Retrieves detailed information about a TRON account, including its balance and frozen resources. ### Method `tronWeb.trx.getAccount(address)` ### Parameters - **address** (string) - The TRON address of the account to query. ### Response Example ```typescript const account = await tronWeb.trx.getAccount('TN3W4H6rK34me3xWQV5zCxmCtg7AixstFH'); console.log('Balance (Sun):', account.balance); console.log('Frozen balance:', account.tron_power); ``` ``` -------------------------------- ### TronWeb SDK Documentation Structure Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/SUMMARY.txt The TronWeb SDK documentation is structured to provide clear and comprehensive information for developers. It includes detailed method/function documentation, type definitions, error documentation, and configuration guides, all with a focus on practical code examples and cross-referencing. ```APIDOC ## TronWeb SDK Documentation Overview This documentation outlines the structure and content of the TronWeb SDK reference materials. ### Documentation Structure 1. **Method/Function Documentation**: * Full TypeScript signature * Parameters table (name, type, required, default, description) * Return type with description * Throws/errors section * Code examples * Source file reference 2. **Type Documentation**: * Type definition in code block * Field/property table * Which functions accept/return type * Usage examples 3. **Error Documentation**: * Error message * Trigger condition * Source location * Example code (❌ wrong, ✓ correct) 4. **Configuration Documentation**: * Default values table * Option descriptions * Common patterns * Best practices ### Quality Metrics * **Documentation Depth**: * Average method documentation: 250-500 words * Average class documentation: 1,000-1,400 words * Average type documentation: 200-300 words * Average error documentation: 100-200 words * **Code Examples Quality**: * Real, executable patterns * Both positive and negative examples * Error handling demonstrations * Best practice illustrations * **Cross-References**: * Internal links between related topics * Source file references with line numbers * Related method cross-references * Type link to usage locations ### Key Features * **Complete Method Signatures**: * All overloads documented separately * All parameter types included * All return types specified * Optional parameters clearly marked * **Practical Examples**: * Real TypeScript/JavaScript code * Best practice patterns * Error handling demonstrations * Common workflow examples * **Type System Coverage**: * All exported types * All interface definitions * All type aliases * All enumerations * **Error Documentation**: * All error conditions * Trigger scenarios * Handling strategies * Prevention patterns * **Configuration Guide**: * All options explained * Default values listed * Environment setup * Multi-environment patterns * **Navigation**: * Main README with quick start * INDEX for document organization * SUMMARY for statistics * Cross-links throughout ### Assumptions & Decisions * **Scope**: Focused on public API only (internal implementation details, private methods/properties, test utilities excluded). * **Examples**: TypeScript/JavaScript, using modern async/await syntax, with type annotations where helpful, including error handling patterns. * **Organization**: By class/module (one file per major class, utilities grouped, types and errors in separate reference docs). * **Audience**: Developers using TronWeb, assuming basic blockchain knowledge and JavaScript/TypeScript fluency, with security-related guidance provided. ``` -------------------------------- ### Run local TRON network with TRE Source: https://github.com/tronprotocol/tronweb/blob/master/README.md Start a local TRON network using Docker and the TRON Runtime Environment (TRE) for development and testing. ```bash docker run -it -p 9090:9090 --rm --name tron tronbox/tre:dev ``` -------------------------------- ### TronWeb Address Conversion Example Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Demonstrates converting addresses between hexadecimal and base58 formats using TronWeb.address methods. ```typescript const base58 = TronWeb.address.fromHex('0x41...'); const hex = TronWeb.address.toHex('TN3W4H6rK34me3xWQV5zCxmCtg7AixstFH'); ``` -------------------------------- ### Get Account Resources Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Fetches the bandwidth and energy resource usage for a given account address. ```typescript async getAccountResources(address: string = this.tronWeb.defaultAddress.hex): Promise ``` -------------------------------- ### TronWeb Account Derivation from Mnemonic Example Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Illustrates deriving an account from a BIP39 mnemonic phrase. Ensure the mnemonic is correct and the derivation path is appropriate. ```typescript const account = TronWeb.fromMnemonic('word1 word2 ... word12'); ``` -------------------------------- ### Send TRX Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Example of sending TRX from one account to another. ```APIDOC ## Send TRX ### Description Transfers TRX from the current account to a specified recipient address. ### Method `tronWeb.trx.sendTransaction(recipientAddress, amount)` ### Parameters - **recipientAddress** (string) - The address of the recipient. - **amount** (number) - The amount of TRX to send, in Sun (1 TRX = 1,000,000 Sun). ### Request Example ```typescript const result = await tronWeb.trx.sendTransaction( 'TN3W4H6rK34me3xWQV5zCxmCtg7AixstFH', 1000000 // 1 TRX in Sun ); console.log('TXID:', result.txid); ``` ``` -------------------------------- ### Handle Multi-Environment Setup Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Configure TronWeb to work with different network environments (mainnet, shasta, local) by reading the network name from an environment variable. ```typescript const networks = { mainnet: { fullHost: 'https://api.trongrid.io' }, shasta: { fullHost: 'https://api.shasta.trongrid.io' }, local: { fullHost: 'http://localhost:9090' } }; const tronWeb = new TronWeb(networks[process.env.TRON_NETWORK || 'mainnet']); ``` -------------------------------- ### Register a Custom Plugin Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Register and activate a custom plugin with TronWeb. This example shows how to define a plugin class and register it, handling potential registration errors. ```typescript class MyPlugin { constructor(tronWeb) { this.tronWeb = tronWeb; } pluginInterface(options) { return { requires: '6.0.0', components: { trx: { myMethod: async function() { // custom implementation } } } }; } } const result = tronWeb.plugin.register(MyPlugin, {}); if (result.error) { console.log('Plugin registration failed:', result.error); } else { console.log('Methods plugged:', result.plugged); } ``` -------------------------------- ### HttpProvider Instance Properties Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Access properties of an HttpProvider instance to get details about the connection configuration. ```APIDOC ## HttpProvider Instance Properties ### Description Properties available on an HttpProvider instance. ### Properties - **host** (string) - Provider URL - **timeout** (number) - Request timeout (ms) - **user** (string) - Basic auth username - **password** (string) - Basic auth password - **headers** (Record) - HTTP headers - **statusPage** (string) - Health check path - **instance** (AxiosInstance) - Axios HTTP client ``` -------------------------------- ### Manage TRON Account Resources Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Provides examples for retrieving account information, checking resource usage (bandwidth, energy), and performing operations like freezing or unfreezing TRX for specific resources. ```typescript // Get account state const account = await tronWeb.trx.getAccount(address); // Check resources const resources = await tronWeb.trx.getAccountResources(address); // Freeze TRX for energy await tronWeb.trx.freezeBalance( 1000000, // 1 TRX in Sun 3, // 3 days 'ENERGY' // Resource type ); // Unfreeze await tronWeb.trx.unfreezeBalance('ENERGY'); ``` -------------------------------- ### Get Account Details Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Fetches confirmed account details, including balance, resources, and permissions. Throws an error if the provided address is invalid. ```typescript async getAccount(address: string = this.tronWeb.defaultAddress.hex): Promise ``` ```javascript const account = await tronWeb.trx.getAccount('TN3W4H6rK34me3xWQV5zCxmCtg7AixstFH'); console.log(account.balance); // Balance in Sun ``` -------------------------------- ### Get Contract Details Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieve details of a deployed smart contract, including its ABI and bytecode, using its address. Throws an error if the contract does not exist. ```typescript async getContract(address: string): Promise // Example: const contract = await tronWeb.trx.getContract('TN3W4H6rK34me3xWQV5zCxmCtg7AixstFH'); console.log(contract.abi.entrys); // Contract ABI ``` -------------------------------- ### Multiple Providers Configuration Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Configure TronWeb to use different nodes for full node, solidity node, and event server. This example uses the same TronGrid API for all, but allows for distinct configurations. ```typescript const tronWeb = new TronWeb({ fullNode: 'https://api.trongrid.io', solidityNode: 'https://api.trongrid.io', eventServer: 'https://event.trongrid.io', headers: { 'TRON-PRO-API-KEY': 'your-key' } }); ``` -------------------------------- ### Typical Workflow: Load Deployed Contract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Illustrates how to load an already deployed smart contract by its address. ```APIDOC ### Load Deployed Contract ```typescript const contract = tronWeb.contract(abi); await contract.at(contractAddress); ``` ``` -------------------------------- ### Typical Workflow: Deploy a Contract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Shows the process of deploying a new smart contract using TronWeb. ```APIDOC ## Typical Workflow ### Deploy a Contract ```typescript const contract = tronWeb.contract(abi, false); const deployed = await contract.new({ abi: abi, bytecode: '0x...', name: 'MyContract', feeLimit: 100000000, parameters: [initialValue] }, privateKey); ``` ``` -------------------------------- ### Get Current Block Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Fetches the most recent block from the TRON network. Use this to get the latest block's data, including its timestamp. ```typescript const block = await tronWeb.trx.getCurrentBlock(); console.log(block.block_header.raw_data.timestamp); ``` -------------------------------- ### Get Transaction Count in Block Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Get the total number of transactions within a specified block. The block can be identified by 'earliest', 'latest', a block number, or a block hash. Defaults to the `tronWeb.defaultBlock` if not specified. ```typescript async getBlockTransactionCount( block: 'earliest' | 'latest' | number | string | false = this.tronWeb.defaultBlock ): Promise ``` -------------------------------- ### Instantiate TronWeb with All Separate Nodes Source: https://github.com/tronprotocol/tronweb/blob/master/README.md Set up TronWeb by specifying distinct servers for the full node, solidity node, and event server, along with a private key. ```javascript 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' } ) ``` -------------------------------- ### Get Account By ID Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieves account information using its numeric ID. ```typescript async getAccountById(id: string): Promise ``` -------------------------------- ### Initialize TronWeb with Options Object Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Initialize TronWeb with configuration options including full node, solidity node, event server, private key, and custom headers. ```typescript import { TronWeb } from 'tronweb'; const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io', privateKey: '0x...', headers: { 'TRON-PRO-API-KEY': 'your-api-key' } }); ``` -------------------------------- ### new(options, privateKey?) Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Deploys a new smart contract to the blockchain. It takes deployment options and an optional private key for signing the transaction. ```APIDOC ## new(options, privateKey?) ### Description Deploys a new smart contract to the blockchain. It takes deployment options and an optional private key for signing the transaction. ### Method `async` ### Parameters #### Parameters - **options** (CreateSmartContractOptions) - Required - Deployment options (see TransactionBuilder.createSmartContract) - **privateKey** (string) - Optional - Default key - Private key for signing ### Returns - New contract instance with the deployed address set. ### Throws - `Error` if deployment fails. ### Example ```typescript const deployedContract = await contract.new({ abi: abi, bytecode: '0x60806040...', name: 'MyToken', feeLimit: 100000000, parameters: [1000000] // constructor args }); console.log(deployedContract.address); // Contract address ``` ``` -------------------------------- ### TronWeb Constructor (Legacy Parameters) Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Initializes TronWeb using individual provider arguments, maintaining backward compatibility with v5. ```APIDOC ## Constructor (Legacy Parameters) ### Description Initialize with individual provider arguments (backwards compatible with v5). ### Parameters - **fullNode** (string | HttpProvider) - Required - Full node provider - **solidityNode** (string | HttpProvider) - Required - Solidity node provider - **eventServer** (string | HttpProvider) - Optional - Event server provider - **privateKey** (string) - Optional - Private key for signing ### Example ```typescript const tronWeb = new TronWeb( 'https://api.trongrid.io', 'https://api.trongrid.io', 'https://api.trongrid.io', '0x...' ); ``` ``` -------------------------------- ### Configure TronWeb with Full Host Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Initialize TronWeb using a fullHost. This host will be used for both the fullNode and solidityNode unless they are explicitly provided. ```typescript const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io' }); // tronWeb.fullNode and tronWeb.solidityNode both point to fullHost ``` ```typescript const tronWeb2 = new TronWeb({ fullHost: 'https://api.trongrid.io', solidityNode: 'https://different-node.example.com' // Overrides fullHost for solidityNode }); ``` -------------------------------- ### Initialize TronWeb for Local Development Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Connect to a local Tron development environment (TRE) by setting the fullHost to localhost. The chain ID may vary. ```typescript const tronWeb = new TronWeb({ fullHost: 'http://localhost:9090' }); ``` -------------------------------- ### Get Unconfirmed Transaction Info by ID Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieve information about an unconfirmed transaction from the full node using its transaction ID. ```typescript async getUnconfirmedTransactionInfo(transactionID: string): Promise ``` -------------------------------- ### Get Events by Transaction ID Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Fetch all events associated with a particular transaction. You can filter to retrieve only confirmed or unconfirmed events. ```typescript const events = await tronWeb.event.getEventsByTransactionID( '0x...', { only_confirmed: true } ); ``` -------------------------------- ### Typical Workflow: Call Write Function Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Explains how to call a state-changing function on a smart contract. ```APIDOC ### Call Write Function ```typescript const result = await contract.transfer(recipientAddress, amount).send({ feeLimit: 100000000 }); ``` ``` -------------------------------- ### Get Chain Parameters Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieves all network parameters that are available for modification through proposals. This includes their current values, descriptions, and valid ranges. ```typescript async getChainParameters(): Promise ``` -------------------------------- ### Get Confirmed Transaction by ID Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieve a confirmed transaction by its ID. This method specifically queries the solidity node for transactions that have been confirmed. ```typescript async getConfirmedTransaction(transactionID: string): Promise ``` -------------------------------- ### Create Smart Contract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/transaction-builder.md Use this method to deploy a new smart contract to the blockchain. Provide the contract's ABI, bytecode, and optional parameters like name, constructor arguments, and fee limits. ```typescript async createSmartContract( options: CreateSmartContractOptions, from: string = this.tronWeb.defaultAddress.hex ): Promise> ``` ```typescript const tx = await tronWeb.transactionBuilder.createSmartContract({ abi: contractABI, bytecode: '0x60806040...', name: 'MyContract', feeLimit: 100000000, parameters: [1000] }); const contractAddress = tx.contract_address; ``` -------------------------------- ### Initialize TronWeb with Legacy Parameters Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Initialize TronWeb using legacy parameters for full node, solidity node, event server, and private key. This is compatible with v5. ```typescript import { TronWeb } from 'tronweb'; const tronWeb = new TronWeb( 'https://api.trongrid.io', 'https://api.trongrid.io', 'https://api.trongrid.io', '0x...' ); ``` -------------------------------- ### Configure Request Timeout Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Adjust the request timeout for TronWeb connections. The default is 30 seconds; this example sets it to 60 seconds. ```typescript const provider = new HttpProvider( 'https://api.trongrid.io', 60000 // 60 seconds timeout (default is 30 seconds) ); const tronWeb = new TronWeb({ fullNode: provider, solidityNode: provider }); ``` -------------------------------- ### Get Proposal by ID Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieves a specific network modification proposal using its unique ID. Ensure the proposal ID is a non-negative number. ```typescript async getProposal(proposalID: number): Promise ``` -------------------------------- ### Use Configuration Object for Initialization Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Recommended approach for initializing TronWeb using a configuration object, which is more maintainable than passing individual arguments. ```typescript // ✓ Recommended: Clear and flexible const config = { fullHost: 'https://api.trongrid.io', privateKey: process.env.PRIVATE_KEY }; const tronWeb = new TronWeb(config); // ✗ Avoid: Less maintainable const tronWeb = new TronWeb( 'https://api.trongrid.io', 'https://api.trongrid.io', 'https://api.trongrid.io', process.env.PRIVATE_KEY ); ``` -------------------------------- ### Initialize TronWeb for Mainnet Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Use this snippet to connect to the Tron mainnet. This is the default configuration. ```typescript const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io' }); ``` -------------------------------- ### Deploy a New Contract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Deploy a new smart contract by providing its ABI, bytecode, name, and initial parameters. Requires a private key for signing the deployment transaction. ```typescript const contract = tronWeb.contract(abi, false); const deployed = await contract.new({ abi: abi, bytecode: '0x...', name: 'MyContract', feeLimit: 100000000, parameters: [initialValue] }, privateKey); ``` -------------------------------- ### Initialize TronWeb with Legacy Positional Parameters Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md This legacy method initializes TronWeb using positional arguments for full node, solidity node, event server, and private key. Ensure parameters are provided in the correct order. ```typescript const tronWeb = new TronWeb( 'https://api.trongrid.io', // fullNode 'https://api.trongrid.io', // solidityNode 'https://api.trongrid.io', // eventServer (optional) '0x...' // privateKey (optional) ); ``` -------------------------------- ### Initialize TronWeb with Environment Variables Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Configure TronWeb instance using environment variables for node hosts, event servers, and private keys. Provides fallback defaults if variables are not set. ```typescript const config = { fullHost: process.env.TRON_FULL_HOST || 'https://api.trongrid.io', eventServer: process.env.TRON_EVENT_SERVER || 'https://api.trongrid.io', privateKey: process.env.TRON_PRIVATE_KEY, headers: process.env.TRON_API_KEY ? { 'TRON-PRO-API-KEY': process.env.TRON_API_KEY } : {} }; const tronWeb = new TronWeb(config); ``` -------------------------------- ### Get Transactions To Address (Deprecated) Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieves transactions received by a specified address. Note that this API is deprecated on full nodes version 4.1.1 and newer. ```typescript async getTransactionsToAddress( address: string = this.tronWeb.defaultAddress.hex, limit: number = 30, offset: number = 0 ): Promise ``` -------------------------------- ### Get Transactions From Address (Deprecated) Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieves transactions sent from a specified address. Note that this API is deprecated on full nodes version 4.1.1 and newer. ```typescript async getTransactionsFromAddress( address: string = this.tronWeb.defaultAddress.hex, limit: number = 30, offset: number = 0 ): Promise ``` -------------------------------- ### Deploy Smart Contract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Illustrates how to deploy a new smart contract to the TRON blockchain. ```APIDOC ## Deploy Smart Contract ### Description Deploys a new smart contract with a given ABI, bytecode, and name. ### Method `tronWeb.contract().new(options, privateKey)` ### Parameters - **options** (object) - Deployment options. - **abi** (array) - The contract's ABI. - **bytecode** (string) - The contract's bytecode. - **name** (string) - The contract name. - **feeLimit** (number) - The maximum fee limit for the deployment. - **privateKey** (string) - The private key of the account deploying the contract. ### Request Example ```typescript const contract = tronWeb.contract(abi); const deployed = await contract.new({ abi: abi, bytecode: '0x...', name: 'MyToken', feeLimit: 100000000 }, privateKey); console.log('Contract:', deployed.address); ``` ``` -------------------------------- ### Typical Workflow: Estimate Gas/Energy Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Shows how to estimate the gas or energy consumption for a contract function call. ```APIDOC ### Estimate Gas/Energy ```typescript const energyEstimate = await contract.complexFunction(params).call({ estimateEnergy: true }); ``` ``` -------------------------------- ### Call Smart Contract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Demonstrates how to interact with a deployed smart contract, including read-only and state-changing calls. ```APIDOC ## Call Smart Contract ### Description Interacts with a deployed smart contract, allowing for read-only queries and state-changing transactions. ### Method `tronWeb.contract(abi).at(contractAddress)` ### Parameters - **abi** (array) - The contract's ABI. - **contractAddress** (string) - The address of the deployed contract. ### Usage #### Read-only Call ```typescript const contract = tronWeb.contract(abi); await contract.at('TN3W4H6rK34me3xWQV5zCxmCtg7AixstFH'); const balance = await contract.balanceOf(userAddress).call(); console.log('Balance:', balance); ``` #### State-changing Call ```typescript const contract = tronWeb.contract(abi); await contract.at('TN3W4H6rK34me3xWQV5zCxmCtg7AixstFH'); const result = await contract.transfer(recipient, amount).send({ feeLimit: 100000000 }); console.log('TXID:', result.txid); ``` ``` -------------------------------- ### Deploy New Smart Contract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Deploy a new smart contract to the blockchain using provided options including ABI, bytecode, and constructor arguments. Returns a new contract instance with the deployed address. ```typescript const deployedContract = await contract.new({ abi: abi, bytecode: '0x60806040...', name: 'MyToken', feeLimit: 100000000, parameters: [1000000] // constructor args }); console.log(deployedContract.address); // Contract address ``` -------------------------------- ### Get Transaction Info by ID Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieve detailed information about a confirmed transaction, including block number, energy usage, and fees. The transaction ID is required. ```typescript async getTransactionInfo(transactionID: string): Promise ``` -------------------------------- ### Get Transaction by ID Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieve a transaction by its ID. This method queries the full node and can return unconfirmed or confirmed transactions. Throws an error if the transaction is not found. ```typescript async getTransaction(transactionID: string): Promise ``` -------------------------------- ### Create Account Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Shows how to generate a new TRON account or create one from a mnemonic phrase. ```APIDOC ## Create Account ### Description Generates a new TRON account or recovers an existing one from a mnemonic. ### Code ```typescript // Generate a new account const account = TronWeb.createAccount(); console.log(account.address.base58); // Or from mnemonic const account = TronWeb.fromMnemonic('word1 word2 ... word12'); ``` ``` -------------------------------- ### Importing HttpProvider Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Demonstrates how to import the HttpProvider from the tronweb library, either through the main providers object or directly. ```typescript import { providers } from 'tronweb'; const { HttpProvider } = providers; // Or directly import { HttpProvider } from 'tronweb'; ``` -------------------------------- ### Instantiate Contract Class Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Create a new Contract instance with TronWeb, ABI, and an optional address. Alternatively, use the tronWeb.contract() helper. ```typescript const contract = new Contract(tronWeb, abi, '0x...'); // Or use tronWeb.contract() helper: const contract = tronWeb.contract(abi, '0x...'); ``` -------------------------------- ### Get Block by Identifier Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieves a specific block using various identifiers. This method supports keywords like 'latest' and 'earliest', block numbers, or block hashes. ```typescript const block = await tronWeb.trx.getBlock('latest'); const block2 = await tronWeb.trx.getBlock(12345); const block3 = await tronWeb.trx.getBlock('0xa1b2c3...') ``` -------------------------------- ### Derive Account from Mnemonic Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/utilities.md Derives a TRON account from an existing BIP39 mnemonic phrase. Ensure the provided path follows the TRON BIP44 pattern (starting with 'm/44'/195'/'). ```typescript generateAccountWithMnemonic( mnemonic: string, path?: string, password?: string | null, wordlist?: Wordlist | null ): { mnemonic: Mnemonic; privateKey: string; publicKey: string; address: { base58: string; hex: string }; } ``` ```typescript const account = utils.accounts.generateAccountWithMnemonic( 'word1 word2 ... word12' ); ``` -------------------------------- ### Constructor Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/transaction-builder.md Initializes a new instance of the TransactionBuilder class. ```APIDOC ## Constructor ```typescript constructor(tronWeb: TronWeb) ``` ### Parameters #### Path Parameters - **tronWeb** (TronWeb) - Required - TronWeb instance **Throws:** `Error` if tronWeb is not a TronWeb instance. ``` -------------------------------- ### Get Delegated Resource Account Index V2 Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieves an index of accounts to which or from which the specified address has delegated resources, using the V2 protocol. This can be used to query confirmed data. ```typescript async getDelegatedResourceAccountIndexV2( address?: string, options?: { confirmed: boolean } ): Promise ``` -------------------------------- ### Instantiate TronWeb with Full Host and Separate Event Server Source: https://github.com/tronprotocol/tronweb/blob/master/README.md Configure TronWeb when using a single server for full and solidity nodes, but a different server for event services. Requires a private key. ```javascript const tronWeb = new TronWeb({ fullHost: 'https://api.trongrid.io', eventServer: 'https://api.someotherevent.io', privateKey: 'your private key' } ) ``` -------------------------------- ### Get Delegated Resources V2 Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Queries the resources delegated between two addresses using the V2 protocol. You can specify the delegating and receiving addresses, and optionally query for confirmed data. ```typescript async getDelegatedResourceV2( fromAddress?: string, toAddress?: string, options?: { confirmed: boolean } ): Promise ``` -------------------------------- ### Get Node Information Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieves detailed information about the Tron full node. This includes the node's version, database version, current block height, and synchronization status. ```typescript async getNodeInfo(): Promise ``` -------------------------------- ### Create a Contract Instance Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Instantiate a contract object using its ABI definition and deployed address. This allows for interaction with contract functions and events. ```typescript const contract = tronWeb.contract(abi, '0x...'); const result = await contract.balanceOf('0x...').call(); ``` -------------------------------- ### Typical Workflow: Call Read Function Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/contract.md Demonstrates how to call a read-only function on a smart contract. ```APIDOC ### Call Read Function ```typescript const balance = await contract.balanceOf(userAddress).call(); ``` ``` -------------------------------- ### Get All Transactions from Block Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieve all transactions contained within a specified block. The block can be identified by 'earliest', 'latest', a block number, or a block hash. Defaults to the `tronWeb.defaultBlock` if not specified. ```typescript async getTransactionsFromBlock( block: 'earliest' | 'latest' | number | string | false = this.tronWeb.defaultBlock ): Promise ``` -------------------------------- ### Get Events by Contract Address Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Retrieve events emitted by a specific smart contract. Supports filtering by event name, confirmation status, block number, timestamps, and pagination. ```typescript const events = await tronWeb.event.getEventsByContractAddress( 'TN3W4H6rK34me3xWQV5zCxmCtg7AixstFH', { limit: 50, eventName: 'Transfer', onlyConfirmed: true } ); if (events.success) { console.log(events.data); } ``` -------------------------------- ### Get Specific Transaction from Block by Index Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Retrieve a specific transaction from a block using its zero-based index. The block can be specified by identifier, defaulting to `tronWeb.defaultBlock`. Throws an error if the index is out of range. ```typescript async getTransactionFromBlock( block: 'earliest' | 'latest' | number | string | false = this.tronWeb.defaultBlock, index: number ): Promise ``` -------------------------------- ### Instantiate TronWeb with Separate Nodes (Retro-compatibility) Source: https://github.com/tronprotocol/tronweb/blob/master/README.md Use the older method of passing fullNode, solidityNode, eventServer, and privateKey as separate arguments. Allows setting headers separately. ```javascript const tronWeb = new TronWeb(fullNode, solidityNode, eventServer, privateKey) tronWeb.setHeader({ "TRON-PRO-API-KEY": 'your api key' }); ``` -------------------------------- ### contract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/tronweb.md Creates a typed instance of a smart contract, allowing interaction with its methods and events. ```APIDOC ## contract(abi?, address?) ### Description Create a contract instance. ### Method ```typescript contract(abi: Abi = [] as any, address?: Address): ContractInstance ``` ### Parameters #### Path Parameters - **abi** (`AbiFragment[]`) - Optional - Contract ABI definition. - **address** (`string`) - Optional - Deployed contract address. ### Returns - `ContractInstance` - Typed contract instance. ### Example ```typescript const contract = tronWeb.contract(abi, '0x...'); const result = await contract.balanceOf('0x...').call(); ``` ``` -------------------------------- ### Instantiate HttpProvider Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Create an instance of HttpProvider to connect to a TRON node. Specify the node URL, timeout, authentication credentials, and custom headers. ```typescript const provider = new HttpProvider('https://api.trongrid.io', 30000, '', '', { 'TRON-PRO-API-KEY': 'your-key' }); ``` -------------------------------- ### Delegate Resource Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/transaction-builder.md Use this method to delegate frozen balance energy or bandwidth to another account. Ensure amounts are specified in Sun (1 TRX = 1,000,000 Sun). ```typescript async delegateResource( amount: number | string, receiverAddress: string, resource: Resource = 'BANDWIDTH', from: string = this.tronWeb.defaultAddress.hex, lockTime?: number, options?: TransactionCommonOptions ): Promise> ``` -------------------------------- ### delegateResource Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/transaction-builder.md Delegates frozen balance (energy or bandwidth) to another account. Amounts are in Sun (1 TRX = 1,000,000 Sun). ```APIDOC ## delegateResource ### Description Delegate frozen balance energy/bandwidth to another account. ### Method Signature ```typescript async delegateResource( amount: number | string, receiverAddress: string, resource: Resource = 'BANDWIDTH', from: string = this.tronWeb.defaultAddress.hex, lockTime?: number, options?: TransactionCommonOptions ): Promise> ``` ### Parameters - **amount** (number | string) - Required - The amount of resource to delegate, in Sun. - **receiverAddress** (string) - Required - The address to delegate resources to. - **resource** (Resource) - Optional - The type of resource to delegate ('BANDWIDTH' or 'ENERGY'). Defaults to 'BANDWIDTH'. - **from** (string) - Optional - The address from which to delegate. Defaults to the user's default address. - **lockTime** (number) - Optional - The duration for which the resources will be locked. - **options** (TransactionCommonOptions) - Optional - Additional transaction options. ### Returns - **Promise>** - An unsigned transaction object for delegation. ``` -------------------------------- ### HttpProvider Constructor Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Instantiate the HttpProvider to connect to a TRON node. You can configure connection details like host, timeout, authentication, and custom headers. ```APIDOC ## HttpProvider Constructor ### Description Create an HTTP provider instance. ### Parameters #### Path Parameters - **host** (string) - Required - Node URL (must be valid URL) - **timeout** (number) - Optional - Request timeout in milliseconds (Default: `30000`) - **user** (string) - Optional - Basic auth username (Default: `''`) - **password** (string) - Optional - Basic auth password (Default: `''`) - **headers** (Record) - Optional - HTTP headers to include in requests (Default: `{}`) - **statusPage** (string) - Optional - Health check endpoint path (Default: `'/'`) ### Throws `Error` if host is not a valid URL, timeout is negative, or headers is not an object. ### Example ```typescript const provider = new HttpProvider('https://api.trongrid.io', 30000, '', '', { 'TRON-PRO-API-KEY': 'your-key' }); ``` ``` -------------------------------- ### Import HttpProvider Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Import the HttpProvider class from the tronweb providers module. This is the first step to using the HTTP provider. ```typescript import { providers } from 'tronweb'; const { HttpProvider } = providers; ``` -------------------------------- ### Multi-Signature Transaction Pattern Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Illustrates how to construct and sign a transaction using multiple private keys for multi-signature accounts, specifying a permission ID. ```typescript // Build transaction const tx = await tronWeb.transactionBuilder.sendTrx(to, amount, from, { permissionId: 2 // Use specific permission }); // Sign with multiple keys const signed = await tronWeb.trx.multiSign(tx, [key1, key2, key3]); // Broadcast await tronWeb.trx.sendRawTransaction(signed); ``` -------------------------------- ### Interact with TRON Smart Contracts Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Shows how to load a contract, call read-only view functions, and execute write functions that modify contract state, including setting transaction options like fee limits. ```typescript // Load contract const contract = tronWeb.contract(abi); await contract.at(contractAddress); // Call read function const result = await contract.myViewFunction(param1).call(); // Call write function const tx = await contract.myFunction(param1, param2).send({ feeLimit: 100000000 }); ``` -------------------------------- ### Local Development (TRE) Configuration Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/configuration.md Set up TronWeb for local development using the TRE (Tron Remote Environment). This configuration points to a local host and can use a development private key. ```typescript const tronWeb = new TronWeb({ fullHost: 'http://localhost:9090', privateKey: process.env.DEV_PRIVATE_KEY }); ``` -------------------------------- ### Plugin Constructor Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/providers-event-plugin.md Initializes the plugin manager for TronWeb. It allows for disabling all plugins if needed. ```APIDOC ## Constructor ```typescript constructor(tronWeb: TronWeb, options?: PluginConstructorOptions) ``` Creates a plugin manager instance. ### Parameters #### Path Parameters * **tronWeb** (`TronWeb`) - Required - The TronWeb instance to associate with the plugin manager. * **options.disablePlugins** (`boolean`) - Optional - If true, all plugins will be disabled. Defaults to false. ``` -------------------------------- ### getAccountResources Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/trx.md Fetches an account's bandwidth and energy resource usage. ```APIDOC ## getAccountResources ### Description Get account bandwidth and energy resource usage. ### Method `getAccountResources(address?) ### Parameters #### Query Parameters - **address** (string) - Optional - Account address. Defaults to the user's default address. ### Response #### Success Response - Returns an object with bandwidth, energy, and storage usage and limits. ``` -------------------------------- ### CreateSmartContractOptions Interface Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/types.md Specifies options for deploying new smart contracts. Requires ABI and bytecode, with optional parameters for constructor arguments, fees, and values. ```typescript interface CreateSmartContractOptions extends TransactionCommonOptions { feeLimit?: number; callValue?: number; tokenId?: string; tokenValue?: number; userFeePercentage?: number; originEnergyLimit?: number; abi: string | { entrys: ContractAbiInterface } | ContractAbiInterface; bytecode: string; parameters?: unknown[]; name?: string; rawParameter?: string; funcABIV2?: AbiFragment; parametersV2?: unknown[]; } ``` -------------------------------- ### createProposal Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/transaction-builder.md Creates a blockchain governance proposal. Requires proposal parameters and optionally accepts the proposer's address and transaction options. ```APIDOC ## createProposal(parameters, from?, options?) ### Description Create a blockchain governance proposal. ### Method Signature ```typescript async createProposal( parameters: any, from: string = this.tronWeb.defaultAddress.hex, options: TransactionCommonOptions = {} ): Promise> ``` ### Parameters #### Parameters - **parameters** (`object`) - Required - Proposal parameters (network property and value) - **from** (`string`) - Optional - Proposer address - **options** (`TransactionCommonOptions`) - Optional - Options ``` -------------------------------- ### createSmartContract Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/api-reference/transaction-builder.md Deploys a new smart contract to the blockchain. It takes contract ABI, bytecode, and optional deployment parameters. ```APIDOC ## createSmartContract ### Description Deploy a new smart contract to the blockchain. ### Method Signature ```typescript async createSmartContract(options: CreateSmartContractOptions, from?: string): Promise> ``` ### Parameters #### options - **abi** (string | object | AbiFragment[]) - Required - Contract ABI - **bytecode** (string) - Required - Contract bytecode (hex string) - **name** (string) - Optional - Contract name - **parameters** (unknown[]) - Optional - Constructor parameters - **rawParameter** (string) - Optional - Raw encoded parameters (hex) - **feeLimit** (number) - Optional - Max TRX to burn (Sun). Default: 150,000,000 - **callValue** (number) - Optional - TRX sent to constructor. Default: 0 - **tokenId** (string) - Optional - TRC10 token ID to send - **tokenValue** (number) - Optional - Amount of TRC10 token. Default: 0 - **userFeePercentage** (number) - Optional - User resource consumption %. Default: 100 - **originEnergyLimit** (number) - Optional - Max energy per execution - **permissionId** (number) - Optional - Permission ID for multi-sig #### from - **from** (string) - Optional - Caller address. Defaults to the default address. ### Returns Unsigned transaction with contract address. ### Example ```typescript const tx = await tronWeb.transactionBuilder.createSmartContract({ abi: contractABI, bytecode: '0x60806040...', name: 'MyContract', feeLimit: 100000000, parameters: [1000] }); const contractAddress = tx.contract_address; ``` ``` -------------------------------- ### Configure HttpProvider with Valid URL Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/errors.md Provide a valid, well-formed URL string when initializing HttpProvider or setting TronWeb nodes. Malformed URLs will trigger an error. ```typescript new HttpProvider('not-a-url'); tronWeb.setFullNode('invalid://url'); // Correct usage: new HttpProvider('https://api.trongrid.io'); ``` -------------------------------- ### TronWeb Class Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/SUMMARY.txt The main TronWeb class provides access to core SDK functionalities, including configuration, instance properties, and event handling. It serves as the entry point for most SDK operations. ```APIDOC ## TronWeb Class ### Description Provides access to core SDK functionalities, including configuration, instance properties, and event handling. Serves as the entry point for most SDK operations. ### Methods - **Constructor**: Initializes a new TronWeb instance. - **Configuration Methods**: Methods for setting up and managing SDK configuration. - **Static Utility Methods**: Utility functions available directly on the TronWeb class. - **EventEmitter Integration**: Methods for handling SDK events. ``` -------------------------------- ### Connect to Local Tron Network (TRE) Source: https://github.com/tronprotocol/tronweb/blob/master/_autodocs/README.md Instantiate TronWeb to connect to a local Tron network instance. This is typically used for development and debugging. ```typescript const local = new TronWeb({ fullHost: 'http://localhost:9090' }); ```