-
Notifications
You must be signed in to change notification settings - Fork 32
/
0-streamBlocks.js
97 lines (85 loc) · 2.65 KB
/
0-streamBlocks.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const API = 'https://cosmoshub.stakesystems.io/';
import fetch from 'node-fetch';
import { decodeTxRaw } from "@cosmjs/proto-signing"
import { fromBase64,toHex} from "@cosmjs/encoding";
import { sha256 } from '@cosmjs/crypto';
let nextBlockNum = 0;
async function getLatestBlock() {
return new Promise((resolve) => {
fetch(API + "/blocks/latest").then(res => {
resolve(res.json());
});
})
}
async function getBlockByHeight(height) {
return new Promise((resolve) => {
fetch(API + `/blocks/${height}`).then(res => {
resolve(res.json());
});
})
}
async function getTxs(hash){
return new Promise((resolve) => {
fetch(API + `/txs/${hash}`).then(res => {
resolve(res.json());
});
})
}
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
function loadNextBlock() {
getLatestBlock().then(res => {
const { height } = res.block.header;
if (height >= nextBlockNum) {
console.log(nextBlockNum);
loadBlock(nextBlockNum);
nextBlockNum++;
} else {
sleep(3000).then(() => {
console.log(
'Waiting for the latest block',
height,
'now nextBlockNum',
nextBlockNum,
);
loadNextBlock();
})
}
}).catch(err => {
console.error("Call api failed", err);
sleep(3000).then(() => {
console.log('Retry loadNextBlock', nextBlockNum);
loadNextBlock();
});
})
}
async function loadBlock(blockNum) {
getBlockByHeight(blockNum).then(res => {
let txs = res.block.data.txs;
for (let tx of txs) {
let transaction = decodeTxRaw(fromBase64(tx));
let messages = transaction.body.messages;
for(let message of messages){
let type = message.typeUrl;
let value = message.value;
if(type == '/cosmos.staking.v1beta1.MsgDelegate'){
let hash = toHex(sha256(fromBase64(tx))).toUpperCase();
getTxs(hash).then(res=>{
let messages = res.tx.value.msg
for(let message of messages){
console.log(message.type);
}
})
}
}
}
loadNextBlock();
})
}
async function start() {
getLatestBlock().then(res=>{
const { height } = res.block.header;
nextBlockNum=height-1;
loadBlock(nextBlockNum);
})
}
start();