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