tronlib

module
v1.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 30, 2025 License: MIT

README ΒΆ

πŸ”— TronLib - Go SDK for TRON Blockchain

Go Reference Go Report Card

A comprehensive, production-ready Go SDK for interacting with the TRON blockchain. TronLib provides high-level abstractions for common operations while maintaining flexibility for advanced use cases.

✨ Features

  • πŸš€ Simple & Intuitive - High-level APIs that make blockchain interaction straightforward
  • πŸ” Secure - Built-in support for private keys and HD wallets
  • πŸ’° TRC20 Ready - First-class support for TRC20 tokens with decimal conversion
  • πŸ“¦ Smart Contracts - Deploy and interact with smart contracts effortlessly
  • 🎯 Event Decoding - Decode transaction logs with built-in TRC20 event support
  • ⚑ Performance - Connection pooling and efficient gRPC communication
  • πŸ” Simulation - Test transactions before broadcasting to the network
  • πŸ“Š Resource Management - Handle bandwidth and energy efficiently

🏁 Quick Start

Installation
go get github.com/kslamph/tronlib
Simple TRX Transfer
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/kslamph/tronlib/pkg/client"
    "github.com/kslamph/tronlib/pkg/signer"
    "github.com/kslamph/tronlib/pkg/types"
)

func main() {
    // Connect to TRON node
    cli, err := client.NewClient("grpc://grpc.nile.trongrid.io:50051")
    if err != nil {
        log.Fatal(err)
    }
    defer cli.Close()

    // Create signer from private key
    signer, err := signer.NewPrivateKeySigner("your-private-key-hex")
    if err != nil {
        log.Fatal(err)
    }

    // Define addresses
    from := signer.Address()
    to, _ := types.NewAddress("TBkfmcE7pM8cwxEhATtkMFwAf1FeQcwY9x")

    // Transfer 1 TRX (1,000,000 SUN)
    tx, err := cli.Accounts().TransferTRX(context.Background(), from, to, 1_000_000)
    if err != nil {
        log.Fatal(err)
    }

    // Sign and broadcast
    result, err := cli.SignAndBroadcast(context.Background(), tx, client.DefaultBroadcastOptions(), signer)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Transaction ID: %s\n", result.TxID)
    fmt.Printf("Success: %v\n", result.Success)
}
TRC20 Token Transfer
package main

import (
    "context"
    "log"

    "github.com/shopspring/decimal"
    "github.com/kslamph/tronlib/pkg/client"
    "github.com/kslamph/tronlib/pkg/signer"
    "github.com/kslamph/tronlib/pkg/trc20"
    "github.com/kslamph/tronlib/pkg/types"
)

func main() {
    cli, _ := client.NewClient("grpc://grpc.nile.trongrid.io:50051")
    defer cli.Close()

    signer, _ := signer.NewPrivateKeySigner("your-private-key-hex")
    
    // USDT contract address on mainnet
    token, _ := types.NewAddress("TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t")
    to, _ := types.NewAddress("TBkfmcE7pM8cwxEhATtkMFwAf1FeQcwY9x")

    // Create TRC20 manager
    trc20Mgr, err := trc20.NewManager(cli, token)
    if err != nil {
        log.Fatal(err)
    }

    // Transfer 10 USDT
    amount := decimal.NewFromInt(10)
    _, tx, err := trc20Mgr.Transfer(context.Background(), signer.Address(), to, amount)
    if err != nil {
        log.Fatal(err)
    }

    // Sign and broadcast
    result, err := cli.SignAndBroadcast(context.Background(), tx, client.DefaultBroadcastOptions(), signer)
    if err != nil {
        log.Fatal(err)
    }

    log.Printf("TRC20 transfer completed: %s", result.TxID)
}

πŸ“š Documentation

Core Concepts
Package Documentation
  • Types - Address handling and fundamental types
  • Client - gRPC client and connection management
  • TRC20 - TRC20 token operations and decimal handling
  • Smart Contracts - Contract deployment and interaction
  • Event Decoder - Transaction log decoding
  • Utils - ABI encoding/decoding utilities
  • Signer - Key management and transaction signing
Examples

πŸ—οΈ Project Structure

tronlib/
β”œβ”€β”€ πŸ“ pkg/                    # Core library packages
β”‚   β”œβ”€β”€ πŸ“ client/            # gRPC client and connection management
β”‚   β”œβ”€β”€ πŸ“ types/             # Fundamental types (Address, constants)
β”‚   β”œβ”€β”€ πŸ“ signer/            # Private key and HD wallet management
β”‚   β”œβ”€β”€ πŸ“ account/           # Account operations (balance, TRX transfers)
β”‚   β”œβ”€β”€ πŸ“ trc20/             # TRC20 token operations
β”‚   β”œβ”€β”€ πŸ“ smartcontract/     # Smart contract deployment and interaction
β”‚   β”œβ”€β”€ πŸ“ eventdecoder/      # Event log decoding
β”‚   β”œβ”€β”€ πŸ“ utils/             # ABI encoding/decoding utilities
β”‚   β”œβ”€β”€ πŸ“ resources/         # Resource management (bandwidth, energy)
β”‚   β”œβ”€β”€ πŸ“ voting/            # Voting operations
β”‚   └── πŸ“ network/           # Network operations
β”œβ”€β”€ πŸ“ example/               # Usage examples
β”œβ”€β”€ πŸ“ cmd/                   # Command-line tools
β”œβ”€β”€ πŸ“ integration_test/      # Integration tests
└── πŸ“ docs/                  # Documentation

πŸš€ Advanced Usage

Transaction Simulation

Test transactions before broadcasting:

// Simulate before sending
simResult, err := cli.Simulate(context.Background(), tx)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Energy needed: %d\n", simResult.EnergyUsage)
fmt.Printf("Would succeed: %v\n", simResult.Success)

// Only broadcast if simulation succeeds
if simResult.Success {
    result, err := cli.SignAndBroadcast(context.Background(), tx, opts, signer)
    // ...
}
Smart Contract Interaction
// Create contract instance
contract, err := smartcontract.NewInstance(cli, contractAddr, abiJSON)
if err != nil {
    log.Fatal(err)
}

// Call contract method
tx, err := contract.Invoke(ctx, signer.Address(), 0, "setValue", uint64(42))
if err != nil {
    log.Fatal(err)
}

// Sign and broadcast
result, err := cli.SignAndBroadcast(ctx, tx, opts, signer)
Event Decoding
// Decode transaction logs
for _, log := range result.Logs {
    event, err := eventdecoder.DecodeLog(log.GetTopics(), log.GetData())
    if err != nil {
        continue
    }
    
    fmt.Printf("Event: %s\n", event.EventName)
    for _, param := range event.Parameters {
        fmt.Printf("  %s: %v\n", param.Name, param.Value)
    }
}

πŸ”§ Configuration

Client Options
cli, err := client.NewClient("grpc://127.0.0.1:50051",
    client.WithTimeout(30*time.Second),     // Default timeout
    client.WithPool(5, 10),                 // Connection pool: 5 initial, 10 max
)
Broadcast Options
opts := client.DefaultBroadcastOptions()
opts.FeeLimit = 100_000_000                // Set fee limit in SUN
opts.WaitForReceipt = true                 // Wait for transaction receipt
opts.WaitTimeout = 20 * time.Second       // Timeout for receipt
opts.PollInterval = 500 * time.Millisecond // Polling interval

🌐 Network Support

  • Mainnet: grpc://grpc.trongrid.io:50051
  • Nile Testnet: grpc://grpc.nile.trongrid.io:50051
  • Local Node: grpc://127.0.0.1:50051

πŸ’‘ Tip: Use testnet for development and testing. Get test TRX from the Nile Testnet Faucet.

🀝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for your changes
  4. Ensure all tests pass
  5. Submit a pull request

πŸ“œ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Built on the foundation of TRON's gRPC API
  • Inspired by Ethereum's web3 libraries
  • Uses Google Protocol Buffers for efficient communication

Made with ❀️ for the TRON community

For questions, issues, or feature requests, please open an issue on GitHub.

Directories ΒΆ

Path Synopsis
cmd
event_abi_generator command
Command event_abi_generator parses contract ABIs and produces compact event signature maps used by pkg/eventdecoder.
Command event_abi_generator parses contract ABIs and produces compact event signature maps used by pkg/eventdecoder.
event_abi_loader command
Command event_abi_loader demonstrates loading ABI JSON and registering its events into the global eventdecoder registry.
Command event_abi_loader demonstrates loading ABI JSON and registering its events into the global eventdecoder registry.
generate_event_builtins command
Command generate_event_builtins compiles a curated corpus of ABIs into a builtin signature table included in pkg/eventdecoder.
Command generate_event_builtins compiles a curated corpus of ABIs into a builtin signature table included in pkg/eventdecoder.
setup_nile_testnet command
Command setup_nile_testnet provides helpers to scaffold local credentials and environment for TRON Nile testnet interactions.
Command setup_nile_testnet provides helpers to scaffold local credentials and environment for TRON Nile testnet interactions.
example
eventdecoder_simple command
This snippet is from docs/eventdecoder.md Simple Event Decoding
This snippet is from docs/eventdecoder.md Simple Event Decoding
quickstart_transaction_simulation command
This is a more advanced example of transaction simulation.
This is a more advanced example of transaction simulation.
quickstart_trc20_transfer command
This snippet is from docs/quickstart.md TRC20 Token Transfer
This snippet is from docs/quickstart.md TRC20 Token Transfer
quickstart_trx_transfer command
This snippet is from docs/quickstart.md Your First TRX Transfer
This snippet is from docs/quickstart.md Your First TRX Transfer
quickstart_trx_transfer_from_example command
This snippet is from example/transfer/main.go
This snippet is from example/transfer/main.go
readme_trc20_transfer command
This snippet is from README.md TRC20 Token Transfer
This snippet is from README.md TRC20 Token Transfer
readme_trx_transfer command
This snippet is from README.md Simple TRX Transfer
This snippet is from README.md Simple TRX Transfer
shielded command
shielded/backup command
simulate command
transfer command
trc20_allowance command
This snippet demonstrates TRC20 allowance checking Check how much a spender is allowed to spend on behalf of an owner
This snippet demonstrates TRC20 allowance checking Check how much a spender is allowed to spend on behalf of an owner
trc20_balance_checking command
This snippet demonstrates TRC20 balance checking Check the token balance of a specific address
This snippet demonstrates TRC20 balance checking Check the token balance of a specific address
trc20_basic_setup command
This snippet is from docs/trc20.md Basic Setup
This snippet is from docs/trc20.md Basic Setup
trc20_token_metadata command
This snippet demonstrates TRC20 token metadata retrieval Get token name, symbol, and decimals information
This snippet demonstrates TRC20 token metadata retrieval Get token name, symbol, and decimals information
trc20_total_supply command
This snippet demonstrates TRC20 total supply checking Get the total supply of tokens for a TRC20 contract
This snippet demonstrates TRC20 total supply checking Get the total supply of tokens for a TRC20 contract
trc20_transfer_with_signing command
This snippet is from docs/trc20.md Transfer with Signing and Broadcasting
This snippet is from docs/trc20.md Transfer with Signing and Broadcasting
types_address_conversion command
This snippet is from docs/types.md Address Conversion
This snippet is from docs/types.md Address Conversion
types_creating_addresses command
This snippet is from docs/types.md Creating Addresses
This snippet is from docs/types.md Creating Addresses
pb
api
pkg
account
Package account provides high-level helpers to query and mutate TRON accounts, such as retrieving balances, resources, and building TRX transfers.
Package account provides high-level helpers to query and mutate TRON accounts, such as retrieving balances, resources, and building TRX transfers.
client
Package client provides high-level client functionality.
Package client provides high-level client functionality.
client/lowlevel
This package contains raw gRPC calls with minimal business logic
This package contains raw gRPC calls with minimal business logic
eventdecoder
Package eventdecoder maintains a compact registry of event signatures and helpers to decode logs into typed values using minimal ABI fragments.
Package eventdecoder maintains a compact registry of event signatures and helpers to decode logs into typed values using minimal ABI fragments.
network
Package network exposes simple accessors for network-level information such as chain parameters and node metadata.
Package network exposes simple accessors for network-level information such as chain parameters and node metadata.
resources
Package resources manages TRON resource economics, including bandwidth and energy queries and operations.
Package resources manages TRON resource economics, including bandwidth and energy queries and operations.
signer
Package signer contains key management and transaction signing utilities, including HD wallet derivation and raw private key signing.
Package signer contains key management and transaction signing utilities, including HD wallet derivation and raw private key signing.
smartcontract
Package smartcontract provides high-level helpers to deploy, query, and interact with TRON smart contracts.
Package smartcontract provides high-level helpers to deploy, query, and interact with TRON smart contracts.
trc10
Package trc10 offers helpers to query TRC10 token metadata and balances.
Package trc10 offers helpers to query TRC10 token metadata and balances.
trc20
Package trc20 provides a typed, ergonomic interface for TRC20 tokens.
Package trc20 provides a typed, ergonomic interface for TRC20 tokens.
types
Package types provides shared types and utilities for the TRON SDK
Package types provides shared types and utilities for the TRON SDK
utils
Package utils houses ABI encode/decode logic, type parsing, and common helpers shared by higher-level packages.
Package utils houses ABI encode/decode logic, type parsing, and common helpers shared by higher-level packages.
voting
Package voting provides a high-level manager for witness voting and related governance operations.
Package voting provides a high-level manager for witness voting and related governance operations.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL