@metamask-previews/controller-utils 11.7.0-preview-0a8680e7 → 11.7.1-preview-d987e9b2

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 CHANGED
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [11.7.1-backport]
11
+
12
+ ### Added
13
+
14
+ - Add `HttpError` class for errors representing non-200 HTTP responses ([#5809](https://github.com/MetaMask/core/pull/5809))
15
+
16
+ ### Changed
17
+
18
+ - Improved circuit breaker behavior to no longer consider HTTP 4XX responses as service failures ([#5798](https://github.com/MetaMask/core/pull/5798), [#5809](https://github.com/MetaMask/core/pull/5809))
19
+ - Changed from using `handleAll` to `handleWhen(isServiceFailure)` in circuit breaker policy
20
+ - This ensures that expected error responses (like 405 Method Not Allowed and 429 Rate Limited) don't trigger the circuit breaker
21
+
10
22
  ## [11.7.0]
11
23
 
12
24
  ### Added
@@ -490,7 +502,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
490
502
 
491
503
  All changes listed after this point were applied to this package following the monorepo conversion.
492
504
 
493
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/controller-utils@11.7.0...HEAD
505
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/controller-utils@11.7.1-backport...HEAD
506
+ [11.7.1-backport]: https://github.com/MetaMask/core/compare/@metamask/controller-utils@11.7.0...@metamask/controller-utils@11.7.1-backport
494
507
  [11.7.0]: https://github.com/MetaMask/core/compare/@metamask/controller-utils@11.6.0...@metamask/controller-utils@11.7.0
495
508
  [11.6.0]: https://github.com/MetaMask/core/compare/@metamask/controller-utils@11.5.0...@metamask/controller-utils@11.6.0
496
509
  [11.5.0]: https://github.com/MetaMask/core/compare/@metamask/controller-utils@11.4.5...@metamask/controller-utils@11.5.0
@@ -30,6 +30,17 @@ exports.DEFAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
30
30
  * regarded as degraded (affecting when `onDegraded` is called).
31
31
  */
32
32
  exports.DEFAULT_DEGRADED_THRESHOLD = 5000;
33
+ const isServiceFailure = (error) => {
34
+ if (typeof error === 'object' &&
35
+ error !== null &&
36
+ 'httpStatus' in error &&
37
+ typeof error.httpStatus === 'number') {
38
+ return error.httpStatus >= 500;
39
+ }
40
+ // If the error is not an object, or doesn't have a numeric code property,
41
+ // consider it a service failure (e.g., network errors, timeouts, etc.)
42
+ return true;
43
+ };
33
44
  /**
34
45
  * Constructs an object exposing an `execute` method which, given a function —
35
46
  * hereafter called the "service" — will retry that service with ever increasing
@@ -91,7 +102,7 @@ function createServicePolicy(options = {}) {
91
102
  backoff,
92
103
  });
93
104
  const onRetry = retryPolicy.onRetry.bind(retryPolicy);
94
- const circuitBreakerPolicy = (0, cockatiel_1.circuitBreaker)(cockatiel_1.handleAll, {
105
+ const circuitBreakerPolicy = (0, cockatiel_1.circuitBreaker)((0, cockatiel_1.handleWhen)(isServiceFailure), {
95
106
  // While the circuit is open, any additional invocations of the service
96
107
  // passed to the policy (either via automatic retries or by manually
97
108
  // executing the policy again) will result in a BrokenCircuitError. This
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAYmB;AAWjB,mGAtBA,8BAAkB,OAsBA;AAClB,6FAtBA,wBAAY,OAsBA;AAEZ,mGArBA,8BAAkB,OAqBA;AADlB,gGAnBA,2BAAe,OAmBA;AAEf,0FAnBA,qBAAS,OAmBA;AACT,2FAnBA,sBAAU,OAmBA;AA8EZ;;;GAGG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACU,QAAA,8BAA8B,GAAG,EAAE,GAAG,EAA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,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACrC,IACE,oBAAoB,CAAC,KAAK,KAAK,wBAAY,CAAC,MAAM;YAClD,QAAQ,GAAG,iBAAiB,EAC5B;YACA,sBAAsB,CAAC,IAAI,EAAE,CAAC;SAC/B;IACH,CAAC,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,sBAAsB,CAAC,WAAW,CAAC;IAEtD,wEAAwE;IACxE,8CAA8C;IAC9C,MAAM,MAAM,GAAG,IAAA,gBAAI,EAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;IAEvD,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,WAAW;QACX,OAAO;QACP,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC;AA9DD,kDA8DC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\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. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\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 * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\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. See\n * {@link CreateServicePolicyOptions}.\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 * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\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 options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n } = options;\n\n const retryPolicy = retry(retryFilterPolicy, {\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: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\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 `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<void>();\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegradedEventEmitter.emit();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegradedEventEmitter.emit();\n }\n });\n const onDegraded = onDegradedEventEmitter.addListener;\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n return {\n ...policy,\n circuitBreakerPolicy,\n retryPolicy,\n onBreak,\n onDegraded,\n onRetry,\n };\n}\n"]}
1
+ {"version":3,"file":"create-service-policy.cjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":";;;AAAA,yCAYmB;AAWjB,mGAtBA,8BAAkB,OAsBA;AAClB,6FAtBA,wBAAY,OAsBA;AAEZ,mGArBA,8BAAkB,OAqBA;AADlB,gGAnBA,2BAAe,OAmBA;AAEf,0FAnBA,qBAAS,OAmBA;AACT,2FAnBA,sBAAU,OAmBA;AA8EZ;;;GAGG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACU,QAAA,gCAAgC,GAAG,CAAC,CAAC,GAAG,2BAAmB,CAAC,GAAG,CAAC,CAAC;AAE9E;;;GAGG;AACU,QAAA,8BAA8B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAE7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AAoB,CAAC,OAAO,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;IAExE,MAAM,sBAAsB,GAAG,IAAI,wBAAqB,EAAQ,CAAC;IACjE,WAAW,CAAC,QAAQ,CAAC,GAAG,EAAE;QACxB,IAAI,oBAAoB,CAAC,KAAK,KAAK,wBAAY,CAAC,MAAM,EAAE;YACtD,sBAAsB,CAAC,IAAI,EAAE,CAAC;SAC/B;IACH,CAAC,CAAC,CAAC;IACH,WAAW,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACrC,IACE,oBAAoB,CAAC,KAAK,KAAK,wBAAY,CAAC,MAAM;YAClD,QAAQ,GAAG,iBAAiB,EAC5B;YACA,sBAAsB,CAAC,IAAI,EAAE,CAAC;SAC/B;IACH,CAAC,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,sBAAsB,CAAC,WAAW,CAAC;IAEtD,wEAAwE;IACxE,8CAA8C;IAC9C,MAAM,MAAM,GAAG,IAAA,gBAAI,EAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;IAEvD,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,WAAW;QACX,OAAO;QACP,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC;AA9DD,kDA8DC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\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. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\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 * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst isServiceFailure = (error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric code property,\n // consider it a service failure (e.g., network errors, timeouts, etc.)\n return true;\n};\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. See\n * {@link CreateServicePolicyOptions}.\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 * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\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 options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n } = options;\n\n const retryPolicy = retry(retryFilterPolicy, {\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: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\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 `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<void>();\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegradedEventEmitter.emit();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegradedEventEmitter.emit();\n }\n });\n const onDegraded = onDegradedEventEmitter.addListener;\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n return {\n ...policy,\n circuitBreakerPolicy,\n retryPolicy,\n onBreak,\n onDegraded,\n onRetry,\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.d.cts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EAGZ,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,CAAC;AAEF,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IACnC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC;;;OAGG;IACH,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;OAGG;IACH,OAAO,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACzC;;;;;;OAMG;IACH,UAAU,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IACjC;;;;OAIG;IACH,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;CACjC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CA4Df"}
1
+ {"version":3,"file":"create-service-policy.d.cts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EAGZ,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,CAAC;AAEF,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IACnC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC;;;OAGG;IACH,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;OAGG;IACH,OAAO,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACzC;;;;;;OAMG;IACH,UAAU,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IACjC;;;;OAIG;IACH,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;CACjC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAiBhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CA4Df"}
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.d.mts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EAGZ,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,GACX,CAAC;AAEF,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC;;;;OAIG;IACH,OAAO,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,CAAC;IACnC;;;OAGG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;OAGG;IACH,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC;;;OAGG;IACH,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C;;OAEG;IACH,WAAW,EAAE,WAAW,CAAC;IACzB;;;OAGG;IACH,OAAO,EAAE,oBAAoB,CAAC,SAAS,CAAC,CAAC;IACzC;;;;;;OAMG;IACH,UAAU,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;IACjC;;;;OAIG;IACH,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;CACjC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,mBAAmB,IAAI,CAAC;AAErC;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,QAAgC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,8BAA8B,QAAiB,CAAC;AAE7D;;;GAGG;AACH,eAAO,MAAM,0BAA0B,OAAQ,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,0BAA+B,GACvC,aAAa,CA4Df"}
1
+ {"version":3,"file":"create-service-policy.d.mts","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EAGZ,kBAAkB,EAClB,eAAe,EAEf,SAAS,EACT,UAAU,EAGX,kBAAkB;AACnB,OAAO,KAAK,EACV,oBAAoB,EACpB,KAAK,IAAI,cAAc,EACvB,eAAe,EACf,OAAO,EACP,MAAM,EACN,WAAW,EACZ,kBAAkB;AAEnB,OAAO,EACL,kBA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FAULT_CIRCUIT_BREAK_DURATION = 30 * 60 * 1000;
22
22
  * regarded as degraded (affecting when `onDegraded` is called).
23
23
  */
24
24
  export const DEFAULT_DEGRADED_THRESHOLD = 5000;
25
+ const isServiceFailure = (error) => {
26
+ if (typeof error === 'object' &&
27
+ error !== null &&
28
+ 'httpStatus' in error &&
29
+ typeof error.httpStatus === 'number') {
30
+ return error.httpStatus >= 500;
31
+ }
32
+ // If the error is not an object, or doesn't have a numeric code property,
33
+ // consider it a service failure (e.g., network errors, timeouts, etc.)
34
+ return true;
35
+ };
25
36
  /**
26
37
  * Constructs an object exposing an `execute` method which, given a function —
27
38
  * hereafter called the "service" — will retry that service with ever increasing
@@ -83,7 +94,7 @@ export function createServicePolicy(options = {}) {
83
94
  backoff,
84
95
  });
85
96
  const onRetry = retryPolicy.onRetry.bind(retryPolicy);
86
- const circuitBreakerPolicy = circuitBreaker(handleAll, {
97
+ const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {
87
98
  // While the circuit is open, any additional invocations of the service
88
99
  // passed to the policy (either via automatic retries or by manually
89
100
  // executing the policy again) will result in a BrokenCircuitError. This
@@ -1 +1 @@
1
- {"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EACrC,kBAAkB,EAClB,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,SAAS,EACT,UAAU,EACV,KAAK,EACL,IAAI,EACL,kBAAkB;AAUnB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,EACX,CAAC;AA6EF;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,GAAG,CAAC,CAAC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AAI,EAAE,CAAC;SAC/B;IACH,CAAC,CAAC,CAAC;IACH,WAAW,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACrC,IACE,oBAAoB,CAAC,KAAK,KAAK,YAAY,CAAC,MAAM;YAClD,QAAQ,GAAG,iBAAiB,EAC5B;YACA,sBAAsB,CAAC,IAAI,EAAE,CAAC;SAC/B;IACH,CAAC,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,sBAAsB,CAAC,WAAW,CAAC;IAEtD,wEAAwE;IACxE,8CAA8C;IAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;IAEvD,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,WAAW;QACX,OAAO;QACP,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\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. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\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 * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\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. See\n * {@link CreateServicePolicyOptions}.\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 * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\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 options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n } = options;\n\n const retryPolicy = retry(retryFilterPolicy, {\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: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\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 `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<void>();\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegradedEventEmitter.emit();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegradedEventEmitter.emit();\n }\n });\n const onDegraded = onDegradedEventEmitter.addListener;\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n return {\n ...policy,\n circuitBreakerPolicy,\n retryPolicy,\n onBreak,\n onDegraded,\n onRetry,\n };\n}\n"]}
1
+ {"version":3,"file":"create-service-policy.mjs","sourceRoot":"","sources":["../src/create-service-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,YAAY,IAAI,qBAAqB,EACrC,kBAAkB,EAClB,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,SAAS,EACT,UAAU,EACV,KAAK,EACL,IAAI,EACL,kBAAkB;AAUnB,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,UAAU,EACX,CAAC;AA6EF;;;GAGG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAErC;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gC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C5E,qEAAqE;QACrE,qDAAqD;QACrD,aAAa,EAAE,oBAAoB;QACnC,OAAO,EAAE,IAAI,kBAAkB,CAAC,sBAAsB,CAAC;KACxD,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,oBAAoB,CAAC,OAAO,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;IAExE,MAAM,sBAAsB,GAAG,IAAI,qBAAqB,EAAQ,CAAC;IACjE,WAAW,CAAC,QAAQ,CAAC,GAAG,EAAE;QACxB,IAAI,oBAAoB,CAAC,KAAK,KAAK,YAAY,CAAC,MAAM,EAAE;YACtD,sBAAsB,CAAC,IAAI,EAAE,CAAC;SAC/B;IACH,CAAC,CAAC,CAAC;IACH,WAAW,CAAC,SAAS,CAAC,CAAC,EAAE,QAAQ,EAAE,EAAE,EAAE;QACrC,IACE,oBAAoB,CAAC,KAAK,KAAK,YAAY,CAAC,MAAM;YAClD,QAAQ,GAAG,iBAAiB,EAC5B;YACA,sBAAsB,CAAC,IAAI,EAAE,CAAC;SAC/B;IACH,CAAC,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,sBAAsB,CAAC,WAAW,CAAC;IAEtD,wEAAwE;IACxE,8CAA8C;IAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,WAAW,EAAE,oBAAoB,CAAC,CAAC;IAEvD,OAAO;QACL,GAAG,MAAM;QACT,oBAAoB;QACpB,WAAW;QACX,OAAO;QACP,UAAU;QACV,OAAO;KACR,CAAC;AACJ,CAAC","sourcesContent":["import {\n BrokenCircuitError,\n CircuitState,\n EventEmitter as CockatielEventEmitter,\n ConsecutiveBreaker,\n ExponentialBackoff,\n ConstantBackoff,\n circuitBreaker,\n handleAll,\n handleWhen,\n retry,\n wrap,\n} from 'cockatiel';\nimport type {\n CircuitBreakerPolicy,\n Event as CockatielEvent,\n IBackoffFactory,\n IPolicy,\n Policy,\n RetryPolicy,\n} from 'cockatiel';\n\nexport {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n ExponentialBackoff,\n handleAll,\n handleWhen,\n};\n\nexport type { CockatielEvent };\n\n/**\n * The options for `createServicePolicy`.\n */\nexport type CreateServicePolicyOptions = {\n /**\n * The backoff strategy to use. Mainly useful for testing so that a constant\n * backoff can be used when mocking timers. Defaults to an instance of\n * ExponentialBackoff.\n */\n backoff?: IBackoffFactory<unknown>;\n /**\n * The length of time (in milliseconds) to pause retries of the action after\n * the number of failures reaches `maxConsecutiveFailures`.\n */\n circuitBreakDuration?: number;\n /**\n * The length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\n degradedThreshold?: number;\n /**\n * The maximum number of times that the service is allowed to fail before\n * pausing further retries.\n */\n maxConsecutiveFailures?: number;\n /**\n * The maximum number of times that a failing service should be re-invoked\n * before giving up.\n */\n maxRetries?: number;\n /**\n * The policy used to control when the service should be retried based on\n * either the result of the service or an error that it throws. For instance,\n * you could use this to retry only certain errors. See `handleWhen` and\n * friends from Cockatiel for more.\n */\n retryFilterPolicy?: Policy;\n};\n\n/**\n * The service policy object.\n */\nexport type ServicePolicy = IPolicy & {\n /**\n * The Cockatiel circuit breaker policy that the service policy uses\n * internally.\n */\n circuitBreakerPolicy: CircuitBreakerPolicy;\n /**\n * The Cockatiel retry policy that the service policy uses internally.\n */\n retryPolicy: RetryPolicy;\n /**\n * A function which is called when the number of times that the service fails\n * in a row meets the set maximum number of consecutive failures.\n */\n onBreak: CircuitBreakerPolicy['onBreak'];\n /**\n * A function which is called in two circumstances: 1) when the service\n * succeeds before the maximum number of consecutive failures is reached, but\n * takes more time than the `degradedThreshold` to run, or 2) if the service\n * never succeeds before the retry policy gives up and before the maximum\n * number of consecutive failures has been reached.\n */\n onDegraded: CockatielEvent<void>;\n /**\n * A function which will be called by the retry policy each time the service\n * fails and the policy kicks off a timer to re-run the service. This is\n * primarily useful in tests where we are mocking timers.\n */\n onRetry: RetryPolicy['onRetry'];\n};\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. This is set to a value such that if given a\n * service that continually fails, the policy needs to be executed 3 times\n * before further retries are paused.\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 * The default length of time (in milliseconds) that governs when the service is\n * regarded as degraded (affecting when `onDegraded` is called).\n */\nexport const DEFAULT_DEGRADED_THRESHOLD = 5_000;\n\nconst isServiceFailure = (error: unknown) => {\n if (\n typeof error === 'object' &&\n error !== null &&\n 'httpStatus' in error &&\n typeof error.httpStatus === 'number'\n ) {\n return error.httpStatus >= 500;\n }\n\n // If the error is not an object, or doesn't have a numeric code property,\n // consider it a service failure (e.g., network errors, timeouts, etc.)\n return true;\n};\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. See\n * {@link CreateServicePolicyOptions}.\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 * maxRetries: 3,\n * retryFilterPolicy: handleWhen((error) => {\n * return error.message.includes('oops');\n * }),\n * maxConsecutiveFailures: 3,\n * circuitBreakDuration: 5000,\n * degradedThreshold: 2000,\n * onBreak: () => {\n * console.log('Circuit broke');\n * },\n * onDegraded: () => {\n * console.log('Service is degraded');\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 options: CreateServicePolicyOptions = {},\n): ServicePolicy {\n const {\n maxRetries = DEFAULT_MAX_RETRIES,\n retryFilterPolicy = handleAll,\n maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,\n circuitBreakDuration = DEFAULT_CIRCUIT_BREAK_DURATION,\n degradedThreshold = DEFAULT_DEGRADED_THRESHOLD,\n backoff = new ExponentialBackoff(),\n } = options;\n\n const retryPolicy = retry(retryFilterPolicy, {\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: maxRetries,\n // Retries of the service will be executed following ever increasing delays,\n // determined by a backoff formula.\n backoff,\n });\n const onRetry = retryPolicy.onRetry.bind(retryPolicy);\n\n const circuitBreakerPolicy = circuitBreaker(handleWhen(isServiceFailure), {\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 `circuitBreakDuration` passes, after which the\n // service will be allowed to run again. If the service succeeds, the\n // circuit will close, otherwise it will remain open.\n halfOpenAfter: circuitBreakDuration,\n breaker: new ConsecutiveBreaker(maxConsecutiveFailures),\n });\n const onBreak = circuitBreakerPolicy.onBreak.bind(circuitBreakerPolicy);\n\n const onDegradedEventEmitter = new CockatielEventEmitter<void>();\n retryPolicy.onGiveUp(() => {\n if (circuitBreakerPolicy.state === CircuitState.Closed) {\n onDegradedEventEmitter.emit();\n }\n });\n retryPolicy.onSuccess(({ duration }) => {\n if (\n circuitBreakerPolicy.state === CircuitState.Closed &&\n duration > degradedThreshold\n ) {\n onDegradedEventEmitter.emit();\n }\n });\n const onDegraded = onDegradedEventEmitter.addListener;\n\n // Every time the retry policy makes an attempt, it executes the circuit\n // breaker policy, which executes the service.\n const policy = wrap(retryPolicy, circuitBreakerPolicy);\n\n return {\n ...policy,\n circuitBreakerPolicy,\n retryPolicy,\n onBreak,\n onDegraded,\n onRetry,\n };\n}\n"]}
package/dist/index.cjs CHANGED
@@ -14,7 +14,7 @@ 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 = exports.handleWhen = exports.handleAll = exports.createServicePolicy = exports.ExponentialBackoff = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_DEGRADED_THRESHOLD = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.ConstantBackoff = exports.CircuitState = exports.BrokenCircuitError = 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.HttpError = exports.hexToText = exports.hexToBN = exports.handleFetch = exports.gweiDecToWEIBN = exports.getBuyURL = exports.fromHex = exports.fractionBN = exports.fetchWithErrorHandling = exports.convertHexToDecimal = exports.BNToHex = exports.handleWhen = exports.handleAll = exports.createServicePolicy = exports.ExponentialBackoff = exports.DEFAULT_MAX_RETRIES = exports.DEFAULT_MAX_CONSECUTIVE_FAILURES = exports.DEFAULT_DEGRADED_THRESHOLD = exports.DEFAULT_CIRCUIT_BREAK_DURATION = exports.ConstantBackoff = exports.CircuitState = exports.BrokenCircuitError = void 0;
18
18
  var create_service_policy_1 = require("./create-service-policy.cjs");
19
19
  Object.defineProperty(exports, "BrokenCircuitError", { enumerable: true, get: function () { return create_service_policy_1.BrokenCircuitError; } });
20
20
  Object.defineProperty(exports, "CircuitState", { enumerable: true, get: function () { return create_service_policy_1.CircuitState; } });
@@ -39,6 +39,7 @@ Object.defineProperty(exports, "gweiDecToWEIBN", { enumerable: true, get: functi
39
39
  Object.defineProperty(exports, "handleFetch", { enumerable: true, get: function () { return util_1.handleFetch; } });
40
40
  Object.defineProperty(exports, "hexToBN", { enumerable: true, get: function () { return util_1.hexToBN; } });
41
41
  Object.defineProperty(exports, "hexToText", { enumerable: true, get: function () { return util_1.hexToText; } });
42
+ Object.defineProperty(exports, "HttpError", { enumerable: true, get: function () { return util_1.HttpError; } });
42
43
  Object.defineProperty(exports, "isNonEmptyArray", { enumerable: true, get: function () { return util_1.isNonEmptyArray; } });
43
44
  Object.defineProperty(exports, "isPlainObject", { enumerable: true, get: function () { return util_1.isPlainObject; } });
44
45
  Object.defineProperty(exports, "isSafeChainId", { enumerable: true, get: function () { return util_1.isSafeChainId; } });
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,qEAYiC;AAX/B,2HAAA,kBAAkB,OAAA;AAClB,qHAAA,YAAY,OAAA;AACZ,wHAAA,eAAe,OAAA;AACf,uIAAA,8BAA8B,OAAA;AAC9B,mIAAA,0BAA0B,OAAA;AAC1B,yIAAA,gCAAgC,OAAA;AAChC,4HAAA,mBAAmB,OAAA;AACnB,2HAAA,kBAAkB,OAAA;AAClB,4HAAA,mBAAmB,OAAA;AACnB,kHAAA,SAAS,OAAA;AACT,mHAAA,UAAU,OAAA;AAOZ,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 {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n ExponentialBackoff,\n createServicePolicy,\n handleAll,\n handleWhen,\n} from './create-service-policy';\nexport type {\n CockatielEvent,\n CreateServicePolicyOptions,\n ServicePolicy,\n} 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"]}
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,qEAYiC;AAX/B,2HAAA,kBAAkB,OAAA;AAClB,qHAAA,YAAY,OAAA;AACZ,wHAAA,eAAe,OAAA;AACf,uIAAA,8BAA8B,OAAA;AAC9B,mIAAA,0BAA0B,OAAA;AAC1B,yIAAA,gCAAgC,OAAA;AAChC,4HAAA,mBAAmB,OAAA;AACnB,2HAAA,kBAAkB,OAAA;AAClB,4HAAA,mBAAmB,OAAA;AACnB,kHAAA,SAAS,OAAA;AACT,mHAAA,UAAU,OAAA;AAOZ,kDAA4B;AAE5B,mCA6BgB;AA5Bd,+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,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 {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n ExponentialBackoff,\n createServicePolicy,\n handleAll,\n handleWhen,\n} from './create-service-policy';\nexport type {\n CockatielEvent,\n CreateServicePolicyOptions,\n ServicePolicy,\n} 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 HttpError,\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
@@ -2,7 +2,7 @@ export { BrokenCircuitError, CircuitState, ConstantBackoff, DEFAULT_CIRCUIT_BREA
2
2
  export type { CockatielEvent, CreateServicePolicyOptions, ServicePolicy, } from "./create-service-policy.cjs";
3
3
  export * from "./constants.cjs";
4
4
  export type { NonEmptyArray } from "./util.cjs";
5
- 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";
5
+ export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, HttpError, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive, } from "./util.cjs";
6
6
  export * from "./types.cjs";
7
7
  export * from "./siwe.cjs";
8
8
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,GACX,oCAAgC;AACjC,YAAY,EACV,cAAc,EACd,0BAA0B,EAC1B,aAAa,GACd,oCAAgC;AACjC,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,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,GACX,oCAAgC;AACjC,YAAY,EACV,cAAc,EACd,0BAA0B,EAC1B,aAAa,GACd,oCAAgC;AACjC,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,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
@@ -2,7 +2,7 @@ export { BrokenCircuitError, CircuitState, ConstantBackoff, DEFAULT_CIRCUIT_BREA
2
2
  export type { CockatielEvent, CreateServicePolicyOptions, ServicePolicy, } from "./create-service-policy.mjs";
3
3
  export * from "./constants.mjs";
4
4
  export type { NonEmptyArray } from "./util.mjs";
5
- 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";
5
+ export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, HttpError, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive, } from "./util.mjs";
6
6
  export * from "./types.mjs";
7
7
  export * from "./siwe.mjs";
8
8
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,GACX,oCAAgC;AACjC,YAAY,EACV,cAAc,EACd,0BAA0B,EAC1B,aAAa,GACd,oCAAgC;AACjC,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,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,GACX,oCAAgC;AACjC,YAAY,EACV,cAAc,EACd,0BAA0B,EAC1B,aAAa,GACd,oCAAgC;AACjC,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,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,6 +1,6 @@
1
1
  export { BrokenCircuitError, CircuitState, ConstantBackoff, DEFAULT_CIRCUIT_BREAK_DURATION, DEFAULT_DEGRADED_THRESHOLD, DEFAULT_MAX_CONSECUTIVE_FAILURES, DEFAULT_MAX_RETRIES, ExponentialBackoff, createServicePolicy, handleAll, handleWhen } from "./create-service-policy.mjs";
2
2
  export * from "./constants.mjs";
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
+ export { BNToHex, convertHexToDecimal, fetchWithErrorHandling, fractionBN, fromHex, getBuyURL, gweiDecToWEIBN, handleFetch, hexToBN, hexToText, HttpError, isNonEmptyArray, isPlainObject, isSafeChainId, isSafeDynamicKey, isSmartContractCode, isValidJson, isValidHexAddress, normalizeEnsName, query, safelyExecute, safelyExecuteWithTimeout, successfulFetch, timeoutFetch, toChecksumHexAddress, toHex, weiHexToGweiDec, isEqualCaseInsensitive } from "./util.mjs";
4
4
  export * from "./types.mjs";
5
5
  export * from "./siwe.mjs";
6
6
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,EACX,oCAAgC;AAMjC,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 {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n ExponentialBackoff,\n createServicePolicy,\n handleAll,\n handleWhen,\n} from './create-service-policy';\nexport type {\n CockatielEvent,\n CreateServicePolicyOptions,\n ServicePolicy,\n} 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"]}
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,eAAe,EACf,8BAA8B,EAC9B,0BAA0B,EAC1B,gCAAgC,EAChC,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,SAAS,EACT,UAAU,EACX,oCAAgC;AAMjC,gCAA4B;AAE5B,OAAO,EACL,OAAO,EACP,mBAAmB,EACnB,sBAAsB,EACtB,UAAU,EACV,OAAO,EACP,SAAS,EACT,cAAc,EACd,WAAW,EACX,OAAO,EACP,SAAS,EACT,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 {\n BrokenCircuitError,\n CircuitState,\n ConstantBackoff,\n DEFAULT_CIRCUIT_BREAK_DURATION,\n DEFAULT_DEGRADED_THRESHOLD,\n DEFAULT_MAX_CONSECUTIVE_FAILURES,\n DEFAULT_MAX_RETRIES,\n ExponentialBackoff,\n createServicePolicy,\n handleAll,\n handleWhen,\n} from './create-service-policy';\nexport type {\n CockatielEvent,\n CreateServicePolicyOptions,\n ServicePolicy,\n} 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 HttpError,\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
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.isEqualCaseInsensitive = exports.isValidJson = exports.isNonEmptyArray = exports.isPlainObject = exports.convertHexToDecimal = exports.query = exports.normalizeEnsName = exports.timeoutFetch = exports.fetchWithErrorHandling = exports.handleFetch = exports.successfulFetch = exports.isSmartContractCode = exports.isValidHexAddress = exports.toChecksumHexAddress = exports.safelyExecuteWithTimeout = exports.safelyExecute = exports.toHex = exports.fromHex = exports.hexToText = exports.hexToBN = exports.getBuyURL = exports.weiHexToGweiDec = exports.gweiDecToWEIBN = exports.fractionBN = exports.BNToHex = exports.isSafeChainId = exports.isSafeDynamicKey = exports.PROTOTYPE_POLLUTION_BLOCKLIST = void 0;
6
+ exports.isEqualCaseInsensitive = exports.isValidJson = exports.isNonEmptyArray = exports.isPlainObject = exports.convertHexToDecimal = exports.query = exports.normalizeEnsName = exports.timeoutFetch = exports.fetchWithErrorHandling = exports.handleFetch = exports.successfulFetch = exports.HttpError = exports.isSmartContractCode = exports.isValidHexAddress = exports.toChecksumHexAddress = exports.safelyExecuteWithTimeout = exports.safelyExecute = exports.toHex = exports.fromHex = exports.hexToText = exports.hexToBN = exports.getBuyURL = exports.weiHexToGweiDec = exports.gweiDecToWEIBN = exports.fractionBN = exports.BNToHex = exports.isSafeChainId = exports.isSafeDynamicKey = exports.PROTOTYPE_POLLUTION_BLOCKLIST = void 0;
7
7
  const util_1 = require("@ethereumjs/util");
8
8
  const ethjs_unit_1 = require("@metamask/ethjs-unit");
9
9
  const utils_1 = require("@metamask/utils");
@@ -298,6 +298,22 @@ function isSmartContractCode(code) {
298
298
  return smartContractCode;
299
299
  }
300
300
  exports.isSmartContractCode = isSmartContractCode;
301
+ /**
302
+ * An error representing a non-200 HTTP response.
303
+ */
304
+ class HttpError extends Error {
305
+ /**
306
+ * Construct an HTTP error.
307
+ *
308
+ * @param status - The HTTP response status.
309
+ * @param message - The error message.
310
+ */
311
+ constructor(status, message) {
312
+ super(message || `Fetch failed with status '${status}'`);
313
+ this.httpStatus = status;
314
+ }
315
+ }
316
+ exports.HttpError = HttpError;
301
317
  /**
302
318
  * Execute fetch and verify that the response was successful.
303
319
  *
@@ -308,7 +324,7 @@ exports.isSmartContractCode = isSmartContractCode;
308
324
  async function successfulFetch(request, options) {
309
325
  const response = await fetch(request, options);
310
326
  if (!response.ok) {
311
- throw new Error(`Fetch failed with status '${response.status}' for request '${String(request)}'`);
327
+ throw new HttpError(response.status, `Fetch failed with status '${response.status}' for request '${String(request)}'`);
312
328
  }
313
329
  return response;
314
330
  }
package/dist/util.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"util.cjs","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ereumjs/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"]}
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,C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C5D;IAAC,OAAO,CAAC,EAAE;QACV,OAAO,KAAK,CAAC;KACd;AACH,CAAC;AAND,kCAMC;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,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 * An error representing a non-200 HTTP response.\n */\nexport class HttpError extends Error {\n public httpStatus: number;\n\n /**\n * Construct an HTTP error.\n *\n * @param status - The HTTP response status.\n * @param message - The error message.\n */\n constructor(status: number, message?: string) {\n super(message || `Fetch failed with status '${status}'`);\n this.httpStatus = status;\n }\n}\n\n/**\n * Execute fetch and verify that the response was successful.\n *\n * @param request - Request information.\n * @param options - Fetch options.\n * @returns The fetch response.\n */\nexport async function successfulFetch(\n request: URL | RequestInfo,\n options?: RequestInit,\n) {\n const response = await fetch(request, options);\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Fetch failed with status '${response.status}' for request '${String(request)}'`,\n );\n }\n return response;\n}\n\n/**\n * Execute fetch and return object response.\n *\n * @param request - The request information.\n * @param options - The fetch options.\n * @returns The fetch response JSON data.\n */\nexport async function handleFetch(\n request: URL | RequestInfo,\n options?: RequestInit,\n) {\n const response = await successfulFetch(request, options);\n const object = await response.json();\n return object;\n}\n\n/**\n * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.\n *\n * @param request - the request options object\n * @param request.url - The request url to query.\n * @param request.options - The fetch options.\n * @param request.timeout - Timeout to fail request\n * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context\n * @returns The fetch response JSON data or undefined (if error occurs).\n */\nexport async function fetchWithErrorHandling({\n url,\n options,\n timeout,\n errorCodesToCatch,\n}: {\n url: string;\n options?: RequestInit;\n timeout?: number;\n errorCodesToCatch?: number[];\n}) {\n let result;\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise<Response>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } else {\n result = await handleFetch(url, options);\n }\n } catch (e) {\n logOrRethrowError(e, errorCodesToCatch);\n }\n return result;\n}\n\n/**\n * Fetch that fails after timeout.\n *\n * @param url - Url to fetch.\n * @param options - Options to send with the request.\n * @param timeout - Timeout to fail request.\n * @returns Promise resolving the request.\n */\nexport async function timeoutFetch(\n url: string,\n options?: RequestInit,\n timeout = 500,\n): Promise<Response> {\n return Promise.race([\n successfulFetch(url, options),\n new Promise<Response>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n}\n\n/**\n * Normalizes the given ENS name.\n *\n * @param ensName - The ENS name.\n * @returns The normalized ENS name string.\n */\nexport function normalizeEnsName(ensName: string): string | null {\n // `.` refers to the registry root contract\n if (ensName === '.') {\n return ensName;\n }\n if (ensName && typeof ensName === 'string') {\n try {\n const normalized = ensNamehash.normalize(ensName.trim());\n // this regex is only sufficient with the above call to ensNamehash.normalize\n // TODO: change 7 in regex to 3 when shorter ENS domains are live\n if (normalized.match(/^(([\\w\\d-]+)\\.)*[\\w\\d-]{7,}\\.(eth|test)$/u)) {\n return normalized;\n }\n } catch (_) {\n // do nothing\n }\n }\n return null;\n}\n\n/**\n * Wrapper method to handle EthQuery requests.\n *\n * @param ethQuery - EthQuery object initialized with a provider.\n * @param method - Method to request.\n * @param args - Arguments to send.\n * @returns Promise resolving the request.\n */\nexport function query(\n ethQuery: EthQuery,\n method: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[] = [],\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> {\n return new Promise((resolve, reject) => {\n const cb = (error: unknown, result: unknown) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n };\n\n // Using `in` rather than `hasProperty` so that we look up the prototype\n // chain for the method.\n if (method in ethQuery && typeof ethQuery[method] === 'function') {\n ethQuery[method](...args, cb);\n } else {\n ethQuery.sendAsync({ method, params: args }, cb);\n }\n });\n}\n\n/**\n * Converts valid hex strings to decimal numbers, and handles unexpected arg types.\n *\n * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.\n * @returns a decimal number.\n */\nexport const convertHexToDecimal = (\n value: string | undefined = '0x0',\n): number => {\n if (isStrictHexString(value)) {\n return parseInt(value, 16);\n }\n\n return Number(value) ? Number(value) : 0;\n};\n\ntype PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Determines whether a value is a \"plain\" object.\n *\n * @param value - A value to check\n * @returns True if the passed value is a plain object\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template T - The non-empty array member type.\n */\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.d.cts CHANGED
@@ -148,6 +148,19 @@ export declare function isValidHexAddress(possibleAddress: string, { allowNonPre
148
148
  * @returns Whether the code was smart contract code or not.
149
149
  */
150
150
  export declare function isSmartContractCode(code: string): boolean;
151
+ /**
152
+ * An error representing a non-200 HTTP response.
153
+ */
154
+ export declare class HttpError extends Error {
155
+ httpStatus: number;
156
+ /**
157
+ * Construct an HTTP error.
158
+ *
159
+ * @param status - The HTTP response status.
160
+ * @param message - The error message.
161
+ */
162
+ constructor(status: number, message?: string);
163
+ }
151
164
  /**
152
165
  * Execute fetch and verify that the response was successful.
153
166
  *
@@ -1 +1 @@
1
- {"version":3,"file":"util.d.cts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,4BAA4B;AAEhD,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,wBAAwB;AAOjD,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB;AAC9C,OAAO,EAAE,cAAc;AAMvB,YAAY,EAAE,SAAS,EAAE,CAAC;AAI1B,e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C,QAAQ,CAAC,CASnB;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAkB/D;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CACnB,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,MAAM,EAGd,IAAI,GAAE,GAAG,EAAO,GAGf,OAAO,CAAC,GAAG,CAAC,CAkBd;AAED;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,WACvB,MAAM,GAAG,SAAS,KACxB,MAMF,CAAC;AAEF,KAAK,WAAW,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC,CAAC;AAE7D;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,WAAW,CAElE;AAED;;;;GAIG;AAGH,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;AAE3C;;;;;;GAMG;AAGH,wBAAgB,eAAe,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,KAAK,IAAI,aAAa,CAAC,CAAC,CAAC,CAExE;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,IAAI,CAMzD;AAiCD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,OAAO,CAKT"}
package/dist/util.d.mts CHANGED
@@ -148,6 +148,19 @@ export declare function isValidHexAddress(possibleAddress: string, { allowNonPre
148
148
  * @returns Whether the code was smart contract code or not.
149
149
  */
150
150
  export declare function isSmartContractCode(code: string): boolean;
151
+ /**
152
+ * An error representing a non-200 HTTP response.
153
+ */
154
+ export declare class HttpError extends Error {
155
+ httpStatus: number;
156
+ /**
157
+ * Construct an HTTP error.
158
+ *
159
+ * @param status - The HTTP response status.
160
+ * @param message - The error message.
161
+ */
162
+ constructor(status: number, message?: string);
163
+ }
151
164
  /**
152
165
  * Execute fetch and verify that the response was successful.
153
166
  *
@@ -1 +1 @@
1
- {"version":3,"file":"util.d.mts","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,4BAA4B;AAEhD,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,wBAAwB;AAOjD,OAAO,KAAK,EAAE,SAAS,EAAE,qBAAqB;AAC9C,OAAO,EAAE,cAAc;AAMvB,YAAY,EAAE,SAAS,EAAE,CAAC;AAI1B,eAAO,MAAM,6BAA6B,oDAIhC,CAAC;AAEX;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAKrD;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAanD;AACD;;;;;GAKG;AAGH,wBAAgB,OAAO,CAAC,OAAO,EAAE,EAAE,GAAG,SAAS,iBAE9C;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CACxB,QAAQ,EAAE,EAAE,EACZ,SAAS,EAAE,MAAM,GAAG,MAAM,EAC1B,WAAW,EAAE,MAAM,GAAG,MAAM,MAK7B;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,OA4BhD;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,OAG1C;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CACvB,WAAW,SAAM,EACjB,OAAO,CAAC,EAAE,MAAM,EAChB,MAAM,SAAI,GACT,MAAM,GAAG,SAAS,CAapB;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,QAAQ,EAAE,MAAM,MAEvC;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,UASpC;AA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G,KAAK,IAAI,IAAI,CAMzD;AAiCD;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,GACb,OAAO,CAKT"}
package/dist/util.mjs CHANGED
@@ -285,6 +285,21 @@ export function isSmartContractCode(code) {
285
285
  const smartContractCode = code !== '0x' && code !== '0x0';
286
286
  return smartContractCode;
287
287
  }
288
+ /**
289
+ * An error representing a non-200 HTTP response.
290
+ */
291
+ export class HttpError extends Error {
292
+ /**
293
+ * Construct an HTTP error.
294
+ *
295
+ * @param status - The HTTP response status.
296
+ * @param message - The error message.
297
+ */
298
+ constructor(status, message) {
299
+ super(message || `Fetch failed with status '${status}'`);
300
+ this.httpStatus = status;
301
+ }
302
+ }
288
303
  /**
289
304
  * Execute fetch and verify that the response was successful.
290
305
  *
@@ -295,7 +310,7 @@ export function isSmartContractCode(code) {
295
310
  export async function successfulFetch(request, options) {
296
311
  const response = await fetch(request, options);
297
312
  if (!response.ok) {
298
- throw new Error(`Fetch failed with status '${response.status}' for request '${String(request)}'`);
313
+ throw new HttpError(response.status, `Fetch failed with status '${response.status}' for request '${String(request)}'`);
299
314
  }
300
315
  return response;
301
316
  }
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;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,CA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AwB,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/only-throw-error\n throw error;\n }\n}\n\n/**\n * Checks if two strings are equal, ignoring case.\n *\n * @param value1 - The first string to compare.\n * @param value2 - The second string to compare.\n * @returns `true` if the strings are equal, ignoring case; otherwise, `false`.\n */\nexport function isEqualCaseInsensitive(\n value1: string,\n value2: string,\n): boolean {\n if (typeof value1 !== 'string' || typeof value2 !== 'string') {\n return false;\n }\n return value1.toLowerCase() === value2.toLowerCase();\n}\n"]}
1
+ {"version":3,"file":"util.mjs","sourceRoot":"","sources":["../src/util.ts"],"names":[],"mappings":";;;;;;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,QAAQ,CACpC,OAAO,EACP,iBAAiB,CAAC,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,iBAAi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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 * An error representing a non-200 HTTP response.\n */\nexport class HttpError extends Error {\n public httpStatus: number;\n\n /**\n * Construct an HTTP error.\n *\n * @param status - The HTTP response status.\n * @param message - The error message.\n */\n constructor(status: number, message?: string) {\n super(message || `Fetch failed with status '${status}'`);\n this.httpStatus = status;\n }\n}\n\n/**\n * Execute fetch and verify that the response was successful.\n *\n * @param request - Request information.\n * @param options - Fetch options.\n * @returns The fetch response.\n */\nexport async function successfulFetch(\n request: URL | RequestInfo,\n options?: RequestInit,\n) {\n const response = await fetch(request, options);\n if (!response.ok) {\n throw new HttpError(\n response.status,\n `Fetch failed with status '${response.status}' for request '${String(request)}'`,\n );\n }\n return response;\n}\n\n/**\n * Execute fetch and return object response.\n *\n * @param request - The request information.\n * @param options - The fetch options.\n * @returns The fetch response JSON data.\n */\nexport async function handleFetch(\n request: URL | RequestInfo,\n options?: RequestInit,\n) {\n const response = await successfulFetch(request, options);\n const object = await response.json();\n return object;\n}\n\n/**\n * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.\n *\n * @param request - the request options object\n * @param request.url - The request url to query.\n * @param request.options - The fetch options.\n * @param request.timeout - Timeout to fail request\n * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context\n * @returns The fetch response JSON data or undefined (if error occurs).\n */\nexport async function fetchWithErrorHandling({\n url,\n options,\n timeout,\n errorCodesToCatch,\n}: {\n url: string;\n options?: RequestInit;\n timeout?: number;\n errorCodesToCatch?: number[];\n}) {\n let result;\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise<Response>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n } else {\n result = await handleFetch(url, options);\n }\n } catch (e) {\n logOrRethrowError(e, errorCodesToCatch);\n }\n return result;\n}\n\n/**\n * Fetch that fails after timeout.\n *\n * @param url - Url to fetch.\n * @param options - Options to send with the request.\n * @param timeout - Timeout to fail request.\n * @returns Promise resolving the request.\n */\nexport async function timeoutFetch(\n url: string,\n options?: RequestInit,\n timeout = 500,\n): Promise<Response> {\n return Promise.race([\n successfulFetch(url, options),\n new Promise<Response>((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR);\n }, timeout),\n ),\n ]);\n}\n\n/**\n * Normalizes the given ENS name.\n *\n * @param ensName - The ENS name.\n * @returns The normalized ENS name string.\n */\nexport function normalizeEnsName(ensName: string): string | null {\n // `.` refers to the registry root contract\n if (ensName === '.') {\n return ensName;\n }\n if (ensName && typeof ensName === 'string') {\n try {\n const normalized = ensNamehash.normalize(ensName.trim());\n // this regex is only sufficient with the above call to ensNamehash.normalize\n // TODO: change 7 in regex to 3 when shorter ENS domains are live\n if (normalized.match(/^(([\\w\\d-]+)\\.)*[\\w\\d-]{7,}\\.(eth|test)$/u)) {\n return normalized;\n }\n } catch (_) {\n // do nothing\n }\n }\n return null;\n}\n\n/**\n * Wrapper method to handle EthQuery requests.\n *\n * @param ethQuery - EthQuery object initialized with a provider.\n * @param method - Method to request.\n * @param args - Arguments to send.\n * @returns Promise resolving the request.\n */\nexport function query(\n ethQuery: EthQuery,\n method: string,\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n args: any[] = [],\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n): Promise<any> {\n return new Promise((resolve, reject) => {\n const cb = (error: unknown, result: unknown) => {\n if (error) {\n reject(error);\n return;\n }\n resolve(result);\n };\n\n // Using `in` rather than `hasProperty` so that we look up the prototype\n // chain for the method.\n if (method in ethQuery && typeof ethQuery[method] === 'function') {\n ethQuery[method](...args, cb);\n } else {\n ethQuery.sendAsync({ method, params: args }, cb);\n }\n });\n}\n\n/**\n * Converts valid hex strings to decimal numbers, and handles unexpected arg types.\n *\n * @param value - a string that is either a hexadecimal with `0x` prefix or a decimal string.\n * @returns a decimal number.\n */\nexport const convertHexToDecimal = (\n value: string | undefined = '0x0',\n): number => {\n if (isStrictHexString(value)) {\n return parseInt(value, 16);\n }\n\n return Number(value) ? Number(value) : 0;\n};\n\ntype PlainObject = Record<number | string | symbol, unknown>;\n\n/**\n * Determines whether a value is a \"plain\" object.\n *\n * @param value - A value to check\n * @returns True if the passed value is a plain object\n */\nexport function isPlainObject(value: unknown): value is PlainObject {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Like {@link Array}, but always non-empty.\n *\n * @template T - The non-empty array member type.\n */\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.7.0-preview-0a8680e7",
3
+ "version": "11.7.1-preview-d987e9b2",
4
4
  "description": "Data and convenience functions shared by multiple packages",
5
5
  "keywords": [
6
6
  "MetaMask",