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 ¶
- func BytesToHex(data []byte) string
- func DecodeAddress(data []byte) string
- func DecodeParameters(abiJSON string, method string, data []byte) ([]interface{}, error)
- func DecodeString(data []byte) (string, error)
- func DecodeTRC20Balance(data []byte) (*big.Int, error)
- func DecodeUint256(data []byte) *big.Int
- func EncodeAddress(address string) ([]byte, error)
- func EncodeMethodSignature(method string) []byte
- func EncodeParameters(abiJSON string, method string, params ...interface{}) ([]byte, error)
- func EncodeString(str string) []byte
- func EncodeTRC20BalanceOf(address string) ([]byte, error)
- func EncodeTRC20Transfer(to string, amount *big.Int) ([]byte, error)
- func EncodeUint256(value *big.Int) []byte
- func ExtractSigners(tx *core.Transaction) ([]*types.Address, error)
- func FormatBigInt(value *big.Int, decimals int) string
- func GetTransactionID(tx *core.Transaction) []byte
- func HexToBytes(hexStr string) ([]byte, error)
- func HumanReadableBalance(balance any, decimals int64) (string, error)
- func HumanReadableNumber(number any, decimal int64) (string, error)
- func HumanReadableTokenAmount(amount any, decimals int64) (string, error)
- func IsValidAmount(amount *big.Int) bool
- func IsValidContractName(name string) bool
- func IsValidDecimals(decimals int) bool
- func IsValidMethodName(method string) bool
- func IsValidNodeURL(url string) bool
- func IsValidPermissionID(permissionID int32) bool
- func IsValidTokenSymbol(symbol string) bool
- func JSONToMap(jsonStr string) (map[string]interface{}, error)
- func MapToJSON(data map[string]interface{}) (string, error)
- func PadLeft(data []byte, length int) []byte
- func PadRight(data []byte, length int) []byte
- func ParseBigInt(str string) (*big.Int, error)
- func SetExpiration(tx any, expiration int64) error
- func SetFeeLimit(tx any, feeLimit int64) error
- func SetPermissionID(tx any, permissionID int32) error
- func SetTimestamp(tx any, timestamp int64) error
- func ValidateAmount(amount *big.Int) error
- func ValidateConsumeUserResourcePercent(percent int64) error
- func ValidateContractData(data []byte) error
- func ValidateContractName(name string) error
- func ValidateDecimals(decimals int) error
- func ValidateMethodName(method string) error
- func ValidateNodeURL(url string) error
- func ValidatePermissionID(permissionID int32) error
- func ValidateTokenSymbol(symbol string) error
- func VerifyMessageV2(message string, signature string, expectedAddress string) (bool, error)
- type ABIProcessor
- func (p *ABIProcessor) DecodeInputData(data []byte, abi *core.SmartContract_ABI) (*DecodedInput, error)
- func (p *ABIProcessor) DecodeResult(data []byte, outputs []*core.SmartContract_ABI_Entry_Param) (interface{}, error)
- func (p *ABIProcessor) EncodeMethod(method string, paramTypes []string, params []interface{}) ([]byte, error)
- func (p *ABIProcessor) GetConstructorTypes(abi *core.SmartContract_ABI) ([]string, error)
- func (p *ABIProcessor) GetMethodTypes(methodName string) ([]string, []string, error)
- func (p *ABIProcessor) ParseABI(abi string) (*core.SmartContract_ABI, error)
- type DecodedInput
- type DecodedInputParameter
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BytesToHex ¶
BytesToHex converts bytes to hex string with 0x prefix
func DecodeAddress ¶
DecodeAddress decodes bytes32 to address
func DecodeParameters ¶
DecodeParameters decodes parameters from smart contract call result using ABI
func DecodeString ¶
DecodeString decodes a string from smart contract result
func DecodeTRC20Balance ¶
DecodeTRC20Balance decodes a TRC20 balance result
func DecodeUint256 ¶
DecodeUint256 decodes uint256 (32 bytes) to big integer
func EncodeAddress ¶
EncodeAddress encodes an address as bytes32
func EncodeMethodSignature ¶
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 ¶
EncodeParameters encodes parameters for smart contract calls using ABI
func EncodeString ¶
EncodeString encodes a string for smart contract calls
func EncodeTRC20BalanceOf ¶
EncodeTRC20BalanceOf encodes a TRC20 balanceOf call
func EncodeTRC20Transfer ¶
EncodeTRC20Transfer encodes a TRC20 transfer call
func EncodeUint256 ¶
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 ¶
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 ¶
HexToBytes converts hex string to bytes
func HumanReadableBalance ¶
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 ¶
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 ¶
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 ¶
IsValidAmount validates that an amount is positive and within reasonable bounds
func IsValidContractName ¶
IsValidContractName validates a smart contract name
func IsValidDecimals ¶
IsValidDecimals validates token decimals
func IsValidMethodName ¶
IsValidMethodName validates a smart contract method name
func IsValidNodeURL ¶
IsValidNodeURL validates a TRON node URL. Requires explicit scheme and host:port, e.g. grpc://host:port or grpcs://host:port
func IsValidPermissionID ¶
IsValidPermissionID validates a permission ID
func IsValidTokenSymbol ¶
IsValidTokenSymbol validates a token symbol
func ParseBigInt ¶
ParseBigInt parses a string to big.Int with support for different formats
func SetExpiration ¶ added in v1.0.11
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
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
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
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 ¶
ValidateAmount validates an amount and returns error if invalid
func ValidateConsumeUserResourcePercent ¶
ValidateConsumeUserResourcePercent validates the consume user resource percentage
func ValidateContractData ¶
ValidateContractData validates smart contract call data
func ValidateContractName ¶
ValidateContractName validates a contract name and returns error if invalid
func ValidateDecimals ¶
ValidateDecimals validates token decimals and returns error if invalid
func ValidateMethodName ¶
ValidateMethodName validates a method name and returns error if invalid
func ValidateNodeURL ¶
ValidateNodeURL validates a node URL and returns error if invalid
func ValidatePermissionID ¶
ValidatePermissionID validates a permission ID and returns error if invalid
func ValidateTokenSymbol ¶
ValidateTokenSymbol validates a token symbol and returns error if invalid
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)})
}
Output:
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