abi

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2022 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package abi implements the Ethereum ABI (Application Binary Interface).

The Ethereum ABI is strongly typed, known at compile time and static. This ABI will handle basic type casting; unsigned to signed and visa versa. It does not handle slice casting such as unsigned slice to signed slice. Bit size type casting is also handled. ints with a bit size of 32 will be properly cast to int256, etc.

Index

Constants

View Source
const (
	IntTy byte = iota
	UintTy
	BoolTy
	StringTy
	SliceTy
	ArrayTy
	AddressTy
	FixedBytesTy
	BytesTy
	HashTy
	FixedPointTy
	FunctionTy
)

Type enumerator

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. suicided).
	ErrNoCode = errors.New("no contract code at given address")

	// This error 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")

	// This error is returned by WaitDeployed if contract creation leaves an
	// empty contract behind.
	ErrNoCodeAfterDeploy = errors.New("no contract code after deployment")
)

Functions

func U256

func U256(n *big.Int) []byte

U256 converts a big Int into a 256bit EVM number.

Types

type ABI

type ABI struct {
	Constructor Method
	Methods     map[string]Method
	Events      map[string]Event
}

The ABI holds information about a contract's context and available invokable methods. It will allow you to type check function calls and packs data accordingly.

func JSON

func JSON(reader io.Reader) (ABI, error)

JSON returns a parsed ABI interface and error if it failed.

func (*ABI) MethodById

func (abi *ABI) MethodById(sigdata []byte) (*Method, error)

MethodById looks up a method by the 4-byte id returns nil if none found

func (ABI) Pack

func (abi ABI) Pack(name string, args ...interface{}) ([]byte, error)

Pack the given method name to conform the ABI. Method call's data will consist of method_id, args0, arg1, ... argN. Method id consists of 4 bytes and arguments are all 32 bytes. Method ids are created from the first 4 bytes of the hash of the methods string signature. (signature = baz(uint32,string32))

func (*ABI) UnmarshalJSON

func (abi *ABI) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface

func (ABI) Unpack

func (abi ABI) Unpack(v interface{}, name string, output []byte) (err error)

Unpack output in v according to the abi specification

type Argument

type Argument struct {
	Name    string
	Type    Type
	Indexed bool // indexed is only used by events
}

Argument holds the name of the argument and the corresponding type. Types are used when packing and testing arguments.

func (*Argument) UnmarshalJSON

func (argument *Argument) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface

type Arguments

type Arguments []Argument

func (Arguments) LengthNonIndexed

func (arguments Arguments) LengthNonIndexed() int

LengthNonIndexed returns the number of arguments when not counting 'indexed' ones. Only events can ever have 'indexed' arguments, it should always be false on arguments for method input/output

func (Arguments) NonIndexed

func (arguments Arguments) NonIndexed() Arguments

NonIndexed returns the arguments with indexed arguments filtered out

func (Arguments) Pack

func (arguments Arguments) Pack(args ...interface{}) ([]byte, error)

Pack performs the operation Go format -> Hexdata

func (Arguments) PackValues

func (arguments Arguments) PackValues(args []interface{}) ([]byte, error)

PackValues performs the operation Go format -> Hexdata It is the semantic opposite of UnpackValues

func (Arguments) Unpack

func (arguments Arguments) Unpack(v interface{}, data []byte) error

Unpack performs the operation hexdata -> Go format

func (Arguments) UnpackValues

func (arguments Arguments) UnpackValues(data []byte) ([]interface{}, error)

UnpackValues can be used to unpack ABI-encoded hexdata according to the ABI-specification, without supplying a struct to unpack into. Instead, this method returns a list containing the values. An atomic argument will be a list with one element.

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, 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, 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, result 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) 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) 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 {
	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

	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)
	// ContractCall executes an Ethereum contract call with the specified data as the
	// input.
	CallContract(ctx context.Context, call types.CallMsg, blockNumber *big.Int) ([]byte, error)
}

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

type ContractFilterer

type ContractFilterer interface {
	// FilterLogs executes a log filter operation, blocking during execution and
	// returning all the results in one batch.
	//
	// TODO(karalabe): Deprecate when the subscription one can return past data too.
	FilterLogs(ctx context.Context, query types.FilterQuery) ([]types.Log, error)

	// SubscribeFilterLogs creates a background log filtering operation, returning
	// a subscription immediately, which can be used to stream the found events.
	SubscribeFilterLogs(ctx context.Context, query types.FilterQuery, ch chan<- types.Log) (types.Subscription, error)
}

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

type ContractTransactor

type ContractTransactor interface {
	// 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)
	// SuggestGasPrice retrieves the currently suggested gas price to allow a timely
	// execution of a transaction.
	SuggestGasPrice(ctx context.Context) (*big.Int, error)
	// EstimateGas tries to estimate the gas needed to execute a specific
	// transaction based on the current pending state of the backend blockchain.
	// There is no guarantee that this is the true gas limit requirement as other
	// transactions may be added or removed by miners, but it should provide a basis
	// for setting a reasonable default.
	EstimateGas(ctx context.Context, call types.CallMsg) (gas uint64, err error)
	// SendTransaction injects the transaction into the pending pool for execution.
	SendTransaction(ctx context.Context, tx *types.Transaction) error
}

ContractTransactor defines the methods needed to allow operating with contract on a write only basis. Beside 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 Event

type Event struct {
	Name      string
	Anonymous bool
	Inputs    Arguments
}

Event is an event potentially triggered by the EVM's LOG mechanism. The Event holds type information (inputs) about the yielded output. Anonymous events don't get the signature canonical representation as the first LOG topic.

func (Event) Id

func (e Event) Id() common.Hash

Id returns the canonical representation of the event's signature used by the abi definition to identify event names and types.

func (Event) String

func (e Event) String() string

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 Method

type Method struct {
	Name    string
	Const   bool
	Inputs  Arguments
	Outputs Arguments
}

Method represents a callable given a `Name` and whether the method is a constant. If the method is `Const` no transaction needs to be created for this particular Method call. It can easily be simulated using a local VM. For example a `Balance()` method only needs to retrieve something from the storage and therefor requires no Tx to be send to the network. A method such as `Transact` does require a Tx and thus will be flagged `true`. Input specifies the required input parameters for this gives method.

func (Method) Id

func (method Method) Id() []byte

func (Method) Sig

func (method Method) Sig() string

Sig returns the methods string signature according to the ABI spec.

Example

function foo(uint32 a, int b)    =    "foo(uint32,int256)"

Please note that "int" is substitute for its canonical representation "int256"

func (Method) String

func (method Method) String() string

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 types.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

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 along the transaction (nil = 0 = no funds)
	GasPrice *big.Int // Gas price to use for the 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)
}

TransactOpts is the collection of authorization data required to create a valid Ethereum transaction.

type Type

type Type struct {
	Elem *Type

	Kind reflect.Kind
	Type reflect.Type
	Size int
	T    byte // Our own type checking
	// contains filtered or unexported fields
}

Type is the reflection of the supported argument type

func NewType

func NewType(t string) (typ Type, err error)

NewType creates a new reflection type of abi type given in t.

func (Type) String

func (t Type) String() (out string)

String implements Stringer

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.

Jump to

Keyboard shortcuts

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