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