-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
220 lines (185 loc) · 6.47 KB
/
index.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
const app = require("express")();
const mongoose = require("mongoose");
const socket_io = require("socket.io");
const Validator = require("./models/Validator.js");
const EventEmitter = require("events");
const { ApiPromise, WsProvider } = require("@polkadot/api");
const eraChange = new EventEmitter();
const config = require("config");
const configDB = config.get("DB");
const configSentryDns = config.get("SENTRY_DNS");
const EI = require("./models/ElectedInfo");
const Intention = require("./models/Intention");
const ValidatorInfo = require("./models/ValidatorInfo");
const Nominator = require("./models/NominatorInfo");
const Sentry = require("@sentry/node");
// const https = require('https');
const { hexToString } = require("@polkadot/util");
const getPolkaData = require("./utils/getPolkaData");
const validatorsInfos = require("./routes/validatorsInfos");
const nominatorInfos = require("./routes/nominatorinfos");
const intentions = require("./routes/intentions");
const _ = require("lodash");
if (!config.get("DB")) {
throw new Error("Database url is required!");
}
if (!config.get("SENTRY_DNS")) {
throw new Error("Sentry dns is required!");
}
//Error Logger
Sentry.init({ dsn: configSentryDns });
//Initialize required middleware before starting the server
require("./startup/startup")(app);
const io = socket_io();
mongoose
.connect(configDB, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("connected to database"))
.catch(() => console.log("database failed to connect"));
/**
* Remove all old validators data
* and fetch fresh validators data
* on newEra trigger change
*/
eraChange.on("newEra", async () => {
try {
console.log("era func start");
const result = await getPolkaData();
let final = {};
await Validator.deleteMany({});
await EI.deleteMany({});
await Intention.deleteMany({});
await ValidatorInfo.deleteMany({});
await Nominator.deleteMany({});
await Nominator.insertMany(
JSON.parse(JSON.stringify(result.finalNominatorsList))
);
const savedValidator = await Validator.insertMany(
JSON.parse(JSON.stringify(result.filteredValidatorData))
);
const electedInfoData = new EI(
JSON.parse(JSON.stringify(result.electedInfo))
);
const savedElectedInfo = await electedInfoData.save();
await ValidatorInfo.insertMany(
JSON.parse(JSON.stringify(result.filteredValidatorInfos))
);
const intentionData = new Intention({
intentions: JSON.parse(JSON.stringify(result.intentions)),
validatorsAndIntentions: JSON.parse(
JSON.stringify(result.validatorsAndIntentions)
),
info: JSON.parse(JSON.stringify(result.intentionsTotalInfo))
});
const savedIntention = await intentionData.save();
final.filteredValidatorsList = savedValidator;
final.electedInfo = savedElectedInfo;
final.intentionsData = savedIntention;
io.emit("onDataChange", final);
console.log("era func end");
} catch (err) {
console.log(err);
}
});
(async () => {
const wsProvider = new WsProvider("wss://kusama-rpc.polkadot.io");
const api = await ApiPromise.create({ provider: wsProvider });
await api.derive.session.progress(header => {
const eraProgress = header.eraProgress.toNumber();
// console.log(eraLength,eraProgress,sessionLength,sessionProgress)
//TODO: handle edge case where eraProgress equals 1 withins few minutes/seconds
//twice thus leading to inconsistency in the data
if (parseInt(eraProgress) === 1) {
Sentry.captureMessage(`Era changed at: ${new Date()}`);
eraChange.emit("newEra");
}
console.log(`eraProgress ${parseInt(eraProgress)}`);
});
})();
io.on("connection", async () => {
try {
let result = {};
result.filteredValidatorsList = await Validator.find();
result.electedInfo = await EI.find();
result.intentionsData = await Intention.find();
io.emit("initial", result);
} catch (err) {
console.log(err);
}
});
app.get("/", (req, res) => {
res.send("Api for polka analytics");
});
app.use("/", validatorsInfos);
app.use("/", nominatorInfos);
app.use("/", intentions);
app.get("/manualfetch", async (req, res) => {
try {
const result = await getPolkaData();
await Validator.deleteMany({});
await EI.deleteMany({});
await Intention.deleteMany({});
await ValidatorInfo.deleteMany({});
await Nominator.deleteMany({});
const savedValidator = await Validator.insertMany(
JSON.parse(JSON.stringify(result.filteredValidatorData))
);
const electedInfoData = new EI(
JSON.parse(JSON.stringify(result.electedInfo))
);
const savedElectedInfo = await electedInfoData.save();
await ValidatorInfo.insertMany(
JSON.parse(JSON.stringify(result.filteredValidatorInfos))
);
const intentionData = new Intention({
intentions: JSON.parse(JSON.stringify(result.intentions)),
validatorsAndIntentions: JSON.parse(
JSON.stringify(result.validatorsAndIntentions)
),
info: JSON.parse(JSON.stringify(result.intentionsTotalInfo))
});
const savedIntention = await intentionData.save();
await Nominator.insertMany(
JSON.parse(JSON.stringify(result.finalNominatorsList))
);
res.json({ savedValidator, savedElectedInfo, savedIntention });
} catch (err) {
console.log("err", err);
res.status(400).json({ err: err, message: "error bro" });
}
});
// app.get('/yo', async (req, res) => {
// try {
// const wsProvider = new WsProvider('wss://kusama-rpc.polkadot.io');
// const api = await ApiPromise.create({ provider: wsProvider });
// // Retrieve all validators
// const allValidators = await api.query.staking.validators();
// // Parse validators
// const parsedValidators = JSON.parse(JSON.stringify(allValidators))[0];
// // Retrieve session validators
// const sessionValidators = await api.query.session.validators();
// const intentions = await parsedValidators.filter(
// validator => !sessionValidators.includes(validator)
// );
// const intentionstotalinfo = await Promise.all(
// intentions.map(val => api.derive.staking.account(val))
// );
// res.json(JSON.parse(JSON.stringify(intentionstotalinfo)));
// } catch (err) {
// console.log(err);
// }
// });
//To keep heroku dyno awake
// setInterval(function() {
// https.get('https://evening-sea-52088.herokuapp.com/');
// }, 300000 * 5); // every 5 minutes (300000)
const PORT = process.env.PORT || 3009;
const server = app.listen(PORT, () =>
console.log(`Connected on port: ${PORT}`)
);
io.attach(server, {
pingInterval: 300000,
pingTimeout: 300000 * 2,
upgradeTimeout: 300000
});
io.listen(server);
server.setTimeout(300000 * 2); // after 10 minutes