@subql/node-ethereum 0.4.1-1 → 0.4.1-10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/ethereum/api.ethereum.d.ts +4 -3
  3. package/dist/ethereum/api.ethereum.js +43 -47
  4. package/dist/ethereum/api.ethereum.js.map +1 -1
  5. package/dist/ethereum/block.ethereum.d.ts +1 -1
  6. package/dist/ethereum/block.ethereum.js +9 -12
  7. package/dist/ethereum/block.ethereum.js.map +1 -1
  8. package/dist/ethereum/safe-api.d.ts +34 -0
  9. package/dist/ethereum/safe-api.js +114 -0
  10. package/dist/ethereum/safe-api.js.map +1 -0
  11. package/dist/ethereum/utils.ethereum.d.ts +1 -1
  12. package/dist/ethereum/utils.ethereum.js +14 -3
  13. package/dist/ethereum/utils.ethereum.js.map +1 -1
  14. package/dist/indexer/blockDispatcher/block-dispatcher.service.js +5 -2
  15. package/dist/indexer/blockDispatcher/block-dispatcher.service.js.map +1 -1
  16. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js +5 -0
  17. package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js.map +1 -1
  18. package/dist/indexer/dictionary.service.js +1 -1
  19. package/dist/indexer/dictionary.service.js.map +1 -1
  20. package/dist/indexer/dynamic-ds.service.d.ts +2 -0
  21. package/dist/indexer/dynamic-ds.service.js +22 -10
  22. package/dist/indexer/dynamic-ds.service.js.map +1 -1
  23. package/dist/indexer/fetch.service.js +52 -28
  24. package/dist/indexer/fetch.service.js.map +1 -1
  25. package/dist/indexer/indexer.manager.d.ts +1 -1
  26. package/dist/indexer/indexer.manager.js +6 -12
  27. package/dist/indexer/indexer.manager.js.map +1 -1
  28. package/dist/indexer/project.service.d.ts +1 -0
  29. package/dist/indexer/project.service.js +5 -1
  30. package/dist/indexer/project.service.js.map +1 -1
  31. package/dist/indexer/worker/worker.d.ts +2 -0
  32. package/dist/indexer/worker/worker.js +14 -1
  33. package/dist/indexer/worker/worker.js.map +1 -1
  34. package/dist/utils/project.d.ts +1 -0
  35. package/dist/utils/project.js +13 -1
  36. package/dist/utils/project.js.map +1 -1
  37. package/package.json +5 -5
@@ -1,13 +1,14 @@
1
1
  import { Block, TransactionReceipt } from '@ethersproject/abstract-provider';
2
2
  import { RuntimeDataSourceV0_2_0 } from '@subql/common-ethereum';
3
3
  import { ApiWrapper, BlockWrapper, EthereumBlockWrapper, EthereumTransaction, EthereumResult, EthereumLog } from '@subql/types-ethereum';
4
+ import { EthereumBlockWrapped } from './block.ethereum';
4
5
  export declare class EthereumApi implements ApiWrapper<EthereumBlockWrapper> {
5
6
  private endpoint;
6
7
  private client;
7
8
  private genesisBlock;
8
9
  private contractInterfaces;
9
10
  private chainId;
10
- private endpointSupportsGetBlockReceipts;
11
+ private supportsFinalization;
11
12
  constructor(endpoint: string);
12
13
  init(): Promise<void>;
13
14
  getFinalizedBlockHeight(): Promise<number>;
@@ -17,9 +18,9 @@ export declare class EthereumApi implements ApiWrapper<EthereumBlockWrapper> {
17
18
  getGenesisHash(): string;
18
19
  getSpecName(): string;
19
20
  getBlockByHeightOrHash(heightOrHash: number | string): Promise<Block>;
20
- getBlockPromise(num: number): Promise<any>;
21
+ private getBlockPromise;
21
22
  getTransactionReceipt(transactionHash: string | Promise<string>): Promise<TransactionReceipt>;
22
- fetchBlock(num: number): Promise<EthereumBlockWrapper>;
23
+ fetchBlock(blockNumber: number, includeTx?: boolean): Promise<EthereumBlockWrapped>;
23
24
  fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]>;
24
25
  freezeApi(processor: any, blockContent: BlockWrapper): void;
25
26
  private buildInterface;
@@ -6,15 +6,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
6
6
  };
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.EthereumApi = void 0;
9
- const assert_1 = __importDefault(require("assert"));
10
9
  const fs_1 = __importDefault(require("fs"));
11
10
  const abi_1 = require("@ethersproject/abi");
12
- const bignumber_1 = require("@ethersproject/bignumber");
13
11
  const providers_1 = require("@ethersproject/providers");
14
12
  const node_core_1 = require("@subql/node-core");
15
13
  const utils_1 = require("ethers/lib/utils");
16
14
  const project_1 = require("../utils/project");
17
15
  const block_ethereum_1 = require("./block.ethereum");
16
+ const safe_api_1 = __importDefault(require("./safe-api"));
18
17
  const utils_ethereum_1 = require("./utils.ethereum");
19
18
  // eslint-disable-next-line @typescript-eslint/no-var-requires
20
19
  const { version: packageVersion } = require('../../package.json');
@@ -38,7 +37,8 @@ class EthereumApi {
38
37
  constructor(endpoint) {
39
38
  this.endpoint = endpoint;
40
39
  this.contractInterfaces = {};
41
- this.endpointSupportsGetBlockReceipts = true;
40
+ // Ethereum POS
41
+ this.supportsFinalization = true;
42
42
  const { hostname, pathname, port, protocol, searchParams } = new URL(endpoint);
43
43
  const protocolStr = protocol.replace(':', '');
44
44
  logger.info(this.endpoint.split('?')[0]);
@@ -66,10 +66,24 @@ class EthereumApi {
66
66
  this.chainId = (await this.client.getNetwork()).chainId;
67
67
  }
68
68
  async getFinalizedBlockHeight() {
69
- return (await this.client.getBlock('finalized')).number;
69
+ try {
70
+ if (this.supportsFinalization) {
71
+ return (await this.client.getBlock('finalised')).number;
72
+ }
73
+ else {
74
+ // TODO make number of blocks finalised configurable
75
+ return (await this.getBestBlockHeight()) - 15; // Consider 15 blocks finalized
76
+ }
77
+ }
78
+ catch (e) {
79
+ // TODO handle specific error for this
80
+ this.supportsFinalization = false;
81
+ return this.getFinalizedBlockHeight();
82
+ }
70
83
  }
71
84
  async getBestBlockHeight() {
72
- return (await this.client.getBlock('safe')).number;
85
+ const tag = this.supportsFinalization ? 'safe' : 'latest';
86
+ return (await this.client.getBlock(tag)).number;
73
87
  }
74
88
  getRuntimeChain() {
75
89
  return 'ethereum';
@@ -84,68 +98,50 @@ class EthereumApi {
84
98
  return 'ethereum';
85
99
  }
86
100
  async getBlockByHeightOrHash(heightOrHash) {
101
+ if (typeof heightOrHash === 'number') {
102
+ heightOrHash = (0, utils_1.hexValue)(heightOrHash);
103
+ }
87
104
  return this.client.getBlock(heightOrHash);
88
105
  }
89
- async getBlockPromise(num) {
90
- return (0, project_1.retryOnFailEth)(() => this.client.send('eth_getBlockByNumber', [(0, utils_1.hexValue)(num), true]));
106
+ async getBlockPromise(num, includeTx = true) {
107
+ const rawBlock = await (0, project_1.retryOnFailEth)(() => this.client.send('eth_getBlockByNumber', [(0, utils_1.hexValue)(num), includeTx]));
108
+ const block = (0, utils_ethereum_1.formatBlock)(rawBlock);
109
+ block.stateRoot = this.client.formatter.hash(block.stateRoot);
110
+ return block;
91
111
  }
92
112
  async getTransactionReceipt(transactionHash) {
93
113
  return (0, project_1.retryOnFailEth)(this.client.getTransactionReceipt.bind(this.client, transactionHash));
94
114
  }
95
- async fetchBlock(num) {
96
- var _a;
97
- const block_promise = await this.getBlockPromise(num);
98
- const block = (0, utils_ethereum_1.formatBlock)(block_promise);
99
- block.stateRoot = this.client.formatter.hash(block.stateRoot);
100
- if (this.endpointSupportsGetBlockReceipts) {
101
- try {
102
- const rawReceipts = await this.client.send('eth_getBlockReceipts', [(0, utils_1.hexValue)(block.number)]);
103
- const receipts = rawReceipts.map((receipt) => (0, utils_ethereum_1.formatReceipt)(receipt, block));
104
- const txs = block.transactions.map((tx) => {
105
- const transaction = (0, utils_ethereum_1.formatTransaction)(tx);
106
- transaction.receipt =
107
- receipts[bignumber_1.BigNumber.from(transaction.transactionIndex).toNumber()];
108
- (0, assert_1.default)(transaction.hash === transaction.receipt.transactionHash, 'Failed to match receipt to transaction');
109
- return transaction;
110
- });
111
- return new block_ethereum_1.EthereumBlockWrapped(block, txs);
112
- }
113
- catch (e) {
114
- // Method not avaialble https://eips.ethereum.org/EIPS/eip-1474
115
- if (((_a = e === null || e === void 0 ? void 0 : e.error) === null || _a === void 0 ? void 0 : _a.code) === -32601) {
116
- logger.warn(`The endpoint doesn't support 'eth_getBlockReceipts', individual receipts will be fetched instead, this will greatly impact performance.`);
117
- this.endpointSupportsGetBlockReceipts = false;
118
- // Should continue and use old method here
119
- }
120
- else {
121
- throw e;
122
- }
123
- }
124
- }
125
- const transactions = await Promise.all(block.transactions.map(async (tx) => {
126
- const transaction = (0, utils_ethereum_1.formatTransaction)(tx);
127
- const receipt = await this.getTransactionReceipt(tx.hash);
128
- transaction.receipt = (0, utils_ethereum_1.formatReceipt)(receipt, block);
129
- return transaction;
130
- }));
131
- return new block_ethereum_1.EthereumBlockWrapped(block, transactions);
115
+ async fetchBlock(blockNumber, includeTx) {
116
+ const [block, logs] = await Promise.all([
117
+ this.getBlockPromise(blockNumber, includeTx),
118
+ this.client.getLogs({
119
+ fromBlock: (0, utils_1.hexValue)(blockNumber),
120
+ toBlock: (0, utils_1.hexValue)(blockNumber),
121
+ }),
122
+ ]);
123
+ return new block_ethereum_1.EthereumBlockWrapped(block, includeTx
124
+ ? block.transactions.map((tx) => (Object.assign(Object.assign({}, (0, utils_ethereum_1.formatTransaction)(tx)), {
125
+ // TODO memoise
126
+ receipt: () => this.getTransactionReceipt(tx).then((r) => (0, utils_ethereum_1.formatReceipt)(r, block)) })))
127
+ : [], logs.map((l) => (0, utils_ethereum_1.formatLog)(l, block)));
132
128
  }
133
129
  async fetchBlocks(bufferBlocks) {
134
130
  return Promise.all(bufferBlocks.map(async (num) => {
135
131
  try {
136
132
  // Fetch Block
137
- return await this.fetchBlock(num);
133
+ return await this.fetchBlock(num, true);
138
134
  }
139
135
  catch (e) {
140
136
  // Wrap error from an axios error to fix issue with error being undefined
141
137
  const error = new Error(e.message);
142
- logger.error(error, `Failed to fetch block at height ${num}`);
138
+ logger.error(e, `Failed to fetch block at height ${num}`);
143
139
  throw error;
144
140
  }
145
141
  }));
146
142
  }
147
143
  freezeApi(processor, blockContent) {
148
- processor.freeze(this.client, 'api');
144
+ processor.freeze(new safe_api_1.default(this.client, blockContent.blockHeight), 'api');
149
145
  }
150
146
  buildInterface(abiName, assets) {
151
147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ED,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;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}`);\n return transaction;\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,4CAA+C;AAE/C,wDAA8E;AAE9E,gDAA6C;AAS7C,4CAA0E;AAC1E,8CAAkD;AAClD,qDAAwD;AACxD,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;YACF,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,YAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAC,CAAC;SACpE;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,IAAI,KAAK,CAAC,mCAAmC,IAAI,EAAE,CAAC,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O,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;AArOD,kCAqOC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport fs from 'fs';\nimport { Interface } from '@ethersproject/abi';\nimport { Block, TransactionReceipt } from '@ethersproject/abstract-provider';\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 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\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 // Ethereum POS\n private supportsFinalization = 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 try {\n if (this.supportsFinalization) {\n return (await this.client.getBlock('finalised')).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 retryOnFailEth(() =>\n this.client.send('eth_getBlockByNumber', [hexValue(num), 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 return new EthereumBlockWrapped(\n block,\n includeTx\n ? block.transactions.map((tx) => ({\n ...formatTransaction(tx),\n // TODO memoise\n receipt: () =>\n this.getTransactionReceipt(tx).then((r) =>\n formatReceipt(r, block),\n ),\n }))\n : [],\n logs.map((l) => formatLog(l, block)),\n );\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, true);\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(e, `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"]}
@@ -3,7 +3,7 @@ export declare class EthereumBlockWrapped implements EthereumBlockWrapper {
3
3
  private _block;
4
4
  private _txs;
5
5
  private _logs;
6
- constructor(_block: EthereumBlock, _txs: EthereumTransaction[]);
6
+ constructor(_block: EthereumBlock, _txs: EthereumTransaction[], _logs: EthereumLog[]);
7
7
  get block(): EthereumBlock;
8
8
  get blockHeight(): number;
9
9
  get hash(): string;
@@ -3,23 +3,20 @@
3
3
  // SPDX-License-Identifier: Apache-2.0
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.EthereumBlockWrapped = void 0;
6
- const lodash_1 = require("lodash");
7
6
  const string_1 = require("../utils/string");
8
- const utils_ethereum_1 = require("./utils.ethereum");
9
7
  class EthereumBlockWrapped {
10
- constructor(_block, _txs) {
8
+ constructor(_block, _txs, _logs) {
11
9
  this._block = _block;
12
10
  this._txs = _txs;
13
- this._logs = (0, lodash_1.flatten)(_txs.map((tx) => tx.receipt.logs)).map((log) => (0, utils_ethereum_1.formatLog)(log, _block));
14
- this._logs.map((log) => {
15
- log.block = this.block;
16
- return log;
17
- });
11
+ this._logs = _logs;
18
12
  this._block.transactions = this._txs;
19
- this._block.logs = this._logs.map((log) => {
20
- const logCopy = Object.assign({}, log);
21
- logCopy.block = undefined;
22
- return logCopy;
13
+ this._block.logs = this._logs;
14
+ // Set logs on tx
15
+ this._logs.forEach((l) => {
16
+ const tx = this._txs.find((tx) => tx.hash === l.transactionHash);
17
+ if (!tx)
18
+ return;
19
+ tx.logs = tx.logs ? [...tx.logs, l] : [l];
23
20
  });
24
21
  }
25
22
  get block() {
@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AI,CAAC,IAAA,2BAAkB,EAAC,OAAO,EAAE,GAAG,CAAC,OAAO,CAAC,EAAE;YACxD,OAAO,KAAK,CAAC;SACd;QAED,IAAI,CAAC,MAAM;YAAE,OAAO,IAAI,CAAC;QAEzB,IAAI,MAAM,CAAC,MAAM,EAAE;YACjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;gBAC1D,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;gBAC/B,IAAI,CAAC,KAAK,EAAE;oBACV,SAAS;iBACV;gBAED,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE;oBAClB,OAAO,KAAK,CAAC;iBACd;gBACD,IAAI,CAAC,IAAA,oBAAW,EAAC,IAAA,qBAAY,EAAC,KAAK,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;oBACpD,OAAO,KAAK,CAAC;iBACd;aACF;SACF;QACD,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAxGD,oDAwGC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n EthereumBlock,\n EthereumTransactionFilter,\n EthereumLog,\n EthereumLogFilter,\n EthereumResult,\n EthereumBlockFilter,\n EthereumBlockWrapper,\n EthereumTransaction,\n} from '@subql/types-ethereum';\nimport { flatten } from 'lodash';\nimport {\n eventToTopic,\n functionToSighash,\n hexStringEq,\n stringNormalizedEq,\n} from '../utils/string';\nimport { formatLog } from './utils.ethereum';\n\nexport class EthereumBlockWrapped implements EthereumBlockWrapper {\n private _logs: EthereumLog[];\n constructor(\n private _block: EthereumBlock,\n private _txs: EthereumTransaction[],\n ) {\n this._logs = flatten(_txs.map((tx) => tx.receipt.logs)).map((log) =>\n formatLog(log, _block),\n ) as EthereumLog[];\n this._logs.map((log) => {\n log.block = this.block;\n return log;\n });\n this._block.transactions = this._txs;\n this._block.logs = this._logs.map((log) => {\n const logCopy = { ...log };\n logCopy.block = undefined;\n return logCopy;\n });\n }\n\n get block(): EthereumBlock {\n return this._block;\n }\n\n get blockHeight(): number {\n return this.block.number;\n }\n\n get hash(): string {\n return this.block.hash;\n }\n\n get transactions(): EthereumTransaction[] {\n return this._txs;\n }\n\n get logs(): EthereumLog[] {\n return this._logs;\n }\n\n static filterBlocksProcessor(\n block: EthereumBlock,\n filter: EthereumBlockFilter,\n address?: string,\n ): boolean {\n if (filter?.modulo && block.number % filter.modulo !== 0) {\n return false;\n }\n return true;\n }\n\n static filterTransactionsProcessor(\n transaction: EthereumTransaction,\n filter: EthereumTransactionFilter,\n address?: string,\n ): boolean {\n if (!filter) return true;\n if (filter.to && !stringNormalizedEq(filter.to, transaction.to)) {\n return false;\n }\n if (filter.from && !stringNormalizedEq(filter.from, transaction.from)) {\n return false;\n }\n if (address && !filter.to && !stringNormalizedEq(address, transaction.to)) {\n return false;\n }\n if (\n filter.function &&\n transaction.input.indexOf(functionToSighash(filter.function)) !== 0\n ) {\n return false;\n }\n return true;\n }\n\n static filterLogsProcessor(\n log: EthereumLog,\n filter: EthereumLogFilter,\n address?: string,\n ): boolean {\n if (address && !stringNormalizedEq(address, log.address)) {\n return false;\n }\n\n if (!filter) return true;\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\n if (!log.topics[i]) {\n return false;\n }\n if (!hexStringEq(eventToTopic(topic), log.topics[i])) {\n return false;\n }\n }\n }\n return true;\n }\n}\n"]}
1
+ {"version":3,"file":"block.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/block.ethereum.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;AAWtC,4CAKyB;AAEzB,MAAa,oBAAoB;IAC/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AM,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;gBAC1D,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;gBAC/B,IAAI,CAAC,KAAK,EAAE;oBACV,SAAS;iBACV;gBAED,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE;oBAClB,OAAO,KAAK,CAAC;iBACd;gBACD,IAAI,CAAC,IAAA,oBAAW,EAAC,IAAA,qBAAY,EAAC,KAAK,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE;oBACpD,OAAO,KAAK,CAAC;iBACd;aACF;SACF;QACD,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AArGD,oDAqGC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n EthereumBlock,\n EthereumTransactionFilter,\n EthereumLog,\n EthereumLogFilter,\n EthereumBlockFilter,\n EthereumBlockWrapper,\n EthereumTransaction,\n} from '@subql/types-ethereum';\nimport {\n eventToTopic,\n functionToSighash,\n hexStringEq,\n stringNormalizedEq,\n} from '../utils/string';\n\nexport class EthereumBlockWrapped implements EthereumBlockWrapper {\n constructor(\n private _block: EthereumBlock,\n private _txs: EthereumTransaction[],\n private _logs: EthereumLog[],\n ) {\n this._block.transactions = this._txs;\n this._block.logs = this._logs;\n\n // Set logs on tx\n this._logs.forEach((l) => {\n const tx = this._txs.find((tx) => tx.hash === l.transactionHash);\n\n if (!tx) return;\n tx.logs = tx.logs ? [...tx.logs, l] : [l];\n });\n }\n\n get block(): EthereumBlock {\n return this._block;\n }\n\n get blockHeight(): number {\n return this.block.number;\n }\n\n get hash(): string {\n return this.block.hash;\n }\n\n get transactions(): EthereumTransaction[] {\n return this._txs;\n }\n\n get logs(): EthereumLog[] {\n return this._logs;\n }\n\n static filterBlocksProcessor(\n block: EthereumBlock,\n filter: EthereumBlockFilter,\n address?: string,\n ): boolean {\n if (filter?.modulo && block.number % filter.modulo !== 0) {\n return false;\n }\n return true;\n }\n\n static filterTransactionsProcessor(\n transaction: EthereumTransaction,\n filter: EthereumTransactionFilter,\n address?: string,\n ): boolean {\n if (!filter) return true;\n if (filter.to && !stringNormalizedEq(filter.to, transaction.to)) {\n return false;\n }\n if (filter.from && !stringNormalizedEq(filter.from, transaction.from)) {\n return false;\n }\n if (address && !filter.to && !stringNormalizedEq(address, transaction.to)) {\n return false;\n }\n if (\n filter.function &&\n transaction.input.indexOf(functionToSighash(filter.function)) !== 0\n ) {\n return false;\n }\n return true;\n }\n\n static filterLogsProcessor(\n log: EthereumLog,\n filter: EthereumLogFilter,\n address?: string,\n ): boolean {\n if (address && !stringNormalizedEq(address, log.address)) {\n return false;\n }\n\n if (!filter) return true;\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\n if (!log.topics[i]) {\n return false;\n }\n if (!hexStringEq(eventToTopic(topic), log.topics[i])) {\n return false;\n }\n }\n }\n return true;\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.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IACrE,WAAW,CAAC,IAA8B;QACxC,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;IACzD,CAAC;IACD,qEAAqE;IACrE,aAAa,CAAC,OAAiC;QAC7C,MAAM,IAAI,KAAK,CAAC,uCAAuC,CAAC,CAAC;IAC3D,CAAC;IACD,EAAE,CAAC,SAAoB,EAAE,QAAkB;QACzC,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;IAChD,CAAC;IACD,IAAI,CAAC,SAAoB,EAAE,QAAkB;QAC3C,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IAClD,CAAC;IACD,IAAI,CAAC,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"]}
@@ -1,6 +1,6 @@
1
1
  import { ApiWrapper, EthereumBlock, EthereumLog, EthereumReceipt, EthereumResult, EthereumTransaction } from '@subql/types-ethereum';
2
2
  export declare function calcInterval(api: ApiWrapper): number;
3
3
  export declare function formatBlock(block: Record<string, any>): EthereumBlock;
4
- export declare function formatLog(log: EthereumLog<EthereumResult> | EthereumLog, block: EthereumBlock): EthereumLog<EthereumResult> | EthereumLog;
4
+ export declare function formatLog(log: Omit<EthereumLog<EthereumResult> | EthereumLog, 'blockTimestamp' | 'block' | 'transaction'>, block: EthereumBlock): EthereumLog<EthereumResult> | EthereumLog;
5
5
  export declare function formatTransaction(tx: Record<string, any>): EthereumTransaction;
6
6
  export declare function formatReceipt(receipt: Record<string, any>, block: EthereumBlock): EthereumReceipt;
@@ -6,6 +6,7 @@ exports.formatReceipt = exports.formatTransaction = exports.formatLog = exports.
6
6
  const address_1 = require("@ethersproject/address");
7
7
  const bignumber_1 = require("@ethersproject/bignumber");
8
8
  const constants_1 = require("@ethersproject/constants");
9
+ const lodash_1 = require("lodash");
9
10
  function calcInterval(api) {
10
11
  // TODO find a way to get this from the blockchain
11
12
  return 6000;
@@ -35,7 +36,14 @@ function formatBlock(block) {
35
36
  }
36
37
  exports.formatBlock = formatBlock;
37
38
  function formatLog(log, block) {
38
- return Object.assign(Object.assign({}, log), { address: handleAddress(log.address), blockNumber: handleNumber(log.blockNumber).toNumber(), transactionIndex: handleNumber(log.transactionIndex).toNumber(), logIndex: handleNumber(log.logIndex).toNumber(), block });
39
+ return Object.assign(Object.assign({}, log), { address: handleAddress(log.address), blockNumber: handleNumber(log.blockNumber).toNumber(), transactionIndex: handleNumber(log.transactionIndex).toNumber(), logIndex: handleNumber(log.logIndex).toNumber(), block,
40
+ get transaction() {
41
+ var _a;
42
+ return (_a = block.transactions) === null || _a === void 0 ? void 0 : _a.find((tx) => tx.hash === log.transactionHash);
43
+ },
44
+ toJson() {
45
+ return JSON.stringify((0, lodash_1.omit)(this, ['transaction', 'block']));
46
+ } });
39
47
  }
40
48
  exports.formatLog = formatLog;
41
49
  function formatTransaction(tx) {
@@ -43,11 +51,14 @@ function formatTransaction(tx) {
43
51
  ? handleNumber(tx.maxFeePerGas).toBigInt()
44
52
  : undefined, maxPriorityFeePerGas: tx.maxPriorityFeePerGas
45
53
  ? handleNumber(tx.maxPriorityFeePerGas).toBigInt()
46
- : undefined, receipt: undefined });
54
+ : undefined, receipt: undefined, // Filled in at AvalancheApi.fetchBlocks
55
+ toJson() {
56
+ return JSON.stringify((0, lodash_1.omit)(this, ['logs']));
57
+ } });
47
58
  }
48
59
  exports.formatTransaction = formatTransaction;
49
60
  function formatReceipt(receipt, block) {
50
- return Object.assign(Object.assign({}, receipt), { from: handleAddress(receipt.from), to: handleAddress(receipt.to), blockNumber: handleNumber(receipt.blockNumber).toNumber(), cumulativeGasUsed: handleNumber(receipt.cumulativeGasUsed).toBigInt(), effectiveGasPrice: handleNumber(receipt.effectiveGasPrice).toBigInt(), gasUsed: handleNumber(receipt.gasUsed).toBigInt(), logs: receipt.logs.map((log) => formatLog(log, block)), status: Boolean(handleNumber(receipt.status).toNumber()), transactionIndex: handleNumber(receipt.transactionIndex).toNumber() });
61
+ return Object.assign(Object.assign({}, receipt), { from: handleAddress(receipt.from), to: handleAddress(receipt.to), blockNumber: handleNumber(receipt.blockNumber).toNumber(), cumulativeGasUsed: handleNumber(receipt.cumulativeGasUsed).toBigInt(), effectiveGasPrice: handleNumber(receipt.effectiveGasPrice).toBigInt(), gasUsed: handleNumber(receipt.gasUsed).toBigInt(), logs: receipt.logs.map(formatLog), status: Boolean(handleNumber(receipt.status).toNumber()), transactionIndex: handleNumber(receipt.transactionIndex).toNumber() });
51
62
  }
52
63
  exports.formatReceipt = formatReceipt;
53
64
  //# sourceMappingURL=utils.ethereum.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/utils.ethereum.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;AAEtC,oDAAoD;AACpD,wDAAqD;AACrD,wDAAgD;AAUhD,SAAgB,YAAY,CAAC,GAAe;IAC1C,kDAAkD;IAClD,OAAO,IAAI,CAAC;AACd,CAAC;AAHD,oCAGC;AAED,SAAS,aAAa,CAAC,KAAa;IAClC,IAAI,CAAC,KAAK,IAAI,KAAK,KAAK,IAAI,EAAE;QAC5B,OAAO,IAAI,CAAC;KACb;IACD,OAAO,IAAA,oBAAU,EAAC,KAAK,CAAC,CAAC;AAC3B,CAAC;AAED,SAAS,YAAY,CAAC,KAAsB;IAC1C,IAAI,KAAK,KAAK,SAAS,EAAE;QACvB,OAAO,gBAAI,CAAC;KACb;IACD,IAAI,KAAK,KAAK,IAAI,EAAE;QAClB,OAAO,gBAAI,CAAC;KACb;IACD,OAAO,qBAAS,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,SAAgB,WAAW,CAAC,KAA0B;IACpD,OAAO,gCACF,KAAK,KACR,UAAU,EAAE,YAAY,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,QAAQ,EAAE,EACrD,QAAQ,EAAE,YAAY,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,QAAQ,EAAE,EACjD,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAC/C,MAAM,EAAE,YAAY,CAAC,KAAK,CAAC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AO,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EACjD,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,EACtD,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC,EACxD,gBAAgB,EAAE,YAAY,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,QAAQ,EAAE,GACjD,CAAC;AACvB,CAAC;AAhBD,sCAgBC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { getAddress } from '@ethersproject/address';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Zero } from '@ethersproject/constants';\nimport {\n ApiWrapper,\n EthereumBlock,\n EthereumLog,\n EthereumReceipt,\n EthereumResult,\n EthereumTransaction,\n} from '@subql/types-ethereum';\n\nexport function calcInterval(api: ApiWrapper): number {\n // TODO find a way to get this from the blockchain\n return 6000;\n}\n\nfunction handleAddress(value: string): string | null {\n if (!value || value === '0x') {\n return null;\n }\n return getAddress(value);\n}\n\nfunction handleNumber(value: string | number): BigNumber {\n if (value === undefined) {\n return Zero;\n }\n if (value === '0x') {\n return Zero;\n }\n return BigNumber.from(value);\n}\n\nexport function formatBlock(block: Record<string, any>): EthereumBlock {\n return {\n ...block,\n difficulty: handleNumber(block.difficulty).toBigInt(),\n gasLimit: handleNumber(block.gasLimit).toBigInt(),\n gasUsed: handleNumber(block.gasUsed).toBigInt(),\n number: handleNumber(block.number).toNumber(),\n size: handleNumber(block.size).toBigInt(),\n timestamp: handleNumber(block.timestamp).toBigInt(),\n totalDifficulty: handleNumber(block.totalDifficulty).toBigInt(),\n baseFeePerGas: block.baseFeePerGas\n ? handleNumber(block.baseFeePerGas).toBigInt()\n : undefined,\n blockGasCost: block.blockGasCost\n ? handleNumber(block.blockGasCost).toBigInt()\n : undefined,\n logs: [], // Filled in at AvalancheBlockWrapped constructor\n } as EthereumBlock;\n}\nexport function formatLog(\n log: EthereumLog<EthereumResult> | EthereumLog,\n block: EthereumBlock,\n): EthereumLog<EthereumResult> | EthereumLog {\n return {\n ...log,\n address: handleAddress(log.address),\n blockNumber: handleNumber(log.blockNumber).toNumber(),\n transactionIndex: handleNumber(log.transactionIndex).toNumber(),\n logIndex: handleNumber(log.logIndex).toNumber(),\n block,\n } as EthereumLog<EthereumResult>;\n}\n\nexport function formatTransaction(\n tx: Record<string, any>,\n): EthereumTransaction {\n return {\n ...tx,\n from: handleAddress(tx.from),\n to: handleAddress(tx.to),\n blockNumber: handleNumber(tx.blockNumber).toNumber(),\n gas: handleNumber(tx.gas).toBigInt(),\n gasPrice: handleNumber(tx.gasPrice).toBigInt(),\n nonce: handleNumber(tx.nonce).toBigInt(),\n transactionIndex: handleNumber(tx.transactionIndex).toBigInt(),\n value: handleNumber(tx.value).toBigInt(),\n v: handleNumber(tx.v).toBigInt(),\n maxFeePerGas: tx.maxFeePerGas\n ? handleNumber(tx.maxFeePerGas).toBigInt()\n : undefined,\n maxPriorityFeePerGas: tx.maxPriorityFeePerGas\n ? handleNumber(tx.maxPriorityFeePerGas).toBigInt()\n : undefined,\n receipt: undefined, // Filled in at AvalancheApi.fetchBlocks\n } as EthereumTransaction;\n}\n\nexport function formatReceipt(\n receipt: Record<string, any>,\n block: EthereumBlock,\n): EthereumReceipt {\n return {\n ...receipt,\n from: handleAddress(receipt.from),\n to: handleAddress(receipt.to),\n blockNumber: handleNumber(receipt.blockNumber).toNumber(),\n cumulativeGasUsed: handleNumber(receipt.cumulativeGasUsed).toBigInt(),\n effectiveGasPrice: handleNumber(receipt.effectiveGasPrice).toBigInt(),\n gasUsed: handleNumber(receipt.gasUsed).toBigInt(),\n logs: receipt.logs.map((log) => formatLog(log, block)),\n status: Boolean(handleNumber(receipt.status).toNumber()),\n transactionIndex: handleNumber(receipt.transactionIndex).to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AE,YAAY,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,QAAQ,EAAE,EACzD,iBAAiB,EAAE,YAAY,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE,EACrE,iBAAiB,EAAE,YAAY,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,QAAQ,EAAE,EACrE,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EACjD,IAAI,EAAE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EACjC,MAAM,EAAE,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,CAAC,EACxD,gBAAgB,EAAE,YAAY,CAAC,OAAO,CAAC,gBAAgB,CAAC,CAAC,QAAQ,EAAE,GACjD,CAAC;AACvB,CAAC;AAhBD,sCAgBC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { getAddress } from '@ethersproject/address';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { Zero } from '@ethersproject/constants';\nimport {\n ApiWrapper,\n EthereumBlock,\n EthereumLog,\n EthereumReceipt,\n EthereumResult,\n EthereumTransaction,\n} from '@subql/types-ethereum';\nimport { omit } from 'lodash';\n\nexport function calcInterval(api: ApiWrapper): number {\n // TODO find a way to get this from the blockchain\n return 6000;\n}\n\nfunction handleAddress(value: string): string | null {\n if (!value || value === '0x') {\n return null;\n }\n return getAddress(value);\n}\n\nfunction handleNumber(value: string | number): BigNumber {\n if (value === undefined) {\n return Zero;\n }\n if (value === '0x') {\n return Zero;\n }\n return BigNumber.from(value);\n}\n\nexport function formatBlock(block: Record<string, any>): EthereumBlock {\n return {\n ...block,\n difficulty: handleNumber(block.difficulty).toBigInt(),\n gasLimit: handleNumber(block.gasLimit).toBigInt(),\n gasUsed: handleNumber(block.gasUsed).toBigInt(),\n number: handleNumber(block.number).toNumber(),\n size: handleNumber(block.size).toBigInt(),\n timestamp: handleNumber(block.timestamp).toBigInt(),\n totalDifficulty: handleNumber(block.totalDifficulty).toBigInt(),\n baseFeePerGas: block.baseFeePerGas\n ? handleNumber(block.baseFeePerGas).toBigInt()\n : undefined,\n blockGasCost: block.blockGasCost\n ? handleNumber(block.blockGasCost).toBigInt()\n : undefined,\n logs: [], // Filled in at AvalancheBlockWrapped constructor\n } as EthereumBlock;\n}\nexport function formatLog(\n log: Omit<\n EthereumLog<EthereumResult> | EthereumLog,\n 'blockTimestamp' | 'block' | 'transaction'\n >,\n block: EthereumBlock,\n): EthereumLog<EthereumResult> | EthereumLog {\n return {\n ...log,\n address: handleAddress(log.address),\n blockNumber: handleNumber(log.blockNumber).toNumber(),\n transactionIndex: handleNumber(log.transactionIndex).toNumber(),\n logIndex: handleNumber(log.logIndex).toNumber(),\n block,\n get transaction() {\n return block.transactions?.find((tx) => tx.hash === log.transactionHash);\n },\n\n toJson() {\n return JSON.stringify(omit(this, ['transaction', 'block']));\n },\n } as EthereumLog<EthereumResult>;\n}\n\nexport function formatTransaction(\n tx: Record<string, any>,\n): EthereumTransaction {\n return {\n ...(tx as Partial<EthereumTransaction>),\n from: handleAddress(tx.from),\n to: handleAddress(tx.to),\n blockNumber: handleNumber(tx.blockNumber).toNumber(),\n gas: handleNumber(tx.gas).toBigInt(),\n gasPrice: handleNumber(tx.gasPrice).toBigInt(),\n nonce: handleNumber(tx.nonce).toBigInt(),\n transactionIndex: handleNumber(tx.transactionIndex).toBigInt(),\n value: handleNumber(tx.value).toBigInt(),\n v: handleNumber(tx.v).toBigInt(),\n maxFeePerGas: tx.maxFeePerGas\n ? handleNumber(tx.maxFeePerGas).toBigInt()\n : undefined,\n maxPriorityFeePerGas: tx.maxPriorityFeePerGas\n ? handleNumber(tx.maxPriorityFeePerGas).toBigInt()\n : undefined,\n receipt: undefined, // Filled in at AvalancheApi.fetchBlocks\n toJson() {\n return JSON.stringify(omit(this, ['logs']));\n },\n } as EthereumTransaction;\n}\n\nexport function formatReceipt(\n receipt: Record<string, any>,\n block: EthereumBlock,\n): EthereumReceipt {\n return {\n ...receipt,\n from: handleAddress(receipt.from),\n to: handleAddress(receipt.to),\n blockNumber: handleNumber(receipt.blockNumber).toNumber(),\n cumulativeGasUsed: handleNumber(receipt.cumulativeGasUsed).toBigInt(),\n effectiveGasPrice: handleNumber(receipt.effectiveGasPrice).toBigInt(),\n gasUsed: handleNumber(receipt.gasUsed).toBigInt(),\n logs: receipt.logs.map(formatLog),\n status: Boolean(handleNumber(receipt.status).toNumber()),\n transactionIndex: handleNumber(receipt.transactionIndex).toNumber(),\n } as EthereumReceipt;\n}\n"]}
@@ -93,8 +93,11 @@ let BlockDispatcherService = class BlockDispatcherService extends base_block_dis
93
93
  }
94
94
  logger.info(`fetch block [${blockNums[0]},${blockNums[blockNums.length - 1]}], total ${blockNums.length} blocks`);
95
95
  const blocks = await this.fetchBlocksBatches(blockNums);
96
- if (bufferedHeight > this._latestBufferedHeight) {
97
- logger.debug(`Queue was reset for new DS, discarding fetched blocks`);
96
+ // Check if the queues have been flushed between queue.takeMany and fetchBlocksBatches resolving
97
+ // Peeking the queue is because the latestBufferedHeight could have regrown since fetching block
98
+ if (bufferedHeight > this._latestBufferedHeight ||
99
+ this.queue.peek() < Math.min(...blockNums)) {
100
+ logger.info(`Queue was reset for new DS, discarding fetched blocks`);
98
101
  continue;
99
102
  }
100
103
  const blockTasks = blocks.map((block) => async () => {