github.com/daethereum/go-dae@v2.2.3+incompatible/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/daethereum/go-dae/common"
    27  	"github.com/daethereum/go-dae/common/hexutil"
    28  	"github.com/daethereum/go-dae/common/math"
    29  	"github.com/daethereum/go-dae/core/types"
    30  	"github.com/daethereum/go-dae/log"
    31  	"github.com/daethereum/go-dae/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/daethereum/go-dae/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 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 chain id is provided, ensure it matches the local chain id. Otherwise, set the local
   169  	// chain id as the default.
   170  	want := b.ChainConfig().ChainID
   171  	if args.ChainID != nil {
   172  		if have := (*big.Int)(args.ChainID); have.Cmp(want) != 0 {
   173  			return fmt.Errorf("chainId does not match node's (have=%v, want=%v)", have, want)
   174  		}
   175  	} else {
   176  		args.ChainID = (*hexutil.Big)(want)
   177  	}
   178  	return nil
   179  }
   180  
   181  // ToMessage converts the transaction arguments to the Message type used by the
   182  // core evm. This method is used in calls and traces that do not require a real
   183  // live transaction.
   184  func (args *TransactionArgs) ToMessage(globalGasCap uint64, baseFee *big.Int) (types.Message, error) {
   185  	// Reject invalid combinations of pre- and post-1559 fee styles
   186  	if args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) {
   187  		return types.Message{}, errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
   188  	}
   189  	// Set sender address or use zero address if none specified.
   190  	addr := args.from()
   191  
   192  	// Set default gas & gas price if none were set
   193  	gas := globalGasCap
   194  	if gas == 0 {
   195  		gas = uint64(math.MaxUint64 / 2)
   196  	}
   197  	if args.Gas != nil {
   198  		gas = uint64(*args.Gas)
   199  	}
   200  	if globalGasCap != 0 && globalGasCap < gas {
   201  		log.Warn("Caller gas above allowance, capping", "requested", gas, "cap", globalGasCap)
   202  		gas = globalGasCap
   203  	}
   204  	var (
   205  		gasPrice  *big.Int
   206  		gasFeeCap *big.Int
   207  		gasTipCap *big.Int
   208  	)
   209  	if baseFee == nil {
   210  		// If there's no basefee, then it must be a non-1559 execution
   211  		gasPrice = new(big.Int)
   212  		if args.GasPrice != nil {
   213  			gasPrice = args.GasPrice.ToInt()
   214  		}
   215  		gasFeeCap, gasTipCap = gasPrice, gasPrice
   216  	} else {
   217  		// A basefee is provided, necessitating 1559-type execution
   218  		if args.GasPrice != nil {
   219  			// User specified the legacy gas field, convert to 1559 gas typing
   220  			gasPrice = args.GasPrice.ToInt()
   221  			gasFeeCap, gasTipCap = gasPrice, gasPrice
   222  		} else {
   223  			// User specified 1559 gas feilds (or none), use those
   224  			gasFeeCap = new(big.Int)
   225  			if args.MaxFeePerGas != nil {
   226  				gasFeeCap = args.MaxFeePerGas.ToInt()
   227  			}
   228  			gasTipCap = new(big.Int)
   229  			if args.MaxPriorityFeePerGas != nil {
   230  				gasTipCap = args.MaxPriorityFeePerGas.ToInt()
   231  			}
   232  			// Backfill the legacy gasPrice for EVM execution, unless we're all zeroes
   233  			gasPrice = new(big.Int)
   234  			if gasFeeCap.BitLen() > 0 || gasTipCap.BitLen() > 0 {
   235  				gasPrice = math.BigMin(new(big.Int).Add(gasTipCap, baseFee), gasFeeCap)
   236  			}
   237  		}
   238  	}
   239  	value := new(big.Int)
   240  	if args.Value != nil {
   241  		value = args.Value.ToInt()
   242  	}
   243  	data := args.data()
   244  	var accessList types.AccessList
   245  	if args.AccessList != nil {
   246  		accessList = *args.AccessList
   247  	}
   248  	msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, gasFeeCap, gasTipCap, data, accessList, true)
   249  	return msg, nil
   250  }
   251  
   252  // toTransaction converts the arguments to a transaction.
   253  // This assumes that setDefaults has been called.
   254  func (args *TransactionArgs) toTransaction() *types.Transaction {
   255  	var data types.TxData
   256  	switch {
   257  	case args.MaxFeePerGas != nil:
   258  		al := types.AccessList{}
   259  		if args.AccessList != nil {
   260  			al = *args.AccessList
   261  		}
   262  		data = &types.DynamicFeeTx{
   263  			To:         args.To,
   264  			ChainID:    (*big.Int)(args.ChainID),
   265  			Nonce:      uint64(*args.Nonce),
   266  			Gas:        uint64(*args.Gas),
   267  			GasFeeCap:  (*big.Int)(args.MaxFeePerGas),
   268  			GasTipCap:  (*big.Int)(args.MaxPriorityFeePerGas),
   269  			Value:      (*big.Int)(args.Value),
   270  			Data:       args.data(),
   271  			AccessList: al,
   272  		}
   273  	case args.AccessList != nil:
   274  		data = &types.AccessListTx{
   275  			To:         args.To,
   276  			ChainID:    (*big.Int)(args.ChainID),
   277  			Nonce:      uint64(*args.Nonce),
   278  			Gas:        uint64(*args.Gas),
   279  			GasPrice:   (*big.Int)(args.GasPrice),
   280  			Value:      (*big.Int)(args.Value),
   281  			Data:       args.data(),
   282  			AccessList: *args.AccessList,
   283  		}
   284  	default:
   285  		data = &types.LegacyTx{
   286  			To:       args.To,
   287  			Nonce:    uint64(*args.Nonce),
   288  			Gas:      uint64(*args.Gas),
   289  			GasPrice: (*big.Int)(args.GasPrice),
   290  			Value:    (*big.Int)(args.Value),
   291  			Data:     args.data(),
   292  		}
   293  	}
   294  	return types.NewTx(data)
   295  }
   296  
   297  // ToTransaction converts the arguments to a transaction.
   298  // This assumes that setDefaults has been called.
   299  func (args *TransactionArgs) ToTransaction() *types.Transaction {
   300  	return args.toTransaction()
   301  }