@metamask-previews/controller-utils 11.16.0-preview-102c9cee → 11.16.0-preview-de995bed
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/create-service-policy.cjs.map +1 -1
- package/dist/create-service-policy.mjs.map +1 -1
- package/dist/siwe.cjs +10 -13
- package/dist/siwe.cjs.map +1 -1
- package/dist/siwe.d.cts.map +1 -1
- package/dist/siwe.d.mts.map +1 -1
- package/dist/siwe.mjs +10 -13
- package/dist/siwe.mjs.map +1 -1
- package/dist/types.cjs +0 -2
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +0 -2
- package/dist/types.mjs.map +1 -1
- package/dist/util.cjs +24 -35
- package/dist/util.cjs.map +1 -1
- package/dist/util.d.cts +10 -10
- package/dist/util.d.cts.map +1 -1
- package/dist/util.d.mts +10 -10
- package/dist/util.d.mts.map +1 -1
- package/dist/util.mjs +24 -35
- package/dist/util.mjs.map +1 -1
- package/package.json +1 -1
package/dist/util.mjs
CHANGED
|
@@ -55,8 +55,6 @@ export function isSafeChainId(chainId) {
|
|
|
55
55
|
* @param inputBn - BN|BigNumber instance to convert to a hex string.
|
|
56
56
|
* @returns A '0x'-prefixed hex string.
|
|
57
57
|
*/
|
|
58
|
-
// TODO: Fix naming convention.
|
|
59
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
60
58
|
export function BNToHex(inputBn) {
|
|
61
59
|
return add0x(inputBn.toString(16));
|
|
62
60
|
}
|
|
@@ -76,14 +74,14 @@ export function fractionBN(targetBN, numerator, denominator) {
|
|
|
76
74
|
/**
|
|
77
75
|
* Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts.
|
|
78
76
|
*
|
|
79
|
-
* @param
|
|
77
|
+
* @param n - The base 10 number to convert to WEI.
|
|
80
78
|
* @returns The number in WEI, as a BN.
|
|
81
79
|
*/
|
|
82
|
-
export function gweiDecToWEIBN(
|
|
83
|
-
if (Number.isNaN(
|
|
80
|
+
export function gweiDecToWEIBN(n) {
|
|
81
|
+
if (Number.isNaN(n)) {
|
|
84
82
|
return new BN(0);
|
|
85
83
|
}
|
|
86
|
-
const parts =
|
|
84
|
+
const parts = n.toString().split('.');
|
|
87
85
|
const wholePart = parts[0] || '0';
|
|
88
86
|
let decimalPart = parts[1] || '';
|
|
89
87
|
if (!decimalPart) {
|
|
@@ -104,11 +102,11 @@ export function gweiDecToWEIBN(value) {
|
|
|
104
102
|
/**
|
|
105
103
|
* Used to convert values from wei hex format to dec gwei format.
|
|
106
104
|
*
|
|
107
|
-
* @param
|
|
105
|
+
* @param hex - The value in hex wei.
|
|
108
106
|
* @returns The value in dec gwei as string.
|
|
109
107
|
*/
|
|
110
|
-
export function weiHexToGweiDec(
|
|
111
|
-
const hexWei = new BN(remove0x(
|
|
108
|
+
export function weiHexToGweiDec(hex) {
|
|
109
|
+
const hexWei = new BN(remove0x(hex), 16);
|
|
112
110
|
return fromWei(hexWei, 'gwei');
|
|
113
111
|
}
|
|
114
112
|
/**
|
|
@@ -143,21 +141,18 @@ export function hexToBN(inputHex) {
|
|
|
143
141
|
/**
|
|
144
142
|
* A helper function that converts hex data to human readable string.
|
|
145
143
|
*
|
|
146
|
-
* @param
|
|
144
|
+
* @param hex - The hex string to convert to string.
|
|
147
145
|
* @returns A human readable string conversion.
|
|
148
146
|
*/
|
|
149
|
-
export function hexToText(
|
|
147
|
+
export function hexToText(hex) {
|
|
150
148
|
try {
|
|
151
|
-
const stripped = remove0x(
|
|
152
|
-
// TODO: Use `@metamask/utils` version of this function to avoid use of
|
|
153
|
-
// Buffer.
|
|
154
|
-
// eslint-disable-next-line no-restricted-globals
|
|
149
|
+
const stripped = remove0x(hex);
|
|
155
150
|
const buff = Buffer.from(stripped, 'hex');
|
|
156
151
|
return buff.toString('utf8');
|
|
157
152
|
}
|
|
158
|
-
catch {
|
|
153
|
+
catch (e) {
|
|
159
154
|
/* istanbul ignore next */
|
|
160
|
-
return
|
|
155
|
+
return hex;
|
|
161
156
|
}
|
|
162
157
|
}
|
|
163
158
|
/**
|
|
@@ -221,7 +216,7 @@ export async function safelyExecuteWithTimeout(operation, logError = false, time
|
|
|
221
216
|
try {
|
|
222
217
|
return await Promise.race([
|
|
223
218
|
operation(),
|
|
224
|
-
new Promise((
|
|
219
|
+
new Promise((_, reject) => setTimeout(() => {
|
|
225
220
|
reject(TIMEOUT_ERROR);
|
|
226
221
|
}, timeout)),
|
|
227
222
|
]);
|
|
@@ -323,7 +318,7 @@ export class HttpError extends Error {
|
|
|
323
318
|
* @param message - The error message.
|
|
324
319
|
*/
|
|
325
320
|
constructor(status, message) {
|
|
326
|
-
super(message
|
|
321
|
+
super(message || `Fetch failed with status '${status}'`);
|
|
327
322
|
this.httpStatus = status;
|
|
328
323
|
}
|
|
329
324
|
}
|
|
@@ -337,10 +332,7 @@ export class HttpError extends Error {
|
|
|
337
332
|
export async function successfulFetch(request, options) {
|
|
338
333
|
const response = await fetch(request, options);
|
|
339
334
|
if (!response.ok) {
|
|
340
|
-
throw new HttpError(response.status,
|
|
341
|
-
// TODO: Replace `String` with more specific conversion.
|
|
342
|
-
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
|
343
|
-
`Fetch failed with status '${response.status}' for request '${String(request)}'`);
|
|
335
|
+
throw new HttpError(response.status, `Fetch failed with status '${response.status}' for request '${String(request)}'`);
|
|
344
336
|
}
|
|
345
337
|
return response;
|
|
346
338
|
}
|
|
@@ -372,7 +364,7 @@ export async function fetchWithErrorHandling({ url, options, timeout, errorCodes
|
|
|
372
364
|
if (timeout) {
|
|
373
365
|
result = Promise.race([
|
|
374
366
|
await handleFetch(url, options),
|
|
375
|
-
new Promise((
|
|
367
|
+
new Promise((_, reject) => setTimeout(() => {
|
|
376
368
|
reject(TIMEOUT_ERROR);
|
|
377
369
|
}, timeout)),
|
|
378
370
|
]);
|
|
@@ -381,8 +373,8 @@ export async function fetchWithErrorHandling({ url, options, timeout, errorCodes
|
|
|
381
373
|
result = await handleFetch(url, options);
|
|
382
374
|
}
|
|
383
375
|
}
|
|
384
|
-
catch (
|
|
385
|
-
logOrRethrowError(
|
|
376
|
+
catch (e) {
|
|
377
|
+
logOrRethrowError(e, errorCodesToCatch);
|
|
386
378
|
}
|
|
387
379
|
return result;
|
|
388
380
|
}
|
|
@@ -397,7 +389,7 @@ export async function fetchWithErrorHandling({ url, options, timeout, errorCodes
|
|
|
397
389
|
export async function timeoutFetch(url, options, timeout = 500) {
|
|
398
390
|
return Promise.race([
|
|
399
391
|
successfulFetch(url, options),
|
|
400
|
-
new Promise((
|
|
392
|
+
new Promise((_, reject) => setTimeout(() => {
|
|
401
393
|
reject(TIMEOUT_ERROR);
|
|
402
394
|
}, timeout)),
|
|
403
395
|
]);
|
|
@@ -422,7 +414,7 @@ export function normalizeEnsName(ensName) {
|
|
|
422
414
|
return normalized;
|
|
423
415
|
}
|
|
424
416
|
}
|
|
425
|
-
catch {
|
|
417
|
+
catch (_) {
|
|
426
418
|
// do nothing
|
|
427
419
|
}
|
|
428
420
|
}
|
|
@@ -441,11 +433,8 @@ export function query(ethQuery, method,
|
|
|
441
433
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
442
434
|
args = []) {
|
|
443
435
|
return new Promise((resolve, reject) => {
|
|
444
|
-
const
|
|
436
|
+
const cb = (error, result) => {
|
|
445
437
|
if (error) {
|
|
446
|
-
// We don't control the error object returned by eth-query, so
|
|
447
|
-
// we can't guarantee it's an instance of Error.
|
|
448
|
-
// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
|
|
449
438
|
reject(error);
|
|
450
439
|
return;
|
|
451
440
|
}
|
|
@@ -454,10 +443,10 @@ args = []) {
|
|
|
454
443
|
// Using `in` rather than `hasProperty` so that we look up the prototype
|
|
455
444
|
// chain for the method.
|
|
456
445
|
if (method in ethQuery && typeof ethQuery[method] === 'function') {
|
|
457
|
-
ethQuery[method](...args,
|
|
446
|
+
ethQuery[method](...args, cb);
|
|
458
447
|
}
|
|
459
448
|
else {
|
|
460
|
-
ethQuery.sendAsync({ method, params: args },
|
|
449
|
+
ethQuery.sendAsync({ method, params: args }, cb);
|
|
461
450
|
}
|
|
462
451
|
});
|
|
463
452
|
}
|
|
@@ -502,7 +491,7 @@ export function isValidJson(value) {
|
|
|
502
491
|
try {
|
|
503
492
|
return deepEqual(value, JSON.parse(JSON.stringify(value)));
|
|
504
493
|
}
|
|
505
|
-
catch {
|
|
494
|
+
catch (_) {
|
|
506
495
|
return false;
|
|
507
496
|
}
|
|
508
497
|
}
|
package/dist/util.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.mjs","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,6BAA6B;AAEtD,OAAO,EACL,iBAAiB,EACjB,KAAK,EACL,WAAW,EACX,QAAQ,EACR,kBAAkB,EAClB,oBAAoB,EACrB,wBAAwB;AAEzB,OAAO,GAAE,cAAc;;AACvB,OAAO,YAAW,yBAAyB;;AAC3C,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EAAE,iBAAiB,EAAE,wBAAoB;AAIhD,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE3C,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC3C,WAAW;IACX,aAAa;IACb,WAAW;CACH,CAAC;AAEX;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,CAAC,6BAA6B,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,GAAG,KAAK,UAAU,CAAC,CACxE,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,OAAY;IACxC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,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KAAK,CAAC;QACd,CAAC;IACH,CAAC;SAAM,CAAC;QACN,+DAA+D;QAC/D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAAc,EACd,MAAc;IAEd,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC7D,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC;AACvD,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { fromWei, toWei } from '@metamask/ethjs-unit';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n isStrictHexString,\n add0x,\n isHexString,\n remove0x,\n getChecksumAddress,\n isHexChecksumAddress,\n} from '@metamask/utils';\nimport type { BigNumber } from 'bignumber.js';\nimport BN from 'bn.js';\nimport ensNamehash from 'eth-ens-namehash';\nimport deepEqual from 'fast-deep-equal';\nimport { memoize } from 'lodash';\n\nimport { MAX_SAFE_CHAIN_ID } from './constants';\n\nexport type { BigNumber };\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\nexport const PROTOTYPE_POLLUTION_BLOCKLIST = [\n '__proto__',\n 'constructor',\n 'prototype',\n] as const;\n\n/**\n * Checks whether a dynamic property key could be used in\n * a [prototype pollution attack](https://portswigger.net/web-security/prototype-pollution).\n *\n * @param key - The dynamic key to validate.\n * @returns Whether the given dynamic key is safe to use.\n */\nexport function isSafeDynamicKey(key: string): boolean {\n return (\n typeof key === 'string' &&\n !PROTOTYPE_POLLUTION_BLOCKLIST.some((blockedKey) => key === blockedKey)\n );\n}\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(\n chainId,\n isStrictHexString(chainId) ? 16 : 10,\n );\n return (\n Number.isSafeInteger(decimalChainId) &&\n decimalChainId > 0 &&\n decimalChainId <= MAX_SAFE_CHAIN_ID\n );\n}\n/**\n * Converts a BN or BigNumber object to a hex string with a '0x' prefix.\n *\n * @param inputBn - BN|BigNumber instance to convert to a hex string.\n * @returns A '0x'-prefixed hex string.\n */\n// TODO: Fix naming convention.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function BNToHex(inputBn: BN | BigNumber): Hex {\n return add0x(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: BN,\n numerator: number | string,\n denominator: number | string,\n): BN {\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 value - The base 10 number to convert to WEI.\n * @returns The number in WEI, as a BN.\n */\nexport function gweiDecToWEIBN(value: number | string): BN {\n if (Number.isNaN(value)) {\n return new BN(0);\n }\n\n const parts = value.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 hexValue - The value in hex wei.\n * @returns The value in dec gwei as string.\n */\nexport function weiHexToGweiDec(hexValue: string): string {\n const hexWei = new BN(remove0x(hexValue), 16);\n return fromWei(hexWei, 'gwei');\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): BN {\n return inputHex ? new BN(remove0x(inputHex), 16) : new BN(0);\n}\n\n/**\n * A helper function that converts hex data to human readable string.\n *\n * @param hexValue - The hex string to convert to string.\n * @returns A human readable string conversion.\n */\nexport function hexToText(hexValue: string): string {\n try {\n const stripped = remove0x(hexValue);\n // TODO: Use `@metamask/utils` version of this function to avoid use of\n // Buffer.\n // eslint-disable-next-line no-restricted-globals\n const buff = Buffer.from(stripped, 'hex');\n return buff.toString('utf8');\n } catch {\n /* istanbul ignore next */\n return hexValue;\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 | bigint | string | BN): Hex {\n if (typeof value === 'string' && isStrictHexString(value)) {\n return value;\n }\n const hexString =\n BN.isBN(value) || typeof value === 'bigint'\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 * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecute<Result>(\n operation: () => Promise<Result>,\n logError = false,\n): Promise<Result | undefined> {\n try {\n return await operation();\n } catch (error) {\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 * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecuteWithTimeout<Result>(\n operation: () => Promise<Result>,\n logError = false,\n timeout = 500,\n): Promise<Result | undefined> {\n try {\n return await Promise.race([\n operation(),\n new Promise<never>((_resolve, 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 hexadecimal address.\n *\n * @param address - The address to convert.\n * @returns The address in 0x-prefixed hexadecimal checksummed form if it is valid.\n */\nfunction toChecksumHexAddressUnmemoized(address: string): string;\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * Note that this particular overload does nothing.\n *\n * @param address - A value that is not a string (e.g. `undefined` or `null`).\n * @returns The `address` untouched.\n * @deprecated This overload is designed to gracefully handle an invalid input\n * and is only present for backward compatibility. It may be removed in a future\n * major version. Please pass a string to `toChecksumHexAddress` instead.\n */\nfunction toChecksumHexAddressUnmemoized<Type>(address: Type): Type;\n\nfunction toChecksumHexAddressUnmemoized(address: unknown): unknown {\n if (typeof address !== 'string') {\n // Mimic behavior of `addHexPrefix` from `ethereumjs-util` (which this\n // function was previously using) for backward compatibility.\n return address;\n }\n\n const hexPrefixed = add0x(address);\n\n if (!isHexString(hexPrefixed)) {\n // Version 5.1 of ethereumjs-util 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\n try {\n return getChecksumAddress(hexPrefixed);\n } catch (error) {\n // This is necessary for backward compatibility with the old behavior of\n // `ethereumjs-util` which would return the original string if the address\n // was invalid.\n if (error instanceof Error && error.message === 'Invalid hex address.') {\n return hexPrefixed;\n }\n throw error;\n }\n}\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * @param address - The address to convert. For backward compatibility reasons,\n * this can be anything, even a non-hex string with an 0x prefix, but that usage\n * is deprecated. Please use a valid hex string (with or without the `0x`\n * prefix).\n * @returns A 0x-prefixed checksummed version of `address` if it is a valid hex\n * string, or the address as given otherwise.\n */\nexport const toChecksumHexAddress: {\n (address: string): string;\n <Type>(address: Type): Type;\n} = memoize(toChecksumHexAddressUnmemoized);\n\nfunction isValidHexAddressUnmemoized(\n possibleAddress: string,\n { allowNonPrefixed = true } = {},\n): boolean {\n const addressToCheck = allowNonPrefixed\n ? add0x(possibleAddress)\n : possibleAddress;\n if (!isStrictHexString(addressToCheck)) {\n return false;\n }\n\n // We used to rely on `isValidAddress` from `@ethereumjs/util` which allows\n // for upper-case characters too. So we preserve this behavior and use our\n // faster and memoized validation function instead.\n return isHexChecksumAddress(addressToCheck);\n}\n\n/**\n * Validates that the input is a hex address. This utility method is a thin\n * wrapper around `isValidHexAddress` from `@metamask/utils`, with the exception\n * that it may return true for non-0x-prefixed hex strings (depending on the\n * option below).\n *\n * @param possibleAddress - Input parameter to check against.\n * @param options - The validation options.\n * @param options.allowNonPrefixed - If true will regard addresses without a\n * `0x` prefix as valid.\n * @returns Whether or not the input is a valid hex address.\n */\nexport const isValidHexAddress: (\n possibleAddress: string,\n options?: { allowNonPrefixed?: boolean },\n) => boolean = memoize(\n isValidHexAddressUnmemoized,\n (possibleAddress, { allowNonPrefixed = true } = {}) =>\n `${possibleAddress}-${allowNonPrefixed}`,\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): boolean {\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 * An error representing a non-200 HTTP response.\n */\nexport class HttpError extends Error {\n public httpStatus: number;\n\n /**\n * Construct an HTTP error.\n *\n * @param status - The HTTP response status.\n * @param message - The error message.\n */\n constructor(status: number, message?: string) {\n super(message ?? `Fetch failed with status '${status}'`);\n this.httpStatus = status;\n }\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(\n request: URL | RequestInfo,\n options?: RequestInit,\n): Promise<Response> {\n const response = await fetch(request, options);\n if (!response.ok) {\n throw new HttpError(\n response.status,\n // TODO: Replace `String` with more specific conversion.\n // eslint-disable-next-line @typescript-eslint/no-base-to-string\n `Fetch failed with status '${response.status}' for request '${String(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(\n request: URL | RequestInfo,\n options?: RequestInit,\n // TODO: Replace `any` with more specific type.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> {\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 // TODO: Replace `any` with more specific type.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n}): Promise<any> {\n let result;\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise<Response>((_resolve, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } else {\n result = await handleFetch(url, options);\n }\n } catch (error) {\n logOrRethrowError(error, 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>((_resolve, 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 // `.` refers to the registry root contract\n if (ensName === '.') {\n return ensName;\n }\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[] = [],\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> {\n return new Promise((resolve, reject) => {\n const callback = (error: unknown, result: unknown): void => {\n if (error) {\n // We don't control the error object returned by eth-query, so\n // we can't guarantee it's an instance of Error.\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\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, callback);\n } else {\n ethQuery.sendAsync({ method, params: args }, callback);\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 (isStrictHexString(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<Type> = [Type, ...Type[]];\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<Type>(\n value: Type[],\n): value is NonEmptyArray<Type> {\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: unknown, codesToCatch: number[] = []): void {\n if (!error) {\n return;\n }\n\n if (error instanceof Error) {\n const includesErrorCodeToCatch = codesToCatch.some((code) =>\n error.message.includes(`Fetch failed with status '${code}'`),\n );\n\n if (\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 } else {\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw error;\n }\n}\n\n/**\n * Checks if two strings are equal, ignoring case.\n *\n * @param value1 - The first string to compare.\n * @param value2 - The second string to compare.\n * @returns `true` if the strings are equal, ignoring case; otherwise, `false`.\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n"]}
|
|
1
|
+
{"version":3,"file":"util.mjs","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,6BAA6B;AAEtD,OAAO,EACL,iBAAiB,EACjB,KAAK,EACL,WAAW,EACX,QAAQ,EACR,kBAAkB,EAClB,oBAAoB,EACrB,wBAAwB;AAEzB,OAAO,GAAE,cAAc;;AACvB,OAAO,YAAW,yBAAyB;;AAC3C,OAAO,UAAS,wBAAwB;;;;AAGxC,OAAO,EAAE,iBAAiB,EAAE,wBAAoB;AAIhD,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE3C,MAAM,CAAC,MA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AAQ,CAAC,6BAA6B,IAAI,GAAG,CAAC,CAC7D,CAAC;QAEF,IACE,wBAAwB;YACxB,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAC;YACzC,KAAK,KAAK,aAAa,EACvB,CAAC;YACD,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;aAAM,CAAC;YACN,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;SAAM,CAAC;QACN,+DAA+D;QAC/D,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAAc,EACd,MAAc;IAEd,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;QAC7D,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC;AACvD,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { fromWei, toWei } from '@metamask/ethjs-unit';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n isStrictHexString,\n add0x,\n isHexString,\n remove0x,\n getChecksumAddress,\n isHexChecksumAddress,\n} from '@metamask/utils';\nimport type { BigNumber } from 'bignumber.js';\nimport BN from 'bn.js';\nimport ensNamehash from 'eth-ens-namehash';\nimport deepEqual from 'fast-deep-equal';\nimport { memoize } from 'lodash';\n\nimport { MAX_SAFE_CHAIN_ID } from './constants';\n\nexport type { BigNumber };\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\nexport const PROTOTYPE_POLLUTION_BLOCKLIST = [\n '__proto__',\n 'constructor',\n 'prototype',\n] as const;\n\n/**\n * Checks whether a dynamic property key could be used in\n * a [prototype pollution attack](https://portswigger.net/web-security/prototype-pollution).\n *\n * @param key - The dynamic key to validate.\n * @returns Whether the given dynamic key is safe to use.\n */\nexport function isSafeDynamicKey(key: string): boolean {\n return (\n typeof key === 'string' &&\n !PROTOTYPE_POLLUTION_BLOCKLIST.some((blockedKey) => key === blockedKey)\n );\n}\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(\n chainId,\n isStrictHexString(chainId) ? 16 : 10,\n );\n return (\n Number.isSafeInteger(decimalChainId) &&\n decimalChainId > 0 &&\n decimalChainId <= MAX_SAFE_CHAIN_ID\n );\n}\n/**\n * Converts a BN or BigNumber object to a hex string with a '0x' prefix.\n *\n * @param inputBn - BN|BigNumber instance to convert to a hex string.\n * @returns A '0x'-prefixed hex string.\n */\nexport function BNToHex(inputBn: BN | BigNumber) {\n return add0x(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: BN,\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(remove0x(hex), 16);\n return fromWei(hexWei, 'gwei');\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(remove0x(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 = remove0x(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 | bigint | string | BN): Hex {\n if (typeof value === 'string' && isStrictHexString(value)) {\n return value;\n }\n const hexString =\n BN.isBN(value) || typeof value === 'bigint'\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 * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecute<Result>(\n operation: () => Promise<Result>,\n logError = false,\n): Promise<Result | undefined> {\n try {\n return await operation();\n } catch (error) {\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 * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecuteWithTimeout<Result>(\n operation: () => Promise<Result>,\n logError = false,\n timeout = 500,\n): Promise<Result | undefined> {\n try {\n return await Promise.race([\n operation(),\n new Promise<never>((_, 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 hexadecimal address.\n *\n * @param address - The address to convert.\n * @returns The address in 0x-prefixed hexadecimal checksummed form if it is valid.\n */\nfunction toChecksumHexAddressUnmemoized(address: string): string;\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * Note that this particular overload does nothing.\n *\n * @param address - A value that is not a string (e.g. `undefined` or `null`).\n * @returns The `address` untouched.\n * @deprecated This overload is designed to gracefully handle an invalid input\n * and is only present for backward compatibility. It may be removed in a future\n * major version. Please pass a string to `toChecksumHexAddress` instead.\n */\nfunction toChecksumHexAddressUnmemoized<T>(address: T): T;\n\nfunction toChecksumHexAddressUnmemoized(address: unknown) {\n if (typeof address !== 'string') {\n // Mimic behavior of `addHexPrefix` from `ethereumjs-util` (which this\n // function was previously using) for backward compatibility.\n return address;\n }\n\n const hexPrefixed = add0x(address);\n\n if (!isHexString(hexPrefixed)) {\n // Version 5.1 of ethereumjs-util 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\n try {\n return getChecksumAddress(hexPrefixed);\n } catch (error) {\n // This is necessary for backward compatibility with the old behavior of\n // `ethereumjs-util` which would return the original string if the address\n // was invalid.\n if (error instanceof Error && error.message === 'Invalid hex address.') {\n return hexPrefixed;\n }\n throw error;\n }\n}\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * @param address - The address to convert. For backward compatibility reasons,\n * this can be anything, even a non-hex string with an 0x prefix, but that usage\n * is deprecated. Please use a valid hex string (with or without the `0x`\n * prefix).\n * @returns A 0x-prefixed checksummed version of `address` if it is a valid hex\n * string, or the address as given otherwise.\n */\nexport const toChecksumHexAddress: {\n (address: string): string;\n <T>(address: T): T;\n} = memoize(toChecksumHexAddressUnmemoized);\n\nfunction isValidHexAddressUnmemoized(\n possibleAddress: string,\n { allowNonPrefixed = true } = {},\n): boolean {\n const addressToCheck = allowNonPrefixed\n ? add0x(possibleAddress)\n : possibleAddress;\n if (!isStrictHexString(addressToCheck)) {\n return false;\n }\n\n // We used to rely on `isValidAddress` from `@ethereumjs/util` which allows\n // for upper-case characters too. So we preserve this behavior and use our\n // faster and memoized validation function instead.\n return isHexChecksumAddress(addressToCheck);\n}\n\n/**\n * Validates that the input is a hex address. This utility method is a thin\n * wrapper around `isValidHexAddress` from `@metamask/utils`, with the exception\n * that it may return true for non-0x-prefixed hex strings (depending on the\n * option below).\n *\n * @param possibleAddress - Input parameter to check against.\n * @param options - The validation options.\n * @param options.allowNonPrefixed - If true will regard addresses without a\n * `0x` prefix as valid.\n * @returns Whether or not the input is a valid hex address.\n */\nexport const isValidHexAddress: (\n possibleAddress: string,\n options?: { allowNonPrefixed?: boolean },\n) => boolean = memoize(\n isValidHexAddressUnmemoized,\n (possibleAddress, { allowNonPrefixed = true } = {}) =>\n `${possibleAddress}-${allowNonPrefixed}`,\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 * An error representing a non-200 HTTP response.\n */\nexport class HttpError extends Error {\n public httpStatus: number;\n\n /**\n * Construct an HTTP error.\n *\n * @param status - The HTTP response status.\n * @param message - The error message.\n */\n constructor(status: number, message?: string) {\n super(message || `Fetch failed with status '${status}'`);\n this.httpStatus = status;\n }\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(\n request: URL | RequestInfo,\n options?: RequestInit,\n) {\n const response = await fetch(request, options);\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Fetch failed with status '${response.status}' for request '${String(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(\n request: URL | RequestInfo,\n options?: RequestInit,\n) {\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 // `.` refers to the registry root contract\n if (ensName === '.') {\n return ensName;\n }\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[] = [],\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-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 (isStrictHexString(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: unknown, codesToCatch: number[] = []) {\n if (!error) {\n return;\n }\n\n if (error instanceof Error) {\n const includesErrorCodeToCatch = codesToCatch.some((code) =>\n error.message.includes(`Fetch failed with status '${code}'`),\n );\n\n if (\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 } else {\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw error;\n }\n}\n\n/**\n * Checks if two strings are equal, ignoring case.\n *\n * @param value1 - The first string to compare.\n * @param value2 - The second string to compare.\n * @returns `true` if the strings are equal, ignoring case; otherwise, `false`.\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n"]}
|
package/package.json
CHANGED