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