@metamask/smart-transactions-controller 18.1.0 → 19.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.
Files changed (48) hide show
  1. package/CHANGELOG.md +34 -1
  2. package/dist/{SmartTransactionsController.js → SmartTransactionsController.cjs} +18 -24
  3. package/dist/SmartTransactionsController.cjs.map +1 -0
  4. package/dist/{SmartTransactionsController.d.ts → SmartTransactionsController.d.cts} +17 -20
  5. package/dist/SmartTransactionsController.d.cts.map +1 -0
  6. package/dist/SmartTransactionsController.d.mts +149 -0
  7. package/dist/SmartTransactionsController.d.mts.map +1 -0
  8. package/dist/SmartTransactionsController.mjs +696 -0
  9. package/dist/SmartTransactionsController.mjs.map +1 -0
  10. package/dist/{constants.js → constants.cjs} +1 -1
  11. package/dist/constants.cjs.map +1 -0
  12. package/dist/{constants.d.ts → constants.d.cts} +1 -0
  13. package/dist/constants.d.cts.map +1 -0
  14. package/dist/constants.d.mts +23 -0
  15. package/dist/constants.d.mts.map +1 -0
  16. package/dist/constants.mjs +30 -0
  17. package/dist/constants.mjs.map +1 -0
  18. package/dist/index.cjs +6 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/{index.d.ts → index.d.cts} +3 -2
  21. package/dist/index.d.cts.map +1 -0
  22. package/dist/index.d.mts +3 -0
  23. package/dist/index.d.mts.map +1 -0
  24. package/dist/index.mjs +2 -0
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/{types.js → types.cjs} +1 -1
  27. package/dist/types.cjs.map +1 -0
  28. package/dist/{types.d.ts → types.d.cts} +2 -8
  29. package/dist/types.d.cts.map +1 -0
  30. package/dist/types.d.mts +118 -0
  31. package/dist/types.d.mts.map +1 -0
  32. package/dist/types.mjs +51 -0
  33. package/dist/types.mjs.map +1 -0
  34. package/dist/{utils.js → utils.cjs} +3 -3
  35. package/dist/utils.cjs.map +1 -0
  36. package/dist/{utils.d.ts → utils.d.cts} +6 -5
  37. package/dist/utils.d.cts.map +1 -0
  38. package/dist/utils.d.mts +90 -0
  39. package/dist/utils.d.mts.map +1 -0
  40. package/dist/utils.mjs +265 -0
  41. package/dist/utils.mjs.map +1 -0
  42. package/package.json +37 -15
  43. package/dist/SmartTransactionsController.js.map +0 -1
  44. package/dist/constants.js.map +0 -1
  45. package/dist/index.js +0 -9
  46. package/dist/index.js.map +0 -1
  47. package/dist/types.js.map +0 -1
  48. package/dist/utils.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import type { TransactionMeta } from '@metamask/transaction-controller';
2
- import type { SmartTransaction, SmartTransactionsStatus, FeatureFlags } from './types';
3
- import { APIType, SmartTransactionStatuses, ClientId } from './types';
1
+ import type { TransactionControllerGetTransactionsAction, TransactionControllerUpdateTransactionAction } from "@metamask/transaction-controller";
2
+ import type { SmartTransaction, SmartTransactionsStatus, FeatureFlags } from "./types.cjs";
3
+ import { APIType, SmartTransactionStatuses, ClientId } from "./types.cjs";
4
4
  export declare function isSmartTransactionPending(smartTransaction: SmartTransaction): boolean;
5
5
  export declare const isSmartTransactionStatusResolved: (stxStatus: SmartTransactionsStatus | string) => boolean;
6
6
  export declare function getAPIRequestURL(apiType: APIType, chainId: string): string;
@@ -84,6 +84,7 @@ export declare const shouldMarkRegularTransactionAsFailed: ({ smartTransaction,
84
84
  }) => boolean;
85
85
  export declare const markRegularTransactionAsFailed: ({ smartTransaction, getRegularTransactions, updateTransaction, }: {
86
86
  smartTransaction: SmartTransaction;
87
- getRegularTransactions: () => TransactionMeta[];
88
- updateTransaction: (transaction: TransactionMeta, note: string) => void;
87
+ getRegularTransactions: TransactionControllerGetTransactionsAction['handler'];
88
+ updateTransaction: TransactionControllerUpdateTransactionAction['handler'];
89
89
  }) => void;
90
+ //# sourceMappingURL=utils.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,0CAA0C,EAC1C,4CAA4C,EAE7C,y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BAAgB;;;;;;;;;;;;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"}
@@ -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
+ //# sourceMappingURL=utils.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,0CAA0C,EAC1C,4CAA4C,EAE7C,yCAAyC;AAY1C,OAAO,KAAK,EACV,gBAAgB,EAChB,uBAAuB,EACvB,YAAY,EACb,oBAAgB;AACjB,OAAO,EACL,OAAO,EACP,wBAAwB,EAIxB,QAAQ,EACT,oBAAgB;AAEjB,wBAAgB,yBAAyB,CAAC,gBAAgB,EAAE,gBAAgB,WAE3E;AAED,eAAO,MAAM,gCAAgC,cAChC,uBAAuB,GAAG,MAAM,YACV,CAAC;AAGpC,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CA+B1E;AAED,eAAO,MAAM,eAAe,cAAe,uBAAuB,6BAuCjE,CAAC;AAEF;;;;;;;;;;;EAWE;AACF,wBAAgB,oBAAoB,CAClC,aAAa,EAAE,GAAG,EAClB,QAAQ,EAAE,GAAG,EACb,IAAI,EAAE,MAAM,OAYb;AAED;;;EAGE;AACF,wBAAgB,aAAa,CAAC,aAAa,EAAE,GAAG,OAK/C;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,GAAG,OAI7C;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,kCACA,MAAM,GAAG,SAAS,KAChD,MAAM,GAAG,SAKX,CAAC;AAEF,eAAO,MAAM,cAAc,QACpB,OAAO,MAAM,EAAE,GAAG,CAAC,KACvB,OAAO,MAAM,EAAE,GAAG,CAcpB,CAAC;AAEF,wBAAsB,WAAW,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,WAAW,gBAavE;AAED,eAAO,MAAM,6BAA6B,cAC7B,uBAAuB,KACjC,OAOF,CAAC;AAEF,eAAO,MAAM,mBAAmB,eAAgB,MAAM,KAAG,MAGxD,CAAC;AAMF,eAAO,MAAM,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,265 @@
1
+ function $importDefault(module) {
2
+ if (module === null || module === void 0 ? void 0 : module.__esModule) {
3
+ return module.default;
4
+ }
5
+ return module;
6
+ }
7
+ import { arrayify, hexlify } from "@ethersproject/bytes";
8
+ import { keccak256 } from "@ethersproject/keccak256";
9
+ import { parse } from "@ethersproject/transactions";
10
+ import { TransactionStatus } from "@metamask/transaction-controller";
11
+ import { BigNumber } from "bignumber.js";
12
+ import $jsonDiffer from "fast-json-patch";
13
+ const jsonDiffer = $importDefault($jsonDiffer);
14
+ import $_ from "lodash";
15
+ const _ = $importDefault($_);
16
+ // Ignoring TypeScript errors here because this import is disallowed for production builds, because
17
+ // the `package.json` file is above the root directory.
18
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
19
+ // @ts-ignore
20
+ import packageJson from "../package.json" assert { type: "json" };
21
+ import { API_BASE_URL, SENTINEL_API_BASE_URL_MAP } from "./constants.mjs";
22
+ import { APIType, SmartTransactionStatuses, SmartTransactionCancellationReason, SmartTransactionMinedTx, cancellationReasonToStatusMap, ClientId } from "./types.mjs";
23
+ export function isSmartTransactionPending(smartTransaction) {
24
+ return smartTransaction.status === SmartTransactionStatuses.PENDING;
25
+ }
26
+ export const isSmartTransactionStatusResolved = (stxStatus) => stxStatus === 'uuid_not_found';
27
+ // TODO use actual url once API is defined
28
+ export function getAPIRequestURL(apiType, chainId) {
29
+ const chainIdDec = parseInt(chainId, 16);
30
+ switch (apiType) {
31
+ case APIType.GET_FEES: {
32
+ return `${API_BASE_URL}/networks/${chainIdDec}/getFees`;
33
+ }
34
+ case APIType.ESTIMATE_GAS: {
35
+ return `${API_BASE_URL}/networks/${chainIdDec}/estimateGas`;
36
+ }
37
+ case APIType.SUBMIT_TRANSACTIONS: {
38
+ return `${API_BASE_URL}/networks/${chainIdDec}/submitTransactions?stxControllerVersion=${packageJson.version}`;
39
+ }
40
+ case APIType.CANCEL: {
41
+ return `${API_BASE_URL}/networks/${chainIdDec}/cancel`;
42
+ }
43
+ case APIType.BATCH_STATUS: {
44
+ return `${API_BASE_URL}/networks/${chainIdDec}/batchStatus`;
45
+ }
46
+ case APIType.LIVENESS: {
47
+ return `${SENTINEL_API_BASE_URL_MAP[chainIdDec]}/network`;
48
+ }
49
+ default: {
50
+ throw new Error(`Invalid APIType`); // It can never get here thanks to TypeScript.
51
+ }
52
+ }
53
+ }
54
+ export const calculateStatus = (stxStatus) => {
55
+ if (isSmartTransactionStatusResolved(stxStatus)) {
56
+ return SmartTransactionStatuses.RESOLVED;
57
+ }
58
+ const cancellations = [
59
+ SmartTransactionCancellationReason.WOULD_REVERT,
60
+ SmartTransactionCancellationReason.TOO_CHEAP,
61
+ SmartTransactionCancellationReason.DEADLINE_MISSED,
62
+ SmartTransactionCancellationReason.INVALID_NONCE,
63
+ SmartTransactionCancellationReason.USER_CANCELLED,
64
+ ];
65
+ if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === SmartTransactionMinedTx.NOT_MINED) {
66
+ if (stxStatus.cancellationReason ===
67
+ SmartTransactionCancellationReason.NOT_CANCELLED) {
68
+ return SmartTransactionStatuses.PENDING;
69
+ }
70
+ const isCancellation = cancellations.findIndex((cancellation) => cancellation === stxStatus.cancellationReason) > -1;
71
+ if (stxStatus.cancellationReason && isCancellation) {
72
+ if (!stxStatus.isSettled) {
73
+ return SmartTransactionStatuses.PENDING;
74
+ }
75
+ return cancellationReasonToStatusMap[stxStatus.cancellationReason];
76
+ }
77
+ }
78
+ else if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === SmartTransactionMinedTx.SUCCESS) {
79
+ return SmartTransactionStatuses.SUCCESS;
80
+ }
81
+ else if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === SmartTransactionMinedTx.CANCELLED) {
82
+ return SmartTransactionStatuses.CANCELLED;
83
+ }
84
+ else if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === SmartTransactionMinedTx.REVERTED) {
85
+ return SmartTransactionStatuses.REVERTED;
86
+ }
87
+ else if ((stxStatus === null || stxStatus === void 0 ? void 0 : stxStatus.minedTx) === SmartTransactionMinedTx.UNKNOWN) {
88
+ return SmartTransactionStatuses.UNKNOWN;
89
+ }
90
+ return SmartTransactionStatuses.UNKNOWN;
91
+ };
92
+ /**
93
+ Generates an array of history objects sense the previous state.
94
+ The object has the keys
95
+ op (the operation performed),
96
+ path (the key and if a nested object then each key will be separated with a `/`)
97
+ value
98
+ with the first entry having the note and a timestamp when the change took place
99
+ @param previousState - the previous state of the object
100
+ @param newState - the update object
101
+ @param [note] - a optional note for the state change
102
+ @returns
103
+ */
104
+ export function generateHistoryEntry(previousState, newState, note) {
105
+ const entry = jsonDiffer.compare(previousState, newState);
106
+ // Add a note to the first op, since it breaks if we append it to the entry
107
+ if (entry[0]) {
108
+ if (note) {
109
+ entry[0].note = note;
110
+ }
111
+ entry[0].timestamp = Date.now();
112
+ }
113
+ return entry;
114
+ }
115
+ /**
116
+ Recovers previous txMeta state obj
117
+ @returns
118
+ */
119
+ export function replayHistory(_shortHistory) {
120
+ const shortHistory = _.cloneDeep(_shortHistory);
121
+ return shortHistory.reduce((val, entry) => jsonDiffer.applyPatch(val, entry).newDocument);
122
+ }
123
+ /**
124
+ * Snapshot {@code txMeta}
125
+ * @param txMeta - the tx metadata object
126
+ * @returns a deep clone without history
127
+ */
128
+ export function snapshotFromTxMeta(txMeta) {
129
+ const shallow = Object.assign({}, txMeta);
130
+ delete shallow.history;
131
+ return _.cloneDeep(shallow);
132
+ }
133
+ /**
134
+ * Returns processing time for an STX in seconds.
135
+ * @param smartTransactionSubmittedtime
136
+ * @returns Processing time in seconds.
137
+ */
138
+ export const getStxProcessingTime = (smartTransactionSubmittedtime) => {
139
+ if (!smartTransactionSubmittedtime) {
140
+ return undefined;
141
+ }
142
+ return Math.round((Date.now() - smartTransactionSubmittedtime) / 1000);
143
+ };
144
+ export const mapKeysToCamel = (obj) => {
145
+ if (!_.isObject(obj)) {
146
+ return obj;
147
+ }
148
+ const mappedValues = _.mapValues(obj, (val) => {
149
+ if (_.isArray(val)) {
150
+ return val.map(mapKeysToCamel);
151
+ }
152
+ else if (_.isObject(val)) {
153
+ return mapKeysToCamel(val);
154
+ }
155
+ return val;
156
+ });
157
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
158
+ return _.mapKeys(mappedValues, (value, key) => _.camelCase(key));
159
+ };
160
+ export async function handleFetch(request, options) {
161
+ const response = await fetch(request, options);
162
+ const json = await response.json();
163
+ if (!response.ok) {
164
+ console.log(`response`, response);
165
+ throw new Error(`Fetch error:${JSON.stringify(Object.assign({ status: response.status }, mapKeysToCamel(json)))}`);
166
+ }
167
+ return json;
168
+ }
169
+ export const isSmartTransactionCancellable = (stxStatus) => {
170
+ return (stxStatus.minedTx === SmartTransactionMinedTx.NOT_MINED &&
171
+ (!stxStatus.cancellationReason ||
172
+ stxStatus.cancellationReason ===
173
+ SmartTransactionCancellationReason.NOT_CANCELLED));
174
+ };
175
+ export const incrementNonceInHex = (nonceInHex) => {
176
+ const nonceInDec = new BigNumber(nonceInHex, 16).toString(10);
177
+ return hexlify(Number(nonceInDec) + 1);
178
+ };
179
+ const isType4Transaction = (signedTxHex) => {
180
+ return typeof signedTxHex === 'string' && signedTxHex.startsWith('0x04');
181
+ };
182
+ export const getTxHash = (signedTxHex) => {
183
+ var _a;
184
+ if (!signedTxHex) {
185
+ return '';
186
+ }
187
+ try {
188
+ const parsed = parse(signedTxHex);
189
+ return (_a = parsed === null || parsed === void 0 ? void 0 : parsed.hash) !== null && _a !== void 0 ? _a : '';
190
+ }
191
+ catch (error) {
192
+ if (isType4Transaction(signedTxHex)) {
193
+ return hexlify(keccak256(arrayify(signedTxHex)));
194
+ }
195
+ throw error;
196
+ }
197
+ };
198
+ export const getSmartTransactionMetricsProperties = (smartTransaction) => {
199
+ if (!smartTransaction) {
200
+ return {};
201
+ }
202
+ const smartTransactionStatusMetadata = smartTransaction.statusMetadata;
203
+ return {
204
+ stx_status: smartTransaction.status,
205
+ type: smartTransaction.type,
206
+ processing_time: getStxProcessingTime(smartTransaction.time),
207
+ is_smart_transaction: true,
208
+ stx_enabled: true,
209
+ current_stx_enabled: true,
210
+ stx_user_opt_in: true,
211
+ stx_duplicated: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.duplicated,
212
+ stx_timed_out: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.timedOut,
213
+ stx_proxied: smartTransactionStatusMetadata === null || smartTransactionStatusMetadata === void 0 ? void 0 : smartTransactionStatusMetadata.proxied,
214
+ };
215
+ };
216
+ export const getSmartTransactionMetricsSensitiveProperties = (smartTransaction) => {
217
+ if (!smartTransaction) {
218
+ return {};
219
+ }
220
+ return {
221
+ token_from_symbol: smartTransaction.sourceTokenSymbol,
222
+ token_to_symbol: smartTransaction.destinationTokenSymbol,
223
+ account_hardware_type: smartTransaction.accountHardwareType,
224
+ account_type: smartTransaction.accountType,
225
+ device_model: smartTransaction.deviceModel,
226
+ };
227
+ };
228
+ export const getReturnTxHashAsap = (clientId, smartTransactionsFeatureFlags) => {
229
+ return clientId === ClientId.Extension
230
+ ? smartTransactionsFeatureFlags === null || smartTransactionsFeatureFlags === void 0 ? void 0 : smartTransactionsFeatureFlags.extensionReturnTxHashAsap
231
+ : smartTransactionsFeatureFlags === null || smartTransactionsFeatureFlags === void 0 ? void 0 : smartTransactionsFeatureFlags.mobileReturnTxHashAsap;
232
+ };
233
+ export const shouldMarkRegularTransactionAsFailed = ({ smartTransaction, clientId, getFeatureFlags, }) => {
234
+ var _a;
235
+ const { status, transactionId } = smartTransaction;
236
+ const failureStatuses = [
237
+ SmartTransactionStatuses.CANCELLED,
238
+ SmartTransactionStatuses.CANCELLED_USER_CANCELLED,
239
+ SmartTransactionStatuses.UNKNOWN,
240
+ SmartTransactionStatuses.RESOLVED,
241
+ ];
242
+ if (!status ||
243
+ !failureStatuses.includes(status)) {
244
+ return false;
245
+ }
246
+ const { smartTransactions: smartTransactionsFeatureFlags } = (_a = getFeatureFlags()) !== null && _a !== void 0 ? _a : {};
247
+ const returnTxHashAsapEnabled = getReturnTxHashAsap(clientId, smartTransactionsFeatureFlags);
248
+ return Boolean(returnTxHashAsapEnabled && transactionId);
249
+ };
250
+ export const markRegularTransactionAsFailed = ({ smartTransaction, getRegularTransactions, updateTransaction, }) => {
251
+ const { transactionId, status } = smartTransaction;
252
+ const originalTransaction = getRegularTransactions().find((transaction) => transaction.id === transactionId);
253
+ if (!originalTransaction) {
254
+ throw new Error('Cannot find regular transaction to mark it as failed');
255
+ }
256
+ if (originalTransaction.status === TransactionStatus.failed) {
257
+ return; // Already marked as failed.
258
+ }
259
+ const updatedTransaction = Object.assign(Object.assign({}, originalTransaction), { status: TransactionStatus.failed, error: {
260
+ name: 'SmartTransactionFailed',
261
+ message: `Smart transaction failed with status: ${status}`,
262
+ } });
263
+ updateTransaction(updatedTransaction, `Smart transaction status: ${status}`);
264
+ };
265
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,6BAA6B;AACzD,OAAO,EAAE,SAAS,EAAE,iCAAiC;AACrD,OAAO,EAAE,KAAK,EAAE,oCAAoC;AAMpD,OAAO,EAAE,iBAAiB,EAAE,yCAAyC;AACrE,OAAO,EAAE,SAAS,EAAE,qBAAqB;AACzC,OAAO,WAAU,wBAAwB;;AACzC,OAAO,EAAC,eAAe;;AAEvB,mGAAmG;AACnG,uDAAuD;AACvD,6DAA6D;AAC7D,aAAa;AACb,OAAO,WAAW,gDAAwB;AAC1C,OAAO,EAAE,YAAY,EAAE,yBAAyB,EAAE,wBAAoB;AAMtE,OAAO,EACL,OAAO,EACP,wBAAwB,EACxB,kCAAkC,EAClC,uBAAuB,EACvB,6BAA6B,EAC7B,QAAQ,EACT,oBAAgB;AAEjB,MAAM,UAAU,yBAAyB,CAAC,gBAAkC;IAC1E,OAAO,gBAAgB,CAAC,MAAM,KAAK,wBAAwB,CAAC,OAAO,CAAC;AACtE,CAAC;AAED,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAC9C,SAA2C,EAC3C,EAAE,CAAC,SAAS,KAAK,gBAAgB,CAAC;AAEpC,0CAA0C;AAC1C,MAAM,UAAU,gBAAgB,CAAC,OAAgB,EAAE,OAAe;IAChE,MAAM,UAAU,GAAG,QAAQ,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;IACzC,QAAQ,OAAO,EAAE;QACf,KAAK,OAAO,CAAC,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AC,EAC7D;QACA,OAAO,KAAK,CAAC;KACd;IACD,MAAM,EAAE,iBAAiB,EAAE,6BAA6B,EAAE,GACxD,MAAA,eAAe,EAAE,mCAAI,EAAE,CAAC;IAC1B,MAAM,uBAAuB,GAAG,mBAAmB,CACjD,QAAQ,EACR,6BAA6B,CAC9B,CAAC;IACF,OAAO,OAAO,CAAC,uBAAuB,IAAI,aAAa,CAAC,CAAC;AAC3D,CAAC,CAAC;AAEF,MAAM,CAAC,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,iBAAiB,CAAC,MAAM,EAAE;QAC3D,OAAO,CAAC,4BAA4B;KACrC;IACD,MAAM,kBAAkB,mCACnB,mBAAmB,KACtB,MAAM,EAAE,iBAAiB,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","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 CHANGED
@@ -1,28 +1,41 @@
1
1
  {
2
2
  "name": "@metamask/smart-transactions-controller",
3
- "version": "18.1.0",
3
+ "version": "19.0.0",
4
4
  "description": "Improves success rates for swaps by trialing transactions privately and finding minimum fees",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "https://github.com/MetaMask/smart-transactions-controller.git"
8
8
  },
9
9
  "license": "SEE LICENSE IN LICENSE",
10
- "main": "dist/index.js",
11
- "types": "dist/index.d.ts",
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",
12
27
  "files": [
13
- "dist/"
28
+ "dist"
14
29
  ],
15
30
  "scripts": {
16
- "build": "tsc --project tsconfig.build.json",
17
- "build:clean": "rm -rf dist && yarn build",
18
- "build:link": "yarn build && cd dist && yarn link && rm -rf node_modules && cd ..",
31
+ "build": "ts-bridge --project tsconfig.build.json --clean",
19
32
  "lint": "yarn lint:eslint && yarn lint:misc --check && yarn lint:changelog",
20
33
  "lint:changelog": "auto-changelog validate --prettier",
21
34
  "lint:eslint": "eslint . --cache --ext js,ts",
22
35
  "lint:fix": "yarn lint:eslint --fix && yarn lint:misc --write && yarn lint:changelog",
23
36
  "lint:misc": "prettier '**/*.json' '**/*.md' '**/*.yml' '!.yarnrc.yml' --ignore-path .gitignore --no-error-on-unmatched-pattern",
24
37
  "prepack": "./scripts/prepack.sh",
25
- "test": "jest",
38
+ "test": "jest && attw --pack",
26
39
  "test:watch": "jest --watchAll"
27
40
  },
28
41
  "dependencies": {
@@ -32,16 +45,17 @@
32
45
  "@ethersproject/bytes": "^5.7.0",
33
46
  "@ethersproject/keccak256": "^5.8.0",
34
47
  "@ethersproject/transactions": "^5.7.0",
35
- "@metamask/base-controller": "^7.0.1",
48
+ "@metamask/base-controller": "^8.3.0",
36
49
  "@metamask/controller-utils": "^11.0.0",
37
50
  "@metamask/eth-json-rpc-provider": "^4.1.6",
38
51
  "@metamask/eth-query": "^4.0.0",
39
- "@metamask/polling-controller": "^12.0.0",
52
+ "@metamask/polling-controller": "^14.0.0",
40
53
  "bignumber.js": "^9.0.1",
41
54
  "fast-json-patch": "^3.1.0",
42
55
  "lodash": "^4.17.21"
43
56
  },
44
57
  "devDependencies": {
58
+ "@arethetypeswrong/cli": "^0.18.2",
45
59
  "@lavamoat/allow-scripts": "^3.2.1",
46
60
  "@lavamoat/preinstall-always-fail": "^2.1.0",
47
61
  "@metamask/auto-changelog": "^3.1.0",
@@ -52,7 +66,8 @@
52
66
  "@metamask/gas-fee-controller": "^22.0.0",
53
67
  "@metamask/json-rpc-engine": "^10.0.1",
54
68
  "@metamask/network-controller": "^24.0.0",
55
- "@metamask/transaction-controller": "^42.0.0",
69
+ "@metamask/transaction-controller": "^60.4.0",
70
+ "@ts-bridge/cli": "^0.6.3",
56
71
  "@types/jest": "^26.0.24",
57
72
  "@types/lodash": "^4.14.194",
58
73
  "@types/node": "^18.19.17",
@@ -78,7 +93,7 @@
78
93
  },
79
94
  "peerDependencies": {
80
95
  "@metamask/network-controller": "^24.0.0",
81
- "@metamask/transaction-controller": "^42.0.0"
96
+ "@metamask/transaction-controller": "^60.4.0"
82
97
  },
83
98
  "peerDependenciesMeta": {
84
99
  "@metamask/accounts-controller": {
@@ -86,6 +101,15 @@
86
101
  },
87
102
  "@metamask/approval-controller": {
88
103
  "optional": true
104
+ },
105
+ "@metamask/eth-block-tracker": {
106
+ "optional": true
107
+ },
108
+ "@metamask/gas-fee-controller": {
109
+ "optional": true
110
+ },
111
+ "@metamask/remote-feature-flag-controller": {
112
+ "optional": true
89
113
  }
90
114
  },
91
115
  "packageManager": "yarn@3.2.1",
@@ -101,9 +125,7 @@
101
125
  "@lavamoat/preinstall-always-fail": false,
102
126
  "@metamask/controller-utils>ethereumjs-util>ethereum-cryptography>keccak": false,
103
127
  "@metamask/controller-utils>ethereumjs-util>ethereum-cryptography>secp256k1": false,
104
- "@metamask/controller-utils>babel-runtime>core-js": false,
105
- "@metamask/transaction-controller>@metamask/accounts-controller>@metamask/keyring-controller>ethereumjs-wallet>ethereum-cryptography>keccak": false,
106
- "@metamask/transaction-controller>@metamask/accounts-controller>@metamask/keyring-controller>ethereumjs-wallet>ethereum-cryptography>secp256k1": false
128
+ "@metamask/controller-utils>babel-runtime>core-js": false
107
129
  }
108
130
  }
109
131
  }