@subql/node-ethereum 0.4.1-4 → 0.4.1-6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.tsbuildinfo +1 -1
- package/dist/ethereum/api.ethereum.js +2 -1
- package/dist/ethereum/api.ethereum.js.map +1 -1
- package/dist/ethereum/safe-api.d.ts +34 -0
- package/dist/ethereum/safe-api.js +114 -0
- package/dist/ethereum/safe-api.js.map +1 -0
- package/dist/indexer/fetch.service.js +2 -1
- package/dist/indexer/fetch.service.js.map +1 -1
- package/package.json +4 -4
|
@@ -15,6 +15,7 @@ const node_core_1 = require("@subql/node-core");
|
|
|
15
15
|
const utils_1 = require("ethers/lib/utils");
|
|
16
16
|
const project_1 = require("../utils/project");
|
|
17
17
|
const block_ethereum_1 = require("./block.ethereum");
|
|
18
|
+
const safe_api_1 = __importDefault(require("./safe-api"));
|
|
18
19
|
const utils_ethereum_1 = require("./utils.ethereum");
|
|
19
20
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
20
21
|
const { version: packageVersion } = require('../../package.json');
|
|
@@ -145,7 +146,7 @@ class EthereumApi {
|
|
|
145
146
|
}));
|
|
146
147
|
}
|
|
147
148
|
freezeApi(processor, blockContent) {
|
|
148
|
-
processor.freeze(this.client, 'api');
|
|
149
|
+
processor.freeze(new safe_api_1.default(this.client, blockContent.blockHeight), 'api');
|
|
149
150
|
}
|
|
150
151
|
buildInterface(abiName, assets) {
|
|
151
152
|
if (!assets[abiName]) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;AAEtC,oDAA4B;AAC5B,4CAAoB;AAGpB,4CAA+C;AAE/C,wDAAqD;AACrD,wDAA8E;AAE9E,gDAA6C;AAS7C,4CAA0E;AAC1E,8CAAkD;AAClD,qDAAwD;AACxD,qD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AAC,CAAC;YACpC,MAAM,KAAK,GAAG,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YAC1D,MAAM,IAAI,GAAG,KAAK,CAAC,WAAW,CAAC,IAAA,oBAAY,EAAC,WAAW,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YACtE,MAAM,IAAI,GAAG,KAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,WAAW,CAAC,KAAK,CAAM,CAAC;YACpE,uCACK,WAAW,KACd,IAAI,IACJ;SACH;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,IAAI,CAAC,qCAAqC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9D,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AAxOD,kCAwOC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport assert from 'assert';\nimport fs from 'fs';\nimport http from 'http';\nimport https from 'https';\nimport { Interface } from '@ethersproject/abi';\nimport { Block, TransactionReceipt } from '@ethersproject/abstract-provider';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { JsonRpcProvider, WebSocketProvider } from '@ethersproject/providers';\nimport { RuntimeDataSourceV0_2_0 } from '@subql/common-ethereum';\nimport { getLogger } from '@subql/node-core';\nimport {\n ApiWrapper,\n BlockWrapper,\n EthereumBlockWrapper,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n} from '@subql/types-ethereum';\nimport { ConnectionInfo, hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport { EthereumBlockWrapped } from './block.ethereum';\nimport {\n formatBlock,\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: RuntimeDataSourceV0_2_0,\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\nexport class EthereumApi implements ApiWrapper<EthereumBlockWrapper> {\n private client: JsonRpcProvider;\n private genesisBlock: Record<string, any>;\n private contractInterfaces: Record<string, Interface> = {};\n private chainId: number;\n\n private endpointSupportsGetBlockReceipts = true;\n\n constructor(private endpoint: string) {\n const { hostname, pathname, port, protocol, searchParams } = new URL(\n endpoint,\n );\n\n const protocolStr = protocol.replace(':', '');\n\n logger.info(this.endpoint.split('?')[0]);\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 };\n searchParams.forEach((value, name, searchParams) => {\n (connection.headers as any)[name] = value;\n });\n this.client = 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.genesisBlock = await this.client.getBlock(0);\n\n this.chainId = (await this.client.getNetwork()).chainId;\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.client.getBlock('finalized')).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n return (await this.client.getBlock('safe')).number;\n }\n\n getRuntimeChain(): string {\n return 'ethereum';\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 return this.client.getBlock(heightOrHash);\n }\n\n async getBlockPromise(num: number): Promise<any> {\n return retryOnFailEth(() =>\n this.client.send('eth_getBlockByNumber', [hexValue(num), true]),\n );\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 async fetchBlock(num: number): Promise<EthereumBlockWrapper> {\n const block_promise = await this.getBlockPromise(num);\n\n const block = formatBlock(block_promise);\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n\n if (this.endpointSupportsGetBlockReceipts) {\n try {\n const rawReceipts: any[] = await this.client.send(\n 'eth_getBlockReceipts',\n [hexValue(block.number)],\n );\n\n const receipts = rawReceipts.map((receipt) =>\n formatReceipt(receipt, block),\n );\n\n const txs = block.transactions.map((tx) => {\n const transaction = formatTransaction(tx);\n transaction.receipt =\n receipts[BigNumber.from(transaction.transactionIndex).toNumber()];\n\n assert(\n transaction.hash === transaction.receipt.transactionHash,\n 'Failed to match receipt to transaction',\n );\n\n return transaction;\n });\n\n return new EthereumBlockWrapped(block, txs);\n } catch (e) {\n // Method not avaialble https://eips.ethereum.org/EIPS/eip-1474\n if (e?.error?.code === -32601) {\n logger.warn(\n `The endpoint doesn't support 'eth_getBlockReceipts', individual receipts will be fetched instead, this will greatly impact performance.`,\n );\n this.endpointSupportsGetBlockReceipts = false;\n\n // Should continue and use old method here\n } else {\n throw e;\n }\n }\n }\n\n const transactions = await Promise.all(\n block.transactions.map(async (tx) => {\n const transaction = formatTransaction(tx);\n const receipt = await this.getTransactionReceipt(tx.hash);\n transaction.receipt = formatReceipt(receipt, block);\n return transaction;\n }),\n );\n return new EthereumBlockWrapped(block, transactions);\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => {\n try {\n // Fetch Block\n return await this.fetchBlock(num);\n } catch (e) {\n // Wrap error from an axios error to fix issue with error being undefined\n const error = new Error(e.message);\n logger.error(error, `Failed to fetch block at height ${num}`);\n throw error;\n }\n }),\n );\n }\n\n freezeApi(processor: any, blockContent: BlockWrapper): void {\n processor.freeze(this.client, 'api');\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: RuntimeDataSourceV0_2_0,\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: RuntimeDataSourceV0_2_0,\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 return {\n ...transaction,\n args,\n };\n } catch (e) {\n logger.warn(`Failed to parse transaction data: ${e.message}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AAO,EAAE,CAAC,CAAC;YACtD,OAAO,GAAG,CAAC;SACZ;IACH,CAAC;IAED,KAAK,CAAC,gBAAgB,CACpB,WAAgC,EAChC,EAA2B;;QAE3B,IAAI;YACF,IAAI,CAAC,CAAA,MAAA,EAAE,aAAF,EAAE,uBAAF,EAAE,CAAE,OAAO,0CAAE,GAAG,CAAA,EAAE;gBACrB,MAAM,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;gBAC9C,OAAO,WAAW,CAAC;aACpB;YACD,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,EAAE,CAAC,CAAC;YACpC,MAAM,KAAK,GAAG,IAAI,CAAC,cAAc,CAAC,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;YAC1D,MAAM,IAAI,GAAG,KAAK,CAAC,WAAW,CAAC,IAAA,oBAAY,EAAC,WAAW,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;YACtE,MAAM,IAAI,GAAG,KAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,WAAW,CAAC,KAAK,CAAM,CAAC;YACpE,uCACK,WAAW,KACd,IAAI,IACJ;SACH;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,IAAI,CAAC,qCAAqC,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC;YAC9D,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AA3OD,kCA2OC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport assert from 'assert';\nimport fs from 'fs';\nimport { Interface } from '@ethersproject/abi';\nimport { Block, TransactionReceipt } from '@ethersproject/abstract-provider';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { JsonRpcProvider, WebSocketProvider } from '@ethersproject/providers';\nimport { RuntimeDataSourceV0_2_0 } from '@subql/common-ethereum';\nimport { getLogger } from '@subql/node-core';\nimport {\n ApiWrapper,\n BlockWrapper,\n EthereumBlockWrapper,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n} from '@subql/types-ethereum';\nimport { ConnectionInfo, hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport { EthereumBlockWrapped } from './block.ethereum';\nimport SafeEthProvider from './safe-api';\nimport {\n formatBlock,\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: RuntimeDataSourceV0_2_0,\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\nexport class EthereumApi implements ApiWrapper<EthereumBlockWrapper> {\n private client: JsonRpcProvider;\n private genesisBlock: Record<string, any>;\n private contractInterfaces: Record<string, Interface> = {};\n private chainId: number;\n\n private endpointSupportsGetBlockReceipts = true;\n\n constructor(private endpoint: string) {\n const { hostname, pathname, port, protocol, searchParams } = new URL(\n endpoint,\n );\n\n const protocolStr = protocol.replace(':', '');\n\n logger.info(this.endpoint.split('?')[0]);\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 };\n searchParams.forEach((value, name, searchParams) => {\n (connection.headers as any)[name] = value;\n });\n this.client = 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.genesisBlock = await this.client.getBlock(0);\n\n this.chainId = (await this.client.getNetwork()).chainId;\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.client.getBlock('finalized')).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n return (await this.client.getBlock('safe')).number;\n }\n\n getRuntimeChain(): string {\n return 'ethereum';\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 return this.client.getBlock(heightOrHash);\n }\n\n async getBlockPromise(num: number): Promise<any> {\n return retryOnFailEth(() =>\n this.client.send('eth_getBlockByNumber', [hexValue(num), true]),\n );\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 async fetchBlock(num: number): Promise<EthereumBlockWrapper> {\n const block_promise = await this.getBlockPromise(num);\n\n const block = formatBlock(block_promise);\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n\n if (this.endpointSupportsGetBlockReceipts) {\n try {\n const rawReceipts: any[] = await this.client.send(\n 'eth_getBlockReceipts',\n [hexValue(block.number)],\n );\n\n const receipts = rawReceipts.map((receipt) =>\n formatReceipt(receipt, block),\n );\n\n const txs = block.transactions.map((tx) => {\n const transaction = formatTransaction(tx);\n transaction.receipt =\n receipts[BigNumber.from(transaction.transactionIndex).toNumber()];\n\n assert(\n transaction.hash === transaction.receipt.transactionHash,\n 'Failed to match receipt to transaction',\n );\n\n return transaction;\n });\n\n return new EthereumBlockWrapped(block, txs);\n } catch (e) {\n // Method not avaialble https://eips.ethereum.org/EIPS/eip-1474\n if (e?.error?.code === -32601) {\n logger.warn(\n `The endpoint doesn't support 'eth_getBlockReceipts', individual receipts will be fetched instead, this will greatly impact performance.`,\n );\n this.endpointSupportsGetBlockReceipts = false;\n\n // Should continue and use old method here\n } else {\n throw e;\n }\n }\n }\n\n const transactions = await Promise.all(\n block.transactions.map(async (tx) => {\n const transaction = formatTransaction(tx);\n const receipt = await this.getTransactionReceipt(tx.hash);\n transaction.receipt = formatReceipt(receipt, block);\n return transaction;\n }),\n );\n return new EthereumBlockWrapped(block, transactions);\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => {\n try {\n // Fetch Block\n return await this.fetchBlock(num);\n } catch (e) {\n // Wrap error from an axios error to fix issue with error being undefined\n const error = new Error(e.message);\n logger.error(error, `Failed to fetch block at height ${num}`);\n throw error;\n }\n }),\n );\n }\n\n freezeApi(processor: any, blockContent: BlockWrapper): void {\n processor.freeze(\n new SafeEthProvider(this.client, blockContent.blockHeight),\n 'api',\n );\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: RuntimeDataSourceV0_2_0,\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: RuntimeDataSourceV0_2_0,\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 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"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { Block, BlockTag, BlockWithTransactions, EventType, Filter, Listener, Log, TransactionReceipt, TransactionRequest, TransactionResponse, Provider } from '@ethersproject/abstract-provider';
|
|
2
|
+
import { BigNumber, BigNumberish } from '@ethersproject/bignumber';
|
|
3
|
+
import type { Network } from '@ethersproject/networks';
|
|
4
|
+
import type { Deferrable } from '@ethersproject/properties';
|
|
5
|
+
export default class SafeEthProvider extends Provider {
|
|
6
|
+
private baseApi;
|
|
7
|
+
private blockHeight;
|
|
8
|
+
constructor(baseApi: Provider, blockHeight: BlockTag | Promise<BlockTag>);
|
|
9
|
+
getBalance(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<BigNumber>;
|
|
10
|
+
getTransactionCount(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<number>;
|
|
11
|
+
getCode(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
|
|
12
|
+
getStorageAt(addressOrName: string | Promise<string>, position: BigNumberish | Promise<BigNumberish>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
|
|
13
|
+
call(transaction: Deferrable<TransactionRequest>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>;
|
|
14
|
+
getBlockWithTransactions(blockHashOrBlockTag: BlockTag | Promise<BlockTag>): Promise<BlockWithTransactions>;
|
|
15
|
+
getBlock(blockHashOrBlockTag: BlockTag | Promise<BlockTag>): Promise<Block>;
|
|
16
|
+
getTransaction(transactionHash: string): Promise<TransactionResponse>;
|
|
17
|
+
getTransactionReceipt(transactionHash: string): Promise<TransactionReceipt>;
|
|
18
|
+
getLogs(filter: Filter): Promise<Log[]>;
|
|
19
|
+
getBlockNumber(): Promise<number>;
|
|
20
|
+
getNetwork(): Promise<Network>;
|
|
21
|
+
getGasPrice(): Promise<BigNumber>;
|
|
22
|
+
estimateGas(transaction: Deferrable<TransactionRequest>): Promise<BigNumber>;
|
|
23
|
+
sendTransaction(signedTransaction: string | Promise<string>): Promise<TransactionResponse>;
|
|
24
|
+
resolveName(name: string | Promise<string>): Promise<string | null>;
|
|
25
|
+
lookupAddress(address: string | Promise<string>): Promise<string | null>;
|
|
26
|
+
on(eventName: EventType, listener: Listener): Provider;
|
|
27
|
+
once(eventName: EventType, listener: Listener): Provider;
|
|
28
|
+
emit(eventName: EventType, ...args: any[]): boolean;
|
|
29
|
+
listenerCount(eventName?: EventType): number;
|
|
30
|
+
listeners(eventName?: EventType): Listener[];
|
|
31
|
+
off(eventName: EventType, listener?: Listener): Provider;
|
|
32
|
+
removeAllListeners(eventName?: EventType): Provider;
|
|
33
|
+
waitForTransaction(transactionHash: string, confirmations?: number, timeout?: number): Promise<TransactionReceipt>;
|
|
34
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// Copyright 2020-2022 OnFinality Limited authors & contributors
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
+
const abstract_provider_1 = require("@ethersproject/abstract-provider");
|
|
6
|
+
const node_core_1 = require("@subql/node-core");
|
|
7
|
+
const logger = (0, node_core_1.getLogger)('safe.api.ethereum');
|
|
8
|
+
class SafeEthProvider extends abstract_provider_1.Provider {
|
|
9
|
+
constructor(baseApi, blockHeight) {
|
|
10
|
+
super();
|
|
11
|
+
this.baseApi = baseApi;
|
|
12
|
+
this.blockHeight = blockHeight;
|
|
13
|
+
}
|
|
14
|
+
async getBalance(addressOrName, blockTag) {
|
|
15
|
+
if (blockTag)
|
|
16
|
+
logger.warn(`Provided parameter 'blockTag' will not be used`);
|
|
17
|
+
return this.baseApi.getBalance(addressOrName, this.blockHeight);
|
|
18
|
+
}
|
|
19
|
+
async getTransactionCount(addressOrName, blockTag) {
|
|
20
|
+
if (blockTag)
|
|
21
|
+
logger.warn(`Provided parameter 'blockTag' will not be used`);
|
|
22
|
+
return this.baseApi.getTransactionCount(addressOrName, this.blockHeight);
|
|
23
|
+
}
|
|
24
|
+
async getCode(addressOrName, blockTag) {
|
|
25
|
+
if (blockTag)
|
|
26
|
+
logger.warn(`Provided parameter 'blockTag' will not be used`);
|
|
27
|
+
return this.baseApi.getCode(addressOrName, this.blockHeight);
|
|
28
|
+
}
|
|
29
|
+
async getStorageAt(addressOrName, position, blockTag) {
|
|
30
|
+
if (blockTag)
|
|
31
|
+
logger.warn(`Provided parameter 'blockTag' will not be used`);
|
|
32
|
+
return this.baseApi.getStorageAt(addressOrName, position, this.blockHeight);
|
|
33
|
+
}
|
|
34
|
+
async call(transaction, blockTag) {
|
|
35
|
+
if (blockTag)
|
|
36
|
+
logger.warn(`Provided parameter 'blockTag' will not be used`);
|
|
37
|
+
return this.baseApi.call(transaction, this.blockHeight);
|
|
38
|
+
}
|
|
39
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
40
|
+
getBlockWithTransactions(blockHashOrBlockTag) {
|
|
41
|
+
throw new Error('Method `getBlockWithTransactions` not supported.');
|
|
42
|
+
}
|
|
43
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
44
|
+
getBlock(blockHashOrBlockTag) {
|
|
45
|
+
throw new Error('Method `getBlock` not supported.');
|
|
46
|
+
}
|
|
47
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
48
|
+
getTransaction(transactionHash) {
|
|
49
|
+
throw new Error('Method `getTransaction` not supported.');
|
|
50
|
+
}
|
|
51
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
52
|
+
getTransactionReceipt(transactionHash) {
|
|
53
|
+
throw new Error('Method `getTransactionReceipt` not supported.');
|
|
54
|
+
}
|
|
55
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
56
|
+
getLogs(filter) {
|
|
57
|
+
throw new Error('Method `getLogs` not supported.');
|
|
58
|
+
}
|
|
59
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
60
|
+
getBlockNumber() {
|
|
61
|
+
throw new Error('Method `getBlockNumber` not supported.');
|
|
62
|
+
}
|
|
63
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
64
|
+
getNetwork() {
|
|
65
|
+
throw new Error('Method `getNetwork` not supported.');
|
|
66
|
+
}
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
68
|
+
getGasPrice() {
|
|
69
|
+
throw new Error('Method `getGasPrice` not supported.');
|
|
70
|
+
}
|
|
71
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
72
|
+
estimateGas(transaction) {
|
|
73
|
+
throw new Error('Method `estimateGas` not supported.');
|
|
74
|
+
}
|
|
75
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
76
|
+
sendTransaction(signedTransaction) {
|
|
77
|
+
throw new Error('Method `sendTransaction` not supported.');
|
|
78
|
+
}
|
|
79
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
80
|
+
resolveName(name) {
|
|
81
|
+
throw new Error('Method `resolveName` not supported.');
|
|
82
|
+
}
|
|
83
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
84
|
+
lookupAddress(address) {
|
|
85
|
+
throw new Error('Method `lookupAddress` not supported.');
|
|
86
|
+
}
|
|
87
|
+
on(eventName, listener) {
|
|
88
|
+
throw new Error('Method `on` not supported.');
|
|
89
|
+
}
|
|
90
|
+
once(eventName, listener) {
|
|
91
|
+
throw new Error('Method `once` not supported.');
|
|
92
|
+
}
|
|
93
|
+
emit(eventName, ...args) {
|
|
94
|
+
throw new Error('Method `emit` not supported.');
|
|
95
|
+
}
|
|
96
|
+
listenerCount(eventName) {
|
|
97
|
+
throw new Error('Method `listenerCount` not supported.');
|
|
98
|
+
}
|
|
99
|
+
listeners(eventName) {
|
|
100
|
+
throw new Error('Method `listeners` not supported.');
|
|
101
|
+
}
|
|
102
|
+
off(eventName, listener) {
|
|
103
|
+
throw new Error('Method `off` not supported.');
|
|
104
|
+
}
|
|
105
|
+
removeAllListeners(eventName) {
|
|
106
|
+
throw new Error('Method `removeAllListeners` not supported.');
|
|
107
|
+
}
|
|
108
|
+
// eslint-disable-next-line @typescript-eslint/promise-function-async
|
|
109
|
+
waitForTransaction(transactionHash, confirmations, timeout) {
|
|
110
|
+
throw new Error('Method `waitForTransaction` not supported.');
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
exports.default = SafeEthProvider;
|
|
114
|
+
//# sourceMappingURL=safe-api.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"safe-api.js","sourceRoot":"","sources":["../../src/ethereum/safe-api.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;AAEtC,wEAY0C;AAI1C,gDAA6C;AAE7C,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,mBAAmB,CAAC,CAAC;AAE9C,MAAqB,eAAgB,SAAQ,4BAAQ;IACnD,YACU,OAAiB,EACjB,WAAyC;QAEjD,KAAK,EAAE,CAAC;QAHA,YAAO,GAAP,OAAO,CAAU;QACjB,gBAAW,GAAX,WAAW,CAA8B;IAGnD,CAAC;IAED,KAAK,CAAC,UAAU,CACd,aAAuC,EACvC,QAAuC;QAEvC,IAAI,QAAQ;YAAE,MAAM,CAAC,IAA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AAC,SAAoB,EAAE,GAAG,IAAW;QACvC,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;IACD,aAAa,CAAC,SAAqB;QACjC,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC3D,CAAC;IACD,SAAS,CAAC,SAAqB;QAC7B,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,CAAC;IACD,GAAG,CAAC,SAAoB,EAAE,QAAmB;QAC3C,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IACjD,CAAC;IACD,kBAAkB,CAAC,SAAqB;QACtC,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,CAAC;IACD,qEAAqE;IACrE,kBAAkB,CAChB,eAAuB,EACvB,aAAsB,EACtB,OAAgB;QAEhB,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;IAChE,CAAC;CACF;AApID,kCAoIC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n Block,\n BlockTag,\n BlockWithTransactions,\n EventType,\n Filter,\n Listener,\n Log,\n TransactionReceipt,\n TransactionRequest,\n TransactionResponse,\n Provider,\n} from '@ethersproject/abstract-provider';\nimport { BigNumber, BigNumberish } from '@ethersproject/bignumber';\nimport type { Network } from '@ethersproject/networks';\nimport type { Deferrable } from '@ethersproject/properties';\nimport { getLogger } from '@subql/node-core';\n\nconst logger = getLogger('safe.api.ethereum');\n\nexport default class SafeEthProvider extends Provider {\n constructor(\n private baseApi: Provider,\n private blockHeight: BlockTag | Promise<BlockTag>,\n ) {\n super();\n }\n\n async getBalance(\n addressOrName: string | Promise<string>,\n blockTag?: BlockTag | Promise<BlockTag>,\n ): Promise<BigNumber> {\n if (blockTag) logger.warn(`Provided parameter 'blockTag' will not be used`);\n return this.baseApi.getBalance(addressOrName, this.blockHeight);\n }\n\n async getTransactionCount(\n addressOrName: string | Promise<string>,\n blockTag?: BlockTag | Promise<BlockTag>,\n ): Promise<number> {\n if (blockTag) logger.warn(`Provided parameter 'blockTag' will not be used`);\n return this.baseApi.getTransactionCount(addressOrName, this.blockHeight);\n }\n\n async getCode(\n addressOrName: string | Promise<string>,\n blockTag?: BlockTag | Promise<BlockTag>,\n ): Promise<string> {\n if (blockTag) logger.warn(`Provided parameter 'blockTag' will not be used`);\n return this.baseApi.getCode(addressOrName, this.blockHeight);\n }\n\n async getStorageAt(\n addressOrName: string | Promise<string>,\n position: BigNumberish | Promise<BigNumberish>,\n blockTag?: BlockTag | Promise<BlockTag>,\n ): Promise<string> {\n if (blockTag) logger.warn(`Provided parameter 'blockTag' will not be used`);\n return this.baseApi.getStorageAt(addressOrName, position, this.blockHeight);\n }\n\n async call(\n transaction: Deferrable<TransactionRequest>,\n blockTag?: BlockTag | Promise<BlockTag>,\n ): Promise<string> {\n if (blockTag) logger.warn(`Provided parameter 'blockTag' will not be used`);\n\n return this.baseApi.call(transaction, this.blockHeight);\n }\n\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n getBlockWithTransactions(\n blockHashOrBlockTag: BlockTag | Promise<BlockTag>,\n ): Promise<BlockWithTransactions> {\n throw new Error('Method `getBlockWithTransactions` not supported.');\n }\n\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n getBlock(blockHashOrBlockTag: BlockTag | Promise<BlockTag>): Promise<Block> {\n throw new Error('Method `getBlock` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n getTransaction(transactionHash: string): Promise<TransactionResponse> {\n throw new Error('Method `getTransaction` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n getTransactionReceipt(transactionHash: string): Promise<TransactionReceipt> {\n throw new Error('Method `getTransactionReceipt` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n getLogs(filter: Filter): Promise<Log[]> {\n throw new Error('Method `getLogs` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n getBlockNumber(): Promise<number> {\n throw new Error('Method `getBlockNumber` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n getNetwork(): Promise<Network> {\n throw new Error('Method `getNetwork` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n getGasPrice(): Promise<BigNumber> {\n throw new Error('Method `getGasPrice` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n estimateGas(transaction: Deferrable<TransactionRequest>): Promise<BigNumber> {\n throw new Error('Method `estimateGas` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n sendTransaction(\n signedTransaction: string | Promise<string>,\n ): Promise<TransactionResponse> {\n throw new Error('Method `sendTransaction` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n resolveName(name: string | Promise<string>): Promise<string | null> {\n throw new Error('Method `resolveName` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n lookupAddress(address: string | Promise<string>): Promise<string | null> {\n throw new Error('Method `lookupAddress` not supported.');\n }\n on(eventName: EventType, listener: Listener): Provider {\n throw new Error('Method `on` not supported.');\n }\n once(eventName: EventType, listener: Listener): Provider {\n throw new Error('Method `once` not supported.');\n }\n emit(eventName: EventType, ...args: any[]): boolean {\n throw new Error('Method `emit` not supported.');\n }\n listenerCount(eventName?: EventType): number {\n throw new Error('Method `listenerCount` not supported.');\n }\n listeners(eventName?: EventType): Listener[] {\n throw new Error('Method `listeners` not supported.');\n }\n off(eventName: EventType, listener?: Listener): Provider {\n throw new Error('Method `off` not supported.');\n }\n removeAllListeners(eventName?: EventType): Provider {\n throw new Error('Method `removeAllListeners` not supported.');\n }\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n waitForTransaction(\n transactionHash: string,\n confirmations?: number,\n timeout?: number,\n ): Promise<TransactionReceipt> {\n throw new Error('Method `waitForTransaction` not supported.');\n }\n}\n"]}
|
|
@@ -33,11 +33,12 @@ const DICTIONARY_MAX_QUERY_SIZE = 10000;
|
|
|
33
33
|
const CHECK_MEMORY_INTERVAL = 60000;
|
|
34
34
|
const MINIMUM_BATCH_SIZE = 5;
|
|
35
35
|
const INTERVAL_PERCENT = 0.9;
|
|
36
|
+
const QUERY_ADDRESS_LIMIT = 50;
|
|
36
37
|
function eventFilterToQueryEntry(filter, dsOptions) {
|
|
37
38
|
const conditions = [];
|
|
38
39
|
if (Array.isArray(dsOptions)) {
|
|
39
40
|
const addresses = dsOptions.map((option) => option.address).filter(Boolean);
|
|
40
|
-
if (addresses.length) {
|
|
41
|
+
if (addresses.length !== 0 && addresses.length <= QUERY_ADDRESS_LIMIT) {
|
|
41
42
|
conditions.push({
|
|
42
43
|
field: 'address',
|
|
43
44
|
value: addresses,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetch.service.js","sourceRoot":"","sources":["../../src/indexer/fetch.service.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;;;;;;;;;;AAEtC,2CAA2E;AAC3E,yDAAsD;AACtD,+CAA+D;AAC/D,4DAIgC;AAChC,gDAU0B;AAU1B,mCAAsE;AACtE,kEAA+E;AAC/E,+DAA0D;AAC1D,4CAAkE;AAElE,6DAAyD;AACzD,6DAAwD;AACxD,2EAAuE;AAEvE,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,OAAO,CAAC,CAAC;AAClC,IAAI,mBAAmB,GAAG,IAAI,CAAC;AAC/B,MAAM,yBAAyB,GAAG,KAAK,CAAC;AACxC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAE7B,SAAS,uBAAuB,CAC9B,MAAyB,EACzB,SAA0E;IAE1E,MAAM,UAAU,GAAG,EAAE,CAAC;IAEtB,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;QAC5B,MAAM,SAAS,GAAG,SAAS,CAAC,GAA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,iCAAe,UAEjC,sCAAiB;QAClB,qCAAgB;QACR,oDAAwB;QACpC,6BAAa;QACR,4BAAiB;GAnBnC,YAAY,CAigBxB;AAjgBY,oCAAY","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { Interval, SchedulerRegistry } from '@nestjs/schedule';\nimport {\n isCustomDs,\n EthereumHandlerKind,\n SubqlHandlerFilter,\n} from '@subql/common-ethereum';\nimport {\n ApiService,\n Dictionary,\n checkMemoryUsage,\n delay,\n getLogger,\n IndexerEvent,\n NodeConfig,\n transformBypassBlocks,\n cleanedBatchBlocks,\n} from '@subql/node-core';\nimport {\n DictionaryQueryEntry,\n ApiWrapper,\n EthereumLogFilter,\n EthereumTransactionFilter,\n SubqlEthereumProcessorOptions,\n DictionaryQueryCondition,\n} from '@subql/types-ethereum';\nimport { MetaData } from '@subql/utils';\nimport { range, sortBy, uniqBy, without, groupBy, add } from 'lodash';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { calcInterval } from '../ethereum/utils.ethereum';\nimport { eventToTopic, functionToSighash } from '../utils/string';\nimport { IBlockDispatcher } from './blockDispatcher';\nimport { DictionaryService } from './dictionary.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport { UnfinalizedBlocksService } from './unfinalizedBlocks.service';\n\nconst logger = getLogger('fetch');\nlet BLOCK_TIME_VARIANCE = 5000;\nconst DICTIONARY_MAX_QUERY_SIZE = 10000;\nconst CHECK_MEMORY_INTERVAL = 60000;\nconst MINIMUM_BATCH_SIZE = 5;\nconst INTERVAL_PERCENT = 0.9;\n\nfunction eventFilterToQueryEntry(\n filter: EthereumLogFilter,\n dsOptions: SubqlEthereumProcessorOptions | SubqlEthereumProcessorOptions[],\n): DictionaryQueryEntry {\n const conditions = [];\n\n if (Array.isArray(dsOptions)) {\n const addresses = dsOptions.map((option) => option.address).filter(Boolean);\n\n if (addresses.length) {\n conditions.push({\n field: 'address',\n value: addresses,\n matcher: 'inInsensitive',\n });\n }\n } else {\n if (dsOptions.address) {\n conditions.push({\n field: 'address',\n value: dsOptions.address.toLowerCase(),\n });\n }\n }\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 conditions.push({ field, value: eventToTopic(topic) });\n }\n }\n return {\n entity: 'evmLogs',\n conditions,\n };\n}\n\nfunction callFilterToQueryEntry(\n filter: EthereumTransactionFilter,\n): DictionaryQueryEntry {\n const conditions = [];\n if (filter.from) {\n conditions.push({\n field: 'from',\n value: filter.from.toLowerCase(),\n });\n }\n if (filter.to) {\n conditions.push({\n field: 'to',\n value: filter.to.toLowerCase(),\n });\n }\n if (filter.function) {\n conditions.push({\n field: 'func',\n value: functionToSighash(filter.function),\n });\n }\n return {\n entity: 'evmTransactions',\n conditions,\n };\n}\n\n@Injectable()\nexport class FetchService implements OnApplicationShutdown {\n private latestBestHeight: number;\n private latestFinalizedHeight: number;\n private isShutdown = false;\n private batchSizeScale: number;\n private templateDynamicDatasouces: SubqlProjectDs[];\n private dictionaryGenesisMatches = true;\n private evmChainId: string;\n private bypassBlocks: number[] = [];\n\n constructor(\n private apiService: ApiService,\n private nodeConfig: NodeConfig,\n @Inject('ISubqueryProject') private project: SubqueryProject,\n @Inject('IBlockDispatcher') private blockDispatcher: IBlockDispatcher,\n private dictionaryService: DictionaryService,\n private dynamicDsService: DynamicDsService,\n private unfinalizedBlocksService: UnfinalizedBlocksService,\n private eventEmitter: EventEmitter2,\n private schedulerRegistry: SchedulerRegistry,\n ) {\n this.batchSizeScale = 1;\n }\n\n onApplicationShutdown(): void {\n this.isShutdown = true;\n }\n\n get api(): ApiWrapper {\n return this.apiService.api;\n }\n\n async syncDynamicDatascourcesFromMeta(): Promise<void> {\n this.templateDynamicDatasouces =\n await this.dynamicDsService.getDynamicDatasources();\n }\n\n buildDictionaryQueryEntries(startBlock: number): DictionaryQueryEntry[] {\n const queryEntries: DictionaryQueryEntry[] = [];\n\n type GroupedSubqlProjectDs = SubqlProjectDs & {\n groupedOptions?: SubqlEthereumProcessorOptions[];\n };\n\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[] = this.project.dataSources\n .concat(groupdDynamicDs)\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 let filterList: SubqlHandlerFilter[];\n filterList = [handler.filter];\n filterList = filterList.filter((f) => f);\n if (!filterList.length) return [];\n switch (handler.kind) {\n case EthereumHandlerKind.Block:\n return [];\n case EthereumHandlerKind.Call: {\n for (const filter of filterList as EthereumTransactionFilter[]) {\n if (\n filter.from !== undefined ||\n filter.to !== undefined ||\n filter.function\n ) {\n queryEntries.push(callFilterToQueryEntry(filter));\n } else {\n return [];\n }\n }\n break;\n }\n case EthereumHandlerKind.Event: {\n for (const filter of filterList 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 }\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 updateDictionary(): void {\n this.dictionaryService.buildDictionaryEntryMap<SubqlProjectDs>(\n this.project.dataSources.concat(this.templateDynamicDatasouces),\n this.buildDictionaryQueryEntries.bind(this),\n );\n }\n\n private get useDictionary(): boolean {\n return (\n !!this.project.network.dictionary &&\n this.dictionaryGenesisMatches &&\n !!this.dictionaryService.getDictionaryQueryEntries(\n this.blockDispatcher.latestBufferedHeight ??\n Math.min(...this.project.dataSources.map((ds) => ds.startBlock)),\n ).length\n );\n }\n\n async init(startHeight: number): Promise<void> {\n if (this.project.network?.bypassBlocks !== undefined) {\n this.bypassBlocks = transformBypassBlocks(\n this.project.network.bypassBlocks,\n ).filter((blk) => blk >= startHeight);\n }\n if (this.api) {\n const CHAIN_INTERVAL = calcInterval(this.api) * INTERVAL_PERCENT;\n\n BLOCK_TIME_VARIANCE = Math.min(BLOCK_TIME_VARIANCE, CHAIN_INTERVAL);\n\n this.schedulerRegistry.addInterval(\n 'getLatestBlockHead',\n setInterval(() => void this.getBestBlockHead(), BLOCK_TIME_VARIANCE),\n );\n }\n await this.syncDynamicDatascourcesFromMeta();\n\n this.updateDictionary();\n this.eventEmitter.emit(IndexerEvent.UsingDictionary, {\n value: Number(this.useDictionary),\n });\n\n if (this.project.network.dictionary) {\n this.evmChainId = await this.dictionaryService.getEvmChainId();\n }\n\n await this.getFinalizedBlockHead();\n await this.getBestBlockHead();\n\n // Call metadata here, other network should align with this\n // For substrate, we might use the specVersion metadata in future if we have same error handling as in node-core\n const metadata = await this.dictionaryService.getMetadata();\n\n const validChecker = this.dictionaryValidation(metadata);\n\n if (validChecker) {\n this.dictionaryService.setDictionaryStartHeight(\n metadata._metadata.startHeight,\n );\n }\n\n await this.blockDispatcher.init(this.resetForNewDs.bind(this));\n void this.startLoop(startHeight);\n }\n\n getUseDictionary(): boolean {\n return this.useDictionary;\n }\n\n getLatestFinalizedHeight(): number {\n return this.latestFinalizedHeight;\n }\n\n @Interval(CHECK_MEMORY_INTERVAL)\n checkBatchScale(): void {\n if (this.nodeConfig['scale-batch-size']) {\n const scale = checkMemoryUsage(this.batchSizeScale, this.nodeConfig);\n\n if (this.batchSizeScale !== scale) {\n this.batchSizeScale = scale;\n }\n }\n }\n\n @Interval(BLOCK_TIME_VARIANCE * 1000)\n async getFinalizedBlockHead(): Promise<void> {\n if (!this.api) {\n logger.debug(`Skip fetch finalized block until API is ready`);\n return;\n }\n try {\n const currentFinalizedHeight = await this.api.getFinalizedBlockHeight();\n logger.debug(`finalized:${currentFinalizedHeight.toString()}`);\n const finalizedHeader = await this.api.getBlockByHeightOrHash(\n currentFinalizedHeight,\n );\n if (this.latestFinalizedHeight !== currentFinalizedHeight) {\n this.latestFinalizedHeight = currentFinalizedHeight;\n this.unfinalizedBlocksService.registerFinalizedBlock(finalizedHeader);\n if (!this.nodeConfig.unfinalizedBlocks) {\n if (!this.nodeConfig.unfinalizedBlocks) {\n this.eventEmitter.emit(IndexerEvent.BlockTarget, {\n height: this.latestFinalizedHeight,\n });\n }\n }\n }\n } catch (e) {\n logger.warn(e, `Having a problem when get finalized block`);\n }\n }\n\n @Interval(BLOCK_TIME_VARIANCE * 1000)\n async getBestBlockHead(): Promise<void> {\n if (!this.api) {\n logger.debug(`Skip fetch best block until API is ready`);\n return;\n }\n try {\n const currentBestHeight = await this.api.getBestBlockHeight();\n logger.debug(`best:${currentBestHeight.toString()}`);\n if (this.latestBestHeight !== currentBestHeight) {\n this.latestBestHeight = currentBestHeight;\n this.eventEmitter.emit(IndexerEvent.BlockBest, {\n height: this.latestBestHeight,\n });\n\n if (this.nodeConfig.unfinalizedBlocks) {\n this.eventEmitter.emit(IndexerEvent.BlockTarget, {\n height: this.latestBestHeight,\n });\n }\n }\n } catch (e) {\n logger.warn(e, `Having a problem when get best block`);\n }\n }\n private async startLoop(initBlockHeight: number): Promise<void> {\n await this.fillNextBlockBuffer(initBlockHeight);\n }\n\n 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 getModuloBlocks(startHeight: number, endHeight: number): number[] {\n const modulos = this.getModulos();\n const moduloBlocks: number[] = [];\n for (let i = startHeight; i < endHeight; i++) {\n if (modulos.find((m) => i % m === 0)) {\n moduloBlocks.push(i);\n }\n }\n return moduloBlocks;\n }\n\n getEnqueuedModuloBlocks(startBlockHeight: number): number[] {\n return this.getModuloBlocks(\n startBlockHeight,\n this.nodeConfig.batchSize * Math.max(...this.getModulos()) +\n startBlockHeight,\n ).slice(0, this.nodeConfig.batchSize);\n }\n\n async fillNextBlockBuffer(initBlockHeight: number): Promise<void> {\n let startBlockHeight: number;\n let scaledBatchSize: number;\n const handlers = [].concat(\n ...this.project.dataSources.map((ds) => ds.mapping.handlers),\n );\n\n const getStartBlockHeight = (): number => {\n return this.blockDispatcher.latestBufferedHeight\n ? this.blockDispatcher.latestBufferedHeight + 1\n : initBlockHeight;\n };\n\n if (this.dictionaryService.startHeight > getStartBlockHeight()) {\n logger.warn(\n `Dictionary start height ${\n this.dictionaryService.startHeight\n } is beyond indexing height ${getStartBlockHeight()}, skipping dictionary for now`,\n );\n }\n\n while (!this.isShutdown) {\n startBlockHeight = getStartBlockHeight();\n\n scaledBatchSize = Math.max(\n Math.round(this.batchSizeScale * this.nodeConfig.batchSize),\n Math.min(MINIMUM_BATCH_SIZE, this.nodeConfig.batchSize * 3),\n );\n const latestHeight = this.nodeConfig.unfinalizedBlocks\n ? this.latestBestHeight\n : this.latestFinalizedHeight;\n\n if (\n this.blockDispatcher.freeSize < scaledBatchSize ||\n startBlockHeight > latestHeight\n ) {\n await delay(1);\n continue;\n }\n\n if (\n this.useDictionary &&\n startBlockHeight >= this.dictionaryService.startHeight\n ) {\n const queryEndBlock = startBlockHeight + DICTIONARY_MAX_QUERY_SIZE;\n const moduloBlocks = this.getModuloBlocks(\n startBlockHeight,\n queryEndBlock,\n );\n\n try {\n const dictionary =\n await this.dictionaryService.scopedDictionaryEntries(\n startBlockHeight,\n queryEndBlock,\n scaledBatchSize,\n );\n\n if (startBlockHeight !== getStartBlockHeight()) {\n logger.debug(\n `Queue was reset for new DS, discarding dictionary query result`,\n );\n continue;\n }\n\n if (\n dictionary &&\n this.dictionaryValidation(dictionary, startBlockHeight)\n ) {\n let { batchBlocks } = dictionary;\n\n batchBlocks = batchBlocks\n .concat(moduloBlocks)\n .sort((a, b) => a - b);\n if (batchBlocks.length === 0) {\n // There we're no blocks in this query range, we can set a new height we're up to\n this.blockDispatcher.enqueueBlocks(\n [],\n Math.min(\n queryEndBlock - 1,\n dictionary._metadata.lastProcessedHeight,\n ),\n );\n } else {\n const maxBlockSize = Math.min(\n batchBlocks.length,\n this.blockDispatcher.freeSize,\n );\n const enqueuingBlocks = batchBlocks.slice(0, maxBlockSize);\n const cleanedBatchBlocks =\n this.filteredBlockBatch(enqueuingBlocks);\n\n this.blockDispatcher.enqueueBlocks(\n cleanedBatchBlocks,\n this.getLatestBufferHeight(cleanedBatchBlocks, enqueuingBlocks),\n );\n }\n continue; // skip nextBlockRange() way\n }\n // else use this.nextBlockRange()\n } catch (e) {\n logger.debug(`Fetch dictionary stopped: ${e.message}`);\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n }\n }\n\n const endHeight = this.nextEndBlockHeight(\n startBlockHeight,\n scaledBatchSize,\n );\n\n if (handlers.length && this.getModulos().length === handlers.length) {\n const enqueuingBlocks = this.getEnqueuedModuloBlocks(startBlockHeight);\n const cleanedBatchBlocks = this.filteredBlockBatch(enqueuingBlocks);\n this.blockDispatcher.enqueueBlocks(\n cleanedBatchBlocks,\n this.getLatestBufferHeight(cleanedBatchBlocks, enqueuingBlocks),\n );\n } else {\n const enqueuingBlocks = range(startBlockHeight, endHeight + 1);\n const cleanedBatchBlocks = this.filteredBlockBatch(enqueuingBlocks);\n this.blockDispatcher.enqueueBlocks(\n cleanedBatchBlocks,\n this.getLatestBufferHeight(cleanedBatchBlocks, enqueuingBlocks),\n );\n }\n }\n }\n\n private getLatestBufferHeight(\n cleanedBatchBlocks: number[],\n rawBatchBlocks: number[],\n ): number {\n return Math.max(...cleanedBatchBlocks, ...rawBatchBlocks);\n }\n private filteredBlockBatch(currentBatchBlocks: number[]): number[] {\n if (!this.bypassBlocks.length || !currentBatchBlocks) {\n return currentBatchBlocks;\n }\n\n const cleanedBatch = cleanedBatchBlocks(\n this.bypassBlocks,\n currentBatchBlocks,\n );\n\n const pollutedBlocks = this.bypassBlocks.filter(\n (b) => b < Math.max(...currentBatchBlocks),\n );\n if (pollutedBlocks.length) {\n logger.info(`Bypassing blocks: ${pollutedBlocks}`);\n }\n this.bypassBlocks = without(this.bypassBlocks, ...pollutedBlocks);\n return cleanedBatch;\n }\n\n private nextEndBlockHeight(\n startBlockHeight: number,\n scaledBatchSize: number,\n ): number {\n let endBlockHeight = startBlockHeight + scaledBatchSize - 1;\n\n if (endBlockHeight > this.latestFinalizedHeight) {\n if (this.nodeConfig.unfinalizedBlocks) {\n if (endBlockHeight >= this.latestBestHeight) {\n endBlockHeight = this.latestBestHeight;\n }\n } else {\n endBlockHeight = this.latestFinalizedHeight;\n }\n }\n return endBlockHeight;\n }\n\n private dictionaryValidation(\n dictionary: { _metadata: MetaData },\n startBlockHeight?: number,\n ): boolean {\n if (dictionary !== undefined) {\n const { _metadata: metaData } = dictionary;\n\n if (\n metaData.genesisHash !== this.api.getGenesisHash() &&\n this.evmChainId !== this.api.getChainId().toString()\n ) {\n logger.error(\n 'The dictionary that you have specified does not match the chain you are indexing, it will be ignored. Please update your project manifest to reference the correct dictionary',\n );\n this.dictionaryGenesisMatches = false;\n this.eventEmitter.emit(IndexerEvent.UsingDictionary, {\n value: Number(this.useDictionary),\n });\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n return false;\n }\n\n if (startBlockHeight !== undefined) {\n if (metaData.lastProcessedHeight < startBlockHeight) {\n logger.warn(\n `Dictionary indexed block is behind current indexing block height`,\n );\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n return false;\n }\n }\n return true;\n }\n return false;\n }\n\n async resetForNewDs(blockHeight: number): Promise<void> {\n await this.syncDynamicDatascourcesFromMeta();\n this.dynamicDsService.deleteTempDsRecords(blockHeight);\n this.updateDictionary();\n this.blockDispatcher.flushQueue(blockHeight);\n }\n\n async resetForIncorrectBestBlock(blockHeight: number): Promise<void> {\n await this.syncDynamicDatascourcesFromMeta();\n this.updateDictionary();\n this.blockDispatcher.flushQueue(blockHeight);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fetch.service.js","sourceRoot":"","sources":["../../src/indexer/fetch.service.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;;;;;;;;;;AAEtC,2CAA2E;AAC3E,yDAAsD;AACtD,+CAA+D;AAC/D,4DAIgC;AAChC,gDAU0B;AAU1B,mCAAsE;AACtE,kEAA+E;AAC/E,+DAA0D;AAC1D,4CAAkE;AAElE,6DAAyD;AACzD,6DAAwD;AACxD,2EAAuE;AAEvE,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,OAAO,CAAC,CAAC;AAClC,IAAI,mBAAmB,GAAG,IAAI,CAAC;AAC/B,MAAM,yBAAyB,GAAG,KAAK,CAAC;AACxC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AACpC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,gBAAgB,GAAG,GAAG,CAAC;AAC7B,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAE/B,SAAS,uBAAuB,CAC9B,MAAyB,EACzB,SAA0E;IAE1E,MAAM,UAAU,GAAG,EAAE,CAAC;IAEtB,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;QA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;QACpC,6BAAa;QACR,4BAAiB;GAnBnC,YAAY,CAigBxB;AAjgBY,oCAAY","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { Interval, SchedulerRegistry } from '@nestjs/schedule';\nimport {\n isCustomDs,\n EthereumHandlerKind,\n SubqlHandlerFilter,\n} from '@subql/common-ethereum';\nimport {\n ApiService,\n Dictionary,\n checkMemoryUsage,\n delay,\n getLogger,\n IndexerEvent,\n NodeConfig,\n transformBypassBlocks,\n cleanedBatchBlocks,\n} from '@subql/node-core';\nimport {\n DictionaryQueryEntry,\n ApiWrapper,\n EthereumLogFilter,\n EthereumTransactionFilter,\n SubqlEthereumProcessorOptions,\n DictionaryQueryCondition,\n} from '@subql/types-ethereum';\nimport { MetaData } from '@subql/utils';\nimport { range, sortBy, uniqBy, without, groupBy, add } from 'lodash';\nimport { SubqlProjectDs, SubqueryProject } from '../configure/SubqueryProject';\nimport { calcInterval } from '../ethereum/utils.ethereum';\nimport { eventToTopic, functionToSighash } from '../utils/string';\nimport { IBlockDispatcher } from './blockDispatcher';\nimport { DictionaryService } from './dictionary.service';\nimport { DynamicDsService } from './dynamic-ds.service';\nimport { UnfinalizedBlocksService } from './unfinalizedBlocks.service';\n\nconst logger = getLogger('fetch');\nlet BLOCK_TIME_VARIANCE = 5000;\nconst DICTIONARY_MAX_QUERY_SIZE = 10000;\nconst CHECK_MEMORY_INTERVAL = 60000;\nconst MINIMUM_BATCH_SIZE = 5;\nconst INTERVAL_PERCENT = 0.9;\nconst QUERY_ADDRESS_LIMIT = 50;\n\nfunction eventFilterToQueryEntry(\n filter: EthereumLogFilter,\n dsOptions: SubqlEthereumProcessorOptions | SubqlEthereumProcessorOptions[],\n): DictionaryQueryEntry {\n const conditions = [];\n\n if (Array.isArray(dsOptions)) {\n const addresses = dsOptions.map((option) => option.address).filter(Boolean);\n\n if (addresses.length !== 0 && addresses.length <= QUERY_ADDRESS_LIMIT) {\n conditions.push({\n field: 'address',\n value: addresses,\n matcher: 'inInsensitive',\n });\n }\n } else {\n if (dsOptions.address) {\n conditions.push({\n field: 'address',\n value: dsOptions.address.toLowerCase(),\n });\n }\n }\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 conditions.push({ field, value: eventToTopic(topic) });\n }\n }\n return {\n entity: 'evmLogs',\n conditions,\n };\n}\n\nfunction callFilterToQueryEntry(\n filter: EthereumTransactionFilter,\n): DictionaryQueryEntry {\n const conditions = [];\n if (filter.from) {\n conditions.push({\n field: 'from',\n value: filter.from.toLowerCase(),\n });\n }\n if (filter.to) {\n conditions.push({\n field: 'to',\n value: filter.to.toLowerCase(),\n });\n }\n if (filter.function) {\n conditions.push({\n field: 'func',\n value: functionToSighash(filter.function),\n });\n }\n return {\n entity: 'evmTransactions',\n conditions,\n };\n}\n\n@Injectable()\nexport class FetchService implements OnApplicationShutdown {\n private latestBestHeight: number;\n private latestFinalizedHeight: number;\n private isShutdown = false;\n private batchSizeScale: number;\n private templateDynamicDatasouces: SubqlProjectDs[];\n private dictionaryGenesisMatches = true;\n private evmChainId: string;\n private bypassBlocks: number[] = [];\n\n constructor(\n private apiService: ApiService,\n private nodeConfig: NodeConfig,\n @Inject('ISubqueryProject') private project: SubqueryProject,\n @Inject('IBlockDispatcher') private blockDispatcher: IBlockDispatcher,\n private dictionaryService: DictionaryService,\n private dynamicDsService: DynamicDsService,\n private unfinalizedBlocksService: UnfinalizedBlocksService,\n private eventEmitter: EventEmitter2,\n private schedulerRegistry: SchedulerRegistry,\n ) {\n this.batchSizeScale = 1;\n }\n\n onApplicationShutdown(): void {\n this.isShutdown = true;\n }\n\n get api(): ApiWrapper {\n return this.apiService.api;\n }\n\n async syncDynamicDatascourcesFromMeta(): Promise<void> {\n this.templateDynamicDatasouces =\n await this.dynamicDsService.getDynamicDatasources();\n }\n\n buildDictionaryQueryEntries(startBlock: number): DictionaryQueryEntry[] {\n const queryEntries: DictionaryQueryEntry[] = [];\n\n type GroupedSubqlProjectDs = SubqlProjectDs & {\n groupedOptions?: SubqlEthereumProcessorOptions[];\n };\n\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[] = this.project.dataSources\n .concat(groupdDynamicDs)\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 let filterList: SubqlHandlerFilter[];\n filterList = [handler.filter];\n filterList = filterList.filter((f) => f);\n if (!filterList.length) return [];\n switch (handler.kind) {\n case EthereumHandlerKind.Block:\n return [];\n case EthereumHandlerKind.Call: {\n for (const filter of filterList as EthereumTransactionFilter[]) {\n if (\n filter.from !== undefined ||\n filter.to !== undefined ||\n filter.function\n ) {\n queryEntries.push(callFilterToQueryEntry(filter));\n } else {\n return [];\n }\n }\n break;\n }\n case EthereumHandlerKind.Event: {\n for (const filter of filterList 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 }\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 updateDictionary(): void {\n this.dictionaryService.buildDictionaryEntryMap<SubqlProjectDs>(\n this.project.dataSources.concat(this.templateDynamicDatasouces),\n this.buildDictionaryQueryEntries.bind(this),\n );\n }\n\n private get useDictionary(): boolean {\n return (\n !!this.project.network.dictionary &&\n this.dictionaryGenesisMatches &&\n !!this.dictionaryService.getDictionaryQueryEntries(\n this.blockDispatcher.latestBufferedHeight ??\n Math.min(...this.project.dataSources.map((ds) => ds.startBlock)),\n ).length\n );\n }\n\n async init(startHeight: number): Promise<void> {\n if (this.project.network?.bypassBlocks !== undefined) {\n this.bypassBlocks = transformBypassBlocks(\n this.project.network.bypassBlocks,\n ).filter((blk) => blk >= startHeight);\n }\n if (this.api) {\n const CHAIN_INTERVAL = calcInterval(this.api) * INTERVAL_PERCENT;\n\n BLOCK_TIME_VARIANCE = Math.min(BLOCK_TIME_VARIANCE, CHAIN_INTERVAL);\n\n this.schedulerRegistry.addInterval(\n 'getLatestBlockHead',\n setInterval(() => void this.getBestBlockHead(), BLOCK_TIME_VARIANCE),\n );\n }\n await this.syncDynamicDatascourcesFromMeta();\n\n this.updateDictionary();\n this.eventEmitter.emit(IndexerEvent.UsingDictionary, {\n value: Number(this.useDictionary),\n });\n\n if (this.project.network.dictionary) {\n this.evmChainId = await this.dictionaryService.getEvmChainId();\n }\n\n await this.getFinalizedBlockHead();\n await this.getBestBlockHead();\n\n // Call metadata here, other network should align with this\n // For substrate, we might use the specVersion metadata in future if we have same error handling as in node-core\n const metadata = await this.dictionaryService.getMetadata();\n\n const validChecker = this.dictionaryValidation(metadata);\n\n if (validChecker) {\n this.dictionaryService.setDictionaryStartHeight(\n metadata._metadata.startHeight,\n );\n }\n\n await this.blockDispatcher.init(this.resetForNewDs.bind(this));\n void this.startLoop(startHeight);\n }\n\n getUseDictionary(): boolean {\n return this.useDictionary;\n }\n\n getLatestFinalizedHeight(): number {\n return this.latestFinalizedHeight;\n }\n\n @Interval(CHECK_MEMORY_INTERVAL)\n checkBatchScale(): void {\n if (this.nodeConfig['scale-batch-size']) {\n const scale = checkMemoryUsage(this.batchSizeScale, this.nodeConfig);\n\n if (this.batchSizeScale !== scale) {\n this.batchSizeScale = scale;\n }\n }\n }\n\n @Interval(BLOCK_TIME_VARIANCE * 1000)\n async getFinalizedBlockHead(): Promise<void> {\n if (!this.api) {\n logger.debug(`Skip fetch finalized block until API is ready`);\n return;\n }\n try {\n const currentFinalizedHeight = await this.api.getFinalizedBlockHeight();\n logger.debug(`finalized:${currentFinalizedHeight.toString()}`);\n const finalizedHeader = await this.api.getBlockByHeightOrHash(\n currentFinalizedHeight,\n );\n if (this.latestFinalizedHeight !== currentFinalizedHeight) {\n this.latestFinalizedHeight = currentFinalizedHeight;\n this.unfinalizedBlocksService.registerFinalizedBlock(finalizedHeader);\n if (!this.nodeConfig.unfinalizedBlocks) {\n if (!this.nodeConfig.unfinalizedBlocks) {\n this.eventEmitter.emit(IndexerEvent.BlockTarget, {\n height: this.latestFinalizedHeight,\n });\n }\n }\n }\n } catch (e) {\n logger.warn(e, `Having a problem when get finalized block`);\n }\n }\n\n @Interval(BLOCK_TIME_VARIANCE * 1000)\n async getBestBlockHead(): Promise<void> {\n if (!this.api) {\n logger.debug(`Skip fetch best block until API is ready`);\n return;\n }\n try {\n const currentBestHeight = await this.api.getBestBlockHeight();\n logger.debug(`best:${currentBestHeight.toString()}`);\n if (this.latestBestHeight !== currentBestHeight) {\n this.latestBestHeight = currentBestHeight;\n this.eventEmitter.emit(IndexerEvent.BlockBest, {\n height: this.latestBestHeight,\n });\n\n if (this.nodeConfig.unfinalizedBlocks) {\n this.eventEmitter.emit(IndexerEvent.BlockTarget, {\n height: this.latestBestHeight,\n });\n }\n }\n } catch (e) {\n logger.warn(e, `Having a problem when get best block`);\n }\n }\n private async startLoop(initBlockHeight: number): Promise<void> {\n await this.fillNextBlockBuffer(initBlockHeight);\n }\n\n 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 getModuloBlocks(startHeight: number, endHeight: number): number[] {\n const modulos = this.getModulos();\n const moduloBlocks: number[] = [];\n for (let i = startHeight; i < endHeight; i++) {\n if (modulos.find((m) => i % m === 0)) {\n moduloBlocks.push(i);\n }\n }\n return moduloBlocks;\n }\n\n getEnqueuedModuloBlocks(startBlockHeight: number): number[] {\n return this.getModuloBlocks(\n startBlockHeight,\n this.nodeConfig.batchSize * Math.max(...this.getModulos()) +\n startBlockHeight,\n ).slice(0, this.nodeConfig.batchSize);\n }\n\n async fillNextBlockBuffer(initBlockHeight: number): Promise<void> {\n let startBlockHeight: number;\n let scaledBatchSize: number;\n const handlers = [].concat(\n ...this.project.dataSources.map((ds) => ds.mapping.handlers),\n );\n\n const getStartBlockHeight = (): number => {\n return this.blockDispatcher.latestBufferedHeight\n ? this.blockDispatcher.latestBufferedHeight + 1\n : initBlockHeight;\n };\n\n if (this.dictionaryService.startHeight > getStartBlockHeight()) {\n logger.warn(\n `Dictionary start height ${\n this.dictionaryService.startHeight\n } is beyond indexing height ${getStartBlockHeight()}, skipping dictionary for now`,\n );\n }\n\n while (!this.isShutdown) {\n startBlockHeight = getStartBlockHeight();\n\n scaledBatchSize = Math.max(\n Math.round(this.batchSizeScale * this.nodeConfig.batchSize),\n Math.min(MINIMUM_BATCH_SIZE, this.nodeConfig.batchSize * 3),\n );\n const latestHeight = this.nodeConfig.unfinalizedBlocks\n ? this.latestBestHeight\n : this.latestFinalizedHeight;\n\n if (\n this.blockDispatcher.freeSize < scaledBatchSize ||\n startBlockHeight > latestHeight\n ) {\n await delay(1);\n continue;\n }\n\n if (\n this.useDictionary &&\n startBlockHeight >= this.dictionaryService.startHeight\n ) {\n const queryEndBlock = startBlockHeight + DICTIONARY_MAX_QUERY_SIZE;\n const moduloBlocks = this.getModuloBlocks(\n startBlockHeight,\n queryEndBlock,\n );\n\n try {\n const dictionary =\n await this.dictionaryService.scopedDictionaryEntries(\n startBlockHeight,\n queryEndBlock,\n scaledBatchSize,\n );\n\n if (startBlockHeight !== getStartBlockHeight()) {\n logger.debug(\n `Queue was reset for new DS, discarding dictionary query result`,\n );\n continue;\n }\n\n if (\n dictionary &&\n this.dictionaryValidation(dictionary, startBlockHeight)\n ) {\n let { batchBlocks } = dictionary;\n\n batchBlocks = batchBlocks\n .concat(moduloBlocks)\n .sort((a, b) => a - b);\n if (batchBlocks.length === 0) {\n // There we're no blocks in this query range, we can set a new height we're up to\n this.blockDispatcher.enqueueBlocks(\n [],\n Math.min(\n queryEndBlock - 1,\n dictionary._metadata.lastProcessedHeight,\n ),\n );\n } else {\n const maxBlockSize = Math.min(\n batchBlocks.length,\n this.blockDispatcher.freeSize,\n );\n const enqueuingBlocks = batchBlocks.slice(0, maxBlockSize);\n const cleanedBatchBlocks =\n this.filteredBlockBatch(enqueuingBlocks);\n\n this.blockDispatcher.enqueueBlocks(\n cleanedBatchBlocks,\n this.getLatestBufferHeight(cleanedBatchBlocks, enqueuingBlocks),\n );\n }\n continue; // skip nextBlockRange() way\n }\n // else use this.nextBlockRange()\n } catch (e) {\n logger.debug(`Fetch dictionary stopped: ${e.message}`);\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n }\n }\n\n const endHeight = this.nextEndBlockHeight(\n startBlockHeight,\n scaledBatchSize,\n );\n\n if (handlers.length && this.getModulos().length === handlers.length) {\n const enqueuingBlocks = this.getEnqueuedModuloBlocks(startBlockHeight);\n const cleanedBatchBlocks = this.filteredBlockBatch(enqueuingBlocks);\n this.blockDispatcher.enqueueBlocks(\n cleanedBatchBlocks,\n this.getLatestBufferHeight(cleanedBatchBlocks, enqueuingBlocks),\n );\n } else {\n const enqueuingBlocks = range(startBlockHeight, endHeight + 1);\n const cleanedBatchBlocks = this.filteredBlockBatch(enqueuingBlocks);\n this.blockDispatcher.enqueueBlocks(\n cleanedBatchBlocks,\n this.getLatestBufferHeight(cleanedBatchBlocks, enqueuingBlocks),\n );\n }\n }\n }\n\n private getLatestBufferHeight(\n cleanedBatchBlocks: number[],\n rawBatchBlocks: number[],\n ): number {\n return Math.max(...cleanedBatchBlocks, ...rawBatchBlocks);\n }\n private filteredBlockBatch(currentBatchBlocks: number[]): number[] {\n if (!this.bypassBlocks.length || !currentBatchBlocks) {\n return currentBatchBlocks;\n }\n\n const cleanedBatch = cleanedBatchBlocks(\n this.bypassBlocks,\n currentBatchBlocks,\n );\n\n const pollutedBlocks = this.bypassBlocks.filter(\n (b) => b < Math.max(...currentBatchBlocks),\n );\n if (pollutedBlocks.length) {\n logger.info(`Bypassing blocks: ${pollutedBlocks}`);\n }\n this.bypassBlocks = without(this.bypassBlocks, ...pollutedBlocks);\n return cleanedBatch;\n }\n\n private nextEndBlockHeight(\n startBlockHeight: number,\n scaledBatchSize: number,\n ): number {\n let endBlockHeight = startBlockHeight + scaledBatchSize - 1;\n\n if (endBlockHeight > this.latestFinalizedHeight) {\n if (this.nodeConfig.unfinalizedBlocks) {\n if (endBlockHeight >= this.latestBestHeight) {\n endBlockHeight = this.latestBestHeight;\n }\n } else {\n endBlockHeight = this.latestFinalizedHeight;\n }\n }\n return endBlockHeight;\n }\n\n private dictionaryValidation(\n dictionary: { _metadata: MetaData },\n startBlockHeight?: number,\n ): boolean {\n if (dictionary !== undefined) {\n const { _metadata: metaData } = dictionary;\n\n if (\n metaData.genesisHash !== this.api.getGenesisHash() &&\n this.evmChainId !== this.api.getChainId().toString()\n ) {\n logger.error(\n 'The dictionary that you have specified does not match the chain you are indexing, it will be ignored. Please update your project manifest to reference the correct dictionary',\n );\n this.dictionaryGenesisMatches = false;\n this.eventEmitter.emit(IndexerEvent.UsingDictionary, {\n value: Number(this.useDictionary),\n });\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n return false;\n }\n\n if (startBlockHeight !== undefined) {\n if (metaData.lastProcessedHeight < startBlockHeight) {\n logger.warn(\n `Dictionary indexed block is behind current indexing block height`,\n );\n this.eventEmitter.emit(IndexerEvent.SkipDictionary);\n return false;\n }\n }\n return true;\n }\n return false;\n }\n\n async resetForNewDs(blockHeight: number): Promise<void> {\n await this.syncDynamicDatascourcesFromMeta();\n this.dynamicDsService.deleteTempDsRecords(blockHeight);\n this.updateDictionary();\n this.blockDispatcher.flushQueue(blockHeight);\n }\n\n async resetForIncorrectBestBlock(blockHeight: number): Promise<void> {\n await this.syncDynamicDatascourcesFromMeta();\n this.updateDictionary();\n this.blockDispatcher.flushQueue(blockHeight);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@subql/node-ethereum",
|
|
3
|
-
"version": "0.4.1-
|
|
3
|
+
"version": "0.4.1-6",
|
|
4
4
|
"description": "",
|
|
5
5
|
"author": "Ian He",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -25,9 +25,9 @@
|
|
|
25
25
|
"@nestjs/platform-express": "^8.2.6",
|
|
26
26
|
"@nestjs/schedule": "^1.0.2",
|
|
27
27
|
"@subql/common": "1.5.0",
|
|
28
|
-
"@subql/common-ethereum": "0.2.2-
|
|
28
|
+
"@subql/common-ethereum": "0.2.2-4",
|
|
29
29
|
"@subql/node-core": "1.8.1-2",
|
|
30
|
-
"@subql/types-ethereum": "0.2.2-
|
|
30
|
+
"@subql/types-ethereum": "0.2.2-5",
|
|
31
31
|
"@subql/utils": "1.3.2-1",
|
|
32
32
|
"@subql/x-merkle-mountain-range": "2.0.0-0.1.2",
|
|
33
33
|
"@willsoto/nestjs-prometheus": "^4.4.0",
|
|
@@ -74,5 +74,5 @@
|
|
|
74
74
|
"/dist",
|
|
75
75
|
"/bin"
|
|
76
76
|
],
|
|
77
|
-
"stableVersion": "0.4.1-
|
|
77
|
+
"stableVersion": "0.4.1-5"
|
|
78
78
|
}
|