gitlab.com/yannislg/go-pulse@v0.0.0-20210722055913-a3e24e95638d/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  	// todo(rjl493456442) check the method is payable or not,
   175  	// reject invalid transaction at the first place
   176  	return c.transact(opts, &c.address, input)
   177  }
   178  
   179  // RawTransact initiates a transaction with the given raw calldata as the input.
   180  // It's usually used to initiates transaction for invoking **Fallback** function.
   181  func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
   182  	// todo(rjl493456442) check the method is payable or not,
   183  	// reject invalid transaction at the first place
   184  	return c.transact(opts, &c.address, calldata)
   185  }
   186  
   187  // Transfer initiates a plain transaction to move funds to the contract, calling
   188  // its default method if one is available.
   189  func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
   190  	// todo(rjl493456442) check the payable fallback or receive is defined
   191  	// or not, reject invalid transaction at the first place
   192  	return c.transact(opts, &c.address, nil)
   193  }
   194  
   195  // transact executes an actual transaction invocation, first deriving any missing
   196  // authorization fields, and then scheduling the transaction for execution.
   197  func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   198  	var err error
   199  
   200  	// Ensure a valid value field and resolve the account nonce
   201  	value := opts.Value
   202  	if value == nil {
   203  		value = new(big.Int)
   204  	}
   205  	var nonce uint64
   206  	if opts.Nonce == nil {
   207  		nonce, err = c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
   208  		if err != nil {
   209  			return nil, fmt.Errorf("failed to retrieve account nonce: %v", err)
   210  		}
   211  	} else {
   212  		nonce = opts.Nonce.Uint64()
   213  	}
   214  	// Figure out the gas allowance and gas price values
   215  	gasPrice := opts.GasPrice
   216  	if gasPrice == nil {
   217  		gasPrice, err = c.transactor.SuggestGasPrice(ensureContext(opts.Context))
   218  		if err != nil {
   219  			return nil, fmt.Errorf("failed to suggest gas price: %v", err)
   220  		}
   221  	}
   222  	gasLimit := opts.GasLimit
   223  	if gasLimit == 0 {
   224  		// Gas estimation cannot succeed without code for method invocations
   225  		if contract != nil {
   226  			if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
   227  				return nil, err
   228  			} else if len(code) == 0 {
   229  				return nil, ErrNoCode
   230  			}
   231  		}
   232  		// If the contract surely has code (or code is not needed), estimate the transaction
   233  		msg := ethereum.CallMsg{From: opts.From, To: contract, GasPrice: gasPrice, Value: value, Data: input}
   234  		gasLimit, err = c.transactor.EstimateGas(ensureContext(opts.Context), msg)
   235  		if err != nil {
   236  			return nil, fmt.Errorf("failed to estimate gas needed: %v", err)
   237  		}
   238  	}
   239  	// Create the transaction, sign it and schedule it for execution
   240  	var rawTx *types.Transaction
   241  	if contract == nil {
   242  		rawTx = types.NewContractCreation(nonce, value, gasLimit, gasPrice, input)
   243  	} else {
   244  		rawTx = types.NewTransaction(nonce, c.address, value, gasLimit, gasPrice, input)
   245  	}
   246  	if opts.Signer == nil {
   247  		return nil, errors.New("no signer to authorize the transaction with")
   248  	}
   249  	signedTx, err := opts.Signer(types.HomesteadSigner{}, opts.From, rawTx)
   250  	if err != nil {
   251  		return nil, err
   252  	}
   253  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
   254  		return nil, err
   255  	}
   256  	return signedTx, nil
   257  }
   258  
   259  // FilterLogs filters contract logs for past blocks, returning the necessary
   260  // channels to construct a strongly typed bound iterator on top of them.
   261  func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   262  	// Don't crash on a lazy user
   263  	if opts == nil {
   264  		opts = new(FilterOpts)
   265  	}
   266  	// Append the event selector to the query parameters and construct the topic set
   267  	query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
   268  
   269  	topics, err := makeTopics(query...)
   270  	if err != nil {
   271  		return nil, nil, err
   272  	}
   273  	// Start the background filtering
   274  	logs := make(chan types.Log, 128)
   275  
   276  	config := ethereum.FilterQuery{
   277  		Addresses: []common.Address{c.address},
   278  		Topics:    topics,
   279  		FromBlock: new(big.Int).SetUint64(opts.Start),
   280  	}
   281  	if opts.End != nil {
   282  		config.ToBlock = new(big.Int).SetUint64(*opts.End)
   283  	}
   284  	/* TODO(karalabe): Replace the rest of the method below with this when supported
   285  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   286  	*/
   287  	buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
   288  	if err != nil {
   289  		return nil, nil, err
   290  	}
   291  	sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
   292  		for _, log := range buff {
   293  			select {
   294  			case logs <- log:
   295  			case <-quit:
   296  				return nil
   297  			}
   298  		}
   299  		return nil
   300  	}), nil
   301  
   302  	if err != nil {
   303  		return nil, nil, err
   304  	}
   305  	return logs, sub, nil
   306  }
   307  
   308  // WatchLogs filters subscribes to contract logs for future blocks, returning a
   309  // subscription object that can be used to tear down the watcher.
   310  func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   311  	// Don't crash on a lazy user
   312  	if opts == nil {
   313  		opts = new(WatchOpts)
   314  	}
   315  	// Append the event selector to the query parameters and construct the topic set
   316  	query = append([][]interface{}{{c.abi.Events[name].ID()}}, query...)
   317  
   318  	topics, err := makeTopics(query...)
   319  	if err != nil {
   320  		return nil, nil, err
   321  	}
   322  	// Start the background filtering
   323  	logs := make(chan types.Log, 128)
   324  
   325  	config := ethereum.FilterQuery{
   326  		Addresses: []common.Address{c.address},
   327  		Topics:    topics,
   328  	}
   329  	if opts.Start != nil {
   330  		config.FromBlock = new(big.Int).SetUint64(*opts.Start)
   331  	}
   332  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   333  	if err != nil {
   334  		return nil, nil, err
   335  	}
   336  	return logs, sub, nil
   337  }
   338  
   339  // UnpackLog unpacks a retrieved log into the provided output structure.
   340  func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
   341  	if len(log.Data) > 0 {
   342  		if err := c.abi.Unpack(out, event, log.Data); err != nil {
   343  			return err
   344  		}
   345  	}
   346  	var indexed abi.Arguments
   347  	for _, arg := range c.abi.Events[event].Inputs {
   348  		if arg.Indexed {
   349  			indexed = append(indexed, arg)
   350  		}
   351  	}
   352  	return parseTopics(out, indexed, log.Topics[1:])
   353  }
   354  
   355  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   356  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
   357  	if len(log.Data) > 0 {
   358  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   359  			return err
   360  		}
   361  	}
   362  	var indexed abi.Arguments
   363  	for _, arg := range c.abi.Events[event].Inputs {
   364  		if arg.Indexed {
   365  			indexed = append(indexed, arg)
   366  		}
   367  	}
   368  	return parseTopicsIntoMap(out, indexed, log.Topics[1:])
   369  }
   370  
   371  // ensureContext is a helper method to ensure a context is not nil, even if the
   372  // user specified it as such.
   373  func ensureContext(ctx context.Context) context.Context {
   374  	if ctx == nil {
   375  		return context.TODO()
   376  	}
   377  	return ctx
   378  }