-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib.js
executable file
·504 lines (433 loc) · 13.5 KB
/
lib.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
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
const BN = require('bn.js');
const web3 = require('web3');
const { Interval, DateTime } = require('luxon');
const { request } = require('graphql-request');
const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
const PAGINATION_SIZE = 1000;
const configuration = {
endpoint:
'https://graph.infra.circles.garden/subgraphs/name/circlesubi/circles-ubi',
relayerAddresses: ['0x0739a8d036c966ac9161ea14855ce0f94c15b87b', '0x9944ce8e27ce1f16c4003f108b1c09e5ae011ba0'],
format: 'csv',
log: undefined,
};
function setConfiguration(customConfiguration) {
const { endpoint, relayerAddresses, format, log } = Object.keys(
configuration,
).reduce((acc, key) => {
if (customConfiguration[key]) {
acc[key] = customConfiguration[key];
} else {
acc[key] = configuration[key];
}
return acc;
}, {});
configuration.endpoint = endpoint;
configuration.relayerAddresses = relayerAddresses;
configuration.format = format;
configuration.log = log;
}
require('cross-fetch/polyfill');
// Utility methods to display results
function print(message) {
if (!configuration.log) {
return;
}
configuration.log(...arguments);
}
function weiToCircles(wei) {
return web3.utils.fromWei(wei, 'ether');
}
// Utility methods to fetch data
async function fetchFromGraph(
name,
fields,
where = '',
lastID = '',
first = PAGINATION_SIZE,
) {
const query = `{
${name}(first: ${first}, orderBy: id, where: {id_gt: "${lastID}", ${where}}) {
${fields}
}
}`;
console.log(query.replace(/\s\s+/g, ' '));
const data = await request(
configuration.endpoint,
query.replace(/\s\s+/g, ' '),
);
return data[name];
}
async function* fetchGraphGenerator(name, fields, where = '') {
// The `skip` argument must be between 0 and 5000 (current limitations by TheGraph).
// Therefore, we sort the elements by id and reference the last element id for the next query
let lastID = '';
let hasData = true;
const pageSize = PAGINATION_SIZE;
let skip = 0;
while (hasData) {
try {
const data = await fetchFromGraph(name, fields, where, lastID, pageSize);
print(
`Fetched ${data.length} entries for "${name}" from Graph (${skip} - ${skip + pageSize
}})...`,
);
hasData = data.length > 0;
if (hasData) {
lastID = data[data.length - 1].id;
}
skip += PAGINATION_SIZE;
yield data;
} catch (e) {
print(`Error: ${e.message} when retrieving (${skip} - ${skip + pageSize}})`);
continue;
};
}
}
async function fetchAllFromGraph(name, fields, where = '') {
let result = [];
let index = 0;
let test = 0;
print(`Request all "${name}" data from Graph ...`);
for await (let data of fetchGraphGenerator(name, fields, where)) {
if (data.length > 0) {
result = result.concat(
data.map((entry) => {
entry.index = ++index;
return entry;
}),
);
}
}
return result;
}
// Utility methods to analyse data
const avg = (arr) => arr.reduce((acc, x) => acc + x, 0) / arr.length;
const avgBN = (arr) => {
const total = arr.reduce((acc, x) => acc.add(new BN(x)), new BN());
return total.divn(arr.length);
};
const maxBN = (arr) => arr.reduce((acc, x) => BN.max(acc, new BN(x)), new BN());
const count = (arr) => {
return arr.reduce((acc, item) => {
Object.keys(item).forEach((key) => {
if (!(key in acc)) {
acc[key] = {};
}
if (!(item[key] in acc[key])) {
acc[key][item[key]] = 0;
}
acc[key][item[key]] += 1;
});
return acc;
}, {});
};
const pick = (arr, key) => arr.map((item) => item[key]);
// The actual analysis commands
const analyses = {
transitive: {
description: 'transitive transactions in the Circles hub',
command: async () => {
const notifications = await fetchAllFromGraph(
'notifications',
'id time hubTransfer { id from to amount }',
'type: HUB_TRANSFER',
);
const hubTransfers = notifications.map(({ hubTransfer, time }) => {
return {
amount: hubTransfer.amount,
from: hubTransfer.from,
to: hubTransfer.to,
id: hubTransfer.id,
time,
};
});
print(
'Average amount',
weiToCircles(avgBN(pick(hubTransfers, 'amount'))),
);
print(
'Average total received transfers per user',
avg(Object.values(count(hubTransfers).from)),
);
print(
'Max total received transfers per user',
Math.max(...Object.values(count(hubTransfers).to)),
);
return hubTransfers;
},
},
transfersWithTimestamp: {
description: 'regular transfer transactions including ubi payouts and gas fees with timestamp',
command: async () => {
const notifications = await fetchAllFromGraph(
'notifications',
'id time transfer { id from to amount }',
'type: TRANSFER',
);
const transfers = notifications.map(({ transfer, time }) => {
return {
amount: transfer.amount,
from: transfer.from,
to: transfer.to,
id: transfer.id,
time,
};
});
const ubiPayouts = transfers.filter((item) => {
return item.from === ZERO_ADDRESS;
});
const gasFees = transfers.filter((item) => {
return configuration.relayerAddresses.includes(item.to);
});
const gasFeesSum = gasFees.reduce((acc, item) => {
return acc.add(new BN(item.amount));
}, new BN());
print(
'Average amount',
weiToCircles(avgBN(pick(transfers, 'amount'))),
);
print(
'Average UBI payout amount',
weiToCircles(avgBN(pick(ubiPayouts, 'amount'))),
);
print('UBI payouts count', ubiPayouts.length);
print('Total gas fees amount (in wei)', gasFeesSum.toString());
print('Average gas fees amount (in wei)', avgBN(pick(gasFees, 'amount')).toString());
return transfers;
},
},
transfers: {
description:
'regular transfer transactions including ubi payouts and gas fees',
command: async () => {
const transfers = await fetchAllFromGraph(
'transfers',
'id from to amount',
);
const ubiPayouts = transfers.filter((item) => {
return item.from === ZERO_ADDRESS;
});
const gasFees = transfers.filter((item) => {
return configuration.relayerAddresses.includes(item.to);
});
const gasFeesSum = gasFees.reduce((acc, item) => {
return acc.add(new BN(item.amount));
}, new BN());
print('Average amount', weiToCircles(avgBN(pick(transfers, 'amount'))));
print(
'Average UBI payout amount',
weiToCircles(avgBN(pick(ubiPayouts, 'amount'))),
);
print('UBI payouts count', ubiPayouts.length);
print('Total gas fees amount (in wei)', gasFeesSum.toString());
print('Average gas fees amount (in wei)', avgBN(pick(gasFees, 'amount')).toString());
return transfers;
},
},
trusts: {
description: 'trust connection events',
command: async () => {
const notifications = await fetchAllFromGraph(
'notifications',
'id time trust { id canSendTo user limitPercentage }',
'type: TRUST',
);
const trusts = notifications.map(({ trust, time }) => {
return {
canSendToAddress: trust.canSendTo,
userAddress: trust.user,
limitPercentage: trust.limitPercentage,
id: trust.id,
time,
};
});
const revokedTrusts = trusts.filter((item) => {
return item.limitPercentage === '0';
});
const createdTrusts = trusts.filter((item) => {
return item.limitPercentage !== '0';
});
const outgoingTrustConnections = count(createdTrusts).canSendToAddress;
const incomingTrustConnections = count(createdTrusts).userAddress;
print('Created trust connections:', createdTrusts.length);
print('Revoked trust connections:', revokedTrusts.length);
print(
'Average outgoing trust connections:',
avg(Object.values(outgoingTrustConnections)),
);
print(
'Average incoming trust connections:',
avg(Object.values(incomingTrustConnections)),
);
// print(
// 'Max outgoing trust connections',
// Math.max(...Object.values(incomingTrustConnections)),
// );
// print(
// 'Max incoming trust connections',
// Math.max(...Object.values(outgoingTrustConnections)),
// );
return trusts;
},
},
ownerships: {
description: 'safe ownership events / device changes',
command: async () => {
const ownershipChanges = await fetchAllFromGraph(
'ownershipChanges',
'id adds removes',
);
const safes = await fetchAllFromGraph('safes', 'id');
const adds = ownershipChanges.filter((item) => {
return item.adds;
});
const removals = ownershipChanges.filter((item) => {
return item.removes;
});
print('Added devices total', adds.length);
print('Manually removed devices', removals.length);
print('Manually added devices', adds.length - safes.length);
print('Deployed Safes total', safes.length);
return ownershipChanges;
},
},
safes: {
description: 'safe deployments and balances',
command: async () => {
const safes = await fetchAllFromGraph('safes', 'id balances { amount }');
print('Deployed Safes total', safes.length);
const totalBalance = safes.reduce((acc, safe) => {
acc[safe.id] = safe.balances.reduce((safeAcc, balance) => {
return safeAcc.add(new BN(balance.amount));
}, new BN());
return acc;
}, {});
print(
'Average total balance per Safe',
weiToCircles(avgBN(Object.values(totalBalance))),
);
print(
'Max total balance per Safe',
weiToCircles(maxBN(Object.values(totalBalance))),
);
const safesFormatted = safes.map((safe, index) => {
return {
index: index + 1,
id: safe.id,
balance: totalBalance[safe.id].toString(10),
};
});
return safesFormatted;
},
},
walletDeployedSafes: {
description: 'safe deployments that are shared wallets',
command: async () => {
const safes = await fetchAllFromGraph('safes', 'id', 'deployed: true, organization: true');
print('Deployed Safes that are Shared Wallets', safes.length);
const safesFormatted = safes.map((safe, index) => {
return {
index: index + 1,
};
});
return safesFormatted;
},
},
userDeployedSafes: {
description: 'safe deployments that are not shared wallets',
command: async () => {
const safes = await fetchAllFromGraph('safes', 'id', 'deployed: true, organization: false');
print('Deployed Safes that are Individual accounts', safes.length);
const safesFormatted = safes.map((safe, index) => {
return {
index: index + 1,
};
});
return safesFormatted;
},
},
velocity: {
description: 'transfer velocity',
command: async () => {
const notifications = await fetchAllFromGraph(
'notifications',
'id time hubTransfer { id from to amount }',
'type: HUB_TRANSFER',
);
const data = {};
let timestampMin = 9999999999999;
let timestampMax = 0;
// Summarize transfer amounts per day
notifications.forEach(({ hubTransfer, time }) => {
const timestamp = parseInt(`${time}000`);
timestampMin = Math.min(timestamp, timestampMin);
timestampMax = Math.max(timestamp, timestampMax);
const date = DateTime.fromMillis(timestamp);
const dateFormatted = date.toFormat('yyyy/MM/dd');
if (!(dateFormatted in data)) {
data[dateFormatted] = new BN();
}
data[dateFormatted] = data[dateFormatted].add(
new BN(hubTransfer.amount),
);
});
// Fill in days without any transfers
const interval = Interval.fromDateTimes(
DateTime.fromMillis(timestampMin),
DateTime.fromMillis(timestampMax),
).splitBy({ days: 1 });
interval.forEach((intervalDay) => {
const dateFormatted = intervalDay.start.toFormat('yyyy/MM/dd');
if (!(dateFormatted in data)) {
data[dateFormatted] = new BN();
}
});
// Sort dates and add index
const velocity = Object.keys(data)
.map((date) => {
return {
amount: data[date].toString(10),
date,
};
})
.sort((itemA, itemB) => itemA.date.localeCompare(itemB.date))
.map((item, index) => {
item.index = index + 1;
return item;
});
print('Total days recorded', velocity.length);
print(
'Velocity (Circles / Day)',
weiToCircles(avgBN(pick(velocity, 'amount'))),
);
print(
'Max velocity (one day)',
weiToCircles(maxBN(pick(velocity, 'amount'))),
);
return velocity;
},
},
};
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
module.exports = {
___: {
analyses,
configuration,
},
...Object.keys(analyses).reduce((acc, key) => {
acc[`get${capitalizeFirstLetter(key)}`] = analyses[key].command;
return acc;
}, {}),
setConfiguration,
utils: {
avg,
avgBN,
count,
maxBN,
pick,
weiToCircles,
},
};