@subql/node-ethereum 1.0.2-0 → 1.0.2-2

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.
@@ -32,4 +32,5 @@ export declare class EthereumApi implements ApiWrapper<EthereumBlockWrapper> {
32
32
  parseTransaction<T extends EthereumResult = EthereumResult>(transaction: EthereumTransaction, ds: RuntimeDataSourceV0_2_0): Promise<EthereumTransaction<T> | EthereumTransaction>;
33
33
  connect(): Promise<void>;
34
34
  disconnect(): Promise<void>;
35
+ handleError(e: Error): Error;
35
36
  }
@@ -155,20 +155,25 @@ class EthereumApi {
155
155
  return (0, project_1.retryOnFailEth)(this.client.getTransactionReceipt.bind(this.client, transactionHash));
156
156
  }
157
157
  async fetchBlock(blockNumber, includeTx) {
158
- const [block, logs] = await Promise.all([
159
- this.getBlockPromise(blockNumber, includeTx),
160
- this.client.getLogs({
161
- fromBlock: (0, utils_1.hexValue)(blockNumber),
162
- toBlock: (0, utils_1.hexValue)(blockNumber),
163
- }),
164
- ]);
165
- const ret = new block_ethereum_1.EthereumBlockWrapped(block, includeTx
166
- ? block.transactions.map((tx) => (Object.assign(Object.assign({}, (0, utils_ethereum_1.formatTransaction)(tx)), {
167
- // TODO memoise
168
- receipt: () => this.getTransactionReceipt(tx.hash).then((r) => (0, utils_ethereum_1.formatReceipt)(r, block)) })))
169
- : [], logs.map((l) => (0, utils_ethereum_1.formatLog)(l, block)));
170
- this.eventEmitter.emit('fetchBlock');
171
- return ret;
158
+ try {
159
+ const [block, logs] = await Promise.all([
160
+ this.getBlockPromise(blockNumber, includeTx),
161
+ this.client.getLogs({
162
+ fromBlock: (0, utils_1.hexValue)(blockNumber),
163
+ toBlock: (0, utils_1.hexValue)(blockNumber),
164
+ }),
165
+ ]);
166
+ const ret = new block_ethereum_1.EthereumBlockWrapped(block, includeTx
167
+ ? block.transactions.map((tx) => (Object.assign(Object.assign({}, (0, utils_ethereum_1.formatTransaction)(tx)), {
168
+ // TODO memoise
169
+ receipt: () => this.getTransactionReceipt(tx.hash).then((r) => (0, utils_ethereum_1.formatReceipt)(r, block)) })))
170
+ : [], logs.map((l) => (0, utils_ethereum_1.formatLog)(l, block)));
171
+ this.eventEmitter.emit('fetchBlock');
172
+ return ret;
173
+ }
174
+ catch (e) {
175
+ throw this.handleError(e);
176
+ }
172
177
  }
173
178
  async fetchBlocks(bufferBlocks) {
174
179
  return Promise.all(bufferBlocks.map(async (num) => this.fetchBlock(num, true)));
@@ -251,6 +256,13 @@ class EthereumApi {
251
256
  logger.warn('Disconnect called on HTTP provider');
252
257
  }
253
258
  }
259
+ handleError(e) {
260
+ if ((e === null || e === void 0 ? void 0 : e.status) === 429) {
261
+ const { hostname } = new URL(this.endpoint);
262
+ return new Error(`Rate Limited at endpoint: ${hostname}`);
263
+ }
264
+ return e;
265
+ }
254
266
  }
255
267
  exports.EthereumApi = EthereumApi;
256
268
  //# sourceMappingURL=api.ethereum.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;AAEtC,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,4CAA+C;AAE/C,wDAA4E;AAG5E,gDAA6C;AAS7C,wEAA+C;AAC/C,4CAA0D;AAC1D,8CAAkD;AAClD,qDAAwD;AACxD,8EAAwE;AACxE,kEAA6D;AAE7D,0DAAyC;AACzC,qDAK0B;AAE1B,8DAA8D;AAC9D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAElE,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,cAAc,CAAC,CAAC;AAEzC,KAAK,UAAU,UAAU,CACvB,EAA2B;IAE3B,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;QACd,OAAO,EAAE,CAAC;KACX;IACD,MAAM,GAAG,GAA2B,EAAE,CAAC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AE;YAC5C,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;SAC7B;aAAM;YACL,MAAM,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;SACnD;IACH,CAAC;CACF;AApQD,kCAoQC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\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 { JsonRpcSigner, WebSocketProvider } from '@ethersproject/providers';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\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 CacheableLookup from 'cacheable-lookup';\nimport { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\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: 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\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\n // Ethereum POS\n private supportsFinalization = true;\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 this.genesisBlock = await this.client.getBlock(0);\n\n const network = await this.client.getNetwork();\n this.chainId = network.chainId;\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 getFinalizedBlockHeight(): Promise<number> {\n try {\n if (this.supportsFinalization) {\n return (await this.client.getBlock('finalized')).number;\n } else {\n // TODO make number of blocks finalised configurable\n return (await this.getBestBlockHeight()) - 15; // Consider 15 blocks finalized\n }\n } catch (e) {\n // TODO handle specific error for this\n this.supportsFinalization = false;\n return this.getFinalizedBlockHeight();\n }\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 '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 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 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 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),\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 }\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 freezeApi(processor: any, blockContent: BlockWrapper): void {\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 processor.freeze(\n new SafeEthProvider(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 // 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"]}
1
+ {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;AAEtC,4CAAoB;AACpB,gDAAwB;AACxB,kDAA0B;AAC1B,4CAA+C;AAE/C,wDAA4E;AAG5E,gDAA6C;AAS7C,wEAA+C;AAC/C,4CAA0D;AAC1D,8CAAkD;AAClD,qDAAwD;AACxD,8EAAwE;AACxE,kEAA6D;AAE7D,0DAAyC;AACzC,qDAK0B;AAE1B,8DAA8D;AAC9D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;AAElE,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,cAAc,CAAC,CAAC;AAEzC,KAAK,UAAU,UAAU,CACvB,EAA2B;IAE3B,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE;QACd,OAAO,EAAE,CAAC;KACX;IACD,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,KAAK,MAAM,CAAC,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE;QACxD,IAAI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C,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;AAjRD,kCAiRC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\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 { JsonRpcSigner, WebSocketProvider } from '@ethersproject/providers';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\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 CacheableLookup from 'cacheable-lookup';\nimport { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\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: 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\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\n // Ethereum POS\n private supportsFinalization = true;\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 this.genesisBlock = await this.client.getBlock(0);\n\n const network = await this.client.getNetwork();\n this.chainId = network.chainId;\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 getFinalizedBlockHeight(): Promise<number> {\n try {\n if (this.supportsFinalization) {\n return (await this.client.getBlock('finalized')).number;\n } else {\n // TODO make number of blocks finalised configurable\n return (await this.getBestBlockHeight()) - 15; // Consider 15 blocks finalized\n }\n } catch (e) {\n // TODO handle specific error for this\n this.supportsFinalization = false;\n return this.getFinalizedBlockHeight();\n }\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 '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 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 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),\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 freezeApi(processor: any, blockContent: BlockWrapper): void {\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 processor.freeze(\n new SafeEthProvider(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 // 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"]}
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.JsonRpcBatchProvider = void 0;
4
4
  /* eslint-disable */
5
5
  const properties_1 = require("@ethersproject/properties");
6
- const web_1 = require("@ethersproject/web");
7
6
  const providers_1 = require("@ethersproject/providers");
7
+ const web_1 = require("./web");
8
8
  const node_core_1 = require("@subql/node-core");
9
9
  const logger = (0, node_core_1.getLogger)('JsonRpcBatchProvider');
10
10
  // Experimental
@@ -1 +1 @@
1
- {"version":3,"file":"json-rpc-batch-provider.js","sourceRoot":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AChC,eAAe,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACF;AA/HD,oDA+HC","sourcesContent":["/* eslint-disable */\nimport { deepCopy } from '@ethersproject/properties';\nimport { fetchJson } from '@ethersproject/web';\n\nimport { JsonRpcProvider } from '@ethersproject/providers';\nimport { Networkish } from '@ethersproject/networks';\nimport { ConnectionInfo } from './web';\nimport { getLogger } from '@subql/node-core';\n\nconst logger = getLogger('JsonRpcBatchProvider');\n\ninterface RpcResult {\n jsonrpc: '2.0';\n id: number;\n result?: string;\n error?: {\n code: number;\n message: string;\n data?: any;\n };\n}\n\n// Experimental\n\nexport class JsonRpcBatchProvider extends JsonRpcProvider {\n _pendingBatchAggregator: NodeJS.Timer;\n _pendingBatch: Array<{\n request: { method: string; params: Array<any>; id: number; jsonrpc: '2.0' };\n resolve: (result: any) => void;\n reject: (error: Error) => void;\n }>;\n\n constructor(url: string | ConnectionInfo, network?: Networkish) {\n super(url, network);\n }\n\n send(method: string, params: Array<any>): Promise<any> {\n const request = {\n method: method,\n params: params,\n id: this._nextId++,\n jsonrpc: '2.0',\n };\n\n if (this._pendingBatch == null) {\n this._pendingBatch = [];\n }\n\n const inflightRequest: any = { request, resolve: null, reject: null };\n\n const promise = new Promise((resolve, reject) => {\n inflightRequest.resolve = resolve;\n inflightRequest.reject = reject;\n });\n\n this._pendingBatch.push(inflightRequest);\n\n if (!this._pendingBatchAggregator) {\n // Schedule batch for next event loop + short duration\n this._pendingBatchAggregator = setTimeout(() => {\n this.runRequests();\n }, 1);\n }\n\n if (this._pendingBatch.length > 10) {\n this.flush();\n }\n\n return promise;\n }\n\n flush(): void {\n if (this._pendingBatchAggregator) {\n clearTimeout(this._pendingBatchAggregator);\n this.runRequests();\n }\n }\n\n private runRequests() {\n // Get teh current batch and clear it, so new requests\n // go into the next batch\n const batch = this._pendingBatch;\n this._pendingBatch = null;\n this._pendingBatchAggregator = null;\n\n // Get the request as an array of requests\n const request = batch.map((inflight) => inflight.request);\n\n this.emit('debug', {\n action: 'requestBatch',\n request: deepCopy(request),\n provider: this,\n });\n\n return fetchJson(this.connection, JSON.stringify(request))\n .then((result: RpcResult[]) => {\n this.emit('debug', {\n action: 'response',\n request: request,\n response: result,\n provider: this,\n });\n\n // if (!Array.isArray(result)) {\n // result = [result];\n // }\n\n // https://github.com/ethers-io/ethers.js/pull/2657\n if (!Array.isArray(result)) {\n const error = new Error(\n 'Invalid response \\n' + JSON.stringify(result),\n );\n batch.forEach((inflightRequest) => {\n inflightRequest.reject(error);\n });\n return;\n }\n const resultMap = result.reduce((resultMap, payload) => {\n resultMap[payload.id] = payload;\n return resultMap;\n }, {} as Record<number, RpcResult>);\n\n // For each result, feed it to the correct Promise, depending\n // on whether it was a success or error\n batch.forEach((inflightRequest) => {\n const payload = resultMap[inflightRequest.request.id];\n if (payload.error) {\n const error = new Error(payload.error.message);\n (<any>error).code = payload.error.code;\n (<any>error).data = payload.error.data;\n inflightRequest.reject(error);\n } else {\n inflightRequest.resolve(payload.result);\n }\n });\n })\n .catch((error) => {\n this.emit('debug', {\n action: 'response',\n error: error,\n request: request,\n provider: this,\n });\n\n logger.error(error);\n\n batch.forEach((inflightRequest) => {\n inflightRequest.reject(error);\n });\n });\n }\n}\n"]}
1
+ {"version":3,"file":"json-rpc-batch-provider.js","sourceRoot":"","sources":["../../../src/ethereum/ethers/json-rpc-batch-provider.ts"],"names":[],"mappings":";;;AAAA,oBAAoB;AACpB,0DAAqD;AAErD,wDAA2D;AAE3D,+BAAkD;AAClD,gDAA6C;AAE7C,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,sBAAsB,CAAC,CAAC;AAajD,eAAe;AAEf,MAAa,oBAAqB,SAAQ,2BAAe;IAQvD,YAAY,GAA4B,EAAE,OAAoB;QAC5D,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACtB,CAAC;IAED,IAAI,CAAC,MAAc,EAAE,MA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K,CAAC,OAAO,CAAC,CAAC,eAAe,EAAE,EAAE;gBAChC,MAAM,OAAO,GAAG,SAAS,CAAC,eAAe,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;gBACtD,IAAI,OAAO,CAAC,KAAK,EAAE;oBACjB,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;oBACzC,KAAM,CAAC,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;oBACjC,KAAM,CAAC,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;oBACvC,eAAe,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;iBAC/B;qBAAM;oBACL,eAAe,CAAC,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;iBACzC;YACH,CAAC,CAAC,CAAC;QACL,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;YACf,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;gBACjB,MAAM,EAAE,UAAU;gBAClB,KAAK,EAAE,KAAK;gBACZ,OAAO,EAAE,OAAO;gBAChB,QAAQ,EAAE,IAAI;aACf,CAAC,CAAC;YAEH,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YAEpB,KAAK,CAAC,OAAO,CAAC,CAAC,eAAe,EAAE,EAAE;gBAChC,eAAe,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACF;AA/HD,oDA+HC","sourcesContent":["/* eslint-disable */\nimport { deepCopy } from '@ethersproject/properties';\n\nimport { JsonRpcProvider } from '@ethersproject/providers';\nimport { Networkish } from '@ethersproject/networks';\nimport { ConnectionInfo, fetchJson } from './web';\nimport { getLogger } from '@subql/node-core';\n\nconst logger = getLogger('JsonRpcBatchProvider');\n\ninterface RpcResult {\n jsonrpc: '2.0';\n id: number;\n result?: string;\n error?: {\n code: number;\n message: string;\n data?: any;\n };\n}\n\n// Experimental\n\nexport class JsonRpcBatchProvider extends JsonRpcProvider {\n _pendingBatchAggregator: NodeJS.Timer;\n _pendingBatch: Array<{\n request: { method: string; params: Array<any>; id: number; jsonrpc: '2.0' };\n resolve: (result: any) => void;\n reject: (error: Error) => void;\n }>;\n\n constructor(url: string | ConnectionInfo, network?: Networkish) {\n super(url, network);\n }\n\n send(method: string, params: Array<any>): Promise<any> {\n const request = {\n method: method,\n params: params,\n id: this._nextId++,\n jsonrpc: '2.0',\n };\n\n if (this._pendingBatch == null) {\n this._pendingBatch = [];\n }\n\n const inflightRequest: any = { request, resolve: null, reject: null };\n\n const promise = new Promise((resolve, reject) => {\n inflightRequest.resolve = resolve;\n inflightRequest.reject = reject;\n });\n\n this._pendingBatch.push(inflightRequest);\n\n if (!this._pendingBatchAggregator) {\n // Schedule batch for next event loop + short duration\n this._pendingBatchAggregator = setTimeout(() => {\n this.runRequests();\n }, 1);\n }\n\n if (this._pendingBatch.length > 10) {\n this.flush();\n }\n\n return promise;\n }\n\n flush(): void {\n if (this._pendingBatchAggregator) {\n clearTimeout(this._pendingBatchAggregator);\n this.runRequests();\n }\n }\n\n private runRequests() {\n // Get teh current batch and clear it, so new requests\n // go into the next batch\n const batch = this._pendingBatch;\n this._pendingBatch = null;\n this._pendingBatchAggregator = null;\n\n // Get the request as an array of requests\n const request = batch.map((inflight) => inflight.request);\n\n this.emit('debug', {\n action: 'requestBatch',\n request: deepCopy(request),\n provider: this,\n });\n\n return fetchJson(this.connection, JSON.stringify(request))\n .then((result: RpcResult[]) => {\n this.emit('debug', {\n action: 'response',\n request: request,\n response: result,\n provider: this,\n });\n\n // if (!Array.isArray(result)) {\n // result = [result];\n // }\n\n // https://github.com/ethers-io/ethers.js/pull/2657\n if (!Array.isArray(result)) {\n const error = new Error(\n 'Invalid response \\n' + JSON.stringify(result),\n );\n batch.forEach((inflightRequest) => {\n inflightRequest.reject(error);\n });\n return;\n }\n const resultMap = result.reduce((resultMap, payload) => {\n resultMap[payload.id] = payload;\n return resultMap;\n }, {} as Record<number, RpcResult>);\n\n // For each result, feed it to the correct Promise, depending\n // on whether it was a success or error\n batch.forEach((inflightRequest) => {\n const payload = resultMap[inflightRequest.request.id];\n if (payload.error) {\n const error = new Error(payload.error.message);\n (<any>error).code = payload.error.code;\n (<any>error).data = payload.error.data;\n inflightRequest.reject(error);\n } else {\n inflightRequest.resolve(payload.result);\n }\n });\n })\n .catch((error) => {\n this.emit('debug', {\n action: 'response',\n error: error,\n request: request,\n provider: this,\n });\n\n logger.error(error);\n\n batch.forEach((inflightRequest) => {\n inflightRequest.reject(error);\n });\n });\n }\n}\n"]}
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.JsonRpcProvider = void 0;
4
4
  /* eslint-disable */
5
5
  const properties_1 = require("@ethersproject/properties");
6
- const web_1 = require("@ethersproject/web");
7
6
  const providers_1 = require("@ethersproject/providers");
7
+ const web_1 = require("./web");
8
8
  function getResult(payload) {
9
9
  if (payload.error) {
10
10
  // @TODO: not any
@@ -1 +1 @@
1
- {"version":3,"file":"json-rpc-provider.js","sourceRoot":"","sources":["../../../src/ethereum/ethers/json-rpc-provider.ts"],"names":[],"mappings":";;;AAAA,oBAAoB;AACpB,0DAAqD;AACrD,4CAA+C;AAE/C,wDAAkF;AAIlF,SAAS,SAAS,CAAC,OAGlB;IACC,IAAI,OAAO,CAAC,KAAK,EAAE;QACjB,iBAAiB;QACjB,MAAM,KAAK,GAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACpD,KAAK,CAAC,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;QAChC,KAAK,CAAC,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;QAChC,MAAM,KAAK,CAAC;KACb;IAED,OAAO,OAAO,CAAC,MAAM,CAAC;AACxB,CAAC;AAED,MAAa,e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,EAAE,IAAI;aACf,CAAC,CAAC;YAEH,MAAM,KAAK,CAAC;QACd,CAAC,CACF,CAAC;QAEF,uDAAuD;QACvD,IAAI,KAAK,EAAE;YACT,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;YAC7B,UAAU,CAAC,GAAG,EAAE;gBACd,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;YAC7B,CAAC,EAAE,CAAC,CAAC,CAAC;SACP;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AA/DD,0CA+DC","sourcesContent":["/* eslint-disable */\nimport { deepCopy } from '@ethersproject/properties';\nimport { fetchJson } from '@ethersproject/web';\n\nimport { JsonRpcProvider as BaseJsonRpcProvider } from '@ethersproject/providers';\nimport { Networkish } from '@ethersproject/networks';\nimport { ConnectionInfo } from './web';\n\nfunction getResult(payload: {\n error?: { code?: number; data?: any; message?: string };\n result?: any;\n}): any {\n if (payload.error) {\n // @TODO: not any\n const error: any = new Error(payload.error.message);\n error.code = payload.error.code;\n error.data = payload.error.data;\n throw error;\n }\n\n return payload.result;\n}\n\nexport class JsonRpcProvider extends BaseJsonRpcProvider {\n constructor(url: string | ConnectionInfo, network?: Networkish) {\n super(url, network);\n }\n\n send(method: string, params: Array<any>): Promise<any> {\n const request = {\n method: method,\n params: params,\n id: this._nextId++,\n jsonrpc: '2.0',\n };\n\n this.emit('debug', {\n action: 'request',\n request: deepCopy(request),\n provider: this,\n });\n\n // We can expand this in the future to any call, but for now these\n // are the biggest wins and do not require any serializing parameters.\n const cache = ['eth_chainId', 'eth_blockNumber'].indexOf(method) >= 0;\n if (cache && this._cache[method]) {\n return this._cache[method];\n }\n\n const result = fetchJson(\n this.connection,\n JSON.stringify(request),\n getResult,\n ).then(\n (result) => {\n this.emit('debug', {\n action: 'response',\n request: request,\n response: result,\n provider: this,\n });\n\n return result;\n },\n (error) => {\n this.emit('debug', {\n action: 'response',\n error: error,\n request: request,\n provider: this,\n });\n\n throw error;\n },\n );\n\n // Cache the fetch, but clear it on the next event loop\n if (cache) {\n this._cache[method] = result;\n setTimeout(() => {\n this._cache[method] = null;\n }, 0);\n }\n\n return result;\n }\n}\n"]}
1
+ {"version":3,"file":"json-rpc-provider.js","sourceRoot":"","sources":["../../../src/ethereum/ethers/json-rpc-provider.ts"],"names":[],"mappings":";;;AAAA,oBAAoB;AACpB,0DAAqD;AAErD,wDAAkF;AAElF,+BAAkD;AAElD,SAAS,SAAS,CAAC,OAGlB;IACC,IAAI,OAAO,CAAC,KAAK,EAAE;QACjB,iBAAiB;QACjB,MAAM,KAAK,GAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACpD,KAAK,CAAC,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;QAChC,KAAK,CAAC,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;QAChC,MAAM,KAAK,CAAC;KACb;IAED,OAAO,OAAO,CAAC,MAAM,CAAC;AACxB,CAAC;AAED,MAAa,eAAgB,SAAQ,2BAAmB;IACtD,YAAY,GAA4B,EAAE,OAAoB;QAC5D,KAAK,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACtB,CAAC;IAED,IAAI,CAAC,MAAc,EAAE,MAAkB;QACrC,MAAM,OAAO,GAAG;YACd,MAAM,EAAE,MAAM;YACd,MAAM,EAAE,MAAM;YACd,EAAE,EAAE,IAAI,CAAC,OAAO,EAAE;YAClB,OAAO,EAAE,KAAK;SACf,CAAC;QAEF,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;YACjB,MAAM,EAAE,SAAS;YACjB,OAAO,EAAE,IAAA,qBAAQ,EAAC,OAAO,CAAC;YAC1B,QAAQ,EAAE,IAAI;SACf,CAAC,CAAC;QAEH,kEAAkE;QAClE,sEAAsE;QACtE,MAAM,KAAK,GAAG,CAAC,aAAa,EAAE,iBAAiB,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACtE,IAAI,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE;YAChC,OAAO,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;SAC5B;QAED,MAAM,MAAM,GAAG,IAAA,eAAS,EACtB,IAAI,CAAC,UAAU,EACf,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,EACvB,SAAS,CACV,CAAC,IAAI,CACJ,CAAC,MAAM,EAAE,EAAE;YACT,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;gBACjB,MAAM,EAAE,UAAU;gBAClB,OAAO,EAAE,OAAO;gBAChB,QAAQ,EAAE,MAAM;gBAChB,QAAQ,EAAE,IAAI;aACf,CAAC,CAAC;YAEH,OAAO,MAAM,CAAC;QAChB,CAAC,EACD,CAAC,KAAK,EAAE,EAAE;YACR,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE;gBACjB,MAAM,EAAE,UAAU;gBAClB,KAAK,EAAE,KAAK;gBACZ,OAAO,EAAE,OAAO;gBAChB,QAAQ,EAAE,IAAI;aACf,CAAC,CAAC;YAEH,MAAM,KAAK,CAAC;QACd,CAAC,CACF,CAAC;QAEF,uDAAuD;QACvD,IAAI,KAAK,EAAE;YACT,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;YAC7B,UAAU,CAAC,GAAG,EAAE;gBACd,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;YAC7B,CAAC,EAAE,CAAC,CAAC,CAAC;SACP;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AA/DD,0CA+DC","sourcesContent":["/* eslint-disable */\nimport { deepCopy } from '@ethersproject/properties';\n\nimport { JsonRpcProvider as BaseJsonRpcProvider } from '@ethersproject/providers';\nimport { Networkish } from '@ethersproject/networks';\nimport { ConnectionInfo, fetchJson } from './web';\n\nfunction getResult(payload: {\n error?: { code?: number; data?: any; message?: string };\n result?: any;\n}): any {\n if (payload.error) {\n // @TODO: not any\n const error: any = new Error(payload.error.message);\n error.code = payload.error.code;\n error.data = payload.error.data;\n throw error;\n }\n\n return payload.result;\n}\n\nexport class JsonRpcProvider extends BaseJsonRpcProvider {\n constructor(url: string | ConnectionInfo, network?: Networkish) {\n super(url, network);\n }\n\n send(method: string, params: Array<any>): Promise<any> {\n const request = {\n method: method,\n params: params,\n id: this._nextId++,\n jsonrpc: '2.0',\n };\n\n this.emit('debug', {\n action: 'request',\n request: deepCopy(request),\n provider: this,\n });\n\n // We can expand this in the future to any call, but for now these\n // are the biggest wins and do not require any serializing parameters.\n const cache = ['eth_chainId', 'eth_blockNumber'].indexOf(method) >= 0;\n if (cache && this._cache[method]) {\n return this._cache[method];\n }\n\n const result = fetchJson(\n this.connection,\n JSON.stringify(request),\n getResult,\n ).then(\n (result) => {\n this.emit('debug', {\n action: 'response',\n request: request,\n response: result,\n provider: this,\n });\n\n return result;\n },\n (error) => {\n this.emit('debug', {\n action: 'response',\n error: error,\n request: request,\n provider: this,\n });\n\n throw error;\n },\n );\n\n // Cache the fetch, but clear it on the next event loop\n if (cache) {\n this._cache[method] = result;\n setTimeout(() => {\n this._cache[method] = null;\n }, 0);\n }\n\n return result;\n }\n}\n"]}
@@ -198,37 +198,41 @@ function _fetchData(connection, body, processFunc) {
198
198
  let response = null;
199
199
  try {
200
200
  response = await (0, geturl_1.getUrl)(url, options);
201
- if (attempt < attemptLimit) {
202
- if (response.statusCode === 301 || response.statusCode === 302) {
203
- // Redirection; for now we only support absolute locataions
204
- const location = response.headers.location || '';
205
- if (options.method === 'GET' && location.match(/^https:/)) {
206
- url = response.headers.location;
207
- continue;
208
- }
201
+ if (response.statusCode === 301 || response.statusCode === 302) {
202
+ // Redirection; for now we only support absolute locataions
203
+ const location = response.headers.location || '';
204
+ if (options.method === 'GET' && location.match(/^https:/)) {
205
+ url = response.headers.location;
206
+ continue;
209
207
  }
210
- else if (response.statusCode === 429) {
211
- // Exponential back-off throttling
212
- let tryAgain = true;
213
- if (throttleCallback) {
214
- tryAgain = await throttleCallback(attempt, url);
208
+ }
209
+ else if (response.statusCode === 429) {
210
+ // If it's the last attempt we throw an error with the response
211
+ if (attempt == attemptLimit - 1) {
212
+ const err = new Error('rate limited');
213
+ err.response = response;
214
+ throw err;
215
+ }
216
+ // Exponential back-off throttling
217
+ let tryAgain = true;
218
+ if (throttleCallback) {
219
+ tryAgain = await throttleCallback(attempt, url);
220
+ }
221
+ if (tryAgain) {
222
+ let stall = 0;
223
+ const retryAfter = response.headers['retry-after'];
224
+ if (typeof retryAfter === 'string' &&
225
+ retryAfter.match(/^[1-9][0-9]*$/)) {
226
+ stall = parseInt(retryAfter) * 1000;
215
227
  }
216
- if (tryAgain) {
217
- let stall = 0;
218
- const retryAfter = response.headers['retry-after'];
219
- if (typeof retryAfter === 'string' &&
220
- retryAfter.match(/^[1-9][0-9]*$/)) {
221
- stall = parseInt(retryAfter) * 1000;
222
- }
223
- else {
224
- stall =
225
- throttleSlotInterval *
226
- parseInt(String(Math.random() * Math.pow(2, attempt)));
227
- }
228
- //console.log("Stalling 429");
229
- await staller(stall);
230
- continue;
228
+ else {
229
+ stall =
230
+ throttleSlotInterval *
231
+ parseInt(String(Math.random() * Math.pow(2, attempt)));
231
232
  }
233
+ //console.log("Stalling 429");
234
+ await staller(stall);
235
+ continue;
232
236
  }
233
237
  }
234
238
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/ethereum/ethers/web/index.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,YAAY,CAAC;;;AAIb,kDAG+B;AAC/B,gDAA4D;AAC5D,0DAAwD;AACxD,oDAAmE;AAEnE,kDAA+C;AAC/C,yCAAqC;AACrC,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC,kBAAO,CAAC,CAAC;AAEnC,qCAA2D;AAE3D,SAAS,OAAO,CAAC,QAAgB;IAC/B,OAAO,IAAI,OAAO,CAAC,CAA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AI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;oBACzD,IAAI,OAAO,GAAG,OAAO,CAAC,KAAK,EAAE;wBAC3B,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC;qBACzB;oBACD,IAAI,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE;wBAC7B,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;qBAC3B;oBAED,UAAU,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;iBAC5B;gBAED,OAAO,IAAI,CAAC;YACd,CAAC,EACD,UAAU,KAAK;gBACb,IAAI,MAAM,EAAE,EAAE;oBACZ,MAAM,CAAC,KAAK,CAAC,CAAC;iBACf;YACH,CAAC,CACF,CAAC;QACJ,CAAC;QACD,KAAK,EAAE,CAAC;IACV,CAAC,CAAC,CAAC;AACL,CAAC;AA5FD,oBA4FC","sourcesContent":["/* eslint-disable */\n'use strict';\n\nimport http from 'http';\nimport https from 'https';\nimport {\n decode as base64Decode,\n encode as base64Encode,\n} from '@ethersproject/base64';\nimport { hexlify, isBytesLike } from '@ethersproject/bytes';\nimport { shallowCopy } from '@ethersproject/properties';\nimport { toUtf8Bytes, toUtf8String } from '@ethersproject/strings';\n\nimport { Logger } from '@ethersproject/logger';\nimport { version } from './_version';\nconst logger = new Logger(version);\n\nimport { getUrl, GetUrlResponse, Options } from './geturl';\n\nfunction staller(duration: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, duration);\n });\n}\n\nfunction bodyify(value: any, type: string): string {\n if (value == null) {\n return null;\n }\n\n if (typeof value === 'string') {\n return value;\n }\n\n if (isBytesLike(value)) {\n if (\n type &&\n (type.split('/')[0] === 'text' ||\n type.split(';')[0].trim() === 'application/json')\n ) {\n try {\n return toUtf8String(value);\n } catch (error) {}\n }\n return hexlify(value);\n }\n\n return value;\n}\n\n// Exported Types\nexport type ConnectionInfo = {\n url: string;\n headers?: { [key: string]: string | number };\n\n user?: string;\n password?: string;\n\n allowInsecureAuthentication?: boolean;\n allowGzip?: boolean;\n\n throttleLimit?: number;\n throttleSlotInterval?: number;\n throttleCallback?: (attempt: number, url: string) => Promise<boolean>;\n\n skipFetchSetup?: boolean;\n fetchOptions?: Record<string, string>;\n errorPassThrough?: boolean;\n\n timeout?: number;\n\n agents?: {\n http?: http.Agent;\n https?: https.Agent;\n };\n};\n\nexport interface OnceBlockable {\n once(eventName: 'block', handler: () => void): void;\n}\n\nexport interface OncePollable {\n once(eventName: 'poll', handler: () => void): void;\n}\n\nexport type PollOptions = {\n timeout?: number;\n floor?: number;\n ceiling?: number;\n interval?: number;\n retryLimit?: number;\n onceBlock?: OnceBlockable;\n oncePoll?: OncePollable;\n};\n\nexport type FetchJsonResponse = {\n statusCode: number;\n headers: { [header: string]: string };\n};\n\ntype Header = { key: string; value: string };\n\nfunction unpercent(value: string): Uint8Array {\n return toUtf8Bytes(\n value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => {\n return String.fromCharCode(parseInt(code, 16));\n }),\n );\n}\n\n// This API is still a work in progress; the future changes will likely be:\n// - ConnectionInfo => FetchDataRequest<T = any>\n// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }\n// - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified)\n// - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T\n// For this reason, it should be considered internal until the API is finalized\nexport function _fetchData<T = Uint8Array>(\n connection: string | ConnectionInfo,\n body?: Uint8Array,\n processFunc?: (value: Uint8Array, response: FetchJsonResponse) => T,\n): Promise<T> {\n // How many times to retry in the event of a throttle\n const attemptLimit =\n typeof connection === 'object' && connection.throttleLimit != null\n ? connection.throttleLimit\n : 12;\n logger.assertArgument(\n attemptLimit > 0 && attemptLimit % 1 === 0,\n 'invalid connection throttle limit',\n 'connection.throttleLimit',\n attemptLimit,\n );\n\n const throttleCallback =\n typeof connection === 'object' ? connection.throttleCallback : null;\n const throttleSlotInterval =\n typeof connection === 'object' &&\n typeof connection.throttleSlotInterval === 'number'\n ? connection.throttleSlotInterval\n : 100;\n logger.assertArgument(\n throttleSlotInterval > 0 && throttleSlotInterval % 1 === 0,\n 'invalid connection throttle slot interval',\n 'connection.throttleSlotInterval',\n throttleSlotInterval,\n );\n\n const errorPassThrough =\n typeof connection === 'object' ? !!connection.errorPassThrough : false;\n\n const headers: { [key: string]: Header } = {};\n\n let url: string = null;\n\n // @TODO: Allow ConnectionInfo to override some of these values\n const options: Options = {\n method: 'GET',\n };\n\n let allow304 = false;\n\n let timeout = 2 * 60 * 1000;\n\n if (typeof connection === 'string') {\n url = connection;\n } else if (typeof connection === 'object') {\n if (connection == null || connection.url == null) {\n logger.throwArgumentError('missing URL', 'connection.url', connection);\n }\n\n url = connection.url;\n\n if (typeof connection.timeout === 'number' && connection.timeout > 0) {\n timeout = connection.timeout;\n }\n\n if (connection.headers) {\n for (const key in connection.headers) {\n headers[key.toLowerCase()] = {\n key: key,\n value: String(connection.headers[key]),\n };\n if (\n ['if-none-match', 'if-modified-since'].indexOf(key.toLowerCase()) >= 0\n ) {\n allow304 = true;\n }\n }\n }\n\n options.allowGzip = !!connection.allowGzip;\n\n if (connection.user != null && connection.password != null) {\n if (\n url.substring(0, 6) !== 'https:' &&\n connection.allowInsecureAuthentication !== true\n ) {\n logger.throwError(\n 'basic authentication requires a secure https url',\n Logger.errors.INVALID_ARGUMENT,\n {\n argument: 'url',\n url: url,\n user: connection.user,\n password: '[REDACTED]',\n },\n );\n }\n\n const authorization = connection.user + ':' + connection.password;\n headers['authorization'] = {\n key: 'Authorization',\n value: 'Basic ' + base64Encode(toUtf8Bytes(authorization)),\n };\n }\n\n if (connection.skipFetchSetup != null) {\n options.skipFetchSetup = !!connection.skipFetchSetup;\n }\n\n if (connection.fetchOptions != null) {\n options.fetchOptions = shallowCopy(connection.fetchOptions);\n }\n\n if (connection.agents != null) {\n options.agents = connection.agents;\n }\n }\n\n const reData = new RegExp('^data:([^;:]*)?(;base64)?,(.*)$', 'i');\n const dataMatch = url ? url.match(reData) : null;\n if (dataMatch) {\n try {\n const response = {\n statusCode: 200,\n statusMessage: 'OK',\n headers: { 'content-type': dataMatch[1] || 'text/plain' },\n body: dataMatch[2]\n ? base64Decode(dataMatch[3])\n : unpercent(dataMatch[3]),\n };\n\n let result: T = <T>(<unknown>response.body);\n if (processFunc) {\n result = processFunc(response.body, response);\n }\n return Promise.resolve(<T>(<unknown>result));\n } catch (error) {\n logger.throwError(\n 'processing response error',\n Logger.errors.SERVER_ERROR,\n {\n body: bodyify(dataMatch[1], dataMatch[2]),\n error: error,\n requestBody: null,\n requestMethod: 'GET',\n url: url,\n },\n );\n }\n }\n\n if (body) {\n options.method = 'POST';\n options.body = body;\n if (headers['content-type'] == null) {\n headers['content-type'] = {\n key: 'Content-Type',\n value: 'application/octet-stream',\n };\n }\n if (headers['content-length'] == null) {\n headers['content-length'] = {\n key: 'Content-Length',\n value: String(body.length),\n };\n }\n }\n\n const flatHeaders: { [key: string]: string } = {};\n Object.keys(headers).forEach((key) => {\n const header = headers[key];\n flatHeaders[header.key] = header.value;\n });\n options.headers = flatHeaders;\n\n const runningTimeout = (function () {\n let timer: NodeJS.Timer = null;\n const promise: Promise<never> = new Promise(function (resolve, reject) {\n if (timeout) {\n timer = setTimeout(() => {\n if (timer == null) {\n return;\n }\n timer = null;\n\n reject(\n logger.makeError('timeout', Logger.errors.TIMEOUT, {\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n timeout: timeout,\n url: url,\n }),\n );\n }, timeout);\n }\n });\n\n const cancel = function () {\n if (timer == null) {\n return;\n }\n clearTimeout(timer);\n timer = null;\n };\n\n return { promise, cancel };\n })();\n\n const runningFetch = (async function () {\n for (let attempt = 0; attempt < attemptLimit; attempt++) {\n let response: GetUrlResponse = null;\n\n try {\n response = await getUrl(url, options);\n\n if (attempt < attemptLimit) {\n if (response.statusCode === 301 || response.statusCode === 302) {\n // Redirection; for now we only support absolute locataions\n const location = response.headers.location || '';\n if (options.method === 'GET' && location.match(/^https:/)) {\n url = response.headers.location;\n continue;\n }\n } else if (response.statusCode === 429) {\n // Exponential back-off throttling\n let tryAgain = true;\n if (throttleCallback) {\n tryAgain = await throttleCallback(attempt, url);\n }\n\n if (tryAgain) {\n let stall = 0;\n\n const retryAfter = response.headers['retry-after'];\n if (\n typeof retryAfter === 'string' &&\n retryAfter.match(/^[1-9][0-9]*$/)\n ) {\n stall = parseInt(retryAfter) * 1000;\n } else {\n stall =\n throttleSlotInterval *\n parseInt(String(Math.random() * Math.pow(2, attempt)));\n }\n\n //console.log(\"Stalling 429\");\n await staller(stall);\n continue;\n }\n }\n }\n } catch (error) {\n response = (<any>error).response;\n if (response == null) {\n runningTimeout.cancel();\n logger.throwError('missing response', Logger.errors.SERVER_ERROR, {\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n serverError: error,\n url: url,\n });\n }\n }\n\n let body = response.body;\n\n if (allow304 && response.statusCode === 304) {\n body = null;\n } else if (\n !errorPassThrough &&\n (response.statusCode < 200 || response.statusCode >= 300)\n ) {\n runningTimeout.cancel();\n logger.throwError('bad response', Logger.errors.SERVER_ERROR, {\n status: response.statusCode,\n headers: response.headers,\n body: bodyify(\n body,\n response.headers ? response.headers['content-type'] : null,\n ),\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n url: url,\n });\n }\n\n if (processFunc) {\n try {\n const result = await processFunc(body, response);\n runningTimeout.cancel();\n return result;\n } catch (error) {\n // Allow the processFunc to trigger a throttle\n if (error.throttleRetry && attempt < attemptLimit) {\n let tryAgain = true;\n if (throttleCallback) {\n tryAgain = await throttleCallback(attempt, url);\n }\n\n if (tryAgain) {\n const timeout =\n throttleSlotInterval *\n parseInt(String(Math.random() * Math.pow(2, attempt)));\n //console.log(\"Stalling callback\");\n await staller(timeout);\n continue;\n }\n }\n\n runningTimeout.cancel();\n logger.throwError(\n 'processing response error',\n Logger.errors.SERVER_ERROR,\n {\n body: bodyify(\n body,\n response.headers ? response.headers['content-type'] : null,\n ),\n error: error,\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n url: url,\n },\n );\n }\n }\n\n runningTimeout.cancel();\n\n // If we had a processFunc, it either returned a T or threw above.\n // The \"body\" is now a Uint8Array.\n return <T>(<unknown>body);\n }\n\n return logger.throwError('failed response', Logger.errors.SERVER_ERROR, {\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n url: url,\n });\n })();\n\n return Promise.race([runningTimeout.promise, runningFetch]);\n}\n\nexport function fetchJson(\n connection: string | ConnectionInfo,\n json?: string,\n processFunc?: (value: any, response: FetchJsonResponse) => any,\n): Promise<any> {\n let processJsonFunc = (value: Uint8Array, response: FetchJsonResponse) => {\n let result: any = null;\n if (value != null) {\n try {\n result = JSON.parse(toUtf8String(value));\n } catch (error) {\n logger.throwError('invalid JSON', Logger.errors.SERVER_ERROR, {\n body: value,\n error: error,\n });\n }\n }\n\n if (processFunc) {\n result = processFunc(result, response);\n }\n\n return result;\n };\n\n // If we have json to send, we must\n // - add content-type of application/json (unless already overridden)\n // - convert the json to bytes\n let body: Uint8Array = null;\n if (json != null) {\n body = toUtf8Bytes(json);\n\n // Create a connection with the content-type set for JSON\n const updated: ConnectionInfo =\n typeof connection === 'string'\n ? { url: connection }\n : shallowCopy(connection);\n if (updated.headers) {\n const hasContentType =\n Object.keys(updated.headers).filter(\n (k) => k.toLowerCase() === 'content-type',\n ).length !== 0;\n if (!hasContentType) {\n updated.headers = shallowCopy(updated.headers);\n updated.headers['content-type'] = 'application/json';\n }\n } else {\n updated.headers = { 'content-type': 'application/json' };\n }\n connection = updated;\n }\n\n return _fetchData<any>(connection, body, processJsonFunc);\n}\n\nexport function poll<T>(\n func: () => Promise<T>,\n options?: PollOptions,\n): Promise<T> {\n if (!options) {\n options = {};\n }\n options = shallowCopy(options);\n if (options.floor == null) {\n options.floor = 0;\n }\n if (options.ceiling == null) {\n options.ceiling = 10000;\n }\n if (options.interval == null) {\n options.interval = 250;\n }\n\n return new Promise(function (resolve, reject) {\n let timer: NodeJS.Timer = null;\n let done: boolean = false;\n\n // Returns true if cancel was successful. Unsuccessful cancel means we're already done.\n const cancel = (): boolean => {\n if (done) {\n return false;\n }\n done = true;\n if (timer) {\n clearTimeout(timer);\n }\n return true;\n };\n\n if (options.timeout) {\n timer = setTimeout(() => {\n if (cancel()) {\n reject(new Error('timeout'));\n }\n }, options.timeout);\n }\n\n const retryLimit = options.retryLimit;\n\n let attempt = 0;\n function check() {\n return func().then(\n function (result) {\n // If we have a result, or are allowed null then we're done\n if (result !== undefined) {\n if (cancel()) {\n resolve(result);\n }\n } else if (options.oncePoll) {\n options.oncePoll.once('poll', check);\n } else if (options.onceBlock) {\n options.onceBlock.once('block', check);\n\n // Otherwise, exponential back-off (up to 10s) our next request\n } else if (!done) {\n attempt++;\n if (attempt > retryLimit) {\n if (cancel()) {\n reject(new Error('retry limit reached'));\n }\n return;\n }\n\n let timeout =\n options.interval *\n parseInt(String(Math.random() * Math.pow(2, attempt)));\n if (timeout < options.floor) {\n timeout = options.floor;\n }\n if (timeout > options.ceiling) {\n timeout = options.ceiling;\n }\n\n setTimeout(check, timeout);\n }\n\n return null;\n },\n function (error) {\n if (cancel()) {\n reject(error);\n }\n },\n );\n }\n check();\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/ethereum/ethers/web/index.ts"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,YAAY,CAAC;;;AAIb,kDAG+B;AAC/B,gDAA4D;AAC5D,0DAAwD;AACxD,oDAAmE;AAEnE,kDAA+C;AAC/C,yCAAqC;AACrC,MAAM,MAAM,GAAG,IAAI,eAAM,CAAC,kBAAO,CAAC,CAAC;AAEnC,qCAA2D;AAE3D,SAAS,OAAO,CAAC,QAAgB;IAC/B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,UAAU,CAAC,OAAO,EAAE,Q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oBAED,IAAI,OAAO,GACT,OAAO,CAAC,QAAQ;wBAChB,QAAQ,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;oBACzD,IAAI,OAAO,GAAG,OAAO,CAAC,KAAK,EAAE;wBAC3B,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC;qBACzB;oBACD,IAAI,OAAO,GAAG,OAAO,CAAC,OAAO,EAAE;wBAC7B,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;qBAC3B;oBAED,UAAU,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;iBAC5B;gBAED,OAAO,IAAI,CAAC;YACd,CAAC,EACD,UAAU,KAAK;gBACb,IAAI,MAAM,EAAE,EAAE;oBACZ,MAAM,CAAC,KAAK,CAAC,CAAC;iBACf;YACH,CAAC,CACF,CAAC;QACJ,CAAC;QACD,KAAK,EAAE,CAAC;IACV,CAAC,CAAC,CAAC;AACL,CAAC;AA5FD,oBA4FC","sourcesContent":["/* eslint-disable */\n'use strict';\n\nimport http from 'http';\nimport https from 'https';\nimport {\n decode as base64Decode,\n encode as base64Encode,\n} from '@ethersproject/base64';\nimport { hexlify, isBytesLike } from '@ethersproject/bytes';\nimport { shallowCopy } from '@ethersproject/properties';\nimport { toUtf8Bytes, toUtf8String } from '@ethersproject/strings';\n\nimport { Logger } from '@ethersproject/logger';\nimport { version } from './_version';\nconst logger = new Logger(version);\n\nimport { getUrl, GetUrlResponse, Options } from './geturl';\n\nfunction staller(duration: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, duration);\n });\n}\n\nfunction bodyify(value: any, type: string): string {\n if (value == null) {\n return null;\n }\n\n if (typeof value === 'string') {\n return value;\n }\n\n if (isBytesLike(value)) {\n if (\n type &&\n (type.split('/')[0] === 'text' ||\n type.split(';')[0].trim() === 'application/json')\n ) {\n try {\n return toUtf8String(value);\n } catch (error) {}\n }\n return hexlify(value);\n }\n\n return value;\n}\n\n// Exported Types\nexport type ConnectionInfo = {\n url: string;\n headers?: { [key: string]: string | number };\n\n user?: string;\n password?: string;\n\n allowInsecureAuthentication?: boolean;\n allowGzip?: boolean;\n\n throttleLimit?: number;\n throttleSlotInterval?: number;\n throttleCallback?: (attempt: number, url: string) => Promise<boolean>;\n\n skipFetchSetup?: boolean;\n fetchOptions?: Record<string, string>;\n errorPassThrough?: boolean;\n\n timeout?: number;\n\n agents?: {\n http?: http.Agent;\n https?: https.Agent;\n };\n};\n\nexport interface OnceBlockable {\n once(eventName: 'block', handler: () => void): void;\n}\n\nexport interface OncePollable {\n once(eventName: 'poll', handler: () => void): void;\n}\n\nexport type PollOptions = {\n timeout?: number;\n floor?: number;\n ceiling?: number;\n interval?: number;\n retryLimit?: number;\n onceBlock?: OnceBlockable;\n oncePoll?: OncePollable;\n};\n\nexport type FetchJsonResponse = {\n statusCode: number;\n headers: { [header: string]: string };\n};\n\ntype Header = { key: string; value: string };\n\nfunction unpercent(value: string): Uint8Array {\n return toUtf8Bytes(\n value.replace(/%([0-9a-f][0-9a-f])/gi, (all, code) => {\n return String.fromCharCode(parseInt(code, 16));\n }),\n );\n}\n\n// This API is still a work in progress; the future changes will likely be:\n// - ConnectionInfo => FetchDataRequest<T = any>\n// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }\n// - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified)\n// - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T\n// For this reason, it should be considered internal until the API is finalized\nexport function _fetchData<T = Uint8Array>(\n connection: string | ConnectionInfo,\n body?: Uint8Array,\n processFunc?: (value: Uint8Array, response: FetchJsonResponse) => T,\n): Promise<T> {\n // How many times to retry in the event of a throttle\n const attemptLimit =\n typeof connection === 'object' && connection.throttleLimit != null\n ? connection.throttleLimit\n : 12;\n logger.assertArgument(\n attemptLimit > 0 && attemptLimit % 1 === 0,\n 'invalid connection throttle limit',\n 'connection.throttleLimit',\n attemptLimit,\n );\n\n const throttleCallback =\n typeof connection === 'object' ? connection.throttleCallback : null;\n const throttleSlotInterval =\n typeof connection === 'object' &&\n typeof connection.throttleSlotInterval === 'number'\n ? connection.throttleSlotInterval\n : 100;\n logger.assertArgument(\n throttleSlotInterval > 0 && throttleSlotInterval % 1 === 0,\n 'invalid connection throttle slot interval',\n 'connection.throttleSlotInterval',\n throttleSlotInterval,\n );\n\n const errorPassThrough =\n typeof connection === 'object' ? !!connection.errorPassThrough : false;\n\n const headers: { [key: string]: Header } = {};\n\n let url: string = null;\n\n // @TODO: Allow ConnectionInfo to override some of these values\n const options: Options = {\n method: 'GET',\n };\n\n let allow304 = false;\n\n let timeout = 2 * 60 * 1000;\n\n if (typeof connection === 'string') {\n url = connection;\n } else if (typeof connection === 'object') {\n if (connection == null || connection.url == null) {\n logger.throwArgumentError('missing URL', 'connection.url', connection);\n }\n\n url = connection.url;\n\n if (typeof connection.timeout === 'number' && connection.timeout > 0) {\n timeout = connection.timeout;\n }\n\n if (connection.headers) {\n for (const key in connection.headers) {\n headers[key.toLowerCase()] = {\n key: key,\n value: String(connection.headers[key]),\n };\n if (\n ['if-none-match', 'if-modified-since'].indexOf(key.toLowerCase()) >= 0\n ) {\n allow304 = true;\n }\n }\n }\n\n options.allowGzip = !!connection.allowGzip;\n\n if (connection.user != null && connection.password != null) {\n if (\n url.substring(0, 6) !== 'https:' &&\n connection.allowInsecureAuthentication !== true\n ) {\n logger.throwError(\n 'basic authentication requires a secure https url',\n Logger.errors.INVALID_ARGUMENT,\n {\n argument: 'url',\n url: url,\n user: connection.user,\n password: '[REDACTED]',\n },\n );\n }\n\n const authorization = connection.user + ':' + connection.password;\n headers['authorization'] = {\n key: 'Authorization',\n value: 'Basic ' + base64Encode(toUtf8Bytes(authorization)),\n };\n }\n\n if (connection.skipFetchSetup != null) {\n options.skipFetchSetup = !!connection.skipFetchSetup;\n }\n\n if (connection.fetchOptions != null) {\n options.fetchOptions = shallowCopy(connection.fetchOptions);\n }\n\n if (connection.agents != null) {\n options.agents = connection.agents;\n }\n }\n\n const reData = new RegExp('^data:([^;:]*)?(;base64)?,(.*)$', 'i');\n const dataMatch = url ? url.match(reData) : null;\n if (dataMatch) {\n try {\n const response = {\n statusCode: 200,\n statusMessage: 'OK',\n headers: { 'content-type': dataMatch[1] || 'text/plain' },\n body: dataMatch[2]\n ? base64Decode(dataMatch[3])\n : unpercent(dataMatch[3]),\n };\n\n let result: T = <T>(<unknown>response.body);\n if (processFunc) {\n result = processFunc(response.body, response);\n }\n return Promise.resolve(<T>(<unknown>result));\n } catch (error) {\n logger.throwError(\n 'processing response error',\n Logger.errors.SERVER_ERROR,\n {\n body: bodyify(dataMatch[1], dataMatch[2]),\n error: error,\n requestBody: null,\n requestMethod: 'GET',\n url: url,\n },\n );\n }\n }\n\n if (body) {\n options.method = 'POST';\n options.body = body;\n if (headers['content-type'] == null) {\n headers['content-type'] = {\n key: 'Content-Type',\n value: 'application/octet-stream',\n };\n }\n if (headers['content-length'] == null) {\n headers['content-length'] = {\n key: 'Content-Length',\n value: String(body.length),\n };\n }\n }\n\n const flatHeaders: { [key: string]: string } = {};\n Object.keys(headers).forEach((key) => {\n const header = headers[key];\n flatHeaders[header.key] = header.value;\n });\n options.headers = flatHeaders;\n\n const runningTimeout = (function () {\n let timer: NodeJS.Timer = null;\n const promise: Promise<never> = new Promise(function (resolve, reject) {\n if (timeout) {\n timer = setTimeout(() => {\n if (timer == null) {\n return;\n }\n timer = null;\n\n reject(\n logger.makeError('timeout', Logger.errors.TIMEOUT, {\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n timeout: timeout,\n url: url,\n }),\n );\n }, timeout);\n }\n });\n\n const cancel = function () {\n if (timer == null) {\n return;\n }\n clearTimeout(timer);\n timer = null;\n };\n\n return { promise, cancel };\n })();\n\n const runningFetch = (async function () {\n for (let attempt = 0; attempt < attemptLimit; attempt++) {\n let response: GetUrlResponse = null;\n\n try {\n response = await getUrl(url, options);\n\n if (response.statusCode === 301 || response.statusCode === 302) {\n // Redirection; for now we only support absolute locataions\n const location = response.headers.location || '';\n if (options.method === 'GET' && location.match(/^https:/)) {\n url = response.headers.location;\n continue;\n }\n } else if (response.statusCode === 429) {\n // If it's the last attempt we throw an error with the response\n if (attempt == attemptLimit - 1) {\n const err = new Error('rate limited');\n (err as any).response = response;\n throw err;\n }\n\n // Exponential back-off throttling\n let tryAgain = true;\n if (throttleCallback) {\n tryAgain = await throttleCallback(attempt, url);\n }\n\n if (tryAgain) {\n let stall = 0;\n\n const retryAfter = response.headers['retry-after'];\n if (\n typeof retryAfter === 'string' &&\n retryAfter.match(/^[1-9][0-9]*$/)\n ) {\n stall = parseInt(retryAfter) * 1000;\n } else {\n stall =\n throttleSlotInterval *\n parseInt(String(Math.random() * Math.pow(2, attempt)));\n }\n\n //console.log(\"Stalling 429\");\n await staller(stall);\n continue;\n }\n }\n } catch (error) {\n response = (<any>error).response;\n if (response == null) {\n runningTimeout.cancel();\n logger.throwError('missing response', Logger.errors.SERVER_ERROR, {\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n serverError: error,\n url: url,\n });\n }\n }\n\n let body = response.body;\n\n if (allow304 && response.statusCode === 304) {\n body = null;\n } else if (\n !errorPassThrough &&\n (response.statusCode < 200 || response.statusCode >= 300)\n ) {\n runningTimeout.cancel();\n logger.throwError('bad response', Logger.errors.SERVER_ERROR, {\n status: response.statusCode,\n headers: response.headers,\n body: bodyify(\n body,\n response.headers ? response.headers['content-type'] : null,\n ),\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n url: url,\n });\n }\n\n if (processFunc) {\n try {\n const result = await processFunc(body, response);\n runningTimeout.cancel();\n return result;\n } catch (error) {\n // Allow the processFunc to trigger a throttle\n if (error.throttleRetry && attempt < attemptLimit) {\n let tryAgain = true;\n if (throttleCallback) {\n tryAgain = await throttleCallback(attempt, url);\n }\n\n if (tryAgain) {\n const timeout =\n throttleSlotInterval *\n parseInt(String(Math.random() * Math.pow(2, attempt)));\n //console.log(\"Stalling callback\");\n await staller(timeout);\n continue;\n }\n }\n\n runningTimeout.cancel();\n logger.throwError(\n 'processing response error',\n Logger.errors.SERVER_ERROR,\n {\n body: bodyify(\n body,\n response.headers ? response.headers['content-type'] : null,\n ),\n error: error,\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n url: url,\n },\n );\n }\n }\n\n runningTimeout.cancel();\n\n // If we had a processFunc, it either returned a T or threw above.\n // The \"body\" is now a Uint8Array.\n return <T>(<unknown>body);\n }\n\n return logger.throwError('failed response', Logger.errors.SERVER_ERROR, {\n requestBody: bodyify(options.body, flatHeaders['content-type']),\n requestMethod: options.method,\n url: url,\n });\n })();\n\n return Promise.race([runningTimeout.promise, runningFetch]);\n}\n\nexport function fetchJson(\n connection: string | ConnectionInfo,\n json?: string,\n processFunc?: (value: any, response: FetchJsonResponse) => any,\n): Promise<any> {\n let processJsonFunc = (value: Uint8Array, response: FetchJsonResponse) => {\n let result: any = null;\n if (value != null) {\n try {\n result = JSON.parse(toUtf8String(value));\n } catch (error) {\n logger.throwError('invalid JSON', Logger.errors.SERVER_ERROR, {\n body: value,\n error: error,\n });\n }\n }\n\n if (processFunc) {\n result = processFunc(result, response);\n }\n\n return result;\n };\n\n // If we have json to send, we must\n // - add content-type of application/json (unless already overridden)\n // - convert the json to bytes\n let body: Uint8Array = null;\n if (json != null) {\n body = toUtf8Bytes(json);\n\n // Create a connection with the content-type set for JSON\n const updated: ConnectionInfo =\n typeof connection === 'string'\n ? { url: connection }\n : shallowCopy(connection);\n if (updated.headers) {\n const hasContentType =\n Object.keys(updated.headers).filter(\n (k) => k.toLowerCase() === 'content-type',\n ).length !== 0;\n if (!hasContentType) {\n updated.headers = shallowCopy(updated.headers);\n updated.headers['content-type'] = 'application/json';\n }\n } else {\n updated.headers = { 'content-type': 'application/json' };\n }\n connection = updated;\n }\n\n return _fetchData<any>(connection, body, processJsonFunc);\n}\n\nexport function poll<T>(\n func: () => Promise<T>,\n options?: PollOptions,\n): Promise<T> {\n if (!options) {\n options = {};\n }\n options = shallowCopy(options);\n if (options.floor == null) {\n options.floor = 0;\n }\n if (options.ceiling == null) {\n options.ceiling = 10000;\n }\n if (options.interval == null) {\n options.interval = 250;\n }\n\n return new Promise(function (resolve, reject) {\n let timer: NodeJS.Timer = null;\n let done: boolean = false;\n\n // Returns true if cancel was successful. Unsuccessful cancel means we're already done.\n const cancel = (): boolean => {\n if (done) {\n return false;\n }\n done = true;\n if (timer) {\n clearTimeout(timer);\n }\n return true;\n };\n\n if (options.timeout) {\n timer = setTimeout(() => {\n if (cancel()) {\n reject(new Error('timeout'));\n }\n }, options.timeout);\n }\n\n const retryLimit = options.retryLimit;\n\n let attempt = 0;\n function check() {\n return func().then(\n function (result) {\n // If we have a result, or are allowed null then we're done\n if (result !== undefined) {\n if (cancel()) {\n resolve(result);\n }\n } else if (options.oncePoll) {\n options.oncePoll.once('poll', check);\n } else if (options.onceBlock) {\n options.onceBlock.once('block', check);\n\n // Otherwise, exponential back-off (up to 10s) our next request\n } else if (!done) {\n attempt++;\n if (attempt > retryLimit) {\n if (cancel()) {\n reject(new Error('retry limit reached'));\n }\n return;\n }\n\n let timeout =\n options.interval *\n parseInt(String(Math.random() * Math.pow(2, attempt)));\n if (timeout < options.floor) {\n timeout = options.floor;\n }\n if (timeout > options.ceiling) {\n timeout = options.ceiling;\n }\n\n setTimeout(check, timeout);\n }\n\n return null;\n },\n function (error) {\n if (cancel()) {\n reject(error);\n }\n },\n );\n }\n check();\n });\n}\n"]}
@@ -46,6 +46,7 @@ let WorkerService = class WorkerService {
46
46
  }
47
47
  catch (e) {
48
48
  logger.error(/*e, */ `Failed to fetch block ${height}`);
49
+ throw e;
49
50
  }
50
51
  }
51
52
  async processBlock(height) {
@@ -1 +1 @@
1
- {"version":3,"file":"worker.service.js","sourceRoot":"","sources":["../../../src/indexer/worker/worker.service.ts"],"names":[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S,CAAC;YACnB,CAAC,CAAC,CAAC;SACJ;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,yBAAyB,MAAM,EAAE,CAAC,CAAC;SACzD;IACH,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,MAAc;QAC/B,IAAI;YACF,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;YACxB,MAAM,KAAK,GAAG,IAAI,CAAC,aAAa,CAAC,MAAM,CAAyB,CAAC;YAEjE,IAAI,CAAC,KAAK,EAAE;gBACV,MAAM,IAAI,KAAK,CAAC,SAAS,MAAM,uBAAuB,CAAC,CAAC;aACzD;YAED,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;YAElC,OAAO,MAAM,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;SACpD;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,yBAAyB,MAAM,KAAK,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;YAC/D,MAAM,CAAC,CAAC;SACT;gBAAS;YACR,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;SAC1B;IACH,CAAC;IAED,IAAI,gBAAgB;QAClB,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,MAAM,CAAC;IAChD,CAAC;IAED,IAAI,iBAAiB;QACnB,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;IACzB,CAAC;IAED,IAAI,UAAU;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;CACF,CAAA;AAvEY,aAAa;IADzB,IAAA,mBAAU,GAAE;qCAQW,sBAAU;QACN,gCAAc;QAC1B,sBAAU;GATb,aAAa,CAuEzB;AAvEY,sCAAa","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { threadId } from 'node:worker_threads';\nimport { Injectable } from '@nestjs/common';\nimport {\n NodeConfig,\n getLogger,\n AutoQueue,\n memoryLock,\n ApiService,\n} from '@subql/node-core';\nimport { BlockWrapper, EthereumBlockWrapper } from '@subql/types-ethereum';\nimport { IndexerManager } from '../indexer.manager';\n\nexport type FetchBlockResponse = { parentHash: string } | undefined;\n\nexport type ProcessBlockResponse = {\n dynamicDsCreated: boolean;\n blockHash: string;\n reindexBlockHeight: number;\n};\n\nexport type WorkerStatusResponse = {\n threadId: number;\n isIndexing: boolean;\n fetchedBlocks: number;\n toFetchBlocks: number;\n};\n\nconst logger = getLogger(`Worker Service #${threadId}`);\n\n@Injectable()\nexport class WorkerService {\n private fetchedBlocks: Record<string, BlockWrapper> = {};\n private _isIndexing = false;\n\n private queue: AutoQueue<FetchBlockResponse>;\n\n constructor(\n private apiService: ApiService,\n private indexerManager: IndexerManager,\n nodeConfig: NodeConfig,\n ) {\n this.queue = new AutoQueue(undefined, nodeConfig.batchSize);\n }\n\n async fetchBlock(height: number): Promise<FetchBlockResponse> {\n try {\n return await this.queue.put(async () => {\n // If a dynamic ds is created we might be asked to fetch blocks again, use existing result\n if (!this.fetchedBlocks[height]) {\n if (memoryLock.isLocked()) {\n const start = Date.now();\n await memoryLock.waitForUnlock();\n const end = Date.now();\n logger.debug(`memory lock wait time: ${end - start}ms`);\n }\n\n const [block] = await this.apiService.api.fetchBlocks([height]);\n this.fetchedBlocks[height] = block;\n }\n\n // const block = this.fetchedBlocks[height];\n\n // Return info to get the runtime version, this lets the worker thread know\n return undefined;\n });\n } catch (e) {\n logger.error(/*e, */ `Failed to fetch block ${height}`);\n }\n }\n\n async processBlock(height: number): Promise<ProcessBlockResponse> {\n try {\n this._isIndexing = true;\n const block = this.fetchedBlocks[height] as EthereumBlockWrapper;\n\n if (!block) {\n throw new Error(`Block ${height} has not been fetched`);\n }\n\n delete this.fetchedBlocks[height];\n\n return await this.indexerManager.indexBlock(block);\n } catch (e) {\n logger.error(e, `Failed to index block ${height}: ${e.stack}`);\n throw e;\n } finally {\n this._isIndexing = false;\n }\n }\n\n get numFetchedBlocks(): number {\n return Object.keys(this.fetchedBlocks).length;\n }\n\n get numFetchingBlocks(): number {\n return this.queue.size;\n }\n\n get isIndexing(): boolean {\n return this._isIndexing;\n }\n}\n"]}
1
+ {"version":3,"file":"worker.service.js","sourceRoot":"","sources":["../../../src/indexer/worker/worker.service.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;;;;;;;AAEtC,6DAA+C;AAC/C,2CAA4C;AAC5C,gDAM0B;AAE1B,wDAAoD;AAiBpD,MAAM,MAAM,GAAG,IAAA,qBAAS,EAAC,mBAAmB,8BAAQ,EAAE,CAAC,CAAC;AAGxD,IAAa,aAAa,GAA1B,MAAa,aAAa;IAMxB,YACU,UAAsB,EACtB,cAA8B,EACtC,UAAsB;QAFd,eAAU,GAAV,UAAU,CAAY;QACtB,mBAAc,GAAd,cAAc,CAAgB;QAPhC,kBAAa,GAAiC,EAAE,CAAC;QACjD,gBAAW,GAAG,KAAK,CAAC;QAS1B,IAAI,CAAC,KAAK,GAAG,IAAI,qBAAS,CAAC,SAAS,EAAE,UAAU,CAAC,SAAS,CAAC,CAAC;IAC9D,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,MAAc;QAC7B,IAAI;YACF,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;gBACrC,0FAA0F;gBAC1F,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE;oBAC/B,IAAI,sBAAU,CAAC,QAAQ,EAAE,EAAE;wBACzB,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;wBACzB,MAAM,sBAAU,CAAC,aAAa,EAAE,CAAC;wBACjC,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;wBACvB,MAAM,CAAC,KAAK,CAAC,0BAA0B,GAAG,GAAG,KAAK,IAAI,CAAC,CA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AU;QACZ,OAAO,IAAI,CAAC,WAAW,CAAC;IAC1B,CAAC;CACF,CAAA;AAxEY,aAAa;IADzB,IAAA,mBAAU,GAAE;qCAQW,sBAAU;QACN,gCAAc;QAC1B,sBAAU;GATb,aAAa,CAwEzB;AAxEY,sCAAa","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { threadId } from 'node:worker_threads';\nimport { Injectable } from '@nestjs/common';\nimport {\n NodeConfig,\n getLogger,\n AutoQueue,\n memoryLock,\n ApiService,\n} from '@subql/node-core';\nimport { BlockWrapper, EthereumBlockWrapper } from '@subql/types-ethereum';\nimport { IndexerManager } from '../indexer.manager';\n\nexport type FetchBlockResponse = { parentHash: string } | undefined;\n\nexport type ProcessBlockResponse = {\n dynamicDsCreated: boolean;\n blockHash: string;\n reindexBlockHeight: number;\n};\n\nexport type WorkerStatusResponse = {\n threadId: number;\n isIndexing: boolean;\n fetchedBlocks: number;\n toFetchBlocks: number;\n};\n\nconst logger = getLogger(`Worker Service #${threadId}`);\n\n@Injectable()\nexport class WorkerService {\n private fetchedBlocks: Record<string, BlockWrapper> = {};\n private _isIndexing = false;\n\n private queue: AutoQueue<FetchBlockResponse>;\n\n constructor(\n private apiService: ApiService,\n private indexerManager: IndexerManager,\n nodeConfig: NodeConfig,\n ) {\n this.queue = new AutoQueue(undefined, nodeConfig.batchSize);\n }\n\n async fetchBlock(height: number): Promise<FetchBlockResponse> {\n try {\n return await this.queue.put(async () => {\n // If a dynamic ds is created we might be asked to fetch blocks again, use existing result\n if (!this.fetchedBlocks[height]) {\n if (memoryLock.isLocked()) {\n const start = Date.now();\n await memoryLock.waitForUnlock();\n const end = Date.now();\n logger.debug(`memory lock wait time: ${end - start}ms`);\n }\n\n const [block] = await this.apiService.api.fetchBlocks([height]);\n this.fetchedBlocks[height] = block;\n }\n\n // const block = this.fetchedBlocks[height];\n\n // Return info to get the runtime version, this lets the worker thread know\n return undefined;\n });\n } catch (e) {\n logger.error(/*e, */ `Failed to fetch block ${height}`);\n throw e;\n }\n }\n\n async processBlock(height: number): Promise<ProcessBlockResponse> {\n try {\n this._isIndexing = true;\n const block = this.fetchedBlocks[height] as EthereumBlockWrapper;\n\n if (!block) {\n throw new Error(`Block ${height} has not been fetched`);\n }\n\n delete this.fetchedBlocks[height];\n\n return await this.indexerManager.indexBlock(block);\n } catch (e) {\n logger.error(e, `Failed to index block ${height}: ${e.stack}`);\n throw e;\n } finally {\n this._isIndexing = false;\n }\n }\n\n get numFetchedBlocks(): number {\n return Object.keys(this.fetchedBlocks).length;\n }\n\n get numFetchingBlocks(): number {\n return this.queue.size;\n }\n\n get isIndexing(): boolean {\n return this._isIndexing;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@subql/node-ethereum",
3
- "version": "1.0.2-0",
3
+ "version": "1.0.2-2",
4
4
  "description": "",
5
5
  "author": "Ian He",
6
6
  "license": "Apache-2.0",
@@ -26,7 +26,7 @@
26
26
  "@nestjs/schedule": "^1.0.2",
27
27
  "@subql/common": "^1.8.1",
28
28
  "@subql/common-ethereum": "1.0.0",
29
- "@subql/node-core": "1.11.2-storeCache-0.0.4",
29
+ "@subql/node-core": "1.11.2-storeCache-0.0.5",
30
30
  "@subql/types-ethereum": "1.0.1",
31
31
  "@subql/utils": "^1.4.1",
32
32
  "@subql/x-merkle-mountain-range": "2.0.0-0.1.2",
@@ -75,5 +75,5 @@
75
75
  "/dist",
76
76
  "/bin"
77
77
  ],
78
- "stableVersion": "1.0.1"
78
+ "stableVersion": "1.0.2-1"
79
79
  }