@subql/node-ethereum 2.11.1-1 → 2.11.1-3

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 (29) hide show
  1. package/CHANGELOG.md +3 -2
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/ethereum/api.ethereum.js +15 -2
  4. package/dist/ethereum/api.ethereum.js.map +1 -1
  5. package/dist/ethereum/ethers/celo/celo-json-rpc-batch-provider.d.ts +7 -0
  6. package/dist/ethereum/ethers/celo/celo-json-rpc-batch-provider.js +23 -0
  7. package/dist/ethereum/ethers/celo/celo-json-rpc-batch-provider.js.map +1 -0
  8. package/dist/ethereum/ethers/celo/celo-json-rpc-batch-provider.spec.d.ts +1 -0
  9. package/dist/ethereum/ethers/celo/celo-json-rpc-batch-provider.spec.js +30 -0
  10. package/dist/ethereum/ethers/celo/celo-json-rpc-batch-provider.spec.js.map +1 -0
  11. package/dist/ethereum/ethers/celo/celo-json-rpc-provider.d.ts +7 -0
  12. package/dist/ethereum/ethers/celo/celo-json-rpc-provider.js +23 -0
  13. package/dist/ethereum/ethers/celo/celo-json-rpc-provider.js.map +1 -0
  14. package/dist/ethereum/ethers/celo/celo-json-rpc-provider.spec.d.ts +1 -0
  15. package/dist/ethereum/ethers/celo/celo-json-rpc-provider.spec.js +30 -0
  16. package/dist/ethereum/ethers/celo/celo-json-rpc-provider.spec.js.map +1 -0
  17. package/dist/ethereum/ethers/celo/celo-ws-provider.d.ts +6 -0
  18. package/dist/ethereum/ethers/celo/celo-ws-provider.js +23 -0
  19. package/dist/ethereum/ethers/celo/celo-ws-provider.js.map +1 -0
  20. package/dist/ethereum/ethers/celo/celo-ws-provider.spec.d.ts +1 -0
  21. package/dist/ethereum/ethers/celo/celo-ws-provider.spec.js +30 -0
  22. package/dist/ethereum/ethers/celo/celo-ws-provider.spec.js.map +1 -0
  23. package/dist/ethereum/utils.ethereum.js +3 -0
  24. package/dist/ethereum/utils.ethereum.js.map +1 -1
  25. package/dist/indexer/fetch.service.js +23 -12
  26. package/dist/indexer/fetch.service.js.map +1 -1
  27. package/dist/indexer/fetch.service.spec.js +39 -1
  28. package/dist/indexer/fetch.service.spec.js.map +1 -1
  29. package/package.json +2 -2
@@ -17,6 +17,9 @@ const utils_1 = require("ethers/lib/utils");
17
17
  const project_1 = require("../utils/project");
18
18
  const yargs_1 = require("../yargs");
19
19
  const block_ethereum_1 = require("./block.ethereum");
20
+ const celo_json_rpc_batch_provider_1 = require("./ethers/celo/celo-json-rpc-batch-provider");
21
+ const celo_json_rpc_provider_1 = require("./ethers/celo/celo-json-rpc-provider");
22
+ const celo_ws_provider_1 = require("./ethers/celo/celo-ws-provider");
20
23
  const json_rpc_batch_provider_1 = require("./ethers/json-rpc-batch-provider");
21
24
  const json_rpc_provider_1 = require("./ethers/json-rpc-provider");
22
25
  const safe_api_1 = __importDefault(require("./safe-api"));
@@ -93,10 +96,20 @@ class EthereumApi {
93
96
  }
94
97
  async init() {
95
98
  this.injectClient();
99
+ const network = await this.client.getNetwork();
100
+ //celo
101
+ if (network.chainId === 42220) {
102
+ if (this.client instanceof providers_1.WebSocketProvider) {
103
+ this.client = new celo_ws_provider_1.CeloWsProvider(this.client.connection.url);
104
+ }
105
+ else {
106
+ this.client = new celo_json_rpc_batch_provider_1.CeloJsonRpcBatchProvider(this.client.connection);
107
+ this.nonBatchClient = new celo_json_rpc_provider_1.CeloJsonRpcProvider(this.client.connection);
108
+ }
109
+ }
96
110
  try {
97
- const [genesisBlock, network, supportsFinalization, supportsSafe] = await Promise.all([
111
+ const [genesisBlock, supportsFinalization, supportsSafe] = await Promise.all([
98
112
  this.client.getBlock('earliest'),
99
- this.client.getNetwork(),
100
113
  this.getSupportsTag('finalized'),
101
114
  this.getSupportsTag('safe'),
102
115
  ]);
@@ -1 +1 @@
1
- {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCA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cesContent":["// 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 EthereumBlockWrapper,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n SubqlRuntimeDatasource,\n} from '@subql/types-ethereum';\nimport CacheableLookup from 'cacheable-lookup';\nimport { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport { yargsOptions } from '../yargs';\nimport { EthereumBlockWrapped } from './block.ethereum';\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<EthereumBlockWrapper> {\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 private blockConfirmations = yargsOptions.argv['block-confirmations'];\n\n constructor(private endpoint: string, private eventEmitter: EventEmitter2) {\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 try {\n const [genesisBlock, network, supportsFinalization, supportsSafe] =\n await Promise.all([\n this.client.getBlock('earliest'),\n this.client.getNetwork(),\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 return this.client.getBlock(height);\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.getFinalizedBlock()).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n const tag = this.supportsFinalization ? '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(\n blockNumber: number,\n includeTx?: boolean,\n ): Promise<EthereumBlockWrapped> {\n try {\n const [block, logs] = await Promise.all([\n this.getBlockPromise(blockNumber, includeTx),\n this.client.getLogs({\n fromBlock: hexValue(blockNumber),\n toBlock: hexValue(blockNumber),\n }),\n ]);\n\n const ret = new EthereumBlockWrapped(\n block,\n includeTx\n ? block.transactions.map((tx) => ({\n ...formatTransaction(tx, block),\n // TODO memoise\n receipt: () =>\n this.getTransactionReceipt(tx.hash).then((r) =>\n formatReceipt(r, block),\n ),\n }))\n : [],\n logs.map((l) => formatLog(l, block)),\n );\n this.eventEmitter.emit('fetchBlock');\n return ret;\n } catch (e) {\n throw this.handleError(e);\n }\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => this.fetchBlock(num, true)),\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,\n ds: SubqlRuntimeDatasource,\n ): Promise<EthereumLog<T> | EthereumLog> {\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 ));\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"]}
1
+ {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;AAEnC,4C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BAAiB,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;AA3UD,kCA2UC","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 EthereumBlockWrapper,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n SubqlRuntimeDatasource,\n} from '@subql/types-ethereum';\nimport CacheableLookup from 'cacheable-lookup';\nimport { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport { yargsOptions } from '../yargs';\nimport { EthereumBlockWrapped } from './block.ethereum';\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<EthereumBlockWrapper> {\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 private blockConfirmations = yargsOptions.argv['block-confirmations'];\n\n constructor(private endpoint: string, private eventEmitter: EventEmitter2) {\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 return this.client.getBlock(height);\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.getFinalizedBlock()).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n const tag = this.supportsFinalization ? '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(\n blockNumber: number,\n includeTx?: boolean,\n ): Promise<EthereumBlockWrapped> {\n try {\n const [block, logs] = await Promise.all([\n this.getBlockPromise(blockNumber, includeTx),\n this.client.getLogs({\n fromBlock: hexValue(blockNumber),\n toBlock: hexValue(blockNumber),\n }),\n ]);\n\n const ret = new EthereumBlockWrapped(\n block,\n includeTx\n ? block.transactions.map((tx) => ({\n ...formatTransaction(tx, block),\n // TODO memoise\n receipt: () =>\n this.getTransactionReceipt(tx.hash).then((r) =>\n formatReceipt(r, block),\n ),\n }))\n : [],\n logs.map((l) => formatLog(l, block)),\n );\n this.eventEmitter.emit('fetchBlock');\n return ret;\n } catch (e) {\n throw this.handleError(e);\n }\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => this.fetchBlock(num, true)),\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,\n ds: SubqlRuntimeDatasource,\n ): Promise<EthereumLog<T> | EthereumLog> {\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 ));\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"]}
@@ -0,0 +1,7 @@
1
+ import { Networkish } from '@ethersproject/networks';
2
+ import { JsonRpcBatchProvider } from '../json-rpc-batch-provider';
3
+ import { ConnectionInfo } from '../web';
4
+ export declare class CeloJsonRpcBatchProvider extends JsonRpcBatchProvider {
5
+ private flanHardForkBlock;
6
+ constructor(url?: ConnectionInfo | string, network?: Networkish);
7
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ // Copyright 2020-2023 SubQuery Pte Ltd authors & contributors
3
+ // SPDX-License-Identifier: GPL-3.0
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.CeloJsonRpcBatchProvider = void 0;
6
+ const node_core_1 = require("@subql/node-core");
7
+ const ethers_1 = require("ethers");
8
+ const json_rpc_batch_provider_1 = require("../json-rpc-batch-provider");
9
+ const logger = (0, node_core_1.getLogger)('celo-batch-provider');
10
+ class CeloJsonRpcBatchProvider extends json_rpc_batch_provider_1.JsonRpcBatchProvider {
11
+ constructor(url, network) {
12
+ super(url, network);
13
+ this.flanHardForkBlock = ethers_1.BigNumber.from('16068685');
14
+ const originalBlockFormatter = this.formatter._block;
15
+ this.formatter._block = (value, format) => {
16
+ return originalBlockFormatter(Object.assign({ gasLimit: ethers_1.BigNumber.from(value.number) < this.flanHardForkBlock
17
+ ? ethers_1.constants.Zero
18
+ : value.gasLimit }, value), format);
19
+ };
20
+ }
21
+ }
22
+ exports.CeloJsonRpcBatchProvider = CeloJsonRpcBatchProvider;
23
+ //# sourceMappingURL=celo-json-rpc-batch-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"celo-json-rpc-batch-provider.js","sourceRoot":"","sources":["../../../../src/ethereum/ethers/celo/celo-json-rpc-batch-provider.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;AAGnC,gDAA6C;AAC7C,mCAA8C;AAC9C,wEAAkE;AAGlE,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,qBAAqB,CAAC,CAAC;AAEhD,MAAa,wBAAyB,SAAQ,8CAAoB;IAEhE,YAAY,GAA6B,EAAE,OAAoB;QAC7D,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAFd,sBAAiB,GAAG,kBAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAIrD,MAAM,sBAAsB,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;QACrD,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;YACxC,OAAO,sBAAsB,iBAEzB,QAAQ,EACN,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,iBAAiB;oBACnD,CAAC,CAAC,kBAAS,CAAC,IAAI;oBAChB,CAAC,CAAC,KAAK,CAAC,QAAQ,IACjB,KAAK,GAEV,MAAM,CACP,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;CACF;AAnBD,4DAmBC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Networkish } from '@ethersproject/networks';\nimport { getLogger } from '@subql/node-core';\nimport { BigNumber, constants } from 'ethers';\nimport { JsonRpcBatchProvider } from '../json-rpc-batch-provider';\nimport { ConnectionInfo } from '../web';\n\nconst logger = getLogger('celo-batch-provider');\n\nexport class CeloJsonRpcBatchProvider extends JsonRpcBatchProvider {\n private flanHardForkBlock = BigNumber.from('16068685');\n constructor(url?: ConnectionInfo | string, network?: Networkish) {\n super(url, network);\n\n const originalBlockFormatter = this.formatter._block;\n this.formatter._block = (value, format) => {\n return originalBlockFormatter(\n {\n gasLimit:\n BigNumber.from(value.number) < this.flanHardForkBlock\n ? constants.Zero\n : value.gasLimit,\n ...value,\n },\n format,\n );\n };\n }\n}\n"]}
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ // Copyright 2020-2023 SubQuery Pte Ltd authors & contributors
3
+ // SPDX-License-Identifier: GPL-3.0
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ const ethers_1 = require("ethers");
6
+ const utils_ethereum_1 = require("../../utils.ethereum");
7
+ const celo_json_rpc_batch_provider_1 = require("./celo-json-rpc-batch-provider");
8
+ describe('CeloJsonRpcProvider', () => {
9
+ let provider;
10
+ beforeEach(() => {
11
+ provider = new celo_json_rpc_batch_provider_1.CeloJsonRpcBatchProvider('https://forno.celo.org');
12
+ });
13
+ // Test if gasLimit is correctly set for blocks before the hard fork
14
+ it('should set gasLimit to zero for blocks before the hard fork', async () => {
15
+ const block = (0, utils_ethereum_1.formatBlock)(await provider.send('eth_getBlockByNumber', [
16
+ ethers_1.utils.hexValue(16068684),
17
+ true,
18
+ ]));
19
+ expect(ethers_1.BigNumber.from(block.gasLimit)).toEqual(ethers_1.constants.Zero);
20
+ });
21
+ // Test if gasLimit is correctly set for blocks after the hard fork
22
+ it('should not set gasLimit to zero for blocks after the hard fork', async () => {
23
+ const block = (0, utils_ethereum_1.formatBlock)(await provider.send('eth_getBlockByNumber', [
24
+ ethers_1.utils.hexValue(21055596),
25
+ true,
26
+ ]));
27
+ expect(ethers_1.BigNumber.from(block.gasLimit)).toEqual(ethers_1.BigNumber.from(0x1312d00));
28
+ });
29
+ });
30
+ //# sourceMappingURL=celo-json-rpc-batch-provider.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"celo-json-rpc-batch-provider.spec.js","sourceRoot":"","sources":["../../../../src/ethereum/ethers/celo/celo-json-rpc-batch-provider.spec.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;AAEnC,mCAAqD;AACrD,yDAAmD;AACnD,iFAA0E;AAE1E,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;IACnC,IAAI,QAAkC,CAAC;IAEvC,UAAU,CAAC,GAAG,EAAE;QACd,QAAQ,GAAG,IAAI,uDAAwB,CAAC,wBAAwB,CAAC,CAAC;IACpE,CAAC,CAAC,CAAC;IAEH,oEAAoE;IACpE,EAAE,CAAC,6DAA6D,EAAE,KAAK,IAAI,EAAE;QAC3E,MAAM,KAAK,GAAG,IAAA,4BAAW,EACvB,MAAM,QAAQ,CAAC,IAAI,CAAC,sBAAsB,EAAE;YAC1C,cAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;YACxB,IAAI;SACL,CAAC,CACH,CAAC;QACF,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAS,CAAC,IAAI,CAAC,CAAC;IACjE,CAAC,CAAC,CAAC;IAEH,mEAAmE;IACnE,EAAE,CAAC,gEAAgE,EAAE,KAAK,IAAI,EAAE;QAC9E,MAAM,KAAK,GAAG,IAAA,4BAAW,EACvB,MAAM,QAAQ,CAAC,IAAI,CAAC,sBAAsB,EAAE;YAC1C,cAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;YACxB,IAAI;SACL,CAAC,CACH,CAAC;QACF,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAC5E,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 { BigNumber, constants, utils } from 'ethers';\nimport { formatBlock } from '../../utils.ethereum';\nimport { CeloJsonRpcBatchProvider } from './celo-json-rpc-batch-provider';\n\ndescribe('CeloJsonRpcProvider', () => {\n let provider: CeloJsonRpcBatchProvider;\n\n beforeEach(() => {\n provider = new CeloJsonRpcBatchProvider('https://forno.celo.org');\n });\n\n // Test if gasLimit is correctly set for blocks before the hard fork\n it('should set gasLimit to zero for blocks before the hard fork', async () => {\n const block = formatBlock(\n await provider.send('eth_getBlockByNumber', [\n utils.hexValue(16068684),\n true,\n ]),\n );\n expect(BigNumber.from(block.gasLimit)).toEqual(constants.Zero);\n });\n\n // Test if gasLimit is correctly set for blocks after the hard fork\n it('should not set gasLimit to zero for blocks after the hard fork', async () => {\n const block = formatBlock(\n await provider.send('eth_getBlockByNumber', [\n utils.hexValue(21055596),\n true,\n ]),\n );\n expect(BigNumber.from(block.gasLimit)).toEqual(BigNumber.from(0x1312d00));\n });\n});\n"]}
@@ -0,0 +1,7 @@
1
+ import { Networkish } from '@ethersproject/networks';
2
+ import { JsonRpcProvider } from '../json-rpc-provider';
3
+ import { ConnectionInfo } from '../web';
4
+ export declare class CeloJsonRpcProvider extends JsonRpcProvider {
5
+ private flanHardForkBlock;
6
+ constructor(url?: ConnectionInfo | string, network?: Networkish);
7
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ // Copyright 2020-2023 SubQuery Pte Ltd authors & contributors
3
+ // SPDX-License-Identifier: GPL-3.0
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.CeloJsonRpcProvider = void 0;
6
+ const node_core_1 = require("@subql/node-core");
7
+ const ethers_1 = require("ethers");
8
+ const json_rpc_provider_1 = require("../json-rpc-provider");
9
+ const logger = (0, node_core_1.getLogger)('celo-provider');
10
+ class CeloJsonRpcProvider extends json_rpc_provider_1.JsonRpcProvider {
11
+ constructor(url, network) {
12
+ super(url, network);
13
+ this.flanHardForkBlock = ethers_1.BigNumber.from('16068685');
14
+ const originalBlockFormatter = this.formatter._block;
15
+ this.formatter._block = (value, format) => {
16
+ return originalBlockFormatter(Object.assign({ gasLimit: ethers_1.BigNumber.from(value.number) < this.flanHardForkBlock
17
+ ? ethers_1.constants.Zero
18
+ : value.gasLimit }, value), format);
19
+ };
20
+ }
21
+ }
22
+ exports.CeloJsonRpcProvider = CeloJsonRpcProvider;
23
+ //# sourceMappingURL=celo-json-rpc-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"celo-json-rpc-provider.js","sourceRoot":"","sources":["../../../../src/ethereum/ethers/celo/celo-json-rpc-provider.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;AAGnC,gDAA6C;AAC7C,mCAA8C;AAC9C,4DAAuD;AAGvD,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,eAAe,CAAC,CAAC;AAE1C,MAAa,mBAAoB,SAAQ,mCAAe;IAEtD,YAAY,GAA6B,EAAE,OAAoB;QAC7D,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAFd,sBAAiB,GAAG,kBAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAIrD,MAAM,sBAAsB,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;QACrD,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;YACxC,OAAO,sBAAsB,iBAEzB,QAAQ,EACN,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,iBAAiB;oBACnD,CAAC,CAAC,kBAAS,CAAC,IAAI;oBAChB,CAAC,CAAC,KAAK,CAAC,QAAQ,IACjB,KAAK,GAEV,MAAM,CACP,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;CACF;AAnBD,kDAmBC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Networkish } from '@ethersproject/networks';\nimport { getLogger } from '@subql/node-core';\nimport { BigNumber, constants } from 'ethers';\nimport { JsonRpcProvider } from '../json-rpc-provider';\nimport { ConnectionInfo } from '../web';\n\nconst logger = getLogger('celo-provider');\n\nexport class CeloJsonRpcProvider extends JsonRpcProvider {\n private flanHardForkBlock = BigNumber.from('16068685');\n constructor(url?: ConnectionInfo | string, network?: Networkish) {\n super(url, network);\n\n const originalBlockFormatter = this.formatter._block;\n this.formatter._block = (value, format) => {\n return originalBlockFormatter(\n {\n gasLimit:\n BigNumber.from(value.number) < this.flanHardForkBlock\n ? constants.Zero\n : value.gasLimit,\n ...value,\n },\n format,\n );\n };\n }\n}\n"]}
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ // Copyright 2020-2023 SubQuery Pte Ltd authors & contributors
3
+ // SPDX-License-Identifier: GPL-3.0
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ const ethers_1 = require("ethers");
6
+ const utils_ethereum_1 = require("../../utils.ethereum");
7
+ const celo_json_rpc_provider_1 = require("./celo-json-rpc-provider");
8
+ describe('CeloJsonRpcProvider', () => {
9
+ let provider;
10
+ beforeEach(() => {
11
+ provider = new celo_json_rpc_provider_1.CeloJsonRpcProvider('https://forno.celo.org');
12
+ });
13
+ // Test if gasLimit is correctly set for blocks before the hard fork
14
+ it('should set gasLimit to zero for blocks before the hard fork', async () => {
15
+ const block = (0, utils_ethereum_1.formatBlock)(await provider.send('eth_getBlockByNumber', [
16
+ ethers_1.utils.hexValue(16068684),
17
+ true,
18
+ ]));
19
+ expect(ethers_1.BigNumber.from(block.gasLimit)).toEqual(ethers_1.constants.Zero);
20
+ });
21
+ // Test if gasLimit is correctly set for blocks after the hard fork
22
+ it('should not set gasLimit to zero for blocks after the hard fork', async () => {
23
+ const block = (0, utils_ethereum_1.formatBlock)(await provider.send('eth_getBlockByNumber', [
24
+ ethers_1.utils.hexValue(21055596),
25
+ true,
26
+ ]));
27
+ expect(ethers_1.BigNumber.from(block.gasLimit)).toEqual(ethers_1.BigNumber.from(0x1312d00));
28
+ });
29
+ });
30
+ //# sourceMappingURL=celo-json-rpc-provider.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"celo-json-rpc-provider.spec.js","sourceRoot":"","sources":["../../../../src/ethereum/ethers/celo/celo-json-rpc-provider.spec.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;AAEnC,mCAAqD;AACrD,yDAAmD;AACnD,qEAA+D;AAE/D,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;IACnC,IAAI,QAA6B,CAAC;IAElC,UAAU,CAAC,GAAG,EAAE;QACd,QAAQ,GAAG,IAAI,4CAAmB,CAAC,wBAAwB,CAAC,CAAC;IAC/D,CAAC,CAAC,CAAC;IAEH,oEAAoE;IACpE,EAAE,CAAC,6DAA6D,EAAE,KAAK,IAAI,EAAE;QAC3E,MAAM,KAAK,GAAG,IAAA,4BAAW,EACvB,MAAM,QAAQ,CAAC,IAAI,CAAC,sBAAsB,EAAE;YAC1C,cAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;YACxB,IAAI;SACL,CAAC,CACH,CAAC;QACF,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAS,CAAC,IAAI,CAAC,CAAC;IACjE,CAAC,CAAC,CAAC;IAEH,mEAAmE;IACnE,EAAE,CAAC,gEAAgE,EAAE,KAAK,IAAI,EAAE;QAC9E,MAAM,KAAK,GAAG,IAAA,4BAAW,EACvB,MAAM,QAAQ,CAAC,IAAI,CAAC,sBAAsB,EAAE;YAC1C,cAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;YACxB,IAAI;SACL,CAAC,CACH,CAAC;QACF,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAC5E,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 { BigNumber, constants, utils } from 'ethers';\nimport { formatBlock } from '../../utils.ethereum';\nimport { CeloJsonRpcProvider } from './celo-json-rpc-provider';\n\ndescribe('CeloJsonRpcProvider', () => {\n let provider: CeloJsonRpcProvider;\n\n beforeEach(() => {\n provider = new CeloJsonRpcProvider('https://forno.celo.org');\n });\n\n // Test if gasLimit is correctly set for blocks before the hard fork\n it('should set gasLimit to zero for blocks before the hard fork', async () => {\n const block = formatBlock(\n await provider.send('eth_getBlockByNumber', [\n utils.hexValue(16068684),\n true,\n ]),\n );\n expect(BigNumber.from(block.gasLimit)).toEqual(constants.Zero);\n });\n\n // Test if gasLimit is correctly set for blocks after the hard fork\n it('should not set gasLimit to zero for blocks after the hard fork', async () => {\n const block = formatBlock(\n await provider.send('eth_getBlockByNumber', [\n utils.hexValue(21055596),\n true,\n ]),\n );\n expect(BigNumber.from(block.gasLimit)).toEqual(BigNumber.from(0x1312d00));\n });\n});\n"]}
@@ -0,0 +1,6 @@
1
+ import { Networkish } from '@ethersproject/networks';
2
+ import { WebSocketProvider } from '@ethersproject/providers';
3
+ export declare class CeloWsProvider extends WebSocketProvider {
4
+ private flanHardForkBlock;
5
+ constructor(url?: string, network?: Networkish);
6
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ // Copyright 2020-2023 SubQuery Pte Ltd authors & contributors
3
+ // SPDX-License-Identifier: GPL-3.0
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.CeloWsProvider = void 0;
6
+ const providers_1 = require("@ethersproject/providers");
7
+ const node_core_1 = require("@subql/node-core");
8
+ const ethers_1 = require("ethers");
9
+ const logger = (0, node_core_1.getLogger)('celo-ws-provider');
10
+ class CeloWsProvider extends providers_1.WebSocketProvider {
11
+ constructor(url, network) {
12
+ super(url, network);
13
+ this.flanHardForkBlock = ethers_1.BigNumber.from('16068685');
14
+ const originalBlockFormatter = this.formatter._block;
15
+ this.formatter._block = (value, format) => {
16
+ return originalBlockFormatter(Object.assign({ gasLimit: ethers_1.BigNumber.from(value.number) < this.flanHardForkBlock
17
+ ? ethers_1.constants.Zero
18
+ : value.gasLimit }, value), format);
19
+ };
20
+ }
21
+ }
22
+ exports.CeloWsProvider = CeloWsProvider;
23
+ //# sourceMappingURL=celo-ws-provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"celo-ws-provider.js","sourceRoot":"","sources":["../../../../src/ethereum/ethers/celo/celo-ws-provider.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;AAGnC,wDAA6D;AAC7D,gDAA6C;AAC7C,mCAA8C;AAE9C,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,kBAAkB,CAAC,CAAC;AAE7C,MAAa,cAAe,SAAQ,6BAAiB;IAEnD,YAAY,GAAY,EAAE,OAAoB;QAC5C,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAFd,sBAAiB,GAAG,kBAAS,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QAIrD,MAAM,sBAAsB,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC;QACrD,IAAI,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE;YACxC,OAAO,sBAAsB,iBAEzB,QAAQ,EACN,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,iBAAiB;oBACnD,CAAC,CAAC,kBAAS,CAAC,IAAI;oBAChB,CAAC,CAAC,KAAK,CAAC,QAAQ,IACjB,KAAK,GAEV,MAAM,CACP,CAAC;QACJ,CAAC,CAAC;IACJ,CAAC;CACF;AAnBD,wCAmBC","sourcesContent":["// Copyright 2020-2023 SubQuery Pte Ltd authors & contributors\n// SPDX-License-Identifier: GPL-3.0\n\nimport { Networkish } from '@ethersproject/networks';\nimport { WebSocketProvider } from '@ethersproject/providers';\nimport { getLogger } from '@subql/node-core';\nimport { BigNumber, constants } from 'ethers';\n\nconst logger = getLogger('celo-ws-provider');\n\nexport class CeloWsProvider extends WebSocketProvider {\n private flanHardForkBlock = BigNumber.from('16068685');\n constructor(url?: string, network?: Networkish) {\n super(url, network);\n\n const originalBlockFormatter = this.formatter._block;\n this.formatter._block = (value, format) => {\n return originalBlockFormatter(\n {\n gasLimit:\n BigNumber.from(value.number) < this.flanHardForkBlock\n ? constants.Zero\n : value.gasLimit,\n ...value,\n },\n format,\n );\n };\n }\n}\n"]}
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ // Copyright 2020-2023 SubQuery Pte Ltd authors & contributors
3
+ // SPDX-License-Identifier: GPL-3.0
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ const ethers_1 = require("ethers");
6
+ const utils_ethereum_1 = require("../../utils.ethereum");
7
+ const celo_ws_provider_1 = require("./celo-ws-provider");
8
+ describe('CeloJsonRpcProvider', () => {
9
+ let provider;
10
+ beforeEach(() => {
11
+ provider = new celo_ws_provider_1.CeloWsProvider('https://forno.celo.org');
12
+ });
13
+ // Test if gasLimit is correctly set for blocks before the hard fork
14
+ it('should set gasLimit to zero for blocks before the hard fork', async () => {
15
+ const block = (0, utils_ethereum_1.formatBlock)(await provider.send('eth_getBlockByNumber', [
16
+ ethers_1.utils.hexValue(16068684),
17
+ true,
18
+ ]));
19
+ expect(ethers_1.BigNumber.from(block.gasLimit)).toEqual(ethers_1.constants.Zero);
20
+ });
21
+ // Test if gasLimit is correctly set for blocks after the hard fork
22
+ it('should not set gasLimit to zero for blocks after the hard fork', async () => {
23
+ const block = (0, utils_ethereum_1.formatBlock)(await provider.send('eth_getBlockByNumber', [
24
+ ethers_1.utils.hexValue(21055596),
25
+ true,
26
+ ]));
27
+ expect(ethers_1.BigNumber.from(block.gasLimit)).toEqual(ethers_1.BigNumber.from(0x1312d00));
28
+ });
29
+ });
30
+ //# sourceMappingURL=celo-ws-provider.spec.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"celo-ws-provider.spec.js","sourceRoot":"","sources":["../../../../src/ethereum/ethers/celo/celo-ws-provider.spec.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;AAEnC,mCAAqD;AACrD,yDAAmD;AACnD,yDAAoD;AAEpD,QAAQ,CAAC,qBAAqB,EAAE,GAAG,EAAE;IACnC,IAAI,QAAwB,CAAC;IAE7B,UAAU,CAAC,GAAG,EAAE;QACd,QAAQ,GAAG,IAAI,iCAAc,CAAC,wBAAwB,CAAC,CAAC;IAC1D,CAAC,CAAC,CAAC;IAEH,oEAAoE;IACpE,EAAE,CAAC,6DAA6D,EAAE,KAAK,IAAI,EAAE;QAC3E,MAAM,KAAK,GAAG,IAAA,4BAAW,EACvB,MAAM,QAAQ,CAAC,IAAI,CAAC,sBAAsB,EAAE;YAC1C,cAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;YACxB,IAAI;SACL,CAAC,CACH,CAAC;QACF,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAS,CAAC,IAAI,CAAC,CAAC;IACjE,CAAC,CAAC,CAAC;IAEH,mEAAmE;IACnE,EAAE,CAAC,gEAAgE,EAAE,KAAK,IAAI,EAAE;QAC9E,MAAM,KAAK,GAAG,IAAA,4BAAW,EACvB,MAAM,QAAQ,CAAC,IAAI,CAAC,sBAAsB,EAAE;YAC1C,cAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;YACxB,IAAI;SACL,CAAC,CACH,CAAC;QACF,MAAM,CAAC,kBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,kBAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IAC5E,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 { BigNumber, constants, utils } from 'ethers';\nimport { formatBlock } from '../../utils.ethereum';\nimport { CeloWsProvider } from './celo-ws-provider';\n\ndescribe('CeloJsonRpcProvider', () => {\n let provider: CeloWsProvider;\n\n beforeEach(() => {\n provider = new CeloWsProvider('https://forno.celo.org');\n });\n\n // Test if gasLimit is correctly set for blocks before the hard fork\n it('should set gasLimit to zero for blocks before the hard fork', async () => {\n const block = formatBlock(\n await provider.send('eth_getBlockByNumber', [\n utils.hexValue(16068684),\n true,\n ]),\n );\n expect(BigNumber.from(block.gasLimit)).toEqual(constants.Zero);\n });\n\n // Test if gasLimit is correctly set for blocks after the hard fork\n it('should not set gasLimit to zero for blocks after the hard fork', async () => {\n const block = formatBlock(\n await provider.send('eth_getBlockByNumber', [\n utils.hexValue(21055596),\n true,\n ]),\n );\n expect(BigNumber.from(block.gasLimit)).toEqual(BigNumber.from(0x1312d00));\n });\n});\n"]}
@@ -25,6 +25,9 @@ function handleNumber(value) {
25
25
  if (value === '0x') {
26
26
  return constants_1.Zero;
27
27
  }
28
+ if (value === null) {
29
+ return constants_1.Zero;
30
+ }
28
31
  return bignumber_1.BigNumber.from(value);
29
32
  }
30
33
  function formatBlock(block) {
@@ -1 +1 @@
1
- {"version":3,"file":"utils.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/utils.ethereum.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;AAEnC,oDAAoD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AAC,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 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 return {\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 get transaction() {\n const rawTransaction = block.transactions?.find(\n (tx) => tx.hash === log.transactionHash,\n );\n return rawTransaction\n ? formatTransaction(rawTransaction, block)\n : undefined;\n },\n toJSON(): string {\n return JSON.stringify(omit(this, ['transaction', 'block', 'toJSON']));\n },\n } 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,IAAI,CAAC;KACb;IACD,OAAO,IAAA,oBAAU,EAAC,KAAK,CAAC,CAAC;AAC3B,CAAC;AAED,SAAS,YAAY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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 return {\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 get transaction() {\n const rawTransaction = block.transactions?.find(\n (tx) => tx.hash === log.transactionHash,\n );\n return rawTransaction\n ? formatTransaction(rawTransaction, block)\n : undefined;\n },\n toJSON(): string {\n return JSON.stringify(omit(this, ['transaction', 'block', 'toJSON']));\n },\n } 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"]}
@@ -91,6 +91,11 @@ function eventFilterToQueryEntry(filter, dsOptions) {
91
91
  function callFilterToQueryEntry(filter, dsOptions) {
92
92
  const conditions = [];
93
93
  appendDsOptions(dsOptions, conditions);
94
+ for (const condition of conditions) {
95
+ if (condition.field === 'address') {
96
+ condition.field = 'to';
97
+ }
98
+ }
94
99
  if (filter.from) {
95
100
  conditions.push({
96
101
  field: 'from',
@@ -98,19 +103,25 @@ function callFilterToQueryEntry(filter, dsOptions) {
98
103
  matcher: 'equalTo',
99
104
  });
100
105
  }
101
- if (filter.to) {
102
- conditions.push({
103
- field: 'to',
104
- value: filter.to.toLowerCase(),
105
- matcher: 'equalTo',
106
- });
106
+ const optionsAddresses = conditions.find((c) => c.field === 'to');
107
+ if (!optionsAddresses) {
108
+ if (filter.to) {
109
+ conditions.push({
110
+ field: 'to',
111
+ value: filter.to.toLowerCase(),
112
+ matcher: 'equalTo',
113
+ });
114
+ }
115
+ else if (filter.to === null) {
116
+ conditions.push({
117
+ field: 'to',
118
+ value: true,
119
+ matcher: 'isNull',
120
+ });
121
+ }
107
122
  }
108
- else if (filter.to === null) {
109
- conditions.push({
110
- field: 'to',
111
- value: true,
112
- matcher: 'isNull',
113
- });
123
+ else {
124
+ logger.warn(`TransactionFilter 'to' conflict with 'address' in data source options`);
114
125
  }
115
126
  if (filter.function) {
116
127
  conditions.push({
@@ -1 +1 @@
1
- {"version":3,"file":"fetch.service.js","sourceRoot":"","sources":["../../src/indexer/fetch.service.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;AAEnC,2CAAoD;AACpD,yDAAsD;AACtD,+CAAqD;AAErD,4DAMgC;AAChC,gDAK0B;AAI1B,mCAAiD;AACjD,kEAA+E;AAG/E,+DAA0D;AAC1D,4CAAkE;AAClE,oCAAwC;AAExC,6DAAyD;AACzD,iEAA4D;AAC5D,6DAAwD;AACxD,2EAGqC;AAErC,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,eAAe,CAAC,CAAC;AAE1C,MAAM,mBAAmB,GAAG,IAAI,CAAC;AAEjC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAE7B,SAAS,eAAe,CACtB,SAA0E,EAC1E,UAAsC;IAEtC,MAAM,iBAAiB,GAAG,oBAAY,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;IACnE,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;QAC5B,MAAM,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QAE5E,IAAI,SAAS,CAAC,MAAM,GAAG,iBAAiB,EAAE;YACxC,MAAM,CAAC,IAAI,CACT,qBAAqB,SAAS,CAAC,MAAM,wBAAwB,iBAAiB,wEAAwE,CACvJ,CAAC;SACH;QAED,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,IAAI,SAAS,CAAC,MAAM,IAAI,iBAAiB,EAAE;YACnE,UAAU,CAAC,IAAI,CAAC;gBACd,KAAK,EAAE,SAAS;gBAChB,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MAAM,CAAC,MAAM,CAAC,CAAC;iBACrC;aACF;SACF;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAES,KAAK,CAAC,mBAAmB;QACjC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACjE,CAAC;IAES,KAAK,CAAC,wBAAwB,CACtC,QAAkB;QAElB,OAAO,OAAO,CAAC,OAAO;QACpB,yBAAyB;QACzB,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC,GAAG,CAAC,cAAc,EAAE;YAChD,6BAA6B;YAC7B,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAC1D,CAAC;IACJ,CAAC;IAES,KAAK,CAAC,WAAW;QACzB,4CAA4C;QAC5C,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF,CAAA;AAvHY,YAAY;IADxB,IAAA,mBAAU,GAAE;IAUR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;IAC1B,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAHf,sBAAU;QACV,sBAAU;QACe,iCAAe,UAGjC,sCAAiB;QAChB,yCAAkB;QACpB,qCAAgB;QACA,oDAAwB;QAC5C,6BAAa;QACR,4BAAiB;GAjB3B,YAAY,CAuHxB;AAvHY,oCAAY","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 { SchedulerRegistry } from '@nestjs/schedule';\n\nimport {\n isCustomDs,\n EthereumHandlerKind,\n EthereumLogFilter,\n SubqlEthereumProcessorOptions,\n EthereumTransactionFilter,\n} from '@subql/common-ethereum';\nimport {\n NodeConfig,\n BaseFetchService,\n ApiService,\n getLogger,\n} from '@subql/node-core';\nimport { DictionaryQueryCondition, DictionaryQueryEntry } from '@subql/types';\nimport { SubqlDatasource } from '@subql/types-ethereum';\nimport { MetaData } from '@subql/utils';\nimport { groupBy, sortBy, uniqBy } from 'lodash';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApi, EthereumApiService } from '../ethereum';\nimport SafeEthProvider from '../ethereum/safe-api';\nimport { calcInterval } from '../ethereum/utils.ethereum';\nimport { eventToTopic, functionToSighash } from '../utils/string';\nimport { yargsOptions } from '../yargs';\nimport { IEthereumBlockDispatcher } from './blockDispatcher';\nimport { DictionaryService } from './dictionary.service';\nimport { DsProcessorService } from './ds-processor.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport {\n blockToHeader,\n UnfinalizedBlocksService,\n} from './unfinalizedBlocks.service';\n\nconst logger = getLogger('fetch.service');\n\nconst BLOCK_TIME_VARIANCE = 5000;\n\nconst INTERVAL_PERCENT = 0.9;\n\nfunction appendDsOptions(\n dsOptions: SubqlEthereumProcessorOptions | SubqlEthereumProcessorOptions[],\n conditions: DictionaryQueryCondition[],\n): void {\n const queryAddressLimit = yargsOptions.argv['query-address-limit'];\n if (Array.isArray(dsOptions)) {\n const addresses = dsOptions.map((option) => option.address).filter(Boolean);\n\n if (addresses.length > queryAddressLimit) {\n logger.warn(\n `Addresses length: ${addresses.length} is exceeding limit: ${queryAddressLimit}. Consider increasing this value with the flag --query-address-limit `,\n );\n }\n\n if (addresses.length !== 0 && addresses.length <= queryAddressLimit) {\n conditions.push({\n field: 'address',\n value: addresses,\n matcher: 'in',\n });\n }\n } else {\n if (dsOptions?.address) {\n conditions.push({\n field: 'address',\n value: dsOptions.address.toLowerCase(),\n matcher: 'equalTo',\n });\n }\n }\n}\n\nfunction eventFilterToQueryEntry(\n filter: EthereumLogFilter,\n dsOptions: SubqlEthereumProcessorOptions | SubqlEthereumProcessorOptions[],\n): DictionaryQueryEntry {\n const conditions: DictionaryQueryCondition[] = [];\n appendDsOptions(dsOptions, conditions);\n if (filter.topics) {\n for (let i = 0; i < Math.min(filter.topics.length, 4); i++) {\n const topic = filter.topics[i];\n if (!topic) {\n continue;\n }\n const field = `topics${i}`;\n\n if (topic === '!null') {\n conditions.push({\n field,\n value: false as any, // TODO update types to allow boolean\n matcher: 'isNull',\n });\n } else {\n conditions.push({\n field,\n value: eventToTopic(topic),\n matcher: 'equalTo',\n });\n }\n }\n }\n return {\n entity: 'evmLogs',\n conditions,\n };\n}\n\nfunction callFilterToQueryEntry(\n filter: EthereumTransactionFilter,\n dsOptions: SubqlEthereumProcessorOptions | SubqlEthereumProcessorOptions[],\n): DictionaryQueryEntry {\n const conditions: DictionaryQueryCondition[] = [];\n appendDsOptions(dsOptions, conditions);\n if (filter.from) {\n conditions.push({\n field: 'from',\n value: filter.from.toLowerCase(),\n matcher: 'equalTo',\n });\n }\n if (filter.to) {\n conditions.push({\n field: 'to',\n value: filter.to.toLowerCase(),\n matcher: 'equalTo',\n });\n } else if (filter.to === null) {\n conditions.push({\n field: 'to',\n value: true as any, // TODO update types to allow boolean\n matcher: 'isNull',\n });\n }\n if (filter.function) {\n conditions.push({\n field: 'func',\n value: functionToSighash(filter.function),\n matcher: 'equalTo',\n });\n }\n return {\n entity: 'evmTransactions',\n conditions,\n };\n}\n\ntype GroupedSubqlProjectDs = SubqlDatasource & {\n groupedOptions?: SubqlEthereumProcessorOptions[];\n};\nexport function buildDictionaryQueryEntries(\n dataSources: GroupedSubqlProjectDs[],\n startBlock: number,\n): DictionaryQueryEntry[] {\n const queryEntries: DictionaryQueryEntry[] = [];\n\n // Only run the ds that is equal or less than startBlock\n // sort array from lowest ds.startBlock to highest\n const filteredDs = dataSources\n .filter((ds) => ds.startBlock <= startBlock)\n .sort((a, b) => a.startBlock - b.startBlock);\n\n for (const ds of filteredDs) {\n for (const handler of ds.mapping.handlers) {\n // No filters, cant use dictionary\n if (!handler.filter) return [];\n\n switch (handler.kind) {\n case EthereumHandlerKind.Block:\n return [];\n case EthereumHandlerKind.Call: {\n const filter = handler.filter as EthereumTransactionFilter;\n if (\n filter.from !== undefined ||\n filter.to !== undefined ||\n filter.function\n ) {\n queryEntries.push(callFilterToQueryEntry(filter, ds.options));\n } else {\n return [];\n }\n break;\n }\n case EthereumHandlerKind.Event: {\n const filter = handler.filter as EthereumLogFilter;\n if (ds.groupedOptions) {\n queryEntries.push(\n eventFilterToQueryEntry(filter, ds.groupedOptions),\n );\n } else if (ds.options?.address || filter.topics) {\n queryEntries.push(eventFilterToQueryEntry(filter, ds.options));\n } else {\n return [];\n }\n break;\n }\n default:\n }\n }\n }\n\n return uniqBy(\n queryEntries,\n (item) =>\n `${item.entity}|${JSON.stringify(\n sortBy(item.conditions, (c) => c.field),\n )}`,\n );\n}\n\n@Injectable()\nexport class FetchService extends BaseFetchService<\n ApiService,\n SubqlDatasource,\n IEthereumBlockDispatcher,\n DictionaryService\n> {\n constructor(\n apiService: ApiService,\n nodeConfig: NodeConfig,\n @Inject('ISubqueryProject') project: SubqueryProject,\n @Inject('IBlockDispatcher')\n blockDispatcher: IEthereumBlockDispatcher,\n dictionaryService: DictionaryService,\n dsProcessorService: DsProcessorService,\n dynamicDsService: DynamicDsService,\n private unfinalizedBlocksService: UnfinalizedBlocksService,\n eventEmitter: EventEmitter2,\n schedulerRegistry: SchedulerRegistry,\n ) {\n super(\n apiService,\n nodeConfig,\n project,\n blockDispatcher,\n dictionaryService,\n dsProcessorService,\n dynamicDsService,\n eventEmitter,\n schedulerRegistry,\n );\n }\n\n get api(): EthereumApi {\n return this.apiService.unsafeApi;\n }\n\n buildDictionaryQueryEntries(startBlock: number): DictionaryQueryEntry[] {\n const groupdDynamicDs: GroupedSubqlProjectDs[] = Object.values(\n groupBy(this.templateDynamicDatasouces, (ds) => ds.name),\n ).map((grouped: SubqlProjectDs[]) => {\n const options = grouped.map((ds) => ds.options);\n const ref = grouped[0];\n\n return {\n ...ref,\n groupedOptions: options,\n };\n });\n\n // Only run the ds that is equal or less than startBlock\n // sort array from lowest ds.startBlock to highest\n const filteredDs: GroupedSubqlProjectDs[] =\n this.project.dataSources.concat(groupdDynamicDs);\n\n return buildDictionaryQueryEntries(filteredDs, startBlock);\n }\n\n protected async getFinalizedHeight(): Promise<number> {\n const block = await this.api.getFinalizedBlock();\n\n const header = blockToHeader(block);\n\n this.unfinalizedBlocksService.registerFinalizedBlock(header);\n return header.blockHeight;\n }\n\n protected async getBestHeight(): Promise<number> {\n return this.api.getBestBlockHeight();\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n protected async getChainInterval(): Promise<number> {\n const CHAIN_INTERVAL = calcInterval(this.api) * INTERVAL_PERCENT;\n\n return Math.min(BLOCK_TIME_VARIANCE, CHAIN_INTERVAL);\n }\n\n protected async getChainId(): Promise<string> {\n return Promise.resolve(this.api.getChainId().toString());\n }\n\n protected getModulos(): number[] {\n const modulos: number[] = [];\n for (const ds of this.project.dataSources) {\n if (isCustomDs(ds)) {\n continue;\n }\n for (const handler of ds.mapping.handlers) {\n if (\n handler.kind === EthereumHandlerKind.Block &&\n handler.filter &&\n handler.filter.modulo\n ) {\n modulos.push(handler.filter.modulo);\n }\n }\n }\n return modulos;\n }\n\n protected async initBlockDispatcher(): Promise<void> {\n await this.blockDispatcher.init(this.resetForNewDs.bind(this));\n }\n\n protected async validatateDictionaryMeta(\n metaData: MetaData,\n ): Promise<boolean> {\n return Promise.resolve(\n // When alias is not used\n metaData.genesisHash !== this.api.getGenesisHash() &&\n // Case when an alias is used\n metaData.genesisHash !== this.dictionaryService.chainId,\n );\n }\n\n protected async preLoopHook(): Promise<void> {\n // Ethereum doesn't need to do anything here\n return Promise.resolve();\n }\n}\n"]}
1
+ {"version":3,"file":"fetch.service.js","sourceRoot":"","sources":["../../src/indexer/fetch.service.ts"],"names":[],"mappings":";AAAA,8DAA8D;AAC9D,mCAAmC;;;;;;;;;;;;;;;AAEnC,2CAAoD;AACpD,yDAAsD;AACtD,+CAAqD;AAErD,4DAMgC;AAChC,gDAK0B;AAI1B,mCAAiD;AACj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AAC,MAAM,CAAC,MAAM,CAAC,CAAC;iBACrC;aACF;SACF;QACD,OAAO,OAAO,CAAC;IACjB,CAAC;IAES,KAAK,CAAC,mBAAmB;QACjC,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;IACjE,CAAC;IAES,KAAK,CAAC,wBAAwB,CACtC,QAAkB;QAElB,OAAO,OAAO,CAAC,OAAO;QACpB,yBAAyB;QACzB,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC,GAAG,CAAC,cAAc,EAAE;YAChD,6BAA6B;YAC7B,QAAQ,CAAC,WAAW,KAAK,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAC1D,CAAC;IACJ,CAAC;IAES,KAAK,CAAC,WAAW;QACzB,4CAA4C;QAC5C,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF,CAAA;AAvHY,YAAY;IADxB,IAAA,mBAAU,GAAE;IAUR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;IAC1B,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAHf,sBAAU;QACV,sBAAU;QACe,iCAAe,UAGjC,sCAAiB;QAChB,yCAAkB;QACpB,qCAAgB;QACA,oDAAwB;QAC5C,6BAAa;QACR,4BAAiB;GAjB3B,YAAY,CAuHxB;AAvHY,oCAAY","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 { SchedulerRegistry } from '@nestjs/schedule';\n\nimport {\n isCustomDs,\n EthereumHandlerKind,\n EthereumLogFilter,\n SubqlEthereumProcessorOptions,\n EthereumTransactionFilter,\n} from '@subql/common-ethereum';\nimport {\n NodeConfig,\n BaseFetchService,\n ApiService,\n getLogger,\n} from '@subql/node-core';\nimport { DictionaryQueryCondition, DictionaryQueryEntry } from '@subql/types';\nimport { SubqlDatasource } from '@subql/types-ethereum';\nimport { MetaData } from '@subql/utils';\nimport { groupBy, sortBy, uniqBy } from 'lodash';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApi, EthereumApiService } from '../ethereum';\nimport SafeEthProvider from '../ethereum/safe-api';\nimport { calcInterval } from '../ethereum/utils.ethereum';\nimport { eventToTopic, functionToSighash } from '../utils/string';\nimport { yargsOptions } from '../yargs';\nimport { IEthereumBlockDispatcher } from './blockDispatcher';\nimport { DictionaryService } from './dictionary.service';\nimport { DsProcessorService } from './ds-processor.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport {\n blockToHeader,\n UnfinalizedBlocksService,\n} from './unfinalizedBlocks.service';\n\nconst logger = getLogger('fetch.service');\n\nconst BLOCK_TIME_VARIANCE = 5000;\n\nconst INTERVAL_PERCENT = 0.9;\n\nfunction appendDsOptions(\n dsOptions: SubqlEthereumProcessorOptions | SubqlEthereumProcessorOptions[],\n conditions: DictionaryQueryCondition[],\n): void {\n const queryAddressLimit = yargsOptions.argv['query-address-limit'];\n if (Array.isArray(dsOptions)) {\n const addresses = dsOptions.map((option) => option.address).filter(Boolean);\n\n if (addresses.length > queryAddressLimit) {\n logger.warn(\n `Addresses length: ${addresses.length} is exceeding limit: ${queryAddressLimit}. Consider increasing this value with the flag --query-address-limit `,\n );\n }\n\n if (addresses.length !== 0 && addresses.length <= queryAddressLimit) {\n conditions.push({\n field: 'address',\n value: addresses,\n matcher: 'in',\n });\n }\n } else {\n if (dsOptions?.address) {\n conditions.push({\n field: 'address',\n value: dsOptions.address.toLowerCase(),\n matcher: 'equalTo',\n });\n }\n }\n}\n\nfunction eventFilterToQueryEntry(\n filter: EthereumLogFilter,\n dsOptions: SubqlEthereumProcessorOptions | SubqlEthereumProcessorOptions[],\n): DictionaryQueryEntry {\n const conditions: DictionaryQueryCondition[] = [];\n appendDsOptions(dsOptions, conditions);\n if (filter.topics) {\n for (let i = 0; i < Math.min(filter.topics.length, 4); i++) {\n const topic = filter.topics[i];\n if (!topic) {\n continue;\n }\n const field = `topics${i}`;\n\n if (topic === '!null') {\n conditions.push({\n field,\n value: false as any, // TODO update types to allow boolean\n matcher: 'isNull',\n });\n } else {\n conditions.push({\n field,\n value: eventToTopic(topic),\n matcher: 'equalTo',\n });\n }\n }\n }\n return {\n entity: 'evmLogs',\n conditions,\n };\n}\n\nfunction callFilterToQueryEntry(\n filter: EthereumTransactionFilter,\n dsOptions: SubqlEthereumProcessorOptions | SubqlEthereumProcessorOptions[],\n): DictionaryQueryEntry {\n const conditions: DictionaryQueryCondition[] = [];\n appendDsOptions(dsOptions, conditions);\n\n for (const condition of conditions) {\n if (condition.field === 'address') {\n condition.field = 'to';\n }\n }\n if (filter.from) {\n conditions.push({\n field: 'from',\n value: filter.from.toLowerCase(),\n matcher: 'equalTo',\n });\n }\n const optionsAddresses = conditions.find((c) => c.field === 'to');\n if (!optionsAddresses) {\n if (filter.to) {\n conditions.push({\n field: 'to',\n value: filter.to.toLowerCase(),\n matcher: 'equalTo',\n });\n } else if (filter.to === null) {\n conditions.push({\n field: 'to',\n value: true as any, // TODO update types to allow boolean\n matcher: 'isNull',\n });\n }\n } else {\n logger.warn(\n `TransactionFilter 'to' conflict with 'address' in data source options`,\n );\n }\n\n if (filter.function) {\n conditions.push({\n field: 'func',\n value: functionToSighash(filter.function),\n matcher: 'equalTo',\n });\n }\n return {\n entity: 'evmTransactions',\n conditions,\n };\n}\n\ntype GroupedSubqlProjectDs = SubqlDatasource & {\n groupedOptions?: SubqlEthereumProcessorOptions[];\n};\nexport function buildDictionaryQueryEntries(\n dataSources: GroupedSubqlProjectDs[],\n startBlock: number,\n): DictionaryQueryEntry[] {\n const queryEntries: DictionaryQueryEntry[] = [];\n\n // Only run the ds that is equal or less than startBlock\n // sort array from lowest ds.startBlock to highest\n const filteredDs = dataSources\n .filter((ds) => ds.startBlock <= startBlock)\n .sort((a, b) => a.startBlock - b.startBlock);\n\n for (const ds of filteredDs) {\n for (const handler of ds.mapping.handlers) {\n // No filters, cant use dictionary\n if (!handler.filter) return [];\n\n switch (handler.kind) {\n case EthereumHandlerKind.Block:\n return [];\n case EthereumHandlerKind.Call: {\n const filter = handler.filter as EthereumTransactionFilter;\n if (\n filter.from !== undefined ||\n filter.to !== undefined ||\n filter.function\n ) {\n queryEntries.push(callFilterToQueryEntry(filter, ds.options));\n } else {\n return [];\n }\n break;\n }\n case EthereumHandlerKind.Event: {\n const filter = handler.filter as EthereumLogFilter;\n if (ds.groupedOptions) {\n queryEntries.push(\n eventFilterToQueryEntry(filter, ds.groupedOptions),\n );\n } else if (ds.options?.address || filter.topics) {\n queryEntries.push(eventFilterToQueryEntry(filter, ds.options));\n } else {\n return [];\n }\n break;\n }\n default:\n }\n }\n }\n\n return uniqBy(\n queryEntries,\n (item) =>\n `${item.entity}|${JSON.stringify(\n sortBy(item.conditions, (c) => c.field),\n )}`,\n );\n}\n\n@Injectable()\nexport class FetchService extends BaseFetchService<\n ApiService,\n SubqlDatasource,\n IEthereumBlockDispatcher,\n DictionaryService\n> {\n constructor(\n apiService: ApiService,\n nodeConfig: NodeConfig,\n @Inject('ISubqueryProject') project: SubqueryProject,\n @Inject('IBlockDispatcher')\n blockDispatcher: IEthereumBlockDispatcher,\n dictionaryService: DictionaryService,\n dsProcessorService: DsProcessorService,\n dynamicDsService: DynamicDsService,\n private unfinalizedBlocksService: UnfinalizedBlocksService,\n eventEmitter: EventEmitter2,\n schedulerRegistry: SchedulerRegistry,\n ) {\n super(\n apiService,\n nodeConfig,\n project,\n blockDispatcher,\n dictionaryService,\n dsProcessorService,\n dynamicDsService,\n eventEmitter,\n schedulerRegistry,\n );\n }\n\n get api(): EthereumApi {\n return this.apiService.unsafeApi;\n }\n\n buildDictionaryQueryEntries(startBlock: number): DictionaryQueryEntry[] {\n const groupdDynamicDs: GroupedSubqlProjectDs[] = Object.values(\n groupBy(this.templateDynamicDatasouces, (ds) => ds.name),\n ).map((grouped: SubqlProjectDs[]) => {\n const options = grouped.map((ds) => ds.options);\n const ref = grouped[0];\n\n return {\n ...ref,\n groupedOptions: options,\n };\n });\n\n // Only run the ds that is equal or less than startBlock\n // sort array from lowest ds.startBlock to highest\n const filteredDs: GroupedSubqlProjectDs[] =\n this.project.dataSources.concat(groupdDynamicDs);\n\n return buildDictionaryQueryEntries(filteredDs, startBlock);\n }\n\n protected async getFinalizedHeight(): Promise<number> {\n const block = await this.api.getFinalizedBlock();\n\n const header = blockToHeader(block);\n\n this.unfinalizedBlocksService.registerFinalizedBlock(header);\n return header.blockHeight;\n }\n\n protected async getBestHeight(): Promise<number> {\n return this.api.getBestBlockHeight();\n }\n\n // eslint-disable-next-line @typescript-eslint/require-await\n protected async getChainInterval(): Promise<number> {\n const CHAIN_INTERVAL = calcInterval(this.api) * INTERVAL_PERCENT;\n\n return Math.min(BLOCK_TIME_VARIANCE, CHAIN_INTERVAL);\n }\n\n protected async getChainId(): Promise<string> {\n return Promise.resolve(this.api.getChainId().toString());\n }\n\n protected getModulos(): number[] {\n const modulos: number[] = [];\n for (const ds of this.project.dataSources) {\n if (isCustomDs(ds)) {\n continue;\n }\n for (const handler of ds.mapping.handlers) {\n if (\n handler.kind === EthereumHandlerKind.Block &&\n handler.filter &&\n handler.filter.modulo\n ) {\n modulos.push(handler.filter.modulo);\n }\n }\n }\n return modulos;\n }\n\n protected async initBlockDispatcher(): Promise<void> {\n await this.blockDispatcher.init(this.resetForNewDs.bind(this));\n }\n\n protected async validatateDictionaryMeta(\n metaData: MetaData,\n ): Promise<boolean> {\n return Promise.resolve(\n // When alias is not used\n metaData.genesisHash !== this.api.getGenesisHash() &&\n // Case when an alias is used\n metaData.genesisHash !== this.dictionaryService.chainId,\n );\n }\n\n protected async preLoopHook(): Promise<void> {\n // Ethereum doesn't need to do anything here\n return Promise.resolve();\n }\n}\n"]}