@metamask-previews/transaction-controller 74.0.0-preview-197d3fef0 → 74.0.0-preview-df8dca72c

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 +0 -1
  2. package/dist/TransactionController.d.ts +2 -2
  3. package/dist/TransactionController.d.ts.map +1 -1
  4. package/dist/TransactionController.js +763 -126
  5. package/dist/TransactionController.js.map +1 -1
  6. package/dist/logger.d.ts +0 -1
  7. package/dist/logger.d.ts.map +1 -1
  8. package/dist/logger.js +0 -1
  9. package/dist/logger.js.map +1 -1
  10. package/package.json +1 -1
  11. package/dist/actions/addTransaction.d.ts +0 -10
  12. package/dist/actions/addTransaction.d.ts.map +0 -1
  13. package/dist/actions/addTransaction.js +0 -37
  14. package/dist/actions/addTransaction.js.map +0 -1
  15. package/dist/lifecycle/add.d.ts +0 -12
  16. package/dist/lifecycle/add.d.ts.map +0 -1
  17. package/dist/lifecycle/add.js +0 -20
  18. package/dist/lifecycle/add.js.map +0 -1
  19. package/dist/lifecycle/approval.d.ts +0 -11
  20. package/dist/lifecycle/approval.d.ts.map +0 -1
  21. package/dist/lifecycle/approval.js +0 -89
  22. package/dist/lifecycle/approval.js.map +0 -1
  23. package/dist/lifecycle/approve.d.ts +0 -8
  24. package/dist/lifecycle/approve.d.ts.map +0 -1
  25. package/dist/lifecycle/approve.js +0 -53
  26. package/dist/lifecycle/approve.js.map +0 -1
  27. package/dist/lifecycle/background.d.ts +0 -15
  28. package/dist/lifecycle/background.d.ts.map +0 -1
  29. package/dist/lifecycle/background.js +0 -66
  30. package/dist/lifecycle/background.js.map +0 -1
  31. package/dist/lifecycle/data.d.ts +0 -18
  32. package/dist/lifecycle/data.d.ts.map +0 -1
  33. package/dist/lifecycle/data.js +0 -165
  34. package/dist/lifecycle/data.js.map +0 -1
  35. package/dist/lifecycle/error.d.ts +0 -36
  36. package/dist/lifecycle/error.d.ts.map +0 -1
  37. package/dist/lifecycle/error.js +0 -106
  38. package/dist/lifecycle/error.js.map +0 -1
  39. package/dist/lifecycle/finish.d.ts +0 -12
  40. package/dist/lifecycle/finish.d.ts.map +0 -1
  41. package/dist/lifecycle/finish.js +0 -41
  42. package/dist/lifecycle/finish.js.map +0 -1
  43. package/dist/lifecycle/init.d.ts +0 -27
  44. package/dist/lifecycle/init.d.ts.map +0 -1
  45. package/dist/lifecycle/init.js +0 -197
  46. package/dist/lifecycle/init.js.map +0 -1
  47. package/dist/lifecycle/sign.d.ts +0 -35
  48. package/dist/lifecycle/sign.d.ts.map +0 -1
  49. package/dist/lifecycle/sign.js +0 -150
  50. package/dist/lifecycle/sign.js.map +0 -1
  51. package/dist/lifecycle/state.d.ts +0 -45
  52. package/dist/lifecycle/state.d.ts.map +0 -1
  53. package/dist/lifecycle/state.js +0 -56
  54. package/dist/lifecycle/state.js.map +0 -1
  55. package/dist/lifecycle/submit.d.ts +0 -8
  56. package/dist/lifecycle/submit.d.ts.map +0 -1
  57. package/dist/lifecycle/submit.js +0 -169
  58. package/dist/lifecycle/submit.js.map +0 -1
  59. package/dist/lifecycle/types.d.ts +0 -68
  60. package/dist/lifecycle/types.d.ts.map +0 -1
  61. package/dist/lifecycle/types.js +0 -2
  62. package/dist/lifecycle/types.js.map +0 -1
  63. package/dist/utils/state.d.ts +0 -56
  64. package/dist/utils/state.d.ts.map +0 -1
  65. package/dist/utils/state.js +0 -104
  66. package/dist/utils/state.js.map +0 -1
@@ -1,13 +1,14 @@
1
1
  import { BaseController } from '@metamask/base-controller';
2
+ import { ApprovalType, ORIGIN_METAMASK, convertHexToDecimal, } from '@metamask/controller-utils';
2
3
  import { NetworkClientType } from '@metamask/network-controller';
3
4
  import { NonceTracker } from '@metamask/nonce-tracker';
5
+ import { errorCodes, rpcErrors, providerErrors, JsonRpcError, } from '@metamask/rpc-errors';
4
6
  import { add0x } from '@metamask/utils';
5
7
  // This package purposefully relies on Node's EventEmitter module.
6
8
  // eslint-disable-next-line import-x/no-nodejs-modules
7
9
  import { EventEmitter } from 'events';
8
10
  import { cloneDeep, mapValues, merge, noop, pickBy, sortBy } from 'lodash-es';
9
11
  import { v1 as random } from 'uuid';
10
- import { addTransaction } from './actions/addTransaction.js';
11
12
  import { DefaultGasFeeFlow } from './gas-flows/DefaultGasFeeFlow.js';
12
13
  import { LineaGasFeeFlow } from './gas-flows/LineaGasFeeFlow.js';
13
14
  import { MantleLayer1GasFeeFlow } from './gas-flows/MantleLayer1GasFeeFlow.js';
@@ -15,34 +16,33 @@ import { OptimismLayer1GasFeeFlow } from './gas-flows/OptimismLayer1GasFeeFlow.j
15
16
  import { RandomisedEstimationsGasFeeFlow } from './gas-flows/RandomisedEstimationsGasFeeFlow.js';
16
17
  import { ScrollLayer1GasFeeFlow } from './gas-flows/ScrollLayer1GasFeeFlow.js';
17
18
  import { TestGasFeeFlow } from './gas-flows/TestGasFeeFlow.js';
18
- import { GasFeePoller, updateTransactionGasEstimates, updateTransactionGasProperties, } from './helpers/GasFeePoller.js';
19
+ import { GasFeePoller, updateTransactionGasProperties, updateTransactionGasEstimates, } from './helpers/GasFeePoller.js';
19
20
  import { MethodDataHelper } from './helpers/MethodDataHelper.js';
20
21
  import { MultichainTrackingHelper } from './helpers/MultichainTrackingHelper.js';
21
22
  import { PendingTransactionTracker } from './helpers/PendingTransactionTracker.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';
23
+ import { ResimulateHelper, hasSimulationDataChanged, shouldResimulate, } from './helpers/ResimulateHelper.js';
24
+ import { ExtraTransactionsPublishHook } from './hooks/ExtraTransactionsPublishHook.js';
26
25
  import { projectLogger as log } from './logger.js';
27
- import { GasFeeEstimateLevel, SimulationErrorCode, TransactionContainerType, TransactionEnvelopeType, TransactionStatus, TransactionType, } from './types.js';
26
+ import { GasFeeEstimateLevel, TransactionContainerType, TransactionEnvelopeType, TransactionType, TransactionStatus, SimulationErrorCode, } from './types.js';
28
27
  import { getBalanceChanges } from './utils/balance-changes.js';
29
28
  import { addTransactionBatch, isAtomicBatchSupported } from './utils/batch.js';
30
- import { getDelegationAddress, updateEIP7702BatchData, } from './utils/eip7702.js';
29
+ import { getDelegationAddress, signAuthorizationList, updateEIP7702BatchData, } from './utils/eip7702.js';
31
30
  import { validateConfirmedExternalTransaction } from './utils/external-transactions.js';
32
- import { getSubmitHistoryLimit } from './utils/feature-flags.js';
33
- import { getGasFeeTokens } from './utils/gas-fee-tokens.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';
34
35
  import { getGasFeeFlow } from './utils/gas-flow.js';
35
36
  import { addGasBuffer, estimateGas, estimateGasBatch, updateGas, } from './utils/gas.js';
36
37
  import { getTransactionLayer1GasFee, updateTransactionLayer1GasFee, } from './utils/layer1-gas-fee-flow.js';
37
- import { getAndFormatTransactionsForNonceTracker } from './utils/nonce.js';
38
+ import { getAndFormatTransactionsForNonceTracker, getNextNonce, } from './utils/nonce.js';
38
39
  import { prepareTransaction, serializeTransaction } from './utils/prepare.js';
39
40
  import { getChainId, getNetworkClientId, rpcRequest, } from './utils/provider.js';
40
41
  import { getTransactionParamsWithIncreasedGasFee } from './utils/retry.js';
41
- import { getTransaction, getTransactionOrThrow, isFinalState, trimTransactionsForState, } from './utils/state.js';
42
- import { updatePostTransactionBalance } from './utils/swaps.js';
42
+ import { updatePostTransactionBalance, updateSwapsTransaction, } from './utils/swaps.js';
43
43
  import { determineTransactionType } from './utils/transaction-type.js';
44
- import { isEIP1559Transaction, normalizeGasFeeValues, normalizeTransactionParams, normalizeTxError, validateGasValues, validateIfTransactionUnapproved, validateIfTransactionUnapprovedOrSubmitted, } from './utils/utils.js';
45
- import { validateTxParams } from './utils/validation.js';
44
+ import { normalizeTransactionParams, isEIP1559Transaction, validateGasValues, validateIfTransactionUnapproved, validateIfTransactionUnapprovedOrSubmitted, normalizeTxError, normalizeGasFeeValues, setEnvelopeType, } from './utils/utils.js';
45
+ import { ErrorCode, validateTransactionOrigin, 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,20 +93,6 @@ 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?.());
110
96
  /**
111
97
  * The name of the {@link TransactionController}.
112
98
  */
@@ -176,22 +162,41 @@ const MESSENGER_EXPOSED_METHODS = [
176
162
  * Controller responsible for submitting and managing transactions.
177
163
  */
178
164
  export class TransactionController extends BaseController {
165
+ #afterAdd;
166
+ #approvingTransactionIds = new Set();
167
+ #beforeCheckPendingTransaction;
168
+ #beforePublish;
169
+ #beforeSign;
179
170
  #gasFeeFlows;
171
+ #getPermittedAccounts;
172
+ #getSavedGasFees;
173
+ #getSimulationConfig;
180
174
  #internalEvents = new EventEmitter();
175
+ #isAutomaticGasFeeUpdateEnabled;
176
+ #isEIP7702GasFeeTokensEnabled;
177
+ #isFirstTimeInteractionEnabled;
178
+ #isSimulationEnabled;
179
+ #isTransactionTrusted;
180
+ #isSwapsDisabled;
181
+ #isTimeoutEnabled;
181
182
  #layer1GasFeeFlows;
182
183
  #methodDataHelper;
183
184
  #multichainTrackingHelper;
184
- #options;
185
+ #publicKeyEIP7702;
186
+ #publish;
187
+ #publishBatchHook;
188
+ #signAbortCallbacks = new Map();
185
189
  #skipSimulationTransactionIds = new Set();
186
190
  #simulationRequestTokens = new Map();
187
- #dependencies;
191
+ #testGasFeeFlows;
192
+ #trace;
188
193
  /**
189
194
  * Constructs a TransactionController.
190
195
  *
191
196
  * @param options - The controller options.
192
197
  */
193
198
  constructor(options) {
194
- const { hooks, messenger, state, ...remainingOptions } = options;
199
+ const { disableSwaps, getPermittedAccounts, getSavedGasFees, getSimulationConfig, hooks, isAutomaticGasFeeUpdateEnabled, isEIP7702GasFeeTokensEnabled, isFirstTimeInteractionEnabled, isSimulationEnabled, isTransactionTrusted, isTimeoutEnabled, messenger, publicKeyEIP7702, state, testGasFeeFlows, trace, } = options;
195
200
  super({
196
201
  name: controllerName,
197
202
  metadata,
@@ -202,11 +207,43 @@ export class TransactionController extends BaseController {
202
207
  },
203
208
  });
204
209
  this.messenger = messenger;
205
- this.#options = {
206
- ...remainingOptions,
207
- getSavedGasFees: remainingOptions.getSavedGasFees?.bind(this),
208
- hooks: { ...hooks, beforeSign: hooks?.beforeSign?.bind(this) },
209
- };
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?.());
210
247
  const findNetworkClientIdByChainId = (chainId) => {
211
248
  return this.messenger.call(`NetworkController:findNetworkClientIdByChainId`, chainId);
212
249
  };
@@ -301,25 +338,24 @@ export class TransactionController extends BaseController {
301
338
  */
302
339
  async addTransactionBatch(request) {
303
340
  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;
305
341
  return await addTransactionBatch({
306
342
  addTransaction: this.addTransaction.bind(this),
307
343
  estimateGas: this.estimateGas.bind(this),
308
344
  getGasFeeEstimates: (options) => this.messenger.call('GasFeeController:fetchGasFeeEstimates', options),
309
345
  getInternalAccounts: this.#getInternalAccounts.bind(this),
310
- getSimulationConfig,
346
+ getSimulationConfig: this.#getSimulationConfig.bind(this),
311
347
  getPendingTransactionTracker: (networkClientId) => this.#createPendingTransactionTracker({
312
348
  blockTracker,
313
349
  networkClientId,
314
350
  }),
315
351
  getTransaction: (transactionId) => this.#getTransactionOrThrow(transactionId),
316
- isSimulationEnabled,
352
+ isSimulationEnabled: this.#isSimulationEnabled,
317
353
  messenger: this.messenger,
318
- publishBatchHook: hooks?.publishBatch,
319
- publicKeyEIP7702,
354
+ publishBatchHook: this.#publishBatchHook,
355
+ publicKeyEIP7702: this.#publicKeyEIP7702,
320
356
  publishTransaction: (transactionMeta) => this.#publishTransaction(transactionMeta),
321
357
  request,
322
- signTransaction: (transactionMeta) => signTransactionMeta(this.#getConstructorOptions(), this.#getDependencies(), transactionMeta),
358
+ signTransaction: this.#signTransaction.bind(this),
323
359
  update: this.update.bind(this),
324
360
  updateTransaction: this.#updateTransactionInternal.bind(this),
325
361
  });
@@ -334,7 +370,7 @@ export class TransactionController extends BaseController {
334
370
  return isAtomicBatchSupported({
335
371
  ...request,
336
372
  messenger: this.messenger,
337
- publicKeyEIP7702: this.#options.publicKeyEIP7702,
373
+ publicKeyEIP7702: this.#publicKeyEIP7702,
338
374
  });
339
375
  }
340
376
  /**
@@ -347,11 +383,170 @@ export class TransactionController extends BaseController {
347
383
  * @returns Object containing a promise resolving to the transaction hash if approved.
348
384
  */
349
385
  async addTransaction(txParams, options) {
350
- return await addTransaction({
351
- addTransactionRequest: { options, txParams },
352
- constructorOptions: this.#getConstructorOptions(),
353
- dependencies: this.#getDependencies(),
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,
354
504
  });
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
+ };
355
550
  }
356
551
  /**
357
552
  * Attempts to cancel a transaction based on its ID by setting its status to "rejected"
@@ -423,7 +618,7 @@ export class TransactionController extends BaseController {
423
618
  prepareTransactionParams?.(newTxParams);
424
619
  const unsignedEthTx = prepareTransaction(transactionMeta.chainId, newTxParams);
425
620
  const signedTxData = await this.messenger.call('KeyringController:signTransaction', unsignedEthTx, transactionMeta.txParams.from);
426
- const transactionMetaWithRsv = updateTransactionMetaRSV(transactionMeta, signedTxData);
621
+ const transactionMetaWithRsv = this.#updateTransactionMetaRSV(transactionMeta, signedTxData);
427
622
  const rawTx = serializeTransaction(transactionMeta.chainId, signedTxData);
428
623
  const newFee = newTxParams.maxFeePerGas ?? newTxParams.gasPrice;
429
624
  const oldFee = newTxParams.maxFeePerGas
@@ -473,11 +668,10 @@ export class TransactionController extends BaseController {
473
668
  * @returns The gas and gas price.
474
669
  */
475
670
  async estimateGas(transaction, networkClientId, { ignoreDelegationSignatures, } = {}) {
476
- const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, } = this.#options;
477
671
  const { estimatedGas, simulationFails } = await estimateGas({
478
672
  ignoreDelegationSignatures,
479
- isSimulationEnabled: isSimulationEnabled(),
480
- getSimulationConfig,
673
+ isSimulationEnabled: this.#isSimulationEnabled(),
674
+ getSimulationConfig: this.#getSimulationConfig,
481
675
  messenger: this.messenger,
482
676
  networkClientId,
483
677
  txParams: transaction,
@@ -494,10 +688,9 @@ export class TransactionController extends BaseController {
494
688
  * @returns Object containing the gas limit.
495
689
  */
496
690
  async estimateGasBatch({ chainId, from, transactions, }) {
497
- const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG } = this.#options;
498
691
  return estimateGasBatch({
499
692
  from,
500
- getSimulationConfig,
693
+ getSimulationConfig: this.#getSimulationConfig,
501
694
  isAtomicBatchSupported: this.isAtomicBatchSupported.bind(this),
502
695
  messenger: this.messenger,
503
696
  networkClientId: getNetworkClientId({
@@ -516,10 +709,9 @@ export class TransactionController extends BaseController {
516
709
  * @returns The buffered estimated gas and whether the estimation failed.
517
710
  */
518
711
  async estimateGasBuffered(transaction, multiplier, networkClientId) {
519
- const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, } = this.#options;
520
712
  const { blockGasLimit, estimatedGas, simulationFails } = await estimateGas({
521
- isSimulationEnabled: isSimulationEnabled(),
522
- getSimulationConfig,
713
+ isSimulationEnabled: this.#isSimulationEnabled(),
714
+ getSimulationConfig: this.#getSimulationConfig,
523
715
  messenger: this.messenger,
524
716
  networkClientId,
525
717
  txParams: transaction,
@@ -697,10 +889,9 @@ export class TransactionController extends BaseController {
697
889
  throw new Error(`Cannot update transaction as no transaction metadata found`);
698
890
  }
699
891
  validateIfTransactionUnapprovedOrSubmitted(transactionMeta, 'updateTransactionGasFees');
700
- const { isAutomaticGasFeeUpdateEnabled: getIsAutomaticGasFeeUpdateEnabled = DEFAULT_IS_AUTOMATIC_GAS_FEE_UPDATE_ENABLED, } = this.#options;
701
892
  const clonedTransactionMeta = cloneDeep(transactionMeta);
702
893
  const isTransactionGasFeeEstimatesExists = transactionMeta.gasFeeEstimates;
703
- const isAutomaticGasFeeUpdateEnabled = getIsAutomaticGasFeeUpdateEnabled(transactionMeta);
894
+ const isAutomaticGasFeeUpdateEnabled = this.#isAutomaticGasFeeUpdateEnabled(transactionMeta);
704
895
  const userFeeLevel = userFeeLevelParam;
705
896
  const isOneOfFeeLevelSelected = Object.values(GasFeeEstimateLevel).includes(userFeeLevel);
706
897
  const shouldUpdateTxParamsGasFees = isTransactionGasFeeEstimatesExists &&
@@ -898,10 +1089,10 @@ export class TransactionController extends BaseController {
898
1089
  });
899
1090
  const initialTxAsEthTx = prepareTransaction(chainId, initialTx);
900
1091
  const initialTxAsSerializedHex = serializeTransaction(chainId, initialTxAsEthTx);
901
- if (isTransactionApproving(this.#getDependencies(), initialTxAsSerializedHex)) {
1092
+ if (this.#approvingTransactionIds.has(initialTxAsSerializedHex)) {
902
1093
  return '';
903
1094
  }
904
- const releaseApproval = startTransactionApproval(this.#getDependencies(), initialTxAsSerializedHex);
1095
+ this.#approvingTransactionIds.add(initialTxAsSerializedHex);
905
1096
  let rawTransactions, nonceLock;
906
1097
  try {
907
1098
  // TODO: we should add a check to verify that all transactions have the same from address
@@ -929,7 +1120,7 @@ export class TransactionController extends BaseController {
929
1120
  }
930
1121
  finally {
931
1122
  nonceLock?.releaseLock();
932
- releaseApproval();
1123
+ this.#approvingTransactionIds.delete(initialTxAsSerializedHex);
933
1124
  }
934
1125
  return rawTransactions;
935
1126
  }
@@ -1150,7 +1341,16 @@ export class TransactionController extends BaseController {
1150
1341
  * @param transactionId - The ID of the transaction to stop signing.
1151
1342
  */
1152
1343
  abortTransactionSigning(transactionId) {
1153
- abortTransactionSigning(this.#getDependencies(), 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);
1154
1354
  }
1155
1355
  /**
1156
1356
  * Update the transaction data of a single nested transaction within an atomic batch transaction.
@@ -1309,42 +1509,33 @@ export class TransactionController extends BaseController {
1309
1509
  });
1310
1510
  }
1311
1511
  #addMetadata(transactionMeta) {
1312
- addTransactionToState(this.#getDependencies(), transactionMeta);
1512
+ validateTxParams(transactionMeta.txParams);
1513
+ this.update((state) => {
1514
+ state.transactions = this.#trimTransactionsForState([
1515
+ ...state.transactions,
1516
+ transactionMeta,
1517
+ ]);
1518
+ });
1313
1519
  }
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,
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,
1324
1528
  gasFeeFlows: this.#gasFeeFlows,
1325
- getNonceLock: (address, networkClientId) => this.#multichainTrackingHelper.getNonceLock(address, networkClientId),
1326
- getState: () => this.state,
1327
- hasNetworkClient: (networkClientId) => this.#multichainTrackingHelper.has(networkClientId),
1328
- internalEvents: this.#internalEvents,
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({
1329
1535
  layer1GasFeeFlows: this.#layer1GasFeeFlows,
1330
1536
  messenger: this.messenger,
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 };
1537
+ transactionMeta,
1538
+ }));
1348
1539
  }
1349
1540
  #onBootCleanup() {
1350
1541
  this.clearUnapprovedTransactions();
@@ -1373,6 +1564,203 @@ export class TransactionController extends BaseController {
1373
1564
  }
1374
1565
  }
1375
1566
  }
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
+ }
1376
1764
  async #publishTransaction(transactionMeta, { skipSubmitHistory } = {}) {
1377
1765
  const { networkClientId, rawTx } = transactionMeta;
1378
1766
  if (!rawTx) {
@@ -1389,6 +1777,33 @@ export class TransactionController extends BaseController {
1389
1777
  }
1390
1778
  return transactionHash;
1391
1779
  }
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
+ }
1392
1807
  /**
1393
1808
  * Trim the amount of transactions that are set on the state. Checks
1394
1809
  * if the length of the tx history is longer then desired persistence
@@ -1404,7 +1819,30 @@ export class TransactionController extends BaseController {
1404
1819
  * @returns The trimmed list of transactions.
1405
1820
  */
1406
1821
  #trimTransactionsForState(transactions) {
1407
- return trimTransactionsForState(transactions, this.messenger);
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;
1408
1846
  }
1409
1847
  /**
1410
1848
  * Determines if the transaction is in a final state.
@@ -1413,13 +1851,89 @@ export class TransactionController extends BaseController {
1413
1851
  * @returns Whether the transaction is in a final state.
1414
1852
  */
1415
1853
  #isFinalState(status) {
1416
- return 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));
1417
1890
  }
1418
1891
  #getTransaction(transactionId) {
1419
- return getTransaction(this.state, transactionId);
1892
+ const { transactions } = this.state;
1893
+ return transactions.find(({ id }) => id === transactionId);
1420
1894
  }
1421
1895
  #getTransactionOrThrow(transactionId, errorMessagePrefix = 'TransactionController') {
1422
- return getTransactionOrThrow(this.state, transactionId, errorMessagePrefix);
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;
1423
1937
  }
1424
1938
  /**
1425
1939
  * Validates and adds external provided transaction to state.
@@ -1500,6 +2014,99 @@ export class TransactionController extends BaseController {
1500
2014
  this.updateTransaction(updatedTransactionMeta, 'TransactionController#setTransactionStatusDropped - Transaction dropped');
1501
2015
  this.#onTransactionStatusChange(updatedTransactionMeta);
1502
2016
  }
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
+ }
1503
2110
  #onTransactionStatusChange(transactionMeta) {
1504
2111
  this.messenger.publish(`${controllerName}:transactionStatusUpdated`, {
1505
2112
  transactionMeta,
@@ -1553,11 +2160,7 @@ export class TransactionController extends BaseController {
1553
2160
  });
1554
2161
  }
1555
2162
  #createPendingTransactionTracker({ blockTracker, networkClientId, }) {
1556
- const chainId = getChainId({
1557
- messenger: this.messenger,
1558
- networkClientId,
1559
- });
1560
- const { hooks, isTimeoutEnabled = DEFAULT_IS_TIMEOUT_ENABLED } = this.#options;
2163
+ const chainId = getChainId({ messenger: this.messenger, networkClientId });
1561
2164
  const pendingTransactionTracker = new PendingTransactionTracker({
1562
2165
  blockTracker,
1563
2166
  getGlobalLock: () => this.#multichainTrackingHelper.acquireNonceLockForChainIdKey({
@@ -1565,9 +2168,9 @@ export class TransactionController extends BaseController {
1565
2168
  }),
1566
2169
  getTransactions: () => this.state.transactions,
1567
2170
  hooks: {
1568
- beforeCheckPendingTransaction: hooks?.beforeCheckPendingTransaction?.bind(this),
2171
+ beforeCheckPendingTransaction: this.#beforeCheckPendingTransaction.bind(this),
1569
2172
  },
1570
- isTimeoutEnabled,
2173
+ isTimeoutEnabled: this.#isTimeoutEnabled,
1571
2174
  messenger: this.messenger,
1572
2175
  networkClientId,
1573
2176
  });
@@ -1628,7 +2231,7 @@ export class TransactionController extends BaseController {
1628
2231
  Boolean(error?.data?.message?.includes('nonce too low')));
1629
2232
  }
1630
2233
  #getGasFeeFlows() {
1631
- if (this.#options.testGasFeeFlows) {
2234
+ if (this.#testGasFeeFlows) {
1632
2235
  return [new TestGasFeeFlow()];
1633
2236
  }
1634
2237
  return [
@@ -1645,7 +2248,6 @@ export class TransactionController extends BaseController {
1645
2248
  ];
1646
2249
  }
1647
2250
  #updateTransactionInternal({ transactionId, skipValidation, skipResimulateCheck, }, callback) {
1648
- const { isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, isTransactionTrusted = DEFAULT_IS_TRANSACTION_TRUSTED, } = this.#options;
1649
2251
  let resimulateResponse;
1650
2252
  this.update((state) => {
1651
2253
  const index = state.transactions.findIndex(({ id }) => id === transactionId);
@@ -1659,8 +2261,8 @@ export class TransactionController extends BaseController {
1659
2261
  transactionMeta.txParams = normalizeTransactionParams(transactionMeta.txParams);
1660
2262
  validateTxParams(transactionMeta.txParams);
1661
2263
  }
1662
- if (!skipResimulateCheck && isSimulationEnabled(transactionMeta)) {
1663
- resimulateResponse = shouldResimulate(originalTransactionMeta, transactionMeta, isTransactionTrusted(transactionMeta));
2264
+ if (!skipResimulateCheck && this.#isSimulationEnabled(transactionMeta)) {
2265
+ resimulateResponse = shouldResimulate(originalTransactionMeta, transactionMeta, this.#isTransactionTrusted(transactionMeta));
1664
2266
  }
1665
2267
  state.transactions[index] = transactionMeta;
1666
2268
  });
@@ -1695,20 +2297,21 @@ export class TransactionController extends BaseController {
1695
2297
  let simulationRevert;
1696
2298
  const simulationRequestToken = Symbol(transactionId);
1697
2299
  this.#simulationRequestTokens.set(transactionId, simulationRequestToken);
1698
- const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isSimulationEnabled: getIsSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, trace = DEFAULT_TRACE, } = this.#options;
1699
2300
  try {
1700
- const isSimulationEnabled = getIsSimulationEnabled(transactionMeta);
2301
+ const isSimulationEnabled = this.#isSimulationEnabled(transactionMeta);
1701
2302
  const isBalanceChangesSkipped = this.#isBalanceChangesSkipped(transactionMeta);
1702
2303
  if (isSimulationEnabled && !isBalanceChangesSkipped) {
1703
- const balanceChangesResult = await trace({ name: 'Simulate', parentContext: traceContext }, () => getBalanceChanges({
2304
+ const balanceChangesResult = await this.#trace({ name: 'Simulate', parentContext: traceContext }, () => getBalanceChanges({
1704
2305
  blockTime,
1705
2306
  chainId,
1706
2307
  messenger: this.messenger,
1707
2308
  networkClientId,
1708
- getSimulationConfig: (url, opts) => getSimulationConfig(url, {
1709
- txMeta: transactionMeta,
1710
- ...opts,
1711
- }),
2309
+ getSimulationConfig: (url, opts) => {
2310
+ return this.#getSimulationConfig(url, {
2311
+ txMeta: transactionMeta,
2312
+ ...opts,
2313
+ });
2314
+ },
1712
2315
  nestedTransactions,
1713
2316
  txParams,
1714
2317
  }));
@@ -1775,13 +2378,12 @@ export class TransactionController extends BaseController {
1775
2378
  }
1776
2379
  }
1777
2380
  #onGasFeePollerTransactionUpdate({ transactionId, gasFeeEstimates, gasFeeEstimatesLoaded, layer1GasFee, }) {
1778
- const { isAutomaticGasFeeUpdateEnabled: isTxParamsGasFeeUpdatesEnabled = DEFAULT_IS_AUTOMATIC_GAS_FEE_UPDATE_ENABLED, } = this.#options;
1779
2381
  this.#updateTransactionInternal({ transactionId }, (txMeta) => {
1780
2382
  updateTransactionGasProperties({
1781
2383
  txMeta,
1782
2384
  gasFeeEstimates,
1783
2385
  gasFeeEstimatesLoaded,
1784
- isTxParamsGasFeeUpdatesEnabled,
2386
+ isTxParamsGasFeeUpdatesEnabled: this.#isAutomaticGasFeeUpdateEnabled,
1785
2387
  layer1GasFee,
1786
2388
  });
1787
2389
  });
@@ -1839,11 +2441,10 @@ export class TransactionController extends BaseController {
1839
2441
  const { networkClientId } = transactionMeta;
1840
2442
  const isCustomNetwork = this.#multichainTrackingHelper.getNetworkClient({ networkClientId })
1841
2443
  .configuration.type === NetworkClientType.Custom;
1842
- const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isSimulationEnabled = DEFAULT_IS_SIMULATION_ENABLED, } = this.#options;
1843
2444
  await updateGas({
1844
2445
  isCustomNetwork,
1845
- isSimulationEnabled: isSimulationEnabled(transactionMeta),
1846
- getSimulationConfig,
2446
+ isSimulationEnabled: this.#isSimulationEnabled(transactionMeta),
2447
+ getSimulationConfig: this.#getSimulationConfig,
1847
2448
  messenger: this.messenger,
1848
2449
  txMeta: transactionMeta,
1849
2450
  });
@@ -1851,6 +2452,28 @@ export class TransactionController extends BaseController {
1851
2452
  #registerActionHandlers() {
1852
2453
  this.messenger.registerMethodActionHandlers(this, MESSENGER_EXPOSED_METHODS);
1853
2454
  }
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
+ }
1854
2477
  #failTransaction(transactionMeta, error, actionId) {
1855
2478
  let newTransactionMeta;
1856
2479
  const { revert: receiptRevert } = error;
@@ -1896,15 +2519,29 @@ export class TransactionController extends BaseController {
1896
2519
  this.messenger.publish(`${controllerName}:transactionFinished`, newTransactionMeta);
1897
2520
  this.#internalEvents.emit(`${transactionMeta.id}:finished`, newTransactionMeta);
1898
2521
  }
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
+ }
1899
2537
  async #getGasFeeTokens(transaction) {
1900
2538
  const { chainId } = transaction;
1901
- const { getSimulationConfig = DEFAULT_GET_SIMULATION_CONFIG, isEIP7702GasFeeTokensEnabled = DEFAULT_IS_EIP7702_GAS_FEE_TOKENS_ENABLED, publicKeyEIP7702, } = this.#options;
1902
2539
  return await getGasFeeTokens({
1903
2540
  chainId,
1904
- getSimulationConfig,
1905
- isEIP7702GasFeeTokensEnabled,
2541
+ getSimulationConfig: this.#getSimulationConfig,
2542
+ isEIP7702GasFeeTokensEnabled: this.#isEIP7702GasFeeTokensEnabled,
1906
2543
  messenger: this.messenger,
1907
- publicKeyEIP7702,
2544
+ publicKeyEIP7702: this.#publicKeyEIP7702,
1908
2545
  transactionMeta: transaction,
1909
2546
  });
1910
2547
  }