client

package
v0.0.0-...-c00f9e8 Latest Latest
Warning

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

Go to latest
Published: May 8, 2026 License: MIT Imports: 41 Imported by: 0

Documentation

Overview

Package client provides a client for interacting with Tron nodes via gRPC or HTTP.

Index

Constants

View Source
const (
	TrxDecimals        = 6
	TrxAssetIdentifier = "trx"
)
View Source
const (
	Trc20TransferEventSignature = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"

	Trc20TransferFromMethodSignature = "0x23b872dd"
)

Variables

View Source
var (
	// Common errors
	ErrInvalidConfig = errors.New("invalid client configuration")
	ErrNotConnected  = errors.New("client not connected")
	ErrInvalidParams = errors.New("invalid parameters")
	ErrNilResponse   = errors.New("nil response from server")

	// Address errors
	ErrInvalidAddress      = errors.New("invalid address")
	ErrEmptyAddress        = errors.New("address is empty")
	ErrAccountNotActivated = errors.New("account is not activated")

	// Transaction errors
	ErrInvalidAmount           = errors.New("invalid amount")
	ErrInvalidTransaction      = errors.New("invalid transaction")
	ErrInvalidPrivateKey       = errors.New("invalid private key")
	ErrTransactionNotFound     = errors.New("transaction not found")
	ErrTransactionInfoNotFound = errors.New("transaction info not found")

	// Resources errors
	ErrInvalidResourceType = errors.New("invalid resource type")

	// ErrNoHealthyNodes is returned when no node in any tier is currently
	// marked healthy. The health-checker runs continuously and will return
	// nodes to the pool as soon as they recover; callers should retry with
	// backoff. Use errors.Is(err, client.ErrNoHealthyNodes) to detect it.
	ErrNoHealthyNodes = errors.New("no healthy nodes available in any tier")
)
View Source
var ErrAccountNotFound = errors.New("account not found")

Functions

func CreateFakeCreateAccountTransaction

func CreateFakeCreateAccountTransaction(fromAddress, toAddress string) (*core.Transaction, error)

func CreateFakeResourceTransaction

func CreateFakeResourceTransaction(fromAddress, toAddress string, amount int64, resourceType core.ResourceCode, reclaim bool) (*core.Transaction, error)

CreateFakeResourceTransaction creates a fake resource transaction.

func GetMessageBytes

func GetMessageBytes(m []byte) *api.BytesMessage

GetMessageBytes return grpc message from bytes

func GetMessageNumber

func GetMessageNumber(n int64) *api.NumberMessage

GetMessageNumber return grpc message number

func GetPaginatedMessage

func GetPaginatedMessage(offset int64, limit int64) *api.PaginatedMessage

GetPaginatedMessage return grpc message number

Types

type AvailableResources

type AvailableResources struct {
	Energy         decimal.Decimal `json:"energy"`
	Bandwidth      decimal.Decimal `json:"bandwidth"`
	TotalEnergy    decimal.Decimal `json:"total_energy"`
	TotalBandwidth decimal.Decimal `json:"total_bandwidth"`
}

AvailableResources represents the resources of an account

type ChainParams

type ChainParams struct {
	EnergyFee                           int64
	TransactionFee                      int64
	TotalEnergyCurrentLimit             int64
	FreeNetLimit                        int64
	CreateNewAccountFeeInSystemContract int64
	CreateAccountFee                    int64
}

type Client

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

Client represents a Tron blockchain client

func New

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

New creates a new Tron client with the given configuration.

By default, requests are routed by HealthAwareTransport: nodes are grouped by NodeConfig.Tier, the lowest-numbered tier with at least one healthy node is used, and a background health-checker tracks every node's status. To restore the legacy plain round-robin (no health-checking, NodeConfig.Tier ignored), set cfg.Health.Disabled = true.

func (*Client) AvailableBandwidth

func (c *Client) AvailableBandwidth(res *api.AccountResourceMessage) decimal.Decimal

AvailableBandwidth calculates the available bandwidth.

func (*Client) AvailableBandwidthWithoutFree

func (c *Client) AvailableBandwidthWithoutFree(res *api.AccountResourceMessage) decimal.Decimal

func (*Client) AvailableEnergy

func (c *Client) AvailableEnergy(res *api.AccountResourceMessage) decimal.Decimal

AvailableEnergy calculates the available energy.

func (*Client) AvailableForDelegateResources

func (c *Client) AvailableForDelegateResources(ctx context.Context, addr string) (*AvailableResources, error)

func (*Client) BroadcastTransaction

func (c *Client) BroadcastTransaction(ctx context.Context, tx *core.Transaction) (*api.Return, error)

BroadcastTransaction broadcasts a signed transaction to the network

func (*Client) ChainParam

func (c *Client) ChainParam(ctx context.Context, paramKey string) (*core.ChainParameters_ChainParameter, error)

ChainParam get chain parameters

func (*Client) ChainParams

func (c *Client) ChainParams(ctx context.Context) (*ChainParams, error)

func (*Client) Close

func (c *Client) Close() error

Close closes the client connection

func (*Client) ConvertBandwidthToStackedTRX

func (c *Client) ConvertBandwidthToStackedTRX(totalNetWeight, totalNetLimit int64, bandwidth decimal.Decimal) decimal.Decimal

ConvertBandwidthToStackedTRX converts bandwidth to stacked TRX. Returns value in SUN.

func (*Client) ConvertEnergyToStackedTRX

func (c *Client) ConvertEnergyToStackedTRX(totalEnergyCurrentLimit, totalEnergyWeight int64, energy decimal.Decimal) decimal.Decimal

ConvertEnergyToStackedTRX converts energy to stacked TRX. Returns value in SUN.

func (*Client) ConvertStackedTRXToBandwidth

func (c *Client) ConvertStackedTRXToBandwidth(totalNetWeight, totalNetLimit, stackedTrx int64) decimal.Decimal

ConvertStackedTRXToBandwidth converts stacked TRX to bandwidth.

func (*Client) ConvertStackedTRXToEnergy

func (c *Client) ConvertStackedTRXToEnergy(totalEnergyCurrentLimit, totalEnergyWeight, stackedTrx int64) decimal.Decimal

ConvertStackedTRXToEnergy converts stacked TRX to energy.

func (*Client) CreateAccount

func (c *Client) CreateAccount(ctx context.Context, from, addr string, accountType core.AccountType) (*api.TransactionExtention, error)

CreateAccount creates a new account on the blockchain.

func (*Client) CreateTransferTransaction

func (c *Client) CreateTransferTransaction(ctx context.Context, from, to string, amount decimal.Decimal) (*api.TransactionExtention, error)

CreateTransferTransaction creates a TRX transfer transaction

Important! The amount is specified in TRX.

func (*Client) DelegateResource

func (c *Client) DelegateResource(ctx context.Context, owner, receiver string, resource ResourceType, delegateBalance int64, lock bool, lockPeriod int64) (*api.TransactionExtention, error)

DelegateResource delegates a resource from one account to another

func (*Client) DeployContract

func (c *Client) DeployContract(ctx context.Context, from, contractName string,
	abi *core.SmartContract_ABI, codeStr string,
	feeLimit, curPercent, oeLimit int64,
) (*api.TransactionExtention, error)

DeployContract and return tx result

func (*Client) EstimateActivateAccount

func (c *Client) EstimateActivateAccount(ctx context.Context, fromAddress, toAddress string) (*EstimateActivateAccountResult, error)

EstimateActivateAccount estimates the activation fee for a Tron address. It checks the available bandwidth and adds the activation fee accordingly. The fee is returned in TRX (1 TRX = 1_000_000 SUN). We assume that fromAddress is ALWAYS activated, being it processing address. Simple swap of arg to BlackHoleAddress on fakeTx creation will always return valid tx.

func (*Client) EstimateActivationFee

func (t *Client) EstimateActivationFee(ctx context.Context, fromAddress, toAddress string) (*EstimateResult, error)

EstimateActivationFee estimates the activation fee for a Tron address. It checks the available bandwidth and adds the activation fee accordingly. The fee is returned in TRX (1 TRX = 1_000_000 SUN). We assume that fromAddress is ALWAYS activated, being it processing address. Simple swap of arg to BlackHoleAddress on fakeTx creation will always return valid tx.

func (*Client) EstimateBandwidth

func (c *Client) EstimateBandwidth(tx *core.Transaction) (decimal.Decimal, error)

EstimateBandwidth calculates the estimated bandwidth.

func (*Client) EstimateEnergy

func (c *Client) EstimateEnergy(ctx context.Context, from, contractAddress, method, jsonString string,
	tAmount int64, tTokenID string, tTokenAmount int64,
) (*api.EstimateEnergyMessage, error)

EstimateEnergy returns enery required

func (*Client) EstimateSystemContractActivation

func (t *Client) EstimateSystemContractActivation(ctx context.Context, caller string, receiver string) (*EstimateResult, error)

EstimateSystemContractActivation estimates the activation fee for a Tron address by building a real CreateAccount transaction via the node API (instead of the local fake transaction used by EstimateActivationFee). The fee is returned in TRX (1 TRX = 1_000_000 SUN).

func (*Client) EstimateTransfer

func (c *Client) EstimateTransfer(
	ctx context.Context,
	fromAddress, toAddress, contractAddress string,
	amount decimal.Decimal,
	decimals int64,
) (*EstimateTransferResult, error)

func (*Client) GetAccount

func (c *Client) GetAccount(ctx context.Context, addr string) (*core.Account, error)

func (*Client) GetAccountBalance

func (c *Client) GetAccountBalance(ctx context.Context, address string) (decimal.Decimal, error)

GetAccountBalance retrieves the TRX balance of the specified address

func (*Client) GetAccountResource

func (c *Client) GetAccountResource(ctx context.Context, addr string) (*api.AccountResourceMessage, error)

GetAccountResource retrieves resource information for the specified account address

func (*Client) GetAssetIssueById

func (c *Client) GetAssetIssueById(ctx context.Context, id string) (*core.AssetIssueContract, error)

GetAssetIssueById returns TRC10 asset information by its ID

func (*Client) GetAssetIssueListByName

func (c *Client) GetAssetIssueListByName(ctx context.Context, name string) (*api.AssetIssueList, error)

GetAssetIssueListByName returns list of TRC10 assets matching the given name

func (*Client) GetBlockByHash

func (c *Client) GetBlockByHash(ctx context.Context, hash []byte) (*core.Block, error)

GetBlockByHash returns block by its hash.

func (*Client) GetBlockByHeight

func (c *Client) GetBlockByHeight(ctx context.Context, height uint64) (*api.BlockExtention, error)

GetBlockByHeight returns block by its number.

func (*Client) GetBlockByLatestNum2

func (c *Client) GetBlockByLatestNum2(ctx context.Context, height uint64) (*api.BlockListExtention, error)

GetBlockByLatestNum returns the latest 'num' blocks.

func (*Client) GetBlockByLimitNext2

func (c *Client) GetBlockByLimitNext2(ctx context.Context, start uint64, end uint64) (*api.BlockListExtention, error)

GetBlockByLimitNext returns blocks in the range [start, start+limit).

func (*Client) GetCanDelegatedMaxSize

func (c *Client) GetCanDelegatedMaxSize(ctx context.Context, address string, resource int32) (*api.CanDelegatedMaxSizeResponseMessage, error)

GetCanDelegatedMaxSize retrieves the maximum size that can be delegated for a given resource type

func (*Client) GetContract

func (c *Client) GetContract(ctx context.Context, contractAddress string) (*core.SmartContract, error)

GetContract returns smart contract information by address

func (*Client) GetContractABI

func (c *Client) GetContractABI(ctx context.Context, contractAddress string) (*core.SmartContract_ABI, error)

GetContractABI return smartContract

func (*Client) GetDelegatedResources

func (c *Client) GetDelegatedResources(ctx context.Context, address string) ([]*api.DelegatedResourceList, error)

GetDelegatedResourcesV2 retrieves delegated resources for the specified account address

func (*Client) GetDelegatedResourcesV2

func (c *Client) GetDelegatedResourcesV2(ctx context.Context, address string) ([]*api.DelegatedResourceList, error)

GetDelegatedResourcesV2 retrieves delegated resources V2 for the specified account address

func (*Client) GetLastBlock

func (c *Client) GetLastBlock(ctx context.Context) (*api.BlockExtention, error)

GetLastBlock return last block from the blockchain.

func (*Client) GetLastBlockHeight

func (c *Client) GetLastBlockHeight(ctx context.Context) (uint64, error)

GetLastBlockHeight return last block number from the blockchain.

func (*Client) GetNetwork

func (c *Client) GetNetwork() Network

GetNetwork returns the current network based on configuration

func (*Client) GetNextMaintenanceTime

func (c *Client) GetNextMaintenanceTime(ctx context.Context) (*api.NumberMessage, error)

GetNextMaintenanceTime get next epoch timestamp

func (*Client) GetNodeInfo

func (c *Client) GetNodeInfo(ctx context.Context) (*core.NodeInfo, error)

GetNodeInfo returns information about the connected Tron node.

func (*Client) GetTransactionByHash

func (c *Client) GetTransactionByHash(ctx context.Context, hash string) (*core.Transaction, error)

GetTransactionByHash returns transaction details by hash

func (*Client) GetTransactionExtensionByHash

func (c *Client) GetTransactionExtensionByHash(ctx context.Context, hash string) (*api.TransactionExtention, *core.TransactionInfo, error)

func (*Client) GetTransactionInfoByBlockNum

func (c *Client) GetTransactionInfoByBlockNum(ctx context.Context, number uint64) (*api.TransactionInfoList, error)

GetTransactionInfoByBlockNum returns transaction info list by block number.

func (*Client) GetTransactionInfoByHash

func (c *Client) GetTransactionInfoByHash(ctx context.Context, hash string) (*core.TransactionInfo, error)

GetTransactionInfoByHash returns transaction receipt by hash

func (*Client) IsAccountActivated

func (c *Client) IsAccountActivated(ctx context.Context, address string) (bool, error)

IsAccountActivated checks if the account with the given address is activated

func (*Client) ListNodes

func (c *Client) ListNodes(ctx context.Context) (*api.NodeList, error)

ListNodes provides list of network nodes

func (*Client) ParseTRC20NumericProperty

func (c *Client) ParseTRC20NumericProperty(data string) (*big.Int, error)

ParseTRC20NumericProperty get number from data

func (*Client) ParseTRC20StringProperty

func (c *Client) ParseTRC20StringProperty(data string) (string, error)

ParseTRC20StringProperty get string from data

func (*Client) ReclaimResource

func (c *Client) ReclaimResource(ctx context.Context, owner, receiver string, resource ResourceType, delegateBalance int64) (*api.TransactionExtention, error)

ReclaimResource reclaims a delegated resource from one account to another

func (*Client) SignTransaction

func (c *Client) SignTransaction(tx *core.Transaction, privateKey *ecdsa.PrivateKey) error

SignTransaction signs a raw transaction with the given private key

func (*Client) TRC20Approve

func (c *Client) TRC20Approve(ctx context.Context, from, to, contract string, amount decimal.Decimal, feeLimit int64) (*api.TransactionExtention, error)

TRC20Approve approve token to address

func (*Client) TRC20Call

func (c *Client) TRC20Call(ctx context.Context, from, contractAddress, data string, constant bool, feeLimit int64) (*api.TransactionExtention, error)

func (*Client) TRC20ContractBalance

func (c *Client) TRC20ContractBalance(ctx context.Context, addr, contractAddress string) (*big.Int, error)

TRC20ContractBalance get Address balance

func (*Client) TRC20GetDecimals

func (c *Client) TRC20GetDecimals(ctx context.Context, contractAddress string) (*big.Int, error)

TRC20GetDecimals get contract decimals

func (*Client) TRC20GetName

func (c *Client) TRC20GetName(ctx context.Context, contractAddress string) (string, error)

TRC20GetName get token name

func (*Client) TRC20GetSymbol

func (c *Client) TRC20GetSymbol(ctx context.Context, contractAddress string) (string, error)

TRC20GetSymbol get contract symbol

func (*Client) TRC20Send

func (c *Client) TRC20Send(ctx context.Context, from, to, contract string, amount decimal.Decimal, feeLimit int64) (*api.TransactionExtention, error)

func (*Client) TRC20TransferFrom

func (c *Client) TRC20TransferFrom(ctx context.Context, owner, from, to, contract string, amount *big.Int, feeLimit int64) (*api.TransactionExtention, error)

func (*Client) TotalAvailableResources

func (c *Client) TotalAvailableResources(ctx context.Context, addr string) (*AvailableResources, error)

TotalAvailableResources calculates the total available resources for the account.

func (*Client) TotalBandwidthLimit

func (c *Client) TotalBandwidthLimit(res *api.AccountResourceMessage) decimal.Decimal

func (*Client) TotalEnergyLimit

func (c *Client) TotalEnergyLimit(res *api.AccountResourceMessage) decimal.Decimal

func (*Client) TotalTransaction

func (c *Client) TotalTransaction(ctx context.Context) (*api.NumberMessage, error)

TotalTransaction return total transciton in network

func (*Client) TriggerConstantContract

func (c *Client) TriggerConstantContract(ctx context.Context, ct *core.TriggerSmartContract) (*api.TransactionExtention, error)

TriggerConstantContract and return tx result

func (*Client) TriggerConstantContractCustom

func (c *Client) TriggerConstantContractCustom(ctx context.Context, from, contractAddress, method, jsonString string) (*api.TransactionExtention, error)

TriggerConstantContractCustom and return tx result

func (*Client) TriggerContract

func (c *Client) TriggerContract(ctx context.Context, from, contractAddress, method, jsonString string,
	feeLimit, tAmount int64, tTokenID string, tTokenAmount int64,
) (*api.TransactionExtention, error)

TriggerContract and return tx result

func (*Client) UpdateEnergyLimitContract

func (c *Client) UpdateEnergyLimitContract(ctx context.Context, from, contractAddress string, value int64) (*api.TransactionExtention, error)

UpdateEnergyLimitContract update contract enery limit

func (*Client) UpdateHash

func (c *Client) UpdateHash(tx *api.TransactionExtention) error

UpdateHash after local changes

func (*Client) UpdateSettingContract

func (c *Client) UpdateSettingContract(ctx context.Context, from, contractAddress string, value int64) (*api.TransactionExtention, error)

UpdateSettingContract change contract owner consumption ratio

type Config

type Config struct {
	// Nodes is a list of node configurations
	// Round-robin load balancing is used across all nodes
	Nodes []NodeConfig

	// Network specifies the Tron network type (informational only)
	Network Network

	// Blockchain identifies this blockchain for metrics labels.
	// Default: "tron"
	Blockchain string

	// Metrics is an optional metrics collector.
	// If nil, no metrics are collected.
	// Use NewMetrics() for built-in Prometheus metrics,
	// or provide a custom MetricsCollector implementation.
	Metrics MetricsCollector

	// Health configures the per-node health-checker and tier-based fallback.
	// Zero value means "use sane defaults": health-checker is enabled,
	// FailureThreshold/SuccessThreshold = 2, HealthyInterval = 30s,
	// UnhealthyInterval = 5s, InactiveTierInterval = 5m, ProbeTimeout = 5s,
	// Probe = GetNowBlock, ClassifyErr = isNetworkError.
	// To completely disable the health-checker (and use the legacy
	// RoundRobinTransport behaviour 1:1), set Health.Disabled = true.
	Health HealthConfig
}

Config holds the configuration for the Tron client

func (Config) Validate

func (c Config) Validate() error

Validate validates the client configuration

type EstimateActivateAccountResult

type EstimateActivateAccountResult struct {
	Energy    decimal.Decimal `json:"energy"`
	Bandwidth decimal.Decimal `json:"bandwidth"`
	Trx       decimal.Decimal `json:"trx"`
}

type EstimateResult

type EstimateResult struct {
	Energy    decimal.Decimal `json:"energy"`
	Bandwidth decimal.Decimal `json:"bandwidth"`
	Trx       decimal.Decimal `json:"trx"`
}

type EstimateTransferResult

type EstimateTransferResult struct {
	Total      EstimateResult `json:"total"`
	Transfer   EstimateResult `json:"transfer"`
	Activation EstimateResult `json:"activation"`
}

EstimateTransferResult contains the estimated cost of a TRX/TRC20 transfer broken down into the transfer itself and the recipient activation (when toAddress is not yet activated). Total is the sum of Transfer and Activation per resource.

For activated recipients Activation is zero-valued and Total equals Transfer.

Note: in Tron, when sending to an unactivated address the activation fee is consumed by the transfer transaction itself rather than a separate CreateAccount call. Total is therefore a conservative upper bound — the real on-chain cost is typically slightly lower than Total.

type GRPCTransport

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

GRPCTransport implements Transport using gRPC protocol

func NewGRPCTransport

func NewGRPCTransport(cfg NodeConfig) (*GRPCTransport, error)

NewGRPCTransport creates a new gRPC transport

func (*GRPCTransport) BroadcastTransaction

func (t *GRPCTransport) BroadcastTransaction(ctx context.Context, tx *core.Transaction) (*api.Return, error)

func (*GRPCTransport) Close

func (t *GRPCTransport) Close() error

Close closes the gRPC connection

func (*GRPCTransport) CreateAccount

func (*GRPCTransport) CreateTransaction

func (t *GRPCTransport) CreateTransaction(ctx context.Context, contract *core.TransferContract) (*api.TransactionExtention, error)

func (*GRPCTransport) DelegateResource

func (t *GRPCTransport) DelegateResource(ctx context.Context, contract *core.DelegateResourceContract) (*api.TransactionExtention, error)

func (*GRPCTransport) DeployContract

func (t *GRPCTransport) DeployContract(ctx context.Context, contract *core.CreateSmartContract) (*api.TransactionExtention, error)

func (*GRPCTransport) EstimateEnergy

func (t *GRPCTransport) EstimateEnergy(ctx context.Context, contract *core.TriggerSmartContract) (*api.EstimateEnergyMessage, error)

func (*GRPCTransport) GetAccount

func (t *GRPCTransport) GetAccount(ctx context.Context, account *core.Account) (*core.Account, error)

func (*GRPCTransport) GetAccountResource

func (t *GRPCTransport) GetAccountResource(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*GRPCTransport) GetAccountResourceMessage

func (t *GRPCTransport) GetAccountResourceMessage(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*GRPCTransport) GetAssetIssueById

func (t *GRPCTransport) GetAssetIssueById(ctx context.Context, id []byte) (*core.AssetIssueContract, error)

func (*GRPCTransport) GetAssetIssueListByName

func (t *GRPCTransport) GetAssetIssueListByName(ctx context.Context, name []byte) (*api.AssetIssueList, error)

func (*GRPCTransport) GetBlockById

func (t *GRPCTransport) GetBlockById(ctx context.Context, id []byte) (*core.Block, error)

func (*GRPCTransport) GetBlockByLatestNum

func (t *GRPCTransport) GetBlockByLatestNum(ctx context.Context, num int64) (*api.BlockListExtention, error)

func (*GRPCTransport) GetBlockByLimitNext

func (t *GRPCTransport) GetBlockByLimitNext(ctx context.Context, start, end int64) (*api.BlockListExtention, error)

func (*GRPCTransport) GetBlockByNum

func (t *GRPCTransport) GetBlockByNum(ctx context.Context, num int64) (*api.BlockExtention, error)

func (*GRPCTransport) GetChainParameters

func (t *GRPCTransport) GetChainParameters(ctx context.Context) (*core.ChainParameters, error)

func (*GRPCTransport) GetContract

func (t *GRPCTransport) GetContract(ctx context.Context, address []byte) (*core.SmartContract, error)

func (*GRPCTransport) GetDelegatedResource

func (*GRPCTransport) GetDelegatedResourceAccountIndex

func (t *GRPCTransport) GetDelegatedResourceAccountIndex(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*GRPCTransport) GetDelegatedResourceAccountIndexV2

func (t *GRPCTransport) GetDelegatedResourceAccountIndexV2(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*GRPCTransport) GetDelegatedResourceV2

func (t *GRPCTransport) GetDelegatedResourceV2(ctx context.Context, msg *api.DelegatedResourceMessage) (*api.DelegatedResourceList, error)

func (*GRPCTransport) GetNextMaintenanceTime

func (t *GRPCTransport) GetNextMaintenanceTime(ctx context.Context) (*api.NumberMessage, error)

func (*GRPCTransport) GetNodeInfo

func (t *GRPCTransport) GetNodeInfo(ctx context.Context) (*core.NodeInfo, error)

func (*GRPCTransport) GetNowBlock

func (t *GRPCTransport) GetNowBlock(ctx context.Context) (*api.BlockExtention, error)

func (*GRPCTransport) GetTransactionById

func (t *GRPCTransport) GetTransactionById(ctx context.Context, id []byte) (*core.Transaction, error)

func (*GRPCTransport) GetTransactionInfoByBlockNum

func (t *GRPCTransport) GetTransactionInfoByBlockNum(ctx context.Context, num int64) (*api.TransactionInfoList, error)

func (*GRPCTransport) GetTransactionInfoById

func (t *GRPCTransport) GetTransactionInfoById(ctx context.Context, id []byte) (*core.TransactionInfo, error)

func (*GRPCTransport) ListNodes

func (t *GRPCTransport) ListNodes(ctx context.Context) (*api.NodeList, error)

func (*GRPCTransport) TotalTransaction

func (t *GRPCTransport) TotalTransaction(ctx context.Context) (*api.NumberMessage, error)

func (*GRPCTransport) TriggerConstantContract

func (t *GRPCTransport) TriggerConstantContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)

func (*GRPCTransport) TriggerContract

func (t *GRPCTransport) TriggerContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)

func (*GRPCTransport) UnDelegateResource

func (t *GRPCTransport) UnDelegateResource(ctx context.Context, contract *core.UnDelegateResourceContract) (*api.TransactionExtention, error)

func (*GRPCTransport) UpdateEnergyLimit

func (t *GRPCTransport) UpdateEnergyLimit(ctx context.Context, contract *core.UpdateEnergyLimitContract) (*api.TransactionExtention, error)

func (*GRPCTransport) UpdateSetting

func (*GRPCTransport) WalletClient

func (t *GRPCTransport) WalletClient() api.WalletClient

WalletClient returns the underlying WalletClient for direct access

type HTTPStatusError

type HTTPStatusError struct {
	// Code is the HTTP status code (e.g. 503).
	Code int
	// Body is the raw response body — kept for diagnostics.
	Body string
}

HTTPStatusError is returned by HTTPTransport when the remote responds with a non-2xx status. It is wrapped in a TransportError before reaching the caller, so use errors.AsType[*HTTPStatusError](err) to inspect the status code.

The health-checker's default classifier treats 5xx, 408 and 429 as network-level failures (count toward the unhealthy threshold) and other 4xx codes as logical errors (do not affect node health).

func (*HTTPStatusError) Error

func (e *HTTPStatusError) Error() string

type HTTPTransport

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

HTTPTransport implements Transport using HTTP REST API

func NewHTTPTransport

func NewHTTPTransport(cfg NodeConfig) (*HTTPTransport, error)

NewHTTPTransport creates a new HTTP transport

func (*HTTPTransport) BroadcastTransaction

func (t *HTTPTransport) BroadcastTransaction(ctx context.Context, tx *core.Transaction) (*api.Return, error)

func (*HTTPTransport) Close

func (t *HTTPTransport) Close() error

Close closes the HTTP transport (no-op for HTTP)

func (*HTTPTransport) CreateAccount

func (*HTTPTransport) CreateTransaction

func (t *HTTPTransport) CreateTransaction(ctx context.Context, contract *core.TransferContract) (*api.TransactionExtention, error)

func (*HTTPTransport) DelegateResource

func (t *HTTPTransport) DelegateResource(ctx context.Context, contract *core.DelegateResourceContract) (*api.TransactionExtention, error)

func (*HTTPTransport) DeployContract

func (t *HTTPTransport) DeployContract(ctx context.Context, contract *core.CreateSmartContract) (*api.TransactionExtention, error)

func (*HTTPTransport) EstimateEnergy

func (t *HTTPTransport) EstimateEnergy(ctx context.Context, contract *core.TriggerSmartContract) (*api.EstimateEnergyMessage, error)

func (*HTTPTransport) GetAccount

func (t *HTTPTransport) GetAccount(ctx context.Context, account *core.Account) (*core.Account, error)

func (*HTTPTransport) GetAccountResource

func (t *HTTPTransport) GetAccountResource(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*HTTPTransport) GetAccountResourceMessage

func (t *HTTPTransport) GetAccountResourceMessage(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*HTTPTransport) GetAssetIssueById

func (t *HTTPTransport) GetAssetIssueById(ctx context.Context, id []byte) (*core.AssetIssueContract, error)

func (*HTTPTransport) GetAssetIssueListByName

func (t *HTTPTransport) GetAssetIssueListByName(ctx context.Context, name []byte) (*api.AssetIssueList, error)

func (*HTTPTransport) GetBlockById

func (t *HTTPTransport) GetBlockById(ctx context.Context, id []byte) (*core.Block, error)

func (*HTTPTransport) GetBlockByLatestNum

func (t *HTTPTransport) GetBlockByLatestNum(ctx context.Context, num int64) (*api.BlockListExtention, error)

func (*HTTPTransport) GetBlockByLimitNext

func (t *HTTPTransport) GetBlockByLimitNext(ctx context.Context, start, end int64) (*api.BlockListExtention, error)

func (*HTTPTransport) GetBlockByNum

func (t *HTTPTransport) GetBlockByNum(ctx context.Context, num int64) (*api.BlockExtention, error)

func (*HTTPTransport) GetChainParameters

func (t *HTTPTransport) GetChainParameters(ctx context.Context) (*core.ChainParameters, error)

func (*HTTPTransport) GetContract

func (t *HTTPTransport) GetContract(ctx context.Context, address []byte) (*core.SmartContract, error)

func (*HTTPTransport) GetDelegatedResource

func (*HTTPTransport) GetDelegatedResourceAccountIndex

func (t *HTTPTransport) GetDelegatedResourceAccountIndex(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*HTTPTransport) GetDelegatedResourceAccountIndexV2

func (t *HTTPTransport) GetDelegatedResourceAccountIndexV2(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*HTTPTransport) GetDelegatedResourceV2

func (t *HTTPTransport) GetDelegatedResourceV2(ctx context.Context, msg *api.DelegatedResourceMessage) (*api.DelegatedResourceList, error)

func (*HTTPTransport) GetNextMaintenanceTime

func (t *HTTPTransport) GetNextMaintenanceTime(ctx context.Context) (*api.NumberMessage, error)

func (*HTTPTransport) GetNodeInfo

func (t *HTTPTransport) GetNodeInfo(ctx context.Context) (*core.NodeInfo, error)

func (*HTTPTransport) GetNowBlock

func (t *HTTPTransport) GetNowBlock(ctx context.Context) (*api.BlockExtention, error)

func (*HTTPTransport) GetTransactionById

func (t *HTTPTransport) GetTransactionById(ctx context.Context, id []byte) (*core.Transaction, error)

func (*HTTPTransport) GetTransactionInfoByBlockNum

func (t *HTTPTransport) GetTransactionInfoByBlockNum(ctx context.Context, num int64) (*api.TransactionInfoList, error)

func (*HTTPTransport) GetTransactionInfoById

func (t *HTTPTransport) GetTransactionInfoById(ctx context.Context, id []byte) (*core.TransactionInfo, error)

func (*HTTPTransport) ListNodes

func (t *HTTPTransport) ListNodes(ctx context.Context) (*api.NodeList, error)

func (*HTTPTransport) TotalTransaction

func (t *HTTPTransport) TotalTransaction(ctx context.Context) (*api.NumberMessage, error)

func (*HTTPTransport) TriggerConstantContract

func (t *HTTPTransport) TriggerConstantContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)

func (*HTTPTransport) TriggerContract

func (t *HTTPTransport) TriggerContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)

func (*HTTPTransport) UnDelegateResource

func (t *HTTPTransport) UnDelegateResource(ctx context.Context, contract *core.UnDelegateResourceContract) (*api.TransactionExtention, error)

func (*HTTPTransport) UpdateEnergyLimit

func (t *HTTPTransport) UpdateEnergyLimit(ctx context.Context, contract *core.UpdateEnergyLimitContract) (*api.TransactionExtention, error)

func (*HTTPTransport) UpdateSetting

type HealthAwareTransport

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

HealthAwareTransport selects the next underlying Transport across multiple nodes grouped by NodeConfig.Tier. Lower-numbered tiers are preferred: requests are routed to the lowest tier that has at least one healthy node. A higher tier is only used when every node of every lower tier is currently marked unhealthy.

A background health-checker probes every node periodically (one goroutine per node, started in the constructor and stopped by Close). Probe cadence depends on node state and tier: HealthyInterval for the active tier, InactiveTierInterval for healthy fallbacks, UnhealthyInterval for any unhealthy node. Live RPC outcomes also feed the per-node thresholds, so reality and probes converge quickly.

func NewHealthAwareTransport

func NewHealthAwareTransport(
	nodes []NodeConfig,
	factory func(NodeConfig) (Transport, error),
	cfg HealthConfig,
	metrics MetricsCollector,
	blockchain string,
) (*HealthAwareTransport, error)

NewHealthAwareTransport builds a HealthAwareTransport from a list of node configs. factory is called once per node to construct the underlying Transport (typically createTransportFromNode). cfg defaults are filled in when fields are zero. If cfg.Disabled is true, callers should skip this constructor entirely and build a RoundRobinTransport instead — the field is honored here for symmetry only by stopping the background loops.

On error, any transports already created are closed.

func (*HealthAwareTransport) BroadcastTransaction

func (h *HealthAwareTransport) BroadcastTransaction(ctx context.Context, tx *core.Transaction) (*api.Return, error)

func (*HealthAwareTransport) Close

func (h *HealthAwareTransport) Close() error

Close stops the health-check loops, waits for them to exit, and closes every underlying transport. Safe to call multiple times.

func (*HealthAwareTransport) CreateAccount

func (*HealthAwareTransport) CreateTransaction

func (h *HealthAwareTransport) CreateTransaction(ctx context.Context, contract *core.TransferContract) (*api.TransactionExtention, error)

func (*HealthAwareTransport) DelegateResource

func (*HealthAwareTransport) DeployContract

func (*HealthAwareTransport) EstimateEnergy

func (*HealthAwareTransport) GetAccount

func (h *HealthAwareTransport) GetAccount(ctx context.Context, account *core.Account) (*core.Account, error)

func (*HealthAwareTransport) GetAccountResource

func (h *HealthAwareTransport) GetAccountResource(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*HealthAwareTransport) GetAccountResourceMessage

func (h *HealthAwareTransport) GetAccountResourceMessage(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*HealthAwareTransport) GetAssetIssueById

func (h *HealthAwareTransport) GetAssetIssueById(ctx context.Context, id []byte) (*core.AssetIssueContract, error)

func (*HealthAwareTransport) GetAssetIssueListByName

func (h *HealthAwareTransport) GetAssetIssueListByName(ctx context.Context, name []byte) (*api.AssetIssueList, error)

func (*HealthAwareTransport) GetBlockById

func (h *HealthAwareTransport) GetBlockById(ctx context.Context, id []byte) (*core.Block, error)

func (*HealthAwareTransport) GetBlockByLatestNum

func (h *HealthAwareTransport) GetBlockByLatestNum(ctx context.Context, num int64) (*api.BlockListExtention, error)

func (*HealthAwareTransport) GetBlockByLimitNext

func (h *HealthAwareTransport) GetBlockByLimitNext(ctx context.Context, start, end int64) (*api.BlockListExtention, error)

func (*HealthAwareTransport) GetBlockByNum

func (h *HealthAwareTransport) GetBlockByNum(ctx context.Context, num int64) (*api.BlockExtention, error)

func (*HealthAwareTransport) GetChainParameters

func (h *HealthAwareTransport) GetChainParameters(ctx context.Context) (*core.ChainParameters, error)

func (*HealthAwareTransport) GetContract

func (h *HealthAwareTransport) GetContract(ctx context.Context, address []byte) (*core.SmartContract, error)

func (*HealthAwareTransport) GetDelegatedResource

func (*HealthAwareTransport) GetDelegatedResourceAccountIndex

func (h *HealthAwareTransport) GetDelegatedResourceAccountIndex(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*HealthAwareTransport) GetDelegatedResourceAccountIndexV2

func (h *HealthAwareTransport) GetDelegatedResourceAccountIndexV2(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*HealthAwareTransport) GetDelegatedResourceV2

func (*HealthAwareTransport) GetNextMaintenanceTime

func (h *HealthAwareTransport) GetNextMaintenanceTime(ctx context.Context) (*api.NumberMessage, error)

func (*HealthAwareTransport) GetNodeInfo

func (h *HealthAwareTransport) GetNodeInfo(ctx context.Context) (*core.NodeInfo, error)

func (*HealthAwareTransport) GetNowBlock

func (h *HealthAwareTransport) GetNowBlock(ctx context.Context) (*api.BlockExtention, error)

func (*HealthAwareTransport) GetTransactionById

func (h *HealthAwareTransport) GetTransactionById(ctx context.Context, id []byte) (*core.Transaction, error)

func (*HealthAwareTransport) GetTransactionInfoByBlockNum

func (h *HealthAwareTransport) GetTransactionInfoByBlockNum(ctx context.Context, num int64) (*api.TransactionInfoList, error)

func (*HealthAwareTransport) GetTransactionInfoById

func (h *HealthAwareTransport) GetTransactionInfoById(ctx context.Context, id []byte) (*core.TransactionInfo, error)

func (*HealthAwareTransport) ListNodes

func (h *HealthAwareTransport) ListNodes(ctx context.Context) (*api.NodeList, error)

func (*HealthAwareTransport) TotalTransaction

func (h *HealthAwareTransport) TotalTransaction(ctx context.Context) (*api.NumberMessage, error)

func (*HealthAwareTransport) TriggerConstantContract

func (h *HealthAwareTransport) TriggerConstantContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)

func (*HealthAwareTransport) TriggerContract

func (*HealthAwareTransport) UnDelegateResource

func (*HealthAwareTransport) UpdateEnergyLimit

func (*HealthAwareTransport) UpdateSetting

type HealthConfig

type HealthConfig struct {
	// Disabled, if true, switches the client back to the legacy RoundRobinTransport
	// (no background probes, no per-node health state, NodeConfig.Tier ignored).
	Disabled bool

	// FailureThreshold is the number of consecutive network-level failures
	// (probe or live request) required to mark a node unhealthy. Default 2.
	FailureThreshold int

	// SuccessThreshold is the number of consecutive successes (probe or live
	// request) required to bring an unhealthy node back to the pool. Default 2.
	SuccessThreshold int

	// HealthyInterval is the probe interval for healthy nodes whose tier is the
	// active tier (i.e. currently serving traffic). Default 30s.
	HealthyInterval time.Duration

	// UnhealthyInterval is the probe interval for any unhealthy node, regardless
	// of tier. Tighter so recovery is detected quickly. Default 5s.
	UnhealthyInterval time.Duration

	// InactiveTierInterval is the probe interval for healthy nodes that belong
	// to an inactive (lower-priority) tier — i.e. fallbacks not currently
	// serving traffic. Looser to save rate-limit/billing on fallback nodes.
	// Default 5m.
	InactiveTierInterval time.Duration

	// ProbeTimeout bounds a single health-probe invocation. Default 5s.
	ProbeTimeout time.Duration

	// Probe is the function used as a health-check. By default, GetNowBlock(ctx).
	// Custom probes must do a read-only call and return an error when the node
	// is misbehaving.
	Probe func(ctx context.Context, t Transport) error

	// ClassifyErr decides whether a given error counts as a network-level
	// failure. By default, isNetworkError covers gRPC status codes,
	// context.DeadlineExceeded, net.Error, io.EOF, net.ErrClosed and the
	// HTTPStatusError 5xx/408/429 family.
	ClassifyErr func(err error) bool

	// Logger receives informational events on node state transitions and tier
	// shifts via Infof. nil means a no-op logger is used (silent).
	Logger Logger
}

HealthConfig configures the health-checker and tier-based fallback behaviour. Zero value is valid — defaults are filled in by NewHealthAwareTransport.

type Logger

type Logger interface {
	Infof(format string, args ...any)
}

Logger is the minimal interface HealthAwareTransport uses to emit informational events (node state transitions, tier shifts, recovered probe panics). HealthConfig.Logger defaults to a no-op when left nil; supply your own implementation to bridge to slog, log, zap, or any other backend.

type Metrics

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

Metrics contains built-in Prometheus metrics for RPC monitoring. It implements MetricsCollector.

func NewMetrics

func NewMetrics(reg prometheus.Registerer) *Metrics

NewMetrics creates and registers Prometheus metrics.

func (*Metrics) DecInFlight

func (m *Metrics) DecInFlight()

DecInFlight decrements the in-flight requests counter.

func (*Metrics) IncInFlight

func (m *Metrics) IncInFlight()

IncInFlight increments the in-flight requests counter.

func (*Metrics) RecordRequest

func (m *Metrics) RecordRequest(blockchain, method, status string, duration time.Duration)

RecordRequest records metrics for an RPC request.

func (*Metrics) RecordRetry

func (m *Metrics) RecordRetry(blockchain, method string)

RecordRetry records a retry attempt.

func (*Metrics) SetPoolHealth

func (m *Metrics) SetPoolHealth(blockchain string, total, healthy, disabled int)

SetPoolHealth updates node pool health metrics.

type MetricsCollector

type MetricsCollector interface {
	// RecordRequest records an RPC request with result.
	// blockchain - the blockchain identifier (e.g., "tron")
	// method - RPC method name
	// status - "success" or "error"
	// duration - request duration
	RecordRequest(blockchain, method, status string, duration time.Duration)

	// RecordRetry records a retry attempt.
	RecordRetry(blockchain, method string)

	// SetPoolHealth updates node pool health metrics.
	SetPoolHealth(blockchain string, total, healthy, disabled int)
}

MetricsCollector defines the interface for collecting RPC metrics. Implementations can use their own Prometheus metrics with custom labels.

type MetricsTransport

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

MetricsTransport wraps a Transport and records metrics for each call.

func NewMetricsTransport

func NewMetricsTransport(transport Transport, metrics MetricsCollector, blockchain string) *MetricsTransport

NewMetricsTransport creates a new metrics-collecting transport wrapper.

func (*MetricsTransport) BroadcastTransaction

func (t *MetricsTransport) BroadcastTransaction(ctx context.Context, tx *core.Transaction) (*api.Return, error)

func (*MetricsTransport) Close

func (t *MetricsTransport) Close() error

Close closes the underlying transport.

func (*MetricsTransport) CreateAccount

func (*MetricsTransport) CreateTransaction

func (t *MetricsTransport) CreateTransaction(ctx context.Context, contract *core.TransferContract) (*api.TransactionExtention, error)

func (*MetricsTransport) DelegateResource

func (*MetricsTransport) DeployContract

func (t *MetricsTransport) DeployContract(ctx context.Context, contract *core.CreateSmartContract) (*api.TransactionExtention, error)

func (*MetricsTransport) EstimateEnergy

func (*MetricsTransport) GetAccount

func (t *MetricsTransport) GetAccount(ctx context.Context, account *core.Account) (*core.Account, error)

func (*MetricsTransport) GetAccountResource

func (t *MetricsTransport) GetAccountResource(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*MetricsTransport) GetAccountResourceMessage

func (t *MetricsTransport) GetAccountResourceMessage(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*MetricsTransport) GetAssetIssueById

func (t *MetricsTransport) GetAssetIssueById(ctx context.Context, id []byte) (*core.AssetIssueContract, error)

func (*MetricsTransport) GetAssetIssueListByName

func (t *MetricsTransport) GetAssetIssueListByName(ctx context.Context, name []byte) (*api.AssetIssueList, error)

func (*MetricsTransport) GetBlockById

func (t *MetricsTransport) GetBlockById(ctx context.Context, id []byte) (*core.Block, error)

func (*MetricsTransport) GetBlockByLatestNum

func (t *MetricsTransport) GetBlockByLatestNum(ctx context.Context, num int64) (*api.BlockListExtention, error)

func (*MetricsTransport) GetBlockByLimitNext

func (t *MetricsTransport) GetBlockByLimitNext(ctx context.Context, startBlock, end int64) (*api.BlockListExtention, error)

func (*MetricsTransport) GetBlockByNum

func (t *MetricsTransport) GetBlockByNum(ctx context.Context, num int64) (*api.BlockExtention, error)

func (*MetricsTransport) GetChainParameters

func (t *MetricsTransport) GetChainParameters(ctx context.Context) (*core.ChainParameters, error)

func (*MetricsTransport) GetContract

func (t *MetricsTransport) GetContract(ctx context.Context, address []byte) (*core.SmartContract, error)

func (*MetricsTransport) GetDelegatedResource

func (*MetricsTransport) GetDelegatedResourceAccountIndex

func (t *MetricsTransport) GetDelegatedResourceAccountIndex(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*MetricsTransport) GetDelegatedResourceAccountIndexV2

func (t *MetricsTransport) GetDelegatedResourceAccountIndexV2(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*MetricsTransport) GetDelegatedResourceV2

func (*MetricsTransport) GetNextMaintenanceTime

func (t *MetricsTransport) GetNextMaintenanceTime(ctx context.Context) (*api.NumberMessage, error)

func (*MetricsTransport) GetNodeInfo

func (t *MetricsTransport) GetNodeInfo(ctx context.Context) (*core.NodeInfo, error)

func (*MetricsTransport) GetNowBlock

func (t *MetricsTransport) GetNowBlock(ctx context.Context) (*api.BlockExtention, error)

func (*MetricsTransport) GetTransactionById

func (t *MetricsTransport) GetTransactionById(ctx context.Context, id []byte) (*core.Transaction, error)

func (*MetricsTransport) GetTransactionInfoByBlockNum

func (t *MetricsTransport) GetTransactionInfoByBlockNum(ctx context.Context, num int64) (*api.TransactionInfoList, error)

func (*MetricsTransport) GetTransactionInfoById

func (t *MetricsTransport) GetTransactionInfoById(ctx context.Context, id []byte) (*core.TransactionInfo, error)

func (*MetricsTransport) ListNodes

func (t *MetricsTransport) ListNodes(ctx context.Context) (*api.NodeList, error)

func (*MetricsTransport) TotalTransaction

func (t *MetricsTransport) TotalTransaction(ctx context.Context) (*api.NumberMessage, error)

func (*MetricsTransport) TriggerConstantContract

func (t *MetricsTransport) TriggerConstantContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)

func (*MetricsTransport) TriggerContract

func (t *MetricsTransport) TriggerContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)

func (*MetricsTransport) UnDelegateResource

func (*MetricsTransport) UpdateEnergyLimit

func (*MetricsTransport) UpdateSetting

type Network

type Network string

Network represents the Tron network type

const (
	// NetworkMainnet represents the Tron mainnet
	NetworkMainnet Network = "mainnet"
	// NetworkShasta represents the Tron testnet (Shasta)
	NetworkShasta Network = "shasta"
	// NetworkNile represents the Tron testnet (Nile)
	NetworkNile Network = "nile"
)

func (Network) String

func (n Network) String() string

String returns the string representation of the network type

func (Network) Validate

func (n Network) Validate() error

Validate validates the network type

type NodeConfig

type NodeConfig struct {
	// Protocol specifies the transport protocol (grpc or http)
	// Default: grpc
	Protocol Protocol

	// Address is the node address
	// For gRPC: "grpc.trongrid.io:50051"
	// For HTTP: "https://api.trongrid.io"
	Address string

	// UseTLS enables TLS for gRPC connections
	UseTLS bool

	// DialOptions are additional gRPC dial options (gRPC only)
	DialOptions []grpc.DialOption

	// HTTPClient allows providing a custom HTTP client (HTTP only)
	HTTPClient *http.Client

	// Headers are custom headers/metadata for requests (HTTP headers and gRPC metadata)
	Headers map[string]string

	// Tier is the priority of this node. 0 = primary, 1 = fallback, 2+ = next.
	// Lower-numbered tiers are preferred: requests are routed to the
	// minimum-numbered tier that has at least one healthy node. A higher tier is
	// only used when every node of every lower tier is unhealthy. Default 0
	// (single primary group, fully backwards compatible).
	Tier int
}

NodeConfig represents configuration for a single node

func (NodeConfig) GetProtocol

func (n NodeConfig) GetProtocol() Protocol

GetProtocol returns the node protocol, defaulting to gRPC

func (NodeConfig) Validate

func (n NodeConfig) Validate() error

Validate validates the node configuration

type Protocol

type Protocol string

Protocol represents the transport protocol type

const (
	// ProtocolGRPC uses gRPC transport (default)
	ProtocolGRPC Protocol = "grpc"
	// ProtocolHTTP uses HTTP REST API transport
	ProtocolHTTP Protocol = "http"
)

type ResourceType

type ResourceType int32

ResourceType represents the type of resource to delegate

const (
	// ResourceTypeBandwidth represents bandwidth resource
	ResourceTypeBandwidth ResourceType = 0
	// ResourceTypeEnergy represents energy resource
	ResourceTypeEnergy ResourceType = 1
)

func (ResourceType) String

func (r ResourceType) String() string

String returns the string representation of the resource type

func (ResourceType) ToProto

func (r ResourceType) ToProto() core.ResourceCode

ToProto converts the resource type to its protobuf representation

func (ResourceType) Validate

func (r ResourceType) Validate() error

Validate validates the resource type

type RoundRobinTransport

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

RoundRobinTransport implements Transport using round-robin load balancing across multiple underlying transports

func NewRoundRobinTransport

func NewRoundRobinTransport(transports []Transport) *RoundRobinTransport

NewRoundRobinTransport creates a new round-robin transport from multiple transports

func (*RoundRobinTransport) BroadcastTransaction

func (t *RoundRobinTransport) BroadcastTransaction(ctx context.Context, tx *core.Transaction) (*api.Return, error)

func (*RoundRobinTransport) Close

func (t *RoundRobinTransport) Close() error

Close closes all underlying transports

func (*RoundRobinTransport) CreateAccount

func (*RoundRobinTransport) CreateTransaction

func (t *RoundRobinTransport) CreateTransaction(ctx context.Context, contract *core.TransferContract) (*api.TransactionExtention, error)

func (*RoundRobinTransport) DelegateResource

func (*RoundRobinTransport) DeployContract

func (*RoundRobinTransport) EstimateEnergy

func (*RoundRobinTransport) GetAccount

func (t *RoundRobinTransport) GetAccount(ctx context.Context, account *core.Account) (*core.Account, error)

func (*RoundRobinTransport) GetAccountResource

func (t *RoundRobinTransport) GetAccountResource(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*RoundRobinTransport) GetAccountResourceMessage

func (t *RoundRobinTransport) GetAccountResourceMessage(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)

func (*RoundRobinTransport) GetAssetIssueById

func (t *RoundRobinTransport) GetAssetIssueById(ctx context.Context, id []byte) (*core.AssetIssueContract, error)

func (*RoundRobinTransport) GetAssetIssueListByName

func (t *RoundRobinTransport) GetAssetIssueListByName(ctx context.Context, name []byte) (*api.AssetIssueList, error)

func (*RoundRobinTransport) GetBlockById

func (t *RoundRobinTransport) GetBlockById(ctx context.Context, id []byte) (*core.Block, error)

func (*RoundRobinTransport) GetBlockByLatestNum

func (t *RoundRobinTransport) GetBlockByLatestNum(ctx context.Context, num int64) (*api.BlockListExtention, error)

func (*RoundRobinTransport) GetBlockByLimitNext

func (t *RoundRobinTransport) GetBlockByLimitNext(ctx context.Context, start, end int64) (*api.BlockListExtention, error)

func (*RoundRobinTransport) GetBlockByNum

func (t *RoundRobinTransport) GetBlockByNum(ctx context.Context, num int64) (*api.BlockExtention, error)

func (*RoundRobinTransport) GetChainParameters

func (t *RoundRobinTransport) GetChainParameters(ctx context.Context) (*core.ChainParameters, error)

func (*RoundRobinTransport) GetContract

func (t *RoundRobinTransport) GetContract(ctx context.Context, address []byte) (*core.SmartContract, error)

func (*RoundRobinTransport) GetDelegatedResource

func (*RoundRobinTransport) GetDelegatedResourceAccountIndex

func (t *RoundRobinTransport) GetDelegatedResourceAccountIndex(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*RoundRobinTransport) GetDelegatedResourceAccountIndexV2

func (t *RoundRobinTransport) GetDelegatedResourceAccountIndexV2(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)

func (*RoundRobinTransport) GetDelegatedResourceV2

func (*RoundRobinTransport) GetNextMaintenanceTime

func (t *RoundRobinTransport) GetNextMaintenanceTime(ctx context.Context) (*api.NumberMessage, error)

func (*RoundRobinTransport) GetNodeInfo

func (t *RoundRobinTransport) GetNodeInfo(ctx context.Context) (*core.NodeInfo, error)

func (*RoundRobinTransport) GetNowBlock

func (t *RoundRobinTransport) GetNowBlock(ctx context.Context) (*api.BlockExtention, error)

func (*RoundRobinTransport) GetTransactionById

func (t *RoundRobinTransport) GetTransactionById(ctx context.Context, id []byte) (*core.Transaction, error)

func (*RoundRobinTransport) GetTransactionInfoByBlockNum

func (t *RoundRobinTransport) GetTransactionInfoByBlockNum(ctx context.Context, num int64) (*api.TransactionInfoList, error)

func (*RoundRobinTransport) GetTransactionInfoById

func (t *RoundRobinTransport) GetTransactionInfoById(ctx context.Context, id []byte) (*core.TransactionInfo, error)

func (*RoundRobinTransport) ListNodes

func (t *RoundRobinTransport) ListNodes(ctx context.Context) (*api.NodeList, error)

func (*RoundRobinTransport) TotalTransaction

func (t *RoundRobinTransport) TotalTransaction(ctx context.Context) (*api.NumberMessage, error)

func (*RoundRobinTransport) TriggerConstantContract

func (t *RoundRobinTransport) TriggerConstantContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)

func (*RoundRobinTransport) TriggerContract

func (*RoundRobinTransport) UnDelegateResource

func (*RoundRobinTransport) UpdateEnergyLimit

func (*RoundRobinTransport) UpdateSetting

type Transport

type Transport interface {
	// Account operations
	GetAccount(ctx context.Context, account *core.Account) (*core.Account, error)
	GetAccountResource(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)
	CreateAccount(ctx context.Context, contract *core.AccountCreateContract) (*api.TransactionExtention, error)

	// Block operations
	GetNowBlock(ctx context.Context) (*api.BlockExtention, error)
	GetBlockByNum(ctx context.Context, num int64) (*api.BlockExtention, error)
	GetBlockById(ctx context.Context, id []byte) (*core.Block, error)
	GetBlockByLimitNext(ctx context.Context, start, end int64) (*api.BlockListExtention, error)
	GetBlockByLatestNum(ctx context.Context, num int64) (*api.BlockListExtention, error)
	GetTransactionInfoByBlockNum(ctx context.Context, num int64) (*api.TransactionInfoList, error)

	// Transaction operations
	GetTransactionById(ctx context.Context, id []byte) (*core.Transaction, error)
	GetTransactionInfoById(ctx context.Context, id []byte) (*core.TransactionInfo, error)
	BroadcastTransaction(ctx context.Context, tx *core.Transaction) (*api.Return, error)
	CreateTransaction(ctx context.Context, contract *core.TransferContract) (*api.TransactionExtention, error)

	// Contract operations
	TriggerContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)
	TriggerConstantContract(ctx context.Context, contract *core.TriggerSmartContract) (*api.TransactionExtention, error)
	EstimateEnergy(ctx context.Context, contract *core.TriggerSmartContract) (*api.EstimateEnergyMessage, error)
	DeployContract(ctx context.Context, contract *core.CreateSmartContract) (*api.TransactionExtention, error)
	GetContract(ctx context.Context, address []byte) (*core.SmartContract, error)
	UpdateSetting(ctx context.Context, contract *core.UpdateSettingContract) (*api.TransactionExtention, error)
	UpdateEnergyLimit(ctx context.Context, contract *core.UpdateEnergyLimitContract) (*api.TransactionExtention, error)

	// Resource operations
	GetAccountResourceMessage(ctx context.Context, account *core.Account) (*api.AccountResourceMessage, error)
	GetDelegatedResource(ctx context.Context, msg *api.DelegatedResourceMessage) (*api.DelegatedResourceList, error)
	GetDelegatedResourceV2(ctx context.Context, msg *api.DelegatedResourceMessage) (*api.DelegatedResourceList, error)
	GetDelegatedResourceAccountIndex(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)
	GetDelegatedResourceAccountIndexV2(ctx context.Context, address []byte) (*core.DelegatedResourceAccountIndex, error)
	GetCanDelegatedMaxSize(ctx context.Context, msg *api.CanDelegatedMaxSizeRequestMessage) (*api.CanDelegatedMaxSizeResponseMessage, error)
	DelegateResource(ctx context.Context, contract *core.DelegateResourceContract) (*api.TransactionExtention, error)
	UnDelegateResource(ctx context.Context, contract *core.UnDelegateResourceContract) (*api.TransactionExtention, error)

	// Asset operations
	GetAssetIssueById(ctx context.Context, id []byte) (*core.AssetIssueContract, error)
	GetAssetIssueListByName(ctx context.Context, name []byte) (*api.AssetIssueList, error)

	// Network operations
	ListNodes(ctx context.Context) (*api.NodeList, error)
	GetNodeInfo(ctx context.Context) (*core.NodeInfo, error)
	GetChainParameters(ctx context.Context) (*core.ChainParameters, error)
	GetNextMaintenanceTime(ctx context.Context) (*api.NumberMessage, error)
	TotalTransaction(ctx context.Context) (*api.NumberMessage, error)

	// Connection management
	Close() error
}

Transport defines the interface for communication with Tron nodes. It can be implemented by different protocols (gRPC, HTTP).

type TransportError

type TransportError struct {
	// Host is the address of the server (e.g. "grpc.trongrid.io:50051" or "https://api.trongrid.io")
	Host string
	// Protocol is the transport protocol ("grpc" or "http")
	Protocol string
	// Method is the RPC method or HTTP endpoint (e.g. "/protocol.Wallet/GetAccount" or "/wallet/getaccount")
	Method string
	// Err is the original error
	Err error
}

TransportError represents an error from a transport-level RPC call. Use errors.AsType[*TransportError] (Go 1.26+) to extract it and access Host, Protocol, Method fields.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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