@metamask/smart-transactions-controller 6.2.1 → 7.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 +71 -5
- package/dist/SmartTransactionsController.d.ts +23 -20
- package/dist/SmartTransactionsController.js +110 -76
- package/dist/SmartTransactionsController.js.map +1 -1
- package/dist/constants.d.ts +8 -0
- package/dist/constants.js +11 -1
- package/dist/constants.js.map +1 -1
- package/dist/test-helpers.d.ts +24 -0
- package/dist/test-helpers.js +34 -0
- package/dist/test-helpers.js.map +1 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.js.map +1 -1
- package/dist/utils.d.ts +3 -1
- package/dist/utils.js +18 -5
- package/dist/utils.js.map +1 -1
- package/package.json +21 -15
package/CHANGELOG.md
CHANGED
|
@@ -6,22 +6,86 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
-
## [
|
|
9
|
+
## [7.0.0]
|
|
10
|
+
### Added
|
|
11
|
+
- **BREAKING:** Track fees and liveness for multiple chains by adding `feesByChainId` and `livenessByChainId` properties to SmartTransactionsControllerState ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237))
|
|
12
|
+
- In particular, clients should prefer accessing `feesByChainId` and `livenessByChainId` instead of `fees` and `liveness`, which will be removed in a future major version.
|
|
13
|
+
- `SmartTransactionsController` now inherits from `StaticIntervalPollingControllerV1` ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237), [#265](https://github.com/MetaMask/smart-transactions-controller/pull/265))
|
|
14
|
+
- This change introduces a set of public methods to the controller which is designed to manage polling on a particular network instead of the globally selected network. Internally, `updateSmartTransactions` will still be called as the legacy polling does. The methods added are:
|
|
15
|
+
- `setIntervalLength`
|
|
16
|
+
- `getIntervalLength`
|
|
17
|
+
- `startPollingByNetworkClientId`
|
|
18
|
+
- `stopAllPolling`
|
|
19
|
+
- `stopPollingByPollingToken`
|
|
20
|
+
- `onPollingCompleteByNetworkClientId`
|
|
21
|
+
- Validation can be now be circumvented by passing the `skipConfirm` option ([#271](https://github.com/MetaMask/smart-transactions-controller/pull/271))
|
|
22
|
+
- Several methods now take a `networkClientId` option within an options object which can be used to operate on smart transactions that live on a particular chain instead of the globally selected one ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237))
|
|
23
|
+
- `updateSmartTransaction`
|
|
24
|
+
- `fetchSmartTransactionsStatus`
|
|
25
|
+
- `getFees`
|
|
26
|
+
- `submitSignedTransactions`
|
|
27
|
+
- `cancelSmartTransaction`
|
|
28
|
+
- `fetchLiveness`
|
|
29
|
+
- Expose `eventEmitter` as a public property ([#298](https://github.com/MetaMask/smart-transactions-controller/pull/298))
|
|
30
|
+
- `submitSignedTransactions` now takes a `transactionMeta` option which is used to set the `type` of the submitted smart transaction ([#298](https://github.com/MetaMask/smart-transactions-controller/pull/298))
|
|
31
|
+
- `submitSignedTransactions` now sets `uuid` and `txHash` on the submitted smart transaction ([#298](https://github.com/MetaMask/smart-transactions-controller/pull/298))
|
|
32
|
+
- `submitSignedTransactions` now returns metadata about the submitted transaction ([#298](https://github.com/MetaMask/smart-transactions-controller/pull/298))
|
|
33
|
+
- Add `getTxHash` utility function which can be used to get the transaction hash from a signed transaction ([#298](https://github.com/MetaMask/smart-transactions-controller/pull/298))
|
|
34
|
+
- `<transaction-uuid>:smartTransaction` is now emitted whenever a smart transaction is updated ([#298](https://github.com/MetaMask/smart-transactions-controller/pull/298))
|
|
35
|
+
- This occurs after transactions are submitted, after they are confirmed, after statuses are updated, and also explicitly via `updateSmartTransaction`.
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
- **BREAKING**: Bump `@metamask/network-controller` from `^15.0.0` to `^17.0.0` ([#238](https://github.com/MetaMask/smart-transactions-controller/pull/238) [#241](https://github.com/MetaMask/smart-transactions-controller/pull/241))
|
|
39
|
+
- This is breaking because the type of the `messenger` has backward-incompatible changes. See the changelog for `@metamask/base-controller@4.0.0` for more.
|
|
40
|
+
- **BREAKING**: The set of supported chains (configurable via `supportedChainIds`) now defaults to including Goerli instead of Rinkeby ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237))
|
|
41
|
+
- **BREAKING**: Minimum Node.js version is now 18.18 ([#270](https://github.com/MetaMask/smart-transactions-controller/pull/270))
|
|
42
|
+
- **BREAKING:** Constrain the type of the constructor `provider` option to `Provider` from `@metamask/network-controller` ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237))
|
|
43
|
+
- **BREAKING:** The constructor now takes a required argument `getNetworkClientById`, which should be bound from NetworkController's `getNetworkClientById` method ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237))
|
|
44
|
+
- **BREAKING:** `fetchSmartTransactionsStatus` now emits `<transaction-uuid>:smartTransaction` instead of `<transaction-uuid>:transaction-hash` ([#279](https://github.com/MetaMask/smart-transactions-controller/pull/279))
|
|
45
|
+
- This event contains more information than just the transaction hash.
|
|
46
|
+
- This event is also always emitted even if there is no transaction hash.
|
|
47
|
+
- **BREAKING:** Use a category of "Transactions" for MetaMetrics events rather than "swaps" ([#282](https://github.com/MetaMask/smart-transactions-controller/pull/282))
|
|
48
|
+
- Bump `@metamask/base-controller` from `^3.2.1` to `^4.0.0` ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237))
|
|
49
|
+
- Bump `@metamask/controller-utils` from `^5.0.0` to `^8.0.3` ([#242](https://github.com/MetaMask/smart-transactions-controller/pull/242) [#244](https://github.com/MetaMask/smart-transactions-controller/pull/244))([#242](https://github.com/MetaMask/smart-transactions-controller/pull/242)) ([#244](https://github.com/MetaMask/smart-transactions-controller/pull/244)) ([#267](https://github.com/MetaMask/smart-transactions-controller/pull/267)) ([#272](https://github.com/MetaMask/smart-transactions-controller/pull/272))
|
|
50
|
+
- Bump `@metamask/network-controller` from `^15.2.0` to `^17.2.0` ([#238](https://github.com/MetaMask/smart-transactions-controller/pull/238)) ([#241](https://github.com/MetaMask/smart-transactions-controller/pull/241)) ([#255](https://github.com/MetaMask/smart-transactions-controller/pull/255)) ([#264](https://github.com/MetaMask/smart-transactions-controller/pull/264)) ([#265](https://github.com/MetaMask/smart-transactions-controller/pull/265))
|
|
51
|
+
- Bump `@metamask/polling-controller` from `^2.0.0` to `^5.0.0` ([#265](https://github.com/MetaMask/smart-transactions-controller/pull/265))
|
|
52
|
+
- Remove `@ethersprovider/bignumber` and `@ethersproject/providers` from dependencies; replace with `@metamask/eth-query@^4.0.0` ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237))
|
|
53
|
+
- Add `events@^3.3.0` as a dependency ([#271](https://github.com/MetaMask/smart-transactions-controller/pull/271))
|
|
54
|
+
- Deprecate `time` property on `SmartTransaction` type in favor of `creationTime` ([#298](https://github.com/MetaMask/smart-transactions-controller/pull/298))
|
|
55
|
+
|
|
56
|
+
### Removed
|
|
57
|
+
- **BREAKING:** Remove property `ethersProvider` from `SmartTransactionsController` ([#237](https://github.com/MetaMask/smart-transactions-controller/pull/237))
|
|
58
|
+
|
|
59
|
+
### Fixed
|
|
60
|
+
- Fix `getFees` so that it does not blow away an existing `nonce` on the trade transaction ([#271](https://github.com/MetaMask/smart-transactions-controller/pull/271))
|
|
61
|
+
- Fix `submitSignedTransactions` so that it sets a `nonce` on the resulting transaction if it doesn't have one ([#271](https://github.com/MetaMask/smart-transactions-controller/pull/271))
|
|
62
|
+
- Fix updating a smart transaction to no longer throw when no smart transactions have been previously saved under the current chain ([#271](https://github.com/MetaMask/smart-transactions-controller/pull/271))
|
|
63
|
+
- Properly override controller name to `SmartTransactionController` ([#273](https://github.com/MetaMask/smart-transactions-controller/pull/273))
|
|
64
|
+
- Properly mark `getFees` as having an optional second argument, since it was being handled that way anyway ([#271](https://github.com/MetaMask/smart-transactions-controller/pull/271))
|
|
65
|
+
- The controller now waits until the first NetworkController update before making use of the `provider` constructor argument to hit the currently selected network ([#274](https://github.com/MetaMask/smart-transactions-controller/pull/274))
|
|
66
|
+
- This change was made because in the future, the `provider` may no longer be defined initially.
|
|
67
|
+
- This change may cause errors to be thrown immediately following a network switch until a future NetworkController state update or polling iteration.
|
|
68
|
+
|
|
69
|
+
## [6.2.2]
|
|
70
|
+
### Fixed
|
|
71
|
+
- Revert "Parameterize SmartTransactionsController state by ChainId for MultiChain + Integrate PollingController Mixin ([#235](https://github.com/MetaMask/smart-transactions-controller/pull/235))
|
|
72
|
+
|
|
73
|
+
## [6.2.1] [DEPRECATED]
|
|
10
74
|
### Fixed
|
|
11
75
|
- Fix a typo in a URL for submitting transactions ([#230](https://github.com/MetaMask/smart-transactions-controller/pull/230))
|
|
12
76
|
|
|
13
|
-
## [6.2.0]
|
|
77
|
+
## [6.2.0] [DEPRECATED]
|
|
14
78
|
### Added
|
|
15
79
|
- Pass current version of this package to API when submitting transactions ([#227](https://github.com/MetaMask/smart-transactions-controller/pull/227))
|
|
16
80
|
|
|
17
|
-
## [6.1.0]
|
|
81
|
+
## [6.1.0] [DEPRECATED]
|
|
18
82
|
### Added
|
|
19
83
|
- Add a new "userOptInV2" prop ([#222](https://github.com/MetaMask/smart-transactions-controller/pull/222))
|
|
20
84
|
|
|
21
85
|
### Changed
|
|
22
86
|
- Bump @metamask/network-controller from 15.0.0 to 15.1.0 ([#219](https://github.com/MetaMask/smart-transactions-controller/pull/219))
|
|
23
87
|
|
|
24
|
-
## [6.0.0]
|
|
88
|
+
## [6.0.0] [DEPRECATED]
|
|
25
89
|
### Added
|
|
26
90
|
- **BREAKING:** `getNetworkClientById` is now required argument in constructor options object ([#210](https://github.com/MetaMask/smart-transactions-controller/pull/210))
|
|
27
91
|
- Integrate `PollingController` mixin and `_executePoll` method used for concurrent multichain polling ([#210](https://github.com/MetaMask/smart-transactions-controller/pull/210))
|
|
@@ -179,7 +243,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
179
243
|
- Add initial SmartTransactionsController ([#1](https://github.com/MetaMask/smart-transactions-controller/pull/1))
|
|
180
244
|
- Initial commit
|
|
181
245
|
|
|
182
|
-
[Unreleased]: https://github.com/MetaMask/smart-transactions-controller/compare/
|
|
246
|
+
[Unreleased]: https://github.com/MetaMask/smart-transactions-controller/compare/v7.0.0...HEAD
|
|
247
|
+
[7.0.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v6.2.2...v7.0.0
|
|
248
|
+
[6.2.2]: https://github.com/MetaMask/smart-transactions-controller/compare/v6.2.1...v6.2.2
|
|
183
249
|
[6.2.1]: https://github.com/MetaMask/smart-transactions-controller/compare/v6.2.0...v6.2.1
|
|
184
250
|
[6.2.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v6.1.0...v6.2.0
|
|
185
251
|
[6.1.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v6.0.0...v6.1.0
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
2
|
+
/// <reference types="node" />
|
|
3
|
+
import type { BaseConfig, BaseState } from '@metamask/base-controller';
|
|
4
|
+
import type { Provider } from '@metamask/eth-query';
|
|
5
|
+
import type { NetworkClientId, NetworkController, NetworkState } from '@metamask/network-controller';
|
|
6
|
+
import { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';
|
|
7
|
+
import EventEmitter from 'events';
|
|
8
|
+
import type { Fees, Hex, IndividualTxFees, SignedCanceledTransaction, SignedTransaction, SmartTransaction, SmartTransactionsStatus, UnsignedTransaction } from './types';
|
|
9
|
+
import { SmartTransactionStatuses } from './types';
|
|
7
10
|
export declare const DEFAULT_INTERVAL: number;
|
|
8
11
|
export declare type SmartTransactionsControllerConfig = BaseConfig & {
|
|
9
12
|
interval: number;
|
|
@@ -26,19 +29,24 @@ export declare type SmartTransactionsControllerState = BaseState & {
|
|
|
26
29
|
livenessByChainId: Record<Hex, boolean>;
|
|
27
30
|
};
|
|
28
31
|
};
|
|
29
|
-
export default class SmartTransactionsController extends
|
|
32
|
+
export default class SmartTransactionsController extends StaticIntervalPollingControllerV1<SmartTransactionsControllerConfig, SmartTransactionsControllerState> {
|
|
30
33
|
#private;
|
|
34
|
+
/**
|
|
35
|
+
* Name of this controller used during composition
|
|
36
|
+
*/
|
|
37
|
+
name: string;
|
|
31
38
|
timeoutHandle?: NodeJS.Timeout;
|
|
32
|
-
private getNonceLock;
|
|
33
|
-
ethQuery
|
|
39
|
+
private readonly getNonceLock;
|
|
40
|
+
private ethQuery;
|
|
34
41
|
confirmExternalTransaction: any;
|
|
35
|
-
private trackMetaMetricsEvent;
|
|
36
|
-
|
|
42
|
+
private readonly trackMetaMetricsEvent;
|
|
43
|
+
eventEmitter: EventEmitter;
|
|
44
|
+
private readonly getNetworkClientById;
|
|
37
45
|
private fetch;
|
|
38
46
|
constructor({ onNetworkStateChange, getNonceLock, provider, confirmExternalTransaction, trackMetaMetricsEvent, getNetworkClientById, }: {
|
|
39
47
|
onNetworkStateChange: (listener: (networkState: NetworkState) => void) => void;
|
|
40
48
|
getNonceLock: any;
|
|
41
|
-
provider:
|
|
49
|
+
provider: Provider;
|
|
42
50
|
confirmExternalTransaction: any;
|
|
43
51
|
trackMetaMetricsEvent: any;
|
|
44
52
|
getNetworkClientById: NetworkController['getNetworkClientById'];
|
|
@@ -59,24 +67,19 @@ export default class SmartTransactionsController extends PollingControllerV1<Sma
|
|
|
59
67
|
}): Promise<void>;
|
|
60
68
|
fetchSmartTransactionsStatus(uuids: string[], { networkClientId }?: {
|
|
61
69
|
networkClientId?: NetworkClientId;
|
|
62
|
-
}): Promise<
|
|
70
|
+
}): Promise<Record<string, SmartTransactionsStatus>>;
|
|
63
71
|
addNonceToTransaction(transaction: UnsignedTransaction): Promise<UnsignedTransaction>;
|
|
64
72
|
clearFees(): Fees;
|
|
65
|
-
getFees(tradeTx: UnsignedTransaction, approvalTx
|
|
73
|
+
getFees(tradeTx: UnsignedTransaction, approvalTx?: UnsignedTransaction, { networkClientId }?: {
|
|
66
74
|
networkClientId?: NetworkClientId;
|
|
67
75
|
}): Promise<Fees>;
|
|
68
|
-
submitSignedTransactions({ txParams, signedTransactions, signedCanceledTransactions, networkClientId, }: {
|
|
76
|
+
submitSignedTransactions({ transactionMeta, txParams, signedTransactions, signedCanceledTransactions, networkClientId, }: {
|
|
69
77
|
signedTransactions: SignedTransaction[];
|
|
70
78
|
signedCanceledTransactions: SignedCanceledTransaction[];
|
|
79
|
+
transactionMeta?: any;
|
|
71
80
|
txParams?: any;
|
|
72
81
|
networkClientId?: NetworkClientId;
|
|
73
82
|
}): Promise<any>;
|
|
74
|
-
getChainId({ networkClientId, }?: {
|
|
75
|
-
networkClientId?: NetworkClientId;
|
|
76
|
-
}): Hex;
|
|
77
|
-
getEthQuery({ networkClientId, }: {
|
|
78
|
-
networkClientId?: NetworkClientId;
|
|
79
|
-
}): EthQuery;
|
|
80
83
|
cancelSmartTransaction(uuid: string, { networkClientId, }?: {
|
|
81
84
|
networkClientId?: NetworkClientId;
|
|
82
85
|
}): Promise<void>;
|
|
@@ -7,27 +7,35 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
7
7
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
8
8
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
9
9
|
};
|
|
10
|
-
var _SmartTransactionsController_instances, _SmartTransactionsController_updateSmartTransaction, _SmartTransactionsController_confirmSmartTransaction;
|
|
10
|
+
var _SmartTransactionsController_instances, _SmartTransactionsController_updateSmartTransaction, _SmartTransactionsController_confirmSmartTransaction, _SmartTransactionsController_getChainId, _SmartTransactionsController_getEthQuery;
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
12
|
exports.DEFAULT_INTERVAL = void 0;
|
|
13
|
+
// eslint-disable-next-line import/no-nodejs-modules
|
|
14
|
+
const bytes_1 = require("@ethersproject/bytes");
|
|
13
15
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
16
|
+
const eth_query_1 = __importDefault(require("@metamask/eth-query"));
|
|
14
17
|
const polling_controller_1 = require("@metamask/polling-controller");
|
|
15
18
|
const bignumber_js_1 = require("bignumber.js");
|
|
16
|
-
|
|
17
|
-
const
|
|
19
|
+
// eslint-disable-next-line import/no-nodejs-modules
|
|
20
|
+
const events_1 = __importDefault(require("events"));
|
|
18
21
|
const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
|
|
22
|
+
const constants_1 = require("./constants");
|
|
19
23
|
const types_1 = require("./types");
|
|
20
24
|
const utils_1 = require("./utils");
|
|
21
|
-
const constants_1 = require("./constants");
|
|
22
25
|
const SECOND = 1000;
|
|
23
26
|
exports.DEFAULT_INTERVAL = SECOND * 5;
|
|
24
|
-
|
|
27
|
+
const ETH_QUERY_ERROR_MSG = '`ethQuery` is not defined on SmartTransactionsController';
|
|
28
|
+
class SmartTransactionsController extends polling_controller_1.StaticIntervalPollingControllerV1 {
|
|
25
29
|
constructor({ onNetworkStateChange, getNonceLock, provider, confirmExternalTransaction, trackMetaMetricsEvent, getNetworkClientById, }, config, state) {
|
|
26
30
|
super(config, state);
|
|
27
31
|
_SmartTransactionsController_instances.add(this);
|
|
32
|
+
/**
|
|
33
|
+
* Name of this controller used during composition
|
|
34
|
+
*/
|
|
35
|
+
this.name = 'SmartTransactionsController';
|
|
28
36
|
this.defaultConfig = {
|
|
29
37
|
interval: exports.DEFAULT_INTERVAL,
|
|
30
|
-
chainId:
|
|
38
|
+
chainId: constants_1.CHAIN_IDS.ETHEREUM,
|
|
31
39
|
clientId: 'default',
|
|
32
40
|
supportedChainIds: [constants_1.CHAIN_IDS.ETHEREUM, constants_1.CHAIN_IDS.GOERLI],
|
|
33
41
|
};
|
|
@@ -57,13 +65,13 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
57
65
|
},
|
|
58
66
|
},
|
|
59
67
|
};
|
|
60
|
-
this.
|
|
68
|
+
this.initialize();
|
|
69
|
+
this.setIntervalLength(this.config.interval);
|
|
61
70
|
this.getNonceLock = getNonceLock;
|
|
62
|
-
this.ethQuery =
|
|
71
|
+
this.ethQuery = undefined;
|
|
63
72
|
this.confirmExternalTransaction = confirmExternalTransaction;
|
|
64
73
|
this.trackMetaMetricsEvent = trackMetaMetricsEvent;
|
|
65
74
|
this.getNetworkClientById = getNetworkClientById;
|
|
66
|
-
this.initialize();
|
|
67
75
|
this.initializeSmartTransactionsForChainId();
|
|
68
76
|
onNetworkStateChange(({ providerConfig: newProvider }) => {
|
|
69
77
|
const { chainId } = newProvider;
|
|
@@ -73,6 +81,7 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
73
81
|
this.ethQuery = new eth_query_1.default(provider);
|
|
74
82
|
});
|
|
75
83
|
this.subscribe((currentState) => this.checkPoll(currentState));
|
|
84
|
+
this.eventEmitter = new events_1.default();
|
|
76
85
|
}
|
|
77
86
|
/* istanbul ignore next */
|
|
78
87
|
async fetch(request, options) {
|
|
@@ -80,12 +89,12 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
80
89
|
const fetchOptions = Object.assign(Object.assign({}, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, (clientId && { 'X-Client-Id': clientId })) });
|
|
81
90
|
return (0, utils_1.handleFetch)(request, fetchOptions);
|
|
82
91
|
}
|
|
83
|
-
_executePoll(networkClientId) {
|
|
92
|
+
async _executePoll(networkClientId) {
|
|
84
93
|
// if this is going to be truly UI driven polling we shouldn't really reach here
|
|
85
94
|
// with a networkClientId that is not supported, but for now I'll add a check in case
|
|
86
95
|
// wondering if we should add some kind of predicate to the polling controller to check whether
|
|
87
96
|
// we should poll or not
|
|
88
|
-
const chainId = this.
|
|
97
|
+
const chainId = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getChainId).call(this, { networkClientId });
|
|
89
98
|
if (!this.config.supportedChainIds.includes(chainId)) {
|
|
90
99
|
return Promise.resolve();
|
|
91
100
|
}
|
|
@@ -118,9 +127,9 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
118
127
|
if (!supportedChainIds.includes(chainId)) {
|
|
119
128
|
return;
|
|
120
129
|
}
|
|
121
|
-
await (0, controller_utils_1.safelyExecute)(() => this.updateSmartTransactions());
|
|
130
|
+
await (0, controller_utils_1.safelyExecute)(async () => this.updateSmartTransactions());
|
|
122
131
|
this.timeoutHandle = setInterval(() => {
|
|
123
|
-
(0, controller_utils_1.safelyExecute)(() => this.updateSmartTransactions());
|
|
132
|
+
(0, controller_utils_1.safelyExecute)(async () => this.updateSmartTransactions());
|
|
124
133
|
}, this.config.interval);
|
|
125
134
|
}
|
|
126
135
|
async stop() {
|
|
@@ -153,8 +162,8 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
153
162
|
stx_user_opt_in: true,
|
|
154
163
|
};
|
|
155
164
|
this.trackMetaMetricsEvent({
|
|
156
|
-
event:
|
|
157
|
-
category:
|
|
165
|
+
event: constants_1.MetaMetricsEventName.StxStatusUpdated,
|
|
166
|
+
category: constants_1.MetaMetricsEventCategory.Transactions,
|
|
158
167
|
sensitiveProperties,
|
|
159
168
|
});
|
|
160
169
|
}
|
|
@@ -167,12 +176,10 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
167
176
|
return currentIndex === -1 || currentIndex === undefined;
|
|
168
177
|
}
|
|
169
178
|
updateSmartTransaction(smartTransaction, { networkClientId } = {}) {
|
|
170
|
-
let { chainId } = this
|
|
171
|
-
let { ethQuery } = this;
|
|
179
|
+
let { ethQuery, config: { chainId }, } = this;
|
|
172
180
|
if (networkClientId) {
|
|
173
181
|
const networkClient = this.getNetworkClientById(networkClientId);
|
|
174
182
|
chainId = networkClient.configuration.chainId;
|
|
175
|
-
// @ts-expect-error TODO: Provider type alignment
|
|
176
183
|
ethQuery = new eth_query_1.default(networkClient.provider);
|
|
177
184
|
}
|
|
178
185
|
__classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, smartTransaction, {
|
|
@@ -182,8 +189,8 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
182
189
|
}
|
|
183
190
|
async updateSmartTransactions({ networkClientId, } = {}) {
|
|
184
191
|
const { smartTransactions } = this.state.smartTransactionsState;
|
|
185
|
-
const chainId = this.
|
|
186
|
-
const smartTransactionsForChainId = smartTransactions
|
|
192
|
+
const chainId = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getChainId).call(this, { networkClientId });
|
|
193
|
+
const smartTransactionsForChainId = smartTransactions[chainId];
|
|
187
194
|
const transactionsToUpdate = smartTransactionsForChainId
|
|
188
195
|
.filter(utils_1.isSmartTransactionPending)
|
|
189
196
|
.map((smartTransaction) => smartTransaction.uuid);
|
|
@@ -198,17 +205,18 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
198
205
|
const params = new URLSearchParams({
|
|
199
206
|
uuids: uuids.join(','),
|
|
200
207
|
});
|
|
201
|
-
const chainId = this.
|
|
202
|
-
const ethQuery = this.
|
|
208
|
+
const chainId = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getChainId).call(this, { networkClientId });
|
|
209
|
+
const ethQuery = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getEthQuery).call(this, { networkClientId });
|
|
203
210
|
const url = `${(0, utils_1.getAPIRequestURL)(types_1.APIType.BATCH_STATUS, chainId)}?${params.toString()}`;
|
|
204
|
-
const data = await this.fetch(url);
|
|
211
|
+
const data = (await this.fetch(url));
|
|
205
212
|
Object.entries(data).forEach(([uuid, stxStatus]) => {
|
|
206
|
-
|
|
213
|
+
const smartTransaction = {
|
|
207
214
|
statusMetadata: stxStatus,
|
|
208
215
|
status: (0, utils_1.calculateStatus)(stxStatus),
|
|
209
216
|
cancellable: (0, utils_1.isSmartTransactionCancellable)(stxStatus),
|
|
210
217
|
uuid,
|
|
211
|
-
}
|
|
218
|
+
};
|
|
219
|
+
__classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, smartTransaction, { chainId, ethQuery });
|
|
212
220
|
});
|
|
213
221
|
return data;
|
|
214
222
|
}
|
|
@@ -229,7 +237,7 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
229
237
|
return fees;
|
|
230
238
|
}
|
|
231
239
|
async getFees(tradeTx, approvalTx, { networkClientId } = {}) {
|
|
232
|
-
const chainId = this.
|
|
240
|
+
const chainId = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getChainId).call(this, { networkClientId });
|
|
233
241
|
const transactions = [];
|
|
234
242
|
let unsignedTradeTransactionWithNonce;
|
|
235
243
|
if (approvalTx) {
|
|
@@ -239,6 +247,9 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
239
247
|
// If there is an approval tx, the trade tx's nonce is increased by 1.
|
|
240
248
|
nonce: (0, utils_1.incrementNonceInHex)(unsignedApprovalTransactionWithNonce.nonce) });
|
|
241
249
|
}
|
|
250
|
+
else if (tradeTx.nonce) {
|
|
251
|
+
unsignedTradeTransactionWithNonce = tradeTx;
|
|
252
|
+
}
|
|
242
253
|
else {
|
|
243
254
|
unsignedTradeTransactionWithNonce = await this.addNonceToTransaction(tradeTx);
|
|
244
255
|
}
|
|
@@ -259,10 +270,12 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
259
270
|
tradeTxFees = data === null || data === void 0 ? void 0 : data.txs[0];
|
|
260
271
|
}
|
|
261
272
|
this.update({
|
|
262
|
-
smartTransactionsState: Object.assign(Object.assign({}, this.state.smartTransactionsState),
|
|
273
|
+
smartTransactionsState: Object.assign(Object.assign(Object.assign({}, this.state.smartTransactionsState), (chainId === this.config.chainId && {
|
|
274
|
+
fees: {
|
|
263
275
|
approvalTxFees,
|
|
264
276
|
tradeTxFees,
|
|
265
|
-
},
|
|
277
|
+
},
|
|
278
|
+
})), { feesByChainId: Object.assign(Object.assign({}, this.state.smartTransactionsState.feesByChainId), { [chainId]: {
|
|
266
279
|
approvalTxFees,
|
|
267
280
|
tradeTxFees,
|
|
268
281
|
} }) }),
|
|
@@ -274,9 +287,10 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
274
287
|
}
|
|
275
288
|
// * After this successful call client must add a nonce representative to
|
|
276
289
|
// * transaction controller external transactions list
|
|
277
|
-
async submitSignedTransactions({ txParams, signedTransactions, signedCanceledTransactions, networkClientId, }) {
|
|
278
|
-
|
|
279
|
-
const
|
|
290
|
+
async submitSignedTransactions({ transactionMeta, txParams, signedTransactions, signedCanceledTransactions, networkClientId, }) {
|
|
291
|
+
var _a;
|
|
292
|
+
const chainId = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getChainId).call(this, { networkClientId });
|
|
293
|
+
const ethQuery = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getEthQuery).call(this, { networkClientId });
|
|
280
294
|
const data = await this.fetch((0, utils_1.getAPIRequestURL)(types_1.APIType.SUBMIT_TRANSACTIONS, chainId), {
|
|
281
295
|
method: 'POST',
|
|
282
296
|
body: JSON.stringify({
|
|
@@ -292,64 +306,63 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
292
306
|
]);
|
|
293
307
|
preTxBalance = new bignumber_js_1.BigNumber(preTxBalanceBN).toString(16);
|
|
294
308
|
}
|
|
295
|
-
catch (
|
|
296
|
-
console.error('provider error',
|
|
309
|
+
catch (error) {
|
|
310
|
+
console.error('provider error', error);
|
|
297
311
|
}
|
|
298
|
-
const
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
312
|
+
const requiresNonce = !txParams.nonce;
|
|
313
|
+
let nonce;
|
|
314
|
+
let nonceLock;
|
|
315
|
+
let nonceDetails = {};
|
|
316
|
+
if (requiresNonce) {
|
|
317
|
+
nonceLock = await this.getNonceLock(txParams === null || txParams === void 0 ? void 0 : txParams.from);
|
|
318
|
+
nonce = (0, bytes_1.hexlify)(nonceLock.nextNonce);
|
|
319
|
+
nonceDetails = nonceLock.nonceDetails;
|
|
320
|
+
if (txParams) {
|
|
321
|
+
(_a = txParams.nonce) !== null && _a !== void 0 ? _a : (txParams.nonce = nonce);
|
|
303
322
|
}
|
|
304
|
-
|
|
323
|
+
}
|
|
324
|
+
const submitTransactionResponse = Object.assign(Object.assign({}, data), { txHash: (0, utils_1.getTxHash)(signedTransactions[0]) });
|
|
325
|
+
try {
|
|
305
326
|
__classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, {
|
|
327
|
+
chainId,
|
|
306
328
|
nonceDetails,
|
|
307
329
|
preTxBalance,
|
|
308
330
|
status: types_1.SmartTransactionStatuses.PENDING,
|
|
309
331
|
time,
|
|
310
332
|
txParams,
|
|
311
|
-
uuid:
|
|
333
|
+
uuid: submitTransactionResponse.uuid,
|
|
334
|
+
txHash: submitTransactionResponse.txHash,
|
|
312
335
|
cancellable: true,
|
|
336
|
+
type: (transactionMeta === null || transactionMeta === void 0 ? void 0 : transactionMeta.type) || 'swap',
|
|
313
337
|
}, { chainId, ethQuery });
|
|
314
338
|
}
|
|
315
339
|
finally {
|
|
316
|
-
nonceLock.releaseLock();
|
|
340
|
+
nonceLock === null || nonceLock === void 0 ? void 0 : nonceLock.releaseLock();
|
|
317
341
|
}
|
|
318
|
-
return
|
|
319
|
-
}
|
|
320
|
-
getChainId({ networkClientId, } = {}) {
|
|
321
|
-
return networkClientId
|
|
322
|
-
? this.getNetworkClientById(networkClientId).configuration.chainId
|
|
323
|
-
: this.config.chainId;
|
|
324
|
-
}
|
|
325
|
-
getEthQuery({ networkClientId, }) {
|
|
326
|
-
return networkClientId
|
|
327
|
-
? // @ts-expect-error TODO: Provider type alignment
|
|
328
|
-
new eth_query_1.default(this.getNetworkClientById(networkClientId).provider)
|
|
329
|
-
: this.ethQuery;
|
|
342
|
+
return submitTransactionResponse;
|
|
330
343
|
}
|
|
331
344
|
// TODO: This should return if the cancellation was on chain or not (for nonce management)
|
|
332
345
|
// After this successful call client must update nonce representative
|
|
333
346
|
// in transaction controller external transactions list
|
|
334
347
|
async cancelSmartTransaction(uuid, { networkClientId, } = {}) {
|
|
335
|
-
const chainId = this.
|
|
348
|
+
const chainId = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getChainId).call(this, { networkClientId });
|
|
336
349
|
await this.fetch((0, utils_1.getAPIRequestURL)(types_1.APIType.CANCEL, chainId), {
|
|
337
350
|
method: 'POST',
|
|
338
351
|
body: JSON.stringify({ uuid }),
|
|
339
352
|
});
|
|
340
353
|
}
|
|
341
354
|
async fetchLiveness({ networkClientId, } = {}) {
|
|
342
|
-
const chainId = this.
|
|
355
|
+
const chainId = __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_getChainId).call(this, { networkClientId });
|
|
343
356
|
let liveness = false;
|
|
344
357
|
try {
|
|
345
358
|
const response = await this.fetch((0, utils_1.getAPIRequestURL)(types_1.APIType.LIVENESS, chainId));
|
|
346
359
|
liveness = Boolean(response.lastBlock);
|
|
347
360
|
}
|
|
348
|
-
catch (
|
|
361
|
+
catch (error) {
|
|
349
362
|
console.log('"fetchLiveness" API call failed');
|
|
350
363
|
}
|
|
351
364
|
this.update({
|
|
352
|
-
smartTransactionsState: Object.assign(Object.assign({}, this.state.smartTransactionsState), { liveness, livenessByChainId: Object.assign(Object.assign({}, this.state.smartTransactionsState.livenessByChainId), { [chainId]: liveness }) }),
|
|
365
|
+
smartTransactionsState: Object.assign(Object.assign(Object.assign({}, this.state.smartTransactionsState), (chainId === this.config.chainId && { liveness })), { livenessByChainId: Object.assign(Object.assign({}, this.state.smartTransactionsState.livenessByChainId), { [chainId]: liveness }) }),
|
|
353
366
|
});
|
|
354
367
|
return liveness;
|
|
355
368
|
}
|
|
@@ -372,12 +385,16 @@ class SmartTransactionsController extends polling_controller_1.PollingController
|
|
|
372
385
|
}
|
|
373
386
|
}
|
|
374
387
|
exports.default = SmartTransactionsController;
|
|
375
|
-
_SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsController_updateSmartTransaction = function _SmartTransactionsController_updateSmartTransaction(smartTransaction, { chainId = this.config.chainId, ethQuery = this.ethQuery, }) {
|
|
388
|
+
_SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsController_updateSmartTransaction = async function _SmartTransactionsController_updateSmartTransaction(smartTransaction, { chainId = this.config.chainId, ethQuery = this.ethQuery, }) {
|
|
389
|
+
var _a;
|
|
376
390
|
const { smartTransactionsState } = this.state;
|
|
377
391
|
const { smartTransactions } = smartTransactionsState;
|
|
378
|
-
const currentSmartTransactions = smartTransactions[chainId];
|
|
392
|
+
const currentSmartTransactions = (_a = smartTransactions[chainId]) !== null && _a !== void 0 ? _a : [];
|
|
379
393
|
const currentIndex = currentSmartTransactions === null || currentSmartTransactions === void 0 ? void 0 : currentSmartTransactions.findIndex((stx) => stx.uuid === smartTransaction.uuid);
|
|
380
394
|
const isNewSmartTransaction = this.isNewSmartTransaction(smartTransaction.uuid);
|
|
395
|
+
if (this.ethQuery === undefined) {
|
|
396
|
+
throw new Error(ETH_QUERY_ERROR_MSG);
|
|
397
|
+
}
|
|
381
398
|
this.trackStxStatusChange(smartTransaction, isNewSmartTransaction
|
|
382
399
|
? undefined
|
|
383
400
|
: currentSmartTransactions[currentIndex]);
|
|
@@ -396,7 +413,7 @@ _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsContro
|
|
|
396
413
|
.slice(0, cancelledNonceIndex)
|
|
397
414
|
.concat(currentSmartTransactions.slice(cancelledNonceIndex + 1))
|
|
398
415
|
.concat(historifiedSmartTransaction)
|
|
399
|
-
: currentSmartTransactions
|
|
416
|
+
: currentSmartTransactions.concat(historifiedSmartTransaction);
|
|
400
417
|
this.update({
|
|
401
418
|
smartTransactionsState: Object.assign(Object.assign({}, smartTransactionsState), { smartTransactions: Object.assign(Object.assign({}, smartTransactionsState.smartTransactions), { [chainId]: nextSmartTransactions }) }),
|
|
402
419
|
});
|
|
@@ -408,19 +425,25 @@ _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsContro
|
|
|
408
425
|
// confirm smart transaction
|
|
409
426
|
const currentSmartTransaction = currentSmartTransactions[currentIndex];
|
|
410
427
|
const nextSmartTransaction = Object.assign(Object.assign({}, currentSmartTransaction), smartTransaction);
|
|
411
|
-
__classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_confirmSmartTransaction).call(this, nextSmartTransaction, {
|
|
428
|
+
await __classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_confirmSmartTransaction).call(this, nextSmartTransaction, {
|
|
412
429
|
chainId,
|
|
413
430
|
ethQuery,
|
|
414
431
|
});
|
|
415
432
|
}
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
}
|
|
433
|
+
else {
|
|
434
|
+
this.update({
|
|
435
|
+
smartTransactionsState: Object.assign(Object.assign({}, smartTransactionsState), { smartTransactions: Object.assign(Object.assign({}, smartTransactionsState.smartTransactions), { [chainId]: smartTransactionsState.smartTransactions[chainId].map((item, index) => {
|
|
436
|
+
return index === currentIndex
|
|
437
|
+
? Object.assign(Object.assign({}, item), smartTransaction) : item;
|
|
438
|
+
}) }) }),
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
this.eventEmitter.emit(`${smartTransaction.uuid}:smartTransaction`, smartTransaction);
|
|
442
|
+
}, _SmartTransactionsController_confirmSmartTransaction = async function _SmartTransactionsController_confirmSmartTransaction(smartTransaction, { chainId = this.config.chainId, ethQuery = this.ethQuery, }) {
|
|
423
443
|
var _a;
|
|
444
|
+
if (ethQuery === undefined) {
|
|
445
|
+
throw new Error(ETH_QUERY_ERROR_MSG);
|
|
446
|
+
}
|
|
424
447
|
const txHash = (_a = smartTransaction.statusMetadata) === null || _a === void 0 ? void 0 : _a.minedHash;
|
|
425
448
|
try {
|
|
426
449
|
const transactionReceipt = await (0, controller_utils_1.query)(ethQuery, 'getTransactionReceipt', [txHash]);
|
|
@@ -430,7 +453,6 @@ _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsContro
|
|
|
430
453
|
if (transactionReceipt === null || transactionReceipt === void 0 ? void 0 : transactionReceipt.blockNumber) {
|
|
431
454
|
const blockData = await (0, controller_utils_1.query)(ethQuery, 'getBlockByNumber', [transactionReceipt === null || transactionReceipt === void 0 ? void 0 : transactionReceipt.blockNumber, false]);
|
|
432
455
|
const baseFeePerGas = blockData === null || blockData === void 0 ? void 0 : blockData.baseFeePerGas;
|
|
433
|
-
const txReceipt = Object.values(transactionReceipt);
|
|
434
456
|
const updatedTxParams = Object.assign(Object.assign({}, smartTransaction.txParams), { maxFeePerGas,
|
|
435
457
|
maxPriorityFeePerGas });
|
|
436
458
|
// call confirmExternalTransaction
|
|
@@ -443,20 +465,32 @@ _SmartTransactionsController_instances = new WeakSet(), _SmartTransactionsContro
|
|
|
443
465
|
const entry = (0, utils_1.generateHistoryEntry)(previousState, snapshot, 'txStateManager: setting status to confirmed');
|
|
444
466
|
const txMeta = entry.length > 0
|
|
445
467
|
? Object.assign(Object.assign({}, originalTxMeta), { history: originalTxMeta.history.concat(entry) }) : originalTxMeta;
|
|
446
|
-
this.confirmExternalTransaction(txMeta,
|
|
468
|
+
this.confirmExternalTransaction(txMeta, transactionReceipt, baseFeePerGas);
|
|
447
469
|
this.trackMetaMetricsEvent({
|
|
448
|
-
event:
|
|
449
|
-
category:
|
|
470
|
+
event: constants_1.MetaMetricsEventName.StxConfirmed,
|
|
471
|
+
category: constants_1.MetaMetricsEventCategory.Transactions,
|
|
450
472
|
});
|
|
451
473
|
__classPrivateFieldGet(this, _SmartTransactionsController_instances, "m", _SmartTransactionsController_updateSmartTransaction).call(this, Object.assign(Object.assign({}, smartTransaction), { confirmed: true }), { chainId, ethQuery });
|
|
452
474
|
}
|
|
453
475
|
}
|
|
454
|
-
catch (
|
|
476
|
+
catch (error) {
|
|
455
477
|
this.trackMetaMetricsEvent({
|
|
456
|
-
event:
|
|
457
|
-
category:
|
|
478
|
+
event: constants_1.MetaMetricsEventName.StxConfirmationFailed,
|
|
479
|
+
category: constants_1.MetaMetricsEventCategory.Transactions,
|
|
458
480
|
});
|
|
459
|
-
console.error('confirm error',
|
|
481
|
+
console.error('confirm error', error);
|
|
482
|
+
}
|
|
483
|
+
}, _SmartTransactionsController_getChainId = function _SmartTransactionsController_getChainId({ networkClientId, } = {}) {
|
|
484
|
+
return networkClientId
|
|
485
|
+
? this.getNetworkClientById(networkClientId).configuration.chainId
|
|
486
|
+
: this.config.chainId;
|
|
487
|
+
}, _SmartTransactionsController_getEthQuery = function _SmartTransactionsController_getEthQuery({ networkClientId, } = {}) {
|
|
488
|
+
if (networkClientId) {
|
|
489
|
+
return new eth_query_1.default(this.getNetworkClientById(networkClientId).provider);
|
|
490
|
+
}
|
|
491
|
+
if (this.ethQuery === undefined) {
|
|
492
|
+
throw new Error(ETH_QUERY_ERROR_MSG);
|
|
460
493
|
}
|
|
494
|
+
return this.ethQuery;
|
|
461
495
|
};
|
|
462
496
|
//# sourceMappingURL=SmartTransactionsController.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SmartTransactionsController.js","sourceRoot":"","sources":["../src/SmartTransactionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,iEAA2E;AAM3E,qEAAmE;AACnE,+CAAyC;AACzC,oEAA2C;AAC3C,gDAA+C;AAC/C,iEAAyC;AAEzC,mCAWiB;AACjB,mCAWiB;AACjB,2CAAwC;AAExC,MAAM,MAAM,GAAG,IAAI,CAAC;AACP,QAAA,gBAAgB,GAAG,MAAM,GAAG,CAAC,CAAC;AA0B3C,MAAqB,2BAA4B,SAAQ,wCAGxD;IA2BC,YACE,EACE,oBAAoB,EACpB,YAAY,EACZ,QAAQ,EACR,0BAA0B,EAC1B,qBAAqB,EACrB,oBAAoB,GAUrB,EACD,MAAmD,EACnD,K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,OAAO;aAClB,CAAC,CAAC;YAEH,uBAAA,IAAI,mGAAwB,MAA5B,IAAI,kCAEG,gBAAgB,KACnB,SAAS,EAAE,IAAI,KAEjB,EAAE,OAAO,EAAE,QAAQ,EAAE,CACtB,CAAC;SACH;KACF;IAAC,OAAO,CAAC,EAAE;QACV,IAAI,CAAC,qBAAqB,CAAC;YACzB,KAAK,EAAE,yBAAyB;YAChC,QAAQ,EAAE,OAAO;SAClB,CAAC,CAAC;QACH,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,CAAC,CAAC,CAAC;KACnC;AACH,CAAC","sourcesContent":["import { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { ChainId, safelyExecute, query } from '@metamask/controller-utils';\nimport {\n NetworkState,\n NetworkController,\n NetworkClientId,\n} from '@metamask/network-controller';\nimport { PollingControllerV1 } from '@metamask/polling-controller';\nimport { BigNumber } from 'bignumber.js';\nimport EthQuery from '@metamask/eth-query';\nimport { hexlify } from '@ethersproject/bytes';\nimport cloneDeep from 'lodash/cloneDeep';\n\nimport {\n APIType,\n SmartTransaction,\n SignedTransaction,\n SignedCanceledTransaction,\n UnsignedTransaction,\n SmartTransactionsStatus,\n SmartTransactionStatuses,\n Fees,\n IndividualTxFees,\n Hex,\n} from './types';\nimport {\n getAPIRequestURL,\n isSmartTransactionPending,\n calculateStatus,\n snapshotFromTxMeta,\n replayHistory,\n generateHistoryEntry,\n getStxProcessingTime,\n handleFetch,\n isSmartTransactionCancellable,\n incrementNonceInHex,\n} from './utils';\nimport { CHAIN_IDS } from './constants';\n\nconst SECOND = 1000;\nexport const DEFAULT_INTERVAL = SECOND * 5;\n\nexport type SmartTransactionsControllerConfig = BaseConfig & {\n interval: number;\n clientId: string;\n chainId: Hex;\n supportedChainIds: string[];\n};\n\ntype FeeEstimates = {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n};\n\nexport type SmartTransactionsControllerState = BaseState & {\n smartTransactionsState: {\n smartTransactions: Record<Hex, SmartTransaction[]>;\n userOptIn: boolean | undefined;\n userOptInV2: boolean | undefined;\n liveness: boolean | undefined;\n fees: FeeEstimates;\n feesByChainId: Record<Hex, FeeEstimates>;\n livenessByChainId: Record<Hex, boolean>;\n };\n};\n\nexport default class SmartTransactionsController extends PollingControllerV1<\n SmartTransactionsControllerConfig,\n SmartTransactionsControllerState\n> {\n public timeoutHandle?: NodeJS.Timeout;\n\n private getNonceLock: any;\n\n public ethQuery: EthQuery;\n\n public confirmExternalTransaction: any;\n\n private trackMetaMetricsEvent: any;\n\n private getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /* istanbul ignore next */\n private async fetch(request: string, options?: RequestInit) {\n const { clientId } = this.config;\n const fetchOptions = {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...(clientId && { 'X-Client-Id': clientId }),\n },\n };\n\n return handleFetch(request, fetchOptions);\n }\n\n constructor(\n {\n onNetworkStateChange,\n getNonceLock,\n provider,\n confirmExternalTransaction,\n trackMetaMetricsEvent,\n getNetworkClientById,\n }: {\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNonceLock: any;\n provider: any;\n confirmExternalTransaction: any;\n trackMetaMetricsEvent: any;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<SmartTransactionsControllerConfig>,\n state?: Partial<SmartTransactionsControllerState>,\n ) {\n super(config, state);\n\n this.defaultConfig = {\n interval: DEFAULT_INTERVAL,\n chainId: ChainId.mainnet,\n clientId: 'default',\n supportedChainIds: [CHAIN_IDS.ETHEREUM, CHAIN_IDS.GOERLI],\n };\n\n this.defaultState = {\n smartTransactionsState: {\n smartTransactions: {},\n userOptIn: undefined,\n userOptInV2: undefined,\n fees: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n liveness: true,\n livenessByChainId: {\n [CHAIN_IDS.ETHEREUM]: true,\n [CHAIN_IDS.GOERLI]: true,\n },\n feesByChainId: {\n [CHAIN_IDS.ETHEREUM]: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n [CHAIN_IDS.GOERLI]: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n },\n },\n };\n this.setIntervalLength(this.config.interval || DEFAULT_INTERVAL);\n this.getNonceLock = getNonceLock;\n this.ethQuery = new EthQuery(provider);\n this.confirmExternalTransaction = confirmExternalTransaction;\n this.trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.getNetworkClientById = getNetworkClientById;\n\n this.initialize();\n this.initializeSmartTransactionsForChainId();\n\n onNetworkStateChange(({ providerConfig: newProvider }) => {\n const { chainId } = newProvider;\n this.configure({ chainId });\n this.initializeSmartTransactionsForChainId();\n this.checkPoll(this.state);\n this.ethQuery = new EthQuery(provider);\n });\n\n this.subscribe((currentState: any) => this.checkPoll(currentState));\n }\n\n _executePoll(networkClientId: string): Promise<void> {\n // if this is going to be truly UI driven polling we shouldn't really reach here\n // with a networkClientId that is not supported, but for now I'll add a check in case\n // wondering if we should add some kind of predicate to the polling controller to check whether\n // we should poll or not\n const chainId = this.getChainId({ networkClientId });\n if (!this.config.supportedChainIds.includes(chainId)) {\n return Promise.resolve();\n }\n return this.updateSmartTransactions({ networkClientId });\n }\n\n checkPoll(state: any) {\n const { smartTransactions } = state.smartTransactionsState;\n const currentSmartTransactions = smartTransactions[this.config.chainId];\n const pendingTransactions = currentSmartTransactions?.filter(\n isSmartTransactionPending,\n );\n if (!this.timeoutHandle && pendingTransactions?.length > 0) {\n this.poll();\n } else if (this.timeoutHandle && pendingTransactions?.length === 0) {\n this.stop();\n }\n }\n\n initializeSmartTransactionsForChainId() {\n if (this.config.supportedChainIds.includes(this.config.chainId)) {\n const { smartTransactionsState } = this.state;\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [this.config.chainId]:\n smartTransactionsState.smartTransactions[this.config.chainId] ??\n [],\n },\n },\n });\n }\n }\n\n async poll(interval?: number): Promise<void> {\n const { chainId, supportedChainIds } = this.config;\n interval && this.configure({ interval }, false, false);\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n if (!supportedChainIds.includes(chainId)) {\n return;\n }\n await safelyExecute(() => this.updateSmartTransactions());\n this.timeoutHandle = setInterval(() => {\n safelyExecute(() => this.updateSmartTransactions());\n }, this.config.interval);\n }\n\n async stop() {\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n this.timeoutHandle = undefined;\n }\n\n setOptInState(state: boolean | undefined): void {\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n userOptInV2: state,\n },\n });\n }\n\n trackStxStatusChange(\n smartTransaction: SmartTransaction,\n prevSmartTransaction?: SmartTransaction,\n ) {\n if (!prevSmartTransaction) {\n return; // Don't track the first STX, because it doesn't have all necessary params.\n }\n\n let updatedSmartTransaction = cloneDeep(smartTransaction);\n updatedSmartTransaction = {\n ...cloneDeep(prevSmartTransaction),\n ...updatedSmartTransaction,\n };\n\n if (\n !updatedSmartTransaction.swapMetaData ||\n (updatedSmartTransaction.status === prevSmartTransaction.status &&\n prevSmartTransaction.swapMetaData)\n ) {\n return; // If status hasn't changed, don't track it again.\n }\n\n const sensitiveProperties = {\n stx_status: updatedSmartTransaction.status,\n token_from_symbol: updatedSmartTransaction.sourceTokenSymbol,\n token_to_symbol: updatedSmartTransaction.destinationTokenSymbol,\n processing_time: getStxProcessingTime(updatedSmartTransaction.time),\n stx_enabled: true,\n current_stx_enabled: true,\n stx_user_opt_in: true,\n };\n\n this.trackMetaMetricsEvent({\n event: 'STX Status Updated',\n category: 'swaps',\n sensitiveProperties,\n });\n }\n\n isNewSmartTransaction(smartTransactionUuid: string): boolean {\n const { chainId } = this.config;\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransactionUuid,\n );\n return currentIndex === -1 || currentIndex === undefined;\n }\n\n updateSmartTransaction(\n smartTransaction: SmartTransaction,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ) {\n let { chainId } = this.config;\n let { ethQuery } = this;\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n chainId = networkClient.configuration.chainId;\n // @ts-expect-error TODO: Provider type alignment\n ethQuery = new EthQuery(networkClient.provider);\n }\n\n this.#updateSmartTransaction(smartTransaction, {\n chainId,\n ethQuery,\n });\n }\n\n #updateSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.config.chainId,\n ethQuery = this.ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery;\n },\n ): void {\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransaction.uuid,\n );\n const isNewSmartTransaction = this.isNewSmartTransaction(\n smartTransaction.uuid,\n );\n\n this.trackStxStatusChange(\n smartTransaction,\n isNewSmartTransaction\n ? undefined\n : currentSmartTransactions[currentIndex],\n );\n\n if (isNewSmartTransaction) {\n // add smart transaction\n const cancelledNonceIndex = currentSmartTransactions?.findIndex(\n (stx: SmartTransaction) =>\n stx.txParams?.nonce === smartTransaction.txParams?.nonce &&\n stx.status?.startsWith('cancelled'),\n );\n const snapshot = cloneDeep(smartTransaction);\n const history = [snapshot];\n const historifiedSmartTransaction = { ...smartTransaction, history };\n const nextSmartTransactions =\n cancelledNonceIndex > -1\n ? currentSmartTransactions\n .slice(0, cancelledNonceIndex)\n .concat(currentSmartTransactions.slice(cancelledNonceIndex + 1))\n .concat(historifiedSmartTransaction)\n : currentSmartTransactions?.concat(historifiedSmartTransaction);\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [chainId]: nextSmartTransactions,\n },\n },\n });\n return;\n }\n\n 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 this.#confirmSmartTransaction(nextSmartTransaction, {\n chainId,\n ethQuery,\n });\n }\n\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [chainId]: smartTransactionsState.smartTransactions[chainId].map(\n (item, index) => {\n return index === currentIndex\n ? { ...item, ...smartTransaction }\n : item;\n },\n ),\n },\n },\n });\n }\n\n async updateSmartTransactions({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): Promise<void> {\n const { smartTransactions } = this.state.smartTransactionsState;\n const chainId = this.getChainId({ networkClientId });\n const smartTransactionsForChainId = smartTransactions?.[chainId];\n\n const transactionsToUpdate: string[] = smartTransactionsForChainId\n .filter(isSmartTransactionPending)\n .map((smartTransaction) => smartTransaction.uuid);\n\n if (transactionsToUpdate.length > 0) {\n this.fetchSmartTransactionsStatus(transactionsToUpdate, {\n networkClientId,\n });\n }\n }\n\n async #confirmSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId,\n ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery;\n },\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\n const transaction: {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n } | null = await query(ethQuery, 'getTransactionByHash', [txHash]);\n\n const maxFeePerGas = transaction?.maxFeePerGas;\n const maxPriorityFeePerGas = transaction?.maxPriorityFeePerGas;\n if (transactionReceipt?.blockNumber) {\n const blockData: { baseFeePerGas?: string } | null = await query(\n ethQuery,\n 'getBlockByNumber',\n [transactionReceipt?.blockNumber, false],\n );\n const baseFeePerGas = blockData?.baseFeePerGas;\n const txReceipt = Object.values(transactionReceipt);\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: '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 this.confirmExternalTransaction(txMeta, txReceipt, baseFeePerGas);\n\n this.trackMetaMetricsEvent({\n event: 'STX Confirmed',\n category: 'swaps',\n });\n\n this.#updateSmartTransaction(\n {\n ...smartTransaction,\n confirmed: true,\n },\n { chainId, ethQuery },\n );\n }\n } catch (e) {\n this.trackMetaMetricsEvent({\n event: 'STX Confirmation Failed',\n category: 'swaps',\n });\n console.error('confirm error', e);\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<SmartTransaction[]> {\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);\n Object.entries(data).forEach(([uuid, stxStatus]) => {\n this.#updateSmartTransaction(\n {\n statusMetadata: stxStatus as SmartTransactionsStatus,\n status: calculateStatus(stxStatus as SmartTransactionsStatus),\n cancellable: isSmartTransactionCancellable(\n stxStatus as SmartTransactionsStatus,\n ),\n uuid,\n },\n { chainId, ethQuery },\n );\n });\n\n return data;\n }\n\n async addNonceToTransaction(\n transaction: UnsignedTransaction,\n ): Promise<UnsignedTransaction> {\n const nonceLock = await this.getNonceLock(transaction.from);\n const nonce = nonceLock.nextNonce;\n nonceLock.releaseLock();\n return {\n ...transaction,\n nonce: `0x${nonce.toString(16)}`,\n };\n }\n\n clearFees(): Fees {\n const fees = {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n };\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n fees,\n },\n });\n return fees;\n }\n\n async getFees(\n tradeTx: UnsignedTransaction,\n approvalTx: UnsignedTransaction,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ): Promise<Fees> {\n const chainId = this.getChainId({ networkClientId });\n const transactions = [];\n let unsignedTradeTransactionWithNonce;\n if (approvalTx) {\n const unsignedApprovalTransactionWithNonce =\n await this.addNonceToTransaction(approvalTx);\n transactions.push(unsignedApprovalTransactionWithNonce);\n unsignedTradeTransactionWithNonce = {\n ...tradeTx,\n // If there is an approval tx, the trade tx's nonce is increased by 1.\n nonce: incrementNonceInHex(unsignedApprovalTransactionWithNonce.nonce),\n };\n } else {\n unsignedTradeTransactionWithNonce = await this.addNonceToTransaction(\n tradeTx,\n );\n }\n transactions.push(unsignedTradeTransactionWithNonce);\n const data = await this.fetch(getAPIRequestURL(APIType.GET_FEES, chainId), {\n method: 'POST',\n body: JSON.stringify({\n txs: transactions,\n }),\n });\n let approvalTxFees;\n let tradeTxFees;\n if (approvalTx) {\n approvalTxFees = data?.txs[0];\n tradeTxFees = data?.txs[1];\n } else {\n tradeTxFees = data?.txs[0];\n }\n\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n fees: {\n approvalTxFees,\n tradeTxFees,\n },\n feesByChainId: {\n ...this.state.smartTransactionsState.feesByChainId,\n [chainId]: {\n approvalTxFees,\n tradeTxFees,\n },\n },\n },\n });\n\n return {\n approvalTxFees,\n tradeTxFees,\n };\n }\n\n // * After this successful call client must add a nonce representative to\n // * transaction controller external transactions list\n async submitSignedTransactions({\n txParams,\n signedTransactions,\n signedCanceledTransactions,\n networkClientId,\n }: {\n signedTransactions: SignedTransaction[];\n signedCanceledTransactions: SignedCanceledTransaction[];\n txParams?: any;\n networkClientId?: NetworkClientId;\n }) {\n const chainId = this.getChainId({ networkClientId });\n const ethQuery = this.getEthQuery({ networkClientId });\n const data = await this.fetch(\n getAPIRequestURL(APIType.SUBMIT_TRANSACTIONS, chainId),\n {\n method: 'POST',\n body: JSON.stringify({\n rawTxs: signedTransactions,\n rawCancelTxs: signedCanceledTransactions,\n }),\n },\n );\n const time = Date.now();\n let preTxBalance;\n try {\n const preTxBalanceBN = await query(ethQuery, 'getBalance', [\n txParams?.from,\n ]);\n preTxBalance = new BigNumber(preTxBalanceBN).toString(16);\n } catch (e) {\n console.error('provider error', e);\n }\n const nonceLock = await this.getNonceLock(txParams?.from);\n try {\n const nonce = hexlify(nonceLock.nextNonce);\n if (txParams && !txParams?.nonce) {\n txParams.nonce = nonce;\n }\n const { nonceDetails } = nonceLock;\n\n this.#updateSmartTransaction(\n {\n nonceDetails,\n preTxBalance,\n status: SmartTransactionStatuses.PENDING,\n time,\n txParams,\n uuid: data.uuid,\n cancellable: true,\n },\n { chainId, ethQuery },\n );\n } finally {\n nonceLock.releaseLock();\n }\n\n return data;\n }\n\n getChainId({\n networkClientId,\n }: { networkClientId?: NetworkClientId } = {}): Hex {\n return networkClientId\n ? this.getNetworkClientById(networkClientId).configuration.chainId\n : this.config.chainId;\n }\n\n getEthQuery({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n }): EthQuery {\n return networkClientId\n ? // @ts-expect-error TODO: Provider type alignment\n new EthQuery(this.getNetworkClientById(networkClientId).provider)\n : this.ethQuery;\n }\n\n // TODO: This should return if the cancellation was on chain or not (for nonce management)\n // After this successful call client must update nonce representative\n // in transaction controller external transactions list\n async cancelSmartTransaction(\n uuid: string,\n {\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {},\n ): Promise<void> {\n const chainId = this.getChainId({ networkClientId });\n await this.fetch(getAPIRequestURL(APIType.CANCEL, chainId), {\n method: 'POST',\n body: JSON.stringify({ uuid }),\n });\n }\n\n async fetchLiveness({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): Promise<boolean> {\n const chainId = this.getChainId({ networkClientId });\n let liveness = false;\n try {\n const response = await this.fetch(\n getAPIRequestURL(APIType.LIVENESS, chainId),\n );\n liveness = Boolean(response.lastBlock);\n } catch (e) {\n console.log('\"fetchLiveness\" API call failed');\n }\n\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n liveness,\n livenessByChainId: {\n ...this.state.smartTransactionsState.livenessByChainId,\n [chainId]: liveness,\n },\n },\n });\n\n return liveness;\n }\n\n async setStatusRefreshInterval(interval: number): Promise<void> {\n if (interval !== this.config.interval) {\n this.configure({ interval }, false, false);\n }\n }\n\n getTransactions({\n addressFrom,\n status,\n }: {\n addressFrom: string;\n status: SmartTransactionStatuses;\n }): SmartTransaction[] {\n const { smartTransactions } = this.state.smartTransactionsState;\n const { chainId } = this.config;\n const currentSmartTransactions = smartTransactions?.[chainId];\n if (!currentSmartTransactions || currentSmartTransactions.length === 0) {\n return [];\n }\n\n return currentSmartTransactions.filter((stx) => {\n return stx.status === status && stx.txParams?.from === addressFrom;\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SmartTransactionsController.js","sourceRoot":"","sources":["../src/SmartTransactionsController.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,oDAAoD;AACpD,gDAA+C;AAE/C,iEAAkE;AAElE,oEAA2C;AAM3C,qEAAiF;AACjF,+CAAyC;AACzC,oDAAoD;AACpD,oDAAkC;AAClC,iEAAyC;AAEzC,2CAIqB;AAWrB,mCAA4D;AAC5D,mCAYiB;AAEjB,MAAM,MAAM,GAAG,IAAI,CAAC;AACP,QAAA,gBAAgB,GAAG,MAAM,GAAG,CAAC,CAAC;AAC3C,MA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BAAqB;YACjD,QAAQ,EAAE,oCAAwB,CAAC,YAAY;SAChD,CAAC,CAAC;QACH,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;KACvC;AACH,CAAC,6FA6MW,EACV,eAAe,MAC0B,EAAE;IAC3C,OAAO,eAAe;QACpB,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,CAAC,aAAa,CAAC,OAAO;QAClE,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC;AAC1B,CAAC,+FAEY,EACX,eAAe,MAGb,EAAE;IACJ,IAAI,eAAe,EAAE;QACnB,OAAO,IAAI,mBAAQ,CAAC,IAAI,CAAC,oBAAoB,CAAC,eAAe,CAAC,CAAC,QAAQ,CAAC,CAAC;KAC1E;IAED,IAAI,IAAI,CAAC,QAAQ,KAAK,SAAS,EAAE;QAC/B,MAAM,IAAI,KAAK,CAAC,mBAAmB,CAAC,CAAC;KACtC;IAED,OAAO,IAAI,CAAC,QAAQ,CAAC;AACvB,CAAC","sourcesContent":["// eslint-disable-next-line import/no-nodejs-modules\nimport { hexlify } from '@ethersproject/bytes';\nimport type { BaseConfig, BaseState } from '@metamask/base-controller';\nimport { query, safelyExecute } from '@metamask/controller-utils';\nimport type { Provider } from '@metamask/eth-query';\nimport EthQuery from '@metamask/eth-query';\nimport type {\n NetworkClientId,\n NetworkController,\n NetworkState,\n} from '@metamask/network-controller';\nimport { StaticIntervalPollingControllerV1 } from '@metamask/polling-controller';\nimport { BigNumber } from 'bignumber.js';\n// eslint-disable-next-line import/no-nodejs-modules\nimport EventEmitter from 'events';\nimport cloneDeep from 'lodash/cloneDeep';\n\nimport {\n CHAIN_IDS,\n MetaMetricsEventCategory,\n MetaMetricsEventName,\n} from './constants';\nimport type {\n Fees,\n Hex,\n IndividualTxFees,\n SignedCanceledTransaction,\n SignedTransaction,\n SmartTransaction,\n SmartTransactionsStatus,\n UnsignedTransaction,\n} from './types';\nimport { APIType, SmartTransactionStatuses } from './types';\nimport {\n calculateStatus,\n generateHistoryEntry,\n getAPIRequestURL,\n getStxProcessingTime,\n handleFetch,\n incrementNonceInHex,\n isSmartTransactionCancellable,\n isSmartTransactionPending,\n replayHistory,\n snapshotFromTxMeta,\n getTxHash,\n} from './utils';\n\nconst SECOND = 1000;\nexport const DEFAULT_INTERVAL = SECOND * 5;\nconst ETH_QUERY_ERROR_MSG =\n '`ethQuery` is not defined on SmartTransactionsController';\n\nexport type SmartTransactionsControllerConfig = BaseConfig & {\n interval: number;\n clientId: string;\n chainId: Hex;\n supportedChainIds: string[];\n};\n\ntype FeeEstimates = {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n};\n\nexport type SmartTransactionsControllerState = BaseState & {\n smartTransactionsState: {\n smartTransactions: Record<Hex, SmartTransaction[]>;\n userOptIn: boolean | undefined;\n userOptInV2: boolean | undefined;\n liveness: boolean | undefined;\n fees: FeeEstimates;\n feesByChainId: Record<Hex, FeeEstimates>;\n livenessByChainId: Record<Hex, boolean>;\n };\n};\n\nexport default class SmartTransactionsController extends StaticIntervalPollingControllerV1<\n SmartTransactionsControllerConfig,\n SmartTransactionsControllerState\n> {\n /**\n * Name of this controller used during composition\n */\n override name = 'SmartTransactionsController';\n\n public timeoutHandle?: NodeJS.Timeout;\n\n private readonly getNonceLock: any;\n\n private ethQuery: EthQuery | undefined;\n\n public confirmExternalTransaction: any;\n\n private readonly trackMetaMetricsEvent: any;\n\n public eventEmitter: EventEmitter;\n\n private readonly getNetworkClientById: NetworkController['getNetworkClientById'];\n\n /* istanbul ignore next */\n private async fetch(request: string, options?: RequestInit) {\n const { clientId } = this.config;\n const fetchOptions = {\n ...options,\n headers: {\n 'Content-Type': 'application/json',\n ...(clientId && { 'X-Client-Id': clientId }),\n },\n };\n\n return handleFetch(request, fetchOptions);\n }\n\n constructor(\n {\n onNetworkStateChange,\n getNonceLock,\n provider,\n confirmExternalTransaction,\n trackMetaMetricsEvent,\n getNetworkClientById,\n }: {\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNonceLock: any;\n provider: Provider;\n confirmExternalTransaction: any;\n trackMetaMetricsEvent: any;\n getNetworkClientById: NetworkController['getNetworkClientById'];\n },\n config?: Partial<SmartTransactionsControllerConfig>,\n state?: Partial<SmartTransactionsControllerState>,\n ) {\n super(config, state);\n\n this.defaultConfig = {\n interval: DEFAULT_INTERVAL,\n chainId: CHAIN_IDS.ETHEREUM,\n clientId: 'default',\n supportedChainIds: [CHAIN_IDS.ETHEREUM, CHAIN_IDS.GOERLI],\n };\n\n this.defaultState = {\n smartTransactionsState: {\n smartTransactions: {},\n userOptIn: undefined,\n userOptInV2: undefined,\n fees: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n liveness: true,\n livenessByChainId: {\n [CHAIN_IDS.ETHEREUM]: true,\n [CHAIN_IDS.GOERLI]: true,\n },\n feesByChainId: {\n [CHAIN_IDS.ETHEREUM]: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n [CHAIN_IDS.GOERLI]: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n },\n },\n };\n\n this.initialize();\n this.setIntervalLength(this.config.interval);\n this.getNonceLock = getNonceLock;\n this.ethQuery = undefined;\n this.confirmExternalTransaction = confirmExternalTransaction;\n this.trackMetaMetricsEvent = trackMetaMetricsEvent;\n this.getNetworkClientById = getNetworkClientById;\n\n this.initializeSmartTransactionsForChainId();\n\n onNetworkStateChange(({ providerConfig: newProvider }) => {\n const { chainId } = newProvider;\n this.configure({ chainId });\n this.initializeSmartTransactionsForChainId();\n this.checkPoll(this.state);\n this.ethQuery = new EthQuery(provider);\n });\n\n this.subscribe((currentState: any) => this.checkPoll(currentState));\n this.eventEmitter = new EventEmitter();\n }\n\n async _executePoll(networkClientId: string): Promise<void> {\n // if this is going to be truly UI driven polling we shouldn't really reach here\n // with a networkClientId that is not supported, but for now I'll add a check in case\n // wondering if we should add some kind of predicate to the polling controller to check whether\n // we should poll or not\n const chainId = this.#getChainId({ networkClientId });\n if (!this.config.supportedChainIds.includes(chainId)) {\n return Promise.resolve();\n }\n return this.updateSmartTransactions({ networkClientId });\n }\n\n checkPoll(state: any) {\n const { smartTransactions } = state.smartTransactionsState;\n const currentSmartTransactions = smartTransactions[this.config.chainId];\n const pendingTransactions = currentSmartTransactions?.filter(\n isSmartTransactionPending,\n );\n if (!this.timeoutHandle && pendingTransactions?.length > 0) {\n this.poll();\n } else if (this.timeoutHandle && pendingTransactions?.length === 0) {\n this.stop();\n }\n }\n\n initializeSmartTransactionsForChainId() {\n if (this.config.supportedChainIds.includes(this.config.chainId)) {\n const { smartTransactionsState } = this.state;\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [this.config.chainId]:\n smartTransactionsState.smartTransactions[this.config.chainId] ??\n [],\n },\n },\n });\n }\n }\n\n async poll(interval?: number): Promise<void> {\n const { chainId, supportedChainIds } = this.config;\n interval && this.configure({ interval }, false, false);\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n if (!supportedChainIds.includes(chainId)) {\n return;\n }\n await safelyExecute(async () => this.updateSmartTransactions());\n this.timeoutHandle = setInterval(() => {\n safelyExecute(async () => this.updateSmartTransactions());\n }, this.config.interval);\n }\n\n async stop() {\n this.timeoutHandle && clearInterval(this.timeoutHandle);\n this.timeoutHandle = undefined;\n }\n\n setOptInState(state: boolean | undefined): void {\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n userOptInV2: state,\n },\n });\n }\n\n trackStxStatusChange(\n smartTransaction: SmartTransaction,\n prevSmartTransaction?: SmartTransaction,\n ) {\n if (!prevSmartTransaction) {\n return; // Don't track the first STX, because it doesn't have all necessary params.\n }\n\n let updatedSmartTransaction = cloneDeep(smartTransaction);\n updatedSmartTransaction = {\n ...cloneDeep(prevSmartTransaction),\n ...updatedSmartTransaction,\n };\n\n if (\n !updatedSmartTransaction.swapMetaData ||\n (updatedSmartTransaction.status === prevSmartTransaction.status &&\n prevSmartTransaction.swapMetaData)\n ) {\n return; // If status hasn't changed, don't track it again.\n }\n\n const sensitiveProperties = {\n stx_status: updatedSmartTransaction.status,\n token_from_symbol: updatedSmartTransaction.sourceTokenSymbol,\n token_to_symbol: updatedSmartTransaction.destinationTokenSymbol,\n processing_time: getStxProcessingTime(updatedSmartTransaction.time),\n stx_enabled: true,\n current_stx_enabled: true,\n stx_user_opt_in: true,\n };\n\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxStatusUpdated,\n category: MetaMetricsEventCategory.Transactions,\n sensitiveProperties,\n });\n }\n\n isNewSmartTransaction(smartTransactionUuid: string): boolean {\n const { chainId } = this.config;\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransactionUuid,\n );\n return currentIndex === -1 || currentIndex === undefined;\n }\n\n updateSmartTransaction(\n smartTransaction: SmartTransaction,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ) {\n let {\n ethQuery,\n config: { chainId },\n } = this;\n if (networkClientId) {\n const networkClient = this.getNetworkClientById(networkClientId);\n chainId = networkClient.configuration.chainId;\n ethQuery = new EthQuery(networkClient.provider);\n }\n\n this.#updateSmartTransaction(smartTransaction, {\n chainId,\n ethQuery,\n });\n }\n\n async #updateSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.config.chainId,\n ethQuery = this.ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery | undefined;\n },\n ): Promise<void> {\n const { smartTransactionsState } = this.state;\n const { smartTransactions } = smartTransactionsState;\n const currentSmartTransactions = smartTransactions[chainId] ?? [];\n const currentIndex = currentSmartTransactions?.findIndex(\n (stx) => stx.uuid === smartTransaction.uuid,\n );\n const isNewSmartTransaction = this.isNewSmartTransaction(\n smartTransaction.uuid,\n );\n if (this.ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n\n this.trackStxStatusChange(\n smartTransaction,\n isNewSmartTransaction\n ? undefined\n : currentSmartTransactions[currentIndex],\n );\n\n if (isNewSmartTransaction) {\n // add smart transaction\n const cancelledNonceIndex = currentSmartTransactions?.findIndex(\n (stx: SmartTransaction) =>\n stx.txParams?.nonce === smartTransaction.txParams?.nonce &&\n stx.status?.startsWith('cancelled'),\n );\n const snapshot = cloneDeep(smartTransaction);\n const history = [snapshot];\n const historifiedSmartTransaction = { ...smartTransaction, history };\n const nextSmartTransactions =\n cancelledNonceIndex > -1\n ? currentSmartTransactions\n .slice(0, cancelledNonceIndex)\n .concat(currentSmartTransactions.slice(cancelledNonceIndex + 1))\n .concat(historifiedSmartTransaction)\n : currentSmartTransactions.concat(historifiedSmartTransaction);\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [chainId]: nextSmartTransactions,\n },\n },\n });\n return;\n }\n\n if (\n (smartTransaction.status === SmartTransactionStatuses.SUCCESS ||\n smartTransaction.status === SmartTransactionStatuses.REVERTED) &&\n !smartTransaction.confirmed\n ) {\n // confirm smart transaction\n const currentSmartTransaction = currentSmartTransactions[currentIndex];\n const nextSmartTransaction = {\n ...currentSmartTransaction,\n ...smartTransaction,\n };\n await this.#confirmSmartTransaction(nextSmartTransaction, {\n chainId,\n ethQuery,\n });\n } else {\n this.update({\n smartTransactionsState: {\n ...smartTransactionsState,\n smartTransactions: {\n ...smartTransactionsState.smartTransactions,\n [chainId]: smartTransactionsState.smartTransactions[chainId].map(\n (item, index) => {\n return index === currentIndex\n ? { ...item, ...smartTransaction }\n : item;\n },\n ),\n },\n },\n });\n }\n\n this.eventEmitter.emit(\n `${smartTransaction.uuid}:smartTransaction`,\n smartTransaction,\n );\n }\n\n async updateSmartTransactions({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): Promise<void> {\n const { smartTransactions } = this.state.smartTransactionsState;\n const chainId = this.#getChainId({ networkClientId });\n const smartTransactionsForChainId = smartTransactions[chainId];\n\n const transactionsToUpdate: string[] = smartTransactionsForChainId\n .filter(isSmartTransactionPending)\n .map((smartTransaction) => smartTransaction.uuid);\n\n if (transactionsToUpdate.length > 0) {\n this.fetchSmartTransactionsStatus(transactionsToUpdate, {\n networkClientId,\n });\n }\n }\n\n async #confirmSmartTransaction(\n smartTransaction: SmartTransaction,\n {\n chainId = this.config.chainId,\n ethQuery = this.ethQuery,\n }: {\n chainId: Hex;\n ethQuery: EthQuery | undefined;\n },\n ) {\n if (ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n const txHash = smartTransaction.statusMetadata?.minedHash;\n try {\n const transactionReceipt: {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n blockNumber: string;\n } | null = await query(ethQuery, 'getTransactionReceipt', [txHash]);\n const transaction: {\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n } | null = await query(ethQuery, 'getTransactionByHash', [txHash]);\n\n const maxFeePerGas = transaction?.maxFeePerGas;\n const maxPriorityFeePerGas = transaction?.maxPriorityFeePerGas;\n if (transactionReceipt?.blockNumber) {\n const blockData: { baseFeePerGas?: string } | null = await query(\n ethQuery,\n 'getBlockByNumber',\n [transactionReceipt?.blockNumber, false],\n );\n const baseFeePerGas = blockData?.baseFeePerGas;\n const updatedTxParams = {\n ...smartTransaction.txParams,\n maxFeePerGas,\n maxPriorityFeePerGas,\n };\n // call confirmExternalTransaction\n const originalTxMeta = {\n ...smartTransaction,\n id: smartTransaction.uuid,\n status: '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 this.confirmExternalTransaction(\n txMeta,\n transactionReceipt,\n baseFeePerGas,\n );\n\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxConfirmed,\n category: MetaMetricsEventCategory.Transactions,\n });\n\n this.#updateSmartTransaction(\n {\n ...smartTransaction,\n confirmed: true,\n },\n { chainId, ethQuery },\n );\n }\n } catch (error) {\n this.trackMetaMetricsEvent({\n event: MetaMetricsEventName.StxConfirmationFailed,\n category: MetaMetricsEventCategory.Transactions,\n });\n console.error('confirm error', error);\n }\n }\n\n // ! Ask backend API to accept list of uuids as params\n async fetchSmartTransactionsStatus(\n uuids: string[],\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ): Promise<Record<string, SmartTransactionsStatus>> {\n const params = new URLSearchParams({\n uuids: uuids.join(','),\n });\n const chainId = this.#getChainId({ networkClientId });\n const ethQuery = this.#getEthQuery({ networkClientId });\n const url = `${getAPIRequestURL(\n APIType.BATCH_STATUS,\n chainId,\n )}?${params.toString()}`;\n\n const data = (await this.fetch(url)) as Record<\n string,\n SmartTransactionsStatus\n >;\n\n Object.entries(data).forEach(([uuid, stxStatus]) => {\n const smartTransaction = {\n statusMetadata: stxStatus,\n status: calculateStatus(stxStatus),\n cancellable: isSmartTransactionCancellable(stxStatus),\n uuid,\n };\n this.#updateSmartTransaction(smartTransaction, { chainId, ethQuery });\n });\n\n return data;\n }\n\n async addNonceToTransaction(\n transaction: UnsignedTransaction,\n ): Promise<UnsignedTransaction> {\n const nonceLock = await this.getNonceLock(transaction.from);\n const nonce = nonceLock.nextNonce;\n nonceLock.releaseLock();\n return {\n ...transaction,\n nonce: `0x${nonce.toString(16)}`,\n };\n }\n\n clearFees(): Fees {\n const fees = {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n };\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n fees,\n },\n });\n return fees;\n }\n\n async getFees(\n tradeTx: UnsignedTransaction,\n approvalTx?: UnsignedTransaction,\n { networkClientId }: { networkClientId?: NetworkClientId } = {},\n ): Promise<Fees> {\n const chainId = this.#getChainId({ networkClientId });\n const transactions = [];\n let unsignedTradeTransactionWithNonce;\n if (approvalTx) {\n const unsignedApprovalTransactionWithNonce =\n await this.addNonceToTransaction(approvalTx);\n transactions.push(unsignedApprovalTransactionWithNonce);\n unsignedTradeTransactionWithNonce = {\n ...tradeTx,\n // If there is an approval tx, the trade tx's nonce is increased by 1.\n nonce: incrementNonceInHex(unsignedApprovalTransactionWithNonce.nonce),\n };\n } else if (tradeTx.nonce) {\n unsignedTradeTransactionWithNonce = tradeTx;\n } else {\n unsignedTradeTransactionWithNonce = await this.addNonceToTransaction(\n tradeTx,\n );\n }\n transactions.push(unsignedTradeTransactionWithNonce);\n const data = await this.fetch(getAPIRequestURL(APIType.GET_FEES, chainId), {\n method: 'POST',\n body: JSON.stringify({\n txs: transactions,\n }),\n });\n let approvalTxFees;\n let tradeTxFees;\n if (approvalTx) {\n approvalTxFees = data?.txs[0];\n tradeTxFees = data?.txs[1];\n } else {\n tradeTxFees = data?.txs[0];\n }\n\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n ...(chainId === this.config.chainId && {\n fees: {\n approvalTxFees,\n tradeTxFees,\n },\n }),\n feesByChainId: {\n ...this.state.smartTransactionsState.feesByChainId,\n [chainId]: {\n approvalTxFees,\n tradeTxFees,\n },\n },\n },\n });\n\n return {\n approvalTxFees,\n tradeTxFees,\n };\n }\n\n // * After this successful call client must add a nonce representative to\n // * transaction controller external transactions list\n async submitSignedTransactions({\n transactionMeta,\n txParams,\n signedTransactions,\n signedCanceledTransactions,\n networkClientId,\n }: {\n signedTransactions: SignedTransaction[];\n signedCanceledTransactions: SignedCanceledTransaction[];\n transactionMeta?: any;\n txParams?: any;\n networkClientId?: NetworkClientId;\n }) {\n const chainId = this.#getChainId({ networkClientId });\n const ethQuery = this.#getEthQuery({ networkClientId });\n const data = await this.fetch(\n getAPIRequestURL(APIType.SUBMIT_TRANSACTIONS, chainId),\n {\n method: 'POST',\n body: JSON.stringify({\n rawTxs: signedTransactions,\n rawCancelTxs: signedCanceledTransactions,\n }),\n },\n );\n const time = Date.now();\n let preTxBalance;\n try {\n const preTxBalanceBN = await query(ethQuery, 'getBalance', [\n txParams?.from,\n ]);\n preTxBalance = new BigNumber(preTxBalanceBN).toString(16);\n } catch (error) {\n console.error('provider error', error);\n }\n\n const requiresNonce = !txParams.nonce;\n let nonce;\n let nonceLock;\n let nonceDetails = {};\n\n if (requiresNonce) {\n nonceLock = await this.getNonceLock(txParams?.from);\n nonce = hexlify(nonceLock.nextNonce);\n nonceDetails = nonceLock.nonceDetails;\n if (txParams) {\n txParams.nonce ??= nonce;\n }\n }\n const submitTransactionResponse = {\n ...data,\n txHash: getTxHash(signedTransactions[0]),\n };\n\n try {\n this.#updateSmartTransaction(\n {\n chainId,\n nonceDetails,\n preTxBalance,\n status: SmartTransactionStatuses.PENDING,\n time,\n txParams,\n uuid: submitTransactionResponse.uuid,\n txHash: submitTransactionResponse.txHash,\n cancellable: true,\n type: transactionMeta?.type || 'swap',\n },\n { chainId, ethQuery },\n );\n } finally {\n nonceLock?.releaseLock();\n }\n\n return submitTransactionResponse;\n }\n\n #getChainId({\n networkClientId,\n }: { networkClientId?: NetworkClientId } = {}): Hex {\n return networkClientId\n ? this.getNetworkClientById(networkClientId).configuration.chainId\n : this.config.chainId;\n }\n\n #getEthQuery({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): EthQuery {\n if (networkClientId) {\n return new EthQuery(this.getNetworkClientById(networkClientId).provider);\n }\n\n if (this.ethQuery === undefined) {\n throw new Error(ETH_QUERY_ERROR_MSG);\n }\n\n return this.ethQuery;\n }\n\n // TODO: This should return if the cancellation was on chain or not (for nonce management)\n // After this successful call client must update nonce representative\n // in transaction controller external transactions list\n async cancelSmartTransaction(\n uuid: string,\n {\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {},\n ): Promise<void> {\n const chainId = this.#getChainId({ networkClientId });\n await this.fetch(getAPIRequestURL(APIType.CANCEL, chainId), {\n method: 'POST',\n body: JSON.stringify({ uuid }),\n });\n }\n\n async fetchLiveness({\n networkClientId,\n }: {\n networkClientId?: NetworkClientId;\n } = {}): Promise<boolean> {\n const chainId = this.#getChainId({ networkClientId });\n let liveness = false;\n try {\n const response = await this.fetch(\n getAPIRequestURL(APIType.LIVENESS, chainId),\n );\n liveness = Boolean(response.lastBlock);\n } catch (error) {\n console.log('\"fetchLiveness\" API call failed');\n }\n\n this.update({\n smartTransactionsState: {\n ...this.state.smartTransactionsState,\n ...(chainId === this.config.chainId && { liveness }),\n livenessByChainId: {\n ...this.state.smartTransactionsState.livenessByChainId,\n [chainId]: liveness,\n },\n },\n });\n\n return liveness;\n }\n\n async setStatusRefreshInterval(interval: number): Promise<void> {\n if (interval !== this.config.interval) {\n this.configure({ interval }, false, false);\n }\n }\n\n getTransactions({\n addressFrom,\n status,\n }: {\n addressFrom: string;\n status: SmartTransactionStatuses;\n }): SmartTransaction[] {\n const { smartTransactions } = this.state.smartTransactionsState;\n const { chainId } = this.config;\n const currentSmartTransactions = smartTransactions?.[chainId];\n if (!currentSmartTransactions || currentSmartTransactions.length === 0) {\n return [];\n }\n\n return currentSmartTransactions.filter((stx) => {\n return stx.status === status && stx.txParams?.from === addressFrom;\n });\n }\n}\n"]}
|
package/dist/constants.d.ts
CHANGED
|
@@ -5,3 +5,11 @@ export declare const CHAIN_IDS: {
|
|
|
5
5
|
readonly RINKEBY: "0x4";
|
|
6
6
|
readonly BSC: "0x38";
|
|
7
7
|
};
|
|
8
|
+
export declare enum MetaMetricsEventName {
|
|
9
|
+
StxStatusUpdated = "STX Status Updated",
|
|
10
|
+
StxConfirmed = "STX Confirmed",
|
|
11
|
+
StxConfirmationFailed = "STX Confirmation Failed"
|
|
12
|
+
}
|
|
13
|
+
export declare enum MetaMetricsEventCategory {
|
|
14
|
+
Transactions = "Transactions"
|
|
15
|
+
}
|
package/dist/constants.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.CHAIN_IDS = exports.API_BASE_URL = void 0;
|
|
3
|
+
exports.MetaMetricsEventCategory = exports.MetaMetricsEventName = exports.CHAIN_IDS = exports.API_BASE_URL = void 0;
|
|
4
4
|
exports.API_BASE_URL = 'https://transaction.metaswap.codefi.network';
|
|
5
5
|
exports.CHAIN_IDS = {
|
|
6
6
|
ETHEREUM: '0x1',
|
|
@@ -8,4 +8,14 @@ exports.CHAIN_IDS = {
|
|
|
8
8
|
RINKEBY: '0x4',
|
|
9
9
|
BSC: '0x38',
|
|
10
10
|
};
|
|
11
|
+
var MetaMetricsEventName;
|
|
12
|
+
(function (MetaMetricsEventName) {
|
|
13
|
+
MetaMetricsEventName["StxStatusUpdated"] = "STX Status Updated";
|
|
14
|
+
MetaMetricsEventName["StxConfirmed"] = "STX Confirmed";
|
|
15
|
+
MetaMetricsEventName["StxConfirmationFailed"] = "STX Confirmation Failed";
|
|
16
|
+
})(MetaMetricsEventName = exports.MetaMetricsEventName || (exports.MetaMetricsEventName = {}));
|
|
17
|
+
var MetaMetricsEventCategory;
|
|
18
|
+
(function (MetaMetricsEventCategory) {
|
|
19
|
+
MetaMetricsEventCategory["Transactions"] = "Transactions";
|
|
20
|
+
})(MetaMetricsEventCategory = exports.MetaMetricsEventCategory || (exports.MetaMetricsEventCategory = {}));
|
|
11
21
|
//# sourceMappingURL=constants.js.map
|
package/dist/constants.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,YAAY,GAAG,6CAA6C,CAAC;AAC7D,QAAA,SAAS,GAAG;IACvB,QAAQ,EAAE,KAAK;IACf,MAAM,EAAE,KAAK;IACb,OAAO,EAAE,KAAK;IACd,GAAG,EAAE,MAAM;CACH,CAAC","sourcesContent":["export const API_BASE_URL = 'https://transaction.metaswap.codefi.network';\nexport const CHAIN_IDS = {\n ETHEREUM: '0x1',\n GOERLI: '0x5',\n RINKEBY: '0x4',\n BSC: '0x38',\n} as const;\n"]}
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,YAAY,GAAG,6CAA6C,CAAC;AAC7D,QAAA,SAAS,GAAG;IACvB,QAAQ,EAAE,KAAK;IACf,MAAM,EAAE,KAAK;IACb,OAAO,EAAE,KAAK;IACd,GAAG,EAAE,MAAM;CACH,CAAC;AAEX,IAAY,oBAIX;AAJD,WAAY,oBAAoB;IAC9B,+DAAuC,CAAA;IACvC,sDAA8B,CAAA;IAC9B,yEAAiD,CAAA;AACnD,CAAC,EAJW,oBAAoB,GAApB,4BAAoB,KAApB,4BAAoB,QAI/B;AAED,IAAY,wBAEX;AAFD,WAAY,wBAAwB;IAClC,yDAA6B,CAAA;AAC/B,CAAC,EAFW,wBAAwB,GAAxB,gCAAwB,KAAxB,gCAAwB,QAEnC","sourcesContent":["export const API_BASE_URL = 'https://transaction.metaswap.codefi.network';\nexport const CHAIN_IDS = {\n ETHEREUM: '0x1',\n GOERLI: '0x5',\n RINKEBY: '0x4',\n BSC: '0x38',\n} as const;\n\nexport enum MetaMetricsEventName {\n StxStatusUpdated = 'STX Status Updated',\n StxConfirmed = 'STX Confirmed',\n StxConfirmationFailed = 'STX Confirmation Failed',\n}\n\nexport enum MetaMetricsEventCategory {\n Transactions = 'Transactions',\n}\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
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>;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.advanceTime = exports.flushPromises = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Resolve all pending promises.
|
|
6
|
+
* This method is used for async tests that use fake timers.
|
|
7
|
+
* See https://stackoverflow.com/a/58716087 and https://jestjs.io/docs/timer-mocks.
|
|
8
|
+
*/
|
|
9
|
+
const flushPromises = async () => {
|
|
10
|
+
return new Promise(jest.requireActual('timers').setImmediate);
|
|
11
|
+
};
|
|
12
|
+
exports.flushPromises = flushPromises;
|
|
13
|
+
/**
|
|
14
|
+
* Advances the provided fake timer by a specified duration in incremental steps.
|
|
15
|
+
* Between each step, any enqueued promises are processed. Fake timers in testing libraries
|
|
16
|
+
* allow simulation of time without actually waiting. However, they don't always account for
|
|
17
|
+
* promises or other asynchronous operations that may get enqueued during the timer's duration.
|
|
18
|
+
* By advancing time in incremental steps and flushing promises between each step,
|
|
19
|
+
* this function ensures that both timers and promises are comprehensively processed.
|
|
20
|
+
* @param options - The options object.
|
|
21
|
+
* @param options.clock - The Sinon fake timer instance used to manipulate time in tests.
|
|
22
|
+
* @param options.duration - The total amount of time (in milliseconds) to advance the timer by.
|
|
23
|
+
* @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.
|
|
24
|
+
*/
|
|
25
|
+
async function advanceTime({ clock, duration, stepSize = Math.floor(duration / 4), }) {
|
|
26
|
+
do {
|
|
27
|
+
await clock.tickAsync(stepSize);
|
|
28
|
+
await (0, exports.flushPromises)();
|
|
29
|
+
// eslint-disable-next-line no-param-reassign
|
|
30
|
+
duration -= stepSize;
|
|
31
|
+
} while (duration > 0);
|
|
32
|
+
}
|
|
33
|
+
exports.advanceTime = advanceTime;
|
|
34
|
+
//# sourceMappingURL=test-helpers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"test-helpers.js","sourceRoot":"","sources":["../src/test-helpers.ts"],"names":[],"mappings":";;;AAAA;;;;GAIG;AACI,MAAM,aAAa,GAAG,KAAK,IAAI,EAAE;IACtC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,YAAY,CAAC,CAAC;AAChE,CAAC,CAAC;AAFW,QAAA,aAAa,iBAExB;AAEF;;;;;;;;;;;GAWG;AACI,KAAK,UAAU,WAAW,CAAC,EAChC,KAAK,EACL,QAAQ,EACR,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,GAAG,CAAC,CAAC,GAKpC;IACC,GAAG;QACD,MAAM,KAAK,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;QAChC,MAAM,IAAA,qBAAa,GAAE,CAAC;QACtB,6CAA6C;QAC7C,QAAQ,IAAI,QAAQ,CAAC;KACtB,QAAQ,QAAQ,GAAG,CAAC,EAAE;AACzB,CAAC;AAfD,kCAeC","sourcesContent":["/**\n * Resolve all pending promises.\n * This method is used for async tests that use fake timers.\n * See https://stackoverflow.com/a/58716087 and https://jestjs.io/docs/timer-mocks.\n */\nexport const flushPromises = async () => {\n return new Promise(jest.requireActual('timers').setImmediate);\n};\n\n/**\n * Advances the provided fake timer by a specified duration in incremental steps.\n * Between each step, any enqueued promises are processed. Fake timers in testing libraries\n * allow simulation of time without actually waiting. However, they don't always account for\n * promises or other asynchronous operations that may get enqueued during the timer's duration.\n * By advancing time in incremental steps and flushing promises between each step,\n * this function ensures that both timers and promises are comprehensively processed.\n * @param options - The options object.\n * @param options.clock - The Sinon fake timer instance used to manipulate time in tests.\n * @param options.duration - The total amount of time (in milliseconds) to advance the timer by.\n * @param options.stepSize - The incremental step size (in milliseconds) by which the timer is advanced in each iteration. Default is 1/4 of the duration.\n */\nexport async function advanceTime({\n clock,\n duration,\n stepSize = Math.floor(duration / 4),\n}: {\n clock: sinon.SinonFakeTimers;\n duration: number;\n stepSize?: number;\n}): Promise<void> {\n do {\n await clock.tickAsync(stepSize);\n await flushPromises();\n // eslint-disable-next-line no-param-reassign\n duration -= stepSize;\n } while (duration > 0);\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -57,6 +57,7 @@ export declare type SmartTransactionsStatus = {
|
|
|
57
57
|
};
|
|
58
58
|
export declare type SmartTransaction = {
|
|
59
59
|
uuid: string;
|
|
60
|
+
txHash?: string;
|
|
60
61
|
chainId?: string;
|
|
61
62
|
destinationTokenAddress?: string;
|
|
62
63
|
destinationTokenDecimals?: string;
|
|
@@ -71,6 +72,7 @@ export declare type SmartTransaction = {
|
|
|
71
72
|
swapMetaData?: any;
|
|
72
73
|
swapTokenValue?: string;
|
|
73
74
|
time?: number;
|
|
75
|
+
creationTime?: number;
|
|
74
76
|
txParams?: any;
|
|
75
77
|
type?: string;
|
|
76
78
|
confirmed?: boolean;
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{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,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":["/** API */\n\nexport enum APIType {\n 'GET_FEES',\n 'ESTIMATE_GAS',\n 'SUBMIT_TRANSACTIONS',\n 'CANCEL',\n 'BATCH_STATUS',\n 'LIVENESS',\n}\n\n/** SmartTransactions */\n\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 | undefined;\n minedTx: SmartTransactionMinedTx;\n isSettled: boolean;\n};\n\nexport type SmartTransaction = {\n uuid: 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;\n txParams?: any;\n type?: string;\n confirmed?: boolean;\n cancellable?: boolean;\n};\n\nexport type Fee = {\n maxFeePerGas: number;\n maxPriorityFeePerGas: number;\n};\n\nexport type IndividualTxFees = {\n fees: Fee[];\n cancelFees: Fee[];\n feeEstimate: number;\n gasLimit: number;\n gasUsed: number;\n};\n\nexport type Fees = {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n};\n\n// TODO\nexport type UnsignedTransaction = any;\n\n// TODO\nexport type SignedTransaction = any;\n\n// TODO\nexport type SignedCanceledTransaction = any;\n\nexport type Hex = `0x${string}`;\n"]}
|
|
1
|
+
{"version":3,"file":"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AAC,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":["/** API */\n\nexport enum APIType {\n 'GET_FEES',\n 'ESTIMATE_GAS',\n 'SUBMIT_TRANSACTIONS',\n 'CANCEL',\n 'BATCH_STATUS',\n 'LIVENESS',\n}\n\n/** SmartTransactions */\n\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 | undefined;\n minedTx: SmartTransactionMinedTx;\n isSettled: boolean;\n};\n\nexport type SmartTransaction = {\n uuid: string;\n txHash?: string;\n chainId?: string;\n destinationTokenAddress?: string;\n destinationTokenDecimals?: string;\n destinationTokenSymbol?: string;\n history?: any;\n nonceDetails?: any;\n origin?: string;\n preTxBalance?: string;\n status?: string;\n statusMetadata?: SmartTransactionsStatus;\n sourceTokenSymbol?: string;\n swapMetaData?: any;\n swapTokenValue?: string;\n time?: number; // @deprecated We should use creationTime instead.\n creationTime?: number;\n txParams?: any;\n type?: string;\n confirmed?: boolean;\n cancellable?: boolean;\n};\n\nexport type Fee = {\n maxFeePerGas: number;\n maxPriorityFeePerGas: number;\n};\n\nexport type IndividualTxFees = {\n fees: Fee[];\n cancelFees: Fee[];\n feeEstimate: number;\n gasLimit: number;\n gasUsed: number;\n};\n\nexport type Fees = {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n};\n\n// TODO\nexport type UnsignedTransaction = any;\n\n// TODO\nexport type SignedTransaction = any;\n\n// TODO\nexport type SignedCanceledTransaction = any;\n\nexport type Hex = `0x${string}`;\n"]}
|
package/dist/utils.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { SmartTransaction, SmartTransactionsStatus } from './types';
|
|
2
|
+
import { APIType, SmartTransactionStatuses } from './types';
|
|
2
3
|
export declare function isSmartTransactionPending(smartTransaction: SmartTransaction): boolean;
|
|
3
4
|
export declare const isSmartTransactionStatusResolved: (stxStatus: SmartTransactionsStatus | string) => boolean;
|
|
4
5
|
export declare function getAPIRequestURL(apiType: APIType, chainId: string): string;
|
|
@@ -37,3 +38,4 @@ export declare const mapKeysToCamel: (obj: Record<string, any>) => Record<string
|
|
|
37
38
|
export declare function handleFetch(request: string, options?: RequestInit): Promise<any>;
|
|
38
39
|
export declare const isSmartTransactionCancellable: (stxStatus: SmartTransactionsStatus) => boolean;
|
|
39
40
|
export declare const incrementNonceInHex: (nonceInHex: string) => string;
|
|
41
|
+
export declare const getTxHash: (signedTxHex: any) => string;
|
package/dist/utils.js
CHANGED
|
@@ -3,16 +3,19 @@ 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.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.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
|
+
const tx_1 = require("@ethereumjs/tx");
|
|
8
|
+
const util_1 = require("@ethereumjs/util");
|
|
9
|
+
const bytes_1 = require("@ethersproject/bytes");
|
|
10
|
+
const bignumber_js_1 = require("bignumber.js");
|
|
7
11
|
const fast_json_patch_1 = __importDefault(require("fast-json-patch"));
|
|
8
12
|
const lodash_1 = __importDefault(require("lodash"));
|
|
9
|
-
|
|
10
|
-
const
|
|
13
|
+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
14
|
+
const constants_1 = require("./constants");
|
|
15
|
+
const types_1 = require("./types");
|
|
11
16
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
12
17
|
// @ts-ignore
|
|
13
18
|
const package_json_1 = __importDefault(require("../package.json"));
|
|
14
|
-
const types_1 = require("./types");
|
|
15
|
-
const constants_1 = require("./constants");
|
|
16
19
|
function isSmartTransactionPending(smartTransaction) {
|
|
17
20
|
return smartTransaction.status === types_1.SmartTransactionStatuses.PENDING;
|
|
18
21
|
}
|
|
@@ -182,4 +185,14 @@ const incrementNonceInHex = (nonceInHex) => {
|
|
|
182
185
|
return (0, bytes_1.hexlify)(Number(nonceInDec) + 1);
|
|
183
186
|
};
|
|
184
187
|
exports.incrementNonceInHex = incrementNonceInHex;
|
|
188
|
+
const getTxHash = (signedTxHex) => {
|
|
189
|
+
if (!signedTxHex) {
|
|
190
|
+
return '';
|
|
191
|
+
}
|
|
192
|
+
const txHashBytes = tx_1.TransactionFactory.fromSerializedData(
|
|
193
|
+
// eslint-disable-next-line no-restricted-globals
|
|
194
|
+
Buffer.from(signedTxHex.slice(2), 'hex')).hash();
|
|
195
|
+
return (0, util_1.bytesToHex)(txHashBytes);
|
|
196
|
+
};
|
|
197
|
+
exports.getTxHash = getTxHash;
|
|
185
198
|
//# 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,sEAAyC;AACzC,oD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AAC,EAAE,EAAE;QAChB,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;QAClC,MAAM,IAAI,KAAK,CACb,eAAe,IAAI,CAAC,SAAS,iBAC3B,MAAM,EAAE,QAAQ,CAAC,MAAM,IACpB,IAAA,sBAAc,EAAC,IAAI,CAAC,EACvB,EAAE,CACL,CAAC;KACH;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAbD,kCAaC;AAEM,MAAM,6BAA6B,GAAG,CAC3C,SAAkC,EACzB,EAAE;IACX,OAAO,CACL,SAAS,CAAC,OAAO,KAAK,+BAAuB,CAAC,SAAS;QACvD,CAAC,CAAC,SAAS,CAAC,kBAAkB;YAC5B,SAAS,CAAC,kBAAkB;gBAC1B,0CAAkC,CAAC,aAAa,CAAC,CACtD,CAAC;AACJ,CAAC,CAAC;AATW,QAAA,6BAA6B,iCASxC;AAEK,MAAM,mBAAmB,GAAG,CAAC,UAAkB,EAAU,EAAE;IAChE,MAAM,UAAU,GAAG,IAAI,wBAAS,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC9D,OAAO,IAAA,eAAO,EAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;AACzC,CAAC,CAAC;AAHW,QAAA,mBAAmB,uBAG9B","sourcesContent":["import jsonDiffer from 'fast-json-patch';\nimport _ from 'lodash';\nimport { BigNumber } from 'bignumber.js';\nimport { hexlify } from '@ethersproject/bytes';\n\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport packageJson from '../package.json';\n\nimport {\n APIType,\n SmartTransaction,\n SmartTransactionsStatus,\n SmartTransactionStatuses,\n SmartTransactionCancellationReason,\n SmartTransactionMinedTx,\n cancellationReasonToStatusMap,\n} from './types';\nimport { API_BASE_URL } from './constants';\n\nexport function isSmartTransactionPending(smartTransaction: SmartTransaction) {\n return smartTransaction.status === SmartTransactionStatuses.PENDING;\n}\n\nexport const isSmartTransactionStatusResolved = (\n stxStatus: SmartTransactionsStatus | string,\n) => stxStatus === 'uuid_not_found';\n\n// TODO use actual url once API is defined\nexport function getAPIRequestURL(apiType: APIType, chainId: string): string {\n const chainIdDec = parseInt(chainId, 16);\n switch (apiType) {\n case APIType.GET_FEES: {\n return `${API_BASE_URL}/networks/${chainIdDec}/getFees`;\n }\n\n case APIType.ESTIMATE_GAS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/estimateGas`;\n }\n\n case APIType.SUBMIT_TRANSACTIONS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`;\n }\n\n case APIType.CANCEL: {\n return `${API_BASE_URL}/networks/${chainIdDec}/cancel`;\n }\n\n case APIType.BATCH_STATUS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/batchStatus`;\n }\n\n case APIType.LIVENESS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/health`;\n }\n\n default: {\n throw new Error(`Invalid APIType`); // It can never get here thanks to TypeScript.\n }\n }\n}\n\nexport const calculateStatus = (stxStatus: SmartTransactionsStatus) => {\n if (isSmartTransactionStatusResolved(stxStatus)) {\n return SmartTransactionStatuses.RESOLVED;\n }\n const cancellations = [\n SmartTransactionCancellationReason.WOULD_REVERT,\n SmartTransactionCancellationReason.TOO_CHEAP,\n SmartTransactionCancellationReason.DEADLINE_MISSED,\n SmartTransactionCancellationReason.INVALID_NONCE,\n SmartTransactionCancellationReason.USER_CANCELLED,\n SmartTransactionCancellationReason.PREVIOUS_TX_CANCELLED,\n ];\n if (stxStatus?.minedTx === SmartTransactionMinedTx.NOT_MINED) {\n if (\n stxStatus.cancellationReason ===\n SmartTransactionCancellationReason.NOT_CANCELLED\n ) {\n return SmartTransactionStatuses.PENDING;\n }\n\n const isCancellation =\n cancellations.findIndex(\n (cancellation) => cancellation === stxStatus.cancellationReason,\n ) > -1;\n if (stxStatus.cancellationReason && isCancellation) {\n if (!stxStatus.isSettled) {\n return SmartTransactionStatuses.PENDING;\n }\n return cancellationReasonToStatusMap[stxStatus.cancellationReason];\n }\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.SUCCESS) {\n return SmartTransactionStatuses.SUCCESS;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.CANCELLED) {\n return SmartTransactionStatuses.CANCELLED;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.REVERTED) {\n return SmartTransactionStatuses.REVERTED;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.UNKNOWN) {\n return SmartTransactionStatuses.UNKNOWN;\n }\n return SmartTransactionStatuses.UNKNOWN;\n};\n\n/**\n Generates an array of history objects sense the previous state.\n The object has the keys\n op (the operation performed),\n path (the key and if a nested object then each key will be separated with a `/`)\n value\n with the first entry having the note and a timestamp when the change took place\n @param previousState - the previous state of the object\n @param newState - the update object\n @param [note] - a optional note for the state change\n @returns\n*/\nexport function generateHistoryEntry(\n previousState: any,\n newState: any,\n note: string,\n) {\n const entry: any = jsonDiffer.compare(previousState, newState);\n // Add a note to the first op, since it breaks if we append it to the entry\n if (entry[0]) {\n if (note) {\n entry[0].note = note;\n }\n\n entry[0].timestamp = Date.now();\n }\n return entry;\n}\n\n/**\n Recovers previous txMeta state obj\n @returns\n*/\nexport function replayHistory(_shortHistory: any) {\n const shortHistory = _.cloneDeep(_shortHistory);\n return shortHistory.reduce(\n (val: any, entry: any) => jsonDiffer.applyPatch(val, entry).newDocument,\n );\n}\n\n/**\n * Snapshot {@code txMeta}\n * @param txMeta - the tx metadata object\n * @returns a deep clone without history\n */\nexport function snapshotFromTxMeta(txMeta: any) {\n const shallow = { ...txMeta };\n delete shallow.history;\n return _.cloneDeep(shallow);\n}\n\n/**\n * Returns processing time for an STX in seconds.\n * @param smartTransactionSubmittedtime\n * @returns Processing time in seconds.\n */\nexport const getStxProcessingTime = (\n smartTransactionSubmittedtime: number | undefined,\n): number | undefined => {\n if (!smartTransactionSubmittedtime) {\n return undefined;\n }\n return Math.round((Date.now() - smartTransactionSubmittedtime) / 1000);\n};\n\nexport const mapKeysToCamel = (\n obj: Record<string, any>,\n): Record<string, any> => {\n if (!_.isObject(obj)) {\n return obj;\n }\n const mappedValues = _.mapValues(obj, (val: Record<string, any>) => {\n if (_.isArray(val)) {\n return val.map(mapKeysToCamel);\n } else if (_.isObject(val)) {\n return mapKeysToCamel(val);\n }\n return val;\n });\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n return _.mapKeys(mappedValues, (value, key) => _.camelCase(key));\n};\n\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options);\n const json = await response.json();\n if (!response.ok) {\n console.log(`response`, response);\n throw new Error(\n `Fetch error:${JSON.stringify({\n status: response.status,\n ...mapKeysToCamel(json),\n })}`,\n );\n }\n return json;\n}\n\nexport const isSmartTransactionCancellable = (\n stxStatus: SmartTransactionsStatus,\n): boolean => {\n return (\n stxStatus.minedTx === SmartTransactionMinedTx.NOT_MINED &&\n (!stxStatus.cancellationReason ||\n stxStatus.cancellationReason ===\n SmartTransactionCancellationReason.NOT_CANCELLED)\n );\n};\n\nexport const incrementNonceInHex = (nonceInHex: string): string => {\n const nonceInDec = new BigNumber(nonceInHex, 16).toString(10);\n return hexlify(Number(nonceInDec) + 1);\n};\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAAA,uCAAoD;AACpD,2CAA8C;AAC9C,gDAA+C;AAC/C,+CAAyC;AACzC,sEAAyC;AACzC,oDAAuB;AAEvB,6DAA6D;AAC7D,2CAA2C;AAE3C,mCAMiB;AACjB,6DAA6D;AAC7D,aAAa;AACb,mEAA0C;AAE1C,SAAgB,yBAAyB,CAAC,gBAAkC;IAC1E,OAAO,gBAAgB,CAAC,MAAM,KAAK,gCAAwB,CAAC,OAAO,CAAC;AACtE,CAAC;AAFD,8DAEC;AAEM,MAAM,gCAAgC,GAAG,CAC9C,SAA2C,EAC3C,EAAE,C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AM,6BAA6B,GAAG,CAC3C,SAAkC,EACzB,EAAE;IACX,OAAO,CACL,SAAS,CAAC,OAAO,KAAK,+BAAuB,CAAC,SAAS;QACvD,CAAC,CAAC,SAAS,CAAC,kBAAkB;YAC5B,SAAS,CAAC,kBAAkB;gBAC1B,0CAAkC,CAAC,aAAa,CAAC,CACtD,CAAC;AACJ,CAAC,CAAC;AATW,QAAA,6BAA6B,iCASxC;AAEK,MAAM,mBAAmB,GAAG,CAAC,UAAkB,EAAU,EAAE;IAChE,MAAM,UAAU,GAAG,IAAI,wBAAS,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC9D,OAAO,IAAA,eAAO,EAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC;AACzC,CAAC,CAAC;AAHW,QAAA,mBAAmB,uBAG9B;AAEK,MAAM,SAAS,GAAG,CAAC,WAAgB,EAAE,EAAE;IAC5C,IAAI,CAAC,WAAW,EAAE;QAChB,OAAO,EAAE,CAAC;KACX;IACD,MAAM,WAAW,GAAG,uBAAkB,CAAC,kBAAkB;IACvD,iDAAiD;IACjD,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CACzC,CAAC,IAAI,EAAE,CAAC;IACT,OAAO,IAAA,iBAAU,EAAC,WAAW,CAAC,CAAC;AACjC,CAAC,CAAC;AATW,QAAA,SAAS,aASpB","sourcesContent":["import { TransactionFactory } from '@ethereumjs/tx';\nimport { bytesToHex } from '@ethereumjs/util';\nimport { hexlify } from '@ethersproject/bytes';\nimport { BigNumber } from 'bignumber.js';\nimport jsonDiffer from 'fast-json-patch';\nimport _ from 'lodash';\n\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\nimport { API_BASE_URL } from './constants';\nimport type { SmartTransaction, SmartTransactionsStatus } from './types';\nimport {\n APIType,\n SmartTransactionStatuses,\n SmartTransactionCancellationReason,\n SmartTransactionMinedTx,\n cancellationReasonToStatusMap,\n} from './types';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport packageJson from '../package.json';\n\nexport function isSmartTransactionPending(smartTransaction: SmartTransaction) {\n return smartTransaction.status === SmartTransactionStatuses.PENDING;\n}\n\nexport const isSmartTransactionStatusResolved = (\n stxStatus: SmartTransactionsStatus | string,\n) => stxStatus === 'uuid_not_found';\n\n// TODO use actual url once API is defined\nexport function getAPIRequestURL(apiType: APIType, chainId: string): string {\n const chainIdDec = parseInt(chainId, 16);\n switch (apiType) {\n case APIType.GET_FEES: {\n return `${API_BASE_URL}/networks/${chainIdDec}/getFees`;\n }\n\n case APIType.ESTIMATE_GAS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/estimateGas`;\n }\n\n case APIType.SUBMIT_TRANSACTIONS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`;\n }\n\n case APIType.CANCEL: {\n return `${API_BASE_URL}/networks/${chainIdDec}/cancel`;\n }\n\n case APIType.BATCH_STATUS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/batchStatus`;\n }\n\n case APIType.LIVENESS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/health`;\n }\n\n default: {\n throw new Error(`Invalid APIType`); // It can never get here thanks to TypeScript.\n }\n }\n}\n\nexport const calculateStatus = (stxStatus: SmartTransactionsStatus) => {\n if (isSmartTransactionStatusResolved(stxStatus)) {\n return SmartTransactionStatuses.RESOLVED;\n }\n const cancellations = [\n SmartTransactionCancellationReason.WOULD_REVERT,\n SmartTransactionCancellationReason.TOO_CHEAP,\n SmartTransactionCancellationReason.DEADLINE_MISSED,\n SmartTransactionCancellationReason.INVALID_NONCE,\n SmartTransactionCancellationReason.USER_CANCELLED,\n SmartTransactionCancellationReason.PREVIOUS_TX_CANCELLED,\n ];\n if (stxStatus?.minedTx === SmartTransactionMinedTx.NOT_MINED) {\n if (\n stxStatus.cancellationReason ===\n SmartTransactionCancellationReason.NOT_CANCELLED\n ) {\n return SmartTransactionStatuses.PENDING;\n }\n\n const isCancellation =\n cancellations.findIndex(\n (cancellation) => cancellation === stxStatus.cancellationReason,\n ) > -1;\n if (stxStatus.cancellationReason && isCancellation) {\n if (!stxStatus.isSettled) {\n return SmartTransactionStatuses.PENDING;\n }\n return cancellationReasonToStatusMap[stxStatus.cancellationReason];\n }\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.SUCCESS) {\n return SmartTransactionStatuses.SUCCESS;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.CANCELLED) {\n return SmartTransactionStatuses.CANCELLED;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.REVERTED) {\n return SmartTransactionStatuses.REVERTED;\n } else if (stxStatus?.minedTx === SmartTransactionMinedTx.UNKNOWN) {\n return SmartTransactionStatuses.UNKNOWN;\n }\n return SmartTransactionStatuses.UNKNOWN;\n};\n\n/**\n Generates an array of history objects sense the previous state.\n The object has the keys\n op (the operation performed),\n path (the key and if a nested object then each key will be separated with a `/`)\n value\n with the first entry having the note and a timestamp when the change took place\n @param previousState - the previous state of the object\n @param newState - the update object\n @param [note] - a optional note for the state change\n @returns\n*/\nexport function generateHistoryEntry(\n previousState: any,\n newState: any,\n note: string,\n) {\n const entry: any = jsonDiffer.compare(previousState, newState);\n // Add a note to the first op, since it breaks if we append it to the entry\n if (entry[0]) {\n if (note) {\n entry[0].note = note;\n }\n\n entry[0].timestamp = Date.now();\n }\n return entry;\n}\n\n/**\n Recovers previous txMeta state obj\n @returns\n*/\nexport function replayHistory(_shortHistory: any) {\n const shortHistory = _.cloneDeep(_shortHistory);\n return shortHistory.reduce(\n (val: any, entry: any) => jsonDiffer.applyPatch(val, entry).newDocument,\n );\n}\n\n/**\n * Snapshot {@code txMeta}\n * @param txMeta - the tx metadata object\n * @returns a deep clone without history\n */\nexport function snapshotFromTxMeta(txMeta: any) {\n const shallow = { ...txMeta };\n delete shallow.history;\n return _.cloneDeep(shallow);\n}\n\n/**\n * Returns processing time for an STX in seconds.\n * @param smartTransactionSubmittedtime\n * @returns Processing time in seconds.\n */\nexport const getStxProcessingTime = (\n smartTransactionSubmittedtime: number | undefined,\n): number | undefined => {\n if (!smartTransactionSubmittedtime) {\n return undefined;\n }\n return Math.round((Date.now() - smartTransactionSubmittedtime) / 1000);\n};\n\nexport const mapKeysToCamel = (\n obj: Record<string, any>,\n): Record<string, any> => {\n if (!_.isObject(obj)) {\n return obj;\n }\n const mappedValues = _.mapValues(obj, (val: Record<string, any>) => {\n if (_.isArray(val)) {\n return val.map(mapKeysToCamel);\n } else if (_.isObject(val)) {\n return mapKeysToCamel(val);\n }\n return val;\n });\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n return _.mapKeys(mappedValues, (value, key) => _.camelCase(key));\n};\n\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options);\n const json = await response.json();\n if (!response.ok) {\n console.log(`response`, response);\n throw new Error(\n `Fetch error:${JSON.stringify({\n status: response.status,\n ...mapKeysToCamel(json),\n })}`,\n );\n }\n return json;\n}\n\nexport const isSmartTransactionCancellable = (\n stxStatus: SmartTransactionsStatus,\n): boolean => {\n return (\n stxStatus.minedTx === SmartTransactionMinedTx.NOT_MINED &&\n (!stxStatus.cancellationReason ||\n stxStatus.cancellationReason ===\n SmartTransactionCancellationReason.NOT_CANCELLED)\n );\n};\n\nexport const incrementNonceInHex = (nonceInHex: string): string => {\n const nonceInDec = new BigNumber(nonceInHex, 16).toString(10);\n return hexlify(Number(nonceInDec) + 1);\n};\n\nexport const getTxHash = (signedTxHex: any) => {\n if (!signedTxHex) {\n return '';\n }\n const txHashBytes = TransactionFactory.fromSerializedData(\n // eslint-disable-next-line no-restricted-globals\n Buffer.from(signedTxHex.slice(2), 'hex'),\n ).hash();\n return bytesToHex(txHashBytes);\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/smart-transactions-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "7.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",
|
|
@@ -25,46 +25,52 @@
|
|
|
25
25
|
"test:watch": "jest --watchAll"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
+
"@ethereumjs/tx": "^5.2.1",
|
|
29
|
+
"@ethereumjs/util": "^9.0.2",
|
|
28
30
|
"@ethersproject/bytes": "^5.7.0",
|
|
29
|
-
"@metamask/base-controller": "^
|
|
30
|
-
"@metamask/controller-utils": "^
|
|
31
|
-
"@metamask/eth-query": "^
|
|
32
|
-
"@metamask/network-controller": "^
|
|
33
|
-
"@metamask/polling-controller": "^0.
|
|
31
|
+
"@metamask/base-controller": "^4.0.0",
|
|
32
|
+
"@metamask/controller-utils": "^8.0.2",
|
|
33
|
+
"@metamask/eth-query": "^4.0.0",
|
|
34
|
+
"@metamask/network-controller": "^17.2.0",
|
|
35
|
+
"@metamask/polling-controller": "^5.0.0",
|
|
34
36
|
"bignumber.js": "^9.0.1",
|
|
37
|
+
"events": "^3.3.0",
|
|
35
38
|
"fast-json-patch": "^3.1.0",
|
|
36
39
|
"lodash": "^4.17.21"
|
|
37
40
|
},
|
|
38
41
|
"devDependencies": {
|
|
39
42
|
"@lavamoat/allow-scripts": "^2.3.1",
|
|
40
43
|
"@metamask/auto-changelog": "^3.1.0",
|
|
41
|
-
"@metamask/eslint-config": "^
|
|
42
|
-
"@metamask/eslint-config-jest": "^
|
|
43
|
-
"@metamask/eslint-config-nodejs": "^
|
|
44
|
-
"@metamask/eslint-config-typescript": "^
|
|
44
|
+
"@metamask/eslint-config": "^12.2.0",
|
|
45
|
+
"@metamask/eslint-config-jest": "^12.1.0",
|
|
46
|
+
"@metamask/eslint-config-nodejs": "^12.1.0",
|
|
47
|
+
"@metamask/eslint-config-typescript": "^12.1.0",
|
|
45
48
|
"@types/jest": "^26.0.24",
|
|
46
49
|
"@types/lodash": "^4.14.194",
|
|
47
50
|
"@types/node": "^16.18.31",
|
|
51
|
+
"@types/sinon": "^9.0.10",
|
|
48
52
|
"@typescript-eslint/eslint-plugin": "^5.33.0",
|
|
49
53
|
"@typescript-eslint/parser": "^5.33.0",
|
|
50
|
-
"eslint": "^8.
|
|
54
|
+
"eslint": "^8.48.0",
|
|
51
55
|
"eslint-config-prettier": "^8.8.0",
|
|
52
56
|
"eslint-plugin-import": "^2.27.5",
|
|
53
|
-
"eslint-plugin-jest": "^
|
|
57
|
+
"eslint-plugin-jest": "^27.1.5",
|
|
54
58
|
"eslint-plugin-jsdoc": "^39.2.9",
|
|
55
|
-
"eslint-plugin-
|
|
59
|
+
"eslint-plugin-n": "^15.7.0",
|
|
56
60
|
"eslint-plugin-prettier": "^4.2.1",
|
|
61
|
+
"eslint-plugin-promise": "^6.1.1",
|
|
57
62
|
"isomorphic-fetch": "^3.0.0",
|
|
58
63
|
"jest": "^26.4.2",
|
|
59
64
|
"nock": "^13.3.1",
|
|
60
65
|
"prettier": "^2.8.8",
|
|
61
66
|
"prettier-plugin-packagejson": "^2.4.3",
|
|
67
|
+
"sinon": "^9.2.4",
|
|
62
68
|
"ts-jest": "^26.5.6",
|
|
63
|
-
"typescript": "~4.
|
|
69
|
+
"typescript": "~4.8.4"
|
|
64
70
|
},
|
|
65
71
|
"packageManager": "yarn@3.2.1",
|
|
66
72
|
"engines": {
|
|
67
|
-
"node": ">=
|
|
73
|
+
"node": "^18.18 || >=20"
|
|
68
74
|
},
|
|
69
75
|
"publishConfig": {
|
|
70
76
|
"access": "public",
|