-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.js
869 lines (774 loc) · 26.1 KB
/
data.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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
import { parseEncointerBalance } from "@encointer/types";
import db from "./db.js";
import {
gatherTransactionData,
getRewardsIssueds,
getBlockNumberByTimestamp,
getTransactionVolume,
getAllIssues,
getAllBlocksByBlockHeights,
getReputableRegistrations,
getAllTransfers,
} from "./graphQl.js";
import {getMonthName, mapRescueCids, parseCid, toNativeDecimal} from "./util.js";
import BN from "bn.js";
function canBeCached(month, year) {
return monthIsOver(month, year);
}
function monthIsOver(month, year) {
const now = new Date();
const yearNow = now.getUTCFullYear();
let monthNow = now.getUTCMonth();
return year < yearNow || month < monthNow;
}
function monthIsInFuture(month, year) {
const now = new Date();
const yearNow = now.getUTCFullYear();
let monthNow = now.getUTCMonth();
return year > yearNow || (year === yearNow && month > monthNow);
}
function getMonthProgress() {
const currentDate = new Date();
const year = currentDate.getFullYear();
const month = currentDate.getMonth();
const totalDaysInMonth = new Date(year, month + 1, 0).getDate();
const currentDay = currentDate.getDate();
const monthProgress = (currentDay / totalDaysInMonth);
return monthProgress.toFixed(4);
}
export async function gatherAccountingOverview(
api,
account,
cid,
year,
month,
includeCurrentMonth = false
) {
const now = new Date();
const yearNow = now.getUTCFullYear();
// we loop over all months including the last and then skip the last month computation at the end.
if (year < yearNow) {
includeCurrentMonth = false;
month += 1;
}
const cachedData = await db.getFromAccountDataCache(account, year, cid);
const data = [];
// encointer started in june 2022
const startMonth = year === 2022 ? 5 : 0;
for (let i = startMonth; i < month; i++) {
const cachedMonthItem = cachedData?.filter((e) => e.month === i)?.[0];
if (cachedMonthItem) {
data.push(cachedMonthItem);
} else {
const accountingData = await getAccountingData(
api,
account,
cid,
year,
i
);
data.push(accountingData);
await db.insertIntoAccountDataCache(
account,
year,
i,
cid,
accountingData
);
}
}
if (includeCurrentMonth) {
const currentMonthData = await getAccountingData(
api,
account,
cid,
year,
month
);
data.push(currentMonthData);
}
return data;
}
async function getBalance(api, cid, address, at) {
const balanceEntry = await api.query.encointerBalances.balance.at(
at,
cid,
address
);
return {
principal: parseEncointerBalance(balanceEntry.principal.bits),
lastUpdate: balanceEntry.lastUpdate.toNumber(),
};
}
export async function getDemurragePerBlock(api, cid, at) {
const demurragePerBlock =
await api.query.encointerBalances.demurragePerBlock.at(at, cid);
return parseEncointerBalance(demurragePerBlock.bits);
}
function getLastTimeStampOfMonth(year, monthIndex) {
return new Date(
Date.UTC(year, monthIndex + 1, 0, 23, 59, 59, 999)
).getTime();
}
function getFirstTimeStampOfMonth(year, monthIndex) {
return new Date(Date.UTC(year, monthIndex)).getTime();
}
export async function getFirstBlockOfMonth(year, monthIndex) {
const firstTimestamp = getFirstTimeStampOfMonth(year, monthIndex);
const blockNumber = await getBlockNumberByTimestamp(firstTimestamp);
return blockNumber;
}
export async function getLastBlockOfMonth(api, year, monthIndex) {
const lastTimestamp = getLastTimeStampOfMonth(year, monthIndex);
if (new Date() < new Date(lastTimestamp)) {
// we are not at the end of the month yet, so we return the current blocknumber
return (await api.rpc.chain.getBlock()).block.header.number;
}
const blockNumber = await getBlockNumberByTimestamp(lastTimestamp);
return blockNumber;
}
export function applyDemurrage(principal, elapsedBlocks, demurragePerBlock) {
return principal * Math.exp(-demurragePerBlock * elapsedBlocks);
}
async function getDemurrageAdjustedBalance(api, address, cid, blockNumber) {
const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
const cidDecoded = parseCid(cid);
let balanceEntry = await getBalance(api, cidDecoded, address, blockHash);
const demurragePerBlock = await getDemurragePerBlock(
api,
cidDecoded,
blockHash
);
const balance = applyDemurrage(
balanceEntry.principal,
blockNumber - balanceEntry.lastUpdate,
demurragePerBlock
);
return balance;
}
export async function getAccountingData(api, account, cid, year, month) {
const start = getFirstTimeStampOfMonth(year, month);
const end = getLastTimeStampOfMonth(year, month);
const lastBlockOfMonth = await getLastBlockOfMonth(api, year, month);
const lastBlockOfPreviousMonth = await getLastBlockOfMonth(
api,
year,
month - 1
);
const [
incoming,
outgoing,
issues,
sumIncoming,
sumOutgoing,
sumIssues,
numDistinctClients,
] = await gatherTransactionData(start, end, account, cid);
const txnLog = generateTxnLog(incoming, outgoing, issues);
const dailyDigest = generateDailyDigestFromTxnLog(txnLog);
const balance = await getDemurrageAdjustedBalance(
api,
account,
cid,
lastBlockOfMonth
);
const previousBalance = await getDemurrageAdjustedBalance(
api,
account,
cid,
lastBlockOfPreviousMonth
);
return {
month,
incomeMinusExpenses: sumIncoming - sumOutgoing,
sumIssues,
balance,
numIncoming: incoming.length,
numOutgoing: outgoing.length,
sumIncoming,
sumOutgoing,
numIssues: issues.length,
numDistinctClients,
costDemurrage:
previousBalance + sumIncoming - sumOutgoing + sumIssues - balance,
avgTxnValue: incoming.length > 0 ? sumIncoming / incoming.length : 0,
txnLog,
dailyDigest,
};
}
export async function getSelectedRangeData(api, account, cid, start, end) {
const [
incoming,
outgoing,
issues,
sumIncoming,
sumOutgoing,
sumIssues,
numDistinctClients,
] = await gatherTransactionData(start, end, account, cid);
const txnLog = generateTxnLog(incoming, outgoing, issues);
const dailyDigest = generateDailyDigestFromTxnLog(txnLog);
const startBalance = await getDemurrageAdjustedBalance(
api,
account,
cid,
await getBlockNumberByTimestamp(start)
);
const endBalance = await getDemurrageAdjustedBalance(
api,
account,
cid,
await getBlockNumberByTimestamp(end)
);
return {
dailyDigest,
startBalance,
endBalance,
incomeMinusExpenses: sumIncoming - sumOutgoing,
sumIssues,
numIncoming: incoming.length,
numOutgoing: outgoing.length,
sumIncoming,
sumOutgoing,
numIssues: issues.length,
numDistinctClients,
costDemurrage:
startBalance + sumIncoming - sumOutgoing + sumIssues - endBalance,
avgTxnValue: incoming.length > 0 ? sumIncoming / incoming.length : 0,
};
}
async function enrichRewardsIssueds(api, rewardsIssueds, cachedData, cid) {
// sorting is important for chaching
// such that we can stop processing the events as soon
// as the data from the given cycle is in the cache
rewardsIssueds.sort((a, b) => b.timestamp - a.timestamp);
const rewardsIssuedsWithCindexAndNominalIncome = [];
for (const issueEvent of rewardsIssueds) {
const h = await api.rpc.chain.getBlockHash(issueEvent.blockNumber);
const apiAt = await api.at(h);
let mappedCid = mapRescueCids(cid, parseInt(issueEvent.blockNumber));
const cidDecoded = parseCid(mappedCid);
let [nominalIncome, cindex, phase] = await apiAt.queryMulti([
[apiAt.query.encointerCommunities.nominalIncome, cidDecoded],
[apiAt.query.encointerScheduler.currentCeremonyIndex],
[apiAt.query.encointerScheduler.currentPhase],
]);
cindex = cindex.toNumber();
issueEvent.cindex =
phase.toHuman() === "Registering" ? cindex - 1 : cindex;
issueEvent.nominalIncome = parseEncointerBalance(nominalIncome.bits);
// we patch this because on chain the nominal income was not set during the first rescue ceremonie
if (parseInt(issueEvent.blockNumber) === 808023)
issueEvent.nominalIncome = 22;
if (cachedData && cindex.toString() in cachedData) break;
rewardsIssuedsWithCindexAndNominalIncome.push(issueEvent);
}
return rewardsIssuedsWithCindexAndNominalIncome;
}
function reduceRewardsIssuedsWithCindexAndNominalIncome(data) {
return data.reduce((acc, cur) => {
const cindex = cur.cindex;
const numParticipants = parseInt(cur.data[2]);
const nominalIncome = cur.nominalIncome;
acc[cindex] = acc[cindex] || {};
acc[cindex].numParticipants =
(acc[cindex].numParticipants || 0) + numParticipants;
acc[cindex].totalRewards =
(acc[cindex].totalRewards || 0) + numParticipants * nominalIncome;
return acc;
}, {});
}
export async function gatherRewardsData(api, cid) {
const rewardsIssueds = await getRewardsIssueds(cid);
const currentCindex = (
await api.query.encointerScheduler.currentCeremonyIndex()
).toNumber();
const cachedData = (await db.getFromRewardsDataCache(cid))?.data;
const rewardsIssuedsWithCindexAndNominalIncome = await enrichRewardsIssueds(
api,
rewardsIssueds,
cachedData,
cid
);
const newData = reduceRewardsIssuedsWithCindexAndNominalIncome(
rewardsIssuedsWithCindexAndNominalIncome
);
let result = newData;
if (cachedData) result = { ...result, ...cachedData };
// cache only data that is sure not to change anymore
const dataToBeCached = Object.fromEntries(
Object.entries(result).filter(
([key]) => parseInt(key) < currentCindex - 1
)
);
await db.insertIntoRewardsDataCache(cid, dataToBeCached);
return result;
}
export function generateTxnLog(incoming, outgoing, issues) {
const incomingLog = incoming.map((e) => ({
blockNumber: e.blockNumber.toString(),
timestamp: e.timestamp.toString(),
counterParty: e.data[1],
amount: e.data[3],
}));
const outgoingLog = outgoing.map((e) => ({
blockNumber: e.blockNumber.toString(),
timestamp: e.timestamp.toString(),
counterParty: e.data[2],
amount: -e.data[3],
}));
const issuesLog = issues.map((e) => ({
blockNumber: e.blockNumber.toString(),
timestamp: e.timestamp.toString(),
counterParty: "ISSUANCE",
amount: e.data[2],
}));
const txnLog = incomingLog.concat(outgoingLog).concat(issuesLog);
txnLog.sort((a, b) => parseInt(a.timestamp) - parseInt(b.timestamp));
return txnLog;
}
export function generateNativeTxnLog(incoming, incomingDrips, incomingXcm, outgoing, outgoingXcm) {
const incomingLog = incoming.map((e) => ({
blockNumber: e.blockNumber.toString(),
timestamp: e.timestamp.toString(),
counterParty: e.signer.Id,
amount: toNativeDecimal(e.args.value),
}));
const incomingDripsLog = incomingDrips.map((e) => {
return {
blockNumber: e.blockNumber.toString(),
timestamp: e.timestamp.toString(),
counterParty: e.data[0],
amount: toNativeDecimal(e.data[2]),
}
});
const incomingXcmLog = incomingXcm.map((e) => {
return {
blockNumber: e.blockNumber.toString(),
timestamp: e.timestamp.toString(),
counterParty: "XCMteleporter",
amount: toNativeDecimal(e.data.amount),
}
});
const outgoingLog = outgoing.map((e) => ({
blockNumber: e.blockNumber.toString(),
timestamp: e.timestamp.toString(),
counterParty: e.args.dest.Id,
amount: -1 * toNativeDecimal(e.args.value),
}));
const outgoingXcmLog = outgoingXcm.map((e) => {
let amount;
if (e.args.assets.V1) {
amount = toNativeDecimal(e.args.assets.V1[0].fun.Fungible);
} else if (e.args.assets.V2) {
amount = toNativeDecimal(e.args.assets.V2[0].fun.Fungible);
} else if (e.args.assets.V3) {
amount = toNativeDecimal(e.args.assets.V3[0].fun.Fungible);
} else if (e.args.assets.V4) {
amount = toNativeDecimal(e.args.assets.V4[0].fun.Fungible);
} else {
amount = 0;
}
let dest;
if (e.args.dest.V1) {
if (e.args.dest.V1.parents === "1") {
dest = (e.args.dest.V1.interior === "Here") ? "Relay" : "Para";
} else { dest = "unknown"; }
} else if (e.args.dest.V2) {
if (e.args.dest.V2.parents === "1") {
dest = (e.args.dest.V2.interior === "Here") ? "Relay" : "Para";
} else { dest = "unknown"; }
} else if (e.args.dest.V3) {
if (e.args.dest.V3.parents === "1") {
dest = (e.args.dest.V3.interior === "Here") ? "Relay" : "Para";
} else { dest = "unknown"; }
} else if (e.args.dest.V4) {
if (e.args.dest.V4.parents === "1") {
dest = (e.args.dest.V4.interior === "Here") ? "Relay" : "Para";
} else { dest = "unknown"; }
} else {
dest = "unknown";
}
return {
blockNumber: e.blockNumber.toString(),
timestamp: e.timestamp.toString(),
counterParty: dest,
amount: -amount,
};
});
const txnLog = incomingLog
.concat(incomingDripsLog)
.concat(incomingXcmLog)
.concat(outgoingLog)
.concat(outgoingXcmLog);
txnLog.sort((a, b) => parseInt(a.timestamp) - parseInt(b.timestamp));
return txnLog;
}
function groupTransactionsByDay(txnLog) {
return txnLog.reduce((acc, cur) => {
const d = new Date(parseInt(cur.timestamp));
const dayString = `${getMonthName(d.getUTCMonth())} ${d.getUTCDate()}`;
acc[dayString] = acc[dayString] || [];
acc[dayString].push(cur);
return acc;
}, {});
}
function generateDailyDigestFromTxnLog(txnLog) {
const groupedTransactions = groupTransactionsByDay(txnLog);
const result = {};
for (const [dayString, txns] of Object.entries(groupedTransactions)) {
let sumIncoming = 0;
let numIncoming = 0;
let sumOutgoing = 0;
let numOutgoing = 0;
let sumIssues = 0;
let numIssues = 0;
const distinctClients = new Set();
for (const txn of txns) {
if (txn.amount > 0) {
if (txn.counterParty === "ISSUANCE") {
numIssues++;
sumIssues += txn.amount;
} else {
numIncoming++;
sumIncoming += txn.amount;
distinctClients.add(txn.counterParty);
}
} else {
numOutgoing++;
sumOutgoing += -txn.amount;
}
}
result[dayString] = {
sumIncoming,
numIncoming,
sumOutgoing,
numOutgoing,
sumIssues,
numIssues,
numDistinctClients: distinctClients.size,
avgTxnValue: numIncoming ? sumIncoming / numIncoming : 0,
};
}
return result;
}
async function getTotalIssuance(api, cid, blockNumber) {
const blockHash = await api.rpc.chain.getBlockHash(blockNumber);
cid = mapRescueCids(cid, blockNumber);
const cidDecoded = parseCid(cid);
return parseEncointerBalance(
(
await api.query.encointerBalances.totalIssuance.at(
blockHash,
cidDecoded
)
).principal.bits
);
}
export async function getMoneyVelocity(
api,
cid,
year,
month,
useTotalVolume = false
) {
if(monthIsInFuture(month, year)) throw Exception("month is in future")
const monthOver = monthIsOver(month, year)
const cachedData = await db.getFromGeneralCache("moneyVelocity", {
cid,
year,
month,
});
if (cachedData.length === 1) return cachedData[0].moneyVelocity;
let totalTurnoverOrVolume = 0;
if (useTotalVolume) {
totalTurnoverOrVolume = await getVolume(cid, year, month);
} else {
let accountingData;
if (monthOver) {
accountingData = await db.getFromAccountDataCacheByMonth(
month,
year,
cid
);
} else {
console.error("not implemented yet for current month");
accountingData = []
// accountingData = await getAccountingData(
// api,
// account,
// cid,
// year,
// i
// );
}
totalTurnoverOrVolume = accountingData.reduce(
(acc, cur) => acc + cur.sumIncoming,
0
);
}
const firstBlockOfMonth = await getFirstBlockOfMonth(year, month);
const lastBlockOfMonth = await getLastBlockOfMonth(api, year, month);
const totalIssuanceStart = await getTotalIssuance(
api,
cid,
firstBlockOfMonth
);
const totalIssuanceEnd = await getTotalIssuance(api, cid, lastBlockOfMonth);
const averagetotalIssuance = (totalIssuanceStart + totalIssuanceEnd) * 0.5;
if(!monthOver) {
const monthProgress = getMonthProgress()
if(monthProgress === 0) return 0
totalTurnoverOrVolume /= monthProgress
}
const moneyVelocity = (totalTurnoverOrVolume * 12) / averagetotalIssuance;
if (canBeCached(month, year)) {
await db.insertIntoGeneralCache(
"moneyVelocity",
{ cid, year, month },
{ moneyVelocity }
);
}
return moneyVelocity;
}
export async function getVolume(cid, year, month) {
const cachedData = await db.getFromGeneralCache("transactionVolume", {
cid,
year,
month,
});
if (cachedData.length === 1) return cachedData[0].transactionVolume;
const start = getFirstTimeStampOfMonth(year, month);
const end = getLastTimeStampOfMonth(year, month);
const transactionVolume = await getTransactionVolume(cid, start, end);
if (canBeCached(month, year)) {
await db.insertIntoGeneralCache(
"transactionVolume",
{ cid, year, month },
{ transactionVolume }
);
}
return transactionVolume;
}
async function getIssuedsWithCindex(cid) {
const issueds = await getAllIssues(cid);
const blocks = await getAllBlocksByBlockHeights([
...new Set(issueds.map((c) => c.blockNumber)),
]);
issueds.forEach((i) => {
let block = blocks.find((b) => b.height === i.blockNumber);
i.cindex = block.cindex;
if (block.phase === "REGISTERING") i.cindex--;
});
return issueds;
}
export async function getCumulativeRewardsData(api, cid) {
const reputationLifetime =
await api.query.encointerCeremonies.reputationLifetime();
const issueds = await getIssuedsWithCindex(cid);
const reputablesByCindex = issueds.reduce((acc, cur) => {
acc[cur.cindex] = acc[cur.cindex] || [];
acc[cur.cindex].push(cur.data[1]);
return acc;
}, {});
const cumulativeReputables = {};
Object.keys(reputablesByCindex).forEach((e) => {
let cindex = parseInt(e);
let minCindex = Math.max(1, cindex - reputationLifetime);
let reputables = new Set();
for (let i = minCindex; i <= cindex; i++) {
(reputablesByCindex[`${i}`] || []).forEach((item) =>
reputables.add(item)
);
}
cumulativeReputables[e] = reputables.size;
});
return cumulativeReputables;
}
export async function getFrequencyOfAttendance(api, cid) {
const reputationLifetime =
await api.query.encointerCeremonies.reputationLifetime();
const currentCindex = (
await api.query.encointerScheduler.currentCeremonyIndex()
).toNumber();
const issueds = await getIssuedsWithCindex(cid);
const repuableRegistrations = await getReputableRegistrations(cid);
const data = {};
issueds.forEach((i) => {
const address = i.data[1];
data[address] = data[address] || {
registrations: 0,
reputations: 0,
potentialCindexes: new Set(),
};
data[address].reputations += 1;
for (let j = 1; j <= reputationLifetime; j++)
data[address].potentialCindexes.add(
Math.min(i.cindex + j, currentCindex)
);
});
repuableRegistrations.forEach((r) => {
data[r.data[2]] = data[r.data[2]] || {
registrations: 0,
reputations: 0,
potentialCindexes: new Set(),
};
data[r.data[2]].registrations += 1;
});
const result = {};
const numReputables = Object.keys(data).length;
for (let i = 1; i <= 14; i++) {
const denominator = 2 * i + 1;
const cutoff = 2 / denominator;
result[`${2}/${denominator}`] =
Object.values(data).filter(
(i) => i.registrations / i.potentialCindexes.size >= cutoff
).length / numReputables;
}
return result;
}
async function getTransactionActiviyData(cid, year, month) {
const start = getFirstTimeStampOfMonth(year, month);
const end = getLastTimeStampOfMonth(year, month);
const voucherAddresses = await db.getVoucherAddresses(cid);
const govAddresses = await db.getGovAddresses(cid);
const acceptancePointAddresses = await db.getAcceptancePointAddresses(cid);
const transfers = await getAllTransfers(start, end, cid);
const totalTransactionCount = transfers.length;
const voucherTransactionCount = transfers.filter((t) =>
voucherAddresses.includes(t.data[2])
).length;
const govTransactionCount = transfers.filter((t) =>
govAddresses.includes(t.data[2])
).length;
const acceptancePointTransactionCount = transfers.filter((t) =>
acceptancePointAddresses.includes(t.data[2])
).length;
return {
month,
voucherTransactionCount,
govTransactionCount,
acceptancePointTransactionCount,
personalTransactionCount:
totalTransactionCount -
voucherTransactionCount -
govTransactionCount -
acceptancePointTransactionCount,
};
}
export async function getTransactionActivityLog(
cid,
year,
month,
includeCurrentMonth = false
) {
const now = new Date();
const yearNow = now.getUTCFullYear();
// we loop over all months including the last and then skip the last month computation at the end.
if (year < yearNow) {
includeCurrentMonth = false;
month += 1;
}
const cachedData = await db.getFromGeneralCache("transactionActivity", {
cid,
year,
});
const data = [];
// encointer started in june 2022
const startMonth = year === 2022 ? 5 : 0;
for (let i = startMonth; i < month; i++) {
const cachedMonthItem = cachedData?.filter((e) => e.month === i)?.[0];
if (cachedMonthItem) {
data.push(cachedMonthItem);
} else {
const transactionActivityData = await getTransactionActiviyData(
cid,
year,
i
);
data.push(transactionActivityData);
await db.insertIntoGeneralCache(
"transactionActivity",
{ cid, year, month: i },
transactionActivityData
);
}
}
if (includeCurrentMonth) {
const currentMonthData = await getTransactionActiviyData(
cid,
year,
month
);
data.push(currentMonthData);
}
return data;
}
export async function getSankeyReport(
api,
cid,
account,
start,
end,
startBlockNumber,
endBlockNumber,
acceptancePointAddresses
) {
const [
incoming,
outgoing,
issues,
sumIncoming,
sumOutgoing,
sumIssues,
numDistinctClients,
] = await gatherTransactionData(start, end, account, cid);
const startBalance = await getDemurrageAdjustedBalance(
api,
account,
cid,
startBlockNumber
);
const endBalance = await getDemurrageAdjustedBalance(
api,
account,
cid,
endBlockNumber
);
const sum = (arr) => arr.reduce((partialSum, a) => partialSum + a, 0);
const ciiToBiz = sumIssues;
const b2bToBiz = sum(
incoming
.filter((e) => acceptancePointAddresses.includes(e.data[1]))
.map((e) => e.data[3])
);
const retailToBiz = sumIncoming - b2bToBiz;
const bizToSuppliers = sum(
outgoing
.filter((e) => acceptancePointAddresses.includes(e.data[2]))
.map((e) => e.data[3])
);
const bizToLea = sum(
outgoing
.filter((e) =>
[
"FD3mHcDJRGcKhT8gzbfiV7fuGnd7hHGdd1VMnYd6LiVv4np",
"5DkVGErvJLPTgec4C73Xk7boEVTKXJYDuCro2kPHkB3XGARh",
"EG6vZCnvhQPSJRVxorae4xoP5jZKyMQMahYRQfFDyG21KJC",
].includes(e.data[2])
)
.map((e) => e.data[3])
);
const bizToDemurrage =
startBalance + sumIncoming + sumIssues - sumOutgoing - endBalance;
const bizToUnknown = sumOutgoing - bizToSuppliers - bizToLea;
return {
ciiToBiz,
b2bToBiz,
retailToBiz,
bizToSuppliers,
bizToLea,
bizToDemurrage,
bizToUnknown,
};
}