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.
- π 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
go get github.com/kslamph/tronlibpackage 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.Account().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)
}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 := cli.TRC20(token)
if trc20Mgr == nil {
log.Fatal("Failed to create TRC20 manager")
}
// 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)
}To get the most out of TronLib, follow this learning path:
- Quick Start Guide - Step-by-step guide to basic operations
- Architecture Overview - Understanding the library structure and design patterns
Detailed documentation for each package:
- Types - Address handling and fundamental types
- TRC20 - TRC20 token operations and decimal handling
- Smart Contracts - Contract deployment and interaction
- Event Decoder - Transaction log decoding
- Utils - ABI encoding/decoding utilities
- API Reference - Complete API documentation
- Complete Examples - Real-world usage examples
- Integration Tests - Comprehensive test suite
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
TronLib provides flexible options for signing transactions and messages.
If you prefer to sign transactions manually before broadcasting, or need to integrate with external signers (e.g., hardware wallets, cloud KMS), you can use the signer.SignTx function.
// Example for manual signing and broadcasting:
// 1. Create the transaction
// tx, err := cli.Account().TransferTRX(...)
// if err != nil {
// log.Fatal(err)
// }
//
// 2. Sign the transaction using SignTx
// err = signer.SignTx(yourSigner, tx) // 'yourSigner' is an instance of signer.Signer
// if err != nil {
// log.Fatal(err)
// }
//
// 3. Broadcast the signed transaction
// result, err := cli.Broadcast(context.Background(), tx)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Transaction ID: %s\n", result.TxID)To sign arbitrary messages following the TRON Improvement Proposal 191 (TIP-191) v2 format, use the standalone signer.SignMessageV2 function.
// Sign an arbitrary message using the standalone SignMessageV2 function
// privateKey := "your-private-key-hex"
// pkSigner, err := signer.NewPrivateKeySigner(privateKey)
// if err != nil {
// log.Fatal(err)
// }
//
// message := "Hello TronLib!"
// signature, err := signer.SignMessageV2(pkSigner, message)
// if err != nil {
// log.Fatal(err)
// }
// fmt.Printf("Signed Message: %s\n", signature)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)
// ...
}// 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)// 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)
}
}cli, err := client.NewClient("grpc://grpc.trongrid.io:50051",
client.WithTimeout(30*time.Second), // Default timeout
client.WithPool(5, 10), // Connection pool: 5 initial, 10 max
)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- 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.
We welcome contributions! Please see our Contributing Guidelines for details.
- Fork the repository
- Create a feature branch
- Add tests for your changes
- Ensure all tests pass
- Submit a pull request
This project is licensed under the MIT License - see the LICENSE file for details.
- Built on the foundation of TRON's gRPC API
- 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.