TronWeb Documentation

repository·master·Indexed 20 days ago

https://github.com/tronprotocol/tronweb

A TypeScript-based JavaScript SDK that encapsulates the TRON HTTP API. TronWeb provides a unified development library for integrating DApps in Node.js, browsers, and IoT devices, featuring tools for transaction building, smart contract interaction via read/write namespaces, and provider management using HttpProvider.

Tokens
11.8K
Snippets
31
Records
61
Agent score
69%

What's inside tronweb

  1. Set up a local private TRON network with TRE

    master

    For heavy testing and automation, you can run a local private TRON network using the TRON Runtime Environment (TRE) via Docker. Once running, the node is available at http://localhost:9090.

    docker run -it -p 9090:9090 --rm --name tron tronbox/tre:dev
  2. Use TronWeb in a browser

    master

    To use TronWeb in a browser, you can copy the dist file to your project directory and include it via a <script> tag. Alternatively, you can use NPM-based CDN mirrors (ensure you use sub-resource integrity).

    # Copy the dist file to your working folder
    cp node_modules/tronweb/dist/TronWeb.js ./js/tronweb.js
    <script src="./js/tronweb.js"></script>
  3. Use `as const` for type-safe Contract instances

    master

    To enable full TypeScript type safety and method discovery when using a contract instance, you must define your ABI using as const.

    If the ABI is not defined with as const, the TypeScript compiler widens the type to a generic AbiFragment[]. This causes the length property to become number and strips the literal types from fragment names and stateMutability. Consequently, the ContractInstance will not be able to derive specific method names from the ABI, and you will lose autocomplete and type checking for contract calls.

    Correct usage:

    const MY_ABI = [
      { name: 'transfer', type: 'function', ... },
    ] as const;
    
    // This allows ContractInstance to map 'transfer' to a specific Method type
    const contract: ContractInstance<typeof MY_ABI> = ...;
  4. Understand AccountResource and resource management

    master

    TRON accounts use resources to execute operations. The AccountResource interface tracks these metrics:

    • energy_usage: Current energy consumption.
    • frozen_balance_for_energy: The amount of TRX frozen specifically to provide energy.
    • storage_limit / storage_usage: Limits and current usage for account state storage.
    • energy_window_size: The window for energy consumption calculation.
    • delegated_frozen_balance_for_energy: Energy acquired via delegation.

    Resource types are defined by the ResourceCode enum:

    • BANDWIDTH (0x00)
    • ENERGY (0x01)
    • TRON_POWER (0x02)
  5. Core modules in TronWeb

    master

    TronWeb's public API surface is composed of several key modules that handle different aspects of interacting with the TRON blockchain. The main entry points include:

    • TronWeb: The primary class used to interact with the TRON network.
    • Contract: Used for interacting with smart contracts.
    • Transaction: Handles transaction-related data and structures.
    • TransactionBuilder: Provides methods to construct various types of transactions.
    • Providers: Manages connections to the blockchain.
    • ABI: Handles Application Binary Interface definitions for smart contracts.
    • Trx: Utilities and types specific to TRX operations.
    • APIResponse: Defines the structure of responses received from the TRON nodes.
    • Event: Handles blockchain event types.
  6. Define EIP-712 Typed Data Domain

    master

    When signing structured data, you must define a TypedDataDomain to prevent replay attacks across different chains or contracts. The domain includes metadata about the signing context.

    interface TypedDataDomain {
        name?: null | string;          // Human-readable name
        version?: null | string;       // Major version
        chainId?: null | BigNumberish; // Chain ID
        verifyingContract?: null | string; // Contract address
        salt?: null | BytesLike;       // Optional salt
    }
  7. Understand ABI fragment types

    master

    The Application Binary Interface (ABI) is composed of several types of fragments that define the interface of a smart contract. When working with contract ABIs, you will encounter these specific fragment types:

    • constructor: Defines the contract's initialization function.
    • function: Defines a contract method that can be called.
    • event: Defines an event that the contract can emit.
    • error: Defines a custom error type.
    • fallback: A special function called when no other function matches the call.
    • receive: A special function used specifically for receiving Ether/TRX.

    Each fragment contains metadata such as name, type, and stateMutability (e.g., pure, view, nonpayable, payable).

  8. Manage account permissions with Permission and PermissionKey

    master

    TRON accounts use a permission system to manage access control. You can define permissions for different roles using the Permission interface.

    Key concepts:

    • Permission_PermissionType: Defines the role type. Owner is 0, Witness is 1, and Active starts from 2.
    • PermissionKey: Associates a specific address (string) with a weight (number).
    • Permission: Defines a group of keys that must meet a certain threshold to authorize operations. It includes a permission_name and optional operations strings.
    export interface PermissionKey {
        address: string;
        weight: number;
    }
    
    export interface Permission {
        type: number;
        /** Owner id=0, Witness id=1, Active id start by 2 */
        id?: number;
        permission_name: string;
        threshold: number;
        operations?: string;
        keys: PermissionKey[];
    }
    
    export enum Permission_PermissionType {
        Owner = 0,
        Witness = 1,
        Active = 2,
        UNRECOGNIZED = -1,
    }
  9. Understand the Transaction and SignedTransaction interfaces

    master

    TronWeb uses several interfaces to represent transactions at different stages of their lifecycle:

    1. Transaction: The base structure representing an unsigned transaction. It includes txID, raw_data (containing the contract, block references, expiration, and timestamp), and raw_data_hex.
    2. SignedTransaction: An extension of Transaction that includes a signature (an array of strings) and an optional contract_address. This represents a transaction that has been cryptographically signed and is ready for broadcasting.
    3. CreateSmartContractTransaction: A specialized Transaction used specifically for deploying new smart contracts, which includes the contract_address of the contract being created.
  10. Understand Transaction response structures

    master

    TRON API responses for transactions follow specific shapes that extend base transaction types:

    • GetTransactionResponse: An extension of SignedTransaction that includes a visible boolean flag and a ret array. The ret array contains objects with a contractRet string, which indicates the execution result of the transaction contract.
    • GetSignWeightResponse: Returned when checking signature weights. It includes the permission (as APIReturnedPermission), a result object containing a code string, and the transaction as a TransactionWrapper.