@lido-nestjs/execution 1.4.0 → 1.7.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;
@@ -0,0 +1,12 @@
1
+ import { BigNumber } from '@ethersproject/bignumber';
2
+ import { ExtendedJsonRpcBatchProvider } from '../provider/extended-json-rpc-batch-provider';
3
+ import { SimpleFallbackJsonRpcBatchProvider } from '../provider/simple-fallback-json-rpc-batch-provider';
4
+ export declare const MIN_BLOCKCOUNT = 1;
5
+ export declare const MAX_BLOCKCOUNT = 1024;
6
+ export interface FeeHistory {
7
+ oldestBlock: number;
8
+ baseFeePerGas: BigNumber[];
9
+ gasUsedRatio: number[];
10
+ reward: BigNumber[][];
11
+ }
12
+ export declare function getFeeHistory(this: ExtendedJsonRpcBatchProvider | SimpleFallbackJsonRpcBatchProvider, blockCount: number, newestBlock?: string | null | number, rewardPercentiles?: number[]): Promise<FeeHistory>;
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var bignumber = require('@ethersproject/bignumber');
6
+ var bytes = require('@ethersproject/bytes');
7
+ var formatBlockNumber = require('./format-block-number.js');
8
+ var logger$1 = require('@ethersproject/logger');
9
+
10
+ /* eslint-disable @typescript-eslint/no-explicit-any */
11
+ const logger = new logger$1.Logger('packages/execution');
12
+ const MIN_BLOCKCOUNT = 1;
13
+ const MAX_BLOCKCOUNT = 1024;
14
+ async function getFeeHistory(blockCount, newestBlock, rewardPercentiles) {
15
+ var _a;
16
+ await this.getNetwork();
17
+ if (blockCount < MIN_BLOCKCOUNT || blockCount > MAX_BLOCKCOUNT) {
18
+ logger.throwArgumentError('Invalid blockCount for `getFeeHistory`. Should be between 1 and 1024.', 'blockCount', blockCount);
19
+ }
20
+ const params = {
21
+ blockCount: bytes.hexValue(blockCount),
22
+ newestBlock: formatBlockNumber.formatBlockNumber(newestBlock),
23
+ rewardPercentiles,
24
+ };
25
+ const result = await this.perform('getFeeHistory', params);
26
+ return {
27
+ baseFeePerGas: result.baseFeePerGas.map((x) => bignumber.BigNumber.from(x)),
28
+ gasUsedRatio: result.gasUsedRatio,
29
+ oldestBlock: bignumber.BigNumber.from(result.oldestBlock).toNumber(),
30
+ reward: ((_a = result.reward) !== null && _a !== void 0 ? _a : []).map((x) => x.map((y) => bignumber.BigNumber.from(y))),
31
+ };
32
+ }
33
+
34
+ exports.MAX_BLOCKCOUNT = MAX_BLOCKCOUNT;
35
+ exports.MIN_BLOCKCOUNT = MIN_BLOCKCOUNT;
36
+ exports.getFeeHistory = getFeeHistory;
@@ -0,0 +1 @@
1
+ export declare const formatBlockNumber: (blockNumber: string | null | number | undefined) => string;
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var bytes = require('@ethersproject/bytes');
6
+
7
+ const formatBlockNumber = (blockNumber) => {
8
+ if (blockNumber === 'latest' ||
9
+ blockNumber === 'earliest' ||
10
+ blockNumber === 'pending') {
11
+ return blockNumber;
12
+ }
13
+ else if (blockNumber !== null &&
14
+ typeof blockNumber !== 'undefined' &&
15
+ (typeof blockNumber === 'number' || bytes.isHexString(blockNumber))) {
16
+ return bytes.hexValue(blockNumber);
17
+ }
18
+ return 'latest';
19
+ };
20
+
21
+ exports.formatBlockNumber = formatBlockNumber;
package/dist/index.d.ts CHANGED
@@ -6,3 +6,4 @@ export * from './batch-provider.module';
6
6
  export * from './interfaces/fallback-provider';
7
7
  export * from './interfaces/simple-fallback-provider-config';
8
8
  export * from './interfaces/module.options';
9
+ export * from './ethers/fee-history';
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ var simpleFallbackJsonRpcBatchProvider = require('./provider/simple-fallback-jso
7
7
  var queue = require('./common/queue.js');
8
8
  var fallbackProvider_module = require('./fallback-provider.module.js');
9
9
  var batchProvider_module = require('./batch-provider.module.js');
10
+ var feeHistory = require('./ethers/fee-history.js');
10
11
 
11
12
 
12
13
 
@@ -27,3 +28,6 @@ Object.defineProperty(exports, 'BatchProviderModule', {
27
28
  enumerable: true,
28
29
  get: function () { return batchProvider_module.BatchProviderModule; }
29
30
  });
31
+ exports.MAX_BLOCKCOUNT = feeHistory.MAX_BLOCKCOUNT;
32
+ exports.MIN_BLOCKCOUNT = feeHistory.MIN_BLOCKCOUNT;
33
+ exports.getFeeHistory = feeHistory.getFeeHistory;
@@ -9,6 +9,7 @@ import { BigNumber, BigNumberish } from '@ethersproject/bignumber';
9
9
  import { BlockTag } from '../ethers/block-tag';
10
10
  import { TransactionRequest } from '@ethersproject/abstract-provider/src.ts/index';
11
11
  import { MiddlewareCallback, MiddlewareService } from '@lido-nestjs/middleware';
12
+ import { FeeHistory } from '../ethers/fee-history';
12
13
  export interface RequestPolicy {
13
14
  jsonRpcMaxBatchSize: number;
14
15
  maxConcurrentRequests: number;
@@ -70,6 +71,8 @@ export declare class ExtendedJsonRpcBatchProvider extends JsonRpcProvider {
70
71
  static getFormatter(): Formatter;
71
72
  protected _batchAggregatorTick(): void;
72
73
  protected _startBatchAggregator(): void;
74
+ getFeeHistory(blockCount: number, newestBlock?: string | null | number, rewardPercentiles?: number[]): Promise<FeeHistory>;
75
+ prepareRequest(method: string, params: any): [string, Array<any>];
73
76
  use(callback: MiddlewareCallback<Promise<any>>): void;
74
77
  send(method: string, params: Array<unknown>): Promise<unknown>;
75
78
  detectNetwork(): Promise<Network>;
@@ -12,6 +12,7 @@ var common = require('@nestjs/common');
12
12
  var promiseLimit = require('../common/promise-limit.js');
13
13
  var formatterWithEip1898 = require('../ethers/formatter-with-eip1898.js');
14
14
  var middleware = require('@lido-nestjs/middleware');
15
+ var feeHistory = require('../ethers/fee-history.js');
15
16
 
16
17
  exports.ExtendedJsonRpcBatchProvider = class ExtendedJsonRpcBatchProvider extends providers.JsonRpcProvider {
17
18
  constructor(url, network, requestPolicy, fetchMiddlewares = []) {
@@ -102,6 +103,20 @@ exports.ExtendedJsonRpcBatchProvider = class ExtendedJsonRpcBatchProvider extend
102
103
  this._batchAggregator = setTimeout(this._batchAggregatorTick.bind(this), this._requestPolicy.batchAggregationWaitMs);
103
104
  }
104
105
  }
106
+ async getFeeHistory(blockCount, newestBlock, rewardPercentiles) {
107
+ return feeHistory.getFeeHistory.call(this, blockCount, newestBlock, rewardPercentiles);
108
+ }
109
+ prepareRequest(method, params) {
110
+ switch (method) {
111
+ case 'getFeeHistory':
112
+ return [
113
+ 'eth_feeHistory',
114
+ [params.blockCount, params.newestBlock, params.rewardPercentiles],
115
+ ];
116
+ default:
117
+ return super.prepareRequest(method, params);
118
+ }
119
+ }
105
120
  use(callback) {
106
121
  this._fetchMiddlewareService.use(callback);
107
122
  }
@@ -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';
@@ -8,6 +9,7 @@ import { BigNumber, BigNumberish } from '@ethersproject/bignumber';
8
9
  import { Deferrable } from '@ethersproject/properties';
9
10
  import { TransactionRequest } from '@ethersproject/abstract-provider/src.ts/index';
10
11
  import { EventType, Listener } from '@ethersproject/abstract-provider';
12
+ import { FeeHistory } from '../ethers/fee-history';
11
13
  /**
12
14
  * EIP-1898 support
13
15
  * https://eips.ethereum.org/EIPS/eip-1898
@@ -20,6 +22,9 @@ declare module '@ethersproject/providers' {
20
22
  getStorageAt(addressOrName: string | Promise<string>, position: BigNumberish | Promise<BigNumberish>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
21
23
  call(transaction: Deferrable<TransactionRequest>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
22
24
  }
25
+ interface CallOverrides extends Omit<CallOverridesSource, 'blockTag'> {
26
+ blockTag?: BlockTag;
27
+ }
23
28
  }
24
29
  export declare class SimpleFallbackJsonRpcBatchProvider extends BaseProvider {
25
30
  protected config: SimpleFallbackProviderConfig;
@@ -28,12 +33,15 @@ export declare class SimpleFallbackJsonRpcBatchProvider extends BaseProvider {
28
33
  protected activeFallbackProviderIndex: number;
29
34
  protected detectNetworkFirstRun: boolean;
30
35
  protected resetTimer: ReturnType<typeof setTimeout> | null;
36
+ protected lastPerformError: Error | null | unknown;
31
37
  constructor(config: SimpleFallbackProviderConfig, logger: LoggerService);
32
38
  static _formatter: Formatter | null;
33
39
  static getFormatter(): Formatter;
34
40
  on(eventName: EventType, listener: Listener): this;
41
+ getFeeHistory(blockCount: number, newestBlock?: string | null | number, rewardPercentiles?: number[]): Promise<FeeHistory>;
35
42
  protected get provider(): FallbackProvider;
36
43
  protected switchToNextProvider(): void;
44
+ protected errorShouldBeReThrown(error: Error | unknown): boolean;
37
45
  perform(method: string, params: {
38
46
  [name: string]: unknown;
39
47
  }): Promise<unknown>;
@@ -10,12 +10,16 @@ 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');
15
+ var feeHistory = require('../ethers/fee-history.js');
13
16
 
14
17
  exports.SimpleFallbackJsonRpcBatchProvider = class SimpleFallbackJsonRpcBatchProvider extends providers.BaseProvider {
15
18
  constructor(config, logger) {
16
19
  super(config.network);
17
20
  this.detectNetworkFirstRun = true;
18
21
  this.resetTimer = null;
22
+ this.lastPerformError = null;
19
23
  this.config = Object.assign({ maxRetries: 3, minBackoffMs: 500, maxBackoffMs: 5000, logRetries: true, resetIntervalMs: 10000, maxTimeWithoutNewBlocksMs: 60000 }, config);
20
24
  this.logger = logger;
21
25
  const conns = config.urls.filter((url) => {
@@ -67,6 +71,9 @@ exports.SimpleFallbackJsonRpcBatchProvider = class SimpleFallbackJsonRpcBatchPro
67
71
  }
68
72
  return super.on(eventName, listener);
69
73
  }
74
+ async getFeeHistory(blockCount, newestBlock, rewardPercentiles) {
75
+ return feeHistory.getFeeHistory.call(this, blockCount, newestBlock, rewardPercentiles);
76
+ }
70
77
  get provider() {
71
78
  if (this.activeFallbackProviderIndex > this.fallbackProviders.length - 1) {
72
79
  this.activeFallbackProviderIndex = 0;
@@ -96,12 +103,16 @@ exports.SimpleFallbackJsonRpcBatchProvider = class SimpleFallbackJsonRpcBatchPro
96
103
  this.activeFallbackProviderIndex++;
97
104
  this.logger.log(`Switched to next provider for execution layer`);
98
105
  }
106
+ errorShouldBeReThrown(error) {
107
+ return errors.isErrorHasCode(error) && errors.nonRetryableErrors.includes(error.code);
108
+ }
99
109
  async perform(method, params) {
100
- const retry = retrier.retrier(this.logger, this.config.maxRetries, this.config.minBackoffMs, this.config.maxBackoffMs, this.config.logRetries);
110
+ const retry = retrier.retrier(this.logger, this.config.maxRetries, this.config.minBackoffMs, this.config.maxBackoffMs, this.config.logRetries, (e) => this.errorShouldBeReThrown(e));
101
111
  let attempt = 0;
102
112
  // will perform maximum `this.config.maxRetries` retries for fetching data with single provider
103
113
  // after failure will switch to next provider
104
114
  // maximum number of switching is limited to total fallback provider count
115
+ let lastError;
105
116
  while (attempt < this.fallbackProviders.length) {
106
117
  try {
107
118
  attempt++;
@@ -110,12 +121,26 @@ exports.SimpleFallbackJsonRpcBatchProvider = class SimpleFallbackJsonRpcBatchPro
110
121
  return await retry(() => this.provider.provider.perform(method, params));
111
122
  }
112
123
  catch (e) {
124
+ if (this.errorShouldBeReThrown(e)) {
125
+ throw e;
126
+ }
113
127
  this.logger.error('Error while doing ETH1 RPC request. Will try to switch to another provider');
128
+ lastError = e;
114
129
  this.logger.error(e);
115
- this.switchToNextProvider();
130
+ // This check is needed to avoid multiple `switchToNextProvider` calls when doing one JSON-RPC batch.
131
+ // This can happen when multiple N calls to `perform` are batched in one JSON-RPC request and
132
+ // that request fails and throws `Error`. This `Error` is bubbled N times to corresponding `perform` calls.
133
+ // Without the following check, each `perform` call from batch catches `Error` and switches to the next provider,
134
+ // so during one batch multiple switching to next provider can occur, which is not needed.
135
+ if (this.lastPerformError != e) {
136
+ this.switchToNextProvider();
137
+ this.lastPerformError = e;
138
+ }
116
139
  }
117
140
  }
118
- throw new Error('All attempts to do ETH1 RPC request failed');
141
+ const allProvidersFailedError = new allProvidersFailed_error.AllProvidersFailedError('All attempts to do ETH1 RPC request failed');
142
+ allProvidersFailedError.originalError = lastError;
143
+ throw allProvidersFailedError;
119
144
  }
120
145
  async detectNetwork() {
121
146
  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.7.0",
4
4
  "main": "dist/index.js",
5
5
  "types": "dist/index.d.ts",
6
6
  "license": "MIT",
@@ -34,6 +34,9 @@
34
34
  "access": "public"
35
35
  },
36
36
  "dependencies": {
37
+ "@ethersproject/bignumber": "^5.5.0",
38
+ "@ethersproject/bytes": "^5.5.0",
39
+ "@ethersproject/logger": "^5.5.0",
37
40
  "@ethersproject/networks": "^5.5.2",
38
41
  "@ethersproject/properties": "^5.5.0",
39
42
  "@ethersproject/providers": "^5.5.3",