@lido-nestjs/execution 1.4.0 → 1.5.0

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.
@@ -0,0 +1,5 @@
1
+ export declare const nonRetryableErrors: (string | number)[];
2
+ export declare type ErrorWithCode = Error & {
3
+ code: number | string;
4
+ };
5
+ export declare const isErrorHasCode: (error: unknown) => error is ErrorWithCode;
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var logger = require('@ethersproject/logger');
6
+
7
+ const nonRetryableErrors = [
8
+ ///////////////////
9
+ // Generic Errors
10
+ // Not Implemented
11
+ logger.ErrorCode.NOT_IMPLEMENTED,
12
+ // Timeout
13
+ logger.ErrorCode.TIMEOUT,
14
+ ///////////////////
15
+ // Operational Errors
16
+ // Buffer Overrun
17
+ logger.ErrorCode.BUFFER_OVERRUN,
18
+ // Numeric Fault
19
+ // - operation: the operation being executed
20
+ // - fault: the reason this faulted
21
+ logger.ErrorCode.NUMERIC_FAULT,
22
+ ///////////////////
23
+ // Argument Errors
24
+ // Missing new operator to an object
25
+ // - name: The name of the class
26
+ logger.ErrorCode.MISSING_NEW,
27
+ // Invalid argument (e.g. value is incompatible with type) to a function:
28
+ // - argument: The argument name that was invalid
29
+ // - value: The value of the argument
30
+ logger.ErrorCode.INVALID_ARGUMENT,
31
+ // Missing argument to a function:
32
+ // - count: The number of arguments received
33
+ // - expectedCount: The number of arguments expected
34
+ logger.ErrorCode.MISSING_ARGUMENT,
35
+ // Too many arguments
36
+ // - count: The number of arguments received
37
+ // - expectedCount: The number of arguments expected
38
+ logger.ErrorCode.UNEXPECTED_ARGUMENT,
39
+ ///////////////////
40
+ // Blockchain Errors
41
+ // Call exception
42
+ // - transaction: the transaction
43
+ // - address?: the contract address
44
+ // - args?: The arguments passed into the function
45
+ // - method?: The Solidity method signature
46
+ // - errorSignature?: The EIP848 error signature
47
+ // - errorArgs?: The EIP848 error parameters
48
+ // - reason: The reason (only for EIP848 "Error(string)")
49
+ logger.ErrorCode.CALL_EXCEPTION,
50
+ // Insufficient funds (< value + gasLimit * gasPrice)
51
+ // - transaction: the transaction attempted
52
+ logger.ErrorCode.INSUFFICIENT_FUNDS,
53
+ // Nonce has already been used
54
+ // - transaction: the transaction attempted
55
+ logger.ErrorCode.NONCE_EXPIRED,
56
+ // The replacement fee for the transaction is too low
57
+ // - transaction: the transaction attempted
58
+ logger.ErrorCode.REPLACEMENT_UNDERPRICED,
59
+ // The gas limit could not be estimated
60
+ // - transaction: the transaction passed to estimateGas
61
+ logger.ErrorCode.UNPREDICTABLE_GAS_LIMIT,
62
+ // The transaction was replaced by one with a higher gas price
63
+ // - reason: "cancelled", "replaced" or "repriced"
64
+ // - cancelled: true if reason == "cancelled" or reason == "replaced")
65
+ // - hash: original transaction hash
66
+ // - replacement: the full TransactionsResponse for the replacement
67
+ // - receipt: the receipt of the replacement
68
+ logger.ErrorCode.TRANSACTION_REPLACED,
69
+ ];
70
+ const isErrorHasCode = (error) => {
71
+ return (error instanceof Error &&
72
+ Object.prototype.hasOwnProperty.call(error, 'code'));
73
+ };
74
+
75
+ exports.isErrorHasCode = isErrorHasCode;
76
+ exports.nonRetryableErrors = nonRetryableErrors;
@@ -1,2 +1,2 @@
1
1
  import { LoggerService } from '@nestjs/common/services/logger.service';
2
- export declare const retrier: (logger?: LoggerService | null | undefined, defaultMaxRetryCount?: number, defaultMinBackoffMs?: number, defaultMaxBackoffMs?: number, defaultLogWarning?: boolean) => <T extends unknown>(callback: () => T | Promise<T>, maxRetryCount?: number | undefined, minBackoffMs?: number | undefined, maxBackoffMs?: number | undefined, logWarning?: boolean | undefined) => Promise<T>;
2
+ export declare const retrier: (logger?: LoggerService | null | undefined, defaultMaxRetryCount?: number, defaultMinBackoffMs?: number, defaultMaxBackoffMs?: number, defaultLogWarning?: boolean, defaultErrorFilter?: ((error: Error | unknown) => boolean) | undefined) => <T extends unknown>(callback: () => T | Promise<T>, maxRetryCount?: number | undefined, minBackoffMs?: number | undefined, maxBackoffMs?: number | undefined, logWarning?: boolean | undefined, errorFilter?: ((error: Error | unknown) => boolean) | undefined) => Promise<T>;
@@ -4,16 +4,20 @@ Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var sleep = require('./sleep.js');
6
6
 
7
- const retrier = (logger, defaultMaxRetryCount = 3, defaultMinBackoffMs = 1000, defaultMaxBackoffMs = 60000, defaultLogWarning = false) => {
8
- return async (callback, maxRetryCount, minBackoffMs, maxBackoffMs, logWarning) => {
7
+ const retrier = (logger, defaultMaxRetryCount = 3, defaultMinBackoffMs = 1000, defaultMaxBackoffMs = 60000, defaultLogWarning = false, defaultErrorFilter) => {
8
+ return async (callback, maxRetryCount, minBackoffMs, maxBackoffMs, logWarning, errorFilter) => {
9
9
  maxRetryCount = maxRetryCount !== null && maxRetryCount !== void 0 ? maxRetryCount : defaultMaxRetryCount;
10
10
  minBackoffMs = minBackoffMs !== null && minBackoffMs !== void 0 ? minBackoffMs : defaultMinBackoffMs;
11
11
  maxBackoffMs = maxBackoffMs !== null && maxBackoffMs !== void 0 ? maxBackoffMs : defaultMaxBackoffMs;
12
12
  logWarning = logWarning !== null && logWarning !== void 0 ? logWarning : defaultLogWarning;
13
+ errorFilter = errorFilter !== null && errorFilter !== void 0 ? errorFilter : defaultErrorFilter;
13
14
  try {
14
15
  return await callback();
15
16
  }
16
17
  catch (err) {
18
+ if (typeof errorFilter === 'function' && errorFilter(err)) {
19
+ throw err;
20
+ }
17
21
  if (logger && logWarning) {
18
22
  logger.warn(err, 'Retrying after (%dms). Remaining retries [%d]', minBackoffMs, maxRetryCount);
19
23
  }
@@ -21,7 +25,7 @@ const retrier = (logger, defaultMaxRetryCount = 3, defaultMinBackoffMs = 1000, d
21
25
  throw err;
22
26
  }
23
27
  await sleep.sleep(minBackoffMs);
24
- return await retrier(logger)(callback, maxRetryCount - 1, minBackoffMs * 2, maxBackoffMs, logWarning);
28
+ return await retrier(logger)(callback, maxRetryCount - 1, minBackoffMs * 2, maxBackoffMs, logWarning, errorFilter);
25
29
  }
26
30
  };
27
31
  };
@@ -0,0 +1,7 @@
1
+ export declare class AllProvidersFailedError extends Error {
2
+ name: string;
3
+ message: string;
4
+ code: number;
5
+ originalError: Error | unknown;
6
+ constructor(message: string);
7
+ }
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ class AllProvidersFailedError extends Error {
6
+ constructor(message) {
7
+ super('');
8
+ this.name = 'AllProvidersFailedError';
9
+ this.code = 0;
10
+ this.message = message;
11
+ }
12
+ }
13
+
14
+ exports.AllProvidersFailedError = AllProvidersFailedError;
@@ -1,4 +1,5 @@
1
1
  import { BaseProvider, Formatter } from '@ethersproject/providers';
2
+ import { CallOverrides as CallOverridesSource } from '@ethersproject/contracts';
2
3
  import { SimpleFallbackProviderConfig } from '../interfaces/simple-fallback-provider-config';
3
4
  import { Network } from '@ethersproject/networks';
4
5
  import { LoggerService } from '@nestjs/common';
@@ -20,6 +21,9 @@ declare module '@ethersproject/providers' {
20
21
  getStorageAt(addressOrName: string | Promise<string>, position: BigNumberish | Promise<BigNumberish>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
21
22
  call(transaction: Deferrable<TransactionRequest>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
22
23
  }
24
+ interface CallOverrides extends Omit<CallOverridesSource, 'blockTag'> {
25
+ blockTag?: BlockTag;
26
+ }
23
27
  }
24
28
  export declare class SimpleFallbackJsonRpcBatchProvider extends BaseProvider {
25
29
  protected config: SimpleFallbackProviderConfig;
@@ -28,12 +32,14 @@ export declare class SimpleFallbackJsonRpcBatchProvider extends BaseProvider {
28
32
  protected activeFallbackProviderIndex: number;
29
33
  protected detectNetworkFirstRun: boolean;
30
34
  protected resetTimer: ReturnType<typeof setTimeout> | null;
35
+ protected lastPerformError: Error | null | unknown;
31
36
  constructor(config: SimpleFallbackProviderConfig, logger: LoggerService);
32
37
  static _formatter: Formatter | null;
33
38
  static getFormatter(): Formatter;
34
39
  on(eventName: EventType, listener: Listener): this;
35
40
  protected get provider(): FallbackProvider;
36
41
  protected switchToNextProvider(): void;
42
+ protected errorShouldBeReThrown(error: Error | unknown): boolean;
37
43
  perform(method: string, params: {
38
44
  [name: string]: unknown;
39
45
  }): Promise<unknown>;
@@ -10,12 +10,15 @@ var retrier = require('../common/retrier.js');
10
10
  var formatterWithEip1898 = require('../ethers/formatter-with-eip1898.js');
11
11
  var networks = require('../common/networks.js');
12
12
  var noNewBlocksWhilePolling_error = require('../error/no-new-blocks-while-polling.error.js');
13
+ var errors = require('../common/errors.js');
14
+ var allProvidersFailed_error = require('../error/all-providers-failed.error.js');
13
15
 
14
16
  exports.SimpleFallbackJsonRpcBatchProvider = class SimpleFallbackJsonRpcBatchProvider extends providers.BaseProvider {
15
17
  constructor(config, logger) {
16
18
  super(config.network);
17
19
  this.detectNetworkFirstRun = true;
18
20
  this.resetTimer = null;
21
+ this.lastPerformError = null;
19
22
  this.config = Object.assign({ maxRetries: 3, minBackoffMs: 500, maxBackoffMs: 5000, logRetries: true, resetIntervalMs: 10000, maxTimeWithoutNewBlocksMs: 60000 }, config);
20
23
  this.logger = logger;
21
24
  const conns = config.urls.filter((url) => {
@@ -96,12 +99,16 @@ exports.SimpleFallbackJsonRpcBatchProvider = class SimpleFallbackJsonRpcBatchPro
96
99
  this.activeFallbackProviderIndex++;
97
100
  this.logger.log(`Switched to next provider for execution layer`);
98
101
  }
102
+ errorShouldBeReThrown(error) {
103
+ return errors.isErrorHasCode(error) && errors.nonRetryableErrors.includes(error.code);
104
+ }
99
105
  async perform(method, params) {
100
- const retry = retrier.retrier(this.logger, this.config.maxRetries, this.config.minBackoffMs, this.config.maxBackoffMs, this.config.logRetries);
106
+ const retry = retrier.retrier(this.logger, this.config.maxRetries, this.config.minBackoffMs, this.config.maxBackoffMs, this.config.logRetries, (e) => this.errorShouldBeReThrown(e));
101
107
  let attempt = 0;
102
108
  // will perform maximum `this.config.maxRetries` retries for fetching data with single provider
103
109
  // after failure will switch to next provider
104
110
  // maximum number of switching is limited to total fallback provider count
111
+ let lastError;
105
112
  while (attempt < this.fallbackProviders.length) {
106
113
  try {
107
114
  attempt++;
@@ -110,12 +117,26 @@ exports.SimpleFallbackJsonRpcBatchProvider = class SimpleFallbackJsonRpcBatchPro
110
117
  return await retry(() => this.provider.provider.perform(method, params));
111
118
  }
112
119
  catch (e) {
120
+ if (this.errorShouldBeReThrown(e)) {
121
+ throw e;
122
+ }
113
123
  this.logger.error('Error while doing ETH1 RPC request. Will try to switch to another provider');
124
+ lastError = e;
114
125
  this.logger.error(e);
115
- this.switchToNextProvider();
126
+ // This check is needed to avoid multiple `switchToNextProvider` calls when doing one JSON-RPC batch.
127
+ // This can happen when multiple N calls to `perform` are batched in one JSON-RPC request and
128
+ // that request fails and throws `Error`. This `Error` is bubbled N times to corresponding `perform` calls.
129
+ // Without the following check, each `perform` call from batch catches `Error` and switches to the next provider,
130
+ // so during one batch multiple switching to next provider can occur, which is not needed.
131
+ if (this.lastPerformError != e) {
132
+ this.switchToNextProvider();
133
+ this.lastPerformError = e;
134
+ }
116
135
  }
117
136
  }
118
- throw new Error('All attempts to do ETH1 RPC request failed');
137
+ const allProvidersFailedError = new allProvidersFailed_error.AllProvidersFailedError('All attempts to do ETH1 RPC request failed');
138
+ allProvidersFailedError.originalError = lastError;
139
+ throw allProvidersFailedError;
119
140
  }
120
141
  async detectNetwork() {
121
142
  const results = await Promise.allSettled(this.fallbackProviders
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lido-nestjs/execution",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "MIT",
@@ -34,6 +34,7 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
+ "@ethersproject/logger": "^5.5.0",
37
38
  "@ethersproject/networks": "^5.5.2",
38
39
  "@ethersproject/properties": "^5.5.0",
39
40
  "@ethersproject/providers": "^5.5.3",