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