github.com/ethxdao/go-ethereum@v0.0.0-20221218102228-5ae34a9cc189/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  	"strings"
    25  	"sync"
    26  
    27  	"github.com/ethxdao/go-ethereum/accounts/abi"
    28  	"github.com/ethxdao/go-ethereum/common"
    29  	"github.com/ethxdao/go-ethereum/core/types"
    30  	"github.com/ethxdao/go-ethereum/crypto"
    31  	"github.com/ethxdao/go-ethereum/event"
    32  )
    33  
    34  // SignerFn is a signer function callback when a contract requires a method to
    35  // sign the transaction before submission.
    36  type SignerFn func(common.Address, *types.Transaction) (*types.Transaction, error)
    37  
    38  // CallOpts is the collection of options to fine tune a contract call request.
    39  type CallOpts struct {
    40  	Pending     bool            // Whether to operate on the pending state or the last known one
    41  	From        common.Address  // Optional the sender address, otherwise the first account is used
    42  	BlockNumber *big.Int        // Optional the block number on which the call should be performed
    43  	Context     context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    44  }
    45  
    46  // TransactOpts is the collection of authorization data required to create a
    47  // valid Ethereum transaction.
    48  type TransactOpts struct {
    49  	From   common.Address // Ethereum account to send the transaction from
    50  	Nonce  *big.Int       // Nonce to use for the transaction execution (nil = use pending state)
    51  	Signer SignerFn       // Method to use for signing the transaction (mandatory)
    52  
    53  	Value     *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
    54  	GasPrice  *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
    55  	GasFeeCap *big.Int // Gas fee cap to use for the 1559 transaction execution (nil = gas price oracle)
    56  	GasTipCap *big.Int // Gas priority fee cap to use for the 1559 transaction execution (nil = gas price oracle)
    57  	GasLimit  uint64   // Gas limit to set for the transaction execution (0 = estimate)
    58  
    59  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    60  
    61  	NoSend bool // Do all transact steps but do not send the transaction
    62  }
    63  
    64  // FilterOpts is the collection of options to fine tune filtering for events
    65  // within a bound contract.
    66  type FilterOpts struct {
    67  	Start uint64  // Start of the queried range
    68  	End   *uint64 // End of the range (nil = latest)
    69  
    70  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    71  }
    72  
    73  // WatchOpts is the collection of options to fine tune subscribing for events
    74  // within a bound contract.
    75  type WatchOpts struct {
    76  	Start   *uint64         // Start of the queried range (nil = latest)
    77  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    78  }
    79  
    80  // MetaData collects all metadata for a bound contract.
    81  type MetaData struct {
    82  	mu   sync.Mutex
    83  	Sigs map[string]string
    84  	Bin  string
    85  	ABI  string
    86  	ab   *abi.ABI
    87  }
    88  
    89  func (m *MetaData) GetAbi() (*abi.ABI, error) {
    90  	m.mu.Lock()
    91  	defer m.mu.Unlock()
    92  	if m.ab != nil {
    93  		return m.ab, nil
    94  	}
    95  	if parsed, err := abi.JSON(strings.NewReader(m.ABI)); err != nil {
    96  		return nil, err
    97  	} else {
    98  		m.ab = &parsed
    99  	}
   100  	return m.ab, nil
   101  }
   102  
   103  // BoundContract is the base wrapper object that reflects a contract on the
   104  // Ethereum network. It contains a collection of methods that are used by the
   105  // higher level contract bindings to operate.
   106  type BoundContract struct {
   107  	address    common.Address     // Deployment address of the contract on the Ethereum blockchain
   108  	abi        abi.ABI            // Reflect based ABI to access the correct Ethereum methods
   109  	caller     ContractCaller     // Read interface to interact with the blockchain
   110  	transactor ContractTransactor // Write interface to interact with the blockchain
   111  	filterer   ContractFilterer   // Event filtering to interact with the blockchain
   112  }
   113  
   114  // NewBoundContract creates a low level contract interface through which calls
   115  // and transactions may be made through.
   116  func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract {
   117  	return &BoundContract{
   118  		address:    address,
   119  		abi:        abi,
   120  		caller:     caller,
   121  		transactor: transactor,
   122  		filterer:   filterer,
   123  	}
   124  }
   125  
   126  // DeployContract deploys a contract onto the Ethereum blockchain and binds the
   127  // deployment address with a Go wrapper.
   128  func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
   129  	// Otherwise try to deploy the contract
   130  	c := NewBoundContract(common.Address{}, abi, backend, backend, backend)
   131  
   132  	input, err := c.abi.Pack("", params...)
   133  	if err != nil {
   134  		return common.Address{}, nil, nil, err
   135  	}
   136  	tx, err := c.transact(opts, nil, append(bytecode, input...))
   137  	if err != nil {
   138  		return common.Address{}, nil, nil, err
   139  	}
   140  	c.address = crypto.CreateAddress(opts.From, tx.Nonce())
   141  	return c.address, tx, c, nil
   142  }
   143  
   144  // Call invokes the (constant) contract method with params as input values and
   145  // sets the output to result. The result type might be a single field for simple
   146  // returns, a slice of interfaces for anonymous returns and a struct for named
   147  // returns.
   148  func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method string, params ...interface{}) error {
   149  	// Don't crash on a lazy user
   150  	if opts == nil {
   151  		opts = new(CallOpts)
   152  	}
   153  	if results == nil {
   154  		results = new([]interface{})
   155  	}
   156  	// Pack the input, call and unpack the results
   157  	input, err := c.abi.Pack(method, params...)
   158  	if err != nil {
   159  		return err
   160  	}
   161  	var (
   162  		msg    = ethereum.CallMsg{From: opts.From, To: &c.address, Data: input}
   163  		ctx    = ensureContext(opts.Context)
   164  		code   []byte
   165  		output []byte
   166  	)
   167  	if opts.Pending {
   168  		pb, ok := c.caller.(PendingContractCaller)
   169  		if !ok {
   170  			return ErrNoPendingState
   171  		}
   172  		output, err = pb.PendingCallContract(ctx, msg)
   173  		if err != nil {
   174  			return err
   175  		}
   176  		if len(output) == 0 {
   177  			// Make sure we have a contract to operate on, and bail out otherwise.
   178  			if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
   179  				return err
   180  			} else if len(code) == 0 {
   181  				return ErrNoCode
   182  			}
   183  		}
   184  	} else {
   185  		output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
   186  		if err != nil {
   187  			return err
   188  		}
   189  		if len(output) == 0 {
   190  			// Make sure we have a contract to operate on, and bail out otherwise.
   191  			if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
   192  				return err
   193  			} else if len(code) == 0 {
   194  				return ErrNoCode
   195  			}
   196  		}
   197  	}
   198  
   199  	if len(*results) == 0 {
   200  		res, err := c.abi.Unpack(method, output)
   201  		*results = res
   202  		return err
   203  	}
   204  	res := *results
   205  	return c.abi.UnpackIntoInterface(res[0], method, output)
   206  }
   207  
   208  // Transact invokes the (paid) contract method with params as input values.
   209  func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
   210  	// Otherwise pack up the parameters and invoke the contract
   211  	input, err := c.abi.Pack(method, params...)
   212  	if err != nil {
   213  		return nil, err
   214  	}
   215  	// todo(rjl493456442) check the method is payable or not,
   216  	// reject invalid transaction at the first place
   217  	return c.transact(opts, &c.address, input)
   218  }
   219  
   220  // RawTransact initiates a transaction with the given raw calldata as the input.
   221  // It's usually used to initiate transactions for invoking **Fallback** function.
   222  func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
   223  	// todo(rjl493456442) check the method is payable or not,
   224  	// reject invalid transaction at the first place
   225  	return c.transact(opts, &c.address, calldata)
   226  }
   227  
   228  // Transfer initiates a plain transaction to move funds to the contract, calling
   229  // its default method if one is available.
   230  func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
   231  	// todo(rjl493456442) check the payable fallback or receive is defined
   232  	// or not, reject invalid transaction at the first place
   233  	return c.transact(opts, &c.address, nil)
   234  }
   235  
   236  func (c *BoundContract) createDynamicTx(opts *TransactOpts, contract *common.Address, input []byte, head *types.Header) (*types.Transaction, error) {
   237  	// Normalize value
   238  	value := opts.Value
   239  	if value == nil {
   240  		value = new(big.Int)
   241  	}
   242  	// Estimate TipCap
   243  	gasTipCap := opts.GasTipCap
   244  	if gasTipCap == nil {
   245  		tip, err := c.transactor.SuggestGasTipCap(ensureContext(opts.Context))
   246  		if err != nil {
   247  			return nil, err
   248  		}
   249  		gasTipCap = tip
   250  	}
   251  	// Estimate FeeCap
   252  	gasFeeCap := opts.GasFeeCap
   253  	if gasFeeCap == nil {
   254  		gasFeeCap = new(big.Int).Add(
   255  			gasTipCap,
   256  			new(big.Int).Mul(head.BaseFee, big.NewInt(2)),
   257  		)
   258  	}
   259  	if gasFeeCap.Cmp(gasTipCap) < 0 {
   260  		return nil, fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", gasFeeCap, gasTipCap)
   261  	}
   262  	// Estimate GasLimit
   263  	gasLimit := opts.GasLimit
   264  	if opts.GasLimit == 0 {
   265  		var err error
   266  		gasLimit, err = c.estimateGasLimit(opts, contract, input, nil, gasTipCap, gasFeeCap, value)
   267  		if err != nil {
   268  			return nil, err
   269  		}
   270  	}
   271  	// create the transaction
   272  	nonce, err := c.getNonce(opts)
   273  	if err != nil {
   274  		return nil, err
   275  	}
   276  	baseTx := &types.DynamicFeeTx{
   277  		To:        contract,
   278  		Nonce:     nonce,
   279  		GasFeeCap: gasFeeCap,
   280  		GasTipCap: gasTipCap,
   281  		Gas:       gasLimit,
   282  		Value:     value,
   283  		Data:      input,
   284  	}
   285  	return types.NewTx(baseTx), nil
   286  }
   287  
   288  func (c *BoundContract) createLegacyTx(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   289  	if opts.GasFeeCap != nil || opts.GasTipCap != nil {
   290  		return nil, errors.New("maxFeePerGas or maxPriorityFeePerGas specified but london is not active yet")
   291  	}
   292  	// Normalize value
   293  	value := opts.Value
   294  	if value == nil {
   295  		value = new(big.Int)
   296  	}
   297  	// Estimate GasPrice
   298  	gasPrice := opts.GasPrice
   299  	if gasPrice == nil {
   300  		price, err := c.transactor.SuggestGasPrice(ensureContext(opts.Context))
   301  		if err != nil {
   302  			return nil, err
   303  		}
   304  		gasPrice = price
   305  	}
   306  	// Estimate GasLimit
   307  	gasLimit := opts.GasLimit
   308  	if opts.GasLimit == 0 {
   309  		var err error
   310  		gasLimit, err = c.estimateGasLimit(opts, contract, input, gasPrice, nil, nil, value)
   311  		if err != nil {
   312  			return nil, err
   313  		}
   314  	}
   315  	// create the transaction
   316  	nonce, err := c.getNonce(opts)
   317  	if err != nil {
   318  		return nil, err
   319  	}
   320  	baseTx := &types.LegacyTx{
   321  		To:       contract,
   322  		Nonce:    nonce,
   323  		GasPrice: gasPrice,
   324  		Gas:      gasLimit,
   325  		Value:    value,
   326  		Data:     input,
   327  	}
   328  	return types.NewTx(baseTx), nil
   329  }
   330  
   331  func (c *BoundContract) estimateGasLimit(opts *TransactOpts, contract *common.Address, input []byte, gasPrice, gasTipCap, gasFeeCap, value *big.Int) (uint64, error) {
   332  	if contract != nil {
   333  		// Gas estimation cannot succeed without code for method invocations.
   334  		if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
   335  			return 0, err
   336  		} else if len(code) == 0 {
   337  			return 0, ErrNoCode
   338  		}
   339  	}
   340  	msg := ethereum.CallMsg{
   341  		From:      opts.From,
   342  		To:        contract,
   343  		GasPrice:  gasPrice,
   344  		GasTipCap: gasTipCap,
   345  		GasFeeCap: gasFeeCap,
   346  		Value:     value,
   347  		Data:      input,
   348  	}
   349  	return c.transactor.EstimateGas(ensureContext(opts.Context), msg)
   350  }
   351  
   352  func (c *BoundContract) getNonce(opts *TransactOpts) (uint64, error) {
   353  	if opts.Nonce == nil {
   354  		return c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
   355  	} else {
   356  		return opts.Nonce.Uint64(), nil
   357  	}
   358  }
   359  
   360  // transact executes an actual transaction invocation, first deriving any missing
   361  // authorization fields, and then scheduling the transaction for execution.
   362  func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   363  	if opts.GasPrice != nil && (opts.GasFeeCap != nil || opts.GasTipCap != nil) {
   364  		return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
   365  	}
   366  	// Create the transaction
   367  	var (
   368  		rawTx *types.Transaction
   369  		err   error
   370  	)
   371  	if opts.GasPrice != nil {
   372  		rawTx, err = c.createLegacyTx(opts, contract, input)
   373  	} else {
   374  		// Only query for basefee if gasPrice not specified
   375  		if head, errHead := c.transactor.HeaderByNumber(ensureContext(opts.Context), nil); errHead != nil {
   376  			return nil, errHead
   377  		} else if head.BaseFee != nil {
   378  			rawTx, err = c.createDynamicTx(opts, contract, input, head)
   379  		} else {
   380  			// Chain is not London ready -> use legacy transaction
   381  			rawTx, err = c.createLegacyTx(opts, contract, input)
   382  		}
   383  	}
   384  	if err != nil {
   385  		return nil, err
   386  	}
   387  	// Sign the transaction and schedule it for execution
   388  	if opts.Signer == nil {
   389  		return nil, errors.New("no signer to authorize the transaction with")
   390  	}
   391  	signedTx, err := opts.Signer(opts.From, rawTx)
   392  	if err != nil {
   393  		return nil, err
   394  	}
   395  	if opts.NoSend {
   396  		return signedTx, nil
   397  	}
   398  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
   399  		return nil, err
   400  	}
   401  	return signedTx, nil
   402  }
   403  
   404  // FilterLogs filters contract logs for past blocks, returning the necessary
   405  // channels to construct a strongly typed bound iterator on top of them.
   406  func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   407  	// Don't crash on a lazy user
   408  	if opts == nil {
   409  		opts = new(FilterOpts)
   410  	}
   411  	// Append the event selector to the query parameters and construct the topic set
   412  	query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
   413  
   414  	topics, err := abi.MakeTopics(query...)
   415  	if err != nil {
   416  		return nil, nil, err
   417  	}
   418  	// Start the background filtering
   419  	logs := make(chan types.Log, 128)
   420  
   421  	config := ethereum.FilterQuery{
   422  		Addresses: []common.Address{c.address},
   423  		Topics:    topics,
   424  		FromBlock: new(big.Int).SetUint64(opts.Start),
   425  	}
   426  	if opts.End != nil {
   427  		config.ToBlock = new(big.Int).SetUint64(*opts.End)
   428  	}
   429  	/* TODO(karalabe): Replace the rest of the method below with this when supported
   430  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   431  	*/
   432  	buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
   433  	if err != nil {
   434  		return nil, nil, err
   435  	}
   436  	sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
   437  		for _, log := range buff {
   438  			select {
   439  			case logs <- log:
   440  			case <-quit:
   441  				return nil
   442  			}
   443  		}
   444  		return nil
   445  	}), nil
   446  
   447  	if err != nil {
   448  		return nil, nil, err
   449  	}
   450  	return logs, sub, nil
   451  }
   452  
   453  // WatchLogs filters subscribes to contract logs for future blocks, returning a
   454  // subscription object that can be used to tear down the watcher.
   455  func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan types.Log, event.Subscription, error) {
   456  	// Don't crash on a lazy user
   457  	if opts == nil {
   458  		opts = new(WatchOpts)
   459  	}
   460  	// Append the event selector to the query parameters and construct the topic set
   461  	query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
   462  
   463  	topics, err := abi.MakeTopics(query...)
   464  	if err != nil {
   465  		return nil, nil, err
   466  	}
   467  	// Start the background filtering
   468  	logs := make(chan types.Log, 128)
   469  
   470  	config := ethereum.FilterQuery{
   471  		Addresses: []common.Address{c.address},
   472  		Topics:    topics,
   473  	}
   474  	if opts.Start != nil {
   475  		config.FromBlock = new(big.Int).SetUint64(*opts.Start)
   476  	}
   477  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   478  	if err != nil {
   479  		return nil, nil, err
   480  	}
   481  	return logs, sub, nil
   482  }
   483  
   484  // UnpackLog unpacks a retrieved log into the provided output structure.
   485  func (c *BoundContract) UnpackLog(out interface{}, event string, log types.Log) error {
   486  	if log.Topics[0] != c.abi.Events[event].ID {
   487  		return fmt.Errorf("event signature mismatch")
   488  	}
   489  	if len(log.Data) > 0 {
   490  		if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
   491  			return err
   492  		}
   493  	}
   494  	var indexed abi.Arguments
   495  	for _, arg := range c.abi.Events[event].Inputs {
   496  		if arg.Indexed {
   497  			indexed = append(indexed, arg)
   498  		}
   499  	}
   500  	return abi.ParseTopics(out, indexed, log.Topics[1:])
   501  }
   502  
   503  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   504  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
   505  	if log.Topics[0] != c.abi.Events[event].ID {
   506  		return fmt.Errorf("event signature mismatch")
   507  	}
   508  	if len(log.Data) > 0 {
   509  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   510  			return err
   511  		}
   512  	}
   513  	var indexed abi.Arguments
   514  	for _, arg := range c.abi.Events[event].Inputs {
   515  		if arg.Indexed {
   516  			indexed = append(indexed, arg)
   517  		}
   518  	}
   519  	return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:])
   520  }
   521  
   522  // ensureContext is a helper method to ensure a context is not nil, even if the
   523  // user specified it as such.
   524  func ensureContext(ctx context.Context) context.Context {
   525  	if ctx == nil {
   526  		return context.Background()
   527  	}
   528  	return ctx
   529  }