@metamask-previews/transaction-controller 74.0.0-preview-bf9d42292 → 74.0.0-preview-8647f16

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 (66) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/dist/TransactionController.d.ts +2 -2
  3. package/dist/TransactionController.d.ts.map +1 -1
  4. package/dist/TransactionController.js +126 -763
  5. package/dist/TransactionController.js.map +1 -1
  6. package/dist/actions/addTransaction.d.ts +10 -0
  7. package/dist/actions/addTransaction.d.ts.map +1 -0
  8. package/dist/actions/addTransaction.js +37 -0
  9. package/dist/actions/addTransaction.js.map +1 -0
  10. package/dist/lifecycle/add.d.ts +12 -0
  11. package/dist/lifecycle/add.d.ts.map +1 -0
  12. package/dist/lifecycle/add.js +20 -0
  13. package/dist/lifecycle/add.js.map +1 -0
  14. package/dist/lifecycle/approval.d.ts +11 -0
  15. package/dist/lifecycle/approval.d.ts.map +1 -0
  16. package/dist/lifecycle/approval.js +89 -0
  17. package/dist/lifecycle/approval.js.map +1 -0
  18. package/dist/lifecycle/approve.d.ts +8 -0
  19. package/dist/lifecycle/approve.d.ts.map +1 -0
  20. package/dist/lifecycle/approve.js +53 -0
  21. package/dist/lifecycle/approve.js.map +1 -0
  22. package/dist/lifecycle/background.d.ts +15 -0
  23. package/dist/lifecycle/background.d.ts.map +1 -0
  24. package/dist/lifecycle/background.js +66 -0
  25. package/dist/lifecycle/background.js.map +1 -0
  26. package/dist/lifecycle/data.d.ts +18 -0
  27. package/dist/lifecycle/data.d.ts.map +1 -0
  28. package/dist/lifecycle/data.js +165 -0
  29. package/dist/lifecycle/data.js.map +1 -0
  30. package/dist/lifecycle/error.d.ts +36 -0
  31. package/dist/lifecycle/error.d.ts.map +1 -0
  32. package/dist/lifecycle/error.js +106 -0
  33. package/dist/lifecycle/error.js.map +1 -0
  34. package/dist/lifecycle/finish.d.ts +12 -0
  35. package/dist/lifecycle/finish.d.ts.map +1 -0
  36. package/dist/lifecycle/finish.js +41 -0
  37. package/dist/lifecycle/finish.js.map +1 -0
  38. package/dist/lifecycle/init.d.ts +27 -0
  39. package/dist/lifecycle/init.d.ts.map +1 -0
  40. package/dist/lifecycle/init.js +197 -0
  41. package/dist/lifecycle/init.js.map +1 -0
  42. package/dist/lifecycle/sign.d.ts +35 -0
  43. package/dist/lifecycle/sign.d.ts.map +1 -0
  44. package/dist/lifecycle/sign.js +150 -0
  45. package/dist/lifecycle/sign.js.map +1 -0
  46. package/dist/lifecycle/state.d.ts +45 -0
  47. package/dist/lifecycle/state.d.ts.map +1 -0
  48. package/dist/lifecycle/state.js +56 -0
  49. package/dist/lifecycle/state.js.map +1 -0
  50. package/dist/lifecycle/submit.d.ts +8 -0
  51. package/dist/lifecycle/submit.d.ts.map +1 -0
  52. package/dist/lifecycle/submit.js +169 -0
  53. package/dist/lifecycle/submit.js.map +1 -0
  54. package/dist/lifecycle/types.d.ts +68 -0
  55. package/dist/lifecycle/types.d.ts.map +1 -0
  56. package/dist/lifecycle/types.js +2 -0
  57. package/dist/lifecycle/types.js.map +1 -0
  58. package/dist/logger.d.ts +1 -0
  59. package/dist/logger.d.ts.map +1 -1
  60. package/dist/logger.js +1 -0
  61. package/dist/logger.js.map +1 -1
  62. package/dist/utils/state.d.ts +56 -0
  63. package/dist/utils/state.d.ts.map +1 -0
  64. package/dist/utils/state.js +104 -0
  65. package/dist/utils/state.js.map +1 -0
  66. package/package.json +1 -1
@@ -1,14 +1,13 @@
1
1
  import { BaseController } from '@metamask/base-controller';
2
- import { ApprovalType, ORIGIN_METAMASK, convertHexToDecimal, } from '@metamask/controller-utils';
3
2
  import { NetworkClientType } from '@metamask/network-controller';
4
3
  import { NonceTracker } from '@metamask/nonce-tracker';
5
- import { errorCodes, rpcErrors, providerErrors, JsonRpcError, } from '@metamask/rpc-errors';
6
4
  import { add0x } from '@metamask/utils';
7
5
  // This package purposefully relies on Node's EventEmitter module.
8
6
  // eslint-disable-next-line import-x/no-nodejs-modules
9
7
  import { EventEmitter } from 'events';
10
8
  import { cloneDeep, mapValues, merge, noop, pickBy, sortBy } from 'lodash-es';
11
9
  import { v1 as random } from 'uuid';
10
+ import { addTransaction } from './actions/addTransaction.js';
12
11
  import { DefaultGasFeeFlow } from './gas-flows/DefaultGasFeeFlow.js';
13
12
  import { LineaGasFeeFlow } from './gas-flows/LineaGasFeeFlow.js';
14
13
  import { MantleLayer1GasFeeFlow } from './gas-flows/MantleLayer1GasFeeFlow.js';
@@ -16,33 +15,34 @@ import { OptimismLayer1GasFeeFlow } from './gas-flows/OptimismLayer1GasFeeFlow.j
16
15
  import { RandomisedEstimationsGasFeeFlow } from './gas-flows/RandomisedEstimationsGasFeeFlow.js';
17
16
  import { ScrollLayer1GasFeeFlow } from './gas-flows/ScrollLayer1GasFeeFlow.js';
18
17
  import { TestGasFeeFlow } from './gas-flows/TestGasFeeFlow.js';
19
- import { GasFeePoller, updateTransactionGasProperties, updateTransactionGasEstimates, } from './helpers/GasFeePoller.js';
18
+ import { GasFeePoller, updateTransactionGasEstimates, updateTransactionGasProperties, } from './helpers/GasFeePoller.js';
20
19
  import { MethodDataHelper } from './helpers/MethodDataHelper.js';
21
20
  import { MultichainTrackingHelper } from './helpers/MultichainTrackingHelper.js';
22
21
  import { PendingTransactionTracker } from './helpers/PendingTransactionTracker.js';
23
- import { ResimulateHelper, hasSimulationDataChanged, shouldResimulate, } from './helpers/ResimulateHelper.js';
24
- import { ExtraTransactionsPublishHook } from './hooks/ExtraTransactionsPublishHook.js';
22
+ import { hasSimulationDataChanged, ResimulateHelper, shouldResimulate, } from './helpers/ResimulateHelper.js';
23
+ import { addTransactionToState } from './lifecycle/add.js';
24
+ import { abortTransactionSigning, signTransactionMeta, updateTransactionMetaRSV, } from './lifecycle/sign.js';
25
+ import { isTransactionApproving, startTransactionApproval, } from './lifecycle/state.js';
25
26
  import { projectLogger as log } from './logger.js';
26
- import { GasFeeEstimateLevel, TransactionContainerType, TransactionEnvelopeType, TransactionType, TransactionStatus, SimulationErrorCode, } from './types.js';
27
+ import { GasFeeEstimateLevel, SimulationErrorCode, TransactionContainerType, TransactionEnvelopeType, TransactionStatus, TransactionType, } from './types.js';
27
28
  import { getBalanceChanges } from './utils/balance-changes.js';
28
29
  import { addTransactionBatch, isAtomicBatchSupported } from './utils/batch.js';
29
- import { getDelegationAddress, signAuthorizationList, updateEIP7702BatchData, } from './utils/eip7702.js';
30
+ import { getDelegationAddress, updateEIP7702BatchData, } from './utils/eip7702.js';
30
31
  import { validateConfirmedExternalTransaction } from './utils/external-transactions.js';
31
- import { getSubmitHistoryLimit, getTransactionHistoryLimit, } from './utils/feature-flags.js';
32
- import { updateFirstTimeInteraction } from './utils/first-time-interaction.js';
33
- import { checkGasFeeTokenBeforePublish, getGasFeeTokens, } from './utils/gas-fee-tokens.js';
34
- import { updateGasFees } from './utils/gas-fees.js';
32
+ import { getSubmitHistoryLimit } from './utils/feature-flags.js';
33
+ import { getGasFeeTokens } from './utils/gas-fee-tokens.js';
35
34
  import { getGasFeeFlow } from './utils/gas-flow.js';
36
35
  import { addGasBuffer, estimateGas, estimateGasBatch, updateGas, } from './utils/gas.js';
37
36
  import { getTransactionLayer1GasFee, updateTransactionLayer1GasFee, } from './utils/layer1-gas-fee-flow.js';
38
- import { getAndFormatTransactionsForNonceTracker, getNextNonce, } from './utils/nonce.js';
37
+ import { getAndFormatTransactionsForNonceTracker } from './utils/nonce.js';
39
38
  import { prepareTransaction, serializeTransaction } from './utils/prepare.js';
40
39
  import { getChainId, getNetworkClientId, rpcRequest, } from './utils/provider.js';
41
40
  import { getTransactionParamsWithIncreasedGasFee } from './utils/retry.js';
42
- import { updatePostTransactionBalance, updateSwapsTransaction, } from './utils/swaps.js';
41
+ import { getTransaction, getTransactionOrThrow, isFinalState, trimTransactionsForState, } from './utils/state.js';
42
+ import { updatePostTransactionBalance } from './utils/swaps.js';
43
43
  import { determineTransactionType } from './utils/transaction-type.js';
44
- import { normalizeTransactionParams, isEIP1559Transaction, validateGasValues, validateIfTransactionUnapproved, validateIfTransactionUnapprovedOrSubmitted, normalizeTxError, normalizeGasFeeValues, setEnvelopeType, } from './utils/utils.js';
45
- import { ErrorCode, validateTransactionOrigin, validateTxParams, } from './utils/validation.js';
44
+ import { isEIP1559Transaction, normalizeGasFeeValues, normalizeTransactionParams, normalizeTxError, validateGasValues, validateIfTransactionUnapproved, validateIfTransactionUnapprovedOrSubmitted, } from './utils/utils.js';
45
+ import { validateTxParams } from './utils/validation.js';
46
46
  /**
47
47
  * Metadata for the TransactionController state, describing how to "anonymize"
48
48
  * the state and which parts should be persisted.
@@ -93,6 +93,20 @@ export const CANCEL_RATE = 1.1;
93
93
  * Multiplier used to determine a transaction's increased gas fee during speed up
94
94
  */
95
95
  export const SPEED_UP_RATE = 1.1;
96
+ // Default for the `getSimulationConfig` option.
97
+ const DEFAULT_GET_SIMULATION_CONFIG = () => Promise.resolve({});
98
+ // Default for the `isAutomaticGasFeeUpdateEnabled` option.
99
+ const DEFAULT_IS_AUTOMATIC_GAS_FEE_UPDATE_ENABLED = () => false;
100
+ // Default for the `isEIP7702GasFeeTokensEnabled` option.
101
+ const DEFAULT_IS_EIP7702_GAS_FEE_TOKENS_ENABLED = () => Promise.resolve(false);
102
+ // Default for the `isTransactionTrusted` option.
103
+ const DEFAULT_IS_TRANSACTION_TRUSTED = () => false;
104
+ // Default for the `isTimeoutEnabled` option.
105
+ const DEFAULT_IS_TIMEOUT_ENABLED = () => true;
106
+ // Default for the `isSimulationEnabled` option.
107
+ const DEFAULT_IS_SIMULATION_ENABLED = () => true;
108
+ // Default for the `trace` option.
109
+ const DEFAULT_TRACE = ((_request, fn) => fn?.());
96
110
  /**
97
111
  * The name of the {@link TransactionController}.
98
112
  */
@@ -162,41 +176,22 @@ const MESSENGER_EXPOSED_METHODS = [
162
176
  * Controller responsible for submitting and managing transactions.
163
177
  */
164
178
  export class TransactionController extends BaseController {
165
- #afterAdd;
166
- #approvingTransactionIds = new Set();
167
- #beforeCheckPendingTransaction;
168
- #beforePublish;
169
- #beforeSign;
170
179
  #gasFeeFlows;
171
- #getPermittedAccounts;
172
- #getSavedGasFees;
173
- #getSimulationConfig;
174
180
  #internalEvents = new EventEmitter();
175
- #isAutomaticGasFeeUpdateEnabled;
176
- #isEIP7702GasFeeTokensEnabled;
177
- #isFirstTimeInteractionEnabled;
178
- #isSimulationEnabled;
179
- #isTransactionTrusted;
180
- #isSwapsDisabled;
181
- #isTimeoutEnabled;
182
181
  #layer1GasFeeFlows;
183
182
  #methodDataHelper;
184
183
  #multichainTrackingHelper;
185
- #publicKeyEIP7702;
186
- #publish;
187
- #publishBatchHook;
188
- #signAbortCallbacks = new Map();
184
+ #options;
189
185
  #skipSimulationTransactionIds = new Set();
190
186
  #simulationRequestTokens = new Map();
191
- #testGasFeeFlows;
192
- #trace;
187
+ #dependencies;
193
188
  /**
194
189
  * Constructs a TransactionController.
195
190
  *
196
191
  * @param options - The controller options.
197
192
  */
198
193
  constructor(options) {
199
- const { disableSwaps, getPermittedAccounts, getSavedGasFees, getSimulationConfig, hooks, isAutomaticGasFeeUpdateEnabled, isEIP7702GasFeeTokensEnabled, isFirstTimeInteractionEnabled, isSimulationEnabled, isTransactionTrusted, isTimeoutEnabled, messenger, publicKeyEIP7702, state, testGasFeeFlows, trace, } = options;
194
+ const { hooks, messenger, state, ...remainingOptions } = options;
200
195
  super({
201
196
  name: controllerName,
202
197
  metadata,
@@ -207,43 +202,11 @@ export class TransactionController extends BaseController {
207
202
  },
208
203
  });
209
204
  this.messenger = messenger;
210
- this.#afterAdd =
211
- hooks?.afterAdd ?? (() => Promise.resolve({}));
212
- this.#beforeCheckPendingTransaction =
213
- /* istanbul ignore next */
214
- hooks?.beforeCheckPendingTransaction ??
215
- (() => Promise.resolve(true));
216
- this.#beforePublish =
217
- hooks?.beforePublish ?? (() => Promise.resolve(true));
218
- this.#beforeSign =
219
- hooks?.beforeSign ??
220
- (() => Promise.resolve({}));
221
- this.#getPermittedAccounts = getPermittedAccounts;
222
- this.#getSavedGasFees =
223
- getSavedGasFees ??
224
- ((_transactionMeta) => undefined);
225
- this.#getSimulationConfig =
226
- getSimulationConfig ??
227
- (() => Promise.resolve({}));
228
- this.#isAutomaticGasFeeUpdateEnabled =
229
- isAutomaticGasFeeUpdateEnabled ??
230
- ((_txMeta) => false);
231
- this.#isEIP7702GasFeeTokensEnabled =
232
- isEIP7702GasFeeTokensEnabled ??
233
- (() => Promise.resolve(false));
234
- this.#isFirstTimeInteractionEnabled =
235
- isFirstTimeInteractionEnabled ?? (() => true);
236
- this.#isSimulationEnabled = isSimulationEnabled ?? (() => true);
237
- this.#isTransactionTrusted = isTransactionTrusted ?? (() => false);
238
- this.#isSwapsDisabled = disableSwaps ?? false;
239
- this.#isTimeoutEnabled = isTimeoutEnabled ?? (() => true);
240
- this.#publicKeyEIP7702 = publicKeyEIP7702;
241
- this.#publish =
242
- hooks?.publish ??
243
- (() => Promise.resolve({ transactionHash: undefined }));
244
- this.#publishBatchHook = hooks?.publishBatch;
245
- this.#testGasFeeFlows = testGasFeeFlows === true;
246
- this.#trace = trace ?? ((_request, fn) => fn?.());
205
+ this.#options = {
206
+ ...remainingOptions,
207
+ getSavedGasFees: remainingOptions.getSavedGasFees?.bind(this),
208
+ hooks: { ...hooks, beforeSign: hooks?.beforeSign?.bind(this) },
209
+ };
247
210
  const findNetworkClientIdByChainId = (chainId) => {
248
211
  return this.messenger.call(`NetworkController:findNetworkClientIdByChainId`, chainId);
249
212
  };
@@ -338,24 +301,25 @@ export class TransactionController extends BaseController {
338
301
  */
339
302
  async addTransactionBatch(request) {
340
303
  const { blockTracker } = this.messenger.call(`NetworkController:getNetworkClientById`, request.networkClientId);
304
+ const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, hooks, isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, publicKeyEIP7702, } = this.#options;
341
305
  return await addTransactionBatch({
342
306
  addTransaction: this.addTransaction.bind(this),
343
307
  estimateGas: this.estimateGas.bind(this),
344
308
  getGasFeeEstimates: (options) => this.messenger.call('GasFeeController:fetchGasFeeEstimates', options),
345
309
  getInternalAccounts: this.#getInternalAccounts.bind(this),
346
- getSimulationConfig: this.#getSimulationConfig.bind(this),
310
+ getSimulationConfig,
347
311
  getPendingTransactionTracker: (networkClientId) => this.#createPendingTransactionTracker({
348
312
  blockTracker,
349
313
  networkClientId,
350
314
  }),
351
315
  getTransaction: (transactionId) => this.#getTransactionOrThrow(transactionId),
352
- isSimulationEnabled: this.#isSimulationEnabled,
316
+ isSimulationEnabled,
353
317
  messenger: this.messenger,
354
- publishBatchHook: this.#publishBatchHook,
355
- publicKeyEIP7702: this.#publicKeyEIP7702,
318
+ publishBatchHook: hooks?.publishBatch,
319
+ publicKeyEIP7702,
356
320
  publishTransaction: (transactionMeta) => this.#publishTransaction(transactionMeta),
357
321
  request,
358
- signTransaction: this.#signTransaction.bind(this),
322
+ signTransaction: (transactionMeta) => signTransactionMeta(this.#getConstructorOptions(), this.#getDependencies(), transactionMeta),
359
323
  update: this.update.bind(this),
360
324
  updateTransaction: this.#updateTransactionInternal.bind(this),
361
325
  });
@@ -370,7 +334,7 @@ export class TransactionController extends BaseController {
370
334
  return isAtomicBatchSupported({
371
335
  ...request,
372
336
  messenger: this.messenger,
373
- publicKeyEIP7702: this.#publicKeyEIP7702,
337
+ publicKeyEIP7702: this.#options.publicKeyEIP7702,
374
338
  });
375
339
  }
376
340
  /**
@@ -383,170 +347,11 @@ export class TransactionController extends BaseController {
383
347
  * @returns Object containing a promise resolving to the transaction hash if approved.
384
348
  */
385
349
  async addTransaction(txParams, options) {
386
- log('Adding transaction', txParams, options);
387
- const { actionId, assetsFiatValues, batchId, deviceConfirmedOn, disableGasBuffer, gasFeeToken, excludeNativeTokenForFee, isGasFeeIncluded, isGasFeeSponsored, isInternal = false, isStateOnly, nestedTransactions, networkClientId, origin, publishHook, requestId, requiredAssets, requireApproval, securityAlertResponse, skipInitialGasEstimate, swaps = {}, traceContext, type, } = options;
388
- // eslint-disable-next-line no-param-reassign
389
- txParams = normalizeTransactionParams(txParams);
390
- if (!this.#multichainTrackingHelper.has(networkClientId)) {
391
- throw new Error(`Network client not found - ${networkClientId}`);
392
- }
393
- const chainId = getChainId({ messenger: this.messenger, networkClientId });
394
- const permittedAddresses = origin === undefined
395
- ? undefined
396
- : await this.#getPermittedAccounts?.(origin);
397
- const internalAccounts = this.#getInternalAccounts();
398
- await validateTransactionOrigin({
399
- data: txParams.data,
400
- from: txParams.from,
401
- internalAccounts,
402
- isInternal,
403
- origin,
404
- permittedAddresses,
405
- txParams,
406
- type,
407
- });
408
- const delegationAddressPromise = getDelegationAddress(txParams.from, this.messenger, networkClientId).catch(() => undefined);
409
- const isEIP1559Compatible = await this.#getEIP1559Compatibility(networkClientId);
410
- validateTxParams(txParams, isEIP1559Compatible, chainId);
411
- if (!txParams.type) {
412
- // Determine transaction type based on transaction parameters and network compatibility
413
- setEnvelopeType(txParams, isEIP1559Compatible);
414
- }
415
- const isDuplicateBatchId = batchId?.length &&
416
- this.state.transactions.some((tx) => tx.batchId?.toLowerCase() === batchId?.toLowerCase());
417
- if (isDuplicateBatchId && !isInternal) {
418
- throw new JsonRpcError(ErrorCode.DuplicateBundleId, 'Batch ID already exists');
419
- }
420
- const dappSuggestedGasFees = this.#generateDappSuggestedGasFees(txParams, origin, isInternal);
421
- const transactionType = type ??
422
- (await determineTransactionType(txParams, {
423
- messenger: this.messenger,
424
- networkClientId,
425
- })).type;
426
- /**
427
- * Original behavior was that this was set to 'true' whenever a gasFeeToken was passed.
428
- * 'excludeNativeTokenForFee' optionally overrides this behavior to prevent native token from
429
- * being used when another gasFeeToken is set.
430
- */
431
- const isGasFeeTokenIgnoredIfBalance = Boolean(gasFeeToken) && !excludeNativeTokenForFee;
432
- let addedTransactionMeta = {
433
- actionId,
434
- assetsFiatValues,
435
- batchId,
436
- chainId,
437
- dappSuggestedGasFees,
438
- deviceConfirmedOn,
439
- disableGasBuffer,
440
- id: random(),
441
- isGasFeeTokenIgnoredIfBalance,
442
- isGasFeeIncluded,
443
- isGasFeeSponsored,
444
- ...(isGasFeeSponsored ? { isExternalSign: true } : {}),
445
- // To avoid the property to be set as undefined.
446
- ...(excludeNativeTokenForFee === undefined
447
- ? {}
448
- : { excludeNativeTokenForFee }),
449
- isFirstTimeInteraction: undefined,
450
- isInternal,
451
- isStateOnly,
452
- nestedTransactions,
453
- networkClientId,
454
- origin,
455
- requestId,
456
- requiredAssets,
457
- securityAlertResponse,
458
- selectedGasFeeToken: gasFeeToken,
459
- status: TransactionStatus.unapproved,
460
- time: Date.now(),
461
- txParams,
462
- type: transactionType,
463
- userEditedGasLimit: false,
464
- verifiedOnBlockchain: false,
465
- };
466
- const { updateTransaction } = await this.#afterAdd({
467
- transactionMeta: addedTransactionMeta,
468
- });
469
- if (updateTransaction) {
470
- log('Updating transaction using afterAdd hook');
471
- addedTransactionMeta.txParamsOriginal = cloneDeep(addedTransactionMeta.txParams);
472
- updateTransaction(addedTransactionMeta);
473
- }
474
- // eslint-disable-next-line no-negated-condition
475
- if (!skipInitialGasEstimate) {
476
- await this.#trace({ name: 'Estimate Gas Properties', parentContext: traceContext }, (context) => this.#updateGasProperties(addedTransactionMeta, {
477
- traceContext: context,
478
- }));
479
- }
480
- else {
481
- const newTransactionMeta = cloneDeep(addedTransactionMeta);
482
- this.#updateGasProperties(newTransactionMeta)
483
- .then(() => {
484
- this.#updateTransactionInternal({
485
- transactionId: newTransactionMeta.id,
486
- skipResimulateCheck: true,
487
- skipValidation: true,
488
- }, (tx) => {
489
- tx.txParams.gas = newTransactionMeta.txParams.gas;
490
- tx.txParams.gasPrice = newTransactionMeta.txParams.gasPrice;
491
- tx.txParams.maxFeePerGas =
492
- newTransactionMeta.txParams.maxFeePerGas;
493
- tx.txParams.maxPriorityFeePerGas =
494
- newTransactionMeta.txParams.maxPriorityFeePerGas;
495
- });
496
- return;
497
- })
498
- .catch(noop);
499
- }
500
- addedTransactionMeta = updateSwapsTransaction(addedTransactionMeta, transactionType, swaps, {
501
- isSwapsDisabled: this.#isSwapsDisabled,
502
- cancelTransaction: this.#rejectTransaction.bind(this),
503
- messenger: this.messenger,
350
+ return await addTransaction({
351
+ addTransactionRequest: { options, txParams },
352
+ constructorOptions: this.#getConstructorOptions(),
353
+ dependencies: this.#getDependencies(),
504
354
  });
505
- this.#addMetadata(addedTransactionMeta);
506
- delegationAddressPromise
507
- .then((delegationAddress) => {
508
- this.#updateTransactionInternal({
509
- transactionId: addedTransactionMeta.id,
510
- skipResimulateCheck: true,
511
- skipValidation: true,
512
- }, (tx) => {
513
- tx.delegationAddress = delegationAddress;
514
- });
515
- return;
516
- })
517
- .catch(noop);
518
- if (requireApproval !== false && !isStateOnly) {
519
- this.#updateSimulationData(addedTransactionMeta, {
520
- traceContext,
521
- }).catch((error) => {
522
- log('Error while updating simulation data', error);
523
- throw error;
524
- });
525
- updateFirstTimeInteraction({
526
- existingTransactions: this.state.transactions,
527
- getTransaction: (transactionId) => this.#getTransaction(transactionId),
528
- isFirstTimeInteractionEnabled: this.#isFirstTimeInteractionEnabled,
529
- trace: this.#trace,
530
- traceContext,
531
- transactionMeta: addedTransactionMeta,
532
- updateTransaction: this.#updateTransactionInternal.bind(this),
533
- }).catch((error) => {
534
- log('Error while updating first interaction properties', error);
535
- });
536
- }
537
- else {
538
- log('Skipping simulation & first interaction update as approval not required');
539
- }
540
- this.messenger.publish(`${controllerName}:unapprovedTransactionAdded`, addedTransactionMeta);
541
- return {
542
- result: this.#processApproval(addedTransactionMeta, {
543
- actionId,
544
- publishHook,
545
- requireApproval,
546
- traceContext,
547
- }),
548
- transactionMeta: addedTransactionMeta,
549
- };
550
355
  }
551
356
  /**
552
357
  * Attempts to cancel a transaction based on its ID by setting its status to "rejected"
@@ -618,7 +423,7 @@ export class TransactionController extends BaseController {
618
423
  prepareTransactionParams?.(newTxParams);
619
424
  const unsignedEthTx = prepareTransaction(transactionMeta.chainId, newTxParams);
620
425
  const signedTxData = await this.messenger.call('KeyringController:signTransaction', unsignedEthTx, transactionMeta.txParams.from);
621
- const transactionMetaWithRsv = this.#updateTransactionMetaRSV(transactionMeta, signedTxData);
426
+ const transactionMetaWithRsv = updateTransactionMetaRSV(transactionMeta, signedTxData);
622
427
  const rawTx = serializeTransaction(transactionMeta.chainId, signedTxData);
623
428
  const newFee = newTxParams.maxFeePerGas ?? newTxParams.gasPrice;
624
429
  const oldFee = newTxParams.maxFeePerGas
@@ -668,10 +473,11 @@ export class TransactionController extends BaseController {
668
473
  * @returns The gas and gas price.
669
474
  */
670
475
  async estimateGas(transaction, networkClientId, { ignoreDelegationSignatures, } = {}) {
476
+ const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, } = this.#options;
671
477
  const { estimatedGas, simulationFails } = await estimateGas({
672
478
  ignoreDelegationSignatures,
673
- isSimulationEnabled: this.#isSimulationEnabled(),
674
- getSimulationConfig: this.#getSimulationConfig,
479
+ isSimulationEnabled: isSimulationEnabled(),
480
+ getSimulationConfig,
675
481
  messenger: this.messenger,
676
482
  networkClientId,
677
483
  txParams: transaction,
@@ -688,9 +494,10 @@ export class TransactionController extends BaseController {
688
494
  * @returns Object containing the gas limit.
689
495
  */
690
496
  async estimateGasBatch({ chainId, from, transactions, }) {
497
+ const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG } = this.#options;
691
498
  return estimateGasBatch({
692
499
  from,
693
- getSimulationConfig: this.#getSimulationConfig,
500
+ getSimulationConfig,
694
501
  isAtomicBatchSupported: this.isAtomicBatchSupported.bind(this),
695
502
  messenger: this.messenger,
696
503
  networkClientId: getNetworkClientId({
@@ -709,9 +516,10 @@ export class TransactionController extends BaseController {
709
516
  * @returns The buffered estimated gas and whether the estimation failed.
710
517
  */
711
518
  async estimateGasBuffered(transaction, multiplier, networkClientId) {
519
+ const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, } = this.#options;
712
520
  const { blockGasLimit, estimatedGas, simulationFails } = await estimateGas({
713
- isSimulationEnabled: this.#isSimulationEnabled(),
714
- getSimulationConfig: this.#getSimulationConfig,
521
+ isSimulationEnabled: isSimulationEnabled(),
522
+ getSimulationConfig,
715
523
  messenger: this.messenger,
716
524
  networkClientId,
717
525
  txParams: transaction,
@@ -889,9 +697,10 @@ export class TransactionController extends BaseController {
889
697
  throw new Error(`Cannot update transaction as no transaction metadata found`);
890
698
  }
891
699
  validateIfTransactionUnapprovedOrSubmitted(transactionMeta, 'updateTransactionGasFees');
700
+ const { isAutomaticGasFeeUpdateEnabled: getIsAutomaticGasFeeUpdateEnabled = DEFAULT_IS_AUTOMATIC_GAS_FEE_UPDATE_ENABLED, } = this.#options;
892
701
  const clonedTransactionMeta = cloneDeep(transactionMeta);
893
702
  const isTransactionGasFeeEstimatesExists = transactionMeta.gasFeeEstimates;
894
- const isAutomaticGasFeeUpdateEnabled = this.#isAutomaticGasFeeUpdateEnabled(transactionMeta);
703
+ const isAutomaticGasFeeUpdateEnabled = getIsAutomaticGasFeeUpdateEnabled(transactionMeta);
895
704
  const userFeeLevel = userFeeLevelParam;
896
705
  const isOneOfFeeLevelSelected = Object.values(GasFeeEstimateLevel).includes(userFeeLevel);
897
706
  const shouldUpdateTxParamsGasFees = isTransactionGasFeeEstimatesExists &&
@@ -1089,10 +898,10 @@ export class TransactionController extends BaseController {
1089
898
  });
1090
899
  const initialTxAsEthTx = prepareTransaction(chainId, initialTx);
1091
900
  const initialTxAsSerializedHex = serializeTransaction(chainId, initialTxAsEthTx);
1092
- if (this.#approvingTransactionIds.has(initialTxAsSerializedHex)) {
901
+ if (isTransactionApproving(this.#getDependencies(), initialTxAsSerializedHex)) {
1093
902
  return '';
1094
903
  }
1095
- this.#approvingTransactionIds.add(initialTxAsSerializedHex);
904
+ const releaseApproval = startTransactionApproval(this.#getDependencies(), initialTxAsSerializedHex);
1096
905
  let rawTransactions, nonceLock;
1097
906
  try {
1098
907
  // TODO: we should add a check to verify that all transactions have the same from address
@@ -1120,7 +929,7 @@ export class TransactionController extends BaseController {
1120
929
  }
1121
930
  finally {
1122
931
  nonceLock?.releaseLock();
1123
- this.#approvingTransactionIds.delete(initialTxAsSerializedHex);
932
+ releaseApproval();
1124
933
  }
1125
934
  return rawTransactions;
1126
935
  }
@@ -1341,16 +1150,7 @@ export class TransactionController extends BaseController {
1341
1150
  * @param transactionId - The ID of the transaction to stop signing.
1342
1151
  */
1343
1152
  abortTransactionSigning(transactionId) {
1344
- const transactionMeta = this.#getTransaction(transactionId);
1345
- if (!transactionMeta) {
1346
- throw new Error(`Cannot abort signing as no transaction metadata found`);
1347
- }
1348
- const abortCallback = this.#signAbortCallbacks.get(transactionId);
1349
- if (!abortCallback) {
1350
- throw new Error(`Cannot abort signing as transaction is not waiting for signing`);
1351
- }
1352
- abortCallback();
1353
- this.#signAbortCallbacks.delete(transactionId);
1153
+ abortTransactionSigning(this.#getDependencies(), transactionId);
1354
1154
  }
1355
1155
  /**
1356
1156
  * Update the transaction data of a single nested transaction within an atomic batch transaction.
@@ -1509,33 +1309,42 @@ export class TransactionController extends BaseController {
1509
1309
  });
1510
1310
  }
1511
1311
  #addMetadata(transactionMeta) {
1512
- validateTxParams(transactionMeta.txParams);
1513
- this.update((state) => {
1514
- state.transactions = this.#trimTransactionsForState([
1515
- ...state.transactions,
1516
- transactionMeta,
1517
- ]);
1518
- });
1312
+ addTransactionToState(this.#getDependencies(), transactionMeta);
1519
1313
  }
1520
- async #updateGasProperties(transactionMeta, { traceContext } = {}) {
1521
- const isEIP1559Compatible = transactionMeta.txParams.type !== TransactionEnvelopeType.legacy &&
1522
- (await this.#getEIP1559Compatibility(transactionMeta.networkClientId));
1523
- await this.#trace({ name: 'Update Gas', parentContext: traceContext }, async () => {
1524
- await this.#updateGasEstimate(transactionMeta);
1525
- });
1526
- await this.#trace({ name: 'Update Gas Fees', parentContext: traceContext }, async () => await updateGasFees({
1527
- eip1559: isEIP1559Compatible,
1314
+ /**
1315
+ * Wire the resources required by the addTransaction lifecycle.
1316
+ *
1317
+ * @returns The dependencies shared by all lifecycle stages.
1318
+ */
1319
+ #getDependencies() {
1320
+ this.#dependencies ??= {
1321
+ addTransactionBatch: this.addTransactionBatch.bind(this),
1322
+ failTransaction: this.#failTransaction.bind(this),
1323
+ fetchGasFeeTokens: async (transactionMeta) => (await this.#getGasFeeTokens(transactionMeta)).gasFeeTokens,
1528
1324
  gasFeeFlows: this.#gasFeeFlows,
1529
- getGasFeeEstimates: (options) => this.messenger.call('GasFeeController:fetchGasFeeEstimates', options),
1530
- getSavedGasFees: this.#getSavedGasFees.bind(this),
1531
- messenger: this.messenger,
1532
- txMeta: transactionMeta,
1533
- }));
1534
- await this.#trace({ name: 'Update Layer 1 Gas Fees', parentContext: traceContext }, async () => await updateTransactionLayer1GasFee({
1325
+ getNonceLock: (address, networkClientId) => this.#multichainTrackingHelper.getNonceLock(address, networkClientId),
1326
+ getState: () => this.state,
1327
+ hasNetworkClient: (networkClientId) => this.#multichainTrackingHelper.has(networkClientId),
1328
+ internalEvents: this.#internalEvents,
1535
1329
  layer1GasFeeFlows: this.#layer1GasFeeFlows,
1536
1330
  messenger: this.messenger,
1537
- transactionMeta,
1538
- }));
1331
+ publishTransaction: this.#publishTransaction.bind(this),
1332
+ skipSimulationTransactionIds: this.#skipSimulationTransactionIds,
1333
+ updateGasEstimate: this.#updateGasEstimate.bind(this),
1334
+ updateSimulationData: this.#updateSimulationData.bind(this),
1335
+ updateState: this.update.bind(this),
1336
+ updateTransaction: this.updateTransaction.bind(this),
1337
+ updateTransactionInternal: this.#updateTransactionInternal.bind(this),
1338
+ };
1339
+ return this.#dependencies;
1340
+ }
1341
+ /**
1342
+ * Narrow the constructor options to those needed by the addTransaction lifecycle.
1343
+ *
1344
+ * @returns The constructor options with the tracer resolved.
1345
+ */
1346
+ #getConstructorOptions() {
1347
+ return { ...this.#options, trace: this.#options.trace ?? DEFAULT_TRACE };
1539
1348
  }
1540
1349
  #onBootCleanup() {
1541
1350
  this.clearUnapprovedTransactions();
@@ -1564,203 +1373,6 @@ export class TransactionController extends BaseController {
1564
1373
  }
1565
1374
  }
1566
1375
  }
1567
- async #processApproval(transactionMeta, { actionId, publishHook, requireApproval, shouldShowRequest = true, traceContext, }) {
1568
- const { id: transactionId, isStateOnly } = transactionMeta;
1569
- if (isStateOnly) {
1570
- this.#updateTransactionInternal({ transactionId, skipValidation: true }, (tx) => {
1571
- tx.status = TransactionStatus.submitted;
1572
- tx.submittedTime = new Date().getTime();
1573
- });
1574
- return '';
1575
- }
1576
- let resultCallbacks;
1577
- const { meta, isCompleted } = this.#isTransactionCompleted(transactionId);
1578
- const finishedPromise = isCompleted
1579
- ? Promise.resolve(meta)
1580
- : this.#waitForTransactionFinished(transactionId);
1581
- if (meta && !isCompleted) {
1582
- try {
1583
- if (requireApproval !== false) {
1584
- const acceptResult = await this.#trace({ name: 'Await Approval', parentContext: traceContext }, (context) => this.#requestApproval(transactionMeta, {
1585
- shouldShowRequest,
1586
- traceContext: context,
1587
- }));
1588
- resultCallbacks = acceptResult.resultCallbacks;
1589
- const approvalValue = acceptResult.value;
1590
- const updatedTransaction = approvalValue?.txMeta;
1591
- if (updatedTransaction) {
1592
- log('Updating transaction with approval data', {
1593
- customNonce: updatedTransaction.customNonceValue,
1594
- params: updatedTransaction.txParams,
1595
- });
1596
- this.updateTransaction(updatedTransaction, 'TransactionController#processApproval - Updated with approval data');
1597
- }
1598
- }
1599
- const { isCompleted: isTxCompleted } = this.#isTransactionCompleted(transactionId);
1600
- if (!isTxCompleted) {
1601
- const approvalResult = await this.#approveTransaction(transactionId, traceContext, publishHook);
1602
- if (approvalResult === ApprovalState.SkippedViaBeforePublishHook &&
1603
- resultCallbacks) {
1604
- resultCallbacks.success();
1605
- }
1606
- const updatedTransactionMeta = this.#getTransaction(transactionId);
1607
- if (approvalResult === ApprovalState.Approved) {
1608
- this.messenger.publish(`${controllerName}:transactionApproved`, {
1609
- transactionMeta: updatedTransactionMeta,
1610
- actionId,
1611
- });
1612
- }
1613
- }
1614
- }
1615
- catch (rawError) {
1616
- const error = rawError;
1617
- const { isCompleted: isTxCompleted } = this.#isTransactionCompleted(transactionId);
1618
- if (!isTxCompleted) {
1619
- if (this.#isRejectError(error)) {
1620
- this.#rejectTransactionAndThrow(transactionId, actionId, error);
1621
- }
1622
- else {
1623
- this.#failTransaction(meta, error, actionId);
1624
- }
1625
- }
1626
- }
1627
- finally {
1628
- this.#skipSimulationTransactionIds.delete(transactionId);
1629
- }
1630
- }
1631
- const finalMeta = await finishedPromise;
1632
- switch (finalMeta?.status) {
1633
- case TransactionStatus.failed: {
1634
- const error = finalMeta.error;
1635
- resultCallbacks?.error(error);
1636
- throw rpcErrors.internal(error.message);
1637
- }
1638
- case TransactionStatus.submitted:
1639
- resultCallbacks?.success();
1640
- return finalMeta.hash;
1641
- default: {
1642
- const internalError = rpcErrors.internal(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finalMeta ?? transactionId)}`);
1643
- resultCallbacks?.error(internalError);
1644
- throw internalError;
1645
- }
1646
- }
1647
- }
1648
- /**
1649
- * Approves a transaction and updates it's status in state. If this is not a
1650
- * retry transaction, a nonce will be generated. The transaction is signed
1651
- * using the sign configuration property, then published to the blockchain.
1652
- * A `<tx.id>:finished` hub event is fired after success or failure.
1653
- *
1654
- * @param transactionId - The ID of the transaction to approve.
1655
- * @param traceContext - The parent context for any new traces.
1656
- * @param publishHookOverride - Custom logic to publish the transaction.
1657
- * @returns The state of the approval.
1658
- */
1659
- async #approveTransaction(transactionId, traceContext, publishHookOverride) {
1660
- let clearApprovingTransactionId;
1661
- let clearNonceLock;
1662
- let transactionMeta = this.#getTransactionOrThrow(transactionId);
1663
- log('Approving transaction', transactionMeta);
1664
- try {
1665
- if (!transactionMeta.chainId) {
1666
- this.#failTransaction(transactionMeta, new Error('No chainId defined.'));
1667
- return ApprovalState.NotApproved;
1668
- }
1669
- if (this.#approvingTransactionIds.has(transactionId)) {
1670
- log('Skipping approval as signing in progress', transactionId);
1671
- return ApprovalState.NotApproved;
1672
- }
1673
- this.#approvingTransactionIds.add(transactionId);
1674
- clearApprovingTransactionId = () => this.#approvingTransactionIds.delete(transactionId);
1675
- const { networkClientId } = transactionMeta;
1676
- const [nonce, releaseNonce] = await getNextNonce(transactionMeta, (address) => this.#multichainTrackingHelper.getNonceLock(address, transactionMeta.networkClientId));
1677
- clearNonceLock = releaseNonce;
1678
- // eslint-disable-next-line require-atomic-updates
1679
- transactionMeta = this.#updateTransactionInternal({
1680
- transactionId,
1681
- }, (draftTxMeta) => {
1682
- const { chainId, txParams } = draftTxMeta;
1683
- const { gas, type } = txParams;
1684
- draftTxMeta.status = TransactionStatus.approved;
1685
- draftTxMeta.txParams.chainId = chainId;
1686
- draftTxMeta.txParams.gasLimit = gas;
1687
- draftTxMeta.txParams.nonce = nonce;
1688
- if (!type && isEIP1559Transaction(txParams)) {
1689
- draftTxMeta.txParams.type = TransactionEnvelopeType.feeMarket;
1690
- }
1691
- });
1692
- this.#onTransactionStatusChange(transactionMeta);
1693
- const rawTx = await this.#trace({ name: 'Sign', parentContext: traceContext }, () => this.#signTransaction(transactionMeta));
1694
- // eslint-disable-next-line require-atomic-updates
1695
- transactionMeta = this.#getTransactionOrThrow(transactionId);
1696
- if (!(await this.#beforePublish(transactionMeta))) {
1697
- log('Skipping publishing transaction based on hook');
1698
- this.messenger.publish(`${controllerName}:transactionPublishingSkipped`, transactionMeta);
1699
- return ApprovalState.SkippedViaBeforePublishHook;
1700
- }
1701
- if (!rawTx && !transactionMeta.isExternalSign) {
1702
- return ApprovalState.NotApproved;
1703
- }
1704
- let preTxBalance;
1705
- const shouldUpdatePreTxBalance = transactionMeta.type === TransactionType.swap;
1706
- if (shouldUpdatePreTxBalance) {
1707
- log('Determining pre-transaction balance');
1708
- preTxBalance = (await rpcRequest({
1709
- messenger: this.messenger,
1710
- networkClientId,
1711
- method: 'eth_getBalance',
1712
- params: [transactionMeta.txParams.from, 'latest'],
1713
- }));
1714
- }
1715
- log('Publishing transaction', transactionMeta.txParams);
1716
- clearNonceLock?.();
1717
- clearNonceLock = undefined;
1718
- let publishHook = this.#defaultPublishHook.bind(this, {
1719
- networkClientId,
1720
- publishHookOverride,
1721
- traceContext,
1722
- });
1723
- if (transactionMeta.batchTransactions?.length) {
1724
- log('Found batch transactions', transactionMeta.batchTransactions);
1725
- const extraTransactionsPublishHook = new ExtraTransactionsPublishHook({
1726
- addTransactionBatch: this.addTransactionBatch.bind(this),
1727
- getTransaction: this.#getTransactionOrThrow.bind(this),
1728
- originalPublishHook: publishHook,
1729
- });
1730
- publishHook = extraTransactionsPublishHook.getHook();
1731
- }
1732
- const { transactionHash: hash } = await publishHook(transactionMeta, rawTx ?? '0x');
1733
- // eslint-disable-next-line require-atomic-updates
1734
- transactionMeta = this.#updateTransactionInternal({
1735
- transactionId,
1736
- }, (draftTxMeta) => {
1737
- draftTxMeta.hash = hash;
1738
- draftTxMeta.status = TransactionStatus.submitted;
1739
- draftTxMeta.submittedTime ??= new Date().getTime();
1740
- if (shouldUpdatePreTxBalance) {
1741
- draftTxMeta.preTxBalance = preTxBalance;
1742
- log('Updated pre-transaction balance', preTxBalance);
1743
- }
1744
- });
1745
- this.messenger.publish(`${controllerName}:transactionSubmitted`, {
1746
- transactionMeta,
1747
- });
1748
- this.messenger.publish(`${controllerName}:transactionFinished`, transactionMeta);
1749
- this.#internalEvents.emit(`${transactionId}:finished`, transactionMeta);
1750
- this.#onTransactionStatusChange(transactionMeta);
1751
- return ApprovalState.Approved;
1752
- // TODO: Replace `any` with type
1753
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1754
- }
1755
- catch (error) {
1756
- this.#failTransaction(transactionMeta, error);
1757
- return ApprovalState.NotApproved;
1758
- }
1759
- finally {
1760
- clearApprovingTransactionId?.();
1761
- clearNonceLock?.();
1762
- }
1763
- }
1764
1376
  async #publishTransaction(transactionMeta, { skipSubmitHistory } = {}) {
1765
1377
  const { networkClientId, rawTx } = transactionMeta;
1766
1378
  if (!rawTx) {
@@ -1777,33 +1389,6 @@ export class TransactionController extends BaseController {
1777
1389
  }
1778
1390
  return transactionHash;
1779
1391
  }
1780
- /**
1781
- * Rejects a transaction based on its ID by setting its status to "rejected"
1782
- * and emitting a `<tx.id>:finished` hub event.
1783
- *
1784
- * @param transactionId - The ID of the transaction to cancel.
1785
- * @param actionId - Unique ID persisted on transaction metadata.
1786
- * @param error - The error that caused the rejection.
1787
- */
1788
- #rejectTransaction(transactionId, actionId, error) {
1789
- const transactionMeta = this.#getTransaction(transactionId);
1790
- if (!transactionMeta) {
1791
- return;
1792
- }
1793
- this.#deleteTransaction(transactionId);
1794
- const updatedTransactionMeta = {
1795
- ...transactionMeta,
1796
- status: TransactionStatus.rejected,
1797
- error: normalizeTxError(error ?? providerErrors.userRejectedRequest()),
1798
- };
1799
- this.messenger.publish(`${controllerName}:transactionFinished`, updatedTransactionMeta);
1800
- this.#internalEvents.emit(`${transactionMeta.id}:finished`, updatedTransactionMeta);
1801
- this.messenger.publish(`${controllerName}:transactionRejected`, {
1802
- transactionMeta: updatedTransactionMeta,
1803
- actionId,
1804
- });
1805
- this.#onTransactionStatusChange(updatedTransactionMeta);
1806
- }
1807
1392
  /**
1808
1393
  * Trim the amount of transactions that are set on the state. Checks
1809
1394
  * if the length of the tx history is longer then desired persistence
@@ -1819,30 +1404,7 @@ export class TransactionController extends BaseController {
1819
1404
  * @returns The trimmed list of transactions.
1820
1405
  */
1821
1406
  #trimTransactionsForState(transactions) {
1822
- const transactionHistoryLimit = getTransactionHistoryLimit(this.messenger);
1823
- if (transactionHistoryLimit === undefined) {
1824
- return transactions;
1825
- }
1826
- const nonceNetworkSet = new Set();
1827
- const txsToKeep = [...transactions]
1828
- .sort((a, b) => (a.time > b.time ? -1 : 1)) // Descending time order
1829
- .filter((tx) => {
1830
- const { chainId, status, txParams, time } = tx;
1831
- if (txParams) {
1832
- const key = `${String(txParams.nonce)}-${convertHexToDecimal(chainId)}-${new Date(time).toDateString()}`;
1833
- if (nonceNetworkSet.has(key)) {
1834
- return true;
1835
- }
1836
- else if (nonceNetworkSet.size < transactionHistoryLimit ||
1837
- !this.#isFinalState(status)) {
1838
- nonceNetworkSet.add(key);
1839
- return true;
1840
- }
1841
- }
1842
- return false;
1843
- });
1844
- txsToKeep.reverse(); // Ascending time order
1845
- return txsToKeep;
1407
+ return trimTransactionsForState(transactions, this.messenger);
1846
1408
  }
1847
1409
  /**
1848
1410
  * Determines if the transaction is in a final state.
@@ -1851,89 +1413,13 @@ export class TransactionController extends BaseController {
1851
1413
  * @returns Whether the transaction is in a final state.
1852
1414
  */
1853
1415
  #isFinalState(status) {
1854
- return (status === TransactionStatus.rejected ||
1855
- status === TransactionStatus.confirmed ||
1856
- status === TransactionStatus.failed ||
1857
- status === TransactionStatus.dropped);
1858
- }
1859
- /**
1860
- * Whether the transaction has at least completed all local processing.
1861
- *
1862
- * @param status - The transaction status.
1863
- * @returns Whether the transaction is in a final state.
1864
- */
1865
- #isLocalFinalState(status) {
1866
- return [
1867
- TransactionStatus.confirmed,
1868
- TransactionStatus.failed,
1869
- TransactionStatus.rejected,
1870
- TransactionStatus.submitted,
1871
- ].includes(status);
1872
- }
1873
- async #requestApproval(txMeta, { shouldShowRequest, traceContext, }) {
1874
- const id = this.#getApprovalId(txMeta);
1875
- const { origin } = txMeta;
1876
- const type = ApprovalType.Transaction;
1877
- const requestData = { txId: txMeta.id };
1878
- await this.#trace({
1879
- name: 'Notification Display',
1880
- id,
1881
- parentContext: traceContext,
1882
- });
1883
- return (await this.messenger.call('ApprovalController:addRequest', {
1884
- id,
1885
- origin: origin ?? ORIGIN_METAMASK,
1886
- type,
1887
- requestData,
1888
- expectsResult: true,
1889
- }, shouldShowRequest));
1416
+ return isFinalState(status);
1890
1417
  }
1891
1418
  #getTransaction(transactionId) {
1892
- const { transactions } = this.state;
1893
- return transactions.find(({ id }) => id === transactionId);
1419
+ return getTransaction(this.state, transactionId);
1894
1420
  }
1895
1421
  #getTransactionOrThrow(transactionId, errorMessagePrefix = 'TransactionController') {
1896
- const txMeta = this.#getTransaction(transactionId);
1897
- if (!txMeta) {
1898
- throw new Error(`${errorMessagePrefix}: No transaction found with id ${transactionId}`);
1899
- }
1900
- return txMeta;
1901
- }
1902
- #getApprovalId(txMeta) {
1903
- return String(txMeta.id);
1904
- }
1905
- #isTransactionCompleted(transactionId) {
1906
- const transaction = this.#getTransaction(transactionId);
1907
- if (!transaction) {
1908
- return { meta: undefined, isCompleted: false };
1909
- }
1910
- const isCompleted = this.#isLocalFinalState(transaction.status);
1911
- return { meta: transaction, isCompleted };
1912
- }
1913
- #generateDappSuggestedGasFees(txParams, origin, isInternal) {
1914
- if (isInternal || !origin) {
1915
- return undefined;
1916
- }
1917
- const { gasPrice, maxFeePerGas, maxPriorityFeePerGas, gas } = txParams;
1918
- if (gasPrice === undefined &&
1919
- maxFeePerGas === undefined &&
1920
- maxPriorityFeePerGas === undefined &&
1921
- gas === undefined) {
1922
- return undefined;
1923
- }
1924
- const dappSuggestedGasFees = {};
1925
- if (gasPrice !== undefined) {
1926
- dappSuggestedGasFees.gasPrice = gasPrice;
1927
- }
1928
- else if (maxFeePerGas !== undefined ||
1929
- maxPriorityFeePerGas !== undefined) {
1930
- dappSuggestedGasFees.maxFeePerGas = maxFeePerGas;
1931
- dappSuggestedGasFees.maxPriorityFeePerGas = maxPriorityFeePerGas;
1932
- }
1933
- if (gas !== undefined) {
1934
- dappSuggestedGasFees.gas = gas;
1935
- }
1936
- return dappSuggestedGasFees;
1422
+ return getTransactionOrThrow(this.state, transactionId, errorMessagePrefix);
1937
1423
  }
1938
1424
  /**
1939
1425
  * Validates and adds external provided transaction to state.
@@ -2014,99 +1500,6 @@ export class TransactionController extends BaseController {
2014
1500
  this.updateTransaction(updatedTransactionMeta, 'TransactionController#setTransactionStatusDropped - Transaction dropped');
2015
1501
  this.#onTransactionStatusChange(updatedTransactionMeta);
2016
1502
  }
2017
- async #waitForTransactionFinished(transactionId) {
2018
- return new Promise((resolve) => {
2019
- this.#internalEvents.once(`${transactionId}:finished`, (txMeta) => {
2020
- resolve(txMeta);
2021
- });
2022
- });
2023
- }
2024
- /**
2025
- * Updates the r, s, and v properties of a TransactionMeta object
2026
- * with values from a signed transaction.
2027
- *
2028
- * @param transactionMeta - The TransactionMeta object to update.
2029
- * @param signedTx - The encompassing type for all transaction types containing r, s, and v values.
2030
- * @returns The updated TransactionMeta object.
2031
- */
2032
- #updateTransactionMetaRSV(transactionMeta, signedTx) {
2033
- const transactionMetaWithRsv = cloneDeep(transactionMeta);
2034
- for (const key of ['r', 's', 'v']) {
2035
- const value = signedTx[key];
2036
- if (value === undefined || value === null) {
2037
- continue;
2038
- }
2039
- transactionMetaWithRsv[key] = add0x(BigInt(value).toString(16));
2040
- }
2041
- return transactionMetaWithRsv;
2042
- }
2043
- async #getEIP1559Compatibility(networkClientId) {
2044
- return ((await this.messenger.call('NetworkController:getEIP1559Compatibility', networkClientId)) ?? false);
2045
- }
2046
- async #signTransaction(originalTransactionMeta) {
2047
- let transactionMeta = originalTransactionMeta;
2048
- const { id: transactionId } = transactionMeta;
2049
- log('Calling before sign hook', transactionMeta);
2050
- const { updateTransaction } = (await this.#beforeSign({ transactionMeta })) ?? {};
2051
- if (updateTransaction) {
2052
- this.#updateTransactionInternal({ transactionId, skipResimulateCheck: true }, updateTransaction);
2053
- log('Updated transaction after before sign hook');
2054
- }
2055
- transactionMeta = this.#getTransactionOrThrow(transactionId);
2056
- const { networkClientId } = transactionMeta;
2057
- await checkGasFeeTokenBeforePublish({
2058
- messenger: this.messenger,
2059
- networkClientId,
2060
- fetchGasFeeTokens: async (tx) => (await this.#getGasFeeTokens(tx)).gasFeeTokens,
2061
- transaction: transactionMeta,
2062
- updateTransaction: (txId, fn) => this.#updateTransactionInternal({ transactionId: txId }, fn),
2063
- });
2064
- transactionMeta = this.#getTransactionOrThrow(transactionId);
2065
- const { chainId, isExternalSign, txParams } = transactionMeta;
2066
- if (isExternalSign) {
2067
- log('Skipping sign as signed externally');
2068
- return undefined;
2069
- }
2070
- const { authorizationList, from } = txParams;
2071
- const signedAuthorizationList = await signAuthorizationList({
2072
- authorizationList,
2073
- messenger: this.messenger,
2074
- transactionMeta,
2075
- });
2076
- if (signedAuthorizationList) {
2077
- this.#updateTransactionInternal({ transactionId }, (txMeta) => {
2078
- txMeta.txParams.authorizationList = signedAuthorizationList;
2079
- });
2080
- }
2081
- transactionMeta = this.#getTransactionOrThrow(transactionId);
2082
- const finalTransactionMeta = this.#getTransactionOrThrow(transactionId);
2083
- const { txParams: finalTxParams } = finalTransactionMeta;
2084
- const unsignedEthTx = prepareTransaction(chainId, finalTxParams);
2085
- this.#approvingTransactionIds.add(transactionId);
2086
- log('Signing transaction', finalTxParams);
2087
- const signedTxData = await new Promise((resolve, reject) => {
2088
- // eslint-disable-next-line promise/catch-or-return
2089
- this.messenger
2090
- .call('KeyringController:signTransaction', unsignedEthTx, from)
2091
- .then(resolve, reject);
2092
- this.#signAbortCallbacks.set(transactionId, () => reject(new Error('Signing aborted by user')));
2093
- });
2094
- this.#signAbortCallbacks.delete(transactionId);
2095
- const transactionMetaFromHook = cloneDeep(finalTransactionMeta);
2096
- const transactionMetaWithRsv = {
2097
- ...this.#updateTransactionMetaRSV(transactionMetaFromHook, signedTxData),
2098
- status: TransactionStatus.signed,
2099
- txParams: finalTxParams,
2100
- };
2101
- this.updateTransaction(transactionMetaWithRsv, 'TransactionController#approveTransaction - Transaction signed');
2102
- this.#onTransactionStatusChange(transactionMetaWithRsv);
2103
- const rawTx = serializeTransaction(chainId, signedTxData);
2104
- const transactionMetaWithRawTx = merge({}, transactionMetaWithRsv, {
2105
- rawTx,
2106
- });
2107
- this.updateTransaction(transactionMetaWithRawTx, 'TransactionController#approveTransaction - RawTransaction added');
2108
- return rawTx;
2109
- }
2110
1503
  #onTransactionStatusChange(transactionMeta) {
2111
1504
  this.messenger.publish(`${controllerName}:transactionStatusUpdated`, {
2112
1505
  transactionMeta,
@@ -2160,7 +1553,11 @@ export class TransactionController extends BaseController {
2160
1553
  });
2161
1554
  }
2162
1555
  #createPendingTransactionTracker({ blockTracker, networkClientId, }) {
2163
- const chainId = getChainId({ messenger: this.messenger, networkClientId });
1556
+ const chainId = getChainId({
1557
+ messenger: this.messenger,
1558
+ networkClientId,
1559
+ });
1560
+ const { hooks, isTimeoutEnabled = DEFAULT_IS_TIMEOUT_ENABLED } = this.#options;
2164
1561
  const pendingTransactionTracker = new PendingTransactionTracker({
2165
1562
  blockTracker,
2166
1563
  getGlobalLock: () => this.#multichainTrackingHelper.acquireNonceLockForChainIdKey({
@@ -2168,9 +1565,9 @@ export class TransactionController extends BaseController {
2168
1565
  }),
2169
1566
  getTransactions: () => this.state.transactions,
2170
1567
  hooks: {
2171
- beforeCheckPendingTransaction: this.#beforeCheckPendingTransaction.bind(this),
1568
+ beforeCheckPendingTransaction: hooks?.beforeCheckPendingTransaction?.bind(this),
2172
1569
  },
2173
- isTimeoutEnabled: this.#isTimeoutEnabled,
1570
+ isTimeoutEnabled,
2174
1571
  messenger: this.messenger,
2175
1572
  networkClientId,
2176
1573
  });
@@ -2231,7 +1628,7 @@ export class TransactionController extends BaseController {
2231
1628
  Boolean(error?.data?.message?.includes('nonce too low')));
2232
1629
  }
2233
1630
  #getGasFeeFlows() {
2234
- if (this.#testGasFeeFlows) {
1631
+ if (this.#options.testGasFeeFlows) {
2235
1632
  return [new TestGasFeeFlow()];
2236
1633
  }
2237
1634
  return [
@@ -2248,6 +1645,7 @@ export class TransactionController extends BaseController {
2248
1645
  ];
2249
1646
  }
2250
1647
  #updateTransactionInternal({ transactionId, skipValidation, skipResimulateCheck, }, callback) {
1648
+ const { isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, isTransactionTrusted = DEFAULT_IS_TRANSACTION_TRUSTED, } = this.#options;
2251
1649
  let resimulateResponse;
2252
1650
  this.update((state) => {
2253
1651
  const index = state.transactions.findIndex(({ id }) => id === transactionId);
@@ -2261,8 +1659,8 @@ export class TransactionController extends BaseController {
2261
1659
  transactionMeta.txParams = normalizeTransactionParams(transactionMeta.txParams);
2262
1660
  validateTxParams(transactionMeta.txParams);
2263
1661
  }
2264
- if (!skipResimulateCheck && this.#isSimulationEnabled(transactionMeta)) {
2265
- resimulateResponse = shouldResimulate(originalTransactionMeta, transactionMeta, this.#isTransactionTrusted(transactionMeta));
1662
+ if (!skipResimulateCheck && isSimulationEnabled(transactionMeta)) {
1663
+ resimulateResponse = shouldResimulate(originalTransactionMeta, transactionMeta, isTransactionTrusted(transactionMeta));
2266
1664
  }
2267
1665
  state.transactions[index] = transactionMeta;
2268
1666
  });
@@ -2297,21 +1695,20 @@ export class TransactionController extends BaseController {
2297
1695
  let simulationRevert;
2298
1696
  const simulationRequestToken = Symbol(transactionId);
2299
1697
  this.#simulationRequestTokens.set(transactionId, simulationRequestToken);
1698
+ const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isSimulationEnabled: getIsSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, trace = DEFAULT_TRACE, } = this.#options;
2300
1699
  try {
2301
- const isSimulationEnabled = this.#isSimulationEnabled(transactionMeta);
1700
+ const isSimulationEnabled = getIsSimulationEnabled(transactionMeta);
2302
1701
  const isBalanceChangesSkipped = this.#isBalanceChangesSkipped(transactionMeta);
2303
1702
  if (isSimulationEnabled && !isBalanceChangesSkipped) {
2304
- const balanceChangesResult = await this.#trace({ name: 'Simulate', parentContext: traceContext }, () => getBalanceChanges({
1703
+ const balanceChangesResult = await trace({ name: 'Simulate', parentContext: traceContext }, () => getBalanceChanges({
2305
1704
  blockTime,
2306
1705
  chainId,
2307
1706
  messenger: this.messenger,
2308
1707
  networkClientId,
2309
- getSimulationConfig: (url, opts) => {
2310
- return this.#getSimulationConfig(url, {
2311
- txMeta: transactionMeta,
2312
- ...opts,
2313
- });
2314
- },
1708
+ getSimulationConfig: (url, opts) => getSimulationConfig(url, {
1709
+ txMeta: transactionMeta,
1710
+ ...opts,
1711
+ }),
2315
1712
  nestedTransactions,
2316
1713
  txParams,
2317
1714
  }));
@@ -2378,12 +1775,13 @@ export class TransactionController extends BaseController {
2378
1775
  }
2379
1776
  }
2380
1777
  #onGasFeePollerTransactionUpdate({ transactionId, gasFeeEstimates, gasFeeEstimatesLoaded, layer1GasFee, }) {
1778
+ const { isAutomaticGasFeeUpdateEnabled: isTxParamsGasFeeUpdatesEnabled = DEFAULT_IS_AUTOMATIC_GAS_FEE_UPDATE_ENABLED, } = this.#options;
2381
1779
  this.#updateTransactionInternal({ transactionId }, (txMeta) => {
2382
1780
  updateTransactionGasProperties({
2383
1781
  txMeta,
2384
1782
  gasFeeEstimates,
2385
1783
  gasFeeEstimatesLoaded,
2386
- isTxParamsGasFeeUpdatesEnabled: this.#isAutomaticGasFeeUpdateEnabled,
1784
+ isTxParamsGasFeeUpdatesEnabled,
2387
1785
  layer1GasFee,
2388
1786
  });
2389
1787
  });
@@ -2441,10 +1839,11 @@ export class TransactionController extends BaseController {
2441
1839
  const { networkClientId } = transactionMeta;
2442
1840
  const isCustomNetwork = this.#multichainTrackingHelper.getNetworkClient({ networkClientId })
2443
1841
  .configuration.type === NetworkClientType.Custom;
1842
+ const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, } = this.#options;
2444
1843
  await updateGas({
2445
1844
  isCustomNetwork,
2446
- isSimulationEnabled: this.#isSimulationEnabled(transactionMeta),
2447
- getSimulationConfig: this.#getSimulationConfig,
1845
+ isSimulationEnabled: isSimulationEnabled(transactionMeta),
1846
+ getSimulationConfig,
2448
1847
  messenger: this.messenger,
2449
1848
  txMeta: transactionMeta,
2450
1849
  });
@@ -2452,28 +1851,6 @@ export class TransactionController extends BaseController {
2452
1851
  #registerActionHandlers() {
2453
1852
  this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
2454
1853
  }
2455
- #deleteTransaction(transactionId) {
2456
- this.update((state) => {
2457
- const transactions = state.transactions.filter(({ id }) => id !== transactionId);
2458
- state.transactions = this.#trimTransactionsForState(transactions);
2459
- });
2460
- }
2461
- #isRejectError(error) {
2462
- return [
2463
- errorCodes.provider.userRejectedRequest,
2464
- ErrorCode.RejectedUpgrade,
2465
- ].includes(error.code);
2466
- }
2467
- #rejectTransactionAndThrow(transactionId, actionId, error) {
2468
- this.#rejectTransaction(transactionId, actionId, error);
2469
- if (error.code === errorCodes.provider.userRejectedRequest) {
2470
- throw providerErrors.userRejectedRequest({
2471
- message: 'MetaMask Tx Signature: User denied transaction signature.',
2472
- data: error?.data,
2473
- });
2474
- }
2475
- throw error;
2476
- }
2477
1854
  #failTransaction(transactionMeta, error, actionId) {
2478
1855
  let newTransactionMeta;
2479
1856
  const { revert: receiptRevert } = error;
@@ -2519,29 +1896,15 @@ export class TransactionController extends BaseController {
2519
1896
  this.messenger.publish(`${controllerName}:transactionFinished`, newTransactionMeta);
2520
1897
  this.#internalEvents.emit(`${transactionMeta.id}:finished`, newTransactionMeta);
2521
1898
  }
2522
- async #defaultPublishHook({ networkClientId, publishHookOverride, traceContext, }, transactionMeta, signedTx) {
2523
- let transactionHash;
2524
- await this.#trace({ name: 'Publish', parentContext: traceContext }, async () => {
2525
- const publishHook = publishHookOverride ?? this.#publish;
2526
- ({ transactionHash } = await publishHook(transactionMeta, signedTx));
2527
- // eslint-disable-next-line require-atomic-updates
2528
- transactionHash ??= await this.#publishTransaction({
2529
- ...transactionMeta,
2530
- networkClientId,
2531
- rawTx: signedTx,
2532
- });
2533
- });
2534
- log('Publish successful', transactionHash);
2535
- return { transactionHash };
2536
- }
2537
1899
  async #getGasFeeTokens(transaction) {
2538
1900
  const { chainId } = transaction;
1901
+ const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isEIP7702GasFeeTokensEnabled = DEFAULT_IS_EIP7702_GAS_FEE_TOKENS_ENABLED, publicKeyEIP7702, } = this.#options;
2539
1902
  return await getGasFeeTokens({
2540
1903
  chainId,
2541
- getSimulationConfig: this.#getSimulationConfig,
2542
- isEIP7702GasFeeTokensEnabled: this.#isEIP7702GasFeeTokensEnabled,
1904
+ getSimulationConfig,
1905
+ isEIP7702GasFeeTokensEnabled,
2543
1906
  messenger: this.messenger,
2544
- publicKeyEIP7702: this.#publicKeyEIP7702,
1907
+ publicKeyEIP7702,
2545
1908
  transactionMeta: transaction,
2546
1909
  });
2547
1910
  }