package bind
import "github.com/ethereum/go-ethereum/accounts/abi/bind/v2"
Package bind implements utilities for interacting with Solidity contracts. This is the 'runtime' for contract bindings generated with the abigen command. It includes methods for calling/transacting, filtering chain history for specific custom Solidity event types, and creating event subscriptions to monitor the chain for event occurrences.
Two methods for contract deployment are provided:
- DeployContract is intended to be used for deployment of a single contract.
- LinkAndDeploy is intended for the deployment of multiple contracts, potentially with library dependencies.
Index ¶
- Variables
- func Call[T any](c *BoundContract, opts *CallOpts, calldata []byte, unpack func([]byte) (T, error)) (T, error)
- func DeployContract(opts *TransactOpts, bytecode []byte, backend ContractBackend, constructorInput []byte) (common.Address, *types.Transaction, error)
- func Transact(c *BoundContract, opt *TransactOpts, data []byte) (*types.Transaction, error)
- func WaitDeployed(ctx context.Context, b DeployBackend, hash common.Hash) (common.Address, error)
- func WaitMined(ctx context.Context, b DeployBackend, txHash common.Hash) (*types.Receipt, error)
- func WatchEvents[Ev ContractEvent](c *BoundContract, opts *WatchOpts, unpack func(*types.Log) (*Ev, error), sink chan<- *Ev, topics ...[]any) (event.Subscription, error)
- type Backend
- type BlockHashContractCaller
- type BoundContract
- func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract
- func (c *BoundContract) Call(opts *CallOpts, results *[]any, method string, params ...any) error
- func (c *BoundContract) CallRaw(opts *CallOpts, input []byte) ([]byte, error)
- func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]any) (chan types.Log, event.Subscription, error)
- func (c *BoundContract) RawCreationTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error)
- func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error)
- func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...any) (*types.Transaction, error)
- func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error)
- func (c *BoundContract) UnpackLog(out any, event string, log types.Log) error
- func (c *BoundContract) UnpackLogIntoMap(out map[string]any, event string, log types.Log) error
- func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]any) (chan types.Log, event.Subscription, error)
- type CallOpts
- type ContractBackend
- type ContractCaller
- type ContractEvent
- type ContractFilterer
- type ContractTransactor
- type DeployBackend
- type DeployFn
- type DeploymentParams
- type DeploymentResult
- type EventIterator
- func FilterEvents[Ev ContractEvent](c *BoundContract, opts *FilterOpts, unpack func(*types.Log) (*Ev, error), topics ...[]any) (*EventIterator[Ev], error)
- func (it *EventIterator[T]) Close() error
- func (it *EventIterator[T]) Error() error
- func (it *EventIterator[T]) Next() (advanced bool)
- func (it *EventIterator[T]) Value() *T
- type FilterOpts
- type MetaData
- type PendingContractCaller
- type SignerFn
- type TransactOpts
- func NewClefTransactor(clef *external.ExternalSigner, account accounts.Account) *TransactOpts
- func NewKeyStoreTransactor(keystore *keystore.KeyStore, account accounts.Account, chainID *big.Int) *TransactOpts
- func NewKeyedTransactor(key *ecdsa.PrivateKey, chainID *big.Int) *TransactOpts
- type WatchOpts
Variables ¶
var ( // ErrNoCode is returned by call and transact operations for which the requested // recipient contract to operate on does not exist in the state db or does not // have any code associated with it (i.e. self-destructed). ErrNoCode = errors.New("no contract code at given address") // ErrNoPendingState is raised when attempting to perform a pending state action // on a backend that doesn't implement PendingContractCaller. ErrNoPendingState = errors.New("backend does not support pending state") // ErrNoBlockHashState is raised when attempting to perform a block hash action // on a backend that doesn't implement BlockHashContractCaller. ErrNoBlockHashState = errors.New("backend does not support block hash state") // ErrNoCodeAfterDeploy is returned by WaitDeployed if contract creation leaves // an empty contract behind. ErrNoCodeAfterDeploy = errors.New("no contract code after deployment") // ErrNoAddressInReceipt is returned by WaitDeployed when the receipt for the // transaction hash does not contain a contract address. This error may indicate // that the transaction hash was not a CREATE transaction. ErrNoAddressInReceipt = errors.New("no contract address in receipt") )
ErrNotAuthorized is returned when an account is not properly unlocked.
Functions ¶
func Call ¶
func Call[T any](c *BoundContract, opts *CallOpts, calldata []byte, unpack func([]byte) (T, error)) (T, error)
Call performs an eth_call to a contract with optional call data.
To call a function that doesn't return any output, pass nil as the unpack function. This can be useful if you just want to check that the function doesn't revert.
Call is intended to be used with contract method unpack methods in bindings generated with the abigen --v2 flag. It should be preferred over BoundContract.Call
func DeployContract ¶
func DeployContract(opts *TransactOpts, bytecode []byte, backend ContractBackend, constructorInput []byte) (common.Address, *types.Transaction, error)
DeployContract creates and submits a deployment transaction based on the deployer bytecode and optional ABI-encoded constructor input. It returns the address and creation transaction of the pending contract, or an error if the creation failed.
To initiate the deployment of multiple contracts with one method call, see the LinkAndDeploy method.
func Transact ¶
func Transact(c *BoundContract, opt *TransactOpts, data []byte) (*types.Transaction, error)
Transact creates and submits a transaction to a contract with optional input data.
Transact is identical to BoundContract.RawTransact, and is provided as a package-level method so that interactions with contracts whose bindings were generated with the abigen --v2 flag are consistent (they do not require calling methods on the BoundContract instance).
func WaitDeployed ¶
WaitDeployed waits for a contract deployment transaction with the provided hash and returns the on-chain contract address when it is mined. It stops waiting when ctx is canceled.
func WaitMined ¶
WaitMined waits for tx to be mined on the blockchain. It stops waiting when the context is canceled.
func WatchEvents ¶
func WatchEvents[Ev ContractEvent](c *BoundContract, opts *WatchOpts, unpack func(*types.Log) (*Ev, error), sink chan<- *Ev, topics ...[]any) (event.Subscription, error)
WatchEvents creates an event subscription to notify when logs of the specified event type are emitted from the given contract. Received logs are unpacked and forwarded to sink. If topics are specified, only events are forwarded which match the topics.
WatchEvents returns a subscription or an error if the provided WatchOpts are invalid or the backend is closed.
WatchEvents is intended to be used with contract event unpack methods in bindings generated with the abigen --v2 flag. It should be preferred over BoundContract.WatchLogs.
Types ¶
type Backend ¶
type Backend interface { DeployBackend ContractBackend }
Backend combines all backend methods used in this package. This type is provided for convenience. It is meant to be used when you need to hold a reference to a backend that is used for both deployment and contract interaction.
type BlockHashContractCaller ¶
type BlockHashContractCaller interface { // CodeAtHash returns the code of the given account in the state at the specified block hash. CodeAtHash(ctx context.Context, contract common.Address, blockHash common.Hash) ([]byte, error) // CallContractAtHash executes an Ethereum contract call against the state at the specified block hash. CallContractAtHash(ctx context.Context, call ethereum.CallMsg, blockHash common.Hash) ([]byte, error) }
BlockHashContractCaller defines methods to perform contract calls on a specific block hash. Call will try to discover this interface when access to a block by hash is requested. If the backend does not support the block hash state, Call returns ErrNoBlockHashState.
type BoundContract ¶
type BoundContract struct {
// contains filtered or unexported fields
}
BoundContract is the base wrapper object that reflects a contract on the Ethereum network. It contains a collection of methods that are used by the higher level contract bindings to operate.
func NewBoundContract ¶
func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract
NewBoundContract creates a low level contract interface through which calls and transactions may be made through.
func (*BoundContract) Call ¶
Call invokes the (constant) contract method with params as input values and sets the output to result. The result type might be a single field for simple returns, a slice of interfaces for anonymous returns and a struct for named returns.
func (*BoundContract) CallRaw ¶
func (c *BoundContract) CallRaw(opts *CallOpts, input []byte) ([]byte, error)
CallRaw executes an eth_call against the contract with the raw calldata as input. It returns the call's return data or an error.
func (*BoundContract) FilterLogs ¶
func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]any) (chan types.Log, event.Subscription, error)
FilterLogs filters contract logs for past blocks, returning the necessary channels to construct a strongly typed bound iterator on top of them.
func (*BoundContract) RawCreationTransact ¶
func (c *BoundContract) RawCreationTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error)
RawCreationTransact creates and submits a contract-creation transaction with the given calldata as the input.
func (*BoundContract) RawTransact ¶
func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error)
RawTransact initiates a transaction with the given raw calldata as the input. It's usually used to initiate transactions for invoking **Fallback** function.
func (*BoundContract) Transact ¶
func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...any) (*types.Transaction, error)
Transact invokes the (paid) contract method with params as input values.
func (*BoundContract) Transfer ¶
func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error)
Transfer initiates a plain transaction to move funds to the contract, calling its default method if one is available.
func (*BoundContract) UnpackLog ¶
UnpackLog unpacks a retrieved log into the provided output structure.
func (*BoundContract) UnpackLogIntoMap ¶
UnpackLogIntoMap unpacks a retrieved log into the provided map.
func (*BoundContract) WatchLogs ¶
func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]any) (chan types.Log, event.Subscription, error)
WatchLogs filters subscribes to contract logs for future blocks, returning a subscription object that can be used to tear down the watcher.
type CallOpts ¶
type CallOpts struct { Pending bool // Whether to operate on the pending state or the last known one From common.Address // Optional the sender address, otherwise the first account is used BlockNumber *big.Int // Optional the block number on which the call should be performed BlockHash common.Hash // Optional the block hash on which the call should be performed Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) }
CallOpts is the collection of options to fine tune a contract call request.
type ContractBackend ¶
type ContractBackend interface { ContractCaller ContractTransactor ContractFilterer }
ContractBackend defines the methods needed to work with contracts on a read-write basis.
type ContractCaller ¶
type ContractCaller interface { // CodeAt returns the code of the given account. This is needed to differentiate // between contract internal errors and the local chain being out of sync. CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) // CallContract executes an Ethereum contract call with the specified data as the // input. CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) }
ContractCaller defines the methods needed to allow operating with a contract on a read only basis.
type ContractEvent ¶
type ContractEvent interface { ContractEventName() string }
ContractEvent is a type constraint for ABI event types.
type ContractFilterer ¶
type ContractFilterer interface { ethereum.LogFilterer }
ContractFilterer defines the methods needed to access log events using one-off queries or continuous event subscriptions.
type ContractTransactor ¶
type ContractTransactor interface { ethereum.GasEstimator ethereum.GasPricer ethereum.GasPricer1559 ethereum.TransactionSender // HeaderByNumber returns a block header from the current canonical chain. If // number is nil, the latest known header is returned. HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) // PendingCodeAt returns the code of the given account in the pending state. PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) // PendingNonceAt retrieves the current pending nonce associated with an account. PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) }
ContractTransactor defines the methods needed to allow operating with a contract on a write only basis. Besides the transacting method, the remainder are helpers used when the user does not provide some needed values, but rather leaves it up to the transactor to decide.
type DeployBackend ¶
type DeployBackend interface { TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error) }
DeployBackend wraps the operations needed by WaitMined and WaitDeployed.
type DeployFn ¶
DeployFn deploys a contract given a deployer and optional input. It returns the address and a pending transaction, or an error if the deployment failed.
func DefaultDeployer ¶
func DefaultDeployer(opts *TransactOpts, backend ContractBackend) DeployFn
DefaultDeployer returns a DeployFn that signs and submits creation transactions using the given signer.
The DeployFn returned by DefaultDeployer should be used by LinkAndDeploy in almost all cases, unless a custom DeployFn implementation is needed.
type DeploymentParams ¶
type DeploymentParams struct { // list of all contracts targeted for the deployment Contracts []*MetaData // optional map of ABI-encoded constructor inputs keyed by the MetaData.ID. Inputs map[string][]byte // optional map of override addresses for specifying already-deployed // contracts. It is keyed by the MetaData.ID. Overrides map[string]common.Address }
DeploymentParams contains parameters needed to deploy one or more contracts via LinkAndDeploy
type DeploymentResult ¶
type DeploymentResult struct { // Map of contract MetaData.ID to pending deployment transaction Txs map[string]*types.Transaction // Map of contract MetaData.ID to the address where it will be deployed Addresses map[string]common.Address }
DeploymentResult contains information about the result of a pending deployment made by LinkAndDeploy.
func LinkAndDeploy ¶
func LinkAndDeploy(params *DeploymentParams, deploy DeployFn) (*DeploymentResult, error)
LinkAndDeploy performs the contract deployment specified by params using the provided DeployFn to create, sign and submit transactions.
Contracts can depend on libraries, which in-turn can have their own library dependencies. Therefore, LinkAndDeploy performs the deployment recursively, starting with libraries (and contracts) that don't have dependencies, and progressing through the contracts that depend upon them.
If an error is encountered, the returned DeploymentResult only contains entries for the contracts whose deployment submission succeeded.
LinkAndDeploy performs creation and submission of creation transactions, but does not ensure that the contracts are included in the chain.
type EventIterator ¶
type EventIterator[T any] struct { // contains filtered or unexported fields }
EventIterator is an object for iterating over the results of a event log filter call.
func FilterEvents ¶
func FilterEvents[Ev ContractEvent](c *BoundContract, opts *FilterOpts, unpack func(*types.Log) (*Ev, error), topics ...[]any) (*EventIterator[Ev], error)
FilterEvents filters a historical block range for instances of emission of a specific event type from a specified contract. It returns an error if the provided filter opts are invalid or the backend is closed.
FilterEvents is intended to be used with contract event unpack methods in bindings generated with the abigen --v2 flag. It should be preferred over BoundContract.FilterLogs.
func (*EventIterator[T]) Close ¶
func (it *EventIterator[T]) Close() error
Close releases any pending underlying resources. Any subsequent calls to Next will not advance the iterator, but the current value remains accessible.
func (*EventIterator[T]) Error ¶
func (it *EventIterator[T]) Error() error
Error returns an error if iteration has failed.
func (*EventIterator[T]) Next ¶
func (it *EventIterator[T]) Next() (advanced bool)
Next advances the iterator to the subsequent event (if there is one), returning true if the iterator advanced.
If the attempt to convert the raw log object to an instance of T using the unpack function provided via FilterEvents returns an error: that error is returned and subsequent calls to Next will not advance the iterator.
func (*EventIterator[T]) Value ¶
func (it *EventIterator[T]) Value() *T
Value returns the current value of the iterator, or nil if there isn't one.
type FilterOpts ¶
type FilterOpts struct { Start uint64 // Start of the queried range End *uint64 // End of the range (nil = latest) Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) }
FilterOpts is the collection of options to fine tune filtering for events within a bound contract.
type MetaData ¶
type MetaData struct { Bin string // deployer bytecode (as a hex string) ABI string // the raw ABI definition (JSON) Deps []*MetaData // library dependencies of the contract // For bindings that were compiled from combined-json ID is the Solidity // library pattern: a 34 character prefix of the hex encoding of the keccak256 // hash of the fully qualified 'library name', i.e. the path of the source file. // // For contracts compiled from the ABI definition alone, this is the type name // of the contract (as specified in the ABI definition or overridden via the // --type flag). // // This is a unique identifier of a contract within a compilation unit. When // used as part of a multi-contract deployment with library dependencies, the // ID is used to link contracts during deployment using [LinkAndDeploy]. ID string // contains filtered or unexported fields }
MetaData collects all metadata for a bound contract.
func (*MetaData) ParseABI ¶
ParseABI returns the parsed ABI specification, or an error if the string representation of the ABI set in the MetaData instance could not be parsed.
type PendingContractCaller ¶
type PendingContractCaller interface { // PendingCodeAt returns the code of the given account in the pending state. PendingCodeAt(ctx context.Context, contract common.Address) ([]byte, error) // PendingCallContract executes an Ethereum contract call against the pending state. PendingCallContract(ctx context.Context, call ethereum.CallMsg) ([]byte, error) }
PendingContractCaller defines methods to perform contract calls on the pending state. Call will try to discover this interface when access to the pending state is requested. If the backend does not support the pending state, Call returns ErrNoPendingState.
type SignerFn ¶
type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
SignerFn is a signer function callback when a contract requires a method to sign the transaction before submission.
type TransactOpts ¶
type TransactOpts struct { From common.Address // Ethereum account to send the transaction from Nonce *big.Int // Nonce to use for the transaction execution (nil = use pending state) Signer SignerFn // Method to use for signing the transaction (mandatory) Value *big.Int // Funds to transfer along the transaction (nil = 0 = no funds) GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle) GasFeeCap *big.Int // Gas fee cap to use for the 1559 transaction execution (nil = gas price oracle) GasTipCap *big.Int // Gas priority fee cap to use for the 1559 transaction execution (nil = gas price oracle) GasLimit uint64 // Gas limit to set for the transaction execution (0 = estimate) AccessList types.AccessList // Access list to set for the transaction execution (nil = no access list) Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) NoSend bool // Do all transact steps but do not send the transaction }
TransactOpts is the collection of authorization data required to create a valid Ethereum transaction.
func NewClefTransactor ¶
func NewClefTransactor(clef *external.ExternalSigner, account accounts.Account) *TransactOpts
NewClefTransactor is a utility method to easily create a transaction signer with a clef backend.
func NewKeyStoreTransactor ¶
func NewKeyStoreTransactor(keystore *keystore.KeyStore, account accounts.Account, chainID *big.Int) *TransactOpts
NewKeyStoreTransactor is a utility method to easily create a transaction signer from a decrypted key from a keystore.
func NewKeyedTransactor ¶
func NewKeyedTransactor(key *ecdsa.PrivateKey, chainID *big.Int) *TransactOpts
NewKeyedTransactor is a utility method to easily create a transaction signer from a single private key.
type WatchOpts ¶
type WatchOpts struct { Start *uint64 // Start of the queried range (nil = latest) Context context.Context // Network context to support cancellation and timeouts (nil = no timeout) }
WatchOpts is the collection of options to fine tune subscribing for events within a bound contract.
Source Files ¶
auth.go backend.go base.go dep_tree.go lib.go util.go
Directories ¶
Path | Synopsis |
---|---|
accounts/abi/bind/v2/internal |
- Version
- v1.16.0 (latest)
- Published
- Jun 26, 2025
- Platform
- linux/amd64
- Imports
- 20 packages
- Last checked
- 23 hours ago –
Tools for package owners.