š tronlib - Awesome Go Library for Blockchain

A comprehensive, production-ready Go SDK for interacting with the TRON blockchain with TRC20 token support
Detailed Description of tronlib
š TronLib - Go SDK for TRON Blockchain
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.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)
}
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 := 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)
}
š Documentation
To get the most out of TronLib, follow this learning path:
š Getting Started
- Quick Start Guide - Step-by-step guide to basic operations
šļø Core Concepts
- Architecture Overview - Understanding the library structure and design patterns
š¦ Package References
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
š” Advanced Topics
- API Reference - Complete API documentation
- Complete Examples - Real-world usage examples
- Integration Tests - Comprehensive test suite
šļø 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
Signing Operations
TronLib provides flexible options for signing transactions and messages.
Manual Transaction Signing and Broadcasting
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)
Message Signing (TIP-191 v2)
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)
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://grpc.trongrid.io: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.
- Fork the repository
- Create a feature branch
- Add tests for your changes
- Ensure all tests pass
- 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
- 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.