@metamask/smart-transactions-controller 3.0.0 → 4.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 ADDED
@@ -0,0 +1,166 @@
1
+ # Changelog
2
+ All notable changes to this project will be documented in this file.
3
+
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [4.0.0]
10
+ ### Changed
11
+ - **BREAKING**: Bump minimum Node.js version to v16 ([#161](https://github.com/MetaMask/smart-transactions-controller/pull/161))
12
+ - **BREAKING:** Remove `isomorphic-fetch` ([#131](https://github.com/MetaMask/smart-transactions-controller/pull/131))
13
+ - Projects lacking `fetch` will now have to supply their own polyfill.
14
+ - Update `metamask/*` dependencies ([#131](https://github.com/MetaMask/smart-transactions-controller/pull/131)), ([#172](https://github.com/MetaMask/smart-transactions-controller/pull/172))
15
+ - Move `@types/lodash` to devDependencies ([#141](https://github.com/MetaMask/smart-transactions-controller/pull/141))
16
+
17
+ ## [3.1.0]
18
+ ### Changed
19
+ - Replace use of full `@metamask/controllers` repo with packages from `@metamask/core-monorepo` ([#110](https://github.com/MetaMask/smart-transactions-controller/pull/110), [#112](https://github.com/MetaMask/smart-transactions-controller/pull/112), [#113](https://github.com/MetaMask/smart-transactions-controller/pull/113))
20
+
21
+ ## [3.0.0]
22
+ ### Changed
23
+ - **BREAKING:** Bump required Node version to v14 ([#90](https://github.com/MetaMask/smart-transactions-controller/pull/90))
24
+ - `@metamask/controllers@32.0.2` ([#104](https://github.com/MetaMask/smart-transactions-controller/pull/104))
25
+
26
+ ### Fixed
27
+ - Ensure the nonce lock is always released ([#108](https://github.com/MetaMask/smart-transactions-controller/pull/108))
28
+
29
+ ## [2.3.2]
30
+ ### Changed
31
+ - Replace `ethers` with submodules (@ethersproject/bignumber,@ethersproject/bytes, @ethersproject/providers,) - no functional change ([#95](https://github.com/MetaMask/smart-transactions-controller/pull/95))
32
+
33
+ ## [2.3.1]
34
+ ### Changed
35
+ - Remove unnecessary event props ([#93](https://github.com/MetaMask/smart-transactions-controller/pull/93))
36
+ - Update `is-release` filter ([#91](https://github.com/MetaMask/smart-transactions-controller/pull/91))
37
+ - update is-release filter ([#89](https://github.com/MetaMask/smart-transactions-controller/pull/89))
38
+ - use `MetaMask/action-is-release@v1.0` ([#88](https://github.com/MetaMask/smart-transactions-controller/pull/88))
39
+ - add config for MetaMask/action-npm-publish ([#85](https://github.com/MetaMask/smart-transactions-controller/pull/85))
40
+
41
+ ## [2.3.0]
42
+ ### Added
43
+ - Add the "clearFees" function ([#84](https://github.com/MetaMask/smart-transactions-controller/pull/84))
44
+
45
+ ## [2.2.0]
46
+ ### Changed
47
+ - chore(deps): bump @metamask/controllers from 30.0.0 to 30.1.0 ([#81](https://github.com/MetaMask/smart-transactions-controller/pull/81))
48
+ - chore(deps-dev): bump @metamask/eslint-config-nodejs from 8.0.0 to 9.0.0 ([#80](https://github.com/MetaMask/smart-transactions-controller/pull/80))
49
+ - chore(deps-dev): bump @metamask/auto-changelog from 2.6.0 to 2.6.1 ([#79](https://github.com/MetaMask/smart-transactions-controller/pull/79))
50
+ - Return all error props in an error response ([#82](https://github.com/MetaMask/smart-transactions-controller/pull/82))
51
+
52
+ ## [2.1.0]
53
+ ### Added
54
+ - chore(deps): bump @metamask/controllers from 29.0.1 to 30.0.0 ([#75](https://github.com/MetaMask/smart-transactions-controller/pull/75))
55
+ - chore(deps-dev): bump @metamask/auto-changelog from 2.5.0 to 2.6.0 ([#71](https://github.com/MetaMask/smart-transactions-controller/pull/71))
56
+ - Return a pending status for a cancelled tx that hasn't been settled yet ([#74](https://github.com/MetaMask/smart-transactions-controller/pull/74))
57
+
58
+ ## [2.0.1]
59
+ ### Changed
60
+ - Previous version deprecated due to missing build files. No code changes made.
61
+
62
+ ## [2.0.0] [DEPRECATED]
63
+ ### Added
64
+ - "estimateGas" -> "getFees", support a new cancellation reason, refactoring ([#69](https://github.com/MetaMask/smart-transactions-controller/pull/69))
65
+ - chore(deps): bump @metamask/controllers from 28.0.0 to 29.0.1 ([#68](https://github.com/MetaMask/smart-transactions-controller/pull/68))
66
+ - If mined status is not mined and cancel reason not set, then show the cancel link, refactoring ([#66](https://github.com/MetaMask/smart-transactions-controller/pull/66))
67
+ - chore(deps): bump @metamask/controllers from 27.1.1 to 28.0.0 ([#65](https://github.com/MetaMask/smart-transactions-controller/pull/65))
68
+
69
+ ## [1.10.0]
70
+ ### Added
71
+ - Handle the "cancelled" status, lower status polling interval from 10s to 5s, don't mark a tx as cancelled immediately, track uuid ([#63](https://github.com/MetaMask/smart-transactions-controller/pull/63))
72
+ - chore(deps): bump @metamask/controllers from 25.1.0 to 27.1.1 ([#62](https://github.com/MetaMask/smart-transactions-controller/pull/62))
73
+ - Add tracking of the "current_stx_enabled" param ([#58](https://github.com/MetaMask/smart-transactions-controller/pull/58))
74
+
75
+ ## [1.9.1]
76
+ ### Added
77
+ - Use the "confirmExternalTransaction" fn directly ([#56](https://github.com/MetaMask/smart-transactions-controller/pull/56))
78
+
79
+ ## [1.9.0]
80
+ ### Added
81
+ - Only accept the "getNonceLock" fn and not the whole "nonceTracker" ([#54](https://github.com/MetaMask/smart-transactions-controller/pull/54))
82
+
83
+ ## [1.8.0]
84
+ ### Added
85
+ - Do not update an STX which doesn't exist anymore, add UTs ([#52](https://github.com/MetaMask/smart-transactions-controller/pull/52))
86
+
87
+ ## [1.7.0]
88
+ ### Added
89
+ - Fix UTs, change threshold ([#49](https://github.com/MetaMask/smart-transactions-controller/pull/49))
90
+
91
+ ## [1.6.0]
92
+ ### Added
93
+ - Change cancellable interval to be 1 minute ([#47](https://github.com/MetaMask/smart-transactions-controller/pull/47))
94
+ - Estimate approval transaction along with swaps transaction ([#46](https://github.com/MetaMask/smart-transactions-controller/pull/46))
95
+ - chore(deps): bump @metamask/controllers from 20.1.0 to 25.1.0 ([#44](https://github.com/MetaMask/smart-transactions-controller/pull/44))
96
+ - Add support for approveTxParams ([#45](https://github.com/MetaMask/smart-transactions-controller/pull/45))
97
+ - Add method for estimateGas ([#43](https://github.com/MetaMask/smart-transactions-controller/pull/43))
98
+
99
+ ## [1.5.0]
100
+ ### Added
101
+ - Add "fees" and "liveness" into the smartTransactionsState, update version ([#41](https://github.com/MetaMask/smart-transactions-controller/pull/41))
102
+
103
+ ## [1.4.0]
104
+ ### Added
105
+ - Add isomorphic-fetch to stx controller ([#38](https://github.com/MetaMask/smart-transactions-controller/pull/38))
106
+ - feat: create new handleFetch with custom error handling ([#35](https://github.com/MetaMask/smart-transactions-controller/pull/35))
107
+ - Unblock submit if ethers errors ([#30](https://github.com/MetaMask/smart-transactions-controller/pull/30))
108
+ - Parse chain ids from hex to dec instead of mapping them ([#31](https://github.com/MetaMask/smart-transactions-controller/pull/31))
109
+ - chore(deps): bump @metamask/controllers from 20.0.0 to 20.1.0 ([#28](https://github.com/MetaMask/smart-transactions-controller/pull/28))
110
+ - getTransactions -> getFees, refactoring ([#27](https://github.com/MetaMask/smart-transactions-controller/pull/27))
111
+ - chore(deps): bump @metamask/controllers from 19.0.0 to 20.0.0 ([#24](https://github.com/MetaMask/smart-transactions-controller/pull/24))
112
+ - Switch license with MetaMask license ([#25](https://github.com/MetaMask/smart-transactions-controller/pull/25))
113
+
114
+ ## [1.3.0]
115
+ ### Added
116
+ - Use the production version of the Transaction APIs repo ([#37](https://github.com/MetaMask/smart-transactions-controller/pull/37))
117
+
118
+ ## [1.2.0]
119
+ ### Added
120
+ - Add more unit tests for SmartTransactionsController ([#23](https://github.com/MetaMask/smart-transactions-controller/pull/23))
121
+ - chore(deps): bump @metamask/controllers from 16.0.0 to 19.0.0 ([#18](https://github.com/MetaMask/smart-transactions-controller/pull/18))
122
+ - Add cancelled status to stx after successful cancel request ([#21](https://github.com/MetaMask/smart-transactions-controller/pull/21))
123
+ - 1.1.0 ([#22](https://github.com/MetaMask/smart-transactions-controller/pull/22))
124
+
125
+ ## [1.1.0]
126
+ ### Added
127
+ - Tracking of STX status changes ([#20](https://github.com/MetaMask/smart-transactions-controller/pull/20))
128
+ - Remove cancelled transaction when new trx with same nonce submitted ([#19](https://github.com/MetaMask/smart-transactions-controller/pull/19))
129
+ - chore: modify polling and clean up tests ([#17](https://github.com/MetaMask/smart-transactions-controller/pull/17))
130
+ - State changes + getTransactions fn ([#16](https://github.com/MetaMask/smart-transactions-controller/pull/16))
131
+ - Add updatedTxParams and confirm history event ([#15](https://github.com/MetaMask/smart-transactions-controller/pull/15))
132
+ - Smart Transactions List ([#13](https://github.com/MetaMask/smart-transactions-controller/pull/13))
133
+
134
+ ## [1.0.0]
135
+ ### Added
136
+ - Adds nonce to a tx, adds `yarn build:link` support, updates functions for API calls, refactoring ([#8](https://github.com/MetaMask/smart-transactions-controller/pull/8))
137
+ - Add many unit tests, support for the batch_status API, refactoring ([#6](https://github.com/MetaMask/smart-transactions-controller/pull/6))
138
+ - Bump @metamask/controllers from 15.1.0 to 16.0.0
139
+ - Bump @metamask/controllers from 15.0.0 to 15.1.0 ([#4](https://github.com/MetaMask/smart-transactions-controller/pull/4))
140
+ - Add initial methods ([#3](https://github.com/MetaMask/smart-transactions-controller/pull/3))
141
+ - Add initial SmartTransactionsController ([#1](https://github.com/MetaMask/smart-transactions-controller/pull/1))
142
+ - Initial commit
143
+
144
+ [Unreleased]: https://github.com/MetaMask/smart-transactions-controller/compare/v4.0.0...HEAD
145
+ [4.0.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v3.1.0...v4.0.0
146
+ [3.1.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v3.0.0...v3.1.0
147
+ [3.0.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v2.3.2...v3.0.0
148
+ [2.3.2]: https://github.com/MetaMask/smart-transactions-controller/compare/v2.3.1...v2.3.2
149
+ [2.3.1]: https://github.com/MetaMask/smart-transactions-controller/compare/v2.3.0...v2.3.1
150
+ [2.3.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v2.2.0...v2.3.0
151
+ [2.2.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v2.1.0...v2.2.0
152
+ [2.1.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v2.0.1...v2.1.0
153
+ [2.0.1]: https://github.com/MetaMask/smart-transactions-controller/compare/v2.0.0...v2.0.1
154
+ [2.0.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.10.0...v2.0.0
155
+ [1.10.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.9.1...v1.10.0
156
+ [1.9.1]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.9.0...v1.9.1
157
+ [1.9.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.8.0...v1.9.0
158
+ [1.8.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.7.0...v1.8.0
159
+ [1.7.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.6.0...v1.7.0
160
+ [1.6.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.5.0...v1.6.0
161
+ [1.5.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.4.0...v1.5.0
162
+ [1.4.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.3.0...v1.4.0
163
+ [1.3.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.2.0...v1.3.0
164
+ [1.2.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.1.0...v1.2.0
165
+ [1.1.0]: https://github.com/MetaMask/smart-transactions-controller/compare/v1.0.0...v1.1.0
166
+ [1.0.0]: https://github.com/MetaMask/smart-transactions-controller/releases/tag/v1.0.0
package/README.md CHANGED
@@ -1,32 +1,23 @@
1
- # MetaMask Module Template
1
+ # `@metamask/smart-transactions-controller`
2
2
 
3
- This TypeScript module is maintained in the style of the MetaMask team.
3
+ Improves success rates for swaps by trialing transactions privately and finding minimum fees.
4
4
 
5
5
  ## Installation
6
6
 
7
- `yarn add @metamask/this-module`
7
+ `yarn add @metamask/smart-transactions-controller`
8
8
 
9
9
  or
10
10
 
11
- `npm install @metamask/this-module`
12
-
13
- ## Usage
14
-
15
- _Add examples here_
16
-
17
- ## API
18
-
19
- _Add examples here_
11
+ `npm install @metamask/smart-transactions-controller`
20
12
 
21
13
  ## Contributing
22
14
 
23
15
  ### Setup
24
16
 
25
- - Install [Node.js](https://nodejs.org) version 14
17
+ - Install [Node.js](https://nodejs.org) version 16
26
18
  - If you are using [nvm](https://github.com/creationix/nvm#installation) (recommended) running `nvm use` will automatically choose the right node version for you.
27
- - Install [Yarn v1](https://yarnpkg.com/en/docs/install)
28
- - Run `yarn setup` to install dependencies and run any requried post-install scripts
29
- - **Warning:** Do not use the `yarn` / `yarn install` command directly. Use `yarn setup` instead. The normal install command will skip required post-install scripts, leaving your development environment in an invalid state.
19
+ - Install [Yarn v3](https://yarnpkg.com/getting-started/install)
20
+ - Run `yarn install` to install dependencies and run any required post-install scripts
30
21
 
31
22
  ### Testing and Linting
32
23
 
@@ -1,14 +1,15 @@
1
1
  /// <reference types="node" />
2
- import { BaseConfig, BaseController, BaseState, NetworkState } from '@metamask/controllers';
2
+ import { BaseConfig, BaseController, BaseState } from '@metamask/base-controller';
3
+ import { NetworkState } from '@metamask/network-controller';
3
4
  import { SmartTransaction, SignedTransaction, SignedCanceledTransaction, UnsignedTransaction, SmartTransactionStatuses, Fees, IndividualTxFees } from './types';
4
5
  export declare const DEFAULT_INTERVAL: number;
5
- export interface SmartTransactionsControllerConfig extends BaseConfig {
6
+ export declare type SmartTransactionsControllerConfig = BaseConfig & {
6
7
  interval: number;
7
8
  clientId: string;
8
9
  chainId: string;
9
10
  supportedChainIds: string[];
10
- }
11
- export interface SmartTransactionsControllerState extends BaseState {
11
+ };
12
+ export declare type SmartTransactionsControllerState = BaseState & {
12
13
  smartTransactionsState: {
13
14
  smartTransactions: Record<string, SmartTransaction[]>;
14
15
  userOptIn: boolean | undefined;
@@ -18,7 +19,7 @@ export interface SmartTransactionsControllerState extends BaseState {
18
19
  tradeTxFees: IndividualTxFees | undefined;
19
20
  };
20
21
  };
21
- }
22
+ };
22
23
  export default class SmartTransactionsController extends BaseController<SmartTransactionsControllerConfig, SmartTransactionsControllerState> {
23
24
  timeoutHandle?: NodeJS.Timeout;
24
25
  private getNonceLock;
@@ -4,7 +4,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.DEFAULT_INTERVAL = void 0;
7
- const controllers_1 = require("@metamask/controllers");
7
+ const base_controller_1 = require("@metamask/base-controller");
8
+ const controller_utils_1 = require("@metamask/controller-utils");
8
9
  const bignumber_js_1 = require("bignumber.js");
9
10
  const bignumber_1 = require("@ethersproject/bignumber");
10
11
  const providers_1 = require("@ethersproject/providers");
@@ -14,10 +15,9 @@ const cloneDeep_1 = __importDefault(require("lodash/cloneDeep"));
14
15
  const types_1 = require("./types");
15
16
  const utils_1 = require("./utils");
16
17
  const constants_1 = require("./constants");
17
- const { safelyExecute } = controllers_1.util;
18
18
  const SECOND = 1000;
19
19
  exports.DEFAULT_INTERVAL = SECOND * 5;
20
- class SmartTransactionsController extends controllers_1.BaseController {
20
+ class SmartTransactionsController extends base_controller_1.BaseController {
21
21
  constructor({ onNetworkStateChange, getNonceLock, getNetwork, provider, confirmExternalTransaction, trackMetaMetricsEvent, }, config, state) {
22
22
  super(config, state);
23
23
  this.defaultConfig = {
@@ -44,7 +44,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
44
44
  this.trackMetaMetricsEvent = trackMetaMetricsEvent;
45
45
  this.initialize();
46
46
  this.initializeSmartTransactionsForChainId();
47
- onNetworkStateChange(({ provider: newProvider }) => {
47
+ onNetworkStateChange(({ providerConfig: newProvider }) => {
48
48
  const { chainId } = newProvider;
49
49
  this.configure({ chainId });
50
50
  this.initializeSmartTransactionsForChainId();
@@ -57,7 +57,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
57
57
  async fetch(request, options) {
58
58
  const { clientId } = this.config;
59
59
  const fetchOptions = Object.assign(Object.assign({}, options), { headers: Object.assign({ 'Content-Type': 'application/json' }, (clientId && { 'X-Client-Id': clientId })) });
60
- return utils_1.handleFetch(request, fetchOptions);
60
+ return (0, utils_1.handleFetch)(request, fetchOptions);
61
61
  }
62
62
  checkPoll(state) {
63
63
  const { smartTransactions } = state.smartTransactionsState;
@@ -86,9 +86,9 @@ class SmartTransactionsController extends controllers_1.BaseController {
86
86
  if (!supportedChainIds.includes(chainId)) {
87
87
  return;
88
88
  }
89
- await safelyExecute(() => this.updateSmartTransactions());
89
+ await (0, controller_utils_1.safelyExecute)(() => this.updateSmartTransactions());
90
90
  this.timeoutHandle = setInterval(() => {
91
- safelyExecute(() => this.updateSmartTransactions());
91
+ (0, controller_utils_1.safelyExecute)(() => this.updateSmartTransactions());
92
92
  }, this.config.interval);
93
93
  }
94
94
  async stop() {
@@ -104,8 +104,8 @@ class SmartTransactionsController extends controllers_1.BaseController {
104
104
  if (!prevSmartTransaction) {
105
105
  return; // Don't track the first STX, because it doesn't have all necessary params.
106
106
  }
107
- let updatedSmartTransaction = cloneDeep_1.default(smartTransaction);
108
- updatedSmartTransaction = Object.assign(Object.assign({}, cloneDeep_1.default(prevSmartTransaction)), updatedSmartTransaction);
107
+ let updatedSmartTransaction = (0, cloneDeep_1.default)(smartTransaction);
108
+ updatedSmartTransaction = Object.assign(Object.assign({}, (0, cloneDeep_1.default)(prevSmartTransaction)), updatedSmartTransaction);
109
109
  if (!updatedSmartTransaction.swapMetaData ||
110
110
  (updatedSmartTransaction.status === prevSmartTransaction.status &&
111
111
  prevSmartTransaction.swapMetaData)) {
@@ -115,7 +115,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
115
115
  stx_status: updatedSmartTransaction.status,
116
116
  token_from_symbol: updatedSmartTransaction.sourceTokenSymbol,
117
117
  token_to_symbol: updatedSmartTransaction.destinationTokenSymbol,
118
- processing_time: utils_1.getStxProcessingTime(updatedSmartTransaction.time),
118
+ processing_time: (0, utils_1.getStxProcessingTime)(updatedSmartTransaction.time),
119
119
  stx_enabled: true,
120
120
  current_stx_enabled: true,
121
121
  stx_user_opt_in: true,
@@ -151,7 +151,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
151
151
  return ((_a = stx.txParams) === null || _a === void 0 ? void 0 : _a.nonce) === ((_b = smartTransaction.txParams) === null || _b === void 0 ? void 0 : _b.nonce) &&
152
152
  ((_c = stx.status) === null || _c === void 0 ? void 0 : _c.startsWith('cancelled'));
153
153
  });
154
- const snapshot = cloneDeep_1.default(smartTransaction);
154
+ const snapshot = (0, cloneDeep_1.default)(smartTransaction);
155
155
  const history = [snapshot];
156
156
  const historifiedSmartTransaction = Object.assign(Object.assign({}, smartTransaction), { history });
157
157
  const nextSmartTransactions = cancelledNonceIndex > -1
@@ -202,7 +202,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
202
202
  if (transactionReceipt === null || transactionReceipt === void 0 ? void 0 : transactionReceipt.blockNumber) {
203
203
  const blockData = await this.ethersProvider.getBlock(transactionReceipt === null || transactionReceipt === void 0 ? void 0 : transactionReceipt.blockNumber, false);
204
204
  const baseFeePerGas = blockData === null || blockData === void 0 ? void 0 : blockData.baseFeePerGas.toHexString();
205
- const txReceipt = mapValues_1.default(transactionReceipt, (value) => {
205
+ const txReceipt = (0, mapValues_1.default)(transactionReceipt, (value) => {
206
206
  if (value instanceof bignumber_1.BigNumber) {
207
207
  return value.toHexString();
208
208
  }
@@ -213,11 +213,11 @@ class SmartTransactionsController extends controllers_1.BaseController {
213
213
  // call confirmExternalTransaction
214
214
  const originalTxMeta = Object.assign(Object.assign({}, smartTransaction), { id: smartTransaction.uuid, status: 'confirmed', hash: txHash, txParams: updatedTxParams });
215
215
  // create txMeta snapshot for history
216
- const snapshot = utils_1.snapshotFromTxMeta(originalTxMeta);
216
+ const snapshot = (0, utils_1.snapshotFromTxMeta)(originalTxMeta);
217
217
  // recover previous tx state obj
218
- const previousState = utils_1.replayHistory(originalTxMeta.history);
218
+ const previousState = (0, utils_1.replayHistory)(originalTxMeta.history);
219
219
  // generate history entry and add to history
220
- const entry = utils_1.generateHistoryEntry(previousState, snapshot, 'txStateManager: setting status to confirmed');
220
+ const entry = (0, utils_1.generateHistoryEntry)(previousState, snapshot, 'txStateManager: setting status to confirmed');
221
221
  const txMeta = entry.length > 0
222
222
  ? Object.assign(Object.assign({}, originalTxMeta), { history: originalTxMeta.history.concat(entry) }) : originalTxMeta;
223
223
  this.confirmExternalTransaction(txMeta, txReceipt, baseFeePerGas);
@@ -242,13 +242,13 @@ class SmartTransactionsController extends controllers_1.BaseController {
242
242
  const params = new URLSearchParams({
243
243
  uuids: uuids.join(','),
244
244
  });
245
- const url = `${utils_1.getAPIRequestURL(types_1.APIType.BATCH_STATUS, chainId)}?${params.toString()}`;
245
+ const url = `${(0, utils_1.getAPIRequestURL)(types_1.APIType.BATCH_STATUS, chainId)}?${params.toString()}`;
246
246
  const data = await this.fetch(url);
247
247
  Object.entries(data).forEach(([uuid, stxStatus]) => {
248
248
  this.updateSmartTransaction({
249
249
  statusMetadata: stxStatus,
250
- status: utils_1.calculateStatus(stxStatus),
251
- cancellable: utils_1.isSmartTransactionCancellable(stxStatus),
250
+ status: (0, utils_1.calculateStatus)(stxStatus),
251
+ cancellable: (0, utils_1.isSmartTransactionCancellable)(stxStatus),
252
252
  uuid,
253
253
  });
254
254
  });
@@ -279,13 +279,13 @@ class SmartTransactionsController extends controllers_1.BaseController {
279
279
  transactions.push(unsignedApprovalTransactionWithNonce);
280
280
  unsignedTradeTransactionWithNonce = Object.assign(Object.assign({}, tradeTx), {
281
281
  // If there is an approval tx, the trade tx's nonce is increased by 1.
282
- nonce: utils_1.incrementNonceInHex(unsignedApprovalTransactionWithNonce.nonce) });
282
+ nonce: (0, utils_1.incrementNonceInHex)(unsignedApprovalTransactionWithNonce.nonce) });
283
283
  }
284
284
  else {
285
285
  unsignedTradeTransactionWithNonce = await this.addNonceToTransaction(tradeTx);
286
286
  }
287
287
  transactions.push(unsignedTradeTransactionWithNonce);
288
- const data = await this.fetch(utils_1.getAPIRequestURL(types_1.APIType.GET_FEES, chainId), {
288
+ const data = await this.fetch((0, utils_1.getAPIRequestURL)(types_1.APIType.GET_FEES, chainId), {
289
289
  method: 'POST',
290
290
  body: JSON.stringify({
291
291
  txs: transactions,
@@ -315,7 +315,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
315
315
  // * transaction controller external transactions list
316
316
  async submitSignedTransactions({ txParams, signedTransactions, signedCanceledTransactions, }) {
317
317
  const { chainId } = this.config;
318
- const data = await this.fetch(utils_1.getAPIRequestURL(types_1.APIType.SUBMIT_TRANSACTIONS, chainId), {
318
+ const data = await this.fetch((0, utils_1.getAPIRequestURL)(types_1.APIType.SUBMIT_TRANSACTIONS, chainId), {
319
319
  method: 'POST',
320
320
  body: JSON.stringify({
321
321
  rawTxs: signedTransactions,
@@ -334,7 +334,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
334
334
  }
335
335
  const nonceLock = await this.getNonceLock(txParams === null || txParams === void 0 ? void 0 : txParams.from);
336
336
  try {
337
- const nonce = bytes_1.hexlify(nonceLock.nextNonce);
337
+ const nonce = (0, bytes_1.hexlify)(nonceLock.nextNonce);
338
338
  if (txParams && !(txParams === null || txParams === void 0 ? void 0 : txParams.nonce)) {
339
339
  txParams.nonce = nonce;
340
340
  }
@@ -361,7 +361,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
361
361
  // in transaction controller external transactions list
362
362
  async cancelSmartTransaction(uuid) {
363
363
  const { chainId } = this.config;
364
- await this.fetch(utils_1.getAPIRequestURL(types_1.APIType.CANCEL, chainId), {
364
+ await this.fetch((0, utils_1.getAPIRequestURL)(types_1.APIType.CANCEL, chainId), {
365
365
  method: 'POST',
366
366
  body: JSON.stringify({ uuid }),
367
367
  });
@@ -370,7 +370,7 @@ class SmartTransactionsController extends controllers_1.BaseController {
370
370
  const { chainId } = this.config;
371
371
  let liveness = false;
372
372
  try {
373
- const response = await this.fetch(utils_1.getAPIRequestURL(types_1.APIType.LIVENESS, chainId));
373
+ const response = await this.fetch((0, utils_1.getAPIRequestURL)(types_1.APIType.LIVENESS, chainId));
374
374
  liveness = Boolean(response.lastBlock);
375
375
  }
376
376
  catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"SmartTransactionsController.js","sourceRoot":"","sources":["../src/SmartTransactionsController.ts"],"names":[],"mappings":";;;;;;AAAA,uDAM+B;AAC/B,+CAAyC;AACzC,wDAAwE;AACxE,wDAAwD;AACxD,gDAA+C;AAC/C,iEAAyC;AACzC,iEAAyC;AACzC,mCAUiB;AACjB,mCAWiB;AACjB,2CAAwC;AAExC,MAAM,EAAE,aAAa,EAAE,GAAG,kBAAI,CAAC;AAE/B,MAAM,MAAM,GAAG,IAAI,CAAC;AACP,QAAA,gBAAgB,GAAG,MAAM,GAAG,CAAC,CAAC;AAqB3C,MAAqB,2BAA4B,SAAQ,4BAGxD;IA2BC,YACE,EACE,oBAAoB,EACpB,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,0BAA0B,EAC1B,qBAAqB,GAUtB,EACD,MAAmD,EACnD,KAAiD;QAEjD,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAErB,IAAI,CAAC,aAAa,GAAG;YACnB,QAAQ,EAAE,wBAAgB;YAC1B,OAAO,EAAE,qBAAS,CAAC,QAAQ;YAC3B,QAAQ,EAAE,SAAS;YACnB,iBAAiB,EAAE,CAAC,qBAAS,CAAC,QAAQ,EAAE,qBAAS,CAAC,OAAO,CAAC;SAC3D,CAAC;QAEF,IAAI,CAAC,YAAY,GAAG;YAClB,sBAAsB,EAAE;gBACtB,iBAAiB,EAAE,EAAE;gBACrB,SAAS,EAAE,SAAS;gBACpB,IAAI,EAAE;oBACJ,cAAc,EAAE,SAAS;oBACzB,WAAW,EAAE,SAAS;iBACvB;gBACD,QAAQ,EAAE,IAAI;aACf;SACF,CAAC;QAEF,IAAI,CAAC,YAAY,GAAG,YAA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AC,wBAAwB,CAAC,QAAgB;QAC7C,IAAI,QAAQ,KAAK,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE;YACrC,IAAI,CAAC,SAAS,CAAC,EAAE,QAAQ,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;SAC5C;IACH,CAAC;IAED,eAAe,CAAC,EACd,WAAW,EACX,MAAM,GAIP;QACC,MAAM,EAAE,iBAAiB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,sBAAsB,CAAC;QAChE,MAAM,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,MAAM,CAAC;QAChC,MAAM,wBAAwB,GAAG,iBAAiB,aAAjB,iBAAiB,uBAAjB,iBAAiB,CAAG,OAAO,CAAC,CAAC;QAC9D,IAAI,CAAC,wBAAwB,IAAI,wBAAwB,CAAC,MAAM,KAAK,CAAC,EAAE;YACtE,OAAO,EAAE,CAAC;SACX;QAED,OAAO,wBAAwB,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE;;YAC7C,OAAO,GAAG,CAAC,MAAM,KAAK,MAAM,IAAI,CAAA,MAAA,GAAG,CAAC,QAAQ,0CAAE,IAAI,MAAK,WAAW,CAAC;QACrE,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA7kBD,8CA6kBC","sourcesContent":["import {\n BaseConfig,\n BaseController,\n BaseState,\n NetworkState,\n util,\n} from '@metamask/controllers';\nimport { BigNumber } from 'bignumber.js';\nimport { BigNumber as ethersBigNumber } from '@ethersproject/bignumber';\nimport { Web3Provider } from '@ethersproject/providers';\nimport { hexlify } from '@ethersproject/bytes';\nimport mapValues from 'lodash/mapValues';\nimport cloneDeep from 'lodash/cloneDeep';\nimport {\n APIType,\n SmartTransaction,\n SignedTransaction,\n SignedCanceledTransaction,\n UnsignedTransaction,\n SmartTransactionsStatus,\n SmartTransactionStatuses,\n Fees,\n IndividualTxFees,\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 { safelyExecute } = util;\n\nconst SECOND = 1000;\nexport const DEFAULT_INTERVAL = SECOND * 5;\n\nexport interface SmartTransactionsControllerConfig extends BaseConfig {\n interval: number;\n clientId: string;\n chainId: string;\n supportedChainIds: string[];\n}\n\nexport interface SmartTransactionsControllerState extends BaseState {\n smartTransactionsState: {\n smartTransactions: Record<string, SmartTransaction[]>;\n userOptIn: boolean | undefined;\n liveness: boolean | undefined;\n fees: {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n };\n };\n}\n\nexport default class SmartTransactionsController extends BaseController<\n SmartTransactionsControllerConfig,\n SmartTransactionsControllerState\n> {\n public timeoutHandle?: NodeJS.Timeout;\n\n private getNonceLock: any;\n\n private getNetwork: any;\n\n public ethersProvider: any;\n\n public confirmExternalTransaction: any;\n\n private trackMetaMetricsEvent: any;\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 getNetwork,\n provider,\n confirmExternalTransaction,\n trackMetaMetricsEvent,\n }: {\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNonceLock: any;\n getNetwork: any;\n provider: any;\n confirmExternalTransaction: any;\n trackMetaMetricsEvent: any;\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.RINKEBY],\n };\n\n this.defaultState = {\n smartTransactionsState: {\n smartTransactions: {},\n userOptIn: undefined,\n fees: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n liveness: true,\n },\n };\n\n this.getNonceLock = getNonceLock;\n this.getNetwork = getNetwork;\n this.ethersProvider = new Web3Provider(provider);\n this.confirmExternalTransaction = confirmExternalTransaction;\n this.trackMetaMetricsEvent = trackMetaMetricsEvent;\n\n this.initialize();\n this.initializeSmartTransactionsForChainId();\n\n onNetworkStateChange(({ provider: newProvider }) => {\n const { chainId } = newProvider;\n this.configure({ chainId });\n this.initializeSmartTransactionsForChainId();\n this.checkPoll(this.state);\n this.ethersProvider = new Web3Provider(provider);\n });\n\n this.subscribe((currentState: any) => this.checkPoll(currentState));\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 userOptIn: 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(smartTransaction: SmartTransaction): void {\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 === smartTransaction.uuid,\n );\n const isNewSmartTransaction = this.isNewSmartTransaction(\n smartTransaction.uuid,\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 }\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 const { smartTransactions } = this.state.smartTransactionsState;\n const { chainId } = this.config;\n\n const currentSmartTransactions = smartTransactions?.[chainId];\n\n const transactionsToUpdate: string[] = currentSmartTransactions\n .filter(isSmartTransactionPending)\n .map((smartTransaction) => smartTransaction.uuid);\n\n if (transactionsToUpdate.length > 0) {\n this.fetchSmartTransactionsStatus(transactionsToUpdate);\n }\n }\n\n async confirmSmartTransaction(smartTransaction: SmartTransaction) {\n const txHash = smartTransaction.statusMetadata?.minedHash;\n try {\n const transactionReceipt = await this.ethersProvider.getTransactionReceipt(\n txHash,\n );\n const transaction = await this.ethersProvider.getTransaction(txHash);\n const maxFeePerGas = transaction.maxFeePerGas?.toHexString();\n const maxPriorityFeePerGas = transaction.maxPriorityFeePerGas?.toHexString();\n if (transactionReceipt?.blockNumber) {\n const blockData = await this.ethersProvider.getBlock(\n transactionReceipt?.blockNumber,\n false,\n );\n const baseFeePerGas = blockData?.baseFeePerGas.toHexString();\n const txReceipt = mapValues(transactionReceipt, (value) => {\n if (value instanceof ethersBigNumber) {\n return value.toHexString();\n }\n return value;\n });\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 this.confirmExternalTransaction(txMeta, txReceipt, baseFeePerGas);\n\n this.trackMetaMetricsEvent({\n event: 'STX Confirmed',\n category: 'swaps',\n });\n\n this.updateSmartTransaction({\n ...smartTransaction,\n confirmed: true,\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 ): Promise<SmartTransaction[]> {\n const { chainId } = this.config;\n\n const params = new URLSearchParams({\n uuids: uuids.join(','),\n });\n\n const url = `${getAPIRequestURL(\n APIType.BATCH_STATUS,\n chainId,\n )}?${params.toString()}`;\n\n const data = await this.fetch(url);\n\n Object.entries(data).forEach(([uuid, stxStatus]) => {\n this.updateSmartTransaction({\n statusMetadata: stxStatus as SmartTransactionsStatus,\n status: calculateStatus(stxStatus as SmartTransactionsStatus),\n cancellable: isSmartTransactionCancellable(\n stxStatus as SmartTransactionsStatus,\n ),\n uuid,\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 ): Promise<Fees> {\n const { chainId } = this.config;\n const transactions = [];\n let unsignedTradeTransactionWithNonce;\n if (approvalTx) {\n const unsignedApprovalTransactionWithNonce = await this.addNonceToTransaction(\n approvalTx,\n );\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 },\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 }: {\n signedTransactions: SignedTransaction[];\n signedCanceledTransactions: SignedCanceledTransaction[];\n txParams?: any;\n }) {\n const { chainId } = this.config;\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 const metamaskNetworkId = this.getNetwork();\n let preTxBalance;\n try {\n const preTxBalanceBN = await this.ethersProvider.getBalance(\n txParams?.from,\n );\n preTxBalance = new BigNumber(preTxBalanceBN.toHexString()).toString(16);\n } catch (e) {\n console.error('ethers 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 chainId,\n nonceDetails,\n metamaskNetworkId,\n preTxBalance,\n status: SmartTransactionStatuses.PENDING,\n time,\n txParams,\n uuid: data.uuid,\n cancellable: true,\n });\n } finally {\n nonceLock.releaseLock();\n }\n\n return data;\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(uuid: string): Promise<void> {\n const { chainId } = this.config;\n await this.fetch(getAPIRequestURL(APIType.CANCEL, chainId), {\n method: 'POST',\n body: JSON.stringify({ uuid }),\n });\n }\n\n async fetchLiveness(): Promise<boolean> {\n const { chainId } = this.config;\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 },\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,+DAImC;AACnC,iEAA2D;AAE3D,+CAAyC;AACzC,wDAAwE;AACxE,wDAAwD;AACxD,gDAA+C;AAC/C,iEAAyC;AACzC,iEAAyC;AACzC,mCAUiB;AACjB,mCAWiB;AACjB,2CAAwC;AAExC,MAAM,MAAM,GAAG,IAAI,CAAC;AACP,QAAA,gBAAgB,GAAG,MAAM,GAAG,CAAC,CAAC;AAqB3C,MAAqB,2BAA4B,SAAQ,gCAGxD;IA2BC,YACE,EACE,oBAAoB,EACpB,YAAY,EACZ,UAAU,EACV,QAAQ,EACR,0BAA0B,EAC1B,qBAAqB,GAUtB,EACD,MAAmD,EACnD,KAAiD;QAEjD,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAErB,IAAI,CAAC,aAAa,GAAG;YACnB,QAAQ,EAAE,wBAAgB;YAC1B,OAAO,EAAE,qBAAS,CAAC,QAAQ;YAC3B,QAAQ,EAAE,SAAS;YACnB,iBAAiB,EAAE,CAAC,qBAAS,CAAC,QAAQ,EAAE,qBAAS,CAAC,O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Controller,\n BaseState,\n} from '@metamask/base-controller';\nimport { safelyExecute } from '@metamask/controller-utils';\nimport { NetworkState } from '@metamask/network-controller';\nimport { BigNumber } from 'bignumber.js';\nimport { BigNumber as ethersBigNumber } from '@ethersproject/bignumber';\nimport { Web3Provider } from '@ethersproject/providers';\nimport { hexlify } from '@ethersproject/bytes';\nimport mapValues from 'lodash/mapValues';\nimport cloneDeep from 'lodash/cloneDeep';\nimport {\n APIType,\n SmartTransaction,\n SignedTransaction,\n SignedCanceledTransaction,\n UnsignedTransaction,\n SmartTransactionsStatus,\n SmartTransactionStatuses,\n Fees,\n IndividualTxFees,\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: string;\n supportedChainIds: string[];\n};\n\nexport type SmartTransactionsControllerState = BaseState & {\n smartTransactionsState: {\n smartTransactions: Record<string, SmartTransaction[]>;\n userOptIn: boolean | undefined;\n liveness: boolean | undefined;\n fees: {\n approvalTxFees: IndividualTxFees | undefined;\n tradeTxFees: IndividualTxFees | undefined;\n };\n };\n};\n\nexport default class SmartTransactionsController extends BaseController<\n SmartTransactionsControllerConfig,\n SmartTransactionsControllerState\n> {\n public timeoutHandle?: NodeJS.Timeout;\n\n private getNonceLock: any;\n\n private getNetwork: any;\n\n public ethersProvider: any;\n\n public confirmExternalTransaction: any;\n\n private trackMetaMetricsEvent: any;\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 getNetwork,\n provider,\n confirmExternalTransaction,\n trackMetaMetricsEvent,\n }: {\n onNetworkStateChange: (\n listener: (networkState: NetworkState) => void,\n ) => void;\n getNonceLock: any;\n getNetwork: any;\n provider: any;\n confirmExternalTransaction: any;\n trackMetaMetricsEvent: any;\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.RINKEBY],\n };\n\n this.defaultState = {\n smartTransactionsState: {\n smartTransactions: {},\n userOptIn: undefined,\n fees: {\n approvalTxFees: undefined,\n tradeTxFees: undefined,\n },\n liveness: true,\n },\n };\n\n this.getNonceLock = getNonceLock;\n this.getNetwork = getNetwork;\n this.ethersProvider = new Web3Provider(provider);\n this.confirmExternalTransaction = confirmExternalTransaction;\n this.trackMetaMetricsEvent = trackMetaMetricsEvent;\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.ethersProvider = new Web3Provider(provider);\n });\n\n this.subscribe((currentState: any) => this.checkPoll(currentState));\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 userOptIn: 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(smartTransaction: SmartTransaction): void {\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 === smartTransaction.uuid,\n );\n const isNewSmartTransaction = this.isNewSmartTransaction(\n smartTransaction.uuid,\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 }\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 const { smartTransactions } = this.state.smartTransactionsState;\n const { chainId } = this.config;\n\n const currentSmartTransactions = smartTransactions?.[chainId];\n\n const transactionsToUpdate: string[] = currentSmartTransactions\n .filter(isSmartTransactionPending)\n .map((smartTransaction) => smartTransaction.uuid);\n\n if (transactionsToUpdate.length > 0) {\n this.fetchSmartTransactionsStatus(transactionsToUpdate);\n }\n }\n\n async confirmSmartTransaction(smartTransaction: SmartTransaction) {\n const txHash = smartTransaction.statusMetadata?.minedHash;\n try {\n const transactionReceipt =\n await this.ethersProvider.getTransactionReceipt(txHash);\n const transaction = await this.ethersProvider.getTransaction(txHash);\n const maxFeePerGas = transaction.maxFeePerGas?.toHexString();\n const maxPriorityFeePerGas =\n transaction.maxPriorityFeePerGas?.toHexString();\n if (transactionReceipt?.blockNumber) {\n const blockData = await this.ethersProvider.getBlock(\n transactionReceipt?.blockNumber,\n false,\n );\n const baseFeePerGas = blockData?.baseFeePerGas.toHexString();\n const txReceipt = mapValues(transactionReceipt, (value) => {\n if (value instanceof ethersBigNumber) {\n return value.toHexString();\n }\n return value;\n });\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 this.confirmExternalTransaction(txMeta, txReceipt, baseFeePerGas);\n\n this.trackMetaMetricsEvent({\n event: 'STX Confirmed',\n category: 'swaps',\n });\n\n this.updateSmartTransaction({\n ...smartTransaction,\n confirmed: true,\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 ): Promise<SmartTransaction[]> {\n const { chainId } = this.config;\n\n const params = new URLSearchParams({\n uuids: uuids.join(','),\n });\n\n const url = `${getAPIRequestURL(\n APIType.BATCH_STATUS,\n chainId,\n )}?${params.toString()}`;\n\n const data = await this.fetch(url);\n\n Object.entries(data).forEach(([uuid, stxStatus]) => {\n this.updateSmartTransaction({\n statusMetadata: stxStatus as SmartTransactionsStatus,\n status: calculateStatus(stxStatus as SmartTransactionsStatus),\n cancellable: isSmartTransactionCancellable(\n stxStatus as SmartTransactionsStatus,\n ),\n uuid,\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 ): Promise<Fees> {\n const { chainId } = this.config;\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 },\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 }: {\n signedTransactions: SignedTransaction[];\n signedCanceledTransactions: SignedCanceledTransaction[];\n txParams?: any;\n }) {\n const { chainId } = this.config;\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 const metamaskNetworkId = this.getNetwork();\n let preTxBalance;\n try {\n const preTxBalanceBN = await this.ethersProvider.getBalance(\n txParams?.from,\n );\n preTxBalance = new BigNumber(preTxBalanceBN.toHexString()).toString(16);\n } catch (e) {\n console.error('ethers 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 chainId,\n nonceDetails,\n metamaskNetworkId,\n preTxBalance,\n status: SmartTransactionStatuses.PENDING,\n time,\n txParams,\n uuid: data.uuid,\n cancellable: true,\n });\n } finally {\n nonceLock.releaseLock();\n }\n\n return data;\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(uuid: string): Promise<void> {\n const { chainId } = this.config;\n await this.fetch(getAPIRequestURL(APIType.CANCEL, chainId), {\n method: 'POST',\n body: JSON.stringify({ uuid }),\n });\n }\n\n async fetchLiveness(): Promise<boolean> {\n const { chainId } = this.config;\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 },\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/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- import 'isomorphic-fetch';
2
1
  import SmartTransactionsController from './SmartTransactionsController';
3
2
  export default SmartTransactionsController;
package/dist/index.js CHANGED
@@ -3,8 +3,6 @@ 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
- // eslint-disable-next-line import/no-unassigned-import
7
- require("isomorphic-fetch");
8
6
  const SmartTransactionsController_1 = __importDefault(require("./SmartTransactionsController"));
9
7
  exports.default = SmartTransactionsController_1.default;
10
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,uDAAuD;AACvD,4BAA0B;AAC1B,gGAAwE;AAExE,kBAAe,qCAA2B,CAAC","sourcesContent":["// eslint-disable-next-line import/no-unassigned-import\nimport 'isomorphic-fetch';\nimport SmartTransactionsController from './SmartTransactionsController';\n\nexport default SmartTransactionsController;\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,gGAAwE;AAExE,kBAAe,qCAA2B,CAAC","sourcesContent":["import SmartTransactionsController from './SmartTransactionsController';\n\nexport default SmartTransactionsController;\n"]}
package/dist/types.d.ts CHANGED
@@ -46,7 +46,7 @@ export declare const cancellationReasonToStatusMap: {
46
46
  user_cancelled: SmartTransactionStatuses;
47
47
  previous_tx_cancelled: SmartTransactionStatuses;
48
48
  };
49
- export interface SmartTransactionsStatus {
49
+ export declare type SmartTransactionsStatus = {
50
50
  error?: string;
51
51
  cancellationFeeWei: number;
52
52
  cancellationReason?: SmartTransactionCancellationReason;
@@ -54,8 +54,8 @@ export interface SmartTransactionsStatus {
54
54
  minedHash: string | undefined;
55
55
  minedTx: SmartTransactionMinedTx;
56
56
  isSettled: boolean;
57
- }
58
- export interface SmartTransaction {
57
+ };
58
+ export declare type SmartTransaction = {
59
59
  uuid: string;
60
60
  chainId?: string;
61
61
  destinationTokenAddress?: string;
@@ -76,22 +76,22 @@ export interface SmartTransaction {
76
76
  type?: string;
77
77
  confirmed?: boolean;
78
78
  cancellable?: boolean;
79
- }
80
- export interface Fee {
79
+ };
80
+ export declare type Fee = {
81
81
  maxFeePerGas: number;
82
82
  maxPriorityFeePerGas: number;
83
- }
84
- export interface IndividualTxFees {
83
+ };
84
+ export declare type IndividualTxFees = {
85
85
  fees: Fee[];
86
86
  cancelFees: Fee[];
87
87
  feeEstimate: number;
88
88
  gasLimit: number;
89
89
  gasUsed: number;
90
- }
91
- export interface Fees {
90
+ };
91
+ export declare type Fees = {
92
92
  approvalTxFees: IndividualTxFees | undefined;
93
93
  tradeTxFees: IndividualTxFees | undefined;
94
- }
94
+ };
95
95
  export declare type UnsignedTransaction = any;
96
96
  export declare type SignedTransaction = any;
97
97
  export declare type SignedCanceledTransaction = any;
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA,UAAU;;;AAEV,IAAY,OAOX;AAPD,WAAY,OAAO;IACjB,6CAAU,CAAA;IACV,qDAAc,CAAA;IACd,mEAAqB,CAAA;IACrB,yCAAQ,CAAA;IACR,qDAAc,CAAA;IACd,6CAAU,CAAA;AACZ,CAAC,EAPW,OAAO,GAAP,eAAO,KAAP,eAAO,QAOlB;AAED,wBAAwB;AAExB,IAAY,uBAMX;AAND,WAAY,uBAAuB;IACjC,kDAAuB,CAAA;IACvB,8CAAmB,CAAA;IACnB,kDAAuB,CAAA;IACvB,gDAAqB,CAAA;IACrB,8CAAmB,CAAA;AACrB,CAAC,EANW,uBAAuB,GAAvB,+BAAuB,KAAvB,+BAAuB,QAMlC;AAED,IAAY,kCAQX;AARD,WAAY,kCAAkC;IAC5C,mEAA6B,CAAA;IAC7B,6DAAuB,CAAA;IACvB,yEAAmC,CAAA;IACnC,qEAA+B,CAAA;IAC/B,uEAAiC,CAAA;IACjC,qEAA+B,CAAA;IAC/B,qFAA+C,CAAA;AACjD,CAAC,EARW,kCAAkC,GAAlC,0CAAkC,KAAlC,0CAAkC,QAQ7C;AAED,IAAY,wBAaX;AAbD,WAAY,wBAAwB;IAClC,+CAAmB,CAAA;IACnB,+CAAmB,CAAA;IACnB,iDAAqB,CAAA;IACrB,+CAAmB,CAAA;IACnB,mDAAuB,CAAA;IACvB,6EAAiD,CAAA;IACjD,uEAA2C,CAAA;IAC3C,mFAAuD,CAAA;IACvD,+EAAmD,CAAA;IACnD,iFAAqD,CAAA;IACrD,+FAAmE,CAAA;IACnE,iDAAqB,CAAA;AACvB,CAAC,EAbW,wBAAwB,GAAxB,gCAAwB,KAAxB,gCAAwB,QAanC;AAEY,QAAA,6BAA6B,GAAG;IAC3C,CAAC,kCAAkC,CAAC,YAAY,CAAC,EAC/C,wBAAwB,CAAC,sBAAsB;IACjD,CAAC,kCAAkC,CAAC,SAAS,CAAC,EAC5C,wBAAwB,CAAC,mBAAmB;IAC9C,CAAC,kCAAkC,CAAC,eAAe,CAAC,EAClD,wBAAwB,CAAC,yBAAyB;IACpD,CAAC,kCAAkC,CAAC,aAAa,CAAC,EAChD,wBAAwB,CAAC,uBAAuB;IAClD,CAAC,kCAAkC,CAAC,cAAc,CAAC,EACjD,wBAAwB,CAAC,wBAAwB;IACnD,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,EACxD,wBAAwB,CAAC,+BAA+B;CAC3D,CAAC","sourcesContent":["/** 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 interface 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 interface SmartTransaction {\n uuid: string;\n chainId?: string;\n destinationTokenAddress?: string;\n destinationTokenDecimals?: string;\n destinationTokenSymbol?: string;\n history?: any;\n metamaskNetworkId?: string;\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 interface Fee {\n maxFeePerGas: number;\n maxPriorityFeePerGas: number;\n}\n\nexport interface IndividualTxFees {\n fees: Fee[];\n cancelFees: Fee[];\n feeEstimate: number;\n gasLimit: number;\n gasUsed: number;\n}\n\nexport interface 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"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";AAAA,UAAU;;;AAEV,IAAY,OAOX;AAPD,WAAY,OAAO;IACjB,6CAAU,CAAA;IACV,qDAAc,CAAA;IACd,mEAAqB,CAAA;IACrB,yCAAQ,CAAA;IACR,qDAAc,CAAA;IACd,6CAAU,CAAA;AACZ,CAAC,EAPW,OAAO,GAAP,eAAO,KAAP,eAAO,QAOlB;AAED,wBAAwB;AAExB,IAAY,uBAMX;AAND,WAAY,uBAAuB;IACjC,kDAAuB,CAAA;IACvB,8CAAmB,CAAA;IACnB,kDAAuB,CAAA;IACvB,gDAAqB,CAAA;IACrB,8CAAmB,CAAA;AACrB,CAAC,EANW,uBAAuB,GAAvB,+BAAuB,KAAvB,+BAAuB,QAMlC;AAED,IAAY,kCAQX;AARD,WAAY,kCAAkC;IAC5C,mEAA6B,CAAA;IAC7B,6DAAuB,CAAA;IACvB,yEAAmC,CAAA;IACnC,qEAA+B,CAAA;IAC/B,uEAAiC,CAAA;IACjC,qEAA+B,CAAA;IAC/B,qFAA+C,CAAA;AACjD,CAAC,EARW,kCAAkC,GAAlC,0CAAkC,KAAlC,0CAAkC,QAQ7C;AAED,IAAY,wBAaX;AAbD,WAAY,wBAAwB;IAClC,+CAAmB,CAAA;IACnB,+CAAmB,CAAA;IACnB,iDAAqB,CAAA;IACrB,+CAAmB,CAAA;IACnB,mDAAuB,CAAA;IACvB,6EAAiD,CAAA;IACjD,uEAA2C,CAAA;IAC3C,mFAAuD,CAAA;IACvD,+EAAmD,CAAA;IACnD,iFAAqD,CAAA;IACrD,+FAAmE,CAAA;IACnE,iDAAqB,CAAA;AACvB,CAAC,EAbW,wBAAwB,GAAxB,gCAAwB,KAAxB,gCAAwB,QAanC;AAEY,QAAA,6BAA6B,GAAG;IAC3C,CAAC,kCAAkC,CAAC,YAAY,CAAC,EAC/C,wBAAwB,CAAC,sBAAsB;IACjD,CAAC,kCAAkC,CAAC,SAAS,CAAC,EAC5C,wBAAwB,CAAC,mBAAmB;IAC9C,CAAC,kCAAkC,CAAC,eAAe,CAAC,EAClD,wBAAwB,CAAC,yBAAyB;IACpD,CAAC,kCAAkC,CAAC,aAAa,CAAC,EAChD,wBAAwB,CAAC,uBAAuB;IAClD,CAAC,kCAAkC,CAAC,cAAc,CAAC,EACjD,wBAAwB,CAAC,wBAAwB;IACnD,CAAC,kCAAkC,CAAC,qBAAqB,CAAC,EACxD,wBAAwB,CAAC,+BAA+B;CAC3D,CAAC","sourcesContent":["/** 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 metamaskNetworkId?: string;\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"]}
package/dist/utils.d.ts CHANGED
@@ -10,27 +10,27 @@ export declare const calculateStatus: (stxStatus: SmartTransactionsStatus) => Sm
10
10
  path (the key and if a nested object then each key will be separated with a `/`)
11
11
  value
12
12
  with the first entry having the note and a timestamp when the change took place
13
- @param {Object} previousState - the previous state of the object
14
- @param {Object} newState - the update object
15
- @param {string} [note] - a optional note for the state change
16
- @returns {Array}
13
+ @param previousState - the previous state of the object
14
+ @param newState - the update object
15
+ @param [note] - a optional note for the state change
16
+ @returns
17
17
  */
18
18
  export declare function generateHistoryEntry(previousState: any, newState: any, note: string): any;
19
19
  /**
20
20
  Recovers previous txMeta state obj
21
- @returns {Object}
21
+ @returns
22
22
  */
23
23
  export declare function replayHistory(_shortHistory: any): any;
24
24
  /**
25
25
  * Snapshot {@code txMeta}
26
- * @param {Object} txMeta - the tx metadata object
27
- * @returns {Object} a deep clone without history
26
+ * @param txMeta - the tx metadata object
27
+ * @returns a deep clone without history
28
28
  */
29
29
  export declare function snapshotFromTxMeta(txMeta: any): any;
30
30
  /**
31
31
  * Returns processing time for an STX in seconds.
32
- * @param {number} smartTransactionSubmittedtime
33
- * @returns {number} Processing time in seconds.
32
+ * @param smartTransactionSubmittedtime
33
+ * @returns Processing time in seconds.
34
34
  */
35
35
  export declare const getStxProcessingTime: (smartTransactionSubmittedtime: number | undefined) => number | undefined;
36
36
  export declare const mapKeysToCamel: (obj: Record<string, any>) => Record<string, any>;
package/dist/utils.js CHANGED
@@ -45,7 +45,7 @@ function getAPIRequestURL(apiType, chainId) {
45
45
  }
46
46
  exports.getAPIRequestURL = getAPIRequestURL;
47
47
  const calculateStatus = (stxStatus) => {
48
- if (exports.isSmartTransactionStatusResolved(stxStatus)) {
48
+ if ((0, exports.isSmartTransactionStatusResolved)(stxStatus)) {
49
49
  return types_1.SmartTransactionStatuses.RESOLVED;
50
50
  }
51
51
  const cancellations = [
@@ -91,10 +91,10 @@ exports.calculateStatus = calculateStatus;
91
91
  path (the key and if a nested object then each key will be separated with a `/`)
92
92
  value
93
93
  with the first entry having the note and a timestamp when the change took place
94
- @param {Object} previousState - the previous state of the object
95
- @param {Object} newState - the update object
96
- @param {string} [note] - a optional note for the state change
97
- @returns {Array}
94
+ @param previousState - the previous state of the object
95
+ @param newState - the update object
96
+ @param [note] - a optional note for the state change
97
+ @returns
98
98
  */
99
99
  function generateHistoryEntry(previousState, newState, note) {
100
100
  const entry = fast_json_patch_1.default.compare(previousState, newState);
@@ -110,7 +110,7 @@ function generateHistoryEntry(previousState, newState, note) {
110
110
  exports.generateHistoryEntry = generateHistoryEntry;
111
111
  /**
112
112
  Recovers previous txMeta state obj
113
- @returns {Object}
113
+ @returns
114
114
  */
115
115
  function replayHistory(_shortHistory) {
116
116
  const shortHistory = lodash_1.default.cloneDeep(_shortHistory);
@@ -119,8 +119,8 @@ function replayHistory(_shortHistory) {
119
119
  exports.replayHistory = replayHistory;
120
120
  /**
121
121
  * Snapshot {@code txMeta}
122
- * @param {Object} txMeta - the tx metadata object
123
- * @returns {Object} a deep clone without history
122
+ * @param txMeta - the tx metadata object
123
+ * @returns a deep clone without history
124
124
  */
125
125
  function snapshotFromTxMeta(txMeta) {
126
126
  const shallow = Object.assign({}, txMeta);
@@ -130,8 +130,8 @@ function snapshotFromTxMeta(txMeta) {
130
130
  exports.snapshotFromTxMeta = snapshotFromTxMeta;
131
131
  /**
132
132
  * Returns processing time for an STX in seconds.
133
- * @param {number} smartTransactionSubmittedtime
134
- * @returns {number} Processing time in seconds.
133
+ * @param smartTransactionSubmittedtime
134
+ * @returns Processing time in seconds.
135
135
  */
136
136
  const getStxProcessingTime = (smartTransactionSubmittedtime) => {
137
137
  if (!smartTransactionSubmittedtime) {
@@ -149,7 +149,7 @@ const mapKeysToCamel = (obj) => {
149
149
  return val.map(exports.mapKeysToCamel);
150
150
  }
151
151
  else if (lodash_1.default.isObject(val)) {
152
- return exports.mapKeysToCamel(val);
152
+ return (0, exports.mapKeysToCamel)(val);
153
153
  }
154
154
  return val;
155
155
  });
@@ -162,7 +162,7 @@ async function handleFetch(request, options) {
162
162
  const json = await response.json();
163
163
  if (!response.ok) {
164
164
  console.log(`response`, response);
165
- throw new Error(`Fetch error:${JSON.stringify(Object.assign({ status: response.status }, exports.mapKeysToCamel(json)))}`);
165
+ throw new Error(`Fetch error:${JSON.stringify(Object.assign({ status: response.status }, (0, exports.mapKeysToCamel)(json)))}`);
166
166
  }
167
167
  return json;
168
168
  }
@@ -176,7 +176,7 @@ const isSmartTransactionCancellable = (stxStatus) => {
176
176
  exports.isSmartTransactionCancellable = isSmartTransactionCancellable;
177
177
  const incrementNonceInHex = (nonceInHex) => {
178
178
  const nonceInDec = new bignumber_js_1.BigNumber(nonceInHex, 16).toString(10);
179
- return bytes_1.hexlify(Number(nonceInDec) + 1);
179
+ return (0, bytes_1.hexlify)(Number(nonceInDec) + 1);
180
180
  };
181
181
  exports.incrementNonceInHex = incrementNonceInHex;
182
182
  //# 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,oDAAuB;AACvB,+CAAyC;AACzC,gDAA+C;AAC/C,mCAQiB;AACjB,2CAA2C;AAE3C,SAAgB,yBAAyB,CAAC,gBAAkC;IAC1E,OAAO,gBAAgB,CAAC,MAAM,KAAK,gCAAwB,CAAC,OAAO,CAAC;AACtE,CAAC;AAFD,8DAEC;AAEM,MAAM,gCAAg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AA6B,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,eAAO,CAAC,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';\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`;\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 {Object} previousState - the previous state of the object\n @param {Object} newState - the update object\n @param {string} [note] - a optional note for the state change\n @returns {Array}\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 {Object}\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 {Object} txMeta - the tx metadata object\n * @returns {Object} 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 {number} smartTransactionSubmittedtime\n * @returns {number} 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,sEAAyC;AACzC,oDAAuB;AACvB,+CAAyC;AACzC,gDAA+C;AAC/C,mCAQiB;AACjB,2CAA2C;AAE3C,SAAgB,yBAAyB,CAAC,gBAAkC;IAC1E,OAAO,gBAAgB,CAAC,MAAM,KAAK,gCAAwB,CAAC,OAAO,CAAC;AACtE,CAAC;AAFD,8DAEC;AAEM,MAAM,gCAAgC,GAAG,CAC9C,SAA2C,EAC3C,EAAE,CAAC,SAAS,KAAK,gBAAgB,CAAC;AAFvB,QAAA,gCAAgC,oCAET;AAEpC,0CAA0C;AAC1C,SAAgB,gBAAgB,CAAC,OAAgB,EAAE,OAAe;IAChE,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACzC,QAAQ,OAAO,EAAE;QACf,KAAK,eAAO,CAAC,QAAQ,CAAC,CAAC;YACrB,OAAO,GAAG,wBAAY,aAAa,UAAU,UAAU,CAAC;SACzD;QAED,KAAK,eAAO,CAAC,YAAY,CAAC,CAAC;YACzB,OAAO,GAAG,wBAAY,aAAa,UAAU,cAAc,CAAC;SAC7D;QAED,KAAK,eAAO,CAAC,mBAAmB,CAAC,CAAC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G,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';\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`;\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"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@metamask/smart-transactions-controller",
3
- "version": "3.0.0",
4
- "description": "MetaMask controller for Smart Transactions.",
3
+ "version": "4.0.0",
4
+ "description": "Improves success rates for swaps by trialing transactions privately and finding minimum fees",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/MetaMask/smart-transactions-controller.git"
@@ -13,56 +13,58 @@
13
13
  "dist/"
14
14
  ],
15
15
  "scripts": {
16
- "setup": "yarn install && yarn allow-scripts",
17
- "test": "jest",
18
- "test:watch": "jest --watchAll",
19
- "prepublishOnly": "yarn build:clean && yarn lint && yarn test",
20
- "lint:eslint": "eslint . --cache --ext js,ts",
21
- "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' --ignore-path .gitignore",
16
+ "build": "tsc --project .",
17
+ "build:clean": "rm -rf dist && yarn build",
18
+ "build:link": "yarn build && cd dist && yarn link && rm -rf node_modules && cd ..",
22
19
  "lint": "yarn lint:eslint && yarn lint:misc --check",
20
+ "lint:eslint": "eslint . --cache --ext js,ts",
23
21
  "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write",
24
- "build:clean": "rimraf dist && yarn build",
25
- "build": "tsc --project .",
26
- "build:link": "yarn build && cd dist && yarn link && rm -rf node_modules && cd .."
22
+ "lint:misc": "prettier '**/*.json' '**/*.md' '!CHANGELOG.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore",
23
+ "prepack": "./scripts/prepack.sh",
24
+ "test": "jest",
25
+ "test:watch": "jest --watchAll"
27
26
  },
28
27
  "dependencies": {
29
28
  "@ethersproject/bignumber": "^5.7.0",
30
29
  "@ethersproject/bytes": "^5.7.0",
31
30
  "@ethersproject/providers": "^5.7.0",
32
- "@metamask/controllers": "^32.0.2",
33
- "@types/lodash": "^4.14.176",
31
+ "@metamask/base-controller": "^3.0.0",
32
+ "@metamask/controller-utils": "^4.1.0",
33
+ "@metamask/network-controller": "^10.3.0",
34
34
  "bignumber.js": "^9.0.1",
35
35
  "fast-json-patch": "^3.1.0",
36
- "isomorphic-fetch": "^3.0.0",
37
36
  "lodash": "^4.17.21"
38
37
  },
39
38
  "devDependencies": {
40
- "@lavamoat/allow-scripts": "^1.0.5",
41
- "@metamask/auto-changelog": "^3.0.0",
42
- "@metamask/eslint-config": "^8.0.0",
43
- "@metamask/eslint-config-jest": "^8.0.0",
44
- "@metamask/eslint-config-nodejs": "^9.0.0",
45
- "@metamask/eslint-config-typescript": "^8.0.0",
46
- "@types/jest": "^26.0.13",
47
- "@types/node": "^16.7.8",
48
- "@typescript-eslint/eslint-plugin": "^4.21.0",
49
- "@typescript-eslint/parser": "^4.21.0",
50
- "eslint": "^7.23.0",
51
- "eslint-config-prettier": "^8.1.0",
52
- "eslint-plugin-import": "^2.22.1",
53
- "eslint-plugin-jest": "^24.3.4",
39
+ "@lavamoat/allow-scripts": "^2.3.1",
40
+ "@metamask/auto-changelog": "^3.1.0",
41
+ "@metamask/eslint-config": "^10.0.0",
42
+ "@metamask/eslint-config-jest": "^10.0.0",
43
+ "@metamask/eslint-config-nodejs": "^10.0.0",
44
+ "@metamask/eslint-config-typescript": "^10.0.0",
45
+ "@types/jest": "^26.0.24",
46
+ "@types/lodash": "^4.14.194",
47
+ "@types/node": "^16.18.31",
48
+ "@typescript-eslint/eslint-plugin": "^5.33.0",
49
+ "@typescript-eslint/parser": "^5.33.0",
50
+ "eslint": "^8.21.0",
51
+ "eslint-config-prettier": "^8.8.0",
52
+ "eslint-plugin-import": "^2.27.5",
53
+ "eslint-plugin-jest": "^26.8.2",
54
+ "eslint-plugin-jsdoc": "^39.2.9",
54
55
  "eslint-plugin-node": "^11.1.0",
55
- "eslint-plugin-prettier": "^3.3.1",
56
+ "eslint-plugin-prettier": "^4.2.1",
57
+ "isomorphic-fetch": "^3.0.0",
56
58
  "jest": "^26.4.2",
57
- "nock": "^13.1.3",
58
- "prettier": "^2.2.1",
59
- "prettier-plugin-packagejson": "^2.2.11",
60
- "rimraf": "^3.0.2",
61
- "ts-jest": "^26.3.0",
62
- "typescript": "^4.2.4"
59
+ "nock": "^13.3.1",
60
+ "prettier": "^2.8.8",
61
+ "prettier-plugin-packagejson": "^2.4.3",
62
+ "ts-jest": "^26.5.6",
63
+ "typescript": "~4.4.4"
63
64
  },
65
+ "packageManager": "yarn@3.2.1",
64
66
  "engines": {
65
- "node": ">=14.0.0"
67
+ "node": ">=16.0.0"
66
68
  },
67
69
  "publishConfig": {
68
70
  "access": "public",
@@ -71,9 +73,9 @@
71
73
  "lavamoat": {
72
74
  "allowScripts": {
73
75
  "@lavamoat/preinstall-always-fail": false,
74
- "keccak": false,
75
- "secp256k1": false,
76
- "core-js": false
76
+ "@metamask/controller-utils>ethereumjs-util>ethereum-cryptography>keccak": false,
77
+ "@metamask/controller-utils>ethereumjs-util>ethereum-cryptography>secp256k1": false,
78
+ "@metamask/controller-utils>babel-runtime>core-js": false
77
79
  }
78
80
  }
79
- }
81
+ }