@metamask-previews/smart-transactions-controller 19.2.1-preview-54c655a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +715 -0
  2. package/LICENSE +18 -0
  3. package/README.md +103 -0
  4. package/dist/SmartTransactionsController.cjs +694 -0
  5. package/dist/SmartTransactionsController.cjs.map +1 -0
  6. package/dist/SmartTransactionsController.d.cts +150 -0
  7. package/dist/SmartTransactionsController.d.cts.map +1 -0
  8. package/dist/SmartTransactionsController.d.mts +150 -0
  9. package/dist/SmartTransactionsController.d.mts.map +1 -0
  10. package/dist/SmartTransactionsController.mjs +702 -0
  11. package/dist/SmartTransactionsController.mjs.map +1 -0
  12. package/dist/constants.cjs +33 -0
  13. package/dist/constants.cjs.map +1 -0
  14. package/dist/constants.d.cts +23 -0
  15. package/dist/constants.d.cts.map +1 -0
  16. package/dist/constants.d.mts +23 -0
  17. package/dist/constants.d.mts.map +1 -0
  18. package/dist/constants.mjs +33 -0
  19. package/dist/constants.mjs.map +1 -0
  20. package/dist/index.cjs +17 -0
  21. package/dist/index.cjs.map +1 -0
  22. package/dist/index.d.cts +6 -0
  23. package/dist/index.d.cts.map +1 -0
  24. package/dist/index.d.mts +6 -0
  25. package/dist/index.d.mts.map +1 -0
  26. package/dist/index.mjs +17 -0
  27. package/dist/index.mjs.map +1 -0
  28. package/dist/types.cjs +54 -0
  29. package/dist/types.cjs.map +1 -0
  30. package/dist/types.d.cts +118 -0
  31. package/dist/types.d.cts.map +1 -0
  32. package/dist/types.d.mts +118 -0
  33. package/dist/types.d.mts.map +1 -0
  34. package/dist/types.mjs +54 -0
  35. package/dist/types.mjs.map +1 -0
  36. package/dist/utils.cjs +281 -0
  37. package/dist/utils.cjs.map +1 -0
  38. package/dist/utils.d.cts +90 -0
  39. package/dist/utils.d.cts.map +1 -0
  40. package/dist/utils.d.mts +90 -0
  41. package/dist/utils.d.mts.map +1 -0
  42. package/dist/utils.mjs +289 -0
  43. package/dist/utils.mjs.map +1 -0
  44. package/package.json +135 -0
@@ -0,0 +1,90 @@
1
+ import type { TransactionControllerGetTransactionsAction, TransactionControllerUpdateTransactionAction } from "@metamask/transaction-controller";
2
+ import type { SmartTransaction, SmartTransactionsStatus, FeatureFlags } from "./types.mjs";
3
+ import { APIType, SmartTransactionStatuses, ClientId } from "./types.mjs";
4
+ export declare function isSmartTransactionPending(smartTransaction: SmartTransaction): boolean;
5
+ export declare const isSmartTransactionStatusResolved: (stxStatus: SmartTransactionsStatus | string) => boolean;
6
+ export declare function getAPIRequestURL(apiType: APIType, chainId: string): string;
7
+ export declare const calculateStatus: (stxStatus: SmartTransactionsStatus) => SmartTransactionStatuses;
8
+ /**
9
+ Generates an array of history objects sense the previous state.
10
+ The object has the keys
11
+ op (the operation performed),
12
+ path (the key and if a nested object then each key will be separated with a `/`)
13
+ value
14
+ with the first entry having the note and a timestamp when the change took place
15
+ @param previousState - the previous state of the object
16
+ @param newState - the update object
17
+ @param [note] - a optional note for the state change
18
+ @returns
19
+ */
20
+ export declare function generateHistoryEntry(previousState: any, newState: any, note: string): any;
21
+ /**
22
+ Recovers previous txMeta state obj
23
+ @returns
24
+ */
25
+ export declare function replayHistory(_shortHistory: any): any;
26
+ /**
27
+ * Snapshot {@code txMeta}
28
+ * @param txMeta - the tx metadata object
29
+ * @returns a deep clone without history
30
+ */
31
+ export declare function snapshotFromTxMeta(txMeta: any): any;
32
+ /**
33
+ * Returns processing time for an STX in seconds.
34
+ * @param smartTransactionSubmittedtime
35
+ * @returns Processing time in seconds.
36
+ */
37
+ export declare const getStxProcessingTime: (smartTransactionSubmittedtime: number | undefined) => number | undefined;
38
+ export declare const mapKeysToCamel: (obj: Record<string, any>) => Record<string, any>;
39
+ export declare function handleFetch(request: string, options?: RequestInit): Promise<any>;
40
+ export declare const isSmartTransactionCancellable: (stxStatus: SmartTransactionsStatus) => boolean;
41
+ export declare const incrementNonceInHex: (nonceInHex: string) => string;
42
+ export declare const getTxHash: (signedTxHex: any) => string;
43
+ export declare const getSmartTransactionMetricsProperties: (smartTransaction: SmartTransaction) => {
44
+ stx_status?: undefined;
45
+ type?: undefined;
46
+ processing_time?: undefined;
47
+ is_smart_transaction?: undefined;
48
+ stx_enabled?: undefined;
49
+ current_stx_enabled?: undefined;
50
+ stx_user_opt_in?: undefined;
51
+ stx_duplicated?: undefined;
52
+ stx_timed_out?: undefined;
53
+ stx_proxied?: undefined;
54
+ } | {
55
+ stx_status: string | undefined;
56
+ type: string | undefined;
57
+ processing_time: number | undefined;
58
+ is_smart_transaction: boolean;
59
+ stx_enabled: boolean;
60
+ current_stx_enabled: boolean;
61
+ stx_user_opt_in: boolean;
62
+ stx_duplicated: boolean | undefined;
63
+ stx_timed_out: boolean | undefined;
64
+ stx_proxied: boolean | undefined;
65
+ };
66
+ export declare const getSmartTransactionMetricsSensitiveProperties: (smartTransaction: SmartTransaction) => {
67
+ token_from_symbol?: undefined;
68
+ token_to_symbol?: undefined;
69
+ account_hardware_type?: undefined;
70
+ account_type?: undefined;
71
+ device_model?: undefined;
72
+ } | {
73
+ token_from_symbol: string | undefined;
74
+ token_to_symbol: string | undefined;
75
+ account_hardware_type: string | undefined;
76
+ account_type: string | undefined;
77
+ device_model: string | undefined;
78
+ };
79
+ export declare const getReturnTxHashAsap: (clientId: ClientId, smartTransactionsFeatureFlags: FeatureFlags['smartTransactions']) => boolean | undefined;
80
+ export declare const shouldMarkRegularTransactionAsFailed: ({ smartTransaction, clientId, getFeatureFlags, }: {
81
+ smartTransaction: SmartTransaction;
82
+ clientId: ClientId;
83
+ getFeatureFlags: () => FeatureFlags;
84
+ }) => boolean;
85
+ export declare const markRegularTransactionAsFailed: ({ smartTransaction, getRegularTransactions, updateTransaction, }: {
86
+ smartTransaction: SmartTransaction;
87
+ getRegularTransactions: TransactionControllerGetTransactionsAction['handler'];
88
+ updateTransaction: TransactionControllerUpdateTransactionAction['handler'];
89
+ }) => void;
90
+ //# sourceMappingUR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AM,SAAS,gBAAiB,GAAG,WAazC,CAAC;AAEF,eAAO,MAAM,oCAAoC,qBAC7B,gBAAgB;;;;;;;;;;;;;;;;;;;;;;CAkBnC,CAAC;AAEF,eAAO,MAAM,6CAA6C,qBACtC,gBAAgB;;;;;;;;;;;;CAYnC,CAAC;AAEF,eAAO,MAAM,mBAAmB,aACpB,QAAQ,iCACa,YAAY,CAAC,mBAAmB,CAAC,wBAKjE,CAAC;AAEF,eAAO,MAAM,oCAAoC;sBAK7B,gBAAgB;cACxB,QAAQ;qBACD,MAAM,YAAY;MACjC,OAqBH,CAAC;AAEF,eAAO,MAAM,8BAA8B;sBAKvB,gBAAgB;4BACV,0CAA0C,CAAC,SAAS,CAAC;uBAC1D,4CAA4C,CAAC,SAAS,CAAC;UAqB3E,CAAC"}
package/dist/utils.mjs ADDED
@@ -0,0 +1,289 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.markRegularTransactionAsFailed = exports.shouldMarkRegularTransactionAsFailed = exports.getReturnTxHashAsap = exports.getSmartTransactionMetricsSensitiveProperties = exports.getSmartTransactionMetricsProperties = exports.getTxHash = exports.incrementNonceInHex = exports.isSmartTransactionCancellable = exports.handleFetch = exports.mapKeysToCamel = exports.getStxProcessingTime = exports.snapshotFromTxMeta = exports.replayHistory = exports.generateHistoryEntry = exports.calculateStatus = exports.getAPIRequestURL = exports.isSmartTransactionStatusResolved = exports.isSmartTransactionPending = void 0;
7
+ function $importDefault(module) {
8
+ if (module === null || module === void 0 ? void 0 : module.__esModule) {
9
+ return module.default;
10
+ }
11
+ return module;
12
+ }
13
+ const bytes_1 = require("@ethersproject/bytes");
14
+ const keccak256_1 = require("@ethersproject/keccak256");
15
+ const transactions_1 = require("@ethersproject/transactions");
16
+ const transaction_controller_1 = require("@metamask/transaction-controller");
17
+ const bignumber_js_1 = require("bignumber.js");
18
+ const fast_json_patch_1 = __importDefault(require("fast-json-patch"));
19
+ const jsonDiffer = $importDefault($jsonDiffer);
20
+ const lodash_1 = __importDefault(require("lodash"));
21
+ const _ = $importDefault($_);
22
+ // Ignoring TypeScript errors here because this import is disallowed for production builds, because
23
+ // the `package.json` file is above the root directory.
24
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
25
+ // @ts-ignore
26
+ const package_json_1 = __importDefault(require("../package.json"));
27
+ const constants_1 = require("./constants.mjs");
28
+ const types_1 = require("./types.mjs");
29
+ function isSmartTransactionPending(smartTransaction) {
30
+ return smartTransaction.status === types_1.SmartTransactionStatuses.PENDING;
31
+ }
32
+ exports.isSmartTransactionPending = isSmartTransactionPending;
33
+ const isSmartTransactionStatusResolved = (stxStatus) => stxStatus === 'uuid_not_found';
34
+ exports.isSmartTransactionStatusResolved = isSmartTransactionStatusResolved;
35
+ // TODO use actual url once API is defined
36
+ function getAPIRequestURL(apiType, chainId) {
37
+ const chainIdDec = parseInt(chainId, 16);
38
+ switch (apiType) {
39
+ case types_1.APIType.GET_FEES: {
40
+ return `${constants_1.API_BASE_URL}/networks/${chainIdDec}/getFees`;
41
+ }
42
+ case types_1.APIType.ESTIMATE_GAS: {
43
+ return `${constants_1.API_BASE_URL}/networks/${chainIdDec}/estimateGas`;
44
+ }
45
+ case types_1.APIType.SUBMIT_TRANSACTIONS: {
46
+ return `${constants_1.API_BASE_URL}/networks/${chainIdDec}/submitTransactions?stxControllerVersion=${package_json_1.default.version}`;
47
+ }
48
+ case types_1.APIType.CANCEL: {
49
+ return `${constants_1.API_BASE_URL}/networks/${chainIdDec}/cancel`;
50
+ }
51
+ case types_1.APIType.BATCH_STATUS: {
52
+ return `${constants_1.API_BASE_URL}/networks/${chainIdDec}/batchStatus`;
53
+ }
54
+ case types_1.APIType.LIVENESS: {
55
+ return `${constants_1.SENTINEL_API_BASE_URL_MAP[chainIdDec]}/network`;
56
+ }
57
+ default: {
58
+ throw new Error(`Invalid APIType`); // It can never get here thanks to TypeScript.
59
+ }
60
+ }
61
+ }
62
+ exports.getAPIRequestURL = getAPIRequestURL;
63
+ const calculateStatus = (stxStatus) => {
64
+ if ((0, exports.isSmartTransactionStatusResolved)(stxStatus)) {
65
+ return types_1.SmartTransactionStatuses.RESOLVED;
66
+ }
67
+ const cancellations = [
68
+ types_1.SmartTransactionCancellationReason.WOULD_REVERT,
69
+ types_1.SmartTransactionCancellationReason.TOO_CHEAP,
70
+ types_1.SmartTransactionCancellationReason.DEADLINE_MISSED,
71
+ types_1.SmartTransactionCancellationReason.INVALID_NONCE,
72
+ types_1.SmartTransactionCancellationReason.USER_CANCELLED,
73
+ ];
74
+ if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === types_1.SmartTransactionMinedTx.NOT_MINED) {
75
+ if (stxStatus.cancellationReason ===
76
+ types_1.SmartTransactionCancellationReason.NOT_CANCELLED) {
77
+ return types_1.SmartTransactionStatuses.PENDING;
78
+ }
79
+ const isCancellation = cancellations.findIndex((cancellation) => cancellation === stxStatus.cancellationReason) > -1;
80
+ if (stxStatus.cancellationReason && isCancellation) {
81
+ if (!stxStatus.isSettled) {
82
+ return types_1.SmartTransactionStatuses.PENDING;
83
+ }
84
+ return types_1.cancellationReasonToStatusMap[stxStatus.cancellationReason];
85
+ }
86
+ }
87
+ else if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === types_1.SmartTransactionMinedTx.SUCCESS) {
88
+ return types_1.SmartTransactionStatuses.SUCCESS;
89
+ }
90
+ else if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === types_1.SmartTransactionMinedTx.CANCELLED) {
91
+ return types_1.SmartTransactionStatuses.CANCELLED;
92
+ }
93
+ else if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === types_1.SmartTransactionMinedTx.REVERTED) {
94
+ return types_1.SmartTransactionStatuses.REVERTED;
95
+ }
96
+ else if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === types_1.SmartTransactionMinedTx.UNKNOWN) {
97
+ return types_1.SmartTransactionStatuses.UNKNOWN;
98
+ }
99
+ return types_1.SmartTransactionStatuses.UNKNOWN;
100
+ };
101
+ exports.calculateStatus = calculateStatus;
102
+ /**
103
+ Generates an array of history objects sense the previous state.
104
+ The object has the keys
105
+ op (the operation performed),
106
+ path (the key and if a nested object then each key will be separated with a `/`)
107
+ value
108
+ with the first entry having the note and a timestamp when the change took place
109
+ @param previousState - the previous state of the object
110
+ @param newState - the update object
111
+ @param [note] - a optional note for the state change
112
+ @returns
113
+ */
114
+ function generateHistoryEntry(previousState, newState, note) {
115
+ const entry = fast_json_patch_1.default.compare(previousState, newState);
116
+ // Add a note to the first op, since it breaks if we append it to the entry
117
+ if (entry[0]) {
118
+ if (note) {
119
+ entry[0].note = note;
120
+ }
121
+ entry[0].timestamp = Date.now();
122
+ }
123
+ return entry;
124
+ }
125
+ exports.generateHistoryEntry = generateHistoryEntry;
126
+ /**
127
+ Recovers previous txMeta state obj
128
+ @returns
129
+ */
130
+ function replayHistory(_shortHistory) {
131
+ const shortHistory = lodash_1.default.cloneDeep(_shortHistory);
132
+ return shortHistory.reduce((val, entry) => fast_json_patch_1.default.applyPatch(val, entry).newDocument);
133
+ }
134
+ exports.replayHistory = replayHistory;
135
+ /**
136
+ * Snapshot {@code txMeta}
137
+ * @param txMeta - the tx metadata object
138
+ * @returns a deep clone without history
139
+ */
140
+ function snapshotFromTxMeta(txMeta) {
141
+ const shallow = Object.assign({}, txMeta);
142
+ delete shallow.history;
143
+ return lodash_1.default.cloneDeep(shallow);
144
+ }
145
+ exports.snapshotFromTxMeta = snapshotFromTxMeta;
146
+ /**
147
+ * Returns processing time for an STX in seconds.
148
+ * @param smartTransactionSubmittedtime
149
+ * @returns Processing time in seconds.
150
+ */
151
+ const getStxProcessingTime = (smartTransactionSubmittedtime) => {
152
+ if (!smartTransactionSubmittedtime) {
153
+ return undefined;
154
+ }
155
+ return Math.round((Date.now() - smartTransactionSubmittedtime) / 1000);
156
+ };
157
+ exports.getStxProcessingTime = getStxProcessingTime;
158
+ const mapKeysToCamel = (obj) => {
159
+ if (!lodash_1.default.isObject(obj)) {
160
+ return obj;
161
+ }
162
+ const mappedValues = lodash_1.default.mapValues(obj, (val) => {
163
+ if (lodash_1.default.isArray(val)) {
164
+ return val.map(exports.mapKeysToCamel);
165
+ }
166
+ else if (lodash_1.default.isObject(val)) {
167
+ return (0, exports.mapKeysToCamel)(val);
168
+ }
169
+ return val;
170
+ });
171
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
172
+ return lodash_1.default.mapKeys(mappedValues, (value, key) => lodash_1.default.camelCase(key));
173
+ };
174
+ exports.mapKeysToCamel = mapKeysToCamel;
175
+ async function handleFetch(request, options) {
176
+ const response = await fetch(request, options);
177
+ const json = await response.json();
178
+ if (!response.ok) {
179
+ console.log(`response`, response);
180
+ throw new Error(`Fetch error:${JSON.stringify(Object.assign({ status: response.status }, (0, exports.mapKeysToCamel)(json)))}`);
181
+ }
182
+ return json;
183
+ }
184
+ exports.handleFetch = handleFetch;
185
+ const isSmartTransactionCancellable = (stxStatus) => {
186
+ return (stxStatus.minedTx === types_1.SmartTransactionMinedTx.NOT_MINED &&
187
+ (!stxStatus.cancellationReason ||
188
+ stxStatus.cancellationReason ===
189
+ types_1.SmartTransactionCancellationReason.NOT_CANCELLED));
190
+ };
191
+ exports.isSmartTransactionCancellable = isSmartTransactionCancellable;
192
+ const incrementNonceInHex = (nonceInHex) => {
193
+ const nonceInDec = new bignumber_js_1.BigNumber(nonceInHex, 16).toString(10);
194
+ return (0, bytes_1.hexlify)(Number(nonceInDec) + 1);
195
+ };
196
+ exports.incrementNonceInHex = incrementNonceInHex;
197
+ const isType4Transaction = (signedTxHex) => {
198
+ return typeof signedTxHex === 'string' && signedTxHex.startsWith('0x04');
199
+ };
200
+ const getTxHash = (signedTxHex) => {
201
+ var _a;
202
+ if (!signedTxHex) {
203
+ return '';
204
+ }
205
+ try {
206
+ const parsed = (0, transactions_1.parse)(signedTxHex);
207
+ return (_a = parsed === null || parsed === void 0 ? void 0 : parsed.hash) !== null && _a !== void 0 ? _a : '';
208
+ }
209
+ catch (error) {
210
+ if (isType4Transaction(signedTxHex)) {
211
+ return (0, bytes_1.hexlify)((0, keccak256_1.keccak256)((0, bytes_1.arrayify)(signedTxHex)));
212
+ }
213
+ throw error;
214
+ }
215
+ };
216
+ exports.getTxHash = getTxHash;
217
+ const getSmartTransactionMetricsProperties = (smartTransaction) => {
218
+ if (!smartTransaction) {
219
+ return {};
220
+ }
221
+ const smartTransactionStatusMetadata = smartTransaction.statusMetadata;
222
+ return {
223
+ stx_status: smartTransaction.status,
224
+ type: smartTransaction.type,
225
+ processing_time: (0, exports.getStxProcessingTime)(smartTransaction.time),
226
+ is_smart_transaction: true,
227
+ stx_enabled: true,
228
+ current_stx_enabled: true,
229
+ stx_user_opt_in: true,
230
+ stx_duplicated: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.duplicated,
231
+ stx_timed_out: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.timedOut,
232
+ stx_proxied: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.proxied,
233
+ };
234
+ };
235
+ exports.getSmartTransactionMetricsProperties = getSmartTransactionMetricsProperties;
236
+ const getSmartTransactionMetricsSensitiveProperties = (smartTransaction) => {
237
+ if (!smartTransaction) {
238
+ return {};
239
+ }
240
+ return {
241
+ token_from_symbol: smartTransaction.sourceTokenSymbol,
242
+ token_to_symbol: smartTransaction.destinationTokenSymbol,
243
+ account_hardware_type: smartTransaction.accountHardwareType,
244
+ account_type: smartTransaction.accountType,
245
+ device_model: smartTransaction.deviceModel,
246
+ };
247
+ };
248
+ exports.getSmartTransactionMetricsSensitiveProperties = getSmartTransactionMetricsSensitiveProperties;
249
+ const getReturnTxHashAsap = (clientId, smartTransactionsFeatureFlags) => {
250
+ return clientId === types_1.ClientId.Extension
251
+ ? smartTransactionsFeatureFlags === null || smartTransactionsFeatureFlags === void 0 ? void 0 : smartTransactionsFeatureFlags.extensionReturnTxHashAsap
252
+ : smartTransactionsFeatureFlags === null || smartTransactionsFeatureFlags === void 0 ? void 0 : smartTransactionsFeatureFlags.mobileReturnTxHashAsap;
253
+ };
254
+ exports.getReturnTxHashAsap = getReturnTxHashAsap;
255
+ const shouldMarkRegularTransactionAsFailed = ({ smartTransaction, clientId, getFeatureFlags, }) => {
256
+ var _a;
257
+ const { status, transactionId } = smartTransaction;
258
+ const failureStatuses = [
259
+ types_1.SmartTransactionStatuses.CANCELLED,
260
+ types_1.SmartTransactionStatuses.CANCELLED_USER_CANCELLED,
261
+ types_1.SmartTransactionStatuses.UNKNOWN,
262
+ types_1.SmartTransactionStatuses.RESOLVED,
263
+ ];
264
+ if (!status ||
265
+ !failureStatuses.includes(status)) {
266
+ return false;
267
+ }
268
+ const { smartTransactions: smartTransactionsFeatureFlags } = (_a = getFeatureFlags()) !== null && _a !== void 0 ? _a : {};
269
+ const returnTxHashAsapEnabled = (0, exports.getReturnTxHashAsap)(clientId, smartTransactionsFeatureFlags);
270
+ return Boolean(returnTxHashAsapEnabled && transactionId);
271
+ };
272
+ exports.shouldMarkRegularTransactionAsFailed = shouldMarkRegularTransactionAsFailed;
273
+ const markRegularTransactionAsFailed = ({ smartTransaction, getRegularTransactions, updateTransaction, }) => {
274
+ const { transactionId, status } = smartTransaction;
275
+ const originalTransaction = getRegularTransactions().find((transaction) => transaction.id === transactionId);
276
+ if (!originalTransaction) {
277
+ throw new Error('Cannot find regular transaction to mark it as failed');
278
+ }
279
+ if (originalTransaction.status === transaction_controller_1.TransactionStatus.failed) {
280
+ return; // Already marked as failed.
281
+ }
282
+ const updatedTransaction = Object.assign(Object.assign({}, originalTransaction), { status: transaction_controller_1.TransactionStatus.failed, error: {
283
+ name: 'SmartTransactionFailed',
284
+ message: `Smart transaction failed with status: ${status}`,
285
+ } });
286
+ updateTransaction(updatedTransaction, `Smart transaction status: ${status}`);
287
+ };
288
+ exports.markRegularTransactionAsFailed = markRegularTransactionAsFailed;
289
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,gDAAyD;AACzD,wDAAqD;AACrD,8DAAoD;AAMpD,6EAAqE;AACrE,+CAAyC;AACzC,sEAAyC;;AACzC,oDAAuB;;AAEvB,mGAAmG;AACnG,uDAAuD;AACvD,6DAA6D;AAC7D,aAAa;AACb,mEAA0C;AAC1C,+CAAsE;AAMtE,uCAOiB;AAEjB,SAAgB,yBAAyB,CAAC,gBAAkC;IAC1E,OAAO,gBAAgB,CAAC,MAAM,KAAK,gCAAwB,CAAC,OAAO,CAAC;AACtE,CAAC;AAFD,8DAEC;AAEM,MAAM,gCAAgC,GAAG,CAC9C,SAA2C,EAC3C,EAAE,CAAC,SAAS,KAAK,gBAAgB,CAAC;AAFvB,QAAA,gCAAgC,oCAET;AAEpC,0CAA0C;AAC1C,SAAgB,gBAAgB,CAAC,OAAgB,EAAE,OAAe;IAChE,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACzC,QAAQ,OAAO,EAAE;QACf,KAAK,eAAO,CAAC,QAAQ,CAAC,CAAC;YACrB,OAAO,GAAG,wBAAY,aAAa,UAAU,UAAU,CAAC;SACzD;QAED,KAAK,eAAO,CAAC,YAAY,CAAC,CAAC;YACzB,OAAO,GAAG,wBAAY,aAAa,UAAU,cAAc,CAAC;SAC7D;QAED,KAAK,eAAO,CAAC,mBAAmB,CAAC,CAAC;YAChC,OAAO,GAAG,wBAAY,aAAa,UAAU,4CAA4C,sBAAW,CAAC,OAAO,EAAE,CAAC;SAChH;QAED,KAAK,eAAO,CAAC,MAAM,CAAC,CAAC;Y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AAE,GACxD,MAAA,eAAe,EAAE,mCAAI,EAAE,CAAC;IAC1B,MAAM,uBAAuB,GAAG,IAAA,2BAAmB,EACjD,QAAQ,EACR,6BAA6B,CAC9B,CAAC;IACF,OAAO,OAAO,CAAC,uBAAuB,IAAI,aAAa,CAAC,CAAC;AAC3D,CAAC,CAAC;AA7BW,QAAA,oCAAoC,wCA6B/C;AAEK,MAAM,8BAA8B,GAAG,CAAC,EAC7C,gBAAgB,EAChB,sBAAsB,EACtB,iBAAiB,GAKlB,EAAE,EAAE;IACH,MAAM,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,gBAAgB,CAAC;IACnD,MAAM,mBAAmB,GAAG,sBAAsB,EAAE,CAAC,IAAI,CACvD,CAAC,WAAW,EAAE,EAAE,CAAC,WAAW,CAAC,EAAE,KAAK,aAAa,CAClD,CAAC;IACF,IAAI,CAAC,mBAAmB,EAAE;QACxB,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;KACzE;IACD,IAAI,mBAAmB,CAAC,MAAM,KAAK,0CAAiB,CAAC,MAAM,EAAE;QAC3D,OAAO,CAAC,4BAA4B;KACrC;IACD,MAAM,kBAAkB,mCACnB,mBAAmB,KACtB,MAAM,EAAE,0CAAiB,CAAC,MAAM,EAChC,KAAK,EAAE;YACL,IAAI,EAAE,wBAAwB;YAC9B,OAAO,EAAE,yCAAyC,MAAM,EAAE;SAC3D,GACF,CAAC;IACF,iBAAiB,CAAC,kBAAkB,EAAE,6BAA6B,MAAM,EAAE,CAAC,CAAC;AAC/E,CAAC,CAAC;AA5BW,QAAA,8BAA8B,kCA4BzC","sourcesContent":["import { arrayify, hexlify } from '@ethersproject/bytes';\nimport { keccak256 } from '@ethersproject/keccak256';\nimport { parse } from '@ethersproject/transactions';\nimport type {\n TransactionControllerGetTransactionsAction,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport { TransactionStatus } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\nimport jsonDiffer from 'fast-json-patch';\nimport _ from 'lodash';\n\n// Ignoring TypeScript errors here because this import is disallowed for production builds, because\n// the `package.json` file is above the root directory.\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport packageJson from '../package.json';\nimport { API_BASE_URL, SENTINEL_API_BASE_URL_MAP } from './constants';\nimport type {\n SmartTransaction,\n SmartTransactionsStatus,\n FeatureFlags,\n} from './types';\nimport {\n APIType,\n SmartTransactionStatuses,\n SmartTransactionCancellationReason,\n SmartTransactionMinedTx,\n cancellationReasonToStatusMap,\n ClientId,\n} from './types';\n\nexport function isSmartTransactionPending(smartTransaction: SmartTransaction) {\n return smartTransaction.status === SmartTransactionStatuses.PENDING;\n}\n\nexport const isSmartTransactionStatusResolved = (\n stxStatus: SmartTransactionsStatus | string,\n) => stxStatus === 'uuid_not_found';\n\n// TODO use actual url once API is defined\nexport function getAPIRequestURL(apiType: APIType, chainId: string): string {\n const chainIdDec = parseInt(chainId, 16);\n switch (apiType) {\n case APIType.GET_FEES: {\n return `${API_BASE_URL}/networks/${chainIdDec}/getFees`;\n }\n\n case APIType.ESTIMATE_GAS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/estimateGas`;\n }\n\n case APIType.SUBMIT_TRANSACTIONS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`;\n }\n\n case APIType.CANCEL: {\n return `${API_BASE_URL}/networks/${chainIdDec}/cancel`;\n }\n\n case APIType.BATCH_STATUS: {\n return `${API_BASE_URL}/networks/${chainIdDec}/batchStatus`;\n }\n\n case APIType.LIVENESS: {\n return `${SENTINEL_API_BASE_URL_MAP[chainIdDec]}/network`;\n }\n\n default: {\n throw new Error(`Invalid APIType`); // It can never get here thanks to TypeScript.\n }\n }\n}\n\nexport const calculateStatus = (stxStatus: SmartTransactionsStatus) => {\n if (isSmartTransactionStatusResolved(stxStatus)) {\n return SmartTransactionStatuses.RESOLVED;\n }\n const cancellations = [\n SmartTransactionCancellationReason.WOULD_REVERT,\n SmartTransactionCancellationReason.TOO_CHEAP,\n SmartTransactionCancellationReason.DEADLINE_MISSED,\n SmartTransactionCancellationReason.INVALID_NONCE,\n SmartTransactionCancellationReason.USER_CANCELLED,\n ];\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\nconst isType4Transaction = (signedTxHex: string) => {\n return typeof signedTxHex === 'string' && signedTxHex.startsWith('0x04');\n};\n\nexport const getTxHash = (signedTxHex: any) => {\n if (!signedTxHex) {\n return '';\n }\n try {\n const parsed = parse(signedTxHex);\n return parsed?.hash ?? '';\n } catch (error) {\n if (isType4Transaction(signedTxHex)) {\n return hexlify(keccak256(arrayify(signedTxHex)));\n }\n throw error;\n }\n};\n\nexport const getSmartTransactionMetricsProperties = (\n smartTransaction: SmartTransaction,\n) => {\n if (!smartTransaction) {\n return {};\n }\n const smartTransactionStatusMetadata = smartTransaction.statusMetadata;\n return {\n stx_status: smartTransaction.status,\n type: smartTransaction.type,\n processing_time: getStxProcessingTime(smartTransaction.time),\n is_smart_transaction: true,\n stx_enabled: true,\n current_stx_enabled: true,\n stx_user_opt_in: true,\n stx_duplicated: smartTransactionStatusMetadata?.duplicated,\n stx_timed_out: smartTransactionStatusMetadata?.timedOut,\n stx_proxied: smartTransactionStatusMetadata?.proxied,\n };\n};\n\nexport const getSmartTransactionMetricsSensitiveProperties = (\n smartTransaction: SmartTransaction,\n) => {\n if (!smartTransaction) {\n return {};\n }\n return {\n token_from_symbol: smartTransaction.sourceTokenSymbol,\n token_to_symbol: smartTransaction.destinationTokenSymbol,\n account_hardware_type: smartTransaction.accountHardwareType,\n account_type: smartTransaction.accountType,\n device_model: smartTransaction.deviceModel,\n };\n};\n\nexport const getReturnTxHashAsap = (\n clientId: ClientId,\n smartTransactionsFeatureFlags: FeatureFlags['smartTransactions'],\n) => {\n return clientId === ClientId.Extension\n ? smartTransactionsFeatureFlags?.extensionReturnTxHashAsap\n : smartTransactionsFeatureFlags?.mobileReturnTxHashAsap;\n};\n\nexport const shouldMarkRegularTransactionAsFailed = ({\n smartTransaction,\n clientId,\n getFeatureFlags,\n}: {\n smartTransaction: SmartTransaction;\n clientId: ClientId;\n getFeatureFlags: () => FeatureFlags;\n}): boolean => {\n const { status, transactionId } = smartTransaction;\n const failureStatuses: SmartTransactionStatuses[] = [\n SmartTransactionStatuses.CANCELLED,\n SmartTransactionStatuses.CANCELLED_USER_CANCELLED,\n SmartTransactionStatuses.UNKNOWN,\n SmartTransactionStatuses.RESOLVED,\n ];\n if (\n !status ||\n !failureStatuses.includes(status as SmartTransactionStatuses)\n ) {\n return false;\n }\n const { smartTransactions: smartTransactionsFeatureFlags } =\n getFeatureFlags() ?? {};\n const returnTxHashAsapEnabled = getReturnTxHashAsap(\n clientId,\n smartTransactionsFeatureFlags,\n );\n return Boolean(returnTxHashAsapEnabled && transactionId);\n};\n\nexport const markRegularTransactionAsFailed = ({\n smartTransaction,\n getRegularTransactions,\n updateTransaction,\n}: {\n smartTransaction: SmartTransaction;\n getRegularTransactions: TransactionControllerGetTransactionsAction['handler'];\n updateTransaction: TransactionControllerUpdateTransactionAction['handler'];\n}) => {\n const { transactionId, status } = smartTransaction;\n const originalTransaction = getRegularTransactions().find(\n (transaction) => transaction.id === transactionId,\n );\n if (!originalTransaction) {\n throw new Error('Cannot find regular transaction to mark it as failed');\n }\n if (originalTransaction.status === TransactionStatus.failed) {\n return; // Already marked as failed.\n }\n const updatedTransaction: TransactionMeta = {\n ...originalTransaction,\n status: TransactionStatus.failed,\n error: {\n name: 'SmartTransactionFailed',\n message: `Smart transaction failed with status: ${status}`,\n },\n };\n updateTransaction(updatedTransaction, `Smart transaction status: ${status}`);\n};\n"]}
package/package.json ADDED
@@ -0,0 +1,135 @@
1
+ {
2
+ "name": "@metamask-previews/smart-transactions-controller",
3
+ "version": "19.2.1-preview-54c655a",
4
+ "description": "Improves success rates for swaps by trialing transactions privately and finding minimum fees",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://github.com/MetaMask/smart-transactions-controller.git"
8
+ },
9
+ "license": "SEE LICENSE IN LICENSE",
10
+ "sideEffects": false,
11
+ "exports": {
12
+ ".": {
13
+ "import": {
14
+ "types": "./dist/index.d.mts",
15
+ "default": "./dist/index.mjs"
16
+ },
17
+ "require": {
18
+ "types": "./dist/index.d.cts",
19
+ "default": "./dist/index.cjs"
20
+ }
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "main": "./dist/index.cjs",
25
+ "module": "./dist/index.mjs",
26
+ "types": "./dist/index.d.cts",
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "scripts": {
31
+ "build": "ts-bridge --project tsconfig.build.json --clean",
32
+ "lint": "yarn lint:eslint && yarn lint:misc --check && yarn lint:changelog",
33
+ "lint:changelog": "auto-changelog validate --prettier",
34
+ "lint:eslint": "eslint . --cache --ext js,ts",
35
+ "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write && yarn lint:changelog",
36
+ "lint:misc": "prettier '**/*.json' '**/*.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore --no-error-on-unmatched-pattern",
37
+ "prepack": "./scripts/prepack.sh",
38
+ "test": "jest && attw --pack",
39
+ "test:watch": "jest --watchAll"
40
+ },
41
+ "resolutions": {
42
+ "@metamask/polling-controller": "npm:@metamask-previews/polling-controller@14.0.0-preview-b896289e"
43
+ },
44
+ "dependencies": {
45
+ "@babel/runtime": "^7.24.1",
46
+ "@ethereumjs/tx": "^5.2.1",
47
+ "@ethereumjs/util": "^9.0.2",
48
+ "@ethersproject/bytes": "^5.7.0",
49
+ "@ethersproject/keccak256": "^5.8.0",
50
+ "@ethersproject/transactions": "^5.7.0",
51
+ "@metamask/base-controller": "^8.4.0",
52
+ "@metamask/controller-utils": "^11.0.0",
53
+ "@metamask/eth-json-rpc-provider": "^4.1.6",
54
+ "@metamask/eth-query": "^4.0.0",
55
+ "@metamask/messenger": "^0.3.0",
56
+ "@metamask/polling-controller": "^14.0.0",
57
+ "bignumber.js": "^9.0.1",
58
+ "fast-json-patch": "^3.1.0",
59
+ "lodash": "^4.17.21"
60
+ },
61
+ "devDependencies": {
62
+ "@arethetypeswrong/cli": "^0.18.2",
63
+ "@lavamoat/allow-scripts": "^3.2.1",
64
+ "@lavamoat/preinstall-always-fail": "^2.1.0",
65
+ "@metamask/auto-changelog": "^3.1.0",
66
+ "@metamask/eslint-config": "^12.2.0",
67
+ "@metamask/eslint-config-jest": "^12.1.0",
68
+ "@metamask/eslint-config-nodejs": "^12.1.0",
69
+ "@metamask/eslint-config-typescript": "^12.1.0",
70
+ "@metamask/gas-fee-controller": "^22.0.0",
71
+ "@metamask/json-rpc-engine": "^10.0.1",
72
+ "@metamask/network-controller": "^24.0.0",
73
+ "@metamask/transaction-controller": "^60.4.0",
74
+ "@ts-bridge/cli": "^0.6.3",
75
+ "@types/jest": "^26.0.24",
76
+ "@types/lodash": "^4.14.194",
77
+ "@types/node": "^18.19.17",
78
+ "@types/sinon": "^9.0.10",
79
+ "@typescript-eslint/eslint-plugin": "^5.33.0",
80
+ "@typescript-eslint/parser": "^5.33.0",
81
+ "eslint": "^8.48.0",
82
+ "eslint-config-prettier": "^8.8.0",
83
+ "eslint-plugin-import": "~2.26.0",
84
+ "eslint-plugin-jest": "^27.1.5",
85
+ "eslint-plugin-jsdoc": "^39.2.9",
86
+ "eslint-plugin-n": "^15.7.0",
87
+ "eslint-plugin-prettier": "^4.2.1",
88
+ "eslint-plugin-promise": "^6.1.1",
89
+ "isomorphic-fetch": "^3.0.0",
90
+ "jest": "^29.7.0",
91
+ "nock": "^14.0.0-beta.7",
92
+ "prettier": "^2.8.8",
93
+ "prettier-plugin-packagejson": "^2.4.3",
94
+ "sinon": "^9.2.4",
95
+ "ts-jest": "^29.1.4",
96
+ "typescript": "~4.8.4"
97
+ },
98
+ "peerDependencies": {
99
+ "@metamask/network-controller": "^24.0.0",
100
+ "@metamask/transaction-controller": "^60.4.0"
101
+ },
102
+ "peerDependenciesMeta": {
103
+ "@metamask/accounts-controller": {
104
+ "optional": true
105
+ },
106
+ "@metamask/approval-controller": {
107
+ "optional": true
108
+ },
109
+ "@metamask/eth-block-tracker": {
110
+ "optional": true
111
+ },
112
+ "@metamask/gas-fee-controller": {
113
+ "optional": true
114
+ },
115
+ "@metamask/remote-feature-flag-controller": {
116
+ "optional": true
117
+ }
118
+ },
119
+ "packageManager": "yarn@3.2.1",
120
+ "engines": {
121
+ "node": "^18.18 || >=20"
122
+ },
123
+ "publishConfig": {
124
+ "access": "public",
125
+ "registry": "https://registry.npmjs.org/"
126
+ },
127
+ "lavamoat": {
128
+ "allowScripts": {
129
+ "@lavamoat/preinstall-always-fail": false,
130
+ "@metamask/controller-utils>ethereumjs-util>ethereum-cryptography>keccak": false,
131
+ "@metamask/controller-utils>ethereumjs-util>ethereum-cryptography>secp256k1": false,
132
+ "@metamask/controller-utils>babel-runtime>core-js": false
133
+ }
134
+ }
135
+ }