Documentation
¶
Overview ¶
Package contract provides smart contract interaction utilities for TRON.
Example (DeferredErrors) ¶
This example demonstrates the deferred-error pattern used by ContractCall. Validation errors from builder methods (e.g. invalid addresses) are accumulated internally and surfaced when a terminal operation is called.
package main
import (
"context"
"errors"
"fmt"
"github.com/fbsobreira/gotron-sdk/pkg/contract"
)
func main() {
// Suppose we have a ContractCall with validation errors set during
// construction (e.g. by a TRC20 helper that validates addresses):
var client contract.Client // nil — we never reach the RPC call
call := contract.New(client, "TContractAddr").
Method("transfer(address,uint256)").
From("TFromAddr")
// Simulate two validation errors that would be set by a higher-level
// helper (e.g. trc20.Transfer):
call.SetError(errors.New("invalid to address"))
call.SetError(errors.New("amount must be positive"))
// The error can be checked early without invoking a terminal:
if call.Err() != nil {
fmt.Println("early check:", call.Err())
}
// Or it surfaces automatically at any terminal:
_, err := call.Build(context.Background())
if err != nil {
fmt.Println("build error:", err)
}
}
Output: early check: invalid to address amount must be positive build error: invalid to address amount must be positive
Index ¶
- Variables
- func JSONtoABI(jsonSTR string) (*core.SmartContract_ABI, error)
- type CallResult
- type Client
- type ContractCall
- func (c *ContractCall) Apply(opts ...Option) *ContractCall
- func (c *ContractCall) Build(ctx context.Context) (*api.TransactionExtention, error)
- func (c *ContractCall) Call(ctx context.Context) (*CallResult, error)
- func (c *ContractCall) Decode(ctx context.Context) (*transaction.ContractData, error)
- func (c *ContractCall) Err() error
- func (c *ContractCall) EstimateEnergy(ctx context.Context) (int64, error)
- func (c *ContractCall) From(addr string) *ContractCall
- func (c *ContractCall) Method(sig string) *ContractCall
- func (c *ContractCall) Params(jsonString string) *ContractCall
- func (c *ContractCall) Send(ctx context.Context, s signer.Signer) (*Receipt, error)
- func (c *ContractCall) SendAndConfirm(ctx context.Context, s signer.Signer) (*Receipt, error)
- func (c *ContractCall) SetError(err error) *ContractCall
- func (c *ContractCall) Sign(ctx context.Context, s signer.Signer) (*core.Transaction, error)
- func (c *ContractCall) WithABI(abiJSON string) *ContractCall
- func (c *ContractCall) WithCallValue(value int64) *ContractCall
- func (c *ContractCall) WithData(data []byte) *ContractCall
- func (c *ContractCall) WithFeeLimit(limit int64) *ContractCall
- func (c *ContractCall) WithPermissionID(id int32) *ContractCall
- func (c *ContractCall) WithTokenValue(tokenID string, amount int64) *ContractCall
- type JSONABI
- type Option
- type Receipt
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrNoFromAddress = errors.New("from address required") ErrNoContract = errors.New("contract address required") ErrNoMethod = errors.New("method signature required") )
Sentinel errors for contract call validation. Callers can test with errors.Is.
Functions ¶
Types ¶
type CallResult ¶ added in v0.25.2
type CallResult struct {
// RawResults contains the raw byte slices returned by the contract call.
// Each entry corresponds to one return value from GetConstantResult().
RawResults [][]byte
// EnergyUsed is the energy consumed by the constant call, as reported
// in the transaction's energy usage field.
EnergyUsed int64
}
CallResult holds the decoded response from a constant (read-only) contract call.
type Client ¶ added in v0.25.2
type Client interface {
TriggerConstantContractCtx(ctx context.Context, from, contractAddress, method, jsonString string, opts ...client.ConstantCallOption) (*api.TransactionExtention, error)
TriggerContractCtx(ctx context.Context, from, contractAddress, method, jsonString string, feeLimit, tAmount int64, tTokenID string, tTokenAmount int64) (*api.TransactionExtention, error)
TriggerConstantContractWithDataCtx(ctx context.Context, from, contractAddress string, data []byte, opts ...client.ConstantCallOption) (*api.TransactionExtention, error)
TriggerContractWithDataCtx(ctx context.Context, from, contractAddress string, data []byte, feeLimit, tAmount int64, tTokenID string, tTokenAmount int64) (*api.TransactionExtention, error)
EstimateEnergyCtx(ctx context.Context, from, contractAddress, method, jsonString string, tAmount int64, tTokenID string, tTokenAmount int64) (*api.EstimateEnergyMessage, error)
EstimateEnergyWithDataCtx(ctx context.Context, from, contractAddress string, data []byte, tAmount int64, tTokenID string, tTokenAmount int64) (*api.EstimateEnergyMessage, error)
BroadcastCtx(ctx context.Context, tx *core.Transaction) (*api.Return, error)
GetTransactionInfoByIDCtx(ctx context.Context, id string) (*core.TransactionInfo, error)
}
Client is the subset of GrpcClient that the contract call builder needs. Accepting an interface avoids tight coupling and simplifies testing.
type ContractCall ¶ added in v0.25.2
type ContractCall struct {
// contains filtered or unexported fields
}
ContractCall is a builder for constructing and executing TRON smart-contract calls. Use New to start a builder chain, configure it with the fluent setter methods, and finish with a terminal operation (Call, EstimateEnergy, Build, Send, or SendAndConfirm).
func New ¶ added in v0.25.2
func New(c Client, contractAddress string) *ContractCall
New creates a new ContractCall builder targeting the given contract address.
func (*ContractCall) Apply ¶ added in v0.25.2
func (c *ContractCall) Apply(opts ...Option) *ContractCall
Apply applies one or more Options to the call configuration.
func (*ContractCall) Build ¶ added in v0.25.2
func (c *ContractCall) Build(ctx context.Context) (*api.TransactionExtention, error)
Build creates a state-changing transaction without signing or broadcasting. The returned TransactionExtention can be inspected or signed externally.
func (*ContractCall) Call ¶ added in v0.25.2
func (c *ContractCall) Call(ctx context.Context) (*CallResult, error)
Call executes a constant (read-only) contract call and returns the raw results.
func (*ContractCall) Decode ¶ added in v0.25.2
func (c *ContractCall) Decode(ctx context.Context) (*transaction.ContractData, error)
Decode builds the transaction and decodes the contract parameters into human-readable fields (base58 addresses, TRX-formatted amounts). Useful for inspecting what a contract call does before signing.
func (*ContractCall) Err ¶ added in v0.25.2
func (c *ContractCall) Err() error
Err returns any deferred error stored in the builder, or nil if none. Use this to check for validation errors without invoking a terminal:
call := token.Transfer(from, "INVALID", amount)
if call.Err() != nil {
log.Fatal(call.Err()) // "invalid to address INVALID: ..."
}
func (*ContractCall) EstimateEnergy ¶ added in v0.25.2
func (c *ContractCall) EstimateEnergy(ctx context.Context) (int64, error)
EstimateEnergy returns the estimated energy required for the contract call. From address is required for accurate estimation.
func (*ContractCall) From ¶ added in v0.25.2
func (c *ContractCall) From(addr string) *ContractCall
From sets the caller address. If not set, a zero address is used for read-only calls and an error is returned for state-changing calls.
func (*ContractCall) Method ¶ added in v0.25.2
func (c *ContractCall) Method(sig string) *ContractCall
Method sets the contract method signature (e.g. "transfer(address,uint256)").
func (*ContractCall) Params ¶ added in v0.25.2
func (c *ContractCall) Params(jsonString string) *ContractCall
Params sets the JSON-encoded parameters for the contract method.
func (*ContractCall) Send ¶ added in v0.25.2
Send builds, signs, and broadcasts a state-changing transaction.
func (*ContractCall) SendAndConfirm ¶ added in v0.25.2
SendAndConfirm is like Send but additionally polls for transaction confirmation on-chain. It relies on the context for timeout control.
func (*ContractCall) SetError ¶ added in v0.25.2
func (c *ContractCall) SetError(err error) *ContractCall
SetError records a deferred error that will be returned by any terminal operation (Call, Build, Send, etc.). Multiple errors are accumulated via errors.Join so callers see every validation failure at once. Nil errors are ignored. This preserves fluent method chaining while ensuring validation errors are never silently lost.
func (*ContractCall) Sign ¶ added in v0.26.0
func (c *ContractCall) Sign(ctx context.Context, s signer.Signer) (*core.Transaction, error)
Sign builds and signs the transaction without broadcasting. Returns the signed transaction ready for deferred broadcast or inspection.
func (*ContractCall) WithABI ¶ added in v0.25.2
func (c *ContractCall) WithABI(abiJSON string) *ContractCall
WithABI stores the ABI JSON for future use (e.g. result decoding).
func (*ContractCall) WithCallValue ¶ added in v0.26.0
func (c *ContractCall) WithCallValue(value int64) *ContractCall
WithCallValue sets the TRX amount (in SUN) sent along with the call. Used by both read-only Call and state-changing Build/Send. Returns itself for chaining.
func (*ContractCall) WithData ¶ added in v0.25.2
func (c *ContractCall) WithData(data []byte) *ContractCall
WithData sets pre-packed ABI call data, bypassing the method+params encoding pipeline. When data is set, Method and Params are ignored.
func (*ContractCall) WithFeeLimit ¶ added in v0.26.0
func (c *ContractCall) WithFeeLimit(limit int64) *ContractCall
WithFeeLimit sets the maximum TRX (in SUN) the caller is willing to spend on energy for a state-changing contract call. Returns itself for chaining.
func (*ContractCall) WithPermissionID ¶ added in v0.26.0
func (c *ContractCall) WithPermissionID(id int32) *ContractCall
WithPermissionID sets the permission ID for multi-signature transactions. Returns itself for chaining.
func (*ContractCall) WithTokenValue ¶ added in v0.26.0
func (c *ContractCall) WithTokenValue(tokenID string, amount int64) *ContractCall
WithTokenValue sets the TRC10 token ID and amount sent with the call. Forwarded by all operations: Call, Build, Send, SendAndConfirm, and EstimateEnergy. Returns itself for chaining.
type JSONABI ¶
type JSONABI struct {
Anonymous bool `json:"anonymous"`
Constant bool `json:"constant"`
Inputs []struct {
Indexed bool `json:"indexed"`
Name string `json:"name"`
Type string `json:"type"`
} `json:"inputs"`
Name string `json:"name"`
Outputs []struct {
Indexed bool `json:"indexed"`
Name string `json:"name"`
Type string `json:"type"`
} `json:"outputs"`
Payable bool `json:"payable"`
StateMutability string `json:"stateMutability"`
Type string `json:"type"`
}
JSONABI represents a single ABI entry in the standard Ethereum JSON ABI format.
type Option ¶ added in v0.25.2
type Option func(*callConfig)
Option configures a ContractCall.
func WithCallValue ¶ added in v0.25.2
WithCallValue sets the TRX amount (in SUN) sent along with the call.
func WithFeeLimit ¶ added in v0.25.2
WithFeeLimit sets the maximum TRX (in SUN) the caller is willing to spend on energy for a state-changing contract call.
func WithPermissionID ¶ added in v0.25.2
WithPermissionID sets the permission ID for multi-signature transactions.
func WithPollInterval ¶ added in v0.26.0
WithPollInterval sets the interval between confirmation checks in SendAndConfirm. If not set, txcore.DefaultPollInterval is used.
func WithTokenValue ¶ added in v0.25.2
WithTokenValue sets the TRC10 token ID and amount sent with the call.