@metamask-previews/controller-utils 8.0.3-preview.0dea691a → 8.0.3-preview.6772b11

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.
@@ -1 +1 @@
1
- {"version":3,"file":"siwe.d.ts","sourceRoot":"","sources":["../src/siwe.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAqCtD;;;;;;;GAOG;AAIH,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,WAAW,CAAC;CACnB;AAKD,UAAU,WAAW;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAOD;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,WACnB,MAAM,kBACE,MAAM,KACrB,WAKF,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,iBAAiB,QAAS,kBAAkB,KAAG,OA4C3D,CAAC;AAEF;;;;;;GAMG;AACH,oBAAY,WAAW,GACnB;IAAE,aAAa,EAAE,IAAI,CAAC;IAAC,aAAa,EAAE,aAAa,CAAA;CAAE,GACrD;IAAE,aAAa,EAAE,KAAK,CAAC;IAAC,aAAa,EAAE,IAAI,CAAA;CAAE,CAAC;AAElD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,UAAU,cAAe;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,KAAG,WAiBxD,CAAC"}
1
+ {"version":3,"file":"siwe.d.ts","sourceRoot":"","sources":["../src/siwe.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAqCtD;;;;;;;GAOG;AAIH,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,WAAW,CAAC;CACnB;AAKD,UAAU,WAAW;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAOD;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,WACnB,MAAM,kBACE,MAAM,KACrB,WAKF,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,iBAAiB,QAAS,kBAAkB,KAAG,OA4C3D,CAAC;AAEF;;;;;;GAMG;AACH,oBAAY,WAAW,GACnB;IAAE,aAAa,EAAE,IAAI,CAAC;IAAC,aAAa,EAAE,aAAa,CAAA;CAAE,GACrD;IAAE,aAAa,EAAE,KAAK,CAAC;IAAC,aAAa,EAAE,IAAI,CAAA;CAAE,CAAC;AAElD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,UAAU,cAAe;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,KAAG,WAiBxD,CAAC"}
package/dist/siwe.js CHANGED
@@ -1,21 +1,22 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.detectSIWE = exports.isValidSIWEOrigin = exports.parseDomainParts = void 0;
4
+ const utils_1 = require("@metamask/utils");
4
5
  const siwe_parser_1 = require("@spruceid/siwe-parser");
5
- const ethereumjs_util_1 = require("ethereumjs-util");
6
6
  const logger_1 = require("./logger");
7
7
  const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'detect-siwe');
8
8
  /**
9
9
  * This function strips the hex prefix from a string if it has one.
10
+ * If the input is not a string, return it unmodified.
10
11
  *
11
12
  * @param str - The string to check
12
13
  * @returns The string without the hex prefix
13
14
  */
14
- function stripHexPrefix(str) {
15
+ function safeStripHexPrefix(str) {
15
16
  if (typeof str !== 'string') {
16
17
  return str;
17
18
  }
18
- return (0, ethereumjs_util_1.isHexPrefixed)(str) ? str.slice(2) : str;
19
+ return (0, utils_1.remove0x)(str);
19
20
  }
20
21
  /**
21
22
  * This function converts a hex string to text if it's not a 32 byte hex string.
@@ -25,7 +26,7 @@ function stripHexPrefix(str) {
25
26
  */
26
27
  function msgHexToText(hex) {
27
28
  try {
28
- const stripped = stripHexPrefix(hex);
29
+ const stripped = safeStripHexPrefix(hex);
29
30
  const buff = Buffer.from(stripped, 'hex');
30
31
  return buff.length === 32 ? hex : buff.toString('utf8');
31
32
  }
package/dist/siwe.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"siwe.js","sourceRoot":"","sources":["../src/siwe.ts"],"names":[],"mappings":";;;AAAA,uDAAsD;AACtD,qDAAgD;AAEhD,qCAA6D;AAE7D,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,aAAa,CAAC,CAAC;AAE7D;;;;;GAKG;AACH,SAAS,cAAc,CAAC,GAAW;IACjC,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,OAAO,GAAG,CAAC;KACZ;IACD,OAAO,IAAA,+BAAa,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,SAAS,YAAY,CAAC,GAAW;IAC/B,IAAI;QACF,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC;QACrC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;QAC1C,OAAO,IAAI,CAAC,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;KACzD;IAAC,OAAO,CAAC,EAAE;QACV,GAAG,CAAC,CAAC,CAAC,CAAC;QACP,OAAO,GAAG,CAAC;KACZ;AACH,CAAC;AA4BD,MAAM,yBAAyB,GAAG;IAChC,OAAO,EAAE,IAAI;IACb,QAAQ,E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H;QAED,IACE,WAAW,CAAC,QAAQ,KAAK,EAAE;YAC3B,WAAW,CAAC,QAAQ,KAAK,WAAW,CAAC,QAAQ,EAC7C;YACA,OAAO,KAAK,CAAC;SACd;QAED,OAAO,IAAI,CAAC;KACb;IAAC,OAAO,CAAC,EAAE;QACV,GAAG,CAAC,CAAC,CAAC,CAAC;QACP,OAAO,KAAK,CAAC;KACd;AACH,CAAC,CAAC;AA5CW,QAAA,iBAAiB,qBA4C5B;AAaF;;;;;;;;;;GAUG;AACI,MAAM,UAAU,GAAG,CAAC,SAA2B,EAAe,EAAE;IACrE,IAAI;QACF,MAAM,EAAE,IAAI,EAAE,GAAG,SAAS,CAAC;QAC3B,MAAM,OAAO,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC;QACnC,MAAM,aAAa,GAAG,IAAI,2BAAa,CAAC,OAAO,CAAC,CAAC;QAEjD,OAAO;YACL,aAAa,EAAE,IAAI;YACnB,aAAa;SACd,CAAC;KACH;IAAC,OAAO,KAAK,EAAE;QACd,8CAA8C;QAC9C,OAAO;YACL,aAAa,EAAE,KAAK;YACpB,aAAa,EAAE,IAAI;SACpB,CAAC;KACH;AACH,CAAC,CAAC;AAjBW,QAAA,UAAU,cAiBrB","sourcesContent":["import { ParsedMessage } from '@spruceid/siwe-parser';\nimport { isHexPrefixed } from 'ethereumjs-util';\n\nimport { projectLogger, createModuleLogger } from './logger';\n\nconst log = createModuleLogger(projectLogger, 'detect-siwe');\n\n/**\n * This function strips the hex prefix from a string if it has one.\n *\n * @param str - The string to check\n * @returns The string without the hex prefix\n */\nfunction stripHexPrefix(str: string) {\n if (typeof str !== 'string') {\n return str;\n }\n return isHexPrefixed(str) ? str.slice(2) : str;\n}\n\n/**\n * This function converts a hex string to text if it's not a 32 byte hex string.\n *\n * @param hex - The hex string to convert to text\n * @returns The text representation of the hex string\n */\nfunction msgHexToText(hex: string): string {\n try {\n const stripped = stripHexPrefix(hex);\n const buff = Buffer.from(stripped, 'hex');\n return buff.length === 32 ? hex : buff.toString('utf8');\n } catch (e) {\n log(e);\n return hex;\n }\n}\n\n/**\n * @type WrappedSIWERequest\n *\n * Sign-In With Ethereum (SIWE)(EIP-4361) message with request metadata\n * @property {string} from - Subject account address\n * @property {string} origin - The RFC 3986 originating authority of the signing request, including scheme\n * @property {ParsedMessage} siwe - The data parsed from the message\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface WrappedSIWERequest {\n from: string;\n origin: string;\n siwe: SIWEMessage;\n}\n\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface DomainParts {\n username?: string;\n hostname: string;\n port?: string;\n}\n\nconst DEFAULT_PORTS_BY_PROTOCOL = {\n 'http:': '80',\n 'https:': '443',\n} as Record<string, string>;\n\n/**\n * Parses parts from RFC 3986 authority from EIP-4361 `domain` field.\n *\n * @param domain - input string\n * @param originProtocol - implied protocol from origin\n * @returns parsed parts\n */\nexport const parseDomainParts = (\n domain: string,\n originProtocol: string,\n): DomainParts => {\n if (domain.match(/^[^/:]*:\\/\\//u)) {\n return new URL(domain);\n }\n return new URL(`${originProtocol}//${domain}`);\n};\n\n/**\n * Validates origin of a Sign-In With Ethereum (SIWE)(EIP-4361) request.\n * As per spec:\n * hostname must match.\n * port and username must match iff specified.\n * Protocol binding and full same-origin are currently not performed.\n *\n * @param req - Signature request\n * @returns true if origin matches domain; false otherwise\n */\nexport const isValidSIWEOrigin = (req: WrappedSIWERequest): boolean => {\n try {\n const { origin, siwe } = req;\n\n // origin = scheme://[user[:password]@]domain[:port]\n // origin is supplied by environment and must match domain claim in message\n if (!origin || !siwe?.parsedMessage?.domain) {\n return false;\n }\n\n const originParts = new URL(origin);\n const domainParts = parseDomainParts(\n siwe.parsedMessage.domain,\n originParts.protocol,\n );\n\n if (\n domainParts.hostname.localeCompare(originParts.hostname, undefined, {\n sensitivity: 'accent',\n }) !== 0\n ) {\n return false;\n }\n\n if (domainParts.port !== '' && domainParts.port !== originParts.port) {\n // If origin port is not specified, protocol default is implied\n return (\n originParts.port === '' &&\n domainParts.port === DEFAULT_PORTS_BY_PROTOCOL[originParts.protocol]\n );\n }\n\n if (\n domainParts.username !== '' &&\n domainParts.username !== originParts.username\n ) {\n return false;\n }\n\n return true;\n } catch (e) {\n log(e);\n return false;\n }\n};\n\n/**\n * A locally defined object used to provide data to identify a Sign-In With Ethereum (SIWE)(EIP-4361) message and provide the parsed message\n *\n * @typedef SIWEMessage\n * @param {boolean} isSIWEMessage - Does the intercepted message conform to the SIWE specification?\n * @param {ParsedMessage} parsedMessage - The data parsed out of the message\n */\nexport type SIWEMessage =\n | { isSIWEMessage: true; parsedMessage: ParsedMessage }\n | { isSIWEMessage: false; parsedMessage: null };\n\n/**\n * This function intercepts a sign message, detects if it's a\n * Sign-In With Ethereum (SIWE)(EIP-4361) message, and returns an object with\n * relevant SIWE data.\n *\n * {@see {@link https://eips.ethereum.org/EIPS/eip-4361}}\n *\n * @param msgParams - The params of the message to sign\n * @param msgParams.data - The data of the message to sign\n * @returns An object with the relevant SIWE data\n */\nexport const detectSIWE = (msgParams: { data: string }): SIWEMessage => {\n try {\n const { data } = msgParams;\n const message = msgHexToText(data);\n const parsedMessage = new ParsedMessage(message);\n\n return {\n isSIWEMessage: true,\n parsedMessage,\n };\n } catch (error) {\n // ignore error, it's not a valid SIWE message\n return {\n isSIWEMessage: false,\n parsedMessage: null,\n };\n }\n};\n"]}
1
+ {"version":3,"file":"siwe.js","sourceRoot":"","sources":["../src/siwe.ts"],"names":[],"mappings":";;;AAAA,2CAA2C;AAC3C,uDAAsD;AAEtD,qCAA6D;AAE7D,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,aAAa,CAAC,CAAC;AAE7D;;;;;;GAMG;AACH,SAAS,kBAAkB,CAAC,GAAW;IACrC,IAAI,OAAO,GAAG,KAAK,QAAQ,EAA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C,OAAO;YACL,aAAa,EAAE,KAAK;YACpB,aAAa,EAAE,IAAI;SACpB,CAAC;KACH;AACH,CAAC,CAAC;AAjBW,QAAA,UAAU,cAiBrB","sourcesContent":["import { remove0x } from '@metamask/utils';\nimport { ParsedMessage } from '@spruceid/siwe-parser';\n\nimport { projectLogger, createModuleLogger } from './logger';\n\nconst log = createModuleLogger(projectLogger, 'detect-siwe');\n\n/**\n * This function strips the hex prefix from a string if it has one.\n * If the input is not a string, return it unmodified.\n *\n * @param str - The string to check\n * @returns The string without the hex prefix\n */\nfunction safeStripHexPrefix(str: string) {\n if (typeof str !== 'string') {\n return str;\n }\n return remove0x(str);\n}\n\n/**\n * This function converts a hex string to text if it's not a 32 byte hex string.\n *\n * @param hex - The hex string to convert to text\n * @returns The text representation of the hex string\n */\nfunction msgHexToText(hex: string): string {\n try {\n const stripped = safeStripHexPrefix(hex);\n const buff = Buffer.from(stripped, 'hex');\n return buff.length === 32 ? hex : buff.toString('utf8');\n } catch (e) {\n log(e);\n return hex;\n }\n}\n\n/**\n * @type WrappedSIWERequest\n *\n * Sign-In With Ethereum (SIWE)(EIP-4361) message with request metadata\n * @property {string} from - Subject account address\n * @property {string} origin - The RFC 3986 originating authority of the signing request, including scheme\n * @property {ParsedMessage} siwe - The data parsed from the message\n */\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface WrappedSIWERequest {\n from: string;\n origin: string;\n siwe: SIWEMessage;\n}\n\n// This interface was created before this ESLint rule was added.\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface DomainParts {\n username?: string;\n hostname: string;\n port?: string;\n}\n\nconst DEFAULT_PORTS_BY_PROTOCOL = {\n 'http:': '80',\n 'https:': '443',\n} as Record<string, string>;\n\n/**\n * Parses parts from RFC 3986 authority from EIP-4361 `domain` field.\n *\n * @param domain - input string\n * @param originProtocol - implied protocol from origin\n * @returns parsed parts\n */\nexport const parseDomainParts = (\n domain: string,\n originProtocol: string,\n): DomainParts => {\n if (domain.match(/^[^/:]*:\\/\\//u)) {\n return new URL(domain);\n }\n return new URL(`${originProtocol}//${domain}`);\n};\n\n/**\n * Validates origin of a Sign-In With Ethereum (SIWE)(EIP-4361) request.\n * As per spec:\n * hostname must match.\n * port and username must match iff specified.\n * Protocol binding and full same-origin are currently not performed.\n *\n * @param req - Signature request\n * @returns true if origin matches domain; false otherwise\n */\nexport const isValidSIWEOrigin = (req: WrappedSIWERequest): boolean => {\n try {\n const { origin, siwe } = req;\n\n // origin = scheme://[user[:password]@]domain[:port]\n // origin is supplied by environment and must match domain claim in message\n if (!origin || !siwe?.parsedMessage?.domain) {\n return false;\n }\n\n const originParts = new URL(origin);\n const domainParts = parseDomainParts(\n siwe.parsedMessage.domain,\n originParts.protocol,\n );\n\n if (\n domainParts.hostname.localeCompare(originParts.hostname, undefined, {\n sensitivity: 'accent',\n }) !== 0\n ) {\n return false;\n }\n\n if (domainParts.port !== '' && domainParts.port !== originParts.port) {\n // If origin port is not specified, protocol default is implied\n return (\n originParts.port === '' &&\n domainParts.port === DEFAULT_PORTS_BY_PROTOCOL[originParts.protocol]\n );\n }\n\n if (\n domainParts.username !== '' &&\n domainParts.username !== originParts.username\n ) {\n return false;\n }\n\n return true;\n } catch (e) {\n log(e);\n return false;\n }\n};\n\n/**\n * A locally defined object used to provide data to identify a Sign-In With Ethereum (SIWE)(EIP-4361) message and provide the parsed message\n *\n * @typedef SIWEMessage\n * @param {boolean} isSIWEMessage - Does the intercepted message conform to the SIWE specification?\n * @param {ParsedMessage} parsedMessage - The data parsed out of the message\n */\nexport type SIWEMessage =\n | { isSIWEMessage: true; parsedMessage: ParsedMessage }\n | { isSIWEMessage: false; parsedMessage: null };\n\n/**\n * This function intercepts a sign message, detects if it's a\n * Sign-In With Ethereum (SIWE)(EIP-4361) message, and returns an object with\n * relevant SIWE data.\n *\n * {@see {@link https://eips.ethereum.org/EIPS/eip-4361}}\n *\n * @param msgParams - The params of the message to sign\n * @param msgParams.data - The data of the message to sign\n * @returns An object with the relevant SIWE data\n */\nexport const detectSIWE = (msgParams: { data: string }): SIWEMessage => {\n try {\n const { data } = msgParams;\n const message = msgHexToText(data);\n const parsedMessage = new ParsedMessage(message);\n\n return {\n isSIWEMessage: true,\n parsedMessage,\n };\n } catch (error) {\n // ignore error, it's not a valid SIWE message\n return {\n isSIWEMessage: false,\n parsedMessage: null,\n };\n }\n};\n"]}
package/dist/util.d.ts CHANGED
@@ -1,7 +1,6 @@
1
- /// <reference types="bn.js" />
2
1
  import type EthQuery from '@metamask/eth-query';
3
2
  import type { Hex, Json } from '@metamask/utils';
4
- import { BN } from 'ethereumjs-util';
3
+ import BN from 'bn.js';
5
4
  /**
6
5
  * Checks whether the given number primitive chain ID is safe.
7
6
  * Because some cryptographic libraries we use expect the chain ID to be a
@@ -17,7 +16,7 @@ export declare function isSafeChainId(chainId: Hex): boolean;
17
16
  * @param inputBn - BN instance to convert to a hex string.
18
17
  * @returns A '0x'-prefixed hex string.
19
18
  */
20
- export declare function BNToHex(inputBn: any): string;
19
+ export declare function BNToHex(inputBn: any): `0x${string}`;
21
20
  /**
22
21
  * Used to multiply a BN by a fraction.
23
22
  *
@@ -102,14 +101,14 @@ export declare function safelyExecuteWithTimeout<Result>(operation: () => Promis
102
101
  * Convert an address to a checksummed hexidecimal address.
103
102
  *
104
103
  * @param address - The address to convert.
105
- * @returns A 0x-prefixed hexidecimal checksummed address.
104
+ * @returns A 0x-prefixed hexidecimal checksummed address, if address is valid. Otherwise original input 0x-prefixe, if address is valid. Otherwise original input 0x-prefixed.
106
105
  */
107
106
  export declare function toChecksumHexAddress(address: string): string;
108
107
  /**
109
108
  * Validates that the input is a hex address. This utility method is a thin
110
- * wrapper around ethereumjs-util.isValidAddress, with the exception that it
111
- * by default will return true for hex strings that meet the length requirement
112
- * of a hex address, but are not prefixed with `0x`.
109
+ * wrapper around @metamask/utils.isValidHexAddress, with the exception that it
110
+ * by default will return true for hex strings that are otherwise valid
111
+ * hex addresses, but are not prefixed with `0x`.
113
112
  *
114
113
  * @param possibleAddress - Input parameter to check against.
115
114
  * @param options - The validation options.
@@ -1 +1 @@
1
- {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAEhD,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAGjD,OAAO,EAIL,EAAE,EAGH,MAAM,iBAAiB,CAAC;AAOzB;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAUnD;AACD;;;;;GAKG;AAGH,wBAAgB,OAAO,CAAC,OAAO,EAAE,GAAG,UAEnC;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAGxB,QAAQ,EAAE,GAAG,EACb,SAAS,EAAE,MAAM,GAAG,MAAM,EAC1B,WAAW,EAAE,MAAM,GAAG,MAAM,OAK7B;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,OA4BhD;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,OAG1C;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CACvB,WAAW,SAAM,EACjB,OAAO,CAAC,EAAE,MAAM,EAChB,MAAM,SAAI,GACT,MAAM,GAAG,SAAS,CAWpB;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,MAEvC;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,UASpC;AAED;;;;;;GAMG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,EAAE,GAAG,EAAE,CAK9C;AAED;;;;;GAKG;AACH,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,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aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAElE;AAED;;;;GAIG;AACH,oBAAY,aAAa,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;AAE3C;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,KAAK,IAAI,aAAa,CAAC,CAAC,CAAC,CAExE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,IAAI,CAMzD"}
package/dist/util.js CHANGED
@@ -13,10 +13,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
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 util_1 = require("@ethereumjs/util");
16
17
  const ethjs_unit_1 = require("@metamask/ethjs-unit");
17
18
  const utils_1 = require("@metamask/utils");
19
+ const bn_js_1 = __importDefault(require("bn.js"));
18
20
  const eth_ens_namehash_1 = __importDefault(require("eth-ens-namehash"));
19
- const ethereumjs_util_1 = require("ethereumjs-util");
20
21
  const fast_deep_equal_1 = __importDefault(require("fast-deep-equal"));
21
22
  const constants_1 = require("./constants");
22
23
  const TIMEOUT_ERROR = new Error('timeout');
@@ -29,10 +30,10 @@ const TIMEOUT_ERROR = new Error('timeout');
29
30
  * @returns Whether the given chain ID is safe.
30
31
  */
31
32
  function isSafeChainId(chainId) {
32
- if (!(0, ethereumjs_util_1.isHexString)(chainId)) {
33
+ if (!(0, utils_1.isHexString)(chainId)) {
33
34
  return false;
34
35
  }
35
- const decimalChainId = Number.parseInt(chainId);
36
+ const decimalChainId = Number.parseInt(chainId, (0, utils_1.isStrictHexString)(chainId) ? 16 : 10);
36
37
  return (Number.isSafeInteger(decimalChainId) &&
37
38
  decimalChainId > 0 &&
38
39
  decimalChainId <= constants_1.MAX_SAFE_CHAIN_ID);
@@ -47,7 +48,7 @@ exports.isSafeChainId = isSafeChainId;
47
48
  // TODO: Replace `any` with type
48
49
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
49
50
  function BNToHex(inputBn) {
50
- return (0, ethereumjs_util_1.addHexPrefix)(inputBn.toString(16));
51
+ return (0, utils_1.add0x)(inputBn.toString(16));
51
52
  }
52
53
  exports.BNToHex = BNToHex;
53
54
  /**
@@ -62,8 +63,8 @@ function fractionBN(
62
63
  // TODO: Replace `any` with type
63
64
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
64
65
  targetBN, numerator, denominator) {
65
- const numBN = new ethereumjs_util_1.BN(numerator);
66
- const denomBN = new ethereumjs_util_1.BN(denominator);
66
+ const numBN = new bn_js_1.default(numerator);
67
+ const denomBN = new bn_js_1.default(denominator);
67
68
  return targetBN.mul(numBN).div(denomBN);
68
69
  }
69
70
  exports.fractionBN = fractionBN;
@@ -75,7 +76,7 @@ exports.fractionBN = fractionBN;
75
76
  */
76
77
  function gweiDecToWEIBN(n) {
77
78
  if (Number.isNaN(n)) {
78
- return new ethereumjs_util_1.BN(0);
79
+ return new bn_js_1.default(0);
79
80
  }
80
81
  const parts = n.toString().split('.');
81
82
  const wholePart = parts[0] || '0';
@@ -91,7 +92,7 @@ function gweiDecToWEIBN(n) {
91
92
  decimalPart = decimalPart.slice(0, 9);
92
93
  let wei = (0, ethjs_unit_1.toWei)(`${wholePart}.${decimalPart}`, 'gwei');
93
94
  if (Number(decimalRoundingDigit) >= 5) {
94
- wei = wei.add(new ethereumjs_util_1.BN(1));
95
+ wei = wei.add(new bn_js_1.default(1));
95
96
  }
96
97
  return wei;
97
98
  }
@@ -103,7 +104,7 @@ exports.gweiDecToWEIBN = gweiDecToWEIBN;
103
104
  * @returns The value in dec gwei as string.
104
105
  */
105
106
  function weiHexToGweiDec(hex) {
106
- const hexWei = new ethereumjs_util_1.BN((0, ethereumjs_util_1.stripHexPrefix)(hex), 16);
107
+ const hexWei = new bn_js_1.default((0, utils_1.remove0x)(hex), 16);
107
108
  return (0, ethjs_unit_1.fromWei)(hexWei, 'gwei');
108
109
  }
109
110
  exports.weiHexToGweiDec = weiHexToGweiDec;
@@ -135,7 +136,7 @@ exports.getBuyURL = getBuyURL;
135
136
  * @returns A BN instance.
136
137
  */
137
138
  function hexToBN(inputHex) {
138
- return inputHex ? new ethereumjs_util_1.BN((0, ethereumjs_util_1.stripHexPrefix)(inputHex), 16) : new ethereumjs_util_1.BN(0);
139
+ return inputHex ? new bn_js_1.default((0, utils_1.remove0x)(inputHex), 16) : new bn_js_1.default(0);
139
140
  }
140
141
  exports.hexToBN = hexToBN;
141
142
  /**
@@ -146,7 +147,7 @@ exports.hexToBN = hexToBN;
146
147
  */
147
148
  function hexToText(hex) {
148
149
  try {
149
- const stripped = (0, ethereumjs_util_1.stripHexPrefix)(hex);
150
+ const stripped = (0, utils_1.remove0x)(hex);
150
151
  const buff = Buffer.from(stripped, 'hex');
151
152
  return buff.toString('utf8');
152
153
  }
@@ -164,10 +165,10 @@ exports.hexToText = hexToText;
164
165
  * @returns The number as a BN object in base-16 mode.
165
166
  */
166
167
  function fromHex(value) {
167
- if (ethereumjs_util_1.BN.isBN(value)) {
168
+ if (bn_js_1.default.isBN(value)) {
168
169
  return value;
169
170
  }
170
- return new ethereumjs_util_1.BN(hexToBN(value).toString(10));
171
+ return new bn_js_1.default(hexToBN(value).toString(10));
171
172
  }
172
173
  exports.fromHex = fromHex;
173
174
  /**
@@ -180,9 +181,9 @@ function toHex(value) {
180
181
  if (typeof value === 'string' && (0, utils_1.isStrictHexString)(value)) {
181
182
  return value;
182
183
  }
183
- const hexString = ethereumjs_util_1.BN.isBN(value)
184
+ const hexString = bn_js_1.default.isBN(value)
184
185
  ? value.toString(16)
185
- : new ethereumjs_util_1.BN(value.toString(), 10).toString(16);
186
+ : new bn_js_1.default(value.toString(), 10).toString(16);
186
187
  return `0x${hexString}`;
187
188
  }
188
189
  exports.toHex = toHex;
@@ -242,25 +243,25 @@ exports.safelyExecuteWithTimeout = safelyExecuteWithTimeout;
242
243
  * Convert an address to a checksummed hexidecimal address.
243
244
  *
244
245
  * @param address - The address to convert.
245
- * @returns A 0x-prefixed hexidecimal checksummed address.
246
+ * @returns A 0x-prefixed hexidecimal checksummed address, if address is valid. Otherwise original input 0x-prefixe, if address is valid. Otherwise original input 0x-prefixed.
246
247
  */
247
248
  function toChecksumHexAddress(address) {
248
- const hexPrefixed = (0, ethereumjs_util_1.addHexPrefix)(address);
249
- if (!(0, ethereumjs_util_1.isHexString)(hexPrefixed)) {
249
+ const hexPrefixed = (0, utils_1.add0x)(address);
250
+ if (!(0, utils_1.isHexString)(hexPrefixed)) {
250
251
  // Version 5.1 of ethereumjs-utils would have returned '0xY' for input 'y'
251
252
  // but we shouldn't waste effort trying to change case on a clearly invalid
252
253
  // string. Instead just return the hex prefixed original string which most
253
254
  // closely mimics the original behavior.
254
255
  return hexPrefixed;
255
256
  }
256
- return (0, ethereumjs_util_1.toChecksumAddress)(hexPrefixed);
257
+ return (0, util_1.toChecksumAddress)(hexPrefixed);
257
258
  }
258
259
  exports.toChecksumHexAddress = toChecksumHexAddress;
259
260
  /**
260
261
  * Validates that the input is a hex address. This utility method is a thin
261
- * wrapper around ethereumjs-util.isValidAddress, with the exception that it
262
- * by default will return true for hex strings that meet the length requirement
263
- * of a hex address, but are not prefixed with `0x`.
262
+ * wrapper around @metamask/utils.isValidHexAddress, with the exception that it
263
+ * by default will return true for hex strings that are otherwise valid
264
+ * hex addresses, but are not prefixed with `0x`.
264
265
  *
265
266
  * @param possibleAddress - Input parameter to check against.
266
267
  * @param options - The validation options.
@@ -269,12 +270,12 @@ exports.toChecksumHexAddress = toChecksumHexAddress;
269
270
  */
270
271
  function isValidHexAddress(possibleAddress, { allowNonPrefixed = true } = {}) {
271
272
  const addressToCheck = allowNonPrefixed
272
- ? (0, ethereumjs_util_1.addHexPrefix)(possibleAddress)
273
+ ? (0, utils_1.add0x)(possibleAddress)
273
274
  : possibleAddress;
274
- if (!(0, ethereumjs_util_1.isHexString)(addressToCheck)) {
275
+ if (!(0, utils_1.isStrictHexString)(addressToCheck)) {
275
276
  return false;
276
277
  }
277
- return (0, ethereumjs_util_1.isValidAddress)(addressToCheck);
278
+ return (0, util_1.isValidAddress)(addressToCheck);
278
279
  }
279
280
  exports.isValidHexAddress = isValidHexAddress;
280
281
  /**
@@ -438,7 +439,7 @@ exports.query = query;
438
439
  * @returns a decimal number.
439
440
  */
440
441
  const convertHexToDecimal = (value = '0x0') => {
441
- if ((0, ethereumjs_util_1.isHexString)(value)) {
442
+ if ((0, utils_1.isStrictHexString)(value)) {
442
443
  return parseInt(value, 16);
443
444
  }
444
445
  return Number(value) ? Number(value) : 0;
package/dist/util.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AACA,qDAAsD;AAEtD,2CAAoD;AACpD,wEAA2C;AAC3C,qDAOyB;AACzB,sEAAwC;AAExC,2CAAgD;AAEhD,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE3C;;;;;;;GAOG;AACH,SAAgB,aAAa,CAAC,OAAY;IACxC,IAAI,CAAC,IAAA,6BAAW,EAAC,OAAO,CAAC,EAAE;QACzB,OAAO,KAAK,CAAC;KACd;IACD,MAAM,cAAc,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IAChD,OAAO,CACL,MAAM,CAAC,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CAAC,KAAK,CAAC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAC9E,CAAC;AAFD,sCAEC;AASD;;;;;;GAMG;AACH,SAAgB,eAAe,CAAI,KAAU;IAC3C,OAAO,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAClD,CAAC;AAFD,0CAEC;AAED;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,IAAI;QACF,OAAO,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,kCAMC;AAED;;;;;GAKG;AACH,gCAAgC;AAChC,8DAA8D;AAC9D,SAAS,iBAAiB,CAAC,KAAU,EAAE,eAAyB,EAAE;;IAChE,IAAI,CAAC,KAAK,EAAE;QACV,OAAO;KACR;IAED,MAAM,wBAAwB,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,WAC1D,OAAA,MAAA,KAAK,CAAC,OAAO,0CAAE,QAAQ,CAAC,6BAA6B,IAAI,GAAG,CAAC,CAAA,EAAA,CAC9D,CAAC;IAEF,IACE,KAAK,YAAY,KAAK;QACtB,CAAC,wBAAwB;aACvB,MAAA,KAAK,CAAC,OAAO,0CAAE,QAAQ,CAAC,iBAAiB,CAAC,CAAA;YAC1C,KAAK,KAAK,aAAa,CAAC,EAC1B;QACA,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;KACtB;SAAM;QACL,MAAM,KAAK,CAAC;KACb;AACH,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { fromWei, toWei } from '@metamask/ethjs-unit';\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 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 */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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');\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 * @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 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(\n request: URL | RequestInfo,\n options?: RequestInit,\n) {\n const response = await fetch(request, options);\n if (!response.ok) {\n throw new Error(\n `Fetch failed with status '${response.status}' for request '${String(\n request,\n )}'`,\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 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 (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 */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\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"]}
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAqE;AAErE,qDAAsD;AAEtD,2CAKyB;AACzB,kDAAuB;AACvB,wEAA2C;AAC3C,sEAAwC;AAExC,2CAAgD;AAEhD,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE3C;;;;;;;GAOG;AACH,SAAgB,aAAa,CAAC,OAAY;IACxC,IAAI,CAAC,IAAA,mBAAW,EAAC,OAAO,CAAC,EAAE;QACzB,OAAO,KAAK,CAAC;KACd;IACD,MAAM,cAAc,GAAG,MAAM,CAAC,QAAQ,CACpC,OAAO,EACP,IAAA,yBAAiB,EAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CACrC,CAAC;IACF,OAAO,CACL,MAAM,CAAC,aAAa,CAAC,cAAc,CAAC;QACpC,cAAc,GAAG,CAAC;QAClB,cAAc,IAAI,6BAAiB,CACpC,CAAC;AACJ,CAAC;AAbD,sCAaC;AACD;;;;;GAKG;AACH,gCAAgC;AAChC,8DAA8D;AAC9D,SAAgB,OAAO,CAAC,OAAY;IAClC,OAAO,IAAA,aAAK,EAAC,O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,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;AAClD,CAAC;AAFD,0CAEC;AAED;;;;;GAKG;AACH,SAAgB,WAAW,CAAC,KAAc;IACxC,IAAI;QACF,OAAO,IAAA,yBAAS,EAAC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC5D;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,kCAMC;AAED;;;;;GAKG;AACH,gCAAgC;AAChC,8DAA8D;AAC9D,SAAS,iBAAiB,CAAC,KAAU,EAAE,eAAyB,EAAE;;IAChE,IAAI,CAAC,KAAK,EAAE;QACV,OAAO;KACR;IAED,MAAM,wBAAwB,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,WAC1D,OAAA,MAAA,KAAK,CAAC,OAAO,0CAAE,QAAQ,CAAC,6BAA6B,IAAI,GAAG,CAAC,CAAA,EAAA,CAC9D,CAAC;IAEF,IACE,KAAK,YAAY,KAAK;QACtB,CAAC,wBAAwB;aACvB,MAAA,KAAK,CAAC,OAAO,0CAAE,QAAQ,CAAC,iBAAiB,CAAC,CAAA;YAC1C,KAAK,KAAK,aAAa,CAAC,EAC1B;QACA,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;KACtB;SAAM;QACL,MAAM,KAAK,CAAC;KACb;AACH,CAAC","sourcesContent":["import { isValidAddress, toChecksumAddress } from '@ethereumjs/util';\nimport 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} from '@metamask/utils';\nimport BN from 'bn.js';\nimport ensNamehash from 'eth-ens-namehash';\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(\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 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 */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function BNToHex(inputBn: any) {\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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(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 | 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 * @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 hexidecimal address.\n *\n * @param address - The address to convert.\n * @returns A 0x-prefixed hexidecimal checksummed address, if address is valid. Otherwise original input 0x-prefixe, if address is valid. Otherwise original input 0x-prefixed.\n */\nexport function toChecksumHexAddress(address: string) {\n const hexPrefixed = add0x(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 @metamask/utils.isValidHexAddress, with the exception that it\n * by default will return true for hex strings that are otherwise valid\n * hex addresses, 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): boolean {\n const addressToCheck = allowNonPrefixed\n ? add0x(possibleAddress)\n : possibleAddress;\n if (!isStrictHexString(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(\n request: URL | RequestInfo,\n options?: RequestInit,\n) {\n const response = await fetch(request, options);\n if (!response.ok) {\n throw new Error(\n `Fetch failed with status '${response.status}' for request '${String(\n request,\n )}'`,\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 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 */\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/controller-utils",
3
- "version": "8.0.3-preview.0dea691a",
3
+ "version": "8.0.3-preview.6772b11",
4
4
  "description": "Data and convenience functions shared by multiple packages",
5
5
  "keywords": [
6
6
  "MetaMask",
@@ -31,12 +31,12 @@
31
31
  "test:watch": "jest --watch"
32
32
  },
33
33
  "dependencies": {
34
+ "@ethereumjs/util": "^8.1.0",
34
35
  "@metamask/eth-query": "^4.0.0",
35
36
  "@metamask/ethjs-unit": "^0.3.0",
36
37
  "@metamask/utils": "^8.3.0",
37
38
  "@spruceid/siwe-parser": "1.1.3",
38
39
  "eth-ens-namehash": "^2.0.8",
39
- "ethereumjs-util": "^7.0.10",
40
40
  "fast-deep-equal": "^3.1.3"
41
41
  },
42
42
  "devDependencies": {