github.com/dominant-strategies/go-quai@v0.28.2/internal/quaiapi/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 quaiapi
    18  
    19  import (
    20  	"bytes"
    21  	"context"
    22  	"errors"
    23  	"fmt"
    24  	"math/big"
    25  
    26  	"github.com/dominant-strategies/go-quai/common"
    27  	"github.com/dominant-strategies/go-quai/common/hexutil"
    28  	"github.com/dominant-strategies/go-quai/common/math"
    29  	"github.com/dominant-strategies/go-quai/core/types"
    30  	"github.com/dominant-strategies/go-quai/log"
    31  	"github.com/dominant-strategies/go-quai/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  	Data  *hexutil.Bytes `json:"data"`
    49  	Input *hexutil.Bytes `json:"input"`
    50  
    51  	// Introduced by AccessListTxType transaction.
    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 (arg *TransactionArgs) from() common.Address {
    58  	if arg.From == nil {
    59  		return common.ZeroAddr
    60  	}
    61  	return *arg.From
    62  }
    63  
    64  // data retrieves the transaction calldata. Input field is preferred.
    65  func (arg *TransactionArgs) data() []byte {
    66  	if arg.Input != nil {
    67  		return *arg.Input
    68  	}
    69  	if arg.Data != nil {
    70  		return *arg.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 args.GasPrice != nil && (args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil) {
    78  		return errors.New("both gasPrice and (maxFeePerGas or maxPriorityFeePerGas) specified")
    79  	}
    80  	head := b.CurrentHeader()
    81  	// If user specifies both maxPriorityfee and maxFee, then we do not
    82  	// need to consult the chain for defaults.
    83  	if args.MaxPriorityFeePerGas == nil || args.MaxFeePerGas == nil {
    84  		// In this clause, user left some fields unspecified.
    85  		if args.GasPrice == nil {
    86  			if args.MaxPriorityFeePerGas == nil {
    87  				tip, err := b.SuggestGasTipCap(ctx)
    88  				if err != nil {
    89  					return err
    90  				}
    91  				args.MaxPriorityFeePerGas = (*hexutil.Big)(tip)
    92  			}
    93  			if args.MaxFeePerGas == nil {
    94  				gasFeeCap := new(big.Int).Add(
    95  					(*big.Int)(args.MaxPriorityFeePerGas),
    96  					new(big.Int).Mul(head.BaseFee(), big.NewInt(2)),
    97  				)
    98  				args.MaxFeePerGas = (*hexutil.Big)(gasFeeCap)
    99  			}
   100  			if args.MaxFeePerGas.ToInt().Cmp(args.MaxPriorityFeePerGas.ToInt()) < 0 {
   101  				return fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", args.MaxFeePerGas, args.MaxPriorityFeePerGas)
   102  			}
   103  		} else {
   104  			if args.MaxFeePerGas != nil || args.MaxPriorityFeePerGas != nil {
   105  				return errors.New("maxFeePerGas or maxPriorityFeePerGas specified but GasPrice is nil")
   106  			}
   107  			if args.GasPrice == nil {
   108  				price, err := b.SuggestGasTipCap(ctx)
   109  				if err != nil {
   110  					return err
   111  				}
   112  
   113  				// The legacy tx gas price suggestion should not add 2x base fee
   114  				// because all fees are consumed, so it would result in a spiral
   115  				// upwards.
   116  				price.Add(price, head.BaseFee())
   117  				args.GasPrice = (*hexutil.Big)(price)
   118  			}
   119  		}
   120  	} else {
   121  		// Both maxPriorityfee and maxFee set by caller. Sanity-check their internal relation
   122  		if args.MaxFeePerGas.ToInt().Cmp(args.MaxPriorityFeePerGas.ToInt()) < 0 {
   123  			return fmt.Errorf("maxFeePerGas (%v) < maxPriorityFeePerGas (%v)", args.MaxFeePerGas, args.MaxPriorityFeePerGas)
   124  		}
   125  	}
   126  	if args.Value == nil {
   127  		args.Value = new(hexutil.Big)
   128  	}
   129  	if args.Nonce == nil {
   130  		nonce, err := b.GetPoolNonce(ctx, args.from())
   131  		if err != nil {
   132  			return err
   133  		}
   134  		args.Nonce = (*hexutil.Uint64)(&nonce)
   135  	}
   136  	if args.Data != nil && args.Input != nil && !bytes.Equal(*args.Data, *args.Input) {
   137  		return errors.New(`both "data" and "input" are set and not equal. Please use "input" to pass transaction call data`)
   138  	}
   139  	if args.To == nil && len(args.data()) == 0 {
   140  		return errors.New(`contract creation without any data provided`)
   141  	}
   142  	// Estimate the gas usage if necessary.
   143  	if args.Gas == nil {
   144  		// These fields are immutable during the estimation, safe to
   145  		// pass the pointer directly.
   146  		callArgs := TransactionArgs{
   147  			From:                 args.From,
   148  			To:                   args.To,
   149  			GasPrice:             args.GasPrice,
   150  			MaxFeePerGas:         args.MaxFeePerGas,
   151  			MaxPriorityFeePerGas: args.MaxPriorityFeePerGas,
   152  			Value:                args.Value,
   153  			Data:                 args.Data,
   154  			AccessList:           args.AccessList,
   155  		}
   156  		pendingBlockNr := rpc.BlockNumberOrHashWithNumber(rpc.PendingBlockNumber)
   157  		estimated, err := DoEstimateGas(ctx, b, callArgs, pendingBlockNr, b.RPCGasCap())
   158  		if err != nil {
   159  			return err
   160  		}
   161  		args.Gas = &estimated
   162  		log.Trace("Estimate gas usage automatically", "gas", args.Gas)
   163  	}
   164  	if args.ChainID == nil {
   165  		id := (*hexutil.Big)(b.ChainConfig().ChainID)
   166  		args.ChainID = id
   167  	}
   168  	return nil
   169  }
   170  
   171  // ToMessage converts th transaction arguments to the Message type used by the
   172  // core evm. This method is used in calls and traces that do not require a real
   173  // live transaction.
   174  func (args *TransactionArgs) ToMessage(globalGasCap uint64, baseFee *big.Int) (types.Message, error) {
   175  	nodeCtx := common.NodeLocation.Context()
   176  	if nodeCtx != common.ZONE_CTX {
   177  		return types.Message{}, errors.New("toMessage can only called in zone chain")
   178  	}
   179  	// Reject invalid combinations of 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  		gasPrice = new(big.Int)
   205  		if args.GasPrice != nil {
   206  			gasPrice = args.GasPrice.ToInt()
   207  		}
   208  		gasFeeCap, gasTipCap = gasPrice, gasPrice
   209  	} else {
   210  		// A basefee is provided
   211  		if args.GasPrice != nil {
   212  			// User specified the legacy gas field, convert
   213  			gasPrice = args.GasPrice.ToInt()
   214  			gasFeeCap, gasTipCap = gasPrice, gasPrice
   215  		} else {
   216  			// User specified max fee (or none), use those
   217  			gasFeeCap = new(big.Int)
   218  			if args.MaxFeePerGas != nil {
   219  				gasFeeCap = args.MaxFeePerGas.ToInt()
   220  			}
   221  			gasTipCap = new(big.Int)
   222  			if args.MaxPriorityFeePerGas != nil {
   223  				gasTipCap = args.MaxPriorityFeePerGas.ToInt()
   224  			}
   225  			// Backfill the legacy gasPrice for EVM execution, unless we're all zeroes
   226  			gasPrice = new(big.Int)
   227  			if gasFeeCap.BitLen() > 0 || gasTipCap.BitLen() > 0 {
   228  				gasPrice = math.BigMin(new(big.Int).Add(gasTipCap, baseFee), gasFeeCap)
   229  			}
   230  		}
   231  	}
   232  	value := new(big.Int)
   233  	if args.Value != nil {
   234  		value = args.Value.ToInt()
   235  	}
   236  	data := args.data()
   237  	var accessList types.AccessList
   238  	if args.AccessList != nil {
   239  		accessList = *args.AccessList
   240  	}
   241  	msg := types.NewMessage(addr, args.To, 0, value, gas, gasPrice, gasFeeCap, gasTipCap, data, accessList, false)
   242  	return msg, nil
   243  }