bind

package
v0.6.9 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2024 License: GPL-3.0, LGPL-3.0 Imports: 25 Imported by: 31

Documentation

Overview

Package bind generates Ethereum contract Go bindings.

Detailed usage document and tutorial available on the go-ethereum Wiki page: https://github.com/ethereum/go-ethereum/wiki/Native-DApps:-Go-bindings-to-Ethereum-contracts

Index

Constants

This section is empty.

Variables

View Source
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")

	// ErrNoAcceptedState is raised when attempting to perform a accepted state action
	// on a backend that doesn't implement AcceptedContractCaller.
	ErrNoAcceptedState = errors.New("backend does not support accepted 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")
)
View Source
var ErrNoChainID = errors.New("no chain id specified")

ErrNoChainID is returned whenever the user failed to specify a chain id.

View Source
var ErrNotAuthorized = errors.New("not authorized to sign this account")

ErrNotAuthorized is returned when an account is not properly unlocked.

Functions

func Bind

func Bind(types []string, abis []string, bytecodes []string, fsigs []map[string]string, pkg string, lang Lang, libs map[string]string, aliases map[string]string) (string, error)

Bind generates a Go wrapper around a contract ABI. This wrapper isn't meant to be used as is in client code, but rather as an intermediate struct which enforces compile time type safety and naming convention as opposed to having to manually maintain hard coded strings that break on runtime.

func BindHelper added in v0.4.10

func BindHelper(types []string, abis []string, bytecodes []string, fsigs []map[string]string, pkg string, lang Lang, libs map[string]string, aliases map[string]string, bindHook BindHook) (string, error)

func IsKeyWord added in v0.5.4

func IsKeyWord(arg string) bool

func WaitDeployed

func WaitDeployed(ctx context.Context, b DeployBackend, tx *types.Transaction) (common.Address, error)

WaitDeployed waits for a contract deployment transaction and returns the on-chain contract address when it is mined. It stops waiting when ctx is canceled.

func WaitMined

func WaitMined(ctx context.Context, b DeployBackend, tx *types.Transaction) (*types.Receipt, error)

WaitMined waits for tx to be mined on the blockchain. It stops waiting when the context is canceled.

Types

type AcceptedContractCaller

type AcceptedContractCaller interface {
	// AcceptedCodeAt returns the code of the given account in the accepted state.
	AcceptedCodeAt(ctx context.Context, contract common.Address) ([]byte, error)

	// AcceptedCallContract executes an Ethereum contract call against the accepted state.
	AcceptedCallContract(ctx context.Context, call interfaces.CallMsg) ([]byte, error)
}

AcceptedContractCaller defines methods to perform contract calls on the pending state. Call will try to discover this interface when access to the accepted state is requested. If the backend does not support the pending state, Call returns ErrNoAcceptedState.

type BindHook added in v0.4.10

type BindHook func(lang Lang, pkg string, types []string, contracts map[string]*TmplContract, structs map[string]*TmplStruct) (data interface{}, templateSource string, err error)

BindHook is a callback function that can be used to customize the binding.

type BlockHashContractCaller added in v0.6.5

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 interfaces.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 DeployContract

func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error)

DeployContract deploys a contract onto the Ethereum blockchain and binds the deployment address with a Go wrapper.

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

func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method string, params ...interface{}) error

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) FilterLogs

func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (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) 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 ...interface{}) (*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

func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error

UnpackLog unpacks a retrieved log into the provided output structure.

func (*BoundContract) UnpackLogIntoMap

func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error

UnpackLogIntoMap unpacks a retrieved log into the provided map.

func (*BoundContract) WatchLogs

func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (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 {
	Accepted    bool            // Whether to operate on the accepted 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 interfaces.CallMsg, blockNumber *big.Int) ([]byte, error)
}

ContractCaller defines the methods needed to allow operating with a contract on a read only basis.

type ContractFilterer

type ContractFilterer interface {
	interfaces.LogFilterer
}

ContractFilterer defines the methods needed to access log events using one-off queries or continuous event subscriptions.

type ContractTransactor

type ContractTransactor interface {
	interfaces.GasEstimator
	interfaces.GasPricer
	interfaces.GasPricer1559
	interfaces.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)

	// AcceptedCodeAt returns the code of the given account in the accepted state.
	AcceptedCodeAt(ctx context.Context, account common.Address) ([]byte, error)

	// NonceAt retrieves the nonce associated with an account.
	NonceAt(ctx context.Context, account common.Address, blockNum *big.Int) (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 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 Lang

type Lang int

Lang is a target programming language selector to generate bindings for.

const (
	LangGo Lang = iota
)

type MetaData

type MetaData struct {
	Sigs map[string]string
	Bin  string
	ABI  string
	// contains filtered or unexported fields
}

MetaData collects all metadata for a bound contract.

func (*MetaData) GetAbi

func (m *MetaData) GetAbi() (*abi.ABI, error)

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 TmplContract added in v0.4.10

type TmplContract struct {
	Type        string                 // Type name of the main contract binding
	InputABI    string                 // JSON ABI used as the input to generate the binding from
	InputBin    string                 // Optional EVM bytecode used to generate deploy code from
	FuncSigs    map[string]string      // Optional map: string signature -> 4-byte signature
	Constructor abi.Method             // Contract constructor for deploy parametrization
	Calls       map[string]*TmplMethod // Contract calls that only read state data
	Transacts   map[string]*TmplMethod // Contract calls that write state data
	Fallback    *TmplMethod            // Additional special fallback function
	Receive     *TmplMethod            // Additional special receive function
	Events      map[string]*tmplEvent  // Contract events accessors
	Libraries   map[string]string      // Same as tmplData, but filtered to only keep what the contract needs
	Library     bool                   // Indicator whether the contract is a library
}

TmplContract contains the data needed to generate an individual contract binding.

type TmplMethod added in v0.4.10

type TmplMethod struct {
	Original   abi.Method // Original method as parsed by the abi package
	Normalized abi.Method // Normalized version of the parsed method (capitalized names, non-anonymous args/returns)
	Structured bool       // Whether the returns should be accumulated into a struct
}

TmplMethod is a wrapper around an abi.Method that contains a few preprocessed and cached data fields.

type TmplStruct added in v0.4.10

type TmplStruct struct {
	Name   string       // Auto-generated struct name(before solidity v0.5.11) or raw name.
	Fields []*tmplField // Struct fields definition depends on the binding language.
}

TmplStruct is a wrapper around an abi.tuple and contains an auto-generated struct name.

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)

	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 deprecated

func NewKeyStoreTransactor(keystore *keystore.KeyStore, account accounts.Account) (*TransactOpts, error)

NewKeyStoreTransactor is a utility method to easily create a transaction signer from a decrypted key from a keystore.

Deprecated: Use NewKeyStoreTransactorWithChainID instead.

func NewKeyStoreTransactorWithChainID

func NewKeyStoreTransactorWithChainID(keystore *keystore.KeyStore, account accounts.Account, chainID *big.Int) (*TransactOpts, error)

NewKeyStoreTransactorWithChainID is a utility method to easily create a transaction signer from a decrypted key from a keystore.

func NewKeyedTransactor deprecated

func NewKeyedTransactor(key *ecdsa.PrivateKey) *TransactOpts

NewKeyedTransactor is a utility method to easily create a transaction signer from a single private key.

Deprecated: Use NewKeyedTransactorWithChainID instead.

func NewKeyedTransactorWithChainID

func NewKeyedTransactorWithChainID(key *ecdsa.PrivateKey, chainID *big.Int) (*TransactOpts, error)

NewKeyedTransactorWithChainID is a utility method to easily create a transaction signer from a single private key.

func NewTransactor deprecated

func NewTransactor(keyin io.Reader, passphrase string) (*TransactOpts, error)

NewTransactor is a utility method to easily create a transaction signer from an encrypted json key stream and the associated passphrase.

Deprecated: Use NewTransactorWithChainID instead.

func NewTransactorWithChainID

func NewTransactorWithChainID(keyin io.Reader, passphrase string, chainID *big.Int) (*TransactOpts, error)

NewTransactorWithChainID is a utility method to easily create a transaction signer from an encrypted json key stream and the associated passphrase.

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.

Directories

Path Synopsis
Package bind generates Ethereum contract Go bindings.
Package bind generates Ethereum contract Go bindings.

Jump to

Keyboard shortcuts

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