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 ¶
- Constants
- Variables
- func WrapTransactionResult(result *api.Return, operation string) error
- type Address
- func MustNewAddressFromBase58(base58Addr string) *Address
- func MustNewAddressFromBytes(byteAddress []byte) *Address
- func MustNewAddressFromHex(hexAddr string) *Address
- func NewAddress[T addressAllowed](v T) (*Address, error)
- func NewAddressFromBase58(base58Addr string) (*Address, error)
- func NewAddressFromBytes(byteAddress []byte) (*Address, error)
- func NewAddressFromEVM(evmAddr eCommon.Address) (*Address, error)
- func NewAddressFromHex(hexAddr string) (*Address, error)
- func (a *Address) Base58() string
- func (a *Address) Bytes() []byte
- func (a *Address) BytesEVM() []byte
- func (a *Address) EVMAddress() eCommon.Address
- func (a *Address) Equal(other *Address) bool
- func (a *Address) Hex() string
- func (a *Address) HexEVM() string
- func (a *Address) IsValid() bool
- func (a *Address) String() string
- type ContractError
- type ContractType
- type Network
- type ResourceType
- type TransactionError
- type TransactionStatus
- type TronError
Examples ¶
Constants ¶
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 )
const ( // BlackHoleAddress is the TRON black hole (burn) address; funds sent // here are permanently destroyed. BlackHoleAddress = "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb" )
Variables ¶
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.
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 ¶
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 ¶
MustNewAddressFromBase58 is a wrapper for NewAddressFromBase58 that panics if the address is invalid
func MustNewAddressFromBytes ¶
MustNewAddressFromBytes is a wrapper for NewAddressFromBytes that panics if the address is invalid
func MustNewAddressFromHex ¶
MustNewAddressFromHex is a wrapper for NewAddressFromHex that panics if the address is invalid
func NewAddress ¶
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 ¶
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 ¶
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 ¶
NewAddressFromEVM converts a 20-byte Ethereum address into a TRON address by prepending the 0x41 TRON prefix.
func NewAddressFromHex ¶
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) Bytes ¶
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) EVMAddress ¶
EVMAddress converts the TRON address to an Ethereum compatible address It panics if the address is nil
func (*Address) 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 ¶
ContractError represents smart contract execution errors.
func NewContractError ¶
func NewContractError(contractAddress, method, message string, cause error) *ContractError
NewContractError creates a new ContractError.
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 ¶
Network represents a TRON network
func GetNetwork ¶
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 ¶
TransactionError represents transaction-specific errors.
func NewTransactionError ¶
func NewTransactionError(txID, message string, cause error) *TransactionError
NewTransactionError creates a new TransactionError.
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 ¶
TronError wraps TRON-specific errors with additional context.
func NewTronError ¶
NewTronError creates a new TronError.