-
Notifications
You must be signed in to change notification settings - Fork 4
/
winBooster.js
336 lines (255 loc) · 10.8 KB
/
winBooster.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
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
const { GetRecentClaims } = require("./functions/getRecentClaims.js")
const { ethers } = require('ethers');
const { PROVIDERS, SIGNER } = require('./constants/providers')
const { ABI } = require('./constants/abi')
const { ADDRESS } = require('./constants/address')
const { CONFIG } = require("./constants/config")
const { GetPrizePoolData } = require("./functions/getPrizePoolData.js");
const { FetchApiPrizes } = require("./functions/fetchApiPrizes.js");
const { SendWinBooster } = require("./functions/sendWinBooster.js")
const { CONTRACTS } = require("./constants/contracts.js")
const { MAX_GAS,MAX_CLAIM_INDICES,BLACKLIST,CLAIM_WINDOW_OPEN,CLAIM_WINDOW_CLOSED,RETRY } = CONFIG
function isTimeBetween(startHour, endHour) {
const date = new Date();
const currentHour = date.getHours();
return currentHour >= startHour && currentHour < endHour;
}
async function runClaims() {
if(!isTimeBetween(CLAIM_WINDOW_OPEN,CLAIM_WINDOW_CLOSED)){console.log("not in claim window");return}
const gas = await PROVIDERS["MAINNET"].getGasPrice()
const prizePoolContract = CONTRACTS.PRIZEPOOL[CONFIG.CHAINNAME]
if((gas/1e9) <= MAX_GAS){
console.log("gas in range ",(gas/1e9).toFixed(2),"gwei")
const [claimPoolers, prizePoolData] = await Promise.all([
getClaimPoolers(),
GetPrizePoolData()
]);
// Destructure prizePoolData to extract the properties
const {
lastDrawId,
numberOfTiers,
tierTimestamps,
prizesForTier,
maxFee,
tierPrizeValues,
tierRemainingLiquidites,
reserve
} = prizePoolData;
// Use claimPoolers and the destructured properties here
console.log(claimPoolers);
// console.log("tier values",tierPrizeValues)
//console.log("tier liquidites",tierRemainingLiquidites)
const isFinalized = await prizePoolContract.isDrawFinalized(lastDrawId)
if(isFinalized){console.log("draw is finalized, waiting for the next draw to be awarded....");return}
let [claims, newWinners] = await Promise.all([
GetRecentClaims(CONFIG.CHAINID),
GetRecentClaims(CONFIG.CHAINID).then(claims =>
FetchApiPrizes(
CONFIG.CHAINID,
lastDrawId,
CONFIG.TIERSTOCLAIM,
claims
)
)
]);
// Use claims and newWinners here
//console.log("using api for winner calculations", { claims, newWinners });
const prizesByTier = countPrizesByTier(newWinners)
console.log("prizes by tier",prizesByTier)
console.log("winners before removing claims", newWinners.length);
const {filteredWinsToClaim, unclaimedPrizesPerTier} = removeAlreadyClaimed(newWinners, claims, lastDrawId);
newWinners = filteredWinsToClaim
console.log("unclaimed prizes per tier",unclaimedPrizesPerTier)
console.log("winners after removing claims", newWinners.length);
newWinners = removeBlacklistedWinners(newWinners,BLACKLIST)
console.log("winners after removing blacklist", newWinners.length);
console.log("claimPoolers", claimPoolers)
//console.log("first 4 of newWinners",newWinners.slice(0,4))
// Check for liquidity issues in each tier
const tiersWithIssues = checkTierLiquidity(unclaimedPrizesPerTier, tierPrizeValues, tierRemainingLiquidites);
if (tiersWithIssues.length > 0) {
console.log("Tiers with liquidity issues:", tiersWithIssues);
} else {
console.log("No liquidity issues detected in any tier.");
}
const claimableList = createClaimableList(claimPoolers,newWinners,tierPrizeValues)
claimableList.sort((a, b) => {
// First, compare by tier
if (a.tier < b.tier) return -1;
if (a.tier > b.tier) return 1;
// If tiers are equal, compare by the length of indices (in reverse order)
return b.indices.length - a.indices.length;
});
//console.log("claimable list",claimableList)
const claimServiceSent = await SendWinBooster(claimableList)
if(claimServiceSent){setTimeout(runClaims,30000)}
}else{console.log("gas too high",(gas/1e9).toString())
setTimeout(runClaims, 60000); //60k is 1 min
}
}
async function getClaimPoolers() {
// contract = new ethers.Contract(ADDRESS[CONFIG.CHAINNAME].CLAIMSERVICEFACTORY,ABI.CLAIMSERVICEFACTORY,PROVIDERS[CONFIG.CHAINNAME])
// Fetch the event logs
const winBoostContract = CONTRACTS.WINBOOSTER[CONFIG.CHAINNAME];
const filter = winBoostContract.filters.Deposit();
const logs = await winBoostContract.queryFilter(filter);
// Use a Set to store unique addresses
const addressSet = new Set(logs.map(log => log.args.user.toLowerCase()));
// Convert the Set back to an array
const uniqueAddresses = Array.from(addressSet);
return uniqueAddresses;
}
/* trying replacement
function removeAlreadyClaimed(winsToClaim, claims, draw) {
const filteredWinsToClaim = winsToClaim.filter((win) => {
const [v, p, t] = win;
return !claims.some(
(claim) =>
claim.drawId.toString() === draw.toString() &&
claim.vault.toLowerCase() === v &&
claim.winner.toLowerCase() === p &&
claim.tier === t
);
});
return filteredWinsToClaim;
}
*/
function removeAlreadyClaimed(winsToClaim, claims, draw) {
const unclaimedPrizesPerTier = {};
//console.log("Sample winsToClaim:", winsToClaim.slice(0, 2)); // Log first two entries of winsToClaim
//console.log("Sample claims:", claims.slice(0, 2)); // Log first two entries of claims
const filteredWinsToClaim = winsToClaim.map(([v, p, t, indices]) => {
if (!unclaimedPrizesPerTier[t]) {
unclaimedPrizesPerTier[t] = 0;
}
const unclaimedIndices = indices.filter(index => {
const isClaimed = claims.some(claim => {
//console.log(`Comparing: DrawID(${claim.drawId.toString()} vs ${draw.toString()}), Vault(${claim.vault.toLowerCase()} vs ${v.toLowerCase()}), Winner(${claim.winner.toLowerCase()} vs ${p.toLowerCase()}), Tier(${claim.tier} vs ${t}), Index(${claim.index} vs ${index})`);
return claim.drawId.toString() === draw.toString() &&
claim.vault.toLowerCase() === v.toLowerCase() &&
claim.winner.toLowerCase() === p.toLowerCase() &&
claim.tier === t &&
claim.index === index;
});
return !isClaimed;
});
unclaimedPrizesPerTier[t] += unclaimedIndices.length;
return unclaimedIndices.length > 0 ? [v, p, t, unclaimedIndices] : null;
}).filter(win => win !== null);
return { filteredWinsToClaim, unclaimedPrizesPerTier };
}
function createClaimableList(claimPoolers, newWinners, tierPrizeValues) {
const filteredWinners = filterWinners(claimPoolers, newWinners);
const groupedWinners = groupByVaultAndTier(filteredWinners, tierPrizeValues);
return groupedWinners;
}
function filterWinners(claimPoolers, newWinners) {
const poolersSet = new Set(claimPoolers.map(pooler => pooler.toLowerCase()));
return newWinners.filter(winner => poolersSet.has(winner[1].toLowerCase()));
}
function groupByVaultAndTier(filteredWinners, tierPrizeValues) {
const groupedWinners = {};
filteredWinners.forEach(([vault, owner, tier, indices]) => {
const key = `${vault}_${tier}`;
if (!groupedWinners[key]) {
groupedWinners[key] = {
vault,
tier,
tierValue: tierPrizeValues[tier], // Include tierValue here
winners: [],
indices: []
};
}
const ownerIndex = groupedWinners[key].winners.indexOf(owner.toLowerCase());
if (ownerIndex === -1) {
groupedWinners[key].winners.push(owner.toLowerCase());
groupedWinners[key].indices.push(indices);
} else {
// Append new indices to the existing array for this winner
groupedWinners[key].indices[ownerIndex].push(...indices);
}
});
console.log("grouped winners", groupedWinners);
// Convert the object to an array
return Object.values(groupedWinners);
}
function splitGroupsByMaxIndices(groupedWinners, tierPrizeValues, MAX_CLAIM_INDICES) {
const finalArray = [];
Object.values(groupedWinners).forEach(group => {
let currentIndices = [];
let currentWinners = [];
for (let idx = 0; idx < group.winners.length; idx++) {
const winner = group.winners[idx];
const indices = group.indices[idx];
indices.forEach(index => {
if (currentIndices.length < MAX_CLAIM_INDICES) {
currentIndices.push(index);
if (!currentWinners.includes(winner)) {
currentWinners.push(winner);
}
} else {
finalArray.push({
vault: group.vault,
tier: group.tier,
tierValue: tierPrizeValues[group.tier],
winners: [...currentWinners],
indices: [...currentIndices]
});
currentIndices = [index];
currentWinners = [winner];
}
});
}
// Add the last group if it has any indices
if (currentIndices.length > 0) {
finalArray.push({
vault: group.vault,
tier: group.tier,
tierValue: tierPrizeValues[group.tier],
winners: currentWinners,
indices: currentIndices
});
}
});
return finalArray;
}
function countPrizesByTier(data) {
const prizeCounts = {};
for (const item of data) {
const tier = item[2];
const prizeIndices = item[3];
const numPrizesWon = prizeIndices.length;
if (!prizeCounts[tier]) {
prizeCounts[tier] = 0;
}
prizeCounts[tier] += numPrizesWon;
}
return prizeCounts;
}
function checkTierLiquidity(prizesByTier, tierPrizeValues, tierRemainingLiquidities) {
const tiersWithIssues = [];
Object.keys(prizesByTier).forEach(tier => {
const numPrizes = prizesByTier[tier];
const prizeValue = tierPrizeValues[tier];
const remainingLiquidity = tierRemainingLiquidities[tier];
// Calculate total claimable value for this tier
const totalClaimableValue = numPrizes * prizeValue;
if (totalClaimableValue > remainingLiquidity) {
console.log(`Liquidity Issue Detected in Tier ${tier}: Total Claimable Value (${(totalClaimableValue/1e18).toFixed(4)}) exceeds Remaining Liquidity (${(remainingLiquidity/1e18).toFixed(4)})`);
tiersWithIssues.push(tier);
}
});
return tiersWithIssues;
}
function removeBlacklistedWinners(filteredWinsToClaim, blacklist) {
return filteredWinsToClaim.filter(win => {
// Access the winner's address using the .winner property
const winnerAddress = win[1];
// Return true for wins whose winner's address is not in the blacklist
return !blacklist.includes(winnerAddress.toLowerCase());
});
}
runClaims()
const interval = RETRY * 60 * 1000; // Convert minutes to milliseconds
// Set up the interval to run the function
const intervalId = setInterval(runClaims, interval);