@metamask-previews/controller-utils 11.4.5-preview-62a75dc → 11.4.5-preview-e05b7d3e
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/CHANGELOG.md +4 -0
- package/dist/create-service-policy.cjs +107 -0
- package/dist/create-service-policy.cjs.map +1 -0
- package/dist/create-service-policy.d.cts +70 -0
- package/dist/create-service-policy.d.cts.map +1 -0
- package/dist/create-service-policy.d.mts +70 -0
- package/dist/create-service-policy.d.mts.map +1 -0
- package/dist/create-service-policy.mjs +103 -0
- package/dist/create-service-policy.mjs.map +1 -0
- package/dist/index.cjs +3 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -1
- package/dist/util.cjs +1 -1
- package/dist/util.cjs.map +1 -1
- package/dist/util.mjs +1 -1
- package/dist/util.mjs.map +1 -1
- package/package.json +4 -1
package/CHANGELOG.md
CHANGED
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
7
7
|
|
8
8
|
## [Unreleased]
|
9
9
|
|
10
|
+
### Added
|
11
|
+
|
12
|
+
- Add `createServicePolicy` function to assist with reducing boilerplate for service classes ([#5053](https://github.com/MetaMask/core/pull/5053))
|
13
|
+
|
10
14
|
## [11.4.5]
|
11
15
|
|
12
16
|
### Changed
|
@@ -0,0 +1,107 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.createServicePolicy = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_MAX_RETRIES = void 0;
|
4
|
+
const cockatiel_1 = require("cockatiel");
|
5
|
+
/**
|
6
|
+
* The maximum number of times that a failing service should be re-run before
|
7
|
+
* giving up.
|
8
|
+
*/
|
9
|
+
exports.DEFAULT_MAX_RETRIES = 3;
|
10
|
+
/**
|
11
|
+
* The maximum number of times that the service is allowed to fail before
|
12
|
+
* pausing further retries.
|
13
|
+
*/
|
14
|
+
exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + exports.DEFAULT_MAX_RETRIES) * 3;
|
15
|
+
/**
|
16
|
+
* The default length of time (in milliseconds) to temporarily pause retries of
|
17
|
+
* the service after enough consecutive failures.
|
18
|
+
*/
|
19
|
+
exports.DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
|
20
|
+
/**
|
21
|
+
* Constructs an object exposing an `execute` method which, given a function —
|
22
|
+
* hereafter called the "service" — will retry that service with ever increasing
|
23
|
+
* delays until it succeeds. If the policy detects too many consecutive
|
24
|
+
* failures, it will block further retries until a designated time period has
|
25
|
+
* passed; this particular behavior is primarily designed for services that wrap
|
26
|
+
* API calls so as not to make needless HTTP requests when the API is down and
|
27
|
+
* to be able to recover when the API comes back up. In addition, hooks allow
|
28
|
+
* for responding to certain events, one of which can be used to detect when an
|
29
|
+
* HTTP request is performing slowly.
|
30
|
+
*
|
31
|
+
* Internally, this function makes use of the retry and circuit breaker policies
|
32
|
+
* from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see
|
33
|
+
* there for more.
|
34
|
+
*
|
35
|
+
* @param options - The options to this function.
|
36
|
+
* @param options.maxConsecutiveFailures - The maximum number of times that the
|
37
|
+
* service is allowed to fail before pausing further retries. Defaults to 12.
|
38
|
+
* @param options.onBreak - A function which is called when the service fails
|
39
|
+
* too many times in a row (specifically, more than `maxConsecutiveFailures`).
|
40
|
+
* @param options.onRetry - A function which will be called the moment the
|
41
|
+
* policy kicks off a timer to re-run the function passed to the policy. This is
|
42
|
+
* primarily useful in tests where we are mocking timers.
|
43
|
+
* @returns The service policy.
|
44
|
+
* @example
|
45
|
+
* This function is designed to be used in the context of a service class like
|
46
|
+
* this:
|
47
|
+
* ``` ts
|
48
|
+
* class Service {
|
49
|
+
* constructor() {
|
50
|
+
* this.#policy = createServicePolicy({
|
51
|
+
* maxConsecutiveFailures: 3,
|
52
|
+
* onBreak: () => {
|
53
|
+
* console.log('Circuit broke');
|
54
|
+
* },
|
55
|
+
* });
|
56
|
+
* }
|
57
|
+
*
|
58
|
+
* async fetch() {
|
59
|
+
* return await this.#policy.execute(async () => {
|
60
|
+
* const response = await fetch('https://some/url');
|
61
|
+
* return await response.json();
|
62
|
+
* });
|
63
|
+
* }
|
64
|
+
* }
|
65
|
+
* ```
|
66
|
+
*/
|
67
|
+
function createServicePolicy({ maxConsecutiveFailures = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES, onBreak = () => {
|
68
|
+
// do nothing
|
69
|
+
}, onRetry = () => {
|
70
|
+
// do nothing
|
71
|
+
}, } = {}) {
|
72
|
+
const retryPolicy = (0, cockatiel_1.retry)(cockatiel_1.handleAll, {
|
73
|
+
// Note that although the option here is called "max attempts", it's really
|
74
|
+
// maximum number of *retries* (attempts past the initial attempt).
|
75
|
+
maxAttempts: exports.DEFAULT_MAX_RETRIES,
|
76
|
+
// Retries of the service will be executed following ever increasing delays,
|
77
|
+
// determined by a backoff formula.
|
78
|
+
backoff: new cockatiel_1.ExponentialBackoff(),
|
79
|
+
});
|
80
|
+
const circuitBreakerPolicy = (0, cockatiel_1.circuitBreaker)(cockatiel_1.handleAll, {
|
81
|
+
// While the circuit is open, any additional invocations of the service
|
82
|
+
// passed to the policy (either via automatic retries or by manually
|
83
|
+
// executing the policy again) will result in a BrokenCircuitError. This
|
84
|
+
// will remain the case until the default circuit break duration passes,
|
85
|
+
// after which the service will be allowed to run again. If the service
|
86
|
+
// succeeds, the circuit will close, otherwise it will remain open.
|
87
|
+
halfOpenAfter: exports.DEFAULT_CIRCUIT_BREAK_DURATION,
|
88
|
+
breaker: new cockatiel_1.ConsecutiveBreaker(maxConsecutiveFailures),
|
89
|
+
});
|
90
|
+
// The `onBreak` callback will be called if the service consistently throws
|
91
|
+
// for as many times as exceeds the maximum consecutive number of failures.
|
92
|
+
// Combined with the retry policy, this can happen if:
|
93
|
+
// - `maxConsecutiveFailures` < the default max retries (3) and the policy is
|
94
|
+
// executed once
|
95
|
+
// - `maxConsecutiveFailures` >= the default max retries (3) but the policy is
|
96
|
+
// executed multiple times, enough for the total number of retries to exceed
|
97
|
+
// `maxConsecutiveFailures`
|
98
|
+
circuitBreakerPolicy.onBreak(onBreak);
|
99
|
+
// The `onRetryPolicy` callback will be called each time the service is
|
100
|
+
// invoked (including retries).
|
101
|
+
retryPolicy.onRetry(onRetry);
|
102
|
+
// The retry policy really retries the circuit breaker policy, which invokes
|
103
|
+
// the service.
|
104
|
+
return (0, cockatiel_1.wrap)(retryPolicy, circuitBreakerPolicy);
|
105
|
+
}
|
106
|
+
exports.createServicePolicy = createServicePolicy;
|
107
|
+
//# sourceMappingURL=create-service-policy.cjs.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAOmB;AAKnB;;;GAGG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;GAGG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACU,QAAA,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,SAAgB,mBAAmB,CAAC,EAClC,sBAAsB,GAAG,wCAAgC,EACzD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,EACD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,MAKC,EAAE;IACJ,MAAM,WAAW,GAAG,IAAA,iBAAK,EAAC,qBAAS,EAAE;QACnC,2EAA2E;QAC3E,mEAAmE;QACnE,WAAW,EAAE,2BAAmB;QAChC,4EAA4E;QAC5E,mCAAmC;QACnC,OAAO,EAAE,IAAI,8BAAkB,EAAE;KAClC,CAAC,CAAC;IAEH,MAAM,oBAAoB,GAAG,IAAA,0BAAc,EAAC,qBAAS,EAAE;QACrD,uEAAuE;QACvE,oEAAoE;QACpE,wEAAwE;QACxE,wEAAwE;QACxE,uEAAuE;QACvE,mEAAmE;QACnE,aAAa,EAAE,sCAA8B;QAC7C,OAAO,EAAE,IAAI,8BAAkB,CAAC,sBAAsB,CAAC;KACxD,CAAC,CAAC;IAEH,2EAA2E;IAC3E,2EAA2E;IAC3E,sDAAsD;IACtD,6EAA6E;IAC7E,gBAAgB;IAChB,8EAA8E;IAC9E,8EAA8E;IAC9E,6BAA6B;IAC7B,oBAAoB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC,uEAAuE;IACvE,+BAA+B;IAC/B,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAE7B,4EAA4E;IAC5E,eAAe;IACf,OAAO,IAAA,gBAAI,EAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;AACjD,CAAC;AAlDD,kDAkDC","sourcesContent":["import {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n retry,\n wrap,\n} from 'cockatiel';\nimport type { IPolicy } from 'cockatiel';\n\nexport type { IPolicy as IServicePolicy };\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function.\n * @param options.maxConsecutiveFailures - The maximum number of times that the\n * service is allowed to fail before pausing further retries. Defaults to 12.\n * @param options.onBreak - A function which is called when the service fails\n * too many times in a row (specifically, more than `maxConsecutiveFailures`).\n * @param options.onRetry - A function which will be called the moment the\n * policy kicks off a timer to re-run the function passed to the policy. This is\n * primarily useful in tests where we are mocking timers.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxConsecutiveFailures: 3,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy({\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak = () => {\n // do nothing\n },\n onRetry = () => {\n // do nothing\n },\n}: {\n maxConsecutiveFailures?: number;\n onBreak?: () => void;\n onRetry?: () => void;\n} = {}): IPolicy {\n const retryPolicy = retry(handleAll, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: DEFAULT_MAX_RETRIES,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff: new ExponentialBackoff(),\n });\n\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until the default circuit break duration passes,\n // after which the service will be allowed to run again. If the service\n // succeeds, the circuit will close, otherwise it will remain open.\n halfOpenAfter: DEFAULT_CIRCUIT_BREAK_DURATION,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n\n // The `onBreak` callback will be called if the service consistently throws\n // for as many times as exceeds the maximum consecutive number of failures.\n // Combined with the retry policy, this can happen if:\n // - `maxConsecutiveFailures` < the default max retries (3) and the policy is\n // executed once\n // - `maxConsecutiveFailures` >= the default max retries (3) but the policy is\n // executed multiple times, enough for the total number of retries to exceed\n // `maxConsecutiveFailures`\n circuitBreakerPolicy.onBreak(onBreak);\n\n // The `onRetryPolicy` callback will be called each time the service is\n // invoked (including retries).\n retryPolicy.onRetry(onRetry);\n\n // The retry policy really retries the circuit breaker policy, which invokes\n // the service.\n return wrap(retryPolicy, circuitBreakerPolicy);\n}\n"]}
|
@@ -0,0 +1,70 @@
|
|
1
|
+
import type { IPolicy } from "cockatiel";
|
2
|
+
export type { IPolicy as IServicePolicy };
|
3
|
+
/**
|
4
|
+
* The maximum number of times that a failing service should be re-run before
|
5
|
+
* giving up.
|
6
|
+
*/
|
7
|
+
export declare const DEFAULT_MAX_RETRIES = 3;
|
8
|
+
/**
|
9
|
+
* The maximum number of times that the service is allowed to fail before
|
10
|
+
* pausing further retries.
|
11
|
+
*/
|
12
|
+
export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
|
13
|
+
/**
|
14
|
+
* The default length of time (in milliseconds) to temporarily pause retries of
|
15
|
+
* the service after enough consecutive failures.
|
16
|
+
*/
|
17
|
+
export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
|
18
|
+
/**
|
19
|
+
* Constructs an object exposing an `execute` method which, given a function —
|
20
|
+
* hereafter called the "service" — will retry that service with ever increasing
|
21
|
+
* delays until it succeeds. If the policy detects too many consecutive
|
22
|
+
* failures, it will block further retries until a designated time period has
|
23
|
+
* passed; this particular behavior is primarily designed for services that wrap
|
24
|
+
* API calls so as not to make needless HTTP requests when the API is down and
|
25
|
+
* to be able to recover when the API comes back up. In addition, hooks allow
|
26
|
+
* for responding to certain events, one of which can be used to detect when an
|
27
|
+
* HTTP request is performing slowly.
|
28
|
+
*
|
29
|
+
* Internally, this function makes use of the retry and circuit breaker policies
|
30
|
+
* from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see
|
31
|
+
* there for more.
|
32
|
+
*
|
33
|
+
* @param options - The options to this function.
|
34
|
+
* @param options.maxConsecutiveFailures - The maximum number of times that the
|
35
|
+
* service is allowed to fail before pausing further retries. Defaults to 12.
|
36
|
+
* @param options.onBreak - A function which is called when the service fails
|
37
|
+
* too many times in a row (specifically, more than `maxConsecutiveFailures`).
|
38
|
+
* @param options.onRetry - A function which will be called the moment the
|
39
|
+
* policy kicks off a timer to re-run the function passed to the policy. This is
|
40
|
+
* primarily useful in tests where we are mocking timers.
|
41
|
+
* @returns The service policy.
|
42
|
+
* @example
|
43
|
+
* This function is designed to be used in the context of a service class like
|
44
|
+
* this:
|
45
|
+
* ``` ts
|
46
|
+
* class Service {
|
47
|
+
* constructor() {
|
48
|
+
* this.#policy = createServicePolicy({
|
49
|
+
* maxConsecutiveFailures: 3,
|
50
|
+
* onBreak: () => {
|
51
|
+
* console.log('Circuit broke');
|
52
|
+
* },
|
53
|
+
* });
|
54
|
+
* }
|
55
|
+
*
|
56
|
+
* async fetch() {
|
57
|
+
* return await this.#policy.execute(async () => {
|
58
|
+
* const response = await fetch('https://some/url');
|
59
|
+
* return await response.json();
|
60
|
+
* });
|
61
|
+
* }
|
62
|
+
* }
|
63
|
+
* ```
|
64
|
+
*/
|
65
|
+
export declare function createServicePolicy({ maxConsecutiveFailures, onBreak, onRetry, }?: {
|
66
|
+
maxConsecutiveFailures?: number;
|
67
|
+
onBreak?: () => void;
|
68
|
+
onRetry?: () => void;
|
69
|
+
}): IPolicy;
|
70
|
+
//# sourceMappingURL=create-service-policy.d.cts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"create-service-policy.d.cts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB;AAEzC,YAAY,EAAE,OAAO,IAAI,cAAc,EAAE,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;GAGG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,sBAAyD,EACzD,OAEC,EACD,OAEC,GACF,GAAE;IACD,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACjB,GAAG,OAAO,CAsCf"}
|
@@ -0,0 +1,70 @@
|
|
1
|
+
import type { IPolicy } from "cockatiel";
|
2
|
+
export type { IPolicy as IServicePolicy };
|
3
|
+
/**
|
4
|
+
* The maximum number of times that a failing service should be re-run before
|
5
|
+
* giving up.
|
6
|
+
*/
|
7
|
+
export declare const DEFAULT_MAX_RETRIES = 3;
|
8
|
+
/**
|
9
|
+
* The maximum number of times that the service is allowed to fail before
|
10
|
+
* pausing further retries.
|
11
|
+
*/
|
12
|
+
export declare const DEFAULT_MAX_CONSECUTIVE_FAILURES: number;
|
13
|
+
/**
|
14
|
+
* The default length of time (in milliseconds) to temporarily pause retries of
|
15
|
+
* the service after enough consecutive failures.
|
16
|
+
*/
|
17
|
+
export declare const DEFAULT_CIRCUIT_BREAK_DURATION: number;
|
18
|
+
/**
|
19
|
+
* Constructs an object exposing an `execute` method which, given a function —
|
20
|
+
* hereafter called the "service" — will retry that service with ever increasing
|
21
|
+
* delays until it succeeds. If the policy detects too many consecutive
|
22
|
+
* failures, it will block further retries until a designated time period has
|
23
|
+
* passed; this particular behavior is primarily designed for services that wrap
|
24
|
+
* API calls so as not to make needless HTTP requests when the API is down and
|
25
|
+
* to be able to recover when the API comes back up. In addition, hooks allow
|
26
|
+
* for responding to certain events, one of which can be used to detect when an
|
27
|
+
* HTTP request is performing slowly.
|
28
|
+
*
|
29
|
+
* Internally, this function makes use of the retry and circuit breaker policies
|
30
|
+
* from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see
|
31
|
+
* there for more.
|
32
|
+
*
|
33
|
+
* @param options - The options to this function.
|
34
|
+
* @param options.maxConsecutiveFailures - The maximum number of times that the
|
35
|
+
* service is allowed to fail before pausing further retries. Defaults to 12.
|
36
|
+
* @param options.onBreak - A function which is called when the service fails
|
37
|
+
* too many times in a row (specifically, more than `maxConsecutiveFailures`).
|
38
|
+
* @param options.onRetry - A function which will be called the moment the
|
39
|
+
* policy kicks off a timer to re-run the function passed to the policy. This is
|
40
|
+
* primarily useful in tests where we are mocking timers.
|
41
|
+
* @returns The service policy.
|
42
|
+
* @example
|
43
|
+
* This function is designed to be used in the context of a service class like
|
44
|
+
* this:
|
45
|
+
* ``` ts
|
46
|
+
* class Service {
|
47
|
+
* constructor() {
|
48
|
+
* this.#policy = createServicePolicy({
|
49
|
+
* maxConsecutiveFailures: 3,
|
50
|
+
* onBreak: () => {
|
51
|
+
* console.log('Circuit broke');
|
52
|
+
* },
|
53
|
+
* });
|
54
|
+
* }
|
55
|
+
*
|
56
|
+
* async fetch() {
|
57
|
+
* return await this.#policy.execute(async () => {
|
58
|
+
* const response = await fetch('https://some/url');
|
59
|
+
* return await response.json();
|
60
|
+
* });
|
61
|
+
* }
|
62
|
+
* }
|
63
|
+
* ```
|
64
|
+
*/
|
65
|
+
export declare function createServicePolicy({ maxConsecutiveFailures, onBreak, onRetry, }?: {
|
66
|
+
maxConsecutiveFailures?: number;
|
67
|
+
onBreak?: () => void;
|
68
|
+
onRetry?: () => void;
|
69
|
+
}): IPolicy;
|
70
|
+
//# sourceMappingURL=create-service-policy.d.mts.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"create-service-policy.d.mts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,OAAO,EAAE,kBAAkB;AAEzC,YAAY,EAAE,OAAO,IAAI,cAAc,EAAE,CAAC;AAE1C;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;GAGG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,wBAAgB,mBAAmB,CAAC,EAClC,sBAAyD,EACzD,OAEC,EACD,OAEC,GACF,GAAE;IACD,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACjB,GAAG,OAAO,CAsCf"}
|
@@ -0,0 +1,103 @@
|
|
1
|
+
import { circuitBreaker, ConsecutiveBreaker, ExponentialBackoff, handleAll, retry, wrap } from "cockatiel";
|
2
|
+
/**
|
3
|
+
* The maximum number of times that a failing service should be re-run before
|
4
|
+
* giving up.
|
5
|
+
*/
|
6
|
+
export const DEFAULT_MAX_RETRIES = 3;
|
7
|
+
/**
|
8
|
+
* The maximum number of times that the service is allowed to fail before
|
9
|
+
* pausing further retries.
|
10
|
+
*/
|
11
|
+
export const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;
|
12
|
+
/**
|
13
|
+
* The default length of time (in milliseconds) to temporarily pause retries of
|
14
|
+
* the service after enough consecutive failures.
|
15
|
+
*/
|
16
|
+
export const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
|
17
|
+
/**
|
18
|
+
* Constructs an object exposing an `execute` method which, given a function —
|
19
|
+
* hereafter called the "service" — will retry that service with ever increasing
|
20
|
+
* delays until it succeeds. If the policy detects too many consecutive
|
21
|
+
* failures, it will block further retries until a designated time period has
|
22
|
+
* passed; this particular behavior is primarily designed for services that wrap
|
23
|
+
* API calls so as not to make needless HTTP requests when the API is down and
|
24
|
+
* to be able to recover when the API comes back up. In addition, hooks allow
|
25
|
+
* for responding to certain events, one of which can be used to detect when an
|
26
|
+
* HTTP request is performing slowly.
|
27
|
+
*
|
28
|
+
* Internally, this function makes use of the retry and circuit breaker policies
|
29
|
+
* from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see
|
30
|
+
* there for more.
|
31
|
+
*
|
32
|
+
* @param options - The options to this function.
|
33
|
+
* @param options.maxConsecutiveFailures - The maximum number of times that the
|
34
|
+
* service is allowed to fail before pausing further retries. Defaults to 12.
|
35
|
+
* @param options.onBreak - A function which is called when the service fails
|
36
|
+
* too many times in a row (specifically, more than `maxConsecutiveFailures`).
|
37
|
+
* @param options.onRetry - A function which will be called the moment the
|
38
|
+
* policy kicks off a timer to re-run the function passed to the policy. This is
|
39
|
+
* primarily useful in tests where we are mocking timers.
|
40
|
+
* @returns The service policy.
|
41
|
+
* @example
|
42
|
+
* This function is designed to be used in the context of a service class like
|
43
|
+
* this:
|
44
|
+
* ``` ts
|
45
|
+
* class Service {
|
46
|
+
* constructor() {
|
47
|
+
* this.#policy = createServicePolicy({
|
48
|
+
* maxConsecutiveFailures: 3,
|
49
|
+
* onBreak: () => {
|
50
|
+
* console.log('Circuit broke');
|
51
|
+
* },
|
52
|
+
* });
|
53
|
+
* }
|
54
|
+
*
|
55
|
+
* async fetch() {
|
56
|
+
* return await this.#policy.execute(async () => {
|
57
|
+
* const response = await fetch('https://some/url');
|
58
|
+
* return await response.json();
|
59
|
+
* });
|
60
|
+
* }
|
61
|
+
* }
|
62
|
+
* ```
|
63
|
+
*/
|
64
|
+
export function createServicePolicy({ maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES, onBreak = () => {
|
65
|
+
// do nothing
|
66
|
+
}, onRetry = () => {
|
67
|
+
// do nothing
|
68
|
+
}, } = {}) {
|
69
|
+
const retryPolicy = retry(handleAll, {
|
70
|
+
// Note that although the option here is called "max attempts", it's really
|
71
|
+
// maximum number of *retries* (attempts past the initial attempt).
|
72
|
+
maxAttempts: DEFAULT_MAX_RETRIES,
|
73
|
+
// Retries of the service will be executed following ever increasing delays,
|
74
|
+
// determined by a backoff formula.
|
75
|
+
backoff: new ExponentialBackoff(),
|
76
|
+
});
|
77
|
+
const circuitBreakerPolicy = circuitBreaker(handleAll, {
|
78
|
+
// While the circuit is open, any additional invocations of the service
|
79
|
+
// passed to the policy (either via automatic retries or by manually
|
80
|
+
// executing the policy again) will result in a BrokenCircuitError. This
|
81
|
+
// will remain the case until the default circuit break duration passes,
|
82
|
+
// after which the service will be allowed to run again. If the service
|
83
|
+
// succeeds, the circuit will close, otherwise it will remain open.
|
84
|
+
halfOpenAfter: DEFAULT_CIRCUIT_BREAK_DURATION,
|
85
|
+
breaker: new ConsecutiveBreaker(maxConsecutiveFailures),
|
86
|
+
});
|
87
|
+
// The `onBreak` callback will be called if the service consistently throws
|
88
|
+
// for as many times as exceeds the maximum consecutive number of failures.
|
89
|
+
// Combined with the retry policy, this can happen if:
|
90
|
+
// - `maxConsecutiveFailures` < the default max retries (3) and the policy is
|
91
|
+
// executed once
|
92
|
+
// - `maxConsecutiveFailures` >= the default max retries (3) but the policy is
|
93
|
+
// executed multiple times, enough for the total number of retries to exceed
|
94
|
+
// `maxConsecutiveFailures`
|
95
|
+
circuitBreakerPolicy.onBreak(onBreak);
|
96
|
+
// The `onRetryPolicy` callback will be called each time the service is
|
97
|
+
// invoked (including retries).
|
98
|
+
retryPolicy.onRetry(onRetry);
|
99
|
+
// The retry policy really retries the circuit breaker policy, which invokes
|
100
|
+
// the service.
|
101
|
+
return wrap(retryPolicy, circuitBreakerPolicy);
|
102
|
+
}
|
103
|
+
//# sourceMappingURL=create-service-policy.mjs.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,kBAAkB,EAClB,kBAAkB,EAClB,SAAS,EACT,KAAK,EACL,IAAI,EACL,kBAAkB;AAKnB;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8CG;AACH,MAAM,UAAU,mBAAmB,CAAC,EAClC,sBAAsB,GAAG,gCAAgC,EACzD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,EACD,OAAO,GAAG,GAAG,EAAE;IACb,aAAa;AACf,CAAC,MAKC,EAAE;IACJ,MAAM,WAAW,GAAG,KAAK,CAAC,SAAS,EAAE;QACnC,2EAA2E;QAC3E,mEAAmE;QACnE,WAAW,EAAE,mBAAmB;QAChC,4EAA4E;QAC5E,mCAAmC;QACnC,OAAO,EAAE,IAAI,kBAAkB,EAAE;KAClC,CAAC,CAAC;IAEH,MAAM,oBAAoB,GAAG,cAAc,CAAC,SAAS,EAAE;QACrD,uEAAuE;QACvE,oEAAoE;QACpE,wEAAwE;QACxE,wEAAwE;QACxE,uEAAuE;QACvE,mEAAmE;QACnE,aAAa,EAAE,8BAA8B;QAC7C,OAAO,EAAE,IAAI,kBAAkB,CAAC,sBAAsB,CAAC;KACxD,CAAC,CAAC;IAEH,2EAA2E;IAC3E,2EAA2E;IAC3E,sDAAsD;IACtD,6EAA6E;IAC7E,gBAAgB;IAChB,8EAA8E;IAC9E,8EAA8E;IAC9E,6BAA6B;IAC7B,oBAAoB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC,uEAAuE;IACvE,+BAA+B;IAC/B,WAAW,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAE7B,4EAA4E;IAC5E,eAAe;IACf,OAAO,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;AACjD,CAAC","sourcesContent":["import {\n circuitBreaker,\n ConsecutiveBreaker,\n ExponentialBackoff,\n handleAll,\n retry,\n wrap,\n} from 'cockatiel';\nimport type { IPolicy } from 'cockatiel';\n\nexport type { IPolicy as IServicePolicy };\n\n/**\n * The maximum number of times that a failing service should be re-run before\n * giving up.\n */\nexport const DEFAULT_MAX_RETRIES = 3;\n\n/**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\nexport const DEFAULT_MAX_CONSECUTIVE_FAILURES = (1 + DEFAULT_MAX_RETRIES) * 3;\n\n/**\n * The default length of time (in milliseconds) to temporarily pause retries of\n * the service after enough consecutive failures.\n */\nexport const DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;\n\n/**\n * Constructs an object exposing an `execute` method which, given a function —\n * hereafter called the \"service\" — will retry that service with ever increasing\n * delays until it succeeds. If the policy detects too many consecutive\n * failures, it will block further retries until a designated time period has\n * passed; this particular behavior is primarily designed for services that wrap\n * API calls so as not to make needless HTTP requests when the API is down and\n * to be able to recover when the API comes back up. In addition, hooks allow\n * for responding to certain events, one of which can be used to detect when an\n * HTTP request is performing slowly.\n *\n * Internally, this function makes use of the retry and circuit breaker policies\n * from the [Cockatiel](https://www.npmjs.com/package/cockatiel) library; see\n * there for more.\n *\n * @param options - The options to this function.\n * @param options.maxConsecutiveFailures - The maximum number of times that the\n * service is allowed to fail before pausing further retries. Defaults to 12.\n * @param options.onBreak - A function which is called when the service fails\n * too many times in a row (specifically, more than `maxConsecutiveFailures`).\n * @param options.onRetry - A function which will be called the moment the\n * policy kicks off a timer to re-run the function passed to the policy. This is\n * primarily useful in tests where we are mocking timers.\n * @returns The service policy.\n * @example\n * This function is designed to be used in the context of a service class like\n * this:\n * ``` ts\n * class Service {\n * constructor() {\n * this.#policy = createServicePolicy({\n * maxConsecutiveFailures: 3,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * });\n * }\n *\n * async fetch() {\n * return await this.#policy.execute(async () => {\n * const response = await fetch('https://some/url');\n * return await response.json();\n * });\n * }\n * }\n * ```\n */\nexport function createServicePolicy({\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n onBreak = () => {\n // do nothing\n },\n onRetry = () => {\n // do nothing\n },\n}: {\n maxConsecutiveFailures?: number;\n onBreak?: () => void;\n onRetry?: () => void;\n} = {}): IPolicy {\n const retryPolicy = retry(handleAll, {\n // Note that although the option here is called \"max attempts\", it's really\n // maximum number of *retries* (attempts past the initial attempt).\n maxAttempts: DEFAULT_MAX_RETRIES,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff: new ExponentialBackoff(),\n });\n\n const circuitBreakerPolicy = circuitBreaker(handleAll, {\n // While the circuit is open, any additional invocations of the service\n // passed to the policy (either via automatic retries or by manually\n // executing the policy again) will result in a BrokenCircuitError. This\n // will remain the case until the default circuit break duration passes,\n // after which the service will be allowed to run again. If the service\n // succeeds, the circuit will close, otherwise it will remain open.\n halfOpenAfter: DEFAULT_CIRCUIT_BREAK_DURATION,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n\n // The `onBreak` callback will be called if the service consistently throws\n // for as many times as exceeds the maximum consecutive number of failures.\n // Combined with the retry policy, this can happen if:\n // - `maxConsecutiveFailures` < the default max retries (3) and the policy is\n // executed once\n // - `maxConsecutiveFailures` >= the default max retries (3) but the policy is\n // executed multiple times, enough for the total number of retries to exceed\n // `maxConsecutiveFailures`\n circuitBreakerPolicy.onBreak(onBreak);\n\n // The `onRetryPolicy` callback will be called each time the service is\n // invoked (including retries).\n retryPolicy.onRetry(onRetry);\n\n // The retry policy really retries the circuit breaker policy, which invokes\n // the service.\n return wrap(retryPolicy, circuitBreakerPolicy);\n}\n"]}
|
package/dist/index.cjs
CHANGED
@@ -14,7 +14,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
14
|
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
15
15
|
};
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
17
|
-
exports.isEqualCaseInsensitive = exports.weiHexToGweiDec = exports.toHex = exports.toChecksumHexAddress = exports.timeoutFetch = exports.successfulFetch = exports.safelyExecuteWithTimeout = exports.safelyExecute = exports.query = exports.normalizeEnsName = exports.isValidHexAddress = exports.isValidJson = exports.isSmartContractCode = exports.isSafeDynamicKey = exports.isSafeChainId = exports.isPlainObject = exports.isNonEmptyArray = exports.hexToText = exports.hexToBN = exports.handleFetch = exports.gweiDecToWEIBN = exports.getBuyURL = exports.fromHex = exports.fractionBN = exports.fetchWithErrorHandling = exports.convertHexToDecimal = exports.BNToHex = void 0;
|
17
|
+
exports.isEqualCaseInsensitive = exports.weiHexToGweiDec = exports.toHex = exports.toChecksumHexAddress = exports.timeoutFetch = exports.successfulFetch = exports.safelyExecuteWithTimeout = exports.safelyExecute = exports.query = exports.normalizeEnsName = exports.isValidHexAddress = exports.isValidJson = exports.isSmartContractCode = exports.isSafeDynamicKey = exports.isSafeChainId = exports.isPlainObject = exports.isNonEmptyArray = exports.hexToText = exports.hexToBN = exports.handleFetch = exports.gweiDecToWEIBN = exports.getBuyURL = exports.fromHex = exports.fractionBN = exports.fetchWithErrorHandling = exports.convertHexToDecimal = exports.BNToHex = exports.createServicePolicy = void 0;
|
18
|
+
var create_service_policy_1 = require("./create-service-policy.cjs");
|
19
|
+
Object.defineProperty(exports, "createServicePolicy", { enumerable: true, get: function () { return create_service_policy_1.createServicePolicy; } });
|
18
20
|
__exportStar(require("./constants.cjs"), exports);
|
19
21
|
var util_1 = require("./util.cjs");
|
20
22
|
Object.defineProperty(exports, "BNToHex", { enumerable: true, get: function () { return util_1.BNToHex; } });
|
package/dist/index.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,kDAA4B;AAE5B,mCA4BgB;AA3Bd,+FAAA,OAAO,OAAA;AACP,2GAAA,mBAAmB,OAAA;AACnB,8GAAA,sBAAsB,OAAA;AACtB,kGAAA,UAAU,OAAA;AACV,+FAAA,OAAO,OAAA;AACP,iGAAA,SAAS,OAAA;AACT,sGAAA,cAAc,OAAA;AACd,mGAAA,WAAW,OAAA;AACX,+FAAA,OAAO,OAAA;AACP,iGAAA,SAAS,OAAA;AACT,uGAAA,eAAe,OAAA;AACf,qGAAA,aAAa,OAAA;AACb,qGAAA,aAAa,OAAA;AACb,wGAAA,gBAAgB,OAAA;AAChB,2GAAA,mBAAmB,OAAA;AACnB,mGAAA,WAAW,OAAA;AACX,yGAAA,iBAAiB,OAAA;AACjB,wGAAA,gBAAgB,OAAA;AAChB,6FAAA,KAAK,OAAA;AACL,qGAAA,aAAa,OAAA;AACb,gHAAA,wBAAwB,OAAA;AACxB,uGAAA,eAAe,OAAA;AACf,oGAAA,YAAY,OAAA;AACZ,4GAAA,oBAAoB,OAAA;AACpB,6FAAA,KAAK,OAAA;AACL,uGAAA,eAAe,OAAA;AACf,8GAAA,sBAAsB,OAAA;AAExB,8CAAwB;AACxB,6CAAuB","sourcesContent":["export * from './constants';\nexport type { NonEmptyArray } from './util';\nexport {\n BNToHex,\n convertHexToDecimal,\n fetchWithErrorHandling,\n fractionBN,\n fromHex,\n getBuyURL,\n gweiDecToWEIBN,\n handleFetch,\n hexToBN,\n hexToText,\n isNonEmptyArray,\n isPlainObject,\n isSafeChainId,\n isSafeDynamicKey,\n isSmartContractCode,\n isValidJson,\n isValidHexAddress,\n normalizeEnsName,\n query,\n safelyExecute,\n safelyExecuteWithTimeout,\n successfulFetch,\n timeoutFetch,\n toChecksumHexAddress,\n toHex,\n weiHexToGweiDec,\n isEqualCaseInsensitive,\n} from './util';\nexport * from './types';\nexport * from './siwe';\n"]}
|
1
|
+
{"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,qEAA8D;AAArD,4HAAA,mBAAmB,OAAA;AAC5B,kDAA4B;AAE5B,mCA4BgB;AA3Bd,+FAAA,OAAO,OAAA;AACP,2GAAA,mBAAmB,OAAA;AACnB,8GAAA,sBAAsB,OAAA;AACtB,kGAAA,UAAU,OAAA;AACV,+FAAA,OAAO,OAAA;AACP,iGAAA,SAAS,OAAA;AACT,sGAAA,cAAc,OAAA;AACd,mGAAA,WAAW,OAAA;AACX,+FAAA,OAAO,OAAA;AACP,iGAAA,SAAS,OAAA;AACT,uGAAA,eAAe,OAAA;AACf,qGAAA,aAAa,OAAA;AACb,qGAAA,aAAa,OAAA;AACb,wGAAA,gBAAgB,OAAA;AAChB,2GAAA,mBAAmB,OAAA;AACnB,mGAAA,WAAW,OAAA;AACX,yGAAA,iBAAiB,OAAA;AACjB,wGAAA,gBAAgB,OAAA;AAChB,6FAAA,KAAK,OAAA;AACL,qGAAA,aAAa,OAAA;AACb,gHAAA,wBAAwB,OAAA;AACxB,uGAAA,eAAe,OAAA;AACf,oGAAA,YAAY,OAAA;AACZ,4GAAA,oBAAoB,OAAA;AACpB,6FAAA,KAAK,OAAA;AACL,uGAAA,eAAe,OAAA;AACf,8GAAA,sBAAsB,OAAA;AAExB,8CAAwB;AACxB,6CAAuB","sourcesContent":["export { createServicePolicy } from './create-service-policy';\nexport * from './constants';\nexport type { NonEmptyArray } from './util';\nexport {\n BNToHex,\n convertHexToDecimal,\n fetchWithErrorHandling,\n fractionBN,\n fromHex,\n getBuyURL,\n gweiDecToWEIBN,\n handleFetch,\n hexToBN,\n hexToText,\n isNonEmptyArray,\n isPlainObject,\n isSafeChainId,\n isSafeDynamicKey,\n isSmartContractCode,\n isValidJson,\n isValidHexAddress,\n normalizeEnsName,\n query,\n safelyExecute,\n safelyExecuteWithTimeout,\n successfulFetch,\n timeoutFetch,\n toChecksumHexAddress,\n toHex,\n weiHexToGweiDec,\n isEqualCaseInsensitive,\n} from './util';\nexport * from './types';\nexport * from './siwe';\n"]}
|
package/dist/index.d.cts
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
export { createServicePolicy } from "./create-service-policy.cjs";
|
1
2
|
export * from "./constants.cjs";
|
2
3
|
export type { NonEmptyArray } from "./util.cjs";
|
3
4
|
export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive, } from "./util.cjs";
|
package/dist/index.d.cts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,gCAA4B;AAC5B,YAAY,EAAE,aAAa,EAAE,mBAAe;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,GACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB"}
|
1
|
+
{"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,oCAAgC;AAC9D,gCAA4B;AAC5B,YAAY,EAAE,aAAa,EAAE,mBAAe;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,GACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB"}
|
package/dist/index.d.mts
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
export { createServicePolicy } from "./create-service-policy.mjs";
|
1
2
|
export * from "./constants.mjs";
|
2
3
|
export type { NonEmptyArray } from "./util.mjs";
|
3
4
|
export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive, } from "./util.mjs";
|
package/dist/index.d.mts.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,gCAA4B;AAC5B,YAAY,EAAE,aAAa,EAAE,mBAAe;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,GACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB"}
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,oCAAgC;AAC9D,gCAA4B;AAC5B,YAAY,EAAE,aAAa,EAAE,mBAAe;AAC5C,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,GACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB"}
|
package/dist/index.mjs
CHANGED
@@ -1,3 +1,4 @@
|
|
1
|
+
export { createServicePolicy } from "./create-service-policy.mjs";
|
1
2
|
export * from "./constants.mjs";
|
2
3
|
export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive } from "./util.mjs";
|
3
4
|
export * from "./types.mjs";
|
package/dist/index.mjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,gCAA4B;AAE5B,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,EACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB","sourcesContent":["export * from './constants';\nexport type { NonEmptyArray } from './util';\nexport {\n BNToHex,\n convertHexToDecimal,\n fetchWithErrorHandling,\n fractionBN,\n fromHex,\n getBuyURL,\n gweiDecToWEIBN,\n handleFetch,\n hexToBN,\n hexToText,\n isNonEmptyArray,\n isPlainObject,\n isSafeChainId,\n isSafeDynamicKey,\n isSmartContractCode,\n isValidJson,\n isValidHexAddress,\n normalizeEnsName,\n query,\n safelyExecute,\n safelyExecuteWithTimeout,\n successfulFetch,\n timeoutFetch,\n toChecksumHexAddress,\n toHex,\n weiHexToGweiDec,\n isEqualCaseInsensitive,\n} from './util';\nexport * from './types';\nexport * from './siwe';\n"]}
|
1
|
+
{"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,oCAAgC;AAC9D,gCAA4B;AAE5B,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,wBAAwB,EACxB,eAAe,EACf,YAAY,EACZ,oBAAoB,EACpB,KAAK,EACL,eAAe,EACf,sBAAsB,EACvB,mBAAe;AAChB,4BAAwB;AACxB,2BAAuB","sourcesContent":["export { createServicePolicy } from './create-service-policy';\nexport * from './constants';\nexport type { NonEmptyArray } from './util';\nexport {\n BNToHex,\n convertHexToDecimal,\n fetchWithErrorHandling,\n fractionBN,\n fromHex,\n getBuyURL,\n gweiDecToWEIBN,\n handleFetch,\n hexToBN,\n hexToText,\n isNonEmptyArray,\n isPlainObject,\n isSafeChainId,\n isSafeDynamicKey,\n isSmartContractCode,\n isValidJson,\n isValidHexAddress,\n normalizeEnsName,\n query,\n safelyExecute,\n safelyExecuteWithTimeout,\n successfulFetch,\n timeoutFetch,\n toChecksumHexAddress,\n toHex,\n weiHexToGweiDec,\n isEqualCaseInsensitive,\n} from './util';\nexport * from './types';\nexport * from './siwe';\n"]}
|
package/dist/util.cjs
CHANGED
package/dist/util.cjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"util.cjs","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;AAAA,2CAAqE;AAErE,qDAAsD;AAEtD,2CAKyB;AAEzB,kDAAuB;AACvB,wEAA2C;AAC3C,sEAAwC;AAExC,+CAAgD;AAIhD,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE9B,QAAA,6BAA6B,GAAG;IAC3C,WAAW;IACX,aAAa;IACb,WAAW;CACH,CAAC;AAEX;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,GAAW;IAC1C,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,CAAC,qCAA6B,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAA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E,IAAI,CAAC,KAAK,EAAE;QACV,OAAO;KACR;IAED,IAAI,KAAK,YAAY,KAAK,EAAE;QAC1B,MAAM,wBAAwB,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAC1D,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,6BAA6B,IAAI,GAAG,CAAC,CAC7D,CAAC;QAEF,IACE,wBAAwB;YACxB,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAC;YACzC,KAAK,KAAK,aAAa,EACvB;YACA,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;SACtB;aAAM;YACL,MAAM,KAAK,CAAC;SACb;KACF;SAAM;QACL,+DAA+D;QAC/D,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,sBAAsB,CACpC,MAAc,EACd,MAAc;IAEd,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QAC5D,OAAO,KAAK,CAAC;KACd;IACD,OAAO,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC;AACvD,CAAC;AARD,wDAQC","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 type { BigNumber } from 'bignumber.js';\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\nexport type { BigNumber };\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\nexport const PROTOTYPE_POLLUTION_BLOCKLIST = [\n '__proto__',\n 'constructor',\n 'prototype',\n] as const;\n\n/**\n * Checks whether a dynamic property key could be used in\n * a [prototype pollution attack](https://portswigger.net/web-security/prototype-pollution).\n *\n * @param key - The dynamic key to validate.\n * @returns Whether the given dynamic key is safe to use.\n */\nexport function isSafeDynamicKey(key: string): boolean {\n return (\n typeof key === 'string' &&\n !PROTOTYPE_POLLUTION_BLOCKLIST.some((blockedKey) => key === blockedKey)\n );\n}\n\n/**\n * Checks whether the given number primitive chain ID is safe.\n * Because some cryptographic libraries we use expect the chain ID to be a\n * number primitive, it must not exceed a certain size.\n *\n * @param chainId - The chain ID to check for safety.\n * @returns Whether the given chain ID is safe.\n */\nexport function isSafeChainId(chainId: Hex): boolean {\n if (!isHexString(chainId)) {\n return false;\n }\n const decimalChainId = Number.parseInt(\n chainId,\n isStrictHexString(chainId) ? 16 : 10,\n );\n return (\n Number.isSafeInteger(decimalChainId) &&\n decimalChainId > 0 &&\n decimalChainId <= MAX_SAFE_CHAIN_ID\n );\n}\n/**\n * Converts a BN or BigNumber object to a hex string with a '0x' prefix.\n *\n * @param inputBn - BN|BigNumber instance to convert to a hex string.\n * @returns A '0x'-prefixed hex string.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function BNToHex(inputBn: BN | BigNumber) {\n return add0x(inputBn.toString(16));\n}\n\n/**\n * Used to multiply a BN by a fraction.\n *\n * @param targetBN - Number to multiply by a fraction.\n * @param numerator - Numerator of the fraction multiplier.\n * @param denominator - Denominator of the fraction multiplier.\n * @returns Product of the multiplication.\n */\nexport function fractionBN(\n targetBN: BN,\n numerator: number | string,\n denominator: number | string,\n) {\n const numBN = new BN(numerator);\n const denomBN = new BN(denominator);\n return targetBN.mul(numBN).div(denomBN);\n}\n\n/**\n * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts.\n *\n * @param n - The base 10 number to convert to WEI.\n * @returns The number in WEI, as a BN.\n */\nexport function gweiDecToWEIBN(n: number | string) {\n if (Number.isNaN(n)) {\n return new BN(0);\n }\n\n const parts = n.toString().split('.');\n const wholePart = parts[0] || '0';\n let decimalPart = parts[1] || '';\n\n if (!decimalPart) {\n return toWei(wholePart, 'gwei');\n }\n\n if (decimalPart.length <= 9) {\n return toWei(`${wholePart}.${decimalPart}`, 'gwei');\n }\n\n const decimalPartToRemove = decimalPart.slice(9);\n const decimalRoundingDigit = decimalPartToRemove[0];\n\n decimalPart = decimalPart.slice(0, 9);\n let wei = toWei(`${wholePart}.${decimalPart}`, 'gwei');\n\n if (Number(decimalRoundingDigit) >= 5) {\n wei = wei.add(new BN(1));\n }\n\n return wei;\n}\n\n/**\n * Used to convert values from wei hex format to dec gwei format.\n *\n * @param hex - The value in hex wei.\n * @returns The value in dec gwei as string.\n */\nexport function weiHexToGweiDec(hex: string) {\n const hexWei = new BN(remove0x(hex), 16);\n return fromWei(hexWei, 'gwei');\n}\n\n/**\n * Return a URL that can be used to obtain ETH for a given network.\n *\n * @param networkCode - Network code of desired network.\n * @param address - Address to deposit obtained ETH.\n * @param amount - How much ETH is desired.\n * @returns URL to buy ETH based on network.\n */\nexport function getBuyURL(\n networkCode = '1',\n address?: string,\n amount = 5,\n): string | undefined {\n switch (networkCode) {\n case '1':\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `https://buy.coinbase.com/?code=9ec56d01-7e81-5017-930c-513daa27bb6a&amount=${amount}&address=${address}&crypto_currency=ETH`;\n case '5':\n return 'https://goerli-faucet.slock.it/';\n case '11155111':\n return 'https://sepoliafaucet.net/';\n default:\n return undefined;\n }\n}\n\n/**\n * Converts a hex string to a BN object.\n *\n * @param inputHex - Number represented as a hex string.\n * @returns A BN instance.\n */\nexport function hexToBN(inputHex: string) {\n return inputHex ? new BN(remove0x(inputHex), 16) : new BN(0);\n}\n\n/**\n * A helper function that converts hex data to human readable string.\n *\n * @param hex - The hex string to convert to string.\n * @returns A human readable string conversion.\n */\nexport function hexToText(hex: string) {\n try {\n const stripped = remove0x(hex);\n const buff = Buffer.from(stripped, 'hex');\n return buff.toString('utf8');\n } catch (e) {\n /* istanbul ignore next */\n return hex;\n }\n}\n\n/**\n * Parses a hex string and converts it into a number that can be operated on in a bignum-safe,\n * base-10 way.\n *\n * @param value - A base-16 number encoded as a string.\n * @returns The number as a BN object in base-16 mode.\n */\nexport function fromHex(value: string | BN): BN {\n if (BN.isBN(value)) {\n return value;\n }\n return new BN(hexToBN(value).toString(10));\n}\n\n/**\n * Converts an integer to a hexadecimal representation.\n *\n * @param value - An integer, an integer encoded as a base-10 string, or a BN.\n * @returns The integer encoded as a hex string.\n */\nexport function toHex(value: number | bigint | string | BN): Hex {\n if (typeof value === 'string' && isStrictHexString(value)) {\n return value;\n }\n const hexString =\n BN.isBN(value) || typeof value === 'bigint'\n ? value.toString(16)\n : new BN(value.toString(), 10).toString(16);\n return `0x${hexString}`;\n}\n\n/**\n * Execute and return an asynchronous operation without throwing errors.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecute<Result>(\n operation: () => Promise<Result>,\n logError = false,\n): Promise<Result | undefined> {\n try {\n return await operation();\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Execute and return an asynchronous operation with a timeout.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @param timeout - Timeout to fail the operation.\n * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecuteWithTimeout<Result>(\n operation: () => Promise<Result>,\n logError = false,\n timeout = 500,\n): Promise<Result | undefined> {\n try {\n return await Promise.race([\n operation(),\n new Promise<never>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * @param address - The address to convert.\n * @returns The address in 0x-prefixed hexadecimal checksummed form if it is valid.\n */\nexport function toChecksumHexAddress(address: string): string;\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * Note that this particular overload does nothing.\n *\n * @param address - A value that is not a string (e.g. `undefined` or `null`).\n * @returns The `address` untouched.\n * @deprecated This overload is designed to gracefully handle an invalid input\n * and is only present for backward compatibility. It may be removed in a future\n * major version. Please pass a string to `toChecksumHexAddress` instead.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function toChecksumHexAddress<T>(address: T): T;\n\n// Tools only see JSDocs for overloads and ignore them for the implementation.\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function toChecksumHexAddress(address: unknown) {\n if (typeof address !== 'string') {\n // Mimic behavior of `addHexPrefix` from `ethereumjs-util` (which this\n // function was previously using) for backward compatibility.\n return address;\n }\n\n const hexPrefixed = add0x(address);\n\n if (!isHexString(hexPrefixed)) {\n // Version 5.1 of ethereumjs-util would have returned '0xY' for input 'y'\n // but we shouldn't waste effort trying to change case on a clearly invalid\n // string. Instead just return the hex prefixed original string which most\n // closely mimics the original behavior.\n return hexPrefixed;\n }\n\n 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 // `.` refers to the registry root contract\n if (ensName === '.') {\n return ensName;\n }\n if (ensName && typeof ensName === 'string') {\n try {\n const normalized = ensNamehash.normalize(ensName.trim());\n // this regex is only sufficient with the above call to ensNamehash.normalize\n // TODO: change 7 in regex to 3 when shorter ENS domains are live\n if (normalized.match(/^(([\\w\\d-]+)\\.)*[\\w\\d-]{7,}\\.(eth|test)$/u)) {\n return normalized;\n }\n } catch (_) {\n // do nothing\n }\n }\n return null;\n}\n\n/**\n * Wrapper method to handle EthQuery requests.\n *\n * @param ethQuery - EthQuery object initialized with a provider.\n * @param method - Method to request.\n * @param args - Arguments to send.\n * @returns Promise resolving the request.\n */\nexport function query(\n ethQuery: EthQuery,\n method: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[] = [],\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> {\n return new Promise((resolve, reject) => {\n const cb = (error: unknown, result: unknown) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n };\n\n // Using `in` rather than `hasProperty` so that we look up the prototype\n // chain for the method.\n if (method in ethQuery && typeof ethQuery[method] === 'function') {\n ethQuery[method](...args, cb);\n } else {\n ethQuery.sendAsync({ method, params: args }, cb);\n }\n });\n}\n\n/**\n * Converts valid hex strings to decimal numbers, and handles unexpected arg types.\n *\n * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.\n * @returns a decimal number.\n */\nexport const convertHexToDecimal = (\n value: string | undefined = '0x0',\n): number => {\n if (isStrictHexString(value)) {\n return parseInt(value, 16);\n }\n\n return Number(value) ? Number(value) : 0;\n};\n\ntype PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Determines whether a value is a \"plain\" object.\n *\n * @param value - A value to check\n * @returns True if the passed value is a plain object\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template T - The non-empty array member type.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\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 */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function isNonEmptyArray<T>(value: T[]): value is NonEmptyArray<T> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: unknown, codesToCatch: number[] = []) {\n if (!error) {\n return;\n }\n\n if (error instanceof Error) {\n const includesErrorCodeToCatch = codesToCatch.some((code) =>\n error.message.includes(`Fetch failed with status '${code}'`),\n );\n\n if (\n includesErrorCodeToCatch ||\n error.message.includes('Failed to fetch') ||\n error === TIMEOUT_ERROR\n ) {\n console.error(error);\n } else {\n throw error;\n }\n } else {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw error;\n }\n}\n\n/**\n * Checks if two strings are equal, ignoring case.\n *\n * @param value1 - The first string to compare.\n * @param value2 - The second string to compare.\n * @returns `true` if the strings are equal, ignoring case; otherwise, `false`.\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n"]}
|
1
|
+
{"version":3,"file":"util.cjs","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;AAAA,2CAAqE;AAErE,qDAAsD;AAEtD,2CAKyB;AAEzB,kDAAuB;AACvB,wEAA2C;AAC3C,sEAAwC;AAExC,+CAAgD;AAIhD,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE9B,QAAA,6BAA6B,GAAG;IAC3C,WAAW;IACX,aAAa;IACb,WAAW;CACH,CAAC;AAEX;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAAC,GAAW;IAC1C,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,CAAC,qCAA6B,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,GAAG,KAAK,UAAU,CAAC,CACxE,CAAC;AACJ,CAAC;AALD,4CAKC;AAED;;;;;;;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,gFAAgF;AAChF,gEAAgE;AACh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MAAc,EACd,MAAc;IAEd,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QAC5D,OAAO,KAAK,CAAC;KACd;IACD,OAAO,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC;AACvD,CAAC;AARD,wDAQC","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 type { BigNumber } from 'bignumber.js';\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\nexport type { BigNumber };\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\nexport const PROTOTYPE_POLLUTION_BLOCKLIST = [\n '__proto__',\n 'constructor',\n 'prototype',\n] as const;\n\n/**\n * Checks whether a dynamic property key could be used in\n * a [prototype pollution attack](https://portswigger.net/web-security/prototype-pollution).\n *\n * @param key - The dynamic key to validate.\n * @returns Whether the given dynamic key is safe to use.\n */\nexport function isSafeDynamicKey(key: string): boolean {\n return (\n typeof key === 'string' &&\n !PROTOTYPE_POLLUTION_BLOCKLIST.some((blockedKey) => key === blockedKey)\n );\n}\n\n/**\n * Checks whether the given number primitive chain ID is safe.\n * Because some cryptographic libraries we use expect the chain ID to be a\n * number primitive, it must not exceed a certain size.\n *\n * @param chainId - The chain ID to check for safety.\n * @returns Whether the given chain ID is safe.\n */\nexport function isSafeChainId(chainId: Hex): boolean {\n if (!isHexString(chainId)) {\n return false;\n }\n const decimalChainId = Number.parseInt(\n chainId,\n isStrictHexString(chainId) ? 16 : 10,\n );\n return (\n Number.isSafeInteger(decimalChainId) &&\n decimalChainId > 0 &&\n decimalChainId <= MAX_SAFE_CHAIN_ID\n );\n}\n/**\n * Converts a BN or BigNumber object to a hex string with a '0x' prefix.\n *\n * @param inputBn - BN|BigNumber instance to convert to a hex string.\n * @returns A '0x'-prefixed hex string.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function BNToHex(inputBn: BN | BigNumber) {\n return add0x(inputBn.toString(16));\n}\n\n/**\n * Used to multiply a BN by a fraction.\n *\n * @param targetBN - Number to multiply by a fraction.\n * @param numerator - Numerator of the fraction multiplier.\n * @param denominator - Denominator of the fraction multiplier.\n * @returns Product of the multiplication.\n */\nexport function fractionBN(\n targetBN: BN,\n numerator: number | string,\n denominator: number | string,\n) {\n const numBN = new BN(numerator);\n const denomBN = new BN(denominator);\n return targetBN.mul(numBN).div(denomBN);\n}\n\n/**\n * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts.\n *\n * @param n - The base 10 number to convert to WEI.\n * @returns The number in WEI, as a BN.\n */\nexport function gweiDecToWEIBN(n: number | string) {\n if (Number.isNaN(n)) {\n return new BN(0);\n }\n\n const parts = n.toString().split('.');\n const wholePart = parts[0] || '0';\n let decimalPart = parts[1] || '';\n\n if (!decimalPart) {\n return toWei(wholePart, 'gwei');\n }\n\n if (decimalPart.length <= 9) {\n return toWei(`${wholePart}.${decimalPart}`, 'gwei');\n }\n\n const decimalPartToRemove = decimalPart.slice(9);\n const decimalRoundingDigit = decimalPartToRemove[0];\n\n decimalPart = decimalPart.slice(0, 9);\n let wei = toWei(`${wholePart}.${decimalPart}`, 'gwei');\n\n if (Number(decimalRoundingDigit) >= 5) {\n wei = wei.add(new BN(1));\n }\n\n return wei;\n}\n\n/**\n * Used to convert values from wei hex format to dec gwei format.\n *\n * @param hex - The value in hex wei.\n * @returns The value in dec gwei as string.\n */\nexport function weiHexToGweiDec(hex: string) {\n const hexWei = new BN(remove0x(hex), 16);\n return fromWei(hexWei, 'gwei');\n}\n\n/**\n * Return a URL that can be used to obtain ETH for a given network.\n *\n * @param networkCode - Network code of desired network.\n * @param address - Address to deposit obtained ETH.\n * @param amount - How much ETH is desired.\n * @returns URL to buy ETH based on network.\n */\nexport function getBuyURL(\n networkCode = '1',\n address?: string,\n amount = 5,\n): string | undefined {\n switch (networkCode) {\n case '1':\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `https://buy.coinbase.com/?code=9ec56d01-7e81-5017-930c-513daa27bb6a&amount=${amount}&address=${address}&crypto_currency=ETH`;\n case '5':\n return 'https://goerli-faucet.slock.it/';\n case '11155111':\n return 'https://sepoliafaucet.net/';\n default:\n return undefined;\n }\n}\n\n/**\n * Converts a hex string to a BN object.\n *\n * @param inputHex - Number represented as a hex string.\n * @returns A BN instance.\n */\nexport function hexToBN(inputHex: string) {\n return inputHex ? new BN(remove0x(inputHex), 16) : new BN(0);\n}\n\n/**\n * A helper function that converts hex data to human readable string.\n *\n * @param hex - The hex string to convert to string.\n * @returns A human readable string conversion.\n */\nexport function hexToText(hex: string) {\n try {\n const stripped = remove0x(hex);\n const buff = Buffer.from(stripped, 'hex');\n return buff.toString('utf8');\n } catch (e) {\n /* istanbul ignore next */\n return hex;\n }\n}\n\n/**\n * Parses a hex string and converts it into a number that can be operated on in a bignum-safe,\n * base-10 way.\n *\n * @param value - A base-16 number encoded as a string.\n * @returns The number as a BN object in base-16 mode.\n */\nexport function fromHex(value: string | BN): BN {\n if (BN.isBN(value)) {\n return value;\n }\n return new BN(hexToBN(value).toString(10));\n}\n\n/**\n * Converts an integer to a hexadecimal representation.\n *\n * @param value - An integer, an integer encoded as a base-10 string, or a BN.\n * @returns The integer encoded as a hex string.\n */\nexport function toHex(value: number | bigint | string | BN): Hex {\n if (typeof value === 'string' && isStrictHexString(value)) {\n return value;\n }\n const hexString =\n BN.isBN(value) || typeof value === 'bigint'\n ? value.toString(16)\n : new BN(value.toString(), 10).toString(16);\n return `0x${hexString}`;\n}\n\n/**\n * Execute and return an asynchronous operation without throwing errors.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecute<Result>(\n operation: () => Promise<Result>,\n logError = false,\n): Promise<Result | undefined> {\n try {\n return await operation();\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Execute and return an asynchronous operation with a timeout.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @param timeout - Timeout to fail the operation.\n * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecuteWithTimeout<Result>(\n operation: () => Promise<Result>,\n logError = false,\n timeout = 500,\n): Promise<Result | undefined> {\n try {\n return await Promise.race([\n operation(),\n new Promise<never>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * @param address - The address to convert.\n * @returns The address in 0x-prefixed hexadecimal checksummed form if it is valid.\n */\nexport function toChecksumHexAddress(address: string): string;\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * Note that this particular overload does nothing.\n *\n * @param address - A value that is not a string (e.g. `undefined` or `null`).\n * @returns The `address` untouched.\n * @deprecated This overload is designed to gracefully handle an invalid input\n * and is only present for backward compatibility. It may be removed in a future\n * major version. Please pass a string to `toChecksumHexAddress` instead.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function toChecksumHexAddress<T>(address: T): T;\n\n// Tools only see JSDocs for overloads and ignore them for the implementation.\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function toChecksumHexAddress(address: unknown) {\n if (typeof address !== 'string') {\n // Mimic behavior of `addHexPrefix` from `ethereumjs-util` (which this\n // function was previously using) for backward compatibility.\n return address;\n }\n\n const hexPrefixed = add0x(address);\n\n if (!isHexString(hexPrefixed)) {\n // Version 5.1 of ethereumjs-util would have returned '0xY' for input 'y'\n // but we shouldn't waste effort trying to change case on a clearly invalid\n // string. Instead just return the hex prefixed original string which most\n // closely mimics the original behavior.\n return hexPrefixed;\n }\n\n 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 // `.` refers to the registry root contract\n if (ensName === '.') {\n return ensName;\n }\n if (ensName && typeof ensName === 'string') {\n try {\n const normalized = ensNamehash.normalize(ensName.trim());\n // this regex is only sufficient with the above call to ensNamehash.normalize\n // TODO: change 7 in regex to 3 when shorter ENS domains are live\n if (normalized.match(/^(([\\w\\d-]+)\\.)*[\\w\\d-]{7,}\\.(eth|test)$/u)) {\n return normalized;\n }\n } catch (_) {\n // do nothing\n }\n }\n return null;\n}\n\n/**\n * Wrapper method to handle EthQuery requests.\n *\n * @param ethQuery - EthQuery object initialized with a provider.\n * @param method - Method to request.\n * @param args - Arguments to send.\n * @returns Promise resolving the request.\n */\nexport function query(\n ethQuery: EthQuery,\n method: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[] = [],\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> {\n return new Promise((resolve, reject) => {\n const cb = (error: unknown, result: unknown) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n };\n\n // Using `in` rather than `hasProperty` so that we look up the prototype\n // chain for the method.\n if (method in ethQuery && typeof ethQuery[method] === 'function') {\n ethQuery[method](...args, cb);\n } else {\n ethQuery.sendAsync({ method, params: args }, cb);\n }\n });\n}\n\n/**\n * Converts valid hex strings to decimal numbers, and handles unexpected arg types.\n *\n * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.\n * @returns a decimal number.\n */\nexport const convertHexToDecimal = (\n value: string | undefined = '0x0',\n): number => {\n if (isStrictHexString(value)) {\n return parseInt(value, 16);\n }\n\n return Number(value) ? Number(value) : 0;\n};\n\ntype PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Determines whether a value is a \"plain\" object.\n *\n * @param value - A value to check\n * @returns True if the passed value is a plain object\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template T - The non-empty array member type.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\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 */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function isNonEmptyArray<T>(value: T[]): value is NonEmptyArray<T> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: unknown, codesToCatch: number[] = []) {\n if (!error) {\n return;\n }\n\n if (error instanceof Error) {\n const includesErrorCodeToCatch = codesToCatch.some((code) =>\n error.message.includes(`Fetch failed with status '${code}'`),\n );\n\n if (\n includesErrorCodeToCatch ||\n error.message.includes('Failed to fetch') ||\n error === TIMEOUT_ERROR\n ) {\n console.error(error);\n } else {\n throw error;\n }\n } else {\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw error;\n }\n}\n\n/**\n * Checks if two strings are equal, ignoring case.\n *\n * @param value1 - The first string to compare.\n * @param value2 - The second string to compare.\n * @returns `true` if the strings are equal, ignoring case; otherwise, `false`.\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n"]}
|
package/dist/util.mjs
CHANGED
package/dist/util.mjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"util.mjs","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,yBAAyB;AAErE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,6BAA6B;AAEtD,OAAO,EACL,iBAAiB,EACjB,KAAK,EACL,WAAW,EACX,QAAQ,EACT,wBAAwB;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ACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAS,iBAAiB,CAAC,KAAc,EAAE,eAAyB,EAAE;IACpE,IAAI,CAAC,KAAK,EAAE;QACV,OAAO;KACR;IAED,IAAI,KAAK,YAAY,KAAK,EAAE;QAC1B,MAAM,wBAAwB,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAC1D,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,6BAA6B,IAAI,GAAG,CAAC,CAC7D,CAAC;QAEF,IACE,wBAAwB;YACxB,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAC;YACzC,KAAK,KAAK,aAAa,EACvB;YACA,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;SACtB;aAAM;YACL,MAAM,KAAK,CAAC;SACb;KACF;SAAM;QACL,+DAA+D;QAC/D,MAAM,KAAK,CAAC;KACb;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CACpC,MAAc,EACd,MAAc;IAEd,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QAC5D,OAAO,KAAK,CAAC;KACd;IACD,OAAO,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC;AACvD,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 type { BigNumber } from 'bignumber.js';\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\nexport type { BigNumber };\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\nexport const PROTOTYPE_POLLUTION_BLOCKLIST = [\n '__proto__',\n 'constructor',\n 'prototype',\n] as const;\n\n/**\n * Checks whether a dynamic property key could be used in\n * a [prototype pollution attack](https://portswigger.net/web-security/prototype-pollution).\n *\n * @param key - The dynamic key to validate.\n * @returns Whether the given dynamic key is safe to use.\n */\nexport function isSafeDynamicKey(key: string): boolean {\n return (\n typeof key === 'string' &&\n !PROTOTYPE_POLLUTION_BLOCKLIST.some((blockedKey) => key === blockedKey)\n );\n}\n\n/**\n * Checks whether the given number primitive chain ID is safe.\n * Because some cryptographic libraries we use expect the chain ID to be a\n * number primitive, it must not exceed a certain size.\n *\n * @param chainId - The chain ID to check for safety.\n * @returns Whether the given chain ID is safe.\n */\nexport function isSafeChainId(chainId: Hex): boolean {\n if (!isHexString(chainId)) {\n return false;\n }\n const decimalChainId = Number.parseInt(\n chainId,\n isStrictHexString(chainId) ? 16 : 10,\n );\n return (\n Number.isSafeInteger(decimalChainId) &&\n decimalChainId > 0 &&\n decimalChainId <= MAX_SAFE_CHAIN_ID\n );\n}\n/**\n * Converts a BN or BigNumber object to a hex string with a '0x' prefix.\n *\n * @param inputBn - BN|BigNumber instance to convert to a hex string.\n * @returns A '0x'-prefixed hex string.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function BNToHex(inputBn: BN | BigNumber) {\n return add0x(inputBn.toString(16));\n}\n\n/**\n * Used to multiply a BN by a fraction.\n *\n * @param targetBN - Number to multiply by a fraction.\n * @param numerator - Numerator of the fraction multiplier.\n * @param denominator - Denominator of the fraction multiplier.\n * @returns Product of the multiplication.\n */\nexport function fractionBN(\n targetBN: BN,\n numerator: number | string,\n denominator: number | string,\n) {\n const numBN = new BN(numerator);\n const denomBN = new BN(denominator);\n return targetBN.mul(numBN).div(denomBN);\n}\n\n/**\n * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts.\n *\n * @param n - The base 10 number to convert to WEI.\n * @returns The number in WEI, as a BN.\n */\nexport function gweiDecToWEIBN(n: number | string) {\n if (Number.isNaN(n)) {\n return new BN(0);\n }\n\n const parts = n.toString().split('.');\n const wholePart = parts[0] || '0';\n let decimalPart = parts[1] || '';\n\n if (!decimalPart) {\n return toWei(wholePart, 'gwei');\n }\n\n if (decimalPart.length <= 9) {\n return toWei(`${wholePart}.${decimalPart}`, 'gwei');\n }\n\n const decimalPartToRemove = decimalPart.slice(9);\n const decimalRoundingDigit = decimalPartToRemove[0];\n\n decimalPart = decimalPart.slice(0, 9);\n let wei = toWei(`${wholePart}.${decimalPart}`, 'gwei');\n\n if (Number(decimalRoundingDigit) >= 5) {\n wei = wei.add(new BN(1));\n }\n\n return wei;\n}\n\n/**\n * Used to convert values from wei hex format to dec gwei format.\n *\n * @param hex - The value in hex wei.\n * @returns The value in dec gwei as string.\n */\nexport function weiHexToGweiDec(hex: string) {\n const hexWei = new BN(remove0x(hex), 16);\n return fromWei(hexWei, 'gwei');\n}\n\n/**\n * Return a URL that can be used to obtain ETH for a given network.\n *\n * @param networkCode - Network code of desired network.\n * @param address - Address to deposit obtained ETH.\n * @param amount - How much ETH is desired.\n * @returns URL to buy ETH based on network.\n */\nexport function getBuyURL(\n networkCode = '1',\n address?: string,\n amount = 5,\n): string | undefined {\n switch (networkCode) {\n case '1':\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `https://buy.coinbase.com/?code=9ec56d01-7e81-5017-930c-513daa27bb6a&amount=${amount}&address=${address}&crypto_currency=ETH`;\n case '5':\n return 'https://goerli-faucet.slock.it/';\n case '11155111':\n return 'https://sepoliafaucet.net/';\n default:\n return undefined;\n }\n}\n\n/**\n * Converts a hex string to a BN object.\n *\n * @param inputHex - Number represented as a hex string.\n * @returns A BN instance.\n */\nexport function hexToBN(inputHex: string) {\n return inputHex ? new BN(remove0x(inputHex), 16) : new BN(0);\n}\n\n/**\n * A helper function that converts hex data to human readable string.\n *\n * @param hex - The hex string to convert to string.\n * @returns A human readable string conversion.\n */\nexport function hexToText(hex: string) {\n try {\n const stripped = remove0x(hex);\n const buff = Buffer.from(stripped, 'hex');\n return buff.toString('utf8');\n } catch (e) {\n /* istanbul ignore next */\n return hex;\n }\n}\n\n/**\n * Parses a hex string and converts it into a number that can be operated on in a bignum-safe,\n * base-10 way.\n *\n * @param value - A base-16 number encoded as a string.\n * @returns The number as a BN object in base-16 mode.\n */\nexport function fromHex(value: string | BN): BN {\n if (BN.isBN(value)) {\n return value;\n }\n return new BN(hexToBN(value).toString(10));\n}\n\n/**\n * Converts an integer to a hexadecimal representation.\n *\n * @param value - An integer, an integer encoded as a base-10 string, or a BN.\n * @returns The integer encoded as a hex string.\n */\nexport function toHex(value: number | bigint | string | BN): Hex {\n if (typeof value === 'string' && isStrictHexString(value)) {\n return value;\n }\n const hexString =\n BN.isBN(value) || typeof value === 'bigint'\n ? value.toString(16)\n : new BN(value.toString(), 10).toString(16);\n return `0x${hexString}`;\n}\n\n/**\n * Execute and return an asynchronous operation without throwing errors.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecute<Result>(\n operation: () => Promise<Result>,\n logError = false,\n): Promise<Result | undefined> {\n try {\n return await operation();\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Execute and return an asynchronous operation with a timeout.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @param timeout - Timeout to fail the operation.\n * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecuteWithTimeout<Result>(\n operation: () => Promise<Result>,\n logError = false,\n timeout = 500,\n): Promise<Result | undefined> {\n try {\n return await Promise.race([\n operation(),\n new Promise<never>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * @param address - The address to convert.\n * @returns The address in 0x-prefixed hexadecimal checksummed form if it is valid.\n */\nexport function toChecksumHexAddress(address: string): string;\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * Note that this particular overload does nothing.\n *\n * @param address - A value that is not a string (e.g. `undefined` or `null`).\n * @returns The `address` untouched.\n * @deprecated This overload is designed to gracefully handle an invalid input\n * and is only present for backward compatibility. It may be removed in a future\n * major version. Please pass a string to `toChecksumHexAddress` instead.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function toChecksumHexAddress<T>(address: T): T;\n\n// Tools only see JSDocs for overloads and ignore them for the implementation.\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function toChecksumHexAddress(address: unknown) {\n if (typeof address !== 'string') {\n // Mimic behavior of `addHexPrefix` from `ethereumjs-util` (which this\n // function was previously using) for backward compatibility.\n return address;\n }\n\n const hexPrefixed = add0x(address);\n\n if (!isHexString(hexPrefixed)) {\n // Version 5.1 of ethereumjs-util would have returned '0xY' for input 'y'\n // but we shouldn't waste effort trying to change case on a clearly invalid\n // string. Instead just return the hex prefixed original string which most\n // closely mimics the original behavior.\n return hexPrefixed;\n }\n\n 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 // `.` refers to the registry root contract\n if (ensName === '.') {\n return ensName;\n }\n if (ensName && typeof ensName === 'string') {\n try {\n const normalized = ensNamehash.normalize(ensName.trim());\n // this regex is only sufficient with the above call to ensNamehash.normalize\n // TODO: change 7 in regex to 3 when shorter ENS domains are live\n if (normalized.match(/^(([\\w\\d-]+)\\.)*[\\w\\d-]{7,}\\.(eth|test)$/u)) {\n return normalized;\n }\n } catch (_) {\n // do nothing\n }\n }\n return null;\n}\n\n/**\n * Wrapper method to handle EthQuery requests.\n *\n * @param ethQuery - EthQuery object initialized with a provider.\n * @param method - Method to request.\n * @param args - Arguments to send.\n * @returns Promise resolving the request.\n */\nexport function query(\n ethQuery: EthQuery,\n method: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[] = [],\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> {\n return new Promise((resolve, reject) => {\n const cb = (error: unknown, result: unknown) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n };\n\n // Using `in` rather than `hasProperty` so that we look up the prototype\n // chain for the method.\n if (method in ethQuery && typeof ethQuery[method] === 'function') {\n ethQuery[method](...args, cb);\n } else {\n ethQuery.sendAsync({ method, params: args }, cb);\n }\n });\n}\n\n/**\n * Converts valid hex strings to decimal numbers, and handles unexpected arg types.\n *\n * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.\n * @returns a decimal number.\n */\nexport const convertHexToDecimal = (\n value: string | undefined = '0x0',\n): number => {\n if (isStrictHexString(value)) {\n return parseInt(value, 16);\n }\n\n return Number(value) ? Number(value) : 0;\n};\n\ntype PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Determines whether a value is a \"plain\" object.\n *\n * @param value - A value to check\n * @returns True if the passed value is a plain object\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template T - The non-empty array member type.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\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 */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function isNonEmptyArray<T>(value: T[]): value is NonEmptyArray<T> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: unknown, codesToCatch: number[] = []) {\n if (!error) {\n return;\n }\n\n if (error instanceof Error) {\n const includesErrorCodeToCatch = codesToCatch.some((code) =>\n error.message.includes(`Fetch failed with status '${code}'`),\n );\n\n if (\n includesErrorCodeToCatch ||\n error.message.includes('Failed to fetch') ||\n error === TIMEOUT_ERROR\n ) {\n console.error(error);\n } else {\n throw error;\n }\n } else {\n // eslint-disable-next-line @typescript-eslint/no-throw-literal\n throw error;\n }\n}\n\n/**\n * Checks if two strings are equal, ignoring case.\n *\n * @param value1 - The first string to compare.\n * @param value2 - The second string to compare.\n * @returns `true` if the strings are equal, ignoring case; otherwise, `false`.\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n"]}
|
1
|
+
{"version":3,"file":"util.mjs","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,yBAAyB;AAErE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,6BAA6B;AAEtD,OAAO,EACL,iBAAiB,EACjB,KAAK,EACL,WAAW,EACX,QAAQ,EACT,wBAAwB;AAEzB,OAAO,GAAE,cAAc;;AACvB,OAAO,YAAW,yBAAyB;;AAC3C,OAAO,UAAS,wBAAwB;;AAExC,OAAO,EAAE,iBAAiB,EAAE,wBAAoB;AAIhD,MAAM,aAAa,GAAG,IAAI,KAAK,CAAC,SAAS,CAAC,CAAC;AAE3C,MAAM,CAAC,MAAM,6BAA6B,GAAG;IAC3C,WAAW;IACX,aAAa;IACb,WAAW;CACH,CAAC;AAEX;;;;;;GAMG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,OAAO,CACL,OAAO,GAAG,KAAK,QAAQ;QACvB,CAAC,6BAA6B,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,GAAG,KAAK,UAAU,CAAC,CACxE,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,aAAa,CAAC,OAAY;IACxC,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,EAAE;QACzB,OAAO,KAAK,CAAC;KACd;IACD,MAAM,cAAc,GAAG,MAAM,CAAC,QAA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c,EACd,MAAc;IAEd,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;QAC5D,OAAO,KAAK,CAAC;KACd;IACD,OAAO,MAAM,CAAC,WAAW,EAAE,KAAK,MAAM,CAAC,WAAW,EAAE,CAAC;AACvD,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 type { BigNumber } from 'bignumber.js';\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\nexport type { BigNumber };\n\nconst TIMEOUT_ERROR = new Error('timeout');\n\nexport const PROTOTYPE_POLLUTION_BLOCKLIST = [\n '__proto__',\n 'constructor',\n 'prototype',\n] as const;\n\n/**\n * Checks whether a dynamic property key could be used in\n * a [prototype pollution attack](https://portswigger.net/web-security/prototype-pollution).\n *\n * @param key - The dynamic key to validate.\n * @returns Whether the given dynamic key is safe to use.\n */\nexport function isSafeDynamicKey(key: string): boolean {\n return (\n typeof key === 'string' &&\n !PROTOTYPE_POLLUTION_BLOCKLIST.some((blockedKey) => key === blockedKey)\n );\n}\n\n/**\n * Checks whether the given number primitive chain ID is safe.\n * Because some cryptographic libraries we use expect the chain ID to be a\n * number primitive, it must not exceed a certain size.\n *\n * @param chainId - The chain ID to check for safety.\n * @returns Whether the given chain ID is safe.\n */\nexport function isSafeChainId(chainId: Hex): boolean {\n if (!isHexString(chainId)) {\n return false;\n }\n const decimalChainId = Number.parseInt(\n chainId,\n isStrictHexString(chainId) ? 16 : 10,\n );\n return (\n Number.isSafeInteger(decimalChainId) &&\n decimalChainId > 0 &&\n decimalChainId <= MAX_SAFE_CHAIN_ID\n );\n}\n/**\n * Converts a BN or BigNumber object to a hex string with a '0x' prefix.\n *\n * @param inputBn - BN|BigNumber instance to convert to a hex string.\n * @returns A '0x'-prefixed hex string.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function BNToHex(inputBn: BN | BigNumber) {\n return add0x(inputBn.toString(16));\n}\n\n/**\n * Used to multiply a BN by a fraction.\n *\n * @param targetBN - Number to multiply by a fraction.\n * @param numerator - Numerator of the fraction multiplier.\n * @param denominator - Denominator of the fraction multiplier.\n * @returns Product of the multiplication.\n */\nexport function fractionBN(\n targetBN: BN,\n numerator: number | string,\n denominator: number | string,\n) {\n const numBN = new BN(numerator);\n const denomBN = new BN(denominator);\n return targetBN.mul(numBN).div(denomBN);\n}\n\n/**\n * Used to convert a base-10 number from GWEI to WEI. Can handle numbers with decimal parts.\n *\n * @param n - The base 10 number to convert to WEI.\n * @returns The number in WEI, as a BN.\n */\nexport function gweiDecToWEIBN(n: number | string) {\n if (Number.isNaN(n)) {\n return new BN(0);\n }\n\n const parts = n.toString().split('.');\n const wholePart = parts[0] || '0';\n let decimalPart = parts[1] || '';\n\n if (!decimalPart) {\n return toWei(wholePart, 'gwei');\n }\n\n if (decimalPart.length <= 9) {\n return toWei(`${wholePart}.${decimalPart}`, 'gwei');\n }\n\n const decimalPartToRemove = decimalPart.slice(9);\n const decimalRoundingDigit = decimalPartToRemove[0];\n\n decimalPart = decimalPart.slice(0, 9);\n let wei = toWei(`${wholePart}.${decimalPart}`, 'gwei');\n\n if (Number(decimalRoundingDigit) >= 5) {\n wei = wei.add(new BN(1));\n }\n\n return wei;\n}\n\n/**\n * Used to convert values from wei hex format to dec gwei format.\n *\n * @param hex - The value in hex wei.\n * @returns The value in dec gwei as string.\n */\nexport function weiHexToGweiDec(hex: string) {\n const hexWei = new BN(remove0x(hex), 16);\n return fromWei(hexWei, 'gwei');\n}\n\n/**\n * Return a URL that can be used to obtain ETH for a given network.\n *\n * @param networkCode - Network code of desired network.\n * @param address - Address to deposit obtained ETH.\n * @param amount - How much ETH is desired.\n * @returns URL to buy ETH based on network.\n */\nexport function getBuyURL(\n networkCode = '1',\n address?: string,\n amount = 5,\n): string | undefined {\n switch (networkCode) {\n case '1':\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n return `https://buy.coinbase.com/?code=9ec56d01-7e81-5017-930c-513daa27bb6a&amount=${amount}&address=${address}&crypto_currency=ETH`;\n case '5':\n return 'https://goerli-faucet.slock.it/';\n case '11155111':\n return 'https://sepoliafaucet.net/';\n default:\n return undefined;\n }\n}\n\n/**\n * Converts a hex string to a BN object.\n *\n * @param inputHex - Number represented as a hex string.\n * @returns A BN instance.\n */\nexport function hexToBN(inputHex: string) {\n return inputHex ? new BN(remove0x(inputHex), 16) : new BN(0);\n}\n\n/**\n * A helper function that converts hex data to human readable string.\n *\n * @param hex - The hex string to convert to string.\n * @returns A human readable string conversion.\n */\nexport function hexToText(hex: string) {\n try {\n const stripped = remove0x(hex);\n const buff = Buffer.from(stripped, 'hex');\n return buff.toString('utf8');\n } catch (e) {\n /* istanbul ignore next */\n return hex;\n }\n}\n\n/**\n * Parses a hex string and converts it into a number that can be operated on in a bignum-safe,\n * base-10 way.\n *\n * @param value - A base-16 number encoded as a string.\n * @returns The number as a BN object in base-16 mode.\n */\nexport function fromHex(value: string | BN): BN {\n if (BN.isBN(value)) {\n return value;\n }\n return new BN(hexToBN(value).toString(10));\n}\n\n/**\n * Converts an integer to a hexadecimal representation.\n *\n * @param value - An integer, an integer encoded as a base-10 string, or a BN.\n * @returns The integer encoded as a hex string.\n */\nexport function toHex(value: number | bigint | string | BN): Hex {\n if (typeof value === 'string' && isStrictHexString(value)) {\n return value;\n }\n const hexString =\n BN.isBN(value) || typeof value === 'bigint'\n ? value.toString(16)\n : new BN(value.toString(), 10).toString(16);\n return `0x${hexString}`;\n}\n\n/**\n * Execute and return an asynchronous operation without throwing errors.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecute<Result>(\n operation: () => Promise<Result>,\n logError = false,\n): Promise<Result | undefined> {\n try {\n return await operation();\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Execute and return an asynchronous operation with a timeout.\n *\n * @param operation - Function returning a Promise.\n * @param logError - Determines if the error should be logged.\n * @param timeout - Timeout to fail the operation.\n * @template Result - Type of the result of the async operation\n * @returns Promise resolving to the result of the async operation.\n */\nexport async function safelyExecuteWithTimeout<Result>(\n operation: () => Promise<Result>,\n logError = false,\n timeout = 500,\n): Promise<Result | undefined> {\n try {\n return await Promise.race([\n operation(),\n new Promise<never>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } catch (error) {\n /* istanbul ignore next */\n if (logError) {\n console.error(error);\n }\n return undefined;\n }\n}\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * @param address - The address to convert.\n * @returns The address in 0x-prefixed hexadecimal checksummed form if it is valid.\n */\nexport function toChecksumHexAddress(address: string): string;\n\n/**\n * Convert an address to a checksummed hexadecimal address.\n *\n * Note that this particular overload does nothing.\n *\n * @param address - A value that is not a string (e.g. `undefined` or `null`).\n * @returns The `address` untouched.\n * @deprecated This overload is designed to gracefully handle an invalid input\n * and is only present for backward compatibility. It may be removed in a future\n * major version. Please pass a string to `toChecksumHexAddress` instead.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function toChecksumHexAddress<T>(address: T): T;\n\n// Tools only see JSDocs for overloads and ignore them for the implementation.\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function toChecksumHexAddress(address: unknown) {\n if (typeof address !== 'string') {\n // Mimic behavior of `addHexPrefix` from `ethereumjs-util` (which this\n // function was previously using) for backward compatibility.\n return address;\n }\n\n const hexPrefixed = add0x(address);\n\n if (!isHexString(hexPrefixed)) {\n // Version 5.1 of ethereumjs-util would have returned '0xY' for input 'y'\n // but we shouldn't waste effort trying to change case on a clearly invalid\n // string. Instead just return the hex prefixed original string which most\n // closely mimics the original behavior.\n return hexPrefixed;\n }\n\n 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 // `.` refers to the registry root contract\n if (ensName === '.') {\n return ensName;\n }\n if (ensName && typeof ensName === 'string') {\n try {\n const normalized = ensNamehash.normalize(ensName.trim());\n // this regex is only sufficient with the above call to ensNamehash.normalize\n // TODO: change 7 in regex to 3 when shorter ENS domains are live\n if (normalized.match(/^(([\\w\\d-]+)\\.)*[\\w\\d-]{7,}\\.(eth|test)$/u)) {\n return normalized;\n }\n } catch (_) {\n // do nothing\n }\n }\n return null;\n}\n\n/**\n * Wrapper method to handle EthQuery requests.\n *\n * @param ethQuery - EthQuery object initialized with a provider.\n * @param method - Method to request.\n * @param args - Arguments to send.\n * @returns Promise resolving the request.\n */\nexport function query(\n ethQuery: EthQuery,\n method: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[] = [],\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> {\n return new Promise((resolve, reject) => {\n const cb = (error: unknown, result: unknown) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n };\n\n // Using `in` rather than `hasProperty` so that we look up the prototype\n // chain for the method.\n if (method in ethQuery && typeof ethQuery[method] === 'function') {\n ethQuery[method](...args, cb);\n } else {\n ethQuery.sendAsync({ method, params: args }, cb);\n }\n });\n}\n\n/**\n * Converts valid hex strings to decimal numbers, and handles unexpected arg types.\n *\n * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.\n * @returns a decimal number.\n */\nexport const convertHexToDecimal = (\n value: string | undefined = '0x0',\n): number => {\n if (isStrictHexString(value)) {\n return parseInt(value, 16);\n }\n\n return Number(value) ? Number(value) : 0;\n};\n\ntype PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Determines whether a value is a \"plain\" object.\n *\n * @param value - A value to check\n * @returns True if the passed value is a plain object\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template T - The non-empty array member type.\n */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\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 */\n// TODO: Either fix this lint violation or explain why it's necessary to ignore.\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function isNonEmptyArray<T>(value: T[]): value is NonEmptyArray<T> {\n return Array.isArray(value) && value.length > 0;\n}\n\n/**\n * Type guard for {@link Json}.\n *\n * @param value - The value to check.\n * @returns Whether the value is valid JSON.\n */\nexport function isValidJson(value: unknown): value is Json {\n try {\n return deepEqual(value, JSON.parse(JSON.stringify(value)));\n } catch (_) {\n return false;\n }\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: unknown, codesToCatch: number[] = []) {\n if (!error) {\n return;\n }\n\n if (error instanceof Error) {\n const includesErrorCodeToCatch = codesToCatch.some((code) =>\n error.message.includes(`Fetch failed with status '${code}'`),\n );\n\n if (\n includesErrorCodeToCatch ||\n error.message.includes('Failed to fetch') ||\n error === TIMEOUT_ERROR\n ) {\n console.error(error);\n } else {\n throw error;\n }\n } else {\n // eslint-disable-next-line @typescript-eslint/only-throw-error\n throw error;\n }\n}\n\n/**\n * Checks if two strings are equal, ignoring case.\n *\n * @param value1 - The first string to compare.\n * @param value2 - The second string to compare.\n * @returns `true` if the strings are equal, ignoring case; otherwise, `false`.\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n"]}
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@metamask-previews/controller-utils",
|
3
|
-
"version": "11.4.5-preview-
|
3
|
+
"version": "11.4.5-preview-e05b7d3e",
|
4
4
|
"description": "Data and convenience functions shared by multiple packages",
|
5
5
|
"keywords": [
|
6
6
|
"MetaMask",
|
@@ -55,6 +55,7 @@
|
|
55
55
|
"@types/bn.js": "^5.1.5",
|
56
56
|
"bignumber.js": "^9.1.2",
|
57
57
|
"bn.js": "^5.2.1",
|
58
|
+
"cockatiel": "^3.1.2",
|
58
59
|
"eth-ens-namehash": "^2.0.8",
|
59
60
|
"fast-deep-equal": "^3.1.3"
|
60
61
|
},
|
@@ -64,7 +65,9 @@
|
|
64
65
|
"@types/jest": "^27.4.1",
|
65
66
|
"deepmerge": "^4.2.2",
|
66
67
|
"jest": "^27.5.1",
|
68
|
+
"jest-environment-jsdom": "^27.5.1",
|
67
69
|
"nock": "^13.3.1",
|
70
|
+
"sinon": "^9.2.4",
|
68
71
|
"ts-jest": "^27.1.4",
|
69
72
|
"typedoc": "^0.24.8",
|
70
73
|
"typedoc-plugin-missing-exports": "^2.0.0",
|