-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
getBlocksForRange.js
53 lines (47 loc) · 1.54 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
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)
let blockBodies = await Promise.all(
missingBlockNumbers.map(blockNum => query(provider, 'eth_getBlockByNumber', [blockNum, false]))
)
blockBodies = blockBodies.filter(block => block !== null);
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
}
async function query(provider, method, params) {
for (let i = 0; i < 3; i++) {
try {
return provider.request({
id: 1,
jsonrpc: "2.0",
method,
params,
});
} catch (error) {
console.error(
`provider.request failed: ${error.stack || error.message || error}`
);
}
}
return null;
}