github.com/theQRL/go-zond@v0.2.1/internal/zondapi/transaction_args.go (about)

     1  // Copyright 2021 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 zondapi
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  
    26  	"github.com/theQRL/go-zond/common"
    27  	"github.com/theQRL/go-zond/common/hexutil"
    28  	"github.com/theQRL/go-zond/common/math"
    29  	"github.com/theQRL/go-zond/core"
    30  	"github.com/theQRL/go-zond/core/types"
    31  	"github.com/theQRL/go-zond/log"
    32  	"github.com/theQRL/go-zond/rpc"
    33  )
    34  
    35  // TransactionArgs represents the arguments to construct a new transaction
    36  // or a message call.
    37  type TransactionArgs struct {
    38  	From                 *common.Address `json:"from"`
    39  	To                   *common.Address `json:"to"`
    40  	Gas                  *hexutil.Uint64 `json:"gas"`
    41  	MaxFeePerGas         *hexutil.Big    `json:"maxFeePerGas"`
    42  	MaxPriorityFeePerGas *hexutil.Big    `json:"maxPriorityFeePerGas"`
    43  	Value                *hexutil.Big    `json:"value"`
    44  	Nonce                *hexutil.Uint64 `json:"nonce"`
    45  
    46  	// We accept "data" and "input" for backwards-compatibility reasons.
    47  	// "input" is the newer name and should be preferred by clients.
    48  	// Issue detail: https://github.com/theQRL/go-zond/issues/15628
    49  	Data  *hexutil.Bytes `json:"data"`
    50  	Input *hexutil.Bytes `json:"input"`
    51  
    52  	AccessList *types.AccessList `json:"accessList,omitempty"`
    53  	ChainID    *hexutil.Big      `json:"chainId,omitempty"`
    54  }
    55  
    56  // from retrieves the transaction sender address.
    57  func (args *TransactionArgs) from() common.Address {
    58  	if args.From == nil {
    59  		return common.Address{}
    60  	}
    61  	return *args.From
    62  }
    63  
    64  // data retrieves the transaction calldata. Input field is preferred.
    65  func (args *TransactionArgs) data() []byte {
    66  	if args.Input != nil {
    67  		return *args.Input
    68  	}
    69  	if args.Data != nil {
    70  		return *args.Data
    71  	}
    72  	return nil
    73  }
    74  
    75  // setDefaults fills in default values for unspecified tx fields.
    76  func (args *TransactionArgs) setDefaults(ctx context.Context, b Backend) error {
    77  	if err := args.setFeeDefaults(ctx, b); err != nil {
    78  		return err
    79  	}
    80  	if args.Value == nil {
    81  		args.Value = new(hexutil.Big)
    82  	}
    83  	if args.Nonce == nil {
    84  		nonce, err := b.GetPoolNonce(ctx, args.from())
    85  		if err != nil {
    86  			return err
    87  		}
    88  		args.Nonce = (*hexutil.Uint64)(&nonce)
    89  	}
    90  	if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
    91  		return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
    92  	}
    93  	if args.To == nil && len(args.data()) == 0 {
    94  		return errors.New(`contract creation without any data provided`)
    95  	}
    96  	// Estimate the gas usage if necessary.
    97  	if args.Gas == nil {
    98  		// These fields are immutable during the estimation, safe to
    99  		// pass the pointer directly.
   100  		data := args.data()
   101  		callArgs := TransactionArgs{
   102  			From:                 args.From,
   103  			To:                   args.To,
   104  			MaxFeePerGas:         args.MaxFeePerGas,
   105  			MaxPriorityFeePerGas: args.MaxPriorityFeePerGas,
   106  			Value:                args.Value,
   107  			Data:                 (*hexutil.Bytes)(&data),
   108  			AccessList:           args.AccessList,
   109  		}
   110  		pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
   111  		estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, nil, b.RPCGasCap())
   112  		if err != nil {
   113  			return err
   114  		}
   115  		args.Gas = &estimated
   116  		log.Trace("Estimate gas usage automatically", "gas", args.Gas)
   117  	}
   118  	// If chain id is provided, ensure it matches the local chain id. Otherwise, set the local
   119  	// chain id as the default.
   120  	want := b.ChainConfig().ChainID
   121  	if args.ChainID != nil {
   122  		if have := (*big.Int)(args.ChainID); have.Cmp(want) != 0 {
   123  			return fmt.Errorf("chainId does not match node's (have=%v, want=%v)", have, want)
   124  		}
   125  	} else {
   126  		args.ChainID = (*hexutil.Big)(want)
   127  	}
   128  	return nil
   129  }
   130  
   131  // setFeeDefaults fills in default fee values for unspecified tx fields.
   132  func (args *TransactionArgs) setFeeDefaults(ctx context.Context, b Backend) error {
   133  	// If the tx has completely specified a fee mechanism, no default is needed. This allows users
   134  	// who are not yet synced past London to get defaults for other tx values. See
   135  	// https://github.com/theQRL/go-zond/pull/23274 for more information.
   136  	eip1559ParamsSet := args.MaxFeePerGas != nil && args.MaxPriorityFeePerGas != nil
   137  	if eip1559ParamsSet {
   138  		// Sanity check the EIP-1559 fee parameters if present.
   139  		if args.MaxFeePerGas.ToInt().Cmp(args.MaxPriorityFeePerGas.ToInt()) < 0 {
   140  			return fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", args.MaxFeePerGas, args.MaxPriorityFeePerGas)
   141  		}
   142  		return nil
   143  	}
   144  	// Now attempt to fill in default value depending on whether London is active or not.
   145  	head := b.CurrentHeader()
   146  	// London is active, set maxPriorityFeePerGas and maxFeePerGas.
   147  	if err := args.setLondonFeeDefaults(ctx, head, b); err != nil {
   148  		return err
   149  	}
   150  
   151  	return nil
   152  }
   153  
   154  // setLondonFeeDefaults fills in reasonable default fee values for unspecified fields.
   155  func (args *TransactionArgs) setLondonFeeDefaults(ctx context.Context, head *types.Header, b Backend) error {
   156  	// Set maxPriorityFeePerGas if it is missing.
   157  	if args.MaxPriorityFeePerGas == nil {
   158  		tip, err := b.SuggestGasTipCap(ctx)
   159  		if err != nil {
   160  			return err
   161  		}
   162  		args.MaxPriorityFeePerGas = (*hexutil.Big)(tip)
   163  	}
   164  	// Set maxFeePerGas if it is missing.
   165  	if args.MaxFeePerGas == nil {
   166  		// Set the max fee to be 2 times larger than the previous block's base fee.
   167  		// The additional slack allows the tx to not become invalidated if the base
   168  		// fee is rising.
   169  		val := new(big.Int).Add(
   170  			args.MaxPriorityFeePerGas.ToInt(),
   171  			new(big.Int).Mul(head.BaseFee, big.NewInt(2)),
   172  		)
   173  		args.MaxFeePerGas = (*hexutil.Big)(val)
   174  	}
   175  	// Both EIP-1559 fee parameters are now set; sanity check them.
   176  	if args.MaxFeePerGas.ToInt().Cmp(args.MaxPriorityFeePerGas.ToInt()) < 0 {
   177  		return fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", args.MaxFeePerGas, args.MaxPriorityFeePerGas)
   178  	}
   179  	return nil
   180  }
   181  
   182  // ToMessage converts the transaction arguments to the Message type used by the
   183  // core zvm. This method is used in calls and traces that do not require a real
   184  // live transaction.
   185  func (args *TransactionArgs) ToMessage(globalGasCap uint64, baseFee *big.Int) (*core.Message, error) {
   186  	// Set sender address or use zero address if none specified.
   187  	addr := args.from()
   188  
   189  	// Set default gas & gas price if none were set
   190  	gas := globalGasCap
   191  	if gas == 0 {
   192  		gas = uint64(math.MaxUint64 / 2)
   193  	}
   194  	if args.Gas != nil {
   195  		gas = uint64(*args.Gas)
   196  	}
   197  	if globalGasCap != 0 && globalGasCap < gas {
   198  		log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
   199  		gas = globalGasCap
   200  	}
   201  	var (
   202  		gasPrice  *big.Int
   203  		gasFeeCap *big.Int
   204  		gasTipCap *big.Int
   205  	)
   206  
   207  	// A basefee is provided, necessitating 1559-type execution
   208  	// User specified 1559 gas fields (or none), use those
   209  	gasFeeCap = new(big.Int)
   210  	if args.MaxFeePerGas != nil {
   211  		gasFeeCap = args.MaxFeePerGas.ToInt()
   212  	}
   213  	gasTipCap = new(big.Int)
   214  	if args.MaxPriorityFeePerGas != nil {
   215  		gasTipCap = args.MaxPriorityFeePerGas.ToInt()
   216  	}
   217  	// Backfill the legacy gasPrice for ZVM execution, unless we're all zeroes
   218  	gasPrice = new(big.Int)
   219  	if gasFeeCap.BitLen() > 0 || gasTipCap.BitLen() > 0 {
   220  		gasPrice = math.BigMin(new(big.Int).Add(gasTipCap, baseFee), gasFeeCap)
   221  	}
   222  
   223  	value := new(big.Int)
   224  	if args.Value != nil {
   225  		value = args.Value.ToInt()
   226  	}
   227  	data := args.data()
   228  	var accessList types.AccessList
   229  	if args.AccessList != nil {
   230  		accessList = *args.AccessList
   231  	}
   232  	msg := &core.Message{
   233  		From:              addr,
   234  		To:                args.To,
   235  		Value:             value,
   236  		GasLimit:          gas,
   237  		GasPrice:          gasPrice,
   238  		GasFeeCap:         gasFeeCap,
   239  		GasTipCap:         gasTipCap,
   240  		Data:              data,
   241  		AccessList:        accessList,
   242  		SkipAccountChecks: true,
   243  	}
   244  	return msg, nil
   245  }
   246  
   247  // toTransaction converts the arguments to a transaction.
   248  // This assumes that setDefaults has been called.
   249  func (args *TransactionArgs) toTransaction() *types.Transaction {
   250  	var data types.TxData
   251  
   252  	al := types.AccessList{}
   253  	if args.AccessList != nil {
   254  		al = *args.AccessList
   255  	}
   256  
   257  	data = &types.DynamicFeeTx{
   258  		To:         args.To,
   259  		ChainID:    (*big.Int)(args.ChainID),
   260  		Nonce:      uint64(*args.Nonce),
   261  		Gas:        uint64(*args.Gas),
   262  		GasFeeCap:  (*big.Int)(args.MaxFeePerGas),
   263  		GasTipCap:  (*big.Int)(args.MaxPriorityFeePerGas),
   264  		Value:      (*big.Int)(args.Value),
   265  		Data:       args.data(),
   266  		AccessList: al,
   267  	}
   268  
   269  	return types.NewTx(data)
   270  }
   271  
   272  // ToTransaction converts the arguments to a transaction.
   273  // This assumes that setDefaults has been called.
   274  func (args *TransactionArgs) ToTransaction() *types.Transaction {
   275  	return args.toTransaction()
   276  }