@metamask-previews/controller-utils 4.3.1-preview.d32a7cc

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/dist/util.js ADDED
@@ -0,0 +1,495 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.isValidJson = exports.isNonEmptyArray = exports.isPlainObject = exports.convertHexToDecimal = exports.query = exports.normalizeEnsName = exports.timeoutFetch = exports.fetchWithErrorHandling = exports.handleFetch = exports.successfulFetch = exports.isSmartContractCode = exports.isValidHexAddress = exports.toChecksumHexAddress = exports.safelyExecuteWithTimeout = exports.safelyExecute = exports.toHex = exports.fromHex = exports.hexToText = exports.hexToBN = exports.getBuyURL = exports.weiHexToGweiDec = exports.gweiDecToWEIBN = exports.fractionBN = exports.BNToHex = exports.isSafeChainId = void 0;
16
+ const utils_1 = require("@metamask/utils");
17
+ const eth_ens_namehash_1 = __importDefault(require("eth-ens-namehash"));
18
+ const ethereumjs_util_1 = require("ethereumjs-util");
19
+ const ethjs_unit_1 = require("ethjs-unit");
20
+ const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
21
+ const constants_1 = require("./constants");
22
+ const TIMEOUT_ERROR = new Error('timeout');
23
+ /**
24
+ * Checks whether the given number primitive chain ID is safe.
25
+ * Because some cryptographic libraries we use expect the chain ID to be a
26
+ * number primitive, it must not exceed a certain size.
27
+ *
28
+ * @param chainId - The chain ID to check for safety.
29
+ * @returns Whether the given chain ID is safe.
30
+ */
31
+ function isSafeChainId(chainId) {
32
+ if (!(0, ethereumjs_util_1.isHexString)(chainId)) {
33
+ return false;
34
+ }
35
+ const decimalChainId = Number.parseInt(chainId);
36
+ return (Number.isSafeInteger(decimalChainId) &&
37
+ decimalChainId > 0 &&
38
+ decimalChainId <= constants_1.MAX_SAFE_CHAIN_ID);
39
+ }
40
+ exports.isSafeChainId = isSafeChainId;
41
+ /**
42
+ * Converts a BN object to a hex string with a '0x' prefix.
43
+ *
44
+ * @param inputBn - BN instance to convert to a hex string.
45
+ * @returns A '0x'-prefixed hex string.
46
+ */
47
+ function BNToHex(inputBn) {
48
+ return (0, ethereumjs_util_1.addHexPrefix)(inputBn.toString(16));
49
+ }
50
+ exports.BNToHex = BNToHex;
51
+ /**
52
+ * Used to multiply a BN by a fraction.
53
+ *
54
+ * @param targetBN - Number to multiply by a fraction.
55
+ * @param numerator - Numerator of the fraction multiplier.
56
+ * @param denominator - Denominator of the fraction multiplier.
57
+ * @returns Product of the multiplication.
58
+ */
59
+ function fractionBN(targetBN, numerator, denominator) {
60
+ const numBN = new ethereumjs_util_1.BN(numerator);
61
+ const denomBN = new ethereumjs_util_1.BN(denominator);
62
+ return targetBN.mul(numBN).div(denomBN);
63
+ }
64
+ exports.fractionBN = fractionBN;
65
+ /**
66
+ * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts.
67
+ *
68
+ * @param n - The base 10 number to convert to WEI.
69
+ * @returns The number in WEI, as a BN.
70
+ */
71
+ function gweiDecToWEIBN(n) {
72
+ if (Number.isNaN(n)) {
73
+ return new ethereumjs_util_1.BN(0);
74
+ }
75
+ const parts = n.toString().split('.');
76
+ const wholePart = parts[0] || '0';
77
+ let decimalPart = parts[1] || '';
78
+ if (!decimalPart) {
79
+ return (0, ethjs_unit_1.toWei)(wholePart, 'gwei');
80
+ }
81
+ if (decimalPart.length <= 9) {
82
+ return (0, ethjs_unit_1.toWei)(`${wholePart}.${decimalPart}`, 'gwei');
83
+ }
84
+ const decimalPartToRemove = decimalPart.slice(9);
85
+ const decimalRoundingDigit = decimalPartToRemove[0];
86
+ decimalPart = decimalPart.slice(0, 9);
87
+ let wei = (0, ethjs_unit_1.toWei)(`${wholePart}.${decimalPart}`, 'gwei');
88
+ if (Number(decimalRoundingDigit) >= 5) {
89
+ wei = wei.add(new ethereumjs_util_1.BN(1));
90
+ }
91
+ return wei;
92
+ }
93
+ exports.gweiDecToWEIBN = gweiDecToWEIBN;
94
+ /**
95
+ * Used to convert values from wei hex format to dec gwei format.
96
+ *
97
+ * @param hex - The value in hex wei.
98
+ * @returns The value in dec gwei as string.
99
+ */
100
+ function weiHexToGweiDec(hex) {
101
+ const hexWei = new ethereumjs_util_1.BN((0, ethereumjs_util_1.stripHexPrefix)(hex), 16);
102
+ return (0, ethjs_unit_1.fromWei)(hexWei, 'gwei').toString(10);
103
+ }
104
+ exports.weiHexToGweiDec = weiHexToGweiDec;
105
+ /**
106
+ * Return a URL that can be used to obtain ETH for a given network.
107
+ *
108
+ * @param networkCode - Network code of desired network.
109
+ * @param address - Address to deposit obtained ETH.
110
+ * @param amount - How much ETH is desired.
111
+ * @returns URL to buy ETH based on network.
112
+ */
113
+ function getBuyURL(networkCode = '1', address, amount = 5) {
114
+ switch (networkCode) {
115
+ case '1':
116
+ return `https://buy.coinbase.com/?code=9ec56d01-7e81-5017-930c-513daa27bb6a&amount=${amount}&address=${address}&crypto_currency=ETH`;
117
+ case '5':
118
+ return 'https://goerli-faucet.slock.it/';
119
+ case '11155111':
120
+ return 'https://sepoliafaucet.net/';
121
+ default:
122
+ return undefined;
123
+ }
124
+ }
125
+ exports.getBuyURL = getBuyURL;
126
+ /**
127
+ * Converts a hex string to a BN object.
128
+ *
129
+ * @param inputHex - Number represented as a hex string.
130
+ * @returns A BN instance.
131
+ */
132
+ function hexToBN(inputHex) {
133
+ return inputHex ? new ethereumjs_util_1.BN((0, ethereumjs_util_1.stripHexPrefix)(inputHex), 16) : new ethereumjs_util_1.BN(0);
134
+ }
135
+ exports.hexToBN = hexToBN;
136
+ /**
137
+ * A helper function that converts hex data to human readable string.
138
+ *
139
+ * @param hex - The hex string to convert to string.
140
+ * @returns A human readable string conversion.
141
+ */
142
+ function hexToText(hex) {
143
+ try {
144
+ const stripped = (0, ethereumjs_util_1.stripHexPrefix)(hex);
145
+ const buff = Buffer.from(stripped, 'hex');
146
+ return buff.toString('utf8');
147
+ }
148
+ catch (e) {
149
+ /* istanbul ignore next */
150
+ return hex;
151
+ }
152
+ }
153
+ exports.hexToText = hexToText;
154
+ /**
155
+ * Parses a hex string and converts it into a number that can be operated on in a bignum-safe,
156
+ * base-10 way.
157
+ *
158
+ * @param value - A base-16 number encoded as a string.
159
+ * @returns The number as a BN object in base-16 mode.
160
+ */
161
+ function fromHex(value) {
162
+ if (ethereumjs_util_1.BN.isBN(value)) {
163
+ return value;
164
+ }
165
+ return new ethereumjs_util_1.BN(hexToBN(value).toString(10));
166
+ }
167
+ exports.fromHex = fromHex;
168
+ /**
169
+ * Converts an integer to a hexadecimal representation.
170
+ *
171
+ * @param value - An integer, an integer encoded as a base-10 string, or a BN.
172
+ * @returns The integer encoded as a hex string.
173
+ */
174
+ function toHex(value) {
175
+ if (typeof value === 'string' && (0, utils_1.isStrictHexString)(value)) {
176
+ return value;
177
+ }
178
+ const hexString = ethereumjs_util_1.BN.isBN(value)
179
+ ? value.toString(16)
180
+ : new ethereumjs_util_1.BN(value.toString(), 10).toString(16);
181
+ return `0x${hexString}`;
182
+ }
183
+ exports.toHex = toHex;
184
+ /**
185
+ * Execute and return an asynchronous operation without throwing errors.
186
+ *
187
+ * @param operation - Function returning a Promise.
188
+ * @param logError - Determines if the error should be logged.
189
+ * @returns Promise resolving to the result of the async operation.
190
+ */
191
+ function safelyExecute(operation, logError = false) {
192
+ return __awaiter(this, void 0, void 0, function* () {
193
+ try {
194
+ return yield operation();
195
+ }
196
+ catch (error) {
197
+ /* istanbul ignore next */
198
+ if (logError) {
199
+ console.error(error);
200
+ }
201
+ return undefined;
202
+ }
203
+ });
204
+ }
205
+ exports.safelyExecute = safelyExecute;
206
+ /**
207
+ * Execute and return an asynchronous operation with a timeout.
208
+ *
209
+ * @param operation - Function returning a Promise.
210
+ * @param logError - Determines if the error should be logged.
211
+ * @param timeout - Timeout to fail the operation.
212
+ * @returns Promise resolving to the result of the async operation.
213
+ */
214
+ function safelyExecuteWithTimeout(operation, logError = false, timeout = 500) {
215
+ return __awaiter(this, void 0, void 0, function* () {
216
+ try {
217
+ return yield Promise.race([
218
+ operation(),
219
+ new Promise((_, reject) => setTimeout(() => {
220
+ reject(TIMEOUT_ERROR);
221
+ }, timeout)),
222
+ ]);
223
+ }
224
+ catch (error) {
225
+ /* istanbul ignore next */
226
+ if (logError) {
227
+ console.error(error);
228
+ }
229
+ return undefined;
230
+ }
231
+ });
232
+ }
233
+ exports.safelyExecuteWithTimeout = safelyExecuteWithTimeout;
234
+ /**
235
+ * Convert an address to a checksummed hexidecimal address.
236
+ *
237
+ * @param address - The address to convert.
238
+ * @returns A 0x-prefixed hexidecimal checksummed address.
239
+ */
240
+ function toChecksumHexAddress(address) {
241
+ const hexPrefixed = (0, ethereumjs_util_1.addHexPrefix)(address);
242
+ if (!(0, ethereumjs_util_1.isHexString)(hexPrefixed)) {
243
+ // Version 5.1 of ethereumjs-utils would have returned '0xY' for input 'y'
244
+ // but we shouldn't waste effort trying to change case on a clearly invalid
245
+ // string. Instead just return the hex prefixed original string which most
246
+ // closely mimics the original behavior.
247
+ return hexPrefixed;
248
+ }
249
+ return (0, ethereumjs_util_1.toChecksumAddress)(hexPrefixed);
250
+ }
251
+ exports.toChecksumHexAddress = toChecksumHexAddress;
252
+ /**
253
+ * Validates that the input is a hex address. This utility method is a thin
254
+ * wrapper around ethereumjs-util.isValidAddress, with the exception that it
255
+ * by default will return true for hex strings that meet the length requirement
256
+ * of a hex address, but are not prefixed with `0x`.
257
+ *
258
+ * @param possibleAddress - Input parameter to check against.
259
+ * @param options - The validation options.
260
+ * @param options.allowNonPrefixed - If true will allow addresses without `0x` prefix.`
261
+ * @returns Whether or not the input is a valid hex address.
262
+ */
263
+ function isValidHexAddress(possibleAddress, { allowNonPrefixed = true } = {}) {
264
+ const addressToCheck = allowNonPrefixed
265
+ ? (0, ethereumjs_util_1.addHexPrefix)(possibleAddress)
266
+ : possibleAddress;
267
+ if (!(0, ethereumjs_util_1.isHexString)(addressToCheck)) {
268
+ return false;
269
+ }
270
+ return (0, ethereumjs_util_1.isValidAddress)(addressToCheck);
271
+ }
272
+ exports.isValidHexAddress = isValidHexAddress;
273
+ /**
274
+ * Returns whether the given code corresponds to a smart contract.
275
+ *
276
+ * @param code - The potential smart contract code.
277
+ * @returns Whether the code was smart contract code or not.
278
+ */
279
+ function isSmartContractCode(code) {
280
+ /* istanbul ignore if */
281
+ if (!code) {
282
+ return false;
283
+ }
284
+ // Geth will return '0x', and ganache-core v2.2.1 will return '0x0'
285
+ const smartContractCode = code !== '0x' && code !== '0x0';
286
+ return smartContractCode;
287
+ }
288
+ exports.isSmartContractCode = isSmartContractCode;
289
+ /**
290
+ * Execute fetch and verify that the response was successful.
291
+ *
292
+ * @param request - Request information.
293
+ * @param options - Fetch options.
294
+ * @returns The fetch response.
295
+ */
296
+ function successfulFetch(request, options) {
297
+ return __awaiter(this, void 0, void 0, function* () {
298
+ const response = yield fetch(request, options);
299
+ if (!response.ok) {
300
+ throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`);
301
+ }
302
+ return response;
303
+ });
304
+ }
305
+ exports.successfulFetch = successfulFetch;
306
+ /**
307
+ * Execute fetch and return object response.
308
+ *
309
+ * @param request - The request information.
310
+ * @param options - The fetch options.
311
+ * @returns The fetch response JSON data.
312
+ */
313
+ function handleFetch(request, options) {
314
+ return __awaiter(this, void 0, void 0, function* () {
315
+ const response = yield successfulFetch(request, options);
316
+ const object = yield response.json();
317
+ return object;
318
+ });
319
+ }
320
+ exports.handleFetch = handleFetch;
321
+ /**
322
+ * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.
323
+ *
324
+ * @param request - the request options object
325
+ * @param request.url - The request url to query.
326
+ * @param request.options - The fetch options.
327
+ * @param request.timeout - Timeout to fail request
328
+ * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context
329
+ * @returns The fetch response JSON data or undefined (if error occurs).
330
+ */
331
+ function fetchWithErrorHandling({ url, options, timeout, errorCodesToCatch, }) {
332
+ return __awaiter(this, void 0, void 0, function* () {
333
+ let result;
334
+ try {
335
+ if (timeout) {
336
+ result = Promise.race([
337
+ yield handleFetch(url, options),
338
+ new Promise((_, reject) => setTimeout(() => {
339
+ reject(TIMEOUT_ERROR);
340
+ }, timeout)),
341
+ ]);
342
+ }
343
+ else {
344
+ result = yield handleFetch(url, options);
345
+ }
346
+ }
347
+ catch (e) {
348
+ logOrRethrowError(e, errorCodesToCatch);
349
+ }
350
+ return result;
351
+ });
352
+ }
353
+ exports.fetchWithErrorHandling = fetchWithErrorHandling;
354
+ /**
355
+ * Fetch that fails after timeout.
356
+ *
357
+ * @param url - Url to fetch.
358
+ * @param options - Options to send with the request.
359
+ * @param timeout - Timeout to fail request.
360
+ * @returns Promise resolving the request.
361
+ */
362
+ function timeoutFetch(url, options, timeout = 500) {
363
+ return __awaiter(this, void 0, void 0, function* () {
364
+ return Promise.race([
365
+ successfulFetch(url, options),
366
+ new Promise((_, reject) => setTimeout(() => {
367
+ reject(TIMEOUT_ERROR);
368
+ }, timeout)),
369
+ ]);
370
+ });
371
+ }
372
+ exports.timeoutFetch = timeoutFetch;
373
+ /**
374
+ * Normalizes the given ENS name.
375
+ *
376
+ * @param ensName - The ENS name.
377
+ * @returns The normalized ENS name string.
378
+ */
379
+ function normalizeEnsName(ensName) {
380
+ if (ensName && typeof ensName === 'string') {
381
+ try {
382
+ const normalized = eth_ens_namehash_1.default.normalize(ensName.trim());
383
+ // this regex is only sufficient with the above call to ensNamehash.normalize
384
+ // TODO: change 7 in regex to 3 when shorter ENS domains are live
385
+ if (normalized.match(/^(([\w\d-]+)\.)*[\w\d-]{7,}\.(eth|test)$/u)) {
386
+ return normalized;
387
+ }
388
+ }
389
+ catch (_) {
390
+ // do nothing
391
+ }
392
+ }
393
+ return null;
394
+ }
395
+ exports.normalizeEnsName = normalizeEnsName;
396
+ /**
397
+ * Wrapper method to handle EthQuery requests.
398
+ *
399
+ * @param ethQuery - EthQuery object initialized with a provider.
400
+ * @param method - Method to request.
401
+ * @param args - Arguments to send.
402
+ * @returns Promise resolving the request.
403
+ */
404
+ function query(ethQuery, method, args = []) {
405
+ return new Promise((resolve, reject) => {
406
+ const cb = (error, result) => {
407
+ if (error) {
408
+ reject(error);
409
+ return;
410
+ }
411
+ resolve(result);
412
+ };
413
+ // Using `in` rather than `hasProperty` so that we look up the prototype
414
+ // chain for the method.
415
+ if (method in ethQuery && typeof ethQuery[method] === 'function') {
416
+ ethQuery[method](...args, cb);
417
+ }
418
+ else {
419
+ ethQuery.sendAsync({ method, params: args }, cb);
420
+ }
421
+ });
422
+ }
423
+ exports.query = query;
424
+ /**
425
+ * Converts valid hex strings to decimal numbers, and handles unexpected arg types.
426
+ *
427
+ * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.
428
+ * @returns a decimal number.
429
+ */
430
+ const convertHexToDecimal = (value = '0x0') => {
431
+ if ((0, ethereumjs_util_1.isHexString)(value)) {
432
+ return parseInt(value, 16);
433
+ }
434
+ return Number(value) ? Number(value) : 0;
435
+ };
436
+ exports.convertHexToDecimal = convertHexToDecimal;
437
+ /**
438
+ * Determines whether a value is a "plain" object.
439
+ *
440
+ * @param value - A value to check
441
+ * @returns True if the passed value is a plain object
442
+ */
443
+ function isPlainObject(value) {
444
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
445
+ }
446
+ exports.isPlainObject = isPlainObject;
447
+ /**
448
+ * Type guard for {@link NonEmptyArray}.
449
+ *
450
+ * @template T - The non-empty array member type.
451
+ * @param value - The value to check.
452
+ * @returns Whether the value is a non-empty array.
453
+ */
454
+ function isNonEmptyArray(value) {
455
+ return Array.isArray(value) && value.length > 0;
456
+ }
457
+ exports.isNonEmptyArray = isNonEmptyArray;
458
+ /**
459
+ * Type guard for {@link Json}.
460
+ *
461
+ * @param value - The value to check.
462
+ * @returns Whether the value is valid JSON.
463
+ */
464
+ function isValidJson(value) {
465
+ try {
466
+ return (0, fast_deep_equal_1.default)(value, JSON.parse(JSON.stringify(value)));
467
+ }
468
+ catch (_) {
469
+ return false;
470
+ }
471
+ }
472
+ exports.isValidJson = isValidJson;
473
+ /**
474
+ * Utility method to log if error is a common fetch error and otherwise rethrow it.
475
+ *
476
+ * @param error - Caught error that we should either rethrow or log to console
477
+ * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context
478
+ */
479
+ function logOrRethrowError(error, codesToCatch = []) {
480
+ var _a;
481
+ if (!error) {
482
+ return;
483
+ }
484
+ const includesErrorCodeToCatch = codesToCatch.some((code) => { var _a; return (_a = error.message) === null || _a === void 0 ? void 0 : _a.includes(`Fetch failed with status '${code}'`); });
485
+ if (error instanceof Error &&
486
+ (includesErrorCodeToCatch ||
487
+ ((_a = error.message) === null || _a === void 0 ? void 0 : _a.includes('Failed to fetch')) ||
488
+ error === TIMEOUT_ERROR)) {
489
+ console.error(error);
490
+ }
491
+ else {
492
+ throw error;
493
+ }
494
+ }
495
+ //# sourceMappingURL=util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAEA,2CAAoD;AACpD,wEAA2C;AAC3C,qDAOyB;AACzB,2CAA4C;AAC5C,sEAAwC;AAExC,2CAAgD;AAEhD,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE3C;;;;;;;GAOG;AACH,SAAgB,aAAa,CAAC,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metamask/eth-query';\nimport type { Hex, Json } from '@metamask/utils';\nimport { isStrictHexString } from '@metamask/utils';\nimport ensNamehash from 'eth-ens-namehash';\nimport {\n addHexPrefix,\n isValidAddress,\n isHexString,\n BN,\n toChecksumAddress,\n stripHexPrefix,\n} from 'ethereumjs-util';\nimport { fromWei, toWei } from 'ethjs-unit';\nimport deepEqual from 'fast-deep-equal';\n\nimport { MAX_SAFE_CHAIN_ID } from './constants';\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\n/**\n * Checks whether the given number primitive chain ID is safe.\n * Because some cryptographic libraries we use expect the chain ID to be a\n * number primitive, it must not exceed a certain size.\n *\n * @param chainId - The chain ID to check for safety.\n * @returns Whether the given chain ID is safe.\n */\nexport function isSafeChainId(chainId: Hex): boolean {\n if (!isHexString(chainId)) {\n return false;\n }\n const decimalChainId = Number.parseInt(chainId);\n return (\n Number.isSafeInteger(decimalChainId) &&\n decimalChainId > 0 &&\n decimalChainId <= MAX_SAFE_CHAIN_ID\n );\n}\n/**\n * Converts a BN object to a hex string with a '0x' prefix.\n *\n * @param inputBn - BN instance to convert to a hex string.\n * @returns A '0x'-prefixed hex string.\n */\nexport function BNToHex(inputBn: any) {\n return addHexPrefix(inputBn.toString(16));\n}\n\n/**\n * Used to multiply a BN by a fraction.\n *\n * @param targetBN - Number to multiply by a fraction.\n * @param numerator - Numerator of the fraction multiplier.\n * @param denominator - Denominator of the fraction multiplier.\n * @returns Product of the multiplication.\n */\nexport function fractionBN(\n targetBN: any,\n numerator: number | string,\n denominator: number | string,\n) {\n const numBN = new BN(numerator);\n const denomBN = new BN(denominator);\n return targetBN.mul(numBN).div(denomBN);\n}\n\n/**\n * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts.\n *\n * @param n - The base 10 number to convert to WEI.\n * @returns The number in WEI, as a BN.\n */\nexport function gweiDecToWEIBN(n: number | string) {\n if (Number.isNaN(n)) {\n return new BN(0);\n }\n\n const parts = n.toString().split('.');\n const wholePart = parts[0] || '0';\n let decimalPart = parts[1] || '';\n\n if (!decimalPart) {\n return toWei(wholePart, 'gwei');\n }\n\n if (decimalPart.length <= 9) {\n return toWei(`${wholePart}.${decimalPart}`, 'gwei');\n }\n\n const decimalPartToRemove = decimalPart.slice(9);\n const decimalRoundingDigit = decimalPartToRemove[0];\n\n decimalPart = decimalPart.slice(0, 9);\n let wei = toWei(`${wholePart}.${decimalPart}`, 'gwei');\n\n if (Number(decimalRoundingDigit) >= 5) {\n wei = wei.add(new BN(1));\n }\n\n return wei;\n}\n\n/**\n * Used to convert values from wei hex format to dec gwei format.\n *\n * @param hex - The value in hex wei.\n * @returns The value in dec gwei as string.\n */\nexport function weiHexToGweiDec(hex: string) {\n const hexWei = new BN(stripHexPrefix(hex), 16);\n return fromWei(hexWei, 'gwei').toString(10);\n}\n\n/**\n * Return a URL that can be used to obtain ETH for a given network.\n *\n * @param networkCode - Network code of desired network.\n * @param address - Address to deposit obtained ETH.\n * @param amount - How much ETH is desired.\n * @returns URL to buy ETH based on network.\n */\nexport function getBuyURL(\n networkCode = '1',\n address?: string,\n amount = 5,\n): string | undefined {\n switch (networkCode) {\n case '1':\n return `https://buy.coinbase.com/?code=9ec56d01-7e81-5017-930c-513daa27bb6a&amount=${amount}&address=${address}&crypto_currency=ETH`;\n case '5':\n return 'https://goerli-faucet.slock.it/';\n case '11155111':\n return 'https://sepoliafaucet.net/';\n default:\n return undefined;\n }\n}\n\n/**\n * Converts a hex string to a BN object.\n *\n * @param inputHex - Number represented as a hex string.\n * @returns A BN instance.\n */\nexport function hexToBN(inputHex: string) {\n return inputHex ? new BN(stripHexPrefix(inputHex), 16) : new BN(0);\n}\n\n/**\n * A helper function that converts hex data to human readable string.\n *\n * @param hex - The hex string to convert to string.\n * @returns A human readable string conversion.\n */\nexport function hexToText(hex: string) {\n try {\n const stripped = stripHexPrefix(hex);\n const buff = Buffer.from(stripped, 'hex');\n return buff.toString('utf8');\n } catch (e) {\n /* istanbul ignore next */\n return hex;\n }\n}\n\n/**\n * Parses a hex string and converts it into a number that can be operated on in a bignum-safe,\n * base-10 way.\n *\n * @param value - A base-16 number encoded as a string.\n * @returns The number as a BN object in base-16 mode.\n */\nexport function fromHex(value: string | BN): BN {\n if (BN.isBN(value)) {\n return value;\n }\n return new BN(hexToBN(value).toString(10));\n}\n\n/**\n * Converts an integer to a hexadecimal representation.\n *\n * @param value - An integer, an integer encoded as a base-10 string, or a BN.\n * @returns The integer encoded as a hex string.\n */\nexport function toHex(value: number | string | BN): Hex {\n if (typeof value === 'string' && isStrictHexString(value)) {\n return value;\n }\n const hexString = BN.isBN(value)\n ? value.toString(16)\n : new BN(value.toString(), 10).toString(16);\n return `0x${hexString}`;\n}\n\n/**\n * Execute and return an asynchronous operation without throwing errors.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecute(\n operation: () => Promise<any>,\n logError = false,\n) {\n try {\n return await operation();\n } catch (error: any) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Execute and return an asynchronous operation with a timeout.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @param timeout - Timeout to fail the operation.\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecuteWithTimeout(\n operation: () => Promise<any>,\n logError = false,\n timeout = 500,\n) {\n try {\n return await Promise.race([\n operation(),\n new Promise<void>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Convert an address to a checksummed hexidecimal address.\n *\n * @param address - The address to convert.\n * @returns A 0x-prefixed hexidecimal checksummed address.\n */\nexport function toChecksumHexAddress(address: string) {\n const hexPrefixed = addHexPrefix(address);\n if (!isHexString(hexPrefixed)) {\n // Version 5.1 of ethereumjs-utils would have returned '0xY' for input 'y'\n // but we shouldn't waste effort trying to change case on a clearly invalid\n // string. Instead just return the hex prefixed original string which most\n // closely mimics the original behavior.\n return hexPrefixed;\n }\n return toChecksumAddress(hexPrefixed);\n}\n\n/**\n * Validates that the input is a hex address. This utility method is a thin\n * wrapper around ethereumjs-util.isValidAddress, with the exception that it\n * by default will return true for hex strings that meet the length requirement\n * of a hex address, but are not prefixed with `0x`.\n *\n * @param possibleAddress - Input parameter to check against.\n * @param options - The validation options.\n * @param options.allowNonPrefixed - If true will allow addresses without `0x` prefix.`\n * @returns Whether or not the input is a valid hex address.\n */\nexport function isValidHexAddress(\n possibleAddress: string,\n { allowNonPrefixed = true } = {},\n) {\n const addressToCheck = allowNonPrefixed\n ? addHexPrefix(possibleAddress)\n : possibleAddress;\n if (!isHexString(addressToCheck)) {\n return false;\n }\n\n return isValidAddress(addressToCheck);\n}\n\n/**\n * Returns whether the given code corresponds to a smart contract.\n *\n * @param code - The potential smart contract code.\n * @returns Whether the code was smart contract code or not.\n */\nexport function isSmartContractCode(code: string) {\n /* istanbul ignore if */\n if (!code) {\n return false;\n }\n // Geth will return '0x', and ganache-core v2.2.1 will return '0x0'\n const smartContractCode = code !== '0x' && code !== '0x0';\n return smartContractCode;\n}\n\n/**\n * Execute fetch and verify that the response was successful.\n *\n * @param request - Request information.\n * @param options - Fetch options.\n * @returns The fetch response.\n */\nexport async function successfulFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options);\n if (!response.ok) {\n throw new Error(\n `Fetch failed with status '${response.status}' for request '${request}'`,\n );\n }\n return response;\n}\n\n/**\n * Execute fetch and return object response.\n *\n * @param request - The request information.\n * @param options - The fetch options.\n * @returns The fetch response JSON data.\n */\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await successfulFetch(request, options);\n const object = await response.json();\n return object;\n}\n\n/**\n * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.\n *\n * @param request - the request options object\n * @param request.url - The request url to query.\n * @param request.options - The fetch options.\n * @param request.timeout - Timeout to fail request\n * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context\n * @returns The fetch response JSON data or undefined (if error occurs).\n */\nexport async function fetchWithErrorHandling({\n url,\n options,\n timeout,\n errorCodesToCatch,\n}: {\n url: string;\n options?: RequestInit;\n timeout?: number;\n errorCodesToCatch?: number[];\n}) {\n let result;\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise<Response>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } else {\n result = await handleFetch(url, options);\n }\n } catch (e) {\n logOrRethrowError(e, errorCodesToCatch);\n }\n return result;\n}\n\n/**\n * Fetch that fails after timeout.\n *\n * @param url - Url to fetch.\n * @param options - Options to send with the request.\n * @param timeout - Timeout to fail request.\n * @returns Promise resolving the request.\n */\nexport async function timeoutFetch(\n url: string,\n options?: RequestInit,\n timeout = 500,\n): Promise<Response> {\n return Promise.race([\n successfulFetch(url, options),\n new Promise<Response>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n}\n\n/**\n * Normalizes the given ENS name.\n *\n * @param ensName - The ENS name.\n * @returns The normalized ENS name string.\n */\nexport function normalizeEnsName(ensName: string): string | null {\n if (ensName && typeof ensName === 'string') {\n try {\n const normalized = ensNamehash.normalize(ensName.trim());\n // this regex is only sufficient with the above call to ensNamehash.normalize\n // TODO: change 7 in regex to 3 when shorter ENS domains are live\n if (normalized.match(/^(([\\w\\d-]+)\\.)*[\\w\\d-]{7,}\\.(eth|test)$/u)) {\n return normalized;\n }\n } catch (_) {\n // do nothing\n }\n }\n return null;\n}\n\n/**\n * Wrapper method to handle EthQuery requests.\n *\n * @param ethQuery - EthQuery object initialized with a provider.\n * @param method - Method to request.\n * @param args - Arguments to send.\n * @returns Promise resolving the request.\n */\nexport function query(\n ethQuery: EthQuery,\n method: string,\n args: any[] = [],\n): Promise<any> {\n return new Promise((resolve, reject) => {\n const cb = (error: unknown, result: unknown) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n };\n\n // Using `in` rather than `hasProperty` so that we look up the prototype\n // chain for the method.\n if (method in ethQuery && typeof ethQuery[method] === 'function') {\n ethQuery[method](...args, cb);\n } else {\n ethQuery.sendAsync({ method, params: args }, cb);\n }\n });\n}\n\n/**\n * Converts valid hex strings to decimal numbers, and handles unexpected arg types.\n *\n * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.\n * @returns a decimal number.\n */\nexport const convertHexToDecimal = (\n value: string | undefined = '0x0',\n): number => {\n if (isHexString(value)) {\n return parseInt(value, 16);\n }\n\n return Number(value) ? Number(value) : 0;\n};\n\ntype PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Determines whether a value is a \"plain\" object.\n *\n * @param value - A value to check\n * @returns True if the passed value is a plain object\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template T - The non-empty array member type.\n */\nexport type NonEmptyArray<T> = [T, ...T[]];\n\n/**\n * Type guard for {@link NonEmptyArray}.\n *\n * @template T - The non-empty array member type.\n * @param value - The value to check.\n * @returns Whether the value is a non-empty array.\n */\nexport function isNonEmptyArray<T>(value: T[]): value is NonEmptyArray<T> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: any, codesToCatch: number[] = []) {\n if (!error) {\n return;\n }\n\n const includesErrorCodeToCatch = codesToCatch.some((code) =>\n error.message?.includes(`Fetch failed with status '${code}'`),\n );\n\n if (\n error instanceof Error &&\n (includesErrorCodeToCatch ||\n error.message?.includes('Failed to fetch') ||\n error === TIMEOUT_ERROR)\n ) {\n console.error(error);\n } else {\n throw error;\n }\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@metamask-previews/controller-utils",
3
+ "version": "4.3.1-preview.d32a7cc",
4
+ "description": "Data and convenience functions shared by multiple packages",
5
+ "keywords": [
6
+ "MetaMask",
7
+ "Ethereum"
8
+ ],
9
+ "homepage": "https://github.com/MetaMask/core/tree/main/packages/controller-utils#readme",
10
+ "bugs": {
11
+ "url": "https://github.com/MetaMask/core/issues"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/MetaMask/core.git"
16
+ },
17
+ "license": "MIT",
18
+ "main": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "files": [
21
+ "dist/"
22
+ ],
23
+ "scripts": {
24
+ "build:docs": "typedoc",
25
+ "changelog:validate": "../../scripts/validate-changelog.sh @metamask/controller-utils",
26
+ "publish:preview": "yarn npm publish --tag preview",
27
+ "test": "jest",
28
+ "test:watch": "jest --watch"
29
+ },
30
+ "dependencies": {
31
+ "@metamask/eth-query": "^3.0.1",
32
+ "@metamask/utils": "^6.2.0",
33
+ "@spruceid/siwe-parser": "1.1.3",
34
+ "eth-ens-namehash": "^2.0.8",
35
+ "eth-rpc-errors": "^4.0.2",
36
+ "ethereumjs-util": "^7.0.10",
37
+ "ethjs-unit": "^0.1.6",
38
+ "fast-deep-equal": "^3.1.3"
39
+ },
40
+ "devDependencies": {
41
+ "@metamask/auto-changelog": "^3.1.0",
42
+ "@types/jest": "^27.4.1",
43
+ "abort-controller": "^3.0.0",
44
+ "deepmerge": "^4.2.2",
45
+ "jest": "^27.5.1",
46
+ "nock": "^13.3.1",
47
+ "ts-jest": "^27.1.4",
48
+ "typedoc": "^0.22.15",
49
+ "typedoc-plugin-missing-exports": "^0.22.6",
50
+ "typescript": "~4.6.3"
51
+ },
52
+ "engines": {
53
+ "node": ">=16.0.0"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public",
57
+ "registry": "https://registry.npmjs.org/"
58
+ }
59
+ }