@metamask/transaction-controller 61.1.0 → 61.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/dist/TransactionController.cjs +25 -12
  3. package/dist/TransactionController.cjs.map +1 -1
  4. package/dist/TransactionController.d.cts.map +1 -1
  5. package/dist/TransactionController.d.mts.map +1 -1
  6. package/dist/TransactionController.mjs +26 -13
  7. package/dist/TransactionController.mjs.map +1 -1
  8. package/dist/api/accounts-api.cjs +9 -9
  9. package/dist/api/accounts-api.cjs.map +1 -1
  10. package/dist/api/accounts-api.mjs +9 -9
  11. package/dist/api/accounts-api.mjs.map +1 -1
  12. package/dist/api/simulation-api.cjs.map +1 -1
  13. package/dist/api/simulation-api.mjs.map +1 -1
  14. package/dist/gas-flows/DefaultGasFeeFlow.cjs.map +1 -1
  15. package/dist/gas-flows/DefaultGasFeeFlow.mjs.map +1 -1
  16. package/dist/gas-flows/LineaGasFeeFlow.cjs.map +1 -1
  17. package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -1
  18. package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs.map +1 -1
  19. package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs.map +1 -1
  20. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs +70 -12
  21. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs.map +1 -1
  22. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.cts.map +1 -1
  23. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.mts.map +1 -1
  24. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs +75 -13
  25. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs.map +1 -1
  26. package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.cjs.map +1 -1
  27. package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.mjs.map +1 -1
  28. package/dist/gas-flows/TestGasFeeFlow.cjs.map +1 -1
  29. package/dist/gas-flows/TestGasFeeFlow.mjs.map +1 -1
  30. package/dist/helpers/AccountsApiRemoteTransactionSource.cjs.map +1 -1
  31. package/dist/helpers/AccountsApiRemoteTransactionSource.mjs.map +1 -1
  32. package/dist/helpers/GasFeePoller.cjs.map +1 -1
  33. package/dist/helpers/GasFeePoller.mjs.map +1 -1
  34. package/dist/helpers/IncomingTransactionHelper.cjs.map +1 -1
  35. package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -1
  36. package/dist/helpers/MethodDataHelper.cjs.map +1 -1
  37. package/dist/helpers/MethodDataHelper.mjs.map +1 -1
  38. package/dist/helpers/MultichainTrackingHelper.cjs.map +1 -1
  39. package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -1
  40. package/dist/helpers/PendingTransactionTracker.cjs +2 -1
  41. package/dist/helpers/PendingTransactionTracker.cjs.map +1 -1
  42. package/dist/helpers/PendingTransactionTracker.d.cts.map +1 -1
  43. package/dist/helpers/PendingTransactionTracker.d.mts.map +1 -1
  44. package/dist/helpers/PendingTransactionTracker.mjs +2 -1
  45. package/dist/helpers/PendingTransactionTracker.mjs.map +1 -1
  46. package/dist/helpers/ResimulateHelper.cjs +0 -1
  47. package/dist/helpers/ResimulateHelper.cjs.map +1 -1
  48. package/dist/helpers/ResimulateHelper.d.cts.map +1 -1
  49. package/dist/helpers/ResimulateHelper.d.mts.map +1 -1
  50. package/dist/helpers/ResimulateHelper.mjs +0 -1
  51. package/dist/helpers/ResimulateHelper.mjs.map +1 -1
  52. package/dist/helpers/TransactionPoller.cjs.map +1 -1
  53. package/dist/helpers/TransactionPoller.mjs.map +1 -1
  54. package/dist/hooks/CollectPublishHook.cjs.map +1 -1
  55. package/dist/hooks/CollectPublishHook.mjs.map +1 -1
  56. package/dist/hooks/ExtraTransactionsPublishHook.cjs.map +1 -1
  57. package/dist/hooks/ExtraTransactionsPublishHook.mjs.map +1 -1
  58. package/dist/hooks/SequentialPublishBatchHook.cjs.map +1 -1
  59. package/dist/hooks/SequentialPublishBatchHook.mjs.map +1 -1
  60. package/dist/types.cjs.map +1 -1
  61. package/dist/types.d.cts +10 -0
  62. package/dist/types.d.cts.map +1 -1
  63. package/dist/types.d.mts +10 -0
  64. package/dist/types.d.mts.map +1 -1
  65. package/dist/types.mjs.map +1 -1
  66. package/dist/utils/balance-changes.cjs +3 -4
  67. package/dist/utils/balance-changes.cjs.map +1 -1
  68. package/dist/utils/balance-changes.d.cts.map +1 -1
  69. package/dist/utils/balance-changes.d.mts.map +1 -1
  70. package/dist/utils/balance-changes.mjs +4 -5
  71. package/dist/utils/balance-changes.mjs.map +1 -1
  72. package/dist/utils/balance.cjs +40 -0
  73. package/dist/utils/balance.cjs.map +1 -0
  74. package/dist/utils/balance.d.cts +23 -0
  75. package/dist/utils/balance.d.cts.map +1 -0
  76. package/dist/utils/balance.d.mts +23 -0
  77. package/dist/utils/balance.d.mts.map +1 -0
  78. package/dist/utils/balance.mjs +35 -0
  79. package/dist/utils/balance.mjs.map +1 -0
  80. package/dist/utils/batch.cjs +3 -1
  81. package/dist/utils/batch.cjs.map +1 -1
  82. package/dist/utils/batch.mjs +3 -1
  83. package/dist/utils/batch.mjs.map +1 -1
  84. package/dist/utils/eip7702.cjs.map +1 -1
  85. package/dist/utils/eip7702.mjs.map +1 -1
  86. package/dist/utils/external-transactions.cjs.map +1 -1
  87. package/dist/utils/external-transactions.mjs.map +1 -1
  88. package/dist/utils/first-time-interaction.cjs.map +1 -1
  89. package/dist/utils/first-time-interaction.mjs.map +1 -1
  90. package/dist/utils/gas-fee-tokens.cjs +42 -1
  91. package/dist/utils/gas-fee-tokens.cjs.map +1 -1
  92. package/dist/utils/gas-fee-tokens.d.cts +16 -0
  93. package/dist/utils/gas-fee-tokens.d.cts.map +1 -1
  94. package/dist/utils/gas-fee-tokens.d.mts +16 -0
  95. package/dist/utils/gas-fee-tokens.d.mts.map +1 -1
  96. package/dist/utils/gas-fee-tokens.mjs +40 -0
  97. package/dist/utils/gas-fee-tokens.mjs.map +1 -1
  98. package/dist/utils/gas-fees.cjs.map +1 -1
  99. package/dist/utils/gas-fees.mjs.map +1 -1
  100. package/dist/utils/gas-flow.cjs.map +1 -1
  101. package/dist/utils/gas-flow.mjs.map +1 -1
  102. package/dist/utils/gas.cjs.map +1 -1
  103. package/dist/utils/gas.mjs.map +1 -1
  104. package/dist/utils/history.cjs.map +1 -1
  105. package/dist/utils/history.mjs.map +1 -1
  106. package/dist/utils/layer1-gas-fee-flow.cjs.map +1 -1
  107. package/dist/utils/layer1-gas-fee-flow.mjs.map +1 -1
  108. package/dist/utils/nonce.cjs.map +1 -1
  109. package/dist/utils/nonce.mjs.map +1 -1
  110. package/dist/utils/prepare.cjs.map +1 -1
  111. package/dist/utils/prepare.mjs.map +1 -1
  112. package/dist/utils/retry.cjs.map +1 -1
  113. package/dist/utils/retry.mjs.map +1 -1
  114. package/dist/utils/signature.cjs.map +1 -1
  115. package/dist/utils/signature.mjs.map +1 -1
  116. package/dist/utils/swaps.cjs.map +1 -1
  117. package/dist/utils/swaps.mjs.map +1 -1
  118. package/dist/utils/transaction-type.cjs.map +1 -1
  119. package/dist/utils/transaction-type.mjs.map +1 -1
  120. package/dist/utils/utils.cjs +54 -1
  121. package/dist/utils/utils.cjs.map +1 -1
  122. package/dist/utils/utils.d.cts +17 -1
  123. package/dist/utils/utils.d.cts.map +1 -1
  124. package/dist/utils/utils.d.mts +17 -1
  125. package/dist/utils/utils.d.mts.map +1 -1
  126. package/dist/utils/utils.mjs +51 -0
  127. package/dist/utils/utils.mjs.map +1 -1
  128. package/dist/utils/validation.cjs.map +1 -1
  129. package/dist/utils/validation.mjs.map +1 -1
  130. package/package.json +5 -3
@@ -1,3 +1,4 @@
1
+ import type EthQuery from "@metamask/eth-query";
1
2
  import type { Hex } from "@metamask/utils";
2
3
  import type { GasFeeToken, TransactionControllerMessenger, TransactionMeta } from "../index.mjs";
3
4
  import type { GetSimulationConfig } from "../types.mjs";
@@ -25,4 +26,19 @@ export declare function getGasFeeTokens({ chainId, isEIP7702GasFeeTokensEnabled,
25
26
  gasFeeTokens: GasFeeToken[];
26
27
  isGasFeeSponsored: boolean;
27
28
  }>;
29
+ /**
30
+ * Check and update gas fee token selection before publishing a transaction.
31
+ *
32
+ * @param request - Request object.
33
+ * @param request.ethQuery - EthQuery instance.
34
+ * @param request.fetchGasFeeTokens - Function to fetch gas fee tokens.
35
+ * @param request.transaction - Transaction metadata.
36
+ * @param request.updateTransaction - Function to update the transaction.
37
+ */
38
+ export declare function checkGasFeeTokenBeforePublish({ ethQuery, fetchGasFeeTokens, transaction, updateTransaction, }: {
39
+ ethQuery: EthQuery;
40
+ fetchGasFeeTokens: (transaction: TransactionMeta) => Promise<GasFeeToken[]>;
41
+ transaction: TransactionMeta;
42
+ updateTransaction: (transactionId: string, fn: (tx: TransactionMeta) => void) => void;
43
+ }): Promise<void>;
28
44
  //# sourceMappingURL=gas-fee-tokens.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"gas-fee-tokens.d.mts","sourceRoot":"","sources":["../../src/utils/gas-fee-tokens.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAM3C,OAAO,KAAK,EACV,WAAW,EACX,8BAA8B,EAC9B,eAAe,EAChB,qBAAW;AAQZ,OAAO,KAAK,EAAE,mBAAmB,EAAE,qBAAiB;AAIpD,MAAM,MAAM,sBAAsB,GAAG;IACnC,OAAO,EAAE,GAAG,CAAC;IACb,4BAA4B,EAAE,CAC5B,eAAe,EAAE,eAAe,KAC7B,OAAO,CAAC,OAAO,CAAC,CAAC;IACtB,mBAAmB,EAAE,mBAAmB,CAAC;IACzC,SAAS,EAAE,8BAA8B,CAAC;IAC1C,gBAAgB,CAAC,EAAE,GAAG,CAAC;IACvB,eAAe,EAAE,eAAe,CAAC;CAClC,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAsB,eAAe,CAAC,EACpC,OAAO,EACP,4BAA4B,EAC5B,SAAS,EACT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cErrors } from "@metamask/rpc-errors";
2
2
  import { createModuleLogger } from "@metamask/utils";
3
+ import { isNativeBalanceSufficientForGas } from "./balance.mjs";
3
4
  import { ERROR_MESSAGE_NO_UPGRADE_CONTRACT } from "./batch.mjs";
4
5
  import { ERROR_MESSGE_PUBLIC_KEY, doesChainSupportEIP7702 } from "./eip7702.mjs";
5
6
  import { getEIP7702UpgradeContractAddress } from "./feature-flags.mjs";
@@ -68,6 +69,45 @@ export async function getGasFeeTokens({ chainId, isEIP7702GasFeeTokensEnabled, m
68
69
  return { gasFeeTokens: [], isGasFeeSponsored: false };
69
70
  }
70
71
  }
72
+ /**
73
+ * Check and update gas fee token selection before publishing a transaction.
74
+ *
75
+ * @param request - Request object.
76
+ * @param request.ethQuery - EthQuery instance.
77
+ * @param request.fetchGasFeeTokens - Function to fetch gas fee tokens.
78
+ * @param request.transaction - Transaction metadata.
79
+ * @param request.updateTransaction - Function to update the transaction.
80
+ */
81
+ export async function checkGasFeeTokenBeforePublish({ ethQuery, fetchGasFeeTokens, transaction, updateTransaction, }) {
82
+ const { gasFeeTokens, isGasFeeTokenIgnoredIfBalance, selectedGasFeeToken } = transaction;
83
+ if (!selectedGasFeeToken || !isGasFeeTokenIgnoredIfBalance) {
84
+ return;
85
+ }
86
+ const hasNativeBalance = await isNativeBalanceSufficientForGas(transaction, ethQuery);
87
+ if (hasNativeBalance) {
88
+ log('Ignoring gas fee token before publish due to sufficient native balance');
89
+ updateTransaction(transaction.id, (tx) => {
90
+ tx.isExternalSign = false;
91
+ tx.selectedGasFeeToken = undefined;
92
+ });
93
+ return;
94
+ }
95
+ updateTransaction(transaction.id, (tx) => {
96
+ tx.isExternalSign = true;
97
+ });
98
+ let finalGasFeeTokens = gasFeeTokens;
99
+ if (finalGasFeeTokens === undefined) {
100
+ const newGasFeeTokens = await fetchGasFeeTokens(transaction);
101
+ updateTransaction(transaction.id, (tx) => {
102
+ tx.gasFeeTokens = newGasFeeTokens;
103
+ });
104
+ log('Updated gas fee tokens before publish', newGasFeeTokens);
105
+ finalGasFeeTokens = newGasFeeTokens;
106
+ }
107
+ if (!finalGasFeeTokens?.some((t) => t.tokenAddress.toLowerCase() === selectedGasFeeToken.toLowerCase())) {
108
+ throw new Error('Gas fee token not found and insufficient native balance');
109
+ }
110
+ }
71
111
  /**
72
112
  * Extract gas fee tokens from a simulation response.
73
113
  *
@@ -1 +1 @@
1
- {"version":3,"file":"gas-fee-tokens.mjs","sourceRoot":"","sources":["../../src/utils/gas-fee-tokens.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,iCAAiC,EAAE,oBAAgB;AAC5D,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,sBAAkB;AAC7E,OAAO,EAAE,gCAAgC,EAAE,4BAAwB;AAOnE,OAAO,EACL,oBAAoB,EAGrB,kCAA8B;AAC/B,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAG1C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAahE;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,EACpC,OAAO,EACP,4BAA4B,EAC5B,SAAS,EACT,gBAAgB,EAChB,eAAe,EACf,mBAAmB,GACI;IACvB,MAAM,EAAE,iBAAiB,EAAE,QAAQ,EAAE,GAAG,eAAe,CAAC;IACxD,MAAM,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,GAAG,QAAQ,CAAC;IACjE,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAW,CAAC;IAClC,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAW,CAAC;IAClC,MAAM,EAAE,GAAG,QAAQ,CAAC,EAAS,CAAC;IAC9B,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAY,CAAC;IAEpC,GAAG,CAAC,SAAS,EAAE,EAAE,OAAO,EAAE,QAA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,CAAC,iCAAiC,CAAC,CAAC;KAC7D;IAED,OAAO;QACL;YACE,OAAO,EAAE,cAAc;YACvB,IAAI,EAAE,IAAW;SAClB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { ERROR_MESSAGE_NO_UPGRADE_CONTRACT } from './batch';\nimport { ERROR_MESSGE_PUBLIC_KEY, doesChainSupportEIP7702 } from './eip7702';\nimport { getEIP7702UpgradeContractAddress } from './feature-flags';\nimport type {\n GasFeeToken,\n TransactionControllerMessenger,\n TransactionMeta,\n} from '..';\nimport type { SimulationRequestTransaction } from '../api/simulation-api';\nimport {\n simulateTransactions,\n type SimulationResponse,\n type SimulationResponseTransaction,\n} from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { GetSimulationConfig } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'gas-fee-tokens');\n\nexport type GetGasFeeTokensRequest = {\n chainId: Hex;\n isEIP7702GasFeeTokensEnabled: (\n transactionMeta: TransactionMeta,\n ) => Promise<boolean>;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n transactionMeta: TransactionMeta;\n};\n\n/**\n * Get gas fee tokens for a transaction.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.isEIP7702GasFeeTokensEnabled - Callback to check if EIP-7702 gas fee tokens are enabled.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - Public key to validate EIP-7702 contract signatures.\n * @param request.transactionMeta - The transaction metadata.\n * @param request.getSimulationConfig - Optional transaction simulation parameters.\n * @returns An array of gas fee tokens.\n */\nexport async function getGasFeeTokens({\n chainId,\n isEIP7702GasFeeTokensEnabled,\n messenger,\n publicKeyEIP7702,\n transactionMeta,\n getSimulationConfig,\n}: GetGasFeeTokensRequest) {\n const { delegationAddress, txParams } = transactionMeta;\n const { authorizationList: authorizationListRequest } = txParams;\n const data = txParams.data as Hex;\n const from = txParams.from as Hex;\n const to = txParams.to as Hex;\n const value = txParams.value as Hex;\n\n log('Request', { chainId, txParams });\n\n const is7702GasFeeTokensEnabled =\n await isEIP7702GasFeeTokensEnabled(transactionMeta);\n\n const with7702 =\n is7702GasFeeTokensEnabled && doesChainSupportEIP7702(chainId, messenger);\n\n let authorizationList:\n | SimulationRequestTransaction['authorizationList']\n | undefined = authorizationListRequest?.map((authorization) => ({\n address: authorization.address,\n from: from as Hex,\n }));\n\n if (with7702 && !delegationAddress && !authorizationList) {\n authorizationList = buildAuthorizationList({\n chainId,\n from: from as Hex,\n messenger,\n publicKeyEIP7702,\n });\n }\n\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n authorizationList,\n data,\n from,\n to,\n value,\n },\n ],\n suggestFees: {\n withTransfer: true,\n withFeeTransfer: true,\n with7702,\n },\n });\n\n log('Response', response);\n\n const result = parseGasFeeTokens(response);\n\n log('Gas fee tokens', result);\n\n return result;\n } catch (error) {\n log('Failed to gas fee tokens', error);\n return { gasFeeTokens: [], isGasFeeSponsored: false };\n }\n}\n\n/**\n * Extract gas fee tokens from a simulation response.\n *\n * @param response - The simulation response.\n * @returns gasFeeTokens: An array of gas fee tokens. isGasFeeSponsored: Whether the transaction is sponsored\n */\nfunction parseGasFeeTokens(response: SimulationResponse): {\n gasFeeTokens: GasFeeToken[];\n isGasFeeSponsored: boolean;\n} {\n const feeLevel = response.transactions?.[0]\n ?.fees?.[0] as Required<SimulationResponseTransaction>['fees'][0];\n\n const isGasFeeSponsored = response.sponsorship?.isSponsored ?? false;\n\n const tokenFees = feeLevel?.tokenFees ?? [];\n\n return {\n gasFeeTokens: tokenFees.map((tokenFee) => ({\n amount: tokenFee.balanceNeededToken,\n balance: tokenFee.currentBalanceToken,\n decimals: tokenFee.token.decimals,\n fee: tokenFee.serviceFee,\n gas: feeLevel.gas,\n gasTransfer: tokenFee.transferEstimate,\n maxFeePerGas: feeLevel.maxFeePerGas,\n maxPriorityFeePerGas: feeLevel.maxPriorityFeePerGas,\n rateWei: tokenFee.rateWei,\n recipient: tokenFee.feeRecipient,\n symbol: tokenFee.token.symbol,\n tokenAddress: tokenFee.token.address,\n })),\n isGasFeeSponsored,\n };\n}\n\n/**\n * Generate the authorization list for the request.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID.\n * @param request.from - The sender's address.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - The public key for EIP-7702.\n * @returns The authorization list.\n */\nfunction buildAuthorizationList({\n chainId,\n from,\n messenger,\n publicKeyEIP7702,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n}): SimulationRequestTransaction['authorizationList'] | undefined {\n if (!publicKeyEIP7702) {\n throw rpcErrors.internal(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n const upgradeAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeAddress) {\n throw rpcErrors.internal(ERROR_MESSAGE_NO_UPGRADE_CONTRACT);\n }\n\n return [\n {\n address: upgradeAddress,\n from: from as Hex,\n },\n ];\n}\n"]}
1
+ {"version":3,"file":"gas-fee-tokens.mjs","sourceRoot":"","sources":["../../src/utils/gas-fee-tokens.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,+BAA+B,EAAE,sBAAkB;AAC5D,OAAO,EAAE,iCAAiC,EAAE,oBAAgB;AAC5D,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,sBAAkB;AAC7E,OAAO,EAAE,gCAAgC,EAAE,4BAAwB;AAOnE,OAAO,EACL,oBAAoB,EAGrB,kCAA8B;AAC/B,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAG1C,MAAM,GAAG,G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ACjC,GAAG,EAAE,QAAQ,CAAC,UAAU;YACxB,GAAG,EAAE,QAAQ,CAAC,GAAG;YACjB,WAAW,EAAE,QAAQ,CAAC,gBAAgB;YACtC,YAAY,EAAE,QAAQ,CAAC,YAAY;YACnC,oBAAoB,EAAE,QAAQ,CAAC,oBAAoB;YACnD,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,SAAS,EAAE,QAAQ,CAAC,YAAY;YAChC,MAAM,EAAE,QAAQ,CAAC,KAAK,CAAC,MAAM;YAC7B,YAAY,EAAE,QAAQ,CAAC,KAAK,CAAC,OAAO;SACrC,CAAC,CAAC;QACH,iBAAiB;KAClB,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,SAAS,sBAAsB,CAAC,EAC9B,OAAO,EACP,IAAI,EACJ,SAAS,EACT,gBAAgB,GAMjB;IACC,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,MAAM,SAAS,CAAC,QAAQ,CAAC,uBAAuB,CAAC,CAAC;IACpD,CAAC;IAED,MAAM,cAAc,GAAG,gCAAgC,CACrD,OAAO,EACP,SAAS,EACT,gBAAgB,CACjB,CAAC;IAEF,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,MAAM,SAAS,CAAC,QAAQ,CAAC,iCAAiC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO;QACL;YACE,OAAO,EAAE,cAAc;YACvB,IAAI,EAAE,IAAW;SAClB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { isNativeBalanceSufficientForGas } from './balance';\nimport { ERROR_MESSAGE_NO_UPGRADE_CONTRACT } from './batch';\nimport { ERROR_MESSGE_PUBLIC_KEY, doesChainSupportEIP7702 } from './eip7702';\nimport { getEIP7702UpgradeContractAddress } from './feature-flags';\nimport type {\n GasFeeToken,\n TransactionControllerMessenger,\n TransactionMeta,\n} from '..';\nimport type { SimulationRequestTransaction } from '../api/simulation-api';\nimport {\n simulateTransactions,\n type SimulationResponse,\n type SimulationResponseTransaction,\n} from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { GetSimulationConfig } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'gas-fee-tokens');\n\nexport type GetGasFeeTokensRequest = {\n chainId: Hex;\n isEIP7702GasFeeTokensEnabled: (\n transactionMeta: TransactionMeta,\n ) => Promise<boolean>;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n transactionMeta: TransactionMeta;\n};\n\n/**\n * Get gas fee tokens for a transaction.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.isEIP7702GasFeeTokensEnabled - Callback to check if EIP-7702 gas fee tokens are enabled.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - Public key to validate EIP-7702 contract signatures.\n * @param request.transactionMeta - The transaction metadata.\n * @param request.getSimulationConfig - Optional transaction simulation parameters.\n * @returns An array of gas fee tokens.\n */\nexport async function getGasFeeTokens({\n chainId,\n isEIP7702GasFeeTokensEnabled,\n messenger,\n publicKeyEIP7702,\n transactionMeta,\n getSimulationConfig,\n}: GetGasFeeTokensRequest) {\n const { delegationAddress, txParams } = transactionMeta;\n const { authorizationList: authorizationListRequest } = txParams;\n const data = txParams.data as Hex;\n const from = txParams.from as Hex;\n const to = txParams.to as Hex;\n const value = txParams.value as Hex;\n\n log('Request', { chainId, txParams });\n\n const is7702GasFeeTokensEnabled =\n await isEIP7702GasFeeTokensEnabled(transactionMeta);\n\n const with7702 =\n is7702GasFeeTokensEnabled && doesChainSupportEIP7702(chainId, messenger);\n\n let authorizationList:\n | SimulationRequestTransaction['authorizationList']\n | undefined = authorizationListRequest?.map((authorization) => ({\n address: authorization.address,\n from: from as Hex,\n }));\n\n if (with7702 && !delegationAddress && !authorizationList) {\n authorizationList = buildAuthorizationList({\n chainId,\n from: from as Hex,\n messenger,\n publicKeyEIP7702,\n });\n }\n\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n authorizationList,\n data,\n from,\n to,\n value,\n },\n ],\n suggestFees: {\n withTransfer: true,\n withFeeTransfer: true,\n with7702,\n },\n });\n\n log('Response', response);\n\n const result = parseGasFeeTokens(response);\n\n log('Gas fee tokens', result);\n\n return result;\n } catch (error) {\n log('Failed to gas fee tokens', error);\n return { gasFeeTokens: [], isGasFeeSponsored: false };\n }\n}\n\n/**\n * Check and update gas fee token selection before publishing a transaction.\n *\n * @param request - Request object.\n * @param request.ethQuery - EthQuery instance.\n * @param request.fetchGasFeeTokens - Function to fetch gas fee tokens.\n * @param request.transaction - Transaction metadata.\n * @param request.updateTransaction - Function to update the transaction.\n */\nexport async function checkGasFeeTokenBeforePublish({\n ethQuery,\n fetchGasFeeTokens,\n transaction,\n updateTransaction,\n}: {\n ethQuery: EthQuery;\n fetchGasFeeTokens: (transaction: TransactionMeta) => Promise<GasFeeToken[]>;\n transaction: TransactionMeta;\n updateTransaction: (\n transactionId: string,\n fn: (tx: TransactionMeta) => void,\n ) => void;\n}) {\n const { gasFeeTokens, isGasFeeTokenIgnoredIfBalance, selectedGasFeeToken } =\n transaction;\n\n if (!selectedGasFeeToken || !isGasFeeTokenIgnoredIfBalance) {\n return;\n }\n\n const hasNativeBalance = await isNativeBalanceSufficientForGas(\n transaction,\n ethQuery,\n );\n\n if (hasNativeBalance) {\n log(\n 'Ignoring gas fee token before publish due to sufficient native balance',\n );\n\n updateTransaction(transaction.id, (tx) => {\n tx.isExternalSign = false;\n tx.selectedGasFeeToken = undefined;\n });\n\n return;\n }\n\n updateTransaction(transaction.id, (tx) => {\n tx.isExternalSign = true;\n });\n\n let finalGasFeeTokens = gasFeeTokens;\n\n if (finalGasFeeTokens === undefined) {\n const newGasFeeTokens = await fetchGasFeeTokens(transaction);\n\n updateTransaction(transaction.id, (tx) => {\n tx.gasFeeTokens = newGasFeeTokens;\n });\n\n log('Updated gas fee tokens before publish', newGasFeeTokens);\n\n finalGasFeeTokens = newGasFeeTokens;\n }\n\n if (\n !finalGasFeeTokens?.some(\n (t) => t.tokenAddress.toLowerCase() === selectedGasFeeToken.toLowerCase(),\n )\n ) {\n throw new Error('Gas fee token not found and insufficient native balance');\n }\n}\n\n/**\n * Extract gas fee tokens from a simulation response.\n *\n * @param response - The simulation response.\n * @returns gasFeeTokens: An array of gas fee tokens. isGasFeeSponsored: Whether the transaction is sponsored\n */\nfunction parseGasFeeTokens(response: SimulationResponse): {\n gasFeeTokens: GasFeeToken[];\n isGasFeeSponsored: boolean;\n} {\n const feeLevel = response.transactions?.[0]\n ?.fees?.[0] as Required<SimulationResponseTransaction>['fees'][0];\n\n const isGasFeeSponsored = response.sponsorship?.isSponsored ?? false;\n\n const tokenFees = feeLevel?.tokenFees ?? [];\n\n return {\n gasFeeTokens: tokenFees.map((tokenFee) => ({\n amount: tokenFee.balanceNeededToken,\n balance: tokenFee.currentBalanceToken,\n decimals: tokenFee.token.decimals,\n fee: tokenFee.serviceFee,\n gas: feeLevel.gas,\n gasTransfer: tokenFee.transferEstimate,\n maxFeePerGas: feeLevel.maxFeePerGas,\n maxPriorityFeePerGas: feeLevel.maxPriorityFeePerGas,\n rateWei: tokenFee.rateWei,\n recipient: tokenFee.feeRecipient,\n symbol: tokenFee.token.symbol,\n tokenAddress: tokenFee.token.address,\n })),\n isGasFeeSponsored,\n };\n}\n\n/**\n * Generate the authorization list for the request.\n *\n * @param request - The request object.\n * @param request.chainId - The chain ID.\n * @param request.from - The sender's address.\n * @param request.messenger - The messenger instance.\n * @param request.publicKeyEIP7702 - The public key for EIP-7702.\n * @returns The authorization list.\n */\nfunction buildAuthorizationList({\n chainId,\n from,\n messenger,\n publicKeyEIP7702,\n}: {\n chainId: Hex;\n from: Hex;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n}): SimulationRequestTransaction['authorizationList'] | undefined {\n if (!publicKeyEIP7702) {\n throw rpcErrors.internal(ERROR_MESSGE_PUBLIC_KEY);\n }\n\n const upgradeAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeAddress) {\n throw rpcErrors.internal(ERROR_MESSAGE_NO_UPGRADE_CONTRACT);\n }\n\n return [\n {\n address: upgradeAddress,\n from: from as Hex,\n },\n ];\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"gas-fees.cjs","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":";;;AAAA,iEAKoC;AAOpC,2CAA4D;AAE5D,6CAA2C;AAC3C,uCAAiD;AACjD,0CAA0C;AAS1C,wCAA4D;AA0B5D,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,UAAU,CAAC,CAAC;AAE1D;;;;GAIG;AACI,KAAK,UAAU,aAAa,CAAC,OAA6B;IAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC3B,MAAM,aAAa,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IAE7C,MAAM,MAAM,GAAG,8BAAsB,CAAC,QAAQ,CAC5C,MAAM,CAAC,IAAuB,CAC/B,CAAC;IACF,MAAM,YAAY,GAAG,MAAM;QACzB,CAAC,CAAC,SAAS;QACX,CAAC,CAAC,OAAO,CAAC,eAAe,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAE5C,MAAM,gBAAgB,GAAG,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;IAE5D,GAAG,CAAC,oBAAoB,EAAE,gBAAgB,CAAC,CAAC;IAE5C,MAAM,gBAAgB,GAAqB;QACzC,GAAG,OAAO;QACV,aAAa;QACb,YAAY;QACZ,gBAAgB;KACjB,CAAC;IAEF,MAAM,CAAC,QAAQ,CAAC,YAAY,GAAG,eAAe,CAAC,gBAAgB,CAAC,CAAC;IAEjE,MAAM,CAAC,QAAQ,CAA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AAC,SAAS,EAAE,IAAI,CAAC;QAEpD,QAAQ,kBAAkB,EAAE;YAC1B,KAAK,0BAAkB,CAAC,SAAS;gBAC/B,OAAO,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC;YACnC,KAAK,0BAAkB,CAAC,MAAM;gBAC5B,OAAO;oBACL,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM;iBACpC,CAAC;YACJ,KAAK,0BAAkB,CAAC,QAAQ;gBAC9B,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;YACnD;gBACE,MAAM,IAAI,KAAK;gBACb,gFAAgF;gBAChF,4EAA4E;gBAC5E,yDAAyD,kBAAkB,EAAE,CAC9E,CAAC;SACL;KACF;IAAC,OAAO,KAAK,EAAE;QACd,GAAG,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;KAChD;IAED,MAAM,eAAe,GAAG,CAAC,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,UAAU,CAAC,CAAW,CAAC;IAEtE,MAAM,QAAQ,GAAG,eAAe;QAC9B,CAAC,CAAC,IAAA,aAAK,EAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\n/**\n * Update the gas fee properties of the provided transaction meta.\n *\n * @param request - The request object.\n */\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\n/**\n * Convert GWEI from decimal string to WEI as hex string.\n *\n * @param value - The GWEI value as a decimal string.\n * @returns The WEI value in hex.\n */\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\n/**\n * Converts a value from Gwei decimal representation to Wei decimal representation\n *\n * @param gweiDecimal - The value in Gwei as a string or number\n * @returns The value in Wei as a string\n *\n * @example\n * // Convert 1.5 Gwei to Wei\n * gweiDecimalToWeiDecimal(\"1.5\")\n * // Returns \"1500000000\"\n */\nexport function gweiDecimalToWeiDecimal(gweiDecimal: string | number): string {\n const weiValue = Number(gweiDecimal) * 1e9;\n\n return weiValue.toString().split('.')[0];\n}\n\n/**\n * Determine the maxFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxFeePerGas value.\n */\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee as string);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the maxPriorityFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxPriorityFeePerGas value.\n */\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the gasPrice value for the transaction.\n *\n * @param request - The request object.\n * @returns The gasPrice value.\n */\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\n/**\n * Determine the user fee level.\n *\n * @param request - The request object.\n * @returns The user fee level.\n */\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { initialParams, savedGasFees, suggestedGasFees, txMeta } = request;\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.gasPrice\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\n/**\n * Update the default gas estimates for the provided transaction.\n *\n * @param txMeta - The transaction metadata.\n */\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\n/**\n * Retrieve the suggested gas fees using the gas fee flows.\n *\n * @param request - The request object.\n * @returns The suggested gas fees.\n */\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const {\n eip1559,\n ethQuery,\n gasFeeFlows,\n getGasFeeEstimates,\n messenger,\n txMeta,\n } = request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(\n txMeta,\n gasFeeFlows,\n messenger,\n ) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
1
+ {"version":3,"file":"gas-fees.cjs","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":";;;AAAA,iEAKoC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B,KAAK,0BAAkB,CAAC,SAAS;gBAC/B,OAAO,QAAQ,CAAC,SAAS,CAAC,MAAM,CAAC;YACnC,KAAK,0BAAkB,CAAC,MAAM;gBAC5B,OAAO;oBACL,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM;iBACpC,CAAC;YACJ,KAAK,0BAAkB,CAAC,QAAQ;gBAC9B,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;YACnD;gBACE,MAAM,IAAI,KAAK;gBACb,gFAAgF;gBAChF,4EAA4E;gBAC5E,yDAAyD,kBAAkB,EAAE,CAC9E,CAAC;QACN,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;IAED,MAAM,eAAe,GAAG,CAAC,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,UAAU,CAAC,CAAW,CAAC;IAEtE,MAAM,QAAQ,GAAG,eAAe;QAC9B,CAAC,CAAC,IAAA,aAAK,EAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\n/**\n * Update the gas fee properties of the provided transaction meta.\n *\n * @param request - The request object.\n */\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\n/**\n * Convert GWEI from decimal string to WEI as hex string.\n *\n * @param value - The GWEI value as a decimal string.\n * @returns The WEI value in hex.\n */\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\n/**\n * Converts a value from Gwei decimal representation to Wei decimal representation\n *\n * @param gweiDecimal - The value in Gwei as a string or number\n * @returns The value in Wei as a string\n *\n * @example\n * // Convert 1.5 Gwei to Wei\n * gweiDecimalToWeiDecimal(\"1.5\")\n * // Returns \"1500000000\"\n */\nexport function gweiDecimalToWeiDecimal(gweiDecimal: string | number): string {\n const weiValue = Number(gweiDecimal) * 1e9;\n\n return weiValue.toString().split('.')[0];\n}\n\n/**\n * Determine the maxFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxFeePerGas value.\n */\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee as string);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the maxPriorityFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxPriorityFeePerGas value.\n */\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the gasPrice value for the transaction.\n *\n * @param request - The request object.\n * @returns The gasPrice value.\n */\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\n/**\n * Determine the user fee level.\n *\n * @param request - The request object.\n * @returns The user fee level.\n */\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { initialParams, savedGasFees, suggestedGasFees, txMeta } = request;\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.gasPrice\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\n/**\n * Update the default gas estimates for the provided transaction.\n *\n * @param txMeta - The transaction metadata.\n */\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\n/**\n * Retrieve the suggested gas fees using the gas fee flows.\n *\n * @param request - The request object.\n * @returns The suggested gas fees.\n */\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const {\n eip1559,\n ethQuery,\n gasFeeFlows,\n getGasFeeEstimates,\n messenger,\n txMeta,\n } = request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(\n txMeta,\n gasFeeFlows,\n messenger,\n ) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"gas-fees.mjs","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,cAAc,EACd,KA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ACJ,KAAK,kBAAkB,CAAC,QAAQ;gBAC9B,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;YACnD;gBACE,MAAM,IAAI,KAAK;gBACb,gFAAgF;gBAChF,4EAA4E;gBAC5E,yDAAyD,kBAAkB,EAAE,CAC9E,CAAC;SACL;KACF;IAAC,OAAO,KAAK,EAAE;QACd,GAAG,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;KAChD;IAED,MAAM,eAAe,GAAG,CAAC,MAAM,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAW,CAAC;IAEtE,MAAM,QAAQ,GAAG,eAAe;QAC9B,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\n/**\n * Update the gas fee properties of the provided transaction meta.\n *\n * @param request - The request object.\n */\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\n/**\n * Convert GWEI from decimal string to WEI as hex string.\n *\n * @param value - The GWEI value as a decimal string.\n * @returns The WEI value in hex.\n */\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\n/**\n * Converts a value from Gwei decimal representation to Wei decimal representation\n *\n * @param gweiDecimal - The value in Gwei as a string or number\n * @returns The value in Wei as a string\n *\n * @example\n * // Convert 1.5 Gwei to Wei\n * gweiDecimalToWeiDecimal(\"1.5\")\n * // Returns \"1500000000\"\n */\nexport function gweiDecimalToWeiDecimal(gweiDecimal: string | number): string {\n const weiValue = Number(gweiDecimal) * 1e9;\n\n return weiValue.toString().split('.')[0];\n}\n\n/**\n * Determine the maxFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxFeePerGas value.\n */\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee as string);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the maxPriorityFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxPriorityFeePerGas value.\n */\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the gasPrice value for the transaction.\n *\n * @param request - The request object.\n * @returns The gasPrice value.\n */\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\n/**\n * Determine the user fee level.\n *\n * @param request - The request object.\n * @returns The user fee level.\n */\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { initialParams, savedGasFees, suggestedGasFees, txMeta } = request;\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.gasPrice\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\n/**\n * Update the default gas estimates for the provided transaction.\n *\n * @param txMeta - The transaction metadata.\n */\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\n/**\n * Retrieve the suggested gas fees using the gas fee flows.\n *\n * @param request - The request object.\n * @returns The suggested gas fees.\n */\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const {\n eip1559,\n ethQuery,\n gasFeeFlows,\n getGasFeeEstimates,\n messenger,\n txMeta,\n } = request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(\n txMeta,\n gasFeeFlows,\n messenger,\n ) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
1
+ {"version":3,"file":"gas-fees.mjs","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,cAAc,EACd,KAAK,EACL,KAAK,EACN,mCAAmC;AAOpC,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,wBAAwB;AAE5D,OAAO,EAAE,aAAa,EAAE,uBAAmB;AAC3C,OAAO,EAAE,sBAAsB,EAAE,oBAAgB;AACjD,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAS1C,OAAO,EAAE,kBAAkB,EAAE,YAAY,E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O;oBACL,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,MAAM;iBACpC,CAAC;YACJ,KAAK,kBAAkB,CAAC,QAAQ;gBAC9B,OAAO,EAAE,QAAQ,EAAE,QAAQ,CAAC,SAAS,CAAC,QAAQ,EAAE,CAAC;YACnD;gBACE,MAAM,IAAI,KAAK;gBACb,gFAAgF;gBAChF,4EAA4E;gBAC5E,yDAAyD,kBAAkB,EAAE,CAC9E,CAAC;QACN,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;IACjD,CAAC;IAED,MAAM,eAAe,GAAG,CAAC,MAAM,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAW,CAAC;IAEtE,MAAM,QAAQ,GAAG,eAAe;QAC9B,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;QACrC,CAAC,CAAC,SAAS,CAAC;IAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;AACtB,CAAC","sourcesContent":["import {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type {\n FetchGasFeeEstimateOptions,\n GasFeeState,\n} from '@metamask/gas-fee-controller';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { getGasFeeFlow } from './gas-flow';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n GasFeeFlow,\n} from '../types';\nimport { GasFeeEstimateType, UserFeeLevel } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n gasFeeFlows: GasFeeFlow[];\n getGasFeeEstimates: (\n options: FetchGasFeeEstimateOptions,\n ) => Promise<GasFeeState>;\n getSavedGasFees: (chainId: Hex) => SavedGasFees | undefined;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n initialParams: TransactionParams;\n savedGasFees?: SavedGasFees;\n suggestedGasFees: SuggestedGasFees;\n};\n\ntype SuggestedGasFees = {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n gasPrice?: string;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\n/**\n * Update the gas fee properties of the provided transaction meta.\n *\n * @param request - The request object.\n */\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap\n ? undefined\n : request.getSavedGasFees(txMeta.chainId);\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest: GetGasFeeRequest = {\n ...request,\n initialParams,\n savedGasFees,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\n/**\n * Convert GWEI from decimal string to WEI as hex string.\n *\n * @param value - The GWEI value as a decimal string.\n * @returns The WEI value in hex.\n */\nexport function gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n\n/**\n * Converts a value from Gwei decimal representation to Wei decimal representation\n *\n * @param gweiDecimal - The value in Gwei as a string or number\n * @returns The value in Wei as a string\n *\n * @example\n * // Convert 1.5 Gwei to Wei\n * gweiDecimalToWeiDecimal(\"1.5\")\n * // Returns \"1500000000\"\n */\nexport function gweiDecimalToWeiDecimal(gweiDecimal: string | number): string {\n const weiValue = Number(gweiDecimal) * 1e9;\n\n return weiValue.toString().split('.')[0];\n}\n\n/**\n * Determine the maxFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxFeePerGas value.\n */\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee as string);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the maxPriorityFeePerGas value for the transaction.\n *\n * @param request - The request object.\n * @returns The maxPriorityFeePerGas value.\n */\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\n/**\n * Determine the gasPrice value for the transaction.\n *\n * @param request - The request object.\n * @returns The gasPrice value.\n */\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\n/**\n * Determine the user fee level.\n *\n * @param request - The request object.\n * @returns The user fee level.\n */\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { initialParams, savedGasFees, suggestedGasFees, txMeta } = request;\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.gasPrice\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\n/**\n * Update the default gas estimates for the provided transaction.\n *\n * @param txMeta - The transaction metadata.\n */\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\n/**\n * Retrieve the suggested gas fees using the gas fee flows.\n *\n * @param request - The request object.\n * @returns The suggested gas fees.\n */\nasync function getSuggestedGasFees(\n request: UpdateGasFeesRequest,\n): Promise<SuggestedGasFees> {\n const {\n eip1559,\n ethQuery,\n gasFeeFlows,\n getGasFeeEstimates,\n messenger,\n txMeta,\n } = request;\n\n const { networkClientId } = txMeta;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n const gasFeeFlow = getGasFeeFlow(\n txMeta,\n gasFeeFlows,\n messenger,\n ) as GasFeeFlow;\n\n try {\n const gasFeeControllerData = await getGasFeeEstimates({ networkClientId });\n\n const response = await gasFeeFlow.getGasFees({\n ethQuery,\n gasFeeControllerData,\n messenger,\n transactionMeta: txMeta,\n });\n\n const gasFeeEstimateType = response.estimates?.type;\n\n switch (gasFeeEstimateType) {\n case GasFeeEstimateType.FeeMarket:\n return response.estimates.medium;\n case GasFeeEstimateType.Legacy:\n return {\n gasPrice: response.estimates.medium,\n };\n case GasFeeEstimateType.GasPrice:\n return { gasPrice: response.estimates.gasPrice };\n default:\n throw new Error(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Unsupported gas fee estimate type returned from flow: ${gasFeeEstimateType}`,\n );\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? add0x(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"gas-flow.cjs","sourceRoot":"","sources":["../../src/utils/gas-flow.ts"],"names":[],"mappings":";;;AAAA,iEAA6D;AAe7D,wCAMkB;AAalB;;;;;;;GAOG;AACH,SAAgB,aAAa,CAC3B,eAAgC,EAChC,WAAyB,EACzB,SAAyC;IAEzC,OAAO,WAAW,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CACrC,U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AC,YAAY,CACvC;QACD,6BAA6B,EAAE,IAAA,kCAAe,EAC5C,yBAAyB,CAAC,oBAAoB,CAC/C;KACe,CAAC;AACrB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,iBAAiB,CACxB,yBAAgD,EAChD,KAA0B;IAE1B,OAAO,IAAA,kCAAe,EAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAC1B,yBAAkD;IAElD,OAAO,IAAA,kCAAe,EAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { weiHexToGweiDec } from '@metamask/controller-utils';\nimport type {\n Eip1559GasFee,\n EthGasPriceEstimate,\n GasFeeEstimates,\n LegacyGasPriceEstimate,\n} from '@metamask/gas-fee-controller';\nimport { type GasFeeState } from '@metamask/gas-fee-controller';\n\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n FeeMarketGasFeeEstimates,\n GasPriceGasFeeEstimates,\n LegacyGasFeeEstimates,\n} from '../types';\nimport {\n type GasFeeFlow,\n type TransactionMeta,\n type FeeMarketGasFeeEstimateForLevel,\n GasFeeEstimateLevel,\n GasFeeEstimateType,\n} from '../types';\n\ntype MergeGasFeeEstimatesRequest = {\n gasFeeControllerEstimates:\n | GasFeeEstimates\n | LegacyGasPriceEstimate\n | EthGasPriceEstimate;\n transactionGasFeeEstimates:\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n};\n\n/**\n * Returns the first gas fee flow that matches the transaction.\n *\n * @param transactionMeta - The transaction metadata to find a gas fee flow for.\n * @param gasFeeFlows - The gas fee flows to search.\n * @param messenger - The messenger instance.\n * @returns The first gas fee flow that matches the transaction, or undefined if none match.\n */\nexport function getGasFeeFlow(\n transactionMeta: TransactionMeta,\n gasFeeFlows: GasFeeFlow[],\n messenger: TransactionControllerMessenger,\n): GasFeeFlow | undefined {\n return gasFeeFlows.find((gasFeeFlow) =>\n gasFeeFlow.matchesTransaction({ transactionMeta, messenger }),\n );\n}\n\n/**\n * Merge the gas fee estimates from the gas fee controller with the gas fee estimates from a transaction.\n *\n * @param request - Data required to merge gas fee estimates.\n * @param request.gasFeeControllerEstimates - Gas fee estimates from the GasFeeController.\n * @param request.transactionGasFeeEstimates - Gas fee estimates from the transaction.\n * @returns The merged gas fee estimates.\n */\nexport function mergeGasFeeEstimates({\n gasFeeControllerEstimates,\n transactionGasFeeEstimates,\n}: MergeGasFeeEstimatesRequest): GasFeeState['gasFeeEstimates'] {\n const transactionEstimateType = transactionGasFeeEstimates.type;\n\n if (transactionEstimateType === GasFeeEstimateType.FeeMarket) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: mergeFeeMarketEstimate(\n (gasFeeControllerEstimates as GasFeeEstimates)?.[level],\n transactionGasFeeEstimates[level],\n ),\n }),\n { ...gasFeeControllerEstimates } as GasFeeEstimates,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.Legacy) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: getLegacyEstimate(transactionGasFeeEstimates, level),\n }),\n {} as LegacyGasPriceEstimate,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.GasPrice) {\n return {\n gasPrice: getGasPriceEstimate(transactionGasFeeEstimates),\n };\n }\n\n return gasFeeControllerEstimates;\n}\n\n/**\n * Merge a specific priority level of EIP-1559 gas fee estimates.\n *\n * @param gasFeeControllerEstimate - The gas fee estimate from the gas fee controller.\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The merged gas fee estimate.\n */\nfunction mergeFeeMarketEstimate(\n gasFeeControllerEstimate: Eip1559GasFee | undefined,\n transactionGasFeeEstimate: FeeMarketGasFeeEstimateForLevel,\n): Eip1559GasFee {\n return {\n ...gasFeeControllerEstimate,\n suggestedMaxFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxFeePerGas,\n ),\n suggestedMaxPriorityFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxPriorityFeePerGas,\n ),\n } as Eip1559GasFee;\n}\n\n/**\n * Generate a specific priority level for a legacy gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @param level - The gas fee estimate level.\n * @returns The legacy gas fee estimate.\n */\nfunction getLegacyEstimate(\n transactionGasFeeEstimate: LegacyGasFeeEstimates,\n level: GasFeeEstimateLevel,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate[level]);\n}\n\n/**\n * Generate the value for a gas price gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The legacy gas fee estimate.\n */\nfunction getGasPriceEstimate(\n transactionGasFeeEstimate: GasPriceGasFeeEstimates,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate.gasPrice);\n}\n"]}
1
+ {"version":3,"file":"gas-flow.cjs","sourceRoot":"","sources":["../../src/utils/gas-flow.ts"],"names":[],"mappings":";;;AAAA,iEAA6D;AAe7D,wCAMkB;AAalB;;;;;;;GAOG;AACH,SAAgB,aAAa,CAC3B,eAAgC,EAChC,WAAyB,EACzB,SAAyC;IAEzC,OAAO,WAAW,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CACrC,UAAU,CAAC,kBAAkB,CAAC,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC,CAC9D,CAAC;AACJ,CAAC;AARD,sCAQC;AAED;;;;;;;GAOG;AACH,SAAgB,oBAAoB,CAAC,EACnC,yBAAyB,EACzB,0BAA0B,GACE;IAC5B,MAAM,uBAAuB,GAAG,0BAA0B,CAAC,IAAI,CAAC;IAEhE,IAAI,uBAAuB,KAAK,0BAAkB,CAAC,SAAS,EAAE,CAAC;QAC7D,OAAO,MAAM,CAAC,MAAM,CAAC,2BAAmB,CAAC,CAAC,MAAM,CAC9C,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,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C,CAAC;AAC7D,CAAC","sourcesContent":["import { weiHexToGweiDec } from '@metamask/controller-utils';\nimport type {\n Eip1559GasFee,\n EthGasPriceEstimate,\n GasFeeEstimates,\n LegacyGasPriceEstimate,\n} from '@metamask/gas-fee-controller';\nimport { type GasFeeState } from '@metamask/gas-fee-controller';\n\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n FeeMarketGasFeeEstimates,\n GasPriceGasFeeEstimates,\n LegacyGasFeeEstimates,\n} from '../types';\nimport {\n type GasFeeFlow,\n type TransactionMeta,\n type FeeMarketGasFeeEstimateForLevel,\n GasFeeEstimateLevel,\n GasFeeEstimateType,\n} from '../types';\n\ntype MergeGasFeeEstimatesRequest = {\n gasFeeControllerEstimates:\n | GasFeeEstimates\n | LegacyGasPriceEstimate\n | EthGasPriceEstimate;\n transactionGasFeeEstimates:\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n};\n\n/**\n * Returns the first gas fee flow that matches the transaction.\n *\n * @param transactionMeta - The transaction metadata to find a gas fee flow for.\n * @param gasFeeFlows - The gas fee flows to search.\n * @param messenger - The messenger instance.\n * @returns The first gas fee flow that matches the transaction, or undefined if none match.\n */\nexport function getGasFeeFlow(\n transactionMeta: TransactionMeta,\n gasFeeFlows: GasFeeFlow[],\n messenger: TransactionControllerMessenger,\n): GasFeeFlow | undefined {\n return gasFeeFlows.find((gasFeeFlow) =>\n gasFeeFlow.matchesTransaction({ transactionMeta, messenger }),\n );\n}\n\n/**\n * Merge the gas fee estimates from the gas fee controller with the gas fee estimates from a transaction.\n *\n * @param request - Data required to merge gas fee estimates.\n * @param request.gasFeeControllerEstimates - Gas fee estimates from the GasFeeController.\n * @param request.transactionGasFeeEstimates - Gas fee estimates from the transaction.\n * @returns The merged gas fee estimates.\n */\nexport function mergeGasFeeEstimates({\n gasFeeControllerEstimates,\n transactionGasFeeEstimates,\n}: MergeGasFeeEstimatesRequest): GasFeeState['gasFeeEstimates'] {\n const transactionEstimateType = transactionGasFeeEstimates.type;\n\n if (transactionEstimateType === GasFeeEstimateType.FeeMarket) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: mergeFeeMarketEstimate(\n (gasFeeControllerEstimates as GasFeeEstimates)?.[level],\n transactionGasFeeEstimates[level],\n ),\n }),\n { ...gasFeeControllerEstimates } as GasFeeEstimates,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.Legacy) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: getLegacyEstimate(transactionGasFeeEstimates, level),\n }),\n {} as LegacyGasPriceEstimate,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.GasPrice) {\n return {\n gasPrice: getGasPriceEstimate(transactionGasFeeEstimates),\n };\n }\n\n return gasFeeControllerEstimates;\n}\n\n/**\n * Merge a specific priority level of EIP-1559 gas fee estimates.\n *\n * @param gasFeeControllerEstimate - The gas fee estimate from the gas fee controller.\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The merged gas fee estimate.\n */\nfunction mergeFeeMarketEstimate(\n gasFeeControllerEstimate: Eip1559GasFee | undefined,\n transactionGasFeeEstimate: FeeMarketGasFeeEstimateForLevel,\n): Eip1559GasFee {\n return {\n ...gasFeeControllerEstimate,\n suggestedMaxFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxFeePerGas,\n ),\n suggestedMaxPriorityFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxPriorityFeePerGas,\n ),\n } as Eip1559GasFee;\n}\n\n/**\n * Generate a specific priority level for a legacy gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @param level - The gas fee estimate level.\n * @returns The legacy gas fee estimate.\n */\nfunction getLegacyEstimate(\n transactionGasFeeEstimate: LegacyGasFeeEstimates,\n level: GasFeeEstimateLevel,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate[level]);\n}\n\n/**\n * Generate the value for a gas price gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The legacy gas fee estimate.\n */\nfunction getGasPriceEstimate(\n transactionGasFeeEstimate: GasPriceGasFeeEstimates,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate.gasPrice);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"gas-flow.mjs","sourceRoot":"","sources":["../../src/utils/gas-flow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,mCAAmC;AAe7D,OAAO,EAIL,mBAAmB,EACnB,kBAAkB,EACnB,qBAAiB;AAalB;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAC3B,eAAgC,EAChC,WAAyB,EACzB,SAAyC;IAEzC,OAAO,WAAW,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CACrC,UAAU,CAAC,kBAAkB,CAAC,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC,CAC9D,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,oBAAoB,CAAC,EACnC,yBAAyB,EACzB,0BAA0B,GACE;IAC5B,MAAM,uBAAuB,GAAG,0BAA0B,CAAC,IAAI,CAAC;IAEhE,IAAI,uBAAuB,KAAK,kBAAkB,CAAC,SAAS,EAAE;QAC5D,OAAO,MAAM,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,MAAM,CAC9C,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;YAClB,GAAG,MAAM;YACT,CAAC,KAAK,CAAC,EAAE,sBAAsB,CAC5B,yBAA6C,EAAE,CAAC,KAAK,CAAC,EACvD,0BAA0B,CAAC,KAAK,CAAC,CAClC;SACF,CAAC,EACF,EAAE,GAAG,yBAAyB,EAAqB,CACpD,CAAC;KACH;IAED,IAAI,uBAAuB,KAAK,kBAAkB,CAAC,MAAM,EAAE;QACzD,OAAO,MAAM,CAAC,MAAM,CAAC,mBAAmB,CAAC,CAAC,MAAM,CAC9C,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;YAClB,GAAG,MAAM;YACT,CAAC,KAAK,CAAC,EAAE,iBAAiB,CAAC,0BAA0B,EAAE,KAAK,CAAC;SAC9D,CAAC,EACF,EAA4B,CAC7B,CAAC;KACH;IAED,IAAI,uBAAuB,KAAK,kBAAkB,CAAC,QAAQ,EAAE;QAC3D,OAAO;YACL,QAAQ,EAAE,mBAAmB,CAAC,0BAA0B,CAAC;SAC1D,CAAC;KACH;IAED,OAAO,yBAAyB,CAAC;AACnC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,sBAAsB,CAC7B,wBAAmD,EACnD,yBAA0D;IAE1D,OAAO;QACL,GAAG,wBAAwB;QAC3B,qBAAqB,EAAE,eAAe,CACpC,yBAAyB,CAAC,YAAY,CACvC;QACD,6BAA6B,EAAE,eAAe,CAC5C,yBAAyB,CAAC,oBAAoB,CAC/C;KACe,CAAC;AACrB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,iBAAiB,CACxB,yBAAgD,EAChD,KAA0B;IAE1B,OAAO,eAAe,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAC1B,yBAAkD;IAElD,OAAO,eAAe,CAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { weiHexToGweiDec } from '@metamask/controller-utils';\nimport type {\n Eip1559GasFee,\n EthGasPriceEstimate,\n GasFeeEstimates,\n LegacyGasPriceEstimate,\n} from '@metamask/gas-fee-controller';\nimport { type GasFeeState } from '@metamask/gas-fee-controller';\n\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n FeeMarketGasFeeEstimates,\n GasPriceGasFeeEstimates,\n LegacyGasFeeEstimates,\n} from '../types';\nimport {\n type GasFeeFlow,\n type TransactionMeta,\n type FeeMarketGasFeeEstimateForLevel,\n GasFeeEstimateLevel,\n GasFeeEstimateType,\n} from '../types';\n\ntype MergeGasFeeEstimatesRequest = {\n gasFeeControllerEstimates:\n | GasFeeEstimates\n | LegacyGasPriceEstimate\n | EthGasPriceEstimate;\n transactionGasFeeEstimates:\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n};\n\n/**\n * Returns the first gas fee flow that matches the transaction.\n *\n * @param transactionMeta - The transaction metadata to find a gas fee flow for.\n * @param gasFeeFlows - The gas fee flows to search.\n * @param messenger - The messenger instance.\n * @returns The first gas fee flow that matches the transaction, or undefined if none match.\n */\nexport function getGasFeeFlow(\n transactionMeta: TransactionMeta,\n gasFeeFlows: GasFeeFlow[],\n messenger: TransactionControllerMessenger,\n): GasFeeFlow | undefined {\n return gasFeeFlows.find((gasFeeFlow) =>\n gasFeeFlow.matchesTransaction({ transactionMeta, messenger }),\n );\n}\n\n/**\n * Merge the gas fee estimates from the gas fee controller with the gas fee estimates from a transaction.\n *\n * @param request - Data required to merge gas fee estimates.\n * @param request.gasFeeControllerEstimates - Gas fee estimates from the GasFeeController.\n * @param request.transactionGasFeeEstimates - Gas fee estimates from the transaction.\n * @returns The merged gas fee estimates.\n */\nexport function mergeGasFeeEstimates({\n gasFeeControllerEstimates,\n transactionGasFeeEstimates,\n}: MergeGasFeeEstimatesRequest): GasFeeState['gasFeeEstimates'] {\n const transactionEstimateType = transactionGasFeeEstimates.type;\n\n if (transactionEstimateType === GasFeeEstimateType.FeeMarket) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: mergeFeeMarketEstimate(\n (gasFeeControllerEstimates as GasFeeEstimates)?.[level],\n transactionGasFeeEstimates[level],\n ),\n }),\n { ...gasFeeControllerEstimates } as GasFeeEstimates,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.Legacy) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: getLegacyEstimate(transactionGasFeeEstimates, level),\n }),\n {} as LegacyGasPriceEstimate,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.GasPrice) {\n return {\n gasPrice: getGasPriceEstimate(transactionGasFeeEstimates),\n };\n }\n\n return gasFeeControllerEstimates;\n}\n\n/**\n * Merge a specific priority level of EIP-1559 gas fee estimates.\n *\n * @param gasFeeControllerEstimate - The gas fee estimate from the gas fee controller.\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The merged gas fee estimate.\n */\nfunction mergeFeeMarketEstimate(\n gasFeeControllerEstimate: Eip1559GasFee | undefined,\n transactionGasFeeEstimate: FeeMarketGasFeeEstimateForLevel,\n): Eip1559GasFee {\n return {\n ...gasFeeControllerEstimate,\n suggestedMaxFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxFeePerGas,\n ),\n suggestedMaxPriorityFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxPriorityFeePerGas,\n ),\n } as Eip1559GasFee;\n}\n\n/**\n * Generate a specific priority level for a legacy gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @param level - The gas fee estimate level.\n * @returns The legacy gas fee estimate.\n */\nfunction getLegacyEstimate(\n transactionGasFeeEstimate: LegacyGasFeeEstimates,\n level: GasFeeEstimateLevel,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate[level]);\n}\n\n/**\n * Generate the value for a gas price gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The legacy gas fee estimate.\n */\nfunction getGasPriceEstimate(\n transactionGasFeeEstimate: GasPriceGasFeeEstimates,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate.gasPrice);\n}\n"]}
1
+ {"version":3,"file":"gas-flow.mjs","sourceRoot":"","sources":["../../src/utils/gas-flow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,mCAAmC;AAe7D,OAAO,EAIL,mBAAmB,EACnB,kBAAkB,EACnB,qB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yBAAyB,CAAC;AACnC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,sBAAsB,CAC7B,wBAAmD,EACnD,yBAA0D;IAE1D,OAAO;QACL,GAAG,wBAAwB;QAC3B,qBAAqB,EAAE,eAAe,CACpC,yBAAyB,CAAC,YAAY,CACvC;QACD,6BAA6B,EAAE,eAAe,CAC5C,yBAAyB,CAAC,oBAAoB,CAC/C;KACe,CAAC;AACrB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,iBAAiB,CACxB,yBAAgD,EAChD,KAA0B;IAE1B,OAAO,eAAe,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED;;;;;GAKG;AACH,SAAS,mBAAmB,CAC1B,yBAAkD;IAElD,OAAO,eAAe,CAAC,yBAAyB,CAAC,QAAQ,CAAC,CAAC;AAC7D,CAAC","sourcesContent":["import { weiHexToGweiDec } from '@metamask/controller-utils';\nimport type {\n Eip1559GasFee,\n EthGasPriceEstimate,\n GasFeeEstimates,\n LegacyGasPriceEstimate,\n} from '@metamask/gas-fee-controller';\nimport { type GasFeeState } from '@metamask/gas-fee-controller';\n\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n FeeMarketGasFeeEstimates,\n GasPriceGasFeeEstimates,\n LegacyGasFeeEstimates,\n} from '../types';\nimport {\n type GasFeeFlow,\n type TransactionMeta,\n type FeeMarketGasFeeEstimateForLevel,\n GasFeeEstimateLevel,\n GasFeeEstimateType,\n} from '../types';\n\ntype MergeGasFeeEstimatesRequest = {\n gasFeeControllerEstimates:\n | GasFeeEstimates\n | LegacyGasPriceEstimate\n | EthGasPriceEstimate;\n transactionGasFeeEstimates:\n | FeeMarketGasFeeEstimates\n | LegacyGasFeeEstimates\n | GasPriceGasFeeEstimates;\n};\n\n/**\n * Returns the first gas fee flow that matches the transaction.\n *\n * @param transactionMeta - The transaction metadata to find a gas fee flow for.\n * @param gasFeeFlows - The gas fee flows to search.\n * @param messenger - The messenger instance.\n * @returns The first gas fee flow that matches the transaction, or undefined if none match.\n */\nexport function getGasFeeFlow(\n transactionMeta: TransactionMeta,\n gasFeeFlows: GasFeeFlow[],\n messenger: TransactionControllerMessenger,\n): GasFeeFlow | undefined {\n return gasFeeFlows.find((gasFeeFlow) =>\n gasFeeFlow.matchesTransaction({ transactionMeta, messenger }),\n );\n}\n\n/**\n * Merge the gas fee estimates from the gas fee controller with the gas fee estimates from a transaction.\n *\n * @param request - Data required to merge gas fee estimates.\n * @param request.gasFeeControllerEstimates - Gas fee estimates from the GasFeeController.\n * @param request.transactionGasFeeEstimates - Gas fee estimates from the transaction.\n * @returns The merged gas fee estimates.\n */\nexport function mergeGasFeeEstimates({\n gasFeeControllerEstimates,\n transactionGasFeeEstimates,\n}: MergeGasFeeEstimatesRequest): GasFeeState['gasFeeEstimates'] {\n const transactionEstimateType = transactionGasFeeEstimates.type;\n\n if (transactionEstimateType === GasFeeEstimateType.FeeMarket) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: mergeFeeMarketEstimate(\n (gasFeeControllerEstimates as GasFeeEstimates)?.[level],\n transactionGasFeeEstimates[level],\n ),\n }),\n { ...gasFeeControllerEstimates } as GasFeeEstimates,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.Legacy) {\n return Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: getLegacyEstimate(transactionGasFeeEstimates, level),\n }),\n {} as LegacyGasPriceEstimate,\n );\n }\n\n if (transactionEstimateType === GasFeeEstimateType.GasPrice) {\n return {\n gasPrice: getGasPriceEstimate(transactionGasFeeEstimates),\n };\n }\n\n return gasFeeControllerEstimates;\n}\n\n/**\n * Merge a specific priority level of EIP-1559 gas fee estimates.\n *\n * @param gasFeeControllerEstimate - The gas fee estimate from the gas fee controller.\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The merged gas fee estimate.\n */\nfunction mergeFeeMarketEstimate(\n gasFeeControllerEstimate: Eip1559GasFee | undefined,\n transactionGasFeeEstimate: FeeMarketGasFeeEstimateForLevel,\n): Eip1559GasFee {\n return {\n ...gasFeeControllerEstimate,\n suggestedMaxFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxFeePerGas,\n ),\n suggestedMaxPriorityFeePerGas: weiHexToGweiDec(\n transactionGasFeeEstimate.maxPriorityFeePerGas,\n ),\n } as Eip1559GasFee;\n}\n\n/**\n * Generate a specific priority level for a legacy gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @param level - The gas fee estimate level.\n * @returns The legacy gas fee estimate.\n */\nfunction getLegacyEstimate(\n transactionGasFeeEstimate: LegacyGasFeeEstimates,\n level: GasFeeEstimateLevel,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate[level]);\n}\n\n/**\n * Generate the value for a gas price gas fee estimate.\n *\n * @param transactionGasFeeEstimate - The gas fee estimate from the transaction.\n * @returns The legacy gas fee estimate.\n */\nfunction getGasPriceEstimate(\n transactionGasFeeEstimate: GasPriceGasFeeEstimates,\n): string {\n return weiHexToGweiDec(transactionGasFeeEstimate.gasPrice);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"gas.cjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";;;AAAA,iEAMoC;AAGpC,2CAAsE;AACtE,iCAA2B;AAE3B,2CAA8C;AAC9C,uDAA+E;AAC/E,8DAA6D;AAC7D,0CAA0C;AAM1C,wCAIkB;AAYL,QAAA,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,KAAK,CAAC,CAAC;AAE/C,QAAA,SAAS,GAAG,QAAQ,CAAC;AACrB,QAAA,sBAAsB,GAAG,GAAG,CAAC;AAC7B,QAAA,qBAAqB,GAAG,EAAE,CAAC;AAC3B,QAAA,aAAa,GAAG,KAAK,CAAC;AAEtB,QAAA,6BAA6B,GACxC,oEAAoE,CAAC;AAEvE;;;;GAIG;AACI,KAAK,UAAU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,aAAa;QAChB,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,OAAO;QACzC,KAAK,EAAE,aAAa,CAAC,KAAK,IAAI,KAAK;QACnC,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,qCAA6B;QACnD,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,qCAA6B;QACnD,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,KAAK;KACxC,CAAC,CAAC,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,eAAe,CACtB,QAAkB,EAClB,QAA2B,EAC3B,iBAAuB;IAEvB,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAC;IAC1B,MAAM,MAAM,GAAG,CAAC,QAAQ,CAAW,CAAC;IAEpC,IAAI,iBAAiB,EAAE;QACrB,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAEtB,MAAM,CAAC,IAAI,CAAC;YACV,CAAC,IAAc,CAAC,EAAE;gBAChB,IAAI,EAAE,2BAAiB,GAAG,IAAA,gBAAQ,EAAC,iBAAiB,CAAC;aACtD;SACF,CAAC,CAAC;KACJ;IAED,OAAO,IAAA,wBAAK,EAAC,QAAQ,EAAE,aAAa,EAAE,MAAM,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import {\n BNToHex,\n fractionBN,\n hexToBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { Hex, Json } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\nimport { BN } from 'bn.js';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n GetSimulationConfig,\n TransactionBatchSingleRequest,\n} from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionMeta,\n type TransactionParams,\n} from '../types';\n\nexport type UpdateGasRequest = {\n chainId: Hex;\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport const log = createModuleLogger(projectLogger, 'gas');\n\nexport const FIXED_GAS = '0x5208';\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\nexport const MAX_GAS_BLOCK_PERCENT = 90;\nexport const INTRINSIC_GAS = 21000;\n\nexport const DUMMY_AUTHORIZATION_SIGNATURE =\n '0x1111111111111111111111111111111111111111111111111111111111111111';\n\n/**\n * Populate the gas properties of the provided transaction meta.\n *\n * @param request - The request object including the necessary parameters.\n */\nexport async function updateGas(request: UpdateGasRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const [gas, simulationFails, gasLimitNoBuffer] = await getGas(request);\n\n txMeta.txParams.gas = gas;\n txMeta.simulationFails = simulationFails;\n txMeta.gasLimitNoBuffer = gasLimitNoBuffer;\n\n if (!initialParams.gas) {\n txMeta.originalGasEstimate = txMeta.txParams.gas;\n }\n\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;\n}\n\n/**\n * Estimate the gas for the provided transaction parameters.\n * If the gas estimate fails, the fallback value is returned.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.ethQuery - The EthQuery instance to interact with the network.\n * @param options.ignoreDelegationSignatures - Ignore signature errors if submitting delegations to the DelegationManager.\n * @param options.isSimulationEnabled - Whether the simulation is enabled.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.messenger - The messenger instance for communication.\n * @param options.txParams - The transaction parameters.\n * @returns The estimated gas and related info.\n */\nexport async function estimateGas({\n chainId,\n ethQuery,\n ignoreDelegationSignatures,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txParams,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n ignoreDelegationSignatures?: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txParams: TransactionParams;\n}) {\n const request = { ...txParams };\n const { authorizationList, data, from, value, to } = request;\n\n if (ignoreDelegationSignatures && !isSimulationEnabled) {\n throw new Error(\n 'Gas estimation with ignored delegation signatures is not supported as simulation disabled',\n );\n }\n\n const { gasLimit: blockGasLimit, number: blockNumber } =\n await getLatestBlock(ethQuery);\n\n const blockGasLimitBN = hexToBN(blockGasLimit);\n const { percentage, fixed } = getGasEstimateFallback(chainId, messenger);\n\n const fallback = fixed\n ? toHex(fixed)\n : BNToHex(fractionBN(blockGasLimitBN, percentage, 100));\n\n log('Estimation fallback values', fallback);\n\n request.data = data ? add0x(data) : data;\n request.value = value || '0x0';\n\n request.authorizationList = normalizeAuthorizationList(\n request.authorizationList,\n chainId,\n );\n\n delete request.gasPrice;\n delete request.maxFeePerGas;\n delete request.maxPriorityFeePerGas;\n\n let estimatedGas = fallback;\n let simulationFails: TransactionMeta['simulationFails'];\n\n const isUpgradeWithDataToSelf =\n txParams.type === TransactionEnvelopeType.setCode &&\n Boolean(authorizationList?.length) &&\n Boolean(data) &&\n data !== '0x' &&\n from?.toLowerCase() === to?.toLowerCase();\n\n try {\n if (isSimulationEnabled && isUpgradeWithDataToSelf) {\n estimatedGas = await estimateGasUpgradeWithDataToSelf(\n request,\n ethQuery,\n chainId,\n getSimulationConfig,\n );\n } else if (ignoreDelegationSignatures && isSimulationEnabled) {\n estimatedGas = await simulateGas({\n chainId,\n getSimulationConfig,\n transaction: request,\n });\n } else {\n estimatedGas = await estimateGasNode(ethQuery, request);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n simulationFails = {\n reason: error.message,\n errorKey: error.errorKey,\n debug: {\n blockNumber,\n blockGasLimit,\n },\n };\n\n log('Estimation failed', { ...simulationFails, fallback });\n }\n\n return {\n blockGasLimit,\n estimatedGas,\n isUpgradeWithDataToSelf,\n simulationFails,\n };\n}\n\n/**\n * Add a buffer to the provided estimated gas.\n * The buffer is calculated based on the block gas limit and a multiplier.\n *\n * @param estimatedGas - The estimated gas.\n * @param blockGasLimit - The block gas limit.\n * @param multiplier - The multiplier to apply to the estimated gas.\n * @returns The gas with the buffer applied.\n */\nexport function addGasBuffer(\n estimatedGas: string,\n blockGasLimit: string,\n multiplier: number,\n) {\n const estimatedGasBN = hexToBN(estimatedGas);\n\n const maxGasBN = fractionBN(\n hexToBN(blockGasLimit),\n MAX_GAS_BLOCK_PERCENT,\n 100,\n );\n\n const paddedGasBN = fractionBN(estimatedGasBN, multiplier * 100, 100);\n\n if (estimatedGasBN.gt(maxGasBN)) {\n const estimatedGasHex = add0x(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return estimatedGasHex;\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = add0x(BNToHex(paddedGasBN));\n log('Using padded estimate', paddedHex, multiplier);\n return paddedHex;\n }\n\n const maxHex = add0x(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return maxHex;\n}\n\n/**\n * Simulate the required gas for a batch of transactions using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transactions.\n * @param options.from - The address of the sender.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transactions - The array of transactions within a batch request.\n * @returns An object containing the transactions with their gas limits and the total gas limit.\n */\nexport async function simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions,\n}: {\n chainId: Hex;\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n transactions: TransactionBatchSingleRequest[];\n}): Promise<{ gasLimit: Hex }> {\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n ...transaction.params,\n from,\n })),\n });\n\n if (\n !response?.transactions ||\n response.transactions.length !== transactions.length\n ) {\n throw new Error('Simulation response does not match transaction count');\n }\n\n const totalGasLimit = response.transactions.reduce((acc, transaction) => {\n const gasLimit = transaction?.gasLimit;\n\n if (!gasLimit) {\n throw new Error(\n 'No simulated gas returned for one of the transactions',\n );\n }\n\n return acc.add(hexToBN(gasLimit));\n }, new BN(0));\n\n return {\n gasLimit: BNToHex(totalGasLimit), // Return the total gas limit as a hex string\n };\n } catch (error: unknown) {\n log('Error while simulating gas batch', error);\n throw new Error(\n 'Cannot estimate transaction batch total gas as simulation failed',\n );\n }\n}\n\n/**\n * Determine the gas for the provided request.\n *\n * @param request - The request object including the necessary parameters.\n * @returns The final gas value and the estimate used.\n */\nasync function getGas(\n request: UpdateGasRequest,\n): Promise<[string, TransactionMeta['simulationFails']?, string?]> {\n const {\n chainId,\n isCustomNetwork,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txMeta,\n } = request;\n const { disableGasBuffer } = txMeta;\n\n if (txMeta.txParams.gas) {\n log('Using value from request', txMeta.txParams.gas);\n return [txMeta.txParams.gas, undefined, txMeta.txParams.gas];\n }\n\n if (await requiresFixedGas(request)) {\n log('Using fixed value', FIXED_GAS);\n return [FIXED_GAS, undefined, FIXED_GAS];\n }\n\n const {\n blockGasLimit,\n estimatedGas,\n isUpgradeWithDataToSelf,\n simulationFails,\n } = await estimateGas({\n chainId,\n ethQuery: request.ethQuery,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txParams: txMeta.txParams,\n });\n\n log('Original estimated gas', estimatedGas);\n\n if (simulationFails) {\n log('Using original fallback estimate as simulation failed');\n }\n\n if (disableGasBuffer) {\n log('Gas buffer disabled');\n }\n\n if (simulationFails || disableGasBuffer) {\n return [estimatedGas, simulationFails, estimatedGas];\n }\n\n const bufferMultiplier = getGasEstimateBuffer({\n chainId,\n isCustomRPC: isCustomNetwork,\n isUpgradeWithDataToSelf,\n messenger,\n });\n\n log('Buffer', bufferMultiplier);\n\n const bufferedGas = addGasBuffer(\n estimatedGas,\n blockGasLimit,\n bufferMultiplier,\n );\n\n log('Buffered gas', bufferedGas);\n\n return [bufferedGas, simulationFails, estimatedGas];\n}\n\n/**\n * Determine if the gas for the provided request should be fixed.\n *\n * @param options - The options object.\n * @param options.ethQuery - The EthQuery instance to interact with the network.\n * @param options.txMeta - The transaction meta object.\n * @param options.isCustomNetwork - Whether the network is a custom network.\n * @returns Whether the gas should be fixed.\n */\nasync function requiresFixedGas({\n ethQuery,\n txMeta,\n isCustomNetwork,\n}: UpdateGasRequest): Promise<boolean> {\n const {\n txParams: { to, data, type },\n } = txMeta;\n\n if (\n isCustomNetwork ||\n !to ||\n data ||\n type === TransactionEnvelopeType.setCode\n ) {\n return false;\n }\n\n const code = await getCode(ethQuery, to);\n\n return !code || code === '0x';\n}\n\n/**\n * Get the contract code for the provided address.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param address - The address to get the code for.\n * @returns The contract code.\n */\nasync function getCode(\n ethQuery: EthQuery,\n address: string,\n): Promise<string | undefined> {\n return await query(ethQuery, 'getCode', [address]);\n}\n\n/**\n * Get the latest block from the network.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @returns The latest block number.\n */\nasync function getLatestBlock(\n ethQuery: EthQuery,\n): Promise<{ gasLimit: string; number: string }> {\n return await query(ethQuery, 'getBlockByNumber', ['latest', false]);\n}\n\n/**\n * Estimate the gas for a type 4 transaction.\n *\n * @param txParams - The transaction parameters.\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param chainId - The chain ID of the transaction.\n * @param getSimulationConfig - The function to get the simulation configuration.\n * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n chainId: Hex,\n getSimulationConfig: GetSimulationConfig,\n) {\n const upgradeGas = await query(ethQuery, 'estimateGas', [\n {\n ...txParams,\n data: '0x',\n },\n ]);\n\n log('Upgrade only gas', upgradeGas);\n\n const delegationAddress = txParams.authorizationList?.[0].address as Hex;\n\n let executeGas: Hex | undefined;\n\n try {\n executeGas = await simulateGas({\n chainId: chainId as Hex,\n delegationAddress,\n getSimulationConfig,\n transaction: txParams,\n });\n } catch (error: unknown) {\n log('Error while simulating data portion of upgrade', error);\n }\n\n if (executeGas === undefined) {\n try {\n executeGas = await estimateGasNode(\n ethQuery,\n { ...txParams, authorizationList: undefined, type: undefined },\n delegationAddress,\n );\n } catch (error: unknown) {\n log('Error while estimating data portion of upgrade', error);\n throw error;\n }\n\n log('Success estimating data portion of upgrade', executeGas);\n }\n\n log('Execute gas', executeGas);\n\n const total = BNToHex(\n hexToBN(upgradeGas)\n .add(hexToBN(executeGas as Hex))\n .subn(INTRINSIC_GAS),\n );\n\n log('Total type 4 gas', total);\n\n return total;\n}\n\n/**\n * Simulate the required gas using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.delegationAddress - The delegation address of the sender to mock.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n getSimulationConfig: GetSimulationConfig;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from as string]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: TransactionParams['authorizationList'],\n chainId: Hex,\n) {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n\n/**\n * Estimate the gas for a transaction using the `eth_estimateGas` method.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param txParams - The transaction parameters.\n * @param delegationAddress - The delegation address of the sender to mock.\n * @returns The estimated gas as a hex string.\n */\nfunction estimateGasNode(\n ethQuery: EthQuery,\n txParams: TransactionParams,\n delegationAddress?: Hex,\n) {\n const { from } = txParams;\n const params = [txParams] as Json[];\n\n if (delegationAddress) {\n params.push('latest');\n\n params.push({\n [from as string]: {\n code: DELEGATION_PREFIX + remove0x(delegationAddress),\n },\n });\n }\n\n return query(ethQuery, 'estimateGas', params);\n}\n"]}
1
+ {"version":3,"file":"gas.cjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";;;AAAA,iEAMoC;AAGpC,2CAAsE;AACtE,iCAA2B;AAE3B,2CAA8C;AAC9C,uDAA+E;AAC/E,8DAA6D;AAC7D,0CAA0C;AAM1C,wCAIkB;AAYL,QAAA,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,KAAK,CAAC,CAAC;AAE/C,QAAA,SAAS,GAAG,QAAQ,CAAC;AACrB,QAAA,sBAAsB,GAAG,GAAG,CAAC;AAC7B,QAAA,qBAAqB,GAAG,EAAE,CAAC;AAC3B,QAAA,aAAa,GAAG,KAAK,CAAC;AAEtB,QAAA,6BAA6B,GACxC,oEAAoE,CAAC;AAEvE;;;;GAIG;AACI,KAAK,UAAU,SAAS,CAAC,OAAyB;IACvD,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAC3B,MAAM,aAAa,GAAG,EAAE,GAAG,MAAM,CAAC,QAAQ,EAAE,CAAC;IAE7C,MAAM,CAAC,GAAG,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AC;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,iBAAyD,EACzD,OAAY;IAEZ,OAAO,iBAAiB,EAAE,GAAG,CAAC,CAAC,aAAa,EAAE,EAAE,CAAC,CAAC;QAChD,GAAG,aAAa;QAChB,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,OAAO;QACzC,KAAK,EAAE,aAAa,CAAC,KAAK,IAAI,KAAK;QACnC,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,qCAA6B;QACnD,CAAC,EAAE,aAAa,CAAC,CAAC,IAAI,qCAA6B;QACnD,OAAO,EAAE,aAAa,CAAC,OAAO,IAAI,KAAK;KACxC,CAAC,CAAC,CAAC;AACN,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,eAAe,CACtB,QAAkB,EAClB,QAA2B,EAC3B,iBAAuB;IAEvB,MAAM,EAAE,IAAI,EAAE,GAAG,QAAQ,CAAC;IAC1B,MAAM,MAAM,GAAG,CAAC,QAAQ,CAAW,CAAC;IAEpC,IAAI,iBAAiB,EAAE,CAAC;QACtB,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAEtB,MAAM,CAAC,IAAI,CAAC;YACV,CAAC,IAAc,CAAC,EAAE;gBAChB,IAAI,EAAE,2BAAiB,GAAG,IAAA,gBAAQ,EAAC,iBAAiB,CAAC;aACtD;SACF,CAAC,CAAC;IACL,CAAC;IAED,OAAO,IAAA,wBAAK,EAAC,QAAQ,EAAE,aAAa,EAAE,MAAM,CAAC,CAAC;AAChD,CAAC","sourcesContent":["import {\n BNToHex,\n fractionBN,\n hexToBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { Hex, Json } from '@metamask/utils';\nimport { add0x, createModuleLogger, remove0x } from '@metamask/utils';\nimport { BN } from 'bn.js';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n GetSimulationConfig,\n TransactionBatchSingleRequest,\n} from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionMeta,\n type TransactionParams,\n} from '../types';\n\nexport type UpdateGasRequest = {\n chainId: Hex;\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txMeta: TransactionMeta;\n};\n\nexport const log = createModuleLogger(projectLogger, 'gas');\n\nexport const FIXED_GAS = '0x5208';\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\nexport const MAX_GAS_BLOCK_PERCENT = 90;\nexport const INTRINSIC_GAS = 21000;\n\nexport const DUMMY_AUTHORIZATION_SIGNATURE =\n '0x1111111111111111111111111111111111111111111111111111111111111111';\n\n/**\n * Populate the gas properties of the provided transaction meta.\n *\n * @param request - The request object including the necessary parameters.\n */\nexport async function updateGas(request: UpdateGasRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const [gas, simulationFails, gasLimitNoBuffer] = await getGas(request);\n\n txMeta.txParams.gas = gas;\n txMeta.simulationFails = simulationFails;\n txMeta.gasLimitNoBuffer = gasLimitNoBuffer;\n\n if (!initialParams.gas) {\n txMeta.originalGasEstimate = txMeta.txParams.gas;\n }\n\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;\n}\n\n/**\n * Estimate the gas for the provided transaction parameters.\n * If the gas estimate fails, the fallback value is returned.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.ethQuery - The EthQuery instance to interact with the network.\n * @param options.ignoreDelegationSignatures - Ignore signature errors if submitting delegations to the DelegationManager.\n * @param options.isSimulationEnabled - Whether the simulation is enabled.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.messenger - The messenger instance for communication.\n * @param options.txParams - The transaction parameters.\n * @returns The estimated gas and related info.\n */\nexport async function estimateGas({\n chainId,\n ethQuery,\n ignoreDelegationSignatures,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txParams,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n ignoreDelegationSignatures?: boolean;\n isSimulationEnabled: boolean;\n getSimulationConfig: GetSimulationConfig;\n messenger: TransactionControllerMessenger;\n txParams: TransactionParams;\n}) {\n const request = { ...txParams };\n const { authorizationList, data, from, value, to } = request;\n\n if (ignoreDelegationSignatures && !isSimulationEnabled) {\n throw new Error(\n 'Gas estimation with ignored delegation signatures is not supported as simulation disabled',\n );\n }\n\n const { gasLimit: blockGasLimit, number: blockNumber } =\n await getLatestBlock(ethQuery);\n\n const blockGasLimitBN = hexToBN(blockGasLimit);\n const { percentage, fixed } = getGasEstimateFallback(chainId, messenger);\n\n const fallback = fixed\n ? toHex(fixed)\n : BNToHex(fractionBN(blockGasLimitBN, percentage, 100));\n\n log('Estimation fallback values', fallback);\n\n request.data = data ? add0x(data) : data;\n request.value = value || '0x0';\n\n request.authorizationList = normalizeAuthorizationList(\n request.authorizationList,\n chainId,\n );\n\n delete request.gasPrice;\n delete request.maxFeePerGas;\n delete request.maxPriorityFeePerGas;\n\n let estimatedGas = fallback;\n let simulationFails: TransactionMeta['simulationFails'];\n\n const isUpgradeWithDataToSelf =\n txParams.type === TransactionEnvelopeType.setCode &&\n Boolean(authorizationList?.length) &&\n Boolean(data) &&\n data !== '0x' &&\n from?.toLowerCase() === to?.toLowerCase();\n\n try {\n if (isSimulationEnabled && isUpgradeWithDataToSelf) {\n estimatedGas = await estimateGasUpgradeWithDataToSelf(\n request,\n ethQuery,\n chainId,\n getSimulationConfig,\n );\n } else if (ignoreDelegationSignatures && isSimulationEnabled) {\n estimatedGas = await simulateGas({\n chainId,\n getSimulationConfig,\n transaction: request,\n });\n } else {\n estimatedGas = await estimateGasNode(ethQuery, request);\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n simulationFails = {\n reason: error.message,\n errorKey: error.errorKey,\n debug: {\n blockNumber,\n blockGasLimit,\n },\n };\n\n log('Estimation failed', { ...simulationFails, fallback });\n }\n\n return {\n blockGasLimit,\n estimatedGas,\n isUpgradeWithDataToSelf,\n simulationFails,\n };\n}\n\n/**\n * Add a buffer to the provided estimated gas.\n * The buffer is calculated based on the block gas limit and a multiplier.\n *\n * @param estimatedGas - The estimated gas.\n * @param blockGasLimit - The block gas limit.\n * @param multiplier - The multiplier to apply to the estimated gas.\n * @returns The gas with the buffer applied.\n */\nexport function addGasBuffer(\n estimatedGas: string,\n blockGasLimit: string,\n multiplier: number,\n) {\n const estimatedGasBN = hexToBN(estimatedGas);\n\n const maxGasBN = fractionBN(\n hexToBN(blockGasLimit),\n MAX_GAS_BLOCK_PERCENT,\n 100,\n );\n\n const paddedGasBN = fractionBN(estimatedGasBN, multiplier * 100, 100);\n\n if (estimatedGasBN.gt(maxGasBN)) {\n const estimatedGasHex = add0x(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return estimatedGasHex;\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = add0x(BNToHex(paddedGasBN));\n log('Using padded estimate', paddedHex, multiplier);\n return paddedHex;\n }\n\n const maxHex = add0x(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return maxHex;\n}\n\n/**\n * Simulate the required gas for a batch of transactions using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transactions.\n * @param options.from - The address of the sender.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transactions - The array of transactions within a batch request.\n * @returns An object containing the transactions with their gas limits and the total gas limit.\n */\nexport async function simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions,\n}: {\n chainId: Hex;\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n transactions: TransactionBatchSingleRequest[];\n}): Promise<{ gasLimit: Hex }> {\n try {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n ...transaction.params,\n from,\n })),\n });\n\n if (\n !response?.transactions ||\n response.transactions.length !== transactions.length\n ) {\n throw new Error('Simulation response does not match transaction count');\n }\n\n const totalGasLimit = response.transactions.reduce((acc, transaction) => {\n const gasLimit = transaction?.gasLimit;\n\n if (!gasLimit) {\n throw new Error(\n 'No simulated gas returned for one of the transactions',\n );\n }\n\n return acc.add(hexToBN(gasLimit));\n }, new BN(0));\n\n return {\n gasLimit: BNToHex(totalGasLimit), // Return the total gas limit as a hex string\n };\n } catch (error: unknown) {\n log('Error while simulating gas batch', error);\n throw new Error(\n 'Cannot estimate transaction batch total gas as simulation failed',\n );\n }\n}\n\n/**\n * Determine the gas for the provided request.\n *\n * @param request - The request object including the necessary parameters.\n * @returns The final gas value and the estimate used.\n */\nasync function getGas(\n request: UpdateGasRequest,\n): Promise<[string, TransactionMeta['simulationFails']?, string?]> {\n const {\n chainId,\n isCustomNetwork,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txMeta,\n } = request;\n const { disableGasBuffer } = txMeta;\n\n if (txMeta.txParams.gas) {\n log('Using value from request', txMeta.txParams.gas);\n return [txMeta.txParams.gas, undefined, txMeta.txParams.gas];\n }\n\n if (await requiresFixedGas(request)) {\n log('Using fixed value', FIXED_GAS);\n return [FIXED_GAS, undefined, FIXED_GAS];\n }\n\n const {\n blockGasLimit,\n estimatedGas,\n isUpgradeWithDataToSelf,\n simulationFails,\n } = await estimateGas({\n chainId,\n ethQuery: request.ethQuery,\n isSimulationEnabled,\n getSimulationConfig,\n messenger,\n txParams: txMeta.txParams,\n });\n\n log('Original estimated gas', estimatedGas);\n\n if (simulationFails) {\n log('Using original fallback estimate as simulation failed');\n }\n\n if (disableGasBuffer) {\n log('Gas buffer disabled');\n }\n\n if (simulationFails || disableGasBuffer) {\n return [estimatedGas, simulationFails, estimatedGas];\n }\n\n const bufferMultiplier = getGasEstimateBuffer({\n chainId,\n isCustomRPC: isCustomNetwork,\n isUpgradeWithDataToSelf,\n messenger,\n });\n\n log('Buffer', bufferMultiplier);\n\n const bufferedGas = addGasBuffer(\n estimatedGas,\n blockGasLimit,\n bufferMultiplier,\n );\n\n log('Buffered gas', bufferedGas);\n\n return [bufferedGas, simulationFails, estimatedGas];\n}\n\n/**\n * Determine if the gas for the provided request should be fixed.\n *\n * @param options - The options object.\n * @param options.ethQuery - The EthQuery instance to interact with the network.\n * @param options.txMeta - The transaction meta object.\n * @param options.isCustomNetwork - Whether the network is a custom network.\n * @returns Whether the gas should be fixed.\n */\nasync function requiresFixedGas({\n ethQuery,\n txMeta,\n isCustomNetwork,\n}: UpdateGasRequest): Promise<boolean> {\n const {\n txParams: { to, data, type },\n } = txMeta;\n\n if (\n isCustomNetwork ||\n !to ||\n data ||\n type === TransactionEnvelopeType.setCode\n ) {\n return false;\n }\n\n const code = await getCode(ethQuery, to);\n\n return !code || code === '0x';\n}\n\n/**\n * Get the contract code for the provided address.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param address - The address to get the code for.\n * @returns The contract code.\n */\nasync function getCode(\n ethQuery: EthQuery,\n address: string,\n): Promise<string | undefined> {\n return await query(ethQuery, 'getCode', [address]);\n}\n\n/**\n * Get the latest block from the network.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @returns The latest block number.\n */\nasync function getLatestBlock(\n ethQuery: EthQuery,\n): Promise<{ gasLimit: string; number: string }> {\n return await query(ethQuery, 'getBlockByNumber', ['latest', false]);\n}\n\n/**\n * Estimate the gas for a type 4 transaction.\n *\n * @param txParams - The transaction parameters.\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param chainId - The chain ID of the transaction.\n * @param getSimulationConfig - The function to get the simulation configuration.\n * @returns The estimated gas.\n */\nasync function estimateGasUpgradeWithDataToSelf(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n chainId: Hex,\n getSimulationConfig: GetSimulationConfig,\n) {\n const upgradeGas = await query(ethQuery, 'estimateGas', [\n {\n ...txParams,\n data: '0x',\n },\n ]);\n\n log('Upgrade only gas', upgradeGas);\n\n const delegationAddress = txParams.authorizationList?.[0].address as Hex;\n\n let executeGas: Hex | undefined;\n\n try {\n executeGas = await simulateGas({\n chainId: chainId as Hex,\n delegationAddress,\n getSimulationConfig,\n transaction: txParams,\n });\n } catch (error: unknown) {\n log('Error while simulating data portion of upgrade', error);\n }\n\n if (executeGas === undefined) {\n try {\n executeGas = await estimateGasNode(\n ethQuery,\n { ...txParams, authorizationList: undefined, type: undefined },\n delegationAddress,\n );\n } catch (error: unknown) {\n log('Error while estimating data portion of upgrade', error);\n throw error;\n }\n\n log('Success estimating data portion of upgrade', executeGas);\n }\n\n log('Execute gas', executeGas);\n\n const total = BNToHex(\n hexToBN(upgradeGas)\n .add(hexToBN(executeGas as Hex))\n .subn(INTRINSIC_GAS),\n );\n\n log('Total type 4 gas', total);\n\n return total;\n}\n\n/**\n * Simulate the required gas using the simulation API.\n *\n * @param options - The options object.\n * @param options.chainId - The chain ID of the transaction.\n * @param options.delegationAddress - The delegation address of the sender to mock.\n * @param options.getSimulationConfig - The function to get the simulation configuration.\n * @param options.transaction - The transaction parameters.\n * @returns The simulated gas.\n */\nasync function simulateGas({\n chainId,\n delegationAddress,\n getSimulationConfig,\n transaction,\n}: {\n chainId: Hex;\n delegationAddress?: Hex;\n getSimulationConfig: GetSimulationConfig;\n transaction: TransactionParams;\n}): Promise<Hex> {\n const response = await simulateTransactions(chainId, {\n getSimulationConfig,\n transactions: [\n {\n to: transaction.to as Hex,\n from: transaction.from as Hex,\n data: transaction.data as Hex,\n value: transaction.value as Hex,\n },\n ],\n overrides: {\n [transaction.from as string]: {\n code:\n delegationAddress &&\n ((DELEGATION_PREFIX + remove0x(delegationAddress)) as Hex),\n },\n },\n });\n\n const gasLimit = response?.transactions?.[0].gasLimit;\n\n if (!gasLimit) {\n throw new Error('No simulated gas returned');\n }\n\n return gasLimit;\n}\n\n/**\n * Populate the authorization list with dummy values.\n *\n * @param authorizationList - The authorization list to prepare.\n * @param chainId - The chain ID to use.\n * @returns The authorization list with dummy values.\n */\nfunction normalizeAuthorizationList(\n authorizationList: TransactionParams['authorizationList'],\n chainId: Hex,\n) {\n return authorizationList?.map((authorization) => ({\n ...authorization,\n chainId: authorization.chainId ?? chainId,\n nonce: authorization.nonce ?? '0x1',\n r: authorization.r ?? DUMMY_AUTHORIZATION_SIGNATURE,\n s: authorization.s ?? DUMMY_AUTHORIZATION_SIGNATURE,\n yParity: authorization.yParity ?? '0x1',\n }));\n}\n\n/**\n * Estimate the gas for a transaction using the `eth_estimateGas` method.\n *\n * @param ethQuery - The EthQuery instance to interact with the network.\n * @param txParams - The transaction parameters.\n * @param delegationAddress - The delegation address of the sender to mock.\n * @returns The estimated gas as a hex string.\n */\nfunction estimateGasNode(\n ethQuery: EthQuery,\n txParams: TransactionParams,\n delegationAddress?: Hex,\n) {\n const { from } = txParams;\n const params = [txParams] as Json[];\n\n if (delegationAddress) {\n params.push('latest');\n\n params.push({\n [from as string]: {\n code: DELEGATION_PREFIX + remove0x(delegationAddress),\n },\n });\n }\n\n return query(ethQuery, 'estimateGas', params);\n}\n"]}