github.com/amazechain/amc@v0.1.3/accounts/abi/bind/base.go (about)

     1  // Copyright 2023 The AmazeChain Authors
     2  // This file is part of the AmazeChain library.
     3  //
     4  // The AmazeChain 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 AmazeChain 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 AmazeChain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package bind
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  	amazechain "github.com/amazechain/amc"
    24  	"github.com/amazechain/amc/accounts/abi"
    25  	"github.com/amazechain/amc/common/block"
    26  	"github.com/amazechain/amc/common/crypto"
    27  	"github.com/amazechain/amc/common/transaction"
    28  	"github.com/amazechain/amc/common/types"
    29  	event "github.com/amazechain/amc/modules/event/v2"
    30  	"github.com/holiman/uint256"
    31  	"strings"
    32  	"sync"
    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(types.Address, *transaction.Transaction) (*transaction.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        types.Address   // Optional the sender address, otherwise the first account is used
    45  	BlockNumber *uint256.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   types.Address // Ethereum account to send the transaction from
    53  	Nonce  *uint64       // 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     *uint256.Int // Funds to transfer along the transaction (nil = 0 = no funds)
    57  	GasPrice  *uint256.Int // Gas price to use for the transaction execution (nil = gas price oracle)
    58  	GasFeeCap *uint256.Int // Gas fee cap to use for the 1559 transaction execution (nil = gas price oracle)
    59  	GasTipCap *uint256.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    types.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 types.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{}) (types.Address, *transaction.Transaction, *BoundContract, error) {
   132  	// Otherwise try to deploy the contract
   133  	c := NewBoundContract(types.Address{}, abi, backend, backend, backend)
   134  
   135  	input, err := c.abi.Pack("", params...)
   136  	if err != nil {
   137  		return types.Address{}, nil, nil, err
   138  	}
   139  	tx, err := c.transact(opts, nil, append(bytecode, input...))
   140  	if err != nil {
   141  		return types.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    = amazechain.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{}) (*transaction.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) (*transaction.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) (*transaction.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 *types.Address, input []byte, head *block.Header) (*transaction.Transaction, error) {
   240  	// Normalize value
   241  	value := opts.Value
   242  	if value == nil {
   243  		value = uint256.NewInt(0)
   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 = gasTipCap.Add(gasTipCap, head.BaseFee.Mod(head.BaseFee, uint256.NewInt(basefeeWiggleMultiplier)))
   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, uint256.NewInt(0), 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 := &transaction.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 transaction.NewTx(baseTx), nil
   286  }
   287  
   288  func (c *BoundContract) createLegacyTx(opts *TransactOpts, contract *types.Address, input []byte) (*transaction.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 = uint256.NewInt(0)
   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, uint256.NewInt(0), uint256.NewInt(0), 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 := &transaction.LegacyTx{
   321  		To:       contract,
   322  		Nonce:    nonce,
   323  		GasPrice: gasPrice,
   324  		Gas:      gasLimit,
   325  		Value:    value,
   326  		Data:     input,
   327  	}
   328  	return transaction.NewTx(baseTx), nil
   329  }
   330  
   331  func (c *BoundContract) estimateGasLimit(opts *TransactOpts, contract *types.Address, input []byte, gasPrice, gasTipCap, gasFeeCap, value *uint256.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 := amazechain.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, 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 *types.Address, input []byte) (*transaction.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 *transaction.Transaction
   369  		err   error
   370  	)
   371  	if opts.GasPrice != nil {
   372  		rawTx, err = c.createLegacyTx(opts, contract, input)
   373  	} else if opts.GasFeeCap != nil && opts.GasTipCap != nil {
   374  		rawTx, err = c.createDynamicTx(opts, contract, input, nil)
   375  	} else {
   376  
   377  		// Only query for basefee if gasPrice not specified
   378  		if head, errHead := c.transactor.HeaderByNumber(ensureContext(opts.Context), uint256.NewInt(0) /* latest */); errHead != nil {
   379  			return nil, errHead
   380  		} else if head.BaseFee != nil {
   381  			rawTx, err = c.createDynamicTx(opts, contract, input, head)
   382  		} else {
   383  			// Chain is not London ready -> use legacy transaction
   384  			rawTx, err = c.createLegacyTx(opts, contract, input)
   385  		}
   386  	}
   387  	if err != nil {
   388  		return nil, err
   389  	}
   390  	// Sign the transaction and schedule it for execution
   391  	if opts.Signer == nil {
   392  		return nil, errors.New("no signer to authorize the transaction with")
   393  	}
   394  	signedTx, err := opts.Signer(opts.From, rawTx)
   395  	if err != nil {
   396  		return nil, err
   397  	}
   398  	if opts.NoSend {
   399  		return signedTx, nil
   400  	}
   401  	if err := c.transactor.SendTransaction(ensureContext(opts.Context), signedTx); err != nil {
   402  		return nil, err
   403  	}
   404  	return signedTx, nil
   405  }
   406  
   407  // FilterLogs filters contract logs for past blocks, returning the necessary
   408  // channels to construct a strongly typed bound iterator on top of them.
   409  func (c *BoundContract) FilterLogs(opts *FilterOpts, name string, query ...[]interface{}) (chan block.Log, event.Subscription, error) {
   410  	// Don't crash on a lazy user
   411  	if opts == nil {
   412  		opts = new(FilterOpts)
   413  	}
   414  	// Append the event selector to the query parameters and construct the topic set
   415  	query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
   416  
   417  	topics, err := abi.MakeTopics(query...)
   418  	if err != nil {
   419  		return nil, nil, err
   420  	}
   421  	// Start the background filtering
   422  	logs := make(chan block.Log, 128)
   423  
   424  	config := amazechain.FilterQuery{
   425  		Addresses: []types.Address{c.address},
   426  		Topics:    topics,
   427  		FromBlock: uint256.NewInt(opts.Start),
   428  	}
   429  	if opts.End != nil {
   430  		config.ToBlock = uint256.NewInt(*opts.End)
   431  	}
   432  	/* TODO(karalabe): Replace the rest of the method below with this when supported
   433  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   434  	*/
   435  	buff, err := c.filterer.FilterLogs(ensureContext(opts.Context), config)
   436  	if err != nil {
   437  		return nil, nil, err
   438  	}
   439  	sub, err := event.NewSubscription(func(quit <-chan struct{}) error {
   440  		for _, log := range buff {
   441  			select {
   442  			case logs <- log:
   443  			case <-quit:
   444  				return nil
   445  			}
   446  		}
   447  		return nil
   448  	}), nil
   449  
   450  	if err != nil {
   451  		return nil, nil, err
   452  	}
   453  	return logs, sub, nil
   454  }
   455  
   456  // WatchLogs filters subscribes to contract logs for future blocks, returning a
   457  // subscription object that can be used to tear down the watcher.
   458  func (c *BoundContract) WatchLogs(opts *WatchOpts, name string, query ...[]interface{}) (chan block.Log, event.Subscription, error) {
   459  	// Don't crash on a lazy user
   460  	if opts == nil {
   461  		opts = new(WatchOpts)
   462  	}
   463  	// Append the event selector to the query parameters and construct the topic set
   464  	query = append([][]interface{}{{c.abi.Events[name].ID}}, query...)
   465  
   466  	topics, err := abi.MakeTopics(query...)
   467  	if err != nil {
   468  		return nil, nil, err
   469  	}
   470  	// Start the background filtering
   471  	logs := make(chan block.Log, 128)
   472  
   473  	config := amazechain.FilterQuery{
   474  		Addresses: []types.Address{c.address},
   475  		Topics:    topics,
   476  	}
   477  	if opts.Start != nil {
   478  		config.FromBlock = uint256.NewInt(*opts.Start)
   479  	}
   480  	sub, err := c.filterer.SubscribeFilterLogs(ensureContext(opts.Context), config, logs)
   481  	if err != nil {
   482  		return nil, nil, err
   483  	}
   484  	return logs, sub, nil
   485  }
   486  
   487  // UnpackLog unpacks a retrieved log into the provided output structure.
   488  func (c *BoundContract) UnpackLog(out interface{}, event string, log block.Log) error {
   489  	if log.Topics[0] != c.abi.Events[event].ID {
   490  		return fmt.Errorf("event signature mismatch")
   491  	}
   492  	if len(log.Data) > 0 {
   493  		if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
   494  			return err
   495  		}
   496  	}
   497  	var indexed abi.Arguments
   498  	for _, arg := range c.abi.Events[event].Inputs {
   499  		if arg.Indexed {
   500  			indexed = append(indexed, arg)
   501  		}
   502  	}
   503  	return abi.ParseTopics(out, indexed, log.Topics[1:])
   504  }
   505  
   506  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   507  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log block.Log) error {
   508  	if log.Topics[0] != c.abi.Events[event].ID {
   509  		return fmt.Errorf("event signature mismatch")
   510  	}
   511  	if len(log.Data) > 0 {
   512  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   513  			return err
   514  		}
   515  	}
   516  	var indexed abi.Arguments
   517  	for _, arg := range c.abi.Events[event].Inputs {
   518  		if arg.Indexed {
   519  			indexed = append(indexed, arg)
   520  		}
   521  	}
   522  	return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:])
   523  }
   524  
   525  // ensureContext is a helper method to ensure a context is not nil, even if the
   526  // user specified it as such.
   527  func ensureContext(ctx context.Context) context.Context {
   528  	if ctx == nil {
   529  		return context.Background()
   530  	}
   531  	return ctx
   532  }