types

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 10 Imported by: 2 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package types provides shared types and utilities for the TRON SDK

Package types defines fundamental types and error values used across the TRON SDK, including Address, transaction wrappers, and common constants.

Address Type

The Address type supports multiple encodings:

  • Base58Check string (T-prefixed, length 34) via Address.Base58() or String()
  • TRON bytes (0x41-prefixed 21 bytes) via Address.Bytes()
  • EVM bytes (20 bytes) via Address.BytesEVM()
  • Hex forms via Address.Hex() (41-prefixed) and Address.HexEVM() (0x-prefixed)

Constructors accept flexible inputs and validate length and prefixes. Prefer NewAddress[...] constructors rather than constructing Address directly.

addr, _ := types.NewAddress("Txxxxxxxxxxxxxxxxxxxxxxxxxxxxxx1")
_ = addr.Hex()

Error Types

The package defines sentinel errors used throughout the SDK:

  • ErrInvalidAddress - Invalid TRON address format
  • ErrInvalidTransaction - Invalid transaction structure
  • ErrInvalidSignature - Invalid transaction signature

Constants

Common constants used in TRON operations:

  • SUN_PER_TRX - Number of SUN in 1 TRX (1,000,000)
  • ADDRESS_SIZE - Size of TRON address in bytes (21)

Always check for errors in production code.

Package types provides shared types and utilities for the TRON SDK

Index

Examples

Constants

View Source
const (
	// Network constants
	TronMainNet = "mainnet"
	TronTestNet = "testnet"
	TronNileNet = "nile"

	// Address constants
	AddressPrefixByte   = 0x41
	AddressLength       = 21
	AddressHexLength    = 42 // Including 0x prefix
	AddressBase58Length = 34

	// Transaction constants
	DefaultFeeLimit           = 1000000 // 1 TRX in SUN
	DefaultTransactionTimeout = 30 * time.Second
	DefaultExpiration         = 10 * time.Minute

	// Energy constants
	DefaultEnergyLimit = 10000000
	EnergyPerByte      = 1

	// Bandwidth constants
	DefaultBandwidthLimit = 5000
	BandwidthPerByte      = 1

	// Resource constants
	SunPerTRX = 1000000 // 1 TRX = 1,000,000 SUN

	// Contract constants
	DefaultContractCallValue = 0
	MaxContractSize          = 65536 // 64KB

	// TRC20 constants
	TRC20TransferMethodID    = "a9059cbb" // transfer(address,uint256)
	TRC20BalanceOfMethodID   = "70a08231" // balanceOf(address)
	TRC20ApproveMethodID     = "095ea7b3" // approve(address,uint256)
	TRC20AllowanceMethodID   = "dd62ed3e" // allowance(address,address)
	TRC20TotalSupplyMethodID = "18160ddd" // totalSupply()
	TRC20NameMethodID        = "06fdde03" // name()
	TRC20SymbolMethodID      = "95d89b41" // symbol()
	TRC20DecimalsMethodID    = "313ce567" // decimals()

	// Block constants
	BlockTimeMS = 3000 // 3 seconds per block

	// Permission constants
	OwnerPermissionID   = 0
	WitnessPermissionID = 1
	ActivePermissionID  = 2

	MaxResultSize = 64 // used for bandwidth estimation
)
View Source
const (
	// BlackHoleAddress is the TRON black hole (burn) address; funds sent
	// here are permanently destroyed.
	BlackHoleAddress = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"
)

Variables

View Source
var (
	MainNet = Network{
		Name:    TronMainNet,
		ChainID: "0x2b6653dc",
		NodeURLs: []string{
			"grpcs://grpc.trongrid.io:50051",
			"grpcs://grpc.shasta.trongrid.io:50051",
		},
	}

	TestNet = Network{
		Name:    TronTestNet,
		ChainID: "0x94a9059e",
		NodeURLs: []string{
			"grpcs://grpc.shasta.trongrid.io:50051",
		},
	}

	NileNet = Network{
		Name:    TronNileNet,
		ChainID: "0xcd8690dc",
		NodeURLs: []string{
			"grpcs://grpc.nile.trongrid.io:50051",
		},
	}
)

Predefined networks.

View Source
var (
	// ErrInvalidAddress indicates an invalid address format or value
	ErrInvalidAddress = errors.New("invalid address: check format and ensure it's a valid TRON address")

	// ErrInvalidAmount indicates an invalid amount value
	ErrInvalidAmount = errors.New("invalid amount: must be positive and within valid range")

	// ErrInvalidContract indicates an invalid contract
	ErrInvalidContract = errors.New("invalid contract: check contract address and ABI")

	// ErrInvalidTransaction indicates an invalid transaction
	ErrInvalidTransaction = errors.New("invalid transaction: check transaction format and parameters")

	// ErrInsufficientBalance indicates insufficient balance for operation
	ErrInsufficientBalance = errors.New("insufficient balance: check account balance and required amount")

	// ErrInsufficientEnergy indicates insufficient energy for contract execution
	ErrInsufficientEnergy = errors.New("insufficient energy: freeze TRX for energy or wait for energy regeneration")

	// ErrInsufficientBandwidth indicates insufficient bandwidth for transaction
	ErrInsufficientBandwidth = errors.New("insufficient bandwidth: freeze TRX for bandwidth or wait for bandwidth regeneration")

	// ErrTransactionFailed indicates transaction execution failed
	ErrTransactionFailed = errors.New("transaction failed: check transaction details and account resources")

	// ErrContractExecutionFailed indicates contract execution failed
	ErrContractExecutionFailed = errors.New("contract execution failed: check contract state and parameters")

	// ErrNetworkError indicates a network-related error
	ErrNetworkError = errors.New("network error: check connection and node availability")

	// ErrTimeout indicates operation timeout
	ErrTimeout = errors.New("operation timeout: try again or increase timeout duration")

	// ErrNotFound indicates resource not found
	ErrNotFound = errors.New("not found: check resource identifier and network")

	// ErrAlreadyExists indicates resource already exists
	ErrAlreadyExists = errors.New("already exists: resource with this identifier already exists")

	// ErrPermissionDenied indicates insufficient permissions
	ErrPermissionDenied = errors.New("permission denied: check account permissions and authorization")

	// ErrInvalidParameter indicates invalid parameter value
	ErrInvalidParameter = errors.New("invalid parameter: check parameter value and format")

	// ErrInvalidPrivateKey indicates an invalid, malformed, or missing private key
	ErrInvalidPrivateKey = errors.New("invalid private key: check key format and value")
)

Functions

func WrapTransactionResult

func WrapTransactionResult(result *api.Return, operation string) error

WrapTransactionResult wraps transaction result errors with context.

Types

type Address

type Address struct {
	// contains filtered or unexported fields
}

Address represents a TRON address that can be stored in different formats. Always construct via the NewAddress[...] helpers to ensure validation.

The Address type can represent TRON addresses in multiple formats:

  • Base58: T-prefixed 34-character string (e.g., "TLCuBEbV6jp9432t4Xhg5E5j7v7vK4gkgX")
  • Bytes: 0x41-prefixed 21-byte array
  • Hex: 42-character hex string with 0x41 prefix
  • EVM Bytes: 20-byte array without prefix (for Ethereum compatibility)

Use the various constructor functions to create Address instances safely.

func MustNewAddressFromBase58

func MustNewAddressFromBase58(base58Addr string) *Address

MustNewAddressFromBase58 is a wrapper for NewAddressFromBase58 that panics if the address is invalid

func MustNewAddressFromBytes

func MustNewAddressFromBytes(byteAddress []byte) *Address

MustNewAddressFromBytes is a wrapper for NewAddressFromBytes that panics if the address is invalid

func MustNewAddressFromHex

func MustNewAddressFromHex(hexAddr string) *Address

MustNewAddressFromHex is a wrapper for NewAddressFromHex that panics if the address is invalid

func NewAddress

func NewAddress[T addressAllowed](v T) (*Address, error)
Example

ExampleNewAddress demonstrates constructing an Address from base58.

package main

import (
	"fmt"

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

func main() {
	addr, _ := types.NewAddress("TBkfmcE7pM8cwxEhATtkMFwAf1FeQcwY9x")
	fmt.Println(len(addr.Bytes()) > 0)
}
Output:
true

func NewAddressFromBase58

func NewAddressFromBase58(base58Addr string) (*Address, error)

NewAddressFromBase58 creates an Address from a Base58Check string. The string must be length 34, T-prefixed.

This function parses a Base58-encoded TRON address and validates its checksum. The address must be exactly 34 characters long and start with "T".

Example:

addr, err := types.NewAddressFromBase58("TLCuBEbV6jp9432t4Xhg5E5j7v7vK4gkgX")
if err != nil {
    // handle error
}
fmt.Printf("Address: %s\n", addr.String())

func NewAddressFromBytes

func NewAddressFromBytes(byteAddress []byte) (*Address, error)

NewAddressFromBytes creates an Address from bytes. Supported lengths:

  • 21 bytes (0x41-prefixed TRON address)
  • 20 bytes (EVM address), which will be promoted by adding 0x41 prefix

func NewAddressFromEVM

func NewAddressFromEVM(evmAddr eCommon.Address) (*Address, error)

NewAddressFromEVM converts a 20-byte Ethereum address into a TRON address by prepending the 0x41 TRON prefix.

func NewAddressFromHex

func NewAddressFromHex(hexAddr string) (*Address, error)

NewAddressFromHex creates an Address from a hex string. Supported forms:

  • 0x41-prefixed 21-byte TRON hex
  • 41-prefixed 21-byte TRON hex (without 0x)
  • 20-byte hex (0x-optional) which will be promoted by adding 0x41 prefix

func (*Address) Base58

func (a *Address) Base58() string

Base58 returns the T prefixed 34 chars base58 representation

func (*Address) Bytes

func (a *Address) Bytes() []byte

Bytes returns the raw bytes of the address (0x41 prefixed 21 bytes).

This method returns the raw byte representation of the address, which includes the 0x41 prefix followed by the 20-byte address hash.

Example:

addr, _ := types.NewAddressFromBase58("TLCuBEbV6jp9432t4Xhg5E5j7v7vK4gkgX")
bytes := addr.Bytes() // Returns 21 bytes: [0x41, ...]

func (*Address) BytesEVM

func (a *Address) BytesEVM() []byte

BytesEVM returns the raw bytes of the address (20 bytes without prefix)

func (*Address) EVMAddress

func (a *Address) EVMAddress() eCommon.Address

EVMAddress converts the TRON address to an Ethereum compatible address It panics if the address is nil

func (*Address) Equal

func (a *Address) Equal(other *Address) bool

Equal checks if two addresses are equal

func (*Address) Hex

func (a *Address) Hex() string

Hex returns the address as 41-prefixed, 42-character hex string.

func (*Address) HexEVM

func (a *Address) HexEVM() string

HexEVM returns the EVM-style 0x-prefixed, 40-character hex string.

func (*Address) IsValid

func (a *Address) IsValid() bool

IsValid checks if the address is valid

func (*Address) String

func (a *Address) String() string

String returns the T prefixed 34 chars base58 representation.

This method implements the fmt.Stringer interface, returning the Base58 representation of the address which is the default string representation.

Example:

addr, _ := types.NewAddressFromBase58("TLCuBEbV6jp9432t4Xhg5E5j7v7vK4gkgX")
fmt.Printf("Address: %s\n", addr.String()) // Prints: TLCuBEbV6jp9432t4Xhg5E5j7v7vK4gkgX

type ContractError

type ContractError struct {
	ContractAddress string
	Method          string
	Message         string
	Cause           error
}

ContractError represents smart contract execution errors.

func NewContractError

func NewContractError(contractAddress, method, message string, cause error) *ContractError

NewContractError creates a new ContractError.

func (*ContractError) Error

func (e *ContractError) Error() string

Error implements error.

func (*ContractError) Unwrap

func (e *ContractError) Unwrap() error

Unwrap returns the underlying cause.

type ContractType

type ContractType int

ContractType represents the type of smart contract

const (
	ContractTypeUnknown ContractType = iota
	ContractTypeTRC20
	ContractTypeTRC721
	ContractTypeTRC1155
	ContractTypeCustom
)

func (ContractType) String

func (c ContractType) String() string

String returns the string representation of ContractType

type Network

type Network struct {
	Name     string
	ChainID  string
	NodeURLs []string
}

Network represents a TRON network

func GetNetwork

func GetNetwork(name string) *Network

GetNetwork returns a predefined network by name

type ResourceType

type ResourceType int

ResourceType represents the type of resource

const (
	ResourceBandwidth ResourceType = iota
	ResourceEnergy
)

func (ResourceType) String

func (r ResourceType) String() string

String returns the string representation of ResourceType

type TransactionError

type TransactionError struct {
	TxID    string
	Message string
	Cause   error
}

TransactionError represents transaction-specific errors.

func NewTransactionError

func NewTransactionError(txID, message string, cause error) *TransactionError

NewTransactionError creates a new TransactionError.

func (*TransactionError) Error

func (e *TransactionError) Error() string

Error implements error.

func (*TransactionError) Unwrap

func (e *TransactionError) Unwrap() error

Unwrap returns the underlying cause.

type TransactionStatus

type TransactionStatus int

TransactionStatus represents the status of a transaction

const (
	TransactionStatusUnknown TransactionStatus = iota
	TransactionStatusPending
	TransactionStatusConfirmed
	TransactionStatusFailed
	TransactionStatusReverted
)

func (TransactionStatus) String

func (s TransactionStatus) String() string

String returns the string representation of TransactionStatus

type TronError

type TronError struct {
	Code    int32
	Message string
	Cause   error
}

TronError wraps TRON-specific errors with additional context.

func NewTronError

func NewTronError(code int32, message string, cause error) *TronError

NewTronError creates a new TronError.

func (*TronError) Error

func (e *TronError) Error() string

Error implements error.

func (*TronError) Unwrap

func (e *TronError) Unwrap() error

Unwrap returns the underlying cause.

Jump to

Keyboard shortcuts

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