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