Repository navigation
Expand file tree
/
Copy pathsnap.js
More file actions
517 lines (486 loc) · 20.1 KB
/
Copy pathsnap.js
File metadata and controls
517 lines (486 loc) · 20.1 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
const { request, gql } = require('graphql-request');
const fetch = require('node-fetch');
const snapshot_endpoint = "https://hub.snapshot.org/graphql";
const SNAPSHOT_SCORE_API = 'https://score.snapshot.org/api/scores';
const ethers = require('ethers');
const { Contract, Provider } = require('./multicall.js'); // multicall, at an archive block
var round = Math.floor(Math.floor(Date.now() / 1000) / (86400 * 14)) - 1348;
// Snapshot vote tallying, for rounds voted on Snapshot (before on-chain voting): history only.
// const snap = require('./snap.js')({ storage, rpc }) rpc: an archive-capable mainnet RPC URL
module.exports = function snap({ storage, rpc }) {
// working variables (formerly implicit globals)
var convexVote, respt, p, del, delegates, graceAdd, graceABI, provider, balanceStrat, multiBalance,
voterScores, graceCh, ptot, poolShot, userPower, userWeightDenominator, n, gauge, toPool, gauges,
pStr, store, gaugesReverse, g, proposals, res, query, i;
async function grabProposal(hashId) {
const proposalQuery = gql`
query {
proposal(id:"${hashId}") {
id
title
body
choices
start
end
snapshot
state
author
created
plugins
network
strategies {
name
params
}
space {
id
name
}
}
}
`
var response = await request(snapshot_endpoint, proposalQuery);
return response.proposal;
}
async function getVoters(hashId) {
const votersQuery = gql`
query Votes {
votes (
first: 1000
where: {
proposal: "${hashId}"
}
orderBy: "created",
orderDirection: desc
) {
id
voter
created
proposal {
id
}
choice
space {
id
}
}
}
`
var response = await request(snapshot_endpoint, votersQuery);
//console.log(response);
//console.log('Number of votes: ' + response.votes.length);
// in Nov 9th week, Convex deployer forgot to vote. This assigns their vote to veFunder just as a placeholder,
// to get a list of non-voting delegates for convex team to reimburse
if(hashId == '0x19683e854234ed9bd75665c22e06b880f91e918b0a21aace406c09d1fcaa9c3c') {
convexVote = {
id: '0x0000009385d66f5d08459d00503b795599964dfb50b24d7e3784a85d7476bad0',
voter: '0x947B7742C403f20e5FaCcDAc5E092C943E7D0277',
created: 1699920047,
proposal: {
id: '0x19683e854234ed9bd75665c22e06b880f91e918b0a21aace406c09d1fcaa9c3c'
},
choice: {
'272': 1
},
space: { id: 'cvx.eth' }
};
response.votes.push(convexVote);
}
return response.votes;
}
async function getVoteAllScores(block, voteAddresses, strategy) {
const params = {
space: "cvx.eth",
network: "1",
snapshot: Number(block),
strategies: strategy,
addresses: voteAddresses
};
var init = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ params })
};
//console.log(JSON.stringify({ params }));
//console.log(util.inspect(init, false, null));
var response = await fetch(SNAPSHOT_SCORE_API, init);
try {
var obj = await response.json();
if(!obj.result || obj.result.scores == undefined) {
console.log("Snapshot score API returned no scores: " + JSON.stringify(obj).slice(0, 300));
return null;
}
return obj.result.scores;
} catch (e) {
console.log(e); // the body is already read, so there's no text to print
return null;
}
}
async function getVoteScores(block, voteAddresses, strategy, voter=null) {
const params = {
space: "cvx.eth",
network: "1",
snapshot: Number(block),
strategies: strategy,
addresses: voteAddresses
};
var init = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ params })
};
//console.log(JSON.stringify({ params }));
//console.log(util.inspect(init, false, null));
var response = await fetch(SNAPSHOT_SCORE_API, init);
var obj = await response.json();
if(!obj.result || obj.result.scores == undefined) {
throw new Error("Snapshot score API returned no scores: " + JSON.stringify(obj).slice(0, 300));
}
// console.log(util.inspect(obj.result.scores, false, null));
var totalAddresses = {};
var totalScore = 0;
for (var x in voteAddresses) {
if(voteAddresses[x] == voter) {
totalAddresses[voteAddresses[x]] = 0;
if(obj.result.scores[0][voteAddresses[x]] != undefined) {
totalAddresses[voteAddresses[x]] += obj.result.scores[0][voteAddresses[x]];
}
if(obj.result.scores[1][voteAddresses[x]] != undefined) {
totalAddresses[voteAddresses[x]] += obj.result.scores[1][voteAddresses[x]];
}
continue;
}
if (obj.result.scores[0][voteAddresses[x]] != undefined) {
totalScore = totalScore + obj.result.scores[0][voteAddresses[x]];
}
if (totalAddresses[voteAddresses[x]] == undefined && obj.result.scores[0][voteAddresses[x]] != undefined) {
totalAddresses[voteAddresses[x]] = obj.result.scores[0][voteAddresses[x]]
} else if (obj.result.scores[0][voteAddresses[x]] != undefined) {
totalAddresses[voteAddresses[x]] = totalAddresses[voteAddresses[x]] + obj.result.scores[0][voteAddresses[x]];
}
}
//console.log('Total Score: ' + totalScore);
return totalAddresses;
}
async function getDelegates(voterAddress, snapshot_block, page) {
let res = await fetch(
"https://subgrapher.snapshot.org/delegation/1",
{
headers: {
"content-type": "application/json",
},
body:
'{"query":"query { delegations (where: {space_in: [\\"cvx.eth\\", \\"\\"], delegate: \\"' +
voterAddress +
'\\", timestamp_gte: '+page+'}, orderBy:timestamp, orderDirection: asc, first: 1000, block: { number: ' + snapshot_block + '}) { delegator space timestamp } }"}',
method: "POST",
}
);
res = await res.text();
res = JSON.parse(res);
let addressList = {};
let delegateList = [];
let delegateListUpper = [];
if (res.data != null) {
//console.log('Number of delegates: ' + res.data.delegations.length);
let lastTimestamp = 0;
res.data.delegations.forEach((key) => {
if (key.space == "cvx.eth" || key.space == null || key.space == '') {
delegateList.push(key.delegator);
delegateListUpper.push(key.delegator.toUpperCase());
lastTimestamp = key.timestamp;
}
});
addressList.normal = delegateList;
addressList.upper = delegateListUpper;
//console.log(delegateList);
return [delegateList, lastTimestamp];
}
return null;
}
async function getProposals(query) {
try {
res = await fetch(snapshot_endpoint + "?", {
"headers": { "content-type": "application/json" },
"body": query,
"method": "POST"
});
res = await res.text()
res = JSON.parse(res);
if (res.data.proposals[0] != null) {
return res.data.proposals;
} else {
return null;
}
} catch (e) {
console.log(e)
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
var voterPlaceholder = 0;
async function tally(toGrab, choices, voter=null) {
var proposal = await grabProposal(toGrab);
var snapshot_block = proposal.snapshot;
var voters = await getVoters(toGrab);
// Start Round 95 exeption
if(toGrab == "0x3016b4856269e94064a8ddd5bd6d229a03f08471c011b6fa4ddbccd225b4e6aa") {
// Round 95's votes as captured during the round (v2's 95snapShot node, whose votes this uses). Votes
// that later changed on Snapshot were paid as captured, and only this capture still has them. It
// ships as data/95snapShot.json; a store that has it (v2's Firebase, say) is the fallback.
var addedVotes = 0;
var round95votes;
try {
round95votes = require('./data/95snapShot.json').votes;
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') { throw e; }
round95votes = await storage.read("95snapShot", "votes");
}
if (round95votes == null) {
throw new Error("Round 95 needs its vote capture: data/95snapShot.json (v2's 95snapShot/votes)");
}
for(var v in round95votes) {
var found = false;
for(var i in voters) {
if(voters[i].voter == round95votes[v].voter) {
found = true;
break;
}
}
if(!found) {
voters.push(round95votes[v]);
console.log("added "+round95votes[v].voter+" to round 95 votes");
addedVotes++;
}
}
console.log("added "+addedVotes+" votes to round 95");
}
// End Round 95 exception
var votersCheck = [];
for (var i in voters) {
votersCheck.push(voters[i].voter);
}
if (voter != null) {
votersCheck.push(voter);
}
var voterAllScores = await getVoteAllScores(snapshot_block, votersCheck, proposal.strategies);
if(voter != null) {
if(voterAllScores[1][voter] > 0) {
voterPlaceholder = voterAllScores[1][voter];
}
}
var delegationTotalComp = {};
for (var i in voters) {
if (voterAllScores[1][voters[i].voter] > 0) {
//console.log("loading delegates from "+voters[i].voter);
if(voters[i].voter == voter) { console.log("skipping "+voter+" delegations"); continue; }
p = 0;
del = null;
while(del == null) {
del = await getDelegates(voters[i].voter, snapshot_block, 0);
if(del == null) {
console.log("retrying delegation api");
await sleep(1000);
}
}
delegates = [];
delegates.push.apply(delegates, del[0])
while (del[0].length == 999 || del[0].length == 1000) {
// last record of del
p = del[1];
//console.log(p);
//console.log("reading delegates page "+(p+1));
del = null;
while(del == null) {
del = await getDelegates(voters[i].voter, snapshot_block, p);
if(del == null) {
console.log("retrying delegation api");
await sleep(1000);
}
}
//console.log(del);
delegates.push.apply(delegates, del[0])
}
if (delegates.length > 0) {
for (var x in delegates) {
delegationTotalComp[delegates[x]] = voters[i].voter;
if (voters.find(a => a.voter.toLowerCase() == delegates[x].toLowerCase()) == undefined) {
//console.log("adding delegated voter "+delegates[x])
votersCheck.push(delegates[x]);
//console.log(delegates[x]);
voters.push({
id: voters[i].id,
voter: delegates[x],
created: voters[i].created,
proposal: voters[i].proposal,
choice: voters[i].choice,
space: voters[i].space
})
}
}
}
}
}
var votersCheck2 = [];
// remove voters with no vlCVX
var batches = [[]];
var batchesA = [[]];
var batch = 0;
graceAdd = "0x81768695e9fDdA232491bec5B21Fd1BC1116F917";
graceABI = [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"_account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lockDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"locker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oldlocker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"rewardsDuration","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}];
provider = new ethers.JsonRpcProvider(rpc, 1, { staticNetwork: true });
balanceStrat = await new ethers.Contract(
graceAdd,
graceABI,
provider
);
const ethcallProvider = new Provider(provider, 1);
multiBalance = new Contract(graceAdd,graceABI);
for (var i in votersCheck) {
if(i % 100 == 0 && i > 0) {
batch++;
batches[batch] = [];
batchesA[batch] = [];
}
batches[batch].push(multiBalance.balanceOf(votersCheck[i]));
batchesA[batch].push(votersCheck[i]);
}
voterScores = {};
var proTotal = 0;
for(var i in batches) {
// a failed multicall throws: retry it once, and let a second failure throw to the caller
try {
graceCh = await ethcallProvider.all(batches[i],snapshot_block);
} catch (e) {
console.log("Grace contract call failed (" + (e.shortMessage || e.message) + "), retrying");
await sleep(1000);
graceCh = await ethcallProvider.all(batches[i],snapshot_block);
}
if(graceCh.length != batches[i].length) {
throw new Error("Grace contract call returned " + graceCh.length + " results for " + batches[i].length + " calls");
}
for (var j in graceCh) {
if (graceCh[j].toString() != "0") {
votersCheck2.push(batchesA[i][j]);
voterScores[batchesA[i][j]] = Number(ethers.formatUnits(graceCh[j], 18));
proTotal += voterScores[batchesA[i][j]];
}
}
await sleep(250); // sleep to avoid rate limiting
}
if(voter != null) {
proTotal += voterPlaceholder;
}
console.log("Total votes counted: " + proTotal);
//var voterScores = await getVoteScores(snapshot_block, votersCheck2, proposal.strategies, voter);
//console.log("-------");
ptot = 0;
poolShot = {total:0,gauges:{}};
for (i = 0; i < voters.length; i++) {
if(voters[i].voter == voter) {
console.log("skipping "+voter+" weights")
continue;
}
if(!voterScores[voters[i].voter]) {
continue;
}
userPower = voterScores[voters[i].voter];
if (userPower > 0) {
ptot += userPower;
//console.log(voters[i].choice);
userWeightDenominator = 0;
for (n in voters[i].choice) {
userWeightDenominator += voters[i].choice[n];
}
for (n in voters[i].choice) {
gauge = choices[n-1];
toPool = userPower * (voters[i].choice[n] / userWeightDenominator);
if (poolShot.gauges[gauge] == null || poolShot.gauges[gauge] == undefined) { poolShot.gauges[gauge] = {total:0,votes:{}}; }
poolShot.gauges[gauge].votes[voters[i].voter] = toPool;
poolShot.gauges[gauge].total += toPool;
poolShot.total += toPool;
}
}
}
return poolShot;
}
return {
endpoint: snapshot_endpoint,
// update snapshot local storage for a specified round, with specified delay between updates
updateSnapshot: async (delay, _round, platform=0, voter=null) => {
if(platform == 0) {
gauges = await storage.read("gauges");
pStr = "Gauge Weight for Week";
var roundstart = 1348 * 86400 * 14 + _round * 86400 * 14;
store = "snapshotVoteData";
} else if(platform==2) {
gauges = await storage.read("fxGauges");
pStr = "FXN Gauge Weight for Week";
var roundstart = 1413 * 86400 * 14 + _round * 86400 * 14;
store = "fxSnapshotVoteData";
}
gaugesReverse = {};
for (g in gauges.gauges) {
if(gauges.gauges[g].shortName == undefined) { continue; }
gaugesReverse[gauges.gauges[g].shortName] = g;
}
var shot = await storage.read(store, _round);
if(shot == null) { shot = {lastUpdated:0}; }
// if lastUpdated is sooner than delay, or round has not started, return cached snapshot
if (shot.lastUpdated + delay < Math.floor(Date.now()/1000) && _round <= round) {
// if snapshot id is not defined, attempt to match it
if(shot.id == undefined) {
// get past 30 proposals from cvx.eth
query = "{\"query\":\"query Proposals { proposals ( first: 30, skip: 0, where: { space_in: [\\\"cvx.eth\\\"]}, orderBy: \\\"created\\\", orderDirection: desc ) { id title state created choices }}\",\"variables\":null,\"operationName\":\"Proposals\"}";
proposals = await getProposals(query);
// if no proposals, create empty array so we can continue with the rest of the function
if (proposals == null) {
proposals = [];
}
for (i = 0; i < proposals.length; i++) {
if (proposals[i].title.indexOf(pStr) === 0) {
// check if proposal was created after, but within 72 hours after round start
if (proposals[i].created > roundstart && proposals[i].created < roundstart + 86400*5) {
shot.id = proposals[i].id; // matched snapshot id
for(g in proposals[i].choices) {
proposals[i].choices[g] = proposals[i].choices[g].trim();
// create gauge list from choice names
if(gaugesReverse[proposals[i].choices[g]] != undefined) {
proposals[i].choices[g] = gaugesReverse[proposals[i].choices[g]];
} else {
console.log("Could not match gauge "+proposals[i].choices[g]+" to gauge address or receiver index");
}
}
shot.choices = proposals[i].choices; // store in round snapshot data
break;
}
}
}
}
// if we failed to match, store lastUpdated and return empty shot object
if (shot.id == undefined) {
shot.lastUpdated = Math.floor(Date.now() / 1000);
if(voter == null) { await storage.write(store, shot, _round); }
return shot;
}
// if we have an id and delay has passed, update snapshot
shot.votes = await tally(shot.id, shot.choices, voter);
shot.lastUpdated = Math.floor(Date.now() / 1000);
if(voter == null) { await storage.write(store, shot, _round); }
}
if(voter != null) {
shot.voter = voterPlaceholder;
}
return shot;
}
};
};