@subql/node-ethereum 4.3.2 → 4.4.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.
Files changed (87) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/admin/admin.module.d.ts +2 -0
  4. package/dist/admin/admin.module.js +25 -0
  5. package/dist/admin/admin.module.js.map +1 -0
  6. package/dist/app.module.js +2 -0
  7. package/dist/app.module.js.map +1 -1
  8. package/dist/configure/SubqueryProject.js +15 -18
  9. package/dist/configure/SubqueryProject.js.map +1 -1
  10. package/dist/ethereum/api.connection.js +4 -1
  11. package/dist/ethereum/api.connection.js.map +1 -1
  12. package/dist/ethereum/api.ethereum.js +26 -11
  13. package/dist/ethereum/api.ethereum.js.map +1 -1
  14. package/dist/ethereum/api.service.ethereum.js +7 -6
  15. package/dist/ethereum/api.service.ethereum.js.map +1 -1
  16. package/dist/ethereum/api.service.ethereum.test.js +1 -1
  17. package/dist/ethereum/api.service.ethereum.test.js.map +1 -1
  18. package/dist/ethereum/block.ethereum.js +1 -1
  19. package/dist/ethereum/block.ethereum.js.map +1 -1
  20. package/dist/ethereum/ethers/celo/celo-provider.js +15 -20
  21. package/dist/ethereum/ethers/celo/celo-provider.js.map +1 -1
  22. package/dist/ethereum/ethers/celo/celo-ws-provider.spec.js +1 -1
  23. package/dist/ethereum/ethers/celo/celo-ws-provider.spec.js.map +1 -1
  24. package/dist/ethereum/ethers/json-rpc-batch-provider.js +9 -9
  25. package/dist/ethereum/ethers/json-rpc-batch-provider.js.map +1 -1
  26. package/dist/ethereum/ethers/json-rpc-batch-provider.spec.js +1 -1
  27. package/dist/ethereum/ethers/json-rpc-batch-provider.spec.js.map +1 -1
  28. package/dist/ethereum/ethers/op/op-provider.js +7 -1
  29. package/dist/ethereum/ethers/op/op-provider.js.map +1 -1
  30. package/dist/ethereum/ethers/web/geturl.js +2 -3
  31. package/dist/ethereum/ethers/web/geturl.js.map +1 -1
  32. package/dist/ethereum/safe-api.js +3 -0
  33. package/dist/ethereum/safe-api.js.map +1 -1
  34. package/dist/ethereum/utils.ethereum.js +58 -13
  35. package/dist/ethereum/utils.ethereum.js.map +1 -1
  36. package/dist/indexer/blockDispatcher/block-dispatcher.service.js +1 -0
  37. package/dist/indexer/blockDispatcher/block-dispatcher.service.js.map +1 -1
  38. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.d.ts +2 -2
  39. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js +3 -3
  40. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js.map +1 -1
  41. package/dist/indexer/dictionary/ethDictionary.service.js +2 -0
  42. package/dist/indexer/dictionary/ethDictionary.service.js.map +1 -1
  43. package/dist/indexer/dictionary/utils.js +5 -2
  44. package/dist/indexer/dictionary/utils.js.map +1 -1
  45. package/dist/indexer/dictionary/utils.spec.js +3 -3
  46. package/dist/indexer/dictionary/utils.spec.js.map +1 -1
  47. package/dist/indexer/dictionary/v1/ethDictionaryV1.js +3 -4
  48. package/dist/indexer/dictionary/v1/ethDictionaryV1.js.map +1 -1
  49. package/dist/indexer/dictionary/v1/ethDictionaryV1.spec.js +3 -3
  50. package/dist/indexer/dictionary/v1/ethDictionaryV1.spec.js.map +1 -1
  51. package/dist/indexer/dictionary/v2/ethDictionaryV2.js +7 -20
  52. package/dist/indexer/dictionary/v2/ethDictionaryV2.js.map +1 -1
  53. package/dist/indexer/dictionary/v2/utils.js +12 -6
  54. package/dist/indexer/dictionary/v2/utils.js.map +1 -1
  55. package/dist/indexer/dictionary/v2/utils.spec.js +4 -15
  56. package/dist/indexer/dictionary/v2/utils.spec.js.map +1 -1
  57. package/dist/indexer/ds-processor.service.js +1 -4
  58. package/dist/indexer/ds-processor.service.js.map +1 -1
  59. package/dist/indexer/dynamic-ds.service.js +9 -2
  60. package/dist/indexer/dynamic-ds.service.js.map +1 -1
  61. package/dist/indexer/fetch.module.js +5 -3
  62. package/dist/indexer/fetch.module.js.map +1 -1
  63. package/dist/indexer/fetch.service.js +2 -0
  64. package/dist/indexer/fetch.service.js.map +1 -1
  65. package/dist/indexer/indexer.manager.js +7 -8
  66. package/dist/indexer/indexer.manager.js.map +1 -1
  67. package/dist/indexer/project.service.js +1 -1
  68. package/dist/indexer/project.service.js.map +1 -1
  69. package/dist/indexer/unfinalizedBlocks.service.js +3 -1
  70. package/dist/indexer/unfinalizedBlocks.service.js.map +1 -1
  71. package/dist/indexer/worker/worker-fetch.module.js +4 -0
  72. package/dist/indexer/worker/worker-fetch.module.js.map +1 -1
  73. package/dist/indexer/worker/worker.service.js +2 -0
  74. package/dist/indexer/worker/worker.service.js.map +1 -1
  75. package/dist/init.js +3 -6
  76. package/dist/init.js.map +1 -1
  77. package/dist/meta/meta.controller.js +1 -0
  78. package/dist/meta/meta.controller.js.map +1 -1
  79. package/dist/meta/meta.service.js +11 -9
  80. package/dist/meta/meta.service.js.map +1 -1
  81. package/dist/subcommands/testing.init.js +1 -2
  82. package/dist/subcommands/testing.init.js.map +1 -1
  83. package/dist/utils/project.js +1 -1
  84. package/dist/utils/project.js.map +1 -1
  85. package/dist/utils/string.js +1 -1
  86. package/dist/utils/string.js.map +1 -1
  87. package/package.json +3 -3
@@ -0,0 +1,2 @@
1
+ export declare class AdminModule {
2
+ }
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ // Copyright 2020-2024 SubQuery Pte Ltd authors & contributors
3
+ // SPDX-License-Identifier: GPL-3.0
4
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
5
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
6
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
7
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
8
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.AdminModule = void 0;
12
+ const common_1 = require("@nestjs/common");
13
+ const admin_1 = require("@subql/node-core/dist/admin");
14
+ const fetch_module_1 = require("../indexer/fetch.module");
15
+ let AdminModule = class AdminModule {
16
+ };
17
+ AdminModule = __decorate([
18
+ (0, common_1.Module)({
19
+ imports: [fetch_module_1.FetchModule],
20
+ controllers: [...admin_1.adminControllers],
21
+ providers: [...admin_1.adminServices],
22
+ })
23
+ ], AdminModule);
24
+ exports.AdminModule = AdminModule;
25
+ //# sourceMappingURL=admin.module.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"admin.module.js","sourceRoot":"","sources":["../../src/admin/admin.module.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;AAEnC,2CAAwC;AACxC,uDAA8E;AAC9E,0DAAsD;AAO/C,IAAM,WAAW,GAAjB,MAAM,WAAW;CAAG,CAAA;AAAd,WAAW;IALvB,IAAA,eAAM,EAAC;QACN,OAAO,EAAE,CAAC,0BAAW,CAAC;QACtB,WAAW,EAAE,CAAC,GAAG,wBAAgB,CAAC;QAClC,SAAS,EAAE,CAAC,GAAG,qBAAa,CAAC;KAC9B,CAAC;GACW,WAAW,CAAG;AAAd,kCAAW","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Module } from '@nestjs/common';\nimport { adminControllers, adminServices } from '@subql/node-core/dist/admin';\nimport { FetchModule } from '../indexer/fetch.module';\n\n@Module({\n imports: [FetchModule],\n controllers: [...adminControllers],\n providers: [...adminServices],\n})\nexport class AdminModule {}\n"]}
@@ -13,6 +13,7 @@ const common_1 = require("@nestjs/common");
13
13
  const event_emitter_1 = require("@nestjs/event-emitter");
14
14
  const schedule_1 = require("@nestjs/schedule");
15
15
  const node_core_1 = require("@subql/node-core");
16
+ const admin_module_1 = require("./admin/admin.module");
16
17
  const configure_module_1 = require("./configure/configure.module");
17
18
  const fetch_module_1 = require("./indexer/fetch.module");
18
19
  const meta_module_1 = require("./meta/meta.module");
@@ -27,6 +28,7 @@ AppModule = __decorate([
27
28
  schedule_1.ScheduleModule.forRoot(),
28
29
  fetch_module_1.FetchModule,
29
30
  meta_module_1.MetaModule,
31
+ admin_module_1.AdminModule,
30
32
  ],
31
33
  controllers: [],
32
34
  })
@@ -1 +1 @@
1
- {"version":3,"file":"app.module.js","sourceRoot":"","sources":["../src/app.module.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;AAEnC,2CAAwC;AACxC,yDAA2D;AAC3D,+CAAkD;AAClD,gDAA4C;AAC5C,mEAA+D;AAC/D,yDAAqD;AACrD,oDAAgD;AAazC,IAAM,SAAS,GAAf,MAAM,SAAS;CAAG,CAAA;AAAZ,SAAS;IAXrB,IAAA,eAAM,EAAC;QACN,OAAO,EAAE;YACP,oBAAQ,CAAC,OAAO,EAAE;YAClB,kCAAkB,CAAC,OAAO,EAAE;YAC5B,kCAAe,CAAC,QAAQ,EAAE;YAC1B,yBAAc,CAAC,OAAO,EAAE;YACxB,0BAAW;YACX,wBAAU;SACX;QACD,WAAW,EAAE,EAAE;KAChB,CAAC;GACW,SAAS,CAAG;AAAZ,8BAAS","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Module } from '@nestjs/common';\nimport { EventEmitterModule } from '@nestjs/event-emitter';\nimport { ScheduleModule } from '@nestjs/schedule';\nimport { DbModule } from '@subql/node-core';\nimport { ConfigureModule } from './configure/configure.module';\nimport { FetchModule } from './indexer/fetch.module';\nimport { MetaModule } from './meta/meta.module';\n\n@Module({\n imports: [\n DbModule.forRoot(),\n EventEmitterModule.forRoot(),\n ConfigureModule.register(),\n ScheduleModule.forRoot(),\n FetchModule,\n MetaModule,\n ],\n controllers: [],\n})\nexport class AppModule {}\n"]}
1
+ {"version":3,"file":"app.module.js","sourceRoot":"","sources":["../src/app.module.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;AAEnC,2CAAwC;AACxC,yDAA2D;AAC3D,+CAAkD;AAClD,gDAA4C;AAC5C,uDAAmD;AACnD,mEAA+D;AAC/D,yDAAqD;AACrD,oDAAgD;AAczC,IAAM,SAAS,GAAf,MAAM,SAAS;CAAG,CAAA;AAAZ,SAAS;IAZrB,IAAA,eAAM,EAAC;QACN,OAAO,EAAE;YACP,oBAAQ,CAAC,OAAO,EAAE;YAClB,kCAAkB,CAAC,OAAO,EAAE;YAC5B,kCAAe,CAAC,QAAQ,EAAE;YAC1B,yBAAc,CAAC,OAAO,EAAE;YACxB,0BAAW;YACX,wBAAU;YACV,0BAAW;SACZ;QACD,WAAW,EAAE,EAAE;KAChB,CAAC;GACW,SAAS,CAAG;AAAZ,8BAAS","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Module } from '@nestjs/common';\nimport { EventEmitterModule } from '@nestjs/event-emitter';\nimport { ScheduleModule } from '@nestjs/schedule';\nimport { DbModule } from '@subql/node-core';\nimport { AdminModule } from './admin/admin.module';\nimport { ConfigureModule } from './configure/configure.module';\nimport { FetchModule } from './indexer/fetch.module';\nimport { MetaModule } from './meta/meta.module';\n\n@Module({\n imports: [\n DbModule.forRoot(),\n EventEmitterModule.forRoot(),\n ConfigureModule.register(),\n ScheduleModule.forRoot(),\n FetchModule,\n MetaModule,\n AdminModule,\n ],\n controllers: [],\n})\nexport class AppModule {}\n"]}
@@ -10,21 +10,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
10
10
  var __metadata = (this && this.__metadata) || function (k, v) {
11
11
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
12
12
  };
13
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
14
- if (kind === "m") throw new TypeError("Private method is not writable");
15
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
16
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
17
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
18
- };
19
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
20
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
21
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
22
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
23
- };
24
13
  var __importDefault = (this && this.__importDefault) || function (mod) {
25
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
26
15
  };
27
- var _SubqueryProject_dataSources;
28
16
  Object.defineProperty(exports, "__esModule", { value: true });
29
17
  exports.SubqueryProject = void 0;
30
18
  const assert_1 = __importDefault(require("assert"));
@@ -40,6 +28,14 @@ const NOT_SUPPORT = (name) => {
40
28
  throw new Error(`Manifest specVersion ${name} is not supported`);
41
29
  };
42
30
  let SubqueryProject = class SubqueryProject {
31
+ id;
32
+ root;
33
+ network;
34
+ schema;
35
+ templates;
36
+ runner;
37
+ parent;
38
+ #dataSources;
43
39
  constructor(id, root, network, dataSources, schema, templates, runner, parent) {
44
40
  this.id = id;
45
41
  this.root = root;
@@ -48,14 +44,13 @@ let SubqueryProject = class SubqueryProject {
48
44
  this.templates = templates;
49
45
  this.runner = runner;
50
46
  this.parent = parent;
51
- _SubqueryProject_dataSources.set(this, void 0);
52
- __classPrivateFieldSet(this, _SubqueryProject_dataSources, dataSources, "f");
47
+ this.#dataSources = dataSources;
53
48
  }
54
49
  get dataSources() {
55
- return __classPrivateFieldGet(this, _SubqueryProject_dataSources, "f");
50
+ return this.#dataSources;
56
51
  }
57
52
  async applyCronTimestamps(getTimestamp) {
58
- __classPrivateFieldSet(this, _SubqueryProject_dataSources, await (0, node_core_1.insertBlockFiltersCronSchedules)(this.dataSources, getTimestamp, common_ethereum_1.isRuntimeDs, common_ethereum_1.EthereumHandlerKind.Block), "f");
53
+ this.#dataSources = await (0, node_core_1.insertBlockFiltersCronSchedules)(this.dataSources, getTimestamp, common_ethereum_1.isRuntimeDs, common_ethereum_1.EthereumHandlerKind.Block);
59
54
  }
60
55
  static async create(path, rawManifest, reader, root, // If project local then directory otherwise temp directory
61
56
  networkOverrides) {
@@ -76,7 +71,6 @@ let SubqueryProject = class SubqueryProject {
76
71
  }
77
72
  }
78
73
  };
79
- _SubqueryProject_dataSources = new WeakMap();
80
74
  SubqueryProject = __decorate([
81
75
  (0, common_1.Injectable)(),
82
76
  __metadata("design:paramtypes", [String, String, Object, Array, graphql_1.GraphQLSchema, Array, Object, Object])
@@ -96,7 +90,10 @@ async function loadProjectFromManifestBase(projectManifest, reader, path, root,
96
90
  if (typeof projectManifest.network.endpoint === 'string') {
97
91
  projectManifest.network.endpoint = [projectManifest.network.endpoint];
98
92
  }
99
- const network = processChainId(Object.assign(Object.assign({}, projectManifest.network), networkOverrides));
93
+ const network = processChainId({
94
+ ...projectManifest.network,
95
+ ...networkOverrides,
96
+ });
100
97
  if (!network.endpoint) {
101
98
  throw new Error(`Network endpoint must be provided for network. chainId="${network.chainId}"`);
102
99
  }
@@ -1 +1 @@
1
- {"version":3,"file":"SubqueryProject.js","sourceRoot":"","sources":["../../src/configure/SubqueryProject.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEnC,oDAA4B;AAC5B,2CAA4C;AAC5C,0CAA+C;AAC/C,4DAOgC;AAChC,gDAK0B;AAQ1B,wCAAqD;AACrD,qCAAwC;AACxC,8CAA0D;AAE1D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAUlE,MAAM,WAAW,GAAG,CAAC,I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,CACb,mCAAmC,eAAe,CAAC,MAAM,CAAC,IAAI,EAAE,CACjE,CAAC;KACH;IACD,MAAM,MAAM,GAAG,IAAA,6BAAqB,EAAC,YAAY,CAAC,CAAC;IAEnD,MAAM,WAAW,GAAG,MAAM,IAAA,gCAAsB,EAC9C,eAAe,CAAC,WAAW,EAC3B,MAAM,EACN,IAAI,CACL,CAAC;IAEF,MAAM,SAAS,GAAG,MAAM,IAAA,gCAAoB,EAC1C,eAAe,CAAC,SAAS,EACzB,IAAI,EACJ,MAAM,EACN,4BAAU,CACX,CAAC;IACF,MAAM,MAAM,GAAG,eAAe,CAAC,MAAM,CAAC;IACtC,IAAA,gBAAM,EACJ,IAAA,uBAAc,EAAC,cAAc,EAAE,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EACnD,IAAI,KAAK,CACP,+BAA+B,MAAM,CAAC,IAAI,CAAC,OAAO,kBAAkB,cAAc,EAAE,CACrF,CACF,CAAC;IAEF,OAAO,IAAI,eAAe,CACxB,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,wCAAwC;IAC1E,IAAI,EACJ,OAAO,EACP,WAAW,EACX,MAAM,EACN,SAAS,EACT,MAAM,EACN,eAAe,CAAC,MAAM,CACvB,CAAC;AACJ,CAAC","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport assert from 'assert';\nimport { Injectable } from '@nestjs/common';\nimport { validateSemver } from '@subql/common';\nimport {\n parseEthereumProjectManifest,\n SubqlEthereumDataSource,\n ProjectManifestV1_0_0Impl,\n isRuntimeDs,\n EthereumHandlerKind,\n isCustomDs,\n} from '@subql/common-ethereum';\nimport {\n CronFilter,\n insertBlockFiltersCronSchedules,\n ISubqueryProject,\n loadProjectTemplates,\n} from '@subql/node-core';\nimport { ParentProject, Reader, RunnerSpecs } from '@subql/types-core';\nimport {\n EthereumNetworkConfig,\n RuntimeDatasourceTemplate,\n CustomDatasourceTemplate,\n EthereumBlockFilter,\n} from '@subql/types-ethereum';\nimport { buildSchemaFromString } from '@subql/utils';\nimport { GraphQLSchema } from 'graphql';\nimport { updateDatasourcesFlare } from '../utils/project';\n\nconst { version: packageVersion } = require('../../package.json');\n\nexport type EthereumProjectDs = SubqlEthereumDataSource;\n\nexport type EthereumProjectDsTemplate =\n | RuntimeDatasourceTemplate\n | CustomDatasourceTemplate;\n\nexport type SubqlProjectBlockFilter = EthereumBlockFilter & CronFilter;\n\nconst NOT_SUPPORT = (name: string) => {\n throw new Error(`Manifest specVersion ${name} is not supported`);\n};\n\n// This is the runtime type after we have mapped genesisHash to chainId and endpoint/dict have been provided when dealing with deployments\ntype NetworkConfig = EthereumNetworkConfig & { chainId: string };\n\n@Injectable()\nexport class SubqueryProject implements ISubqueryProject {\n #dataSources: EthereumProjectDs[];\n\n constructor(\n readonly id: string,\n readonly root: string,\n readonly network: NetworkConfig,\n dataSources: EthereumProjectDs[],\n readonly schema: GraphQLSchema,\n readonly templates: EthereumProjectDsTemplate[],\n readonly runner?: RunnerSpecs,\n readonly parent?: ParentProject,\n ) {\n this.#dataSources = dataSources;\n }\n\n get dataSources(): EthereumProjectDs[] {\n return this.#dataSources;\n }\n\n async applyCronTimestamps(\n getTimestamp: (height: number) => Promise<Date>,\n ): Promise<void> {\n this.#dataSources = await insertBlockFiltersCronSchedules(\n this.dataSources,\n getTimestamp,\n isRuntimeDs,\n EthereumHandlerKind.Block,\n );\n }\n\n static async create(\n path: string,\n rawManifest: unknown,\n reader: Reader,\n root: string, // If project local then directory otherwise temp directory\n networkOverrides?: Partial<EthereumNetworkConfig>,\n ): Promise<SubqueryProject> {\n // rawManifest and reader can be reused here.\n // It has been pre-fetched and used for rebase manifest runner options with args\n // in order to generate correct configs.\n\n // But we still need reader here, because path can be remote or local\n // and the `loadProjectManifest(projectPath)` only support local mode\n if (rawManifest === undefined) {\n throw new Error(`Get manifest from project path ${path} failed`);\n }\n const manifest = parseEthereumProjectManifest(rawManifest);\n\n if (manifest.isV1_0_0) {\n return loadProjectFromManifestBase(\n manifest.asV1_0_0,\n reader,\n path,\n root,\n networkOverrides,\n );\n } else {\n NOT_SUPPORT(manifest.specVersion);\n }\n }\n}\n\nfunction processChainId(network: any): NetworkConfig {\n if (network.chainId && network.genesisHash) {\n throw new Error('Please only provide one of chainId and genesisHash');\n } else if (network.genesisHash && !network.chainId) {\n network.chainId = network.genesisHash;\n }\n delete network.genesisHash;\n return network;\n}\n\ntype SUPPORT_MANIFEST = ProjectManifestV1_0_0Impl;\n\nasync function loadProjectFromManifestBase(\n projectManifest: SUPPORT_MANIFEST,\n reader: Reader,\n path: string,\n root: string,\n networkOverrides?: Partial<EthereumNetworkConfig>,\n): Promise<SubqueryProject> {\n if (typeof projectManifest.network.endpoint === 'string') {\n projectManifest.network.endpoint = [projectManifest.network.endpoint];\n }\n\n const network = processChainId({\n ...projectManifest.network,\n ...networkOverrides,\n });\n\n if (!network.endpoint) {\n throw new Error(\n `Network endpoint must be provided for network. chainId=\"${network.chainId}\"`,\n );\n }\n\n let schemaString: string;\n try {\n schemaString = await reader.getFile(projectManifest.schema.file);\n } catch (e) {\n throw new Error(\n `unable to fetch the schema from ${projectManifest.schema.file}`,\n );\n }\n const schema = buildSchemaFromString(schemaString);\n\n const dataSources = await updateDatasourcesFlare(\n projectManifest.dataSources,\n reader,\n root,\n );\n\n const templates = await loadProjectTemplates(\n projectManifest.templates,\n root,\n reader,\n isCustomDs,\n );\n const runner = projectManifest.runner;\n assert(\n validateSemver(packageVersion, runner.node.version),\n new Error(\n `Runner require node version ${runner.node.version}, current node ${packageVersion}`,\n ),\n );\n\n return new SubqueryProject(\n reader.root ? reader.root : path, //TODO, need to method to get project_id\n root,\n network,\n dataSources,\n schema,\n templates,\n runner,\n projectManifest.parent,\n );\n}\n"]}
1
+ {"version":3,"file":"SubqueryProject.js","sourceRoot":"","sources":["../../src/configure/SubqueryProject.ts"],"names":[],"mapp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GPL-3.0\n\nimport assert from 'assert';\nimport { Injectable } from '@nestjs/common';\nimport { validateSemver } from '@subql/common';\nimport {\n parseEthereumProjectManifest,\n SubqlEthereumDataSource,\n ProjectManifestV1_0_0Impl,\n isRuntimeDs,\n EthereumHandlerKind,\n isCustomDs,\n} from '@subql/common-ethereum';\nimport {\n CronFilter,\n insertBlockFiltersCronSchedules,\n ISubqueryProject,\n loadProjectTemplates,\n} from '@subql/node-core';\nimport { ParentProject, Reader, RunnerSpecs } from '@subql/types-core';\nimport {\n EthereumNetworkConfig,\n RuntimeDatasourceTemplate,\n CustomDatasourceTemplate,\n EthereumBlockFilter,\n} from '@subql/types-ethereum';\nimport { buildSchemaFromString } from '@subql/utils';\nimport { GraphQLSchema } from 'graphql';\nimport { updateDatasourcesFlare } from '../utils/project';\n\nconst { version: packageVersion } = require('../../package.json');\n\nexport type EthereumProjectDs = SubqlEthereumDataSource;\n\nexport type EthereumProjectDsTemplate =\n | RuntimeDatasourceTemplate\n | CustomDatasourceTemplate;\n\nexport type SubqlProjectBlockFilter = EthereumBlockFilter & CronFilter;\n\nconst NOT_SUPPORT = (name: string) => {\n throw new Error(`Manifest specVersion ${name} is not supported`);\n};\n\n// This is the runtime type after we have mapped genesisHash to chainId and endpoint/dict have been provided when dealing with deployments\ntype NetworkConfig = EthereumNetworkConfig & { chainId: string };\n\n@Injectable()\nexport class SubqueryProject implements ISubqueryProject {\n #dataSources: EthereumProjectDs[];\n\n constructor(\n readonly id: string,\n readonly root: string,\n readonly network: NetworkConfig,\n dataSources: EthereumProjectDs[],\n readonly schema: GraphQLSchema,\n readonly templates: EthereumProjectDsTemplate[],\n readonly runner?: RunnerSpecs,\n readonly parent?: ParentProject,\n ) {\n this.#dataSources = dataSources;\n }\n\n get dataSources(): EthereumProjectDs[] {\n return this.#dataSources;\n }\n\n async applyCronTimestamps(\n getTimestamp: (height: number) => Promise<Date>,\n ): Promise<void> {\n this.#dataSources = await insertBlockFiltersCronSchedules(\n this.dataSources,\n getTimestamp,\n isRuntimeDs,\n EthereumHandlerKind.Block,\n );\n }\n\n static async create(\n path: string,\n rawManifest: unknown,\n reader: Reader,\n root: string, // If project local then directory otherwise temp directory\n networkOverrides?: Partial<EthereumNetworkConfig>,\n ): Promise<SubqueryProject> {\n // rawManifest and reader can be reused here.\n // It has been pre-fetched and used for rebase manifest runner options with args\n // in order to generate correct configs.\n\n // But we still need reader here, because path can be remote or local\n // and the `loadProjectManifest(projectPath)` only support local mode\n if (rawManifest === undefined) {\n throw new Error(`Get manifest from project path ${path} failed`);\n }\n const manifest = parseEthereumProjectManifest(rawManifest);\n\n if (manifest.isV1_0_0) {\n return loadProjectFromManifestBase(\n manifest.asV1_0_0,\n reader,\n path,\n root,\n networkOverrides,\n );\n } else {\n NOT_SUPPORT(manifest.specVersion);\n }\n }\n}\n\nfunction processChainId(network: any): NetworkConfig {\n if (network.chainId && network.genesisHash) {\n throw new Error('Please only provide one of chainId and genesisHash');\n } else if (network.genesisHash && !network.chainId) {\n network.chainId = network.genesisHash;\n }\n delete network.genesisHash;\n return network;\n}\n\ntype SUPPORT_MANIFEST = ProjectManifestV1_0_0Impl;\n\nasync function loadProjectFromManifestBase(\n projectManifest: SUPPORT_MANIFEST,\n reader: Reader,\n path: string,\n root: string,\n networkOverrides?: Partial<EthereumNetworkConfig>,\n): Promise<SubqueryProject> {\n if (typeof projectManifest.network.endpoint === 'string') {\n projectManifest.network.endpoint = [projectManifest.network.endpoint];\n }\n\n const network = processChainId({\n ...projectManifest.network,\n ...networkOverrides,\n });\n\n if (!network.endpoint) {\n throw new Error(\n `Network endpoint must be provided for network. chainId=\"${network.chainId}\"`,\n );\n }\n\n let schemaString: string;\n try {\n schemaString = await reader.getFile(projectManifest.schema.file);\n } catch (e) {\n throw new Error(\n `unable to fetch the schema from ${projectManifest.schema.file}`,\n );\n }\n const schema = buildSchemaFromString(schemaString);\n\n const dataSources = await updateDatasourcesFlare(\n projectManifest.dataSources,\n reader,\n root,\n );\n\n const templates = await loadProjectTemplates(\n projectManifest.templates,\n root,\n reader,\n isCustomDs,\n );\n const runner = projectManifest.runner;\n assert(\n validateSemver(packageVersion, runner.node.version),\n new Error(\n `Runner require node version ${runner.node.version}, current node ${packageVersion}`,\n ),\n );\n\n return new SubqueryProject(\n reader.root ? reader.root : path, //TODO, need to method to get project_id\n root,\n network,\n dataSources,\n schema,\n templates,\n runner,\n projectManifest.parent,\n );\n}\n"]}
@@ -6,10 +6,12 @@ exports.EthereumApiConnection = void 0;
6
6
  const node_core_1 = require("@subql/node-core");
7
7
  const api_ethereum_1 = require("./api.ethereum");
8
8
  class EthereumApiConnection {
9
+ unsafeApi;
10
+ fetchBlocksBatches;
11
+ networkMeta;
9
12
  constructor(unsafeApi, fetchBlocksBatches) {
10
13
  this.unsafeApi = unsafeApi;
11
14
  this.fetchBlocksBatches = fetchBlocksBatches;
12
- this.handleError = EthereumApiConnection.handleError;
13
15
  this.networkMeta = {
14
16
  chain: unsafeApi.getChainId().toString(),
15
17
  specName: unsafeApi.getSpecName(),
@@ -34,6 +36,7 @@ class EthereumApiConnection {
34
36
  const blocks = await this.fetchBlocksBatches()(this.unsafeApi, heights);
35
37
  return blocks;
36
38
  }
39
+ handleError = EthereumApiConnection.handleError;
37
40
  static handleError(e) {
38
41
  let formatted_error;
39
42
  if (e.message.startsWith(`No response received from RPC endpoint in`)) {
@@ -1 +1 @@
1
- {"version":3,"file":"api.connection.js","sourceRoot":"","sources":["../../src/ethereum/api.connection.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;AAGnC,gDAU0B;AAE1B,iDAA6C;AAa7C,MAAa,qBAAqB;IAUhC,YACS,SAAsB,EACrB,kBAAgC;QADjC,cAAS,GAAT,SAAS,CAAa;QACrB,uBAAkB,GAAlB,kBAAkB,CAAc;QA+C1C,gBAAW,GAAG,qBAAqB,CAAC,WAAW,CAAC;QA7C9C,IAAI,CAAC,WAAW,GAAG;YACjB,KAAK,EAAE,SAAS,CAAC,UAAU,EAA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IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,0BAA0B,CAAC,EAAE;YAC3D,eAAe,GAAG,IAAI,0BAAc,CAAC,CAAC,CAAC,CAAC;SACzC;aAAM,IAAI,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAC,EAAE;YACtD,eAAe,GAAG,IAAI,8BAAkB,CAAC,CAAC,CAAC,CAAC;SAC7C;aAAM;YACL,eAAe,GAAG,IAAI,8BAAkB,CACtC,CAAC,CAAC,IAAI,EACN,CAAC,CAAC,OAAO,EACT,wBAAY,CAAC,OAAO,CACrB,CAAC;SACH;QACD,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AAhFD,sDAgFC","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n ApiConnectionError,\n ApiErrorType,\n DisconnectionError,\n LargeResponseError,\n NetworkMetadataPayload,\n RateLimitError,\n TimeoutError,\n IApiConnectionSpecific,\n IBlock,\n} from '@subql/node-core';\nimport { EthereumBlock, LightEthereumBlock } from '@subql/types-ethereum';\nimport { EthereumApi } from './api.ethereum';\nimport SafeEthProvider from './safe-api';\n\nexport type FetchFunc =\n | ((api: EthereumApi, batch: number[]) => Promise<IBlock<EthereumBlock>[]>)\n | ((\n api: EthereumApi,\n batch: number[],\n ) => Promise<IBlock<LightEthereumBlock>[]>);\n\n// We use a function to get the fetch function because it can change depending on the skipBlocks feature\nexport type GetFetchFunc = () => FetchFunc;\n\nexport class EthereumApiConnection\n implements\n IApiConnectionSpecific<\n EthereumApi,\n SafeEthProvider,\n IBlock<EthereumBlock>[] | IBlock<LightEthereumBlock>[]\n >\n{\n readonly networkMeta: NetworkMetadataPayload;\n\n private constructor(\n public unsafeApi: EthereumApi,\n private fetchBlocksBatches: GetFetchFunc,\n ) {\n this.networkMeta = {\n chain: unsafeApi.getChainId().toString(),\n specName: unsafeApi.getSpecName(),\n genesisHash: unsafeApi.getGenesisHash(),\n };\n }\n\n static async create(\n endpoint: string,\n blockConfirmations: number,\n fetchBlocksBatches: GetFetchFunc,\n eventEmitter: EventEmitter2,\n unfinalizedBlocks: boolean,\n ): Promise<EthereumApiConnection> {\n const api = new EthereumApi(\n endpoint,\n blockConfirmations,\n eventEmitter,\n unfinalizedBlocks,\n );\n\n await api.init();\n\n return new EthereumApiConnection(api, fetchBlocksBatches);\n }\n\n safeApi(height: number): SafeEthProvider {\n throw new Error(`Not Implemented`);\n }\n\n async apiConnect(): Promise<void> {\n await this.unsafeApi.connect();\n }\n\n async apiDisconnect(): Promise<void> {\n await this.unsafeApi.disconnect();\n }\n\n async fetchBlocks(\n heights: number[],\n ): Promise<IBlock<EthereumBlock>[] | IBlock<LightEthereumBlock>[]> {\n const blocks = await this.fetchBlocksBatches()(this.unsafeApi, heights);\n return blocks;\n }\n\n handleError = EthereumApiConnection.handleError;\n\n static handleError(e: Error): ApiConnectionError {\n let formatted_error: ApiConnectionError;\n if (e.message.startsWith(`No response received from RPC endpoint in`)) {\n formatted_error = new TimeoutError(e);\n } else if (e.message.startsWith(`disconnected from `)) {\n formatted_error = new DisconnectionError(e);\n } else if (e.message.startsWith(`Rate Limited at endpoint`)) {\n formatted_error = new RateLimitError(e);\n } else if (e.message.includes(`Exceeded max limit of`)) {\n formatted_error = new LargeResponseError(e);\n } else {\n formatted_error = new ApiConnectionError(\n e.name,\n e.message,\n ApiErrorType.Default,\n );\n }\n return formatted_error;\n }\n}\n"]}
1
+ {"version":3,"file":"api.connection.js","sourceRoot":"","sources":["../../src/ethereum/api.connection.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;AAGnC,gDAU0B;AAE1B,iDAA6C;AAa7C,MAAa,qBAAqB;IAWvB;IACC;IAJD,WAAW,CAAyB;IAE7C,YACS,SAAsB,EACrB,kBAAgC;QADjC,cAAS,GAAT,SAAS,CAAa;QACrB,uBAAkB,GAAlB,kBAA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AAC,CAAC,OAAO,CAAC,UAAU,CAAC,oBAAoB,CAAC,EAAE;YACrD,eAAe,GAAG,IAAI,8BAAkB,CAAC,CAAC,CAAC,CAAC;SAC7C;aAAM,IAAI,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,0BAA0B,CAAC,EAAE;YAC3D,eAAe,GAAG,IAAI,0BAAc,CAAC,CAAC,CAAC,CAAC;SACzC;aAAM,IAAI,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,uBAAuB,CAAC,EAAE;YACtD,eAAe,GAAG,IAAI,8BAAkB,CAAC,CAAC,CAAC,CAAC;SAC7C;aAAM;YACL,eAAe,GAAG,IAAI,8BAAkB,CACtC,CAAC,CAAC,IAAI,EACN,CAAC,CAAC,OAAO,EACT,wBAAY,CAAC,OAAO,CACrB,CAAC;SACH;QACD,OAAO,eAAe,CAAC;IACzB,CAAC;CACF;AAhFD,sDAgFC","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n ApiConnectionError,\n ApiErrorType,\n DisconnectionError,\n LargeResponseError,\n NetworkMetadataPayload,\n RateLimitError,\n TimeoutError,\n IApiConnectionSpecific,\n IBlock,\n} from '@subql/node-core';\nimport { EthereumBlock, LightEthereumBlock } from '@subql/types-ethereum';\nimport { EthereumApi } from './api.ethereum';\nimport SafeEthProvider from './safe-api';\n\nexport type FetchFunc =\n | ((api: EthereumApi, batch: number[]) => Promise<IBlock<EthereumBlock>[]>)\n | ((\n api: EthereumApi,\n batch: number[],\n ) => Promise<IBlock<LightEthereumBlock>[]>);\n\n// We use a function to get the fetch function because it can change depending on the skipBlocks feature\nexport type GetFetchFunc = () => FetchFunc;\n\nexport class EthereumApiConnection\n implements\n IApiConnectionSpecific<\n EthereumApi,\n SafeEthProvider,\n IBlock<EthereumBlock>[] | IBlock<LightEthereumBlock>[]\n >\n{\n readonly networkMeta: NetworkMetadataPayload;\n\n private constructor(\n public unsafeApi: EthereumApi,\n private fetchBlocksBatches: GetFetchFunc,\n ) {\n this.networkMeta = {\n chain: unsafeApi.getChainId().toString(),\n specName: unsafeApi.getSpecName(),\n genesisHash: unsafeApi.getGenesisHash(),\n };\n }\n\n static async create(\n endpoint: string,\n blockConfirmations: number,\n fetchBlocksBatches: GetFetchFunc,\n eventEmitter: EventEmitter2,\n unfinalizedBlocks: boolean,\n ): Promise<EthereumApiConnection> {\n const api = new EthereumApi(\n endpoint,\n blockConfirmations,\n eventEmitter,\n unfinalizedBlocks,\n );\n\n await api.init();\n\n return new EthereumApiConnection(api, fetchBlocksBatches);\n }\n\n safeApi(height: number): SafeEthProvider {\n throw new Error(`Not Implemented`);\n }\n\n async apiConnect(): Promise<void> {\n await this.unsafeApi.connect();\n }\n\n async apiDisconnect(): Promise<void> {\n await this.unsafeApi.disconnect();\n }\n\n async fetchBlocks(\n heights: number[],\n ): Promise<IBlock<EthereumBlock>[] | IBlock<LightEthereumBlock>[]> {\n const blocks = await this.fetchBlocksBatches()(this.unsafeApi, heights);\n return blocks;\n }\n\n handleError = EthereumApiConnection.handleError;\n\n static handleError(e: Error): ApiConnectionError {\n let formatted_error: ApiConnectionError;\n if (e.message.startsWith(`No response received from RPC endpoint in`)) {\n formatted_error = new TimeoutError(e);\n } else if (e.message.startsWith(`disconnected from `)) {\n formatted_error = new DisconnectionError(e);\n } else if (e.message.startsWith(`Rate Limited at endpoint`)) {\n formatted_error = new RateLimitError(e);\n } else if (e.message.includes(`Exceeded max limit of`)) {\n formatted_error = new LargeResponseError(e);\n } else {\n formatted_error = new ApiConnectionError(\n e.name,\n e.message,\n ApiErrorType.Default,\n );\n }\n return formatted_error;\n }\n}\n"]}
@@ -57,6 +57,19 @@ function getHttpAgents() {
57
57
  };
58
58
  }
59
59
  class EthereumApi {
60
+ endpoint;
61
+ blockConfirmations;
62
+ eventEmitter;
63
+ unfinalizedBlocks;
64
+ client;
65
+ // This is used within the sandbox when HTTP is used
66
+ nonBatchClient;
67
+ genesisBlock;
68
+ contractInterfaces = {};
69
+ chainId;
70
+ name;
71
+ // Ethereum POS
72
+ _supportsFinalization = true;
60
73
  get supportsFinalization() {
61
74
  return this._supportsFinalization;
62
75
  }
@@ -70,9 +83,6 @@ class EthereumApi {
70
83
  this.blockConfirmations = blockConfirmations;
71
84
  this.eventEmitter = eventEmitter;
72
85
  this.unfinalizedBlocks = unfinalizedBlocks;
73
- this.contractInterfaces = {};
74
- // Ethereum POS
75
- this._supportsFinalization = true;
76
86
  const { hostname, protocol, searchParams } = new URL(endpoint);
77
87
  const protocolStr = protocol.replace(':', '');
78
88
  logger.info(`Api host: ${hostname}, method: ${protocolStr}`);
@@ -243,7 +253,11 @@ class EthereumApi {
243
253
  });
244
254
  }
245
255
  block.logs = logsRaw.map((l) => (0, utils_ethereum_1.formatLog)(l, block));
246
- block.transactions = block.transactions.map((tx) => (Object.assign(Object.assign({}, (0, utils_ethereum_1.formatTransaction)(tx, block)), { receipt: () => this.getTransactionReceipt(tx.hash).then((r) => (0, utils_ethereum_1.formatReceipt)(r, block)), logs: block.logs.filter((l) => l.transactionHash === tx.hash) })));
256
+ block.transactions = block.transactions.map((tx) => ({
257
+ ...(0, utils_ethereum_1.formatTransaction)(tx, block),
258
+ receipt: () => this.getTransactionReceipt(tx.hash).then((r) => (0, utils_ethereum_1.formatReceipt)(r, block)),
259
+ logs: block.logs.filter((l) => l.transactionHash === tx.hash),
260
+ }));
247
261
  this.eventEmitter.emit('fetchBlock');
248
262
  return (0, utils_ethereum_1.formatBlockUtil)(block);
249
263
  }
@@ -254,7 +268,10 @@ class EthereumApi {
254
268
  async fetchLightBlock(blockNumber) {
255
269
  const block = await this.getBlockPromise(blockNumber, false);
256
270
  const logs = await this.client.getLogs({ blockHash: block.hash });
257
- const lightBlock = Object.assign(Object.assign({}, block), { logs: logs.map((l) => (0, utils_ethereum_1.formatLog)(l, block)) });
271
+ const lightBlock = {
272
+ ...block,
273
+ logs: logs.map((l) => (0, utils_ethereum_1.formatLog)(l, block)),
274
+ };
258
275
  return (0, utils_ethereum_1.formatBlockUtil)(lightBlock);
259
276
  }
260
277
  async fetchBlocks(bufferBlocks) {
@@ -299,14 +316,13 @@ class EthereumApi {
299
316
  return this.contractInterfaces[abiName];
300
317
  }
301
318
  async parseLog(log, ds) {
302
- var _a;
303
319
  try {
304
- if (!((_a = ds === null || ds === void 0 ? void 0 : ds.options) === null || _a === void 0 ? void 0 : _a.abi)) {
320
+ if (!ds?.options?.abi) {
305
321
  logger.warn('No ABI provided for datasource');
306
322
  return log;
307
323
  }
308
324
  const iface = this.buildInterface(ds.options.abi, await loadAssets(ds));
309
- log.args = iface === null || iface === void 0 ? void 0 : iface.parseLog(log).args;
325
+ log.args = iface?.parseLog(log).args;
310
326
  return log;
311
327
  }
312
328
  catch (e) {
@@ -315,9 +331,8 @@ class EthereumApi {
315
331
  }
316
332
  }
317
333
  async parseTransaction(transaction, ds) {
318
- var _a;
319
334
  try {
320
- if (!((_a = ds === null || ds === void 0 ? void 0 : ds.options) === null || _a === void 0 ? void 0 : _a.abi)) {
335
+ if (!ds?.options?.abi) {
321
336
  if (transaction.input !== '0x') {
322
337
  logger.warn('No ABI provided for datasource');
323
338
  }
@@ -352,7 +367,7 @@ class EthereumApi {
352
367
  }
353
368
  }
354
369
  handleError(e) {
355
- if ((e === null || e === void 0 ? void 0 : e.status) === 429) {
370
+ if (e?.status === 429) {
356
371
  const { hostname } = new URL(this.endpoint);
357
372
  return new Error(`Rate Limited at endpoint: ${hostname}`);
358
373
  }
@@ -1 +1 @@
1
- {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;AAEnC,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,4CAA+C;AAM/C,wDAA2E;AAE3E,gDAA8D;AAW9D,wEAA+C;AAC/C,4CAA0D;AAC1D,8CAAkD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020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport fs from 'fs';\nimport http from 'http';\nimport https from 'https';\nimport { Interface } from '@ethersproject/abi';\nimport {\n BlockTag,\n Block,\n TransactionReceipt,\n} from '@ethersproject/abstract-provider';\nimport { WebSocketProvider, BaseProvider } from '@ethersproject/providers';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { getLogger, IBlock, timeout } from '@subql/node-core';\nimport {\n ApiWrapper,\n EthereumBlock,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n SubqlRuntimeDatasource,\n LightEthereumBlock,\n LightEthereumLog,\n} from '@subql/types-ethereum';\nimport CacheableLookup from 'cacheable-lookup';\nimport { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport {\n CeloJsonRpcBatchProvider,\n CeloJsonRpcProvider,\n CeloWsProvider,\n} from './ethers/celo/celo-provider';\nimport { JsonRpcBatchProvider } from './ethers/json-rpc-batch-provider';\nimport { JsonRpcProvider } from './ethers/json-rpc-provider';\nimport { OPFormatterMixin } from './ethers/op/op-provider';\nimport { ConnectionInfo } from './ethers/web';\nimport SafeEthProvider from './safe-api';\nimport {\n formatBlock,\n formatBlockUtil,\n formatLog,\n formatReceipt,\n formatTransaction,\n handleNumber,\n} from './utils.ethereum';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst { version: packageVersion } = require('../../package.json');\n\nconst logger = getLogger('api.ethereum');\n\nasync function loadAssets(\n ds: SubqlRuntimeDatasource,\n): Promise<Record<string, string>> {\n if (!ds.assets) {\n return {};\n }\n const res: Record<string, string> = {};\n\n for (const [name, { file }] of ds.assets.entries()) {\n try {\n res[name] = await fs.promises.readFile(file, { encoding: 'utf8' });\n } catch (e) {\n throw new Error(`Failed to load datasource asset ${file}`);\n }\n }\n\n return res;\n}\n\nfunction getHttpAgents() {\n // By default Nodejs doesn't cache DNS lookups\n // https://httptoolkit.com/blog/configuring-nodejs-dns/\n const lookup = new CacheableLookup();\n\n const options: http.AgentOptions = {\n keepAlive: true,\n /*, maxSockets: 100*/\n };\n\n const httpAgent = new http.Agent(options);\n const httpsAgent = new https.Agent(options);\n\n lookup.install(httpAgent);\n lookup.install(httpsAgent);\n\n return {\n http: httpAgent,\n https: httpsAgent,\n };\n}\n\nexport class EthereumApi implements ApiWrapper {\n private client: JsonRpcProvider;\n\n // This is used within the sandbox when HTTP is used\n private nonBatchClient?: JsonRpcProvider;\n private genesisBlock: Record<string, any>;\n private contractInterfaces: Record<string, Interface> = {};\n private chainId: number;\n private name: string;\n\n // Ethereum POS\n private _supportsFinalization = true;\n\n get supportsFinalization(): boolean {\n return this._supportsFinalization;\n }\n\n /**\n * @param {string} endpoint - The endpoint of the RPC provider\n * @param {number} blockConfirmations - Used to determine how many blocks behind the head a block is considered finalized. Not used if the network has a concrete finalization mechanism.\n * @param {object} eventEmitter - Used to monitor the number of RPC requests\n */\n constructor(\n private endpoint: string,\n private blockConfirmations: number,\n private eventEmitter: EventEmitter2,\n private unfinalizedBlocks = false,\n ) {\n const { hostname, protocol, searchParams } = new URL(endpoint);\n\n const protocolStr = protocol.replace(':', '');\n\n logger.info(`Api host: ${hostname}, method: ${protocolStr}`);\n if (protocolStr === 'https' || protocolStr === 'http') {\n const connection: ConnectionInfo = {\n url: this.endpoint.split('?')[0],\n headers: {\n 'User-Agent': `Subquery-Node ${packageVersion}`,\n },\n allowGzip: true,\n throttleLimit: 5,\n throttleSlotInterval: 1,\n agents: getHttpAgents(),\n };\n searchParams.forEach((value, name, searchParams) => {\n (connection.headers as any)[name] = value;\n });\n this.client = new (OPFormatterMixin(JsonRpcBatchProvider))(connection);\n this.nonBatchClient = new (OPFormatterMixin(JsonRpcProvider))(connection);\n } else if (protocolStr === 'ws' || protocolStr === 'wss') {\n this.client = new (OPFormatterMixin(WebSocketProvider))(this.endpoint);\n } else {\n throw new Error(`Unsupported protocol: ${protocol}`);\n }\n }\n\n async init(): Promise<void> {\n this.injectClient();\n\n const network = await this.client.getNetwork();\n\n //celo\n if (network.chainId === 42220) {\n if (this.client instanceof WebSocketProvider) {\n this.client = new CeloWsProvider(this.client.connection.url);\n } else {\n this.client = new CeloJsonRpcBatchProvider(this.client.connection);\n this.nonBatchClient = new CeloJsonRpcProvider(this.client.connection);\n }\n }\n\n try {\n const [genesisBlock, supportsFinalization, supportsSafe] =\n await Promise.all([\n this.getGenesisBlock(network.chainId),\n this.getSupportsTag('finalized'),\n this.getSupportsTag('safe'),\n ]);\n\n this.genesisBlock = genesisBlock;\n this._supportsFinalization = supportsFinalization && supportsSafe;\n this.chainId = network.chainId;\n this.name = network.name;\n } catch (e) {\n if ((e as Error).message.startsWith('Invalid response')) {\n this.client = this.nonBatchClient;\n\n logger.warn(\n `The RPC Node at ${this.endpoint} cannot process batch requests. ` +\n `Switching to non-batch mode for subsequent requests. Please consider checking if batch processing is supported on the RPC node.`,\n );\n\n return this.init();\n }\n\n throw e;\n }\n }\n\n private async getSupportsTag(tag: BlockTag): Promise<boolean> {\n try {\n // We set the timeout here because there is a bug in ethers where it will never resolve\n // It was happening with arbitrum on a syncing node\n await timeout(this.client.getBlock(tag), 2);\n\n return true;\n } catch (e) {\n logger.info(`Chain doesnt support ${tag} tag`);\n return false;\n }\n }\n\n private injectClient(): void {\n const orig = this.client.send.bind(this.client);\n Object.defineProperty(this.client, 'send', {\n value: (...args) => {\n this.eventEmitter.emit('rpcCall');\n return orig(...args);\n },\n });\n }\n\n private async getGenesisBlock(chainId: number): Promise<Block> {\n const tag = () => {\n switch (chainId) {\n // BEVM Canary\n case 1501:\n return 4157986;\n default:\n return 'earliest';\n }\n };\n\n const block = await this.client.getBlock(tag());\n if (block === null) {\n throw new Error(`Getting genesis block returned null from tag: ${tag()}`);\n }\n return block;\n }\n\n async getFinalizedBlock(): Promise<Block> {\n const height = this.supportsFinalization\n ? 'finalized'\n : (await this.getBestBlockHeight()) - this.blockConfirmations;\n\n const block = await this.client.getBlock(height);\n // The finalized block could sometimes fail to fetch,\n // due to some nodes on the network falling behind the synced node.\n if (!block) {\n throw new Error(`get finalized block \"${height}\" failed `);\n }\n return block;\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.getFinalizedBlock()).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n // Cronos \"safe\" tag doesn't currently work as indended\n const tag =\n !this.unfinalizedBlocks &&\n this.supportsFinalization &&\n this.chainId !== 25\n ? 'safe'\n : 'latest';\n return (await this.client.getBlock(tag)).number;\n }\n\n getRuntimeChain(): string {\n return this.name;\n }\n\n getChainId(): number {\n return this.chainId;\n }\n\n getGenesisHash(): string {\n return this.genesisBlock.hash;\n }\n\n getSpecName(): string {\n return 'ethereum';\n }\n\n async getBlockByHeightOrHash(heightOrHash: number | string): Promise<Block> {\n if (typeof heightOrHash === 'number') {\n heightOrHash = hexValue(heightOrHash);\n }\n return this.client.getBlock(heightOrHash);\n }\n\n private async getBlockPromise(num: number, includeTx = true): Promise<any> {\n const rawBlock = await this.client.send('eth_getBlockByNumber', [\n hexValue(num),\n includeTx,\n ]);\n\n if (!rawBlock) {\n throw new Error(`Failed to fetch block ${num}`);\n }\n\n const block = formatBlock(rawBlock);\n\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n\n return block;\n }\n async getTransactionReceipt(\n transactionHash: string | Promise<string>,\n ): Promise<TransactionReceipt> {\n return retryOnFailEth<TransactionReceipt>(\n this.client.getTransactionReceipt.bind(this.client, transactionHash),\n );\n }\n\n async fetchBlock(blockNumber: number): Promise<IBlock<EthereumBlock>> {\n try {\n const block = await this.getBlockPromise(blockNumber, true);\n const logsRaw = await this.client.getLogs({\n blockHash: block.hash,\n });\n\n // Certain RPC may not accommodate for blockHash, and would return wrong logs\n if (logsRaw.length) {\n logsRaw.forEach((l) => {\n if (l.blockHash.toLowerCase() !== block.hash.toLowerCase()) {\n throw new Error(\n `Log BlockHash does not match block: ${blockNumber}, blockHash ${\n block.hash\n }. Log ${handleNumber(\n l.logIndex,\n ).toNumber()} got block ${handleNumber(\n l.blockNumber,\n ).toNumber()} blockHash ${\n l.blockHash\n }. Please check with rpc provider`,\n );\n }\n });\n }\n\n block.logs = logsRaw.map((l) => formatLog(l, block));\n block.transactions = block.transactions.map((tx) => ({\n ...formatTransaction(tx, block),\n receipt: () =>\n this.getTransactionReceipt(tx.hash).then((r) =>\n formatReceipt(r, block),\n ),\n logs: block.logs.filter((l) => l.transactionHash === tx.hash),\n }));\n\n this.eventEmitter.emit('fetchBlock');\n return formatBlockUtil(block);\n } catch (e) {\n throw this.handleError(e);\n }\n }\n\n private async fetchLightBlock(\n blockNumber: number,\n ): Promise<IBlock<LightEthereumBlock>> {\n const block = await this.getBlockPromise(blockNumber, false);\n const logs = await this.client.getLogs({ blockHash: block.hash });\n\n const lightBlock: LightEthereumBlock = {\n ...block,\n logs: logs.map((l) => formatLog(l, block)),\n };\n return formatBlockUtil<LightEthereumBlock>(lightBlock);\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<IBlock<EthereumBlock>[]> {\n return Promise.all(bufferBlocks.map(async (num) => this.fetchBlock(num)));\n }\n\n async fetchBlocksLight(\n bufferBlocks: number[],\n ): Promise<IBlock<LightEthereumBlock>[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => this.fetchLightBlock(num)),\n );\n }\n\n get api(): BaseProvider {\n return this.client;\n }\n\n getSafeApi(blockHeight: number): SafeEthProvider {\n // We cannot use a batch http client because OnF don't support routing historical queries in batches to an archive nodes\n const client =\n this.client instanceof WebSocketProvider\n ? this.client\n : this.nonBatchClient;\n\n return new SafeEthProvider(client, blockHeight);\n }\n\n private buildInterface(\n abiName: string,\n assets: Record<string, string>,\n ): Interface | undefined {\n if (!assets[abiName]) {\n throw new Error(`ABI named \"${abiName}\" not referenced in assets`);\n }\n\n // This assumes that all datasources have a different abi name or they are the same abi\n if (!this.contractInterfaces[abiName]) {\n // Constructing the interface validates the ABI\n try {\n let abiObj = JSON.parse(assets[abiName]);\n\n /*\n * Allows parsing JSON artifacts as well as ABIs\n * https://trufflesuite.github.io/artifact-updates/background.html#what-are-artifacts\n */\n if (!Array.isArray(abiObj) && abiObj.abi) {\n abiObj = abiObj.abi;\n }\n\n this.contractInterfaces[abiName] = new Interface(abiObj);\n } catch (e) {\n logger.error(`Unable to parse ABI: ${e.message}`);\n throw new Error('ABI is invalid');\n }\n }\n\n return this.contractInterfaces[abiName];\n }\n\n async parseLog<T extends EthereumResult = EthereumResult>(\n log: EthereumLog | LightEthereumLog,\n ds: SubqlRuntimeDatasource,\n ): Promise<\n EthereumLog | LightEthereumLog | EthereumLog<T> | LightEthereumLog<T>\n > {\n try {\n if (!ds?.options?.abi) {\n logger.warn('No ABI provided for datasource');\n return log;\n }\n const iface = this.buildInterface(ds.options.abi, await loadAssets(ds));\n\n log.args = iface?.parseLog(log).args as T;\n\n return log;\n } catch (e) {\n logger.warn(`Failed to parse log data: ${e.message}`);\n return log;\n }\n }\n\n async parseTransaction<T extends EthereumResult = EthereumResult>(\n transaction: EthereumTransaction,\n ds: SubqlRuntimeDatasource,\n ): Promise<EthereumTransaction<T> | EthereumTransaction> {\n try {\n if (!ds?.options?.abi) {\n if (transaction.input !== '0x') {\n logger.warn('No ABI provided for datasource');\n }\n return transaction;\n }\n const assets = await loadAssets(ds);\n const iface = this.buildInterface(ds.options.abi, assets);\n const func = iface.getFunction(hexDataSlice(transaction.input, 0, 4));\n const args = iface.decodeFunctionData(func, transaction.input) as T;\n\n transaction.logs =\n transaction.logs &&\n ((await Promise.all(\n transaction.logs.map(async (log) => this.parseLog(log, ds)),\n )) as Array<EthereumLog | EthereumLog<T>>);\n\n transaction.args = args;\n return transaction;\n } catch (e) {\n logger.warn(`Failed to parse transaction data: ${e.message}`);\n return transaction;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n async connect(): Promise<void> {\n logger.error('Ethereum API connect is not implemented');\n throw new Error('Not implemented');\n }\n\n async disconnect(): Promise<void> {\n if (this.client instanceof WebSocketProvider) {\n await this.client.destroy();\n } else {\n logger.warn('Disconnect called on HTTP provider');\n }\n }\n\n handleError(e: Error): Error {\n if ((e as any)?.status === 429) {\n const { hostname } = new URL(this.endpoint);\n return new Error(`Rate Limited at endpoint: ${hostname}`);\n }\n\n return e;\n }\n}\n"]}
1
+ {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;AAEnC,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,4CAA+C;AAM/C,wDAA2E;AAE3E,gDAA8D;AAW9D,wEAA+C;AAC/C,4CAA0D;AAC1D,8CAAkD;AAClD,+DAIqC;AACrC,8EAAwE;AACxE,kEAA6D;AAC7D,yDAA2D;AAE3D,0DAAyC;AACzC,qDAO0B;AAE1B,8DAA8D;AAC9D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAElE,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,cAAc,CAAC,CAAC;AAEzC,KAAK,UAAU,UAAU,CACvB,EAA0B;IAE1B,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;QACd,OAAO,EAAE,CAAC;KACX;IACD,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE;QAClD,IAAI;YACF,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,YAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;SACpE;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,IAAI,KAAK,CAAC,mCAAmC,IAAI,EAAE,CAAC,CAAC;SAC5D;KACF;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,aAAa;IACpB,8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AE;YAC5C,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;SAC7B;aAAM;YACL,MAAM,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;SACnD;IACH,CAAC;IAED,WAAW,CAAC,CAAQ;QAClB,IAAK,CAAS,EAAE,MAAM,KAAK,GAAG,EAAE;YAC9B,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC5C,OAAO,IAAI,KAAK,CAAC,6BAA6B,QAAQ,EAAE,CAAC,CAAC;SAC3D;QAED,OAAO,CAAC,CAAC;IACX,CAAC;CACF;AApZD,kCAoZC","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport fs from 'fs';\nimport http from 'http';\nimport https from 'https';\nimport { Interface } from '@ethersproject/abi';\nimport {\n BlockTag,\n Block,\n TransactionReceipt,\n} from '@ethersproject/abstract-provider';\nimport { WebSocketProvider, BaseProvider } from '@ethersproject/providers';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { getLogger, IBlock, timeout } from '@subql/node-core';\nimport {\n ApiWrapper,\n EthereumBlock,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n SubqlRuntimeDatasource,\n LightEthereumBlock,\n LightEthereumLog,\n} from '@subql/types-ethereum';\nimport CacheableLookup from 'cacheable-lookup';\nimport { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport {\n CeloJsonRpcBatchProvider,\n CeloJsonRpcProvider,\n CeloWsProvider,\n} from './ethers/celo/celo-provider';\nimport { JsonRpcBatchProvider } from './ethers/json-rpc-batch-provider';\nimport { JsonRpcProvider } from './ethers/json-rpc-provider';\nimport { OPFormatterMixin } from './ethers/op/op-provider';\nimport { ConnectionInfo } from './ethers/web';\nimport SafeEthProvider from './safe-api';\nimport {\n formatBlock,\n formatBlockUtil,\n formatLog,\n formatReceipt,\n formatTransaction,\n handleNumber,\n} from './utils.ethereum';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst { version: packageVersion } = require('../../package.json');\n\nconst logger = getLogger('api.ethereum');\n\nasync function loadAssets(\n ds: SubqlRuntimeDatasource,\n): Promise<Record<string, string>> {\n if (!ds.assets) {\n return {};\n }\n const res: Record<string, string> = {};\n\n for (const [name, { file }] of ds.assets.entries()) {\n try {\n res[name] = await fs.promises.readFile(file, { encoding: 'utf8' });\n } catch (e) {\n throw new Error(`Failed to load datasource asset ${file}`);\n }\n }\n\n return res;\n}\n\nfunction getHttpAgents() {\n // By default Nodejs doesn't cache DNS lookups\n // https://httptoolkit.com/blog/configuring-nodejs-dns/\n const lookup = new CacheableLookup();\n\n const options: http.AgentOptions = {\n keepAlive: true,\n /*, maxSockets: 100*/\n };\n\n const httpAgent = new http.Agent(options);\n const httpsAgent = new https.Agent(options);\n\n lookup.install(httpAgent);\n lookup.install(httpsAgent);\n\n return {\n http: httpAgent,\n https: httpsAgent,\n };\n}\n\nexport class EthereumApi implements ApiWrapper {\n private client: JsonRpcProvider;\n\n // This is used within the sandbox when HTTP is used\n private nonBatchClient?: JsonRpcProvider;\n private genesisBlock: Record<string, any>;\n private contractInterfaces: Record<string, Interface> = {};\n private chainId: number;\n private name: string;\n\n // Ethereum POS\n private _supportsFinalization = true;\n\n get supportsFinalization(): boolean {\n return this._supportsFinalization;\n }\n\n /**\n * @param {string} endpoint - The endpoint of the RPC provider\n * @param {number} blockConfirmations - Used to determine how many blocks behind the head a block is considered finalized. Not used if the network has a concrete finalization mechanism.\n * @param {object} eventEmitter - Used to monitor the number of RPC requests\n */\n constructor(\n private endpoint: string,\n private blockConfirmations: number,\n private eventEmitter: EventEmitter2,\n private unfinalizedBlocks = false,\n ) {\n const { hostname, protocol, searchParams } = new URL(endpoint);\n\n const protocolStr = protocol.replace(':', '');\n\n logger.info(`Api host: ${hostname}, method: ${protocolStr}`);\n if (protocolStr === 'https' || protocolStr === 'http') {\n const connection: ConnectionInfo = {\n url: this.endpoint.split('?')[0],\n headers: {\n 'User-Agent': `Subquery-Node ${packageVersion}`,\n },\n allowGzip: true,\n throttleLimit: 5,\n throttleSlotInterval: 1,\n agents: getHttpAgents(),\n };\n searchParams.forEach((value, name, searchParams) => {\n (connection.headers as any)[name] = value;\n });\n this.client = new (OPFormatterMixin(JsonRpcBatchProvider))(connection);\n this.nonBatchClient = new (OPFormatterMixin(JsonRpcProvider))(connection);\n } else if (protocolStr === 'ws' || protocolStr === 'wss') {\n this.client = new (OPFormatterMixin(WebSocketProvider))(this.endpoint);\n } else {\n throw new Error(`Unsupported protocol: ${protocol}`);\n }\n }\n\n async init(): Promise<void> {\n this.injectClient();\n\n const network = await this.client.getNetwork();\n\n //celo\n if (network.chainId === 42220) {\n if (this.client instanceof WebSocketProvider) {\n this.client = new CeloWsProvider(this.client.connection.url);\n } else {\n this.client = new CeloJsonRpcBatchProvider(this.client.connection);\n this.nonBatchClient = new CeloJsonRpcProvider(this.client.connection);\n }\n }\n\n try {\n const [genesisBlock, supportsFinalization, supportsSafe] =\n await Promise.all([\n this.getGenesisBlock(network.chainId),\n this.getSupportsTag('finalized'),\n this.getSupportsTag('safe'),\n ]);\n\n this.genesisBlock = genesisBlock;\n this._supportsFinalization = supportsFinalization && supportsSafe;\n this.chainId = network.chainId;\n this.name = network.name;\n } catch (e) {\n if ((e as Error).message.startsWith('Invalid response')) {\n this.client = this.nonBatchClient;\n\n logger.warn(\n `The RPC Node at ${this.endpoint} cannot process batch requests. ` +\n `Switching to non-batch mode for subsequent requests. Please consider checking if batch processing is supported on the RPC node.`,\n );\n\n return this.init();\n }\n\n throw e;\n }\n }\n\n private async getSupportsTag(tag: BlockTag): Promise<boolean> {\n try {\n // We set the timeout here because there is a bug in ethers where it will never resolve\n // It was happening with arbitrum on a syncing node\n await timeout(this.client.getBlock(tag), 2);\n\n return true;\n } catch (e) {\n logger.info(`Chain doesnt support ${tag} tag`);\n return false;\n }\n }\n\n private injectClient(): void {\n const orig = this.client.send.bind(this.client);\n Object.defineProperty(this.client, 'send', {\n value: (...args) => {\n this.eventEmitter.emit('rpcCall');\n return orig(...args);\n },\n });\n }\n\n private async getGenesisBlock(chainId: number): Promise<Block> {\n const tag = () => {\n switch (chainId) {\n // BEVM Canary\n case 1501:\n return 4157986;\n default:\n return 'earliest';\n }\n };\n\n const block = await this.client.getBlock(tag());\n if (block === null) {\n throw new Error(`Getting genesis block returned null from tag: ${tag()}`);\n }\n return block;\n }\n\n async getFinalizedBlock(): Promise<Block> {\n const height = this.supportsFinalization\n ? 'finalized'\n : (await this.getBestBlockHeight()) - this.blockConfirmations;\n\n const block = await this.client.getBlock(height);\n // The finalized block could sometimes fail to fetch,\n // due to some nodes on the network falling behind the synced node.\n if (!block) {\n throw new Error(`get finalized block \"${height}\" failed `);\n }\n return block;\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.getFinalizedBlock()).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n // Cronos \"safe\" tag doesn't currently work as indended\n const tag =\n !this.unfinalizedBlocks &&\n this.supportsFinalization &&\n this.chainId !== 25\n ? 'safe'\n : 'latest';\n return (await this.client.getBlock(tag)).number;\n }\n\n getRuntimeChain(): string {\n return this.name;\n }\n\n getChainId(): number {\n return this.chainId;\n }\n\n getGenesisHash(): string {\n return this.genesisBlock.hash;\n }\n\n getSpecName(): string {\n return 'ethereum';\n }\n\n async getBlockByHeightOrHash(heightOrHash: number | string): Promise<Block> {\n if (typeof heightOrHash === 'number') {\n heightOrHash = hexValue(heightOrHash);\n }\n return this.client.getBlock(heightOrHash);\n }\n\n private async getBlockPromise(num: number, includeTx = true): Promise<any> {\n const rawBlock = await this.client.send('eth_getBlockByNumber', [\n hexValue(num),\n includeTx,\n ]);\n\n if (!rawBlock) {\n throw new Error(`Failed to fetch block ${num}`);\n }\n\n const block = formatBlock(rawBlock);\n\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n\n return block;\n }\n async getTransactionReceipt(\n transactionHash: string | Promise<string>,\n ): Promise<TransactionReceipt> {\n return retryOnFailEth<TransactionReceipt>(\n this.client.getTransactionReceipt.bind(this.client, transactionHash),\n );\n }\n\n async fetchBlock(blockNumber: number): Promise<IBlock<EthereumBlock>> {\n try {\n const block = await this.getBlockPromise(blockNumber, true);\n const logsRaw = await this.client.getLogs({\n blockHash: block.hash,\n });\n\n // Certain RPC may not accommodate for blockHash, and would return wrong logs\n if (logsRaw.length) {\n logsRaw.forEach((l) => {\n if (l.blockHash.toLowerCase() !== block.hash.toLowerCase()) {\n throw new Error(\n `Log BlockHash does not match block: ${blockNumber}, blockHash ${\n block.hash\n }. Log ${handleNumber(\n l.logIndex,\n ).toNumber()} got block ${handleNumber(\n l.blockNumber,\n ).toNumber()} blockHash ${\n l.blockHash\n }. Please check with rpc provider`,\n );\n }\n });\n }\n\n block.logs = logsRaw.map((l) => formatLog(l, block));\n block.transactions = block.transactions.map((tx) => ({\n ...formatTransaction(tx, block),\n receipt: () =>\n this.getTransactionReceipt(tx.hash).then((r) =>\n formatReceipt(r, block),\n ),\n logs: block.logs.filter((l) => l.transactionHash === tx.hash),\n }));\n\n this.eventEmitter.emit('fetchBlock');\n return formatBlockUtil(block);\n } catch (e) {\n throw this.handleError(e);\n }\n }\n\n private async fetchLightBlock(\n blockNumber: number,\n ): Promise<IBlock<LightEthereumBlock>> {\n const block = await this.getBlockPromise(blockNumber, false);\n const logs = await this.client.getLogs({ blockHash: block.hash });\n\n const lightBlock: LightEthereumBlock = {\n ...block,\n logs: logs.map((l) => formatLog(l, block)),\n };\n return formatBlockUtil<LightEthereumBlock>(lightBlock);\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<IBlock<EthereumBlock>[]> {\n return Promise.all(bufferBlocks.map(async (num) => this.fetchBlock(num)));\n }\n\n async fetchBlocksLight(\n bufferBlocks: number[],\n ): Promise<IBlock<LightEthereumBlock>[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => this.fetchLightBlock(num)),\n );\n }\n\n get api(): BaseProvider {\n return this.client;\n }\n\n getSafeApi(blockHeight: number): SafeEthProvider {\n // We cannot use a batch http client because OnF don't support routing historical queries in batches to an archive nodes\n const client =\n this.client instanceof WebSocketProvider\n ? this.client\n : this.nonBatchClient;\n\n return new SafeEthProvider(client, blockHeight);\n }\n\n private buildInterface(\n abiName: string,\n assets: Record<string, string>,\n ): Interface | undefined {\n if (!assets[abiName]) {\n throw new Error(`ABI named \"${abiName}\" not referenced in assets`);\n }\n\n // This assumes that all datasources have a different abi name or they are the same abi\n if (!this.contractInterfaces[abiName]) {\n // Constructing the interface validates the ABI\n try {\n let abiObj = JSON.parse(assets[abiName]);\n\n /*\n * Allows parsing JSON artifacts as well as ABIs\n * https://trufflesuite.github.io/artifact-updates/background.html#what-are-artifacts\n */\n if (!Array.isArray(abiObj) && abiObj.abi) {\n abiObj = abiObj.abi;\n }\n\n this.contractInterfaces[abiName] = new Interface(abiObj);\n } catch (e) {\n logger.error(`Unable to parse ABI: ${e.message}`);\n throw new Error('ABI is invalid');\n }\n }\n\n return this.contractInterfaces[abiName];\n }\n\n async parseLog<T extends EthereumResult = EthereumResult>(\n log: EthereumLog | LightEthereumLog,\n ds: SubqlRuntimeDatasource,\n ): Promise<\n EthereumLog | LightEthereumLog | EthereumLog<T> | LightEthereumLog<T>\n > {\n try {\n if (!ds?.options?.abi) {\n logger.warn('No ABI provided for datasource');\n return log;\n }\n const iface = this.buildInterface(ds.options.abi, await loadAssets(ds));\n\n log.args = iface?.parseLog(log).args as T;\n\n return log;\n } catch (e) {\n logger.warn(`Failed to parse log data: ${e.message}`);\n return log;\n }\n }\n\n async parseTransaction<T extends EthereumResult = EthereumResult>(\n transaction: EthereumTransaction,\n ds: SubqlRuntimeDatasource,\n ): Promise<EthereumTransaction<T> | EthereumTransaction> {\n try {\n if (!ds?.options?.abi) {\n if (transaction.input !== '0x') {\n logger.warn('No ABI provided for datasource');\n }\n return transaction;\n }\n const assets = await loadAssets(ds);\n const iface = this.buildInterface(ds.options.abi, assets);\n const func = iface.getFunction(hexDataSlice(transaction.input, 0, 4));\n const args = iface.decodeFunctionData(func, transaction.input) as T;\n\n transaction.logs =\n transaction.logs &&\n ((await Promise.all(\n transaction.logs.map(async (log) => this.parseLog(log, ds)),\n )) as Array<EthereumLog | EthereumLog<T>>);\n\n transaction.args = args;\n return transaction;\n } catch (e) {\n logger.warn(`Failed to parse transaction data: ${e.message}`);\n return transaction;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n async connect(): Promise<void> {\n logger.error('Ethereum API connect is not implemented');\n throw new Error('Not implemented');\n }\n\n async disconnect(): Promise<void> {\n if (this.client instanceof WebSocketProvider) {\n await this.client.destroy();\n } else {\n logger.warn('Disconnect called on HTTP provider');\n }\n }\n\n handleError(e: Error): Error {\n if ((e as any)?.status === 429) {\n const { hostname } = new URL(this.endpoint);\n return new Error(`Rate Limited at endpoint: ${hostname}`);\n }\n\n return e;\n }\n}\n"]}
@@ -24,10 +24,13 @@ const project_1 = require("../utils/project");
24
24
  const api_connection_1 = require("./api.connection");
25
25
  const logger = (0, node_core_1.getLogger)('api');
26
26
  let EthereumApiService = class EthereumApiService extends node_core_1.ApiService {
27
+ project;
28
+ fetchBlocksFunction;
29
+ fetchBlocksBatches = () => this.fetchBlocksFunction;
30
+ nodeConfig;
27
31
  constructor(project, connectionPoolService, eventEmitter, nodeConfig) {
28
32
  super(connectionPoolService, eventEmitter);
29
33
  this.project = project;
30
- this.fetchBlocksBatches = () => this.fetchBlocksFunction;
31
34
  this.nodeConfig = new NodeConfig_1.EthereumNodeConfig(nodeConfig);
32
35
  this.updateBlockFetching();
33
36
  }
@@ -37,8 +40,7 @@ let EthereumApiService = class EthereumApiService extends node_core_1.ApiService
37
40
  network = this.project.network;
38
41
  }
39
42
  catch (e) {
40
- logger.error(Object.keys(e));
41
- process.exit(1);
43
+ (0, node_core_1.exitWithError)(new Error(`Failed to init api`, { cause: Object.keys(e) }), logger);
42
44
  }
43
45
  const endpoints = Array.isArray(network.endpoint)
44
46
  ? network.endpoint
@@ -82,7 +84,7 @@ let EthereumApiService = class EthereumApiService extends node_core_1.ApiService
82
84
  }
83
85
  catch (error) {
84
86
  // other than retryErrorCodes, other errors does not have anything to do with network request, retrying would not change its outcome
85
- if (!retryErrorCodes.includes(error === null || error === void 0 ? void 0 : error.code)) {
87
+ if (!retryErrorCodes.includes(error?.code)) {
86
88
  throw error;
87
89
  }
88
90
  logger.warn(`Request failed with api at height ${height} (retry ${retries}): ${error.message}`);
@@ -107,7 +109,6 @@ let EthereumApiService = class EthereumApiService extends node_core_1.ApiService
107
109
  return api.fetchBlocksLight(batch);
108
110
  }
109
111
  updateBlockFetching() {
110
- var _a;
111
112
  const onlyEventHandlers = (0, project_1.isOnlyEventHandlers)(this.project);
112
113
  const skipTransactions = this.nodeConfig.skipTransactions && onlyEventHandlers;
113
114
  if (this.nodeConfig.skipTransactions) {
@@ -129,7 +130,7 @@ let EthereumApiService = class EthereumApiService extends node_core_1.ApiService
129
130
  const fetchFunc = skipTransactions
130
131
  ? this.fetchLightBlocksBatch.bind(this)
131
132
  : this.fetchFullBlocksBatch.bind(this);
132
- if ((_a = this.nodeConfig) === null || _a === void 0 ? void 0 : _a.profiler) {
133
+ if (this.nodeConfig?.profiler) {
133
134
  this.fetchBlocksFunction = (0, node_core_1.profilerWrap)(fetchFunc, 'SubstrateUtil', 'fetchBlocksBatches');
134
135
  }
135
136
  else {
@@ -1 +1 @@
1
- {"version":3,"file":"api.service.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.service.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;AAEnC,2CAAoD;AACpD,yDAAsD;AACtD,gDAO0B;AAM1B,wDAA6D;AAC7D,kEAA+D;AAC/D,8CAAuD;AACvD,qDAI0B;AAI1B,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,KAAK,CAAC,CAAC;AAGzB,IAAM,kBAAk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qB,CAAC,IAAI,CAAC,IAAI,CAAC;YACvC,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEzC,IAAI,MAAA,IAAI,CAAC,UAAU,0CAAE,QAAQ,EAAE;YAC7B,IAAI,CAAC,mBAAmB,GAAG,IAAA,wBAAY,EACrC,SAAS,EACT,eAAe,EACf,oBAAoB,CACrB,CAAC;SACH;aAAM;YACL,IAAI,CAAC,mBAAmB,GAAG,SAAS,CAAC;SACtC;IACH,CAAC;CACF,CAAA;AA7KY,kBAAkB;IAD9B,IAAA,mBAAU,GAAE;IAWR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAAkB,iCAAe;QACrC,iCAAqB;QAC9B,6BAAa;QACf,sBAAU;GAbb,kBAAkB,CA6K9B;AA7KY,gDAAkB","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Inject, Injectable } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n ApiService,\n ConnectionPoolService,\n getLogger,\n NodeConfig,\n profilerWrap,\n IBlock,\n} from '@subql/node-core';\nimport {\n EthereumBlock,\n EthereumNetworkConfig,\n LightEthereumBlock,\n} from '@subql/types-ethereum';\nimport { EthereumNodeConfig } from '../configure/NodeConfig';\nimport { SubqueryProject } from '../configure/SubqueryProject';\nimport { isOnlyEventHandlers } from '../utils/project';\nimport {\n EthereumApiConnection,\n FetchFunc,\n GetFetchFunc,\n} from './api.connection';\nimport { EthereumApi } from './api.ethereum';\nimport SafeEthProvider from './safe-api';\n\nconst logger = getLogger('api');\n\n@Injectable()\nexport class EthereumApiService extends ApiService<\n EthereumApi,\n SafeEthProvider,\n IBlock<EthereumBlock>[] | IBlock<LightEthereumBlock>[]\n> {\n private fetchBlocksFunction: FetchFunc;\n private fetchBlocksBatches: GetFetchFunc = () => this.fetchBlocksFunction;\n private nodeConfig: EthereumNodeConfig;\n\n constructor(\n @Inject('ISubqueryProject') private project: SubqueryProject,\n connectionPoolService: ConnectionPoolService<EthereumApiConnection>,\n eventEmitter: EventEmitter2,\n nodeConfig: NodeConfig,\n ) {\n super(connectionPoolService, eventEmitter);\n this.nodeConfig = new EthereumNodeConfig(nodeConfig);\n\n this.updateBlockFetching();\n }\n\n async init(): Promise<EthereumApiService> {\n let network: EthereumNetworkConfig;\n try {\n network = this.project.network;\n } catch (e) {\n logger.error(Object.keys(e));\n process.exit(1);\n }\n\n const endpoints = Array.isArray(network.endpoint)\n ? network.endpoint\n : [network.endpoint];\n\n if (this.nodeConfig.primaryNetworkEndpoint) {\n endpoints.push(this.nodeConfig.primaryNetworkEndpoint);\n }\n\n await this.createConnections(network, (endpoint) =>\n EthereumApiConnection.create(\n endpoint,\n this.nodeConfig.blockConfirmations,\n this.fetchBlocksBatches,\n this.eventEmitter,\n this.nodeConfig.unfinalizedBlocks,\n ),\n );\n\n return this;\n }\n\n protected metadataMismatchError(\n metadata: string,\n expected: string,\n actual: string,\n ): Error {\n return Error(\n `Value of ${metadata} does not match across all endpoints. Please check that your endpoints are for the same network.\\n\n Expected: ${expected}\n Actual: ${actual}`,\n );\n }\n\n get api(): EthereumApi {\n return this.unsafeApi;\n }\n\n safeApi(height: number): SafeEthProvider {\n const maxRetries = 5;\n\n const retryErrorCodes = [\n 'UNKNOWN_ERROR',\n 'NOT_IMPLEMENTED',\n 'NETWORK_ERROR',\n 'SERVER_ERROR',\n 'TIMEOUT',\n 'BAD_DATA',\n 'CANCELLED',\n ];\n\n const handler: ProxyHandler<SafeEthProvider> = {\n get: (target, prop, receiver) => {\n const originalMethod = target[prop as keyof SafeEthProvider];\n if (typeof originalMethod === 'function') {\n return async (...args: any[]) => {\n let retries = 0;\n let currentApi = target;\n let throwingError: Error;\n\n while (retries < maxRetries) {\n try {\n return await originalMethod.apply(currentApi, args);\n } catch (error: any) {\n // other than retryErrorCodes, other errors does not have anything to do with network request, retrying would not change its outcome\n if (!retryErrorCodes.includes(error?.code)) {\n throw error;\n }\n\n logger.warn(\n `Request failed with api at height ${height} (retry ${retries}): ${error.message}`,\n );\n throwingError = error;\n currentApi = this.unsafeApi.getSafeApi(height);\n retries++;\n }\n }\n\n logger.error(\n `Maximum retries (${maxRetries}) exceeded for api at height ${height}`,\n );\n throw throwingError;\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n };\n\n return new Proxy(this.unsafeApi.getSafeApi(height), handler);\n }\n\n private async fetchFullBlocksBatch(\n api: EthereumApi,\n batch: number[],\n ): Promise<IBlock<EthereumBlock>[]> {\n return api.fetchBlocks(batch);\n }\n\n private async fetchLightBlocksBatch(\n api: EthereumApi,\n batch: number[],\n ): Promise<IBlock<LightEthereumBlock>[]> {\n return api.fetchBlocksLight(batch);\n }\n\n updateBlockFetching(): void {\n const onlyEventHandlers = isOnlyEventHandlers(this.project);\n const skipTransactions =\n this.nodeConfig.skipTransactions && onlyEventHandlers;\n\n if (this.nodeConfig.skipTransactions) {\n if (onlyEventHandlers) {\n logger.info(\n 'skipTransactions is enabled, only events and block headers will be fetched.',\n );\n } else {\n logger.info(\n `skipTransactions is disabled, the project contains handlers that aren't event handlers.`,\n );\n }\n } else {\n if (onlyEventHandlers) {\n logger.warn(\n 'skipTransactions is disabled, the project contains only event handlers, it could be enabled to improve indexing performance.',\n );\n } else {\n logger.info(`skipTransactions is disabled.`);\n }\n }\n\n const fetchFunc = skipTransactions\n ? this.fetchLightBlocksBatch.bind(this)\n : this.fetchFullBlocksBatch.bind(this);\n\n if (this.nodeConfig?.profiler) {\n this.fetchBlocksFunction = profilerWrap(\n fetchFunc,\n 'SubstrateUtil',\n 'fetchBlocksBatches',\n );\n } else {\n this.fetchBlocksFunction = fetchFunc;\n }\n }\n}\n"]}
1
+ {"version":3,"file":"api.service.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.service.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;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H;SACF;aAAM;YACL,IAAI,iBAAiB,EAAE;gBACrB,MAAM,CAAC,IAAI,CACT,8HAA8H,CAC/H,CAAC;aACH;iBAAM;gBACL,MAAM,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;aAC9C;SACF;QAED,MAAM,SAAS,GAAG,gBAAgB;YAChC,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC;YACvC,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAEzC,IAAI,IAAI,CAAC,UAAU,EAAE,QAAQ,EAAE;YAC7B,IAAI,CAAC,mBAAmB,GAAG,IAAA,wBAAY,EACrC,SAAS,EACT,eAAe,EACf,oBAAoB,CACrB,CAAC;SACH;aAAM;YACL,IAAI,CAAC,mBAAmB,GAAG,SAAS,CAAC;SACtC;IACH,CAAC;CACF,CAAA;AA/KY,kBAAkB;IAD9B,IAAA,mBAAU,GAAE;IAWR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAAkB,iCAAe;QACrC,iCAAqB;QAC9B,6BAAa;QACf,sBAAU;GAbb,kBAAkB,CA+K9B;AA/KY,gDAAkB","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Inject, Injectable } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n ApiService,\n ConnectionPoolService,\n getLogger,\n NodeConfig,\n profilerWrap,\n IBlock,\n exitWithError,\n} from '@subql/node-core';\nimport {\n EthereumBlock,\n EthereumNetworkConfig,\n LightEthereumBlock,\n} from '@subql/types-ethereum';\nimport { EthereumNodeConfig } from '../configure/NodeConfig';\nimport { SubqueryProject } from '../configure/SubqueryProject';\nimport { isOnlyEventHandlers } from '../utils/project';\nimport {\n EthereumApiConnection,\n FetchFunc,\n GetFetchFunc,\n} from './api.connection';\nimport { EthereumApi } from './api.ethereum';\nimport SafeEthProvider from './safe-api';\n\nconst logger = getLogger('api');\n\n@Injectable()\nexport class EthereumApiService extends ApiService<\n EthereumApi,\n SafeEthProvider,\n IBlock<EthereumBlock>[] | IBlock<LightEthereumBlock>[]\n> {\n private fetchBlocksFunction: FetchFunc;\n private fetchBlocksBatches: GetFetchFunc = () => this.fetchBlocksFunction;\n private nodeConfig: EthereumNodeConfig;\n\n constructor(\n @Inject('ISubqueryProject') private project: SubqueryProject,\n connectionPoolService: ConnectionPoolService<EthereumApiConnection>,\n eventEmitter: EventEmitter2,\n nodeConfig: NodeConfig,\n ) {\n super(connectionPoolService, eventEmitter);\n this.nodeConfig = new EthereumNodeConfig(nodeConfig);\n\n this.updateBlockFetching();\n }\n\n async init(): Promise<EthereumApiService> {\n let network: EthereumNetworkConfig;\n try {\n network = this.project.network;\n } catch (e) {\n exitWithError(\n new Error(`Failed to init api`, { cause: Object.keys(e) }),\n logger,\n );\n }\n\n const endpoints = Array.isArray(network.endpoint)\n ? network.endpoint\n : [network.endpoint];\n\n if (this.nodeConfig.primaryNetworkEndpoint) {\n endpoints.push(this.nodeConfig.primaryNetworkEndpoint);\n }\n\n await this.createConnections(network, (endpoint) =>\n EthereumApiConnection.create(\n endpoint,\n this.nodeConfig.blockConfirmations,\n this.fetchBlocksBatches,\n this.eventEmitter,\n this.nodeConfig.unfinalizedBlocks,\n ),\n );\n\n return this;\n }\n\n protected metadataMismatchError(\n metadata: string,\n expected: string,\n actual: string,\n ): Error {\n return Error(\n `Value of ${metadata} does not match across all endpoints. Please check that your endpoints are for the same network.\\n\n Expected: ${expected}\n Actual: ${actual}`,\n );\n }\n\n get api(): EthereumApi {\n return this.unsafeApi;\n }\n\n safeApi(height: number): SafeEthProvider {\n const maxRetries = 5;\n\n const retryErrorCodes = [\n 'UNKNOWN_ERROR',\n 'NOT_IMPLEMENTED',\n 'NETWORK_ERROR',\n 'SERVER_ERROR',\n 'TIMEOUT',\n 'BAD_DATA',\n 'CANCELLED',\n ];\n\n const handler: ProxyHandler<SafeEthProvider> = {\n get: (target, prop, receiver) => {\n const originalMethod = target[prop as keyof SafeEthProvider];\n if (typeof originalMethod === 'function') {\n return async (...args: any[]) => {\n let retries = 0;\n let currentApi = target;\n let throwingError: Error;\n\n while (retries < maxRetries) {\n try {\n return await originalMethod.apply(currentApi, args);\n } catch (error: any) {\n // other than retryErrorCodes, other errors does not have anything to do with network request, retrying would not change its outcome\n if (!retryErrorCodes.includes(error?.code)) {\n throw error;\n }\n\n logger.warn(\n `Request failed with api at height ${height} (retry ${retries}): ${error.message}`,\n );\n throwingError = error;\n currentApi = this.unsafeApi.getSafeApi(height);\n retries++;\n }\n }\n\n logger.error(\n `Maximum retries (${maxRetries}) exceeded for api at height ${height}`,\n );\n throw throwingError;\n };\n }\n return Reflect.get(target, prop, receiver);\n },\n };\n\n return new Proxy(this.unsafeApi.getSafeApi(height), handler);\n }\n\n private async fetchFullBlocksBatch(\n api: EthereumApi,\n batch: number[],\n ): Promise<IBlock<EthereumBlock>[]> {\n return api.fetchBlocks(batch);\n }\n\n private async fetchLightBlocksBatch(\n api: EthereumApi,\n batch: number[],\n ): Promise<IBlock<LightEthereumBlock>[]> {\n return api.fetchBlocksLight(batch);\n }\n\n updateBlockFetching(): void {\n const onlyEventHandlers = isOnlyEventHandlers(this.project);\n const skipTransactions =\n this.nodeConfig.skipTransactions && onlyEventHandlers;\n\n if (this.nodeConfig.skipTransactions) {\n if (onlyEventHandlers) {\n logger.info(\n 'skipTransactions is enabled, only events and block headers will be fetched.',\n );\n } else {\n logger.info(\n `skipTransactions is disabled, the project contains handlers that aren't event handlers.`,\n );\n }\n } else {\n if (onlyEventHandlers) {\n logger.warn(\n 'skipTransactions is disabled, the project contains only event handlers, it could be enabled to improve indexing performance.',\n );\n } else {\n logger.info(`skipTransactions is disabled.`);\n }\n }\n\n const fetchFunc = skipTransactions\n ? this.fetchLightBlocksBatch.bind(this)\n : this.fetchFullBlocksBatch.bind(this);\n\n if (this.nodeConfig?.profiler) {\n this.fetchBlocksFunction = profilerWrap(\n fetchFunc,\n 'SubstrateUtil',\n 'fetchBlocksBatches',\n );\n } else {\n this.fetchBlocksFunction = fetchFunc;\n }\n }\n}\n"]}
@@ -56,7 +56,7 @@ describe('ApiService', () => {
56
56
  [apiService, app] = await prepareApiService();
57
57
  });
58
58
  afterEach(async () => {
59
- return app === null || app === void 0 ? void 0 : app.close();
59
+ return app?.close();
60
60
  });
61
61
  it('can instantiate api', () => {
62
62
  expect(apiService.api.getChainId()).toEqual(1);
@@ -1 +1 @@
1
- {"version":3,"file":"api.service.ethereum.test.js","sourceRoot":"","sources":["../../src/ethereum/api.service.ethereum.test.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;AAGnC,yDAA2D;AAC3D,6CAAuC;AACvC,gDAI0B;AAC1B,qCAAwC;AACxC,mCAA+B;AAE/B,iEAA4D;AAE5D,sBAAsB;AACtB,MAAM,WAAW,GAAG,wCAAwC,CAAC;AAC7D,gEAAgE;AAChE,MAAM,aAAa,GAAG,0BAA0B,CAAC;AAEjD,SAAS,mBAAmB,CAAC,QAAgB;IAC3C,OAAO;QACL,OAAO,EAAE;YACP,QAAQ,EAAE,CAAC,QAAQ,CAAC;YACpB,OAAO,EAAE,GAAG;SACb;QACD,WAAW,EAAE,EAAE;QACf,EAAE,EAAE,MAAM;QACV,IAAI,EAAE,IAAI;QACV,MAAM,EAAE,IAAI,uBAAa,CAAC,EAAE,CAAC;QAC7B,SAAS,EAAE,EAAE;KACP,CAAC;AACX,CAAC;AAED,MAAM,iBAAiB,GAAG,KAAK,EAC7B,WAAmB,aAAa,EACiB,EAAE;IACnD,MAAM,MAAM,GAAG,MAAM,cAAI,CAAC,mBAAmB,CAAC;QAC5C,SAAS,EAAE;YACT,iCAAqB;YACrB,sCAA0B;YAC1B;gBACE,OAAO,EAAE,sBAAU;gBACnB,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC;aACvB;YACD;gBACE,OAAO,EA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CAAC,CAAC,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,8BAA8B,EAAE,KAAK,IAAI,EAAE;QAC5C,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,GAAG,CAAC,uBAAuB,EAAE,CAAC;QAE9D,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC;QACxC,MAAM,CAAC,MAAM,CAAC,CAAC,eAAe,CAAC,QAAU,CAAC,CAAC;IAC7C,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,+CAA+C,EAAE,KAAK,IAAI,EAAE;QAC7D,MAAM,MAAM,CACV,UAAU;aACP,OAAO,CAAC,QAAQ,CAAC;aACjB,OAAO,CAAC,2CAA2C,CAAC,CACxD,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;IACH,EAAE,CAAC,sDAAsD,EAAE,KAAK,IAAI,EAAE;QACpE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;QAC/D,MAAM,MAAM,CACV,UAAU;aACP,OAAO,CAAC,QAAQ,CAAC;aACjB,OAAO,CAAC,2CAA2C,CAAC,CACxD,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;QAErD,MAAM,CAAC,OAAO,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { INestApplication } from '@nestjs/common';\nimport { EventEmitterModule } from '@nestjs/event-emitter';\nimport { Test } from '@nestjs/testing';\nimport {\n ConnectionPoolService,\n ConnectionPoolStateManager,\n NodeConfig,\n} from '@subql/node-core';\nimport { GraphQLSchema } from 'graphql';\nimport { range } from 'lodash';\nimport { SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApiService } from './api.service.ethereum';\n\n// Add api key to work\nconst WS_ENDPOINT = 'wss://eth.api.onfinality.io/ws?apikey=';\n// const HTTP_ENDPOINT = 'https://eth.api.onfinality.io/public';\nconst HTTP_ENDPOINT = 'https://eth.llamarpc.com';\n\nfunction testSubqueryProject(endpoint: string): SubqueryProject {\n return {\n network: {\n endpoint: [endpoint],\n chainId: '1',\n },\n dataSources: [],\n id: 'test',\n root: './',\n schema: new GraphQLSchema({}),\n templates: [],\n } as any;\n}\n\nconst prepareApiService = async (\n endpoint: string = HTTP_ENDPOINT,\n): Promise<[EthereumApiService, INestApplication]> => {\n const module = await Test.createTestingModule({\n providers: [\n ConnectionPoolService,\n ConnectionPoolStateManager,\n {\n provide: NodeConfig,\n useFactory: () => ({}),\n },\n {\n provide: 'ISubqueryProject',\n useFactory: () => testSubqueryProject(endpoint),\n },\n EthereumApiService,\n ],\n imports: [EventEmitterModule.forRoot()],\n }).compile();\n\n const app = module.createNestApplication();\n await app.init();\n const apiService = app.get(EthereumApiService);\n await apiService.init();\n return [apiService, app];\n};\n\njest.setTimeout(90000);\ndescribe('ApiService', () => {\n let apiService: EthereumApiService;\n let app: INestApplication;\n\n beforeEach(async () => {\n [apiService, app] = await prepareApiService();\n });\n\n afterEach(async () => {\n return app?.close();\n });\n\n it('can instantiate api', () => {\n expect(apiService.api.getChainId()).toEqual(1);\n });\n\n it('can fetch blocks', async () => {\n await expect(\n apiService.api.fetchBlocks(range(12369621, 12369625)),\n ).resolves.toHaveLength(4);\n });\n\n it('can get the finalized height', async () => {\n const height = await apiService.api.getFinalizedBlockHeight();\n\n console.log('Finalized height', height);\n expect(height).toBeGreaterThan(16_000_000);\n });\n\n it('ensure api errorCode is exposed when throwing', async () => {\n await expect(\n apiService\n .safeApi(17520376)\n .getCode('0x75F0398549C9fDEa03BbDde388361827cb376D5'),\n ).rejects.toHaveProperty('code', 'INVALID_ARGUMENT');\n });\n it('should not retry on any errors not in the retry list', async () => {\n const callSpy = jest.spyOn(apiService.unsafeApi, 'getSafeApi');\n await expect(\n apiService\n .safeApi(17520376)\n .getCode('0x75F0398549C9fDEa03BbDde388361827cb376D5'),\n ).rejects.toHaveProperty('code', 'INVALID_ARGUMENT');\n\n expect(callSpy).toHaveBeenCalledTimes(1);\n });\n});\n"]}
1
+ {"version":3,"file":"api.service.ethereum.test.js","sourceRoot":"","sources":["../../src/ethereum/api.service.ethereum.test.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;AAGnC,yDAA2D;AAC3D,6CAAuC;AACvC,gDAI0B;AAC1B,qCAAwC;AACxC,mCAA+B;AAE/B,iEAA4D;AAE5D,sBAAsB;AACtB,MAAM,WAAW,GAAG,wCAAwC,CAAC;AAC7D,gEAAgE;AAChE,MAAM,aAAa,GAAG,0BAA0B,CAAC;AAEjD,SAAS,mBAAmB,CAAC,QAAgB;IAC3C,OAAO;QACL,OAAO,EAAE;YACP,QAAQ,EAAE,CAAC,QAAQ,CAAC;YACpB,OAAO,EAAE,GAAG;SACb;QACD,WAAW,EAAE,EAAE;QACf,EAAE,EAAE,MAAM;QACV,IAAI,EAAE,IAAI;QACV,MAAM,EAAE,IAAI,uBAAa,CAAC,EAAE,CAAC;QAC7B,SAAS,EAAE,EAAE;KACP,CAAC;AACX,CAAC;AAED,MAAM,iBAAiB,GAAG,KAAK,EAC7B,WAAmB,aAAa,EACiB,EAAE;IACnD,MAAM,MAAM,GAAG,MAAM,cAAI,CAAC,mBAAmB,CAAC;QAC5C,SAAS,EAAE;YACT,iCAAqB;YACrB,sCAA0B;YAC1B;gBACE,OAAO,EAAE,sBAAU;gBACnB,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC;aACvB;YACD;gBACE,OAAO,EAAE,kBAAkB;gBAC3B,UAAU,EAAE,GAAG,EAAE,CAAC,mBAAmB,CAAC,QAAQ,CAAC;aAChD;YACD,yCAAkB;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G,MAAM,UAAU,CAAC,GAAG,CAAC,uBAAuB,EAAE,CAAC;QAE9D,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,MAAM,CAAC,CAAC;QACxC,MAAM,CAAC,MAAM,CAAC,CAAC,eAAe,CAAC,QAAU,CAAC,CAAC;IAC7C,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,+CAA+C,EAAE,KAAK,IAAI,EAAE;QAC7D,MAAM,MAAM,CACV,UAAU;aACP,OAAO,CAAC,QAAQ,CAAC;aACjB,OAAO,CAAC,2CAA2C,CAAC,CACxD,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;IACvD,CAAC,CAAC,CAAC;IACH,EAAE,CAAC,sDAAsD,EAAE,KAAK,IAAI,EAAE;QACpE,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,SAAS,EAAE,YAAY,CAAC,CAAC;QAC/D,MAAM,MAAM,CACV,UAAU;aACP,OAAO,CAAC,QAAQ,CAAC;aACjB,OAAO,CAAC,2CAA2C,CAAC,CACxD,CAAC,OAAO,CAAC,cAAc,CAAC,MAAM,EAAE,kBAAkB,CAAC,CAAC;QAErD,MAAM,CAAC,OAAO,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC;IAC3C,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["// Copyright 2020-2024 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { INestApplication } from '@nestjs/common';\nimport { EventEmitterModule } from '@nestjs/event-emitter';\nimport { Test } from '@nestjs/testing';\nimport {\n ConnectionPoolService,\n ConnectionPoolStateManager,\n NodeConfig,\n} from '@subql/node-core';\nimport { GraphQLSchema } from 'graphql';\nimport { range } from 'lodash';\nimport { SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApiService } from './api.service.ethereum';\n\n// Add api key to work\nconst WS_ENDPOINT = 'wss://eth.api.onfinality.io/ws?apikey=';\n// const HTTP_ENDPOINT = 'https://eth.api.onfinality.io/public';\nconst HTTP_ENDPOINT = 'https://eth.llamarpc.com';\n\nfunction testSubqueryProject(endpoint: string): SubqueryProject {\n return {\n network: {\n endpoint: [endpoint],\n chainId: '1',\n },\n dataSources: [],\n id: 'test',\n root: './',\n schema: new GraphQLSchema({}),\n templates: [],\n } as any;\n}\n\nconst prepareApiService = async (\n endpoint: string = HTTP_ENDPOINT,\n): Promise<[EthereumApiService, INestApplication]> => {\n const module = await Test.createTestingModule({\n providers: [\n ConnectionPoolService,\n ConnectionPoolStateManager,\n {\n provide: NodeConfig,\n useFactory: () => ({}),\n },\n {\n provide: 'ISubqueryProject',\n useFactory: () => testSubqueryProject(endpoint),\n },\n EthereumApiService,\n ],\n imports: [EventEmitterModule.forRoot()],\n }).compile();\n\n const app = module.createNestApplication();\n await app.init();\n const apiService = app.get(EthereumApiService);\n await apiService.init();\n return [apiService, app];\n};\n\njest.setTimeout(90000);\ndescribe('ApiService', () => {\n let apiService: EthereumApiService;\n let app: INestApplication;\n\n beforeEach(async () => {\n [apiService, app] = await prepareApiService();\n });\n\n afterEach(async () => {\n return app?.close();\n });\n\n it('can instantiate api', () => {\n expect(apiService.api.getChainId()).toEqual(1);\n });\n\n it('can fetch blocks', async () => {\n await expect(\n apiService.api.fetchBlocks(range(12369621, 12369625)),\n ).resolves.toHaveLength(4);\n });\n\n it('can get the finalized height', async () => {\n const height = await apiService.api.getFinalizedBlockHeight();\n\n console.log('Finalized height', height);\n expect(height).toBeGreaterThan(16_000_000);\n });\n\n it('ensure api errorCode is exposed when throwing', async () => {\n await expect(\n apiService\n .safeApi(17520376)\n .getCode('0x75F0398549C9fDEa03BbDde388361827cb376D5'),\n ).rejects.toHaveProperty('code', 'INVALID_ARGUMENT');\n });\n it('should not retry on any errors not in the retry list', async () => {\n const callSpy = jest.spyOn(apiService.unsafeApi, 'getSafeApi');\n await expect(\n apiService\n .safeApi(17520376)\n .getCode('0x75F0398549C9fDEa03BbDde388361827cb376D5'),\n ).rejects.toHaveProperty('code', 'INVALID_ARGUMENT');\n\n expect(callSpy).toHaveBeenCalledTimes(1);\n });\n});\n"]}
@@ -7,7 +7,7 @@ const node_core_1 = require("@subql/node-core");
7
7
  const string_1 = require("../utils/string");
8
8
  const logger = (0, node_core_1.getLogger)('block.ethereum');
9
9
  function filterBlocksProcessor(block, filter, address) {
10
- if ((filter === null || filter === void 0 ? void 0 : filter.modulo) && block.number % filter.modulo !== 0) {
10
+ if (filter?.modulo && block.number % filter.modulo !== 0) {
11
11
  return false;
12
12
  }
13
13
  // Multiply to add MS