@subql/node-ethereum 1.10.1-2 → 1.10.1-3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,16 +7,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.EthereumApi = void 0;
9
9
  const fs_1 = __importDefault(require("fs"));
10
- const http_1 = __importDefault(require("http"));
11
- const https_1 = __importDefault(require("https"));
12
10
  const abi_1 = require("@ethersproject/abi");
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 block_ethereum_1 = require("./block.ethereum");
17
15
  const utils_ethereum_1 = require("./utils.ethereum");
18
- const Web3HttpProvider = require('web3-providers-http');
19
- const Web3WsProvider = require('web3-providers-ws');
20
16
  // eslint-disable-next-line @typescript-eslint/no-var-requires
21
17
  const { version: packageVersion } = require('../../package.json');
22
18
  const logger = (0, node_core_1.getLogger)('api.ethereum');
@@ -40,60 +36,29 @@ class EthereumApi {
40
36
  this.endpoint = endpoint;
41
37
  this.contractInterfaces = {};
42
38
  const { hostname, pathname, port, protocol, searchParams } = new URL(endpoint);
43
- const httpAgent = new http_1.default.Agent({ keepAlive: true, maxSockets: 10 });
44
- const httpsAgent = new https_1.default.Agent({ keepAlive: true, maxSockets: 10 });
45
39
  const protocolStr = protocol.replace(':', '');
46
- const portNum = port
47
- ? parseInt(port, 10)
48
- : protocolStr === 'https'
49
- ? undefined
50
- : 80;
51
- let provider;
52
40
  if (protocolStr === 'https' || protocolStr === 'http') {
53
- const options = {
54
- keepAlive: true,
55
- headers: [
56
- {
57
- name: 'User-Agent',
58
- value: `Subquery-Node ${packageVersion}`,
59
- },
60
- ],
61
- agent: {
62
- http: httpAgent,
63
- https: httpsAgent,
64
- },
65
- };
66
- if (searchParams.apiKey) {
67
- options.headers.apiKey = searchParams.get('apiKey');
68
- }
69
- provider = new Web3HttpProvider(this.endpoint, options);
70
- }
71
- else if (protocolStr === 'ws' || protocolStr === 'wss') {
72
- const options = {
41
+ const connection = {
42
+ url: this.endpoint,
73
43
  headers: {
74
44
  'User-Agent': `Subquery-Node ${packageVersion}`,
75
45
  },
76
- clientConfig: {
77
- keepAlive: true,
78
- },
79
46
  };
80
47
  if (searchParams.apiKey) {
81
- options.headers.apiKey = searchParams.get('apiKey');
48
+ connection.headers.apiKey = searchParams.get('apiKey');
82
49
  }
83
- provider = new Web3WsProvider(endpoint, options);
50
+ this.client = new providers_1.JsonRpcProvider(connection);
51
+ }
52
+ else if (protocolStr === 'ws' || protocolStr === 'wss') {
53
+ this.client = new providers_1.WebSocketProvider(this.endpoint);
84
54
  }
85
55
  else {
86
56
  throw new Error(`Unsupported protocol: ${protocol}`);
87
57
  }
88
- this.client = new providers_1.Web3Provider(provider);
89
58
  }
90
59
  async init() {
91
- this.genesisBlock = await this.client.send('eth_getBlockByNumber', [
92
- (0, utils_1.hexValue)(0),
93
- true,
94
- ]);
95
- logger.info(this.endpoint);
96
- this.chainId = await this.client.send('net_version', []);
60
+ this.genesisBlock = await this.client.getBlock(0);
61
+ this.chainId = (await this.client.getNetwork()).chainId;
97
62
  }
98
63
  async getLastHeight() {
99
64
  return this.client.getBlockNumber();
@@ -132,7 +97,7 @@ class EthereumApi {
132
97
  const transactions = await Promise.all(block.transactions.map(async (tx) => {
133
98
  //logger.info(JSON.stringify(tx))
134
99
  const transaction = (0, utils_ethereum_1.formatTransaction)(tx);
135
- const receipt = await this.client.send('eth_getTransactionReceipt', [tx.hash]);
100
+ const receipt = await this.client.getTransactionReceipt(tx.hash);
136
101
  transaction.receipt = (0, utils_ethereum_1.formatReceipt)(receipt, block);
137
102
  return transaction;
138
103
  }));
@@ -1 +1 @@
1
- {"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;A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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 } from '@ethersproject/abstract-provider';\nimport { Web3Provider } 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 { hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { EthereumBlockWrapped } from './block.ethereum';\nimport {\n formatBlock,\n formatReceipt,\n formatTransaction,\n} from './utils.ethereum';\nconst Web3HttpProvider = require('web3-providers-http');\nconst Web3WsProvider = require('web3-providers-ws');\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: Web3Provider;\n private genesisBlock: Record<string, any>;\n private contractInterfaces: Record<string, Interface> = {};\n private chainId: number;\n\n constructor(private endpoint: string) {\n const { hostname, pathname, port, protocol, searchParams } = new URL(\n endpoint,\n );\n const httpAgent = new http.Agent({ keepAlive: true, maxSockets: 10 });\n const httpsAgent = new https.Agent({ keepAlive: true, maxSockets: 10 });\n\n const protocolStr = protocol.replace(':', '');\n const portNum = port\n ? parseInt(port, 10)\n : protocolStr === 'https'\n ? undefined\n : 80;\n\n let provider;\n if (protocolStr === 'https' || protocolStr === 'http') {\n const options = {\n keepAlive: true,\n headers: [\n {\n name: 'User-Agent',\n value: `Subquery-Node ${packageVersion}`,\n },\n ],\n agent: {\n http: httpAgent,\n https: httpsAgent,\n },\n };\n if ((searchParams as any).apiKey) {\n (options.headers as any).apiKey = searchParams.get('apiKey');\n }\n provider = new Web3HttpProvider(this.endpoint, options);\n } else if (protocolStr === 'ws' || protocolStr === 'wss') {\n const options = {\n headers: {\n 'User-Agent': `Subquery-Node ${packageVersion}`,\n },\n clientConfig: {\n keepAlive: true,\n },\n };\n if ((searchParams as any).apiKey) {\n (options.headers as any).apiKey = searchParams.get('apiKey');\n }\n\n provider = new Web3WsProvider(endpoint, options);\n } else {\n throw new Error(`Unsupported protocol: ${protocol}`);\n }\n\n this.client = new Web3Provider(provider);\n }\n\n async init(): Promise<void> {\n this.genesisBlock = await this.client.send('eth_getBlockByNumber', [\n hexValue(0),\n true,\n ]);\n logger.info(this.endpoint);\n\n this.chainId = await this.client.send('net_version', []);\n }\n\n async getLastHeight(): Promise<number> {\n return this.client.getBlockNumber();\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 getFinalizedBlockHeight(): Promise<number> {\n // Doesn't seem to be a difference between finalized and latest\n return this.client.getBlockNumber();\n }\n\n async getBlockByHeight(height: number): Promise<Block> {\n return this.client.getBlock(height);\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => {\n try {\n // Fetch Block\n const block_promise = await this.client.send('eth_getBlockByNumber', [\n hexValue(num),\n true,\n ]);\n\n const block = formatBlock(block_promise);\n //const block = this.client.formatter.blockWithTransactions(rawBlock);\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n // Get transaction receipts\n const transactions = await Promise.all(\n block.transactions.map(async (tx) => {\n //logger.info(JSON.stringify(tx))\n const transaction = formatTransaction(tx);\n const receipt = await this.client.send(\n 'eth_getTransactionReceipt',\n [tx.hash],\n );\n\n transaction.receipt = formatReceipt(receipt, block);\n return transaction;\n }),\n );\n return new EthereumBlockWrapped(block, transactions);\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;AAGpB,4CAA+C;AAE/C,wDAA8E;AAE9E,gDAA6C;AAS7C,4CAA0E;AAC1E,qDAAwD;AACxD,qDAI0B;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,CAAC;SAC5D;KACF;IAED,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAa,WAAW;IAMtB,YAAo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AC;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;AApLD,kCAoLC","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 } 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 { 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 constructor(private endpoint: string) {\n const { hostname, pathname, port, protocol, searchParams } = new URL(\n endpoint,\n );\n\n const protocolStr = protocol.replace(':', '');\n\n if (protocolStr === 'https' || protocolStr === 'http') {\n const connection: ConnectionInfo = {\n url: this.endpoint,\n headers: {\n 'User-Agent': `Subquery-Node ${packageVersion}`,\n },\n };\n if ((searchParams as any).apiKey) {\n (connection.headers as any).apiKey = searchParams.get('apiKey');\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 getLastHeight(): Promise<number> {\n return this.client.getBlockNumber();\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 getFinalizedBlockHeight(): Promise<number> {\n // Doesn't seem to be a difference between finalized and latest\n return this.client.getBlockNumber();\n }\n\n async getBlockByHeight(height: number): Promise<Block> {\n return this.client.getBlock(height);\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => {\n try {\n // Fetch Block\n const block_promise = await this.client.send('eth_getBlockByNumber', [\n hexValue(num),\n true,\n ]);\n\n const block = formatBlock(block_promise);\n\n //const block = this.client.formatter.blockWithTransactions(rawBlock);\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n // Get transaction receipts\n const transactions = await Promise.all(\n block.transactions.map(async (tx) => {\n //logger.info(JSON.stringify(tx))\n const transaction = formatTransaction(tx);\n const receipt = await this.client.getTransactionReceipt(tx.hash);\n\n transaction.receipt = formatReceipt(receipt, block);\n return transaction;\n }),\n );\n return new EthereumBlockWrapped(block, transactions);\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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@subql/node-ethereum",
3
- "version": "1.10.1-2",
3
+ "version": "1.10.1-3",
4
4
  "description": "",
5
5
  "author": "Ian He",
6
6
  "license": "Apache-2.0",
@@ -74,5 +74,5 @@
74
74
  "/dist",
75
75
  "/bin"
76
76
  ],
77
- "stableVersion": "1.10.1-1"
77
+ "stableVersion": "1.10.1-2"
78
78
  }