transaction_args.go 11 KB

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