forked from moonsama/lions-raffle
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdrawing.js
76 lines (60 loc) · 1.78 KB
/
drawing.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
const seedrandom = require("seedrandom");
const fs = require("fs");
// Hash from block #8535000
const hash =
"0x093efa911694a307448ce78e88aecfb56c740f0e4c9ea3eff1e6b01868ff2022";
// isolate all numeric values from hash. ouput: '07366801591728373564622813150817306143240'
const seed = hash.replace(/[a-zA-Z]/g, "");
console.log("seed", seed);
const rng = seedrandom(seed);
const data = JSON.parse(fs.readFileSync("leaderboard.json"));
const leaders = data.leaderboards[0].leaderboard;
const list = leaders.filter((item) => item.amount > 0);
// sort by amount in descending order
list.sort((a, b) => b.amount - a.amount);
// extracting names and weights list
const names = [];
const weights = [];
list
.filter((item) => item["amount"] !== "0")
.map((item) => {
names.push(item["name"]);
weights.push(item["amount"]);
});
// draw 1 unique winner
const winnersList = [];
for (let round = 0; round < 1; round++) {
const rnd = rng();
let random = rnd * weights.reduce((a, b) => a + b, 0);
let i = 0;
for (i; i < weights.length; i++) {
if (random < weights.slice(0, i + 1).reduce((a, b) => a + b, 0)) {
const winner = names[i];
if (winnersList.includes(winner)) {
// continue drawing until unique winner is found
round--;
break;
} else {
winnersList.push(winner);
break;
}
}
}
}
// count winners
const winners = {};
winnersList.map((winner) => {
if (winners[winner]) {
winners[winner]++;
} else {
winners[winner] = 1;
}
});
// sort winner list from high to low
const sortedWinners = Object.entries(winners)
.sort((a, b) => b[1] - a[1])
.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
fs.writeFileSync("drawing_winner.json", JSON.stringify(sortedWinners, null, 2));