@subql/node-ethereum 3.3.4 → 3.3.5-poi-logs

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 (33) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/ethereum/api.ethereum.js +2 -4
  3. package/dist/ethereum/api.ethereum.js.map +1 -1
  4. package/dist/ethereum/api.ethereum.test.js +0 -15
  5. package/dist/ethereum/api.ethereum.test.js.map +1 -1
  6. package/dist/ethereum/utils.ethereum.d.ts +2 -0
  7. package/dist/ethereum/utils.ethereum.js +2 -1
  8. package/dist/ethereum/utils.ethereum.js.map +1 -1
  9. package/dist/indexer/blockDispatcher/block-dispatcher.service.d.ts +1 -0
  10. package/dist/indexer/blockDispatcher/block-dispatcher.service.js +3 -0
  11. package/dist/indexer/blockDispatcher/block-dispatcher.service.js.map +1 -1
  12. package/dist/indexer/blockDispatcher/ethereum-block-dispatcher.d.ts +2 -1
  13. package/dist/indexer/blockDispatcher/ethereum-block-dispatcher.js.map +1 -1
  14. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.d.ts +3 -1
  15. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js +3 -0
  16. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js.map +1 -1
  17. package/dist/indexer/dictionary.service.js +4 -7
  18. package/dist/indexer/dictionary.service.js.map +1 -1
  19. package/dist/indexer/eth-fat-dictionary.service.d.ts +83 -0
  20. package/dist/indexer/eth-fat-dictionary.service.js +246 -0
  21. package/dist/indexer/eth-fat-dictionary.service.js.map +1 -0
  22. package/dist/indexer/fetch.module.js +16 -0
  23. package/dist/indexer/fetch.module.js.map +1 -1
  24. package/dist/indexer/fetch.service.d.ts +4 -3
  25. package/dist/indexer/fetch.service.js +5 -3
  26. package/dist/indexer/fetch.service.js.map +1 -1
  27. package/dist/indexer/fetch.service.spec.js +1 -1
  28. package/dist/indexer/fetch.service.spec.js.map +1 -1
  29. package/dist/yargs.d.ts +232 -1
  30. package/dist/yargs.js +270 -7
  31. package/dist/yargs.js.map +1 -1
  32. package/package.json +5 -5
  33. package/CHANGELOG.md +0 -383
@@ -273,8 +273,7 @@ class EthereumApi {
273
273
  return log;
274
274
  }
275
275
  const iface = this.buildInterface(ds.options.abi, await loadAssets(ds));
276
- log.args = iface === null || iface === void 0 ? void 0 : iface.parseLog(log).args;
277
- return log;
276
+ return Object.assign(Object.assign({}, log), { args: iface === null || iface === void 0 ? void 0 : iface.parseLog(log).args });
278
277
  }
279
278
  catch (e) {
280
279
  logger.warn(`Failed to parse log data: ${e.message}`);
@@ -295,8 +294,7 @@ class EthereumApi {
295
294
  transaction.logs =
296
295
  transaction.logs &&
297
296
  (await Promise.all(transaction.logs.map(async (log) => this.parseLog(log, ds))));
298
- transaction.args = args;
299
- return transaction;
297
+ return Object.assign(Object.assign({}, transaction), { args });
300
298
  }
301
299
  catch (e) {
302
300
  logger.warn(`Failed to parse transaction data: ${e.message}`);
@@ -1 +1 @@
1
- {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;AAGnC,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,4CAA+C;AAO/C,wDAA6D;AAE7D,gDAAsD;AAWtD,wEAA+C;AAC/C,4CAA0D;AAC1D,8CAAkD;AAClD,6FAAsF;AACtF,iFAA2E;AAC3E,qEAAgE;AAChE,8EAAwE;AACxE,kEAA6D;AAE7D,0DAAyC;AACzC,qDAK0B;AAE1B,8DAA8D;AAC9D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAElE,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,cAAc,CAAC,CAAC;AAEzC,KAAK,UAAU,UAAU,CACvB,EAA0B;IAE1B,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;QACd,OAAO,EAAE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;SACpB;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,IAAI,CAAC,qCAAqC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9D,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;IAED,4DAA4D;IAC5D,KAAK,CAAC,OAAO;QACX,MAAM,CAAC,KAAK,CAAC,yCAAyC,CAAC,CAAC;QACxD,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,UAAU;QACd,IAAI,IAAI,CAAC,MAAM,YAAY,6BAAiB,EAAE;YAC5C,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;SAC7B;aAAM;YACL,MAAM,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;SACnD;IACH,CAAC;IAED,WAAW,CAAC,CAAQ;QAClB,IAAI,CAAC,CAAS,aAAT,CAAC,uBAAD,CAAC,CAAU,MAAM,MAAK,GAAG,EAAE;YAC9B,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC5C,OAAO,IAAI,KAAK,CAAC,6BAA6B,QAAQ,EAAE,CAAC,CAAC;SAC3D;QAED,OAAO,CAAC,CAAC;IACX,CAAC;CACF;AApWD,kCAoWC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport assert from 'assert';\nimport fs from 'fs';\nimport http from 'http';\nimport https from 'https';\nimport { Interface } from '@ethersproject/abi';\nimport {\n BlockTag,\n Provider,\n Block,\n TransactionReceipt,\n} from '@ethersproject/abstract-provider';\nimport { WebSocketProvider } from '@ethersproject/providers';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { getLogger, timeout } from '@subql/node-core';\nimport {\n ApiWrapper,\n EthereumBlock,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n SubqlRuntimeDatasource,\n LightEthereumBlock,\n LightEthereumLog,\n} from '@subql/types-ethereum';\nimport CacheableLookup from 'cacheable-lookup';\nimport { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport { CeloJsonRpcBatchProvider } from './ethers/celo/celo-json-rpc-batch-provider';\nimport { CeloJsonRpcProvider } from './ethers/celo/celo-json-rpc-provider';\nimport { CeloWsProvider } from './ethers/celo/celo-ws-provider';\nimport { JsonRpcBatchProvider } from './ethers/json-rpc-batch-provider';\nimport { JsonRpcProvider } from './ethers/json-rpc-provider';\nimport { ConnectionInfo } from './ethers/web';\nimport SafeEthProvider from './safe-api';\nimport {\n formatBlock,\n formatLog,\n formatReceipt,\n formatTransaction,\n} from './utils.ethereum';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst { version: packageVersion } = require('../../package.json');\n\nconst logger = getLogger('api.ethereum');\n\nasync function loadAssets(\n ds: SubqlRuntimeDatasource,\n): Promise<Record<string, string>> {\n if (!ds.assets) {\n return {};\n }\n const res: Record<string, string> = {};\n\n for (const [name, { file }] of Object.entries(ds.assets)) {\n try {\n res[name] = await fs.promises.readFile(file, { encoding: 'utf8' });\n } catch (e) {\n throw new Error(`Failed to load datasource asset ${file}`);\n }\n }\n\n return res;\n}\n\nfunction getHttpAgents() {\n // By default Nodejs doesn't cache DNS lookups\n // https://httptoolkit.com/blog/configuring-nodejs-dns/\n const lookup = new CacheableLookup();\n\n const options: http.AgentOptions = {\n keepAlive: true,\n /*, maxSockets: 100*/\n };\n\n const httpAgent = new http.Agent(options);\n const httpsAgent = new https.Agent(options);\n\n lookup.install(httpAgent);\n lookup.install(httpsAgent);\n\n return {\n http: httpAgent,\n https: httpsAgent,\n };\n}\n\nexport class EthereumApi implements ApiWrapper {\n private client: JsonRpcProvider;\n\n // This is used within the sandbox when HTTP is used\n private nonBatchClient?: JsonRpcProvider;\n private genesisBlock: Record<string, any>;\n private contractInterfaces: Record<string, Interface> = {};\n private chainId: number;\n private name: string;\n\n // Ethereum POS\n private supportsFinalization = true;\n\n /**\n * @param {string} endpoint - The endpoint of the RPC provider\n * @param {number} blockConfirmations - Used to determine how many blocks behind the head a block is considered finalized. Not used if the network has a concrete finalization mechanism.\n * @param {object} eventEmitter - Used to monitor the number of RPC requests\n */\n constructor(\n private endpoint: string,\n private blockConfirmations: number,\n private eventEmitter: EventEmitter2,\n ) {\n const { hostname, protocol, searchParams } = new URL(endpoint);\n\n const protocolStr = protocol.replace(':', '');\n\n logger.info(`Api host: ${hostname}, method: ${protocolStr}`);\n if (protocolStr === 'https' || protocolStr === 'http') {\n const connection: ConnectionInfo = {\n url: this.endpoint.split('?')[0],\n headers: {\n 'User-Agent': `Subquery-Node ${packageVersion}`,\n },\n allowGzip: true,\n throttleLimit: 5,\n throttleSlotInterval: 1,\n agents: getHttpAgents(),\n };\n searchParams.forEach((value, name, searchParams) => {\n (connection.headers as any)[name] = value;\n });\n this.client = new JsonRpcBatchProvider(connection);\n this.nonBatchClient = new JsonRpcProvider(connection);\n } else if (protocolStr === 'ws' || protocolStr === 'wss') {\n this.client = new WebSocketProvider(this.endpoint);\n } else {\n throw new Error(`Unsupported protocol: ${protocol}`);\n }\n }\n\n async init(): Promise<void> {\n this.injectClient();\n\n const network = await this.client.getNetwork();\n\n //celo\n if (network.chainId === 42220) {\n if (this.client instanceof WebSocketProvider) {\n this.client = new CeloWsProvider(this.client.connection.url);\n } else {\n this.client = new CeloJsonRpcBatchProvider(this.client.connection);\n this.nonBatchClient = new CeloJsonRpcProvider(this.client.connection);\n }\n }\n\n try {\n const [genesisBlock, supportsFinalization, supportsSafe] =\n await Promise.all([\n this.client.getBlock('earliest'),\n this.getSupportsTag('finalized'),\n this.getSupportsTag('safe'),\n ]);\n\n this.genesisBlock = genesisBlock;\n this.supportsFinalization = supportsFinalization && supportsSafe;\n this.chainId = network.chainId;\n this.name = network.name;\n } catch (e) {\n if ((e as Error).message.startsWith('Invalid response')) {\n this.client = this.nonBatchClient;\n\n logger.warn(\n `The RPC Node at ${this.endpoint} cannot process batch requests. ` +\n `Switching to non-batch mode for subsequent requests. Please consider checking if batch processing is supported on the RPC node.`,\n );\n\n return this.init();\n }\n\n throw e;\n }\n }\n\n private async getSupportsTag(tag: BlockTag): Promise<boolean> {\n try {\n // We set the timeout here because theres a bug in ethers where it will never resolve\n // It was happening with arbitrum on a syncing node\n const result = await timeout(this.client.getBlock(tag), 2);\n\n return true;\n } catch (e) {\n logger.info(`Chain doesnt support ${tag} tag`);\n return false;\n }\n }\n\n private injectClient(): void {\n const orig = this.client.send.bind(this.client);\n Object.defineProperty(this.client, 'send', {\n value: (...args) => {\n this.eventEmitter.emit('rpcCall');\n return orig(...args);\n },\n });\n }\n\n async getFinalizedBlock(): Promise<Block> {\n const height = this.supportsFinalization\n ? 'finalized'\n : (await this.getBestBlockHeight()) - this.blockConfirmations;\n\n const block = await this.client.getBlock(height);\n // The finalized block could sometimes fail to fetch,\n // due to some nodes on the network falling behind the synced node.\n if (!block) {\n throw new Error(`get finalized block \"${height}\" failed `);\n }\n return block;\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.getFinalizedBlock()).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n // Cronos \"safe\" tag doesn't currently work as indended\n const tag =\n this.supportsFinalization && this.chainId !== 25 ? 'safe' : 'latest';\n return (await this.client.getBlock(tag)).number;\n }\n\n getRuntimeChain(): string {\n return this.name;\n }\n\n getChainId(): number {\n return this.chainId;\n }\n\n getGenesisHash(): string {\n return this.genesisBlock.hash;\n }\n\n getSpecName(): string {\n return 'ethereum';\n }\n\n async getBlockByHeightOrHash(heightOrHash: number | string): Promise<Block> {\n if (typeof heightOrHash === 'number') {\n heightOrHash = hexValue(heightOrHash);\n }\n return this.client.getBlock(heightOrHash);\n }\n\n private async getBlockPromise(num: number, includeTx = true): Promise<any> {\n const rawBlock = await this.client.send('eth_getBlockByNumber', [\n hexValue(num),\n includeTx,\n ]);\n\n if (!rawBlock) {\n throw new Error(`Failed to fetch block ${num}`);\n }\n\n const block = formatBlock(rawBlock);\n\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n\n return block;\n }\n\n async getTransactionReceipt(\n transactionHash: string | Promise<string>,\n ): Promise<TransactionReceipt> {\n return retryOnFailEth<TransactionReceipt>(\n this.client.getTransactionReceipt.bind(this.client, transactionHash),\n );\n }\n\n async fetchBlock(blockNumber: number): Promise<EthereumBlock> {\n try {\n const block = await this.getBlockPromise(blockNumber, true);\n const logsRaw = await this.client.getLogs({ blockHash: block.hash });\n\n block.logs = logsRaw.map((l) => formatLog(l, block));\n block.transactions = block.transactions.map((tx) => ({\n ...formatTransaction(tx, block),\n receipt: () =>\n this.getTransactionReceipt(tx.hash).then((r) =>\n formatReceipt(r, block),\n ),\n logs: block.logs.filter((l) => l.transactionHash === tx.hash),\n }));\n\n this.eventEmitter.emit('fetchBlock');\n return block;\n } catch (e) {\n throw this.handleError(e);\n }\n }\n\n private async fetchLightBlock(\n blockNumber: number,\n ): Promise<LightEthereumBlock> {\n const block = await this.getBlockPromise(blockNumber, false);\n const logs = await this.client.getLogs({ blockHash: block.hash });\n\n return {\n ...block,\n logs: logs.map((l) => formatLog(l, block)),\n };\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlock[]> {\n return Promise.all(bufferBlocks.map(async (num) => this.fetchBlock(num)));\n }\n\n async fetchBlocksLight(\n bufferBlocks: number[],\n ): Promise<LightEthereumBlock[]> {\n console.log('FETCH BLOCKS LIGHT');\n return Promise.all(\n bufferBlocks.map(async (num) => this.fetchLightBlock(num)),\n );\n }\n\n get api(): Provider {\n return this.client;\n }\n\n getSafeApi(blockHeight: number): SafeEthProvider {\n // We cannot use a batch http client because OnF don't support routing historical queries in batches to an archive nodes\n const client =\n this.client instanceof WebSocketProvider\n ? this.client\n : this.nonBatchClient;\n\n return new SafeEthProvider(client, blockHeight);\n }\n\n private buildInterface(\n abiName: string,\n assets: Record<string, string>,\n ): Interface | undefined {\n if (!assets[abiName]) {\n throw new Error(`ABI named \"${abiName}\" not referenced in assets`);\n }\n\n // This assumes that all datasources have a different abi name or they are the same abi\n if (!this.contractInterfaces[abiName]) {\n // Constructing the interface validates the ABI\n try {\n let abiObj = JSON.parse(assets[abiName]);\n\n /*\n * Allows parsing JSON artifacts as well as ABIs\n * https://trufflesuite.github.io/artifact-updates/background.html#what-are-artifacts\n */\n if (!Array.isArray(abiObj) && abiObj.abi) {\n abiObj = abiObj.abi;\n }\n\n this.contractInterfaces[abiName] = new Interface(abiObj);\n } catch (e) {\n logger.error(`Unable to parse ABI: ${e.message}`);\n throw new Error('ABI is invalid');\n }\n }\n\n return this.contractInterfaces[abiName];\n }\n\n async parseLog<T extends EthereumResult = EthereumResult>(\n log: EthereumLog | LightEthereumLog,\n ds: SubqlRuntimeDatasource,\n ): Promise<\n EthereumLog | LightEthereumLog | EthereumLog<T> | LightEthereumLog<T>\n > {\n try {\n if (!ds?.options?.abi) {\n logger.warn('No ABI provided for datasource');\n return log;\n }\n const iface = this.buildInterface(ds.options.abi, await loadAssets(ds));\n\n log.args = iface?.parseLog(log).args as T;\n\n return log;\n } catch (e) {\n logger.warn(`Failed to parse log data: ${e.message}`);\n return log;\n }\n }\n\n async parseTransaction<T extends EthereumResult = EthereumResult>(\n transaction: EthereumTransaction,\n ds: SubqlRuntimeDatasource,\n ): Promise<EthereumTransaction<T> | EthereumTransaction> {\n try {\n if (!ds?.options?.abi) {\n logger.warn('No ABI provided for datasource');\n return transaction;\n }\n const assets = await loadAssets(ds);\n const iface = this.buildInterface(ds.options.abi, assets);\n const func = iface.getFunction(hexDataSlice(transaction.input, 0, 4));\n const args = iface.decodeFunctionData(func, transaction.input) as T;\n\n transaction.logs =\n transaction.logs &&\n ((await Promise.all(\n transaction.logs.map(async (log) => this.parseLog(log, ds)),\n )) as Array<EthereumLog | EthereumLog<T>>);\n\n transaction.args = args;\n\n return transaction;\n } catch (e) {\n logger.warn(`Failed to parse transaction data: ${e.message}`);\n return transaction;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n async connect(): Promise<void> {\n logger.error('Ethereum API connect is not implemented');\n throw new Error('Not implemented');\n }\n\n async disconnect(): Promise<void> {\n if (this.client instanceof WebSocketProvider) {\n await this.client.destroy();\n } else {\n logger.warn('Disconnect called on HTTP provider');\n }\n }\n\n handleError(e: Error): Error {\n if ((e as any)?.status === 429) {\n const { hostname } = new URL(this.endpoint);\n return new Error(`Rate Limited at endpoint: ${hostname}`);\n }\n\n return e;\n }\n}\n"]}
1
+ {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;AAEnC,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,4CAA+C;AAO/C,wDAA6D;AAE7D,gDAAsD;AAWtD,wEAA+C;AAC/C,4CAA0D;AAC1D,8CAAkD;AAClD,6FAAsF;AACtF,iFAA2E;AAC3E,qEAAgE;AAChE,8EAAwE;AACxE,kEAA6D;AAE7D,0DAAyC;AACzC,qDAK0B;AAE1B,8DAA8D;AAC9D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAElE,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,cAAc,CAAC,CAAC;AAEzC,KAAK,UAAU,UAAU,CACvB,EAA0B;IAE1B,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;QACd,OAAO,EAAE,CAAC;KACX;IACD,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE;QACxD,IAAI;YACF,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,YAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CA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E;YAC5C,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;SAC7B;aAAM;YACL,MAAM,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;SACnD;IACH,CAAC;IAED,WAAW,CAAC,CAAQ;QAClB,IAAI,CAAC,CAAS,aAAT,CAAC,uBAAD,CAAC,CAAU,MAAM,MAAK,GAAG,EAAE;YAC9B,MAAM,EAAE,QAAQ,EAAE,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;YAC5C,OAAO,IAAI,KAAK,CAAC,6BAA6B,QAAQ,EAAE,CAAC,CAAC;SAC3D;QAED,OAAO,CAAC,CAAC;IACX,CAAC;CACF;AArWD,kCAqWC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport fs from 'fs';\nimport http from 'http';\nimport https from 'https';\nimport { Interface } from '@ethersproject/abi';\nimport {\n BlockTag,\n Provider,\n Block,\n TransactionReceipt,\n} from '@ethersproject/abstract-provider';\nimport { WebSocketProvider } from '@ethersproject/providers';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { getLogger, timeout } from '@subql/node-core';\nimport {\n ApiWrapper,\n EthereumBlock,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n SubqlRuntimeDatasource,\n LightEthereumBlock,\n LightEthereumLog,\n} from '@subql/types-ethereum';\nimport CacheableLookup from 'cacheable-lookup';\nimport { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport { CeloJsonRpcBatchProvider } from './ethers/celo/celo-json-rpc-batch-provider';\nimport { CeloJsonRpcProvider } from './ethers/celo/celo-json-rpc-provider';\nimport { CeloWsProvider } from './ethers/celo/celo-ws-provider';\nimport { JsonRpcBatchProvider } from './ethers/json-rpc-batch-provider';\nimport { JsonRpcProvider } from './ethers/json-rpc-provider';\nimport { ConnectionInfo } from './ethers/web';\nimport SafeEthProvider from './safe-api';\nimport {\n formatBlock,\n formatLog,\n formatReceipt,\n formatTransaction,\n} from './utils.ethereum';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst { version: packageVersion } = require('../../package.json');\n\nconst logger = getLogger('api.ethereum');\n\nasync function loadAssets(\n ds: SubqlRuntimeDatasource,\n): Promise<Record<string, string>> {\n if (!ds.assets) {\n return {};\n }\n const res: Record<string, string> = {};\n\n for (const [name, { file }] of Object.entries(ds.assets)) {\n try {\n res[name] = await fs.promises.readFile(file, { encoding: 'utf8' });\n } catch (e) {\n throw new Error(`Failed to load datasource asset ${file}`);\n }\n }\n\n return res;\n}\n\nfunction getHttpAgents() {\n // By default Nodejs doesn't cache DNS lookups\n // https://httptoolkit.com/blog/configuring-nodejs-dns/\n const lookup = new CacheableLookup();\n\n const options: http.AgentOptions = {\n keepAlive: true,\n /*, maxSockets: 100*/\n };\n\n const httpAgent = new http.Agent(options);\n const httpsAgent = new https.Agent(options);\n\n lookup.install(httpAgent);\n lookup.install(httpsAgent);\n\n return {\n http: httpAgent,\n https: httpsAgent,\n };\n}\n\nexport class EthereumApi implements ApiWrapper {\n private client: JsonRpcProvider;\n\n // This is used within the sandbox when HTTP is used\n private nonBatchClient?: JsonRpcProvider;\n private genesisBlock: Record<string, any>;\n private contractInterfaces: Record<string, Interface> = {};\n private chainId: number;\n private name: string;\n\n // Ethereum POS\n private supportsFinalization = true;\n\n /**\n * @param {string} endpoint - The endpoint of the RPC provider\n * @param {number} blockConfirmations - Used to determine how many blocks behind the head a block is considered finalized. Not used if the network has a concrete finalization mechanism.\n * @param {object} eventEmitter - Used to monitor the number of RPC requests\n */\n constructor(\n private endpoint: string,\n private blockConfirmations: number,\n private eventEmitter: EventEmitter2,\n ) {\n const { hostname, protocol, searchParams } = new URL(endpoint);\n\n const protocolStr = protocol.replace(':', '');\n\n logger.info(`Api host: ${hostname}, method: ${protocolStr}`);\n if (protocolStr === 'https' || protocolStr === 'http') {\n const connection: ConnectionInfo = {\n url: this.endpoint.split('?')[0],\n headers: {\n 'User-Agent': `Subquery-Node ${packageVersion}`,\n },\n allowGzip: true,\n throttleLimit: 5,\n throttleSlotInterval: 1,\n agents: getHttpAgents(),\n };\n searchParams.forEach((value, name, searchParams) => {\n (connection.headers as any)[name] = value;\n });\n this.client = new JsonRpcBatchProvider(connection);\n this.nonBatchClient = new JsonRpcProvider(connection);\n } else if (protocolStr === 'ws' || protocolStr === 'wss') {\n this.client = new WebSocketProvider(this.endpoint);\n } else {\n throw new Error(`Unsupported protocol: ${protocol}`);\n }\n }\n\n async init(): Promise<void> {\n this.injectClient();\n\n const network = await this.client.getNetwork();\n\n //celo\n if (network.chainId === 42220) {\n if (this.client instanceof WebSocketProvider) {\n this.client = new CeloWsProvider(this.client.connection.url);\n } else {\n this.client = new CeloJsonRpcBatchProvider(this.client.connection);\n this.nonBatchClient = new CeloJsonRpcProvider(this.client.connection);\n }\n }\n\n try {\n const [genesisBlock, supportsFinalization, supportsSafe] =\n await Promise.all([\n this.client.getBlock('earliest'),\n this.getSupportsTag('finalized'),\n this.getSupportsTag('safe'),\n ]);\n\n this.genesisBlock = genesisBlock;\n this.supportsFinalization = supportsFinalization && supportsSafe;\n this.chainId = network.chainId;\n this.name = network.name;\n } catch (e) {\n if ((e as Error).message.startsWith('Invalid response')) {\n this.client = this.nonBatchClient;\n\n logger.warn(\n `The RPC Node at ${this.endpoint} cannot process batch requests. ` +\n `Switching to non-batch mode for subsequent requests. Please consider checking if batch processing is supported on the RPC node.`,\n );\n\n return this.init();\n }\n\n throw e;\n }\n }\n\n private async getSupportsTag(tag: BlockTag): Promise<boolean> {\n try {\n // We set the timeout here because theres a bug in ethers where it will never resolve\n // It was happening with arbitrum on a syncing node\n const result = await timeout(this.client.getBlock(tag), 2);\n\n return true;\n } catch (e) {\n logger.info(`Chain doesnt support ${tag} tag`);\n return false;\n }\n }\n\n private injectClient(): void {\n const orig = this.client.send.bind(this.client);\n Object.defineProperty(this.client, 'send', {\n value: (...args) => {\n this.eventEmitter.emit('rpcCall');\n return orig(...args);\n },\n });\n }\n\n async getFinalizedBlock(): Promise<Block> {\n const height = this.supportsFinalization\n ? 'finalized'\n : (await this.getBestBlockHeight()) - this.blockConfirmations;\n\n const block = await this.client.getBlock(height);\n // The finalized block could sometimes fail to fetch,\n // due to some nodes on the network falling behind the synced node.\n if (!block) {\n throw new Error(`get finalized block \"${height}\" failed `);\n }\n return block;\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.getFinalizedBlock()).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n // Cronos \"safe\" tag doesn't currently work as indended\n const tag =\n this.supportsFinalization && this.chainId !== 25 ? 'safe' : 'latest';\n return (await this.client.getBlock(tag)).number;\n }\n\n getRuntimeChain(): string {\n return this.name;\n }\n\n getChainId(): number {\n return this.chainId;\n }\n\n getGenesisHash(): string {\n return this.genesisBlock.hash;\n }\n\n getSpecName(): string {\n return 'ethereum';\n }\n\n async getBlockByHeightOrHash(heightOrHash: number | string): Promise<Block> {\n if (typeof heightOrHash === 'number') {\n heightOrHash = hexValue(heightOrHash);\n }\n return this.client.getBlock(heightOrHash);\n }\n\n private async getBlockPromise(num: number, includeTx = true): Promise<any> {\n const rawBlock = await this.client.send('eth_getBlockByNumber', [\n hexValue(num),\n includeTx,\n ]);\n\n if (!rawBlock) {\n throw new Error(`Failed to fetch block ${num}`);\n }\n\n const block = formatBlock(rawBlock);\n\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n\n return block;\n }\n\n async getTransactionReceipt(\n transactionHash: string | Promise<string>,\n ): Promise<TransactionReceipt> {\n return retryOnFailEth<TransactionReceipt>(\n this.client.getTransactionReceipt.bind(this.client, transactionHash),\n );\n }\n\n async fetchBlock(blockNumber: number): Promise<EthereumBlock> {\n try {\n const block = await this.getBlockPromise(blockNumber, true);\n const logsRaw = await this.client.getLogs({ blockHash: block.hash });\n\n block.logs = logsRaw.map((l) => formatLog(l, block));\n block.transactions = block.transactions.map((tx) => ({\n ...formatTransaction(tx, block),\n receipt: () =>\n this.getTransactionReceipt(tx.hash).then((r) =>\n formatReceipt(r, block),\n ),\n logs: block.logs.filter((l) => l.transactionHash === tx.hash),\n }));\n\n this.eventEmitter.emit('fetchBlock');\n return block;\n } catch (e) {\n throw this.handleError(e);\n }\n }\n\n private async fetchLightBlock(\n blockNumber: number,\n ): Promise<LightEthereumBlock> {\n const block = await this.getBlockPromise(blockNumber, false);\n const logs = await this.client.getLogs({ blockHash: block.hash });\n\n return {\n ...block,\n logs: logs.map((l) => formatLog(l, block)),\n };\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlock[]> {\n return Promise.all(bufferBlocks.map(async (num) => this.fetchBlock(num)));\n }\n\n async fetchBlocksLight(\n bufferBlocks: number[],\n ): Promise<LightEthereumBlock[]> {\n console.log('FETCH BLOCKS LIGHT');\n return Promise.all(\n bufferBlocks.map(async (num) => this.fetchLightBlock(num)),\n );\n }\n\n get api(): Provider {\n return this.client;\n }\n\n getSafeApi(blockHeight: number): SafeEthProvider {\n // We cannot use a batch http client because OnF don't support routing historical queries in batches to an archive nodes\n const client =\n this.client instanceof WebSocketProvider\n ? this.client\n : this.nonBatchClient;\n\n return new SafeEthProvider(client, blockHeight);\n }\n\n private buildInterface(\n abiName: string,\n assets: Record<string, string>,\n ): Interface | undefined {\n if (!assets[abiName]) {\n throw new Error(`ABI named \"${abiName}\" not referenced in assets`);\n }\n\n // This assumes that all datasources have a different abi name or they are the same abi\n if (!this.contractInterfaces[abiName]) {\n // Constructing the interface validates the ABI\n try {\n let abiObj = JSON.parse(assets[abiName]);\n\n /*\n * Allows parsing JSON artifacts as well as ABIs\n * https://trufflesuite.github.io/artifact-updates/background.html#what-are-artifacts\n */\n if (!Array.isArray(abiObj) && abiObj.abi) {\n abiObj = abiObj.abi;\n }\n\n this.contractInterfaces[abiName] = new Interface(abiObj);\n } catch (e) {\n logger.error(`Unable to parse ABI: ${e.message}`);\n throw new Error('ABI is invalid');\n }\n }\n\n return this.contractInterfaces[abiName];\n }\n\n async parseLog<T extends EthereumResult = EthereumResult>(\n log: EthereumLog | LightEthereumLog,\n ds: SubqlRuntimeDatasource,\n ): Promise<\n EthereumLog | LightEthereumLog | EthereumLog<T> | LightEthereumLog<T>\n > {\n try {\n if (!ds?.options?.abi) {\n logger.warn('No ABI provided for datasource');\n return log;\n }\n const iface = this.buildInterface(ds.options.abi, await loadAssets(ds));\n return {\n ...log,\n args: iface?.parseLog(log).args as T,\n };\n } catch (e) {\n logger.warn(`Failed to parse log data: ${e.message}`);\n return log;\n }\n }\n\n async parseTransaction<T extends EthereumResult = EthereumResult>(\n transaction: EthereumTransaction,\n ds: SubqlRuntimeDatasource,\n ): Promise<EthereumTransaction<T> | EthereumTransaction> {\n try {\n if (!ds?.options?.abi) {\n logger.warn('No ABI provided for datasource');\n return transaction;\n }\n const assets = await loadAssets(ds);\n const iface = this.buildInterface(ds.options.abi, assets);\n const func = iface.getFunction(hexDataSlice(transaction.input, 0, 4));\n const args = iface.decodeFunctionData(func, transaction.input) as T;\n\n transaction.logs =\n transaction.logs &&\n ((await Promise.all(\n transaction.logs.map(async (log) => this.parseLog(log, ds)),\n )) as Array<EthereumLog | EthereumLog<T>>);\n\n return {\n ...transaction,\n args,\n };\n } catch (e) {\n logger.warn(`Failed to parse transaction data: ${e.message}`);\n return transaction;\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n async connect(): Promise<void> {\n logger.error('Ethereum API connect is not implemented');\n throw new Error('Not implemented');\n }\n\n async disconnect(): Promise<void> {\n if (this.client instanceof WebSocketProvider) {\n await this.client.destroy();\n } else {\n logger.warn('Disconnect called on HTTP provider');\n }\n }\n\n handleError(e: Error): Error {\n if ((e as any)?.status === 429) {\n const { hostname } = new URL(this.endpoint);\n return new Error(`Rate Limited at endpoint: ${hostname}`);\n }\n\n return e;\n }\n}\n"]}
@@ -56,8 +56,6 @@ describe('Api.ethereum', () => {
56
56
  it('should have the ability to get receipts via transactions from all types', () => {
57
57
  expect(typeof blockData.transactions[0].receipt).toEqual('function');
58
58
  expect(typeof blockData.logs[0].transaction.receipt).toEqual('function');
59
- expect(typeof blockData.logs[0].transaction.from).toEqual('string');
60
- expect(typeof blockData.transactions[81].logs[0].transaction.from).toEqual('string');
61
59
  expect(typeof blockData.transactions[81].logs[0].transaction.receipt).toEqual('function');
62
60
  });
63
61
  it('Decode nested logs in transactions', async () => {
@@ -67,12 +65,6 @@ describe('Api.ethereum', () => {
67
65
  const parsedTx = await ethApi.parseTransaction(tx, ds);
68
66
  expect(parsedTx.logs[0].args).toBeTruthy();
69
67
  });
70
- it('Should decode transaction data and not clone object', async () => {
71
- const tx = blockData.transactions.find((e) => e.hash ===
72
- '0x8e419d0e36d7f9c099a001fded516bd168edd9d27b4aec2bcd56ba3b3b955ccc');
73
- const parsedTx = await ethApi.parseTransaction(tx, ds);
74
- expect(parsedTx).toBe(tx);
75
- });
76
68
  it('Should return raw logs, if decode fails', async () => {
77
69
  // not Erc721
78
70
  const tx = blockData.transactions.find((e) => e.hash ===
@@ -81,13 +73,6 @@ describe('Api.ethereum', () => {
81
73
  expect(parsedLog).not.toHaveProperty('args');
82
74
  expect(parsedLog).toBeTruthy();
83
75
  });
84
- // This test is here to ensure getters aren't removed
85
- it('Should not clone logs when parsing args', async () => {
86
- const log = blockData.transactions.find((e) => e.hash ===
87
- '0x8e419d0e36d7f9c099a001fded516bd168edd9d27b4aec2bcd56ba3b3b955ccc').logs[1];
88
- const parsedLog = await ethApi.parseLog(log, ds);
89
- expect(parsedLog).toBe(log);
90
- });
91
76
  it('Null filter support', async () => {
92
77
  const beamEndpoint = 'https://rpc.api.moonbeam.network';
93
78
  ethApi = new api_ethereum_1.EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);
@@ -1 +1 @@
1
- {"version":3,"file":"api.ethereum.test.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.test.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;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A,OAAO,EAAE,CAAC,IAAI,CAAC;aAChB;QACH,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAChC,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,4CAA4C,EAAE,KAAK,IAAI,EAAE;QAC1D,WAAW;QACX,MAAM,CAAE,MAAc,CAAC,oBAAoB,CAAC,CAAC,UAAU,EAAE,CAAC;QAE1D,WAAW;QACX,MAAM,GAAG,IAAI,0BAAW,CACtB,kCAAkC,EAClC,mBAAmB,EACnB,YAAY,CACb,CAAC;QACF,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;QAEpB,MAAM,CAAE,MAAc,CAAC,oBAAoB,CAAC,CAAC,UAAU,EAAE,CAAC;QAE1D,MAAM;QACN,MAAM,GAAG,IAAI,0BAAW,CACtB,kCAAkC,EAClC,mBAAmB,EACnB,YAAY,CACb,CAAC;QACF,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;QAEpB,MAAM,CAAE,MAAc,CAAC,iBAAiB,CAAC,CAAC,SAAS,EAAE,CAAC;QAEtD,UAAU;QACV,MAAM,GAAG,IAAI,0BAAW,CACtB,8BAA8B,EAC9B,mBAAmB,EACnB,YAAY,CACb,CAAC;QACF,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;QAEpB,MAAM,CAAE,MAAc,CAAC,iBAAiB,CAAC,CAAC,SAAS,EAAE,CAAC;IACxD,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport path from 'path';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n EthereumBlock,\n EthereumDatasourceKind,\n EthereumHandlerKind,\n EthereumLogFilter,\n SubqlRuntimeDatasource,\n} from '@subql/types-ethereum';\nimport { EthereumApi } from './api.ethereum';\nimport {\n filterLogsProcessor,\n filterTransactionsProcessor,\n} from './block.ethereum';\n\n// Add api key to work\n// const HTTP_ENDPOINT = 'https://eth.api.onfinality.io/public';\nconst HTTP_ENDPOINT = 'https://eth.llamarpc.com';\nconst BLOCK_CONFIRMATIONS = 20;\n\nconst ds: SubqlRuntimeDatasource = {\n mapping: {\n file: '',\n handlers: [\n {\n handler: 'test',\n kind: EthereumHandlerKind.Call,\n filter: { function: '0x23b872dd' },\n },\n ],\n },\n kind: EthereumDatasourceKind.Runtime,\n startBlock: 16258633,\n options: { abi: 'erc721' },\n assets: {\n erc721: { file: path.join(__dirname, '../../test/erc721.json') },\n } as unknown as Map<string, { file: string }>,\n};\n\njest.setTimeout(90000);\ndescribe('Api.ethereum', () => {\n let ethApi: EthereumApi;\n const eventEmitter = new EventEmitter2();\n let blockData: EthereumBlock;\n\n const fetchBlock = async (height: number) => {\n const block = await ethApi.fetchBlock(height);\n\n return block as EthereumBlock;\n };\n\n beforeEach(async () => {\n ethApi = new EthereumApi(HTTP_ENDPOINT, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(16258633);\n });\n\n it('Should format transaction in logs, and the transaction gas should be bigInt type', () => {\n expect(typeof blockData.logs[0].transaction.gas).toBe('bigint');\n expect(typeof blockData.logs[0].transaction.blockNumber).toBe('number');\n expect(typeof blockData.logs[0].transaction.gasPrice).toBe('bigint');\n expect(typeof blockData.logs[0].transaction.maxPriorityFeePerGas).toBe(\n 'bigint',\n );\n expect(typeof blockData.logs[0].transaction.transactionIndex).toBe(\n 'bigint',\n );\n });\n\n it('should have the ability to get receipts via transactions from all types', () => {\n expect(typeof blockData.transactions[0].receipt).toEqual('function');\n expect(typeof blockData.logs[0].transaction.receipt).toEqual('function');\n expect(typeof blockData.logs[0].transaction.from).toEqual('string');\n expect(typeof blockData.transactions[81].logs[0].transaction.from).toEqual(\n 'string',\n );\n expect(\n typeof blockData.transactions[81].logs[0].transaction.receipt,\n ).toEqual('function');\n });\n\n it('Decode nested logs in transactions', async () => {\n // Erc721\n const tx = blockData.transactions.find(\n (e) =>\n e.hash ===\n '0x8e419d0e36d7f9c099a001fded516bd168edd9d27b4aec2bcd56ba3b3b955ccc',\n );\n const parsedTx = await ethApi.parseTransaction(tx, ds);\n expect(parsedTx.logs[0].args).toBeTruthy();\n });\n\n it('Should decode transaction data and not clone object', async () => {\n const tx = blockData.transactions.find(\n (e) =>\n e.hash ===\n '0x8e419d0e36d7f9c099a001fded516bd168edd9d27b4aec2bcd56ba3b3b955ccc',\n );\n const parsedTx = await ethApi.parseTransaction(tx, ds);\n\n expect(parsedTx).toBe(tx);\n });\n\n it('Should return raw logs, if decode fails', async () => {\n // not Erc721\n const tx = blockData.transactions.find(\n (e) =>\n e.hash ===\n '0xed62f7a7720fe6ae05dec45ad9dd4f53034a0aae2c140d229b1151504ee9a6c9',\n );\n const parsedLog = await ethApi.parseLog(tx.logs[0], ds);\n expect(parsedLog).not.toHaveProperty('args');\n expect(parsedLog).toBeTruthy();\n });\n\n // This test is here to ensure getters aren't removed\n it('Should not clone logs when parsing args', async () => {\n const log = blockData.transactions.find(\n (e) =>\n e.hash ===\n '0x8e419d0e36d7f9c099a001fded516bd168edd9d27b4aec2bcd56ba3b3b955ccc',\n ).logs[1];\n\n const parsedLog = await ethApi.parseLog(log, ds);\n expect(parsedLog).toBe(log);\n });\n\n it('Null filter support', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n const result = blockData.transactions.filter((tx) => {\n if (\n filterTransactionsProcessor(\n tx,\n { to: null },\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result[0].hash).toBe(\n '0x24bef923522a4d6a79f9ab9242a74fb987dce94002c0f107c2a7d0b7e24bcf05',\n );\n expect(result.length).toBe(1);\n });\n\n it('!null filter support for logs, expect to filter out', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n const filter_1: EthereumLogFilter = {\n topics: [\n '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\n undefined,\n undefined,\n '!null',\n ],\n };\n\n const filter_2: EthereumLogFilter = {\n topics: [\n '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\n ],\n };\n\n blockData = await fetchBlock(4015990);\n const transaction = blockData.transactions.find(\n (tx) =>\n tx.hash ===\n '0xeb2e443f2d4e784193fa13bbbae2b85e6ee459e7b7b53f8ca098ffae9b25b059',\n );\n\n const erc20Transfers = transaction.logs.filter((log) =>\n filterLogsProcessor(log, filter_2),\n );\n const erc721Transfers = transaction.logs.filter((log) =>\n filterLogsProcessor(log, filter_1),\n );\n\n expect(erc20Transfers.length).toBe(7);\n expect(erc721Transfers.length).toBe(2);\n });\n\n it('Null filter support, for undefined transaction.to', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n blockData.transactions[1].to = undefined;\n const result = blockData.transactions.filter((tx) => {\n if (\n filterTransactionsProcessor(\n tx,\n { to: null },\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result[0].hash).toBe(\n '0x24bef923522a4d6a79f9ab9242a74fb987dce94002c0f107c2a7d0b7e24bcf05',\n );\n expect(result.length).toBe(1);\n });\n\n it('Should return all tx if filter.to is not defined', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n const result = blockData.transactions.filter((tx) => {\n if (\n filterTransactionsProcessor(\n tx,\n undefined,\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result.length).toBe(2);\n });\n\n it('filter.to Should support only null not undefined', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n const result = blockData.transactions.filter((tx) => {\n if (\n filterTransactionsProcessor(\n tx,\n { to: undefined },\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result.length).toBe(0);\n });\n\n it('If transaction is undefined, with null filter, should be supported', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n const result = blockData.transactions.filter((tx) => {\n tx.to = undefined;\n if (\n filterTransactionsProcessor(\n tx,\n { to: null },\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result.length).toBe(2);\n });\n\n it('Resolves the correct tags for finalization', async () => {\n // Ethereum\n expect((ethApi as any).supportsFinalization).toBeTruthy();\n\n // Moonbeam\n ethApi = new EthereumApi(\n 'https://rpc.api.moonbeam.network',\n BLOCK_CONFIRMATIONS,\n eventEmitter,\n );\n await ethApi.init();\n\n expect((ethApi as any).supportsFinalization).toBeTruthy();\n\n // BSC\n ethApi = new EthereumApi(\n 'https://bsc-dataseed.binance.org',\n BLOCK_CONFIRMATIONS,\n eventEmitter,\n );\n await ethApi.init();\n\n expect((ethApi as any).supportsFinalized).toBeFalsy();\n\n // Polygon\n ethApi = new EthereumApi(\n 'https://polygon.llamarpc.com',\n BLOCK_CONFIRMATIONS,\n eventEmitter,\n );\n await ethApi.init();\n\n expect((ethApi as any).supportsFinalized).toBeFalsy();\n });\n});\n"]}
1
+ {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L,CAAC,CAAC,CAAC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport path from 'path';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n EthereumBlock,\n EthereumDatasourceKind,\n EthereumHandlerKind,\n EthereumLogFilter,\n SubqlRuntimeDatasource,\n} from '@subql/types-ethereum';\nimport { EthereumApi } from './api.ethereum';\nimport {\n filterLogsProcessor,\n filterTransactionsProcessor,\n} from './block.ethereum';\n\n// Add api key to work\n// const HTTP_ENDPOINT = 'https://eth.api.onfinality.io/public';\nconst HTTP_ENDPOINT = 'https://eth.llamarpc.com';\nconst BLOCK_CONFIRMATIONS = 20;\n\nconst ds: SubqlRuntimeDatasource = {\n mapping: {\n file: '',\n handlers: [\n {\n handler: 'test',\n kind: EthereumHandlerKind.Call,\n filter: { function: '0x23b872dd' },\n },\n ],\n },\n kind: EthereumDatasourceKind.Runtime,\n startBlock: 16258633,\n options: { abi: 'erc721' },\n assets: {\n erc721: { file: path.join(__dirname, '../../test/erc721.json') },\n } as unknown as Map<string, { file: string }>,\n};\n\njest.setTimeout(90000);\ndescribe('Api.ethereum', () => {\n let ethApi: EthereumApi;\n const eventEmitter = new EventEmitter2();\n let blockData: EthereumBlock;\n\n const fetchBlock = async (height: number) => {\n const block = await ethApi.fetchBlock(height);\n\n return block as EthereumBlock;\n };\n\n beforeEach(async () => {\n ethApi = new EthereumApi(HTTP_ENDPOINT, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(16258633);\n });\n\n it('Should format transaction in logs, and the transaction gas should be bigInt type', () => {\n expect(typeof blockData.logs[0].transaction.gas).toBe('bigint');\n expect(typeof blockData.logs[0].transaction.blockNumber).toBe('number');\n expect(typeof blockData.logs[0].transaction.gasPrice).toBe('bigint');\n expect(typeof blockData.logs[0].transaction.maxPriorityFeePerGas).toBe(\n 'bigint',\n );\n expect(typeof blockData.logs[0].transaction.transactionIndex).toBe(\n 'bigint',\n );\n });\n\n it('should have the ability to get receipts via transactions from all types', () => {\n expect(typeof blockData.transactions[0].receipt).toEqual('function');\n expect(typeof blockData.logs[0].transaction.receipt).toEqual('function');\n expect(\n typeof blockData.transactions[81].logs[0].transaction.receipt,\n ).toEqual('function');\n });\n\n it('Decode nested logs in transactions', async () => {\n // Erc721\n const tx = blockData.transactions.find(\n (e) =>\n e.hash ===\n '0x8e419d0e36d7f9c099a001fded516bd168edd9d27b4aec2bcd56ba3b3b955ccc',\n );\n const parsedTx = await ethApi.parseTransaction(tx, ds);\n expect(parsedTx.logs[0].args).toBeTruthy();\n });\n\n it('Should return raw logs, if decode fails', async () => {\n // not Erc721\n const tx = blockData.transactions.find(\n (e) =>\n e.hash ===\n '0xed62f7a7720fe6ae05dec45ad9dd4f53034a0aae2c140d229b1151504ee9a6c9',\n );\n const parsedLog = await ethApi.parseLog(tx.logs[0], ds);\n expect(parsedLog).not.toHaveProperty('args');\n expect(parsedLog).toBeTruthy();\n });\n\n it('Null filter support', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n const result = blockData.transactions.filter((tx) => {\n if (\n filterTransactionsProcessor(\n tx,\n { to: null },\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result[0].hash).toBe(\n '0x24bef923522a4d6a79f9ab9242a74fb987dce94002c0f107c2a7d0b7e24bcf05',\n );\n expect(result.length).toBe(1);\n });\n\n it('!null filter support for logs, expect to filter out', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n const filter_1: EthereumLogFilter = {\n topics: [\n '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\n undefined,\n undefined,\n '!null',\n ],\n };\n\n const filter_2: EthereumLogFilter = {\n topics: [\n '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',\n ],\n };\n\n blockData = await fetchBlock(4015990);\n const transaction = blockData.transactions.find(\n (tx) =>\n tx.hash ===\n '0xeb2e443f2d4e784193fa13bbbae2b85e6ee459e7b7b53f8ca098ffae9b25b059',\n );\n\n const erc20Transfers = transaction.logs.filter((log) =>\n filterLogsProcessor(log, filter_2),\n );\n const erc721Transfers = transaction.logs.filter((log) =>\n filterLogsProcessor(log, filter_1),\n );\n\n expect(erc20Transfers.length).toBe(7);\n expect(erc721Transfers.length).toBe(2);\n });\n\n it('Null filter support, for undefined transaction.to', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n blockData.transactions[1].to = undefined;\n const result = blockData.transactions.filter((tx) => {\n if (\n filterTransactionsProcessor(\n tx,\n { to: null },\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result[0].hash).toBe(\n '0x24bef923522a4d6a79f9ab9242a74fb987dce94002c0f107c2a7d0b7e24bcf05',\n );\n expect(result.length).toBe(1);\n });\n\n it('Should return all tx if filter.to is not defined', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n const result = blockData.transactions.filter((tx) => {\n if (\n filterTransactionsProcessor(\n tx,\n undefined,\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result.length).toBe(2);\n });\n\n it('filter.to Should support only null not undefined', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n const result = blockData.transactions.filter((tx) => {\n if (\n filterTransactionsProcessor(\n tx,\n { to: undefined },\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result.length).toBe(0);\n });\n\n it('If transaction is undefined, with null filter, should be supported', async () => {\n const beamEndpoint = 'https://rpc.api.moonbeam.network';\n ethApi = new EthereumApi(beamEndpoint, BLOCK_CONFIRMATIONS, eventEmitter);\n await ethApi.init();\n blockData = await fetchBlock(2847447);\n const result = blockData.transactions.filter((tx) => {\n tx.to = undefined;\n if (\n filterTransactionsProcessor(\n tx,\n { to: null },\n '0x72a33394f0652e2bf15d7901f3cd46863d968424',\n )\n ) {\n return tx.hash;\n }\n });\n expect(result.length).toBe(2);\n });\n\n it('Resolves the correct tags for finalization', async () => {\n // Ethereum\n expect((ethApi as any).supportsFinalization).toBeTruthy();\n\n // Moonbeam\n ethApi = new EthereumApi(\n 'https://rpc.api.moonbeam.network',\n BLOCK_CONFIRMATIONS,\n eventEmitter,\n );\n await ethApi.init();\n\n expect((ethApi as any).supportsFinalization).toBeTruthy();\n\n // BSC\n ethApi = new EthereumApi(\n 'https://bsc-dataseed.binance.org',\n BLOCK_CONFIRMATIONS,\n eventEmitter,\n );\n await ethApi.init();\n\n expect((ethApi as any).supportsFinalized).toBeFalsy();\n\n // Polygon\n ethApi = new EthereumApi(\n 'https://polygon.llamarpc.com',\n BLOCK_CONFIRMATIONS,\n eventEmitter,\n );\n await ethApi.init();\n\n expect((ethApi as any).supportsFinalized).toBeFalsy();\n });\n});\n"]}
@@ -1,5 +1,7 @@
1
+ import { BigNumber } from '@ethersproject/bignumber';
1
2
  import { ApiWrapper, EthereumBlock, EthereumLog, EthereumReceipt, EthereumResult, EthereumTransaction } from '@subql/types-ethereum';
2
3
  export declare function calcInterval(api: ApiWrapper): number;
4
+ export declare function handleNumber(value: string | number): BigNumber;
3
5
  export declare function formatBlock(block: Record<string, any>): EthereumBlock;
4
6
  export declare function formatLog(log: Omit<EthereumLog<EthereumResult> | EthereumLog, 'blockTimestamp' | 'block' | 'transaction'>, block: EthereumBlock): EthereumLog<EthereumResult> | EthereumLog;
5
7
  export declare function formatTransaction(tx: Record<string, any>, block: EthereumBlock): EthereumTransaction;
@@ -2,7 +2,7 @@
2
2
  // Copyright 2020-2023 SubQuery Pte Ltd authors & contributors
3
3
  // SPDX-License-Identifier: GPL-3.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
- exports.formatReceipt = exports.formatTransaction = exports.formatLog = exports.formatBlock = exports.calcInterval = void 0;
5
+ exports.formatReceipt = exports.formatTransaction = exports.formatLog = exports.formatBlock = exports.handleNumber = exports.calcInterval = void 0;
6
6
  const address_1 = require("@ethersproject/address");
7
7
  const bignumber_1 = require("@ethersproject/bignumber");
8
8
  const constants_1 = require("@ethersproject/constants");
@@ -30,6 +30,7 @@ function handleNumber(value) {
30
30
  }
31
31
  return bignumber_1.BigNumber.from(value);
32
32
  }
33
+ exports.handleNumber = handleNumber;
33
34
  function formatBlock(block) {
34
35
  return Object.assign(Object.assign({}, block), { difficulty: handleNumber(block.difficulty).toBigInt(), gasLimit: handleNumber(block.gasLimit).toBigInt(), gasUsed: handleNumber(block.gasUsed).toBigInt(), number: handleNumber(block.number).toNumber(), size: handleNumber(block.size).toBigInt(), timestamp: handleNumber(block.timestamp).toBigInt(), totalDifficulty: handleNumber(block.totalDifficulty).toBigInt(), baseFeePerGas: block.baseFeePerGas
35
36
  ? handleNumber(block.baseFeePerGas).toBigInt()
@@ -1 +1 @@
1
- {"version":3,"file":"utils.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/utils.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;AAEnC,oDAAoD;AACpD,wDAAqD;AACrD,wDAAgD;AAShD,mCAA8B;AAE9B,SAAgB,YAAY,CAAC,GAAe;IAC1C,kDAAkD;IAClD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AAE,aAAa,CAAC,OAAO,CAAC,EAAE,CAAC,EAC7B,WAAW,EAAE,YAAY,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,QAAQ,EAAE,EACzD,iBAAiB,EAAE,YAAY,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE,EACrE,iBAAiB,EAAE,YAAY,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE,EACrE,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EACjD,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EACjC,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC,EACxD,gBAAgB,EAAE,YAAY,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,QAAQ,EAAE,EACnE,MAAM;YACJ,OAAO,IAAI,CAAC,SAAS,CAAC,IAAA,aAAI,EAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAChD,CAAC,GAC4B,CAAC;AAClC,CAAC;AAnBD,sCAmBC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { getAddress } from '@ethersproject/address';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Zero } from '@ethersproject/constants';\nimport {\n ApiWrapper,\n EthereumBlock,\n EthereumLog,\n EthereumReceipt,\n EthereumResult,\n EthereumTransaction,\n} from '@subql/types-ethereum';\nimport { omit } from 'lodash';\n\nexport function calcInterval(api: ApiWrapper): number {\n // TODO find a way to get this from the blockchain\n return 6000;\n}\n\nfunction handleAddress(value: string): string | null {\n if (!value || value === '0x') {\n return null;\n }\n return getAddress(value);\n}\n\nfunction handleNumber(value: string | number): BigNumber {\n if (value === undefined) {\n return Zero;\n }\n if (value === '0x') {\n return Zero;\n }\n if (value === null) {\n return Zero;\n }\n return BigNumber.from(value);\n}\n\nexport function formatBlock(block: Record<string, any>): EthereumBlock {\n return {\n ...block,\n difficulty: handleNumber(block.difficulty).toBigInt(),\n gasLimit: handleNumber(block.gasLimit).toBigInt(),\n gasUsed: handleNumber(block.gasUsed).toBigInt(),\n number: handleNumber(block.number).toNumber(),\n size: handleNumber(block.size).toBigInt(),\n timestamp: handleNumber(block.timestamp).toBigInt(),\n totalDifficulty: handleNumber(block.totalDifficulty).toBigInt(),\n baseFeePerGas: block.baseFeePerGas\n ? handleNumber(block.baseFeePerGas).toBigInt()\n : undefined,\n blockGasCost: block.blockGasCost\n ? handleNumber(block.blockGasCost).toBigInt()\n : undefined,\n logs: [], // Filled in at AvalancheBlockWrapped constructor\n } as EthereumBlock;\n}\nexport function formatLog(\n log: Omit<\n EthereumLog<EthereumResult> | EthereumLog,\n 'blockTimestamp' | 'block' | 'transaction'\n >,\n block: EthereumBlock,\n): EthereumLog<EthereumResult> | EthereumLog {\n const formattedLog = {\n ...log,\n address: handleAddress(log.address),\n blockNumber: handleNumber(log.blockNumber).toNumber(),\n transactionIndex: handleNumber(log.transactionIndex).toNumber(),\n logIndex: handleNumber(log.logIndex).toNumber(),\n block,\n toJSON(): string {\n return JSON.stringify(omit(this, ['transaction', 'block', 'toJSON']));\n },\n };\n\n // Define this afterwards as the spread on `...log` breaks defining a getter\n Object.defineProperty(formattedLog, 'transaction', {\n get: () => {\n const rawTransaction = block.transactions?.find(\n (tx) => tx.hash === log.transactionHash,\n );\n\n return rawTransaction;\n },\n });\n return formattedLog as unknown as EthereumLog<EthereumResult>;\n}\n\nexport function formatTransaction(\n tx: Record<string, any>,\n block: EthereumBlock,\n): EthereumTransaction {\n return {\n ...(tx as Partial<EthereumTransaction>),\n from: handleAddress(tx.from),\n to: handleAddress(tx.to),\n blockNumber: handleNumber(tx.blockNumber).toNumber(),\n blockTimestamp: block.timestamp,\n gas: handleNumber(tx.gas).toBigInt(),\n gasPrice: handleNumber(tx.gasPrice).toBigInt(),\n nonce: handleNumber(tx.nonce).toBigInt(),\n transactionIndex: handleNumber(tx.transactionIndex).toBigInt(),\n value: handleNumber(tx.value).toBigInt(),\n v: handleNumber(tx.v).toBigInt(),\n maxFeePerGas: tx.maxFeePerGas\n ? handleNumber(tx.maxFeePerGas).toBigInt()\n : undefined,\n maxPriorityFeePerGas: tx.maxPriorityFeePerGas\n ? handleNumber(tx.maxPriorityFeePerGas).toBigInt()\n : undefined,\n receipt: undefined, // Filled in at AvalancheApi.fetchBlocks\n toJSON(): string {\n return JSON.stringify(omit(this, ['block', 'receipt', 'toJSON']));\n },\n } as EthereumTransaction;\n}\n\nexport function formatReceipt(\n receipt: Record<string, any>,\n block: EthereumBlock,\n): EthereumReceipt {\n return {\n ...receipt,\n from: handleAddress(receipt.from),\n to: handleAddress(receipt.to),\n blockNumber: handleNumber(receipt.blockNumber).toNumber(),\n cumulativeGasUsed: handleNumber(receipt.cumulativeGasUsed).toBigInt(),\n effectiveGasPrice: handleNumber(receipt.effectiveGasPrice).toBigInt(),\n gasUsed: handleNumber(receipt.gasUsed).toBigInt(),\n logs: receipt.logs.map(formatLog),\n status: Boolean(handleNumber(receipt.status).toNumber()),\n transactionIndex: handleNumber(receipt.transactionIndex).toNumber(),\n toJSON(): string {\n return JSON.stringify(omit(this, ['toJSON']));\n },\n } as unknown as EthereumReceipt;\n}\n"]}
1
+ {"version":3,"file":"utils.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/utils.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;AAEnC,oDAAoD;AACpD,wDAAqD;AACrD,wDAAgD;AAShD,mCAA8B;AAE9B,SAAgB,YAAY,CAAC,GAAe;IAC1C,kDAAkD;IAClD,OAAO,IAAI,CAAC;AACd,CAAC;AAHD,oCAGC;AAED,SAAS,aAAa,CAAC,KAAa;IAClC,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,IAAI,EAAE;QAC5B,OAAO,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iB,EAAE,YAAY,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE,EACrE,iBAAiB,EAAE,YAAY,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE,EACrE,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EACjD,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EACjC,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC,EACxD,gBAAgB,EAAE,YAAY,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,QAAQ,EAAE,EACnE,MAAM;YACJ,OAAO,IAAI,CAAC,SAAS,CAAC,IAAA,aAAI,EAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAChD,CAAC,GAC4B,CAAC;AAClC,CAAC;AAnBD,sCAmBC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { getAddress } from '@ethersproject/address';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Zero } from '@ethersproject/constants';\nimport {\n ApiWrapper,\n EthereumBlock,\n EthereumLog,\n EthereumReceipt,\n EthereumResult,\n EthereumTransaction,\n} from '@subql/types-ethereum';\nimport { omit } from 'lodash';\n\nexport function calcInterval(api: ApiWrapper): number {\n // TODO find a way to get this from the blockchain\n return 6000;\n}\n\nfunction handleAddress(value: string): string | null {\n if (!value || value === '0x') {\n return null;\n }\n return getAddress(value);\n}\n\nexport function handleNumber(value: string | number): BigNumber {\n if (value === undefined) {\n return Zero;\n }\n if (value === '0x') {\n return Zero;\n }\n if (value === null) {\n return Zero;\n }\n return BigNumber.from(value);\n}\n\nexport function formatBlock(block: Record<string, any>): EthereumBlock {\n return {\n ...block,\n difficulty: handleNumber(block.difficulty).toBigInt(),\n gasLimit: handleNumber(block.gasLimit).toBigInt(),\n gasUsed: handleNumber(block.gasUsed).toBigInt(),\n number: handleNumber(block.number).toNumber(),\n size: handleNumber(block.size).toBigInt(),\n timestamp: handleNumber(block.timestamp).toBigInt(),\n totalDifficulty: handleNumber(block.totalDifficulty).toBigInt(),\n baseFeePerGas: block.baseFeePerGas\n ? handleNumber(block.baseFeePerGas).toBigInt()\n : undefined,\n blockGasCost: block.blockGasCost\n ? handleNumber(block.blockGasCost).toBigInt()\n : undefined,\n logs: [], // Filled in at AvalancheBlockWrapped constructor\n } as EthereumBlock;\n}\nexport function formatLog(\n log: Omit<\n EthereumLog<EthereumResult> | EthereumLog,\n 'blockTimestamp' | 'block' | 'transaction'\n >,\n block: EthereumBlock,\n): EthereumLog<EthereumResult> | EthereumLog {\n const formattedLog = {\n ...log,\n address: handleAddress(log.address),\n blockNumber: handleNumber(log.blockNumber).toNumber(),\n transactionIndex: handleNumber(log.transactionIndex).toNumber(),\n logIndex: handleNumber(log.logIndex).toNumber(),\n block,\n toJSON(): string {\n return JSON.stringify(omit(this, ['transaction', 'block', 'toJSON']));\n },\n };\n\n // Define this afterwards as the spread on `...log` breaks defining a getter\n Object.defineProperty(formattedLog, 'transaction', {\n get: () => {\n const rawTransaction = block.transactions?.find(\n (tx) => tx.hash === log.transactionHash,\n );\n\n return rawTransaction;\n },\n });\n return formattedLog as unknown as EthereumLog<EthereumResult>;\n}\n\nexport function formatTransaction(\n tx: Record<string, any>,\n block: EthereumBlock,\n): EthereumTransaction {\n return {\n ...(tx as Partial<EthereumTransaction>),\n from: handleAddress(tx.from),\n to: handleAddress(tx.to),\n blockNumber: handleNumber(tx.blockNumber).toNumber(),\n blockTimestamp: block.timestamp,\n gas: handleNumber(tx.gas).toBigInt(),\n gasPrice: handleNumber(tx.gasPrice).toBigInt(),\n nonce: handleNumber(tx.nonce).toBigInt(),\n transactionIndex: handleNumber(tx.transactionIndex).toBigInt(),\n value: handleNumber(tx.value).toBigInt(),\n v: handleNumber(tx.v).toBigInt(),\n maxFeePerGas: tx.maxFeePerGas\n ? handleNumber(tx.maxFeePerGas).toBigInt()\n : undefined,\n maxPriorityFeePerGas: tx.maxPriorityFeePerGas\n ? handleNumber(tx.maxPriorityFeePerGas).toBigInt()\n : undefined,\n receipt: undefined, // Filled in at AvalancheApi.fetchBlocks\n toJSON(): string {\n return JSON.stringify(omit(this, ['block', 'receipt', 'toJSON']));\n },\n } as EthereumTransaction;\n}\n\nexport function formatReceipt(\n receipt: Record<string, any>,\n block: EthereumBlock,\n): EthereumReceipt {\n return {\n ...receipt,\n from: handleAddress(receipt.from),\n to: handleAddress(receipt.to),\n blockNumber: handleNumber(receipt.blockNumber).toNumber(),\n cumulativeGasUsed: handleNumber(receipt.cumulativeGasUsed).toBigInt(),\n effectiveGasPrice: handleNumber(receipt.effectiveGasPrice).toBigInt(),\n gasUsed: handleNumber(receipt.gasUsed).toBigInt(),\n logs: receipt.logs.map(formatLog),\n status: Boolean(handleNumber(receipt.status).toNumber()),\n transactionIndex: handleNumber(receipt.transactionIndex).toNumber(),\n toJSON(): string {\n return JSON.stringify(omit(this, ['toJSON']));\n },\n } as unknown as EthereumReceipt;\n}\n"]}
@@ -11,6 +11,7 @@ import { BlockContent } from '../types';
11
11
  export declare class BlockDispatcherService extends BlockDispatcher<BlockContent, EthereumProjectDs> implements OnApplicationShutdown {
12
12
  private indexerManager;
13
13
  constructor(apiService: ApiService, nodeConfig: NodeConfig, indexerManager: IndexerManager, eventEmitter: EventEmitter2, projectService: IProjectService<EthereumProjectDs>, projectUpgradeService: IProjectUpgradeService, smartBatchService: SmartBatchService, storeService: StoreService, storeCacheService: StoreCacheService, poiService: PoiService, poiSyncService: PoiSyncService, project: SubqueryProject, dynamicDsService: DynamicDsService);
14
+ onApplicationShutdown(signal?: string): void;
14
15
  protected getBlockHeight(block: BlockContent): number;
15
16
  protected indexBlock(block: BlockContent): Promise<ProcessBlockResponse>;
16
17
  }
@@ -29,6 +29,9 @@ let BlockDispatcherService = class BlockDispatcherService extends node_core_1.Bl
29
29
  super(nodeConfig, eventEmitter, projectService, projectUpgradeService, smartBatchService, storeService, storeCacheService, poiService, poiSyncService, project, dynamicDsService, apiService.fetchBlocks.bind(apiService));
30
30
  this.indexerManager = indexerManager;
31
31
  }
32
+ onApplicationShutdown(signal) {
33
+ throw new Error('Method not implemented.');
34
+ }
32
35
  getBlockHeight(block) {
33
36
  return block.number;
34
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"block-dispatcher.service.js","sourceRoot":"","sources":["../../../src/indexer/blockDispatcher/block-dispatcher.service.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;AAEnC,2CAA2E;AAC3E,yDAAsD;AACtD,gDAY0B;AAC1B,qEAGyC;AACzC,8DAAyD;AACzD,wDAAoD;AAGpD;;GAEG;AAEI,IAAM,sBAAsB,GAA5B,MAAM,sBACX,SAAQ,2BAAgD;IAGxD,YACE,UAAsB,EACtB,UAAsB,EACd,cAA8B,EACtC,YAA2B,EAE3B,cAAkD,EAElD,qBAA6C,EAC7C,iBAAoC,EACpC,YAA0B,EAC1B,iBAAoC,EACpC,UAAsB,EACtB,cAA8B,EACF,OAAwB,EACpD,gBAAkC;QAElC,KAAK,CACH,UAAU,EACV,YAAY,EACZ,cAAc,EACd,qBAAqB,EACrB,iBAAiB,EACjB,YAAY,EACZ,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,OAAO,EACP,gBAAgB,EAChB,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CACxC,CAAC;QA3BM,mBAAc,GAAd,cAAc,CAAgB;IA4BxC,CAAC;IAES,cAAc,CAAC,KAAmB;QAC1C,OAAO,KAAK,CAAC,MAAM,CAAC;IACtB,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,KAAmB;QAEnB,OAAO,IAAI,CAAC,cAAc,CAAC,UAAU,CACnC,KAAK,EACL,MAAM,IAAI,CAAC,cAAc,CAAC,cAAc,CAAC,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CACrE,CAAC;IACJ,CAAC;CACF,CAAA;AAjDY,sBAAsB;IADlC,IAAA,mBAAU,GAAE;IAUR,WAAA,IAAA,eAAM,EAAC,iBAAiB,CAAC,CAAA;IAEzB,WAAA,IAAA,eAAM,EAAC,wBAAwB,CAAC,CAAA;IAOhC,YAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAbf,sBAAU;QACV,sBAAU;QACE,gCAAc;QACxB,6BAAa,kBAKR,6BAAiB;QACtB,wBAAY;QACP,6BAAiB;QACxB,sBAAU;QACN,0BAAc;QACO,iCAAe;QAClC,qCAAgB;GAnBzB,sBAAsB,CAiDlC;AAjDY,wDAAsB","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n NodeConfig,\n SmartBatchService,\n StoreCacheService,\n StoreService,\n IProjectService,\n PoiService,\n BlockDispatcher,\n ProcessBlockResponse,\n ApiService,\n IProjectUpgradeService,\n PoiSyncService,\n} from '@subql/node-core';\nimport {\n EthereumProjectDs,\n SubqueryProject,\n} from '../../configure/SubqueryProject';\nimport { DynamicDsService } from '../dynamic-ds.service';\nimport { IndexerManager } from '../indexer.manager';\nimport { BlockContent } from '../types';\n\n/**\n * @description Intended to behave the same as WorkerBlockDispatcherService but doesn't use worker threads or any parallel processing\n */\n@Injectable()\nexport class BlockDispatcherService\n extends BlockDispatcher<BlockContent, EthereumProjectDs>\n implements OnApplicationShutdown\n{\n constructor(\n apiService: ApiService,\n nodeConfig: NodeConfig,\n private indexerManager: IndexerManager,\n eventEmitter: EventEmitter2,\n @Inject('IProjectService')\n projectService: IProjectService<EthereumProjectDs>,\n @Inject('IProjectUpgradeService')\n projectUpgradeService: IProjectUpgradeService,\n smartBatchService: SmartBatchService,\n storeService: StoreService,\n storeCacheService: StoreCacheService,\n poiService: PoiService,\n poiSyncService: PoiSyncService,\n @Inject('ISubqueryProject') project: SubqueryProject,\n dynamicDsService: DynamicDsService,\n ) {\n super(\n nodeConfig,\n eventEmitter,\n projectService,\n projectUpgradeService,\n smartBatchService,\n storeService,\n storeCacheService,\n poiService,\n poiSyncService,\n project,\n dynamicDsService,\n apiService.fetchBlocks.bind(apiService),\n );\n }\n\n protected getBlockHeight(block: BlockContent): number {\n return block.number;\n }\n\n protected async indexBlock(\n block: BlockContent,\n ): Promise<ProcessBlockResponse> {\n return this.indexerManager.indexBlock(\n block,\n await this.projectService.getDataSources(this.getBlockHeight(block)),\n );\n }\n}\n"]}
1
+ {"version":3,"file":"block-dispatcher.service.js","sourceRoot":"","sources":["../../../src/indexer/blockDispatcher/block-dispatcher.service.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;AAEnC,2CAA2E;AAC3E,yDAAsD;AACtD,gDAY0B;AAC1B,qEAGyC;AACzC,8DAAyD;AACzD,wDAAoD;AAGpD;;GAEG;AAEI,IAAM,sBAAsB,GAA5B,MAAM,sBACX,SAAQ,2BAAgD;IAGxD,YACE,UAAsB,EACtB,UAAsB,EACd,cAA8B,EACtC,YAA2B,EAE3B,cAAkD,EAElD,qBAA6C,EAC7C,iBAAoC,EACpC,YAA0B,EAC1B,iBAAoC,EACpC,UAAsB,EACtB,cAA8B,EACF,OAAwB,EACpD,gBAAkC;QAElC,KAAK,CACH,UAAU,EACV,YAAY,EACZ,cAAc,EACd,qBAAqB,EACrB,iBAAiB,EACjB,YAAY,EACZ,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,OAAO,EACP,gBAAgB,EAChB,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC,UAAU,CAAC,CACxC,CAAC;QA3BM,mBAAc,GAAd,cAAc,CAAgB;IA4BxC,CAAC;IAED,qBAAqB,CAAC,MAAe;QAC/B,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC/C,CAAC;IAEO,cAAc,CAAC,KAAmB;QAC1C,OAAO,KAAK,CAAC,MAAM,CAAC;IACtB,CAAC;IAES,KAAK,CAAC,UAAU,CACxB,KAAmB;QAEnB,OAAO,IAAI,CAAC,cAAc,CAAC,UAAU,CACnC,KAAK,EACL,MAAM,IAAI,CAAC,cAAc,CAAC,cAAc,CAAC,IAAI,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC,CACrE,CAAC;IACJ,CAAC;CACF,CAAA;AArDY,sBAAsB;IADlC,IAAA,mBAAU,GAAE;IAUR,WAAA,IAAA,eAAM,EAAC,iBAAiB,CAAC,CAAA;IAEzB,WAAA,IAAA,eAAM,EAAC,wBAAwB,CAAC,CAAA;IAOhC,YAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAbf,sBAAU;QACV,sBAAU;QACE,gCAAc;QACxB,6BAAa,kBAKR,6BAAiB;QACtB,wBAAY;QACP,6BAAiB;QACxB,sBAAU;QACN,0BAAc;QACO,iCAAe;QAClC,qCAAgB;GAnBzB,sBAAsB,CAqDlC;AArDY,wDAAsB","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n NodeConfig,\n SmartBatchService,\n StoreCacheService,\n StoreService,\n IProjectService,\n PoiService,\n BlockDispatcher,\n ProcessBlockResponse,\n ApiService,\n IProjectUpgradeService,\n PoiSyncService,\n} from '@subql/node-core';\nimport {\n EthereumProjectDs,\n SubqueryProject,\n} from '../../configure/SubqueryProject';\nimport { DynamicDsService } from '../dynamic-ds.service';\nimport { IndexerManager } from '../indexer.manager';\nimport { BlockContent } from '../types';\n\n/**\n * @description Intended to behave the same as WorkerBlockDispatcherService but doesn't use worker threads or any parallel processing\n */\n@Injectable()\nexport class BlockDispatcherService\n extends BlockDispatcher<BlockContent, EthereumProjectDs>\n implements OnApplicationShutdown\n{\n constructor(\n apiService: ApiService,\n nodeConfig: NodeConfig,\n private indexerManager: IndexerManager,\n eventEmitter: EventEmitter2,\n @Inject('IProjectService')\n projectService: IProjectService<EthereumProjectDs>,\n @Inject('IProjectUpgradeService')\n projectUpgradeService: IProjectUpgradeService,\n smartBatchService: SmartBatchService,\n storeService: StoreService,\n storeCacheService: StoreCacheService,\n poiService: PoiService,\n poiSyncService: PoiSyncService,\n @Inject('ISubqueryProject') project: SubqueryProject,\n dynamicDsService: DynamicDsService,\n ) {\n super(\n nodeConfig,\n eventEmitter,\n projectService,\n projectUpgradeService,\n smartBatchService,\n storeService,\n storeCacheService,\n poiService,\n poiSyncService,\n project,\n dynamicDsService,\n apiService.fetchBlocks.bind(apiService),\n );\n }\n\n onApplicationShutdown(signal?: string) {\n throw new Error('Method not implemented.');\n }\n\n protected getBlockHeight(block: BlockContent): number {\n return block.number;\n }\n\n protected async indexBlock(\n block: BlockContent,\n ): Promise<ProcessBlockResponse> {\n return this.indexerManager.indexBlock(\n block,\n await this.projectService.getDataSources(this.getBlockHeight(block)),\n );\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { IBlockDispatcher } from '@subql/node-core';
2
- export interface IEthereumBlockDispatcher extends IBlockDispatcher {
2
+ import { EthereumBlock } from '@subql/types-ethereum';
3
+ export interface IEthereumBlockDispatcher extends IBlockDispatcher<EthereumBlock> {
3
4
  init(onDynamicDsCreated: (height: number) => Promise<void>): Promise<void>;
4
5
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ethereum-block-dispatcher.js","sourceRoot":"","sources":["../../../src/indexer/blockDispatcher/ethereum-block-dispatcher.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { IBlockDispatcher } from '@subql/node-core';\n\nexport interface IEthereumBlockDispatcher extends IBlockDispatcher {\n init(onDynamicDsCreated: (height: number) => Promise<void>): Promise<void>;\n}\n"]}
1
+ {"version":3,"file":"ethereum-block-dispatcher.js","sourceRoot":"","sources":["../../../src/indexer/blockDispatcher/ethereum-block-dispatcher.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { IBlockDispatcher } from '@subql/node-core';\nimport {EthereumBlock} from '@subql/types-ethereum';\n\nexport interface IEthereumBlockDispatcher extends IBlockDispatcher<EthereumBlock> {\n init(onDynamicDsCreated: (height: number) => Promise<void>): Promise<void>;\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { OnApplicationShutdown } from '@nestjs/common';
2
2
  import { EventEmitter2 } from '@nestjs/event-emitter';
3
3
  import { NodeConfig, SmartBatchService, StoreService, PoiService, StoreCacheService, IProjectService, WorkerBlockDispatcher, ConnectionPoolStateManager, IProjectUpgradeService, PoiSyncService, InMemoryCacheService } from '@subql/node-core';
4
+ import { EthereumBlock } from '@subql/types-ethereum';
4
5
  import { EthereumProjectDs, SubqueryProject } from '../../configure/SubqueryProject';
5
6
  import { EthereumApiConnection } from '../../ethereum/api.connection';
6
7
  import { DynamicDsService } from '../dynamic-ds.service';
@@ -9,7 +10,8 @@ import { IIndexerWorker } from '../worker/worker';
9
10
  type IndexerWorker = IIndexerWorker & {
10
11
  terminate: () => Promise<number>;
11
12
  };
12
- export declare class WorkerBlockDispatcherService extends WorkerBlockDispatcher<EthereumProjectDs, IndexerWorker> implements OnApplicationShutdown {
13
+ export declare class WorkerBlockDispatcherService extends WorkerBlockDispatcher<EthereumProjectDs, IndexerWorker, EthereumBlock> implements OnApplicationShutdown {
14
+ enqueueFatBlocks<B>(fatBlock: B[], latestBufferHeight?: number): void | Promise<void>;
13
15
  constructor(nodeConfig: NodeConfig, eventEmitter: EventEmitter2, projectService: IProjectService<EthereumProjectDs>, projectUpgadeService: IProjectUpgradeService, smartBatchService: SmartBatchService, cacheService: InMemoryCacheService, storeService: StoreService, storeCacheService: StoreCacheService, poiService: PoiService, poiSyncService: PoiSyncService, project: SubqueryProject, dynamicDsService: DynamicDsService, unfinalizedBlocksSevice: UnfinalizedBlocksService, connectionPoolState: ConnectionPoolStateManager<EthereumApiConnection>);
14
16
  protected fetchBlock(worker: IndexerWorker, height: number): Promise<void>;
15
17
  }
@@ -26,6 +26,9 @@ const SubqueryProject_1 = require("../../configure/SubqueryProject");
26
26
  const dynamic_ds_service_1 = require("../dynamic-ds.service");
27
27
  const unfinalizedBlocks_service_1 = require("../unfinalizedBlocks.service");
28
28
  let WorkerBlockDispatcherService = class WorkerBlockDispatcherService extends node_core_1.WorkerBlockDispatcher {
29
+ enqueueFatBlocks(fatBlock, latestBufferHeight) {
30
+ throw new Error('Method not implemented.');
31
+ }
29
32
  constructor(nodeConfig, eventEmitter, projectService, projectUpgadeService, smartBatchService, cacheService, storeService, storeCacheService, poiService, poiSyncService, project, dynamicDsService, unfinalizedBlocksSevice, connectionPoolState) {
30
33
  super(nodeConfig, eventEmitter, projectService, projectUpgadeService, smartBatchService, storeService, storeCacheService, poiService, poiSyncService, project, dynamicDsService, () => (0, node_core_1.createIndexerWorker)(path_1.default.resolve(__dirname, '../../../dist/indexer/worker/worker.js'), [], storeService.getStore(), cacheService.getCache(), dynamicDsService, unfinalizedBlocksSevice, connectionPoolState, project.root, projectService.startHeight));
31
34
  }
@@ -1 +1 @@
1
- {"version":3,"file":"worker-block-dispatcher.service.js","sourceRoot":"","sources":["../../../src/indexer/blockDispatcher/worker-block-dispatcher.service.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;;;;AAEnC,gDAAwB;AACxB,2CAA2E;AAC3E,yDAAsD;AACtD,gDAa0B;AAC1B,qEAGyC;AAEzC,8DAAyD;AAEzD,4EAAwE;AAQjE,IAAM,4BAA4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AAC,CAAA;qCAZf,sBAAU;QACR,6BAAa,kBAKR,6BAAiB;QACtB,gCAAoB;QACpB,wBAAY;QACP,6BAAiB;QACxB,sBAAU;QACN,0BAAc;QACO,iCAAe;QAClC,qCAAgB;QACT,oDAAwB;QAC5B,sCAA0B;GApBtC,4BAA4B,CAyExC;AAzEY,oEAA4B","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport path from 'path';\nimport { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n NodeConfig,\n SmartBatchService,\n StoreService,\n PoiService,\n StoreCacheService,\n IProjectService,\n WorkerBlockDispatcher,\n ConnectionPoolStateManager,\n IProjectUpgradeService,\n PoiSyncService,\n InMemoryCacheService,\n createIndexerWorker,\n} from '@subql/node-core';\nimport {\n EthereumProjectDs,\n SubqueryProject,\n} from '../../configure/SubqueryProject';\nimport { EthereumApiConnection } from '../../ethereum/api.connection';\nimport { DynamicDsService } from '../dynamic-ds.service';\nimport { BlockContent } from '../types';\nimport { UnfinalizedBlocksService } from '../unfinalizedBlocks.service';\nimport { IIndexerWorker } from '../worker/worker';\n\ntype IndexerWorker = IIndexerWorker & {\n terminate: () => Promise<number>;\n};\n\n@Injectable()\nexport class WorkerBlockDispatcherService\n extends WorkerBlockDispatcher<EthereumProjectDs, IndexerWorker>\n implements OnApplicationShutdown\n{\n constructor(\n nodeConfig: NodeConfig,\n eventEmitter: EventEmitter2,\n @Inject('IProjectService')\n projectService: IProjectService<EthereumProjectDs>,\n @Inject('IProjectUpgradeService')\n projectUpgadeService: IProjectUpgradeService,\n smartBatchService: SmartBatchService,\n cacheService: InMemoryCacheService,\n storeService: StoreService,\n storeCacheService: StoreCacheService,\n poiService: PoiService,\n poiSyncService: PoiSyncService,\n @Inject('ISubqueryProject') project: SubqueryProject,\n dynamicDsService: DynamicDsService,\n unfinalizedBlocksSevice: UnfinalizedBlocksService,\n connectionPoolState: ConnectionPoolStateManager<EthereumApiConnection>,\n ) {\n super(\n nodeConfig,\n eventEmitter,\n projectService,\n projectUpgadeService,\n smartBatchService,\n storeService,\n storeCacheService,\n poiService,\n poiSyncService,\n project,\n dynamicDsService,\n () =>\n createIndexerWorker<\n IIndexerWorker,\n EthereumApiConnection,\n BlockContent,\n EthereumProjectDs\n >(\n path.resolve(__dirname, '../../../dist/indexer/worker/worker.js'),\n [],\n storeService.getStore(),\n cacheService.getCache(),\n dynamicDsService,\n unfinalizedBlocksSevice,\n connectionPoolState,\n project.root,\n projectService.startHeight,\n ),\n );\n }\n\n protected async fetchBlock(\n worker: IndexerWorker,\n height: number,\n ): Promise<void> {\n const start = new Date();\n await worker.fetchBlock(height, null);\n const end = new Date();\n\n // const waitTime = end.getTime() - start.getTime();\n // if (waitTime > 1000) {\n // logger.info(\n // `Waiting to fetch block ${height}: ${chalk.red(`${waitTime}ms`)}`,\n // );\n // } else if (waitTime > 200) {\n // logger.info(\n // `Waiting to fetch block ${height}: ${chalk.yellow(`${waitTime}ms`)}`,\n // );\n // }\n }\n}\n"]}
1
+ {"version":3,"file":"worker-block-dispatcher.service.js","sourceRoot":"","sources":["../../../src/indexer/blockDispatcher/worker-block-dispatcher.service.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;;;;AAEnC,gDAAwB;AACxB,2CAA2E;AAC3E,yDAAsD;AACtD,gDAa0B;AAE1B,qEAGyC;AAEzC,8DAAuD;AAEvD,4EAAsE;AAQ/D,IAAM,4BAA4B,GAAlC,MAAM,4BACX,SAAQ,iCAAqE;IAG7E,gBAAgB,CAAI,QAAa,EAAE,kBAA2B;QAC1D,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC/C,CAAC;IACD,YACE,UAAsB,EACtB,YAA2B,EAE3B,cAAkD,EAElD,oBAA4C,EAC5C,iBAAoC,EACpC,YAAkC,EAClC,YAA0B,EAC1B,i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,oDAAwB;QAC5B,sCAA0B;GAvBtC,4BAA4B,CA4ExC;AA5EY,oEAA4B","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport path from 'path';\nimport { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n NodeConfig,\n SmartBatchService,\n StoreService,\n PoiService,\n StoreCacheService,\n IProjectService,\n WorkerBlockDispatcher,\n ConnectionPoolStateManager,\n IProjectUpgradeService,\n PoiSyncService,\n InMemoryCacheService,\n createIndexerWorker,\n} from '@subql/node-core';\nimport {EthereumBlock} from '@subql/types-ethereum';\nimport {\n EthereumProjectDs,\n SubqueryProject,\n} from '../../configure/SubqueryProject';\nimport {EthereumApiConnection} from '../../ethereum/api.connection';\nimport {DynamicDsService} from '../dynamic-ds.service';\nimport {BlockContent} from '../types';\nimport {UnfinalizedBlocksService} from '../unfinalizedBlocks.service';\nimport {IIndexerWorker} from '../worker/worker';\n\ntype IndexerWorker = IIndexerWorker & {\n terminate: () => Promise<number>;\n};\n\n@Injectable()\nexport class WorkerBlockDispatcherService\n extends WorkerBlockDispatcher<EthereumProjectDs, IndexerWorker,EthereumBlock>\n implements OnApplicationShutdown\n{\n enqueueFatBlocks<B>(fatBlock: B[], latestBufferHeight?: number): void | Promise<void> {\n throw new Error('Method not implemented.');\n }\n constructor(\n nodeConfig: NodeConfig,\n eventEmitter: EventEmitter2,\n @Inject('IProjectService')\n projectService: IProjectService<EthereumProjectDs>,\n @Inject('IProjectUpgradeService')\n projectUpgadeService: IProjectUpgradeService,\n smartBatchService: SmartBatchService,\n cacheService: InMemoryCacheService,\n storeService: StoreService,\n storeCacheService: StoreCacheService,\n poiService: PoiService,\n poiSyncService: PoiSyncService,\n @Inject('ISubqueryProject') project: SubqueryProject,\n dynamicDsService: DynamicDsService,\n unfinalizedBlocksSevice: UnfinalizedBlocksService,\n connectionPoolState: ConnectionPoolStateManager<EthereumApiConnection>,\n ) {\n super(\n nodeConfig,\n eventEmitter,\n projectService,\n projectUpgadeService,\n smartBatchService,\n storeService,\n storeCacheService,\n poiService,\n poiSyncService,\n project,\n dynamicDsService,\n () =>\n createIndexerWorker<\n IIndexerWorker,\n EthereumApiConnection,\n BlockContent,\n EthereumProjectDs\n >(\n path.resolve(__dirname, '../../../dist/indexer/worker/worker.js'),\n [],\n storeService.getStore(),\n cacheService.getCache(),\n dynamicDsService,\n unfinalizedBlocksSevice,\n connectionPoolState,\n project.root,\n projectService.startHeight,\n ),\n );\n }\n\n protected async fetchBlock(\n worker: IndexerWorker,\n height: number,\n ): Promise<void> {\n const start = new Date();\n await worker.fetchBlock(height, null);\n const end = new Date();\n\n // const waitTime = end.getTime() - start.getTime();\n // if (waitTime > 1000) {\n // logger.info(\n // `Waiting to fetch block ${height}: ${chalk.red(`${waitTime}ms`)}`,\n // );\n // } else if (waitTime > 200) {\n // logger.info(\n // `Waiting to fetch block ${height}: ${chalk.yellow(`${waitTime}ms`)}`,\n // );\n // }\n }\n}\n"]}
@@ -21,27 +21,24 @@ Object.defineProperty(exports, "__esModule", { value: true });
21
21
  exports.DictionaryService = void 0;
22
22
  const common_1 = require("@nestjs/common");
23
23
  const event_emitter_1 = require("@nestjs/event-emitter");
24
- const common_2 = require("@subql/common");
25
24
  const node_core_1 = require("@subql/node-core");
26
25
  const json5_1 = __importDefault(require("json5"));
27
26
  const node_fetch_1 = __importDefault(require("node-fetch"));
28
27
  const SubqueryProject_1 = require("../configure/SubqueryProject");
29
28
  const CHAIN_ALIASES_URL = 'https://raw.githubusercontent.com/subquery/templates/main/chainAliases.json5';
30
29
  let DictionaryService = DictionaryService_1 = class DictionaryService extends node_core_1.DictionaryService {
31
- constructor(project, nodeConfig, eventEmitter, chainId, dictionaryUrl) {
32
- super(dictionaryUrl !== null && dictionaryUrl !== void 0 ? dictionaryUrl : project.network.dictionary, chainId !== null && chainId !== void 0 ? chainId : project.network.chainId, nodeConfig, eventEmitter);
30
+ constructor(project, nodeConfig, eventEmitter, chainId) {
31
+ super(project.network.dictionary, chainId !== null && chainId !== void 0 ? chainId : project.network.chainId, nodeConfig, eventEmitter);
33
32
  this.project = project;
34
33
  }
35
34
  static async create(project, nodeConfig, eventEmitter) {
36
- var _a;
37
35
  /*Some dictionarys for EVM are built with other SDKs as they are chains with an EVM runtime
38
36
  * we maintain a list of aliases so we can map the evmChainId to the genesis hash of the other SDKs
39
37
  * e.g moonbeam is built with Substrate SDK but can be used as an EVM dictionary
40
38
  */
41
39
  const chainAliases = await this.getEvmChainId();
42
40
  const chainAlias = chainAliases[project.network.chainId];
43
- const url = (_a = project.network.dictionary) !== null && _a !== void 0 ? _a : (await node_core_1.DictionaryService.resolveDictionary(common_2.NETWORK_FAMILY.ethereum, chainAlias, nodeConfig.dictionaryRegistry));
44
- return new DictionaryService_1(project, nodeConfig, eventEmitter, chainAlias, url);
41
+ return new DictionaryService_1(project, nodeConfig, eventEmitter, chainAlias);
45
42
  }
46
43
  validateChainMeta(metaData) {
47
44
  // Due to dictionary metadata doesn't include chainId, in here we only validate endpoint genesisHash with metadata
@@ -59,7 +56,7 @@ DictionaryService = DictionaryService_1 = __decorate([
59
56
  __param(0, (0, common_1.Inject)('ISubqueryProject')),
60
57
  __metadata("design:paramtypes", [SubqueryProject_1.SubqueryProject,
61
58
  node_core_1.NodeConfig,
62
- event_emitter_1.EventEmitter2, String, String])
59
+ event_emitter_1.EventEmitter2, String])
63
60
  ], DictionaryService);
64
61
  exports.DictionaryService = DictionaryService;
65
62
  //# sourceMappingURL=dictionary.service.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dictionary.service.js","sourceRoot":"","sources":["../../src/indexer/dictionary.service.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;;;;;AAEnC,2CAAoD;AACpD,yDAAsD;AACtD,0CAA+C;AAC/C,gDAG0B;AAE1B,kDAA0B;AAC1B,4DAA+B;AAC/B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C;QAClC,wDAAwD;QACxD,OAAO,eAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC1B,CAAC;CACF,CAAA;AAzDY,iBAAiB;IAD7B,IAAA,mBAAU,GAAE;IAGR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAAoB,iCAAe;QAClD,sBAAU;QACR,6BAAa;GAJlB,iBAAiB,CAyD7B;AAzDY,8CAAiB","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Inject, Injectable } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { NETWORK_FAMILY } from '@subql/common';\nimport {\n NodeConfig,\n DictionaryService as CoreDictionaryService,\n} from '@subql/node-core';\nimport { MetaData } from '@subql/utils';\nimport JSON5 from 'json5';\nimport fetch from 'node-fetch';\nimport { SubqueryProject } from '../configure/SubqueryProject';\n\nconst CHAIN_ALIASES_URL =\n 'https://raw.githubusercontent.com/subquery/templates/main/chainAliases.json5';\n\n@Injectable()\nexport class DictionaryService extends CoreDictionaryService {\n private constructor(\n @Inject('ISubqueryProject') protected project: SubqueryProject,\n nodeConfig: NodeConfig,\n eventEmitter: EventEmitter2,\n chainId?: string,\n dictionaryUrl?: string,\n ) {\n super(\n dictionaryUrl ?? project.network.dictionary,\n chainId ?? project.network.chainId,\n nodeConfig,\n eventEmitter,\n );\n }\n\n static async create(\n project: SubqueryProject,\n nodeConfig: NodeConfig,\n eventEmitter: EventEmitter2,\n ): Promise<DictionaryService> {\n /*Some dictionarys for EVM are built with other SDKs as they are chains with an EVM runtime\n * we maintain a list of aliases so we can map the evmChainId to the genesis hash of the other SDKs\n * e.g moonbeam is built with Substrate SDK but can be used as an EVM dictionary\n */\n const chainAliases = await this.getEvmChainId();\n const chainAlias = chainAliases[project.network.chainId];\n\n const url =\n project.network.dictionary ??\n (await CoreDictionaryService.resolveDictionary(\n NETWORK_FAMILY.ethereum,\n chainAlias,\n nodeConfig.dictionaryRegistry,\n ));\n\n return new DictionaryService(\n project,\n nodeConfig,\n eventEmitter,\n chainAlias,\n url,\n );\n }\n\n protected validateChainMeta(metaData: MetaData): boolean {\n // Due to dictionary metadata doesn't include chainId, in here we only validate endpoint genesisHash with metadata\n return this.apiGenesisHash === metaData.genesisHash;\n }\n\n private static async getEvmChainId(): Promise<Record<string, string>> {\n const response = await fetch(CHAIN_ALIASES_URL);\n\n const raw = await response.text();\n // We use JSON5 here because the file has comments in it\n return JSON5.parse(raw);\n }\n}\n"]}
1
+ {"version":3,"file":"dictionary.service.js","sourceRoot":"","sources":["../../src/indexer/dictionary.service.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;;;;;AAEnC,2CAAoD;AACpD,yDAAsD;AACtD,gDAG0B;AAE1B,kDAA0B;AAC1B,4DAA+B;AAC/B,kEAA+D;AAE/D,MAAM,iBAAiB,GACrB,8EAA8E,CAAC;AAG1E,IAAM,iBAAiB,yBAAvB,MAAM,iBAAkB,SAAQ,6BAAqB;IAC1D,YACwC,OAAwB,EAC9D,UAAsB,EACtB,YAA2B,EAC3B,OAAgB;QAEhB,KAAK,CACH,OAAO,CAAC,OAAO,CAAC,UAAU,EAC1B,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,OAAO,CAAC,OAAO,CAAC,OAAO,EAClC,UAAU,EACV,YAAY,CACb,CAAC;QAVoC,YAAO,GAAP,OAAO,CAAiB;IAWhE,CAAC;IAED,MAAM,CAAC,KAAK,CAAC,MAAM,CACjB,OAAwB,EACxB,UAAsB,EACtB,YAA2B;QAE3B;;;WAGG;QACH,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,aAAa,EAAE,CAAC;QAChD,MAAM,UAAU,GAAG,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAEzD,OAAO,IAAI,mBAAiB,CAAC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;IAC9E,CAAC;IAES,iBAAiB,CAAC,QAAkB;QAC5C,kHAAkH;QAClH,OAAO,IAAI,CAAC,cAAc,KAAK,QAAQ,CAAC,WAAW,CAAC;IACtD,CAAC;IAEO,MAAM,CAAC,KAAK,CAAC,aAAa;QAChC,MAAM,QAAQ,GAAG,MAAM,IAAA,oBAAK,EAAC,iBAAiB,CAAC,CAAC;QAEhD,MAAM,GAAG,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QAClC,wDAAwD;QACxD,OAAO,eAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC1B,CAAC;CACF,CAAA;AA1CY,iBAAiB;IAD7B,IAAA,mBAAU,GAAE;IAGR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAAoB,iCAAe;QAClD,sBAAU;QACR,6BAAa;GAJlB,iBAAiB,CA0C7B;AA1CY,8CAAiB","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Inject, Injectable } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport {\n NodeConfig,\n DictionaryService as CoreDictionaryService,\n} from '@subql/node-core';\nimport { MetaData } from '@subql/utils';\nimport JSON5 from 'json5';\nimport fetch from 'node-fetch';\nimport { SubqueryProject } from '../configure/SubqueryProject';\n\nconst CHAIN_ALIASES_URL =\n 'https://raw.githubusercontent.com/subquery/templates/main/chainAliases.json5';\n\n@Injectable()\nexport class DictionaryService extends CoreDictionaryService {\n private constructor(\n @Inject('ISubqueryProject') protected project: SubqueryProject,\n nodeConfig: NodeConfig,\n eventEmitter: EventEmitter2,\n chainId?: string,\n ) {\n super(\n project.network.dictionary,\n chainId ?? project.network.chainId,\n nodeConfig,\n eventEmitter,\n );\n }\n\n static async create(\n project: SubqueryProject,\n nodeConfig: NodeConfig,\n eventEmitter: EventEmitter2,\n ): Promise<DictionaryService> {\n /*Some dictionarys for EVM are built with other SDKs as they are chains with an EVM runtime\n * we maintain a list of aliases so we can map the evmChainId to the genesis hash of the other SDKs\n * e.g moonbeam is built with Substrate SDK but can be used as an EVM dictionary\n */\n const chainAliases = await this.getEvmChainId();\n const chainAlias = chainAliases[project.network.chainId];\n\n return new DictionaryService(project, nodeConfig, eventEmitter, chainAlias);\n }\n\n protected validateChainMeta(metaData: MetaData): boolean {\n // Due to dictionary metadata doesn't include chainId, in here we only validate endpoint genesisHash with metadata\n return this.apiGenesisHash === metaData.genesisHash;\n }\n\n private static async getEvmChainId(): Promise<Record<string, string>> {\n const response = await fetch(CHAIN_ALIASES_URL);\n\n const raw = await response.text();\n // We use JSON5 here because the file has comments in it\n return JSON5.parse(raw);\n }\n}\n"]}
@@ -0,0 +1,83 @@
1
+ import { NodeConfig } from '@subql/node-core';
2
+ import { FatDictionaryResponse, FatDictionaryService } from '@subql/node-core/indexer/fat-dictionary.service';
3
+ import { BlockHeightMap } from '@subql/node-core/utils/blockHeightMap';
4
+ import { DictionaryQueryEntry, BaseDataSource } from '@subql/types-core';
5
+ import { EthereumBlock } from '@subql/types-ethereum';
6
+ export declare class EthFatDictionaryService extends FatDictionaryService<EthereumBlock> {
7
+ constructor(nodeConfig: NodeConfig);
8
+ get dictionaryEndpoint(): string;
9
+ /**
10
+ *
11
+ * @param startBlock
12
+ * @param queryEndBlock this block number will limit the max query range, increase dictionary query speed
13
+ * @param batchSize
14
+ * @param conditions
15
+ */
16
+ queryFatDictionary(startBlock: number, queryEndBlock: number, limit?: number, conditions?: DictionaryQueryEntry[]): Promise<UnwrappedFatDictionaryResponseData | undefined>;
17
+ dictionaryFatQuery(dictionaryQueryEntries: DictionaryQueryEntry[]): {
18
+ logs: any[];
19
+ transactions: any[];
20
+ };
21
+ buildDictionaryEntryMap<DS extends BaseDataSource>(dataSources: BlockHeightMap<DS[]>, buildDictionaryQueryEntries: (dataSources: DS[]) => DictionaryQueryEntry[]): void;
22
+ convertResponseBlocks(data: UnwrappedFatDictionaryResponseData): FatDictionaryResponse<EthereumBlock> | undefined;
23
+ }
24
+ interface UnwrappedEthFatBlock {
25
+ Header: {
26
+ parentHash: string;
27
+ sha3Uncles: string;
28
+ miner: string;
29
+ stateRoot: string;
30
+ transactionRoot: string;
31
+ receiptsRoot: string;
32
+ logsBloom: string;
33
+ difficulty: bigint;
34
+ number: bigint;
35
+ gasLimit: bigint;
36
+ gasUsed: bigint;
37
+ timestamp: bigint;
38
+ extraData: string;
39
+ mixHash: string;
40
+ nonce: string;
41
+ baseFeePerGas: bigint;
42
+ withdrawalsRoot: string;
43
+ blobGasUsed: bigint;
44
+ excessBlobGas: bigint;
45
+ parentBeaconBlockRoot: string;
46
+ hash: string;
47
+ };
48
+ Transactions: UnwrappedEthFatTransaction[];
49
+ Logs: UnwrappedEthFatLog[];
50
+ }
51
+ interface UnwrappedEthFatTransaction {
52
+ type: string;
53
+ nonce: bigint;
54
+ to: string;
55
+ gas: bigint;
56
+ gasPrice: bigint;
57
+ maxPriorityFeePerGas: bigint;
58
+ maxFeePerGas: bigint;
59
+ value: bigint;
60
+ v: bigint;
61
+ r: string;
62
+ s: string;
63
+ input: string;
64
+ hash: string;
65
+ from: string;
66
+ }
67
+ interface UnwrappedEthFatLog {
68
+ address: string;
69
+ topics: string[];
70
+ data: string;
71
+ blockNumber: bigint;
72
+ transactionHash: string;
73
+ transactionIndex: bigint;
74
+ blockHash: string;
75
+ logIndex: bigint;
76
+ removed: boolean;
77
+ }
78
+ interface UnwrappedFatDictionaryResponseData {
79
+ Blocks: UnwrappedEthFatBlock[];
80
+ BlockRange: number[];
81
+ GenesisHash: string;
82
+ }
83
+ export {};