utils

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: 16 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 utils houses ABI encode/decode logic, type parsing, and common helpers shared by higher-level packages. The ABIProcessor is the central type for converting between Go values and TRON/EVM ABI representations.

ABI Processing

The ABIProcessor handles encoding and decoding of ABI data:

abi, _ := utils.NewABIProcessor(nil).ParseABI(abiJSON)
proc := utils.NewABIProcessor(abi)
data, _ := proc.EncodeMethod("setValue", []string{"uint256"}, 42)

Encoding Functions

The package provides direct encoding functions for common types:

  • EncodeAddress - Encode an address
  • EncodeUint256 - Encode a uint256 value
  • EncodeString - Encode a string

Decoding Functions

The package provides direct decoding functions:

  • DecodeAddress - Decode an address
  • DecodeUint256 - Decode a uint256 value
  • DecodeString - Decode a string

Error Handling

Common error types:

  • ErrInvalidABI - Invalid ABI format
  • ErrInvalidType - Invalid data type
  • ErrInvalidData - Invalid data format

Always check for errors in production code.

Package utils provides encoding and decoding utilities for the TRON SDK

Package types provides shared types and utilities for the TRON SDK

Package utils provides validation utilities for the TRON SDK

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BytesToHex

func BytesToHex(data []byte) string

BytesToHex converts bytes to hex string with 0x prefix

func DecodeAddress

func DecodeAddress(data []byte) string

DecodeAddress decodes bytes32 to address

func DecodeParameters

func DecodeParameters(abiJSON string, method string, data []byte) ([]interface{}, error)

DecodeParameters decodes parameters from smart contract call result using ABI

func DecodeString

func DecodeString(data []byte) (string, error)

DecodeString decodes a string from smart contract result

func DecodeTRC20Balance

func DecodeTRC20Balance(data []byte) (*big.Int, error)

DecodeTRC20Balance decodes a TRC20 balance result

func DecodeUint256

func DecodeUint256(data []byte) *big.Int

DecodeUint256 decodes uint256 (32 bytes) to big integer

func EncodeAddress

func EncodeAddress(address string) ([]byte, error)

EncodeAddress encodes an address as bytes32

func EncodeMethodSignature

func EncodeMethodSignature(method string) []byte

EncodeMethodSignature encodes a method signature for smart contract calls using the first 4 bytes of the Keccak256 hash of the canonical signature (e.g., "transfer(address,uint256)" -> 0xa9059cbb).

func EncodeParameters

func EncodeParameters(abiJSON string, method string, params ...interface{}) ([]byte, error)

EncodeParameters encodes parameters for smart contract calls using ABI

func EncodeString

func EncodeString(str string) []byte

EncodeString encodes a string for smart contract calls

func EncodeTRC20BalanceOf

func EncodeTRC20BalanceOf(address string) ([]byte, error)

EncodeTRC20BalanceOf encodes a TRC20 balanceOf call

func EncodeTRC20Transfer

func EncodeTRC20Transfer(to string, amount *big.Int) ([]byte, error)

EncodeTRC20Transfer encodes a TRC20 transfer call

func EncodeUint256

func EncodeUint256(value *big.Int) []byte

EncodeUint256 encodes a big integer as uint256 (32 bytes)

func ExtractSigners added in v1.0.9

func ExtractSigners(tx *core.Transaction) ([]*types.Address, error)

ExtractSigners returns the addresses whose signatures are attached to the transaction, or nil for a nil transaction. It queries the network for permission details when the transaction uses multi-signature permissions.

func FormatBigInt

func FormatBigInt(value *big.Int, decimals int) string

FormatBigInt formats a big.Int to string with optional decimal places

func GetTransactionID added in v1.0.8

func GetTransactionID(tx *core.Transaction) []byte

GetTransactionID calculates the transaction ID from a transaction

func HexToBytes

func HexToBytes(hexStr string) ([]byte, error)

HexToBytes converts hex string to bytes

func HumanReadableBalance

func HumanReadableBalance(balance any, decimals int64) (string, error)

HumanReadableBalance is a convenience function for displaying balances It formats numbers with comma separators and a reasonable number of decimal places

Parameters:

  • balance: Balance amount - must be a whole number
  • decimals: Number of decimal places to show (default recommendation: 6)

Returns:

  • string: Human-readable balance
  • error: Error if conversion fails

Examples:

HumanReadableBalance("1234567890123456789", 6) -> "1,234,567,890.123457", nil
HumanReadableBalance(-1000000, 2) -> "-10.00", nil

func HumanReadableNumber

func HumanReadableNumber(number any, decimal int64) (string, error)

HumanReadableNumber converts a number to human-readable format with comma separators and decimal places. Handles negative numbers and various input types.

Parameters:

  • number: Input number (raw value, e.g., from smart contract) - must be a whole number
  • decimal: Number of decimal places the raw number should be divided by (e.g., 6 for USDT, 18 for ETH)

Returns:

  • string: Formatted number with comma separators (e.g., "1,234,567.890000")
  • error: Error if conversion fails

Examples:

HumanReadableNumber("1234567890", 6) -> "1,234.567890", nil (divides by 10^6)
HumanReadableNumber(-1234567890, 2) -> "-12,345,678.90", nil (divides by 10^2)
HumanReadableNumber("0", 0) -> "0", nil (no division)

func HumanReadableTokenAmount

func HumanReadableTokenAmount(amount any, decimals int64) (string, error)

HumanReadableTokenAmount is a convenience function for token amounts It handles the common case of converting token amounts with known decimals

Parameters:

  • amount: Token amount (raw value from smart contract) - must be a whole number
  • decimals: Token decimals (e.g., 18 for most ERC20 tokens, 6 for USDT)

Returns:

  • string: Human-readable token amount
  • error: Error if conversion fails

Examples:

HumanReadableTokenAmount("1000000000000000000", 18) -> "1.000000000000000000", nil
HumanReadableTokenAmount("1000000", 6) -> "1.000000", nil

func IsValidAmount

func IsValidAmount(amount *big.Int) bool

IsValidAmount validates that an amount is positive and within reasonable bounds

func IsValidContractName

func IsValidContractName(name string) bool

IsValidContractName validates a smart contract name

func IsValidDecimals

func IsValidDecimals(decimals int) bool

IsValidDecimals validates token decimals

func IsValidMethodName

func IsValidMethodName(method string) bool

IsValidMethodName validates a smart contract method name

func IsValidNodeURL

func IsValidNodeURL(url string) bool

IsValidNodeURL validates a TRON node URL. Requires explicit scheme and host:port, e.g. grpc://host:port or grpcs://host:port

func IsValidPermissionID

func IsValidPermissionID(permissionID int32) bool

IsValidPermissionID validates a permission ID

func IsValidTokenSymbol

func IsValidTokenSymbol(symbol string) bool

IsValidTokenSymbol validates a token symbol

func JSONToMap

func JSONToMap(jsonStr string) (map[string]interface{}, error)

JSONToMap converts JSON string to map

func MapToJSON

func MapToJSON(data map[string]interface{}) (string, error)

MapToJSON converts map to JSON string

func PadLeft

func PadLeft(data []byte, length int) []byte

PadLeft pads data to the left with zeros to reach the specified length

func PadRight

func PadRight(data []byte, length int) []byte

PadRight pads data to the right with zeros to reach the specified length

func ParseBigInt

func ParseBigInt(str string) (*big.Int, error)

ParseBigInt parses a string to big.Int with support for different formats

func SetExpiration added in v1.0.11

func SetExpiration(tx any, expiration int64) error

SetExpiration sets the expiration time for a transaction. IMPORTANT: This must be called before signing the transaction, as the signature is calculated based on the transaction's raw data including the expiration time.

The function supports both *core.Transaction and *api.TransactionExtention types. The expiration should be a Unix timestamp in milliseconds in the future.

Example:

tx, err := cli.Account().TransferTRX(ctx, from, to, amount)
if err != nil {
    // handle error
}

// Set expiration BEFORE signing (e.g., 1 hour from now)
expiration := time.Now().Add(time.Hour).UnixMilli()
err = utils.SetExpiration(tx, expiration)
if err != nil {
    // handle error
}

// Now sign the transaction
err = signer.SignTx(signer1, tx)
if err != nil {
    // handle error
}

func SetFeeLimit added in v1.0.11

func SetFeeLimit(tx any, feeLimit int64) error

SetFeeLimit sets the fee limit for a transaction. IMPORTANT: This must be called before signing the transaction, as the signature is calculated based on the transaction's raw data including the fee limit.

The function supports both *core.Transaction and *api.TransactionExtention types.

Example:

tx, err := cli.Account().TransferTRX(ctx, from, to, amount)
if err != nil {
    // handle error
}

// Set fee limit BEFORE signing
err = utils.SetFeeLimit(tx, 150_000_000)  // 0.15 TRX
if err != nil {
    // handle error
}

// Now sign the transaction
err = signer.SignTx(signer1, tx)
if err != nil {
    // handle error
}

func SetPermissionID added in v1.0.11

func SetPermissionID(tx any, permissionID int32) error

SetPermissionID sets the permission ID for a transaction contract. IMPORTANT: This must be called before signing the transaction, as the signature is calculated based on the transaction's raw data including the permission ID.

The function supports both *core.Transaction and *api.TransactionExtention types. For multi-signature transactions, ensure the permission ID is set before calling signer.SignTx() with any signers.

Example:

tx, err := cli.Account().TransferTRX(ctx, from, to, amount)
if err != nil {
    // handle error
}

// Set permission ID BEFORE signing
err = utils.SetPermissionID(tx, 3)
if err != nil {
    // handle error
}

// Now sign the transaction
err = signer.SignTx(signer1, tx)
if err != nil {
    // handle error
}

func SetTimestamp added in v1.0.11

func SetTimestamp(tx any, timestamp int64) error

SetTimestamp sets the timestamp for a transaction. IMPORTANT: This must be called before signing the transaction, as the signature is calculated based on the transaction's raw data including the timestamp.

The function supports both *core.Transaction and *api.TransactionExtention types. Note that if not set, the TRON node will typically set this when processing the transaction.

Example:

tx, err := cli.Account().TransferTRX(ctx, from, to, amount)
if err != nil {
    // handle error
}

// Set timestamp BEFORE signing (usually current time in milliseconds)
err = utils.SetTimestamp(tx, time.Now().UnixMilli())
if err != nil {
    // handle error
}

// Now sign the transaction
err = signer.SignTx(signer1, tx)
if err != nil {
    // handle error
}

func ValidateAmount

func ValidateAmount(amount *big.Int) error

ValidateAmount validates an amount and returns error if invalid

func ValidateConsumeUserResourcePercent

func ValidateConsumeUserResourcePercent(percent int64) error

ValidateConsumeUserResourcePercent validates the consume user resource percentage

func ValidateContractData

func ValidateContractData(data []byte) error

ValidateContractData validates smart contract call data

func ValidateContractName

func ValidateContractName(name string) error

ValidateContractName validates a contract name and returns error if invalid

func ValidateDecimals

func ValidateDecimals(decimals int) error

ValidateDecimals validates token decimals and returns error if invalid

func ValidateMethodName

func ValidateMethodName(method string) error

ValidateMethodName validates a method name and returns error if invalid

func ValidateNodeURL

func ValidateNodeURL(url string) error

ValidateNodeURL validates a node URL and returns error if invalid

func ValidatePermissionID

func ValidatePermissionID(permissionID int32) error

ValidatePermissionID validates a permission ID and returns error if invalid

func ValidateTokenSymbol

func ValidateTokenSymbol(symbol string) error

ValidateTokenSymbol validates a token symbol and returns error if invalid

func VerifyMessageV2

func VerifyMessageV2(message string, signature string, expectedAddress string) (bool, error)

VerifyMessageV2 verifies a message signature using TIP-191 format (v2)

Types

type ABIProcessor

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

ABIProcessor handles all smart contract ABI operations including encoding, decoding, parsing, and event processing

Example

ExampleABIProcessor demonstrates encoding a simple method call.

package main

import (
	"math/big"

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

func main() {
	abiJSON := `{"entrys":[{"type":"function","name":"set","inputs":[{"name":"v","type":"uint256"}]}]}`
	abi, _ := utils.NewABIProcessor(nil).ParseABI(abiJSON)
	proc := utils.NewABIProcessor(abi)
	_, _ = proc.EncodeMethod("set", []string{"uint256"}, []interface{}{big.NewInt(1)})
}

func NewABIProcessor

func NewABIProcessor(abi *core.SmartContract_ABI) *ABIProcessor

NewABIProcessor creates an ABIProcessor bound to the provided ABI. The processor exposes helpers to parse ABI JSON, encode inputs, decode outputs, and decode events.

func (*ABIProcessor) DecodeInputData

func (p *ABIProcessor) DecodeInputData(data []byte, abi *core.SmartContract_ABI) (*DecodedInput, error)

DecodeInputData decodes call data into a DecodedInput using the provided ABI.

func (*ABIProcessor) DecodeResult

func (p *ABIProcessor) DecodeResult(data []byte, outputs []*core.SmartContract_ABI_Entry_Param) (interface{}, error)

DecodeResult decodes method return bytes. Behavior:

  • no outputs: returns nil
  • one output: returns the value directly
  • many outputs: returns []interface{}

func (*ABIProcessor) EncodeMethod

func (p *ABIProcessor) EncodeMethod(method string, paramTypes []string, params []interface{}) ([]byte, error)

EncodeMethod encodes a method call with parameters. For constructors, pass method="" to encode only parameters (no 4-byte method ID).

func (*ABIProcessor) GetConstructorTypes

func (p *ABIProcessor) GetConstructorTypes(abi *core.SmartContract_ABI) ([]string, error)

GetConstructorTypes returns the constructor input type names.

func (*ABIProcessor) GetMethodTypes

func (p *ABIProcessor) GetMethodTypes(methodName string) ([]string, []string, error)

GetMethodTypes returns input and output type names for the given method.

func (*ABIProcessor) ParseABI

func (p *ABIProcessor) ParseABI(abi string) (*core.SmartContract_ABI, error)

ParseABI decodes a standard ABI JSON string into a *core.SmartContract_ABI.

type DecodedInput

type DecodedInput struct {
	Method     string                  `json:"method"`
	Parameters []DecodedInputParameter `json:"parameters"`
}

DecodedInput represents decoded input data

type DecodedInputParameter

type DecodedInputParameter struct {
	Name  string      `json:"name"`
	Type  string      `json:"type"`
	Value interface{} `json:"value"`
}

DecodedInputParameter represents a decoded parameter

Jump to

Keyboard shortcuts

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