github.com/LampardNguyen234/go-ethereum@v1.10.16-0.20220117140830-b6a3b0260724/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/LampardNguyen234/go-ethereum/common"
    27  	"github.com/LampardNguyen234/go-ethereum/common/hexutil"
    28  	"github.com/LampardNguyen234/go-ethereum/common/math"
    29  	"github.com/LampardNguyen234/go-ethereum/core/types"
    30  	"github.com/LampardNguyen234/go-ethereum/log"
    31  	"github.com/LampardNguyen234/go-ethereum/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/LampardNguyen234/go-ethereum/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 (arg *TransactionArgs) from() common.Address {
    59  	if arg.From == nil {
    60  		return common.Address{}
    61  	}
    62  	return *arg.From
    63  }
    64  
    65  // data retrieves the transaction calldata. Input field is preferred.
    66  func (arg *TransactionArgs) data() []byte {
    67  	if arg.Input != nil {
    68  		return *arg.Input
    69  	}
    70  	if arg.Data != nil {
    71  		return *arg.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 args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) {
    79  		return errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
    80  	}
    81  	// After london, default to 1559 unless gasPrice is set
    82  	head := b.CurrentHeader()
    83  	// If user specifies both maxPriorityfee and maxFee, then we do not
    84  	// need to consult the chain for defaults. It's definitely a London tx.
    85  	if args.MaxPriorityFeePerGas == nil || args.MaxFeePerGas == nil {
    86  		// In this clause, user left some fields unspecified.
    87  		if b.ChainConfig().IsLondon(head.Number) && args.GasPrice == nil {
    88  			if args.MaxPriorityFeePerGas == nil {
    89  				tip, err := b.SuggestGasTipCap(ctx)
    90  				if err != nil {
    91  					return err
    92  				}
    93  				args.MaxPriorityFeePerGas = (*hexutil.Big)(tip)
    94  			}
    95  			if args.MaxFeePerGas == nil {
    96  				gasFeeCap := new(big.Int).Add(
    97  					(*big.Int)(args.MaxPriorityFeePerGas),
    98  					new(big.Int).Mul(head.BaseFee, big.NewInt(2)),
    99  				)
   100  				args.MaxFeePerGas = (*hexutil.Big)(gasFeeCap)
   101  			}
   102  			if args.MaxFeePerGas.ToInt().Cmp(args.MaxPriorityFeePerGas.ToInt()) < 0 {
   103  				return fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", args.MaxFeePerGas, args.MaxPriorityFeePerGas)
   104  			}
   105  		} else {
   106  			if args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil {
   107  				return errors.New("maxFeePerGas or maxPriorityFeePerGas specified but london is not active yet")
   108  			}
   109  			if args.GasPrice == nil {
   110  				price, err := b.SuggestGasTipCap(ctx)
   111  				if err != nil {
   112  					return err
   113  				}
   114  				if b.ChainConfig().IsLondon(head.Number) {
   115  					// The legacy tx gas price suggestion should not add 2x base fee
   116  					// because all fees are consumed, so it would result in a spiral
   117  					// upwards.
   118  					price.Add(price, head.BaseFee)
   119  				}
   120  				args.GasPrice = (*hexutil.Big)(price)
   121  			}
   122  		}
   123  	} else {
   124  		// Both maxPriorityfee and maxFee set by caller. Sanity-check their internal relation
   125  		if args.MaxFeePerGas.ToInt().Cmp(args.MaxPriorityFeePerGas.ToInt()) < 0 {
   126  			return fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", args.MaxFeePerGas, args.MaxPriorityFeePerGas)
   127  		}
   128  	}
   129  	if args.Value == nil {
   130  		args.Value = new(hexutil.Big)
   131  	}
   132  	if args.Nonce == nil {
   133  		nonce, err := b.GetPoolNonce(ctx, args.from())
   134  		if err != nil {
   135  			return err
   136  		}
   137  		args.Nonce = (*hexutil.Uint64)(&nonce)
   138  	}
   139  	if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
   140  		return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
   141  	}
   142  	if args.To == nil && len(args.data()) == 0 {
   143  		return errors.New(`contract creation without any data provided`)
   144  	}
   145  	// Estimate the gas usage if necessary.
   146  	if args.Gas == nil {
   147  		// These fields are immutable during the estimation, safe to
   148  		// pass the pointer directly.
   149  		data := args.data()
   150  		callArgs := TransactionArgs{
   151  			From:                 args.From,
   152  			To:                   args.To,
   153  			GasPrice:             args.GasPrice,
   154  			MaxFeePerGas:         args.MaxFeePerGas,
   155  			MaxPriorityFeePerGas: args.MaxPriorityFeePerGas,
   156  			Value:                args.Value,
   157  			Data:                 (*hexutil.Bytes)(&data),
   158  			AccessList:           args.AccessList,
   159  		}
   160  		pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
   161  		estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
   162  		if err != nil {
   163  			return err
   164  		}
   165  		args.Gas = &estimated
   166  		log.Trace("Estimate gas usage automatically", "gas", args.Gas)
   167  	}
   168  	if args.ChainID == nil {
   169  		id := (*hexutil.Big)(b.ChainConfig().ChainID)
   170  		args.ChainID = id
   171  	}
   172  	return nil
   173  }
   174  
   175  // ToMessage converts the transaction arguments to the Message type used by the
   176  // core evm. This method is used in calls and traces that do not require a real
   177  // live transaction.
   178  func (args *TransactionArgs) ToMessage(globalGasCap uint64, baseFee *big.Int) (types.Message, error) {
   179  	// Reject invalid combinations of pre- and post-1559 fee styles
   180  	if args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) {
   181  		return types.Message{}, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
   182  	}
   183  	// Set sender address or use zero address if none specified.
   184  	addr := args.from()
   185  
   186  	// Set default gas & gas price if none were set
   187  	gas := globalGasCap
   188  	if gas == 0 {
   189  		gas = uint64(math.MaxUint64 / 2)
   190  	}
   191  	if args.Gas != nil {
   192  		gas = uint64(*args.Gas)
   193  	}
   194  	if globalGasCap != 0 && globalGasCap < gas {
   195  		log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
   196  		gas = globalGasCap
   197  	}
   198  	var (
   199  		gasPrice  *big.Int
   200  		gasFeeCap *big.Int
   201  		gasTipCap *big.Int
   202  	)
   203  	if baseFee == nil {
   204  		// If there's no basefee, then it must be a non-1559 execution
   205  		gasPrice = new(big.Int)
   206  		if args.GasPrice != nil {
   207  			gasPrice = args.GasPrice.ToInt()
   208  		}
   209  		gasFeeCap, gasTipCap = gasPrice, gasPrice
   210  	} else {
   211  		// A basefee is provided, necessitating 1559-type execution
   212  		if args.GasPrice != nil {
   213  			// User specified the legacy gas field, convert to 1559 gas typing
   214  			gasPrice = args.GasPrice.ToInt()
   215  			gasFeeCap, gasTipCap = gasPrice, gasPrice
   216  		} else {
   217  			// User specified 1559 gas feilds (or none), use those
   218  			gasFeeCap = new(big.Int)
   219  			if args.MaxFeePerGas != nil {
   220  				gasFeeCap = args.MaxFeePerGas.ToInt()
   221  			}
   222  			gasTipCap = new(big.Int)
   223  			if args.MaxPriorityFeePerGas != nil {
   224  				gasTipCap = args.MaxPriorityFeePerGas.ToInt()
   225  			}
   226  			// Backfill the legacy gasPrice for EVM execution, unless we're all zeroes
   227  			gasPrice = new(big.Int)
   228  			if gasFeeCap.BitLen() > 0 || gasTipCap.BitLen() > 0 {
   229  				gasPrice = math.BigMin(new(big.Int).Add(gasTipCap, baseFee), gasFeeCap)
   230  			}
   231  		}
   232  	}
   233  	value := new(big.Int)
   234  	if args.Value != nil {
   235  		value = args.Value.ToInt()
   236  	}
   237  	data := args.data()
   238  	var accessList types.AccessList
   239  	if args.AccessList != nil {
   240  		accessList = *args.AccessList
   241  	}
   242  	msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, gasFeeCap, gasTipCap, data, accessList, true)
   243  	return msg, nil
   244  }
   245  
   246  // toTransaction converts the arguments to a transaction.
   247  // This assumes that setDefaults has been called.
   248  func (args *TransactionArgs) toTransaction() *types.Transaction {
   249  	var data types.TxData
   250  	switch {
   251  	case args.MaxFeePerGas != nil:
   252  		al := types.AccessList{}
   253  		if args.AccessList != nil {
   254  			al = *args.AccessList
   255  		}
   256  		data = &types.DynamicFeeTx{
   257  			To:         args.To,
   258  			ChainID:    (*big.Int)(args.ChainID),
   259  			Nonce:      uint64(*args.Nonce),
   260  			Gas:        uint64(*args.Gas),
   261  			GasFeeCap:  (*big.Int)(args.MaxFeePerGas),
   262  			GasTipCap:  (*big.Int)(args.MaxPriorityFeePerGas),
   263  			Value:      (*big.Int)(args.Value),
   264  			Data:       args.data(),
   265  			AccessList: al,
   266  		}
   267  	case args.AccessList != nil:
   268  		data = &types.AccessListTx{
   269  			To:         args.To,
   270  			ChainID:    (*big.Int)(args.ChainID),
   271  			Nonce:      uint64(*args.Nonce),
   272  			Gas:        uint64(*args.Gas),
   273  			GasPrice:   (*big.Int)(args.GasPrice),
   274  			Value:      (*big.Int)(args.Value),
   275  			Data:       args.data(),
   276  			AccessList: *args.AccessList,
   277  		}
   278  	default:
   279  		data = &types.LegacyTx{
   280  			To:       args.To,
   281  			Nonce:    uint64(*args.Nonce),
   282  			Gas:      uint64(*args.Gas),
   283  			GasPrice: (*big.Int)(args.GasPrice),
   284  			Value:    (*big.Int)(args.Value),
   285  			Data:     args.data(),
   286  		}
   287  	}
   288  	return types.NewTx(data)
   289  }
   290  
   291  // ToTransaction converts the arguments to a transaction.
   292  // This assumes that setDefaults has been called.
   293  func (args *TransactionArgs) ToTransaction() *types.Transaction {
   294  	return args.toTransaction()
   295  }