github.com/theQRL/go-zond@v0.1.1/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/theQRL/go-zond"
    28  	"github.com/theQRL/go-zond/accounts/abi"
    29  	"github.com/theQRL/go-zond/common"
    30  	"github.com/theQRL/go-zond/core/types"
    31  	"github.com/theQRL/go-zond/crypto"
    32  	"github.com/theQRL/go-zond/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  	Context     context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    52  }
    53  
    54  // TransactOpts is the collection of authorization data required to create a
    55  // valid Ethereum transaction.
    56  type TransactOpts struct {
    57  	From   common.Address // Ethereum account to send the transaction from
    58  	Nonce  *big.Int       // Nonce to use for the transaction execution (nil = use pending state)
    59  	Signer SignerFn       // Method to use for signing the transaction (mandatory)
    60  
    61  	Value     *big.Int // Funds to transfer along the transaction (nil = 0 = no funds)
    62  	GasPrice  *big.Int // Gas price to use for the transaction execution (nil = gas price oracle)
    63  	GasFeeCap *big.Int // Gas fee cap to use for the 1559 transaction execution (nil = gas price oracle)
    64  	GasTipCap *big.Int // Gas priority fee cap to use for the 1559 transaction execution (nil = gas price oracle)
    65  	GasLimit  uint64   // Gas limit to set for the transaction execution (0 = estimate)
    66  
    67  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    68  
    69  	NoSend bool // Do all transact steps but do not send the transaction
    70  }
    71  
    72  // FilterOpts is the collection of options to fine tune filtering for events
    73  // within a bound contract.
    74  type FilterOpts struct {
    75  	Start uint64  // Start of the queried range
    76  	End   *uint64 // End of the range (nil = latest)
    77  
    78  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    79  }
    80  
    81  // WatchOpts is the collection of options to fine tune subscribing for events
    82  // within a bound contract.
    83  type WatchOpts struct {
    84  	Start   *uint64         // Start of the queried range (nil = latest)
    85  	Context context.Context // Network context to support cancellation and timeouts (nil = no timeout)
    86  }
    87  
    88  // MetaData collects all metadata for a bound contract.
    89  type MetaData struct {
    90  	mu   sync.Mutex
    91  	Sigs map[string]string
    92  	Bin  string
    93  	ABI  string
    94  	ab   *abi.ABI
    95  }
    96  
    97  func (m *MetaData) GetAbi() (*abi.ABI, error) {
    98  	m.mu.Lock()
    99  	defer m.mu.Unlock()
   100  	if m.ab != nil {
   101  		return m.ab, nil
   102  	}
   103  	if parsed, err := abi.JSON(strings.NewReader(m.ABI)); err != nil {
   104  		return nil, err
   105  	} else {
   106  		m.ab = &parsed
   107  	}
   108  	return m.ab, nil
   109  }
   110  
   111  // BoundContract is the base wrapper object that reflects a contract on the
   112  // Ethereum network. It contains a collection of methods that are used by the
   113  // higher level contract bindings to operate.
   114  type BoundContract struct {
   115  	address    common.Address     // Deployment address of the contract on the Ethereum blockchain
   116  	abi        abi.ABI            // Reflect based ABI to access the correct Ethereum methods
   117  	caller     ContractCaller     // Read interface to interact with the blockchain
   118  	transactor ContractTransactor // Write interface to interact with the blockchain
   119  	filterer   ContractFilterer   // Event filtering to interact with the blockchain
   120  }
   121  
   122  // NewBoundContract creates a low level contract interface through which calls
   123  // and transactions may be made through.
   124  func NewBoundContract(address common.Address, abi abi.ABI, caller ContractCaller, transactor ContractTransactor, filterer ContractFilterer) *BoundContract {
   125  	return &BoundContract{
   126  		address:    address,
   127  		abi:        abi,
   128  		caller:     caller,
   129  		transactor: transactor,
   130  		filterer:   filterer,
   131  	}
   132  }
   133  
   134  // DeployContract deploys a contract onto the Ethereum blockchain and binds the
   135  // deployment address with a Go wrapper.
   136  func DeployContract(opts *TransactOpts, abi abi.ABI, bytecode []byte, backend ContractBackend, params ...interface{}) (common.Address, *types.Transaction, *BoundContract, error) {
   137  	// Otherwise try to deploy the contract
   138  	c := NewBoundContract(common.Address{}, abi, backend, backend, backend)
   139  
   140  	input, err := c.abi.Pack("", params...)
   141  	if err != nil {
   142  		return common.Address{}, nil, nil, err
   143  	}
   144  	tx, err := c.transact(opts, nil, append(bytecode, input...))
   145  	if err != nil {
   146  		return common.Address{}, nil, nil, err
   147  	}
   148  	c.address = crypto.CreateAddress(opts.From, tx.Nonce())
   149  	return c.address, tx, c, nil
   150  }
   151  
   152  // Call invokes the (constant) contract method with params as input values and
   153  // sets the output to result. The result type might be a single field for simple
   154  // returns, a slice of interfaces for anonymous returns and a struct for named
   155  // returns.
   156  func (c *BoundContract) Call(opts *CallOpts, results *[]interface{}, method string, params ...interface{}) error {
   157  	// Don't crash on a lazy user
   158  	if opts == nil {
   159  		opts = new(CallOpts)
   160  	}
   161  	if results == nil {
   162  		results = new([]interface{})
   163  	}
   164  	// Pack the input, call and unpack the results
   165  	input, err := c.abi.Pack(method, params...)
   166  	if err != nil {
   167  		return err
   168  	}
   169  	var (
   170  		msg    = zond.CallMsg{From: opts.From, To: &c.address, Data: input}
   171  		ctx    = ensureContext(opts.Context)
   172  		code   []byte
   173  		output []byte
   174  	)
   175  	if opts.Pending {
   176  		pb, ok := c.caller.(PendingContractCaller)
   177  		if !ok {
   178  			return ErrNoPendingState
   179  		}
   180  		output, err = pb.PendingCallContract(ctx, msg)
   181  		if err != nil {
   182  			return err
   183  		}
   184  		if len(output) == 0 {
   185  			// Make sure we have a contract to operate on, and bail out otherwise.
   186  			if code, err = pb.PendingCodeAt(ctx, c.address); err != nil {
   187  				return err
   188  			} else if len(code) == 0 {
   189  				return ErrNoCode
   190  			}
   191  		}
   192  	} else {
   193  		output, err = c.caller.CallContract(ctx, msg, opts.BlockNumber)
   194  		if err != nil {
   195  			return err
   196  		}
   197  		if len(output) == 0 {
   198  			// Make sure we have a contract to operate on, and bail out otherwise.
   199  			if code, err = c.caller.CodeAt(ctx, c.address, opts.BlockNumber); err != nil {
   200  				return err
   201  			} else if len(code) == 0 {
   202  				return ErrNoCode
   203  			}
   204  		}
   205  	}
   206  
   207  	if len(*results) == 0 {
   208  		res, err := c.abi.Unpack(method, output)
   209  		*results = res
   210  		return err
   211  	}
   212  	res := *results
   213  	return c.abi.UnpackIntoInterface(res[0], method, output)
   214  }
   215  
   216  // Transact invokes the (paid) contract method with params as input values.
   217  func (c *BoundContract) Transact(opts *TransactOpts, method string, params ...interface{}) (*types.Transaction, error) {
   218  	// Otherwise pack up the parameters and invoke the contract
   219  	input, err := c.abi.Pack(method, params...)
   220  	if err != nil {
   221  		return nil, err
   222  	}
   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, input)
   226  }
   227  
   228  // RawTransact initiates a transaction with the given raw calldata as the input.
   229  // It's usually used to initiate transactions for invoking **Fallback** function.
   230  func (c *BoundContract) RawTransact(opts *TransactOpts, calldata []byte) (*types.Transaction, error) {
   231  	// todo(rjl493456442) check the method is payable or not,
   232  	// reject invalid transaction at the first place
   233  	return c.transact(opts, &c.address, calldata)
   234  }
   235  
   236  // Transfer initiates a plain transaction to move funds to the contract, calling
   237  // its default method if one is available.
   238  func (c *BoundContract) Transfer(opts *TransactOpts) (*types.Transaction, error) {
   239  	// todo(rjl493456442) check the payable fallback or receive is defined
   240  	// or not, reject invalid transaction at the first place
   241  	return c.transact(opts, &c.address, nil)
   242  }
   243  
   244  func (c *BoundContract) createDynamicTx(opts *TransactOpts, contract *common.Address, input []byte, head *types.Header) (*types.Transaction, error) {
   245  	// Normalize value
   246  	value := opts.Value
   247  	if value == nil {
   248  		value = new(big.Int)
   249  	}
   250  	// Estimate TipCap
   251  	gasTipCap := opts.GasTipCap
   252  	if gasTipCap == nil {
   253  		tip, err := c.transactor.SuggestGasTipCap(ensureContext(opts.Context))
   254  		if err != nil {
   255  			return nil, err
   256  		}
   257  		gasTipCap = tip
   258  	}
   259  	// Estimate FeeCap
   260  	gasFeeCap := opts.GasFeeCap
   261  	if gasFeeCap == nil {
   262  		gasFeeCap = new(big.Int).Add(
   263  			gasTipCap,
   264  			new(big.Int).Mul(head.BaseFee, big.NewInt(basefeeWiggleMultiplier)),
   265  		)
   266  	}
   267  	if gasFeeCap.Cmp(gasTipCap) < 0 {
   268  		return nil, fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", gasFeeCap, gasTipCap)
   269  	}
   270  	// Estimate GasLimit
   271  	gasLimit := opts.GasLimit
   272  	if opts.GasLimit == 0 {
   273  		var err error
   274  		gasLimit, err = c.estimateGasLimit(opts, contract, input, nil, gasTipCap, gasFeeCap, value)
   275  		if err != nil {
   276  			return nil, err
   277  		}
   278  	}
   279  	// create the transaction
   280  	nonce, err := c.getNonce(opts)
   281  	if err != nil {
   282  		return nil, err
   283  	}
   284  	baseTx := &types.DynamicFeeTx{
   285  		To:        contract,
   286  		Nonce:     nonce,
   287  		GasFeeCap: gasFeeCap,
   288  		GasTipCap: gasTipCap,
   289  		Gas:       gasLimit,
   290  		Value:     value,
   291  		Data:      input,
   292  	}
   293  	return types.NewTx(baseTx), nil
   294  }
   295  
   296  func (c *BoundContract) createLegacyTx(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   297  	if opts.GasFeeCap != nil || opts.GasTipCap != nil {
   298  		return nil, errors.New("maxFeePerGas or maxPriorityFeePerGas specified but london is not active yet")
   299  	}
   300  	// Normalize value
   301  	value := opts.Value
   302  	if value == nil {
   303  		value = new(big.Int)
   304  	}
   305  	// Estimate GasPrice
   306  	gasPrice := opts.GasPrice
   307  	if gasPrice == nil {
   308  		price, err := c.transactor.SuggestGasPrice(ensureContext(opts.Context))
   309  		if err != nil {
   310  			return nil, err
   311  		}
   312  		gasPrice = price
   313  	}
   314  	// Estimate GasLimit
   315  	gasLimit := opts.GasLimit
   316  	if opts.GasLimit == 0 {
   317  		var err error
   318  		gasLimit, err = c.estimateGasLimit(opts, contract, input, gasPrice, nil, nil, value)
   319  		if err != nil {
   320  			return nil, err
   321  		}
   322  	}
   323  	// create the transaction
   324  	nonce, err := c.getNonce(opts)
   325  	if err != nil {
   326  		return nil, err
   327  	}
   328  	baseTx := &types.LegacyTx{
   329  		To:       contract,
   330  		Nonce:    nonce,
   331  		GasPrice: gasPrice,
   332  		Gas:      gasLimit,
   333  		Value:    value,
   334  		Data:     input,
   335  	}
   336  	return types.NewTx(baseTx), nil
   337  }
   338  
   339  func (c *BoundContract) estimateGasLimit(opts *TransactOpts, contract *common.Address, input []byte, gasPrice, gasTipCap, gasFeeCap, value *big.Int) (uint64, error) {
   340  	if contract != nil {
   341  		// Gas estimation cannot succeed without code for method invocations.
   342  		if code, err := c.transactor.PendingCodeAt(ensureContext(opts.Context), c.address); err != nil {
   343  			return 0, err
   344  		} else if len(code) == 0 {
   345  			return 0, ErrNoCode
   346  		}
   347  	}
   348  	msg := zond.CallMsg{
   349  		From:      opts.From,
   350  		To:        contract,
   351  		GasPrice:  gasPrice,
   352  		GasTipCap: gasTipCap,
   353  		GasFeeCap: gasFeeCap,
   354  		Value:     value,
   355  		Data:      input,
   356  	}
   357  	return c.transactor.EstimateGas(ensureContext(opts.Context), msg)
   358  }
   359  
   360  func (c *BoundContract) getNonce(opts *TransactOpts) (uint64, error) {
   361  	if opts.Nonce == nil {
   362  		return c.transactor.PendingNonceAt(ensureContext(opts.Context), opts.From)
   363  	} else {
   364  		return opts.Nonce.Uint64(), nil
   365  	}
   366  }
   367  
   368  // transact executes an actual transaction invocation, first deriving any missing
   369  // authorization fields, and then scheduling the transaction for execution.
   370  func (c *BoundContract) transact(opts *TransactOpts, contract *common.Address, input []byte) (*types.Transaction, error) {
   371  	if opts.GasPrice != nil && (opts.GasFeeCap != nil || opts.GasTipCap != nil) {
   372  		return nil, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
   373  	}
   374  	// Create the transaction
   375  	var (
   376  		rawTx *types.Transaction
   377  		err   error
   378  	)
   379  	if opts.GasPrice != nil {
   380  		rawTx, err = c.createLegacyTx(opts, contract, input)
   381  	} else if opts.GasFeeCap != nil && opts.GasTipCap != nil {
   382  		rawTx, err = c.createDynamicTx(opts, contract, input, nil)
   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 := zond.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 := zond.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  	// Anonymous events are not supported.
   497  	if len(log.Topics) == 0 {
   498  		return errNoEventSignature
   499  	}
   500  	if log.Topics[0] != c.abi.Events[event].ID {
   501  		return errEventSignatureMismatch
   502  	}
   503  	if len(log.Data) > 0 {
   504  		if err := c.abi.UnpackIntoInterface(out, event, log.Data); err != nil {
   505  			return err
   506  		}
   507  	}
   508  	var indexed abi.Arguments
   509  	for _, arg := range c.abi.Events[event].Inputs {
   510  		if arg.Indexed {
   511  			indexed = append(indexed, arg)
   512  		}
   513  	}
   514  	return abi.ParseTopics(out, indexed, log.Topics[1:])
   515  }
   516  
   517  // UnpackLogIntoMap unpacks a retrieved log into the provided map.
   518  func (c *BoundContract) UnpackLogIntoMap(out map[string]interface{}, event string, log types.Log) error {
   519  	// Anonymous events are not supported.
   520  	if len(log.Topics) == 0 {
   521  		return errNoEventSignature
   522  	}
   523  	if log.Topics[0] != c.abi.Events[event].ID {
   524  		return errEventSignatureMismatch
   525  	}
   526  	if len(log.Data) > 0 {
   527  		if err := c.abi.UnpackIntoMap(out, event, log.Data); err != nil {
   528  			return err
   529  		}
   530  	}
   531  	var indexed abi.Arguments
   532  	for _, arg := range c.abi.Events[event].Inputs {
   533  		if arg.Indexed {
   534  			indexed = append(indexed, arg)
   535  		}
   536  	}
   537  	return abi.ParseTopicsIntoMap(out, indexed, log.Topics[1:])
   538  }
   539  
   540  // ensureContext is a helper method to ensure a context is not nil, even if the
   541  // user specified it as such.
   542  func ensureContext(ctx context.Context) context.Context {
   543  	if ctx == nil {
   544  		return context.Background()
   545  	}
   546  	return ctx
   547  }