@eclesia/indexer-engine 2.7.6 → 2.8.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 (72) hide show
  1. package/dist/_virtual/rolldown_runtime.cjs +34 -0
  2. package/dist/_virtual/rolldown_runtime.js +13 -0
  3. package/dist/emitter/index.cjs +57 -0
  4. package/dist/emitter/index.cjs.map +1 -0
  5. package/dist/emitter/index.d.cts +21 -0
  6. package/dist/emitter/index.d.cts.map +1 -0
  7. package/dist/emitter/index.d.ts +19 -15
  8. package/dist/emitter/index.d.ts.map +1 -1
  9. package/dist/emitter/index.js +55 -67
  10. package/dist/emitter/index.js.map +1 -0
  11. package/dist/index.cjs +23 -0
  12. package/dist/index.d.cts +6 -0
  13. package/dist/index.d.ts +6 -6
  14. package/dist/index.js +7 -7
  15. package/dist/indexer/index.cjs +570 -0
  16. package/dist/indexer/index.cjs.map +1 -0
  17. package/dist/indexer/index.d.cts +54 -0
  18. package/dist/indexer/index.d.cts.map +1 -0
  19. package/dist/indexer/index.d.ts +50 -46
  20. package/dist/indexer/index.d.ts.map +1 -1
  21. package/dist/indexer/index.js +551 -717
  22. package/dist/indexer/index.js.map +1 -0
  23. package/dist/promise-queue/index.cjs +140 -0
  24. package/dist/promise-queue/index.cjs.map +1 -0
  25. package/dist/promise-queue/index.d.cts +39 -0
  26. package/dist/promise-queue/index.d.cts.map +1 -0
  27. package/dist/promise-queue/index.d.ts +36 -33
  28. package/dist/promise-queue/index.d.ts.map +1 -1
  29. package/dist/promise-queue/index.js +138 -167
  30. package/dist/promise-queue/index.js.map +1 -0
  31. package/dist/types/index.cjs +12 -0
  32. package/dist/types/index.cjs.map +1 -0
  33. package/dist/types/index.d.cts +102 -0
  34. package/dist/types/index.d.cts.map +1 -0
  35. package/dist/types/index.d.ts +88 -83
  36. package/dist/types/index.d.ts.map +1 -1
  37. package/dist/types/index.js +6 -1
  38. package/dist/types/index.js.map +1 -0
  39. package/dist/utils/bech32.cjs +27 -0
  40. package/dist/utils/bech32.cjs.map +1 -0
  41. package/dist/utils/bech32.d.cts +7 -0
  42. package/dist/utils/bech32.d.cts.map +1 -0
  43. package/dist/utils/bech32.d.ts +3 -1
  44. package/dist/utils/bech32.d.ts.map +1 -1
  45. package/dist/utils/bech32.js +17 -17
  46. package/dist/utils/bech32.js.map +1 -0
  47. package/dist/utils/bigint.cjs +9 -0
  48. package/dist/utils/bigint.cjs.map +1 -0
  49. package/dist/utils/bigint.d.cts +5 -0
  50. package/dist/utils/bigint.d.cts.map +1 -0
  51. package/dist/utils/bigint.d.ts +3 -1
  52. package/dist/utils/bigint.d.ts.map +1 -1
  53. package/dist/utils/bigint.js +6 -2
  54. package/dist/utils/bigint.js.map +1 -0
  55. package/dist/utils/index.cjs +22 -0
  56. package/dist/utils/index.cjs.map +1 -0
  57. package/dist/utils/index.d.cts +11 -0
  58. package/dist/utils/index.d.cts.map +1 -0
  59. package/dist/utils/index.d.ts +10 -3
  60. package/dist/utils/index.d.ts.map +1 -1
  61. package/dist/utils/index.js +17 -3
  62. package/dist/utils/index.js.map +1 -0
  63. package/dist/utils/text.cjs +11 -0
  64. package/dist/utils/text.cjs.map +1 -0
  65. package/dist/utils/text.d.cts +5 -0
  66. package/dist/utils/text.d.cts.map +1 -0
  67. package/dist/utils/text.d.ts +4 -1
  68. package/dist/utils/text.d.ts.map +1 -1
  69. package/dist/utils/text.js +9 -10
  70. package/dist/utils/text.js.map +1 -0
  71. package/package.json +25 -5
  72. package/dist/index.d.ts.map +0 -1
@@ -1,719 +1,553 @@
1
- /* eslint-disable max-lines */
2
- import { createHash, } from "node:crypto";
3
- import fs from "node:fs";
4
- import { toRfc3339WithNanoseconds, } from "@cosmjs/tendermint-rpc";
5
- import { connectComet, } from "@cosmjs/tendermint-rpc";
6
- import { MsgExec, } from "cosmjs-types/cosmos/authz/v1beta1/tx";
7
- import { QueryValidatorsRequest, QueryValidatorsResponse, } from "cosmjs-types/cosmos/staking/v1beta1/query";
8
- import { Tx, } from "cosmjs-types/cosmos/tx/v1beta1/tx";
1
+ import { EclesiaEmitter } from "../emitter/index.js";
2
+ import { CircularBuffer } from "../promise-queue/index.js";
3
+ import { decodeAttr } from "../utils/text.js";
4
+ import "../utils/index.js";
5
+ import { createHash } from "node:crypto";
6
+ import * as fs from "node:fs";
7
+ import { connectComet, toRfc3339WithNanoseconds } from "@cosmjs/tendermint-rpc";
8
+ import { MsgExec } from "cosmjs-types/cosmos/authz/v1beta1/tx.js";
9
+ import { QueryValidatorsRequest, QueryValidatorsResponse } from "cosmjs-types/cosmos/staking/v1beta1/query.js";
10
+ import { Tx } from "cosmjs-types/cosmos/tx/v1beta1/tx.js";
9
11
  import Fastify from "fastify";
10
- import { chain, } from "stream-chain";
11
- import { parser, } from "stream-json";
12
- import { pick, } from "stream-json/filters/Pick";
13
- import { streamArray, } from "stream-json/streamers/StreamArray";
14
- import { streamValues, } from "stream-json/streamers/StreamValues";
15
- import { batch, } from "stream-json/utils/Batch";
16
- import { v4 as uuidv4, } from "uuid";
17
- import winston from "winston";
18
- import { EclesiaEmitter, } from "../emitter";
19
- import { CircularBuffer, } from "../promise-queue";
20
- import { decodeAttr, } from "../utils";
21
- export const defaultIndexerConfig = {
22
- startHeight: 1,
23
- batchSize: 500,
24
- modules: [],
25
- getNextHeight: () => 1,
26
- logLevel: "info",
27
- usePolling: false,
28
- pollingInterval: 5000,
29
- processGenesis: false,
30
- minimal: true,
31
- init: () => Promise.resolve(),
32
- beginTransaction: () => Promise.resolve(),
33
- endTransaction: (_status) => Promise.resolve(),
12
+ import { chain } from "stream-chain";
13
+ import * as Parser from "stream-json";
14
+ import * as Pick from "stream-json/filters/Pick.js";
15
+ import * as StreamArray from "stream-json/streamers/StreamArray.js";
16
+ import * as StreamValues from "stream-json/streamers/StreamValues.js";
17
+ import * as Batch from "stream-json/utils/Batch.js";
18
+ import { v4 } from "uuid";
19
+ import * as winston from "winston";
20
+
21
+ //#region src/indexer/index.ts
22
+ const defaultIndexerConfig = {
23
+ startHeight: 1,
24
+ batchSize: 500,
25
+ modules: [],
26
+ getNextHeight: () => 1,
27
+ logLevel: "info",
28
+ usePolling: false,
29
+ pollingInterval: 5e3,
30
+ processGenesis: false,
31
+ minimal: true,
32
+ init: () => Promise.resolve(),
33
+ beginTransaction: () => Promise.resolve(),
34
+ endTransaction: (_status) => Promise.resolve()
34
35
  };
35
- export class EcleciaIndexer extends EclesiaEmitter {
36
- constructor(config) {
37
- super();
38
- this.initialized = false;
39
- this.retryCount = 0;
40
- this.tryToRecover = false;
41
- this.healthCheck = {
42
- status: "CONNECTING",
43
- };
44
- this.subscription = null;
45
- this.blockListener = {
46
- next: (data) => {
47
- this.newBlockReceived(data.header.height);
48
- },
49
- };
50
- this.asyncEmit = async (type, event) => {
51
- event.uuid = uuidv4();
52
- /*
53
- * More than 1 listener can be registered for an event type
54
- * Fortunately these are all set up during module init() so we have a consistent count
55
- * so we can count responses to resolve when complete
56
- * values are irrelevant as promise resolution is only used for flow control
57
- */
58
- let listenerCount = this.handled.get(type);
59
- if (!listenerCount) {
60
- // Setting listenerCount to 1 (the unhandled listener)
61
- listenerCount = 1;
62
- }
63
- let listenersResponded = 0;
64
- const prom = new Promise((resolve, reject) => {
65
- const returnFunc = (ev) => {
66
- if (ev.uuid == event.uuid) {
67
- if (ev.status) {
68
- listenersResponded++;
69
- if (listenersResponded == listenerCount) {
70
- // All listeners have done their thing so we can remove listener, resolve and continue execution
71
- this.off("uuid", returnFunc);
72
- resolve();
73
- }
74
- }
75
- else {
76
- // At least 1 listener is reporting an error. Reject and handle exception at the original asyncEmit location
77
- reject(ev.error);
78
- }
79
- }
80
- };
81
- this.on("uuid", returnFunc);
82
- });
83
- this.emit(type, event);
84
- return prom;
85
- };
86
- this.config = {
87
- ...defaultIndexerConfig,
88
- ...config,
89
- };
90
- if (this.config.minimal) {
91
- this.blockQueue = new CircularBuffer(this.config.batchSize);
92
- }
93
- else {
94
- this.blockQueue = new CircularBuffer(this.config.batchSize);
95
- }
96
- const { printf, } = winston.format;
97
- const eclesiaFormat = printf(({ level, message, timestamp, }) => {
98
- return `${timestamp} [${level.toUpperCase()}]:\t${message}`;
99
- });
100
- this.log = winston.createLogger({
101
- level: this.config.logLevel,
102
- defaultMeta: {
103
- service: "Eclesia Indexer",
104
- },
105
- transports: [
106
- new winston.transports.File({
107
- filename: "error.log",
108
- level: "error",
109
- }),
110
- new winston.transports.File({
111
- filename: "combined.log",
112
- }),
113
- new winston.transports.Console({
114
- format: winston.format.combine(winston.format.splat(), winston.format.timestamp(), eclesiaFormat, winston.format.colorize({
115
- all: true,
116
- })),
117
- }),
118
- ],
119
- });
120
- this.fastify = Fastify({
121
- logger: false,
122
- });
123
- this.on("_unhandled", (msg) => {
124
- if (msg.uuid) {
125
- this.log.verbose("Unhandled event: " + msg.type);
126
- this.emit("uuid", {
127
- status: true,
128
- uuid: msg.uuid,
129
- });
130
- }
131
- });
132
- this.fastify.get("/health", async (_request, reply) => {
133
- const code = this.healthCheck.status == "OK"
134
- ? 200
135
- : 503;
136
- reply.code(code).send(this.healthCheck);
137
- });
138
- this.fastify.listen({
139
- port: 80,
140
- host: "0.0.0.0",
141
- }, (err) => {
142
- if (err) {
143
- this.log.error(err);
144
- process.exit(1);
145
- }
146
- });
147
- }
148
- setStatus(status) {
149
- this.healthCheck.status = status;
150
- }
151
- isMinimal(_blockqueue) {
152
- if (this.config.minimal) {
153
- return true;
154
- }
155
- else {
156
- return false;
157
- }
158
- }
159
- async connect() {
160
- try {
161
- if (this.client && this.tryToRecover) {
162
- this.log.verbose("Recover from error. Attempting to disconnect from RPC");
163
- this.client.disconnect();
164
- this.blockClient.disconnect();
165
- this.log.verbose("Disconnected from RPC");
166
- }
167
- this.client = await connectComet(this.config.rpcUrl);
168
- this.log.info("Connected to RPC for ad hoc queries");
169
- this.blockClient = await connectComet(this.config.rpcUrl);
170
- this.log.info("Connected to RPC for block & validator info");
171
- return true;
172
- }
173
- catch (error) {
174
- this.log.error(error);
175
- this.tryToRecover = true;
176
- return false;
177
- }
178
- }
179
- async start() {
180
- if (this.blockQueue) {
181
- this.blockQueue.clear();
182
- this.log.verbose("Starting, clearing block queue");
183
- }
184
- if (!this.initialized) {
185
- try {
186
- if (this.config.init) {
187
- await this.config.init();
188
- }
189
- }
190
- catch (e) {
191
- this.log.error("Failed to initialize indexer: " + e);
192
- this.setStatus("FAILED");
193
- throw e;
194
- }
195
- if (this.config.processGenesis) {
196
- try {
197
- if (this.config.genesisPath) {
198
- await this.parseGenesis();
199
- }
200
- }
201
- catch (e) {
202
- this.log.error("Failed to parse genesis: " + e);
203
- this.setStatus("FAILED");
204
- throw e;
205
- }
206
- }
207
- this.initialized = true;
208
- }
209
- try {
210
- await this.connect();
211
- if (!this.config.usePolling && this.subscription) {
212
- this.subscription.removeListener(this.blockListener);
213
- this.subscription = null;
214
- this.log.verbose("Removed existing block listener and subscription");
215
- }
216
- this.subscription = this.client.subscribeNewBlock
217
- ? this.client.subscribeNewBlock()
218
- : null;
219
- const status = await this.client.status();
220
- this.latestHeight = status.syncInfo.latestBlockHeight;
221
- this.log.info("Current chain height: " + this.latestHeight);
222
- this.heightToProcess = await this.config.getNextHeight();
223
- if (this.config.usePolling) {
224
- this.pollForBlock();
225
- }
226
- else {
227
- if (this.subscription) {
228
- this.subscription.addListener(this.blockListener);
229
- }
230
- else {
231
- throw new Error("Could not subscribe to new blocks");
232
- }
233
- }
234
- }
235
- catch (e) {
236
- this.log.error("Failed to set up block listening: " + e);
237
- this.setStatus("FAILED");
238
- throw e;
239
- }
240
- this.tryToRecover = false;
241
- this.fetcher().catch((e) => {
242
- this.setStatus("FAILED");
243
- throw new Error("Error in fetching service: " + e);
244
- });
245
- const hrTime = process.hrtime();
246
- let ms = hrTime[0] * 1000000 + hrTime[1] / 1000;
247
- while (this.blockQueue.size() > 0 && !this.tryToRecover) {
248
- // await the dequeued promise is essentially awaiting fetched data for that block
249
- try {
250
- if (this.tryToRecover) {
251
- throw new Error("Exiting processing loop. Attempting to recover indexer");
252
- }
253
- // Index block inside a db transaction to ensure data consistency
254
- await this.config.beginTransaction();
255
- this.log.silly("Started db tx");
256
- let height, timestamp;
257
- if (this.isMinimal(this.blockQueue)) {
258
- const toProcess = await this.blockQueue.dequeue();
259
- this.log.silly("Retrieved block data");
260
- if (!toProcess || !toProcess[0] || !toProcess[1]) {
261
- throw new Error("Could not fetch block");
262
- }
263
- height = toProcess[0].block.header.height;
264
- timestamp = toRfc3339WithNanoseconds(toProcess[0].block.header.time);
265
- await this.processBlock(toProcess[0], toProcess[1]);
266
- }
267
- else {
268
- const toProcess = await this.blockQueue.dequeue();
269
- this.log.silly("Retrieved block data");
270
- if (!toProcess || !toProcess[0] || !toProcess[1] || !toProcess[2]) {
271
- throw new Error("Could not fetch block");
272
- }
273
- this.log.silly("Decoded block");
274
- height = toProcess[0].block.header.height;
275
- timestamp = toRfc3339WithNanoseconds(toProcess[0].block.header.time);
276
- await this.processBlock(toProcess[0], toProcess[1], QueryValidatorsResponse.decode(toProcess[2]).validators);
277
- }
278
- // Emit events to trigger periodic operations every 50, 100 and 1000 blocks
279
- if (height % 1000 == 0) {
280
- const hrTime = process.hrtime();
281
- const newms = hrTime[0] * 1000000 + hrTime[1] / 1000;
282
- const duration = newms - ms;
283
- ms = newms;
284
- const rate = 1000000000 / duration;
285
- this.log.info("Processing:" + rate.toFixed(2) + "blocks/sec");
286
- await this.asyncEmit("periodic/1000", {
287
- value: null,
288
- height,
289
- timestamp,
290
- });
291
- }
292
- if (height % 100 == 0) {
293
- await this.asyncEmit("periodic/100", {
294
- value: null,
295
- height,
296
- timestamp,
297
- });
298
- }
299
- if (height % 50 == 0) {
300
- await this.asyncEmit("periodic/50", {
301
- value: null,
302
- height,
303
- timestamp,
304
- });
305
- }
306
- this.log.silly("Handled periodic events");
307
- await this.config.endTransaction(true);
308
- this.log.silly("Committed db tx");
309
- }
310
- catch (e) {
311
- this.log.error("" + e);
312
- this.setStatus("FAILED");
313
- try {
314
- await this.config.endTransaction(false);
315
- }
316
- catch (dbe) {
317
- this.log.error("Error ending transaction. Must be a DB error: " + dbe);
318
- }
319
- this.tryToRecover = true;
320
- this.retryCount++;
321
- break;
322
- }
323
- this.retryCount = 0;
324
- this.setStatus("OK");
325
- }
326
- if (this.retryCount < 3) {
327
- this.log.debug("Indexer retryCount: " + this.retryCount);
328
- this.log.info("Indexer is restarting");
329
- setTimeout(() => this.start(), this.retryCount * 5000);
330
- }
331
- else {
332
- this.log.info("Indexer failed too many times. Exiting.");
333
- process.exit(1);
334
- }
335
- }
336
- async processBlock(block, block_results, validators) {
337
- let processStart = [0, 0];
338
- if (this.config.logLevel == "silly") {
339
- processStart = process.hrtime();
340
- }
341
- const height = block.block.header.height;
342
- this.log.debug("Processing block: %d", height);
343
- this.log.silly("Started db tx");
344
- // Initialize height & timestamp to be used for this block-processing run
345
- const timestamp = toRfc3339WithNanoseconds(block.block.header.time);
346
- // Use & await asyncEmit to ensure db insertions in order
347
- /*
348
- * Emit block information to any interested modules.
349
- * Primarily the required block module listens to this
350
- */
351
- await this.asyncEmit("block", {
352
- value: {
353
- block,
354
- block_results,
355
- },
356
- height,
357
- timestamp,
358
- });
359
- this.log.silly("Modules handled block event");
360
- // Deal with begin_block events first
361
- await this.asyncEmit("begin_block", {
362
- value: {
363
- events: block_results.beginBlockEvents,
364
- validators,
365
- },
366
- height,
367
- timestamp,
368
- });
369
- this.log.silly("Modules handled begin_block events");
370
- // Then individual tx_events
371
- await this.asyncEmit("tx_events", {
372
- value: block_results.results,
373
- height,
374
- timestamp,
375
- });
376
- this.log.silly("Modules handled tx events");
377
- // Emit details and result for each tx msg separately
378
- for (let t = 0; t < block.block.txs.length; t++) {
379
- const tx = Tx.decode(block.block.txs[t]);
380
- const result = block_results.results[t].code;
381
- const txlog = block_results.results[t].log;
382
- if (result != 0) {
383
- // Tx failed. Ignore
384
- continue;
385
- }
386
- if (tx.body && tx.body.memo != "") {
387
- const txHash = createHash("sha256").update(block.block.txs[t])
388
- .digest("hex");
389
- await this.asyncEmit("tx_memo", {
390
- value: {
391
- txHash,
392
- txBody: tx.body,
393
- },
394
- height,
395
- timestamp,
396
- });
397
- }
398
- // parsing log rather than using events directly in order to have msg_index available to filter appropriate events for each msg
399
- const events = txlog
400
- ? JSON.parse(txlog)
401
- : [];
402
- const msgs = tx.body?.messages;
403
- if (msgs) {
404
- for (let i = 0; i < msgs.length; i++) {
405
- this.log.silly("Indexer broadcasting msg for handling: " + msgs[i].typeUrl);
406
- const msgevents = msgs.length > 1
407
- ? events.find(x => x.msg_index == i)?.events
408
- : events[0].events;
409
- await this.asyncEmit(msgs[i].typeUrl, {
410
- value: {
411
- tx: msgs[i].value,
412
- events: msgevents,
413
- },
414
- height,
415
- timestamp,
416
- });
417
- if (msgs[i].typeUrl == "/cosmos.authz.v1beta1.MsgExec") {
418
- const authzMsgs = MsgExec.decode(msgs[i].value).msgs;
419
- if (authzMsgs) {
420
- for (let r = 0; r < authzMsgs.length; r++) {
421
- this.log.silly("Indexer broadcasting msg for handling: " + authzMsgs[r].typeUrl);
422
- const authzMsgEvents = msgevents?.reduce((events, evt) => {
423
- if (evt.attributes.filter(x => decodeAttr(x.key) == "authz_msg_index" && decodeAttr(x.value) == "" + r).length > 0) {
424
- events.push(evt);
425
- }
426
- return events;
427
- }, []);
428
- await this.asyncEmit(authzMsgs[r].typeUrl, {
429
- value: {
430
- tx: authzMsgs[r].value,
431
- events: authzMsgEvents,
432
- },
433
- height,
434
- timestamp,
435
- });
436
- }
437
- }
438
- }
439
- }
440
- }
441
- }
442
- this.log.silly("Modules handled msg events");
443
- // Then deal with end_block events
444
- await this.asyncEmit("end_block", {
445
- value: block_results.endBlockEvents,
446
- height,
447
- timestamp,
448
- });
449
- this.log.silly("Modules handled end_block events");
450
- if (this.config.logLevel == "silly") {
451
- const processEnd = process.hrtime(processStart);
452
- const processTime = processEnd[0] * 1000 + processEnd[1] / 1000000;
453
- this.log.silly("Processed block %d in %d ms", height, processTime.toFixed(2));
454
- }
455
- }
456
- async fetcher() {
457
- for (let i = this.heightToProcess; i <= this.latestHeight; i++) {
458
- this.log.debug("Fetching: " + i);
459
- if (this.tryToRecover) {
460
- this.log.verbose("Exiting fetcher loop. Attempting to recover indexer");
461
- break;
462
- }
463
- try {
464
- if (this.isMinimal(this.blockQueue)) {
465
- const timeoutPromise = new Promise((resolve, reject) => {
466
- setTimeout(reject, 20000, false);
467
- });
468
- const toIndex = Promise.race([Promise.all([this.blockClient.block(i), this.blockClient.blockResults(i)]), timeoutPromise]).catch((e) => {
469
- this.log.error("Error fetching block: " + i + " : " + e);
470
- this.tryToRecover = true;
471
- return Promise.resolve([]);
472
- });
473
- this.blockQueue.enqueue(toIndex);
474
- }
475
- else {
476
- const timeoutPromise = new Promise((resolve, reject) => {
477
- setTimeout(reject, 20000, false);
478
- });
479
- const q = QueryValidatorsRequest.fromPartial({
480
- pagination: {
481
- limit: 1000n,
482
- },
483
- });
484
- const vals = QueryValidatorsRequest.encode(q).finish();
485
- const toIndex = Promise.race([
486
- Promise.all([
487
- this.blockClient.block(i),
488
- this.blockClient.blockResults(i),
489
- this.callABCI("/cosmos.staking.v1beta1.Query/Validators", vals, i, false),
490
- ]),
491
- timeoutPromise,
492
- ]).catch((e) => {
493
- this.log.error("Error fetching block: " + i + " : " + e);
494
- this.tryToRecover = true;
495
- return Promise.resolve([]);
496
- });
497
- this.blockQueue.enqueue(toIndex);
498
- }
499
- await this.blockQueue.continue();
500
- if (this.tryToRecover) {
501
- this.retryCount++;
502
- throw new Error("RPC not responding");
503
- }
504
- }
505
- catch (e) {
506
- this.log.error(e);
507
- break;
508
- }
509
- }
510
- if (!this.tryToRecover) {
511
- this.blockQueue.setSynced();
512
- this.log.info("Synced to latest height");
513
- }
514
- }
515
- async callABCI(path, data, height, adHoc = true) {
516
- try {
517
- const abciq = await (adHoc
518
- ? this.client
519
- : this.blockClient).abciQuery({
520
- path,
521
- data,
522
- height: height,
523
- });
524
- if (abciq) {
525
- return abciq.value;
526
- }
527
- else {
528
- this.tryToRecover = true;
529
- this.setStatus("FAILED");
530
- throw new Error("RPC not responding. Query at: " + path);
531
- }
532
- }
533
- catch (_e) {
534
- this.tryToRecover = true;
535
- this.setStatus("FAILED");
536
- this.retryCount++;
537
- throw new Error("RPC not responding. Query at: " + path);
538
- }
539
- }
540
- newBlockReceived(height) {
541
- this.log.info("Received new block: %d", height);
542
- // If we are synced, add to end of queue
543
- if (this.blockQueue.synced && !this.tryToRecover) {
544
- if (this.blockQueue.size() + 1 == this.config.batchSize) {
545
- this.log.error("Block queue is full. Cannot add new block");
546
- this.tryToRecover = true;
547
- this.retryCount++;
548
- return;
549
- }
550
- try {
551
- if (this.isMinimal(this.blockQueue)) {
552
- this.blockQueue.enqueue(Promise.all([this.client.block(height), this.client.blockResults(height)]).catch((e) => {
553
- this.log.error("Error fetching block: " + height + " : " + e);
554
- return Promise.resolve([]);
555
- }));
556
- }
557
- else {
558
- const q = QueryValidatorsRequest.fromPartial({
559
- pagination: {
560
- limit: 1000n,
561
- },
562
- });
563
- const vals = QueryValidatorsRequest.encode(q).finish();
564
- this.blockQueue.enqueue(Promise.all([
565
- this.client.block(height),
566
- this.client.blockResults(height),
567
- this.callABCI("/cosmos.staking.v1beta1.Query/Validators", vals, height, false),
568
- ]).catch((e) => {
569
- this.log.error("Error fetching block: " + height + " : " + e);
570
- return Promise.resolve([]);
571
- }));
572
- }
573
- }
574
- catch (e) {
575
- this.log.error("" + e);
576
- }
577
- }
578
- else {
579
- this.latestHeight = height;
580
- }
581
- }
582
- async pollForBlock() {
583
- const status = await this.client.status();
584
- if (status.syncInfo.latestBlockHeight > this.latestHeight) {
585
- while (this.latestHeight < status.syncInfo.latestBlockHeight) {
586
- this.newBlockReceived(this.latestHeight + 1);
587
- }
588
- }
589
- setTimeout(() => {
590
- this.pollForBlock();
591
- }, this.config.pollingInterval);
592
- }
593
- readGenesis() {
594
- if (this.config.genesisPath) {
595
- return fs.createReadStream(this.config.genesisPath).pipe(parser());
596
- }
597
- else {
598
- throw new Error("Genesis path not set");
599
- }
600
- }
601
- async setArrayReader(path, processor) {
602
- const readPromise = new Promise((resolve, reject) => {
603
- try {
604
- const filters = path.split(".");
605
- const pickers = filters.map(filter => pick({
606
- filter,
607
- }));
608
- let counter = 0;
609
- chain([
610
- this.readGenesis(),
611
- ...pickers,
612
- streamArray(),
613
- batch({
614
- batchSize: 1000,
615
- }),
616
- processor,
617
- ])
618
- .on("data", (data) => {
619
- if (data && Array.isArray(data)) {
620
- counter = counter + data.length;
621
- }
622
- })
623
- .on("end", () => {
624
- this.log.info(`Processed ${counter} entries`);
625
- resolve(true);
626
- });
627
- }
628
- catch (_e) {
629
- this.log.verbose("Error in setArrayReader: " + _e);
630
- reject();
631
- }
632
- });
633
- return readPromise;
634
- }
635
- async setValueReader(path, processor) {
636
- const readPromise = new Promise((resolve, reject) => {
637
- try {
638
- const filters = path.split(".");
639
- const pickers = filters.map(filter => pick({
640
- filter,
641
- }));
642
- let counter = 0;
643
- chain([this.readGenesis(), ...pickers, streamValues(), processor])
644
- .on("data", (_data) => {
645
- counter++;
646
- })
647
- .on("end", () => {
648
- this.log.info(`Processed ${counter} entries`);
649
- resolve(true);
650
- });
651
- }
652
- catch (_e) {
653
- reject();
654
- }
655
- });
656
- return readPromise;
657
- }
658
- async parseGenesis() {
659
- this.log.info("Parsing genesis");
660
- await this.config.beginTransaction();
661
- try {
662
- this.log.info("Starting genesis import");
663
- this.log.debug("Importing genesis file...");
664
- for (const [key, _value] of this.handled) {
665
- if (key.startsWith("genesis/")) {
666
- const genesisEntry = key.split("/");
667
- this.log.verbose("Importing " + key + "...");
668
- if (genesisEntry[1] == "array") {
669
- await this.setArrayReader(genesisEntry[2],
670
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
671
- async (data) => {
672
- await this.asyncEmit(key, {
673
- value: data.map((x) => x.value),
674
- });
675
- return data;
676
- });
677
- }
678
- else {
679
- await this.setValueReader(genesisEntry[2],
680
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
681
- async (data) => {
682
- await this.asyncEmit(key, {
683
- value: data.value,
684
- });
685
- return data;
686
- });
687
- }
688
- }
689
- }
690
- this.log.info("Importing gen TXs...");
691
- await this.setArrayReader("app_state.genutil.gen_txs",
692
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
693
- async (data) => {
694
- for (let j = 0; j < data.length; j++) {
695
- const gentx = data[j].value;
696
- for (let i = 0; i < gentx.body.messages.length; i++) {
697
- const msg = gentx.body.messages[i];
698
- await this.asyncEmit(("gentx" + msg["@type"]), {
699
- value: msg,
700
- });
701
- }
702
- }
703
- return data;
704
- });
705
- await this.config.endTransaction(true);
706
- this.log.info("Finished importing");
707
- }
708
- catch (e) {
709
- try {
710
- await this.config.endTransaction(false);
711
- }
712
- catch (dbe) {
713
- this.log.error("Error ending transaction. Must be a DB error: " + dbe);
714
- }
715
- this.log.error("Failed to import genesis");
716
- throw e;
717
- }
718
- }
719
- }
36
+ var EcleciaIndexer = class extends EclesiaEmitter {
37
+ constructor(config) {
38
+ super();
39
+ this.initialized = false;
40
+ this.retryCount = 0;
41
+ this.tryToRecover = false;
42
+ this.healthCheck = { status: "CONNECTING" };
43
+ this.subscription = null;
44
+ this.blockListener = { next: (data) => {
45
+ this.newBlockReceived(data.header.height);
46
+ } };
47
+ this.asyncEmit = async (type, event) => {
48
+ event.uuid = v4();
49
+ let listenerCount = this.handled.get(type);
50
+ if (!listenerCount) listenerCount = 1;
51
+ let listenersResponded = 0;
52
+ const prom = new Promise((resolve, reject) => {
53
+ const returnFunc = (ev) => {
54
+ if (ev.uuid == event.uuid) if (ev.status) {
55
+ listenersResponded++;
56
+ if (listenersResponded == listenerCount) {
57
+ this.off("uuid", returnFunc);
58
+ resolve();
59
+ }
60
+ } else reject(ev.error);
61
+ };
62
+ this.on("uuid", returnFunc);
63
+ });
64
+ this.emit(type, event);
65
+ return prom;
66
+ };
67
+ this.config = {
68
+ ...defaultIndexerConfig,
69
+ ...config
70
+ };
71
+ if (this.config.minimal) this.blockQueue = new CircularBuffer(this.config.batchSize);
72
+ else this.blockQueue = new CircularBuffer(this.config.batchSize);
73
+ const { printf } = winston.format;
74
+ const eclesiaFormat = printf(({ level, message, timestamp }) => {
75
+ return `${timestamp} [${level.toUpperCase()}]:\t${message}`;
76
+ });
77
+ this.log = winston.createLogger({
78
+ level: this.config.logLevel,
79
+ defaultMeta: { service: "Eclesia Indexer" },
80
+ transports: [
81
+ new winston.transports.File({
82
+ filename: "error.log",
83
+ level: "error"
84
+ }),
85
+ new winston.transports.File({ filename: "combined.log" }),
86
+ new winston.transports.Console({ format: winston.format.combine(winston.format.splat(), winston.format.timestamp(), eclesiaFormat, winston.format.colorize({ all: true })) })
87
+ ]
88
+ });
89
+ this.fastify = Fastify({ logger: false });
90
+ this.on("_unhandled", (msg) => {
91
+ if (msg.uuid) {
92
+ this.log.verbose("Unhandled event: " + msg.type);
93
+ this.emit("uuid", {
94
+ status: true,
95
+ uuid: msg.uuid
96
+ });
97
+ }
98
+ });
99
+ this.fastify.get("/health", async (_request, reply) => {
100
+ const code = this.healthCheck.status == "OK" ? 200 : 503;
101
+ reply.code(code).send(this.healthCheck);
102
+ });
103
+ this.fastify.listen({
104
+ port: 80,
105
+ host: "0.0.0.0"
106
+ }, (err) => {
107
+ if (err) {
108
+ this.log.error(err);
109
+ process.exit(1);
110
+ }
111
+ });
112
+ }
113
+ setStatus(status) {
114
+ this.healthCheck.status = status;
115
+ }
116
+ isMinimal(_blockqueue) {
117
+ if (this.config.minimal) return true;
118
+ else return false;
119
+ }
120
+ async connect() {
121
+ try {
122
+ if (this.client && this.tryToRecover) {
123
+ this.log.verbose("Recover from error. Attempting to disconnect from RPC");
124
+ this.client.disconnect();
125
+ this.blockClient.disconnect();
126
+ this.log.verbose("Disconnected from RPC");
127
+ }
128
+ this.client = await connectComet(this.config.rpcUrl);
129
+ this.log.info("Connected to RPC for ad hoc queries");
130
+ this.blockClient = await connectComet(this.config.rpcUrl);
131
+ this.log.info("Connected to RPC for block & validator info");
132
+ return true;
133
+ } catch (error) {
134
+ this.log.error(error);
135
+ this.tryToRecover = true;
136
+ return false;
137
+ }
138
+ }
139
+ async start() {
140
+ if (this.blockQueue) {
141
+ this.blockQueue.clear();
142
+ this.log.verbose("Starting, clearing block queue");
143
+ }
144
+ if (!this.initialized) {
145
+ try {
146
+ if (this.config.init) await this.config.init();
147
+ } catch (e) {
148
+ this.log.error("Failed to initialize indexer: " + e);
149
+ this.setStatus("FAILED");
150
+ throw e;
151
+ }
152
+ if (this.config.processGenesis) try {
153
+ if (this.config.genesisPath) await this.parseGenesis();
154
+ } catch (e) {
155
+ this.log.error("Failed to parse genesis: " + e);
156
+ this.setStatus("FAILED");
157
+ throw e;
158
+ }
159
+ this.initialized = true;
160
+ }
161
+ try {
162
+ await this.connect();
163
+ if (!this.config.usePolling && this.subscription) {
164
+ this.subscription.removeListener(this.blockListener);
165
+ this.subscription = null;
166
+ this.log.verbose("Removed existing block listener and subscription");
167
+ }
168
+ this.subscription = this.client.subscribeNewBlock ? this.client.subscribeNewBlock() : null;
169
+ this.latestHeight = (await this.client.status()).syncInfo.latestBlockHeight;
170
+ this.log.info("Current chain height: " + this.latestHeight);
171
+ this.heightToProcess = await this.config.getNextHeight();
172
+ if (this.config.usePolling) this.pollForBlock();
173
+ else if (this.subscription) this.subscription.addListener(this.blockListener);
174
+ else throw new Error("Could not subscribe to new blocks");
175
+ } catch (e) {
176
+ this.log.error("Failed to set up block listening: " + e);
177
+ this.setStatus("FAILED");
178
+ throw e;
179
+ }
180
+ this.tryToRecover = false;
181
+ this.fetcher().catch((e) => {
182
+ this.setStatus("FAILED");
183
+ throw new Error("Error in fetching service: " + e);
184
+ });
185
+ const hrTime = process.hrtime();
186
+ let ms = hrTime[0] * 1e6 + hrTime[1] / 1e3;
187
+ while (this.blockQueue.size() > 0 && !this.tryToRecover) {
188
+ try {
189
+ if (this.tryToRecover) throw new Error("Exiting processing loop. Attempting to recover indexer");
190
+ await this.config.beginTransaction();
191
+ this.log.silly("Started db tx");
192
+ let height, timestamp;
193
+ if (this.isMinimal(this.blockQueue)) {
194
+ const toProcess = await this.blockQueue.dequeue();
195
+ this.log.silly("Retrieved block data");
196
+ if (!toProcess || !toProcess[0] || !toProcess[1]) throw new Error("Could not fetch block");
197
+ height = toProcess[0].block.header.height;
198
+ timestamp = toRfc3339WithNanoseconds(toProcess[0].block.header.time);
199
+ await this.processBlock(toProcess[0], toProcess[1]);
200
+ } else {
201
+ const toProcess = await this.blockQueue.dequeue();
202
+ this.log.silly("Retrieved block data");
203
+ if (!toProcess || !toProcess[0] || !toProcess[1] || !toProcess[2]) throw new Error("Could not fetch block");
204
+ this.log.silly("Decoded block");
205
+ height = toProcess[0].block.header.height;
206
+ timestamp = toRfc3339WithNanoseconds(toProcess[0].block.header.time);
207
+ await this.processBlock(toProcess[0], toProcess[1], QueryValidatorsResponse.decode(toProcess[2]).validators);
208
+ }
209
+ if (height % 1e3 == 0) {
210
+ const hrTime$1 = process.hrtime();
211
+ const newms = hrTime$1[0] * 1e6 + hrTime$1[1] / 1e3;
212
+ const duration = newms - ms;
213
+ ms = newms;
214
+ const rate = 1e9 / duration;
215
+ this.log.info("Processing:" + rate.toFixed(2) + "blocks/sec");
216
+ await this.asyncEmit("periodic/1000", {
217
+ value: null,
218
+ height,
219
+ timestamp
220
+ });
221
+ }
222
+ if (height % 100 == 0) await this.asyncEmit("periodic/100", {
223
+ value: null,
224
+ height,
225
+ timestamp
226
+ });
227
+ if (height % 50 == 0) await this.asyncEmit("periodic/50", {
228
+ value: null,
229
+ height,
230
+ timestamp
231
+ });
232
+ this.log.silly("Handled periodic events");
233
+ await this.config.endTransaction(true);
234
+ this.log.silly("Committed db tx");
235
+ } catch (e) {
236
+ this.log.error("" + e);
237
+ this.setStatus("FAILED");
238
+ try {
239
+ await this.config.endTransaction(false);
240
+ } catch (dbe) {
241
+ this.log.error("Error ending transaction. Must be a DB error: " + dbe);
242
+ }
243
+ this.tryToRecover = true;
244
+ this.retryCount++;
245
+ break;
246
+ }
247
+ this.retryCount = 0;
248
+ this.setStatus("OK");
249
+ }
250
+ if (this.retryCount < 3) {
251
+ this.log.debug("Indexer retryCount: " + this.retryCount);
252
+ this.log.info("Indexer is restarting");
253
+ setTimeout(() => this.start(), this.retryCount * 5e3);
254
+ } else {
255
+ this.log.info("Indexer failed too many times. Exiting.");
256
+ process.exit(1);
257
+ }
258
+ }
259
+ async processBlock(block, block_results, validators) {
260
+ let processStart = [0, 0];
261
+ if (this.config.logLevel == "silly") processStart = process.hrtime();
262
+ const height = block.block.header.height;
263
+ this.log.debug("Processing block: %d", height);
264
+ this.log.silly("Started db tx");
265
+ const timestamp = toRfc3339WithNanoseconds(block.block.header.time);
266
+ await this.asyncEmit("block", {
267
+ value: {
268
+ block,
269
+ block_results
270
+ },
271
+ height,
272
+ timestamp
273
+ });
274
+ this.log.silly("Modules handled block event");
275
+ await this.asyncEmit("begin_block", {
276
+ value: {
277
+ events: block_results.beginBlockEvents,
278
+ validators
279
+ },
280
+ height,
281
+ timestamp
282
+ });
283
+ this.log.silly("Modules handled begin_block events");
284
+ await this.asyncEmit("tx_events", {
285
+ value: block_results.results,
286
+ height,
287
+ timestamp
288
+ });
289
+ this.log.silly("Modules handled tx events");
290
+ for (let t = 0; t < block.block.txs.length; t++) {
291
+ const tx = Tx.decode(block.block.txs[t]);
292
+ const result = block_results.results[t].code;
293
+ const txlog = block_results.results[t].log;
294
+ if (result != 0) continue;
295
+ if (tx.body && tx.body.memo != "") {
296
+ const txHash = createHash("sha256").update(block.block.txs[t]).digest("hex");
297
+ await this.asyncEmit("tx_memo", {
298
+ value: {
299
+ txHash,
300
+ txBody: tx.body
301
+ },
302
+ height,
303
+ timestamp
304
+ });
305
+ }
306
+ const events = txlog ? JSON.parse(txlog) : [];
307
+ const msgs = tx.body?.messages;
308
+ if (msgs) for (let i = 0; i < msgs.length; i++) {
309
+ this.log.silly("Indexer broadcasting msg for handling: " + msgs[i].typeUrl);
310
+ const msgevents = msgs.length > 1 ? events.find((x) => x.msg_index == i)?.events : events[0].events;
311
+ await this.asyncEmit(msgs[i].typeUrl, {
312
+ value: {
313
+ tx: msgs[i].value,
314
+ events: msgevents
315
+ },
316
+ height,
317
+ timestamp
318
+ });
319
+ if (msgs[i].typeUrl == "/cosmos.authz.v1beta1.MsgExec") {
320
+ const authzMsgs = MsgExec.decode(msgs[i].value).msgs;
321
+ if (authzMsgs) for (let r = 0; r < authzMsgs.length; r++) {
322
+ this.log.silly("Indexer broadcasting msg for handling: " + authzMsgs[r].typeUrl);
323
+ const authzMsgEvents = msgevents?.reduce((events$1, evt) => {
324
+ if (evt.attributes.filter((x) => decodeAttr(x.key) == "authz_msg_index" && decodeAttr(x.value) == "" + r).length > 0) events$1.push(evt);
325
+ return events$1;
326
+ }, []);
327
+ await this.asyncEmit(authzMsgs[r].typeUrl, {
328
+ value: {
329
+ tx: authzMsgs[r].value,
330
+ events: authzMsgEvents
331
+ },
332
+ height,
333
+ timestamp
334
+ });
335
+ }
336
+ }
337
+ }
338
+ }
339
+ this.log.silly("Modules handled msg events");
340
+ await this.asyncEmit("end_block", {
341
+ value: block_results.endBlockEvents,
342
+ height,
343
+ timestamp
344
+ });
345
+ this.log.silly("Modules handled end_block events");
346
+ if (this.config.logLevel == "silly") {
347
+ const processEnd = process.hrtime(processStart);
348
+ const processTime = processEnd[0] * 1e3 + processEnd[1] / 1e6;
349
+ this.log.silly("Processed block %d in %d ms", height, processTime.toFixed(2));
350
+ }
351
+ }
352
+ async fetcher() {
353
+ for (let i = this.heightToProcess; i <= this.latestHeight; i++) {
354
+ this.log.debug("Fetching: " + i);
355
+ if (this.tryToRecover) {
356
+ this.log.verbose("Exiting fetcher loop. Attempting to recover indexer");
357
+ break;
358
+ }
359
+ try {
360
+ if (this.isMinimal(this.blockQueue)) {
361
+ const timeoutPromise = new Promise((resolve, reject) => {
362
+ setTimeout(reject, 2e4, false);
363
+ });
364
+ const toIndex = Promise.race([Promise.all([this.blockClient.block(i), this.blockClient.blockResults(i)]), timeoutPromise]).catch((e) => {
365
+ this.log.error("Error fetching block: " + i + " : " + e);
366
+ this.tryToRecover = true;
367
+ return Promise.resolve([]);
368
+ });
369
+ this.blockQueue.enqueue(toIndex);
370
+ } else {
371
+ const timeoutPromise = new Promise((resolve, reject) => {
372
+ setTimeout(reject, 2e4, false);
373
+ });
374
+ const q = QueryValidatorsRequest.fromPartial({ pagination: { limit: 1000n } });
375
+ const vals = QueryValidatorsRequest.encode(q).finish();
376
+ const toIndex = Promise.race([Promise.all([
377
+ this.blockClient.block(i),
378
+ this.blockClient.blockResults(i),
379
+ this.callABCI("/cosmos.staking.v1beta1.Query/Validators", vals, i, false)
380
+ ]), timeoutPromise]).catch((e) => {
381
+ this.log.error("Error fetching block: " + i + " : " + e);
382
+ this.tryToRecover = true;
383
+ return Promise.resolve([]);
384
+ });
385
+ this.blockQueue.enqueue(toIndex);
386
+ }
387
+ await this.blockQueue.continue();
388
+ if (this.tryToRecover) {
389
+ this.retryCount++;
390
+ throw new Error("RPC not responding");
391
+ }
392
+ } catch (e) {
393
+ this.log.error(e);
394
+ break;
395
+ }
396
+ }
397
+ if (!this.tryToRecover) {
398
+ this.blockQueue.setSynced();
399
+ this.log.info("Synced to latest height");
400
+ }
401
+ }
402
+ async callABCI(path, data, height, adHoc = true) {
403
+ try {
404
+ const abciq = await (adHoc ? this.client : this.blockClient).abciQuery({
405
+ path,
406
+ data,
407
+ height
408
+ });
409
+ if (abciq) return abciq.value;
410
+ else {
411
+ this.tryToRecover = true;
412
+ this.setStatus("FAILED");
413
+ throw new Error("RPC not responding. Query at: " + path);
414
+ }
415
+ } catch (_e) {
416
+ this.tryToRecover = true;
417
+ this.setStatus("FAILED");
418
+ this.retryCount++;
419
+ throw new Error("RPC not responding. Query at: " + path);
420
+ }
421
+ }
422
+ newBlockReceived(height) {
423
+ this.log.info("Received new block: %d", height);
424
+ if (this.blockQueue.synced && !this.tryToRecover) {
425
+ if (this.blockQueue.size() + 1 == this.config.batchSize) {
426
+ this.log.error("Block queue is full. Cannot add new block");
427
+ this.tryToRecover = true;
428
+ this.retryCount++;
429
+ return;
430
+ }
431
+ try {
432
+ if (this.isMinimal(this.blockQueue)) this.blockQueue.enqueue(Promise.all([this.client.block(height), this.client.blockResults(height)]).catch((e) => {
433
+ this.log.error("Error fetching block: " + height + " : " + e);
434
+ return Promise.resolve([]);
435
+ }));
436
+ else {
437
+ const q = QueryValidatorsRequest.fromPartial({ pagination: { limit: 1000n } });
438
+ const vals = QueryValidatorsRequest.encode(q).finish();
439
+ this.blockQueue.enqueue(Promise.all([
440
+ this.client.block(height),
441
+ this.client.blockResults(height),
442
+ this.callABCI("/cosmos.staking.v1beta1.Query/Validators", vals, height, false)
443
+ ]).catch((e) => {
444
+ this.log.error("Error fetching block: " + height + " : " + e);
445
+ return Promise.resolve([]);
446
+ }));
447
+ }
448
+ } catch (e) {
449
+ this.log.error("" + e);
450
+ }
451
+ } else this.latestHeight = height;
452
+ }
453
+ async pollForBlock() {
454
+ const status = await this.client.status();
455
+ if (status.syncInfo.latestBlockHeight > this.latestHeight) while (this.latestHeight < status.syncInfo.latestBlockHeight) this.newBlockReceived(this.latestHeight + 1);
456
+ setTimeout(() => {
457
+ this.pollForBlock();
458
+ }, this.config.pollingInterval);
459
+ }
460
+ readGenesis() {
461
+ if (this.config.genesisPath) return fs.createReadStream(this.config.genesisPath).pipe(Parser.parser());
462
+ else throw new Error("Genesis path not set");
463
+ }
464
+ async setArrayReader(path, processor) {
465
+ return new Promise((resolve, reject) => {
466
+ try {
467
+ const pickers = path.split(".").map((filter) => Pick.pick({ filter }));
468
+ let counter = 0;
469
+ chain([
470
+ this.readGenesis(),
471
+ ...pickers,
472
+ StreamArray.streamArray(),
473
+ Batch.batch({ batchSize: 1e3 }),
474
+ processor
475
+ ]).on("data", (data) => {
476
+ if (data && Array.isArray(data)) counter = counter + data.length;
477
+ }).on("end", () => {
478
+ this.log.info(`Processed ${counter} entries`);
479
+ resolve(true);
480
+ });
481
+ } catch (_e) {
482
+ this.log.verbose("Error in setArrayReader: " + _e);
483
+ reject();
484
+ }
485
+ });
486
+ }
487
+ async setValueReader(path, processor) {
488
+ return new Promise((resolve, reject) => {
489
+ try {
490
+ const pickers = path.split(".").map((filter) => Pick.pick({ filter }));
491
+ let counter = 0;
492
+ chain([
493
+ this.readGenesis(),
494
+ ...pickers,
495
+ StreamValues.streamValues(),
496
+ processor
497
+ ]).on("data", (_data) => {
498
+ counter++;
499
+ }).on("end", () => {
500
+ this.log.info(`Processed ${counter} entries`);
501
+ resolve(true);
502
+ });
503
+ } catch (_e) {
504
+ reject();
505
+ }
506
+ });
507
+ }
508
+ async parseGenesis() {
509
+ this.log.info("Parsing genesis");
510
+ await this.config.beginTransaction();
511
+ try {
512
+ this.log.info("Starting genesis import");
513
+ this.log.debug("Importing genesis file...");
514
+ for (const [key, _value] of this.handled) if (key.startsWith("genesis/")) {
515
+ const genesisEntry = key.split("/");
516
+ this.log.verbose("Importing " + key + "...");
517
+ if (genesisEntry[1] == "array") await this.setArrayReader(genesisEntry[2], async (data) => {
518
+ await this.asyncEmit(key, { value: data.map((x) => x.value) });
519
+ return data;
520
+ });
521
+ else await this.setValueReader(genesisEntry[2], async (data) => {
522
+ await this.asyncEmit(key, { value: data.value });
523
+ return data;
524
+ });
525
+ }
526
+ this.log.info("Importing gen TXs...");
527
+ await this.setArrayReader("app_state.genutil.gen_txs", async (data) => {
528
+ for (let j = 0; j < data.length; j++) {
529
+ const gentx = data[j].value;
530
+ for (let i = 0; i < gentx.body.messages.length; i++) {
531
+ const msg = gentx.body.messages[i];
532
+ await this.asyncEmit("gentx" + msg["@type"], { value: msg });
533
+ }
534
+ }
535
+ return data;
536
+ });
537
+ await this.config.endTransaction(true);
538
+ this.log.info("Finished importing");
539
+ } catch (e) {
540
+ try {
541
+ await this.config.endTransaction(false);
542
+ } catch (dbe) {
543
+ this.log.error("Error ending transaction. Must be a DB error: " + dbe);
544
+ }
545
+ this.log.error("Failed to import genesis");
546
+ throw e;
547
+ }
548
+ }
549
+ };
550
+
551
+ //#endregion
552
+ export { EcleciaIndexer, defaultIndexerConfig };
553
+ //# sourceMappingURL=index.js.map