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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/siwe.js ADDED
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.detectSIWE = exports.isValidSIWEOrigin = exports.parseDomainParts = void 0;
4
+ const siwe_parser_1 = require("@spruceid/siwe-parser");
5
+ const ethereumjs_util_1 = require("ethereumjs-util");
6
+ const logger_1 = require("./logger");
7
+ const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'detect-siwe');
8
+ /**
9
+ * This function strips the hex prefix from a string if it has one.
10
+ *
11
+ * @param str - The string to check
12
+ * @returns The string without the hex prefix
13
+ */
14
+ function stripHexPrefix(str) {
15
+ if (typeof str !== 'string') {
16
+ return str;
17
+ }
18
+ return (0, ethereumjs_util_1.isHexPrefixed)(str) ? str.slice(2) : str;
19
+ }
20
+ /**
21
+ * This function converts a hex string to text if it's not a 32 byte hex string.
22
+ *
23
+ * @param hex - The hex string to convert to text
24
+ * @returns The text representation of the hex string
25
+ */
26
+ function msgHexToText(hex) {
27
+ try {
28
+ const stripped = stripHexPrefix(hex);
29
+ const buff = Buffer.from(stripped, 'hex');
30
+ return buff.length === 32 ? hex : buff.toString('utf8');
31
+ }
32
+ catch (e) {
33
+ log(e);
34
+ return hex;
35
+ }
36
+ }
37
+ const DEFAULT_PORTS_BY_PROTOCOL = {
38
+ 'http:': '80',
39
+ 'https:': '443',
40
+ };
41
+ /**
42
+ * Parses parts from RFC 3986 authority from EIP-4361 `domain` field.
43
+ *
44
+ * @param domain - input string
45
+ * @param originProtocol - implied protocol from origin
46
+ * @returns parsed parts
47
+ */
48
+ const parseDomainParts = (domain, originProtocol) => {
49
+ if (domain.match(/^[^/:]*:\/\//u)) {
50
+ return new URL(domain);
51
+ }
52
+ return new URL(`${originProtocol}//${domain}`);
53
+ };
54
+ exports.parseDomainParts = parseDomainParts;
55
+ /**
56
+ * Validates origin of a Sign-In With Ethereum (SIWE)(EIP-4361) request.
57
+ * As per spec:
58
+ * hostname must match.
59
+ * port and username must match iff specified.
60
+ * Protocol binding and full same-origin are currently not performed.
61
+ *
62
+ * @param req - Signature request
63
+ * @returns true if origin matches domain; false otherwise
64
+ */
65
+ const isValidSIWEOrigin = (req) => {
66
+ var _a;
67
+ try {
68
+ const { origin, siwe } = req;
69
+ // origin = scheme://[user[:password]@]domain[:port]
70
+ // origin is supplied by environment and must match domain claim in message
71
+ if (!origin || !((_a = siwe === null || siwe === void 0 ? void 0 : siwe.parsedMessage) === null || _a === void 0 ? void 0 : _a.domain)) {
72
+ return false;
73
+ }
74
+ const originParts = new URL(origin);
75
+ const domainParts = (0, exports.parseDomainParts)(siwe.parsedMessage.domain, originParts.protocol);
76
+ if (domainParts.hostname.localeCompare(originParts.hostname, undefined, {
77
+ sensitivity: 'accent',
78
+ }) !== 0) {
79
+ return false;
80
+ }
81
+ if (domainParts.port !== '' && domainParts.port !== originParts.port) {
82
+ // If origin port is not specified, protocol default is implied
83
+ return (originParts.port === '' &&
84
+ domainParts.port === DEFAULT_PORTS_BY_PROTOCOL[originParts.protocol]);
85
+ }
86
+ if (domainParts.username !== '' &&
87
+ domainParts.username !== originParts.username) {
88
+ return false;
89
+ }
90
+ return true;
91
+ }
92
+ catch (e) {
93
+ log(e);
94
+ return false;
95
+ }
96
+ };
97
+ exports.isValidSIWEOrigin = isValidSIWEOrigin;
98
+ /**
99
+ * This function intercepts a sign message, detects if it's a
100
+ * Sign-In With Ethereum (SIWE)(EIP-4361) message, and returns an object with
101
+ * relevant SIWE data.
102
+ *
103
+ * {@see {@link https://eips.ethereum.org/EIPS/eip-4361}}
104
+ *
105
+ * @param msgParams - The params of the message to sign
106
+ * @param msgParams.data - The data of the message to sign
107
+ * @returns An object with the relevant SIWE data
108
+ */
109
+ const detectSIWE = (msgParams) => {
110
+ try {
111
+ const { data } = msgParams;
112
+ const message = msgHexToText(data);
113
+ const parsedMessage = new siwe_parser_1.ParsedMessage(message);
114
+ return {
115
+ isSIWEMessage: true,
116
+ parsedMessage,
117
+ };
118
+ }
119
+ catch (error) {
120
+ // ignore error, it's not a valid SIWE message
121
+ return {
122
+ isSIWEMessage: false,
123
+ parsedMessage: null,
124
+ };
125
+ }
126
+ };
127
+ exports.detectSIWE = detectSIWE;
128
+ //# sourceMappingURL=siwe.js.map
@@ -0,0 +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;AAsBD,MAAM,yBAAyB,GAAG;IAChC,OAAO,EAAE,IAAI;IACb,QAAQ,EAAE,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ED,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 */\nexport interface WrappedSIWERequest {\n from: string;\n origin: string;\n siwe: SIWEMessage;\n}\n\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"]}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The names of built-in Infura networks
3
+ */
4
+ export declare const InfuraNetworkType: {
5
+ readonly mainnet: "mainnet";
6
+ readonly goerli: "goerli";
7
+ readonly sepolia: "sepolia";
8
+ readonly 'linea-goerli': "linea-goerli";
9
+ readonly 'linea-mainnet': "linea-mainnet";
10
+ };
11
+ export declare type InfuraNetworkType = (typeof InfuraNetworkType)[keyof typeof InfuraNetworkType];
12
+ /**
13
+ * The "network type"; either the name of a built-in network, or "rpc" for custom networks.
14
+ */
15
+ export declare const NetworkType: {
16
+ readonly rpc: "rpc";
17
+ readonly mainnet: "mainnet";
18
+ readonly goerli: "goerli";
19
+ readonly sepolia: "sepolia";
20
+ readonly 'linea-goerli': "linea-goerli";
21
+ readonly 'linea-mainnet': "linea-mainnet";
22
+ };
23
+ export declare type NetworkType = (typeof NetworkType)[keyof typeof NetworkType];
24
+ /**
25
+ * A helper to determine whether a given input is NetworkType.
26
+ *
27
+ * @param val - the value to check whether it is NetworkType or not.
28
+ * @returns boolean indicating whether or not the argument is NetworkType.
29
+ */
30
+ export declare function isNetworkType(val: any): val is NetworkType;
31
+ /**
32
+ * Names of networks built into the wallet.
33
+ *
34
+ * This includes both Infura and non-Infura networks.
35
+ */
36
+ export declare enum BuiltInNetworkName {
37
+ Mainnet = "mainnet",
38
+ Goerli = "goerli",
39
+ Sepolia = "sepolia",
40
+ LineaGoerli = "linea-goerli",
41
+ LineaMainnet = "linea-mainnet",
42
+ Aurora = "aurora"
43
+ }
44
+ /**
45
+ * Decimal string chain IDs of built-in networks, by name.
46
+ *
47
+ * `toHex` not invoked to avoid cyclic dependency
48
+ */
49
+ export declare const ChainId: {
50
+ readonly mainnet: "0x1";
51
+ readonly goerli: "0x5";
52
+ readonly sepolia: "0xaa36a7";
53
+ readonly aurora: "0x4e454152";
54
+ readonly "linea-goerli": "0xe704";
55
+ readonly "linea-mainnet": "0xe708";
56
+ };
57
+ export declare type ChainId = (typeof ChainId)[keyof typeof ChainId];
58
+ /**
59
+ * Decimal string network IDs of built-in Infura networks, by name.
60
+ */
61
+ export declare const NetworkId: {
62
+ readonly mainnet: "1";
63
+ readonly goerli: "5";
64
+ readonly sepolia: "11155111";
65
+ readonly "linea-goerli": "59140";
66
+ readonly "linea-mainnet": "59144";
67
+ };
68
+ export declare type NetworkId = (typeof NetworkId)[keyof typeof NetworkId];
69
+ export declare enum NetworksTicker {
70
+ mainnet = "ETH",
71
+ goerli = "GoerliETH",
72
+ sepolia = "SepoliaETH",
73
+ 'linea-goerli' = "LineaETH",
74
+ 'linea-mainnet' = "ETH",
75
+ rpc = ""
76
+ }
77
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;CAMpB,CAAC;AAEX,oBAAY,iBAAiB,GAC3B,CAAC,OAAO,iBAAiB,CAAC,CAAC,MAAM,OAAO,iBAAiB,CAAC,CAAC;AAE7D;;GAEG;AACH,eAAO,MAAM,WAAW;;;;;;;CAGd,CAAC;AAEX,oBAAY,WAAW,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,OAAO,WAAW,CAAC,CAAC;AAEzE;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,GAAG,IAAI,WAAW,CAE1D;AAED;;;;GAIG;AACH,oBAAY,kBAAkB;IAC5B,OAAO,YAAY;IACnB,MAAM,WAAW;IACjB,OAAO,YAAY;IACnB,WAAW,iBAAiB;IAC5B,YAAY,kBAAkB;IAC9B,MAAM,WAAW;CAClB;AAED;;;;GAIG;AACH,eAAO,MAAM,OAAO;;;;;;;CAOV,CAAC;AACX,oBAAY,OAAO,GAAG,CAAC,OAAO,OAAO,CAAC,CAAC,MAAM,OAAO,OAAO,CAAC,CAAC;AAE7D;;GAEG;AACH,eAAO,MAAM,SAAS;;;;;;CAMZ,CAAC;AACX,oBAAY,SAAS,GAAG,CAAC,OAAO,SAAS,CAAC,CAAC,MAAM,OAAO,SAAS,CAAC,CAAC;AAEnE,oBAAY,cAAc;IACxB,OAAO,QAAQ;IACf,MAAM,cAAc;IACpB,OAAO,eAAe;IACtB,cAAc,aAAa;IAC3B,eAAe,QAAQ;IACvB,GAAG,KAAK;CACT"}
package/dist/types.js ADDED
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NetworksTicker = exports.NetworkId = exports.ChainId = exports.BuiltInNetworkName = exports.isNetworkType = exports.NetworkType = exports.InfuraNetworkType = void 0;
4
+ /**
5
+ * The names of built-in Infura networks
6
+ */
7
+ exports.InfuraNetworkType = {
8
+ mainnet: 'mainnet',
9
+ goerli: 'goerli',
10
+ sepolia: 'sepolia',
11
+ 'linea-goerli': 'linea-goerli',
12
+ 'linea-mainnet': 'linea-mainnet',
13
+ };
14
+ /**
15
+ * The "network type"; either the name of a built-in network, or "rpc" for custom networks.
16
+ */
17
+ exports.NetworkType = Object.assign(Object.assign({}, exports.InfuraNetworkType), { rpc: 'rpc' });
18
+ /**
19
+ * A helper to determine whether a given input is NetworkType.
20
+ *
21
+ * @param val - the value to check whether it is NetworkType or not.
22
+ * @returns boolean indicating whether or not the argument is NetworkType.
23
+ */
24
+ function isNetworkType(val) {
25
+ return Object.values(exports.NetworkType).includes(val);
26
+ }
27
+ exports.isNetworkType = isNetworkType;
28
+ /**
29
+ * Names of networks built into the wallet.
30
+ *
31
+ * This includes both Infura and non-Infura networks.
32
+ */
33
+ var BuiltInNetworkName;
34
+ (function (BuiltInNetworkName) {
35
+ BuiltInNetworkName["Mainnet"] = "mainnet";
36
+ BuiltInNetworkName["Goerli"] = "goerli";
37
+ BuiltInNetworkName["Sepolia"] = "sepolia";
38
+ BuiltInNetworkName["LineaGoerli"] = "linea-goerli";
39
+ BuiltInNetworkName["LineaMainnet"] = "linea-mainnet";
40
+ BuiltInNetworkName["Aurora"] = "aurora";
41
+ })(BuiltInNetworkName = exports.BuiltInNetworkName || (exports.BuiltInNetworkName = {}));
42
+ /**
43
+ * Decimal string chain IDs of built-in networks, by name.
44
+ *
45
+ * `toHex` not invoked to avoid cyclic dependency
46
+ */
47
+ exports.ChainId = {
48
+ [BuiltInNetworkName.Mainnet]: '0x1',
49
+ [BuiltInNetworkName.Goerli]: '0x5',
50
+ [BuiltInNetworkName.Sepolia]: '0xaa36a7',
51
+ [BuiltInNetworkName.Aurora]: '0x4e454152',
52
+ [BuiltInNetworkName.LineaGoerli]: '0xe704',
53
+ [BuiltInNetworkName.LineaMainnet]: '0xe708', // toHex(59144)
54
+ };
55
+ /**
56
+ * Decimal string network IDs of built-in Infura networks, by name.
57
+ */
58
+ exports.NetworkId = {
59
+ [exports.InfuraNetworkType.mainnet]: '1',
60
+ [exports.InfuraNetworkType.goerli]: '5',
61
+ [exports.InfuraNetworkType.sepolia]: '11155111',
62
+ [exports.InfuraNetworkType['linea-goerli']]: '59140',
63
+ [exports.InfuraNetworkType['linea-mainnet']]: '59144',
64
+ };
65
+ var NetworksTicker;
66
+ (function (NetworksTicker) {
67
+ NetworksTicker["mainnet"] = "ETH";
68
+ NetworksTicker["goerli"] = "GoerliETH";
69
+ NetworksTicker["sepolia"] = "SepoliaETH";
70
+ NetworksTicker["linea-goerli"] = "LineaETH";
71
+ NetworksTicker["linea-mainnet"] = "ETH";
72
+ NetworksTicker["rpc"] = "";
73
+ })(NetworksTicker = exports.NetworksTicker || (exports.NetworksTicker = {}));
74
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AAAA;;GAEG;AACU,QAAA,iBAAiB,GAAG;IAC/B,OAAO,EAAE,SAAS;IAClB,MAAM,EAAE,QAAQ;IAChB,OAAO,EAAE,SAAS;IAClB,cAAc,EAAE,cAAc;IAC9B,eAAe,EAAE,eAAe;CACxB,CAAC;AAKX;;GAEG;AACU,QAAA,WAAW,GAAG,gCACtB,yBAAiB,KACpB,GAAG,EAAE,KAAK,GACF,CAAC;AAIX;;;;;GAKG;AACH,SAAgB,aAAa,CAAC,GAAQ;IACpC,OAAO,MAAM,CAAC,MAAM,CAAC,mBAAW,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AAClD,CAAC;AAFD,sCAEC;AAED;;;;GAIG;AACH,IAAY,kBAOX;AAPD,WAAY,kBAAkB;IAC5B,yCAAmB,CAAA;IACnB,uCAAiB,CAAA;IACjB,yCAAmB,CAAA;IACnB,kDAA4B,CAAA;IAC5B,oDAA8B,CAAA;IAC9B,uCAAiB,CAAA;AACnB,CAAC,EAPW,kBAAkB,GAAlB,0BAAkB,KAAlB,0BAAkB,QAO7B;AAED;;;;GAIG;AACU,QAAA,OAAO,GAAG;IACrB,CAAC,kBAAkB,CAAC,OAAO,CAAC,EAAE,KAAK;IACnC,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,KAAK;IAClC,CAAC,kBAAkB,CAAC,OAAO,CAAC,EAAE,UAAU;IACxC,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,YAAY;IACzC,CAAC,kBAAkB,CAAC,WAAW,CAAC,EAAE,QAAQ;IAC1C,CAAC,kBAAkB,CAAC,YAAY,CAAC,EAAE,QAAQ,EAAE,eAAe;CACpD,CAAC;AAGX;;GAEG;AACU,QAAA,SAAS,GAAG;IACvB,CAAC,yBAAiB,CAAC,OAAO,CAAC,EAAE,GAAG;IAChC,CAAC,yBAAiB,CAAC,MAAM,CAAC,EAAE,GAAG;IAC/B,CAAC,yBAAiB,CAAC,OAAO,CAAC,EAAE,UAAU;IACvC,CAAC,yBAAiB,CAAC,cAAc,CAAC,CAAC,EAAE,OAAO;IAC5C,CAAC,yBAAiB,CAAC,eAAe,CAAC,CAAC,EAAE,OAAO;CACrC,CAAC;AAGX,IAAY,cAOX;AAPD,WAAY,cAAc;IACxB,iCAAe,CAAA;IACf,sCAAoB,CAAA;IACpB,wCAAsB,CAAA;IACtB,2CAA2B,CAAA;IAC3B,uCAAuB,CAAA;IACvB,0BAAQ,CAAA;AACV,CAAC,EAPW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAOzB","sourcesContent":["/**\n * The names of built-in Infura networks\n */\nexport const InfuraNetworkType = {\n mainnet: 'mainnet',\n goerli: 'goerli',\n sepolia: 'sepolia',\n 'linea-goerli': 'linea-goerli',\n 'linea-mainnet': 'linea-mainnet',\n} as const;\n\nexport type InfuraNetworkType =\n (typeof InfuraNetworkType)[keyof typeof InfuraNetworkType];\n\n/**\n * The \"network type\"; either the name of a built-in network, or \"rpc\" for custom networks.\n */\nexport const NetworkType = {\n ...InfuraNetworkType,\n rpc: 'rpc',\n} as const;\n\nexport type NetworkType = (typeof NetworkType)[keyof typeof NetworkType];\n\n/**\n * A helper to determine whether a given input is NetworkType.\n *\n * @param val - the value to check whether it is NetworkType or not.\n * @returns boolean indicating whether or not the argument is NetworkType.\n */\nexport function isNetworkType(val: any): val is NetworkType {\n return Object.values(NetworkType).includes(val);\n}\n\n/**\n * Names of networks built into the wallet.\n *\n * This includes both Infura and non-Infura networks.\n */\nexport enum BuiltInNetworkName {\n Mainnet = 'mainnet',\n Goerli = 'goerli',\n Sepolia = 'sepolia',\n LineaGoerli = 'linea-goerli',\n LineaMainnet = 'linea-mainnet',\n Aurora = 'aurora',\n}\n\n/**\n * Decimal string chain IDs of built-in networks, by name.\n *\n * `toHex` not invoked to avoid cyclic dependency\n */\nexport const ChainId = {\n [BuiltInNetworkName.Mainnet]: '0x1', // toHex(1)\n [BuiltInNetworkName.Goerli]: '0x5', // toHex(5)\n [BuiltInNetworkName.Sepolia]: '0xaa36a7', // toHex(11155111)\n [BuiltInNetworkName.Aurora]: '0x4e454152', // toHex(1313161554)\n [BuiltInNetworkName.LineaGoerli]: '0xe704', // toHex(59140)\n [BuiltInNetworkName.LineaMainnet]: '0xe708', // toHex(59144)\n} as const;\nexport type ChainId = (typeof ChainId)[keyof typeof ChainId];\n\n/**\n * Decimal string network IDs of built-in Infura networks, by name.\n */\nexport const NetworkId = {\n [InfuraNetworkType.mainnet]: '1',\n [InfuraNetworkType.goerli]: '5',\n [InfuraNetworkType.sepolia]: '11155111',\n [InfuraNetworkType['linea-goerli']]: '59140',\n [InfuraNetworkType['linea-mainnet']]: '59144',\n} as const;\nexport type NetworkId = (typeof NetworkId)[keyof typeof NetworkId];\n\nexport enum NetworksTicker {\n mainnet = 'ETH',\n goerli = 'GoerliETH',\n sepolia = 'SepoliaETH',\n 'linea-goerli' = 'LineaETH',\n 'linea-mainnet' = 'ETH',\n rpc = '',\n}\n"]}
package/dist/util.d.ts ADDED
@@ -0,0 +1,221 @@
1
+ /// <reference types="bn.js" />
2
+ import type EthQuery from '@metamask/eth-query';
3
+ import type { Hex, Json } from '@metamask/utils';
4
+ import { BN } from 'ethereumjs-util';
5
+ /**
6
+ * Checks whether the given number primitive chain ID is safe.
7
+ * Because some cryptographic libraries we use expect the chain ID to be a
8
+ * number primitive, it must not exceed a certain size.
9
+ *
10
+ * @param chainId - The chain ID to check for safety.
11
+ * @returns Whether the given chain ID is safe.
12
+ */
13
+ export declare function isSafeChainId(chainId: Hex): boolean;
14
+ /**
15
+ * Converts a BN object to a hex string with a '0x' prefix.
16
+ *
17
+ * @param inputBn - BN instance to convert to a hex string.
18
+ * @returns A '0x'-prefixed hex string.
19
+ */
20
+ export declare function BNToHex(inputBn: any): string;
21
+ /**
22
+ * Used to multiply a BN by a fraction.
23
+ *
24
+ * @param targetBN - Number to multiply by a fraction.
25
+ * @param numerator - Numerator of the fraction multiplier.
26
+ * @param denominator - Denominator of the fraction multiplier.
27
+ * @returns Product of the multiplication.
28
+ */
29
+ export declare function fractionBN(targetBN: any, numerator: number | string, denominator: number | string): any;
30
+ /**
31
+ * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts.
32
+ *
33
+ * @param n - The base 10 number to convert to WEI.
34
+ * @returns The number in WEI, as a BN.
35
+ */
36
+ export declare function gweiDecToWEIBN(n: number | string): any;
37
+ /**
38
+ * Used to convert values from wei hex format to dec gwei format.
39
+ *
40
+ * @param hex - The value in hex wei.
41
+ * @returns The value in dec gwei as string.
42
+ */
43
+ export declare function weiHexToGweiDec(hex: string): any;
44
+ /**
45
+ * Return a URL that can be used to obtain ETH for a given network.
46
+ *
47
+ * @param networkCode - Network code of desired network.
48
+ * @param address - Address to deposit obtained ETH.
49
+ * @param amount - How much ETH is desired.
50
+ * @returns URL to buy ETH based on network.
51
+ */
52
+ export declare function getBuyURL(networkCode?: string, address?: string, amount?: number): string | undefined;
53
+ /**
54
+ * Converts a hex string to a BN object.
55
+ *
56
+ * @param inputHex - Number represented as a hex string.
57
+ * @returns A BN instance.
58
+ */
59
+ export declare function hexToBN(inputHex: string): BN;
60
+ /**
61
+ * A helper function that converts hex data to human readable string.
62
+ *
63
+ * @param hex - The hex string to convert to string.
64
+ * @returns A human readable string conversion.
65
+ */
66
+ export declare function hexToText(hex: string): string;
67
+ /**
68
+ * Parses a hex string and converts it into a number that can be operated on in a bignum-safe,
69
+ * base-10 way.
70
+ *
71
+ * @param value - A base-16 number encoded as a string.
72
+ * @returns The number as a BN object in base-16 mode.
73
+ */
74
+ export declare function fromHex(value: string | BN): BN;
75
+ /**
76
+ * Converts an integer to a hexadecimal representation.
77
+ *
78
+ * @param value - An integer, an integer encoded as a base-10 string, or a BN.
79
+ * @returns The integer encoded as a hex string.
80
+ */
81
+ export declare function toHex(value: number | string | BN): Hex;
82
+ /**
83
+ * Execute and return an asynchronous operation without throwing errors.
84
+ *
85
+ * @param operation - Function returning a Promise.
86
+ * @param logError - Determines if the error should be logged.
87
+ * @returns Promise resolving to the result of the async operation.
88
+ */
89
+ export declare function safelyExecute(operation: () => Promise<any>, logError?: boolean): Promise<any>;
90
+ /**
91
+ * Execute and return an asynchronous operation with a timeout.
92
+ *
93
+ * @param operation - Function returning a Promise.
94
+ * @param logError - Determines if the error should be logged.
95
+ * @param timeout - Timeout to fail the operation.
96
+ * @returns Promise resolving to the result of the async operation.
97
+ */
98
+ export declare function safelyExecuteWithTimeout(operation: () => Promise<any>, logError?: boolean, timeout?: number): Promise<any>;
99
+ /**
100
+ * Convert an address to a checksummed hexidecimal address.
101
+ *
102
+ * @param address - The address to convert.
103
+ * @returns A 0x-prefixed hexidecimal checksummed address.
104
+ */
105
+ export declare function toChecksumHexAddress(address: string): string;
106
+ /**
107
+ * Validates that the input is a hex address. This utility method is a thin
108
+ * wrapper around ethereumjs-util.isValidAddress, with the exception that it
109
+ * by default will return true for hex strings that meet the length requirement
110
+ * of a hex address, but are not prefixed with `0x`.
111
+ *
112
+ * @param possibleAddress - Input parameter to check against.
113
+ * @param options - The validation options.
114
+ * @param options.allowNonPrefixed - If true will allow addresses without `0x` prefix.`
115
+ * @returns Whether or not the input is a valid hex address.
116
+ */
117
+ export declare function isValidHexAddress(possibleAddress: string, { allowNonPrefixed }?: {
118
+ allowNonPrefixed?: boolean | undefined;
119
+ }): boolean;
120
+ /**
121
+ * Returns whether the given code corresponds to a smart contract.
122
+ *
123
+ * @param code - The potential smart contract code.
124
+ * @returns Whether the code was smart contract code or not.
125
+ */
126
+ export declare function isSmartContractCode(code: string): boolean;
127
+ /**
128
+ * Execute fetch and verify that the response was successful.
129
+ *
130
+ * @param request - Request information.
131
+ * @param options - Fetch options.
132
+ * @returns The fetch response.
133
+ */
134
+ export declare function successfulFetch(request: string, options?: RequestInit): Promise<Response>;
135
+ /**
136
+ * Execute fetch and return object response.
137
+ *
138
+ * @param request - The request information.
139
+ * @param options - The fetch options.
140
+ * @returns The fetch response JSON data.
141
+ */
142
+ export declare function handleFetch(request: string, options?: RequestInit): Promise<any>;
143
+ /**
144
+ * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.
145
+ *
146
+ * @param request - the request options object
147
+ * @param request.url - The request url to query.
148
+ * @param request.options - The fetch options.
149
+ * @param request.timeout - Timeout to fail request
150
+ * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context
151
+ * @returns The fetch response JSON data or undefined (if error occurs).
152
+ */
153
+ export declare function fetchWithErrorHandling({ url, options, timeout, errorCodesToCatch, }: {
154
+ url: string;
155
+ options?: RequestInit;
156
+ timeout?: number;
157
+ errorCodesToCatch?: number[];
158
+ }): Promise<any>;
159
+ /**
160
+ * Fetch that fails after timeout.
161
+ *
162
+ * @param url - Url to fetch.
163
+ * @param options - Options to send with the request.
164
+ * @param timeout - Timeout to fail request.
165
+ * @returns Promise resolving the request.
166
+ */
167
+ export declare function timeoutFetch(url: string, options?: RequestInit, timeout?: number): Promise<Response>;
168
+ /**
169
+ * Normalizes the given ENS name.
170
+ *
171
+ * @param ensName - The ENS name.
172
+ * @returns The normalized ENS name string.
173
+ */
174
+ export declare function normalizeEnsName(ensName: string): string | null;
175
+ /**
176
+ * Wrapper method to handle EthQuery requests.
177
+ *
178
+ * @param ethQuery - EthQuery object initialized with a provider.
179
+ * @param method - Method to request.
180
+ * @param args - Arguments to send.
181
+ * @returns Promise resolving the request.
182
+ */
183
+ export declare function query(ethQuery: EthQuery, method: string, args?: any[]): Promise<any>;
184
+ /**
185
+ * Converts valid hex strings to decimal numbers, and handles unexpected arg types.
186
+ *
187
+ * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.
188
+ * @returns a decimal number.
189
+ */
190
+ export declare const convertHexToDecimal: (value?: string | undefined) => number;
191
+ declare type PlainObject = Record<number | string | symbol, unknown>;
192
+ /**
193
+ * Determines whether a value is a "plain" object.
194
+ *
195
+ * @param value - A value to check
196
+ * @returns True if the passed value is a plain object
197
+ */
198
+ export declare function isPlainObject(value: unknown): value is PlainObject;
199
+ /**
200
+ * Like {@link Array}, but always non-empty.
201
+ *
202
+ * @template T - The non-empty array member type.
203
+ */
204
+ export declare type NonEmptyArray<T> = [T, ...T[]];
205
+ /**
206
+ * Type guard for {@link NonEmptyArray}.
207
+ *
208
+ * @template T - The non-empty array member type.
209
+ * @param value - The value to check.
210
+ * @returns Whether the value is a non-empty array.
211
+ */
212
+ export declare function isNonEmptyArray<T>(value: T[]): value is NonEmptyArray<T>;
213
+ /**
214
+ * Type guard for {@link Json}.
215
+ *
216
+ * @param value - The value to check.
217
+ * @returns Whether the value is valid JSON.
218
+ */
219
+ export declare function isValidJson(value: unknown): value is Json;
220
+ export {};
221
+ //# sourceMappingURL=util.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAChD,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAGjD,OAAO,EAIL,EA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