forked from MetaMask/eth-json-rpc-filters
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetBlocksForRange.js
68 lines (61 loc) · 1.95 KB
/
getBlocksForRange.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
module.exports = getBlocksForRange
async function getBlocksForRange({ provider, fromBlock, toBlock }) {
if (!fromBlock) fromBlock = toBlock
const fromBlockNumber = hexToInt(fromBlock)
const toBlockNumber = hexToInt(toBlock)
const blockCountToQuery = toBlockNumber - fromBlockNumber + 1
// load all blocks from old to new (inclusive)
const missingBlockNumbers = Array(blockCountToQuery).fill()
.map((_,index) => fromBlockNumber + index)
.map(intToHex)
const blockBodies = await Promise.all(
missingBlockNumbers.map(blockNum => query(provider, 'eth_getBlockByNumber', [blockNum, false]))
)
return blockBodies
}
function hexToInt(hexString) {
if (hexString === undefined || hexString === null) return hexString
return Number.parseInt(hexString, 16)
}
function incrementHexInt(hexString){
if (hexString === undefined || hexString === null) return hexString
const value = hexToInt(hexString)
return intToHex(value + 1)
}
function intToHex(int) {
if (int === undefined || int === null) return int
const hexString = int.toString(16)
return '0x' + hexString
}
function sendAsync(provider, request) {
return new Promise((resolve, reject) => {
provider.sendAsync(request, (error, response) => {
if (error) {
reject(error);
} else if (response.error) {
reject(response.error);
} else if (response.result) {
resolve(response.result);
} else {
reject(new Error("Result was empty"));
}
});
});
}
async function query(provider, method, params) {
for (let i = 0; i < 3; i++) {
try {
return await sendAsync(provider, {
id: 1,
jsonrpc: "2.0",
method,
params,
});
} catch (error) {
console.error(
`provider.sendAsync failed: ${error.stack || error.message || error}`
);
}
}
throw new Error(`Block not found for params: ${JSON.stringify(params)}`);
}