tronlib

module
v1.0.2 Latest Latest
Warning

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

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

README ΒΆ

tronlib πŸš€

GoDoc Go Report Card

Go library for interacting with the TRON blockchain. It provides:

  • A core gRPC client with connection pooling and timeouts
  • High-level managers: account, resources, network, smartcontract, trc10, trc20

πŸ“¦ Installation

go get github.com/kslamph/tronlib

πŸš€ Quick Start

package main

import (
    "context"
    "log"
    "time"

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

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    // Replace with your TRON node URL (grpc://host:port or grpcs://host:port)
    node := "grpc://your.tron.node:port"
    cli, err := client.NewClient(node)
    if err != nil {
        log.Fatalf("new client: %v", err)
    }
    defer cli.Close()

    // Use cli with high-level managers below
}
πŸ• Context Usage
  • Pass context.Context to every call. Prefer short per-operation timeouts.
  • If your context has no deadline, the client applies its own default timeout.

πŸ“š Documentation

πŸ”„ Workflow Diagram

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚        High-level APIs       β”‚
β”‚ account / resources / networkβ”‚
β”‚ smartcontract / trc10 / trc20β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                β”‚ build txs / make queries
                β–Ό
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚ client.Client β”‚
        β”‚ RPC / simulateβ”‚
        β”‚ sign+broadcastβ”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
                β”‚
                β–Ό
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚   TRON Node   β”‚
        β”‚ (gRPC endpoint)β”‚
        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  • Transaction read: managers β†’ client β†’ node β†’ data
  • Contract read (constant): smartcontract/trc20 β†’ client (constant trigger) β†’ node β†’ ABI-decode return values
  • Transaction write: managers build tx β†’ client.SignAndBroadcast (uses signer) β†’ node β†’ receipt β†’ eventdecoder.DecodeLogs
  • Simulation: managers or client.Simulate β†’ node β†’ inspect result β†’ optionally decode logs with eventdecoder
πŸ”§ Key Components
  • types.Address πŸ“ - Unified address representation supporting multiple formats
  • signer πŸ” - Private key and HD wallet management
  • broadcaster πŸ“‘ - Broadcasting with receipt waiting (in client)
  • ABI Processor 🧬 - Encoding/decoding of ABI data
  • Event Decoder πŸ“Š - Log decoding with built-in events
  • High-level Managers πŸ› οΈ - Simplified interfaces for common operations
🎯 Usage Patterns

High-level usage (recommended for most applications):

// Using account manager for TRX transfer
am := account.NewManager(cli)
txExt, err := am.TransferTRX(ctx, from, to, 1_000_000, nil)

Low-level usage (for advanced customization):

// Direct client usage for custom transactions
tx := &core.Transaction{ /* ... */ }
signedTx, err := cli.SignTransaction(ctx, tx, signer)

πŸ’‘ Examples

πŸ‘€ Accounts and Resources
package main

import (
    "context"
    "log"
    "time"

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

func exampleAccounts(node string) {
    ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    defer cancel()

    cli, err := client.NewClient(node)
    if err != nil { log.Fatal(err) }
    defer cli.Close()

    am := account.NewManager(cli)
    rm := resources.NewManager(cli)

    from, _ := types.NewAddress("Txxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1")
    to, _ := types.NewAddress("Tyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy2")

    // Get account balance
    bal, err := am.GetBalance(ctx, from)
    if err != nil { log.Fatal(err) }
    _ = bal

    // Build a TRX transfer (unsigned)
    txExt, err := am.TransferTRX(ctx, from, to, 1_000_000, nil) // 1 TRX = 1_000_000 SUN
    if err != nil { log.Fatal(err) }

    // Sign & broadcast
    pk, _ := signer.NewPrivateKeySigner("0x<hex-privkey>")
    res, err := cli.SignAndBroadcast(ctx, txExt, client.DefaultBroadcastOptions(), pk)
    if err != nil { log.Fatal(err) }
    if !res.Success { log.Printf("broadcast failed: %s", res.Message) }

    // Freeze/Unfreeze resources
    _, _ = rm.FreezeBalanceV2(ctx, from, 1_000_000, resources.ResourceTypeEnergy)
    _, _ = rm.UnfreezeBalanceV2(ctx, from, 1_000_000, resources.ResourceTypeEnergy)
}
πŸ“œ Smart Contracts

Deploy and interact using smartcontract.Manager or a typed smartcontract.Contract.

package main

import (
    "context"
    "encoding/hex"
    "log"
    "time"

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

func exampleSmartContract(node string) {
    ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
    defer cancel()

    cli, _ := client.NewClient(node)
    defer cli.Close()

    mgr := smartcontract.NewManager(cli)
    owner, _ := types.NewAddress("Townerxxxxxxxxxxxxxxxxxxxxxxxxxx")

    abiJSON := `{"entrys":[{"type":"constructor","inputs":[{"name":"_owner","type":"address"}]},{"type":"function","name":"setValue","inputs":[{"name":"v","type":"uint256"}]},{"type":"function","name":"getValue","inputs":[],"outputs":[{"name":"","type":"uint256"}],"constant":true}]}`
    bytecode, _ := hex.DecodeString("60806040...deadbeef")

    // Deploy
    txExt, err := mgr.DeployContract(ctx, owner, "MyContract", abiJSON, bytecode, 0, 100, 30000, owner.Bytes())
    if err != nil { log.Fatal(err) }
    pk, _ := signer.NewPrivateKeySigner("0x<hex-privkey>")
    _, _ = cli.SignAndBroadcast(ctx, txExt, client.DefaultBroadcastOptions(), pk)

    // Interact via Contract
    contractAddr, _ := types.NewAddress("Tcontractxxxxxxxxxxxxxxxxxxxxxxxx")
    c, err := smartcontract.NewContract(cli, contractAddr, abiJSON)
    if err != nil { log.Fatal(err) }

    // State-changing call (build tx only)
    txExt, err = c.TriggerSmartContract(ctx, owner, 0, "setValue", uint64(42))
    if err != nil { log.Fatal(err) }

    // Sign & broadcast and wait for execution result
    opts := client.DefaultBroadcastOptions()
    opts.WaitForReceipt = true
    res, err := cli.SignAndBroadcast(ctx, txExt, opts, pk)
    if err != nil { log.Fatalf("broadcast error: %v", err) }
    log.Printf("txid=%s", res.TxID) // always available
}
πŸ’° TRC20

Read and write helpers plus exact unit conversion using shopspring/decimal.

package main

import (
    "context"
    "log"
    "time"

    "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 exampleTRC20(node string) {
    ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
    defer cancel()

    cli, _ := client.NewClient(node)
    defer cli.Close()

    token, _ := types.NewAddress("Ttokenxxxxxxxxxxxxxxxxxxxxxxxxxxx")
    holder, _ := types.NewAddress("Tholderxxxxxxxxxxxxxxxxxxxxxxxxx")
    recipient, _ := types.NewAddress("Trecipientxxxxxxxxxxxxxxxxxxxxx")

    trc20Contract, err := trc20.NewManager(cli, token)
    if err != nil { log.Fatal(err) }

    // Reads
    _, _ = trc20Contract.Name(ctx)
    _, _ = trc20Contract.Symbol(ctx)
    _, _ = trc20Contract.Decimals(ctx)
    _, _ = trc20Contract.BalanceOf(ctx, holder)

    // Write (build tx then sign & broadcast)
    amount := decimal.NewFromFloat(12.34)
    txid, txExt, err := trc20Contract.Transfer(ctx, holder, recipient, amount)
    if err != nil { log.Fatal(err) }
    log.Printf("built txid=%s", txid)
    pk, _ := signer.NewPrivateKeySigner("0x<hex-privkey>")
    opts := client.DefaultBroadcastOptions()
    opts.WaitForReceipt = true
    _, _ = cli.SignAndBroadcast(ctx, txExt, opts, pk)
}

πŸ“Š Decoding Events

See Event Decoding Guide for details and examples.

🀝 Contributing

Contributions are welcome! Please read our contributing guidelines before submitting pull requests.

πŸ“„ License

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

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
simulate command
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
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.
simulation
Package simulation contains helpers and examples for offline or preflight simulation of contract interactions.
Package simulation contains helpers and examples for offline or preflight simulation of contract interactions.
smartcontract
Package smartcontract exposes high-level helpers for deploying and interacting with TRON smart contracts.
Package smartcontract exposes high-level helpers for deploying and interacting 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