@metamask/transaction-controller 62.5.0 → 62.6.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 (176) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/dist/TransactionController.cjs +105 -48
  3. package/dist/TransactionController.cjs.map +1 -1
  4. package/dist/TransactionController.d.cts +33 -21
  5. package/dist/TransactionController.d.cts.map +1 -1
  6. package/dist/TransactionController.d.mts +33 -21
  7. package/dist/TransactionController.d.mts.map +1 -1
  8. package/dist/TransactionController.mjs +106 -49
  9. package/dist/TransactionController.mjs.map +1 -1
  10. package/dist/api/accounts-api.cjs +1 -1
  11. package/dist/api/accounts-api.cjs.map +1 -1
  12. package/dist/api/accounts-api.mjs +1 -1
  13. package/dist/api/accounts-api.mjs.map +1 -1
  14. package/dist/api/simulation-api.cjs +1 -1
  15. package/dist/api/simulation-api.cjs.map +1 -1
  16. package/dist/api/simulation-api.mjs +1 -1
  17. package/dist/api/simulation-api.mjs.map +1 -1
  18. package/dist/gas-flows/LineaGasFeeFlow.cjs.map +1 -1
  19. package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -1
  20. package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs +28 -17
  21. package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs.map +1 -1
  22. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts +1 -6
  23. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts.map +1 -1
  24. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts +1 -6
  25. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts.map +1 -1
  26. package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs +28 -17
  27. package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs.map +1 -1
  28. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs +1 -0
  29. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs.map +1 -1
  30. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.cts.map +1 -1
  31. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.mts.map +1 -1
  32. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs +1 -0
  33. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs.map +1 -1
  34. package/dist/helpers/AccountsApiRemoteTransactionSource.cjs.map +1 -1
  35. package/dist/helpers/AccountsApiRemoteTransactionSource.mjs.map +1 -1
  36. package/dist/helpers/GasFeePoller.cjs.map +1 -1
  37. package/dist/helpers/GasFeePoller.mjs.map +1 -1
  38. package/dist/helpers/IncomingTransactionHelper.cjs.map +1 -1
  39. package/dist/helpers/IncomingTransactionHelper.d.cts.map +1 -1
  40. package/dist/helpers/IncomingTransactionHelper.d.mts.map +1 -1
  41. package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -1
  42. package/dist/helpers/MultichainTrackingHelper.cjs +2 -2
  43. package/dist/helpers/MultichainTrackingHelper.cjs.map +1 -1
  44. package/dist/helpers/MultichainTrackingHelper.d.cts.map +1 -1
  45. package/dist/helpers/MultichainTrackingHelper.d.mts.map +1 -1
  46. package/dist/helpers/MultichainTrackingHelper.mjs +2 -2
  47. package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -1
  48. package/dist/helpers/PendingTransactionTracker.cjs +88 -22
  49. package/dist/helpers/PendingTransactionTracker.cjs.map +1 -1
  50. package/dist/helpers/PendingTransactionTracker.d.cts +7 -6
  51. package/dist/helpers/PendingTransactionTracker.d.cts.map +1 -1
  52. package/dist/helpers/PendingTransactionTracker.d.mts +7 -6
  53. package/dist/helpers/PendingTransactionTracker.d.mts.map +1 -1
  54. package/dist/helpers/PendingTransactionTracker.mjs +88 -22
  55. package/dist/helpers/PendingTransactionTracker.mjs.map +1 -1
  56. package/dist/helpers/ResimulateHelper.cjs.map +1 -1
  57. package/dist/helpers/ResimulateHelper.d.cts +1 -4
  58. package/dist/helpers/ResimulateHelper.d.cts.map +1 -1
  59. package/dist/helpers/ResimulateHelper.d.mts +1 -4
  60. package/dist/helpers/ResimulateHelper.d.mts.map +1 -1
  61. package/dist/helpers/ResimulateHelper.mjs.map +1 -1
  62. package/dist/helpers/TransactionPoller.cjs.map +1 -1
  63. package/dist/helpers/TransactionPoller.d.cts.map +1 -1
  64. package/dist/helpers/TransactionPoller.d.mts.map +1 -1
  65. package/dist/helpers/TransactionPoller.mjs.map +1 -1
  66. package/dist/hooks/CollectPublishHook.cjs +1 -1
  67. package/dist/hooks/CollectPublishHook.cjs.map +1 -1
  68. package/dist/hooks/CollectPublishHook.d.cts.map +1 -1
  69. package/dist/hooks/CollectPublishHook.d.mts.map +1 -1
  70. package/dist/hooks/CollectPublishHook.mjs +1 -1
  71. package/dist/hooks/CollectPublishHook.mjs.map +1 -1
  72. package/dist/hooks/ExtraTransactionsPublishHook.cjs.map +1 -1
  73. package/dist/hooks/ExtraTransactionsPublishHook.mjs.map +1 -1
  74. package/dist/index.cjs.map +1 -1
  75. package/dist/index.d.cts +1 -1
  76. package/dist/index.d.cts.map +1 -1
  77. package/dist/index.d.mts +1 -1
  78. package/dist/index.d.mts.map +1 -1
  79. package/dist/index.mjs.map +1 -1
  80. package/dist/types.cjs +5 -0
  81. package/dist/types.cjs.map +1 -1
  82. package/dist/types.d.cts +6 -0
  83. package/dist/types.d.cts.map +1 -1
  84. package/dist/types.d.mts +6 -0
  85. package/dist/types.d.mts.map +1 -1
  86. package/dist/types.mjs +5 -0
  87. package/dist/types.mjs.map +1 -1
  88. package/dist/utils/balance-changes.cjs +5 -5
  89. package/dist/utils/balance-changes.cjs.map +1 -1
  90. package/dist/utils/balance-changes.d.cts.map +1 -1
  91. package/dist/utils/balance-changes.d.mts.map +1 -1
  92. package/dist/utils/balance-changes.mjs +5 -5
  93. package/dist/utils/balance-changes.mjs.map +1 -1
  94. package/dist/utils/balance.cjs.map +1 -1
  95. package/dist/utils/balance.d.cts.map +1 -1
  96. package/dist/utils/balance.d.mts.map +1 -1
  97. package/dist/utils/balance.mjs.map +1 -1
  98. package/dist/utils/batch.cjs +9 -4
  99. package/dist/utils/batch.cjs.map +1 -1
  100. package/dist/utils/batch.d.cts.map +1 -1
  101. package/dist/utils/batch.d.mts.map +1 -1
  102. package/dist/utils/batch.mjs +9 -4
  103. package/dist/utils/batch.mjs.map +1 -1
  104. package/dist/utils/eip7702.cjs +4 -3
  105. package/dist/utils/eip7702.cjs.map +1 -1
  106. package/dist/utils/eip7702.d.cts +1 -1
  107. package/dist/utils/eip7702.d.cts.map +1 -1
  108. package/dist/utils/eip7702.d.mts +1 -1
  109. package/dist/utils/eip7702.d.mts.map +1 -1
  110. package/dist/utils/eip7702.mjs +4 -3
  111. package/dist/utils/eip7702.mjs.map +1 -1
  112. package/dist/utils/external-transactions.cjs.map +1 -1
  113. package/dist/utils/external-transactions.d.cts.map +1 -1
  114. package/dist/utils/external-transactions.d.mts.map +1 -1
  115. package/dist/utils/external-transactions.mjs.map +1 -1
  116. package/dist/utils/feature-flags.cjs +22 -7
  117. package/dist/utils/feature-flags.cjs.map +1 -1
  118. package/dist/utils/feature-flags.d.cts +24 -0
  119. package/dist/utils/feature-flags.d.cts.map +1 -1
  120. package/dist/utils/feature-flags.d.mts +24 -0
  121. package/dist/utils/feature-flags.d.mts.map +1 -1
  122. package/dist/utils/feature-flags.mjs +20 -6
  123. package/dist/utils/feature-flags.mjs.map +1 -1
  124. package/dist/utils/first-time-interaction.cjs +3 -5
  125. package/dist/utils/first-time-interaction.cjs.map +1 -1
  126. package/dist/utils/first-time-interaction.d.cts.map +1 -1
  127. package/dist/utils/first-time-interaction.d.mts.map +1 -1
  128. package/dist/utils/first-time-interaction.mjs +3 -5
  129. package/dist/utils/first-time-interaction.mjs.map +1 -1
  130. package/dist/utils/gas-fee-tokens.cjs +1 -1
  131. package/dist/utils/gas-fee-tokens.cjs.map +1 -1
  132. package/dist/utils/gas-fee-tokens.d.cts.map +1 -1
  133. package/dist/utils/gas-fee-tokens.d.mts.map +1 -1
  134. package/dist/utils/gas-fee-tokens.mjs +1 -1
  135. package/dist/utils/gas-fee-tokens.mjs.map +1 -1
  136. package/dist/utils/gas-fees.cjs +1 -3
  137. package/dist/utils/gas-fees.cjs.map +1 -1
  138. package/dist/utils/gas-fees.d.cts +1 -1
  139. package/dist/utils/gas-fees.d.cts.map +1 -1
  140. package/dist/utils/gas-fees.d.mts +1 -1
  141. package/dist/utils/gas-fees.d.mts.map +1 -1
  142. package/dist/utils/gas-fees.mjs +1 -3
  143. package/dist/utils/gas-fees.mjs.map +1 -1
  144. package/dist/utils/gas.cjs +71 -15
  145. package/dist/utils/gas.cjs.map +1 -1
  146. package/dist/utils/gas.d.cts +18 -12
  147. package/dist/utils/gas.d.cts.map +1 -1
  148. package/dist/utils/gas.d.mts +18 -12
  149. package/dist/utils/gas.d.mts.map +1 -1
  150. package/dist/utils/gas.mjs +70 -15
  151. package/dist/utils/gas.mjs.map +1 -1
  152. package/dist/utils/layer1-gas-fee-flow.cjs.map +1 -1
  153. package/dist/utils/layer1-gas-fee-flow.d.cts.map +1 -1
  154. package/dist/utils/layer1-gas-fee-flow.d.mts.map +1 -1
  155. package/dist/utils/layer1-gas-fee-flow.mjs.map +1 -1
  156. package/dist/utils/prepare.cjs.map +1 -1
  157. package/dist/utils/prepare.d.cts +1 -1
  158. package/dist/utils/prepare.d.cts.map +1 -1
  159. package/dist/utils/prepare.d.mts +1 -1
  160. package/dist/utils/prepare.d.mts.map +1 -1
  161. package/dist/utils/prepare.mjs.map +1 -1
  162. package/dist/utils/swaps.cjs.map +1 -1
  163. package/dist/utils/swaps.mjs.map +1 -1
  164. package/dist/utils/utils.cjs +10 -10
  165. package/dist/utils/utils.cjs.map +1 -1
  166. package/dist/utils/utils.d.cts +4 -4
  167. package/dist/utils/utils.d.cts.map +1 -1
  168. package/dist/utils/utils.d.mts +4 -4
  169. package/dist/utils/utils.d.mts.map +1 -1
  170. package/dist/utils/utils.mjs +10 -10
  171. package/dist/utils/utils.mjs.map +1 -1
  172. package/dist/utils/validation.cjs.map +1 -1
  173. package/dist/utils/validation.d.cts.map +1 -1
  174. package/dist/utils/validation.d.mts.map +1 -1
  175. package/dist/utils/validation.mjs.map +1 -1
  176. package/package.json +1 -1
@@ -1,9 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.simulateGasBatch = exports.addGasBuffer = exports.estimateGas = exports.updateGas = exports.DUMMY_AUTHORIZATION_SIGNATURE = exports.INTRINSIC_GAS = exports.MAX_GAS_BLOCK_PERCENT = exports.DEFAULT_GAS_MULTIPLIER = exports.FIXED_GAS = exports.log = void 0;
3
+ exports.simulateGasBatch = exports.addGasBuffer = exports.estimateGasBatch = exports.estimateGas = exports.updateGas = exports.DUMMY_AUTHORIZATION_SIGNATURE = exports.INTRINSIC_GAS = exports.MAX_GAS_BLOCK_PERCENT = exports.DEFAULT_GAS_MULTIPLIER = exports.FIXED_GAS = exports.log = void 0;
4
4
  const controller_utils_1 = require("@metamask/controller-utils");
5
5
  const utils_1 = require("@metamask/utils");
6
- const bn_js_1 = require("bn.js");
6
+ const bignumber_js_1 = require("bignumber.js");
7
7
  const eip7702_1 = require("./eip7702.cjs");
8
8
  const feature_flags_1 = require("./feature-flags.cjs");
9
9
  const simulation_api_1 = require("../api/simulation-api.cjs");
@@ -30,9 +30,7 @@ async function updateGas(request) {
30
30
  if (!initialParams.gas) {
31
31
  txMeta.originalGasEstimate = txMeta.txParams.gas;
32
32
  }
33
- if (!txMeta.defaultGasEstimates) {
34
- txMeta.defaultGasEstimates = {};
35
- }
33
+ txMeta.defaultGasEstimates ?? (txMeta.defaultGasEstimates = {});
36
34
  txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;
37
35
  }
38
36
  exports.updateGas = updateGas;
@@ -64,7 +62,7 @@ async function estimateGas({ chainId, ethQuery, ignoreDelegationSignatures, isSi
64
62
  : (0, controller_utils_1.BNToHex)((0, controller_utils_1.fractionBN)(blockGasLimitBN, percentage, 100));
65
63
  (0, exports.log)('Estimation fallback values', fallback);
66
64
  request.data = data ? (0, utils_1.add0x)(data) : data;
67
- request.value = value || '0x0';
65
+ request.value = value ?? '0x0';
68
66
  request.authorizationList = normalizeAuthorizationList(request.authorizationList, chainId);
69
67
  delete request.gasPrice;
70
68
  delete request.maxFeePerGas;
@@ -111,6 +109,64 @@ async function estimateGas({ chainId, ethQuery, ignoreDelegationSignatures, isSi
111
109
  };
112
110
  }
113
111
  exports.estimateGas = estimateGas;
112
+ async function estimateGasBatch({ chainId, ethQuery, from, getSimulationConfig, isAtomicBatchSupported, messenger, transactions, }) {
113
+ const is7702Result = await isAtomicBatchSupported({
114
+ address: from,
115
+ chainIds: [chainId],
116
+ });
117
+ const chainResult = is7702Result.find((result) => result.chainId === chainId);
118
+ const isUpgradeRequired = Boolean(chainResult && !chainResult.isSupported);
119
+ if (isUpgradeRequired && !chainResult?.upgradeContractAddress) {
120
+ throw new Error('Upgrade contract address not found');
121
+ }
122
+ if (chainResult) {
123
+ const authorizationList = isUpgradeRequired
124
+ ? [{ address: chainResult.upgradeContractAddress }]
125
+ : undefined;
126
+ const type = isUpgradeRequired
127
+ ? types_1.TransactionEnvelopeType.setCode
128
+ : undefined;
129
+ const params = {
130
+ ...(0, eip7702_1.generateEIP7702BatchTransaction)(from, transactions),
131
+ authorizationList,
132
+ from,
133
+ type,
134
+ };
135
+ const { estimatedGas: gasLimitHex } = await estimateGas({
136
+ chainId,
137
+ ethQuery,
138
+ isSimulationEnabled: true,
139
+ getSimulationConfig,
140
+ messenger,
141
+ txParams: params,
142
+ });
143
+ const totalGasLimit = new bignumber_js_1.BigNumber(gasLimitHex).toNumber();
144
+ (0, exports.log)('Estimated EIP-7702 gas limit', totalGasLimit);
145
+ return { totalGasLimit, gasLimits: [totalGasLimit] };
146
+ }
147
+ const allTransactionsHaveGas = transactions.every((transaction) => transaction.gas !== undefined);
148
+ if (allTransactionsHaveGas) {
149
+ const gasLimits = transactions.map((transaction) => new bignumber_js_1.BigNumber(transaction.gas).toNumber());
150
+ const total = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);
151
+ (0, exports.log)('Using batch parameter gas limits', { gasLimits, total });
152
+ return { totalGasLimit: total, gasLimits };
153
+ }
154
+ const { gasLimits: gasLimitsHex } = await simulateGasBatch({
155
+ chainId,
156
+ from,
157
+ getSimulationConfig,
158
+ transactions: transactions.map((transaction) => ({
159
+ params: transaction,
160
+ })),
161
+ });
162
+ const gasLimits = transactions.map((transaction, index) => transaction.gas
163
+ ? new bignumber_js_1.BigNumber(transaction.gas).toNumber()
164
+ : new bignumber_js_1.BigNumber(gasLimitsHex[index]).toNumber());
165
+ const totalGasLimit = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);
166
+ (0, exports.log)('Simulated batch gas limits', { totalGasLimit, gasLimits });
167
+ return { totalGasLimit, gasLimits };
168
+ }
169
+ exports.estimateGasBatch = estimateGasBatch;
114
170
  /**
115
171
  * Add a buffer to the provided estimated gas.
116
172
  * The buffer is calculated based on the block gas limit and a multiplier.
@@ -162,16 +218,18 @@ async function simulateGasBatch({ chainId, from, getSimulationConfig, transactio
162
218
  response.transactions.length !== transactions.length) {
163
219
  throw new Error('Simulation response does not match transaction count');
164
220
  }
165
- const totalGasLimit = response.transactions.reduce((acc, transaction) => {
221
+ return response.transactions.reduce((acc, transaction) => {
166
222
  const gasLimit = transaction?.gasLimit;
167
223
  if (!gasLimit) {
168
224
  throw new Error('No simulated gas returned for one of the transactions');
169
225
  }
170
- return acc.add((0, controller_utils_1.hexToBN)(gasLimit));
171
- }, new bn_js_1.BN(0));
172
- return {
173
- gasLimit: (0, controller_utils_1.BNToHex)(totalGasLimit), // Return the total gas limit as a hex string
174
- };
226
+ acc.gasLimits.push(gasLimit);
227
+ acc.totalGasLimit = (0, controller_utils_1.BNToHex)((0, controller_utils_1.hexToBN)(acc.totalGasLimit).add((0, controller_utils_1.hexToBN)(gasLimit)));
228
+ return acc;
229
+ }, {
230
+ totalGasLimit: '0x0',
231
+ gasLimits: [],
232
+ });
175
233
  }
176
234
  catch (error) {
177
235
  (0, exports.log)('Error while simulating gas batch', error);
@@ -305,9 +363,7 @@ async function estimateGasUpgradeWithDataToSelf(txParams, ethQuery, chainId, get
305
363
  (0, exports.log)('Success estimating data portion of upgrade', executeGas);
306
364
  }
307
365
  (0, exports.log)('Execute gas', executeGas);
308
- const total = (0, controller_utils_1.BNToHex)((0, controller_utils_1.hexToBN)(upgradeGas)
309
- .add((0, controller_utils_1.hexToBN)(executeGas))
310
- .subn(exports.INTRINSIC_GAS));
366
+ const total = (0, controller_utils_1.BNToHex)((0, controller_utils_1.hexToBN)(upgradeGas).add((0, controller_utils_1.hexToBN)(executeGas)).subn(exports.INTRINSIC_GAS));
311
367
  (0, exports.log)('Total type 4 gas', total);
312
368
  return total;
313
369
  }
@@ -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;AAE1C,wCAAmD;AAkBtC,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,EAAE,eAAe,EAAE,gBAAgB,CAAC,GAAG,MAAM,MAAM,CAAC,OAAO,C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,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,IAAI,CAAC,EAAE;gBACN,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 { TransactionEnvelopeType } from '../types';\nimport type {\n GetSimulationConfig,\n TransactionBatchSingleRequest,\n TransactionMeta,\n 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,\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]: {\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]: {\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,+CAAyC;AAEzC,2CAA+E;AAC/E,uDAA+E;AAC/E,8DAA6D;AAC7D,0CAA0C;AAE1C,wCAAmD;AAsBtC,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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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 { BigNumber } from 'bignumber.js';\n\nimport { DELEGATION_PREFIX, generateEIP7702BatchTransaction } from './eip7702';\nimport { getGasEstimateBuffer, getGasEstimateFallback } from './feature-flags';\nimport { simulateTransactions } from '../api/simulation-api';\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport { TransactionEnvelopeType } from '../types';\nimport type {\n AuthorizationList,\n BatchTransactionParams,\n GetSimulationConfig,\n IsAtomicBatchSupportedRequest,\n IsAtomicBatchSupportedResult,\n TransactionBatchSingleRequest,\n TransactionMeta,\n 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): Promise<void> {\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 txMeta.defaultGasEstimates ??= {};\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}): Promise<{\n blockGasLimit: string;\n estimatedGas: string;\n isUpgradeWithDataToSelf: boolean;\n simulationFails: TransactionMeta['simulationFails'];\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\nexport async function estimateGasBatch({\n chainId,\n ethQuery,\n from,\n getSimulationConfig,\n isAtomicBatchSupported,\n messenger,\n transactions,\n}: {\n chainId: Hex;\n ethQuery: EthQuery;\n from: Hex;\n getSimulationConfig: GetSimulationConfig;\n isAtomicBatchSupported: (\n request: IsAtomicBatchSupportedRequest,\n ) => Promise<IsAtomicBatchSupportedResult>;\n messenger: TransactionControllerMessenger;\n transactions: BatchTransactionParams[];\n}): Promise<{ totalGasLimit: number; gasLimits: number[] }> {\n const is7702Result = await isAtomicBatchSupported({\n address: from,\n chainIds: [chainId],\n });\n\n const chainResult = is7702Result.find((result) => result.chainId === chainId);\n const isUpgradeRequired = Boolean(chainResult && !chainResult.isSupported);\n\n if (isUpgradeRequired && !chainResult?.upgradeContractAddress) {\n throw new Error('Upgrade contract address not found');\n }\n\n if (chainResult) {\n const authorizationList = isUpgradeRequired\n ? [{ address: chainResult.upgradeContractAddress as Hex }]\n : undefined;\n\n const type = isUpgradeRequired\n ? TransactionEnvelopeType.setCode\n : undefined;\n\n const params: TransactionParams = {\n ...generateEIP7702BatchTransaction(from, transactions),\n authorizationList,\n from,\n type,\n };\n\n const { estimatedGas: gasLimitHex } = await estimateGas({\n chainId,\n ethQuery,\n isSimulationEnabled: true,\n getSimulationConfig,\n messenger,\n txParams: params,\n });\n\n const totalGasLimit = new BigNumber(gasLimitHex).toNumber();\n\n log('Estimated EIP-7702 gas limit', totalGasLimit);\n\n return { totalGasLimit, gasLimits: [totalGasLimit] };\n }\n\n const allTransactionsHaveGas = transactions.every(\n (transaction) => transaction.gas !== undefined,\n );\n\n if (allTransactionsHaveGas) {\n const gasLimits = transactions.map((transaction) =>\n new BigNumber(transaction.gas as Hex).toNumber(),\n );\n\n const total = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);\n\n log('Using batch parameter gas limits', { gasLimits, total });\n\n return { totalGasLimit: total, gasLimits };\n }\n\n const { gasLimits: gasLimitsHex } = await simulateGasBatch({\n chainId,\n from,\n getSimulationConfig,\n transactions: transactions.map((transaction) => ({\n params: transaction,\n })),\n });\n\n const gasLimits = transactions.map((transaction, index) =>\n transaction.gas\n ? new BigNumber(transaction.gas).toNumber()\n : new BigNumber(gasLimitsHex[index]).toNumber(),\n );\n\n const totalGasLimit = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);\n\n log('Simulated batch gas limits', { totalGasLimit, gasLimits });\n\n return { totalGasLimit, gasLimits };\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): string {\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<{ totalGasLimit: Hex; gasLimits: 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 return response.transactions.reduce<{\n totalGasLimit: Hex;\n gasLimits: Hex[];\n }>(\n (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 acc.gasLimits.push(gasLimit);\n\n acc.totalGasLimit = BNToHex(\n hexToBN(acc.totalGasLimit).add(hexToBN(gasLimit)),\n );\n\n return acc;\n },\n {\n totalGasLimit: '0x0',\n gasLimits: [],\n },\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): Promise<Hex> {\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,\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).add(hexToBN(executeGas)).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]: {\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: AuthorizationList | undefined,\n chainId: Hex,\n): AuthorizationList | undefined {\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): Promise<Hex> {\n const { from } = txParams;\n const params = [txParams] as Json[];\n\n if (delegationAddress) {\n params.push('latest');\n\n params.push({\n [from]: {\n code: DELEGATION_PREFIX + remove0x(delegationAddress),\n },\n });\n }\n\n return query(ethQuery, 'estimateGas', params);\n}\n"]}
@@ -2,7 +2,7 @@
2
2
  import type EthQuery from "@metamask/eth-query";
3
3
  import type { Hex } from "@metamask/utils";
4
4
  import type { TransactionControllerMessenger } from "../TransactionController.cjs";
5
- import type { GetSimulationConfig, TransactionBatchSingleRequest, TransactionMeta, TransactionParams } from "../types.cjs";
5
+ import type { BatchTransactionParams, GetSimulationConfig, IsAtomicBatchSupportedRequest, IsAtomicBatchSupportedResult, TransactionBatchSingleRequest, TransactionMeta, TransactionParams } from "../types.cjs";
6
6
  export type UpdateGasRequest = {
7
7
  chainId: Hex;
8
8
  ethQuery: EthQuery;
@@ -48,16 +48,21 @@ export declare function estimateGas({ chainId, ethQuery, ignoreDelegationSignatu
48
48
  txParams: TransactionParams;
49
49
  }): Promise<{
50
50
  blockGasLimit: string;
51
- estimatedGas: `0x${string}`;
51
+ estimatedGas: string;
52
52
  isUpgradeWithDataToSelf: boolean;
53
- simulationFails: {
54
- reason?: string | undefined;
55
- errorKey?: string | undefined;
56
- debug: {
57
- blockNumber?: string | undefined;
58
- blockGasLimit?: string | undefined;
59
- };
60
- } | undefined;
53
+ simulationFails: TransactionMeta['simulationFails'];
54
+ }>;
55
+ export declare function estimateGasBatch({ chainId, ethQuery, from, getSimulationConfig, isAtomicBatchSupported, messenger, transactions, }: {
56
+ chainId: Hex;
57
+ ethQuery: EthQuery;
58
+ from: Hex;
59
+ getSimulationConfig: GetSimulationConfig;
60
+ isAtomicBatchSupported: (request: IsAtomicBatchSupportedRequest) => Promise<IsAtomicBatchSupportedResult>;
61
+ messenger: TransactionControllerMessenger;
62
+ transactions: BatchTransactionParams[];
63
+ }): Promise<{
64
+ totalGasLimit: number;
65
+ gasLimits: number[];
61
66
  }>;
62
67
  /**
63
68
  * Add a buffer to the provided estimated gas.
@@ -68,7 +73,7 @@ export declare function estimateGas({ chainId, ethQuery, ignoreDelegationSignatu
68
73
  * @param multiplier - The multiplier to apply to the estimated gas.
69
74
  * @returns The gas with the buffer applied.
70
75
  */
71
- export declare function addGasBuffer(estimatedGas: string, blockGasLimit: string, multiplier: number): `0x${string}`;
76
+ export declare function addGasBuffer(estimatedGas: string, blockGasLimit: string, multiplier: number): string;
72
77
  /**
73
78
  * Simulate the required gas for a batch of transactions using the simulation API.
74
79
  *
@@ -85,6 +90,7 @@ export declare function simulateGasBatch({ chainId, from, getSimulationConfig, t
85
90
  getSimulationConfig: GetSimulationConfig;
86
91
  transactions: TransactionBatchSingleRequest[];
87
92
  }): Promise<{
88
- gasLimit: Hex;
93
+ totalGasLimit: Hex;
94
+ gasLimits: Hex[];
89
95
  }>;
90
96
  //# sourceMappingURL=gas.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"gas.d.cts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";AAOA,OAAO,KAAK,QAAQ,4BAA4B;AAChD,OAAO,KAAK,EAAE,GAAG,EAAQ,wBAAwB;AAQjD,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAE/E,OAAO,KAAK,EACV,mBAAmB,EACnB,6BAA6B,EAC7B,eAAe,EACf,iBAAiB,EAClB,qBAAiB;AAElB,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EA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AAG,CAAC;IACV,mBAAmB,EAAE,mBAAmB,CAAC;IACzC,YAAY,EAAE,6BAA6B,EAAE,CAAC;CAC/C,GAAG,OAAO,CAAC;IAAE,aAAa,EAAE,GAAG,CAAC;IAAC,SAAS,EAAE,GAAG,EAAE,CAAA;CAAE,CAAC,CAiDpD"}
@@ -2,7 +2,7 @@
2
2
  import type EthQuery from "@metamask/eth-query";
3
3
  import type { Hex } from "@metamask/utils";
4
4
  import type { TransactionControllerMessenger } from "../TransactionController.mjs";
5
- import type { GetSimulationConfig, TransactionBatchSingleRequest, TransactionMeta, TransactionParams } from "../types.mjs";
5
+ import type { BatchTransactionParams, GetSimulationConfig, IsAtomicBatchSupportedRequest, IsAtomicBatchSupportedResult, TransactionBatchSingleRequest, TransactionMeta, TransactionParams } from "../types.mjs";
6
6
  export type UpdateGasRequest = {
7
7
  chainId: Hex;
8
8
  ethQuery: EthQuery;
@@ -48,16 +48,21 @@ export declare function estimateGas({ chainId, ethQuery, ignoreDelegationSignatu
48
48
  txParams: TransactionParams;
49
49
  }): Promise<{
50
50
  blockGasLimit: string;
51
- estimatedGas: `0x${string}`;
51
+ estimatedGas: string;
52
52
  isUpgradeWithDataToSelf: boolean;
53
- simulationFails: {
54
- reason?: string | undefined;
55
- errorKey?: string | undefined;
56
- debug: {
57
- blockNumber?: string | undefined;
58
- blockGasLimit?: string | undefined;
59
- };
60
- } | undefined;
53
+ simulationFails: TransactionMeta['simulationFails'];
54
+ }>;
55
+ export declare function estimateGasBatch({ chainId, ethQuery, from, getSimulationConfig, isAtomicBatchSupported, messenger, transactions, }: {
56
+ chainId: Hex;
57
+ ethQuery: EthQuery;
58
+ from: Hex;
59
+ getSimulationConfig: GetSimulationConfig;
60
+ isAtomicBatchSupported: (request: IsAtomicBatchSupportedRequest) => Promise<IsAtomicBatchSupportedResult>;
61
+ messenger: TransactionControllerMessenger;
62
+ transactions: BatchTransactionParams[];
63
+ }): Promise<{
64
+ totalGasLimit: number;
65
+ gasLimits: number[];
61
66
  }>;
62
67
  /**
63
68
  * Add a buffer to the provided estimated gas.
@@ -68,7 +73,7 @@ export declare function estimateGas({ chainId, ethQuery, ignoreDelegationSignatu
68
73
  * @param multiplier - The multiplier to apply to the estimated gas.
69
74
  * @returns The gas with the buffer applied.
70
75
  */
71
- export declare function addGasBuffer(estimatedGas: string, blockGasLimit: string, multiplier: number): `0x${string}`;
76
+ export declare function addGasBuffer(estimatedGas: string, blockGasLimit: string, multiplier: number): string;
72
77
  /**
73
78
  * Simulate the required gas for a batch of transactions using the simulation API.
74
79
  *
@@ -85,6 +90,7 @@ export declare function simulateGasBatch({ chainId, from, getSimulationConfig, t
85
90
  getSimulationConfig: GetSimulationConfig;
86
91
  transactions: TransactionBatchSingleRequest[];
87
92
  }): Promise<{
88
- gasLimit: Hex;
93
+ totalGasLimit: Hex;
94
+ gasLimits: Hex[];
89
95
  }>;
90
96
  //# sourceMappingURL=gas.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"gas.d.mts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";AAOA,OAAO,KAAK,QAAQ,4BAA4B;AAChD,OAAO,KAAK,EAAE,GAAG,EAAQ,wBAAwB;AAQjD,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAE/E,OAAO,KAAK,EACV,mBAAmB,EACnB,6BAA6B,EAC7B,eAAe,EACf,iBAAiB,EAClB,qBAAiB;AAElB,MAAM,MAAM,gBAAgB,GAAG;IAC7B,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,QAAQ,CAAC;IACnB,eAAe,EAAE,OAAO,CAAC;IACzB,mBAAmB,EAAE,OAAO,CAAC;IAC7B,mBAAmB,EAAE,mBAAmB,CAAC;IACzC,SAAS,EAAE,8BAA8B,CAAC;IAC1C,MAAM,EAAE,eAAe,CAAC;CACzB,CAAC;AAEF,eAAO,MAAM,GAAG,0BAA2C,CAAC;AAE5D,eAAO,MAAM,SAAS,WAAW,CAAC;AAClC,eA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Y,EAAE,MAAM,CAAC;IACrB,uBAAuB,EAAE,OAAO,CAAC;IACjC,eAAe,EAAE,eAAe,CAAC,iBAAiB,CAAC,CAAC;CACrD,CAAC,CAiFD;AAED,wBAAsB,gBAAgB,CAAC,EACrC,OAAO,EACP,QAAQ,EACR,IAAI,EACJ,mBAAmB,EACnB,sBAAsB,EACtB,SAAS,EACT,YAAY,GACb,EAAE;IACD,OAAO,EAAE,GAAG,CAAC;IACb,QAAQ,EAAE,QAAQ,CAAC;IACnB,IAAI,EAAE,GAAG,CAAC;IACV,mBAAmB,EAAE,mBAAmB,CAAC;IACzC,sBAAsB,EAAE,CACtB,OAAO,EAAE,6BAA6B,KACnC,OAAO,CAAC,4BAA4B,CAAC,CAAC;IAC3C,SAAS,EAAE,8BAA8B,CAAC;IAC1C,YAAY,EAAE,sBAAsB,EAAE,CAAC;CACxC,GAAG,OAAO,CAAC;IAAE,aAAa,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAiF1D;AAED;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAC1B,YAAY,EAAE,MAAM,EACpB,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,MAAM,GACjB,MAAM,CA0BR;AAED;;;;;;;;;GASG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,OAAO,EACP,IAAI,EACJ,mBAAmB,EACnB,YAAY,GACb,EAAE;IACD,OAAO,EAAE,GAAG,CAAC;IACb,IAAI,EAAE,GAAG,CAAC;IACV,mBAAmB,EAAE,mBAAmB,CAAC;IACzC,YAAY,EAAE,6BAA6B,EAAE,CAAC;CAC/C,GAAG,OAAO,CAAC;IAAE,aAAa,EAAE,GAAG,CAAC;IAAC,SAAS,EAAE,GAAG,EAAE,CAAA;CAAE,CAAC,CAiDpD"}
@@ -1,7 +1,7 @@
1
1
  import { BNToHex, fractionBN, hexToBN, query, toHex } from "@metamask/controller-utils";
2
2
  import { add0x, createModuleLogger, remove0x } from "@metamask/utils";
3
- import { BN } from "bn.js";
4
- import { DELEGATION_PREFIX } from "./eip7702.mjs";
3
+ import { BigNumber } from "bignumber.js";
4
+ import { DELEGATION_PREFIX, generateEIP7702BatchTransaction } from "./eip7702.mjs";
5
5
  import { getGasEstimateBuffer, getGasEstimateFallback } from "./feature-flags.mjs";
6
6
  import { simulateTransactions } from "../api/simulation-api.mjs";
7
7
  import { projectLogger } from "../logger.mjs";
@@ -27,9 +27,7 @@ export async function updateGas(request) {
27
27
  if (!initialParams.gas) {
28
28
  txMeta.originalGasEstimate = txMeta.txParams.gas;
29
29
  }
30
- if (!txMeta.defaultGasEstimates) {
31
- txMeta.defaultGasEstimates = {};
32
- }
30
+ txMeta.defaultGasEstimates ?? (txMeta.defaultGasEstimates = {});
33
31
  txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;
34
32
  }
35
33
  /**
@@ -60,7 +58,7 @@ export async function estimateGas({ chainId, ethQuery, ignoreDelegationSignature
60
58
  : BNToHex(fractionBN(blockGasLimitBN, percentage, 100));
61
59
  log('Estimation fallback values', fallback);
62
60
  request.data = data ? add0x(data) : data;
63
- request.value = value || '0x0';
61
+ request.value = value ?? '0x0';
64
62
  request.authorizationList = normalizeAuthorizationList(request.authorizationList, chainId);
65
63
  delete request.gasPrice;
66
64
  delete request.maxFeePerGas;
@@ -106,6 +104,63 @@ export async function estimateGas({ chainId, ethQuery, ignoreDelegationSignature
106
104
  simulationFails,
107
105
  };
108
106
  }
107
+ export async function estimateGasBatch({ chainId, ethQuery, from, getSimulationConfig, isAtomicBatchSupported, messenger, transactions, }) {
108
+ const is7702Result = await isAtomicBatchSupported({
109
+ address: from,
110
+ chainIds: [chainId],
111
+ });
112
+ const chainResult = is7702Result.find((result) => result.chainId === chainId);
113
+ const isUpgradeRequired = Boolean(chainResult && !chainResult.isSupported);
114
+ if (isUpgradeRequired && !chainResult?.upgradeContractAddress) {
115
+ throw new Error('Upgrade contract address not found');
116
+ }
117
+ if (chainResult) {
118
+ const authorizationList = isUpgradeRequired
119
+ ? [{ address: chainResult.upgradeContractAddress }]
120
+ : undefined;
121
+ const type = isUpgradeRequired
122
+ ? TransactionEnvelopeType.setCode
123
+ : undefined;
124
+ const params = {
125
+ ...generateEIP7702BatchTransaction(from, transactions),
126
+ authorizationList,
127
+ from,
128
+ type,
129
+ };
130
+ const { estimatedGas: gasLimitHex } = await estimateGas({
131
+ chainId,
132
+ ethQuery,
133
+ isSimulationEnabled: true,
134
+ getSimulationConfig,
135
+ messenger,
136
+ txParams: params,
137
+ });
138
+ const totalGasLimit = new BigNumber(gasLimitHex).toNumber();
139
+ log('Estimated EIP-7702 gas limit', totalGasLimit);
140
+ return { totalGasLimit, gasLimits: [totalGasLimit] };
141
+ }
142
+ const allTransactionsHaveGas = transactions.every((transaction) => transaction.gas !== undefined);
143
+ if (allTransactionsHaveGas) {
144
+ const gasLimits = transactions.map((transaction) => new BigNumber(transaction.gas).toNumber());
145
+ const total = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);
146
+ log('Using batch parameter gas limits', { gasLimits, total });
147
+ return { totalGasLimit: total, gasLimits };
148
+ }
149
+ const { gasLimits: gasLimitsHex } = await simulateGasBatch({
150
+ chainId,
151
+ from,
152
+ getSimulationConfig,
153
+ transactions: transactions.map((transaction) => ({
154
+ params: transaction,
155
+ })),
156
+ });
157
+ const gasLimits = transactions.map((transaction, index) => transaction.gas
158
+ ? new BigNumber(transaction.gas).toNumber()
159
+ : new BigNumber(gasLimitsHex[index]).toNumber());
160
+ const totalGasLimit = gasLimits.reduce((acc, gasLimit) => acc + gasLimit, 0);
161
+ log('Simulated batch gas limits', { totalGasLimit, gasLimits });
162
+ return { totalGasLimit, gasLimits };
163
+ }
109
164
  /**
110
165
  * Add a buffer to the provided estimated gas.
111
166
  * The buffer is calculated based on the block gas limit and a multiplier.
@@ -156,16 +211,18 @@ export async function simulateGasBatch({ chainId, from, getSimulationConfig, tra
156
211
  response.transactions.length !== transactions.length) {
157
212
  throw new Error('Simulation response does not match transaction count');
158
213
  }
159
- const totalGasLimit = response.transactions.reduce((acc, transaction) => {
214
+ return response.transactions.reduce((acc, transaction) => {
160
215
  const gasLimit = transaction?.gasLimit;
161
216
  if (!gasLimit) {
162
217
  throw new Error('No simulated gas returned for one of the transactions');
163
218
  }
164
- return acc.add(hexToBN(gasLimit));
165
- }, new BN(0));
166
- return {
167
- gasLimit: BNToHex(totalGasLimit), // Return the total gas limit as a hex string
168
- };
219
+ acc.gasLimits.push(gasLimit);
220
+ acc.totalGasLimit = BNToHex(hexToBN(acc.totalGasLimit).add(hexToBN(gasLimit)));
221
+ return acc;
222
+ }, {
223
+ totalGasLimit: '0x0',
224
+ gasLimits: [],
225
+ });
169
226
  }
170
227
  catch (error) {
171
228
  log('Error while simulating gas batch', error);
@@ -298,9 +355,7 @@ async function estimateGasUpgradeWithDataToSelf(txParams, ethQuery, chainId, get
298
355
  log('Success estimating data portion of upgrade', executeGas);
299
356
  }
300
357
  log('Execute gas', executeGas);
301
- const total = BNToHex(hexToBN(upgradeGas)
302
- .add(hexToBN(executeGas))
303
- .subn(INTRINSIC_GAS));
358
+ const total = BNToHex(hexToBN(upgradeGas).add(hexToBN(executeGas)).subn(INTRINSIC_GAS));
304
359
  log('Total type 4 gas', total);
305
360
  return total;
306
361
  }