-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
2366 lines (2233 loc) · 106 KB
/
script.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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Caches to store fetched data and reduce network requests
const nameCache = {};
const hiddenPollsCache = {};
const displayNameCache = {};
const accountLevelCache = {};
const pubkeyCache = {};
let cachedTxs = [];
let appResultsMap = {};
let currentSortColumnMap = {};
let sortDirectionMap = {};
const sortDirectionsDefault = {
'Rating': -1, // Descending
'Name': 1, // Ascending
'Size': -1, // Descending
'Created': -1, // Descending
'Last Updated': -1 // Descending
};
document.addEventListener('DOMContentLoaded', function() {
initApplication();
showSection('home');
});
document.getElementById('node-checkbox').addEventListener('change', changeRefreshSetting, false);
function initApplication() {
document.getElementById('home-page').style.display = 'block';
document.getElementById('menu-home').classList.add('active-menu');
document.getElementById('menu-button').addEventListener('mouseover', showOverlay);
document.getElementById('main-content').addEventListener('mouseover', hideOverlay);
if ((typeof qortalRequest === 'undefined') || (_qdnContext === 'gateway')) {
document.getElementById('login-button').innerHTML =
`<a href='https://qortal.dev' target='blank'>Download</a>`;
} else {
document.getElementById('login-button').addEventListener('click', getUserAccount);
}
initHomePage();
getNodeStatus();
getNodeInfo();
}
let autoRefreshInterval;
function changeRefreshSetting(event) {
var refreshing = event.target.checked;
if (refreshing) {
startNodeRefreshing();
} else {
stopNodeRefreshing();
}
}
function startNodeRefreshing() {
refreshNode();
autoRefreshInterval = setInterval(refreshNode, 15000);
}
function stopNodeRefreshing() {
clearInterval(autoRefreshInterval);
}
function refreshNode() {
getNodeStatus();
getNodeInfo();
}
function getNodeStatus() {
fetch('/admin/status')
.then(response => response.json())
.then(status => {
let nodeStatus = document.getElementById('node-status')
nodeStatus.textContent =
`${typeof qortalRequest !== 'function'?'Gateway: ':'Core: '}`;
if (status.isSynchronizing === false && status.syncPercent == 100) {
nodeStatus.textContent += `${status.isMintingPossible?'Minting':'Synced'}`;
} else if (status.isSynchronizing === true) {
nodeStatus.textContent += 'Syncing';
}
document.getElementById('node-height').textContent = `Height: ${status.height}`;
document.getElementById('node-peers').textContent =
`Peers: ${status.numberOfConnections}`;
})
.catch(error => console.error('Error getting node status:', error));
}
function getNodeInfo() {
fetch('/admin/info')
.then(response => response.json())
.then(info => {
document.getElementById('node-version').textContent =
`Version: ${info.buildVersion.slice(7, info.buildVersion.indexOf("-", 7))}`;
})
.catch(error => console.error('Error getting node info:', error));
}
function fetchQdnTotalSize() {
document.getElementById('qdn-size').textContent = 'Loading';
let totalSize = 0;
fetch('/arbitrary/resources')
.then(response => response.json())
.then(data => {
data.forEach(transaction => {
const size = transaction.size;
totalSize += size;
});
document.getElementById('qdn-size').textContent = formatSize(totalSize);
})
.catch(error => {
document.getElementById('qdn-size').textContent = 'Error';
console.error('Error fetching QDN size:', error);
});
}
function fetchBlockHeight() {
document.getElementById('home-blockheight').textContent = 'Loading';
return fetch('/blocks/height')
.then(response => response.text())
.then(data => {
document.getElementById('home-blockheight').textContent = data;
return data;
})
.catch(error => {
document.getElementById('home-blockheight').textContent = `Error fetching block height: ${error}`;
console.error('Error fetching block height:', error);
});
}
function fetchBlockReward(currentHeight) {
document.getElementById('home-blockreward').textContent = 'Loading';
let reward = 5;
const decreaseInterval = 259200;
if (currentHeight > decreaseInterval) {
reward -= Math.floor((currentHeight - 1) / decreaseInterval) * 0.25;
}
document.getElementById('home-blockreward').textContent = `${reward.toFixed(2)} QORT`;
}
function fetchCirculatingSupply() {
document.getElementById('home-totalsupply').textContent = 'Loading';
return fetch('/stats/supply/circulating')
.then(response => response.text())
.then(data => {
document.getElementById('home-totalsupply').textContent = `${parseFloat(data).toFixed(2)} QORT`;
return parseFloat(data);
})
.catch(error => {
document.getElementById('home-totalsupply').textContent = `Error fetching circulating supply: ${error}`;
console.error('Error fetching circulating supply:', error);
throw error;
});
}
function fetchHomeDailyBlocks() {
document.getElementById('home-blocktime').textContent = 'Loading';
return fetch('/blocks/height')
.then(response => response.text())
.then(currentBlockHeight => {
return currentBlockHeight;
})
.then(currentBlockHeight => {
currentBlockHeight = parseInt(currentBlockHeight);
return fetch('/utils/timestamp')
.then(response => response.text())
.then(currentTimestamp => {
const oneDayAgoTimestamp = parseInt(currentTimestamp) - (24 * 60 * 60 * 1000);
return fetch('/blocks/timestamp/' + oneDayAgoTimestamp)
.then(response => response.json())
.then(data => {
const oneDayAgoBlockHeight = data.height;
const blocksInPastDay = currentBlockHeight - oneDayAgoBlockHeight;
const blockTime = Math.floor(24*60*60/blocksInPastDay);
document.getElementById('home-blocktime').textContent = `${blockTime} seconds`;
document.getElementById('home-blocksperday').textContent = blocksInPastDay;
return blocksInPastDay;
});
});
})
.catch(error => {
console.error('Error in fetchHomeDailyBlocks:', error);
});
}
function calculateDailyQort() {
document.getElementById('home-qortperday').textContent = 'Loading';
const blocksInPastDay = parseInt(document.getElementById('home-blocksperday').textContent);
const blockReward = parseFloat(document.getElementById('home-blockreward').textContent);
const dailyQort = blocksInPastDay * blockReward;
const totalCirculatingSupply = parseFloat(document.getElementById('home-totalsupply').textContent);
const percentageOfTotal = (dailyQort / totalCirculatingSupply) * 100;
const dailyQortString = `${dailyQort.toFixed(2)} QORT (${percentageOfTotal.toFixed(2)}% of total)`;
document.getElementById('home-qortperday').textContent = dailyQortString;
}
function fetchOnlineAccounts() {
let totalCount = 0;
fetch('/addresses/online/levels')
.then(response => response.json())
.then(data => {
const qortPerDayString = document.getElementById('home-qortperday').textContent;
const qortPerDay = parseFloat(qortPerDayString.match(/\d+/)[0]);
const blocksInPastDay = parseInt(document.getElementById('home-blocksperday').textContent);
const qortPerThousandBlocks = (qortPerDay/blocksInPastDay)*1000;
const levelCounts = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0};
data.forEach(account => {
totalCount += account.count;
document.getElementById(`level-${account.level}-count`).textContent = account.count;
levelCounts[account.level] += account.count;
});
const percentages = [6, 13, 19, 26, 32, 3];
percentages.forEach((percent, index) => {
const tierCount = levelCounts[(index*2)+1] + levelCounts[(index*2)+2]
const tierReward = (qortPerThousandBlocks * (percent / 100)) / tierCount;
for (let level = index * 2 + 1; level <= index * 2 + 2; level++) {
if (levelCounts[11] === 0) {
if ((level === 9) && (levelCounts[9] < 30)) {
document.getElementById(`level-${level}-reward`).textContent = '0';
} else if ((level === 10) && (levelCounts[9] < 30)) {
document.getElementById(`level-${level}-reward`).textContent = ((tierReward/32)*(32+3)).toFixed(3);
} else if (level === 10) {
document.getElementById(`level-${level}-reward`).textContent = ((tierReward/32)*(3)).toFixed(3);
} else if (level === 11) {
document.getElementById(`level-${level}-reward`).textContent = '<- F';
} else if (level < 11) {
document.getElementById(`level-${level}-reward`).textContent = tierReward.toFixed(3);
}
} else {
if ((level === 9 || level === 10) && (levelCounts[9]+levelCounts[10] < 30)) {
document.getElementById(`level-${level}-reward`).textContent = '0';
} else if ((level === 11) && (levelCounts[9]+levelCounts[10] < 30)) {
document.getElementById(`level-${level}-reward`).textContent = ((tierReward/3)*(32+3)).toFixed(3);
} else if (level < 12) {
document.getElementById(`level-${level}-reward`).textContent = tierReward.toFixed(3);
}
}
}
});
document.getElementById(`total-count`).textContent = `Total: ${totalCount}`;
})
.catch(error => console.error('Error fetching online accounts:', error));
}
function fetchUnconfirmedTransactions() {
document.getElementById('transaction-table').innerHTML = '<tr><th>Loading</th></tr>';
fetch('/transactions/unconfirmed')
.then(response => response.json())
.then(data => {
const transactionTypes = {};
data.forEach(transaction => {
const type = transaction.type;
transactionTypes[type] = (transactionTypes[type] || 0) + 1;
});
const totalUnconfirmed = data.length;
let tableHtmlUpper = '<table><tr><th>Tx Type:</th>';
Object.keys(transactionTypes).forEach(type => {
tableHtmlUpper += `<th>${type}</th>`;
});
tableHtmlUpper += '</tr>';
let tableHtmlLower = `<tr><th>Total: ${totalUnconfirmed}</th>`;
Object.keys(transactionTypes).forEach(type => {
tableHtmlLower += `<td>${transactionTypes[type]}</td>`;
});
tableHtmlLower += '</tr></table>';
document.getElementById('transaction-table').innerHTML = tableHtmlUpper + tableHtmlLower;
})
.catch(error => {
document.getElementById('transaction-table').innerHTML = `<tr><th>Error fetching unconfirmed txs:</th><td>${error}</td></tr>`;
console.error('Error fetching unconfirmed transactions:', error);
});
}
async function fetchAndCacheTxs(params, limit) {
try {
// Clear previous results and reset pagination
cachedTxs = [];
currentPage = 1;
resultsPerPage = parseInt(limit) || 20;
let queryParams = [];
if (params.startBlock) {
queryParams.push(`startBlock=${params.startBlock}`);
}
if (params.blockLimit) {
queryParams.push(`blockLimit=${params.blockLimit}`);
}
if (params.txGroupId) {
queryParams.push(`txGroupId=${params.txGroupId}`);
}
if (params.txTypes && params.txTypes.length > 0) {
params.txTypes.forEach(type => {
queryParams.push(`txType=${type}`);
});
}
if (params.address) {
queryParams.push(`address=${encodeURIComponent(params.address)}`);
}
if (params.reverse !== undefined) {
queryParams.push(`reverse=${params.reverse}`);
} else {
queryParams.push(`reverse=true`);
}
if ((params.confirmed !== undefined) && (params.confirmed === false)) {
queryParams.push(`confirmationStatus=UNCONFIRMED`);
} else {
queryParams.push(`confirmationStatus=CONFIRMED`);
}
if (params.offset) {
queryParams.push(`offset=${params.offset}`);
}
if (limit) {
queryParams.push(`limit=${limit}`);
}
const queryString = queryParams.join('&');
const tableBody = document.getElementById('txs-table').getElementsByTagName('tbody')[0];
tableBody.innerHTML = `<tr><td colspan="7">Fetching: /transactions/search?${queryString}</td></tr>`;
console.log(`Fetching: /transactions/search?${queryString}`);
// Fetch transactions with limit
const response = await fetch(`/transactions/search?${queryString}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
cachedTxs = await response.json();
// Calculate total pages
totalPages = Math.ceil(cachedTxs.length / resultsPerPage);
// Display the first page
displayTxsPage(currentPage);
} catch (error) {
console.error('Error fetching transactions:', error);
const tableBody = document.getElementById('txs-table').getElementsByTagName('tbody')[0];
tableBody.innerHTML += `<tr><td colspan="7">Error fetching transactions: ${error.message}</td></tr>`;
}
}
async function displayTxsPage(page) {
const tableBody = document.getElementById('txs-table').getElementsByTagName('tbody')[0];
tableBody.innerHTML = '<tr><td colspan="7">Loading</td></tr>'; // Clear previous results
// Calculate start and end indices
const startIndex = (page - 1) * resultsPerPage;
const endIndex = Math.min(startIndex + resultsPerPage, cachedTxs.length);
// Get the transactions for the current page
const txsToDisplay = cachedTxs.slice(startIndex, endIndex);
if (txsToDisplay.length === 0) {
tableBody.innerHTML = '<tr><td colspan="7">No transactions found.</td></tr>';
// document.getElementById('pagination-info').textContent = `Page ${currentPage} of ${totalPages}`;
return;
}
tableBody.innerHTML = ''; // Clear previous results
// Display transactions
for (let tx of txsToDisplay) {
let row = document.createElement('tr');
row.insertCell(0).textContent = tx.blockHeight;
let shortenedSignature = tx.signature.substring(0, 4) + '...' + tx.signature.substring(tx.signature.length - 4);
row.insertCell(1).textContent = shortenedSignature;
row.insertCell(2).textContent = tx.type;
let nameOrAddress = '';
if (tx.creatorAddress === 'QdSnUy6sUiEnaN87dWmE92g1uQjrvPgrWG') {
nameOrAddress = '[Null Account]';
} else {
nameOrAddress = await displayNameOrAddress(tx.creatorAddress);
}
row.insertCell(3).innerHTML = nameOrAddress;
// Handle different transaction types
switch (tx.type) {
case 'PAYMENT':
let payNameOrAddress = await displayNameOrAddress(tx.recipient);
row.insertCell(4).innerHTML = `${parseFloat(tx.amount)} QORT -> ${payNameOrAddress}`;
break;
case 'REGISTER_NAME':
row.insertCell(4).innerHTML = `${tx.creatorAddress}<br>${tx.data}`;
break;
case 'UPDATE_NAME':
row.insertCell(4).innerHTML = `${tx.name} -> ${tx.newName}<br>${tx.newData}`;
break;
case 'SELL_NAME':
row.insertCell(4).innerHTML = `${tx.name} (${parseFloat(tx.amount)} QORT)`;
break;
case 'CANCEL_SELL_NAME':
row.insertCell(4).innerHTML = `${tx.name}`;
break;
case 'BUY_NAME':
let sellerNameOrAddress = await displayNameOrAddress(tx.seller);
row.insertCell(4).innerHTML = `${tx.name}<br>${parseFloat(tx.amount)} QORT -> ${sellerNameOrAddress}`;
break;
case 'CREATE_POLL':
row.insertCell(4).innerHTML = `${tx.pollName}<br>${tx.description}`;
break;
case 'VOTE_ON_POLL':
row.insertCell(4).innerHTML = `${tx.pollName}: ${tx.optionIndex}`;
break;
case 'ARBITRARY':
row.insertCell(4).innerHTML = `${displayServiceName(tx.service)}<br>${tx.identifier}`;
break;
case 'ISSUE_ASSET':
row.insertCell(4).innerHTML = `(${tx.assetId}) ${parseFloat(tx.quantity)} ${tx.assetName}<br>${tx.description}`;
break;
case 'TRANSFER_ASSET':
let xferNameOrAddress = await displayNameOrAddress(tx.recipient);
row.insertCell(4).innerHTML = `${parseFloat(tx.amount)} ${tx.assetName} -> ${xferNameOrAddress}`;
break;
case 'DEPLOY_AT':
row.insertCell(4).innerHTML = `${tx.name}<br>${parseFloat(tx.amount)} QORT -> ${tx.aTAddress}`;
break;
case 'MESSAGE':
row.insertCell(4).innerHTML = `${tx.recipient}`;
break;
// case 'PUBLICIZE':
// N/A
case 'AT':
let atRecipientName = await displayNameOrAddress(tx.recipient)
row.insertCell(4).innerHTML = `${tx.atAddress}<br>${parseFloat(tx.amount)} QORT -> ${atRecipientName}`;
break;
case 'CREATE_GROUP':
row.insertCell(4).innerHTML = `${tx.groupId}: ${tx.groupName}${tx.isOpen ? '' : ' (Private)'}<br>${tx.description}`;
break;
case 'UPDATE_GROUP':
let groupUpdateName = await displayGroupName(tx.groupId)
row.insertCell(4).innerHTML = `${tx.groupId}: ${groupUpdateName}${tx.newIsOpen ? '' : ' (Private)'}<br>${tx.newDescription}`;
break;
case 'ADD_GROUP_ADMIN':
let adminGroupName = await displayGroupName(tx.groupId);
let adminNameOrAddress = await displayNameOrAddress(tx.member)
row.insertCell(4).innerHTML = `${tx.groupId}: ${adminGroupName}<br>${adminNameOrAddress}`;
break;
case 'REMOVE_GROUP_ADMIN':
let removeGroupName = await displayGroupName(tx.groupId);
let removeNameOrAddress = await displayNameOrAddress(tx.admin)
row.insertCell(4).innerHTML = `${tx.groupId}: ${removeGroupName}<br>${removeNameOrAddress}`;
break;
case 'GROUP_BAN':
let banGroupName = await displayGroupName(tx.groupId);
let banNameOrAddress = await displayNameOrAddress(tx.offender)
row.insertCell(4).innerHTML = `${tx.groupId}: ${banGroupName}<br>${banNameOrAddress}`;
break;
case 'CANCEL_GROUP_BAN':
case 'GROUP_KICK':
let kickGroupName = await displayGroupName(tx.groupId);
let kickNameOrAddress = await displayNameOrAddress(tx.member)
row.insertCell(4).innerHTML = `${tx.groupId}: ${kickGroupName}<br>${kickNameOrAddress}`;
break;
case 'GROUP_INVITE':
let groupInviteName = await displayGroupName(tx.groupId);
let inviteeNameOrAddress = await displayNameOrAddress(tx.invitee);
row.insertCell(4).innerHTML = `${inviteeNameOrAddress}<br>${tx.groupId}: ${groupInviteName}`;
break;
case 'CANCEL_GROUP_INVITE':
// needs to link to transaction
row.insertCell(4).innerHTML = `${tx.reference}`;
break;
case 'JOIN_GROUP':
case 'LEAVE_GROUP':
let groupName = await displayGroupName(tx.groupId);
row.insertCell(4).innerHTML = `${tx.groupId}: ${groupName}`;
break;
case 'GROUP_APPROVAL':
// needs to link to transaction
row.insertCell(4).innerHTML = `${tx.pendingSignature}`;
break;
case 'REWARD_SHARE':
let rewardShareNameOrAddress = await displayNameOrAddress(tx.recipient);
row.insertCell(4).innerHTML = `${tx.sharePercent}: ${rewardShareNameOrAddress}`;
break;
case 'ACCOUNT_FLAGS':
let targetNameOrAddress = await displayNameOrAddress(tx.target);
row.insertCell(4).innerHTML = `${targetNameOrAddress}<br>and=${tx.andMask},or=${tx.orMask},xor=${tx.xorMask}`;
break;
case 'ACCOUNT_LEVEL':
let levelNameOrAddress = await displayNameOrAddress(tx.target);
row.insertCell(4).innerHTML = `${levelNameOrAddress} -> Lv.${tx.level}`;
break;
case 'GENESIS':
let genesisNameOrAddress = await displayNameOrAddress(tx.recipient);
row.insertCell(4).innerHTML = `${parseFloat(tx.amount)} (${tx.assetId}) -> ${genesisNameOrAddress}`;
break;
// case 'TRANSFER_PRIVS':
// needs to show previous address
case '':
// Add other cases as needed
/*
// Never Used:
CREATE_ASSET_ORDER
CANCEL_ASSET_ORDER
MULTI_PAYMENT
AIRDROP
SET_GROUP
UPDATE_ASSET
ENABLE_FORGING
// Never Confirmed:
PRESENCE
CHAT
*/
default:
row.insertCell(4).textContent = 'N/A';
break;
}
row.insertCell(5).textContent = parseFloat(tx.fee);
let formattedTimestamp = new Date(tx.timestamp).toLocaleString();
row.insertCell(6).textContent = formattedTimestamp;
tableBody.appendChild(row);
}
// Update pagination info
// document.getElementById('pagination-info').textContent = `Page ${currentPage} of ${totalPages}`;
}
function fetchAndDisplayBlocks() {
let height = 100
const oldTableBody = document.getElementById('blocks-table').getElementsByTagName('tbody')[0];
const oldLastRow = oldTableBody.lastElementChild;
if (oldLastRow) {
height = parseInt(oldLastRow.cells[0].textContent)-1;
} else {
height = parseInt(document.getElementById('node-height').textContent.slice(8));
}
fetch(`/blocks/summaries?start=${height-9}&end=${height+1}`)
.then(response => response.json())
.then(blocks => {
const tableBody = document.getElementById('blocks-table').getElementsByTagName('tbody')[0];
blocks.reverse().forEach(block => {
let row = document.createElement('tr');
let th = document.createElement('td');
th.className = "clickable-name";
th.setAttribute('data-name', block.height);
th.textContent = block.height;
row.appendChild(th);
let shortenedSignature = block.signature.substring(0, 4) + '...' + block.signature.substring(block.signature.length - 4);
row.insertCell(1).textContent = shortenedSignature;
row.insertCell(2).textContent = block.transactionCount;
row.insertCell(3).textContent = block.onlineAccountsCount;
let formattedTimestamp = new Date(block.timestamp).toLocaleString();
row.insertCell(4).textContent = formattedTimestamp;
tableBody.appendChild(row);
});
document.querySelectorAll('.clickable-name').forEach(element => {
element.addEventListener('click', function() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
let target = this.getAttribute('data-name');
searchByBlock(target);
});
});
})
.catch(error => console.error('Error fetching blocks:', error));
}
function searchByHeight() {
const currentHeightText = document.getElementById('node-height').textContent.slice(8);
const currentBlockHeight = parseInt(currentHeightText);
const searchQuery = document.getElementById('block-input').value.trim();
const searchNumber = parseInt(searchQuery, 10);
if (!searchQuery || isNaN(searchNumber)) return;
if (searchNumber >= 1 && searchNumber <= currentBlockHeight) {
searchByBlock(searchNumber);
} else {
document.getElementById('block-details').innerHTML = `<p>Invalid search: ${searchQuery}</p>`;
return;
}
}
function searchByBlock(height) {
document.getElementById('block-details').innerHTML = '';
fetch('/blocks/byheight/' + height)
.then(response => response.json())
.then(result => {
if (result) {
let resultHtml = '<table><tr>';
let shortenedSignature = result.signature.substring(0, 4) + '...' + result.signature.substring(result.signature.length - 4);
resultHtml += `<th>${result.height}</th><td>${shortenedSignature}</td><td>${result.transactionCount} Txs</td>
<td>${result.onlineAccountsCount} Minters</td><td>${new Date(result.timestamp).toLocaleString()}</td></tr></table>`;
if (result.transactionCount > 0) {
fetchTxsBySignature(result.signature);
} else {
const tableBody = document.getElementById('block-txs').getElementsByTagName('tbody')[0];
while (tableBody.firstChild) {
tableBody.removeChild(tableBody.firstChild);
}
}
document.getElementById('block-details').innerHTML = resultHtml;
} else {
document.getElementById('block-details').innerHTML = `<p>Block ${height} not found.</p>`;
}
})
.catch(error => {
document.getElementById('block-details').innerHTML = `<p>Error searching by block: ${error}</p>`;
console.error('Error searching by block:', error);
});
}
async function fetchTxsBySignature(signature) {
try {
const response = await fetch(`/transactions/block/${signature}`);
const txs = await response.json();
const tableBody = document.getElementById('block-txs').getElementsByTagName('tbody')[0];
while (tableBody.firstChild) {
tableBody.removeChild(tableBody.firstChild);
}
txs.sort((a, b) => b.timestamp - a.timestamp);
for (const tx of txs) {
let row = document.createElement('tr');
row.insertCell(0).textContent = tx.blockHeight;
let shortenedSignature = tx.signature.substring(0, 4) + '...' + tx.signature.substring(tx.signature.length - 4);
row.insertCell(1).textContent = shortenedSignature;
row.insertCell(2).textContent = tx.type;
let nameOrAddress = await displayNameOrAddress(tx.creatorAddress);
row.insertCell(3).innerHTML = nameOrAddress;
row.insertCell(4).textContent = tx.fee;
let formattedTimestamp = new Date(tx.timestamp).toLocaleString();
row.insertCell(5).textContent = formattedTimestamp;
tableBody.appendChild(row);
}
} catch (error) {
console.error('Error fetching transactions:', error);
}
}
async function fetchDailyVolumes(timestamp) {
const coins = ['LITECOIN', 'BITCOIN', 'DOGECOIN', 'RAVENCOIN', 'DIGIBYTE', 'PIRATECHAIN'];
for (const coin of coins) {
document.getElementById(`${coin.toLowerCase()}-spent`).textContent = 'Loading';
try {
const response = await fetch(`/crosschain/trades?foreignBlockchain=${coin}&minimumTimestamp=${timestamp}`);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const trades = await response.json();
let dailyQort = 0;
let dailyForeign = 0;
trades.forEach(trade => {
dailyQort += +trade.qortAmount;
dailyForeign += +trade.foreignAmount;
});
if (trades.length > 0) {
const avgPerQort = dailyForeign / dailyQort;
document.getElementById(`${coin.toLowerCase()}-spent`).textContent = `${dailyForeign.toFixed(8)}`;
document.getElementById(`${coin.toLowerCase()}-bought`).textContent = `${dailyQort.toFixed(8)}`;
document.getElementById(`${coin.toLowerCase()}-price`).textContent = `${avgPerQort.toFixed(8)}`;
} else {
document.getElementById(`${coin.toLowerCase()}-spent`).textContent = `0`;
document.getElementById(`${coin.toLowerCase()}-bought`).textContent = `0`;
document.getElementById(`${coin.toLowerCase()}-price`).textContent = `-`;
}
} catch (error) {
console.error(`Error fetching ${coin} daily volume: ${error}`);
}
}
}
async function fetchAndDisplayTrades(start, coin) {
try {
const response = await fetch(`/crosschain/trades?foreignBlockchain=${coin}&minimumTimestamp=${start}`);
const trades = await response.json();
const tableBody = document.getElementById('trades-table').getElementsByTagName('tbody')[0];
tableBody.innerHTML = '';
trades.reverse().forEach(async trade => {
let row = document.createElement('tr');
row.insertCell(0).textContent = trade.qortAmount;
let fromNameOrAddress = await displayNameOrAddress(trade.sellerAddress);
row.insertCell(1).innerHTML = fromNameOrAddress;
let toNameOrAddress = await displayNameOrAddress(trade.buyerReceivingAddress);
row.insertCell(2).innerHTML = toNameOrAddress;
row.insertCell(3).textContent = trade.foreignAmount;
row.insertCell(4).textContent = (trade.foreignAmount / trade.qortAmount).toFixed(8);
let formattedTimestamp = new Date(trade.tradeTimestamp).toLocaleString();
row.insertCell(5).textContent = formattedTimestamp;
tableBody.appendChild(row);
});
} catch (error) {
console.error(`Error fetching ${coin} trades: ${error}`);
}
}
async function searchPolls() {
document.getElementById('poll-results').innerHTML = '<p>Searching...</p>';
let userAddress = document.getElementById('user-address');
// Start building the table header
let tableHtml = `
<table>
<tr>
<th>Poll Name</th>
<th>Description</th>
<th>Owner</th>
<th>Poll Options</th>
<th>Published</th>
</tr>
</table>
<p id="loading-indicator">Loading</p>
`;
// Insert the initial table structure and loading indicator
document.getElementById('poll-results').innerHTML = tableHtml;
// Counters for shown and hidden polls
let shownPollsCount = 0;
let hiddenPollsCount = 0;
try {
const response = await fetch('/polls');
const results = await response.json();
if (results && results.length > 0) {
// Sort the results by published date descending
results.sort((a, b) => b.published - a.published);
// Process each poll sequentially
for (const result of results) {
const [isHidden, displayName, creatorLevel] = await Promise.all([
checkHiddenPolls(result.owner, result.pollName),
displayNameOrAddress(result.owner),
fetchAccountLevel(result.owner)
]);
// Update counters based on poll visibility
if (isHidden) {
hiddenPollsCount++;
} else {
shownPollsCount++;
let publishedString = new Date(result.published).toLocaleString();
let pollOptionsString = result.pollOptions.map(option => option.optionName).join(', ');
// Construct row HTML for this poll
let rowHtml = `
<tr>
<td><span class="clickable-name" data-name="${result.pollName}">${result.pollName}</span>`;
if (userAddress.textContent === shortString(result.owner)) {
rowHtml += `<br><button onclick="hidePoll('${result.pollName}')">Hide from Qombo</button>`;
}
rowHtml += `</td>
<td>${result.description}</td>
<td>${displayName} (Lv.${creatorLevel})</td>
<td>${pollOptionsString}</td>
<td>${publishedString}</td>
</tr>
`;
// Append the row to the table
document.querySelector('#poll-results table').insertAdjacentHTML('beforeend', rowHtml);
// Attach click listener for the clickable poll name
const clickableElement = document.querySelector(`.clickable-name[data-name="${result.pollName}"]`);
if (clickableElement) {
clickableElement.addEventListener('click', function() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
let target = this.getAttribute('data-name');
fetchPoll(target);
});
} else {
console.error(`Element not found for pollName: ${result.pollName}`);
}
}
// Optional: Small delay to yield control back to the main thread
//await new Promise(resolve => setTimeout(resolve, 0));
}
// Update the loading indicator after processing all polls
document.getElementById('loading-indicator').innerHTML = `${shownPollsCount} Polls Shown, ${hiddenPollsCount} Polls Hidden`;
} else {
document.getElementById('poll-results').innerHTML = '<p>No results found.</p>';
}
} catch (error) {
console.error('Error searching polls:', error);
document.getElementById('poll-results').innerHTML = `<p>Error: ${error}</p>`;
}
}
async function fetchPoll(pollName) {
try {
const pollResponse = await fetch('/polls/' + encodeURIComponent(pollName));
const pollData = await pollResponse.json();
const voteResponse = await fetch('/polls/votes/' + encodeURIComponent(pollName));
const voteData = await voteResponse.json();
const voteCountMap = new Map(voteData.voteCounts.map(item => [item.optionName, item.voteCount]));
const voteWeightMap = new Map(voteData.voteWeights.map(item => [item.optionName, item.voteWeight]));
pollData.pollOptions.forEach(option => {
option.voteCount = voteCountMap.get(option.optionName) || 0;
option.voteWeight = voteWeightMap.get(option.optionName) || 0;
});
let displayName = await displayNameOrAddress(pollData.owner);
let publishedString = new Date(pollData.published).toLocaleString();
let htmlContent = `<table><tr><th>${pollData.pollName} <button id="copy-embed-link-button" data-poll-name="${encodeURIComponent(pollData.pollName)}">Copy Embed Link</button></th><td>${displayName}</td>`;
htmlContent += `<td>${publishedString}</td></tr></table>`;
htmlContent += `<table><tr><td>${pollData.description}</td></tr></table>`;
htmlContent += `<table><tr><th>Poll Options</th>`;
pollData.pollOptions.forEach((option, index) => {
htmlContent += `<td>Vote <button onclick="voteOnPoll('${pollData.pollName}', ${index})">${option.optionName}</button></td>`;
});
htmlContent += `</tr><tr><th>Vote Counts (Total: ${voteData.totalVotes})</th>`;
pollData.pollOptions.forEach(option => {
let percentage = (option.voteCount/voteData.totalVotes*100).toFixed(2);
htmlContent += `<td>${option.voteCount} (${percentage}%)</td>`;
});
htmlContent += `</tr><tr><th>Vote Weights (Total: ${voteData.totalWeight})</th>`;
pollData.pollOptions.forEach(option => {
let percentage = (option.voteWeight/voteData.totalWeight*100).toFixed(2);
htmlContent += `<td>${option.voteWeight} (${percentage}%)</td>`;
});
htmlContent += `</tr></table>`;
htmlContent += `<button onclick="showVotes('${pollData.pollName}')">Show Votes</button>`;
htmlContent += `<div id="voter-info"></div>`;
document.getElementById('poll-details').innerHTML = htmlContent;
// Attach the event listener
const copyEmbedLinkButton = document.getElementById('copy-embed-link-button');
if (copyEmbedLinkButton) {
copyEmbedLinkButton.addEventListener('click', function() {
const pollName = decodeURIComponent(this.getAttribute('data-poll-name'));
copyEmbedLink(pollName);
});
}
} catch (error) {
console.error('Error fetching poll:', error);
document.getElementById('poll-details').innerHTML = `Error: ${error}`;
}
}
async function showVotes(pollName) {
try {
const voteResponse = await fetch('/polls/votes/' + encodeURIComponent(pollName));
const voteData = await voteResponse.json();
let voterInfoHtml = '<table><tr><th>Voter</th><th>Option</th></tr>';
for (const vote of voteData.votes) {
let voterAddress = await pubkeyToAddress(vote.voterPublicKey);
let voterDisplayName = await displayNameOrAddress(voterAddress);
let optionName = vote.optionIndex;
voterInfoHtml += `<tr><td>${voterDisplayName}</td><td>${optionName}</td></tr>`;
}
voterInfoHtml += '</table>';
document.getElementById('voter-info').innerHTML = voterInfoHtml;
} catch (error) {
console.error('Error fetching voter information:', error);
document.getElementById('voter-info').innerHTML = `Error: ${error}`;
}
}
async function searchAssets() {
document.getElementById('asset-details').textContent = 'Loading';
try {
const response = await fetch('/assets');
const results = await response.json();
let tableHtml = '<table>';
tableHtml += `
<tr>
<th>Name</th>
<th>Description</th>
<th>Owner</th>
<th>Quantity</th>
</tr>
`;
for (const result of results) {
let assetQuantity = (result.isDivisible === false) ? (result.quantity / 100000000) : result.quantity;
let assetOwner = await displayNameOrAddress(result.owner);
tableHtml += `<tr>
<td>${result.assetId}: ${result.name}</td>
<td>${result.description}</td>
<td>${assetOwner}</td>
<td>${assetQuantity}</td>
</tr>`;
}
tableHtml += '</table>';
document.getElementById('asset-details').innerHTML = tableHtml;
} catch (error) {
document.getElementById('asset-details').textContent = `Error fetching assets: ${error}`;
console.error('Error fetching assets:', error);
}
}
function searchByNameOrAddress(searchType) {
const searchQuery = document.getElementById(`${searchType}-input`).value;
if (!searchQuery) {
searchByName('', searchType);
// fetchAnyResults(searchType);
}
if (searchQuery.startsWith('Q') && !searchQuery.includes('0') && !searchQuery.includes('O') && !searchQuery.includes('I') && !searchQuery.includes('l') && searchQuery.length >= 26 && searchQuery.length <= 35) {
validateAddress(searchQuery, searchType);
} else if (searchQuery.length >= 0 && searchQuery.length <= 40) {
searchByName(searchQuery, searchType);
}
}
function validateAddress(address, searchType) {
fetch('/addresses/validate/' + address)
.then(response => response.json())
.then(isValid => {
if (isValid) {
// fetchAddressDetails(address);
searchByAddress(address, searchType);
} else {
searchByName(address, searchType);
}
})
.catch(error => console.error('Error validating address:', error));
}
function searchByAddress(address, searchType) {
Promise.all([
fetch('/names/address/' + address).then(response => response.json())
]).then(([names]) => {
if (names.length > 0) {
searchByName(names[0].name, searchType);
} else {
searchByName(address, searchType);
}
}).catch(error => console.error('Error fetching address details:', error));
}
async function searchByName(name, type) {
if (type === 'account') {
searchAccounts(name);
return;
}
const service = type.toUpperCase();
document.getElementById(`${type}-results`).innerHTML = '<p>Searching...</p>';
try {
const response = await fetch(`/arbitrary/resources/search?service=${service}&name=${name}`);
const results = await response.json();
if (results.length > 0) {
appResultsMap[type] = results;
// Fetch ratings and attach to appResultsMap
const ratingPromises = appResultsMap[type].map(async (result) => {
const appName = result.name;
const pollName = `app-library-${service}-rating-${appName}`;
let ratingInfo = {
appName: appName,
ratingText: '',
ratingValue: null,
ratingCount: null
};
try {
// Fetch poll details and votes
const pollVotesResponse = await fetch(`/polls/votes/${pollName}`);
if (pollVotesResponse.ok) {
const pollVotesData = await pollVotesResponse.json();
const voteCounts = pollVotesData.voteCounts;
let totalRating = 0;
let ratingCount = 0;
for (let i = 0; i < voteCounts.length; i++) {
const count = voteCounts[i].voteCount;
const optionName = voteCounts[i].optionName;
if (optionName.startsWith('initialValue-')) {
const initialValueMatch = optionName.match(/initialValue-(\d+)/);
if (initialValueMatch) {
const initialRating = parseInt(initialValueMatch[1]);
totalRating += initialRating;
ratingCount += 1; // Count initial value only once
}
} else if (['1', '2', '3', '4', '5'].includes(optionName)) {
const ratingValue = parseInt(optionName);
totalRating += ratingValue * count;
ratingCount += count;
}
}
if (ratingCount > 0) {
const averageRating = (totalRating / ratingCount).toFixed(2);
ratingInfo.ratingText = `${averageRating} (${ratingCount} ratings)`;
ratingInfo.ratingValue = averageRating;
ratingInfo.ratingCount = ratingCount;
} else {
ratingInfo.ratingText = 'No ratings';
}
} else {
ratingInfo.ratingText = `Rate this ${service}`;
}
} catch (error) {
console.error(`Error fetching poll for ${appName}:`, error);
ratingInfo.ratingText = `Rate this ${service}`;
}
return ratingInfo;
});
const ratingsArray = await Promise.all(ratingPromises);
const ratingMap = {};
ratingsArray.forEach((ratingInfo) => {
ratingMap[ratingInfo.appName] = ratingInfo;
});
appResultsMap[type].forEach((result) => {
const appName = result.name;
const ratingInfo = ratingMap[appName];
result.ratingInfo = ratingInfo;
});
renderTable(type);
} else {
document.getElementById(`${type}-results`).innerHTML = '<p>No results found.</p>';
}
} catch (error) {
console.error('Error searching by name:', error);
document.getElementById(`${type}-results`).innerHTML = `<p>Error: ${error}</p>`;
}
}
function renderTable(type) {
const appResults = appResultsMap[type];
if (appResults && appResults.length > 0) {
// Initialize sorting state if not set
if (!currentSortColumnMap[type]) {
currentSortColumnMap[type] = 'Last Updated';
}
if (sortDirectionMap[type] == null) {
sortDirectionMap[type] = sortDirectionsDefault[currentSortColumnMap[type]];
}
// Build table headers with sortable columns
let tableHtml = '<table>';
tableHtml += `
<tr>