-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapr.js
361 lines (294 loc) · 12.5 KB
/
apr.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
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
const BN = require('bn.js');
const axios = require('axios');
const createCsvWriter = require('csv-writer').createObjectCsvWriter;
const DAILY_ARB_REWARD = 1785;
const QUEST_START_TIME = 1719492300
const SUBGRAPH_API = '';
const SUBGRAPH_MARKET_ID = "";
const DUNE_API_KEY = '';
async function fetchSupplyMarketData(subgraphUrl, marketId, transactionThreshold, suppliers) {
let lastSkip = 0;
let allInteractions = [];
const first = 1000
while (true) {
const query = `
query {
market(id: "${marketId}") {
supplyBaseInteractions(where: {supplier_in: [${suppliers.map(supplier => `"${supplier}"`).join(', ')}],transaction_: {timestamp_gt: "${transactionThreshold}"}}, skip: ${lastSkip}, first: ${first}){
amount
amountUsd
supplier
transaction {
timestamp
}
}
}
}`;
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ query })
};
try {
const response = await fetch(subgraphUrl, options);
const { data } = await response.json();
const interactions = data.market.supplyBaseInteractions;
if (!interactions.length) break;
allInteractions.push(...interactions);
lastSkip += first
if (interactions.length < first) {
break; // Assumes there are no more data if less than `pageSize` results are returned.
}
} catch (error) {
console.error('Error fetching data from The Graph:', error);
break;
}
}
return allInteractions;
}
async function fetchWithdrawMarketData(subgraphUrl, marketId, transactionThreshold, withdrawals) {
let lastSkip = 0;
let allInteractions = [];
const first = 1000
while (true) {
const query = `
query {
market(id: "${marketId}") {
withdrawBaseInteractions(where: {transaction_:{timestamp_gt: "${transactionThreshold}" ,from_in: [${withdrawals.map(withdraw => `"${withdraw}"`).join(', ')}]}}, skip: ${lastSkip}, first: ${first}){
amount
transaction{
timestamp
from
}
}
}
}`;
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({ query })
};
try {
const response = await fetch(subgraphUrl, options);
const { data } = await response.json();
const interactions = data.market.withdrawBaseInteractions;
if (!interactions.length) break;
allInteractions.push(...interactions);
lastSkip += first
if (interactions.length < first) {
break;
}
} catch (error) {
console.error('Error fetching data from The Graph:', error);
break;
}
}
return allInteractions;
}
const getLayer3QuestUsers = async () => {
const response = await axios(`https://api.dune.com/api/v1/query/3868071/results`, { headers: { 'X-Dune-API-Key': DUNE_API_KEY, 'Content-Type': 'application/json' } })
const addresses = response.data.result.rows
const addressesInArray = addresses.map(({ address }) => address)
const uniqueAddressArray = [...new Set(addressesInArray)];
return uniqueAddressArray
}
const getSuppliers = async (users, timestamp) => {
const allSuppliers = [];
const maxAmountOfUsers = 1000;
let i = 0;
while (true) {
const currentUsers = users.slice(i * maxAmountOfUsers, (i + 1) * maxAmountOfUsers)
const arrayOfSupplies = await fetchSupplyMarketData(SUBGRAPH_API, SUBGRAPH_MARKET_ID, timestamp, currentUsers)
allSuppliers.push(...arrayOfSupplies)
if (currentUsers.length < 1000) break
i += 1
}
return allSuppliers.map(({ amount, supplier, transaction: { timestamp } }) => ({ type: 'supply', amount, address: supplier, timestamp }))
}
const getWithdrawals = async (users, timestamp) => {
const allWithdrawal = [];
const maxAmountOfUsers = 1000;
let i = 0;
while (true) {
const currentUsers = users.slice(i * maxAmountOfUsers, (i + 1) * maxAmountOfUsers)
const arrayOfWithdrawal = await fetchWithdrawMarketData(SUBGRAPH_API, SUBGRAPH_MARKET_ID, timestamp, currentUsers)
allWithdrawal.push(...arrayOfWithdrawal)
if (currentUsers.length < 1000) break
i += 1
}
return allWithdrawal.map(({ amount, transaction: { from, timestamp } }) => ({ type: 'withdraw', amount, address: from, timestamp }))
}
const getActionsByAddress = (supply, withdraw) => {
const addresses = {};
[...supply, ...withdraw].forEach((action) => {
if (!addresses[action.address]) {
addresses[action.address] = []
}
addresses[action.address].push(action)
})
return addresses
}
/**
* Adds one hour to the given Unix timestamp.
*
* @param {number} unixTimestamp - The Unix timestamp in seconds.
* @returns {number} - The new Unix timestamp, with one hour added, in seconds.
*/
function addHours(unixTimestamp, hours = 1) {
// One hour in seconds
const oneHourInSeconds = hours * 3600;
// Add one hour to the timestamp
const newTimestamp = +unixTimestamp + oneHourInSeconds;
return newTimestamp;
}
const calculateCurrentBalanceBasedOnPrevActions = (actions) => {
let balance = new BN(0)
actions.forEach(action => {
if (action.type === 'supply') {
balance = balance.add(new BN(action.amount))
}
if (action.type === 'withdraw') {
balance = balance.sub(new BN(action.amount))
}
// in case when user withdraw funds that was in market before the campaign start
if (balance.lt(new BN(0))) {
balance = new BN(0)
}
})
return balance.toString()
}
const getBalancesByHour = (allActions, startUnixTimestamp, finishUnixTimestamp) => {
const uniquedAddresses = [...allActions.map((action) => action.address)]
const usersActions = getActionsByAddress(allActions, [])
let currentTime = startUnixTimestamp;
const finishTime = finishUnixTimestamp;
// [fromTimestamp-toTimestamp] -> address -> balance
const actionsByHour = {}
while (currentTime < finishTime) {
const fromTimestamp = currentTime;
const toTimestamp = addHours(currentTime)
const key = `${fromTimestamp}-${toTimestamp}`
actionsByHour[key] = {}
uniquedAddresses.forEach((address) => {
// { type, amount, address, timestamp }
const userActions = usersActions[address];
const userActionsBeforeCurrentTimestamp = userActions.filter(userAction => +userAction.timestamp < +toTimestamp);
const userActionsBeforeCurrentTimestampSortedByTimestamp = userActionsBeforeCurrentTimestamp.sort((a, b) => +a.timestamp - +b.timestamp)
const currentHourUserBalance = calculateCurrentBalanceBasedOnPrevActions(userActionsBeforeCurrentTimestampSortedByTimestamp)
actionsByHour[key][address] = currentHourUserBalance
})
currentTime = addHours(currentTime)
}
return actionsByHour
}
const getTvlShanshotByHour = (balancesByHour) => {
const hours = Object.keys(balancesByHour)
const balanceByHour = {};
hours.forEach(hour => {
const tvl = Object.values(balancesByHour[hour]).reduce((accumulator, currentValue) => accumulator.add(new BN(currentValue)), new BN(0));
balanceByHour[hour] = tvl.toString()
})
return balanceByHour
}
const getUserArbAmountPerHour = (balancesByHour, tvlByHour, arbPerHour) => {
const hours = Object.keys(balancesByHour)
const addressToHourToArbReward = {};
hours.forEach(hour => {
const tvl = tvlByHour[hour] // string number
const userObj = balancesByHour[hour] // {address: "balance"}
const addresses = Object.keys(userObj) // [address]
addressToHourToArbReward[hour] = {}
addresses.forEach(address => {
const userBalance = userObj[address]
const arbPerHourBN = new BN(arbPerHour).mul(new BN('1000000000000000000'));
const a = new BN(userBalance).mul(new BN('1000000000000000000')); // mul on purpose
const b = new BN(tvl)
const result = a.div(b).mul(arbPerHourBN).div(new BN('1000000000000000000')) // div on purpose
addressToHourToArbReward[hour][address] = result.toString()
})
})
return addressToHourToArbReward
}
const getUserTotalArbReward = (timeToAddressToAmount) => {
const addressToReward = {};
const dates = Object.keys(timeToAddressToAmount)
dates.forEach(date => {
const rewardPerHourForUsers = timeToAddressToAmount[date]
const addresses = Object.keys(rewardPerHourForUsers)
addresses.forEach(address => {
if (!addressToReward[address]) {
addressToReward[address] = '0'
}
addressToReward[address] = new BN(addressToReward[address]).add(new BN(rewardPerHourForUsers[address])).toString()
})
})
return addressToReward
}
const sumOfRewardsForAllUsers = (data) => {
return (Object.values(data).reduce((accumulator, currentValue) => accumulator.add(new BN(currentValue)), new BN(0))).toString();
}
const prepareDataForCsv = (data) => {
const result = []
const addresses = Object.keys(data)
addresses.forEach(address => {
const numerator = new BN(data[address]);
const denominator = new BN('1000000000000000000');
const integerPart = numerator.div(denominator);
const remainder = numerator.mod(denominator);
const fractionalPart = remainder.toString(10).padStart(18, '0');
const amount = `${integerPart.toString()}.${fractionalPart}`;
result.push({ address, amountWei: data[address], amount })
})
return result
}
const main = async () => {
const DAY_FROM_THE_START = 7
const SNAPSHOT_FROM_TIMESTAMP = +QUEST_START_TIME;
const SNAPSHOT_TO_TIMESTAMP = +addHours(QUEST_START_TIME, 24 * DAY_FROM_THE_START);
if (SNAPSHOT_TO_TIMESTAMP > Math.floor(Date.now() / 1000)) {
console.error('Cannot make snapshot. The final date is not reached')
process.exit(0)
}
const users = await getLayer3QuestUsers();
const suppliers = await getSuppliers(users, QUEST_START_TIME)
const withdrawals = await getWithdrawals(users, QUEST_START_TIME)
const allActions = [...suppliers, ...withdrawals]
const getBalancesForUserPerHour = getBalancesByHour(allActions, +SNAPSHOT_FROM_TIMESTAMP, SNAPSHOT_TO_TIMESTAMP)
const hourlyTvlSnapshot = getTvlShanshotByHour(getBalancesForUserPerHour)
const usersArbRewardsByHours = getUserArbAmountPerHour(getBalancesForUserPerHour, hourlyTvlSnapshot, DAILY_ARB_REWARD / 24)
const totalUsersRewards = getUserTotalArbReward(usersArbRewardsByHours)
// verify how much arb should be destributed and how much will be destributed
const destributedRewards = sumOfRewardsForAllUsers(totalUsersRewards)
const shouldBeDestributed = new BN(DAY_FROM_THE_START * DAILY_ARB_REWARD).mul(new BN('1000000000000000000')).toString()
const diff = new BN(destributedRewards).sub(new BN(shouldBeDestributed))
if (diff.lt(new BN(0))) {
console.log(`Will be destirbuted less arb then should for ${diff.toString()} in wei (devide it by 1e18)`)
} else {
console.log(`Will be destirbuted more arb then should for ${diff.toString()} in wei (devide it by 1e18)`)
}
// prepare and export to csv
const dataForCsv = prepareDataForCsv(totalUsersRewards)
const csvFilePath = `layer3-compound-ltipp-${SNAPSHOT_FROM_TIMESTAMP}-${SNAPSHOT_TO_TIMESTAMP}.csv`;
const csvWriter = createCsvWriter({
path: csvFilePath,
header: [
{ id: 'address', title: 'Address' },
{ id: 'amountWei', title: 'ARB amount (wei)' },
{ id: 'amount', title: 'ARB amount' }
]
})
csvWriter.writeRecords(dataForCsv)
.then(() => {
console.log('CSV file was written successfully');
})
.catch((err) => {
console.error('Error writing CSV file', err);
});
}
main().then().catch()