This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
start.js
54 lines (49 loc) · 1.68 KB
/
start.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
const express = require('express');
const Promise = require('bluebird');
const { init, work } = require('./src/index');
const client = require('./helpers/client');
const redis = require('./helpers/redis');
require('./src/obyte');
const app = express();
const port = process.env.PORT || 4000;
const server = app.listen(port, () => console.log(`Listening on ${port}`));
let lastIrreversibleBlockNum = 0;
const stream = setInterval(() => {
client.database.getDynamicGlobalProperties().then(props => {
lastIrreversibleBlockNum = parseInt(props.last_irreversible_block_num);
});
}, 3000);
const start = () => {
init().then(() => {
redis.getAsync('block_height').then(blockHeight => {
console.log(`Last loaded block was ${blockHeight}`);
const nextBlockNum = blockHeight ? parseInt(blockHeight) + 1 : 1;
handleBlock(nextBlockNum);
}).catch((err) => {
console.error("Failed to get 'block_height' on Redis", err);
});
});
};
const handleBlock = (blockNum) => {
if (lastIrreversibleBlockNum >= blockNum) {
client.database.getBlock(blockNum).then(block => {
work(block, blockNum).then(() => {
redis.setAsync('block_height', blockNum).then(() => {
console.log(`New block height is ${blockNum} ${block.timestamp}`);
handleBlock(blockNum + 1);
}).catch((err) => {
console.error("Failed to set 'block_height' on Redis", err);
handleBlock(blockNum);
});
});
}).catch(err => {
console.error(`Request 'getBlock' failed at block num: ${blockNum}, retry`, err);
handleBlock(blockNum);
});
} else {
Promise.delay(100).then(() => {
handleBlock(blockNum);
});
}
};
start();