-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
297 lines (246 loc) · 10.3 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
require("dotenv").config({ path: __dirname + "/.env" });
const { twitterClient } = require("./twitterClient.js")
const { ApiPromise, WsProvider } = require('@polkadot/api')
const CronJob = require("cron").CronJob;
const express = require('express')
const app = express()
const port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`Listening on port ${port}`)
})
const subscan = async () => {
const data = {
"origin": "string",
"page": 0,
"row": 10,
"status": "active"
};
const API_KEY = process.env.SUBSCAN_API_KEY;
try {
const response = await fetch("https://kusama.api.subscan.io/api/scan/referenda/referendums", {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify(data)
});
const responseData = await response.json();
const referendumIndexes = responseData.data.list.map(item => item.referendum_index);
// Call polkassembly with each referendum_index
for (const postId of referendumIndexes) {
await polkassembly(postId);
}
} catch (error) {
console.error('Error:', error);
}
};
const polkassembly = async (postId) => {
const data = {
postId: postId,
page: 1,
listingLimit: 5,
voteType: 'ReferendumV2'
};
const url = `https://api.polkassembly.io/api/v1/votes?postId=${data.postId}&page=${data.page}&listingLimit=${data.listingLimit}&voteType=${data.voteType}`;
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-network': 'kusama'
},
body: JSON.stringify(data)
});
// ... (your existing code)
let abstain, nay, aye;
try {
const responseData = await response.json();
if (responseData.abstain && responseData.no && responseData.yes) {
abstain = (responseData.abstain.votes || []).map((abstain) => ({
decision: abstain.decision,
createdAt: abstain.createdAt,
voter: abstain.voter,
balance: abstain.balance.abstain,
lockPeriod: abstain.lockPeriod
}));
nay = (responseData.no.votes || []).map((nay) => ({
decision: nay.decision,
createdAt: nay.createdAt,
voter: nay.voter,
balance: nay.balance.value,
lockPeriod: nay.lockPeriod
}));
aye = (responseData.yes.votes || []).map((aye) => ({
decision: aye.decision,
createdAt: aye.createdAt,
voter: aye.voter,
balance: aye.balance.value,
lockPeriod: aye.lockPeriod
}));
}
//... (rest of your code)
} catch (error) {
console.error('Error:', error);
}
//console.log(abstain)
const timestampArrayAbstain = abstain.map((vote) => {
const timestamp = new Date(vote.createdAt).getTime();
return timestamp;
});
const timestampArrayNay = nay.map((vote) => {
const timestamp = new Date(vote.createdAt).getTime();
return timestamp;
});
const timestampArrayAye = aye.map((vote) => {
const timestamp = new Date(vote.createdAt).getTime();
return timestamp;
});
console.log("Abstain Timestamp Array:", timestampArrayAbstain);
console.log("Nay Timestamp Array:", timestampArrayNay);
console.log("Aye Timestamp Array:", timestampArrayAye);
const wsProvider = new WsProvider('wss://kusama-rpc.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });
const timestamps = Number((await api.query.timestamp.now()).toString());
console.log(timestamps);
// Define a tolerance in milliseconds for timestamp matching
const timestampTolerance = 300000; // 5 minutes in milliseconds
const matchingVotesAbstain = abstain.filter(vote => {
const timestamp = new Date(vote.createdAt).getTime();
return Math.abs(timestamp - timestamps) <= timestampTolerance;
});
const matchingVotesNay = nay.filter(vote => {
const timestamp = new Date(vote.createdAt).getTime();
return Math.abs(timestamp - timestamps) <= timestampTolerance;
});
const matchingVotesAye = aye.filter(vote => {
const timestamp = new Date(vote.createdAt).getTime();
return Math.abs(timestamp - timestamps) <= timestampTolerance;
});
const processMatchingVotes = async(matchingVotes, voteType) => {
if (matchingVotes.length > 0) {
const voters = matchingVotes.map(vote => vote.voter);
const decision = matchingVotes.map((vote) => {
if (vote.decision.toLowerCase() === 'yes') {
return 'aye 👍';
} else if (vote.decision.toLowerCase() === 'no') {
return 'nay 👎';
} else {
return 'abstain 🤐';
}
});
const identities = await Promise.all(voters.map(async (voter) => {
try {
const wsProvider = new WsProvider('wss://kusama-rpc.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });
const identity = await api.query.identity.identityOf(voter);
if (identity.toPrimitive().info.display.raw.startsWith('0x')) {
const emojiIdentityHex = identity.toPrimitive().info.display.raw;
// Remove the '0x' prefix
const emojiIdentityWithoutPrefix = emojiIdentityHex.slice(2);
// Convert hex to UTF-8
const emojiIdentityUTF8 = Buffer.from(emojiIdentityWithoutPrefix, 'hex').toString('utf-8');
return emojiIdentityUTF8;
}
return identity.toPrimitive().info.display.raw
} catch (error) {
try {
const wsProvider = new WsProvider('wss://kusama-rpc.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });
const identity = await api.query.identity.superOf(voter);
const render = identity.toJSON()
const raw = render[1].raw
const rawIdentity = raw.slice(2);
const rawString = Buffer.from(rawIdentity, 'hex').toString('utf-8');
return rawString
}
catch (error) {
return "Someone"
}
}
}));
const twitter = await Promise.all(voters.map(async (voter) => {
try {
const wsProvider = new WsProvider('wss://kusama-rpc.polkadot.io');
const api = await ApiPromise.create({ provider: wsProvider });
const identity = await api.query.identity.identityOf(voter);
if (identity && identity.toPrimitive() && identity.toPrimitive().info && identity.toPrimitive().info.twitter && identity.toPrimitive().info.twitter.raw) {
const twitterIdentity = identity.toPrimitive().info.twitter.raw || "";
return twitterIdentity;
} else {
return "";
}
} catch (error) {
console.error(`Error fetching identity for ${voter}:`, error);
return "";
}
}));
const lockPeriod = matchingVotes.map(vote => {
if (vote.lockPeriod === 0 || vote.lockPeriod === null) {
return 0.1;
} else {
return vote.lockPeriod;
}
});
const balanceKSM = matchingVotes.map(vote => vote.balance / 1000000000000);
const TotalKSM = Math.floor(balanceKSM)
const formattedTotalKSM = TotalKSM.toLocaleString();
const effectiveVotes = (balanceKSM * lockPeriod).toLocaleString();
const referendumLink = `https://kusama.polkassembly.io/referenda/${postId}`
const tweetData = `${identities.join(', ')} ${twitter} voted ${decision} with ${formattedTotalKSM} KSM with a total effective votes of ${effectiveVotes} KSM and ${lockPeriod}x conviction on Referendum ${postId} ${referendumLink}\n\n#KSM #kusama #OpenGOV #votes`;
const totalVotes = balanceKSM * lockPeriod;
const tweet = async () => {
try {
await twitterClient.v2.tweet(tweetData);
} catch (e) {
console.log(e);
}
};
console.log(voters);
console.log(decision);
console.log(formattedTotalKSM);
console.log(effectiveVotes)
console.log(lockPeriod);
console.log(postId)
console.log(identities.join(', '))
console.log(twitter)
if(totalVotes > 10){
console.log("success")
return tweet()
} else {
console.log("tweet not sent")
}
// return tweet()
} else {
console.log(`${voteType} failed`);
}
};
processMatchingVotes(matchingVotesAbstain, 'Abstain');
processMatchingVotes(matchingVotesNay, 'Nay');
processMatchingVotes(matchingVotesAye, 'Aye');
} catch (error) {
console.error('Error:', error);
}
// const tweet = async () => {
// try {
// await twitterClient.v2.tweet("here");
// } catch (e) {
// console.log(e)
// }
// }
// tweet();
};
// subscan()
// polkassembly()
const pollingJob = new CronJob("0 */5 * * * *", async () => {
console.log("Checking for new votes...");
await subscan();
await polkassembly();
});
// Start the CronJob
pollingJob.start();
// const pollingInterval = 600000; // 1 minute
// setInterval(async () => {
// console.log("Checking for new votes...");
// await polkassembly(); // Make sure to await the function
// }, pollingInterval);