@metamask/smart-transactions-controller 13.2.0 → 15.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 +24 -1
- package/dist/SmartTransactionsController.d.ts +25 -6
- package/dist/SmartTransactionsController.js +24 -11
- package/dist/SmartTransactionsController.js.map +1 -1
- package/dist/types.d.ts +11 -0
- package/dist/types.js +6 -1
- package/dist/types.js.map +1 -1
- package/dist/utils.d.ts +3 -2
- package/dist/utils.js +11 -4
- package/dist/utils.js.map +1 -1
- package/package.json +24 -10
- package/dist/test-helpers.d.ts +0 -25
- package/dist/test-helpers.js +0 -40
- package/dist/test-helpers.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [15.0.0]
|
|
10
|
+
### Changed
|
|
11
|
+
- **BREAKING**: Recategorize controllers as peer dependencies ([#472](https://github.com/MetaMask/smart-transactions-controller/pull/472))
|
|
12
|
+
- The following packages have been removed as dependencies, and added as peer dependencies:
|
|
13
|
+
- `@metamask/network-controller@^22.0.0`
|
|
14
|
+
- `@metamask/transaction-controller@^38.0.0`
|
|
15
|
+
- Note that these versions have also been updated
|
|
16
|
+
- `@metamask/network-controller` updated from v21.1.0 to v22.0.0 ([#471](https://github.com/MetaMask/smart-transactions-controller/pull/471))
|
|
17
|
+
- `@metamask/transaction-controller` updated from v37.3.0 to v38.0.0 ([#471](https://github.com/MetaMask/smart-transactions-controller/pull/471))
|
|
18
|
+
- Update `@metamask/polling-controller` from v11.0.0 to v12.0.0 ([#471](https://github.com/MetaMask/smart-transactions-controller/pull/471))
|
|
19
|
+
- Remove test-helpers from build ([#459](https://github.com/MetaMask/smart-transactions-controller/pull/459))
|
|
20
|
+
- Bump `@metamask/eth-json-rpc-provider` from `^4.1.0` to `^4.1.6` ([#460](https://github.com/MetaMask/smart-transactions-controller/pull/460))
|
|
21
|
+
|
|
22
|
+
## [14.0.0]
|
|
23
|
+
### Changed
|
|
24
|
+
- **BREAKING** Update `@metamask/polling-controller` from `^8.0.0` to `^11.0.0` ([#448](https://github.com/MetaMask/smart-transactions-controller/pull/448))
|
|
25
|
+
- `startPollingByNetworkClientId` has been renamed to `startPolling`, accepting a `SmartTransactionsControllerPollingInput` object instead of a string as argument.
|
|
26
|
+
- Update `@metamask/transaction-controller` from `^34.0.0` to `^37.3.0` ([#446](https://github.com/MetaMask/smart-transactions-controller/pull/446))
|
|
27
|
+
- Update `@metamask/base-controller` from `^6.0.0` to `^7.0.1` ([#448](https://github.com/MetaMask/smart-transactions-controller/pull/448))
|
|
28
|
+
- Update `@metamask/network-controller` from `^20.0.0` to `^21.1.0` ([#447](https://github.com/MetaMask/smart-transactions-controller/pull/447))
|
|
29
|
+
|
|
9
30
|
## [13.2.0]
|
|
10
31
|
### Added
|
|
11
32
|
- Add metrics events for Receive and Request ([#429](https://github.com/MetaMask/smart-transactions-controller/pull/429))
|
|
@@ -356,7 +377,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
356
377
|
- Add initial SmartTransactionsController ([#1](https://github.com/MetaMask/smart-transactions-controller/pull/1))
|
|
357
378
|
- Initial commit
|
|
358
379
|
|
|
359
|
-
[Unreleased]: https://github.com/MetaMask/smart-transactions-controller/compare/
|
|
380
|
+
[Unreleased]: https://github.com/MetaMask/smart-transactions-controller/compare/v15.0.0...HEAD
|
|
381
|
+
[15.0.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v14.0.0...v15.0.0
|
|
382
|
+
[14.0.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v13.2.0...v14.0.0
|
|
360
383
|
[13.2.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v13.1.0...v13.2.0
|
|
361
384
|
[13.1.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v13.0.0...v13.1.0
|
|
362
385
|
[13.0.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v12.0.1...v13.0.0
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
import type { ControllerGetStateAction, ControllerStateChangeEvent, RestrictedControllerMessenger } from '@metamask/base-controller';
|
|
3
3
|
import type { NetworkClientId, NetworkControllerGetNetworkClientByIdAction, NetworkControllerStateChangeEvent } from '@metamask/network-controller';
|
|
4
|
-
import { StaticIntervalPollingController } from '@metamask/polling-controller';
|
|
5
4
|
import type { TransactionController, TransactionMeta, TransactionParams } from '@metamask/transaction-controller';
|
|
6
5
|
import { MetaMetricsEventCategory, MetaMetricsEventName } from './constants';
|
|
7
|
-
import type { Fees, Hex, IndividualTxFees, SignedCanceledTransaction, SignedTransaction, SmartTransaction, SmartTransactionsStatus, UnsignedTransaction, GetTransactionsOptions, MetaMetricsProps } from './types';
|
|
6
|
+
import type { Fees, Hex, IndividualTxFees, SignedCanceledTransaction, SignedTransaction, SmartTransaction, SmartTransactionsStatus, UnsignedTransaction, GetTransactionsOptions, MetaMetricsProps, FeatureFlags, ClientId } from './types';
|
|
8
7
|
import { SmartTransactionStatuses } from './types';
|
|
9
8
|
import { getSmartTransactionMetricsProperties, getSmartTransactionMetricsSensitiveProperties } from './utils';
|
|
10
9
|
export declare const DEFAULT_INTERVAL: number;
|
|
@@ -59,7 +58,7 @@ export declare type AllowedEvents = NetworkControllerStateChangeEvent;
|
|
|
59
58
|
export declare type SmartTransactionsControllerMessenger = RestrictedControllerMessenger<typeof controllerName, SmartTransactionsControllerActions | AllowedActions, SmartTransactionsControllerEvents | AllowedEvents, AllowedActions['type'], AllowedEvents['type']>;
|
|
60
59
|
declare type SmartTransactionsControllerOptions = {
|
|
61
60
|
interval?: number;
|
|
62
|
-
clientId
|
|
61
|
+
clientId: ClientId;
|
|
63
62
|
chainId?: Hex;
|
|
64
63
|
supportedChainIds?: Hex[];
|
|
65
64
|
getNonceLock: TransactionController['getNonceLock'];
|
|
@@ -76,12 +75,32 @@ declare type SmartTransactionsControllerOptions = {
|
|
|
76
75
|
messenger: SmartTransactionsControllerMessenger;
|
|
77
76
|
getTransactions: (options?: GetTransactionsOptions) => TransactionMeta[];
|
|
78
77
|
getMetaMetricsProps: () => Promise<MetaMetricsProps>;
|
|
78
|
+
getFeatureFlags: () => FeatureFlags;
|
|
79
|
+
updateTransaction: (transaction: TransactionMeta, note: string) => void;
|
|
79
80
|
};
|
|
80
|
-
export
|
|
81
|
+
export declare type SmartTransactionsControllerPollingInput = {
|
|
82
|
+
networkClientId: string;
|
|
83
|
+
};
|
|
84
|
+
declare const SmartTransactionsController_base: (abstract new (...args: any[]) => {
|
|
85
|
+
readonly "__#787890@#intervalIds": Record<string, NodeJS.Timeout>;
|
|
86
|
+
"__#787890@#intervalLength": number | undefined;
|
|
87
|
+
setIntervalLength(intervalLength: number): void;
|
|
88
|
+
getIntervalLength(): number | undefined;
|
|
89
|
+
_startPolling(input: SmartTransactionsControllerPollingInput): void;
|
|
90
|
+
_stopPollingByPollingTokenSetId(key: string): void;
|
|
91
|
+
readonly "__#787882@#pollingTokenSets": Map<string, Set<string>>;
|
|
92
|
+
"__#787882@#callbacks": Map<string, Set<(input: SmartTransactionsControllerPollingInput) => void>>;
|
|
93
|
+
_executePoll(input: SmartTransactionsControllerPollingInput): Promise<void>;
|
|
94
|
+
startPolling(input: SmartTransactionsControllerPollingInput): string;
|
|
95
|
+
stopAllPolling(): void;
|
|
96
|
+
stopPollingByPollingToken(pollingToken: string): void;
|
|
97
|
+
onPollingComplete(input: SmartTransactionsControllerPollingInput, callback: (input: SmartTransactionsControllerPollingInput) => void): void;
|
|
98
|
+
}) & typeof import("@metamask/base-controller").BaseController;
|
|
99
|
+
export default class SmartTransactionsController extends SmartTransactionsController_base<typeof controllerName, SmartTransactionsControllerState, SmartTransactionsControllerMessenger> {
|
|
81
100
|
#private;
|
|
82
101
|
timeoutHandle?: NodeJS.Timeout;
|
|
83
|
-
constructor({ interval, clientId, chainId: InitialChainId, supportedChainIds, getNonceLock, confirmExternalTransaction, trackMetaMetricsEvent, state, messenger, getTransactions, getMetaMetricsProps, }: SmartTransactionsControllerOptions);
|
|
84
|
-
_executePoll(networkClientId:
|
|
102
|
+
constructor({ interval, clientId, chainId: InitialChainId, supportedChainIds, getNonceLock, confirmExternalTransaction, trackMetaMetricsEvent, state, messenger, getTransactions, getMetaMetricsProps, getFeatureFlags, updateTransaction, }: SmartTransactionsControllerOptions);
|
|
103
|
+
_executePoll({ networkClientId, }: SmartTransactionsControllerPollingInput): Promise<void>;
|
|
85
104
|
checkPoll({ smartTransactionsState: { smartTransactions }, }: SmartTransactionsControllerState): void;
|
|
86
105
|
initializeSmartTransactionsForChainId(): void;
|
|
87
106
|
poll(interval?: number): Promise<void>;
|
|
@@ -13,7 +13,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
13
13
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
14
14
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
15
15
|
};
|
|
16
|
-
var _SmartTransactionsController_instances, _SmartTransactionsController_interval, _SmartTransactionsController_clientId, _SmartTransactionsController_chainId, _SmartTransactionsController_supportedChainIds, _SmartTransactionsController_getNonceLock, _SmartTransactionsController_ethQuery, _SmartTransactionsController_confirmExternalTransaction, _SmartTransactionsController_getRegularTransactions, _SmartTransactionsController_trackMetaMetricsEvent, _SmartTransactionsController_getMetaMetricsProps, _SmartTransactionsController_fetch, _SmartTransactionsController_updateSmartTransaction, _SmartTransactionsController_addMetaMetricsPropsToNewSmartTransaction, _SmartTransactionsController_createOrUpdateSmartTransaction, _SmartTransactionsController_doesTransactionNeedConfirmation, _SmartTransactionsController_confirmSmartTransaction, _SmartTransactionsController_getChainId, _SmartTransactionsController_getEthQuery, _SmartTransactionsController_getCurrentSmartTransactions, _SmartTransactionsController_wipeSmartTransactionsPerChainId;
|
|
16
|
+
var _SmartTransactionsController_instances, _SmartTransactionsController_interval, _SmartTransactionsController_clientId, _SmartTransactionsController_chainId, _SmartTransactionsController_supportedChainIds, _SmartTransactionsController_getNonceLock, _SmartTransactionsController_ethQuery, _SmartTransactionsController_confirmExternalTransaction, _SmartTransactionsController_getRegularTransactions, _SmartTransactionsController_trackMetaMetricsEvent, _SmartTransactionsController_getMetaMetricsProps, _SmartTransactionsController_getFeatureFlags, _SmartTransactionsController_updateTransaction, _SmartTransactionsController_fetch, _SmartTransactionsController_updateSmartTransaction, _SmartTransactionsController_addMetaMetricsPropsToNewSmartTransaction, _SmartTransactionsController_createOrUpdateSmartTransaction, _SmartTransactionsController_doesTransactionNeedConfirmation, _SmartTransactionsController_confirmSmartTransaction, _SmartTransactionsController_getChainId, _SmartTransactionsController_getEthQuery, _SmartTransactionsController_getCurrentSmartTransactions, _SmartTransactionsController_wipeSmartTransactionsPerChainId;
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.getDefaultSmartTransactionsControllerState = exports.DEFAULT_INTERVAL = void 0;
|
|
19
19
|
const bytes_1 = require("@ethersproject/bytes");
|
|
@@ -28,7 +28,6 @@ const types_1 = require("./types");
|
|
|
28
28
|
const utils_1 = require("./utils");
|
|
29
29
|
const SECOND = 1000;
|
|
30
30
|
exports.DEFAULT_INTERVAL = SECOND * 5;
|
|
31
|
-
const DEFAULT_CLIENT_ID = 'default';
|
|
32
31
|
const ETH_QUERY_ERROR_MSG = '`ethQuery` is not defined on SmartTransactionsController';
|
|
33
32
|
/**
|
|
34
33
|
* The name of the {@link SmartTransactionsController}
|
|
@@ -74,8 +73,8 @@ function getDefaultSmartTransactionsControllerState() {
|
|
|
74
73
|
};
|
|
75
74
|
}
|
|
76
75
|
exports.getDefaultSmartTransactionsControllerState = getDefaultSmartTransactionsControllerState;
|
|
77
|
-
class SmartTransactionsController extends polling_controller_1.StaticIntervalPollingController {
|
|
78
|
-
constructor({ interval = exports.DEFAULT_INTERVAL, clientId
|
|
76
|
+
class SmartTransactionsController extends (0, polling_controller_1.StaticIntervalPollingController)() {
|
|
77
|
+
constructor({ interval = exports.DEFAULT_INTERVAL, clientId, chainId: InitialChainId = controller_utils_1.ChainId.mainnet, supportedChainIds = [controller_utils_1.ChainId.mainnet, controller_utils_1.ChainId.sepolia], getNonceLock, confirmExternalTransaction, trackMetaMetricsEvent, state = {}, messenger, getTransactions, getMetaMetricsProps, getFeatureFlags, updateTransaction, }) {
|
|
79
78
|
super({
|
|
80
79
|
name: controllerName,
|
|
81
80
|
metadata: controllerMetadata,
|
|
@@ -93,6 +92,8 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
|
|
|
93
92
|
_SmartTransactionsController_getRegularTransactions.set(this, void 0);
|
|
94
93
|
_SmartTransactionsController_trackMetaMetricsEvent.set(this, void 0);
|
|
95
94
|
_SmartTransactionsController_getMetaMetricsProps.set(this, void 0);
|
|
95
|
+
_SmartTransactionsController_getFeatureFlags.set(this, void 0);
|
|
96
|
+
_SmartTransactionsController_updateTransaction.set(this, void 0);
|
|
96
97
|
__classPrivateFieldSet(this, _SmartTransactionsController_interval, interval, "f");
|
|
97
98
|
__classPrivateFieldSet(this, _SmartTransactionsController_clientId, clientId, "f");
|
|
98
99
|
__classPrivateFieldSet(this, _SmartTransactionsController_chainId, InitialChainId, "f");
|
|
@@ -104,6 +105,8 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
|
|
|
104
105
|
__classPrivateFieldSet(this, _SmartTransactionsController_getRegularTransactions, getTransactions, "f");
|
|
105
106
|
__classPrivateFieldSet(this, _SmartTransactionsController_trackMetaMetricsEvent, trackMetaMetricsEvent, "f");
|
|
106
107
|
__classPrivateFieldSet(this, _SmartTransactionsController_getMetaMetricsProps, getMetaMetricsProps, "f");
|
|
108
|
+
__classPrivateFieldSet(this, _SmartTransactionsController_getFeatureFlags, getFeatureFlags, "f");
|
|
109
|
+
__classPrivateFieldSet(this, _SmartTransactionsController_updateTransaction, updateTransaction, "f");
|
|
107
110
|
this.initializeSmartTransactionsForChainId();
|
|
108
111
|
this.messagingSystem.subscribe('NetworkController:stateChange', ({ selectedNetworkClientId }) => {
|
|
109
112
|
const { configuration: { chainId }, provider, } = this.messagingSystem.call('NetworkController:getNetworkClientById', selectedNetworkClientId);
|
|
@@ -114,7 +117,7 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
|
|
|
114
117
|
});
|
|
115
118
|
this.messagingSystem.subscribe(`${controllerName}:stateChange`, (currentState) => this.checkPoll(currentState));
|
|
116
119
|
}
|
|
117
|
-
async _executePoll(networkClientId) {
|
|
120
|
+
async _executePoll({ networkClientId, }) {
|
|
118
121
|
// if this is going to be truly UI driven polling we shouldn't really reach here
|
|
119
122
|
// with a networkClientId that is not supported, but for now I'll add a check in case
|
|
120
123
|
// wondering if we should add some kind of predicate to the polling controller to check whether
|
|
@@ -348,6 +351,7 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
|
|
|
348
351
|
txHash: submitTransactionResponse.txHash,
|
|
349
352
|
cancellable: true,
|
|
350
353
|
type: (_b = transactionMeta === null || transactionMeta === void 0 ? void 0 : transactionMeta.type) !== null && _b !== void 0 ? _b : 'swap',
|
|
354
|
+
transactionId: transactionMeta === null || transactionMeta === void 0 ? void 0 : transactionMeta.id,
|
|
351
355
|
}, { chainId, ethQuery });
|
|
352
356
|
}
|
|
353
357
|
finally {
|
|
@@ -429,7 +433,7 @@ class SmartTransactionsController extends polling_controller_1.StaticIntervalPol
|
|
|
429
433
|
}
|
|
430
434
|
}
|
|
431
435
|
exports.default = SmartTransactionsController;
|
|
432
|
-
_SmartTransactionsController_interval = new WeakMap(), _SmartTransactionsController_clientId = new WeakMap(), _SmartTransactionsController_chainId = new WeakMap(), _SmartTransactionsController_supportedChainIds = new WeakMap(), _SmartTransactionsController_getNonceLock = new WeakMap(), _SmartTransactionsController_ethQuery = new WeakMap(), _SmartTransactionsController_confirmExternalTransaction = new WeakMap(), _SmartTransactionsController_getRegularTransactions = new WeakMap(), _SmartTransactionsController_trackMetaMetricsEvent = new WeakMap(), _SmartTransactionsController_getMetaMetricsProps = new WeakMap(), _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsController_fetch =
|
|
436
|
+
_SmartTransactionsController_interval = new WeakMap(), _SmartTransactionsController_clientId = new WeakMap(), _SmartTransactionsController_chainId = new WeakMap(), _SmartTransactionsController_supportedChainIds = new WeakMap(), _SmartTransactionsController_getNonceLock = new WeakMap(), _SmartTransactionsController_ethQuery = new WeakMap(), _SmartTransactionsController_confirmExternalTransaction = new WeakMap(), _SmartTransactionsController_getRegularTransactions = new WeakMap(), _SmartTransactionsController_trackMetaMetricsEvent = new WeakMap(), _SmartTransactionsController_getMetaMetricsProps = new WeakMap(), _SmartTransactionsController_getFeatureFlags = new WeakMap(), _SmartTransactionsController_updateTransaction = new WeakMap(), _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsController_fetch =
|
|
433
437
|
/* istanbul ignore next */
|
|
434
438
|
async function _SmartTransactionsController_fetch(request, options) {
|
|
435
439
|
const fetchOptions = Object.assign(Object.assign({}, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, (__classPrivateFieldGet(this, _SmartTransactionsController_clientId, "f") && { 'X-Client-Id': __classPrivateFieldGet(this, _SmartTransactionsController_clientId, "f") })) });
|
|
@@ -455,7 +459,7 @@ async function _SmartTransactionsController_fetch(request, options) {
|
|
|
455
459
|
smartTransaction.accountType = metaMetricsProps === null || metaMetricsProps === void 0 ? void 0 : metaMetricsProps.accountType;
|
|
456
460
|
smartTransaction.deviceModel = metaMetricsProps === null || metaMetricsProps === void 0 ? void 0 : metaMetricsProps.deviceModel;
|
|
457
461
|
}, _SmartTransactionsController_createOrUpdateSmartTransaction = async function _SmartTransactionsController_createOrUpdateSmartTransaction(smartTransaction, { chainId = __classPrivateFieldGet(this, _SmartTransactionsController_chainId, "f"), ethQuery = __classPrivateFieldGet(this, _SmartTransactionsController_ethQuery, "f"), }) {
|
|
458
|
-
var _a;
|
|
462
|
+
var _a, _b;
|
|
459
463
|
const { smartTransactionsState: { smartTransactions }, } = this.state;
|
|
460
464
|
const currentSmartTransactions = (_a = smartTransactions[chainId]) !== null && _a !== void 0 ? _a : [];
|
|
461
465
|
const currentIndex = currentSmartTransactions === null || currentSmartTransactions === void 0 ? void 0 : currentSmartTransactions.findIndex((stx) => stx.uuid === smartTransaction.uuid);
|
|
@@ -491,15 +495,24 @@ async function _SmartTransactionsController_fetch(request, options) {
|
|
|
491
495
|
});
|
|
492
496
|
return;
|
|
493
497
|
}
|
|
498
|
+
const currentSmartTransaction = currentSmartTransactions[currentIndex];
|
|
499
|
+
const nextSmartTransaction = Object.assign(Object.assign({}, currentSmartTransaction), smartTransaction);
|
|
494
500
|
// We have to emit this event here, because then a txHash is returned to the TransactionController once it's available
|
|
495
501
|
// and the #doesTransactionNeedConfirmation function will work properly, since it will find the txHash in the regular transactions list.
|
|
496
|
-
this.messagingSystem.publish(`SmartTransactionsController:smartTransaction`,
|
|
502
|
+
this.messagingSystem.publish(`SmartTransactionsController:smartTransaction`, nextSmartTransaction);
|
|
503
|
+
if (nextSmartTransaction.status === types_1.SmartTransactionStatuses.CANCELLED) {
|
|
504
|
+
const returnTxHashAsap = (0, utils_1.getReturnTxHashAsap)(__classPrivateFieldGet(this, _SmartTransactionsController_clientId, "f"), (_b = __classPrivateFieldGet(this, _SmartTransactionsController_getFeatureFlags, "f").call(this)) === null || _b === void 0 ? void 0 : _b.smartTransactions);
|
|
505
|
+
if (returnTxHashAsap && nextSmartTransaction.transactionId) {
|
|
506
|
+
const foundTransaction = __classPrivateFieldGet(this, _SmartTransactionsController_getRegularTransactions, "f").call(this).find((transaction) => transaction.id === nextSmartTransaction.transactionId);
|
|
507
|
+
if (foundTransaction) {
|
|
508
|
+
const updatedTransaction = Object.assign(Object.assign({}, foundTransaction), { status: transaction_controller_1.TransactionStatus.failed });
|
|
509
|
+
__classPrivateFieldGet(this, _SmartTransactionsController_updateTransaction, "f").call(this, updatedTransaction, 'Smart transaction cancelled');
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
}
|
|
497
513
|
if ((smartTransaction.status === types_1.SmartTransactionStatuses.SUCCESS ||
|
|
498
514
|
smartTransaction.status === types_1.SmartTransactionStatuses.REVERTED) &&
|
|
499
515
|
!smartTransaction.confirmed) {
|
|
500
|
-
// confirm smart transaction
|
|
501
|
-
const currentSmartTransaction = currentSmartTransactions[currentIndex];
|
|
502
|
-
const nextSmartTransaction = Object.assign(Object.assign({}, currentSmartTransaction), smartTransaction);
|
|
503
516
|
await __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_confirmSmartTransaction).call(this, nextSmartTransaction, {
|
|
504
517
|
chainId,
|
|
505
518
|
ethQuery,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SmartTransactionsController.js","sourceRoot":"","sources":["../src/SmartTransactionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,gDAA+C;AAM/C,iEAKoC;AACpC,oEAA2C;AAM3C,qEAA+E;AAM/E,6EAAqE;AACrE,+CAAyC;AACzC,iEAAyC;AAEzC,2CAA6E;AAa7E,mCAA4D;AAC5D,mCAaiB;AAEjB,MAAM,MAAM,GAAG,IAAI,CAAC;AACP,QAAA,gBAAgB,GAAG,MAAM,GAAG,CAAC,CAAC;AAC3C,MAAM,iBAAiB,GAAG,SAAS,CAAC;AACpC,MAAM,mBAAmB,GACvB,0DAA0D,CAAC;AAE7D;;GAEG;AACH,MAAM,cAAc,GAAG,6BAA6B,CAAC;AAErD,MAAM,kBAAkB,GAAG;IACzB,sBAAsB,EAAE;QACtB,OAAO,EAAE,KAAK;QACd,SAAS,EAAE,IAAI;KAChB;CACF,CAAC;AAmBF;;;;GAIG;AACH,SAAgB,0CAA0C;IACxD,OAAO;QACL,sBAAsB,EAAE;YACtB,iBAAiB,EAAE,EAAE;YACrB,SAAS,EAAE,IAAI;YACf,WAAW,EAAE,IAAI;YACjB,IAAI,EAAE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,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,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,sBAAsB,CAAC,iBAAiB,CAAC,OAAO,CAAC;YACrD,oCAAoC,CAAC;IACzC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { hexlify } from '@ethersproject/bytes';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n query,\n safelyExecute,\n ChainId,\n isSafeDynamicKey,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerStateChangeEvent,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n TransactionController,\n TransactionMeta,\n TransactionParams,\n} from '@metamask/transaction-controller';\nimport { TransactionStatus } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\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 DEFAULT_CLIENT_ID = 'default';\nconst ETH_QUERY_ERROR_MSG =\n '`ethQuery` is not defined on SmartTransactionsController';\n\n/**\n * The name of the {@link SmartTransactionsController}\n */\nconst controllerName = 'SmartTransactionsController';\n\nconst controllerMetadata = {\n smartTransactionsState: {\n persist: false,\n anonymous: true,\n },\n};\n\ntype FeeEstimates = {\n approvalTxFees: IndividualTxFees | null;\n tradeTxFees: IndividualTxFees | null;\n};\n\nexport type SmartTransactionsControllerState = {\n smartTransactionsState: {\n smartTransactions: Record<Hex, SmartTransaction[]>;\n userOptIn: boolean | null;\n userOptInV2: boolean | null;\n liveness: boolean | null;\n fees: FeeEstimates;\n feesByChainId: Record<Hex, FeeEstimates>;\n livenessByChainId: Record<Hex, boolean>;\n };\n};\n\n/**\n * Get the default {@link SmartTransactionsController} state.\n *\n * @returns The default {@link SmartTransactionsController} state.\n */\nexport function getDefaultSmartTransactionsControllerState(): SmartTransactionsControllerState {\n return {\n smartTransactionsState: {\n smartTransactions: {},\n userOptIn: null,\n userOptInV2: null,\n fees: {\n approvalTxFees: null,\n tradeTxFees: null,\n },\n liveness: true,\n livenessByChainId: {\n [ChainId.mainnet]: true,\n [ChainId.sepolia]: true,\n },\n feesByChainId: {\n [ChainId.mainnet]: {\n approvalTxFees: null,\n tradeTxFees: null,\n },\n [ChainId.sepolia]: {\n approvalTxFees: null,\n tradeTxFees: null,\n },\n },\n },\n };\n}\n\nexport type SmartTransactionsControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n SmartTransactionsControllerState\n >;\n\n/**\n * The actions that can be performed using the {@link SmartTransactionsController}.\n */\nexport type SmartTransactionsControllerActions =\n SmartTransactionsControllerGetStateAction;\n\nexport type AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\nexport type SmartTransactionsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n SmartTransactionsControllerState\n >;\n\nexport type SmartTransactionsControllerSmartTransactionEvent = {\n type: 'SmartTransactionsController:smartTransaction';\n payload: [SmartTransaction];\n};\n\nexport type SmartTransactionsControllerSmartTransactionConfirmationDoneEvent = {\n type: 'SmartTransactionsController:smartTransactionConfirmationDone';\n payload: [SmartTransaction];\n};\n\n/**\n * The events that {@link SmartTransactionsController} can emit.\n */\nexport type SmartTransactionsControllerEvents =\n | SmartTransactionsControllerStateChangeEvent\n | SmartTransactionsControllerSmartTransactionEvent\n | SmartTransactionsControllerSmartTransactionConfirmationDoneEvent;\n\nexport type AllowedEvents = NetworkControllerStateChangeEvent;\n\n/**\n * The messenger of the {@link SmartTransactionsController}.\n */\nexport type SmartTransactionsControllerMessenger =\n RestrictedControllerMessenger<\n typeof controllerName,\n SmartTransactionsControllerActions | AllowedActions,\n SmartTransactionsControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n >;\n\ntype SmartTransactionsControllerOptions = {\n interval?: number;\n clientId?: string;\n chainId?: Hex;\n supportedChainIds?: Hex[];\n getNonceLock: TransactionController['getNonceLock'];\n confirmExternalTransaction: TransactionController['confirmExternalTransaction'];\n trackMetaMetricsEvent: (\n event: {\n event: MetaMetricsEventName;\n category: MetaMetricsEventCategory;\n properties?: ReturnType<typeof getSmartTransactionMetricsProperties>;\n sensitiveProperties?: ReturnType<\n typeof getSmartTransactionMetricsSensitiveProperties\n >;\n },\n options?: { metaMetricsId?: string } & Record<string, boolean>,\n ) => void;\n state?: Partial<SmartTransactionsControllerState>;\n messenger: SmartTransactionsControllerMessenger;\n getTransactions: (options?: GetTransactionsOptions) => TransactionMeta[];\n getMetaMetricsProps: () => Promise<MetaMetricsProps>;\n};\n\nexport default class SmartTransactionsController extends StaticIntervalPollingController<\n typeof controllerName,\n SmartTransactionsControllerState,\n SmartTransactionsControllerMessenger\n> {\n #interval: number;\n\n #clientId: string;\n\n #chainId: Hex;\n\n #supportedChainIds: Hex[];\n\n timeoutHandle?: NodeJS.Timeout;\n\n readonly #getNonceLock: SmartTransactionsControllerOptions['getNonceLock'];\n\n #ethQuery: EthQuery | undefined;\n\n #confirmExternalTransaction: SmartTransactionsControllerOptions['confirmExternalTransaction'];\n\n #getRegularTransactions: (\n options?: GetTransactionsOptions,\n ) => TransactionMeta[];\n\n readonly #trackMetaMetricsEvent: SmartTransactionsControllerOptions['trackMetaMetricsEvent'];\n\n readonly #getMetaMetricsProps: () => Promise<MetaMetricsProps>;\n\n /* istanbul ignore next */\n async #fetch(request: string, options?: RequestInit) {\n const fetchOptions = {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...(this.#clientId && { 'X-Client-Id': this.#clientId }),\n },\n };\n\n return handleFetch(request, fetchOptions);\n }\n\n constructor({\n interval = DEFAULT_INTERVAL,\n clientId = DEFAULT_CLIENT_ID,\n chainId: InitialChainId = ChainId.mainnet,\n supportedChainIds = [ChainId.mainnet, ChainId.sepolia],\n getNonceLock,\n confirmExternalTransaction,\n trackMetaMetricsEvent,\n state = {},\n messenger,\n getTransactions,\n getMetaMetricsProps,\n }: SmartTransactionsControllerOptions) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultSmartTransactionsControllerState(),\n ...state,\n },\n });\n this.#interval = interval;\n this.#clientId = clientId;\n this.#chainId = InitialChainId;\n this.#supportedChainIds = supportedChainIds;\n this.setIntervalLength(interval);\n this.#getNonceLock = getNonceLock;\n this.#ethQuery = undefined;\n this.#confirmExternalTransaction = confirmExternalTransaction;\n this.#getRegularTransactions = getTransactions;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.#getMetaMetricsProps = getMetaMetricsProps;\n\n this.initializeSmartTransactionsForChainId();\n\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n ({ selectedNetworkClientId }) => {\n const {\n configuration: { chainId },\n provider,\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n this.#chainId = chainId;\n this.#ethQuery = new EthQuery(provider);\n this.initializeSmartTransactionsForChainId();\n this.checkPoll(this.state);\n },\n );\n\n this.messagingSystem.subscribe(\n `${controllerName}:stateChange`,\n (currentState) => this.checkPoll(currentState),\n );\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.#supportedChainIds.includes(chainId)) {\n return Promise.resolve();\n }\n return this.updateSmartTransactions({ networkClientId });\n }\n\n checkPoll({\n smartTransactionsState: { smartTransactions },\n }: SmartTransactionsControllerState) {\n const currentSmartTransactions = smartTransactions[this.#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.#supportedChainIds.includes(this.#chainId)) {\n this.update((state) => {\n state.smartTransactionsState.smartTransactions[this.#chainId] =\n state.smartTransactionsState.smartTransactions[this.#chainId] ?? [];\n });\n }\n }\n\n async poll(interval?: number): Promise<void> {\n if (interval) {\n this.#interval = interval;\n }\n\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n\n if (!this.#supportedChainIds.includes(this.#chainId)) {\n return;\n }\n\n this.timeoutHandle = setInterval(() => {\n safelyExecute(async () => this.updateSmartTransactions());\n }, this.#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(optInState: boolean | null): void {\n this.update((state) => {\n state.smartTransactionsState.userOptInV2 = optInState;\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 {\n smartTransactionsState: { smartTransactions },\n } = this.state;\n const currentSmartTransactions = smartTransactions[this.#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 ethQuery = this.#ethQuery;\n let chainId = this.#chainId;\n if (networkClientId) {\n const { configuration, provider } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n chainId = configuration.chainId;\n ethQuery = new EthQuery(provider);\n }\n\n this.#createOrUpdateSmartTransaction(smartTransaction, {\n chainId,\n ethQuery,\n });\n }\n\n #updateSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.#chainId,\n }: {\n chainId: Hex;\n },\n ) {\n const {\n smartTransactionsState: { smartTransactions },\n } = this.state;\n const currentSmartTransactions = smartTransactions[chainId] ?? [];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransaction.uuid,\n );\n\n if (currentIndex === -1) {\n return; // Smart transaction not found, don't update anything.\n }\n\n if (!isSafeDynamicKey(chainId)) {\n return;\n }\n\n this.update((state) => {\n state.smartTransactionsState.smartTransactions[chainId][currentIndex] = {\n ...state.smartTransactionsState.smartTransactions[chainId][\n currentIndex\n ],\n ...smartTransaction,\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.#chainId,\n ethQuery = this.#ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery | undefined;\n },\n ): Promise<void> {\n const {\n smartTransactionsState: { smartTransactions },\n } = this.state;\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\n this.update((state) => {\n state.smartTransactionsState.smartTransactions[this.#chainId] =\n nextSmartTransactions;\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.messagingSystem.publish(\n `SmartTransactionsController: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 {\n smartTransactionsState: { smartTransactions },\n } = this.state;\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.#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?: Hex } | 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 // TODO: Replace 'as' assertion with correct typing for `txMeta`\n txMeta as TransactionMeta,\n transactionReceipt,\n // TODO: Replace 'as' assertion with correct typing for `baseFeePerGas`\n baseFeePerGas as Hex,\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 } finally {\n this.messagingSystem.publish(\n `SmartTransactionsController:smartTransactionConfirmationDone`,\n smartTransaction,\n );\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: null,\n tradeTxFees: null,\n };\n this.update((state) => {\n state.smartTransactionsState.fees = 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(\n getAPIRequestURL(APIType.GET_FEES, chainId),\n {\n method: 'POST',\n body: JSON.stringify({\n txs: transactions,\n }),\n },\n );\n let approvalTxFees: IndividualTxFees | null;\n let tradeTxFees: IndividualTxFees | null;\n if (approvalTx) {\n approvalTxFees = data?.txs[0];\n tradeTxFees = data?.txs[1];\n } else {\n approvalTxFees = null;\n tradeTxFees = data?.txs[0];\n }\n\n this.update((state) => {\n if (chainId === this.#chainId) {\n state.smartTransactionsState.fees = {\n approvalTxFees,\n tradeTxFees,\n };\n }\n state.smartTransactionsState.feesByChainId[chainId] = {\n approvalTxFees,\n tradeTxFees,\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?: TransactionMeta;\n txParams?: TransactionParams;\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 && !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 txParams.nonce ??= nonce;\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 if (networkClientId) {\n return this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n ).configuration.chainId;\n }\n\n return this.#chainId;\n }\n\n #getEthQuery({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): EthQuery {\n if (networkClientId) {\n const { provider } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return new EthQuery(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.smartTransactions);\n } catch (error) {\n console.log('\"fetchLiveness\" API call failed');\n }\n\n this.update((state) => {\n if (chainId === this.#chainId) {\n state.smartTransactionsState.liveness = liveness;\n }\n state.smartTransactionsState.livenessByChainId[chainId] = liveness;\n });\n\n return liveness;\n }\n\n async setStatusRefreshInterval(interval: number): Promise<void> {\n if (interval !== this.#interval) {\n this.#interval = interval;\n }\n }\n\n #getCurrentSmartTransactions(): SmartTransaction[] {\n const {\n smartTransactionsState: { smartTransactions },\n } = this.state;\n const currentSmartTransactions = smartTransactions?.[this.#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 {\n smartTransactionsState: { smartTransactions },\n } = this.state;\n (Object.keys(smartTransactions) as Hex[]).forEach((chainId) => {\n this.#wipeSmartTransactionsPerChainId({\n chainId,\n addressLowerCase,\n });\n });\n } else {\n this.#wipeSmartTransactionsPerChainId({\n chainId: this.#chainId,\n addressLowerCase,\n });\n }\n }\n\n #wipeSmartTransactionsPerChainId({\n chainId,\n addressLowerCase,\n }: {\n chainId: Hex;\n addressLowerCase: string;\n }): void {\n const {\n smartTransactionsState: { smartTransactions },\n } = this.state;\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((state) => {\n state.smartTransactionsState.smartTransactions[chainId] =\n newSmartTransactionsForSelectedChain;\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SmartTransactionsController.js","sourceRoot":"","sources":["../src/SmartTransactionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAAA,gDAA+C;AAM/C,iEAKoC;AACpC,oEAA2C;AAM3C,qEAA+E;AAM/E,6EAAqE;AACrE,+CAAyC;AACzC,iEAAyC;AAEzC,2CAA6E;AAe7E,mCAA4D;AAC5D,mCAciB;AAEjB,MAAM,MAAM,GAAG,IAAI,CAAC;AACP,QAAA,gBAAgB,GAAG,MAAM,GAAG,CAAC,CAAC;AAC3C,MAAM,mBAAmB,GACvB,0DAA0D,CAAC;AAE7D;;GAEG;AACH,MAAM,cAAc,GAAG,6BAA6B,CAAC;AAErD,MAA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oC,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,CAAC,KAAK,EAAE,EAAE;QACpB,KAAK,CAAC,sBAAsB,CAAC,iBAAiB,CAAC,OAAO,CAAC;YACrD,oCAAoC,CAAC;IACzC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { hexlify } from '@ethersproject/bytes';\nimport type {\n ControllerGetStateAction,\n ControllerStateChangeEvent,\n RestrictedControllerMessenger,\n} from '@metamask/base-controller';\nimport {\n query,\n safelyExecute,\n ChainId,\n isSafeDynamicKey,\n} from '@metamask/controller-utils';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkControllerGetNetworkClientByIdAction,\n NetworkControllerStateChangeEvent,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingController } from '@metamask/polling-controller';\nimport type {\n TransactionController,\n TransactionMeta,\n TransactionParams,\n} from '@metamask/transaction-controller';\nimport { TransactionStatus } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\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 FeatureFlags,\n ClientId,\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 getReturnTxHashAsap,\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\n/**\n * The name of the {@link SmartTransactionsController}\n */\nconst controllerName = 'SmartTransactionsController';\n\nconst controllerMetadata = {\n smartTransactionsState: {\n persist: false,\n anonymous: true,\n },\n};\n\ntype FeeEstimates = {\n approvalTxFees: IndividualTxFees | null;\n tradeTxFees: IndividualTxFees | null;\n};\n\nexport type SmartTransactionsControllerState = {\n smartTransactionsState: {\n smartTransactions: Record<Hex, SmartTransaction[]>;\n userOptIn: boolean | null;\n userOptInV2: boolean | null;\n liveness: boolean | null;\n fees: FeeEstimates;\n feesByChainId: Record<Hex, FeeEstimates>;\n livenessByChainId: Record<Hex, boolean>;\n };\n};\n\n/**\n * Get the default {@link SmartTransactionsController} state.\n *\n * @returns The default {@link SmartTransactionsController} state.\n */\nexport function getDefaultSmartTransactionsControllerState(): SmartTransactionsControllerState {\n return {\n smartTransactionsState: {\n smartTransactions: {},\n userOptIn: null,\n userOptInV2: null,\n fees: {\n approvalTxFees: null,\n tradeTxFees: null,\n },\n liveness: true,\n livenessByChainId: {\n [ChainId.mainnet]: true,\n [ChainId.sepolia]: true,\n },\n feesByChainId: {\n [ChainId.mainnet]: {\n approvalTxFees: null,\n tradeTxFees: null,\n },\n [ChainId.sepolia]: {\n approvalTxFees: null,\n tradeTxFees: null,\n },\n },\n },\n };\n}\n\nexport type SmartTransactionsControllerGetStateAction =\n ControllerGetStateAction<\n typeof controllerName,\n SmartTransactionsControllerState\n >;\n\n/**\n * The actions that can be performed using the {@link SmartTransactionsController}.\n */\nexport type SmartTransactionsControllerActions =\n SmartTransactionsControllerGetStateAction;\n\nexport type AllowedActions = NetworkControllerGetNetworkClientByIdAction;\n\nexport type SmartTransactionsControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof controllerName,\n SmartTransactionsControllerState\n >;\n\nexport type SmartTransactionsControllerSmartTransactionEvent = {\n type: 'SmartTransactionsController:smartTransaction';\n payload: [SmartTransaction];\n};\n\nexport type SmartTransactionsControllerSmartTransactionConfirmationDoneEvent = {\n type: 'SmartTransactionsController:smartTransactionConfirmationDone';\n payload: [SmartTransaction];\n};\n\n/**\n * The events that {@link SmartTransactionsController} can emit.\n */\nexport type SmartTransactionsControllerEvents =\n | SmartTransactionsControllerStateChangeEvent\n | SmartTransactionsControllerSmartTransactionEvent\n | SmartTransactionsControllerSmartTransactionConfirmationDoneEvent;\n\nexport type AllowedEvents = NetworkControllerStateChangeEvent;\n\n/**\n * The messenger of the {@link SmartTransactionsController}.\n */\nexport type SmartTransactionsControllerMessenger =\n RestrictedControllerMessenger<\n typeof controllerName,\n SmartTransactionsControllerActions | AllowedActions,\n SmartTransactionsControllerEvents | AllowedEvents,\n AllowedActions['type'],\n AllowedEvents['type']\n >;\n\ntype SmartTransactionsControllerOptions = {\n interval?: number;\n clientId: ClientId;\n chainId?: Hex;\n supportedChainIds?: Hex[];\n getNonceLock: TransactionController['getNonceLock'];\n confirmExternalTransaction: TransactionController['confirmExternalTransaction'];\n trackMetaMetricsEvent: (\n event: {\n event: MetaMetricsEventName;\n category: MetaMetricsEventCategory;\n properties?: ReturnType<typeof getSmartTransactionMetricsProperties>;\n sensitiveProperties?: ReturnType<\n typeof getSmartTransactionMetricsSensitiveProperties\n >;\n },\n options?: { metaMetricsId?: string } & Record<string, boolean>,\n ) => void;\n state?: Partial<SmartTransactionsControllerState>;\n messenger: SmartTransactionsControllerMessenger;\n getTransactions: (options?: GetTransactionsOptions) => TransactionMeta[];\n getMetaMetricsProps: () => Promise<MetaMetricsProps>;\n getFeatureFlags: () => FeatureFlags;\n updateTransaction: (transaction: TransactionMeta, note: string) => void;\n};\n\nexport type SmartTransactionsControllerPollingInput = {\n networkClientId: string;\n};\n\nexport default class SmartTransactionsController extends StaticIntervalPollingController<SmartTransactionsControllerPollingInput>()<\n typeof controllerName,\n SmartTransactionsControllerState,\n SmartTransactionsControllerMessenger\n> {\n #interval: number;\n\n #clientId: ClientId;\n\n #chainId: Hex;\n\n #supportedChainIds: Hex[];\n\n timeoutHandle?: NodeJS.Timeout;\n\n readonly #getNonceLock: SmartTransactionsControllerOptions['getNonceLock'];\n\n #ethQuery: EthQuery | undefined;\n\n #confirmExternalTransaction: SmartTransactionsControllerOptions['confirmExternalTransaction'];\n\n #getRegularTransactions: (\n options?: GetTransactionsOptions,\n ) => TransactionMeta[];\n\n readonly #trackMetaMetricsEvent: SmartTransactionsControllerOptions['trackMetaMetricsEvent'];\n\n readonly #getMetaMetricsProps: () => Promise<MetaMetricsProps>;\n\n #getFeatureFlags: SmartTransactionsControllerOptions['getFeatureFlags'];\n\n #updateTransaction: SmartTransactionsControllerOptions['updateTransaction'];\n\n /* istanbul ignore next */\n async #fetch(request: string, options?: RequestInit) {\n const fetchOptions = {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...(this.#clientId && { 'X-Client-Id': this.#clientId }),\n },\n };\n\n return handleFetch(request, fetchOptions);\n }\n\n constructor({\n interval = DEFAULT_INTERVAL,\n clientId,\n chainId: InitialChainId = ChainId.mainnet,\n supportedChainIds = [ChainId.mainnet, ChainId.sepolia],\n getNonceLock,\n confirmExternalTransaction,\n trackMetaMetricsEvent,\n state = {},\n messenger,\n getTransactions,\n getMetaMetricsProps,\n getFeatureFlags,\n updateTransaction,\n }: SmartTransactionsControllerOptions) {\n super({\n name: controllerName,\n metadata: controllerMetadata,\n messenger,\n state: {\n ...getDefaultSmartTransactionsControllerState(),\n ...state,\n },\n });\n this.#interval = interval;\n this.#clientId = clientId;\n this.#chainId = InitialChainId;\n this.#supportedChainIds = supportedChainIds;\n this.setIntervalLength(interval);\n this.#getNonceLock = getNonceLock;\n this.#ethQuery = undefined;\n this.#confirmExternalTransaction = confirmExternalTransaction;\n this.#getRegularTransactions = getTransactions;\n this.#trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.#getMetaMetricsProps = getMetaMetricsProps;\n this.#getFeatureFlags = getFeatureFlags;\n this.#updateTransaction = updateTransaction;\n\n this.initializeSmartTransactionsForChainId();\n\n this.messagingSystem.subscribe(\n 'NetworkController:stateChange',\n ({ selectedNetworkClientId }) => {\n const {\n configuration: { chainId },\n provider,\n } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n selectedNetworkClientId,\n );\n this.#chainId = chainId;\n this.#ethQuery = new EthQuery(provider);\n this.initializeSmartTransactionsForChainId();\n this.checkPoll(this.state);\n },\n );\n\n this.messagingSystem.subscribe(\n `${controllerName}:stateChange`,\n (currentState) => this.checkPoll(currentState),\n );\n }\n\n async _executePoll({\n networkClientId,\n }: SmartTransactionsControllerPollingInput): 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.#supportedChainIds.includes(chainId)) {\n return Promise.resolve();\n }\n return this.updateSmartTransactions({ networkClientId });\n }\n\n checkPoll({\n smartTransactionsState: { smartTransactions },\n }: SmartTransactionsControllerState) {\n const currentSmartTransactions = smartTransactions[this.#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.#supportedChainIds.includes(this.#chainId)) {\n this.update((state) => {\n state.smartTransactionsState.smartTransactions[this.#chainId] =\n state.smartTransactionsState.smartTransactions[this.#chainId] ?? [];\n });\n }\n }\n\n async poll(interval?: number): Promise<void> {\n if (interval) {\n this.#interval = interval;\n }\n\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n\n if (!this.#supportedChainIds.includes(this.#chainId)) {\n return;\n }\n\n this.timeoutHandle = setInterval(() => {\n safelyExecute(async () => this.updateSmartTransactions());\n }, this.#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(optInState: boolean | null): void {\n this.update((state) => {\n state.smartTransactionsState.userOptInV2 = optInState;\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 {\n smartTransactionsState: { smartTransactions },\n } = this.state;\n const currentSmartTransactions = smartTransactions[this.#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 ethQuery = this.#ethQuery;\n let chainId = this.#chainId;\n if (networkClientId) {\n const { configuration, provider } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n chainId = configuration.chainId;\n ethQuery = new EthQuery(provider);\n }\n\n this.#createOrUpdateSmartTransaction(smartTransaction, {\n chainId,\n ethQuery,\n });\n }\n\n #updateSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.#chainId,\n }: {\n chainId: Hex;\n },\n ) {\n const {\n smartTransactionsState: { smartTransactions },\n } = this.state;\n const currentSmartTransactions = smartTransactions[chainId] ?? [];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransaction.uuid,\n );\n\n if (currentIndex === -1) {\n return; // Smart transaction not found, don't update anything.\n }\n\n if (!isSafeDynamicKey(chainId)) {\n return;\n }\n\n this.update((state) => {\n state.smartTransactionsState.smartTransactions[chainId][currentIndex] = {\n ...state.smartTransactionsState.smartTransactions[chainId][\n currentIndex\n ],\n ...smartTransaction,\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.#chainId,\n ethQuery = this.#ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery | undefined;\n },\n ): Promise<void> {\n const {\n smartTransactionsState: { smartTransactions },\n } = this.state;\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\n this.update((state) => {\n state.smartTransactionsState.smartTransactions[this.#chainId] =\n nextSmartTransactions;\n });\n return;\n }\n\n const currentSmartTransaction = currentSmartTransactions[currentIndex];\n const nextSmartTransaction = {\n ...currentSmartTransaction,\n ...smartTransaction,\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.messagingSystem.publish(\n `SmartTransactionsController:smartTransaction`,\n nextSmartTransaction,\n );\n\n if (nextSmartTransaction.status === SmartTransactionStatuses.CANCELLED) {\n const returnTxHashAsap = getReturnTxHashAsap(\n this.#clientId,\n this.#getFeatureFlags()?.smartTransactions,\n );\n if (returnTxHashAsap && nextSmartTransaction.transactionId) {\n const foundTransaction = this.#getRegularTransactions().find(\n (transaction) =>\n transaction.id === nextSmartTransaction.transactionId,\n );\n if (foundTransaction) {\n const updatedTransaction = {\n ...foundTransaction,\n status: TransactionStatus.failed,\n };\n this.#updateTransaction(\n updatedTransaction as TransactionMeta,\n 'Smart transaction cancelled',\n );\n }\n }\n }\n\n if (\n (smartTransaction.status === SmartTransactionStatuses.SUCCESS ||\n smartTransaction.status === SmartTransactionStatuses.REVERTED) &&\n !smartTransaction.confirmed\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 {\n smartTransactionsState: { smartTransactions },\n } = this.state;\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.#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?: Hex } | 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 // TODO: Replace 'as' assertion with correct typing for `txMeta`\n txMeta as TransactionMeta,\n transactionReceipt,\n // TODO: Replace 'as' assertion with correct typing for `baseFeePerGas`\n baseFeePerGas as Hex,\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 } finally {\n this.messagingSystem.publish(\n `SmartTransactionsController:smartTransactionConfirmationDone`,\n smartTransaction,\n );\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: null,\n tradeTxFees: null,\n };\n this.update((state) => {\n state.smartTransactionsState.fees = 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(\n getAPIRequestURL(APIType.GET_FEES, chainId),\n {\n method: 'POST',\n body: JSON.stringify({\n txs: transactions,\n }),\n },\n );\n let approvalTxFees: IndividualTxFees | null;\n let tradeTxFees: IndividualTxFees | null;\n if (approvalTx) {\n approvalTxFees = data?.txs[0];\n tradeTxFees = data?.txs[1];\n } else {\n approvalTxFees = null;\n tradeTxFees = data?.txs[0];\n }\n\n this.update((state) => {\n if (chainId === this.#chainId) {\n state.smartTransactionsState.fees = {\n approvalTxFees,\n tradeTxFees,\n };\n }\n state.smartTransactionsState.feesByChainId[chainId] = {\n approvalTxFees,\n tradeTxFees,\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?: TransactionMeta;\n txParams?: TransactionParams;\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 && !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 txParams.nonce ??= nonce;\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 transactionId: transactionMeta?.id,\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 if (networkClientId) {\n return this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n ).configuration.chainId;\n }\n\n return this.#chainId;\n }\n\n #getEthQuery({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): EthQuery {\n if (networkClientId) {\n const { provider } = this.messagingSystem.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n return new EthQuery(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.smartTransactions);\n } catch (error) {\n console.log('\"fetchLiveness\" API call failed');\n }\n\n this.update((state) => {\n if (chainId === this.#chainId) {\n state.smartTransactionsState.liveness = liveness;\n }\n state.smartTransactionsState.livenessByChainId[chainId] = liveness;\n });\n\n return liveness;\n }\n\n async setStatusRefreshInterval(interval: number): Promise<void> {\n if (interval !== this.#interval) {\n this.#interval = interval;\n }\n }\n\n #getCurrentSmartTransactions(): SmartTransaction[] {\n const {\n smartTransactionsState: { smartTransactions },\n } = this.state;\n const currentSmartTransactions = smartTransactions?.[this.#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 {\n smartTransactionsState: { smartTransactions },\n } = this.state;\n (Object.keys(smartTransactions) as Hex[]).forEach((chainId) => {\n this.#wipeSmartTransactionsPerChainId({\n chainId,\n addressLowerCase,\n });\n });\n } else {\n this.#wipeSmartTransactionsPerChainId({\n chainId: this.#chainId,\n addressLowerCase,\n });\n }\n }\n\n #wipeSmartTransactionsPerChainId({\n chainId,\n addressLowerCase,\n }: {\n chainId: Hex;\n addressLowerCase: string;\n }): void {\n const {\n smartTransactionsState: { smartTransactions },\n } = this.state;\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((state) => {\n state.smartTransactionsState.smartTransactions[chainId] =\n newSmartTransactionsForSelectedChain;\n });\n }\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -39,6 +39,10 @@ export declare enum SmartTransactionStatuses {
|
|
|
39
39
|
CANCELLED_PREVIOUS_TX_CANCELLED = "cancelled_previous_tx_cancelled",
|
|
40
40
|
RESOLVED = "resolved"
|
|
41
41
|
}
|
|
42
|
+
export declare enum ClientId {
|
|
43
|
+
Mobile = "mobile",
|
|
44
|
+
Extension = "extension"
|
|
45
|
+
}
|
|
42
46
|
export declare const cancellationReasonToStatusMap: {
|
|
43
47
|
would_revert: SmartTransactionStatuses;
|
|
44
48
|
too_cheap: SmartTransactionStatuses;
|
|
@@ -84,6 +88,7 @@ export declare type SmartTransaction = {
|
|
|
84
88
|
accountHardwareType?: string;
|
|
85
89
|
accountType?: string;
|
|
86
90
|
deviceModel?: string;
|
|
91
|
+
transactionId?: string;
|
|
87
92
|
};
|
|
88
93
|
export declare type Fee = {
|
|
89
94
|
maxFeePerGas: number;
|
|
@@ -115,3 +120,9 @@ export declare type MetaMetricsProps = {
|
|
|
115
120
|
accountType?: string;
|
|
116
121
|
deviceModel?: string;
|
|
117
122
|
};
|
|
123
|
+
export declare type FeatureFlags = {
|
|
124
|
+
smartTransactions?: {
|
|
125
|
+
mobileReturnTxHashAsap?: boolean;
|
|
126
|
+
extensionReturnTxHashAsap?: boolean;
|
|
127
|
+
};
|
|
128
|
+
};
|
package/dist/types.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.cancellationReasonToStatusMap = exports.SmartTransactionStatuses = exports.SmartTransactionCancellationReason = exports.SmartTransactionMinedTx = exports.APIType = void 0;
|
|
3
|
+
exports.cancellationReasonToStatusMap = exports.ClientId = exports.SmartTransactionStatuses = exports.SmartTransactionCancellationReason = exports.SmartTransactionMinedTx = exports.APIType = void 0;
|
|
4
4
|
/** API */
|
|
5
5
|
var APIType;
|
|
6
6
|
(function (APIType) {
|
|
@@ -45,6 +45,11 @@ var SmartTransactionStatuses;
|
|
|
45
45
|
SmartTransactionStatuses["CANCELLED_PREVIOUS_TX_CANCELLED"] = "cancelled_previous_tx_cancelled";
|
|
46
46
|
SmartTransactionStatuses["RESOLVED"] = "resolved";
|
|
47
47
|
})(SmartTransactionStatuses = exports.SmartTransactionStatuses || (exports.SmartTransactionStatuses = {}));
|
|
48
|
+
var ClientId;
|
|
49
|
+
(function (ClientId) {
|
|
50
|
+
ClientId["Mobile"] = "mobile";
|
|
51
|
+
ClientId["Extension"] = "extension";
|
|
52
|
+
})(ClientId = exports.ClientId || (exports.ClientId = {}));
|
|
48
53
|
exports.cancellationReasonToStatusMap = {
|
|
49
54
|
[SmartTransactionCancellationReason.WOULD_REVERT]: SmartTransactionStatuses.CANCELLED_WOULD_REVERT,
|
|
50
55
|
[SmartTransactionCancellationReason.TOO_CHEAP]: SmartTransactionStatuses.CANCELLED_TOO_CHEAP,
|
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 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 | null;\n tradeTxFees: IndividualTxFees | null;\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"]}
|
|
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,CAA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AC,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 enum ClientId {\n Mobile = 'mobile',\n Extension = 'extension',\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 transactionId?: string; // It's an ID for a regular transaction from the TransactionController.\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 | null;\n tradeTxFees: IndividualTxFees | null;\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\nexport type FeatureFlags = {\n smartTransactions?: {\n mobileReturnTxHashAsap?: boolean;\n extensionReturnTxHashAsap?: boolean;\n };\n};\n"]}
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import type { SmartTransaction, SmartTransactionsStatus } from './types';
|
|
2
|
-
import { APIType, SmartTransactionStatuses } from './types';
|
|
1
|
+
import type { SmartTransaction, SmartTransactionsStatus, FeatureFlags } from './types';
|
|
2
|
+
import { APIType, SmartTransactionStatuses, ClientId } from './types';
|
|
3
3
|
export declare function isSmartTransactionPending(smartTransaction: SmartTransaction): boolean;
|
|
4
4
|
export declare const isSmartTransactionStatusResolved: (stxStatus: SmartTransactionsStatus | string) => boolean;
|
|
5
5
|
export declare function getAPIRequestURL(apiType: APIType, chainId: string): string;
|
|
@@ -75,3 +75,4 @@ export declare const getSmartTransactionMetricsSensitiveProperties: (smartTransa
|
|
|
75
75
|
account_type: string | undefined;
|
|
76
76
|
device_model: string | undefined;
|
|
77
77
|
};
|
|
78
|
+
export declare const getReturnTxHashAsap: (clientId: ClientId, smartTransactionsFeatureFlags: FeatureFlags['smartTransactions']) => boolean | undefined;
|
package/dist/utils.js
CHANGED
|
@@ -3,19 +3,20 @@ 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.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;
|
|
6
|
+
exports.getReturnTxHashAsap = 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");
|
|
10
10
|
const bignumber_js_1 = require("bignumber.js");
|
|
11
11
|
const fast_json_patch_1 = __importDefault(require("fast-json-patch"));
|
|
12
12
|
const lodash_1 = __importDefault(require("lodash"));
|
|
13
|
-
//
|
|
14
|
-
|
|
15
|
-
const types_1 = require("./types");
|
|
13
|
+
// Ignoring TypeScript errors here because this import is disallowed for production builds, because
|
|
14
|
+
// the `package.json` file is above the root directory.
|
|
16
15
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
17
16
|
// @ts-ignore
|
|
18
17
|
const package_json_1 = __importDefault(require("../package.json"));
|
|
18
|
+
const constants_1 = require("./constants");
|
|
19
|
+
const types_1 = require("./types");
|
|
19
20
|
function isSmartTransactionPending(smartTransaction) {
|
|
20
21
|
return smartTransaction.status === types_1.SmartTransactionStatuses.PENDING;
|
|
21
22
|
}
|
|
@@ -227,4 +228,10 @@ const getSmartTransactionMetricsSensitiveProperties = (smartTransaction) => {
|
|
|
227
228
|
};
|
|
228
229
|
};
|
|
229
230
|
exports.getSmartTransactionMetricsSensitiveProperties = getSmartTransactionMetricsSensitiveProperties;
|
|
231
|
+
const getReturnTxHashAsap = (clientId, smartTransactionsFeatureFlags) => {
|
|
232
|
+
return clientId === types_1.ClientId.Extension
|
|
233
|
+
? smartTransactionsFeatureFlags === null || smartTransactionsFeatureFlags === void 0 ? void 0 : smartTransactionsFeatureFlags.extensionReturnTxHashAsap
|
|
234
|
+
: smartTransactionsFeatureFlags === null || smartTransactionsFeatureFlags === void 0 ? void 0 : smartTransactionsFeatureFlags.mobileReturnTxHashAsap;
|
|
235
|
+
};
|
|
236
|
+
exports.getReturnTxHashAsap = getReturnTxHashAsap;
|
|
230
237
|
//# 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,2CAAsE;AAEtE,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,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A8B,aAA9B,8BAA8B,uBAA9B,8BAA8B,CAAE,OAAO;KACrD,CAAC;AACJ,CAAC,CAAC;AAnBW,QAAA,oCAAoC,wCAmB/C;AAEK,MAAM,6CAA6C,GAAG,CAC3D,gBAAkC,EAClC,EAAE;IACF,IAAI,CAAC,gBAAgB,EAAE;QACrB,OAAO,EAAE,CAAC;KACX;IACD,OAAO;QACL,iBAAiB,EAAE,gBAAgB,CAAC,iBAAiB;QACrD,eAAe,EAAE,gBAAgB,CAAC,sBAAsB;QACxD,qBAAqB,EAAE,gBAAgB,CAAC,mBAAmB;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, SENTINEL_API_BASE_URL_MAP } 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 `${SENTINEL_API_BASE_URL_MAP[chainIdDec]}/network`;\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"]}
|
|
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,mGAAmG;AACnG,uDAAuD;AACvD,6DAA6D;AAC7D,aAAa;AACb,mEAA0C;AAC1C,2CAAsE;AAMtE,mCAOiB;AAEjB,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;QAED,K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AAmB;QAC3D,YAAY,EAAE,gBAAgB,CAAC,WAAW;QAC1C,YAAY,EAAE,gBAAgB,CAAC,WAAW;KAC3C,CAAC;AACJ,CAAC,CAAC;AAbW,QAAA,6CAA6C,iDAaxD;AAEK,MAAM,mBAAmB,GAAG,CACjC,QAAkB,EAClB,6BAAgE,EAChE,EAAE;IACF,OAAO,QAAQ,KAAK,gBAAQ,CAAC,SAAS;QACpC,CAAC,CAAC,6BAA6B,aAA7B,6BAA6B,uBAA7B,6BAA6B,CAAE,yBAAyB;QAC1D,CAAC,CAAC,6BAA6B,aAA7B,6BAA6B,uBAA7B,6BAA6B,CAAE,sBAAsB,CAAC;AAC5D,CAAC,CAAC;AAPW,QAAA,mBAAmB,uBAO9B","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// Ignoring TypeScript errors here because this import is disallowed for production builds, because\n// the `package.json` file is above the root directory.\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport packageJson from '../package.json';\nimport { API_BASE_URL, SENTINEL_API_BASE_URL_MAP } from './constants';\nimport type {\n SmartTransaction,\n SmartTransactionsStatus,\n FeatureFlags,\n} from './types';\nimport {\n APIType,\n SmartTransactionStatuses,\n SmartTransactionCancellationReason,\n SmartTransactionMinedTx,\n cancellationReasonToStatusMap,\n ClientId,\n} from './types';\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 `${SENTINEL_API_BASE_URL_MAP[chainIdDec]}/network`;\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\nexport const getReturnTxHashAsap = (\n clientId: ClientId,\n smartTransactionsFeatureFlags: FeatureFlags['smartTransactions'],\n) => {\n return clientId === ClientId.Extension\n ? smartTransactionsFeatureFlags?.extensionReturnTxHashAsap\n : smartTransactionsFeatureFlags?.mobileReturnTxHashAsap;\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/smart-transactions-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "15.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",
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"dist/"
|
|
14
14
|
],
|
|
15
15
|
"scripts": {
|
|
16
|
-
"build": "tsc --project .",
|
|
16
|
+
"build": "tsc --project tsconfig.build.json",
|
|
17
17
|
"build:clean": "rm -rf dist && yarn build",
|
|
18
18
|
"build:link": "yarn build && cd dist && yarn link && rm -rf node_modules && cd ..",
|
|
19
19
|
"lint": "yarn lint:eslint && yarn lint:misc --check",
|
|
@@ -29,26 +29,28 @@
|
|
|
29
29
|
"@ethereumjs/tx": "^5.2.1",
|
|
30
30
|
"@ethereumjs/util": "^9.0.2",
|
|
31
31
|
"@ethersproject/bytes": "^5.7.0",
|
|
32
|
-
"@metamask/base-controller": "^
|
|
32
|
+
"@metamask/base-controller": "^7.0.1",
|
|
33
33
|
"@metamask/controller-utils": "^11.0.0",
|
|
34
|
-
"@metamask/eth-json-rpc-provider": "^4.1.
|
|
34
|
+
"@metamask/eth-json-rpc-provider": "^4.1.6",
|
|
35
35
|
"@metamask/eth-query": "^4.0.0",
|
|
36
|
-
"@metamask/
|
|
37
|
-
"@metamask/polling-controller": "^8.0.0",
|
|
38
|
-
"@metamask/transaction-controller": "^34.0.0",
|
|
36
|
+
"@metamask/polling-controller": "^12.0.0",
|
|
39
37
|
"bignumber.js": "^9.0.1",
|
|
40
38
|
"events": "^3.3.0",
|
|
41
39
|
"fast-json-patch": "^3.1.0",
|
|
42
40
|
"lodash": "^4.17.21"
|
|
43
41
|
},
|
|
44
42
|
"devDependencies": {
|
|
45
|
-
"@lavamoat/allow-scripts": "^2.
|
|
43
|
+
"@lavamoat/allow-scripts": "^3.2.1",
|
|
44
|
+
"@lavamoat/preinstall-always-fail": "^2.1.0",
|
|
46
45
|
"@metamask/auto-changelog": "^3.1.0",
|
|
47
46
|
"@metamask/eslint-config": "^12.2.0",
|
|
48
47
|
"@metamask/eslint-config-jest": "^12.1.0",
|
|
49
48
|
"@metamask/eslint-config-nodejs": "^12.1.0",
|
|
50
49
|
"@metamask/eslint-config-typescript": "^12.1.0",
|
|
51
|
-
"@metamask/
|
|
50
|
+
"@metamask/gas-fee-controller": "^22.0.0",
|
|
51
|
+
"@metamask/json-rpc-engine": "^10.0.1",
|
|
52
|
+
"@metamask/network-controller": "^22.0.0",
|
|
53
|
+
"@metamask/transaction-controller": "^38.0.0",
|
|
52
54
|
"@types/jest": "^26.0.24",
|
|
53
55
|
"@types/lodash": "^4.14.194",
|
|
54
56
|
"@types/node": "^18.19.17",
|
|
@@ -57,7 +59,7 @@
|
|
|
57
59
|
"@typescript-eslint/parser": "^5.33.0",
|
|
58
60
|
"eslint": "^8.48.0",
|
|
59
61
|
"eslint-config-prettier": "^8.8.0",
|
|
60
|
-
"eslint-plugin-import": "
|
|
62
|
+
"eslint-plugin-import": "~2.26.0",
|
|
61
63
|
"eslint-plugin-jest": "^27.1.5",
|
|
62
64
|
"eslint-plugin-jsdoc": "^39.2.9",
|
|
63
65
|
"eslint-plugin-n": "^15.7.0",
|
|
@@ -72,6 +74,18 @@
|
|
|
72
74
|
"ts-jest": "^29.1.4",
|
|
73
75
|
"typescript": "~4.8.4"
|
|
74
76
|
},
|
|
77
|
+
"peerDependencies": {
|
|
78
|
+
"@metamask/network-controller": "^22.0.0",
|
|
79
|
+
"@metamask/transaction-controller": "^38.0.0"
|
|
80
|
+
},
|
|
81
|
+
"peerDependenciesMeta": {
|
|
82
|
+
"@metamask/accounts-controller": {
|
|
83
|
+
"optional": true
|
|
84
|
+
},
|
|
85
|
+
"@metamask/approval-controller": {
|
|
86
|
+
"optional": true
|
|
87
|
+
}
|
|
88
|
+
},
|
|
75
89
|
"packageManager": "yarn@3.2.1",
|
|
76
90
|
"engines": {
|
|
77
91
|
"node": "^18.18 || >=20"
|
package/dist/test-helpers.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
/// <reference types="sinon" />
|
|
2
|
-
/**
|
|
3
|
-
* Resolve all pending promises.
|
|
4
|
-
* This method is used for async tests that use fake timers.
|
|
5
|
-
* See https://stackoverflow.com/a/58716087 and https://jestjs.io/docs/timer-mocks.
|
|
6
|
-
*/
|
|
7
|
-
export declare const flushPromises: () => Promise<unknown>;
|
|
8
|
-
/**
|
|
9
|
-
* Advances the provided fake timer by a specified duration in incremental steps.
|
|
10
|
-
* Between each step, any enqueued promises are processed. Fake timers in testing libraries
|
|
11
|
-
* allow simulation of time without actually waiting. However, they don't always account for
|
|
12
|
-
* promises or other asynchronous operations that may get enqueued during the timer's duration.
|
|
13
|
-
* By advancing time in incremental steps and flushing promises between each step,
|
|
14
|
-
* this function ensures that both timers and promises are comprehensively processed.
|
|
15
|
-
* @param options - The options object.
|
|
16
|
-
* @param options.clock - The Sinon fake timer instance used to manipulate time in tests.
|
|
17
|
-
* @param options.duration - The total amount of time (in milliseconds) to advance the timer by.
|
|
18
|
-
* @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.
|
|
19
|
-
*/
|
|
20
|
-
export declare function advanceTime({ clock, duration, stepSize, }: {
|
|
21
|
-
clock: sinon.SinonFakeTimers;
|
|
22
|
-
duration: number;
|
|
23
|
-
stepSize?: number;
|
|
24
|
-
}): Promise<void>;
|
|
25
|
-
export declare function getFakeProvider(): import("@metamask/eth-json-rpc-provider").SafeEventEmitterProvider;
|
package/dist/test-helpers.js
DELETED
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
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");
|
|
6
|
-
/**
|
|
7
|
-
* Resolve all pending promises.
|
|
8
|
-
* This method is used for async tests that use fake timers.
|
|
9
|
-
* See https://stackoverflow.com/a/58716087 and https://jestjs.io/docs/timer-mocks.
|
|
10
|
-
*/
|
|
11
|
-
const flushPromises = async () => {
|
|
12
|
-
return new Promise(jest.requireActual('timers').setImmediate);
|
|
13
|
-
};
|
|
14
|
-
exports.flushPromises = flushPromises;
|
|
15
|
-
/**
|
|
16
|
-
* Advances the provided fake timer by a specified duration in incremental steps.
|
|
17
|
-
* Between each step, any enqueued promises are processed. Fake timers in testing libraries
|
|
18
|
-
* allow simulation of time without actually waiting. However, they don't always account for
|
|
19
|
-
* promises or other asynchronous operations that may get enqueued during the timer's duration.
|
|
20
|
-
* By advancing time in incremental steps and flushing promises between each step,
|
|
21
|
-
* this function ensures that both timers and promises are comprehensively processed.
|
|
22
|
-
* @param options - The options object.
|
|
23
|
-
* @param options.clock - The Sinon fake timer instance used to manipulate time in tests.
|
|
24
|
-
* @param options.duration - The total amount of time (in milliseconds) to advance the timer by.
|
|
25
|
-
* @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.
|
|
26
|
-
*/
|
|
27
|
-
async function advanceTime({ clock, duration, stepSize = Math.floor(duration / 4), }) {
|
|
28
|
-
do {
|
|
29
|
-
await clock.tickAsync(stepSize);
|
|
30
|
-
await (0, exports.flushPromises)();
|
|
31
|
-
// eslint-disable-next-line no-param-reassign
|
|
32
|
-
duration -= stepSize;
|
|
33
|
-
} while (duration > 0);
|
|
34
|
-
}
|
|
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;
|
|
40
|
-
//# sourceMappingURL=test-helpers.js.map
|
package/dist/test-helpers.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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"]}
|