gotron

package module
v0.0.0-...-7beb898 Latest Latest
Warning

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

Go to latest
Published: Dec 17, 2025 License: MIT Imports: 1 Imported by: 0

README

Gotron SDK

A comprehensive Go SDK for the Tron blockchain. This library provides a complete client implementation for interacting with Tron nodes via gRPC, managing addresses, creating and signing transactions, and working with TRC20 tokens.

Features

  • Complete gRPC Client - Full implementation of Tron Wallet API
  • Address Management - BIP39/BIP44 mnemonic support, address generation and validation
  • Transaction Handling - Create, sign, and broadcast transactions
  • TRC20 Token Support - Transfer, approve, balance queries, token info
  • Resource Management - Delegate/undelegate bandwidth and energy
  • Account Operations - Balance queries, account info, activation
  • Block & Transaction Queries - Get blocks, transactions, and receipts
  • Multi-Network Support - Mainnet, Shasta testnet, Nile testnet
  • Precision Arithmetic - Uses decimal.Decimal for accurate calculations
  • Type Safety - Full type definitions with validation
  • Native Implementation - Built on official Tron protocol buffers

Installation

go get github.com/sxwebdev/gotron

Quick Start

Initialize Client
package main

import (
  "context"
  "fmt"
  "log"

  "github.com/sxwebdev/gotron"
)

func main() {
  // Create client with default mainnet configuration
  cfg := gotron.Config{
    GRPCAddress: "your-custom-node-grpc-address:50051",
  }

  tron, err := gotron.New(cfg)
  if err != nil {
    log.Fatal(err)
  }
  defer tron.Close()

  ctx := context.Background()

  // Get account balance (in TRX)
  balance, err := tron.GetAccountBalance(ctx, "TYourAddress")
  if err != nil {
    log.Fatal(err)
  }
  fmt.Printf("Balance: %s TRX\n", balance.String())
}
Generate Addresses
import "github.com/sxwebdev/gotron/pkg/address"

// Generate a new 12-word mnemonic
mnemonic, err := address.GenerateMnemonic(128)
if err != nil {
  log.Fatal(err)
}

// Derive address from mnemonic (BIP44 path: m/44'/195'/0'/0/0)
addr, err := address.FromMnemonic(mnemonic, "", 0)
if err != nil {
  log.Fatal(err)
}

fmt.Printf("Address: %s\n", addr.Address)
fmt.Printf("Private Key: %s\n", addr.PrivateKey)
fmt.Printf("Mnemonic: %s\n", addr.Mnemonic)

// Generate random address
randomAddr, err := address.Generate()
if err != nil {
  log.Fatal(err)
}

// Import from private key
importedAddr, err := address.FromPrivateKey("your-hex-private-key")
if err != nil {
  log.Fatal(err)
}
Transfer TRX
import (
  "context"
  "github.com/shopspring/decimal"
  "github.com/sxwebdev/gotron/pkg/address"
)

ctx := context.Background()

// Create transfer transaction (amount in TRX)
tx, err := tron.CreateTransferTransaction(
  ctx,
  "TFromAddress",
  "TToAddress",
  decimal.NewFromFloat(1.5), // 1.5 TRX
)
if err != nil {
  log.Fatal(err)
}

// Import private key
privateKey, err := address.PrivateKeyFromHex("your-hex-private-key")
if err != nil {
  log.Fatal(err)
}

// Sign transaction
err = tron.SignTransaction(tx.Transaction, privateKey)
if err != nil {
  log.Fatal(err)
}

// Broadcast transaction
result, err := tron.BroadcastTransaction(ctx, tx.Transaction)
if err != nil {
  log.Fatal(err)
}

fmt.Printf("Transaction broadcasted: %s\n", result.Message)
TRC20 Token Operations
const (
  usdtContract = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t" // USDT on Tron
)

ctx := context.Background()

// Get token info
name, _ := tron.TRC20GetName(ctx, usdtContract)
symbol, _ := tron.TRC20GetSymbol(ctx, usdtContract)
decimals, _ := tron.TRC20GetDecimals(ctx, usdtContract)

fmt.Printf("Token: %s (%s), Decimals: %d\n", name, symbol, decimals)

// Get token balance
balance, err := tron.TRC20ContractBalance(ctx, "TYourAddress", usdtContract)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Balance: %s\n", balance.String())

// Transfer tokens (amount in smallest unit, 1 USDT = 1000000)
tx, err := tron.TRC20Send(
  ctx,
  "TFromAddress",
  "TToAddress",
  usdtContract,
  decimal.NewFromInt(1000000), // 1 USDT
  100_000_000, // Fee limit in SUN (100 TRX)
)
if err != nil {
    log.Fatal(err)
}

// Sign and broadcast...
privateKey, _ := address.PrivateKeyFromHex("your-private-key")
tron.SignTransaction(tx.Transaction, privateKey)
result, _ := tron.BroadcastTransaction(ctx, tx.Transaction)
Delegate & Reclaim Resources
import "github.com/sxwebdev/gotron"

ctx := context.Background()

// Delegate 1000 TRX worth of energy to another address
tx, err := tron.DelegateResource(
  ctx,
  "TOwnerAddress",
  "TReceiverAddress",
  gotron.Energy,              // Resource type
  1000_000_000,               // Balance in SUN (1000 TRX)
  false,                      // Lock
  0,                          // Lock period
)
if err != nil {
    log.Fatal(err)
}

// Sign and broadcast...

// Reclaim delegated resources
reclaimTx, err := tron.ReclaimResource(
  ctx,
  "TOwnerAddress",
  "TReceiverAddress",
  gotron.Energy,
  1000_000_000, // Amount in SUN
)
Query Blocks and Transactions
ctx := context.Background()

// Get latest block
block, err := tron.GetLastBlock(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Latest block: %d\n", block.BlockHeader.RawData.Number)

// Get block by height
specificBlock, err := tron.GetBlockByHeight(ctx, 12345678)

// Get transaction by hash
tx, err := tron.GetTransactionByHash(ctx, "transaction-hash")

// Get transaction receipt
receipt, err := tron.GetTransactionInfoByHash(ctx, "transaction-hash")
fmt.Printf("Result: %s\n", receipt.Result)
Account Operations
ctx := context.Background()

// Check if account is activated
isActivated, err := tron.IsAccountActivated(ctx, "TAddress")

// Estimate activation cost
estimate, err := tron.EstimateActivateAccount(ctx, "TFromAddress", "TToAddress")
fmt.Printf("Activation cost: %s TRX\n", estimate.Trx.String())

// Get account resources
resources, err := tron.TotalAvailableResources(ctx, "TAddress")
fmt.Printf("Energy: %s, Bandwidth: %s\n",
  resources.Energy.String(),
  resources.Bandwidth.String(),
)

Network Configuration

Predefined Networks
// Mainnet (default)
cfg := gotron.Config{
    Network: gotron.Mainnet,
}

// Shasta Testnet
cfg := gotron.Config{
    Network: gotron.Shasta,
}

// Nile Testnet
cfg := gotron.Config{
    Network: gotron.Nile,
}
Custom Configuration
import (
    "github.com/sxwebdev/gotron/pkg/client"
    "google.golang.org/grpc"
)

cfg := client.Config{
  GRPCAddress: "your-custom-node:50051",
  UseTLS:      true,
  DialOptions: []grpc.DialOption{
      // Add custom dial options here
  },
}

tron, err := gotron.New(cfg)
TronGrid with API Key (Interceptor Pattern)

For production use with TronGrid, implement an interceptor to add the API key header:

import (
    "context"

    "github.com/sxwebdev/gotron/pkg/client"
    "google.golang.org/grpc"
    "google.golang.org/grpc/metadata"
)

// Create interceptor that adds TRON-PRO-API-KEY header
func tronGridAPIKeyInterceptor(apiKey string) grpc.UnaryClientInterceptor {
  return func(
    ctx context.Context,
    method string,
    req, reply any,
    cc *grpc.ClientConn,
    invoker grpc.UnaryInvoker,
    opts ...grpc.CallOption,
  ) error {
    ctx = metadata.AppendToOutgoingContext(ctx, "TRON-PRO-API-KEY", apiKey)
    return invoker(ctx, method, req, reply, cc, opts...)
  }
}

func main() {
  apiKey := "your-trongrid-api-key"

  cfg := client.Config{
    Network: client.NetworkMainnet,
    Address: "grpc.trongrid.io:50051",
    DialOptions: []grpc.DialOption{
        grpc.WithUnaryInterceptor(tronGridAPIKeyInterceptor(apiKey)),
    },
  }

  tron, err := gotron.New(cfg)
  if err != nil {
    log.Fatal(err)
  }
  defer tron.Close()

  // All requests will include the API key header
  balance, err := tron.GetAccountBalance(ctx, "TAddress")
}

Package Structure

gotron/
├── tron.go              # High-level wrapper and constants
├── pkg/
│   ├── address/         # Address generation, validation, BIP39/BIP44
│   ├── client/          # Core gRPC client implementation
│   │   ├── client.go    # Client initialization
│   │   ├── account.go   # Account operations
│   │   ├── transfer.go  # TRX transfers
│   │   ├── trc20.go     # TRC20 token operations
│   │   ├── resources.go # Resource delegation
│   │   ├── block.go     # Block queries
│   │   ├── transactions.go # Transaction operations
│   │   └── ...
│   └── utils/           # Utility functions
└── schema/pb/           # Protocol buffer definitions
    ├── api/             # Tron API definitions
    └── core/            # Core protocol types

Constants

// Networks
gotron.Mainnet
gotron.Shasta
gotron.Nile

// Resource Types
gotron.Bandwidth
gotron.Energy

// Decimals
gotron.TrxDecimals = 6

// Event Signatures
gotron.Trc20TransferEventSignature

Error Handling

The library provides typed errors for common scenarios:

import "github.com/sxwebdev/gotron/pkg/client"

_, err := tron.GetAccount(ctx, "invalid-address")
if errors.Is(err, client.ErrAccountNotFound) {
  fmt.Println("Account not found")
}

// Other errors:
// - client.ErrInvalidAddress
// - client.ErrInvalidAmount
// - client.ErrInvalidConfig
// - client.ErrTransactionNotFound
// - client.ErrInvalidResourceType

Advanced Usage

Address Generator with Custom Derivation
import "github.com/sxwebdev/gotron/pkg/address"

// Create address generator
generator := address.NewAddressGenerator(mnemonic, "passphrase")

// Customize BIP44 path
generator.
  SetBipPurpose(44).
  SetCoinType(195).
  SetAccount(0)

// Generate multiple addresses
for i := uint32(0); i < 10; i++ {
  addr, err := generator.Generate(i)
  if err != nil {
      log.Fatal(err)
  }
  fmt.Printf("Address %d: %s\n", i, addr.Address)
}
Direct API Access
// Access underlying gRPC client for advanced operations
walletAPI := tron.API()

// Use any Wallet API method directly
nodeInfo, err := walletAPI.GetNodeInfo(ctx, &api.EmptyMessage{})

Testing

go test ./...

License

MIT License - see LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit issues and pull requests.

Resources

Documentation

Overview

Package gotron provides a comprehensive SDK for interacting with the Tron blockchain.

This package offers a complete implementation of Tron's gRPC API with a clean, idiomatic Go interface. It handles address generation, transaction creation and signing, TRC20 token operations, resource management, and blockchain queries.

Features

  • Full gRPC client for Tron Wallet API
  • BIP39/BIP44 mnemonic and address generation
  • Transaction creation, signing, and broadcasting
  • TRC20 token support (transfer, balance, metadata)
  • Resource delegation (bandwidth and energy)
  • Account operations and activation
  • Block and transaction queries
  • Multi-network support (Mainnet, Shasta, Nile)
  • Type-safe operations with validation

Quick Start

Create a client and query an account balance:

import (
    "context"
    "fmt"
    "log"

    "github.com/sxwebdev/gotron"
)

func main() {
    cfg := gotron.Config{
        Network: gotron.Mainnet,
    }

    tron, err := gotron.New(cfg)
    if err != nil {
        log.Fatal(err)
    }
    defer tron.Close()

    ctx := context.Background()
    balance, err := tron.GetAccountBalance(ctx, "TYourAddress")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Balance: %s TRX\n", balance.String())
}

Using TronGrid with API Key

TronGrid requires an API key via the TRON-PRO-API-KEY header. Use a gRPC interceptor to add it:

import (
    "context"

    "github.com/sxwebdev/gotron/pkg/client"
    "google.golang.org/grpc"
    "google.golang.org/grpc/metadata"
)

func apiKeyInterceptor(apiKey string) grpc.UnaryClientInterceptor {
    return func(ctx context.Context, method string, req, reply interface{},
        cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {

        ctx = metadata.AppendToOutgoingContext(ctx, "TRON-PRO-API-KEY", apiKey)
        return invoker(ctx, method, req, reply, cc, opts...)
    }
}

func main() {
    cfg := client.Config{
        Network: client.NetworkMainnet,
        DialOptions: []grpc.DialOption{
            grpc.WithUnaryInterceptor(apiKeyInterceptor("your-api-key")),
        },
    }

    tron, err := gotron.New(cfg)
    // Use client...
}

Address Generation

Generate addresses from mnemonic phrases using BIP39/BIP44:

import "github.com/sxwebdev/gotron/pkg/address"

// Generate a new 12-word mnemonic
mnemonic, err := address.GenerateMnemonic(128)
if err != nil {
    log.Fatal(err)
}

// Derive address at index 0 (m/44'/195'/0'/0/0)
addr, err := address.FromMnemonic(mnemonic, "", 0)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Address: %s\n", addr.Address)
fmt.Printf("Private Key: %s\n", addr.PrivateKey)

Transactions

Create and broadcast a TRX transfer:

import (
    "github.com/shopspring/decimal"
    "github.com/sxwebdev/gotron/pkg/address"
)

ctx := context.Background()

// Create transaction (amount in TRX)
tx, err := tron.CreateTransferTransaction(
    ctx,
    "TFromAddress",
    "TToAddress",
    decimal.NewFromFloat(1.5), // 1.5 TRX
)
if err != nil {
    log.Fatal(err)
}

// Sign with private key
privateKey, _ := address.PrivateKeyFromHex("your-hex-private-key")
err = tron.SignTransaction(tx.Transaction, privateKey)
if err != nil {
    log.Fatal(err)
}

// Broadcast to network
result, err := tron.BroadcastTransaction(ctx, tx.Transaction)
if err != nil {
    log.Fatal(err)
}

TRC20 Tokens

Work with TRC20 tokens:

const usdtContract = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"

// Get token info
name, _ := tron.TRC20GetName(ctx, usdtContract)
symbol, _ := tron.TRC20GetSymbol(ctx, usdtContract)
decimals, _ := tron.TRC20GetDecimals(ctx, usdtContract)

// Get balance
balance, err := tron.TRC20ContractBalance(ctx, "TAddress", usdtContract)

// Transfer tokens
tx, err := tron.TRC20Send(
    ctx,
    "TFromAddress",
    "TToAddress",
    usdtContract,
    decimal.NewFromInt(1000000), // Amount in smallest unit
    100_000_000,                  // Fee limit in SUN
)

Resource Management

Delegate and reclaim resources:

// Delegate energy
tx, err := tron.DelegateResource(
    ctx,
    "TOwnerAddress",
    "TReceiverAddress",
    gotron.Energy,
    1000_000_000, // 1000 TRX in SUN
    false,         // lock
    0,             // lock period
)

// Reclaim resources
tx, err = tron.ReclaimResource(
    ctx,
    "TOwnerAddress",
    "TReceiverAddress",
    gotron.Energy,
    1000_000_000,
)

Network Configuration

The package supports multiple networks:

// Mainnet
cfg := gotron.Config{Network: gotron.Mainnet}

// Shasta Testnet
cfg := gotron.Config{Network: gotron.Shasta}

// Nile Testnet
cfg := gotron.Config{Network: gotron.Nile}

// Custom node
cfg := client.Config{
    GRPCAddress: "custom-node:50051",
    UseTLS:      true,
    Network:     client.NetworkMainnet,
}

Package Organization

The SDK is organized into several packages:

  • gotron: High-level wrapper and convenience functions
  • pkg/client: Core gRPC client with all blockchain operations
  • pkg/address: Address generation, validation, and key management
  • pkg/utils: Utility functions for encoding, formatting, etc.
  • schema/pb: Protocol buffer definitions from Tron protocol

Error Handling

The package provides typed errors for common scenarios:

import "github.com/sxwebdev/gotron/pkg/client"

_, err := tron.GetAccount(ctx, "address")
if errors.Is(err, client.ErrAccountNotFound) {
    // Handle account not found
}

Common errors:

  • client.ErrAccountNotFound
  • client.ErrInvalidAddress
  • client.ErrInvalidAmount
  • client.ErrTransactionNotFound
  • client.ErrInvalidConfig

Advanced Usage

For advanced use cases, access the underlying gRPC client directly:

// Get the raw Wallet API client
walletAPI := tron.API()

// Use any Wallet API method
nodeInfo, err := walletAPI.GetNodeInfo(ctx, &api.EmptyMessage{})

Generate multiple addresses from a single mnemonic:

generator := address.NewAddressGenerator(mnemonic, "")
for i := uint32(0); i < 10; i++ {
    addr, err := generator.Generate(i)
    // Use addr...
}

Documentation

For detailed API documentation, visit https://pkg.go.dev/github.com/sxwebdev/gotron

Index

Constants

View Source
const (
	// Mainnet is the Tron mainnet
	Mainnet = client.NetworkMainnet
	// Shasta is the Tron Shasta testnet (grpc.shasta.trongrid.io:50051)
	Shasta = client.NetworkShasta
	// Nile is the Tron Nile testnet (grpc.nile.trongrid.io:50051)
	Nile = client.NetworkNile
)

Network types for Tron blockchain

View Source
const (
	// Bandwidth represents bandwidth resource type
	Bandwidth = client.ResourceTypeBandwidth
	// Energy represents energy resource type
	Energy = client.ResourceTypeEnergy
)

Resource types for delegation operations

View Source
const (
	// TrxDecimals is the number of decimals for TRX (1 TRX = 1,000,000 SUN)
	TrxDecimals = client.TrxDecimals
	// Trc20TransferEventSignature is the event signature for TRC20 transfers
	Trc20TransferEventSignature = client.Trc20TransferEventSignature
)

Blockchain constants

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config = client.Config

Config is an alias for client.Config for convenience

type Tron

type Tron struct {
	*client.Client
}

Tron is the high-level Tron blockchain client. It wraps the underlying gRPC client and provides convenient methods for common blockchain operations.

func New

func New(cfg Config) (*Tron, error)

New creates a new Tron client with the specified configuration.

Example:

cfg := gotron.Config{
    GRPCAddress: "your-custom-node-grpc-address:50051",
}
tron, err := gotron.New(cfg)
if err != nil {
    log.Fatal(err)
}
defer tron.Close()

Directories

Path Synopsis
pkg
address
Package address provides functionality for generating and managing Tron addresses.
Package address provides functionality for generating and managing Tron addresses.
client
Package client provides a gRPC client for interacting with Tron nodes.
Package client provides a gRPC client for interacting with Tron nodes.
crypto
Package crypto provides cryptographic functions for Tron transactions.
Package crypto provides cryptographic functions for Tron transactions.
schema

Jump to

Keyboard shortcuts

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