Documentation
¶
Overview ¶
Package client provides high-level client functionality. Low-level 1:1 gRPC helpers are implemented in package lowlevel.
Package client provides core infrastructure for gRPC client management ¶
Package client provides connection management and RPC helpers for interacting with TRON full nodes over gRPC.
The core type is Client, which maintains a small pool of gRPC connections to a single node endpoint. Endpoints are expressed with an explicit scheme:
- grpc://host:port plaintext
- grpcs://host:port TLS
Construction uses functional options:
- WithTimeout(d) applies a default timeout when a context has no deadline
- WithPool(init, max) configures the connection pool size
Connection Management ¶
The client maintains a pool of connections to improve performance. The pool size can be configured during client creation:
cli, err := client.NewClient("grpc://grpc.trongrid.io:50051",
client.WithPool(5, 10), // 5 initial, 10 max connections
client.WithTimeout(30*time.Second))
if err != nil { /* handle */ }
defer cli.Close()
Quick Start ¶
cli, err := client.NewClient("grpc://grpc.trongrid.io:50051", client.WithTimeout(30*time.Second))
if err != nil { /* handle */ }
defer cli.Close()
Pass the client to higher-level managers (smartcontract, trc20, account, resources, network). Transport concerns remain centralized, making it easy to switch node endpoints.
Broadcasting ¶
Build a transaction via a manager, then sign and broadcast. Use DefaultBroadcastOptions to control receipt waiting and timing.
opts := client.DefaultBroadcastOptions() opts.FeeLimit = 100_000_000 opts.WaitForReceipt = true opts.WaitTimeout = 20 * time.Second opts.PollInterval = 500 * time.Millisecond ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() res, err := cli.SignAndBroadcast(ctx, txExt, opts, signer) _ = res; _ = err
When WaitForReceipt is true and the receipt arrives in time, Success reflects the final on-chain execution status. res.TxID is always populated.
Simulation ¶
Predict execution result and estimate energy before sending any transaction:
sim, err := cli.Simulate(ctx, txExt /* or *core.Transaction */)
if err != nil { /* handle */ }
if !sim.Success { /* would fail */ }
_ = sim.EnergyUsage
Simulation does not require signatures. Bandwidth (net usage) depends on signatures and payload; for accurate bandwidth, broadcast a signed transaction and inspect the receipt.
Error Handling ¶
The client returns specific error types for common issues:
- ErrNoConnection - No connection available in the pool
- ErrTimeout - Operation timed out
- ErrInvalidEndpoint - Invalid endpoint format
Always check for errors in production code.
Best Practices ¶
Always close the client when finished to free up resources: defer cli.Close()
Use context with timeout for all operations to prevent hanging: ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel()
3. Configure appropriate pool sizes based on your application's concurrency needs
4. Use simulation to estimate energy costs before broadcasting transactions
5. Handle errors appropriately, especially network and timeout errors
Common Usage Patterns ¶
Creating a client with custom configuration: cli, err := client.NewClient("grpc://grpc.trongrid.io:50051", client.WithTimeout(30*time.Second), client.WithPool(5, 10))
Broadcasting a transaction with custom options: opts := client.DefaultBroadcastOptions() opts.FeeLimit = 50_000_000 opts.WaitForReceipt = true result, err := cli.SignAndBroadcast(ctx, tx, opts, signer)
Simulating a transaction before broadcasting: sim, err := cli.Simulate(ctx, tx) if err != nil { /* handle error */ } if !sim.Success { /* would fail on chain */ }
Index ¶
- Variables
- type BroadcastOptions
- type BroadcastResult
- type Client
- func (c *Client) Account() *account.AccountManager
- func (c *Client) Close()
- func (c *Client) ContractInstance(contractAddress *types.Address, abi any) (*smartcontract.Instance, error)
- func (c *Client) GetConnection(ctx context.Context) (*grpc.ClientConn, error)
- func (c *Client) GetNodeAddress() string
- func (c *Client) GetTimeout() time.Duration
- func (c *Client) IsConnected() bool
- func (c *Client) Network() *network.NetworkManager
- func (c *Client) Resources() *resources.ResourcesManager
- func (c *Client) ReturnConnection(conn *grpc.ClientConn)
- func (c *Client) SignAndBroadcast(ctx context.Context, anytx any, opt BroadcastOptions, signers ...signer.Signer) (*BroadcastResult, error)
- func (c *Client) Simulate(ctx context.Context, anytx any) (*BroadcastResult, error)
- func (c *Client) SmartContract() *smartcontract.Manager
- func (c *Client) TRC10() *trc10.TRC10Manager
- func (c *Client) TRC20(addr *types.Address) *trc20.TRC20Managerdeprecated
- func (c *Client) TRC20Manager(addr *types.Address) (*trc20.TRC20Manager, error)
- func (c *Client) Voting() *voting.VotingManager
- type Option
- type ValidationFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrConnectionFailed = types.NewTronError(1001, "connection to node failed", nil) ErrClientClosed = types.NewTronError(1002, "client is closed", nil) ErrContextCancelled = types.NewTronError(1003, "context cancelled", nil) )
Client errors
Functions ¶
This section is empty.
Types ¶
type BroadcastOptions ¶
type BroadcastOptions struct {
FeeLimit int64 // Fee limit for the transaction
PermissionID int32 // Permission ID for the transaction
WaitForReceipt bool // Wait for transaction receipt
WaitTimeout time.Duration // Timeout for waiting for receipt
PollInterval time.Duration // Polling interval when waiting for receipt
}
BroadcastOptions controls high-level signing and broadcasting workflows. Fields with zero values are defaulted by DefaultBroadcastOptions unless explicitly documented otherwise.
These options control how transactions are signed, broadcast, and confirmed. Use DefaultBroadcastOptions() to get sensible defaults, then modify as needed.
func DefaultBroadcastOptions ¶
func DefaultBroadcastOptions() BroadcastOptions
DefaultBroadcastOptions returns sane defaults for broadcasting transactions.
The default options are:
- FeeLimit: 150,000,000 SUN (0.15 TRX)
- PermissionID: 0 (owner permission)
- WaitForReceipt: true (wait for transaction confirmation)
- WaitTimeout: 15 seconds
- PollInterval: 3 seconds
type BroadcastResult ¶
type BroadcastResult struct {
TxID string `json:"txID"`
Success bool `json:"success"`
Code api.ReturnResponseCode `json:"returnCode"` // TRON return code
Message string `json:"returnMessage"` // TRON return message concat with contract return message
// ConstantReturn has the details of the contract returned error message or result
// Populated for smart contract transactions when WaitForReceipt is true
ConstantReturn [][]byte //test if nil before use
// Fields primarily populated by simulation (TriggerConstantContract) or
// for smart contract transactions when WaitForReceipt is true
EnergyUsage int64 `json:"energyUsed,omitempty"`
NetUsage int64 `json:"netUsage,omitempty"`
Logs []*core.TransactionInfo_Log `json:"logs,omitempty"`
}
BroadcastResult summarizes the outcome of a simulation or a broadcasted transaction, including TRON return status, and for smart contract transactions, resource usage and logs.
This struct contains the results of either a Simulate or SignAndBroadcast operation. For smart contract transactions (CreateSmartContract and TriggerSmartContract), when WaitForReceipt is true in SignAndBroadcast, additional fields like EnergyUsage and Logs will be populated with data from the transaction receipt. For other transaction types (like TRX transfers), only the basic success/failure information will be available.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client manages connection to a single Tron node with connection pooling.
The Client maintains a pool of gRPC connections to improve performance for concurrent operations. It automatically handles connection lifecycle, including reconnection and timeout management.
Use NewClient to create a new client instance, and always call Close when finished to free up resources.
func NewClient ¶
NewClient creates a new client to a TRON node using endpoint like grpc://host:port or grpcs://host:port
The endpoint must include a scheme (grpc:// or grpcs://) followed by host and port. The client maintains a connection pool for improved performance.
Options can be used to configure:
- Connection timeout with WithTimeout()
- Connection pool size with WithPool()
Example:
cli, err := client.NewClient("grpc://grpc.trongrid.io:50051",
client.WithTimeout(30*time.Second),
client.WithPool(5, 10))
if err != nil {
// handle error
}
defer cli.Close()
Returns an error if the endpoint is invalid or connection fails.
func NewClientWithDialer ¶
func NewClientWithDialer(endpoint string, dialer func(ctx context.Context, s string) (net.Conn, error), opts ...Option) (*Client, error)
NewClientWithDialer is a test-only constructor that builds a *Client whose internal pool dials using the provided dialer (e.g., bufconn) rather than a real network address.
func (*Client) Account ¶ added in v1.0.5
func (c *Client) Account() *account.AccountManager
Account is the gateway method to access the AccountManager. It returns an *account.AccountManager, satisfying the high-level API need.
func (*Client) Close ¶
func (c *Client) Close()
Close closes the client and all connections in the pool.
This method should be called when the client is no longer needed to free up resources. It is safe to call multiple times.
func (*Client) ContractInstance ¶ added in v1.0.4
func (c *Client) ContractInstance(contractAddress *types.Address, abi any) (*smartcontract.Instance, error)
ContractInstance constructs a contract instance for the given address using the provided TRON client. The ABI can be omitted to fetch from the network, or supplied as either a JSON string or a *core.SmartContract_ABI.
func (*Client) GetConnection ¶
GetConnection safely gets a connection from the pool.
This method should be used in conjunction with ReturnConnection to properly manage connection lifecycle. It applies the client's default timeout if the context doesn't have a deadline.
Returns ErrClientClosed if the client has been closed, or ErrConnectionFailed if no connection is available.
func (*Client) GetNodeAddress ¶
GetNodeAddress returns the configured node address.
The address is in the format scheme://host:port (e.g., grpc://grpc.trongrid.io:50051).
func (*Client) GetTimeout ¶
GetTimeout returns the client's configured timeout.
This timeout is applied to operations when the context doesn't have a deadline.
func (*Client) IsConnected ¶
IsConnected checks if the client is connected (not closed).
Returns true if the client is still open and can be used for operations, false if it has been closed.
func (*Client) Network ¶ added in v1.0.4
func (c *Client) Network() *network.NetworkManager
Network returns the high-level NetworkManager.
func (*Client) Resources ¶ added in v1.0.4
func (c *Client) Resources() *resources.ResourcesManager
Resources returns the high-level ResourcesManager.
func (*Client) ReturnConnection ¶
func (c *Client) ReturnConnection(conn *grpc.ClientConn)
ReturnConnection safely returns a connection to the pool.
This method should always be called after GetConnection to return the connection to the pool for reuse. It is safe to call on a closed client.
func (*Client) SignAndBroadcast ¶
func (c *Client) SignAndBroadcast(ctx context.Context, anytx any, opt BroadcastOptions, signers ...signer.Signer) (*BroadcastResult, error)
SignAndBroadcast signs a single-contract transaction using the provided signers (if any), applies BroadcastOptions, broadcasts it to the network, and optionally waits for receipt. It returns a BroadcastResult with txid, TRON return code/message, and, if waiting for smart contract transactions, resource usage and logs.
This is the primary method for sending transactions to the TRON network. It handles signing, broadcasting, and (optionally) waiting for the transaction to be confirmed.
For smart contract transactions (CreateSmartContract and TriggerSmartContract), when WaitForReceipt is enabled, it will retrieve execution results including energy usage, logs, and contract return values. For other transaction types (like TRX transfers), it will only indicate success/failure status.
Supported input types are *api.TransactionExtention and *core.Transaction.
Example:
opts := client.DefaultBroadcastOptions()
opts.FeeLimit = 100_000_000
opts.WaitForReceipt = true
result, err := cli.SignAndBroadcast(ctx, txExt, opts, signer)
if err != nil {
// handle error
}
if result.Success {
fmt.Printf("Transaction successful: %s\n", result.TxID)
// For smart contract transactions, additional info will be available:
if result.EnergyUsage > 0 {
fmt.Printf("Energy used: %d\n", result.EnergyUsage)
}
}
Example ¶
ExampleClient_SignAndBroadcast demonstrates customizing broadcast options.
package main
import (
"context"
"testing"
"time"
"github.com/kslamph/tronlib/pkg/client"
)
func main() {
if testing.Short() {
return
}
cli, _ := client.NewClient("grpc://grpc.trongrid.io:50051")
defer cli.Close()
// Some transaction built elsewhere; nil here just to illustrate API.
var tx any
opts := client.DefaultBroadcastOptions()
opts.FeeLimit = 100_000_000
opts.WaitForReceipt = true
opts.WaitTimeout = 20 * time.Second
opts.PollInterval = 500 * time.Millisecond
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_, _ = cli.SignAndBroadcast(ctx, tx, opts, nil)
}
Output:
func (*Client) Simulate ¶
Simulate performs a read-only execution of a single-contract transaction and returns a BroadcastResult with constant return data, energy usage, and logs.
This method allows you to test a transaction without actually broadcasting it to the network. It's useful for estimating energy usage and checking if a transaction would succeed before actually sending it.
Supported input types are *api.TransactionExtention and *core.Transaction. The transaction must contain exactly one contract and must not be expired.
Example:
sim, err := cli.Simulate(ctx, txExt)
if err != nil {
// handle error
}
if !sim.Success {
// transaction would fail
}
fmt.Printf("Energy usage: %d\n", sim.EnergyUsage)
Example ¶
ExampleClient_Simulate demonstrates read-only simulation of a transaction.
package main
import (
"context"
"testing"
"time"
"github.com/kslamph/tronlib/pkg/client"
)
func main() {
if testing.Short() {
return
}
cli, _ := client.NewClient("grpc://grpc.trongrid.io:50051")
defer cli.Close()
// Some transaction built elsewhere; nil here just to illustrate API.
var tx any
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
_, _ = cli.Simulate(ctx, tx)
}
Output:
func (*Client) SmartContract ¶ added in v1.0.5
func (c *Client) SmartContract() *smartcontract.Manager
SmartContract is the gateway method to access the Manager.
func (*Client) TRC10 ¶ added in v1.0.4
func (c *Client) TRC10() *trc10.TRC10Manager
TRC10 returns the high-level TRC10Manager.
func (*Client) TRC20
deprecated
added in
v1.0.4
func (c *Client) TRC20(addr *types.Address) *trc20.TRC20Manager
TRC20 returns a TRC20 manager for a given token address. It returns nil when the manager cannot be initialized (for example when the token metadata cannot be fetched from the node).
Deprecated: TRC20 swallows the initialization error and returns nil on failure. Use TRC20Manager, which reports the error instead.
func (*Client) TRC20Manager ¶ added in v1.2.0
TRC20Manager returns a TRC20 manager for a given token address, reporting initialization errors (invalid contract, unreachable node, non-TRC20 contract) instead of silently returning nil.
func (*Client) Voting ¶ added in v1.0.4
func (c *Client) Voting() *voting.VotingManager
Voting returns the high-level VotingManager.
type Option ¶
type Option func(*clientOptions)
Functional options for Client
func WithPool ¶
WithPool configures the initial and maximum connections for the pool.
This option configures the connection pool size:
- initConnections: Number of connections to create initially (default: 1)
- maxConnections: Maximum number of connections in the pool (default: 5)
func WithTimeout ¶
WithTimeout sets the default timeout for client operations when the context has no deadline.
This option configures the default timeout that will be applied to operations when the context doesn't have a deadline. The default is 30 seconds.
type ValidationFunc ¶
type ValidationFunc[T any] = lowlevel.ValidationFunc[T]
ValidationFunc is a function type for validating gRPC call results T represents the return type of the gRPC call Re-exported from lowlevel for backward compatibility.