@metamask/smart-transactions-controller 10.1.6 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [11.0.0]
10
+ ### Changed
11
+ - adapt to eip-1193 provider changes ([#384](https://github.com/MetaMask/smart-transactions-controller/pull/384))
12
+ - **BREAKING**: Save new event props to a newly created smart transaction, use both `properties` and `sensitiveProperties` for events. ([#386](https://github.com/MetaMask/smart-transactions-controller/pull/386))([#390](https://github.com/MetaMask/smart-transactions-controller/pull/390))
13
+
14
+ ## [10.2.0]
15
+ ### Changed
16
+ - Update metrics, so events work even for non-swaps transactions ([#374](https://github.com/MetaMask/smart-transactions-controller/pull/374))
17
+ - Update @metamask/transaction-controller from 32.0.0 to 34.0.0 ([#371](https://github.com/MetaMask/smart-transactions-controller/pull/371))
18
+ - Update braces from 3.0.2 to 3.0.3 and remove the `--immutable-cache` flag in a build file ([#367](https://github.com/MetaMask/smart-transactions-controller/pull/367))
19
+
9
20
  ## [10.1.6]
10
21
  ### Changed
11
22
  - Update @metamask/transaction-controller from 29.1.0 to 32.0.0 ([#348](https://github.com/MetaMask/smart-transactions-controller/pull/348))
@@ -309,7 +320,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
309
320
  - Add initial SmartTransactionsController ([#1](https://github.com/MetaMask/smart-transactions-controller/pull/1))
310
321
  - Initial commit
311
322
 
312
- [Unreleased]: https://github.com/MetaMask/smart-transactions-controller/compare/v10.1.6...HEAD
323
+ [Unreleased]: https://github.com/MetaMask/smart-transactions-controller/compare/v11.0.0...HEAD
324
+ [11.0.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v10.2.0...v11.0.0
325
+ [10.2.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v10.1.6...v10.2.0
313
326
  [10.1.6]: https://github.com/MetaMask/smart-transactions-controller/compare/v10.1.5...v10.1.6
314
327
  [10.1.5]: https://github.com/MetaMask/smart-transactions-controller/compare/v10.1.4...v10.1.5
315
328
  [10.1.4]: https://github.com/MetaMask/smart-transactions-controller/compare/v10.1.3...v10.1.4
@@ -1,12 +1,12 @@
1
1
  /// <reference types="node" />
2
2
  /// <reference types="node" />
3
3
  import type { BaseConfig, BaseState } from '@metamask/base-controller';
4
- import type { Provider } from '@metamask/eth-query';
4
+ import type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';
5
5
  import type { NetworkClientId, NetworkController, NetworkState } from '@metamask/network-controller';
6
6
  import { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';
7
7
  import type { TransactionMeta } from '@metamask/transaction-controller';
8
8
  import EventEmitter from 'events';
9
- import type { Fees, Hex, IndividualTxFees, SignedCanceledTransaction, SignedTransaction, SmartTransaction, SmartTransactionsStatus, UnsignedTransaction, GetTransactionsOptions } from './types';
9
+ import type { Fees, Hex, IndividualTxFees, SignedCanceledTransaction, SignedTransaction, SmartTransaction, SmartTransactionsStatus, UnsignedTransaction, GetTransactionsOptions, MetaMetricsProps } from './types';
10
10
  import { SmartTransactionStatuses } from './types';
11
11
  export declare const DEFAULT_INTERVAL: number;
12
12
  export declare type SmartTransactionsControllerConfig = BaseConfig & {
@@ -44,15 +44,17 @@ export default class SmartTransactionsController extends StaticIntervalPollingCo
44
44
  private readonly trackMetaMetricsEvent;
45
45
  eventEmitter: EventEmitter;
46
46
  private readonly getNetworkClientById;
47
+ private readonly getMetaMetricsProps;
47
48
  private fetch;
48
- constructor({ onNetworkStateChange, getNonceLock, provider, confirmExternalTransaction, getTransactions, trackMetaMetricsEvent, getNetworkClientById, }: {
49
+ constructor({ onNetworkStateChange, getNonceLock, provider, confirmExternalTransaction, getTransactions, trackMetaMetricsEvent, getNetworkClientById, getMetaMetricsProps, }: {
49
50
  onNetworkStateChange: (listener: (networkState: NetworkState) => void) => void;
50
51
  getNonceLock: any;
51
- provider: Provider;
52
+ provider: SafeEventEmitterProvider;
52
53
  confirmExternalTransaction: any;
53
54
  getTransactions: (options?: GetTransactionsOptions) => TransactionMeta[];
54
55
  trackMetaMetricsEvent: any;
55
56
  getNetworkClientById: NetworkController['getNetworkClientById'];
57
+ getMetaMetricsProps: () => Promise<MetaMetricsProps>;
56
58
  }, config?: Partial<SmartTransactionsControllerConfig>, state?: Partial<SmartTransactionsControllerState>);
57
59
  _executePoll(networkClientId: string): Promise<void>;
58
60
  checkPoll(state: any): void;
@@ -7,7 +7,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
7
7
  var __importDefault = (this && this.__importDefault) || function (mod) {
8
8
  return (mod && mod.__esModule) ? mod : { "default": mod };
9
9
  };
10
- var _SmartTransactionsController_instances, _SmartTransactionsController_ensureUniqueSmartTransactions, _SmartTransactionsController_updateSmartTransaction, _SmartTransactionsController_doesTransactionNeedConfirmation, _SmartTransactionsController_confirmSmartTransaction, _SmartTransactionsController_getChainId, _SmartTransactionsController_getEthQuery, _SmartTransactionsController_getCurrentSmartTransactions, _SmartTransactionsController_wipeSmartTransactionsPerChainId;
10
+ var _SmartTransactionsController_instances, _SmartTransactionsController_ensureUniqueSmartTransactions, _SmartTransactionsController_updateSmartTransaction, _SmartTransactionsController_addMetaMetricsPropsToNewSmartTransaction, _SmartTransactionsController_createOrUpdateSmartTransaction, _SmartTransactionsController_doesTransactionNeedConfirmation, _SmartTransactionsController_confirmSmartTransaction, _SmartTransactionsController_getChainId, _SmartTransactionsController_getEthQuery, _SmartTransactionsController_getCurrentSmartTransactions, _SmartTransactionsController_wipeSmartTransactionsPerChainId;
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.DEFAULT_INTERVAL = void 0;
13
13
  // eslint-disable-next-line import/no-nodejs-modules
@@ -27,7 +27,7 @@ const SECOND = 1000;
27
27
  exports.DEFAULT_INTERVAL = SECOND * 5;
28
28
  const ETH_QUERY_ERROR_MSG = '`ethQuery` is not defined on SmartTransactionsController';
29
29
  class SmartTransactionsController extends polling_controller_1.StaticIntervalPollingControllerV1 {
30
- constructor({ onNetworkStateChange, getNonceLock, provider, confirmExternalTransaction, getTransactions, trackMetaMetricsEvent, getNetworkClientById, }, config, state) {
30
+ constructor({ onNetworkStateChange, getNonceLock, provider, confirmExternalTransaction, getTransactions, trackMetaMetricsEvent, getNetworkClientById, getMetaMetricsProps, }, config, state) {
31
31
  super(config, state);
32
32
  _SmartTransactionsController_instances.add(this);
33
33
  /**
@@ -74,6 +74,7 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
74
74
  this.getRegularTransactions = getTransactions;
75
75
  this.trackMetaMetricsEvent = trackMetaMetricsEvent;
76
76
  this.getNetworkClientById = getNetworkClientById;
77
+ this.getMetaMetricsProps = getMetaMetricsProps;
77
78
  this.initializeSmartTransactionsForChainId();
78
79
  __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_ensureUniqueSmartTransactions).call(this);
79
80
  onNetworkStateChange(({ providerConfig: newProvider }) => {
@@ -149,29 +150,16 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
149
150
  });
150
151
  }
151
152
  trackStxStatusChange(smartTransaction, prevSmartTransaction) {
152
- if (!prevSmartTransaction) {
153
- return; // Don't track the first STX, because it doesn't have all necessary params.
154
- }
155
153
  let updatedSmartTransaction = (0, cloneDeep_1.default)(smartTransaction);
156
154
  updatedSmartTransaction = Object.assign(Object.assign({}, (0, cloneDeep_1.default)(prevSmartTransaction)), updatedSmartTransaction);
157
- if (!updatedSmartTransaction.swapMetaData ||
158
- (updatedSmartTransaction.status === prevSmartTransaction.status &&
159
- prevSmartTransaction.swapMetaData)) {
155
+ if (updatedSmartTransaction.status === (prevSmartTransaction === null || prevSmartTransaction === void 0 ? void 0 : prevSmartTransaction.status)) {
160
156
  return; // If status hasn't changed, don't track it again.
161
157
  }
162
- const sensitiveProperties = {
163
- stx_status: updatedSmartTransaction.status,
164
- token_from_symbol: updatedSmartTransaction.sourceTokenSymbol,
165
- token_to_symbol: updatedSmartTransaction.destinationTokenSymbol,
166
- processing_time: (0, utils_1.getStxProcessingTime)(updatedSmartTransaction.time),
167
- stx_enabled: true,
168
- current_stx_enabled: true,
169
- stx_user_opt_in: true,
170
- };
171
158
  this.trackMetaMetricsEvent({
172
159
  event: constants_1.MetaMetricsEventName.StxStatusUpdated,
173
160
  category: constants_1.MetaMetricsEventCategory.Transactions,
174
- sensitiveProperties,
161
+ properties: (0, utils_1.getSmartTransactionMetricsProperties)(updatedSmartTransaction),
162
+ sensitiveProperties: (0, utils_1.getSmartTransactionMetricsSensitiveProperties)(updatedSmartTransaction),
175
163
  });
176
164
  }
177
165
  isNewSmartTransaction(smartTransactionUuid) {
@@ -189,7 +177,7 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
189
177
  chainId = networkClient.configuration.chainId;
190
178
  ethQuery = new eth_query_1.default(networkClient.provider);
191
179
  }
192
- __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, smartTransaction, {
180
+ __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_createOrUpdateSmartTransaction).call(this, smartTransaction, {
193
181
  chainId,
194
182
  ethQuery,
195
183
  });
@@ -216,15 +204,18 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
216
204
  const ethQuery = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getEthQuery).call(this, { networkClientId });
217
205
  const url = `${(0, utils_1.getAPIRequestURL)(types_1.APIType.BATCH_STATUS, chainId)}?${params.toString()}`;
218
206
  const data = (await this.fetch(url));
219
- Object.entries(data).forEach(([uuid, stxStatus]) => {
207
+ for (const [uuid, stxStatus] of Object.entries(data)) {
220
208
  const smartTransaction = {
221
209
  statusMetadata: stxStatus,
222
210
  status: (0, utils_1.calculateStatus)(stxStatus),
223
211
  cancellable: (0, utils_1.isSmartTransactionCancellable)(stxStatus),
224
212
  uuid,
225
213
  };
226
- __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, smartTransaction, { chainId, ethQuery });
227
- });
214
+ await __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_createOrUpdateSmartTransaction).call(this, smartTransaction, {
215
+ chainId,
216
+ ethQuery,
217
+ });
218
+ }
228
219
  return data;
229
220
  }
230
221
  async addNonceToTransaction(transaction) {
@@ -330,7 +321,7 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
330
321
  }
331
322
  const submitTransactionResponse = Object.assign(Object.assign({}, data), { txHash: (0, utils_1.getTxHash)(signedTransactions[0]) });
332
323
  try {
333
- __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, {
324
+ await __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_createOrUpdateSmartTransaction).call(this, {
334
325
  chainId,
335
326
  nonceDetails,
336
327
  preTxBalance,
@@ -438,7 +429,28 @@ _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsContro
438
429
  this.update({
439
430
  smartTransactionsState: Object.assign(Object.assign({}, this.state.smartTransactionsState), { smartTransactions: Object.assign(Object.assign({}, smartTransactions), { [chainId]: uniqueSmartTransactionsForChainId }) }),
440
431
  });
441
- }, _SmartTransactionsController_updateSmartTransaction = async function _SmartTransactionsController_updateSmartTransaction(smartTransaction, { chainId = this.config.chainId, ethQuery = this.ethQuery, }) {
432
+ }, _SmartTransactionsController_updateSmartTransaction = function _SmartTransactionsController_updateSmartTransaction(smartTransaction, { chainId = this.config.chainId, }) {
433
+ var _a;
434
+ const { smartTransactionsState } = this.state;
435
+ const { smartTransactions } = smartTransactionsState;
436
+ const currentSmartTransactions = (_a = smartTransactions[chainId]) !== null && _a !== void 0 ? _a : [];
437
+ const currentIndex = currentSmartTransactions === null || currentSmartTransactions === void 0 ? void 0 : currentSmartTransactions.findIndex((stx) => stx.uuid === smartTransaction.uuid);
438
+ if (currentIndex === -1) {
439
+ return; // Smart transaction not found, don't update anything.
440
+ }
441
+ this.update({
442
+ smartTransactionsState: Object.assign(Object.assign({}, smartTransactionsState), { smartTransactions: Object.assign(Object.assign({}, smartTransactionsState.smartTransactions), { [chainId]: smartTransactionsState.smartTransactions[chainId].map((existingSmartTransaction, index) => {
443
+ return index === currentIndex
444
+ ? Object.assign(Object.assign({}, existingSmartTransaction), smartTransaction) : existingSmartTransaction;
445
+ }) }) }),
446
+ });
447
+ }, _SmartTransactionsController_addMetaMetricsPropsToNewSmartTransaction = async function _SmartTransactionsController_addMetaMetricsPropsToNewSmartTransaction(smartTransaction) {
448
+ const metaMetricsProps = await this.getMetaMetricsProps();
449
+ smartTransaction.accountHardwareType =
450
+ metaMetricsProps === null || metaMetricsProps === void 0 ? void 0 : metaMetricsProps.accountHardwareType;
451
+ smartTransaction.accountType = metaMetricsProps === null || metaMetricsProps === void 0 ? void 0 : metaMetricsProps.accountType;
452
+ smartTransaction.deviceModel = metaMetricsProps === null || metaMetricsProps === void 0 ? void 0 : metaMetricsProps.deviceModel;
453
+ }, _SmartTransactionsController_createOrUpdateSmartTransaction = async function _SmartTransactionsController_createOrUpdateSmartTransaction(smartTransaction, { chainId = this.config.chainId, ethQuery = this.ethQuery, }) {
442
454
  var _a;
443
455
  const { smartTransactionsState } = this.state;
444
456
  const { smartTransactions } = smartTransactionsState;
@@ -448,6 +460,9 @@ _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsContro
448
460
  if (this.ethQuery === undefined) {
449
461
  throw new Error(ETH_QUERY_ERROR_MSG);
450
462
  }
463
+ if (isNewSmartTransaction) {
464
+ await __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_addMetaMetricsPropsToNewSmartTransaction).call(this, smartTransaction);
465
+ }
451
466
  this.trackStxStatusChange(smartTransaction, isNewSmartTransaction
452
467
  ? undefined
453
468
  : currentSmartTransactions[currentIndex]);
@@ -487,11 +502,8 @@ _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsContro
487
502
  });
488
503
  }
489
504
  else {
490
- this.update({
491
- smartTransactionsState: Object.assign(Object.assign({}, smartTransactionsState), { smartTransactions: Object.assign(Object.assign({}, smartTransactionsState.smartTransactions), { [chainId]: smartTransactionsState.smartTransactions[chainId].map((item, index) => {
492
- return index === currentIndex
493
- ? Object.assign(Object.assign({}, item), smartTransaction) : item;
494
- }) }) }),
505
+ __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, smartTransaction, {
506
+ chainId,
495
507
  });
496
508
  }
497
509
  }, _SmartTransactionsController_doesTransactionNeedConfirmation = function _SmartTransactionsController_doesTransactionNeedConfirmation(txHash) {
@@ -542,8 +554,12 @@ _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsContro
542
554
  this.trackMetaMetricsEvent({
543
555
  event: constants_1.MetaMetricsEventName.StxConfirmed,
544
556
  category: constants_1.MetaMetricsEventCategory.Transactions,
557
+ properties: (0, utils_1.getSmartTransactionMetricsProperties)(smartTransaction),
558
+ sensitiveProperties: (0, utils_1.getSmartTransactionMetricsSensitiveProperties)(smartTransaction),
559
+ });
560
+ __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, Object.assign(Object.assign({}, smartTransaction), { confirmed: true }), {
561
+ chainId,
545
562
  });
546
- __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, Object.assign(Object.assign({}, smartTransaction), { confirmed: true }), { chainId, ethQuery });
547
563
  }
548
564
  }
549
565
  catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"SmartTransactionsController.js","sourceRoot":"","sources":["../src/SmartTransactionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAAoD;AACpD,gDAA+C;AAE/C,iEAA2E;AAE3E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wB,IAAI,wBAAwB,CAAC,MAAM,KAAK,CAAC,EAAE;QACtE,OAAO,EAAE,CAAC;KACX;IACD,OAAO,wBAAwB,CAAC;AAClC,CAAC,uIA0DgC,EAC/B,OAAO,EACP,gBAAgB,GAIjB;IACC,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,sBAAsB,CAAC;IAChE,MAAM,iCAAiC,GACrC,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAG,OAAO,CAAC,CAAC;IAC/B,IACE,CAAC,iCAAiC;QAClC,iCAAiC,CAAC,MAAM,KAAK,CAAC,EAC9C;QACA,OAAO;KACR;IACD,MAAM,oCAAoC,GACxC,iCAAiC,CAAC,MAAM,CACtC,CAAC,gBAAkC,EAAE,EAAE,WACrC,OAAA,CAAA,MAAA,gBAAgB,CAAC,QAAQ,0CAAE,IAAI,MAAK,gBAAgB,CAAA,EAAA,CACvD,CAAC;IACJ,IAAI,CAAC,MAAM,CAAC;QACV,sBAAsB,kCACjB,IAAI,CAAC,KAAK,CAAC,sBAAsB,KACpC,iBAAiB,kCACZ,iBAAiB,KACpB,CAAC,OAAO,CAAC,EAAE,oCAAoC,MAElD;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// eslint-disable-next-line import/no-nodejs-modules\nimport { hexlify } from '@ethersproject/bytes';\nimport type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { query, safelyExecute, ChainId } from '@metamask/controller-utils';\nimport type { Provider } from '@metamask/eth-query';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { TransactionStatus } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\n// eslint-disable-next-line import/no-nodejs-modules\nimport EventEmitter from 'events';\nimport cloneDeep from 'lodash/cloneDeep';\n\nimport { MetaMetricsEventCategory, MetaMetricsEventName } from './constants';\nimport type {\n Fees,\n Hex,\n IndividualTxFees,\n SignedCanceledTransaction,\n SignedTransaction,\n SmartTransaction,\n SmartTransactionsStatus,\n UnsignedTransaction,\n GetTransactionsOptions,\n} from './types';\nimport { APIType, SmartTransactionStatuses } from './types';\nimport {\n calculateStatus,\n generateHistoryEntry,\n getAPIRequestURL,\n getStxProcessingTime,\n handleFetch,\n incrementNonceInHex,\n isSmartTransactionCancellable,\n isSmartTransactionPending,\n replayHistory,\n snapshotFromTxMeta,\n getTxHash,\n} from './utils';\n\nconst SECOND = 1000;\nexport const DEFAULT_INTERVAL = SECOND * 5;\nconst ETH_QUERY_ERROR_MSG =\n '`ethQuery` is not defined on SmartTransactionsController';\n\nexport type SmartTransactionsControllerConfig = BaseConfig & {\n interval: number;\n clientId: string;\n chainId: Hex;\n supportedChainIds: Hex[];\n};\n\ntype FeeEstimates = {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n};\n\nexport type SmartTransactionsControllerState = BaseState & {\n smartTransactionsState: {\n smartTransactions: Record<Hex, SmartTransaction[]>;\n userOptIn: boolean | undefined;\n userOptInV2: boolean | undefined;\n liveness: boolean | undefined;\n fees: FeeEstimates;\n feesByChainId: Record<Hex, FeeEstimates>;\n livenessByChainId: Record<Hex, boolean>;\n };\n};\n\nexport default class SmartTransactionsController extends StaticIntervalPollingControllerV1<\n SmartTransactionsControllerConfig,\n SmartTransactionsControllerState\n> {\n /**\n * Name of this controller used during composition\n */\n override name = 'SmartTransactionsController';\n\n public timeoutHandle?: NodeJS.Timeout;\n\n private readonly getNonceLock: any;\n\n private ethQuery: EthQuery | undefined;\n\n public confirmExternalTransaction: any;\n\n public getRegularTransactions: (\n options?: GetTransactionsOptions,\n ) => TransactionMeta[];\n\n private readonly trackMetaMetricsEvent: any;\n\n public eventEmitter: EventEmitter;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /* istanbul ignore next */\n private async fetch(request: string, options?: RequestInit) {\n const { clientId } = this.config;\n const fetchOptions = {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...(clientId && { 'X-Client-Id': clientId }),\n },\n };\n\n return handleFetch(request, fetchOptions);\n }\n\n constructor(\n {\n onNetworkStateChange,\n getNonceLock,\n provider,\n confirmExternalTransaction,\n getTransactions,\n trackMetaMetricsEvent,\n getNetworkClientById,\n }: {\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNonceLock: any;\n provider: Provider;\n confirmExternalTransaction: any;\n getTransactions: (options?: GetTransactionsOptions) => TransactionMeta[];\n trackMetaMetricsEvent: any;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<SmartTransactionsControllerConfig>,\n state?: Partial<SmartTransactionsControllerState>,\n ) {\n super(config, state);\n\n this.defaultConfig = {\n interval: DEFAULT_INTERVAL,\n chainId: ChainId.mainnet,\n clientId: 'default',\n supportedChainIds: [ChainId.mainnet, ChainId.sepolia],\n };\n\n this.defaultState = {\n smartTransactionsState: {\n smartTransactions: {},\n userOptIn: undefined,\n userOptInV2: undefined,\n fees: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n liveness: true,\n livenessByChainId: {\n [ChainId.mainnet]: true,\n [ChainId.sepolia]: true,\n },\n feesByChainId: {\n [ChainId.mainnet]: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n [ChainId.sepolia]: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n },\n },\n };\n\n this.initialize();\n this.setIntervalLength(this.config.interval);\n this.getNonceLock = getNonceLock;\n this.ethQuery = undefined;\n this.confirmExternalTransaction = confirmExternalTransaction;\n this.getRegularTransactions = getTransactions;\n this.trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.getNetworkClientById = getNetworkClientById;\n\n this.initializeSmartTransactionsForChainId();\n this.#ensureUniqueSmartTransactions();\n\n onNetworkStateChange(({ providerConfig: newProvider }) => {\n const { chainId } = newProvider;\n const isNewChainId = chainId !== this.config.chainId;\n this.configure({ chainId });\n this.initializeSmartTransactionsForChainId();\n if (isNewChainId) {\n this.#ensureUniqueSmartTransactions();\n }\n this.checkPoll(this.state);\n this.ethQuery = new EthQuery(provider);\n });\n\n this.subscribe((currentState: any) => this.checkPoll(currentState));\n this.eventEmitter = new EventEmitter();\n }\n\n async _executePoll(networkClientId: string): Promise<void> {\n // if this is going to be truly UI driven polling we shouldn't really reach here\n // with a networkClientId that is not supported, but for now I'll add a check in case\n // wondering if we should add some kind of predicate to the polling controller to check whether\n // we should poll or not\n const chainId = this.#getChainId({ networkClientId });\n if (!this.config.supportedChainIds.includes(chainId)) {\n return Promise.resolve();\n }\n return this.updateSmartTransactions({ networkClientId });\n }\n\n checkPoll(state: any) {\n const { smartTransactions } = state.smartTransactionsState;\n const currentSmartTransactions = smartTransactions[this.config.chainId];\n const pendingTransactions = currentSmartTransactions?.filter(\n isSmartTransactionPending,\n );\n if (!this.timeoutHandle && pendingTransactions?.length > 0) {\n this.poll();\n } else if (this.timeoutHandle && pendingTransactions?.length === 0) {\n this.stop();\n }\n }\n\n initializeSmartTransactionsForChainId() {\n if (this.config.supportedChainIds.includes(this.config.chainId)) {\n const { smartTransactionsState } = this.state;\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [this.config.chainId]:\n smartTransactionsState.smartTransactions[this.config.chainId] ??\n [],\n },\n },\n });\n }\n }\n\n // We fixed having duplicate smart transactions with the same uuid in a very rare edge case.\n // This function resolves it for a few users who have this issue and once we see in logs\n // that everything is fine, we can remove this function.\n #ensureUniqueSmartTransactions() {\n const { smartTransactions } = this.state.smartTransactionsState;\n const chainId = ChainId.mainnet; // Smart Transactions are only available on Ethereum mainnet at the moment.\n const smartTransactionsForChainId = smartTransactions[chainId];\n if (!smartTransactionsForChainId) {\n return;\n }\n const uniqueUUIDs = new Set();\n const uniqueSmartTransactionsForChainId = [];\n for (const transaction of smartTransactionsForChainId) {\n if (!uniqueUUIDs.has(transaction.uuid)) {\n uniqueUUIDs.add(transaction.uuid);\n uniqueSmartTransactionsForChainId.push(transaction);\n }\n }\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n smartTransactions: {\n ...smartTransactions,\n [chainId]: uniqueSmartTransactionsForChainId,\n },\n },\n });\n }\n\n async poll(interval?: number): Promise<void> {\n const { chainId, supportedChainIds } = this.config;\n interval && this.configure({ interval }, false, false);\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n if (!supportedChainIds.includes(chainId)) {\n return;\n }\n this.timeoutHandle = setInterval(() => {\n safelyExecute(async () => this.updateSmartTransactions());\n }, this.config.interval);\n await safelyExecute(async () => this.updateSmartTransactions());\n }\n\n async stop() {\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n this.timeoutHandle = undefined;\n }\n\n setOptInState(state: boolean | undefined): void {\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n userOptInV2: state,\n },\n });\n }\n\n trackStxStatusChange(\n smartTransaction: SmartTransaction,\n prevSmartTransaction?: SmartTransaction,\n ) {\n if (!prevSmartTransaction) {\n return; // Don't track the first STX, because it doesn't have all necessary params.\n }\n\n let updatedSmartTransaction = cloneDeep(smartTransaction);\n updatedSmartTransaction = {\n ...cloneDeep(prevSmartTransaction),\n ...updatedSmartTransaction,\n };\n\n if (\n !updatedSmartTransaction.swapMetaData ||\n (updatedSmartTransaction.status === prevSmartTransaction.status &&\n prevSmartTransaction.swapMetaData)\n ) {\n return; // If status hasn't changed, don't track it again.\n }\n\n const sensitiveProperties = {\n stx_status: updatedSmartTransaction.status,\n token_from_symbol: updatedSmartTransaction.sourceTokenSymbol,\n token_to_symbol: updatedSmartTransaction.destinationTokenSymbol,\n processing_time: getStxProcessingTime(updatedSmartTransaction.time),\n stx_enabled: true,\n current_stx_enabled: true,\n stx_user_opt_in: true,\n };\n\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxStatusUpdated,\n category: MetaMetricsEventCategory.Transactions,\n sensitiveProperties,\n });\n }\n\n isNewSmartTransaction(smartTransactionUuid: string): boolean {\n const { chainId } = this.config;\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransactionUuid,\n );\n return currentIndex === -1 || currentIndex === undefined;\n }\n\n updateSmartTransaction(\n smartTransaction: SmartTransaction,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ) {\n let {\n ethQuery,\n config: { chainId },\n } = this;\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n chainId = networkClient.configuration.chainId;\n ethQuery = new EthQuery(networkClient.provider);\n }\n\n this.#updateSmartTransaction(smartTransaction, {\n chainId,\n ethQuery,\n });\n }\n\n async #updateSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.config.chainId,\n ethQuery = this.ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery | undefined;\n },\n ): Promise<void> {\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId] ?? [];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransaction.uuid,\n );\n const isNewSmartTransaction = this.isNewSmartTransaction(\n smartTransaction.uuid,\n );\n if (this.ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n\n this.trackStxStatusChange(\n smartTransaction,\n isNewSmartTransaction\n ? undefined\n : currentSmartTransactions[currentIndex],\n );\n\n if (isNewSmartTransaction) {\n // add smart transaction\n const cancelledNonceIndex = currentSmartTransactions?.findIndex(\n (stx: SmartTransaction) =>\n stx.txParams?.nonce === smartTransaction.txParams?.nonce &&\n stx.status?.startsWith('cancelled'),\n );\n const snapshot = cloneDeep(smartTransaction);\n const history = [snapshot];\n const historifiedSmartTransaction = { ...smartTransaction, history };\n const nextSmartTransactions =\n cancelledNonceIndex > -1\n ? currentSmartTransactions\n .slice(0, cancelledNonceIndex)\n .concat(currentSmartTransactions.slice(cancelledNonceIndex + 1))\n .concat(historifiedSmartTransaction)\n : currentSmartTransactions.concat(historifiedSmartTransaction);\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [chainId]: nextSmartTransactions,\n },\n },\n });\n return;\n }\n\n // We have to emit this event here, because then a txHash is returned to the TransactionController once it's available\n // and the #doesTransactionNeedConfirmation function will work properly, since it will find the txHash in the regular transactions list.\n this.eventEmitter.emit(\n `${smartTransaction.uuid}:smartTransaction`,\n smartTransaction,\n );\n\n if (\n (smartTransaction.status === SmartTransactionStatuses.SUCCESS ||\n smartTransaction.status === SmartTransactionStatuses.REVERTED) &&\n !smartTransaction.confirmed\n ) {\n // confirm smart transaction\n const currentSmartTransaction = currentSmartTransactions[currentIndex];\n const nextSmartTransaction = {\n ...currentSmartTransaction,\n ...smartTransaction,\n };\n await this.#confirmSmartTransaction(nextSmartTransaction, {\n chainId,\n ethQuery,\n });\n } else {\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [chainId]: smartTransactionsState.smartTransactions[chainId].map(\n (item, index) => {\n return index === currentIndex\n ? { ...item, ...smartTransaction }\n : item;\n },\n ),\n },\n },\n });\n }\n }\n\n async updateSmartTransactions({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): Promise<void> {\n const { smartTransactions } = this.state.smartTransactionsState;\n const chainId = this.#getChainId({ networkClientId });\n const smartTransactionsForChainId = smartTransactions[chainId];\n\n const transactionsToUpdate: string[] = smartTransactionsForChainId\n .filter(isSmartTransactionPending)\n .map((smartTransaction) => smartTransaction.uuid);\n\n if (transactionsToUpdate.length > 0) {\n this.fetchSmartTransactionsStatus(transactionsToUpdate, {\n networkClientId,\n });\n }\n }\n\n #doesTransactionNeedConfirmation(txHash: string | undefined): boolean {\n if (!txHash) {\n return true;\n }\n const transactions = this.getRegularTransactions();\n const foundTransaction = transactions?.find((tx) => {\n return tx.hash?.toLowerCase() === txHash.toLowerCase();\n });\n if (!foundTransaction) {\n return true;\n }\n // If a found transaction is either confirmed or submitted, it doesn't need confirmation from the STX controller.\n // When it's in the submitted state, the TransactionController checks its status and confirms it,\n // so no need to confirm it again here.\n return ![TransactionStatus.confirmed, TransactionStatus.submitted].includes(\n foundTransaction.status,\n );\n }\n\n async #confirmSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.config.chainId,\n ethQuery = this.ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery | undefined;\n },\n ) {\n if (ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n const txHash = smartTransaction.statusMetadata?.minedHash;\n try {\n const transactionReceipt: {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n blockNumber: string;\n } | null = await query(ethQuery, 'getTransactionReceipt', [txHash]);\n const transaction: {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n } | null = await query(ethQuery, 'getTransactionByHash', [txHash]);\n\n const maxFeePerGas = transaction?.maxFeePerGas;\n const maxPriorityFeePerGas = transaction?.maxPriorityFeePerGas;\n if (transactionReceipt?.blockNumber) {\n const blockData: { baseFeePerGas?: string } | null = await query(\n ethQuery,\n 'getBlockByNumber',\n [transactionReceipt?.blockNumber, false],\n );\n const baseFeePerGas = blockData?.baseFeePerGas;\n const updatedTxParams = {\n ...smartTransaction.txParams,\n maxFeePerGas,\n maxPriorityFeePerGas,\n };\n // call confirmExternalTransaction\n const originalTxMeta = {\n ...smartTransaction,\n id: smartTransaction.uuid,\n status: TransactionStatus.confirmed,\n hash: txHash,\n txParams: updatedTxParams,\n };\n // create txMeta snapshot for history\n const snapshot = snapshotFromTxMeta(originalTxMeta);\n // recover previous tx state obj\n const previousState = replayHistory(originalTxMeta.history);\n // generate history entry and add to history\n const entry = generateHistoryEntry(\n previousState,\n snapshot,\n 'txStateManager: setting status to confirmed',\n );\n const txMeta =\n entry.length > 0\n ? {\n ...originalTxMeta,\n history: originalTxMeta.history.concat(entry),\n }\n : originalTxMeta;\n\n if (this.#doesTransactionNeedConfirmation(txHash)) {\n this.confirmExternalTransaction(\n txMeta,\n transactionReceipt,\n baseFeePerGas,\n );\n }\n\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxConfirmed,\n category: MetaMetricsEventCategory.Transactions,\n });\n\n this.#updateSmartTransaction(\n {\n ...smartTransaction,\n confirmed: true,\n },\n { chainId, ethQuery },\n );\n }\n } catch (error) {\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxConfirmationFailed,\n category: MetaMetricsEventCategory.Transactions,\n });\n console.error('confirm error', error);\n }\n }\n\n // ! Ask backend API to accept list of uuids as params\n async fetchSmartTransactionsStatus(\n uuids: string[],\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ): Promise<Record<string, SmartTransactionsStatus>> {\n const params = new URLSearchParams({\n uuids: uuids.join(','),\n });\n const chainId = this.#getChainId({ networkClientId });\n const ethQuery = this.#getEthQuery({ networkClientId });\n const url = `${getAPIRequestURL(\n APIType.BATCH_STATUS,\n chainId,\n )}?${params.toString()}`;\n\n const data = (await this.fetch(url)) as Record<\n string,\n SmartTransactionsStatus\n >;\n\n Object.entries(data).forEach(([uuid, stxStatus]) => {\n const smartTransaction = {\n statusMetadata: stxStatus,\n status: calculateStatus(stxStatus),\n cancellable: isSmartTransactionCancellable(stxStatus),\n uuid,\n };\n this.#updateSmartTransaction(smartTransaction, { chainId, ethQuery });\n });\n\n return data;\n }\n\n async addNonceToTransaction(\n transaction: UnsignedTransaction,\n ): Promise<UnsignedTransaction> {\n const nonceLock = await this.getNonceLock(transaction.from);\n const nonce = nonceLock.nextNonce;\n nonceLock.releaseLock();\n return {\n ...transaction,\n nonce: `0x${nonce.toString(16)}`,\n };\n }\n\n clearFees(): Fees {\n const fees = {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n };\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n fees,\n },\n });\n return fees;\n }\n\n async getFees(\n tradeTx: UnsignedTransaction,\n approvalTx?: UnsignedTransaction,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ): Promise<Fees> {\n const chainId = this.#getChainId({ networkClientId });\n const transactions = [];\n let unsignedTradeTransactionWithNonce;\n if (approvalTx) {\n const unsignedApprovalTransactionWithNonce =\n await this.addNonceToTransaction(approvalTx);\n transactions.push(unsignedApprovalTransactionWithNonce);\n unsignedTradeTransactionWithNonce = {\n ...tradeTx,\n // If there is an approval tx, the trade tx's nonce is increased by 1.\n nonce: incrementNonceInHex(unsignedApprovalTransactionWithNonce.nonce),\n };\n } else if (tradeTx.nonce) {\n unsignedTradeTransactionWithNonce = tradeTx;\n } else {\n unsignedTradeTransactionWithNonce = await this.addNonceToTransaction(\n tradeTx,\n );\n }\n transactions.push(unsignedTradeTransactionWithNonce);\n const data = await this.fetch(getAPIRequestURL(APIType.GET_FEES, chainId), {\n method: 'POST',\n body: JSON.stringify({\n txs: transactions,\n }),\n });\n let approvalTxFees;\n let tradeTxFees;\n if (approvalTx) {\n approvalTxFees = data?.txs[0];\n tradeTxFees = data?.txs[1];\n } else {\n tradeTxFees = data?.txs[0];\n }\n\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n ...(chainId === this.config.chainId && {\n fees: {\n approvalTxFees,\n tradeTxFees,\n },\n }),\n feesByChainId: {\n ...this.state.smartTransactionsState.feesByChainId,\n [chainId]: {\n approvalTxFees,\n tradeTxFees,\n },\n },\n },\n });\n\n return {\n approvalTxFees,\n tradeTxFees,\n };\n }\n\n // * After this successful call client must add a nonce representative to\n // * transaction controller external transactions list\n async submitSignedTransactions({\n transactionMeta,\n txParams,\n signedTransactions,\n signedCanceledTransactions,\n networkClientId,\n }: {\n signedTransactions: SignedTransaction[];\n signedCanceledTransactions: SignedCanceledTransaction[];\n transactionMeta?: any;\n txParams?: any;\n networkClientId?: NetworkClientId;\n }) {\n const chainId = this.#getChainId({ networkClientId });\n const ethQuery = this.#getEthQuery({ networkClientId });\n const data = await this.fetch(\n getAPIRequestURL(APIType.SUBMIT_TRANSACTIONS, chainId),\n {\n method: 'POST',\n body: JSON.stringify({\n rawTxs: signedTransactions,\n rawCancelTxs: signedCanceledTransactions,\n }),\n },\n );\n const time = Date.now();\n let preTxBalance;\n try {\n const preTxBalanceBN = await query(ethQuery, 'getBalance', [\n txParams?.from,\n ]);\n preTxBalance = new BigNumber(preTxBalanceBN).toString(16);\n } catch (error) {\n console.error('provider error', error);\n }\n\n const requiresNonce = !txParams.nonce;\n let nonce;\n let nonceLock;\n let nonceDetails = {};\n\n if (requiresNonce) {\n nonceLock = await this.getNonceLock(txParams?.from);\n nonce = hexlify(nonceLock.nextNonce);\n nonceDetails = nonceLock.nonceDetails;\n if (txParams) {\n txParams.nonce ??= nonce;\n }\n }\n const submitTransactionResponse = {\n ...data,\n txHash: getTxHash(signedTransactions[0]),\n };\n\n try {\n this.#updateSmartTransaction(\n {\n chainId,\n nonceDetails,\n preTxBalance,\n status: SmartTransactionStatuses.PENDING,\n time,\n txParams,\n uuid: submitTransactionResponse.uuid,\n txHash: submitTransactionResponse.txHash,\n cancellable: true,\n type: transactionMeta?.type || 'swap',\n },\n { chainId, ethQuery },\n );\n } finally {\n nonceLock?.releaseLock();\n }\n\n return submitTransactionResponse;\n }\n\n #getChainId({\n networkClientId,\n }: { networkClientId?: NetworkClientId } = {}): Hex {\n return networkClientId\n ? this.getNetworkClientById(networkClientId).configuration.chainId\n : this.config.chainId;\n }\n\n #getEthQuery({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): EthQuery {\n if (networkClientId) {\n return new EthQuery(this.getNetworkClientById(networkClientId).provider);\n }\n\n if (this.ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n\n return this.ethQuery;\n }\n\n // TODO: This should return if the cancellation was on chain or not (for nonce management)\n // After this successful call client must update nonce representative\n // in transaction controller external transactions list\n async cancelSmartTransaction(\n uuid: string,\n {\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {},\n ): Promise<void> {\n const chainId = this.#getChainId({ networkClientId });\n await this.fetch(getAPIRequestURL(APIType.CANCEL, chainId), {\n method: 'POST',\n body: JSON.stringify({ uuid }),\n });\n }\n\n async fetchLiveness({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): Promise<boolean> {\n const chainId = this.#getChainId({ networkClientId });\n let liveness = false;\n try {\n const response = await this.fetch(\n getAPIRequestURL(APIType.LIVENESS, chainId),\n );\n liveness = Boolean(response.lastBlock);\n } catch (error) {\n console.log('\"fetchLiveness\" API call failed');\n }\n\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n ...(chainId === this.config.chainId && { liveness }),\n livenessByChainId: {\n ...this.state.smartTransactionsState.livenessByChainId,\n [chainId]: liveness,\n },\n },\n });\n\n return liveness;\n }\n\n async setStatusRefreshInterval(interval: number): Promise<void> {\n if (interval !== this.config.interval) {\n this.configure({ interval }, false, false);\n }\n }\n\n #getCurrentSmartTransactions(): SmartTransaction[] {\n const { smartTransactions } = this.state.smartTransactionsState;\n const { chainId } = this.config;\n const currentSmartTransactions = smartTransactions?.[chainId];\n if (!currentSmartTransactions || currentSmartTransactions.length === 0) {\n return [];\n }\n return currentSmartTransactions;\n }\n\n getTransactions({\n addressFrom,\n status,\n }: {\n addressFrom: string;\n status: SmartTransactionStatuses;\n }): SmartTransaction[] {\n const currentSmartTransactions = this.#getCurrentSmartTransactions();\n return currentSmartTransactions.filter((stx) => {\n return stx.status === status && stx.txParams?.from === addressFrom;\n });\n }\n\n getSmartTransactionByMinedTxHash(\n txHash: string | undefined,\n ): SmartTransaction | undefined {\n if (!txHash) {\n return undefined;\n }\n const currentSmartTransactions = this.#getCurrentSmartTransactions();\n return currentSmartTransactions.find((smartTransaction) => {\n return (\n smartTransaction.statusMetadata?.minedHash?.toLowerCase() ===\n txHash.toLowerCase()\n );\n });\n }\n\n wipeSmartTransactions({\n address,\n ignoreNetwork,\n }: {\n address: string;\n ignoreNetwork?: boolean;\n }): void {\n if (!address) {\n return;\n }\n const addressLowerCase = address.toLowerCase();\n if (ignoreNetwork) {\n const { smartTransactions } = this.state.smartTransactionsState;\n Object.keys(smartTransactions).forEach((chainId) => {\n const chainIdHex: Hex = chainId as Hex;\n this.#wipeSmartTransactionsPerChainId({\n chainId: chainIdHex,\n addressLowerCase,\n });\n });\n } else {\n this.#wipeSmartTransactionsPerChainId({\n chainId: this.config.chainId,\n addressLowerCase,\n });\n }\n }\n\n #wipeSmartTransactionsPerChainId({\n chainId,\n addressLowerCase,\n }: {\n chainId: Hex;\n addressLowerCase: string;\n }): void {\n const { smartTransactions } = this.state.smartTransactionsState;\n const smartTransactionsForSelectedChain: SmartTransaction[] =\n smartTransactions?.[chainId];\n if (\n !smartTransactionsForSelectedChain ||\n smartTransactionsForSelectedChain.length === 0\n ) {\n return;\n }\n const newSmartTransactionsForSelectedChain =\n smartTransactionsForSelectedChain.filter(\n (smartTransaction: SmartTransaction) =>\n smartTransaction.txParams?.from !== addressLowerCase,\n );\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n smartTransactions: {\n ...smartTransactions,\n [chainId]: newSmartTransactionsForSelectedChain,\n },\n },\n });\n }\n}\n"]}
1
+ {"version":3,"file":"SmartTransactionsController.js","sourceRoot":"","sources":["../src/SmartTransactionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAAoD;AACpD,gDAA+C;AAE/C,iEAA2E;AAE3E,oEAA2C;AAM3C,qEAAiF;AAEjF,6EAAqE;AACrE,+CAAyC;AACzC,oDAAoD;AACpD,oDAAkC;AAClC,iEAAyC;AAEzC,2CAA6E;AAa7E,mCAA4D;AAC5D,mCAaiB;AAEjB,MAAM,MAAM,GAAG,IAAI,CAAC;AACP,QAAA,gBAAgB,GAAG,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OAAA,CAAA,MAAA,gBAAgB,CAAC,QAAQ,0CAAE,IAAI,MAAK,gBAAgB,CAAA,EAAA,CACvD,CAAC;IACJ,IAAI,CAAC,MAAM,CAAC;QACV,sBAAsB,kCACjB,IAAI,CAAC,KAAK,CAAC,sBAAsB,KACpC,iBAAiB,kCACZ,iBAAiB,KACpB,CAAC,OAAO,CAAC,EAAE,oCAAoC,MAElD;KACF,CAAC,CAAC;AACL,CAAC","sourcesContent":["// eslint-disable-next-line import/no-nodejs-modules\nimport { hexlify } from '@ethersproject/bytes';\nimport type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { query, safelyExecute, ChainId } from '@metamask/controller-utils';\nimport type { SafeEventEmitterProvider } from '@metamask/eth-json-rpc-provider';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { TransactionStatus } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\n// eslint-disable-next-line import/no-nodejs-modules\nimport EventEmitter from 'events';\nimport cloneDeep from 'lodash/cloneDeep';\n\nimport { MetaMetricsEventCategory, MetaMetricsEventName } from './constants';\nimport type {\n Fees,\n Hex,\n IndividualTxFees,\n SignedCanceledTransaction,\n SignedTransaction,\n SmartTransaction,\n SmartTransactionsStatus,\n UnsignedTransaction,\n GetTransactionsOptions,\n MetaMetricsProps,\n} from './types';\nimport { APIType, SmartTransactionStatuses } from './types';\nimport {\n calculateStatus,\n generateHistoryEntry,\n getAPIRequestURL,\n handleFetch,\n incrementNonceInHex,\n isSmartTransactionCancellable,\n isSmartTransactionPending,\n replayHistory,\n snapshotFromTxMeta,\n getTxHash,\n getSmartTransactionMetricsProperties,\n getSmartTransactionMetricsSensitiveProperties,\n} from './utils';\n\nconst SECOND = 1000;\nexport const DEFAULT_INTERVAL = SECOND * 5;\nconst ETH_QUERY_ERROR_MSG =\n '`ethQuery` is not defined on SmartTransactionsController';\n\nexport type SmartTransactionsControllerConfig = BaseConfig & {\n interval: number;\n clientId: string;\n chainId: Hex;\n supportedChainIds: Hex[];\n};\n\ntype FeeEstimates = {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n};\n\nexport type SmartTransactionsControllerState = BaseState & {\n smartTransactionsState: {\n smartTransactions: Record<Hex, SmartTransaction[]>;\n userOptIn: boolean | undefined;\n userOptInV2: boolean | undefined;\n liveness: boolean | undefined;\n fees: FeeEstimates;\n feesByChainId: Record<Hex, FeeEstimates>;\n livenessByChainId: Record<Hex, boolean>;\n };\n};\n\nexport default class SmartTransactionsController extends StaticIntervalPollingControllerV1<\n SmartTransactionsControllerConfig,\n SmartTransactionsControllerState\n> {\n /**\n * Name of this controller used during composition\n */\n override name = 'SmartTransactionsController';\n\n public timeoutHandle?: NodeJS.Timeout;\n\n private readonly getNonceLock: any;\n\n private ethQuery: EthQuery | undefined;\n\n public confirmExternalTransaction: any;\n\n public getRegularTransactions: (\n options?: GetTransactionsOptions,\n ) => TransactionMeta[];\n\n private readonly trackMetaMetricsEvent: any;\n\n public eventEmitter: EventEmitter;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n private readonly getMetaMetricsProps: () => Promise<MetaMetricsProps>;\n\n /* istanbul ignore next */\n private async fetch(request: string, options?: RequestInit) {\n const { clientId } = this.config;\n const fetchOptions = {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...(clientId && { 'X-Client-Id': clientId }),\n },\n };\n\n return handleFetch(request, fetchOptions);\n }\n\n constructor(\n {\n onNetworkStateChange,\n getNonceLock,\n provider,\n confirmExternalTransaction,\n getTransactions,\n trackMetaMetricsEvent,\n getNetworkClientById,\n getMetaMetricsProps,\n }: {\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNonceLock: any;\n provider: SafeEventEmitterProvider;\n confirmExternalTransaction: any;\n getTransactions: (options?: GetTransactionsOptions) => TransactionMeta[];\n trackMetaMetricsEvent: any;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n getMetaMetricsProps: () => Promise<MetaMetricsProps>;\n },\n config?: Partial<SmartTransactionsControllerConfig>,\n state?: Partial<SmartTransactionsControllerState>,\n ) {\n super(config, state);\n\n this.defaultConfig = {\n interval: DEFAULT_INTERVAL,\n chainId: ChainId.mainnet,\n clientId: 'default',\n supportedChainIds: [ChainId.mainnet, ChainId.sepolia],\n };\n\n this.defaultState = {\n smartTransactionsState: {\n smartTransactions: {},\n userOptIn: undefined,\n userOptInV2: undefined,\n fees: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n liveness: true,\n livenessByChainId: {\n [ChainId.mainnet]: true,\n [ChainId.sepolia]: true,\n },\n feesByChainId: {\n [ChainId.mainnet]: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n [ChainId.sepolia]: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n },\n },\n };\n\n this.initialize();\n this.setIntervalLength(this.config.interval);\n this.getNonceLock = getNonceLock;\n this.ethQuery = undefined;\n this.confirmExternalTransaction = confirmExternalTransaction;\n this.getRegularTransactions = getTransactions;\n this.trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.getNetworkClientById = getNetworkClientById;\n this.getMetaMetricsProps = getMetaMetricsProps;\n\n this.initializeSmartTransactionsForChainId();\n this.#ensureUniqueSmartTransactions();\n\n onNetworkStateChange(({ providerConfig: newProvider }) => {\n const { chainId } = newProvider;\n const isNewChainId = chainId !== this.config.chainId;\n this.configure({ chainId });\n this.initializeSmartTransactionsForChainId();\n if (isNewChainId) {\n this.#ensureUniqueSmartTransactions();\n }\n this.checkPoll(this.state);\n this.ethQuery = new EthQuery(provider);\n });\n\n this.subscribe((currentState: any) => this.checkPoll(currentState));\n this.eventEmitter = new EventEmitter();\n }\n\n async _executePoll(networkClientId: string): Promise<void> {\n // if this is going to be truly UI driven polling we shouldn't really reach here\n // with a networkClientId that is not supported, but for now I'll add a check in case\n // wondering if we should add some kind of predicate to the polling controller to check whether\n // we should poll or not\n const chainId = this.#getChainId({ networkClientId });\n if (!this.config.supportedChainIds.includes(chainId)) {\n return Promise.resolve();\n }\n return this.updateSmartTransactions({ networkClientId });\n }\n\n checkPoll(state: any) {\n const { smartTransactions } = state.smartTransactionsState;\n const currentSmartTransactions = smartTransactions[this.config.chainId];\n const pendingTransactions = currentSmartTransactions?.filter(\n isSmartTransactionPending,\n );\n if (!this.timeoutHandle && pendingTransactions?.length > 0) {\n this.poll();\n } else if (this.timeoutHandle && pendingTransactions?.length === 0) {\n this.stop();\n }\n }\n\n initializeSmartTransactionsForChainId() {\n if (this.config.supportedChainIds.includes(this.config.chainId)) {\n const { smartTransactionsState } = this.state;\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [this.config.chainId]:\n smartTransactionsState.smartTransactions[this.config.chainId] ??\n [],\n },\n },\n });\n }\n }\n\n // We fixed having duplicate smart transactions with the same uuid in a very rare edge case.\n // This function resolves it for a few users who have this issue and once we see in logs\n // that everything is fine, we can remove this function.\n #ensureUniqueSmartTransactions() {\n const { smartTransactions } = this.state.smartTransactionsState;\n const chainId = ChainId.mainnet; // Smart Transactions are only available on Ethereum mainnet at the moment.\n const smartTransactionsForChainId = smartTransactions[chainId];\n if (!smartTransactionsForChainId) {\n return;\n }\n const uniqueUUIDs = new Set();\n const uniqueSmartTransactionsForChainId = [];\n for (const transaction of smartTransactionsForChainId) {\n if (!uniqueUUIDs.has(transaction.uuid)) {\n uniqueUUIDs.add(transaction.uuid);\n uniqueSmartTransactionsForChainId.push(transaction);\n }\n }\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n smartTransactions: {\n ...smartTransactions,\n [chainId]: uniqueSmartTransactionsForChainId,\n },\n },\n });\n }\n\n async poll(interval?: number): Promise<void> {\n const { chainId, supportedChainIds } = this.config;\n interval && this.configure({ interval }, false, false);\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n if (!supportedChainIds.includes(chainId)) {\n return;\n }\n this.timeoutHandle = setInterval(() => {\n safelyExecute(async () => this.updateSmartTransactions());\n }, this.config.interval);\n await safelyExecute(async () => this.updateSmartTransactions());\n }\n\n async stop() {\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n this.timeoutHandle = undefined;\n }\n\n setOptInState(state: boolean | undefined): void {\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n userOptInV2: state,\n },\n });\n }\n\n trackStxStatusChange(\n smartTransaction: SmartTransaction,\n prevSmartTransaction?: SmartTransaction,\n ) {\n let updatedSmartTransaction = cloneDeep(smartTransaction);\n updatedSmartTransaction = {\n ...cloneDeep(prevSmartTransaction),\n ...updatedSmartTransaction,\n };\n\n if (updatedSmartTransaction.status === prevSmartTransaction?.status) {\n return; // If status hasn't changed, don't track it again.\n }\n\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxStatusUpdated,\n category: MetaMetricsEventCategory.Transactions,\n properties: getSmartTransactionMetricsProperties(updatedSmartTransaction),\n sensitiveProperties: getSmartTransactionMetricsSensitiveProperties(\n updatedSmartTransaction,\n ),\n });\n }\n\n isNewSmartTransaction(smartTransactionUuid: string): boolean {\n const { chainId } = this.config;\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransactionUuid,\n );\n return currentIndex === -1 || currentIndex === undefined;\n }\n\n updateSmartTransaction(\n smartTransaction: SmartTransaction,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ) {\n let {\n ethQuery,\n config: { chainId },\n } = this;\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n chainId = networkClient.configuration.chainId;\n ethQuery = new EthQuery(networkClient.provider);\n }\n\n this.#createOrUpdateSmartTransaction(smartTransaction, {\n chainId,\n ethQuery,\n });\n }\n\n #updateSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.config.chainId,\n }: {\n chainId: Hex;\n },\n ) {\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId] ?? [];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransaction.uuid,\n );\n if (currentIndex === -1) {\n return; // Smart transaction not found, don't update anything.\n }\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [chainId]: smartTransactionsState.smartTransactions[chainId].map(\n (existingSmartTransaction, index) => {\n return index === currentIndex\n ? { ...existingSmartTransaction, ...smartTransaction }\n : existingSmartTransaction;\n },\n ),\n },\n },\n });\n }\n\n async #addMetaMetricsPropsToNewSmartTransaction(\n smartTransaction: SmartTransaction,\n ) {\n const metaMetricsProps = await this.getMetaMetricsProps();\n smartTransaction.accountHardwareType =\n metaMetricsProps?.accountHardwareType;\n smartTransaction.accountType = metaMetricsProps?.accountType;\n smartTransaction.deviceModel = metaMetricsProps?.deviceModel;\n }\n\n async #createOrUpdateSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.config.chainId,\n ethQuery = this.ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery | undefined;\n },\n ): Promise<void> {\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId] ?? [];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransaction.uuid,\n );\n const isNewSmartTransaction = this.isNewSmartTransaction(\n smartTransaction.uuid,\n );\n if (this.ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n\n if (isNewSmartTransaction) {\n await this.#addMetaMetricsPropsToNewSmartTransaction(smartTransaction);\n }\n\n this.trackStxStatusChange(\n smartTransaction,\n isNewSmartTransaction\n ? undefined\n : currentSmartTransactions[currentIndex],\n );\n\n if (isNewSmartTransaction) {\n // add smart transaction\n const cancelledNonceIndex = currentSmartTransactions?.findIndex(\n (stx: SmartTransaction) =>\n stx.txParams?.nonce === smartTransaction.txParams?.nonce &&\n stx.status?.startsWith('cancelled'),\n );\n const snapshot = cloneDeep(smartTransaction);\n const history = [snapshot];\n const historifiedSmartTransaction = { ...smartTransaction, history };\n const nextSmartTransactions =\n cancelledNonceIndex > -1\n ? currentSmartTransactions\n .slice(0, cancelledNonceIndex)\n .concat(currentSmartTransactions.slice(cancelledNonceIndex + 1))\n .concat(historifiedSmartTransaction)\n : currentSmartTransactions.concat(historifiedSmartTransaction);\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [chainId]: nextSmartTransactions,\n },\n },\n });\n return;\n }\n\n // We have to emit this event here, because then a txHash is returned to the TransactionController once it's available\n // and the #doesTransactionNeedConfirmation function will work properly, since it will find the txHash in the regular transactions list.\n this.eventEmitter.emit(\n `${smartTransaction.uuid}:smartTransaction`,\n smartTransaction,\n );\n\n if (\n (smartTransaction.status === SmartTransactionStatuses.SUCCESS ||\n smartTransaction.status === SmartTransactionStatuses.REVERTED) &&\n !smartTransaction.confirmed\n ) {\n // confirm smart transaction\n const currentSmartTransaction = currentSmartTransactions[currentIndex];\n const nextSmartTransaction = {\n ...currentSmartTransaction,\n ...smartTransaction,\n };\n await this.#confirmSmartTransaction(nextSmartTransaction, {\n chainId,\n ethQuery,\n });\n } else {\n this.#updateSmartTransaction(smartTransaction, {\n chainId,\n });\n }\n }\n\n async updateSmartTransactions({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): Promise<void> {\n const { smartTransactions } = this.state.smartTransactionsState;\n const chainId = this.#getChainId({ networkClientId });\n const smartTransactionsForChainId = smartTransactions[chainId];\n\n const transactionsToUpdate: string[] = smartTransactionsForChainId\n .filter(isSmartTransactionPending)\n .map((smartTransaction) => smartTransaction.uuid);\n\n if (transactionsToUpdate.length > 0) {\n this.fetchSmartTransactionsStatus(transactionsToUpdate, {\n networkClientId,\n });\n }\n }\n\n #doesTransactionNeedConfirmation(txHash: string | undefined): boolean {\n if (!txHash) {\n return true;\n }\n const transactions = this.getRegularTransactions();\n const foundTransaction = transactions?.find((tx) => {\n return tx.hash?.toLowerCase() === txHash.toLowerCase();\n });\n if (!foundTransaction) {\n return true;\n }\n // If a found transaction is either confirmed or submitted, it doesn't need confirmation from the STX controller.\n // When it's in the submitted state, the TransactionController checks its status and confirms it,\n // so no need to confirm it again here.\n return ![TransactionStatus.confirmed, TransactionStatus.submitted].includes(\n foundTransaction.status,\n );\n }\n\n async #confirmSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.config.chainId,\n ethQuery = this.ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery | undefined;\n },\n ) {\n if (ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n const txHash = smartTransaction.statusMetadata?.minedHash;\n try {\n const transactionReceipt: {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n blockNumber: string;\n } | null = await query(ethQuery, 'getTransactionReceipt', [txHash]);\n const transaction: {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n } | null = await query(ethQuery, 'getTransactionByHash', [txHash]);\n\n const maxFeePerGas = transaction?.maxFeePerGas;\n const maxPriorityFeePerGas = transaction?.maxPriorityFeePerGas;\n if (transactionReceipt?.blockNumber) {\n const blockData: { baseFeePerGas?: string } | null = await query(\n ethQuery,\n 'getBlockByNumber',\n [transactionReceipt?.blockNumber, false],\n );\n const baseFeePerGas = blockData?.baseFeePerGas;\n const updatedTxParams = {\n ...smartTransaction.txParams,\n maxFeePerGas,\n maxPriorityFeePerGas,\n };\n // call confirmExternalTransaction\n const originalTxMeta = {\n ...smartTransaction,\n id: smartTransaction.uuid,\n status: TransactionStatus.confirmed,\n hash: txHash,\n txParams: updatedTxParams,\n };\n // create txMeta snapshot for history\n const snapshot = snapshotFromTxMeta(originalTxMeta);\n // recover previous tx state obj\n const previousState = replayHistory(originalTxMeta.history);\n // generate history entry and add to history\n const entry = generateHistoryEntry(\n previousState,\n snapshot,\n 'txStateManager: setting status to confirmed',\n );\n const txMeta =\n entry.length > 0\n ? {\n ...originalTxMeta,\n history: originalTxMeta.history.concat(entry),\n }\n : originalTxMeta;\n\n if (this.#doesTransactionNeedConfirmation(txHash)) {\n this.confirmExternalTransaction(\n txMeta,\n transactionReceipt,\n baseFeePerGas,\n );\n }\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxConfirmed,\n category: MetaMetricsEventCategory.Transactions,\n properties: getSmartTransactionMetricsProperties(smartTransaction),\n sensitiveProperties:\n getSmartTransactionMetricsSensitiveProperties(smartTransaction),\n });\n this.#updateSmartTransaction(\n { ...smartTransaction, confirmed: true },\n {\n chainId,\n },\n );\n }\n } catch (error) {\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxConfirmationFailed,\n category: MetaMetricsEventCategory.Transactions,\n });\n console.error('confirm error', error);\n }\n }\n\n // ! Ask backend API to accept list of uuids as params\n async fetchSmartTransactionsStatus(\n uuids: string[],\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ): Promise<Record<string, SmartTransactionsStatus>> {\n const params = new URLSearchParams({\n uuids: uuids.join(','),\n });\n const chainId = this.#getChainId({ networkClientId });\n const ethQuery = this.#getEthQuery({ networkClientId });\n const url = `${getAPIRequestURL(\n APIType.BATCH_STATUS,\n chainId,\n )}?${params.toString()}`;\n\n const data = (await this.fetch(url)) as Record<\n string,\n SmartTransactionsStatus\n >;\n\n for (const [uuid, stxStatus] of Object.entries(data)) {\n const smartTransaction: SmartTransaction = {\n statusMetadata: stxStatus,\n status: calculateStatus(stxStatus),\n cancellable: isSmartTransactionCancellable(stxStatus),\n uuid,\n };\n await this.#createOrUpdateSmartTransaction(smartTransaction, {\n chainId,\n ethQuery,\n });\n }\n\n return data;\n }\n\n async addNonceToTransaction(\n transaction: UnsignedTransaction,\n ): Promise<UnsignedTransaction> {\n const nonceLock = await this.getNonceLock(transaction.from);\n const nonce = nonceLock.nextNonce;\n nonceLock.releaseLock();\n return {\n ...transaction,\n nonce: `0x${nonce.toString(16)}`,\n };\n }\n\n clearFees(): Fees {\n const fees = {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n };\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n fees,\n },\n });\n return fees;\n }\n\n async getFees(\n tradeTx: UnsignedTransaction,\n approvalTx?: UnsignedTransaction,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ): Promise<Fees> {\n const chainId = this.#getChainId({ networkClientId });\n const transactions = [];\n let unsignedTradeTransactionWithNonce;\n if (approvalTx) {\n const unsignedApprovalTransactionWithNonce =\n await this.addNonceToTransaction(approvalTx);\n transactions.push(unsignedApprovalTransactionWithNonce);\n unsignedTradeTransactionWithNonce = {\n ...tradeTx,\n // If there is an approval tx, the trade tx's nonce is increased by 1.\n nonce: incrementNonceInHex(unsignedApprovalTransactionWithNonce.nonce),\n };\n } else if (tradeTx.nonce) {\n unsignedTradeTransactionWithNonce = tradeTx;\n } else {\n unsignedTradeTransactionWithNonce = await this.addNonceToTransaction(\n tradeTx,\n );\n }\n transactions.push(unsignedTradeTransactionWithNonce);\n const data = await this.fetch(getAPIRequestURL(APIType.GET_FEES, chainId), {\n method: 'POST',\n body: JSON.stringify({\n txs: transactions,\n }),\n });\n let approvalTxFees;\n let tradeTxFees;\n if (approvalTx) {\n approvalTxFees = data?.txs[0];\n tradeTxFees = data?.txs[1];\n } else {\n tradeTxFees = data?.txs[0];\n }\n\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n ...(chainId === this.config.chainId && {\n fees: {\n approvalTxFees,\n tradeTxFees,\n },\n }),\n feesByChainId: {\n ...this.state.smartTransactionsState.feesByChainId,\n [chainId]: {\n approvalTxFees,\n tradeTxFees,\n },\n },\n },\n });\n\n return {\n approvalTxFees,\n tradeTxFees,\n };\n }\n\n // * After this successful call client must add a nonce representative to\n // * transaction controller external transactions list\n async submitSignedTransactions({\n transactionMeta,\n txParams,\n signedTransactions,\n signedCanceledTransactions,\n networkClientId,\n }: {\n signedTransactions: SignedTransaction[];\n signedCanceledTransactions: SignedCanceledTransaction[];\n transactionMeta?: any;\n txParams?: any;\n networkClientId?: NetworkClientId;\n }) {\n const chainId = this.#getChainId({ networkClientId });\n const ethQuery = this.#getEthQuery({ networkClientId });\n const data = await this.fetch(\n getAPIRequestURL(APIType.SUBMIT_TRANSACTIONS, chainId),\n {\n method: 'POST',\n body: JSON.stringify({\n rawTxs: signedTransactions,\n rawCancelTxs: signedCanceledTransactions,\n }),\n },\n );\n const time = Date.now();\n let preTxBalance;\n try {\n const preTxBalanceBN = await query(ethQuery, 'getBalance', [\n txParams?.from,\n ]);\n preTxBalance = new BigNumber(preTxBalanceBN).toString(16);\n } catch (error) {\n console.error('provider error', error);\n }\n\n const requiresNonce = !txParams.nonce;\n let nonce;\n let nonceLock;\n let nonceDetails = {};\n\n if (requiresNonce) {\n nonceLock = await this.getNonceLock(txParams?.from);\n nonce = hexlify(nonceLock.nextNonce);\n nonceDetails = nonceLock.nonceDetails;\n if (txParams) {\n txParams.nonce ??= nonce;\n }\n }\n const submitTransactionResponse = {\n ...data,\n txHash: getTxHash(signedTransactions[0]),\n };\n\n try {\n await this.#createOrUpdateSmartTransaction(\n {\n chainId,\n nonceDetails,\n preTxBalance,\n status: SmartTransactionStatuses.PENDING,\n time,\n txParams,\n uuid: submitTransactionResponse.uuid,\n txHash: submitTransactionResponse.txHash,\n cancellable: true,\n type: transactionMeta?.type || 'swap',\n },\n { chainId, ethQuery },\n );\n } finally {\n nonceLock?.releaseLock();\n }\n\n return submitTransactionResponse;\n }\n\n #getChainId({\n networkClientId,\n }: { networkClientId?: NetworkClientId } = {}): Hex {\n return networkClientId\n ? this.getNetworkClientById(networkClientId).configuration.chainId\n : this.config.chainId;\n }\n\n #getEthQuery({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): EthQuery {\n if (networkClientId) {\n return new EthQuery(this.getNetworkClientById(networkClientId).provider);\n }\n\n if (this.ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n\n return this.ethQuery;\n }\n\n // TODO: This should return if the cancellation was on chain or not (for nonce management)\n // After this successful call client must update nonce representative\n // in transaction controller external transactions list\n async cancelSmartTransaction(\n uuid: string,\n {\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {},\n ): Promise<void> {\n const chainId = this.#getChainId({ networkClientId });\n await this.fetch(getAPIRequestURL(APIType.CANCEL, chainId), {\n method: 'POST',\n body: JSON.stringify({ uuid }),\n });\n }\n\n async fetchLiveness({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): Promise<boolean> {\n const chainId = this.#getChainId({ networkClientId });\n let liveness = false;\n try {\n const response = await this.fetch(\n getAPIRequestURL(APIType.LIVENESS, chainId),\n );\n liveness = Boolean(response.lastBlock);\n } catch (error) {\n console.log('\"fetchLiveness\" API call failed');\n }\n\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n ...(chainId === this.config.chainId && { liveness }),\n livenessByChainId: {\n ...this.state.smartTransactionsState.livenessByChainId,\n [chainId]: liveness,\n },\n },\n });\n\n return liveness;\n }\n\n async setStatusRefreshInterval(interval: number): Promise<void> {\n if (interval !== this.config.interval) {\n this.configure({ interval }, false, false);\n }\n }\n\n #getCurrentSmartTransactions(): SmartTransaction[] {\n const { smartTransactions } = this.state.smartTransactionsState;\n const { chainId } = this.config;\n const currentSmartTransactions = smartTransactions?.[chainId];\n if (!currentSmartTransactions || currentSmartTransactions.length === 0) {\n return [];\n }\n return currentSmartTransactions;\n }\n\n getTransactions({\n addressFrom,\n status,\n }: {\n addressFrom: string;\n status: SmartTransactionStatuses;\n }): SmartTransaction[] {\n const currentSmartTransactions = this.#getCurrentSmartTransactions();\n return currentSmartTransactions.filter((stx) => {\n return stx.status === status && stx.txParams?.from === addressFrom;\n });\n }\n\n getSmartTransactionByMinedTxHash(\n txHash: string | undefined,\n ): SmartTransaction | undefined {\n if (!txHash) {\n return undefined;\n }\n const currentSmartTransactions = this.#getCurrentSmartTransactions();\n return currentSmartTransactions.find((smartTransaction) => {\n return (\n smartTransaction.statusMetadata?.minedHash?.toLowerCase() ===\n txHash.toLowerCase()\n );\n });\n }\n\n wipeSmartTransactions({\n address,\n ignoreNetwork,\n }: {\n address: string;\n ignoreNetwork?: boolean;\n }): void {\n if (!address) {\n return;\n }\n const addressLowerCase = address.toLowerCase();\n if (ignoreNetwork) {\n const { smartTransactions } = this.state.smartTransactionsState;\n Object.keys(smartTransactions).forEach((chainId) => {\n const chainIdHex: Hex = chainId as Hex;\n this.#wipeSmartTransactionsPerChainId({\n chainId: chainIdHex,\n addressLowerCase,\n });\n });\n } else {\n this.#wipeSmartTransactionsPerChainId({\n chainId: this.config.chainId,\n addressLowerCase,\n });\n }\n }\n\n #wipeSmartTransactionsPerChainId({\n chainId,\n addressLowerCase,\n }: {\n chainId: Hex;\n addressLowerCase: string;\n }): void {\n const { smartTransactions } = this.state.smartTransactionsState;\n const smartTransactionsForSelectedChain: SmartTransaction[] =\n smartTransactions?.[chainId];\n if (\n !smartTransactionsForSelectedChain ||\n smartTransactionsForSelectedChain.length === 0\n ) {\n return;\n }\n const newSmartTransactionsForSelectedChain =\n smartTransactionsForSelectedChain.filter(\n (smartTransaction: SmartTransaction) =>\n smartTransaction.txParams?.from !== addressLowerCase,\n );\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n smartTransactions: {\n ...smartTransactions,\n [chainId]: newSmartTransactionsForSelectedChain,\n },\n },\n });\n }\n}\n"]}
@@ -22,3 +22,4 @@ export declare function advanceTime({ clock, duration, stepSize, }: {
22
22
  duration: number;
23
23
  stepSize?: number;
24
24
  }): Promise<void>;
25
+ export declare function getFakeProvider(): import("@metamask/eth-json-rpc-provider").SafeEventEmitterProvider;
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.advanceTime = exports.flushPromises = void 0;
3
+ exports.getFakeProvider = exports.advanceTime = exports.flushPromises = void 0;
4
+ const eth_json_rpc_provider_1 = require("@metamask/eth-json-rpc-provider");
5
+ const json_rpc_engine_1 = require("@metamask/json-rpc-engine");
4
6
  /**
5
7
  * Resolve all pending promises.
6
8
  * This method is used for async tests that use fake timers.
@@ -31,4 +33,8 @@ async function advanceTime({ clock, duration, stepSize = Math.floor(duration / 4
31
33
  } while (duration > 0);
32
34
  }
33
35
  exports.advanceTime = advanceTime;
36
+ function getFakeProvider() {
37
+ return (0, eth_json_rpc_provider_1.providerFromEngine)(new json_rpc_engine_1.JsonRpcEngine());
38
+ }
39
+ exports.getFakeProvider = getFakeProvider;
34
40
  //# sourceMappingURL=test-helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"test-helpers.js","sourceRoot":"","sources":["../src/test-helpers.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACI,MAAM,aAAa,GAAG,KAAK,IAAI,EAAE;IACtC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,YAAY,CAAC,CAAC;AAChE,CAAC,CAAC;AAFW,QAAA,aAAa,iBAExB;AAEF;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,WAAW,CAAC,EAChC,KAAK,EACL,QAAQ,EACR,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC,GAKpC;IACC,GAAG;QACD,MAAM,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAChC,MAAM,IAAA,qBAAa,GAAE,CAAC;QACtB,6CAA6C;QAC7C,QAAQ,IAAI,QAAQ,CAAC;KACtB,QAAQ,QAAQ,GAAG,CAAC,EAAE;AACzB,CAAC;AAfD,kCAeC","sourcesContent":["/**\n * Resolve all pending promises.\n * This method is used for async tests that use fake timers.\n * See https://stackoverflow.com/a/58716087 and https://jestjs.io/docs/timer-mocks.\n */\nexport const flushPromises = async () => {\n return new Promise(jest.requireActual('timers').setImmediate);\n};\n\n/**\n * Advances the provided fake timer by a specified duration in incremental steps.\n * Between each step, any enqueued promises are processed. Fake timers in testing libraries\n * allow simulation of time without actually waiting. However, they don't always account for\n * promises or other asynchronous operations that may get enqueued during the timer's duration.\n * By advancing time in incremental steps and flushing promises between each step,\n * this function ensures that both timers and promises are comprehensively processed.\n * @param options - The options object.\n * @param options.clock - The Sinon fake timer instance used to manipulate time in tests.\n * @param options.duration - The total amount of time (in milliseconds) to advance the timer by.\n * @param options.stepSize - The incremental step size (in milliseconds) by which the timer is advanced in each iteration. Default is 1/4 of the duration.\n */\nexport async function advanceTime({\n clock,\n duration,\n stepSize = Math.floor(duration / 4),\n}: {\n clock: sinon.SinonFakeTimers;\n duration: number;\n stepSize?: number;\n}): Promise<void> {\n do {\n await clock.tickAsync(stepSize);\n await flushPromises();\n // eslint-disable-next-line no-param-reassign\n duration -= stepSize;\n } while (duration > 0);\n}\n"]}
1
+ {"version":3,"file":"test-helpers.js","sourceRoot":"","sources":["../src/test-helpers.ts"],"names":[],"mappings":";;;AAAA,2EAAqE;AACrE,+DAA0D;AAE1D;;;;GAIG;AACI,MAAM,aAAa,GAAG,KAAK,IAAI,EAAE;IACtC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,YAAY,CAAC,CAAC;AAChE,CAAC,CAAC;AAFW,QAAA,aAAa,iBAExB;AAEF;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,WAAW,CAAC,EAChC,KAAK,EACL,QAAQ,EACR,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC,GAKpC;IACC,GAAG;QACD,MAAM,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAChC,MAAM,IAAA,qBAAa,GAAE,CAAC;QACtB,6CAA6C;QAC7C,QAAQ,IAAI,QAAQ,CAAC;KACtB,QAAQ,QAAQ,GAAG,CAAC,EAAE;AACzB,CAAC;AAfD,kCAeC;AAED,SAAgB,eAAe;IAC7B,OAAO,IAAA,0CAAkB,EAAC,IAAI,+BAAa,EAAE,CAAC,CAAC;AACjD,CAAC;AAFD,0CAEC","sourcesContent":["import { providerFromEngine } from '@metamask/eth-json-rpc-provider';\nimport { JsonRpcEngine } from '@metamask/json-rpc-engine';\n\n/**\n * Resolve all pending promises.\n * This method is used for async tests that use fake timers.\n * See https://stackoverflow.com/a/58716087 and https://jestjs.io/docs/timer-mocks.\n */\nexport const flushPromises = async () => {\n return new Promise(jest.requireActual('timers').setImmediate);\n};\n\n/**\n * Advances the provided fake timer by a specified duration in incremental steps.\n * Between each step, any enqueued promises are processed. Fake timers in testing libraries\n * allow simulation of time without actually waiting. However, they don't always account for\n * promises or other asynchronous operations that may get enqueued during the timer's duration.\n * By advancing time in incremental steps and flushing promises between each step,\n * this function ensures that both timers and promises are comprehensively processed.\n * @param options - The options object.\n * @param options.clock - The Sinon fake timer instance used to manipulate time in tests.\n * @param options.duration - The total amount of time (in milliseconds) to advance the timer by.\n * @param options.stepSize - The incremental step size (in milliseconds) by which the timer is advanced in each iteration. Default is 1/4 of the duration.\n */\nexport async function advanceTime({\n clock,\n duration,\n stepSize = Math.floor(duration / 4),\n}: {\n clock: sinon.SinonFakeTimers;\n duration: number;\n stepSize?: number;\n}): Promise<void> {\n do {\n await clock.tickAsync(stepSize);\n await flushPromises();\n // eslint-disable-next-line no-param-reassign\n duration -= stepSize;\n } while (duration > 0);\n}\n\nexport function getFakeProvider() {\n return providerFromEngine(new JsonRpcEngine());\n}\n"]}
package/dist/types.d.ts CHANGED
@@ -81,6 +81,9 @@ export declare type SmartTransaction = {
81
81
  type?: string;
82
82
  confirmed?: boolean;
83
83
  cancellable?: boolean;
84
+ accountHardwareType?: string;
85
+ accountType?: string;
86
+ deviceModel?: string;
84
87
  };
85
88
  export declare type Fee = {
86
89
  maxFeePerGas: number;
@@ -107,3 +110,8 @@ export declare type GetTransactionsOptions = {
107
110
  filterToCurrentNetwork?: boolean;
108
111
  limit?: number;
109
112
  };
113
+ export declare type MetaMetricsProps = {
114
+ accountHardwareType?: string;
115
+ accountType?: string;
116
+ deviceModel?: string;
117
+ };
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAEA,UAAU;AACV,IAAY,OAOX;AAPD,WAAY,OAAO;IACjB,6CAAU,CAAA;IACV,qDAAc,CAAA;IACd,mEAAqB,CAAA;IACrB,yCAAQ,CAAA;IACR,qDAAc,CAAA;IACd,6CAAU,CAAA;AACZ,CAAC,EAPW,OAAO,GAAP,eAAO,KAAP,eAAO,QAOlB;AAED,wBAAwB;AACxB,IAAY,uBAMX;AAND,WAAY,uBAAuB;IACjC,kDAAuB,CAAA;IACvB,8CAAmB,CAAA;IACnB,kDAAuB,CAAA;IACvB,gDAAqB,CAAA;IACrB,8CAAmB,CAAA;AACrB,CAAC,EANW,uBAAuB,GAAvB,+BAAuB,KAAvB,+BAAuB,QAMlC;AAED,IAAY,kCAQX;AARD,WAAY,kCAAkC;IAC5C,mEAA6B,CAAA;IAC7B,6DAAuB,CAAA;IACvB,yEAAmC,CAAA;IACnC,qEAA+B,CAAA;IAC/B,uEAAiC,CAAA;IACjC,qEAA+B,CAAA;IAC/B,qFAA+C,CAAA;AACjD,CAAC,EARW,kCAAkC,GAAlC,0CAAkC,KAAlC,0CAAkC,QAQ7C;AAED,IAAY,wBAaX;AAbD,WAAY,wBAAwB;IAClC,+CAAmB,CAAA;IACnB,+CAAmB,CAAA;IACnB,iDAAqB,CAAA;IACrB,+CAAmB,CAAA;IACnB,mDAAuB,CAAA;IACvB,6EAAiD,CAAA;IACjD,uEAA2C,CAAA;IAC3C,mFAAuD,CAAA;IACvD,+EAAmD,CAAA;IACnD,iFAAqD,CAAA;IACrD,+FAAmE,CAAA;IACnE,iDAAqB,CAAA;AACvB,CAAC,EAbW,wBAAwB,GAAxB,gCAAwB,KAAxB,gCAAwB,QAanC;AAEY,QAAA,6BAA6B,GAAG;IAC3C,CAAC,kCAAkC,CAAC,YAAY,CAAC,EAC/C,wBAAwB,CAAC,sBAAsB;IACjD,CAAC,kCAAkC,CAAC,SAAS,CAAC,EAC5C,wBAAwB,CAAC,mBAAmB;IAC9C,CAAC,kCAAkC,CAAC,eAAe,CAAC,EAClD,wBAAwB,CAAC,yBAAyB;IACpD,CAAC,kCAAkC,CAAC,aAAa,CAAC,EAChD,wBAAwB,CAAC,uBAAuB;IAClD,CAAC,kCAAkC,CAAC,cAAc,CAAC,EACjD,wBAAwB,CAAC,wBAAwB;IACnD,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,EACxD,wBAAwB,CAAC,+BAA+B;CAC3D,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\n\n/** API */\nexport enum APIType {\n 'GET_FEES',\n 'ESTIMATE_GAS',\n 'SUBMIT_TRANSACTIONS',\n 'CANCEL',\n 'BATCH_STATUS',\n 'LIVENESS',\n}\n\n/** SmartTransactions */\nexport enum SmartTransactionMinedTx {\n NOT_MINED = 'not_mined',\n SUCCESS = 'success',\n CANCELLED = 'cancelled',\n REVERTED = 'reverted',\n UNKNOWN = 'unknown',\n}\n\nexport enum SmartTransactionCancellationReason {\n WOULD_REVERT = 'would_revert',\n TOO_CHEAP = 'too_cheap',\n DEADLINE_MISSED = 'deadline_missed',\n INVALID_NONCE = 'invalid_nonce',\n USER_CANCELLED = 'user_cancelled',\n NOT_CANCELLED = 'not_cancelled',\n PREVIOUS_TX_CANCELLED = 'previous_tx_cancelled',\n}\n\nexport enum SmartTransactionStatuses {\n PENDING = 'pending',\n SUCCESS = 'success',\n REVERTED = 'reverted',\n UNKNOWN = 'unknown',\n CANCELLED = 'cancelled',\n CANCELLED_WOULD_REVERT = 'cancelled_would_revert',\n CANCELLED_TOO_CHEAP = 'cancelled_too_cheap',\n CANCELLED_DEADLINE_MISSED = 'cancelled_deadline_missed',\n CANCELLED_INVALID_NONCE = 'cancelled_invalid_nonce',\n CANCELLED_USER_CANCELLED = 'cancelled_user_cancelled',\n CANCELLED_PREVIOUS_TX_CANCELLED = 'cancelled_previous_tx_cancelled',\n RESOLVED = 'resolved',\n}\n\nexport const cancellationReasonToStatusMap = {\n [SmartTransactionCancellationReason.WOULD_REVERT]:\n SmartTransactionStatuses.CANCELLED_WOULD_REVERT,\n [SmartTransactionCancellationReason.TOO_CHEAP]:\n SmartTransactionStatuses.CANCELLED_TOO_CHEAP,\n [SmartTransactionCancellationReason.DEADLINE_MISSED]:\n SmartTransactionStatuses.CANCELLED_DEADLINE_MISSED,\n [SmartTransactionCancellationReason.INVALID_NONCE]:\n SmartTransactionStatuses.CANCELLED_INVALID_NONCE,\n [SmartTransactionCancellationReason.USER_CANCELLED]:\n SmartTransactionStatuses.CANCELLED_USER_CANCELLED,\n [SmartTransactionCancellationReason.PREVIOUS_TX_CANCELLED]:\n SmartTransactionStatuses.CANCELLED_PREVIOUS_TX_CANCELLED,\n};\n\nexport type SmartTransactionsStatus = {\n error?: string;\n cancellationFeeWei: number;\n cancellationReason?: SmartTransactionCancellationReason;\n deadlineRatio: number;\n minedHash: string;\n minedTx: SmartTransactionMinedTx;\n isSettled: boolean;\n duplicated?: boolean;\n timedOut?: boolean;\n proxied?: boolean;\n};\n\nexport type SmartTransaction = {\n uuid: string;\n txHash?: string;\n chainId?: string;\n destinationTokenAddress?: string;\n destinationTokenDecimals?: string;\n destinationTokenSymbol?: string;\n history?: any;\n nonceDetails?: any;\n origin?: string;\n preTxBalance?: string;\n status?: string;\n statusMetadata?: SmartTransactionsStatus;\n sourceTokenSymbol?: string;\n swapMetaData?: any;\n swapTokenValue?: string;\n time?: number; // @deprecated We should use creationTime instead.\n creationTime?: number;\n txParams?: any;\n type?: string;\n confirmed?: boolean;\n cancellable?: boolean;\n};\n\nexport type Fee = {\n maxFeePerGas: number;\n maxPriorityFeePerGas: number;\n};\n\nexport type IndividualTxFees = {\n fees: Fee[];\n cancelFees: Fee[];\n feeEstimate: number;\n gasLimit: number;\n gasUsed: number;\n};\n\nexport type Fees = {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n};\n\n// TODO\nexport type UnsignedTransaction = any;\n\n// TODO\nexport type SignedTransaction = any;\n\n// TODO\nexport type SignedCanceledTransaction = any;\n\nexport type Hex = `0x${string}`;\n\nexport type GetTransactionsOptions = {\n searchCriteria?: any;\n initialList?: TransactionMeta[];\n filterToCurrentNetwork?: boolean;\n limit?: number;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAEA,UAAU;AACV,IAAY,OAOX;AAPD,WAAY,OAAO;IACjB,6CAAU,CAAA;IACV,qDAAc,CAAA;IACd,mEAAqB,CAAA;IACrB,yCAAQ,CAAA;IACR,qDAAc,CAAA;IACd,6CAAU,CAAA;AACZ,CAAC,EAPW,OAAO,GAAP,eAAO,KAAP,eAAO,QAOlB;AAED,wBAAwB;AACxB,IAAY,uBAMX;AAND,WAAY,uBAAuB;IACjC,kDAAuB,CAAA;IACvB,8CAAmB,CAAA;IACnB,kDAAuB,CAAA;IACvB,gDAAqB,CAAA;IACrB,8CAAmB,CAAA;AACrB,CAAC,EANW,uBAAuB,GAAvB,+BAAuB,KAAvB,+BAAuB,QAMlC;AAED,IAAY,kCAQX;AARD,WAAY,kCAAkC;IAC5C,mEAA6B,CAAA;IAC7B,6DAAuB,CAAA;IACvB,yEAAmC,CAAA;IACnC,qEAA+B,CAAA;IAC/B,uEAAiC,CAAA;IACjC,qEAA+B,CAAA;IAC/B,qFAA+C,CAAA;AACjD,CAAC,EARW,kCAAkC,GAAlC,0CAAkC,KAAlC,0CAAkC,QAQ7C;AAED,IAAY,wBAaX;AAbD,WAAY,wBAAwB;IAClC,+CAAmB,CAAA;IACnB,+CAAmB,CAAA;IACnB,iDAAqB,CAAA;IACrB,+CAAmB,CAAA;IACnB,mDAAuB,CAAA;IACvB,6EAAiD,CAAA;IACjD,uEAA2C,CAAA;IAC3C,mFAAuD,CAAA;IACvD,+EAAmD,CAAA;IACnD,iFAAqD,CAAA;IACrD,+FAAmE,CAAA;IACnE,iDAAqB,CAAA;AACvB,CAAC,EAbW,wBAAwB,GAAxB,gCAAwB,KAAxB,gCAAwB,QAanC;AAEY,QAAA,6BAA6B,GAAG;IAC3C,CAAC,kCAAkC,CAAC,YAAY,CAAC,EAC/C,wBAAwB,CAAC,sBAAsB;IACjD,CAAC,kCAAkC,CAAC,SAAS,CAAC,EAC5C,wBAAwB,CAAC,mBAAmB;IAC9C,CAAC,kCAAkC,CAAC,eAAe,CAAC,EAClD,wBAAwB,CAAC,yBAAyB;IACpD,CAAC,kCAAkC,CAAC,aAAa,CAAC,EAChD,wBAAwB,CAAC,uBAAuB;IAClD,CAAC,kCAAkC,CAAC,cAAc,CAAC,EACjD,wBAAwB,CAAC,wBAAwB;IACnD,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,EACxD,wBAAwB,CAAC,+BAA+B;CAC3D,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\n\n/** API */\nexport enum APIType {\n 'GET_FEES',\n 'ESTIMATE_GAS',\n 'SUBMIT_TRANSACTIONS',\n 'CANCEL',\n 'BATCH_STATUS',\n 'LIVENESS',\n}\n\n/** SmartTransactions */\nexport enum SmartTransactionMinedTx {\n NOT_MINED = 'not_mined',\n SUCCESS = 'success',\n CANCELLED = 'cancelled',\n REVERTED = 'reverted',\n UNKNOWN = 'unknown',\n}\n\nexport enum SmartTransactionCancellationReason {\n WOULD_REVERT = 'would_revert',\n TOO_CHEAP = 'too_cheap',\n DEADLINE_MISSED = 'deadline_missed',\n INVALID_NONCE = 'invalid_nonce',\n USER_CANCELLED = 'user_cancelled',\n NOT_CANCELLED = 'not_cancelled',\n PREVIOUS_TX_CANCELLED = 'previous_tx_cancelled',\n}\n\nexport enum SmartTransactionStatuses {\n PENDING = 'pending',\n SUCCESS = 'success',\n REVERTED = 'reverted',\n UNKNOWN = 'unknown',\n CANCELLED = 'cancelled',\n CANCELLED_WOULD_REVERT = 'cancelled_would_revert',\n CANCELLED_TOO_CHEAP = 'cancelled_too_cheap',\n CANCELLED_DEADLINE_MISSED = 'cancelled_deadline_missed',\n CANCELLED_INVALID_NONCE = 'cancelled_invalid_nonce',\n CANCELLED_USER_CANCELLED = 'cancelled_user_cancelled',\n CANCELLED_PREVIOUS_TX_CANCELLED = 'cancelled_previous_tx_cancelled',\n RESOLVED = 'resolved',\n}\n\nexport const cancellationReasonToStatusMap = {\n [SmartTransactionCancellationReason.WOULD_REVERT]:\n SmartTransactionStatuses.CANCELLED_WOULD_REVERT,\n [SmartTransactionCancellationReason.TOO_CHEAP]:\n SmartTransactionStatuses.CANCELLED_TOO_CHEAP,\n [SmartTransactionCancellationReason.DEADLINE_MISSED]:\n SmartTransactionStatuses.CANCELLED_DEADLINE_MISSED,\n [SmartTransactionCancellationReason.INVALID_NONCE]:\n SmartTransactionStatuses.CANCELLED_INVALID_NONCE,\n [SmartTransactionCancellationReason.USER_CANCELLED]:\n SmartTransactionStatuses.CANCELLED_USER_CANCELLED,\n [SmartTransactionCancellationReason.PREVIOUS_TX_CANCELLED]:\n SmartTransactionStatuses.CANCELLED_PREVIOUS_TX_CANCELLED,\n};\n\nexport type SmartTransactionsStatus = {\n error?: string;\n cancellationFeeWei: number;\n cancellationReason?: SmartTransactionCancellationReason;\n deadlineRatio: number;\n minedHash: string;\n minedTx: SmartTransactionMinedTx;\n isSettled: boolean;\n duplicated?: boolean;\n timedOut?: boolean;\n proxied?: boolean;\n};\n\nexport type SmartTransaction = {\n uuid: string;\n txHash?: string;\n chainId?: string;\n destinationTokenAddress?: string;\n destinationTokenDecimals?: string;\n destinationTokenSymbol?: string;\n history?: any;\n nonceDetails?: any;\n origin?: string;\n preTxBalance?: string;\n status?: string;\n statusMetadata?: SmartTransactionsStatus;\n sourceTokenSymbol?: string;\n swapMetaData?: any;\n swapTokenValue?: string;\n time?: number; // @deprecated We should use creationTime instead.\n creationTime?: number;\n txParams?: any;\n type?: string;\n confirmed?: boolean;\n cancellable?: boolean;\n accountHardwareType?: string;\n accountType?: string;\n deviceModel?: string;\n};\n\nexport type Fee = {\n maxFeePerGas: number;\n maxPriorityFeePerGas: number;\n};\n\nexport type IndividualTxFees = {\n fees: Fee[];\n cancelFees: Fee[];\n feeEstimate: number;\n gasLimit: number;\n gasUsed: number;\n};\n\nexport type Fees = {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n};\n\n// TODO\nexport type UnsignedTransaction = any;\n\n// TODO\nexport type SignedTransaction = any;\n\n// TODO\nexport type SignedCanceledTransaction = any;\n\nexport type Hex = `0x${string}`;\n\nexport type GetTransactionsOptions = {\n searchCriteria?: any;\n initialList?: TransactionMeta[];\n filterToCurrentNetwork?: boolean;\n limit?: number;\n};\n\nexport type MetaMetricsProps = {\n accountHardwareType?: string;\n accountType?: string;\n deviceModel?: string;\n};\n"]}
package/dist/utils.d.ts CHANGED
@@ -39,3 +39,39 @@ export declare function handleFetch(request: string, options?: RequestInit): Pro
39
39
  export declare const isSmartTransactionCancellable: (stxStatus: SmartTransactionsStatus) => boolean;
40
40
  export declare const incrementNonceInHex: (nonceInHex: string) => string;
41
41
  export declare const getTxHash: (signedTxHex: any) => string;
42
+ export declare const getSmartTransactionMetricsProperties: (smartTransaction: SmartTransaction) => {
43
+ stx_status?: undefined;
44
+ type?: undefined;
45
+ processing_time?: undefined;
46
+ is_smart_transaction?: undefined;
47
+ stx_enabled?: undefined;
48
+ current_stx_enabled?: undefined;
49
+ stx_user_opt_in?: undefined;
50
+ stx_duplicated?: undefined;
51
+ stx_timed_out?: undefined;
52
+ stx_proxied?: undefined;
53
+ } | {
54
+ stx_status: string | undefined;
55
+ type: string | undefined;
56
+ processing_time: number | undefined;
57
+ is_smart_transaction: boolean;
58
+ stx_enabled: boolean;
59
+ current_stx_enabled: boolean;
60
+ stx_user_opt_in: boolean;
61
+ stx_duplicated: boolean | undefined;
62
+ stx_timed_out: boolean | undefined;
63
+ stx_proxied: boolean | undefined;
64
+ };
65
+ export declare const getSmartTransactionMetricsSensitiveProperties: (smartTransaction: SmartTransaction) => {
66
+ token_from_symbol?: undefined;
67
+ token_to_symbol?: undefined;
68
+ account_hardware_type?: undefined;
69
+ account_type?: undefined;
70
+ device_model?: undefined;
71
+ } | {
72
+ token_from_symbol: string | undefined;
73
+ token_to_symbol: string | undefined;
74
+ account_hardware_type: string | undefined;
75
+ account_type: string | undefined;
76
+ device_model: string | undefined;
77
+ };
package/dist/utils.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getTxHash = exports.incrementNonceInHex = exports.isSmartTransactionCancellable = exports.handleFetch = exports.mapKeysToCamel = exports.getStxProcessingTime = exports.snapshotFromTxMeta = exports.replayHistory = exports.generateHistoryEntry = exports.calculateStatus = exports.getAPIRequestURL = exports.isSmartTransactionStatusResolved = exports.isSmartTransactionPending = void 0;
6
+ exports.getSmartTransactionMetricsSensitiveProperties = exports.getSmartTransactionMetricsProperties = exports.getTxHash = exports.incrementNonceInHex = exports.isSmartTransactionCancellable = exports.handleFetch = exports.mapKeysToCamel = exports.getStxProcessingTime = exports.snapshotFromTxMeta = exports.replayHistory = exports.generateHistoryEntry = exports.calculateStatus = exports.getAPIRequestURL = exports.isSmartTransactionStatusResolved = exports.isSmartTransactionPending = void 0;
7
7
  const tx_1 = require("@ethereumjs/tx");
8
8
  const util_1 = require("@ethereumjs/util");
9
9
  const bytes_1 = require("@ethersproject/bytes");
@@ -195,4 +195,36 @@ const getTxHash = (signedTxHex) => {
195
195
  return (0, util_1.bytesToHex)(txHashBytes);
196
196
  };
197
197
  exports.getTxHash = getTxHash;
198
+ const getSmartTransactionMetricsProperties = (smartTransaction) => {
199
+ if (!smartTransaction) {
200
+ return {};
201
+ }
202
+ const smartTransactionStatusMetadata = smartTransaction.statusMetadata;
203
+ return {
204
+ stx_status: smartTransaction.status,
205
+ type: smartTransaction.type,
206
+ processing_time: (0, exports.getStxProcessingTime)(smartTransaction.time),
207
+ is_smart_transaction: true,
208
+ stx_enabled: true,
209
+ current_stx_enabled: true,
210
+ stx_user_opt_in: true,
211
+ stx_duplicated: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.duplicated,
212
+ stx_timed_out: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.timedOut,
213
+ stx_proxied: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.proxied,
214
+ };
215
+ };
216
+ exports.getSmartTransactionMetricsProperties = getSmartTransactionMetricsProperties;
217
+ const getSmartTransactionMetricsSensitiveProperties = (smartTransaction) => {
218
+ if (!smartTransaction) {
219
+ return {};
220
+ }
221
+ return {
222
+ token_from_symbol: smartTransaction.sourceTokenSymbol,
223
+ token_to_symbol: smartTransaction.destinationTokenSymbol,
224
+ account_hardware_type: smartTransaction.accountHardwareType,
225
+ account_type: smartTransaction.accountType,
226
+ device_model: smartTransaction.deviceModel,
227
+ };
228
+ };
229
+ exports.getSmartTransactionMetricsSensitiveProperties = getSmartTransactionMetricsSensitiveProperties;
198
230
  //# sourceMappingURL=utils.js.map
package/dist/utils.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAAA,uCAAoD;AACpD,2CAA8C;AAC9C,gDAA+C;AAC/C,+CAAyC;AACzC,sEAAyC;AACzC,oDAAuB;AAEvB,6DAA6D;AAC7D,2CA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import { hexlify } from '@ethersproject/bytes';\nimport { BigNumber } from 'bignumber.js';\nimport jsonDiffer from 'fast-json-patch';\nimport _ from 'lodash';\n\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\nimport { API_BASE_URL } from './constants';\nimport type { SmartTransaction, SmartTransactionsStatus } from './types';\nimport {\n APIType,\n SmartTransactionStatuses,\n SmartTransactionCancellationReason,\n SmartTransactionMinedTx,\n cancellationReasonToStatusMap,\n} from './types';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport packageJson from '../package.json';\n\nexport function isSmartTransactionPending(smartTransaction: SmartTransaction) {\n return smartTransaction.status === SmartTransactionStatuses.PENDING;\n}\n\nexport const isSmartTransactionStatusResolved = (\n stxStatus: SmartTransactionsStatus | string,\n) => stxStatus === 'uuid_not_found';\n\n// TODO use actual url once API is defined\nexport function getAPIRequestURL(apiType: APIType, chainId: string): string {\n const chainIdDec = parseInt(chainId, 16);\n switch (apiType) {\n case APIType.GET_FEES: {\n return `${API_BASE_URL}/networks/${chainIdDec}/getFees`;\n }\n\n case APIType.ESTIMATE_GAS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/estimateGas`;\n }\n\n case APIType.SUBMIT_TRANSACTIONS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`;\n }\n\n case APIType.CANCEL: {\n return `${API_BASE_URL}/networks/${chainIdDec}/cancel`;\n }\n\n case APIType.BATCH_STATUS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/batchStatus`;\n }\n\n case APIType.LIVENESS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/health`;\n }\n\n default: {\n throw new Error(`Invalid APIType`); // It can never get here thanks to TypeScript.\n }\n }\n}\n\nexport const calculateStatus = (stxStatus: SmartTransactionsStatus) => {\n if (isSmartTransactionStatusResolved(stxStatus)) {\n return SmartTransactionStatuses.RESOLVED;\n }\n const cancellations = [\n SmartTransactionCancellationReason.WOULD_REVERT,\n SmartTransactionCancellationReason.TOO_CHEAP,\n SmartTransactionCancellationReason.DEADLINE_MISSED,\n SmartTransactionCancellationReason.INVALID_NONCE,\n SmartTransactionCancellationReason.USER_CANCELLED,\n SmartTransactionCancellationReason.PREVIOUS_TX_CANCELLED,\n ];\n if (stxStatus?.minedTx === SmartTransactionMinedTx.NOT_MINED) {\n if (\n stxStatus.cancellationReason ===\n SmartTransactionCancellationReason.NOT_CANCELLED\n ) {\n return SmartTransactionStatuses.PENDING;\n }\n\n const isCancellation =\n cancellations.findIndex(\n (cancellation) => cancellation === stxStatus.cancellationReason,\n ) > -1;\n if (stxStatus.cancellationReason && isCancellation) {\n if (!stxStatus.isSettled) {\n return SmartTransactionStatuses.PENDING;\n }\n return cancellationReasonToStatusMap[stxStatus.cancellationReason];\n }\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.SUCCESS) {\n return SmartTransactionStatuses.SUCCESS;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.CANCELLED) {\n return SmartTransactionStatuses.CANCELLED;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.REVERTED) {\n return SmartTransactionStatuses.REVERTED;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.UNKNOWN) {\n return SmartTransactionStatuses.UNKNOWN;\n }\n return SmartTransactionStatuses.UNKNOWN;\n};\n\n/**\n Generates an array of history objects sense the previous state.\n The object has the keys\n op (the operation performed),\n path (the key and if a nested object then each key will be separated with a `/`)\n value\n with the first entry having the note and a timestamp when the change took place\n @param previousState - the previous state of the object\n @param newState - the update object\n @param [note] - a optional note for the state change\n @returns\n*/\nexport function generateHistoryEntry(\n previousState: any,\n newState: any,\n note: string,\n) {\n const entry: any = jsonDiffer.compare(previousState, newState);\n // Add a note to the first op, since it breaks if we append it to the entry\n if (entry[0]) {\n if (note) {\n entry[0].note = note;\n }\n\n entry[0].timestamp = Date.now();\n }\n return entry;\n}\n\n/**\n Recovers previous txMeta state obj\n @returns\n*/\nexport function replayHistory(_shortHistory: any) {\n const shortHistory = _.cloneDeep(_shortHistory);\n return shortHistory.reduce(\n (val: any, entry: any) => jsonDiffer.applyPatch(val, entry).newDocument,\n );\n}\n\n/**\n * Snapshot {@code txMeta}\n * @param txMeta - the tx metadata object\n * @returns a deep clone without history\n */\nexport function snapshotFromTxMeta(txMeta: any) {\n const shallow = { ...txMeta };\n delete shallow.history;\n return _.cloneDeep(shallow);\n}\n\n/**\n * Returns processing time for an STX in seconds.\n * @param smartTransactionSubmittedtime\n * @returns Processing time in seconds.\n */\nexport const getStxProcessingTime = (\n smartTransactionSubmittedtime: number | undefined,\n): number | undefined => {\n if (!smartTransactionSubmittedtime) {\n return undefined;\n }\n return Math.round((Date.now() - smartTransactionSubmittedtime) / 1000);\n};\n\nexport const mapKeysToCamel = (\n obj: Record<string, any>,\n): Record<string, any> => {\n if (!_.isObject(obj)) {\n return obj;\n }\n const mappedValues = _.mapValues(obj, (val: Record<string, any>) => {\n if (_.isArray(val)) {\n return val.map(mapKeysToCamel);\n } else if (_.isObject(val)) {\n return mapKeysToCamel(val);\n }\n return val;\n });\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n return _.mapKeys(mappedValues, (value, key) => _.camelCase(key));\n};\n\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options);\n const json = await response.json();\n if (!response.ok) {\n console.log(`response`, response);\n throw new Error(\n `Fetch error:${JSON.stringify({\n status: response.status,\n ...mapKeysToCamel(json),\n })}`,\n );\n }\n return json;\n}\n\nexport const isSmartTransactionCancellable = (\n stxStatus: SmartTransactionsStatus,\n): boolean => {\n return (\n stxStatus.minedTx === SmartTransactionMinedTx.NOT_MINED &&\n (!stxStatus.cancellationReason ||\n stxStatus.cancellationReason ===\n SmartTransactionCancellationReason.NOT_CANCELLED)\n );\n};\n\nexport const incrementNonceInHex = (nonceInHex: string): string => {\n const nonceInDec = new BigNumber(nonceInHex, 16).toString(10);\n return hexlify(Number(nonceInDec) + 1);\n};\n\nexport const getTxHash = (signedTxHex: any) => {\n if (!signedTxHex) {\n return '';\n }\n const txHashBytes = TransactionFactory.fromSerializedData(\n // eslint-disable-next-line no-restricted-globals\n Buffer.from(signedTxHex.slice(2), 'hex'),\n ).hash();\n return bytesToHex(txHashBytes);\n};\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAAA,uCAAoD;AACpD,2CAA8C;AAC9C,gDAA+C;AAC/C,+CAAyC;AACzC,sEAAyC;AACzC,oDAAuB;AAEvB,6DAA6D;AAC7D,2CAA2C;AAE3C,mCAMiB;AACjB,6DAA6D;AAC7D,aAAa;AACb,mEAA0C;AAE1C,SAAgB,yBAAyB,CAAC,gBAAkC;IAC1E,OAAO,gBAAgB,CAAC,MAAM,KAAK,gCAAwB,CAAC,OAAO,CAAC;AACtE,CAAC;AAFD,8DAEC;AAEM,MAAM,gCAAgC,GAAG,CAC9C,SAA2C,EAC3C,EAAE,CAAC,SAAS,KAAK,gBAAgB,CAAC;AAFvB,QAAA,gCAAgC,oCAET;AAEpC,0CAA0C;AAC1C,SAAgB,gBAAgB,CAAC,OAAgB,EAAE,OAAe;IAChE,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACzC,QAAQ,OAAO,EAAE;QACf,KAAK,eAAO,CAAC,QAAQ,CAAC,CAAC;YACrB,OAAO,GAAG,wBAAY,aAAa,UAAU,UAAU,CAAC;SACzD;QAED,KAAK,eAAO,CAAC,YAAY,CAAC,CAAC;YACzB,OAAO,GAAG,wBAAY,aAAa,UAAU,cAAc,CAAC;SAC7D;QAED,KAAK,eAAO,CAAC,mBAAmB,CAAC,CAAC;YAChC,OAAO,GAAG,wBAAY,aAAa,UAAU,4CAA4C,sBAAW,CAAC,OAAO,EAAE,CAAC;SAChH;QAED,KAAK,eAAO,CAAC,MAAM,CAAC,CAAC;YACnB,OAAO,GAAG,wBAAY,aAAa,UAAU,SAAS,CAAC;SACxD;Q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B;QAC3D,YAAY,EAAE,gBAAgB,CAAC,WAAW;QAC1C,YAAY,EAAE,gBAAgB,CAAC,WAAW;KAC3C,CAAC;AACJ,CAAC,CAAC;AAbW,QAAA,6CAA6C,iDAaxD","sourcesContent":["import { TransactionFactory } from '@ethereumjs/tx';\nimport { bytesToHex } from '@ethereumjs/util';\nimport { hexlify } from '@ethersproject/bytes';\nimport { BigNumber } from 'bignumber.js';\nimport jsonDiffer from 'fast-json-patch';\nimport _ from 'lodash';\n\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\nimport { API_BASE_URL } from './constants';\nimport type { SmartTransaction, SmartTransactionsStatus } from './types';\nimport {\n APIType,\n SmartTransactionStatuses,\n SmartTransactionCancellationReason,\n SmartTransactionMinedTx,\n cancellationReasonToStatusMap,\n} from './types';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport packageJson from '../package.json';\n\nexport function isSmartTransactionPending(smartTransaction: SmartTransaction) {\n return smartTransaction.status === SmartTransactionStatuses.PENDING;\n}\n\nexport const isSmartTransactionStatusResolved = (\n stxStatus: SmartTransactionsStatus | string,\n) => stxStatus === 'uuid_not_found';\n\n// TODO use actual url once API is defined\nexport function getAPIRequestURL(apiType: APIType, chainId: string): string {\n const chainIdDec = parseInt(chainId, 16);\n switch (apiType) {\n case APIType.GET_FEES: {\n return `${API_BASE_URL}/networks/${chainIdDec}/getFees`;\n }\n\n case APIType.ESTIMATE_GAS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/estimateGas`;\n }\n\n case APIType.SUBMIT_TRANSACTIONS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`;\n }\n\n case APIType.CANCEL: {\n return `${API_BASE_URL}/networks/${chainIdDec}/cancel`;\n }\n\n case APIType.BATCH_STATUS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/batchStatus`;\n }\n\n case APIType.LIVENESS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/health`;\n }\n\n default: {\n throw new Error(`Invalid APIType`); // It can never get here thanks to TypeScript.\n }\n }\n}\n\nexport const calculateStatus = (stxStatus: SmartTransactionsStatus) => {\n if (isSmartTransactionStatusResolved(stxStatus)) {\n return SmartTransactionStatuses.RESOLVED;\n }\n const cancellations = [\n SmartTransactionCancellationReason.WOULD_REVERT,\n SmartTransactionCancellationReason.TOO_CHEAP,\n SmartTransactionCancellationReason.DEADLINE_MISSED,\n SmartTransactionCancellationReason.INVALID_NONCE,\n SmartTransactionCancellationReason.USER_CANCELLED,\n SmartTransactionCancellationReason.PREVIOUS_TX_CANCELLED,\n ];\n if (stxStatus?.minedTx === SmartTransactionMinedTx.NOT_MINED) {\n if (\n stxStatus.cancellationReason ===\n SmartTransactionCancellationReason.NOT_CANCELLED\n ) {\n return SmartTransactionStatuses.PENDING;\n }\n\n const isCancellation =\n cancellations.findIndex(\n (cancellation) => cancellation === stxStatus.cancellationReason,\n ) > -1;\n if (stxStatus.cancellationReason && isCancellation) {\n if (!stxStatus.isSettled) {\n return SmartTransactionStatuses.PENDING;\n }\n return cancellationReasonToStatusMap[stxStatus.cancellationReason];\n }\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.SUCCESS) {\n return SmartTransactionStatuses.SUCCESS;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.CANCELLED) {\n return SmartTransactionStatuses.CANCELLED;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.REVERTED) {\n return SmartTransactionStatuses.REVERTED;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.UNKNOWN) {\n return SmartTransactionStatuses.UNKNOWN;\n }\n return SmartTransactionStatuses.UNKNOWN;\n};\n\n/**\n Generates an array of history objects sense the previous state.\n The object has the keys\n op (the operation performed),\n path (the key and if a nested object then each key will be separated with a `/`)\n value\n with the first entry having the note and a timestamp when the change took place\n @param previousState - the previous state of the object\n @param newState - the update object\n @param [note] - a optional note for the state change\n @returns\n*/\nexport function generateHistoryEntry(\n previousState: any,\n newState: any,\n note: string,\n) {\n const entry: any = jsonDiffer.compare(previousState, newState);\n // Add a note to the first op, since it breaks if we append it to the entry\n if (entry[0]) {\n if (note) {\n entry[0].note = note;\n }\n\n entry[0].timestamp = Date.now();\n }\n return entry;\n}\n\n/**\n Recovers previous txMeta state obj\n @returns\n*/\nexport function replayHistory(_shortHistory: any) {\n const shortHistory = _.cloneDeep(_shortHistory);\n return shortHistory.reduce(\n (val: any, entry: any) => jsonDiffer.applyPatch(val, entry).newDocument,\n );\n}\n\n/**\n * Snapshot {@code txMeta}\n * @param txMeta - the tx metadata object\n * @returns a deep clone without history\n */\nexport function snapshotFromTxMeta(txMeta: any) {\n const shallow = { ...txMeta };\n delete shallow.history;\n return _.cloneDeep(shallow);\n}\n\n/**\n * Returns processing time for an STX in seconds.\n * @param smartTransactionSubmittedtime\n * @returns Processing time in seconds.\n */\nexport const getStxProcessingTime = (\n smartTransactionSubmittedtime: number | undefined,\n): number | undefined => {\n if (!smartTransactionSubmittedtime) {\n return undefined;\n }\n return Math.round((Date.now() - smartTransactionSubmittedtime) / 1000);\n};\n\nexport const mapKeysToCamel = (\n obj: Record<string, any>,\n): Record<string, any> => {\n if (!_.isObject(obj)) {\n return obj;\n }\n const mappedValues = _.mapValues(obj, (val: Record<string, any>) => {\n if (_.isArray(val)) {\n return val.map(mapKeysToCamel);\n } else if (_.isObject(val)) {\n return mapKeysToCamel(val);\n }\n return val;\n });\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n return _.mapKeys(mappedValues, (value, key) => _.camelCase(key));\n};\n\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options);\n const json = await response.json();\n if (!response.ok) {\n console.log(`response`, response);\n throw new Error(\n `Fetch error:${JSON.stringify({\n status: response.status,\n ...mapKeysToCamel(json),\n })}`,\n );\n }\n return json;\n}\n\nexport const isSmartTransactionCancellable = (\n stxStatus: SmartTransactionsStatus,\n): boolean => {\n return (\n stxStatus.minedTx === SmartTransactionMinedTx.NOT_MINED &&\n (!stxStatus.cancellationReason ||\n stxStatus.cancellationReason ===\n SmartTransactionCancellationReason.NOT_CANCELLED)\n );\n};\n\nexport const incrementNonceInHex = (nonceInHex: string): string => {\n const nonceInDec = new BigNumber(nonceInHex, 16).toString(10);\n return hexlify(Number(nonceInDec) + 1);\n};\n\nexport const getTxHash = (signedTxHex: any) => {\n if (!signedTxHex) {\n return '';\n }\n const txHashBytes = TransactionFactory.fromSerializedData(\n // eslint-disable-next-line no-restricted-globals\n Buffer.from(signedTxHex.slice(2), 'hex'),\n ).hash();\n return bytesToHex(txHashBytes);\n};\n\nexport const getSmartTransactionMetricsProperties = (\n smartTransaction: SmartTransaction,\n) => {\n if (!smartTransaction) {\n return {};\n }\n const smartTransactionStatusMetadata = smartTransaction.statusMetadata;\n return {\n stx_status: smartTransaction.status,\n type: smartTransaction.type,\n processing_time: getStxProcessingTime(smartTransaction.time),\n is_smart_transaction: true,\n stx_enabled: true,\n current_stx_enabled: true,\n stx_user_opt_in: true,\n stx_duplicated: smartTransactionStatusMetadata?.duplicated,\n stx_timed_out: smartTransactionStatusMetadata?.timedOut,\n stx_proxied: smartTransactionStatusMetadata?.proxied,\n };\n};\n\nexport const getSmartTransactionMetricsSensitiveProperties = (\n smartTransaction: SmartTransaction,\n) => {\n if (!smartTransaction) {\n return {};\n }\n return {\n token_from_symbol: smartTransaction.sourceTokenSymbol,\n token_to_symbol: smartTransaction.destinationTokenSymbol,\n account_hardware_type: smartTransaction.accountHardwareType,\n account_type: smartTransaction.accountType,\n device_model: smartTransaction.deviceModel,\n };\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/smart-transactions-controller",
3
- "version": "10.1.6",
3
+ "version": "11.0.0",
4
4
  "description": "Improves success rates for swaps by trialing transactions privately and finding minimum fees",
5
5
  "repository": {
6
6
  "type": "git",
@@ -31,10 +31,11 @@
31
31
  "@ethersproject/bytes": "^5.7.0",
32
32
  "@metamask/base-controller": "^6.0.0",
33
33
  "@metamask/controller-utils": "^11.0.0",
34
+ "@metamask/eth-json-rpc-provider": "^4.1.0",
34
35
  "@metamask/eth-query": "^4.0.0",
35
36
  "@metamask/network-controller": "^19.0.0",
36
37
  "@metamask/polling-controller": "^8.0.0",
37
- "@metamask/transaction-controller": "^32.0.0",
38
+ "@metamask/transaction-controller": "^34.0.0",
38
39
  "bignumber.js": "^9.0.1",
39
40
  "events": "^3.3.0",
40
41
  "fast-json-patch": "^3.1.0",
@@ -47,6 +48,7 @@
47
48
  "@metamask/eslint-config-jest": "^12.1.0",
48
49
  "@metamask/eslint-config-nodejs": "^12.1.0",
49
50
  "@metamask/eslint-config-typescript": "^12.1.0",
51
+ "@metamask/json-rpc-engine": "^9.0.0",
50
52
  "@types/jest": "^26.0.24",
51
53
  "@types/lodash": "^4.14.194",
52
54
  "@types/node": "^18.19.17",
@@ -83,7 +85,9 @@
83
85
  "@lavamoat/preinstall-always-fail": false,
84
86
  "@metamask/controller-utils>ethereumjs-util>ethereum-cryptography>keccak": false,
85
87
  "@metamask/controller-utils>ethereumjs-util>ethereum-cryptography>secp256k1": false,
86
- "@metamask/controller-utils>babel-runtime>core-js": false
88
+ "@metamask/controller-utils>babel-runtime>core-js": false,
89
+ "@metamask/transaction-controller>@metamask/accounts-controller>@metamask/keyring-controller>ethereumjs-wallet>ethereum-cryptography>keccak": false,
90
+ "@metamask/transaction-controller>@metamask/accounts-controller>@metamask/keyring-controller>ethereumjs-wallet>ethereum-cryptography>secp256k1": false
87
91
  }
88
92
  }
89
93
  }