@subql/node-ethereum 0.4.1-8 → 0.4.1-storeCache-0.0.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.
- package/CHANGELOG.md +1 -0
- package/README.md +3 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/ethereum/api.ethereum.d.ts +8 -4
- package/dist/ethereum/api.ethereum.js +70 -49
- package/dist/ethereum/api.ethereum.js.map +1 -1
- package/dist/ethereum/api.service.ethereum.js +1 -1
- package/dist/ethereum/api.service.ethereum.js.map +1 -1
- package/dist/ethereum/block.ethereum.d.ts +1 -1
- package/dist/ethereum/block.ethereum.js +9 -12
- package/dist/ethereum/block.ethereum.js.map +1 -1
- package/dist/ethereum/ethers/json-rpc-batch-provider.d.ts +21 -0
- package/dist/ethereum/ethers/json-rpc-batch-provider.js +102 -0
- package/dist/ethereum/ethers/json-rpc-batch-provider.js.map +1 -0
- package/dist/ethereum/ethers/json-rpc-provider.d.ts +7 -0
- package/dist/ethereum/ethers/json-rpc-provider.js +68 -0
- package/dist/ethereum/ethers/json-rpc-provider.js.map +1 -0
- package/dist/ethereum/ethers/web/_version.d.ts +1 -0
- package/dist/ethereum/ethers/web/_version.js +6 -0
- package/dist/ethereum/ethers/web/_version.js.map +1 -0
- package/dist/ethereum/ethers/web/geturl.d.ts +3 -0
- package/dist/ethereum/ethers/web/geturl.js +116 -0
- package/dist/ethereum/ethers/web/geturl.js.map +1 -0
- package/dist/ethereum/ethers/web/index.d.ts +49 -0
- package/dist/ethereum/ethers/web/index.js +433 -0
- package/dist/ethereum/ethers/web/index.js.map +1 -0
- package/dist/ethereum/ethers/web/types.d.ts +26 -0
- package/dist/ethereum/ethers/web/types.js +4 -0
- package/dist/ethereum/ethers/web/types.js.map +1 -0
- package/dist/ethereum/utils.ethereum.d.ts +1 -1
- package/dist/ethereum/utils.ethereum.js +16 -3
- package/dist/ethereum/utils.ethereum.js.map +1 -1
- package/dist/indexer/blockDispatcher/block-dispatcher.service.d.ts +8 -15
- package/dist/indexer/blockDispatcher/block-dispatcher.service.js +20 -108
- package/dist/indexer/blockDispatcher/block-dispatcher.service.js.map +1 -1
- package/dist/indexer/blockDispatcher/ethereum-block-dispatcher.d.ts +4 -0
- package/dist/indexer/blockDispatcher/ethereum-block-dispatcher.js +5 -0
- package/dist/indexer/blockDispatcher/ethereum-block-dispatcher.js.map +1 -0
- package/dist/indexer/blockDispatcher/index.d.ts +2 -2
- package/dist/indexer/blockDispatcher/index.js.map +1 -1
- package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.d.ts +12 -17
- package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js +48 -134
- package/dist/indexer/blockDispatcher/worker-block-dispatcher.service.js.map +1 -1
- package/dist/indexer/dynamic-ds.service.d.ts +3 -22
- package/dist/indexer/dynamic-ds.service.js +4 -91
- package/dist/indexer/dynamic-ds.service.js.map +1 -1
- package/dist/indexer/fetch.module.js +24 -6
- package/dist/indexer/fetch.module.js.map +1 -1
- package/dist/indexer/fetch.service.d.ts +3 -3
- package/dist/indexer/fetch.service.js +40 -39
- package/dist/indexer/fetch.service.js.map +1 -1
- package/dist/indexer/indexer.manager.d.ts +5 -17
- package/dist/indexer/indexer.manager.js +25 -70
- package/dist/indexer/indexer.manager.js.map +1 -1
- package/dist/indexer/indexer.module.js +25 -2
- package/dist/indexer/indexer.module.js.map +1 -1
- package/dist/indexer/project.service.d.ts +5 -10
- package/dist/indexer/project.service.js +49 -100
- package/dist/indexer/project.service.js.map +1 -1
- package/dist/indexer/sandbox.service.js +6 -1
- package/dist/indexer/sandbox.service.js.map +1 -1
- package/dist/indexer/unfinalizedBlocks.service.d.ts +12 -12
- package/dist/indexer/unfinalizedBlocks.service.js +33 -38
- package/dist/indexer/unfinalizedBlocks.service.js.map +1 -1
- package/dist/indexer/unfinalizedBlocks.spec.js +41 -34
- package/dist/indexer/unfinalizedBlocks.spec.js.map +1 -1
- package/dist/indexer/worker/worker.d.ts +22 -8
- package/dist/indexer/worker/worker.js +14 -7
- package/dist/indexer/worker/worker.js.map +1 -1
- package/dist/indexer/worker/worker.service.d.ts +2 -2
- package/dist/indexer/worker/worker.service.js +11 -4
- package/dist/indexer/worker/worker.service.js.map +1 -1
- package/dist/indexer/worker/worker.unfinalizedBlocks.service.d.ts +11 -0
- package/dist/indexer/worker/worker.unfinalizedBlocks.service.js +32 -0
- package/dist/indexer/worker/worker.unfinalizedBlocks.service.js.map +1 -0
- package/dist/init.js +2 -2
- package/dist/init.js.map +1 -1
- package/dist/meta/meta.module.js +8 -0
- package/dist/meta/meta.module.js.map +1 -1
- package/dist/meta/meta.service.d.ts +18 -3
- package/dist/meta/meta.service.js +89 -5
- package/dist/meta/meta.service.js.map +1 -1
- package/dist/subcommands/forceClean.service.js +8 -4
- package/dist/subcommands/forceClean.service.js.map +1 -1
- package/dist/subcommands/reindex.init.js +5 -1
- package/dist/subcommands/reindex.init.js.map +1 -1
- package/dist/subcommands/reindex.module.js +8 -0
- package/dist/subcommands/reindex.module.js.map +1 -1
- package/dist/subcommands/reindex.service.d.ts +4 -1
- package/dist/subcommands/reindex.service.js +21 -10
- package/dist/subcommands/reindex.service.js.map +1 -1
- package/dist/utils/project.d.ts +1 -0
- package/dist/utils/project.js +13 -1
- package/dist/utils/project.js.map +1 -1
- package/dist/utils/reindex.d.ts +2 -1
- package/dist/utils/reindex.js +6 -2
- package/dist/utils/reindex.js.map +1 -1
- package/dist/utils/string.js +10 -2
- package/dist/utils/string.js.map +1 -1
- package/dist/yargs.d.ts +85 -53
- package/dist/yargs.js +103 -71
- package/dist/yargs.js.map +1 -1
- package/package.json +9 -9
- package/dist/indexer/blockDispatcher/base-block-dispatcher.d.ts +0 -40
- package/dist/indexer/blockDispatcher/base-block-dispatcher.js +0 -99
- package/dist/indexer/blockDispatcher/base-block-dispatcher.js.map +0 -1
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
import { Block, TransactionReceipt } from '@ethersproject/abstract-provider';
|
|
2
|
+
import { EventEmitter2 } from '@nestjs/event-emitter';
|
|
2
3
|
import { RuntimeDataSourceV0_2_0 } from '@subql/common-ethereum';
|
|
3
4
|
import { ApiWrapper, BlockWrapper, EthereumBlockWrapper, EthereumTransaction, EthereumResult, EthereumLog } from '@subql/types-ethereum';
|
|
5
|
+
import { EthereumBlockWrapped } from './block.ethereum';
|
|
4
6
|
export declare class EthereumApi implements ApiWrapper<EthereumBlockWrapper> {
|
|
5
7
|
private endpoint;
|
|
8
|
+
private eventEmitter;
|
|
6
9
|
private client;
|
|
7
10
|
private genesisBlock;
|
|
8
11
|
private contractInterfaces;
|
|
9
12
|
private chainId;
|
|
10
|
-
private
|
|
11
|
-
constructor(endpoint: string);
|
|
13
|
+
private supportsFinalization;
|
|
14
|
+
constructor(endpoint: string, eventEmitter: EventEmitter2);
|
|
12
15
|
init(): Promise<void>;
|
|
16
|
+
private injectClient;
|
|
13
17
|
getFinalizedBlockHeight(): Promise<number>;
|
|
14
18
|
getBestBlockHeight(): Promise<number>;
|
|
15
19
|
getRuntimeChain(): string;
|
|
@@ -17,9 +21,9 @@ export declare class EthereumApi implements ApiWrapper<EthereumBlockWrapper> {
|
|
|
17
21
|
getGenesisHash(): string;
|
|
18
22
|
getSpecName(): string;
|
|
19
23
|
getBlockByHeightOrHash(heightOrHash: number | string): Promise<Block>;
|
|
20
|
-
getBlockPromise
|
|
24
|
+
private getBlockPromise;
|
|
21
25
|
getTransactionReceipt(transactionHash: string | Promise<string>): Promise<TransactionReceipt>;
|
|
22
|
-
fetchBlock(
|
|
26
|
+
fetchBlock(blockNumber: number, includeTx?: boolean): Promise<EthereumBlockWrapped>;
|
|
23
27
|
fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]>;
|
|
24
28
|
freezeApi(processor: any, blockContent: BlockWrapper): void;
|
|
25
29
|
private buildInterface;
|
|
@@ -6,15 +6,16 @@ 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"));
|
|
10
|
+
const http_1 = __importDefault(require("http"));
|
|
11
|
+
const https_1 = __importDefault(require("https"));
|
|
11
12
|
const abi_1 = require("@ethersproject/abi");
|
|
12
|
-
const bignumber_1 = require("@ethersproject/bignumber");
|
|
13
13
|
const providers_1 = require("@ethersproject/providers");
|
|
14
14
|
const node_core_1 = require("@subql/node-core");
|
|
15
15
|
const utils_1 = require("ethers/lib/utils");
|
|
16
16
|
const project_1 = require("../utils/project");
|
|
17
17
|
const block_ethereum_1 = require("./block.ethereum");
|
|
18
|
+
const json_rpc_batch_provider_1 = require("./ethers/json-rpc-batch-provider");
|
|
18
19
|
const safe_api_1 = __importDefault(require("./safe-api"));
|
|
19
20
|
const utils_ethereum_1 = require("./utils.ethereum");
|
|
20
21
|
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
@@ -36,24 +37,33 @@ async function loadAssets(ds) {
|
|
|
36
37
|
return res;
|
|
37
38
|
}
|
|
38
39
|
class EthereumApi {
|
|
39
|
-
constructor(endpoint) {
|
|
40
|
+
constructor(endpoint, eventEmitter) {
|
|
40
41
|
this.endpoint = endpoint;
|
|
42
|
+
this.eventEmitter = eventEmitter;
|
|
41
43
|
this.contractInterfaces = {};
|
|
42
|
-
|
|
44
|
+
// Ethereum POS
|
|
45
|
+
this.supportsFinalization = true;
|
|
43
46
|
const { hostname, pathname, port, protocol, searchParams } = new URL(endpoint);
|
|
44
47
|
const protocolStr = protocol.replace(':', '');
|
|
45
|
-
logger.info(
|
|
48
|
+
logger.info(`Api host: ${hostname}, method: ${protocolStr}`);
|
|
46
49
|
if (protocolStr === 'https' || protocolStr === 'http') {
|
|
47
50
|
const connection = {
|
|
48
51
|
url: this.endpoint.split('?')[0],
|
|
49
52
|
headers: {
|
|
50
53
|
'User-Agent': `Subquery-Node ${packageVersion}`,
|
|
51
54
|
},
|
|
55
|
+
allowGzip: true,
|
|
56
|
+
throttleLimit: 5,
|
|
57
|
+
throttleSlotInterval: 1,
|
|
58
|
+
agents: {
|
|
59
|
+
http: new http_1.default.Agent({ keepAlive: true /*, maxSockets: 100*/ }),
|
|
60
|
+
https: new https_1.default.Agent({ keepAlive: true /*, maxSockets: 100*/ }),
|
|
61
|
+
},
|
|
52
62
|
};
|
|
53
63
|
searchParams.forEach((value, name, searchParams) => {
|
|
54
64
|
connection.headers[name] = value;
|
|
55
65
|
});
|
|
56
|
-
this.client = new
|
|
66
|
+
this.client = new json_rpc_batch_provider_1.JsonRpcBatchProvider(connection);
|
|
57
67
|
}
|
|
58
68
|
else if (protocolStr === 'ws' || protocolStr === 'wss') {
|
|
59
69
|
this.client = new providers_1.WebSocketProvider(this.endpoint);
|
|
@@ -63,14 +73,38 @@ class EthereumApi {
|
|
|
63
73
|
}
|
|
64
74
|
}
|
|
65
75
|
async init() {
|
|
76
|
+
this.injectClient();
|
|
66
77
|
this.genesisBlock = await this.client.getBlock(0);
|
|
67
78
|
this.chainId = (await this.client.getNetwork()).chainId;
|
|
68
79
|
}
|
|
80
|
+
injectClient() {
|
|
81
|
+
const orig = this.client.send.bind(this.client);
|
|
82
|
+
Object.defineProperty(this.client, 'send', {
|
|
83
|
+
value: (...args) => {
|
|
84
|
+
this.eventEmitter.emit('rpcCall');
|
|
85
|
+
return orig(...args);
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
}
|
|
69
89
|
async getFinalizedBlockHeight() {
|
|
70
|
-
|
|
90
|
+
try {
|
|
91
|
+
if (this.supportsFinalization) {
|
|
92
|
+
return (await this.client.getBlock('finalised')).number;
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
// TODO make number of blocks finalised configurable
|
|
96
|
+
return (await this.getBestBlockHeight()) - 15; // Consider 15 blocks finalized
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
// TODO handle specific error for this
|
|
101
|
+
this.supportsFinalization = false;
|
|
102
|
+
return this.getFinalizedBlockHeight();
|
|
103
|
+
}
|
|
71
104
|
}
|
|
72
105
|
async getBestBlockHeight() {
|
|
73
|
-
|
|
106
|
+
const tag = this.supportsFinalization ? 'safe' : 'latest';
|
|
107
|
+
return (await this.client.getBlock(tag)).number;
|
|
74
108
|
}
|
|
75
109
|
getRuntimeChain() {
|
|
76
110
|
return 'ethereum';
|
|
@@ -85,62 +119,49 @@ class EthereumApi {
|
|
|
85
119
|
return 'ethereum';
|
|
86
120
|
}
|
|
87
121
|
async getBlockByHeightOrHash(heightOrHash) {
|
|
122
|
+
if (typeof heightOrHash === 'number') {
|
|
123
|
+
heightOrHash = (0, utils_1.hexValue)(heightOrHash);
|
|
124
|
+
}
|
|
88
125
|
return this.client.getBlock(heightOrHash);
|
|
89
126
|
}
|
|
90
|
-
async getBlockPromise(num) {
|
|
91
|
-
|
|
127
|
+
async getBlockPromise(num, includeTx = true) {
|
|
128
|
+
const rawBlock = await this.client.send('eth_getBlockByNumber', [
|
|
129
|
+
(0, utils_1.hexValue)(num),
|
|
130
|
+
includeTx,
|
|
131
|
+
]);
|
|
132
|
+
const block = (0, utils_ethereum_1.formatBlock)(rawBlock);
|
|
133
|
+
block.stateRoot = this.client.formatter.hash(block.stateRoot);
|
|
134
|
+
return block;
|
|
92
135
|
}
|
|
93
136
|
async getTransactionReceipt(transactionHash) {
|
|
94
137
|
return (0, project_1.retryOnFailEth)(this.client.getTransactionReceipt.bind(this.client, transactionHash));
|
|
95
138
|
}
|
|
96
|
-
async fetchBlock(
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
});
|
|
112
|
-
return new block_ethereum_1.EthereumBlockWrapped(block, txs);
|
|
113
|
-
}
|
|
114
|
-
catch (e) {
|
|
115
|
-
// Method not avaialble https://eips.ethereum.org/EIPS/eip-1474
|
|
116
|
-
if (((_a = e === null || e === void 0 ? void 0 : e.error) === null || _a === void 0 ? void 0 : _a.code) === -32601) {
|
|
117
|
-
logger.warn(`The endpoint doesn't support 'eth_getBlockReceipts', individual receipts will be fetched instead, this will greatly impact performance.`);
|
|
118
|
-
this.endpointSupportsGetBlockReceipts = false;
|
|
119
|
-
// Should continue and use old method here
|
|
120
|
-
}
|
|
121
|
-
else {
|
|
122
|
-
throw e;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
const transactions = await Promise.all(block.transactions.map(async (tx) => {
|
|
127
|
-
const transaction = (0, utils_ethereum_1.formatTransaction)(tx);
|
|
128
|
-
const receipt = await this.getTransactionReceipt(tx.hash);
|
|
129
|
-
transaction.receipt = (0, utils_ethereum_1.formatReceipt)(receipt, block);
|
|
130
|
-
return transaction;
|
|
131
|
-
}));
|
|
132
|
-
return new block_ethereum_1.EthereumBlockWrapped(block, transactions);
|
|
139
|
+
async fetchBlock(blockNumber, includeTx) {
|
|
140
|
+
const [block, logs] = await Promise.all([
|
|
141
|
+
this.getBlockPromise(blockNumber, includeTx),
|
|
142
|
+
this.client.getLogs({
|
|
143
|
+
fromBlock: (0, utils_1.hexValue)(blockNumber),
|
|
144
|
+
toBlock: (0, utils_1.hexValue)(blockNumber),
|
|
145
|
+
}),
|
|
146
|
+
]);
|
|
147
|
+
const ret = new block_ethereum_1.EthereumBlockWrapped(block, includeTx
|
|
148
|
+
? block.transactions.map((tx) => (Object.assign(Object.assign({}, (0, utils_ethereum_1.formatTransaction)(tx)), {
|
|
149
|
+
// TODO memoise
|
|
150
|
+
receipt: () => this.getTransactionReceipt(tx).then((r) => (0, utils_ethereum_1.formatReceipt)(r, block)) })))
|
|
151
|
+
: [], logs.map((l) => (0, utils_ethereum_1.formatLog)(l, block)));
|
|
152
|
+
this.eventEmitter.emit('fetchBlock');
|
|
153
|
+
return ret;
|
|
133
154
|
}
|
|
134
155
|
async fetchBlocks(bufferBlocks) {
|
|
135
156
|
return Promise.all(bufferBlocks.map(async (num) => {
|
|
136
157
|
try {
|
|
137
158
|
// Fetch Block
|
|
138
|
-
return await this.fetchBlock(num);
|
|
159
|
+
return await this.fetchBlock(num, true);
|
|
139
160
|
}
|
|
140
161
|
catch (e) {
|
|
141
162
|
// Wrap error from an axios error to fix issue with error being undefined
|
|
142
163
|
const error = new Error(e.message);
|
|
143
|
-
logger.error(
|
|
164
|
+
logger.error(e, `Failed to fetch block at height ${num}`);
|
|
144
165
|
throw error;
|
|
145
166
|
}
|
|
146
167
|
}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.ethereum.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;;;;AAEtC,oDAA4B;AAC5B,4CAAoB;AACpB,4CAA+C;AAE/C,wDAAqD;AACrD,wDAA8E;AAE9E,gDAA6C;AAS7C,4CAA0E;AAC1E,8CAAkD;AAClD,qDAAwD;AACxD,0DAAyC;AACzC,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,C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E,CAAC,CAAC;YAC9D,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AA3OD,kCA2OC","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport assert from 'assert';\nimport fs from 'fs';\nimport { Interface } from '@ethersproject/abi';\nimport { Block, TransactionReceipt } from '@ethersproject/abstract-provider';\nimport { BigNumber } from '@ethersproject/bignumber';\nimport { JsonRpcProvider, WebSocketProvider } from '@ethersproject/providers';\nimport { RuntimeDataSourceV0_2_0 } from '@subql/common-ethereum';\nimport { getLogger } from '@subql/node-core';\nimport {\n ApiWrapper,\n BlockWrapper,\n EthereumBlockWrapper,\n EthereumTransaction,\n EthereumResult,\n EthereumLog,\n} from '@subql/types-ethereum';\nimport { ConnectionInfo, hexDataSlice, hexValue } from 'ethers/lib/utils';\nimport { retryOnFailEth } from '../utils/project';\nimport { EthereumBlockWrapped } from './block.ethereum';\nimport SafeEthProvider from './safe-api';\nimport {\n formatBlock,\n formatReceipt,\n formatTransaction,\n} from './utils.ethereum';\n\n// eslint-disable-next-line @typescript-eslint/no-var-requires\nconst { version: packageVersion } = require('../../package.json');\n\nconst logger = getLogger('api.ethereum');\n\nasync function loadAssets(\n ds: RuntimeDataSourceV0_2_0,\n): Promise<Record<string, string>> {\n if (!ds.assets) {\n return {};\n }\n const res: Record<string, string> = {};\n\n for (const [name, { file }] of Object.entries(ds.assets)) {\n try {\n res[name] = await fs.promises.readFile(file, { encoding: 'utf8' });\n } catch (e) {\n throw new Error(`Failed to load datasource asset ${file}`);\n }\n }\n\n return res;\n}\n\nexport class EthereumApi implements ApiWrapper<EthereumBlockWrapper> {\n private client: JsonRpcProvider;\n private genesisBlock: Record<string, any>;\n private contractInterfaces: Record<string, Interface> = {};\n private chainId: number;\n\n private endpointSupportsGetBlockReceipts = true;\n\n constructor(private endpoint: string) {\n const { hostname, pathname, port, protocol, searchParams } = new URL(\n endpoint,\n );\n\n const protocolStr = protocol.replace(':', '');\n\n logger.info(this.endpoint.split('?')[0]);\n if (protocolStr === 'https' || protocolStr === 'http') {\n const connection: ConnectionInfo = {\n url: this.endpoint.split('?')[0],\n headers: {\n 'User-Agent': `Subquery-Node ${packageVersion}`,\n },\n };\n searchParams.forEach((value, name, searchParams) => {\n (connection.headers as any)[name] = value;\n });\n this.client = new JsonRpcProvider(connection);\n } else if (protocolStr === 'ws' || protocolStr === 'wss') {\n this.client = new WebSocketProvider(this.endpoint);\n } else {\n throw new Error(`Unsupported protocol: ${protocol}`);\n }\n }\n\n async init(): Promise<void> {\n this.genesisBlock = await this.client.getBlock(0);\n\n this.chainId = (await this.client.getNetwork()).chainId;\n }\n\n async getFinalizedBlockHeight(): Promise<number> {\n return (await this.client.getBlock('finalized')).number;\n }\n\n async getBestBlockHeight(): Promise<number> {\n return (await this.client.getBlock('safe')).number;\n }\n\n getRuntimeChain(): string {\n return 'ethereum';\n }\n\n getChainId(): number {\n return this.chainId;\n }\n\n getGenesisHash(): string {\n return this.genesisBlock.hash;\n }\n\n getSpecName(): string {\n return 'ethereum';\n }\n\n async getBlockByHeightOrHash(heightOrHash: number | string): Promise<Block> {\n return this.client.getBlock(heightOrHash);\n }\n\n async getBlockPromise(num: number): Promise<any> {\n return retryOnFailEth(() =>\n this.client.send('eth_getBlockByNumber', [hexValue(num), true]),\n );\n }\n\n async getTransactionReceipt(\n transactionHash: string | Promise<string>,\n ): Promise<TransactionReceipt> {\n return retryOnFailEth<TransactionReceipt>(\n this.client.getTransactionReceipt.bind(this.client, transactionHash),\n );\n }\n async fetchBlock(num: number): Promise<EthereumBlockWrapper> {\n const block_promise = await this.getBlockPromise(num);\n\n const block = formatBlock(block_promise);\n block.stateRoot = this.client.formatter.hash(block.stateRoot);\n\n if (this.endpointSupportsGetBlockReceipts) {\n try {\n const rawReceipts: any[] = await this.client.send(\n 'eth_getBlockReceipts',\n [hexValue(block.number)],\n );\n\n const receipts = rawReceipts.map((receipt) =>\n formatReceipt(receipt, block),\n );\n\n const txs = block.transactions.map((tx) => {\n const transaction = formatTransaction(tx);\n transaction.receipt =\n receipts[BigNumber.from(transaction.transactionIndex).toNumber()];\n\n assert(\n transaction.hash === transaction.receipt.transactionHash,\n 'Failed to match receipt to transaction',\n );\n\n return transaction;\n });\n\n return new EthereumBlockWrapped(block, txs);\n } catch (e) {\n // Method not avaialble https://eips.ethereum.org/EIPS/eip-1474\n if (e?.error?.code === -32601) {\n logger.warn(\n `The endpoint doesn't support 'eth_getBlockReceipts', individual receipts will be fetched instead, this will greatly impact performance.`,\n );\n this.endpointSupportsGetBlockReceipts = false;\n\n // Should continue and use old method here\n } else {\n throw e;\n }\n }\n }\n\n const transactions = await Promise.all(\n block.transactions.map(async (tx) => {\n const transaction = formatTransaction(tx);\n const receipt = await this.getTransactionReceipt(tx.hash);\n transaction.receipt = formatReceipt(receipt, block);\n return transaction;\n }),\n );\n return new EthereumBlockWrapped(block, transactions);\n }\n\n async fetchBlocks(bufferBlocks: number[]): Promise<EthereumBlockWrapper[]> {\n return Promise.all(\n bufferBlocks.map(async (num) => {\n try {\n // Fetch Block\n return await this.fetchBlock(num);\n } catch (e) {\n // Wrap error from an axios error to fix issue with error being undefined\n const error = new Error(e.message);\n logger.error(error, `Failed to fetch block at height ${num}`);\n throw error;\n }\n }),\n );\n }\n\n freezeApi(processor: any, blockContent: BlockWrapper): void {\n processor.freeze(\n new SafeEthProvider(this.client, blockContent.blockHeight),\n 'api',\n );\n }\n\n private buildInterface(\n abiName: string,\n assets: Record<string, string>,\n ): Interface | undefined {\n if (!assets[abiName]) {\n throw new Error(`ABI named \"${abiName}\" not referenced in assets`);\n }\n\n // This assumes that all datasources have a different abi name or they are the same abi\n if (!this.contractInterfaces[abiName]) {\n // Constructing the interface validates the ABI\n try {\n let abiObj = JSON.parse(assets[abiName]);\n\n /*\n * Allows parsing JSON artifacts as well as ABIs\n * https://trufflesuite.github.io/artifact-updates/background.html#what-are-artifacts\n */\n if (!Array.isArray(abiObj) && abiObj.abi) {\n abiObj = abiObj.abi;\n }\n\n this.contractInterfaces[abiName] = new Interface(abiObj);\n } catch (e) {\n logger.error(`Unable to parse ABI: ${e.message}`);\n throw new Error('ABI is invalid');\n }\n }\n\n return this.contractInterfaces[abiName];\n }\n\n async parseLog<T extends EthereumResult = EthereumResult>(\n log: EthereumLog,\n ds: RuntimeDataSourceV0_2_0,\n ): Promise<EthereumLog<T> | EthereumLog> {\n try {\n if (!ds?.options?.abi) {\n logger.warn('No ABI provided for datasource');\n return log;\n }\n const iface = this.buildInterface(ds.options.abi, await loadAssets(ds));\n return {\n ...log,\n args: iface?.parseLog(log).args as T,\n };\n } catch (e) {\n logger.warn(`Failed to parse log data: ${e.message}`);\n return log;\n }\n }\n\n async parseTransaction<T extends EthereumResult = EthereumResult>(\n transaction: EthereumTransaction,\n ds: RuntimeDataSourceV0_2_0,\n ): Promise<EthereumTransaction<T> | EthereumTransaction> {\n try {\n if (!ds?.options?.abi) {\n logger.warn('No ABI provided for datasource');\n return transaction;\n }\n const assets = await loadAssets(ds);\n const iface = this.buildInterface(ds.options.abi, assets);\n const func = iface.getFunction(hexDataSlice(transaction.input, 0, 4));\n const args = iface.decodeFunctionData(func, transaction.input) as T;\n return {\n ...transaction,\n args,\n };\n } catch (e) {\n logger.warn(`Failed to parse transaction data: ${e.message}`);\n return transaction;\n }\n }\n}\n"]}
|
|
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,wDAA6D;AAG7D,gDAA6C;AAS7C,4CAA0D;AAC1D,8CAAkD;AAClD,qDAAwD;AACxD,8EAAwE;AAGxE,0DAAyC;AACzC,qDAK0B;AAE1B,8DAA8D;AAC9D,MAAM,EAAE,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,oBAAoB,CAAC,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C,GAAG,EAAE,IAAS,IACpC;SACH;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,CAAC,IAAI,CAAC,6BAA6B,CAAC,CAAC,OAAO,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;AA1PD,kCA0PC","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 { 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 { 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\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, private eventEmitter: EventEmitter2) {\n const { hostname, pathname, port, protocol, searchParams } = new URL(\n endpoint,\n );\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: {\n http: new http.Agent({ keepAlive: true /*, maxSockets: 100*/ }),\n https: new https.Agent({ keepAlive: true /*, maxSockets: 100*/ }),\n },\n };\n searchParams.forEach((value, name, searchParams) => {\n (connection.headers as any)[name] = value;\n });\n this.client = new JsonRpcBatchProvider(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 this.chainId = (await this.client.getNetwork()).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('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 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).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) => {\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"]}
|
|
@@ -36,7 +36,7 @@ let EthereumApiService = class EthereumApiService extends node_core_1.ApiService
|
|
|
36
36
|
logger.error(Object.keys(e));
|
|
37
37
|
process.exit(1);
|
|
38
38
|
}
|
|
39
|
-
this.api = new api_ethereum_1.EthereumApi(network.endpoint);
|
|
39
|
+
this.api = new api_ethereum_1.EthereumApi(network.endpoint, this.eventEmitter);
|
|
40
40
|
await this.api.init();
|
|
41
41
|
this.networkMeta = {
|
|
42
42
|
chain: this.api.getRuntimeChain(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.service.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/api.service.ethereum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C,IAAI,CAAC,IAAI,GAAG,KAAK,CAAC;IACpB,CAAC;CACF,CAAA;AApDY,kBAAkB;IAD9B,IAAA,mBAAU,GAAE;IAGR,WAAA,IAAA,eAAM,EAAC,kBAAkB,CAAC,CAAA;qCAAU,iCAAe;QAC9B,6BAAa;GAH1B,kBAAkB,CAoD9B;AApDY,gDAAkB","sourcesContent":["// Copyright 2020-2022 OnFinality Limited authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Inject, Injectable } from '@nestjs/common';\nimport { EventEmitter2 } from '@nestjs/event-emitter';\nimport { ProjectNetworkV1_0_0 } from '@subql/common-ethereum';\nimport { ApiService, getLogger } from '@subql/node-core';\nimport { SubqueryProject } from '../configure/SubqueryProject';\nimport { EthereumApi } from './api.ethereum';\n\nconst logger = getLogger('api');\n\n@Injectable()\nexport class EthereumApiService extends ApiService {\n constructor(\n @Inject('ISubqueryProject') project: SubqueryProject,\n private eventEmitter: EventEmitter2,\n ) {\n super(project);\n }\n private _api: EthereumApi;\n\n async init(): Promise<EthereumApiService> {\n try {\n let network: ProjectNetworkV1_0_0;\n try {\n network = this.project.network;\n } catch (e) {\n logger.error(Object.keys(e));\n process.exit(1);\n }\n\n this.api = new EthereumApi(network.endpoint, this.eventEmitter);\n\n await this.api.init();\n this.networkMeta = {\n chain: this.api.getRuntimeChain(),\n specName: this.api.getSpecName(),\n genesisHash: this.api.getGenesisHash(),\n };\n\n if (network.chainId !== this.api.getChainId().toString()) {\n const err = new Error(\n `Network chainId doesn't match expected chainId. expected=\"${\n network.chainId\n }\" actual=\"${this.api.getChainId()}`,\n );\n logger.error(err, err.message);\n throw err;\n }\n\n return this;\n } catch (e) {\n logger.error(e, 'Failed to init api service');\n process.exit(1);\n }\n }\n\n get api(): EthereumApi {\n return this._api;\n }\n\n private set api(value: EthereumApi) {\n this._api = value;\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 =
|
|
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
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"block.ethereum.js","sourceRoot":"","sources":["../../src/ethereum/block.ethereum.ts"],"names":[],"mappings":";AAAA,gEAAgE;AAChE,sCAAsC;;;
|
|
1
|
+
{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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;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,21 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { JsonRpcProvider } from '@ethersproject/providers';
|
|
3
|
+
import { Networkish } from '@ethersproject/networks';
|
|
4
|
+
import { ConnectionInfo } from './web';
|
|
5
|
+
export declare class JsonRpcBatchProvider extends JsonRpcProvider {
|
|
6
|
+
_pendingBatchAggregator: NodeJS.Timer;
|
|
7
|
+
_pendingBatch: Array<{
|
|
8
|
+
request: {
|
|
9
|
+
method: string;
|
|
10
|
+
params: Array<any>;
|
|
11
|
+
id: number;
|
|
12
|
+
jsonrpc: '2.0';
|
|
13
|
+
};
|
|
14
|
+
resolve: (result: any) => void;
|
|
15
|
+
reject: (error: Error) => void;
|
|
16
|
+
}>;
|
|
17
|
+
constructor(url: string | ConnectionInfo, network?: Networkish);
|
|
18
|
+
send(method: string, params: Array<any>): Promise<any>;
|
|
19
|
+
flush(): void;
|
|
20
|
+
private runRequests;
|
|
21
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.JsonRpcBatchProvider = void 0;
|
|
4
|
+
/* eslint-disable */
|
|
5
|
+
const properties_1 = require("@ethersproject/properties");
|
|
6
|
+
const web_1 = require("@ethersproject/web");
|
|
7
|
+
const providers_1 = require("@ethersproject/providers");
|
|
8
|
+
// Experimental
|
|
9
|
+
class JsonRpcBatchProvider extends providers_1.JsonRpcProvider {
|
|
10
|
+
constructor(url, network) {
|
|
11
|
+
super(url, network);
|
|
12
|
+
}
|
|
13
|
+
send(method, params) {
|
|
14
|
+
const request = {
|
|
15
|
+
method: method,
|
|
16
|
+
params: params,
|
|
17
|
+
id: this._nextId++,
|
|
18
|
+
jsonrpc: '2.0',
|
|
19
|
+
};
|
|
20
|
+
if (this._pendingBatch == null) {
|
|
21
|
+
this._pendingBatch = [];
|
|
22
|
+
}
|
|
23
|
+
const inflightRequest = { request, resolve: null, reject: null };
|
|
24
|
+
const promise = new Promise((resolve, reject) => {
|
|
25
|
+
inflightRequest.resolve = resolve;
|
|
26
|
+
inflightRequest.reject = reject;
|
|
27
|
+
});
|
|
28
|
+
this._pendingBatch.push(inflightRequest);
|
|
29
|
+
if (!this._pendingBatchAggregator) {
|
|
30
|
+
// Schedule batch for next event loop + short duration
|
|
31
|
+
this._pendingBatchAggregator = setTimeout(() => {
|
|
32
|
+
this.runRequests();
|
|
33
|
+
}, 1);
|
|
34
|
+
}
|
|
35
|
+
if (this._pendingBatch.length > 10) {
|
|
36
|
+
this.flush();
|
|
37
|
+
}
|
|
38
|
+
return promise;
|
|
39
|
+
}
|
|
40
|
+
flush() {
|
|
41
|
+
if (this._pendingBatchAggregator) {
|
|
42
|
+
clearTimeout(this._pendingBatchAggregator);
|
|
43
|
+
this.runRequests();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
runRequests() {
|
|
47
|
+
// Get teh current batch and clear it, so new requests
|
|
48
|
+
// go into the next batch
|
|
49
|
+
const batch = this._pendingBatch;
|
|
50
|
+
this._pendingBatch = null;
|
|
51
|
+
this._pendingBatchAggregator = null;
|
|
52
|
+
// Get the request as an array of requests
|
|
53
|
+
const request = batch.map((inflight) => inflight.request);
|
|
54
|
+
this.emit('debug', {
|
|
55
|
+
action: 'requestBatch',
|
|
56
|
+
request: (0, properties_1.deepCopy)(request),
|
|
57
|
+
provider: this,
|
|
58
|
+
});
|
|
59
|
+
return (0, web_1.fetchJson)(this.connection, JSON.stringify(request)).then((result) => {
|
|
60
|
+
this.emit('debug', {
|
|
61
|
+
action: 'response',
|
|
62
|
+
request: request,
|
|
63
|
+
response: result,
|
|
64
|
+
provider: this,
|
|
65
|
+
});
|
|
66
|
+
// if (!Array.isArray(result)) {
|
|
67
|
+
// result = [result];
|
|
68
|
+
// }
|
|
69
|
+
// https://github.com/ethers-io/ethers.js/pull/2657
|
|
70
|
+
const resultMap = result.reduce((resultMap, payload) => {
|
|
71
|
+
resultMap[payload.id] = payload;
|
|
72
|
+
return resultMap;
|
|
73
|
+
}, {});
|
|
74
|
+
// For each result, feed it to the correct Promise, depending
|
|
75
|
+
// on whether it was a success or error
|
|
76
|
+
batch.forEach((inflightRequest) => {
|
|
77
|
+
const payload = resultMap[inflightRequest.request.id];
|
|
78
|
+
if (payload.error) {
|
|
79
|
+
const error = new Error(payload.error.message);
|
|
80
|
+
error.code = payload.error.code;
|
|
81
|
+
error.data = payload.error.data;
|
|
82
|
+
inflightRequest.reject(error);
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
inflightRequest.resolve(payload.result);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
} /*).catch(*/, (error) => {
|
|
89
|
+
this.emit('debug', {
|
|
90
|
+
action: 'response',
|
|
91
|
+
error: error,
|
|
92
|
+
request: request,
|
|
93
|
+
provider: this,
|
|
94
|
+
});
|
|
95
|
+
batch.forEach((inflightRequest) => {
|
|
96
|
+
inflightRequest.reject(error);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
exports.JsonRpcBatchProvider = JsonRpcBatchProvider;
|
|
102
|
+
//# sourceMappingURL=json-rpc-batch-provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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;AACrD,4CAA+C;AAE/C,wDAA2D;AAe3D,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,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,IAAI,CAAC,aAAa,IAAI,IAAI,EAAE;YAC9B,IAAI,CAAC,aAAa,GAAG,EAAE,CAAC;SACzB;QAED,MAAM,eAAe,GAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;QAEtE,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC9C,eAAe,CAAC,OAAO,GAAG,OAAO,CAAC;YAClC,eAAe,CAAC,MAAM,GAAG,M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AAe,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAChC,CAAC,CAAC,CAAC;QACL,CAAC,CACF,CAAC;IACJ,CAAC;CACF;AArHD,oDAqHC","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';\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)).then(\n (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 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 } /*).catch(*/,\n (error) => {\n this.emit('debug', {\n action: 'response',\n error: error,\n request: request,\n provider: this,\n });\n\n batch.forEach((inflightRequest) => {\n inflightRequest.reject(error);\n });\n },\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { JsonRpcProvider as BaseJsonRpcProvider } from '@ethersproject/providers';
|
|
2
|
+
import { Networkish } from '@ethersproject/networks';
|
|
3
|
+
import { ConnectionInfo } from './web';
|
|
4
|
+
export declare class JsonRpcProvider extends BaseJsonRpcProvider {
|
|
5
|
+
constructor(url: string | ConnectionInfo, network?: Networkish);
|
|
6
|
+
send(method: string, params: Array<any>): Promise<any>;
|
|
7
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.JsonRpcProvider = void 0;
|
|
4
|
+
/* eslint-disable */
|
|
5
|
+
const properties_1 = require("@ethersproject/properties");
|
|
6
|
+
const web_1 = require("@ethersproject/web");
|
|
7
|
+
const providers_1 = require("@ethersproject/providers");
|
|
8
|
+
function getResult(payload) {
|
|
9
|
+
if (payload.error) {
|
|
10
|
+
// @TODO: not any
|
|
11
|
+
const error = new Error(payload.error.message);
|
|
12
|
+
error.code = payload.error.code;
|
|
13
|
+
error.data = payload.error.data;
|
|
14
|
+
throw error;
|
|
15
|
+
}
|
|
16
|
+
return payload.result;
|
|
17
|
+
}
|
|
18
|
+
class JsonRpcProvider extends providers_1.JsonRpcProvider {
|
|
19
|
+
constructor(url, network) {
|
|
20
|
+
super(url, network);
|
|
21
|
+
}
|
|
22
|
+
send(method, params) {
|
|
23
|
+
const request = {
|
|
24
|
+
method: method,
|
|
25
|
+
params: params,
|
|
26
|
+
id: this._nextId++,
|
|
27
|
+
jsonrpc: '2.0',
|
|
28
|
+
};
|
|
29
|
+
this.emit('debug', {
|
|
30
|
+
action: 'request',
|
|
31
|
+
request: (0, properties_1.deepCopy)(request),
|
|
32
|
+
provider: this,
|
|
33
|
+
});
|
|
34
|
+
// We can expand this in the future to any call, but for now these
|
|
35
|
+
// are the biggest wins and do not require any serializing parameters.
|
|
36
|
+
const cache = ['eth_chainId', 'eth_blockNumber'].indexOf(method) >= 0;
|
|
37
|
+
if (cache && this._cache[method]) {
|
|
38
|
+
return this._cache[method];
|
|
39
|
+
}
|
|
40
|
+
const result = (0, web_1.fetchJson)(this.connection, JSON.stringify(request), getResult).then((result) => {
|
|
41
|
+
this.emit('debug', {
|
|
42
|
+
action: 'response',
|
|
43
|
+
request: request,
|
|
44
|
+
response: result,
|
|
45
|
+
provider: this,
|
|
46
|
+
});
|
|
47
|
+
return result;
|
|
48
|
+
}, (error) => {
|
|
49
|
+
this.emit('debug', {
|
|
50
|
+
action: 'response',
|
|
51
|
+
error: error,
|
|
52
|
+
request: request,
|
|
53
|
+
provider: this,
|
|
54
|
+
});
|
|
55
|
+
throw error;
|
|
56
|
+
});
|
|
57
|
+
// Cache the fetch, but clear it on the next event loop
|
|
58
|
+
if (cache) {
|
|
59
|
+
this._cache[method] = result;
|
|
60
|
+
setTimeout(() => {
|
|
61
|
+
this._cache[method] = null;
|
|
62
|
+
}, 0);
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
exports.JsonRpcProvider = JsonRpcProvider;
|
|
68
|
+
//# sourceMappingURL=json-rpc-provider.js.map
|