github.com/googgoog/go-ethereum@v1.9.7/accounts/abi/bind/base.go (about)

     1  // Copyright 2015 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package bind
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  
    25  	"github.com/ethereum/go-ethereum"
    26  	"github.com/ethereum/go-ethereum/accounts/abi"
    27  	"github.com/ethereum/go-ethereum/common"
    28  	"github.com/ethereum/go-ethereum/core/types"
    29  	"github.com/ethereum/go-ethereum/crypto"
    30  	"github.com/ethereum/go-ethereum/event"
    31  )
    32  
    33  // SignerFn is a signer function callback when a contract requires a method to
    34  // sign the transaction before submission.
    35  type SignerFn func(types.Signer, common.Address, *types.Transaction) (*types.Transaction, error)
    36  
    37  // CallOpts is the collection of options to fine tune a contract call request.
    38  type CallOpts struct {
    39  	Pending     bool            // Whether to operate on the pending state or the last known one
    40  	From        common.Address  // Optional the sender address, otherwise the first account is used
    41  	BlockNumber *big.Int        // Optional the block number on which the call should be performed
    42  	Context     context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    43  }
    44  
    45  // TransactOpts is the collection of authorization data required to create a
    46  // valid Ethereum transaction.
    47  type TransactOpts struct {
    48  	From   common.Address // Ethereum account to send the transaction from
    49  	Nonce  *big.Int       // Nonce to use for the transaction execution (nil = use pending state)
    50  	Signer SignerFn       // Method to use for signing the transaction (mandatory)
    51  
    52  	Value    *big.Int // Funds to transfer along along the transaction (nil = 0 = no funds)
    53  	GasPrice *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
    54  	GasLimit uint64   // Gas limit to set for the transaction execution (0 = estimate)
    55  
    56  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    57  }
    58  
    59  // FilterOpts is the collection of options to fine tune filtering for events
    60  // within a bound contract.
    61  type FilterOpts struct {
    62  	Start uint64  // Start of the queried range
    63  	End   *uint64 // End of the range (nil = latest)
    64  
    65  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    66  }
    67  
    68  // WatchOpts is the collection of options to fine tune subscribing for events
    69  // within a bound contract.
    70  type WatchOpts struct {
    71  	Start   *uint64         // Start of the queried range (nil = latest)
    72  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    73  }
    74  
    75  // BoundContract is the base wrapper object that reflects a contract on the
    76  // Ethereum network. It contains a collection of methods that are used by the
    77  // higher level contract bindings to operate.
    78  type BoundContract struct {
    79  	address    common.Address     // Deployment address of the contract on the Ethereum blockchain
    80  	abi        abi.ABI            // Reflect based ABI to access the correct Ethereum methods
    81  	caller     ContractCaller     // Read interface to interact with the blockchain
    82  	transactor ContractTransactor // Write interface to interact with the blockchain
    83  	filterer   ContractFilterer   // Event filtering to interact with the blockchain
    84  }
    85  
    86  // NewBoundContract creates a low level contract interface through which calls
    87  // and transactions may be made through.
    88  func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract {
    89  	return &BoundContract{
    90  		address:    address,
    91  		abi:        abi,
    92  		caller:     caller,
    93  		transactor: transactor,
    94  		filterer:   filterer,
    95  	}
    96  }
    97  
    98  // DeployContract deploys a contract onto the Ethereum blockchain and binds the
    99  // deployment address with a Go wrapper.
   100  func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
   101  	// Otherwise try to deploy the contract
   102  	c := NewBoundContract(common.Address{}, abi, backend, backend, backend)
   103  
   104  	input, err := c.abi.Pack("", params...)
   105  	if err != nil {
   106  		return common.Address{}, nil, nil, err
   107  	}
   108  	tx, err := c.transact(opts, nil, append(bytecode, input...))
   109  	if err != nil {
   110  		return common.Address{}, nil, nil, err
   111  	}
   112  	c.address = crypto.CreateAddress(opts.From, tx.Nonce())
   113  	return c.address, tx, c, nil
   114  }
   115  
   116  // Call invokes the (constant) contract method with params as input values and
   117  // sets the output to result. The result type might be a single field for simple
   118  // returns, a slice of interfaces for anonymous returns and a struct for named
   119  // returns.
   120  func (c *BoundContract) Call(opts *CallOpts, result interface{}, method string, params ...interface{}) error {
   121  	// Don't crash on a lazy user
   122  	if opts == nil {
   123  		opts = new(CallOpts)
   124  	}
   125  	// Pack the input, call and unpack the results
   126  	input, err := c.abi.Pack(method, params...)
   127  	if err != nil {
   128  		return err
   129  	}
   130  	var (
   131  		msg    = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input}
   132  		ctx    = ensureContext(opts.Context)
   133  		code   []byte
   134  		output []byte
   135  	)
   136  	if opts.Pending {
   137  		pb, ok := c.caller.(PendingContractCaller)
   138  		if !ok {
   139  			return ErrNoPendingState
   140  		}
   141  		output, err = pb.PendingCallContract(ctx, msg)
   142  		if err == nil && len(output) == 0 {
   143  			// Make sure we have a contract to operate on, and bail out otherwise.
   144  			if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
   145  				return err
   146  			} else if len(code) == 0 {
   147  				return ErrNoCode
   148  			}
   149  		}
   150  	} else {
   151  		output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
   152  		if err == nil && len(output) == 0 {
   153  			// Make sure we have a contract to operate on, and bail out otherwise.
   154  			if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
   155  				return err
   156  			} else if len(code) == 0 {
   157  				return ErrNoCode
   158  			}
   159  		}
   160  	}
   161  	if err != nil {
   162  		return err
   163  	}
   164  	return c.abi.Unpack(result, method, output)
   165  }
   166  
   167  // Transact invokes the (paid) contract method with params as input values.
   168  func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
   169  	// Otherwise pack up the parameters and invoke the contract
   170  	input, err := c.abi.Pack(method, params...)
   171  	if err != nil {
   172  		return nil, err
   173  	}
   174  	return c.transact(opts, &c.address, input)
   175  }
   176  
   177  // Transfer initiates a plain transaction to move funds to the contract, calling
   178  // its default method if one is available.
   179  func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
   180  	return c.transact(opts, &c.address, nil)
   181  }
   182  
   183  // transact executes an actual transaction invocation, first deriving any missing
   184  // authorization fields, and then scheduling the transaction for execution.
   185  func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   186  	var err error
   187  
   188  	// Ensure a valid value field and resolve the account nonce
   189  	value := opts.Value
   190  	if value == nil {
   191  		value = new(big.Int)
   192  	}
   193  	var nonce uint64
   194  	if opts.Nonce == nil {
   195  		nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
   196  		if err != nil {
   197  			return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
   198  		}
   199  	} else {
   200  		nonce = opts.Nonce.Uint64()
   201  	}
   202  	// Figure out the gas allowance and gas price values
   203  	gasPrice := opts.GasPrice
   204  	if gasPrice == nil {
   205  		gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
   206  		if err != nil {
   207  			return nil, fmt.Errorf("failed to suggest gas price: %v", err)
   208  		}
   209  	}
   210  	gasLimit := opts.GasLimit
   211  	if gasLimit == 0 {
   212  		// Gas estimation cannot succeed without code for method invocations
   213  		if contract != nil {
   214  			if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
   215  				return nil, err
   216  			} else if len(code) == 0 {
   217  				return nil, ErrNoCode
   218  			}
   219  		}
   220  		// If the contract surely has code (or code is not needed), estimate the transaction
   221  		msg := ethereum.CallMsg{From: opts.From, To: contract, GasPrice: gasPrice, Value: value, Data: input}
   222  		gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
   223  		if err != nil {
   224  			return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
   225  		}
   226  	}
   227  	// Create the transaction, sign it and schedule it for execution
   228  	var rawTx *types.Transaction
   229  	if contract == nil {
   230  		rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
   231  	} else {
   232  		rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
   233  	}
   234  	if opts.Signer == nil {
   235  		return nil, errors.New("no signer to authorize the transaction with")
   236  	}
   237  	signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
   238  	if err != nil {
   239  		return nil, err
   240  	}
   241  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
   242  		return nil, err
   243  	}
   244  	return signedTx, nil
   245  }
   246  
   247  // FilterLogs filters contract logs for past blocks, returning the necessary
   248  // channels to construct a strongly typed bound iterator on top of them.
   249  func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   250  	// Don't crash on a lazy user
   251  	if opts == nil {
   252  		opts = new(FilterOpts)
   253  	}
   254  	// Append the event selector to the query parameters and construct the topic set
   255  	query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
   256  
   257  	topics, err := makeTopics(query...)
   258  	if err != nil {
   259  		return nil, nil, err
   260  	}
   261  	// Start the background filtering
   262  	logs := make(chan types.Log, 128)
   263  
   264  	config := ethereum.FilterQuery{
   265  		Addresses: []common.Address{c.address},
   266  		Topics:    topics,
   267  		FromBlock: new(big.Int).SetUint64(opts.Start),
   268  	}
   269  	if opts.End != nil {
   270  		config.ToBlock = new(big.Int).SetUint64(*opts.End)
   271  	}
   272  	/* TODO(karalabe): Replace the rest of the method below with this when supported
   273  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   274  	*/
   275  	buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
   276  	if err != nil {
   277  		return nil, nil, err
   278  	}
   279  	sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
   280  		for _, log := range buff {
   281  			select {
   282  			case logs <- log:
   283  			case <-quit:
   284  				return nil
   285  			}
   286  		}
   287  		return nil
   288  	}), nil
   289  
   290  	if err != nil {
   291  		return nil, nil, err
   292  	}
   293  	return logs, sub, nil
   294  }
   295  
   296  // WatchLogs filters subscribes to contract logs for future blocks, returning a
   297  // subscription object that can be used to tear down the watcher.
   298  func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   299  	// Don't crash on a lazy user
   300  	if opts == nil {
   301  		opts = new(WatchOpts)
   302  	}
   303  	// Append the event selector to the query parameters and construct the topic set
   304  	query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
   305  
   306  	topics, err := makeTopics(query...)
   307  	if err != nil {
   308  		return nil, nil, err
   309  	}
   310  	// Start the background filtering
   311  	logs := make(chan types.Log, 128)
   312  
   313  	config := ethereum.FilterQuery{
   314  		Addresses: []common.Address{c.address},
   315  		Topics:    topics,
   316  	}
   317  	if opts.Start != nil {
   318  		config.FromBlock = new(big.Int).SetUint64(*opts.Start)
   319  	}
   320  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   321  	if err != nil {
   322  		return nil, nil, err
   323  	}
   324  	return logs, sub, nil
   325  }
   326  
   327  // UnpackLog unpacks a retrieved log into the provided output structure.
   328  func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
   329  	if len(log.Data) > 0 {
   330  		if err := c.abi.Unpack(out, event, log.Data); err != nil {
   331  			return err
   332  		}
   333  	}
   334  	var indexed abi.Arguments
   335  	for _, arg := range c.abi.Events[event].Inputs {
   336  		if arg.Indexed {
   337  			indexed = append(indexed, arg)
   338  		}
   339  	}
   340  	return parseTopics(out, indexed, log.Topics[1:])
   341  }
   342  
   343  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   344  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
   345  	if len(log.Data) > 0 {
   346  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   347  			return err
   348  		}
   349  	}
   350  	var indexed abi.Arguments
   351  	for _, arg := range c.abi.Events[event].Inputs {
   352  		if arg.Indexed {
   353  			indexed = append(indexed, arg)
   354  		}
   355  	}
   356  	return parseTopicsIntoMap(out, indexed, log.Topics[1:])
   357  }
   358  
   359  // ensureContext is a helper method to ensure a context is not nil, even if the
   360  // user specified it as such.
   361  func ensureContext(ctx context.Context) context.Context {
   362  	if ctx == nil {
   363  		return context.TODO()
   364  	}
   365  	return ctx
   366  }