accounts/abi/bind, cmd/abigen: Go API generator around an EVM ABI
This commit is contained in:
@ -26,11 +26,6 @@ import (
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
)
|
||||
|
||||
// Executer is an executer method for performing state executions. It takes one
|
||||
// argument which is the input data and expects output data to be returned as
|
||||
// multiple 32 byte word length concatenated slice
|
||||
type Executer func(datain []byte) []byte
|
||||
|
||||
// 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.
|
||||
@ -169,21 +164,6 @@ func toGoType(i int, t Argument, output []byte) (interface{}, error) {
|
||||
return nil, fmt.Errorf("abi: unknown type %v", t.Type.T)
|
||||
}
|
||||
|
||||
// Call will unmarshal the output of the call in v. It will return an error if
|
||||
// invalid type is given or if the output is too short to conform to the ABI
|
||||
// spec.
|
||||
//
|
||||
// Call supports all of the available types and accepts a struct or an interface
|
||||
// slice if the return is a tuple.
|
||||
func (abi ABI) Call(executer Executer, v interface{}, name string, args ...interface{}) error {
|
||||
callData, err := abi.Pack(name, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return abi.unmarshal(v, name, executer(callData))
|
||||
}
|
||||
|
||||
// these variable are used to determine certain types during type assertion for
|
||||
// assignment.
|
||||
var (
|
||||
@ -193,8 +173,8 @@ var (
|
||||
r_byte = reflect.TypeOf(byte(0))
|
||||
)
|
||||
|
||||
// unmarshal output in v according to the abi specification
|
||||
func (abi ABI) unmarshal(v interface{}, name string, output []byte) error {
|
||||
// Unpack output in v according to the abi specification
|
||||
func (abi ABI) Unpack(v interface{}, name string, output []byte) error {
|
||||
var method = abi.Methods[name]
|
||||
|
||||
if len(output) == 0 {
|
||||
|
@ -579,7 +579,7 @@ func TestMultiReturnWithStruct(t *testing.T) {
|
||||
Int *big.Int
|
||||
String string
|
||||
}
|
||||
err = abi.unmarshal(&inter, "multi", buff.Bytes())
|
||||
err = abi.Unpack(&inter, "multi", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -597,7 +597,7 @@ func TestMultiReturnWithStruct(t *testing.T) {
|
||||
Int *big.Int
|
||||
}
|
||||
|
||||
err = abi.unmarshal(&reversed, "multi", buff.Bytes())
|
||||
err = abi.Unpack(&reversed, "multi", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -629,7 +629,7 @@ func TestMultiReturnWithSlice(t *testing.T) {
|
||||
buff.Write(common.RightPadBytes([]byte(stringOut), 32))
|
||||
|
||||
var inter []interface{}
|
||||
err = abi.unmarshal(&inter, "multi", buff.Bytes())
|
||||
err = abi.Unpack(&inter, "multi", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -661,13 +661,13 @@ func TestMarshalArrays(t *testing.T) {
|
||||
output := common.LeftPadBytes([]byte{1}, 32)
|
||||
|
||||
var bytes10 [10]byte
|
||||
err = abi.unmarshal(&bytes10, "bytes32", output)
|
||||
err = abi.Unpack(&bytes10, "bytes32", output)
|
||||
if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
|
||||
t.Error("expected error or bytes32 not be assignable to bytes10:", err)
|
||||
}
|
||||
|
||||
var bytes32 [32]byte
|
||||
err = abi.unmarshal(&bytes32, "bytes32", output)
|
||||
err = abi.Unpack(&bytes32, "bytes32", output)
|
||||
if err != nil {
|
||||
t.Error("didn't expect error:", err)
|
||||
}
|
||||
@ -681,13 +681,13 @@ func TestMarshalArrays(t *testing.T) {
|
||||
)
|
||||
|
||||
var b10 B10
|
||||
err = abi.unmarshal(&b10, "bytes32", output)
|
||||
err = abi.Unpack(&b10, "bytes32", output)
|
||||
if err == nil || err.Error() != "abi: cannot unmarshal src (len=32) in to dst (len=10)" {
|
||||
t.Error("expected error or bytes32 not be assignable to bytes10:", err)
|
||||
}
|
||||
|
||||
var b32 B32
|
||||
err = abi.unmarshal(&b32, "bytes32", output)
|
||||
err = abi.Unpack(&b32, "bytes32", output)
|
||||
if err != nil {
|
||||
t.Error("didn't expect error:", err)
|
||||
}
|
||||
@ -697,7 +697,7 @@ func TestMarshalArrays(t *testing.T) {
|
||||
|
||||
output[10] = 1
|
||||
var shortAssignLong [32]byte
|
||||
err = abi.unmarshal(&shortAssignLong, "bytes10", output)
|
||||
err = abi.Unpack(&shortAssignLong, "bytes10", output)
|
||||
if err != nil {
|
||||
t.Error("didn't expect error:", err)
|
||||
}
|
||||
@ -722,7 +722,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
|
||||
// marshal int
|
||||
var Int *big.Int
|
||||
err = abi.unmarshal(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
|
||||
err = abi.Unpack(&Int, "int", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -733,7 +733,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
|
||||
// marshal bool
|
||||
var Bool bool
|
||||
err = abi.unmarshal(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
|
||||
err = abi.Unpack(&Bool, "bool", common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000001"))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -750,7 +750,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
buff.Write(bytesOut)
|
||||
|
||||
var Bytes []byte
|
||||
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes())
|
||||
err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -766,7 +766,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
bytesOut = common.RightPadBytes([]byte("hello"), 64)
|
||||
buff.Write(bytesOut)
|
||||
|
||||
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes())
|
||||
err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -782,7 +782,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
bytesOut = common.RightPadBytes([]byte("hello"), 63)
|
||||
buff.Write(bytesOut)
|
||||
|
||||
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes())
|
||||
err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -792,7 +792,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
}
|
||||
|
||||
// marshal dynamic bytes output empty
|
||||
err = abi.unmarshal(&Bytes, "bytes", nil)
|
||||
err = abi.Unpack(&Bytes, "bytes", nil)
|
||||
if err == nil {
|
||||
t.Error("expected error")
|
||||
}
|
||||
@ -803,7 +803,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000005"))
|
||||
buff.Write(common.RightPadBytes([]byte("hello"), 32))
|
||||
|
||||
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes())
|
||||
err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -817,7 +817,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
buff.Write(common.RightPadBytes([]byte("hello"), 32))
|
||||
|
||||
var hash common.Hash
|
||||
err = abi.unmarshal(&hash, "fixed", buff.Bytes())
|
||||
err = abi.Unpack(&hash, "fixed", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
@ -830,12 +830,12 @@ func TestUnmarshal(t *testing.T) {
|
||||
// marshal error
|
||||
buff.Reset()
|
||||
buff.Write(common.Hex2Bytes("0000000000000000000000000000000000000000000000000000000000000020"))
|
||||
err = abi.unmarshal(&Bytes, "bytes", buff.Bytes())
|
||||
err = abi.Unpack(&Bytes, "bytes", buff.Bytes())
|
||||
if err == nil {
|
||||
t.Error("expected error")
|
||||
}
|
||||
|
||||
err = abi.unmarshal(&Bytes, "multi", make([]byte, 64))
|
||||
err = abi.Unpack(&Bytes, "multi", make([]byte, 64))
|
||||
if err == nil {
|
||||
t.Error("expected error")
|
||||
}
|
||||
@ -850,7 +850,7 @@ func TestUnmarshal(t *testing.T) {
|
||||
buff.Write(bytesOut)
|
||||
|
||||
var out []interface{}
|
||||
err = abi.unmarshal(&out, "mixedBytes", buff.Bytes())
|
||||
err = abi.Unpack(&out, "mixedBytes", buff.Bytes())
|
||||
if err != nil {
|
||||
t.Fatal("didn't expect error:", err)
|
||||
}
|
||||
|
247
accounts/abi/bind/backend.go
Normal file
247
accounts/abi/bind/backend.go
Normal file
@ -0,0 +1,247 @@
|
||||
// Copyright 2016 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package bind
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
"github.com/ethereum/go-ethereum/rlp"
|
||||
"github.com/ethereum/go-ethereum/rpc"
|
||||
)
|
||||
|
||||
// ContractCaller defines the methods needed to allow operating with contract on a read
|
||||
// only basis.
|
||||
type ContractCaller interface {
|
||||
// ContractCall executes an Ethereum contract call with the specified data as
|
||||
// the input.
|
||||
ContractCall(contract common.Address, data []byte) ([]byte, 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 ContractTransactor interface {
|
||||
// Nonce retrieves the current pending nonce associated with an account.
|
||||
AccountNonce(account common.Address) (uint64, error)
|
||||
|
||||
// GasPrice retrieves the currently suggested gas price to allow a timely execution
|
||||
// of a transaction.
|
||||
GasPrice() (*big.Int, error)
|
||||
|
||||
// GasLimit tries to estimate the gas needed to execute a specific transaction.
|
||||
GasLimit(sender, contract common.Address, value *big.Int, data []byte) (*big.Int, error)
|
||||
|
||||
// SendTransaction injects the transaction into the pending pool for execution.
|
||||
SendTransaction(*types.Transaction) error
|
||||
}
|
||||
|
||||
// ContractBackend defines the methods needed to allow operating with contract
|
||||
// on a read-write basis.
|
||||
type ContractBackend interface {
|
||||
ContractCaller
|
||||
ContractTransactor
|
||||
}
|
||||
|
||||
// nilBackend implements bind.ContractBackend, but panics on any method call.
|
||||
// Its sole purpose is to support the binding tests to construct the generated
|
||||
// wrappers without calling any methods on them.
|
||||
type nilBackend struct{}
|
||||
|
||||
func (*nilBackend) ContractCall(common.Address, []byte) ([]byte, error) { panic("not implemented") }
|
||||
func (*nilBackend) SendTransaction(*types.Transaction) error { panic("not implemented") }
|
||||
func (*nilBackend) AccountNonce(common.Address) (uint64, error) { panic("not implemented") }
|
||||
func (*nilBackend) GasPrice() (*big.Int, error) { panic("not implemented") }
|
||||
func (*nilBackend) GasLimit(common.Address, common.Address, *big.Int, []byte) (*big.Int, error) {
|
||||
panic("not implemented")
|
||||
}
|
||||
|
||||
// Helper backend for internal tests. Will panic on any invocation!
|
||||
var NilBackend = new(nilBackend)
|
||||
|
||||
// rpcBackend implements bind.ContractBackend, and acts as the data provider to
|
||||
// Ethereum contracts bound to Go structs. It uses an RPC connection to delegate
|
||||
// all its functionality.
|
||||
//
|
||||
// Note: The current implementation is a blocking one. This should be replaced
|
||||
// by a proper async version when a real RPC client is created.
|
||||
type rpcBackend struct {
|
||||
client rpc.Client // RPC client connection to interact with an API server
|
||||
autoid uint32 // ID number to use for the next API request
|
||||
lock sync.Mutex // Singleton access until we get to request multiplexing
|
||||
}
|
||||
|
||||
// NewRPCBackend creates a new binding backend to an RPC provider that can be
|
||||
// used to interact with remote contracts.
|
||||
func NewRPCBackend(client rpc.Client) ContractBackend {
|
||||
return &rpcBackend{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
// request is a JSON RPC request package assembled internally from the client
|
||||
// method calls.
|
||||
type request struct {
|
||||
JsonRpc string `json:"jsonrpc"` // Version of the JSON RPC protocol, always set to 2.0
|
||||
Id int `json:"id"` // Auto incrementing ID number for this request
|
||||
Method string `json:"method"` // Remote procedure name to invoke on the server
|
||||
Params []interface{} `json:"params"` // List of parameters to pass through (keep types simple)
|
||||
}
|
||||
|
||||
// response is a JSON RPC response package sent back from the API server.
|
||||
type response struct {
|
||||
JsonRpc string `json:"jsonrpc"` // Version of the JSON RPC protocol, always set to 2.0
|
||||
Id int `json:"id"` // Auto incrementing ID number for this request
|
||||
Error json.RawMessage `json:"error"` // Any error returned by the remote side
|
||||
Result json.RawMessage `json:"result"` // Whatever the remote side sends us in reply
|
||||
}
|
||||
|
||||
// request forwards an API request to the RPC server, and parses the response.
|
||||
//
|
||||
// This is currently painfully non-concurrent, but it will have to do until we
|
||||
// find the time for niceties like this :P
|
||||
func (backend *rpcBackend) request(method string, params []interface{}) (json.RawMessage, error) {
|
||||
backend.lock.Lock()
|
||||
defer backend.lock.Unlock()
|
||||
|
||||
// Ugly hack to serialize an empty list properly
|
||||
if params == nil {
|
||||
params = []interface{}{}
|
||||
}
|
||||
// Assemble the request object
|
||||
req := &request{
|
||||
JsonRpc: "2.0",
|
||||
Id: int(atomic.AddUint32(&backend.autoid, 1)),
|
||||
Method: method,
|
||||
Params: params,
|
||||
}
|
||||
if err := backend.client.Send(req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res := new(response)
|
||||
if err := backend.client.Recv(res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(res.Error) > 0 {
|
||||
return nil, fmt.Errorf("remote error: %s", string(res.Error))
|
||||
}
|
||||
return res.Result, nil
|
||||
}
|
||||
|
||||
// ContractCall implements ContractCaller.ContractCall, delegating the execution of
|
||||
// a contract call to the remote node, returning the reply to for local processing.
|
||||
func (b *rpcBackend) ContractCall(contract common.Address, data []byte) ([]byte, error) {
|
||||
// Pack up the request into an RPC argument
|
||||
args := struct {
|
||||
To common.Address `json:"to"`
|
||||
Data string `json:"data"`
|
||||
}{
|
||||
To: contract,
|
||||
Data: common.ToHex(data),
|
||||
}
|
||||
// Execute the RPC call and retrieve the response
|
||||
res, err := b.request("eth_call", []interface{}{args, "pending"})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var hex string
|
||||
if err := json.Unmarshal(res, &hex); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Convert the response back to a Go byte slice and return
|
||||
return common.FromHex(hex), nil
|
||||
}
|
||||
|
||||
// AccountNonce implements ContractTransactor.AccountNonce, delegating the
|
||||
// current account nonce retrieval to the remote node.
|
||||
func (b *rpcBackend) AccountNonce(account common.Address) (uint64, error) {
|
||||
res, err := b.request("eth_getTransactionCount", []interface{}{account.Hex(), "pending"})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var hex string
|
||||
if err := json.Unmarshal(res, &hex); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return new(big.Int).SetBytes(common.FromHex(hex)).Uint64(), nil
|
||||
}
|
||||
|
||||
// GasPrice implements ContractTransactor.GasPrice, delegating the gas price
|
||||
// oracle request to the remote node.
|
||||
func (b *rpcBackend) GasPrice() (*big.Int, error) {
|
||||
res, err := b.request("eth_gasPrice", nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var hex string
|
||||
if err := json.Unmarshal(res, &hex); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return new(big.Int).SetBytes(common.FromHex(hex)), nil
|
||||
}
|
||||
|
||||
// GasLimit implements ContractTransactor.GasLimit, delegating the gas estimation
|
||||
// to the remote node.
|
||||
func (b *rpcBackend) GasLimit(sender, contract common.Address, value *big.Int, data []byte) (*big.Int, error) {
|
||||
// Pack up the request into an RPC argument
|
||||
args := struct {
|
||||
From common.Address `json:"from"`
|
||||
To common.Address `json:"to"`
|
||||
Value *rpc.HexNumber `json:"value"`
|
||||
Data string `json:"data"`
|
||||
}{
|
||||
From: sender,
|
||||
To: contract,
|
||||
Data: common.ToHex(data),
|
||||
Value: rpc.NewHexNumber(value),
|
||||
}
|
||||
// Execute the RPC call and retrieve the response
|
||||
res, err := b.request("eth_estimateGas", []interface{}{args})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var hex string
|
||||
if err := json.Unmarshal(res, &hex); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Convert the response back to a Go byte slice and return
|
||||
return new(big.Int).SetBytes(common.FromHex(hex)), nil
|
||||
}
|
||||
|
||||
// Transact implements ContractTransactor.SendTransaction, delegating the raw
|
||||
// transaction injection to the remote node.
|
||||
func (b *rpcBackend) SendTransaction(tx *types.Transaction) error {
|
||||
data, err := rlp.EncodeToBytes(tx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
res, err := b.request("eth_sendRawTransaction", []interface{}{common.ToHex(data)})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var hex string
|
||||
if err := json.Unmarshal(res, &hex); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
130
accounts/abi/bind/base.go
Normal file
130
accounts/abi/bind/base.go
Normal file
@ -0,0 +1,130 @@
|
||||
// Copyright 2016 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package bind
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts/abi"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/core/types"
|
||||
)
|
||||
|
||||
// SignerFn is a signer function callback when a contract requires a method to
|
||||
// sign the transaction before submission.
|
||||
type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
|
||||
|
||||
// AuthOpts is the authorization data required to create a valid Ethereum transaction.
|
||||
type AuthOpts struct {
|
||||
Account 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 *big.Int // Gas limit to set for the transaction execution (nil = estimate + 10%)
|
||||
}
|
||||
|
||||
// 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.
|
||||
type BoundContract struct {
|
||||
address common.Address // Deployment address of the contract on the Ethereum blockchain
|
||||
abi abi.ABI // Reflect based ABI to access the correct Ethereum methods
|
||||
caller ContractCaller // Read interface to interact with the blockchain
|
||||
transactor ContractTransactor // Write interface to interact with the blockchain
|
||||
}
|
||||
|
||||
// NewBoundContract creates a low level contract interface through which calls
|
||||
// and transactions may be made through.
|
||||
func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor) *BoundContract {
|
||||
return &BoundContract{
|
||||
address: address,
|
||||
abi: abi,
|
||||
caller: caller,
|
||||
transactor: transactor,
|
||||
}
|
||||
}
|
||||
|
||||
// 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 (c *BoundContract) Call(result interface{}, method string, params ...interface{}) error {
|
||||
input, err := c.abi.Pack(method, params...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
output, err := c.caller.ContractCall(c.address, input)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return c.abi.Unpack(result, method, output)
|
||||
}
|
||||
|
||||
// Transact invokes the (paid) contract method with params as input values and
|
||||
// value as the fund transfer to the contract.
|
||||
func (c *BoundContract) Transact(opts *AuthOpts, method string, params ...interface{}) (*types.Transaction, error) {
|
||||
input, err := c.abi.Pack(method, params...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Ensure a valid value field and resolve the account nonce
|
||||
value := opts.Value
|
||||
if value == nil {
|
||||
value = new(big.Int)
|
||||
}
|
||||
nonce := uint64(0)
|
||||
if opts.Nonce == nil {
|
||||
nonce, err = c.transactor.AccountNonce(opts.Account)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
|
||||
}
|
||||
} else {
|
||||
nonce = opts.Nonce.Uint64()
|
||||
}
|
||||
// Figure out the gas allowance and gas price values
|
||||
gasPrice := opts.GasPrice
|
||||
if gasPrice == nil {
|
||||
gasPrice, err = c.transactor.GasPrice()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to suggest gas price: %v", err)
|
||||
}
|
||||
}
|
||||
gasLimit := opts.GasLimit
|
||||
if gasLimit == nil {
|
||||
gasLimit, err = c.transactor.GasLimit(opts.Account, c.address, value, input)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to exstimate gas needed: %v", err)
|
||||
}
|
||||
}
|
||||
// Create the transaction, sign it and schedule it for execution
|
||||
rawTx := types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
|
||||
if opts.Signer == nil {
|
||||
return nil, errors.New("no signer to authorize the transaction with")
|
||||
}
|
||||
signedTx, err := opts.Signer(opts.Account, rawTx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := c.transactor.SendTransaction(signedTx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return signedTx, nil
|
||||
}
|
317
accounts/abi/bind/bind.go
Normal file
317
accounts/abi/bind/bind.go
Normal file
@ -0,0 +1,317 @@
|
||||
// Copyright 2016 The go-ethereum Authors
|
||||
// This file is part of the go-ethereum library.
|
||||
//
|
||||
// The go-ethereum library is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Lesser General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// The go-ethereum library is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public License
|
||||
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Package bind generates Ethereum contract Go bindings.
|
||||
package bind
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/ethereum/go-ethereum/accounts/abi"
|
||||
"golang.org/x/tools/imports"
|
||||
)
|
||||
|
||||
// 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 opposed to having to
|
||||
// manually maintain hard coded strings that break on runtime.
|
||||
func Bind(jsonABI string, pkg string, kind string) (string, error) {
|
||||
// Parse the actual ABI to generate the binding for
|
||||
abi, err := abi.JSON(strings.NewReader(jsonABI))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Generate the contract type, fields and methods
|
||||
code := new(bytes.Buffer)
|
||||
kind = strings.ToUpper(kind[:1]) + kind[1:]
|
||||
fmt.Fprintf(code, "%s\n", bindContract(kind, jsonABI))
|
||||
|
||||
methods := make([]string, 0, len(abi.Methods))
|
||||
for name, _ := range abi.Methods {
|
||||
methods = append(methods, name)
|
||||
}
|
||||
sort.Strings(methods)
|
||||
|
||||
for _, method := range methods {
|
||||
fmt.Fprintf(code, "%s\n", bindMethod(kind, abi.Methods[method]))
|
||||
}
|
||||
// Format the code with goimports and return
|
||||
buffer := new(bytes.Buffer)
|
||||
|
||||
fmt.Fprintf(buffer, "package %s\n\n", pkg)
|
||||
fmt.Fprintf(buffer, "%s\n\n", string(code.Bytes()))
|
||||
|
||||
blob, err := imports.Process("", buffer.Bytes(), nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(blob), nil
|
||||
}
|
||||
|
||||
// bindContract generates the basic wrapper code for interacting with an Ethereum
|
||||
// contract via the abi package. All contract methods will call into the generic
|
||||
// ones generated here.
|
||||
func bindContract(kind string, abi string) string {
|
||||
code := ""
|
||||
|
||||
// Generate the hard coded ABI used for Ethereum interaction
|
||||
code += fmt.Sprintf("// Ethereum ABI used to generate the binding from.\nconst %sABI = `%s`\n\n", kind, strings.TrimSpace(abi))
|
||||
|
||||
// Generate the Go struct with all the maintenance fields
|
||||
code += fmt.Sprintf("// %s is an auto generated Go binding around an Ethereum contract.\n", kind)
|
||||
code += fmt.Sprintf("type %s struct {\n", kind)
|
||||
code += fmt.Sprintf(" %sCaller // Read-only binding to the contract\n", kind)
|
||||
code += fmt.Sprintf(" %sTransactor // Write-only binding to the contract\n", kind)
|
||||
code += fmt.Sprintf("}\n\n")
|
||||
|
||||
code += fmt.Sprintf("// %sCaller is an auto generated read-only Go binding around an Ethereum contract.\n", kind)
|
||||
code += fmt.Sprintf("type %sCaller struct {\n", kind)
|
||||
code += fmt.Sprintf(" common *common%s // Contract binding common to callers and transactors\n", kind)
|
||||
code += fmt.Sprintf("}\n\n")
|
||||
|
||||
code += fmt.Sprintf("// %sTransactor is an auto generated write-only Go binding around an Ethereum contract.\n", kind)
|
||||
code += fmt.Sprintf("type %sTransactor struct {\n", kind)
|
||||
code += fmt.Sprintf(" common *common%s // Contract binding common to callers and transactors\n", kind)
|
||||
code += fmt.Sprintf("}\n\n")
|
||||
|
||||
code += fmt.Sprintf("// common%s is an auto generated Go binding around an Ethereum contract.\n", kind)
|
||||
code += fmt.Sprintf("type common%s struct {\n", kind)
|
||||
code += fmt.Sprintf(" contract *bind.BoundContract // Generic contract wrapper for the low level calls\n")
|
||||
code += fmt.Sprintf("}\n\n")
|
||||
|
||||
// Generate the constructor to create a bound contract
|
||||
code += fmt.Sprintf("// New%s creates a new instance of %s, bound to a specific deployed contract.\n", kind, kind)
|
||||
code += fmt.Sprintf("func New%s(address common.Address, backend bind.ContractBackend) (*%s, error) {\n", kind, kind)
|
||||
code += fmt.Sprintf(" common, err := newCommon%s(address, backend.(bind.ContractCaller), backend.(bind.ContractTransactor))\n", kind)
|
||||
code += fmt.Sprintf(" if err != nil {\n")
|
||||
code += fmt.Sprintf(" return nil, err\n")
|
||||
code += fmt.Sprintf(" }\n")
|
||||
code += fmt.Sprintf(" return &%s{%sCaller: %sCaller{common: common}, %sTransactor: %sTransactor{common: common}}, nil\n", kind, kind, kind, kind, kind)
|
||||
code += fmt.Sprintf("}\n\n")
|
||||
|
||||
code += fmt.Sprintf("// New%sCaller creates a new read-only instance of %s, bound to a specific deployed contract.\n", kind, kind)
|
||||
code += fmt.Sprintf("func New%sCaller(address common.Address, caller bind.ContractCaller) (*%sCaller, error) {\n", kind, kind)
|
||||
code += fmt.Sprintf(" common, err := newCommon%s(address, caller, nil)\n", kind)
|
||||
code += fmt.Sprintf(" if err != nil {\n")
|
||||
code += fmt.Sprintf(" return nil, err\n")
|
||||
code += fmt.Sprintf(" }\n")
|
||||
code += fmt.Sprintf(" return &%sCaller{common: common}, nil\n", kind)
|
||||
code += fmt.Sprintf("}\n\n")
|
||||
|
||||
code += fmt.Sprintf("// New%sTransactor creates a new write-only instance of %s, bound to a specific deployed contract.\n", kind, kind)
|
||||
code += fmt.Sprintf("func New%sTransactor(address common.Address, transactor bind.ContractTransactor) (*%sTransactor, error) {\n", kind, kind)
|
||||
code += fmt.Sprintf(" common, err := newCommon%s(address, nil, transactor)\n", kind)
|
||||
code += fmt.Sprintf(" if err != nil {\n")
|
||||
code += fmt.Sprintf(" return nil, err\n")
|
||||
code += fmt.Sprintf(" }\n")
|
||||
code += fmt.Sprintf(" return &%sTransactor{common: common}, nil\n", kind)
|
||||
code += fmt.Sprintf("}\n\n")
|
||||
|
||||
code += fmt.Sprintf("// newCommon%s creates an internal instance of %s, bound to a specific deployed contract.\n", kind, kind)
|
||||
code += fmt.Sprintf("func newCommon%s(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor) (*common%s, error) {\n", kind, kind)
|
||||
code += fmt.Sprintf(" parsed, err := abi.JSON(strings.NewReader(%sABI))\n", kind)
|
||||
code += fmt.Sprintf(" if err != nil {\n")
|
||||
code += fmt.Sprintf(" return nil, err\n")
|
||||
code += fmt.Sprintf(" }\n")
|
||||
code += fmt.Sprintf(" return &common%s{\n", kind)
|
||||
code += fmt.Sprintf(" contract: bind.NewBoundContract(address, parsed, caller, transactor),\n")
|
||||
code += fmt.Sprintf(" }, nil\n")
|
||||
code += fmt.Sprintf("}")
|
||||
|
||||
return code
|
||||
}
|
||||
|
||||
// bindMethod
|
||||
func bindMethod(kind string, method abi.Method) string {
|
||||
var (
|
||||
name = strings.ToUpper(method.Name[:1]) + method.Name[1:]
|
||||
prologue = new(bytes.Buffer)
|
||||
)
|
||||
// Generate the argument and return list for the function
|
||||
args := make([]string, 0, len(method.Inputs))
|
||||
for i, arg := range method.Inputs {
|
||||
param := arg.Name
|
||||
if param == "" {
|
||||
param = fmt.Sprintf("arg%d", i)
|
||||
}
|
||||
args = append(args, fmt.Sprintf("%s %s", param, bindType(arg.Type)))
|
||||
}
|
||||
returns, _ := bindReturn(prologue, name, method.Outputs)
|
||||
|
||||
// Generate the docs to help with coding against the binding
|
||||
callTypeDoc := "free data retrieval call"
|
||||
if !method.Const {
|
||||
callTypeDoc = "paid mutator transaction"
|
||||
}
|
||||
docs := fmt.Sprintf("// %s is a %s binding the contract method 0x%x.\n", name, callTypeDoc, method.Id())
|
||||
docs += fmt.Sprintf("// \n")
|
||||
docs += fmt.Sprintf("// Solidity: %s", strings.TrimPrefix(method.String(), "function "))
|
||||
|
||||
// Generate the method itself for both the read/write version and the combo too
|
||||
code := fmt.Sprintf("%s\n", prologue)
|
||||
if method.Const {
|
||||
code += fmt.Sprintf("%s\nfunc (_%s *%sCaller) %s(%s) (%s) {\n%s\n}\n", docs, kind, kind, name, strings.Join(args, ","), strings.Join(returns, ","), bindCallBody(kind, method.Name, args, returns))
|
||||
} else {
|
||||
args = append([]string{"auth *bind.AuthOpts"}, args...)
|
||||
code += fmt.Sprintf("%s\nfunc (_%s *%sTransactor) %s(%s) (*types.Transaction, error) {\n%s\n}\n", docs, kind, kind, name, strings.Join(args, ","), bindTransactionBody(kind, method.Name, args))
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
// bindType converts a Solidity type to a Go one. Since there is no clear mapping
|
||||
// from all Solidity types to Go ones (e.g. uint17), those that cannot be exactly
|
||||
// mapped will use an upscaled type (e.g. *big.Int).
|
||||
func bindType(kind abi.Type) string {
|
||||
stringKind := kind.String()
|
||||
|
||||
switch {
|
||||
case stringKind == "address":
|
||||
return "common.Address"
|
||||
|
||||
case stringKind == "hash":
|
||||
return "common.Hash"
|
||||
|
||||
case strings.HasPrefix(stringKind, "bytes"):
|
||||
if stringKind == "bytes" {
|
||||
return "[]byte"
|
||||
}
|
||||
return fmt.Sprintf("[%s]byte", stringKind[5:])
|
||||
|
||||
case strings.HasPrefix(stringKind, "int"):
|
||||
switch stringKind[:3] {
|
||||
case "8", "16", "32", "64":
|
||||
return stringKind
|
||||
}
|
||||
return "*big.Int"
|
||||
|
||||
case strings.HasPrefix(stringKind, "uint"):
|
||||
switch stringKind[:4] {
|
||||
case "8", "16", "32", "64":
|
||||
return stringKind
|
||||
}
|
||||
return "*big.Int"
|
||||
|
||||
default:
|
||||
return stringKind
|
||||
}
|
||||
}
|
||||
|
||||
// bindReturn creates the list of return parameters for a method invocation. If
|
||||
// all the fields of the return type are named, and there is more than one value
|
||||
// being returned, the returns are wrapped in a result struct.
|
||||
func bindReturn(prologue *bytes.Buffer, method string, outputs []abi.Argument) ([]string, string) {
|
||||
// Generate the anonymous return list for when a struct is not needed/possible
|
||||
var (
|
||||
returns = make([]string, 0, len(outputs)+1)
|
||||
anonymous = false
|
||||
)
|
||||
for _, ret := range outputs {
|
||||
returns = append(returns, bindType(ret.Type))
|
||||
if ret.Name == "" {
|
||||
anonymous = true
|
||||
}
|
||||
}
|
||||
if anonymous || len(returns) < 2 {
|
||||
returns = append(returns, "error")
|
||||
return returns, ""
|
||||
}
|
||||
// If the returns are named and numerous, wrap in a result struct
|
||||
wrapper, impl := bindReturnStruct(method, outputs)
|
||||
prologue.WriteString(impl + "\n")
|
||||
return []string{"*" + wrapper, "error"}, wrapper
|
||||
}
|
||||
|
||||
// bindReturnStruct creates a Go structure with the specified fields to be used
|
||||
// as the return type from a method call.
|
||||
func bindReturnStruct(method string, returns []abi.Argument) (string, string) {
|
||||
fields := make([]string, 0, len(returns))
|
||||
for _, ret := range returns {
|
||||
fields = append(fields, fmt.Sprintf("%s %s", strings.ToUpper(ret.Name[:1])+ret.Name[1:], bindType(ret.Type)))
|
||||
}
|
||||
kind := fmt.Sprintf("%sResult", method)
|
||||
docs := fmt.Sprintf("// %s is the result of the %s invocation.", kind, method)
|
||||
|
||||
return kind, fmt.Sprintf("%s\ntype %s struct {\n%s\n}", docs, kind, strings.Join(fields, "\n"))
|
||||
}
|
||||
|
||||
// bindCallBody creates the Go code to declare a batch of return values, invoke
|
||||
// an Ethereum method call with the requested parameters, parse the binary output
|
||||
// into the return values and return them.
|
||||
func bindCallBody(kind string, method string, params []string, returns []string) string {
|
||||
body := ""
|
||||
|
||||
// Allocate memory for each of the return values
|
||||
rets := make([]string, 0, len(returns)-1)
|
||||
if len(returns) > 1 {
|
||||
body += "var ("
|
||||
for i, kind := range returns[:len(returns)-1] { // Omit the final error
|
||||
name := fmt.Sprintf("ret%d", i)
|
||||
|
||||
rets = append(rets, name)
|
||||
body += fmt.Sprintf("%s = new(%s)\n", name, strings.TrimPrefix(kind, "*"))
|
||||
}
|
||||
body += ")\n"
|
||||
}
|
||||
// Assemble a single collector variable for the result ABI initialization
|
||||
result := strings.Join(rets, ",")
|
||||
if len(returns) > 2 {
|
||||
result = "[]interface{}{" + result + "}"
|
||||
}
|
||||
// Extract the parameter list into a flat variable name list
|
||||
inputs := make([]string, len(params))
|
||||
for i, param := range params {
|
||||
inputs[i] = strings.Split(param, " ")[0]
|
||||
}
|
||||
input := ""
|
||||
if len(inputs) > 0 {
|
||||
input = "," + strings.Join(inputs, ",")
|
||||
}
|
||||
// Request executing the contract call and return the results with the errors
|
||||
body += fmt.Sprintf("err := _%s.common.contract.Call(%s, \"%s\" %s)\n", kind, result, method, input)
|
||||
|
||||
outs := make([]string, 0, len(returns))
|
||||
for i, ret := range returns[:len(returns)-1] { // Handle th final error separately
|
||||
if strings.HasPrefix(ret, "*") {
|
||||
outs = append(outs, rets[i])
|
||||
} else {
|
||||
outs = append(outs, "*"+rets[i])
|
||||
}
|
||||
}
|
||||
outs = append(outs, "err")
|
||||
|
||||
body += fmt.Sprintf("return %s", strings.Join(outs, ","))
|
||||
|
||||
return body
|
||||
}
|
||||
|
||||
// bindTransactionBody creates the Go code to invoke an Ethereum transaction call
|
||||
// with the requested parameters, and return the assembled transaction object.
|
||||
func bindTransactionBody(kind string, method string, params []string) string {
|
||||
// Extract the parameter list into a flat variable name list
|
||||
inputs := make([]string, len(params)-1) // Omit the auth options
|
||||
for i, param := range params[1:] {
|
||||
inputs[i] = strings.Split(param, " ")[0]
|
||||
}
|
||||
input := ""
|
||||
if len(inputs) > 0 {
|
||||
input = "," + strings.Join(inputs, ",")
|
||||
}
|
||||
// Request executing the contract call and return the results with the errors
|
||||
return fmt.Sprintf("return _%s.common.contract.Transact(auth, \"%s\" %s)", kind, method, input)
|
||||
}
|
140
accounts/abi/bind/bind_test.go
Normal file
140
accounts/abi/bind/bind_test.go
Normal file
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user