@eclesia/indexer-engine 2.10.0 → 2.11.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.
- package/dist/_virtual/rolldown_runtime.cjs +4 -0
- package/dist/_virtual/rolldown_runtime.mjs +38 -0
- package/dist/constants.cjs +6 -2
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +6 -3
- package/dist/constants.d.cts.map +1 -1
- package/dist/{constants.d.ts → constants.d.mts} +7 -4
- package/dist/constants.d.mts.map +1 -0
- package/dist/{constants.js → constants.mjs} +7 -4
- package/dist/constants.mjs.map +1 -0
- package/dist/emitter/index.cjs +6 -3
- package/dist/emitter/index.cjs.map +1 -1
- package/dist/emitter/index.d.cts.map +1 -1
- package/dist/emitter/{index.d.ts → index.d.mts} +2 -2
- package/dist/emitter/index.d.mts.map +1 -0
- package/dist/emitter/{index.js → index.mjs} +7 -4
- package/dist/emitter/index.mjs.map +1 -0
- package/dist/errors/index.cjs +18 -0
- package/dist/errors/index.cjs.map +1 -1
- package/dist/errors/index.d.cts.map +1 -1
- package/dist/errors/{index.d.ts → index.d.mts} +1 -1
- package/dist/errors/index.d.mts.map +1 -0
- package/dist/errors/{index.js → index.mjs} +19 -1
- package/dist/errors/index.mjs.map +1 -0
- package/dist/index.cjs +10 -2
- package/dist/index.d.cts +6 -5
- package/dist/index.d.mts +11 -0
- package/dist/index.mjs +12 -0
- package/dist/indexer/index.cjs +113 -67
- package/dist/indexer/index.cjs.map +1 -1
- package/dist/indexer/index.d.cts +7 -1
- package/dist/indexer/index.d.cts.map +1 -1
- package/dist/indexer/{index.d.ts → index.d.mts} +11 -5
- package/dist/indexer/index.d.mts.map +1 -0
- package/dist/indexer/{index.js → index.mjs} +121 -75
- package/dist/indexer/index.mjs.map +1 -0
- package/dist/metrics/index.cjs +28 -0
- package/dist/metrics/index.cjs.map +1 -1
- package/dist/metrics/index.d.cts.map +1 -1
- package/dist/metrics/{index.d.ts → index.d.mts} +1 -1
- package/dist/metrics/index.d.mts.map +1 -0
- package/dist/metrics/{index.js → index.mjs} +29 -1
- package/dist/metrics/index.mjs.map +1 -0
- package/dist/mocks/index.cjs +18 -0
- package/dist/mocks/index.cjs.map +1 -0
- package/dist/mocks/index.d.cts +9 -0
- package/dist/mocks/index.d.cts.map +1 -0
- package/dist/mocks/index.d.mts +9 -0
- package/dist/mocks/index.d.mts.map +1 -0
- package/dist/mocks/index.mjs +13 -0
- package/dist/mocks/index.mjs.map +1 -0
- package/dist/mocks/rpc-client.cjs +209 -0
- package/dist/mocks/rpc-client.cjs.map +1 -0
- package/dist/mocks/rpc-client.d.cts +44 -0
- package/dist/mocks/rpc-client.d.cts.map +1 -0
- package/dist/mocks/rpc-client.d.mts +44 -0
- package/dist/mocks/rpc-client.d.mts.map +1 -0
- package/dist/mocks/rpc-client.mjs +208 -0
- package/dist/mocks/rpc-client.mjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/ascii.cjs +32 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/ascii.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/ascii.mjs +29 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/ascii.mjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/base64.cjs +67 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/base64.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/base64.mjs +64 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/base64.mjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/bech32.cjs +80 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/bech32.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/bech32.mjs +77 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/bech32.mjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/hex.cjs +33 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/hex.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/hex.mjs +30 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/hex.mjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/index.cjs +106 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/index.mjs +103 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/index.mjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/rfc3339.cjs +52 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/rfc3339.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/rfc3339.mjs +49 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/rfc3339.mjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/utf8.cjs +31 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/utf8.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/utf8.mjs +28 -0
- package/dist/node_modules/.pnpm/@cosmjs_encoding@0.36.0/node_modules/@cosmjs/encoding/build/utf8.mjs.map +1 -0
- package/dist/node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.cjs +98 -0
- package/dist/node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.mjs +95 -0
- package/dist/node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.mjs.map +1 -0
- package/dist/promise-queue/index.cjs +34 -5
- package/dist/promise-queue/index.cjs.map +1 -1
- package/dist/promise-queue/index.d.cts.map +1 -1
- package/dist/promise-queue/{index.d.ts → index.d.mts} +1 -1
- package/dist/promise-queue/index.d.mts.map +1 -0
- package/dist/promise-queue/{index.js → index.mjs} +35 -6
- package/dist/promise-queue/index.mjs.map +1 -0
- package/dist/types/index.cjs.map +1 -1
- package/dist/types/index.d.cts +2 -1
- package/dist/types/index.d.cts.map +1 -1
- package/dist/types/{index.d.ts → index.d.mts} +5 -4
- package/dist/types/index.d.mts.map +1 -0
- package/dist/types/{index.js → index.mjs} +1 -1
- package/dist/types/index.mjs.map +1 -0
- package/dist/utils/{bech32.d.ts → bech32.d.mts} +1 -1
- package/dist/utils/bech32.d.mts.map +1 -0
- package/dist/utils/{bech32.js → bech32.mjs} +1 -1
- package/dist/utils/bech32.mjs.map +1 -0
- package/dist/utils/{bigint.d.ts → bigint.d.mts} +1 -1
- package/dist/utils/bigint.d.mts.map +1 -0
- package/dist/utils/{bigint.js → bigint.mjs} +1 -1
- package/dist/utils/bigint.mjs.map +1 -0
- package/dist/utils/{index.d.ts → index.d.mts} +4 -4
- package/dist/utils/index.d.mts.map +1 -0
- package/dist/utils/{index.js → index.mjs} +5 -5
- package/dist/utils/index.mjs.map +1 -0
- package/dist/utils/{text.d.ts → text.d.mts} +1 -1
- package/dist/utils/text.d.mts.map +1 -0
- package/dist/utils/{text.js → text.mjs} +1 -1
- package/dist/utils/text.mjs.map +1 -0
- package/dist/validation/{index.d.ts → index.d.mts} +1 -1
- package/dist/validation/index.d.mts.map +1 -0
- package/dist/validation/{index.js → index.mjs} +3 -3
- package/dist/validation/index.mjs.map +1 -0
- package/package.json +23 -20
- package/dist/_virtual/rolldown_runtime.js +0 -13
- package/dist/constants.d.ts.map +0 -1
- package/dist/constants.js.map +0 -1
- package/dist/emitter/index.d.ts.map +0 -1
- package/dist/emitter/index.js.map +0 -1
- package/dist/errors/index.d.ts.map +0 -1
- package/dist/errors/index.js.map +0 -1
- package/dist/index.d.ts +0 -10
- package/dist/index.js +0 -11
- package/dist/indexer/index.d.ts.map +0 -1
- package/dist/indexer/index.js.map +0 -1
- package/dist/metrics/index.d.ts.map +0 -1
- package/dist/metrics/index.js.map +0 -1
- package/dist/promise-queue/index.d.ts.map +0 -1
- package/dist/promise-queue/index.js.map +0 -1
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/index.js.map +0 -1
- package/dist/utils/bech32.d.ts.map +0 -1
- package/dist/utils/bech32.js.map +0 -1
- package/dist/utils/bigint.d.ts.map +0 -1
- package/dist/utils/bigint.js.map +0 -1
- package/dist/utils/index.d.ts.map +0 -1
- package/dist/utils/index.js.map +0 -1
- package/dist/utils/text.d.ts.map +0 -1
- package/dist/utils/text.js.map +0 -1
- package/dist/validation/index.d.ts.map +0 -1
- package/dist/validation/index.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["uuidv4","timeoutPromise: ReturnType<typeof this.blockQueue.dequeue>","hrTime","processStart: [number, number]","beginBlockEvents: readonly Event[] | readonly Event38[]","endBlockEvents: readonly Event[] | readonly Event38[]","events: Array<{\n msg_index?: number\n events: (Event | Event38)[]\n }>","eventsToAdd: typeof events","events","timeoutPromise: Promise<[BlockResponse, BlockResultsResponse]>","timeoutPromise: Promise<[BlockResponse, BlockResultsResponse, Uint8Array]>"],"sources":["../../src/indexer/index.ts"],"sourcesContent":["/* eslint-disable @stylistic/no-multi-spaces */\n/* eslint-disable max-lines */\nimport {\n createHash,\n} from \"node:crypto\";\nimport * as fs from \"node:fs\";\n\nimport {\n BlockResponse, BlockResultsResponse, CometClient, connectComet, Event, toRfc3339WithNanoseconds,\n} from \"@cosmjs/tendermint-rpc\";\nimport {\n BlockResultsResponse as BlockResultsResponse38, Event as Event38,\n} from \"@cosmjs/tendermint-rpc/build/comet38/responses.js\";\nimport {\n MsgExec,\n} from \"cosmjs-types/cosmos/authz/v1beta1/tx.js\";\nimport {\n QueryValidatorsRequest,\n QueryValidatorsResponse,\n} from \"cosmjs-types/cosmos/staking/v1beta1/query.js\";\nimport {\n Validator,\n} from \"cosmjs-types/cosmos/staking/v1beta1/staking.js\";\nimport {\n Tx,\n} from \"cosmjs-types/cosmos/tx/v1beta1/tx.js\";\nimport Fastify, {\n FastifyInstance,\n} from \"fastify\";\nimport {\n chain,\n} from \"stream-chain\";\nimport Parser from \"stream-json\";\nimport Pick from \"stream-json/filters/Pick.js\";\nimport StreamArray from \"stream-json/streamers/StreamArray.js\";\nimport StreamValues from \"stream-json/streamers/StreamValues.js\";\nimport Batch from \"stream-json/utils/Batch.js\";\nimport {\n v4 as uuidv4,\n} from \"uuid\";\nimport * as winston from \"winston\";\n\nimport {\n DEFAULT_BATCH_SIZE, DEFAULT_HEALTH_CHECK_PORT, DEFAULT_POLLING_INTERVAL_MS, DEFAULT_START_HEIGHT,\n GENESIS_BATCH_SIZE, PAGINATION_LIMITS, PERIODIC_INTERVALS, QUEUE_DEQUEUE_TIMEOUT_MS, RPC_TIMEOUT_MS,\n} from \"../constants.js\";\nimport {\n EclesiaEmitter,\n} from \"../emitter/index.js\";\nimport {\n IndexerMetrics,\n} from \"../metrics/index.js\";\nimport {\n CircularBuffer,\n} from \"../promise-queue/index.js\";\nimport {\n BlockQueue, EcleciaIndexerConfig, EmitFunc, MinimalBlockQueue,\n UUIDEvent, WithHeightAndUUID,\n} from \"../types/index.js\";\nimport {\n decodeAttr,\n} from \"../utils/index.js\";\nimport {\n validateFilePath, validatePort, validatePositiveInteger, validateUrl,\n} from \"../validation/index.js\";\n\n/** Default configuration for the Eclesia indexer */\nexport const defaultIndexerConfig = {\n startHeight: DEFAULT_START_HEIGHT, // Start indexing from block 1\n batchSize: DEFAULT_BATCH_SIZE, // Process blocks in batches of 500\n modules: [], // No modules enabled by default\n getNextHeight: () => DEFAULT_START_HEIGHT, // Default height retrieval function\n logLevel: \"info\" as EcleciaIndexerConfig[\"logLevel\"], // Default log level\n usePolling: false, // Use WebSocket subscription by default\n pollingInterval: DEFAULT_POLLING_INTERVAL_MS, // Poll every 5 seconds when polling enabled\n shouldProcessGenesis: () => false, // Skip genesis processing by default\n minimal: true, // Use minimal indexing by default\n healthCheckPort: DEFAULT_HEALTH_CHECK_PORT, // Default health check port\n enablePrometheus: false, // Disable Prometheus metrics server by default\n prometheusPort: 9090, // Default Prometheus metrics server port\n init: () => Promise.resolve(), // No-op initialization function\n beginTransaction: () => Promise.resolve(), // No-op transaction begin function\n endTransaction: (_status: boolean) => Promise.resolve(), // No-op transaction end function\n};\n\n/**\n * Core blockchain indexer that connects to Tendermint RPC and processes blocks\n * Extends EclesiaEmitter to provide event-driven architecture for modules\n */\nexport class EcleciaIndexer extends EclesiaEmitter {\n /** Indexer configuration settings */\n public config: EcleciaIndexerConfig;\n\n /** Fastify HTTP server for health checks */\n private fastify: FastifyInstance;\n\n /** Prometheus HTTP server instance */\n private prometheusServer: FastifyInstance | null = null;\n\n /** Queue for managing block processing pipeline */\n private blockQueue: BlockQueue;\n\n /** Latest block height from the chain */\n private latestHeight!: number;\n\n /** Next block height to process */\n private heightToProcess!: number;\n\n /** Whether the indexer has been initialized */\n private initialized = false;\n\n /** Prometheus metrics server instance */\n public prometheus: IndexerMetrics | null = null;\n\n /** Number of retry attempts for error recovery */\n private retryCount = 0;\n\n /** CometBFT client for ad-hoc queries */\n public client!: CometClient;\n\n /** CometBFT client for block and validator queries */\n public blockClient!: CometClient;\n\n /** Winston logger instance */\n public log: winston.Logger;\n\n /** Flag indicating if indexer should attempt recovery */\n private tryToRecover: boolean = false;\n\n /** Health check status for monitoring */\n private healthCheck = {\n status: \"CONNECTING\",\n };\n\n /** WebSocket subscription for new block notifications */\n private subscription: ReturnType<CometClient[\"subscribeNewBlock\"]> | null = null;\n\n /**\n * Creates a new Eclesia indexer instance\n * @param config - Indexer configuration options\n */\n constructor(config: EcleciaIndexerConfig) {\n super();\n\n // Validate required configuration\n validateUrl(config.rpcUrl, \"rpcUrl\");\n validatePositiveInteger(config.batchSize, \"batchSize\");\n\n // Validate optional genesis path if processing genesis\n if (config.genesisPath) {\n validateFilePath(config.genesisPath, \"genesisPath\");\n }\n\n // Validate health check port if provided\n if (config.healthCheckPort !== undefined) {\n validatePort(config.healthCheckPort, \"healthCheckPort\");\n }\n\n // Validate start height if provided\n if (config.startHeight !== undefined) {\n validatePositiveInteger(config.startHeight, \"startHeight\");\n }\n\n // Validate polling interval if provided\n if (config.pollingInterval !== undefined) {\n validatePositiveInteger(config.pollingInterval, \"pollingInterval\");\n }\n\n this.config = {\n ...defaultIndexerConfig,\n ...config,\n };\n\n // Initialize logger first so it can be used by queue error handler\n const {\n printf,\n } = winston.format;\n\n const eclesiaFormat = printf(({\n level, message, timestamp,\n }) => {\n return `${timestamp} [${level.toUpperCase()}]:\\t${message}`;\n });\n this.log = winston.createLogger({\n level: this.config.logLevel,\n defaultMeta: {\n service: \"Eclesia Indexer\",\n },\n transports: [\n new winston.transports.File({\n filename: \"error.log\",\n level: \"error\",\n }),\n new winston.transports.File({\n filename: \"combined.log\",\n }),\n new winston.transports.Console({\n format: winston.format.combine(winston.format.splat(),\n winston.format.timestamp(),\n eclesiaFormat,\n winston.format.colorize({\n all: true,\n })),\n }),\n ],\n });\n\n // Initialize block queue based on minimal or full indexing mode\n // Pass error handler that uses the logger\n const queueErrorHandler = (e: unknown) => {\n this.prometheus?.recordError(\"block_queue\");\n this.log.error(\"Error enqueueing block data: \" + e);\n };\n\n if (this.config.minimal) {\n // Minimal mode: only store block and block results\n this.blockQueue = new CircularBuffer<[BlockResponse, BlockResultsResponse]>(this.config.batchSize, queueErrorHandler);\n }\n else {\n // Full mode: also store validator information\n this.blockQueue = new CircularBuffer<[BlockResponse, BlockResultsResponse, Uint8Array]>(this.config.batchSize, queueErrorHandler);\n }\n if (this.config.enablePrometheus) {\n this.prometheus = new IndexerMetrics();\n this.prometheusServer = Fastify({\n logger: false,\n });\n this.prometheusServer.get(\"/metrics\",\n async (_req, res) => {\n res.header(\"Content-Type\", this.prometheus!.registry.contentType);\n res.send(await this.prometheus!.getMetrics());\n },\n );\n this.prometheusServer.listen({\n port: this.config.prometheusPort,\n host: \"0.0.0.0\",\n },\n (err) => {\n if (err) {\n this.log.error(err);\n this.prometheus?.recordError(\"metrics_server\");\n this.emit(\"fatal-error\", {\n error: err,\n message: \"Failed to start metrics server\",\n });\n }\n });\n }\n this.fastify = Fastify({\n logger: false,\n });\n this.on(\"_unhandled\",\n (msg) => {\n if (msg.uuid) {\n this.log.verbose(\"Unhandled event: \" + msg.type);\n this.emit(\"uuid\",\n {\n status: true,\n uuid: msg.uuid,\n });\n }\n });\n this.fastify.get(\"/health\",\n async (_request, reply) => {\n const code = this.healthCheck.status == \"OK\"\n ? 200\n : 503;\n reply.code(code).send(this.healthCheck);\n });\n const healthPort = this.config.healthCheckPort\n ?? (process.env.HEALTH_CHECK_PORT ? parseInt(process.env.HEALTH_CHECK_PORT, 10) : 8080);\n this.fastify.listen({\n port: healthPort,\n host: \"0.0.0.0\",\n },\n (err) => {\n if (err) {\n this.log.error(err);\n this.prometheus?.recordError(\"health_check_server\");\n this.emit(\"fatal-error\", {\n error: err,\n message: \"Failed to start health check server\",\n });\n }\n });\n }\n\n private setStatus(status: string) {\n this.healthCheck.status = status;\n }\n\n private blockListener = {\n next: (data: {\n header: {\n height: number\n }\n }) => {\n this.newBlockReceived(data.header.height);\n },\n };\n\n private isMinimal(_blockqueue: BlockQueue): _blockqueue is MinimalBlockQueue {\n if (this.config.minimal) {\n return true;\n }\n else {\n return false;\n }\n }\n\n public async connect() {\n try {\n if (this.client && this.tryToRecover) {\n this.log.verbose(\"Recover from error. Attempting to disconnect from RPC\");\n this.client.disconnect();\n this.blockClient.disconnect();\n this.log.verbose(\"Disconnected from RPC\");\n }\n this.client = await connectComet(this.config.rpcUrl);\n this.log.info(\"Connected to RPC for ad hoc queries\");\n\n this.blockClient = await connectComet(this.config.rpcUrl);\n this.log.info(\"Connected to RPC for block & validator info\");\n\n return true;\n }\n catch (error) {\n this.log.error(error);\n this.prometheus?.recordError(\"connect_rpc_error\");\n this.tryToRecover = true;\n return false;\n }\n }\n\n public async start() {\n if (this.blockQueue) {\n this.blockQueue.clear();\n this.log.verbose(\"Starting, clearing block queue\");\n }\n if (!this.initialized) {\n try {\n if (this.config.init) {\n await this.config.init();\n }\n }\n catch (e) {\n this.log.error(\"Failed to initialize indexer: \" + e);\n\n this.prometheus?.recordError(\"init_error\");\n this.setStatus(\"FAILED\");\n throw e;\n }\n if (await this.config.shouldProcessGenesis()) {\n try {\n if (this.config.genesisPath) {\n await this.parseGenesis();\n }\n }\n catch (e) {\n this.log.error(\"Failed to parse genesis: \" + e);\n\n this.prometheus?.recordError(\"genesis_error\");\n this.setStatus(\"FAILED\");\n throw e;\n }\n }\n this.initialized = true;\n }\n try {\n await this.connect();\n if (!this.config.usePolling && this.subscription) {\n this.subscription.removeListener(this.blockListener);\n this.subscription = null;\n this.log.verbose(\"Removed existing block listener and subscription\");\n }\n if (!this.config.usePolling) {\n this.subscription = this.client.subscribeNewBlock\n ? this.client.subscribeNewBlock()\n : null;\n }\n const status = await this.client.status();\n this.latestHeight = status.syncInfo.latestBlockHeight;\n this.log.info(\"Current chain height: \" + this.latestHeight);\n\n this.heightToProcess = await this.config.getNextHeight();\n if (this.config.usePolling) {\n this.pollForBlock();\n }\n else {\n if (this.subscription) {\n this.subscription.addListener(this.blockListener);\n }\n else {\n this.prometheus?.recordError(\"subscription_error\");\n throw new Error(\"Could not subscribe to new blocks\");\n }\n }\n }\n catch (e) {\n this.log.error(\"Failed to set up block listening: \" + e);\n this.prometheus?.recordError(\"block_listening_error\");\n this.setStatus(\"FAILED\");\n throw e;\n }\n\n this.tryToRecover = false;\n this.fetcher().catch((e) => {\n this.setStatus(\"FAILED\");\n\n this.prometheus?.recordError(\"fetching_error\");\n throw new Error(\"Error in fetching service: \" + e);\n });\n\n const hrTime = process.hrtime();\n let ms = hrTime[0] * 1000000 + hrTime[1] / 1000;\n while (this.blockQueue.size() > 0 && !this.tryToRecover) {\n if (this.config.enablePrometheus) {\n this.prometheus!.updateRetryCount(this.retryCount);\n }\n // await the dequeued promise is essentially awaiting fetched data for that block\n try {\n if (this.tryToRecover) {\n throw new Error(\"Exiting processing loop. Attempting to recover indexer\");\n }\n // Index block inside a db transaction to ensure data consistency\n await this.config.beginTransaction();\n this.log.silly(\"Started db tx\");\n let height, timestamp;\n if (this.isMinimal(this.blockQueue)) {\n const timeoutPromise: ReturnType<typeof this.blockQueue.dequeue> = new Promise((resolve, reject) => {\n setTimeout(reject, QUEUE_DEQUEUE_TIMEOUT_MS, []);\n });\n const toProcess = await Promise.race([this.blockQueue.dequeue(), timeoutPromise]);\n this.log.silly(\"Retrieved block data\");\n if (!toProcess || !toProcess[0] || !toProcess[1]) {\n this.prometheus?.recordError(\"rpc_error\");\n throw new Error(\"Could not fetch block\");\n }\n height = toProcess[0].block.header.height;\n timestamp = toRfc3339WithNanoseconds(toProcess[0].block.header.time);\n await this.processBlock(toProcess[0],\n toProcess[1]);\n }\n else {\n const timeoutPromise: ReturnType<typeof this.blockQueue.dequeue> = new Promise((resolve, reject) => {\n setTimeout(reject, QUEUE_DEQUEUE_TIMEOUT_MS, []);\n });\n const toProcess = await Promise.race([this.blockQueue.dequeue(), timeoutPromise]);\n this.log.silly(\"Retrieved block data\");\n if (!toProcess || !toProcess[0] || !toProcess[1] || !toProcess[2]) {\n this.prometheus?.recordError(\"rpc_error\");\n throw new Error(\"Could not fetch block\");\n }\n\n this.log.silly(\"Decoded block\");\n height = toProcess[0].block.header.height;\n timestamp = toRfc3339WithNanoseconds(toProcess[0].block.header.time);\n await this.processBlock(toProcess[0],\n toProcess[1],\n QueryValidatorsResponse.decode(toProcess[2]).validators);\n }\n // Emit events to trigger periodic operations every 50, 100 and 1000 blocks\n if (height % PERIODIC_INTERVALS.LARGE == 0) {\n const hrTime = process.hrtime();\n const newms = hrTime[0] * 1000000 + hrTime[1] / 1000;\n const duration = newms - ms;\n ms = newms;\n const rate = 1000000000 / duration;\n this.log.info(\"Processing:\" + rate.toFixed(2) + \"blocks/sec\");\n await this.asyncEmit(\"periodic/1000\",\n {\n value: null,\n height,\n timestamp,\n });\n }\n if (height % PERIODIC_INTERVALS.MEDIUM == 0) {\n await this.asyncEmit(\"periodic/100\",\n {\n value: null,\n height,\n timestamp,\n });\n }\n if (height % PERIODIC_INTERVALS.SMALL == 0) {\n await this.asyncEmit(\"periodic/50\",\n {\n value: null,\n height,\n timestamp,\n });\n }\n this.log.silly(\"Handled periodic events\");\n\n await this.config.endTransaction(true);\n\n this.log.silly(\"Committed db tx\");\n }\n catch (e) {\n this.prometheus?.recordError(\"block_processing_error\");\n this.log.error(\"\" + e);\n this.setStatus(\"FAILED\");\n try {\n await this.config.endTransaction(false);\n }\n catch (dbe) {\n this.prometheus?.recordError(\"database\");\n this.log.error(\"Error ending transaction. Must be a DB error: \" + dbe);\n }\n this.tryToRecover = true;\n this.retryCount++;\n break;\n }\n this.retryCount = 0;\n this.setStatus(\"OK\");\n }\n if (this.retryCount < 3) {\n this.log.debug(\"Indexer retryCount: \" + this.retryCount);\n this.log.info(\"Indexer is restarting\");\n setTimeout(() => this.start(),\n this.retryCount * 5000);\n }\n else {\n this.log.info(\"Indexer failed too many times. Exiting.\");\n this.emit(\"fatal-error\", {\n error: new Error(\"Max retry attempts exceeded\"),\n message: \"Indexer failed too many times\",\n retryCount: this.retryCount,\n });\n }\n }\n\n public asyncEmit: EmitFunc<keyof WithHeightAndUUID<EventMap>> = async (\n type,\n event,\n ) => {\n event.uuid = uuidv4();\n\n /*\n * More than 1 listener can be registered for an event type\n * Fortunately these are all set up during module init() so we have a consistent count\n * so we can count responses to resolve when complete\n * values are irrelevant as promise resolution is only used for flow control\n */\n let listenerCount = this.handled.get(type);\n if (!listenerCount) {\n // Setting listenerCount to 1 (the unhandled listener)\n listenerCount = 1;\n }\n let listenersResponded = 0;\n const prom = new Promise<void>((resolve, reject) => {\n const returnFunc = (ev: UUIDEvent) => {\n if (ev.uuid == event.uuid) {\n if (ev.status) {\n listenersResponded++;\n if (listenersResponded == listenerCount) {\n // All listeners have done their thing so we can remove listener, resolve and continue execution\n this.off(\"uuid\",\n returnFunc);\n resolve();\n }\n }\n else {\n // At least 1 listener is reporting an error. Reject and handle exception at the original asyncEmit location\n reject(ev.error);\n }\n }\n };\n this.on(\"uuid\",\n returnFunc);\n });\n this.emit(type,\n event);\n\n return prom;\n };\n\n private async processBlock(block: BlockResponse, block_results: BlockResultsResponse | BlockResultsResponse38, validators?: Validator[]) {\n let processStart: [number, number] = [0, 0];\n if (this.config.logLevel == \"silly\") {\n processStart = process.hrtime();\n }\n let endTimer;\n if (this.config.enablePrometheus) {\n endTimer = this.prometheus!.timeBlockProcessing();\n }\n const height = block.block.header.height;\n this.log.debug(\"Processing block: %d\",\n height);\n\n // Initialize height & timestamp to be used for this block-processing run\n const timestamp = toRfc3339WithNanoseconds(block.block.header.time);\n\n // Use & await asyncEmit to ensure db insertions in order\n\n /*\n * Emit block information to any interested modules.\n * Primarily the required block module listens to this\n */\n await this.asyncEmit(\"block\",\n {\n value: {\n block,\n block_results,\n },\n height,\n timestamp,\n });\n this.log.silly(\"Modules handled block event\");\n\n let beginBlockEvents: readonly Event[] | readonly Event38[];\n let endBlockEvents: readonly Event[] | readonly Event38[];\n if ((block_results as BlockResultsResponse38).finalizeBlockEvents) {\n beginBlockEvents = (block_results as BlockResultsResponse38).finalizeBlockEvents.filter(x => x.attributes.find(a => decodeAttr(a.key) == \"mode\" && decodeAttr(a.value) == \"begin_block\")) as readonly Event38[];\n endBlockEvents = (block_results as BlockResultsResponse38).finalizeBlockEvents.filter(x => x.attributes.find(a => decodeAttr(a.key) == \"mode\" && decodeAttr(a.value) == \"end_block\")) as readonly Event38[];\n }\n else {\n beginBlockEvents = (block_results as BlockResultsResponse).beginBlockEvents;\n endBlockEvents = (block_results as BlockResultsResponse).endBlockEvents;\n }\n // Deal with begin_block events first\n await this.asyncEmit(\"begin_block\",\n {\n value: {\n events: beginBlockEvents!,\n validators,\n },\n height,\n timestamp,\n });\n\n this.log.silly(\"Modules handled begin_block events\");\n\n // Then individual tx_events\n await this.asyncEmit(\"tx_events\",\n {\n value: block_results.results,\n height,\n timestamp,\n });\n this.log.silly(\"Modules handled tx events\");\n\n // Emit details and result for each tx msg separately\n for (let t = 0; t < block.block.txs.length; t++) {\n const tx = Tx.decode(block.block.txs[t]);\n\n const result = block_results.results[t].code;\n const txlog = block_results.results[t].log;\n\n if (result != 0) {\n // Tx failed. Ignore\n continue;\n }\n if (tx.body && tx.body.memo != \"\") {\n const txHash = createHash(\"sha256\").update(block.block.txs[t])\n .digest(\"hex\");\n await this.asyncEmit(\"tx_memo\",\n {\n value: {\n txHash,\n txBody: tx.body,\n },\n height,\n timestamp,\n });\n }\n // parsing log rather than using events directly in order to have msg_index available to filter appropriate events for each msg\n let events: Array<{\n msg_index?: number\n events: (Event | Event38)[]\n }> = txlog\n ? JSON.parse(txlog)\n : [];\n if (events.length == 0) {\n const eventsToAdd: typeof events = [];\n this.log.silly(\"No events found in tx log. Parsing events for msg_index\");\n for (let m = 0; m < block_results.results[t].events.length; m++) {\n if (block_results.results[t].events[m].attributes.find(a => decodeAttr(a.key) == \"msg_index\")) {\n const mi = decodeAttr(block_results.results[t].events[m].attributes.find(a => decodeAttr(a.key) == \"msg_index\")?.value ?? \"\");\n if (mi != \"\") {\n const miNum = parseInt(mi);\n let ev = eventsToAdd.find(x => x.msg_index == miNum);\n if (!ev) {\n ev = {\n msg_index: miNum,\n events: [block_results.results[t].events[m]],\n };\n eventsToAdd.push(ev);\n }\n else {\n ev.events.push(block_results.results[t].events[m] as Event);\n }\n }\n }\n }\n events = events.concat(eventsToAdd);\n }\n const msgs = tx.body?.messages;\n\n if (msgs) {\n for (let i = 0; i < msgs.length; i++) {\n this.log.silly(\"Indexer broadcasting msg for handling: \" + msgs[i].typeUrl);\n const msgevents\n = msgs.length > 1\n ? events.find(x => x.msg_index == i)?.events\n : events[0].events;\n await this.asyncEmit(msgs[i].typeUrl as never,\n {\n value: {\n tx: msgs[i].value as never,\n events: msgevents,\n } as never,\n height,\n timestamp,\n });\n if (msgs[i].typeUrl == \"/cosmos.authz.v1beta1.MsgExec\") {\n const authzMsgs = MsgExec.decode(msgs[i].value).msgs;\n if (authzMsgs) {\n for (let r = 0; r < authzMsgs.length; r++) {\n this.log.silly(\"Indexer broadcasting msg for handling: \" + authzMsgs[r].typeUrl);\n const authzMsgEvents = msgevents?.reduce((events, evt) => {\n if (evt.attributes.filter(x => decodeAttr(x.key) == \"authz_msg_index\" && decodeAttr(x.value) == \"\" + r).length > 0) {\n events.push(evt);\n }\n return events;\n },\n [] as (Event | Event38)[]);\n await this.asyncEmit(authzMsgs[r].typeUrl as never,\n {\n value: {\n tx: authzMsgs[r].value as never,\n events: authzMsgEvents,\n } as never,\n height,\n timestamp,\n });\n }\n }\n }\n }\n }\n }\n this.log.silly(\"Modules handled msg events\");\n if (this.config.enablePrometheus) {\n this.prometheus!.recordTransactions(block.block.txs.length);\n }\n // Then deal with end_block events\n await this.asyncEmit(\"end_block\",\n {\n value: endBlockEvents!,\n height,\n timestamp,\n });\n this.log.silly(\"Modules handled end_block events\");\n if (this.config.logLevel == \"silly\") {\n const processEnd = process.hrtime(processStart);\n const processTime = processEnd[0] * 1000 + processEnd[1] / 1000000;\n this.log.silly(\"Processed block %d in %d ms\",\n height,\n processTime.toFixed(2));\n }\n\n if (this.config.enablePrometheus) {\n endTimer!();\n }\n if (this.config.enablePrometheus) {\n this.prometheus!.updateBlockMetrics(height, this.latestHeight, this.blockQueue.size());\n }\n }\n\n private async fetcher() {\n for (let i = this.heightToProcess; i <= this.latestHeight; i++) {\n this.log.debug(\"Fetching: \" + i);\n if (this.tryToRecover) {\n this.log.verbose(\"Exiting fetcher loop. Attempting to recover indexer\");\n break;\n }\n try {\n if (this.isMinimal(this.blockQueue)) {\n const timeoutPromise: Promise<[BlockResponse, BlockResultsResponse]> = new Promise((resolve, reject) => {\n setTimeout(reject,\n RPC_TIMEOUT_MS,\n false);\n });\n const toIndex = Promise.race([Promise.all([this.blockClient.block(i) as Promise<BlockResponse>, this.blockClient.blockResults(i) as Promise<BlockResultsResponse>]), timeoutPromise]).catch((e) => {\n this.log.error(\"Error fetching block: \" + i + \" : \" + e);\n this.tryToRecover = true;\n return Promise.resolve([]);\n }) as Promise<[BlockResponse, BlockResultsResponse]>;\n this.blockQueue.enqueue(toIndex);\n }\n else {\n const timeoutPromise: Promise<[BlockResponse, BlockResultsResponse, Uint8Array]> = new Promise((resolve, reject) => {\n setTimeout(reject,\n RPC_TIMEOUT_MS,\n false);\n });\n const q = QueryValidatorsRequest.fromPartial({\n pagination: {\n limit: PAGINATION_LIMITS.VALIDATORS,\n },\n });\n const vals = QueryValidatorsRequest.encode(q).finish();\n const toIndex = Promise.race([\n Promise.all([\n this.blockClient.block(i) as Promise<BlockResponse>,\n this.blockClient.blockResults(i) as Promise<BlockResultsResponse>,\n this.callABCI(\"/cosmos.staking.v1beta1.Query/Validators\",\n vals,\n i,\n false),\n ]),\n timeoutPromise,\n ]).catch((e) => {\n this.log.error(\"Error fetching block: \" + i + \" : \" + e);\n this.tryToRecover = true;\n return Promise.resolve([]);\n }) as Promise<[BlockResponse, BlockResultsResponse, Uint8Array]>;\n this.blockQueue.enqueue(toIndex);\n }\n await this.blockQueue.continue();\n if (this.tryToRecover) {\n this.retryCount++;\n throw new Error(\"RPC not responding\");\n }\n }\n catch (e) {\n this.log.error(e);\n break;\n }\n }\n if (!this.tryToRecover) {\n this.blockQueue.setSynced();\n this.log.info(\"Synced to latest height\");\n }\n }\n\n public async callABCI(path: string, data: Uint8Array, height?: number, adHoc: boolean = true): Promise<Uint8Array> {\n try {\n const endTimer = this.prometheus?.timeRpcCall(path) ?? void 0;\n const abciq = await\n (adHoc\n ? this.client\n : this.blockClient).abciQuery({\n path,\n data,\n height: height,\n });\n endTimer?.();\n if (abciq) {\n return abciq.value;\n }\n else {\n this.tryToRecover = true;\n this.setStatus(\"FAILED\");\n this.prometheus?.recordError(\"abci_query_error\");\n throw new Error(\"RPC not responding. Query at: \" + path);\n }\n }\n catch (_e) {\n this.tryToRecover = true;\n this.setStatus(\"FAILED\");\n this.retryCount++;\n throw new Error(\"RPC not responding. Query at: \" + path);\n }\n }\n\n private newBlockReceived(height: number): void {\n this.log.info(\"Received new block: %d\",\n height);\n if (height == this.latestHeight) {\n return;\n }\n // If we are synced, add to end of queue\n if (this.blockQueue.synced && !this.tryToRecover) {\n this.latestHeight = height;\n if (this.blockQueue.size() + 1 == this.config.batchSize) {\n this.prometheus?.recordError(\"block_queue_full\");\n this.log.error(\"Block queue is full. Cannot add new block\");\n this.tryToRecover = true;\n this.retryCount++;\n return;\n }\n try {\n if (this.isMinimal(this.blockQueue)) {\n this.blockQueue.enqueue(Promise.all([this.client.block(height) as Promise<BlockResponse>, this.client.blockResults(height) as Promise<BlockResultsResponse>]).catch((e) => {\n this.log.error(\"Error fetching block: \" + height + \" : \" + e);\n\n return Promise.resolve([]);\n }) as Promise<[BlockResponse, BlockResultsResponse]>);\n }\n else {\n const q = QueryValidatorsRequest.fromPartial({\n pagination: {\n limit: 1000n,\n },\n });\n const vals = QueryValidatorsRequest.encode(q).finish();\n this.blockQueue.enqueue(Promise.all([\n this.client.block(height) as Promise<BlockResponse>,\n this.client.blockResults(height) as Promise<BlockResultsResponse>,\n this.callABCI(\"/cosmos.staking.v1beta1.Query/Validators\",\n vals,\n height,\n false),\n ]).catch((e) => {\n this.log.error(\"Error fetching block: \" + height + \" : \" + e);\n return Promise.resolve([]);\n }) as Promise<[BlockResponse, BlockResultsResponse, Uint8Array]>);\n }\n }\n catch (e) {\n this.log.error(\"\" + e);\n }\n }\n else {\n this.latestHeight = height;\n }\n }\n\n private async pollForBlock() {\n try {\n const status = await this.client.status();\n if (status.syncInfo.latestBlockHeight > this.latestHeight) {\n while (this.latestHeight < status.syncInfo.latestBlockHeight) {\n this.newBlockReceived(this.latestHeight + 1);\n }\n }\n setTimeout(() => {\n this.pollForBlock();\n },\n this.config.pollingInterval);\n }\n catch (e) {\n this.log.error(\"Error polling for new block: \" + e);\n this.tryToRecover = true;\n this.retryCount++;\n }\n }\n\n private readGenesis(): Parser.Parser {\n if (this.config.genesisPath) {\n return fs.createReadStream(this.config.genesisPath).pipe(Parser.parser());\n }\n else {\n throw new Error(\"Genesis path not set\");\n }\n }\n\n private async setArrayReader(path: string, processor: (chunk: unknown) => Promise<void>): Promise<boolean> {\n const readPromise = new Promise<boolean>((resolve, reject) => {\n try {\n const filters = path.split(\".\");\n const pickers = filters.map(filter => Pick.pick({\n filter,\n }));\n let counter = 0;\n let chunkCounter = 0;\n\n // Wrapper processor that handles transaction chunking\n const chunkProcessor = async (data: unknown) => {\n chunkCounter++;\n this.log.debug(`Processing genesis chunk ${chunkCounter}`);\n\n await processor(data);\n\n // Commit and restart transaction every 5 chunks (5000 entries)\n // This prevents timeout on large genesis files\n if (chunkCounter % 5 === 0) {\n this.log.debug(`Committing transaction after chunk ${chunkCounter}`);\n await this.config.endTransaction(true);\n await this.config.beginTransaction();\n }\n };\n\n chain([\n this.readGenesis(),\n ...pickers,\n StreamArray.streamArray(),\n Batch.batch({\n batchSize: GENESIS_BATCH_SIZE,\n }),\n chunkProcessor,\n ])\n .on(\"data\",\n (data) => {\n if (data && Array.isArray(data)) {\n counter = counter + data.length;\n }\n })\n .on(\"end\",\n () => {\n this.log.info(`Processed ${counter} entries in ${chunkCounter} chunks`);\n resolve(true);\n });\n }\n catch (_e) {\n this.log.verbose(\"Error in setArrayReader: \" + _e);\n reject();\n }\n });\n\n return readPromise;\n }\n\n private async setValueReader(path: string, processor: (chunk: unknown) => Promise<void>): Promise<boolean> {\n const readPromise = new Promise<boolean>((resolve, reject) => {\n try {\n const filters = path.split(\".\");\n const pickers = filters.map(filter => Pick.pick({\n filter,\n }));\n\n let counter = 0;\n chain([this.readGenesis(), ...pickers, StreamValues.streamValues(), processor])\n .on(\"data\",\n (_data) => {\n counter++;\n })\n .on(\"end\",\n () => {\n this.log.info(`Processed ${counter} entries`);\n resolve(true);\n });\n }\n catch (_e) {\n reject();\n }\n });\n\n return readPromise;\n }\n\n private async parseGenesis() {\n this.log.info(\"Parsing genesis\");\n await this.config.beginTransaction();\n try {\n this.log.info(\"Starting genesis import\");\n this.log.debug(\"Importing genesis file...\");\n\n for (const [key, _value] of this.handled) {\n if (key.startsWith(\"genesis/\")) {\n const genesisEntry = key.split(\"/\");\n\n this.log.verbose(\"Importing \" + key + \"...\");\n if (genesisEntry[1] == \"array\") {\n await this.setArrayReader(genesisEntry[2],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async (data: any) => {\n await this.asyncEmit(key as never,\n {\n value: data.map((x: {\n value: never\n }) => x.value),\n } as never);\n return data;\n });\n }\n else {\n await this.setValueReader(genesisEntry[2],\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async (data: any) => {\n await this.asyncEmit(key as never,\n {\n value: data.value,\n } as never);\n return data;\n });\n }\n }\n }\n\n this.log.info(\"Importing gen TXs...\");\n\n await this.setArrayReader(\"app_state.genutil.gen_txs\",\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async (data: any) => {\n for (let j = 0; j < data.length; j++) {\n const gentx = data[j].value;\n for (let i = 0; i < gentx.body.messages.length; i++) {\n const msg = gentx.body.messages[i];\n await this.asyncEmit((\"gentx\" + msg[\"@type\"]) as never,\n {\n value: msg,\n } as never);\n }\n }\n return data;\n });\n await this.config.endTransaction(true);\n\n this.log.info(\"Finished importing\");\n }\n catch (e) {\n try {\n await this.config.endTransaction(false);\n }\n catch (dbe) {\n this.prometheus?.recordError(\"database_error\");\n this.log.error(\"Error ending transaction. Must be a DB error: \" + dbe);\n }\n this.log.error(\"Failed to import genesis\");\n throw e;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,MAAa,uBAAuB;CAClC,aAAa;CACb,WAAW;CACX,SAAS,EAAE;CACX,qBAAqB;CACrB,UAAU;CACV,YAAY;CACZ,iBAAiB;CACjB,4BAA4B;CAC5B,SAAS;CACT,iBAAiB;CACjB,kBAAkB;CAClB,gBAAgB;CAChB,YAAY,QAAQ,SAAS;CAC7B,wBAAwB,QAAQ,SAAS;CACzC,iBAAiB,YAAqB,QAAQ,SAAS;CACxD;;;;;AAMD,IAAa,iBAAb,cAAoC,eAAe;;;;;CAoDjD,YAAY,QAA8B;AACxC,SAAO;OA7CD,mBAA2C;OAY3C,cAAc;OAGf,aAAoC;OAGnC,aAAa;OAYb,eAAwB;OAGxB,cAAc,EACpB,QAAQ,cACT;OAGO,eAAoE;OA4JpE,gBAAgB,EACtB,OAAO,SAID;AACJ,QAAK,iBAAiB,KAAK,OAAO,OAAO;KAE5C;OAyOM,YAAyD,OAC9D,MACA,UACG;AACH,SAAM,OAAOA,IAAQ;GAQrB,IAAI,gBAAgB,KAAK,QAAQ,IAAI,KAAK;AAC1C,OAAI,CAAC,cAEH,iBAAgB;GAElB,IAAI,qBAAqB;GACzB,MAAM,OAAO,IAAI,SAAe,SAAS,WAAW;IAClD,MAAM,cAAc,OA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A4Od;;4BAzOM;;kCAGM;;uBAGX;;kCAGW;;;;;;;;;;;;;;;;;;;;;;;mCA8IpB,QAAA;;;;;;;;;;;;yCAoBO,QAAA;;;;;;;;;;;;kDAsBS,QAAA;;;;;;;;;;;;;;;;;;;;;;;gBAwCf"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/metrics/index.ts"],"sourcesContent":["/**\n * Prometheus metrics for monitoring indexer performance and health\n * Exposes metrics for blocks indexed, queue depth, errors, and processing times\n */\n\nimport {\n collectDefaultMetrics, Counter, Gauge, Histogram, Registry,\n} from \"prom-client\";\n\n/** Prometheus metrics registry */\nexport class IndexerMetrics {\n /** Prometheus registry instance */\n public readonly registry: Registry;\n\n /** Counter for total blocks indexed */\n public readonly blocksIndexed: Counter;\n\n /** Gauge for current block height */\n public readonly currentHeight: Gauge;\n\n /** Gauge for latest chain block height */\n public readonly latestHeight: Gauge;\n\n /** Gauge for blocks behind chain tip */\n public readonly blocksBehind: Gauge;\n\n /** Gauge for block queue depth */\n public readonly queueDepth: Gauge;\n\n /** Counter for total errors */\n public readonly errors: Counter;\n\n /** Counter for RPC errors */\n public readonly rpcErrors: Counter;\n\n /** Counter for database errors */\n public readonly databaseErrors: Counter;\n\n /** Histogram for block processing duration */\n public readonly blockProcessingDuration: Histogram;\n\n /** Histogram for RPC call duration */\n public readonly rpcCallDuration: Histogram;\n\n /** Histogram for database query duration */\n public readonly databaseQueryDuration: Histogram;\n\n /** Gauge for retry count */\n public readonly retryCount: Gauge;\n\n /** Counter for total transactions processed */\n public readonly transactionsProcessed: Counter;\n\n constructor() {\n this.registry = new Registry();\n\n // Collect default Node.js metrics (memory, CPU, etc.)\n collectDefaultMetrics({\n register: this.registry,\n });\n\n // Block indexing metrics\n this.blocksIndexed = new Counter({\n name: \"indexer_blocks_indexed_total\",\n help: \"Total number of blocks indexed\",\n registers: [this.registry],\n });\n\n this.currentHeight = new Gauge({\n name: \"indexer_current_height\",\n help: \"Current block height being processed\",\n registers: [this.registry],\n });\n\n this.latestHeight = new Gauge({\n name: \"indexer_latest_chain_height\",\n help: \"Latest block height on the chain\",\n registers: [this.registry],\n });\n\n this.blocksBehind = new Gauge({\n name: \"indexer_blocks_behind\",\n help: \"Number of blocks behind chain tip\",\n registers: [this.registry],\n });\n\n this.queueDepth = new Gauge({\n name: \"indexer_queue_depth\",\n help: \"Current depth of block processing queue\",\n registers: [this.registry],\n });\n\n // Error metrics\n this.errors = new Counter({\n name: \"indexer_errors_total\",\n help: \"Total number of indexer errors\",\n labelNames: [\"type\"],\n registers: [this.registry],\n });\n\n this.rpcErrors = new Counter({\n name: \"indexer_rpc_errors_total\",\n help: \"Total number of RPC errors\",\n registers: [this.registry],\n });\n\n this.databaseErrors = new Counter({\n name: \"indexer_database_errors_total\",\n help: \"Total number of database errors\",\n registers: [this.registry],\n });\n\n // Performance metrics\n this.blockProcessingDuration = new Histogram({\n name: \"indexer_block_processing_duration_seconds\",\n help: \"Time spent processing a single block\",\n buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 2, 5],\n registers: [this.registry],\n });\n\n this.rpcCallDuration = new Histogram({\n name: \"indexer_rpc_call_duration_seconds\",\n help: \"Duration of RPC calls\",\n buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5, 10],\n labelNames: [\"method\"],\n registers: [this.registry],\n });\n\n this.databaseQueryDuration = new Histogram({\n name: \"indexer_database_query_duration_seconds\",\n help: \"Duration of database queries\",\n buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1],\n labelNames: [\"query_type\"],\n registers: [this.registry],\n });\n\n // Operational metrics\n this.retryCount = new Gauge({\n name: \"indexer_retry_count\",\n help: \"Current number of retry attempts\",\n registers: [this.registry],\n });\n\n this.transactionsProcessed = new Counter({\n name: \"indexer_transactions_processed_total\",\n help: \"Total number of transactions processed\",\n registers: [this.registry],\n });\n }\n\n /**\n * Updates block indexing metrics\n * @param currentHeight - Current height being processed\n * @param latestHeight - Latest height on chain\n * @param queueSize - Current queue depth\n */\n updateBlockMetrics(currentHeight: number, latestHeight: number, queueSize: number) {\n this.blocksIndexed.inc();\n this.currentHeight.set(currentHeight);\n this.latestHeight.set(latestHeight);\n this.blocksBehind.set(latestHeight - currentHeight);\n this.queueDepth.set(queueSize);\n }\n\n /**\n * Records an error occurrence\n * @param type - Error type (rpc, database, processing, etc.)\n */\n recordError(type: string) {\n this.errors.inc({\n type,\n });\n\n if (type === \"rpc\") {\n this.rpcErrors.inc();\n }\n else if (type === \"database\") {\n this.databaseErrors.inc();\n }\n }\n\n /**\n * Records block processing duration\n * @param durationSeconds - Duration in seconds\n */\n recordBlockProcessing(durationSeconds: number) {\n this.blockProcessingDuration.observe(durationSeconds);\n }\n\n /**\n * Times a block processing operation\n * @returns End timer function to call when operation completes\n */\n timeBlockProcessing() {\n return this.blockProcessingDuration.startTimer();\n }\n\n /**\n * Records RPC call duration\n * @param method - RPC method name\n * @param durationSeconds - Duration in seconds\n */\n recordRpcCall(method: string, durationSeconds: number) {\n this.rpcCallDuration.observe({\n method,\n }, durationSeconds);\n }\n\n /**\n * Times an RPC call operation\n * @param method - RPC method name\n * @returns End timer function to call when operation completes\n */\n timeRpcCall(method: string) {\n return this.rpcCallDuration.startTimer({\n method,\n });\n }\n\n /**\n * Records database query duration\n * @param queryType - Type of query (select, insert, update, delete, etc.)\n * @param durationSeconds - Duration in seconds\n */\n recordDatabaseQuery(queryType: string, durationSeconds: number) {\n this.databaseQueryDuration.observe({\n query_type: queryType,\n }, durationSeconds);\n }\n\n /**\n * Times a database query operation\n * @param queryType - Type of query (select, insert, update, delete, etc.)\n * @returns End timer function to call when operation completes\n */\n timeDatabaseQuery(queryType: string) {\n return this.databaseQueryDuration.startTimer({\n query_type: queryType,\n });\n }\n\n /**\n * Updates the retry count gauge\n * @param count - Current retry count\n */\n updateRetryCount(count: number) {\n this.retryCount.set(count);\n }\n\n /**\n * Increments the retry count gauge by 1\n */\n incrementRetryCount() {\n this.retryCount.inc();\n }\n\n /**\n * Resets the retry count gauge to 0\n */\n resetRetryCount() {\n this.retryCount.set(0);\n }\n\n /**\n * Records transactions processed\n * @param count - Number of transactions to record (defaults to 1)\n */\n recordTransactions(count: number = 1) {\n this.transactionsProcessed.inc(count);\n }\n\n /**\n * Gets metrics in Prometheus format\n * @returns Prometheus metrics string\n */\n async getMetrics(): Promise<string> {\n return this.registry.metrics();\n }\n}\n"],"mappings":";;;;;;;;AAUA,IAAa,iBAAb,MAA4B;CA2C1B,cAAc;AACZ,OAAK,WAAW,IAAI,UAAU;AAG9B,wBAAsB,EACpB,UAAU,KAAK,UAChB,CAAC;AAGF,OAAK,gBAAgB,IAAI,QAAQ;GAC/B,MAAM;GACN,MAAM;GACN,WAAW,CAAC,KAAK,SAAS;GAC3B,CAAC;AAEF,OAAK,gBAAgB,IAAI,MAAM;GAC7B,MAAM;GACN,MAAM;GACN,WAAW,CAAC,KAAK,SAAS;GAC3B,CAAC;AAEF,OAAK,eAAe,IAAI,MAAM;GAC5B,MAAM;GACN,MAAM;GACN,WAAW,CAAC,KAAK,SAAS;GAC3B,CAAC;AAEF,OAAK,eAAe,IAAI,MAAM;GAC5B,MAAM;GACN,MAAM;GACN,WAAW,CAAC,KAAK,SAAS;GAC3B,CAAC;AAEF,OAAK,aAAa,IAAI,MAAM;GAC1B,MAAM;GACN,MAAM;GACN,WAAW,CAAC,KAAK,SAAS;GAC3B,CAAC;AAGF,OAAK,SAAS,IAAI,QAAQ;GACxB,MAAM;GACN,MAAM;GACN,YAAY,CAAC,OAAO;GACpB,WAAW,CAAC,KAAK,SAAS;GAC3B,CAAC;AAEF,OAAK,YAAY,IAAI,QAAQ;GAC3B,MAAM;GACN,MAAM;GACN,WAAW,CAAC,KAAK,SAAS;GAC3B,CAAC;AAEF,OAAK,iBAAiB,IAAI,QAAQ;GAChC,MAAM;GACN,MAAM;GACN,WAAW,CAAC,KAAK,SAAS;GAC3B,CAAC;AAGF,OAAK,0BAA0B,IA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AAQ,EAC3B,QACD,EAAE,gBAAgB;;;;;;;CAQrB,YAAY,QAAgB;AAC1B,SAAO,KAAK,gBAAgB,WAAW,EACrC,QACD,CAAC;;;;;;;CAQJ,oBAAoB,WAAmB,iBAAyB;AAC9D,OAAK,sBAAsB,QAAQ,EACjC,YAAY,WACb,EAAE,gBAAgB;;;;;;;CAQrB,kBAAkB,WAAmB;AACnC,SAAO,KAAK,sBAAsB,WAAW,EAC3C,YAAY,WACb,CAAC;;;;;;CAOJ,iBAAiB,OAAe;AAC9B,OAAK,WAAW,IAAI,MAAM;;;;;CAM5B,sBAAsB;AACpB,OAAK,WAAW,KAAK;;;;;CAMvB,kBAAkB;AAChB,OAAK,WAAW,IAAI,EAAE;;;;;;CAOxB,mBAAmB,QAAgB,GAAG;AACpC,OAAK,sBAAsB,IAAI,MAAM;;;;;;CAOvC,MAAM,aAA8B;AAClC,SAAO,KAAK,SAAS,SAAS"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/promise-queue/index.ts"],"sourcesContent":[],"mappings":";;AAMA;;;;;AAwE2B,cAxEd,YAwEc,CAAA,CAAA,CAAA,CAAA;;UAGjB,YAAA;EAAA;EA2BG,QAAA,KAAA;EAAc;UAsDX,QAAA;;UAAI,OAAA;;QA2BX,EAAA,OAAA;;EAkCC,QAAA,SAAA;;;;gBAvLM,IAAI,YAAY;;aAsCb,QAAQ;cAGjB;;;;;;;;;;cA2BG;;;;;;;;;;;;;;;;;;;;;;gBAsDG,IAAI,YAAY;aA2BvB,QAAA;;cAkCC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/promise-queue/index.ts"],"sourcesContent":["/**\n * Implements an \"infinite\" FIFO queue of fixed size using promises\n * - await `continue()` before enqueing items to ensure fixed size (resolves when space available)\n * - await `dequeue()` to pop an item (resolves when next item is available)\n * - size() is always at minimum 1 item which is the promise for the next enqueued item\n */\nexport class PromiseQueue<T> {\n /** Optional error handler for enqueue failures */\n private errorHandler?: (error: unknown) => void;\n /** Array of promises representing queued items */\n private items: Array<Promise<T>>;\n\n /** Function to resolve the next enqueued promise */\n private enqueuer!: (val: T | PromiseLike<T>) => void;\n\n /** Function to resolve the continue promise when space is available */\n private batcher!: (val: boolean) => void;\n\n /** Flag indicating if the queue is synced with the data source */\n public synced = false;\n\n /** Maximum number of items to keep in the queue */\n private batchSize: number;\n\n /** Promise that resolves when it's safe to enqueue more items */\n private continuePromise: Promise<boolean>;\n\n constructor(batchSize: number, errorHandler?: (error: unknown) => void) {\n const nextVal = new Promise<T>((resolve, _reject) => {\n this.enqueuer = resolve;\n });\n this.batchSize = batchSize;\n this.errorHandler = errorHandler;\n this.continuePromise = new Promise<boolean>((resolve, _reject) => {\n this.batcher = resolve;\n });\n this.batcher(true);\n this.items = [nextVal];\n }\n\n enqueue(item: T | PromiseLike<T>) {\n try {\n this.enqueuer(item);\n const nextVal = new Promise<T>((resolve, _reject) => {\n this.enqueuer = resolve;\n });\n this.items.push(nextVal);\n if (this.size() > this.batchSize) {\n this.continuePromise = new Promise<boolean>((resolve, _reject) => {\n this.batcher = resolve;\n });\n }\n }\n catch (e) {\n if (this.errorHandler) {\n this.errorHandler(e);\n }\n // If no error handler provided, silently ignore (existing behavior for backward compatibility)\n }\n }\n\n clear() {\n const nextVal = new Promise<T>((resolve, _reject) => {\n this.enqueuer = resolve;\n });\n this.continuePromise = new Promise<boolean>((resolve, _reject) => {\n this.batcher = resolve;\n });\n this.batcher(true);\n this.items = [nextVal];\n }\n\n dequeue() {\n const item = this.items.shift();\n if (this.size() <= this.batchSize) {\n this.batcher(true);\n }\n\n return item as Promise<T>;\n }\n\n continue() {\n return this.continuePromise;\n }\n\n setSynced() {\n this.synced = true;\n }\n\n isEmpty() {\n if (this.items.length == 0) {\n return true;\n }\n else {\n return false;\n }\n }\n\n size() {\n return this.items.length;\n }\n}\n\n/**\n * Circular buffer implementation using promises for efficient memory usage\n * Reuses array slots in a circular fashion to maintain constant memory footprint\n * Used by the indexer for managing block processing queues\n */\nexport class CircularBuffer<T> {\n /** Optional error handler for enqueue failures */\n private errorHandler?: (error: unknown) => void;\n\n /** Fixed-size array of promises representing buffered items */\n private items: Array<Promise<T>>;\n\n /** Function to resolve the next enqueued promise */\n private enqueuer!: (val: T | PromiseLike<T>) => void;\n\n /** Current number of items in the buffer */\n private count: number = 0;\n\n /** Index of the next item to dequeue */\n private next: number = 0;\n\n /** Function to resolve the continue promise when space is available */\n private batcher!: (val: boolean) => void;\n\n /** Flag indicating if the buffer is synced with the data source */\n public synced = false;\n\n /** Maximum number of items the buffer can hold */\n private batchSize: number;\n\n /** Promise that resolves when it's safe to enqueue more items */\n private continuePromise: Promise<boolean>;\n\n /** Index of the next available slot for enqueueing */\n private nextAvail: number = 0;\n\n constructor(batchSize: number, errorHandler?: (error: unknown) => void) {\n if (batchSize <= 1) {\n throw new Error(\"Batch size must be greater than 1\");\n }\n const nextVal = new Promise<T>((resolve, _reject) => {\n this.enqueuer = resolve;\n });\n this.items = new Array<Promise<T>>(batchSize);\n this.batchSize = batchSize;\n this.errorHandler = errorHandler;\n this.items[this.nextAvail] = nextVal;\n this.count = 1;\n this.nextAvail++;\n if (this.nextAvail >= this.batchSize) {\n this.nextAvail = 0;\n }\n\n this.continuePromise = new Promise<boolean>((resolve, _reject) => {\n this.batcher = resolve;\n });\n this.batcher(true);\n }\n\n enqueue(item: T | PromiseLike<T>) {\n try {\n this.enqueuer(item);\n const nextVal = new Promise<T>((resolve, _reject) => {\n this.enqueuer = resolve;\n });\n this.items[this.nextAvail] = nextVal;\n this.count++;\n this.nextAvail++;\n if (this.nextAvail >= this.batchSize) {\n this.nextAvail = 0;\n }\n\n if (this.nextAvail == this.next) {\n this.continuePromise = new Promise<boolean>((resolve, _reject) => {\n this.batcher = resolve;\n });\n }\n }\n catch (e) {\n if (this.errorHandler) {\n this.errorHandler(e);\n }\n // If no error handler provided, silently ignore (existing behavior for backward compatibility)\n }\n }\n\n dequeue() {\n const item = this.items[this.next];\n this.next++;\n this.count--;\n if (this.next >= this.batchSize) {\n this.next = 0;\n }\n if (this.count <= this.batchSize) {\n this.batcher(true);\n }\n return item;\n }\n\n clear() {\n this.next = 0;\n this.nextAvail = 0;\n const nextVal = new Promise<T>((resolve, _reject) => {\n this.enqueuer = resolve;\n });\n this.items = new Array<Promise<T>>(this.batchSize);\n this.items[this.nextAvail] = nextVal;\n this.synced = false;\n this.count = 1;\n this.nextAvail++;\n if (this.nextAvail >= this.batchSize) {\n this.nextAvail = 0;\n }\n\n this.continuePromise = new Promise<boolean>((resolve, _reject) => {\n this.batcher = resolve;\n });\n this.batcher(true);\n }\n\n continue() {\n return this.continuePromise;\n }\n\n setSynced() {\n this.synced = true;\n }\n\n isEmpty() {\n if (this.count == 0) {\n return true;\n }\n else {\n return false;\n }\n }\n\n size() {\n return this.count;\n }\n}\n"],"mappings":";;;;;;;AAMA,IAAa,eAAb,MAA6B;CAqB3B,YAAY,WAAmB,cAAyC;OARjE,SAAS;EASd,MAAM,UAAU,IAAI,SAAY,SAAS,YAAY;AACnD,QAAK,WAAW;IAChB;AACF,OAAK,YAAY;AACjB,OAAK,eAAe;AACpB,OAAK,kBAAkB,IAAI,SAAkB,SAAS,YAAY;AAChE,QAAK,UAAU;IACf;AACF,OAAK,QAAQ,KAAK;AAClB,OAAK,QAAQ,CAAC,QAAQ;;CAGxB,QAAQ,MAA0B;AAChC,MAAI;AACF,QAAK,SAAS,KAAK;GACnB,MAAM,UAAU,IAAI,SAAY,SAAS,YAAY;AACnD,SAAK,WAAW;KAChB;AACF,QAAK,MAAM,KAAK,QAAQ;AACxB,OAAI,KAAK,MAAM,GAAG,KAAK,UACrB,MAAK,kBAAkB,IAAI,SAAkB,SAAS,YAAY;AAChE,SAAK,UAAU;KACf;WAGC,GAAG;AACR,OAAI,KAAK,aACP,MAAK,aAAa,EAAE;;;CAM1B,QAAQ;EACN,MAAM,UAAU,IAAI,SAAY,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KA,KAAA,EAAA;IAAM,KAAA,EAAA;MACX,KAAA,EAgBM,aAhBN;MACC,aAAA,EAgBa,oBAhBb,GAgBoC,sBAhBpC;IAEG,CAAA;;WAM8C,EAAA;IACvC,KAAA,EAWP,oBAXO,CAAA,gBAAA,CAAA,GAWkC,sBAXlC,CAAA,qBAAA,CAAA;;WAOG,EAAA;IAAuB,KAAA,EAOjC,oBAPiC,CAAA,SAAA,CAAA,GAOC,sBAPD,CAAA,SAAA,CAAA;;SAIQ,EAAA;IAGzC,KAAA,EAAA;MAAkC,MAAA,EAAA,MAAA;MAK/B,MAAA,EAAA,MAAA;IAAM,CAAA;EAiBR,CAAA;EAAQ,UAAA,EAAA;IACd,IAAA,EAAA,MAAA;IACI,KAAA,EAAA,OAAA;EAAK,CAAA;EAIE,aAAA,EAAA;IAAc,KAAA,EAAA,IAAA;;gBAKhB,EAAA;IAAO,KAAA,EAAA,IAAA;;;;;;KAXV;MACN;UACI;;;UAIO,cAAA;WACN;;;;eAII"}
|
package/dist/types/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["/* eslint-disable @stylistic/no-multi-spaces */\nimport {\n BlockResponse, BlockResultsResponse,\n} from \"@cosmjs/tendermint-rpc\";\nimport {\n BlockResultsResponse as BlockResultsResponse38, Event,\n} from \"@cosmjs/tendermint-rpc/build/comet38/responses\";\nimport {\n Validator,\n} from \"cosmjs-types/cosmos/staking/v1beta1/staking\";\nimport {\n TxBody,\n} from \"cosmjs-types/cosmos/tx/v1beta1/tx\";\n\nimport {\n EcleciaIndexer,\n} from \"../indexer\";\nimport {\n CircularBuffer,\n} from \"../promise-queue\";\n\n/** Configuration interface for the Eclesia indexer */\nexport type EcleciaIndexerConfig = {\n startHeight?: number // Block height to start indexing from\n endHeight?: number // Block height to stop indexing at (optional)\n batchSize: number // Number of blocks to process in parallel\n modules: string[] // List of module names to enable\n getNextHeight: () => number | PromiseLike<number> // Function to determine next block to process\n logLevel: \"error\" | \"warn\" | \"info\" | \"http\" | \"verbose\" | \"debug\" | \"silly\" // Logging verbosity level\n rpcUrl: string // Tendermint RPC endpoint URL\n shouldProcessGenesis: () => Promise<boolean> // Whether to process genesis state\n genesisPath?: string // Path to genesis file\n usePolling?: boolean // Use polling instead of WebSocket subscription\n pollingInterval?: number // Interval between polls in milliseconds\n minimal?: boolean // Use minimal indexing mode (blocks only)\n healthCheckPort?: number // Port for health check HTTP server (default: 8080)\n enablePrometheus?: boolean // Enable Prometheus metrics server\n prometheusPort?: number // Port for Prometheus metrics server (default: 9090)\n init?: () => Promise<void> // Custom initialization function\n beginTransaction: () => Promise<void> // Function to begin database transaction\n endTransaction: (status: boolean) => Promise<void> // Function to end database transaction\n};\n\n/** Queue for full indexing mode with validator data */\nexport type FullBlockQueue = CircularBuffer<[BlockResponse, BlockResultsResponse, Uint8Array]>;\n\n/** Queue for minimal indexing mode without validator data */\nexport type MinimalBlockQueue = CircularBuffer<[BlockResponse, BlockResultsResponse]>;\n\n/** Union type for block queues */\nexport type BlockQueue = FullBlockQueue | MinimalBlockQueue;\n\n/** Utility type to add height, timestamp, and UUID to event types */\nexport type WithHeightAndUUID<T> = {\n [K in keyof T]: T[K] & {\n uuid?: string // Unique identifier for event tracking\n height?: number // Block height when event occurred\n timestamp?: string // Block timestamp when event occurred\n };\n};\n\n/** Function signature for emitting events asynchronously */\nexport type EmitFunc<K extends keyof WithHeightAndUUID<EventMap>> = (\n t: K,\n e: WithHeightAndUUID<EventMap>[K]\n) => Promise<void | void[]>;\n\nexport type LogEvent = {\n type: \"log\" | \"info\" | \"warning\" | \"error\" | \"verbose\" | \"transient\"\n message: string\n};\nexport type UUIDEvent = {\n uuid: string\n error?: string\n status: boolean\n};\nexport type Events = {\n log: LogEvent\n uuid: UUIDEvent\n \"fatal-error\": {\n error: Error\n message: string\n retryCount?: number\n }\n begin_block: {\n value: {\n events: BlockResultsResponse[\"beginBlockEvents\"] | BlockResultsResponse38[\"finalizeBlockEvents\"]\n validators: Validator[] | undefined\n }\n }\n\n block: {\n value: {\n block: BlockResponse\n block_results: BlockResultsResponse | BlockResultsResponse38\n }\n }\n end_block: {\n value: BlockResultsResponse[\"endBlockEvents\"] | BlockResultsResponse38[\"finalizeBlockEvents\"]\n }\n tx_events: {\n value: BlockResultsResponse[\"results\"] | BlockResultsResponse38[\"results\"]\n }\n tx_memo: {\n value: {\n txHash: string\n txBody: TxBody\n }\n }\n _unhandled: {\n type: string\n event: unknown\n }\n \"periodic/50\": {\n value: null\n }\n \"periodic/100\": {\n value: null\n }\n \"periodic/1000\": {\n value: null\n }\n};\nexport type TxResult<T> = {\n tx: T\n events: Event[]\n};\n\n/** Interface that all indexing modules must implement */\nexport interface IndexingModule {\n indexer: EcleciaIndexer // Reference to the main indexer instance\n name: string // Unique module name\n depends: string[] // Array of module names this module depends on\n provides: string[] // Array of capabilities this module provides\n setup: () => Promise<void> // Async setup function for database schema initialization\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n init: (...args: any[]) => void // Initialization function called by the indexer\n}\n"],"mappings":""}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bech32.d.ts","names":[],"sources":["../../src/utils/bech32.ts"],"sourcesContent":[],"mappings":";;;AASoB;AAgBO;;iBAhBlB,WAAA;;;;;;;iBAgBA,kBAAA;;;;;;;iBAeA,uBAAA"}
|
package/dist/utils/bech32.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bech32.js","names":[],"sources":["../../src/utils/bech32.ts"],"sourcesContent":["import {\n bech32,\n} from \"bech32\";\n\n/**\n * Converts a byte array to a hexadecimal string representation\n * @param byteArray - Array of bytes to convert\n * @returns Hexadecimal string\n */\nfunction toHexString(byteArray: number[]) {\n return Array.prototype.map\n .call(\n byteArray, (byte) => {\n return (\"0\" + (byte & 0xff).toString(16)).slice(-2);\n },\n )\n .join(\"\");\n}\n\n/**\n * Extracts the key hash from a bech32-encoded address\n * @param address - Bech32-encoded address string\n * @returns Hexadecimal key hash\n * @throws Error if address cannot be decoded\n */\nfunction keyHashfromAddress(address: string): string {\n try {\n return toHexString(bech32.fromWords(bech32.decode(address).words));\n }\n catch (_e) {\n throw new Error(\"Could not decode address\");\n }\n}\n\n/**\n * Creates a bech32-encoded address from a key hash and prefix\n * @param prefix - Address prefix (e.g., \"cosmos\", \"cosmosvalcons\")\n * @param keyhash - Hexadecimal key hash\n * @returns Bech32-encoded address or empty string if keyhash is empty\n */\nfunction chainAddressfromKeyhash(prefix: string, keyhash: string) {\n const words = bech32.toWords(Buffer.from(\n keyhash, \"hex\",\n ));\n\n return keyhash !== \"\"\n ? bech32.encode(\n prefix, words,\n )\n : \"\";\n}\n\nexport {\n chainAddressfromKeyhash, keyHashfromAddress, toHexString,\n};\n"],"mappings":";;;;;;;;AASA,SAAS,YAAY,WAAqB;AACxC,QAAO,MAAM,UAAU,IACpB,KACC,YAAY,SAAS;AACnB,UAAQ,OAAO,OAAO,KAAM,SAAS,GAAG,EAAE,MAAM,GAAG;GAEtD,CACA,KAAK,GAAG;;;;;;;;AASb,SAAS,mBAAmB,SAAyB;AACnD,KAAI;AACF,SAAO,YAAY,OAAO,UAAU,OAAO,OAAO,QAAQ,CAAC,MAAM,CAAC;UAE7D,IAAI;AACT,QAAM,IAAI,MAAM,2BAA2B;;;;;;;;;AAU/C,SAAS,wBAAwB,QAAgB,SAAiB;CAChE,MAAM,QAAQ,OAAO,QAAQ,OAAO,KAClC,SAAS,MACV,CAAC;AAEF,QAAO,YAAY,KACf,OAAO,OACP,QAAQ,MACT,GACC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bigint.d.ts","names":[],"sources":["../../src/utils/bigint.ts"],"sourcesContent":[],"mappings":";;;;;;;cAMM"}
|
package/dist/utils/bigint.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"bigint.js","names":[],"sources":["../../src/utils/bigint.ts"],"sourcesContent":["/**\n * Converts an object containing BigInt values to a plain JavaScript object\n * BigInt values are converted to strings to maintain precision in JSON serialization\n * @param obj - Object that may contain BigInt values\n * @returns Plain object with BigInt values converted to strings\n */\nconst toPlainObject = (obj: unknown) => {\n return JSON.parse(JSON.stringify(obj,\n (key, value) => (typeof value === \"bigint\" ? value.toString() : value), // return everything else unchanged\n ));\n};\nexport {\n toPlainObject,\n};\n"],"mappings":";;;;;;;AAMA,MAAM,iBAAiB,QAAiB;AACtC,QAAO,KAAK,MAAM,KAAK,UAAU,MAC9B,KAAK,UAAW,OAAO,UAAU,WAAW,MAAM,UAAU,GAAG,MACjE,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":[],"mappings":""}
|
package/dist/utils/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/utils/index.ts"],"sourcesContent":["/* eslint-disable @stylistic/no-multi-spaces */\n// Utility function exports\nexport * from \"./bech32\"; // Bech32 address encoding/decoding utilities\nexport * from \"./bigint\"; // BigInt handling utilities\nexport * from \"./text\"; // Text processing and encoding utilities\n"],"mappings":""}
|
package/dist/utils/text.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"text.d.ts","names":[],"sources":["../../src/utils/text.ts"],"sourcesContent":[],"mappings":";;AAMA;;;;;cAAa,gBAAiB"}
|
package/dist/utils/text.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"text.js","names":[],"sources":["../../src/utils/text.ts"],"sourcesContent":["/**\n * Decodes blockchain event attributes from various formats to strings\n * Handles both string and Uint8Array inputs from Tendermint events\n * @param x - The attribute value to decode (string or Uint8Array)\n * @returns Decoded string value\n */\nexport const decodeAttr = (x: Uint8Array | string) => {\n if (typeof x === \"string\") {\n return x;\n }\n else if (x instanceof Uint8Array) {\n return Buffer.from(x).toString();\n }\n else {\n return \"\";\n }\n};\n"],"mappings":";;;;;;;AAMA,MAAa,cAAc,MAA2B;AACpD,KAAI,OAAO,MAAM,SACf,QAAO;UAEA,aAAa,WACpB,QAAO,OAAO,KAAK,EAAE,CAAC,UAAU;KAGhC,QAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/validation/index.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;iBAiBgB,WAAA;AAAhB;AA6CA;AAiCA;AAgCA;AAwBA;AAeA;iBAxGgB,gBAAA;;;;;;;iBAiCA,gCAAA;;;;;;;iBAgCA,YAAA;;;;;;;iBAwBA,uBAAA;;;;;;;iBAeA,cAAA"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/validation/index.ts"],"sourcesContent":["/**\n * Configuration validation utilities for the Eclesia indexer\n * Validates configuration parameters before initialization\n */\n\nimport * as fs from \"node:fs\";\n\nimport {\n ConfigurationError,\n} from \"../errors/index.js\";\n\n/**\n * Validates a URL string\n * @param url - The URL to validate\n * @param fieldName - Name of the field for error messages\n * @throws {ConfigurationError} If URL is invalid\n */\nexport function validateUrl(url: string, fieldName: string = \"URL\"): void {\n if (!url || typeof url !== \"string\") {\n throw new ConfigurationError(`${fieldName} is required and must be a string`, {\n fieldName,\n value: url,\n });\n }\n\n try {\n const parsed = new URL(url);\n\n // Ensure protocol is http or https\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\" && parsed.protocol !== \"ws:\" && parsed.protocol !== \"wss:\") {\n throw new ConfigurationError(`${fieldName} must use http, https, ws, or wss protocol`, {\n fieldName,\n url,\n protocol: parsed.protocol,\n });\n }\n\n // Ensure hostname is present\n if (!parsed.hostname) {\n throw new ConfigurationError(`${fieldName} must include a hostname`, {\n fieldName,\n url,\n });\n }\n }\n catch (error) {\n if (error instanceof ConfigurationError) {\n throw error;\n }\n throw new ConfigurationError(`${fieldName} is not a valid URL: ${error}`, {\n fieldName,\n url,\n });\n }\n}\n\n/**\n * Validates a file path exists and is readable\n * @param filePath - The file path to validate\n * @param fieldName - Name of the field for error messages\n * @throws {ConfigurationError} If file doesn't exist or isn't readable\n */\nexport function validateFilePath(filePath: string, fieldName: string = \"File path\"): void {\n if (!filePath || typeof filePath !== \"string\") {\n throw new ConfigurationError(`${fieldName} is required and must be a string`, {\n fieldName,\n value: filePath,\n });\n }\n\n if (!fs.existsSync(filePath)) {\n throw new ConfigurationError(`${fieldName} does not exist: ${filePath}`, {\n fieldName,\n filePath,\n });\n }\n\n try {\n fs.accessSync(filePath, fs.constants.R_OK);\n }\n catch (error) {\n throw new ConfigurationError(`${fieldName} is not readable: ${filePath}`, {\n fieldName,\n filePath,\n error: String(error),\n });\n }\n}\n\n/**\n * Validates a PostgreSQL connection string\n * @param connectionString - The connection string to validate\n * @param fieldName - Name of the field for error messages\n * @throws {ConfigurationError} If connection string is invalid\n */\nexport function validatePostgresConnectionString(\n connectionString: string,\n fieldName: string = \"Database connection string\",\n): void {\n if (!connectionString || typeof connectionString !== \"string\") {\n throw new ConfigurationError(`${fieldName} is required and must be a string`, {\n fieldName,\n value: connectionString,\n });\n }\n\n // Basic PostgreSQL connection string format validation\n // Format: postgres://user:password@host:port/database\n const pgRegex = /^postgres(?:ql)?:\\/\\/(?:([^:]+)(?::([^@]+))?@)?([^:/]+)(?::(\\d+))?\\/(.+)$/;\n\n if (!pgRegex.test(connectionString)) {\n throw new ConfigurationError(\n `${fieldName} must be in format: postgres://user:password@host:port/database`,\n {\n fieldName,\n format: \"postgres://user:password@host:port/database\",\n },\n );\n }\n}\n\n/**\n * Validates a port number\n * @param port - The port number to validate\n * @param fieldName - Name of the field for error messages\n * @throws {ConfigurationError} If port is invalid\n */\nexport function validatePort(port: number, fieldName: string = \"Port\"): void {\n if (typeof port !== \"number\" || !Number.isInteger(port)) {\n throw new ConfigurationError(`${fieldName} must be an integer`, {\n fieldName,\n value: port,\n });\n }\n\n if (port < 1 || port > 65535) {\n throw new ConfigurationError(`${fieldName} must be between 1 and 65535`, {\n fieldName,\n value: port,\n min: 1,\n max: 65535,\n });\n }\n}\n\n/**\n * Validates a positive integer\n * @param value - The value to validate\n * @param fieldName - Name of the field for error messages\n * @throws {ConfigurationError} If value is not a positive integer\n */\nexport function validatePositiveInteger(value: number, fieldName: string = \"Value\"): void {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0) {\n throw new ConfigurationError(`${fieldName} must be a positive integer`, {\n fieldName,\n value,\n });\n }\n}\n\n/**\n * Gets and validates the chain prefix from environment variables\n * @param defaultPrefix - Default prefix to use if environment variable is not set\n * @returns The validated chain prefix\n * @throws {ConfigurationError} If chain prefix is invalid\n */\nexport function getChainPrefix(defaultPrefix: string = \"cosmos\"): string {\n const prefix = process.env.CHAIN_PREFIX ?? defaultPrefix;\n\n if (!prefix || typeof prefix !== \"string\") {\n throw new ConfigurationError(\"CHAIN_PREFIX must be a non-empty string\", {\n value: prefix,\n defaultPrefix,\n });\n }\n\n // Validate prefix format (lowercase alphanumeric)\n if (!/^[a-z][a-z0-9]*$/.test(prefix)) {\n throw new ConfigurationError(\n \"CHAIN_PREFIX must start with lowercase letter and contain only lowercase letters and numbers\",\n {\n value: prefix,\n pattern: \"^[a-z][a-z0-9]*$\",\n },\n );\n }\n\n return prefix;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,YAAY,KAAa,YAAoB,OAAa;AACxE,KAAI,CAAC,OAAO,OAAO,QAAQ,SACzB,OAAM,IAAI,mBAAmB,GAAG,UAAU,oCAAoC;EAC5E;EACA,OAAO;EACR,CAAC;AAGJ,KAAI;EACF,MAAM,SAAS,IAAI,IAAI,IAAI;AAG3B,MAAI,OAAO,aAAa,WAAW,OAAO,aAAa,YAAY,OAAO,aAAa,SAAS,OAAO,aAAa,OAClH,OAAM,IAAI,mBAAmB,GAAG,UAAU,6CA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