-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
1666 lines (1473 loc) · 55.1 KB
/
script.js
File metadata and controls
1666 lines (1473 loc) · 55.1 KB
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
// S256 Block Explorer Frontend
const API_BASE = window.location.origin;
let currentPage = 1;
const blocksPerPage = 20;
let totalBlocks = 0;
let maxPage = 1;
let isLoadingBlocks = false;
// Theme Management
function initTheme() {
const savedTheme = localStorage.getItem("theme") || "dark";
document.documentElement.setAttribute("data-theme", savedTheme);
updateThemeIcon(savedTheme);
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute("data-theme");
const newTheme = currentTheme === "dark" ? "light" : "dark";
document.documentElement.setAttribute("data-theme", newTheme);
localStorage.setItem("theme", newTheme);
updateThemeIcon(newTheme);
}
function updateThemeIcon(theme) {
const icon = document.querySelector(".theme-icon");
icon.textContent = theme === "dark" ? "☀️" : "🌙";
}
// Hamburger Menu Toggle
function toggleMobileMenu() {
const hamburger = document.getElementById("hamburger");
const navMenu = document.getElementById("nav-menu");
const navControls = document.getElementById("nav-controls");
hamburger.classList.toggle("active");
navMenu.classList.toggle("active");
navControls.classList.toggle("active");
}
// Matrix Terminal Easter Egg
let terminalContentLoaded = false;
async function openMatrixTerminal() {
const terminal = document.getElementById("matrix-terminal");
terminal.classList.add("active");
if (!terminalContentLoaded) {
await loadCoinSupply();
terminalContentLoaded = true;
}
}
function closeMatrixTerminal() {
const terminal = document.getElementById("matrix-terminal");
terminal.classList.remove("active");
}
async function loadCoinSupply() {
const content = document.getElementById("terminal-content");
try {
// Show loading message
content.innerHTML = `
<div class="terminal-line">Initializing secure connection...</div>
<div class="terminal-line">Decrypting blockchain parameters...</div>
<div class="terminal-line">Accessing S256_SUPPLY.dat...</div>
<div class="terminal-line">Loading...</div>
`;
// Fetch the COIN_SUPPLY.txt file
const response = await fetch('/COIN_SUPPLY.txt');
const text = await response.text();
// Clear content and display with typewriter effect
setTimeout(() => {
displayTerminalContent(text);
}, 1000);
} catch (error) {
content.innerHTML = `
<div class="terminal-line">ERROR: Unable to access COIN_SUPPLY.txt</div>
<div class="terminal-line">Connection failed: ${error.message}</div>
<div class="terminal-line"><span class="terminal-cursor"></span></div>
`;
}
}
function displayTerminalContent(text) {
const content = document.getElementById("terminal-content");
const lines = text.split('\n');
content.innerHTML = `
<div class="terminal-line">Connection established...</div>
<div class="terminal-line">Decryption complete.</div>
<div class="terminal-line">Displaying: COIN_SUPPLY.txt</div>
<div class="terminal-line">═══════════════════════════════════════════════════════════════════</div>
<br>
`;
// Add lines with staggered fade-in effect
lines.forEach((line, index) => {
setTimeout(() => {
const lineDiv = document.createElement('div');
lineDiv.className = 'terminal-line';
lineDiv.textContent = line;
lineDiv.style.animationDelay = '0s';
content.appendChild(lineDiv);
// Auto-scroll to bottom
content.scrollTop = content.scrollHeight;
}, index * 20); // 20ms delay between lines for smooth effect
});
// Add cursor at the end
setTimeout(() => {
const cursorDiv = document.createElement('div');
cursorDiv.className = 'terminal-line';
cursorDiv.innerHTML = '<br><span class="terminal-cursor"></span>';
content.appendChild(cursorDiv);
content.scrollTop = content.scrollHeight;
}, lines.length * 20 + 100);
}
// Initialize
document.addEventListener("DOMContentLoaded", () => {
initTheme();
loadBlockchainInfo();
// Hamburger menu
const hamburger = document.getElementById("hamburger");
if (hamburger) {
hamburger.addEventListener("click", toggleMobileMenu);
}
// Close mobile menu when clicking a link
const navLinks = document.querySelectorAll(".nav-link");
navLinks.forEach(link => {
link.addEventListener("click", () => {
const navMenu = document.getElementById("nav-menu");
const navControls = document.getElementById("nav-controls");
const hamburger = document.getElementById("hamburger");
if (navMenu && navMenu.classList.contains("active")) {
hamburger.classList.remove("active");
navMenu.classList.remove("active");
navControls.classList.remove("active");
}
});
});
// Matrix Terminal Easter Egg
const piSymbol = document.getElementById("pi-easter-egg");
const terminalClose = document.getElementById("terminal-close");
const matrixTerminal = document.getElementById("matrix-terminal");
if (piSymbol) {
piSymbol.addEventListener("click", openMatrixTerminal);
}
if (terminalClose) {
terminalClose.addEventListener("click", closeMatrixTerminal);
}
if (matrixTerminal) {
matrixTerminal.addEventListener("click", (e) => {
if (e.target === matrixTerminal) {
closeMatrixTerminal();
}
});
}
// Check URL path for direct block or transaction access
const path = window.location.pathname;
// Handle both single and double (or multiple) slashes for buggy pool URLs
const blockMatch = path.match(/^\/*block\/([a-f0-9]+|\d+)$/i);
const txMatch = path.match(/^\/*tx\/([a-f0-9]+)$/i);
const addressMatch = path.match(/^\/*address\/([a-z0-9]+)$/i);
// Check for search query parameter
const urlParams = new URLSearchParams(window.location.search);
const searchQuery = urlParams.get('search');
if (searchQuery) {
// Perform search from URL parameter
document.getElementById('search').value = searchQuery;
performSearch();
} else if (blockMatch) {
// URL is /block/:hash or /block/:height
const hashOrHeight = blockMatch[1];
showBlockDetails(hashOrHeight);
} else if (txMatch) {
// URL is /tx/:txid
const txid = txMatch[1];
showTransactionDetails(txid);
} else if (addressMatch) {
// URL is /address/:address
const address = addressMatch[1];
showAddressDetails(address);
} else {
// Default: load recent blocks
loadRecentBlocks();
}
// Theme toggle
document
.getElementById("theme-toggle")
.addEventListener("click", toggleTheme);
// Auto-refresh every 30 seconds (only refresh blocks if on page 1)
setInterval(() => {
loadBlockchainInfo();
if (
!document.getElementById("search-results").style.display ||
document.getElementById("search-results").style.display === "none"
) {
// Only auto-refresh if we're on page 1
if (currentPage === 1) {
loadRecentBlocks(1);
}
}
}, 30000);
// Search button
document
.getElementById("search-btn")
.addEventListener("click", performSearch);
document.getElementById("search").addEventListener("keypress", (e) => {
if (e.key === "Enter") {
performSearch();
}
});
// Page jump input - Enter key support
document.getElementById("page-jump-input").addEventListener("keypress", (e) => {
if (e.key === "Enter") {
jumpToPage();
}
});
});
// Load blockchain info
async function loadBlockchainInfo() {
try {
const response = await fetch(`${API_BASE}/api/blockchain-info`);
const data = await response.json();
totalBlocks = data.blocks;
maxPage = Math.max(1, Math.ceil(totalBlocks / blocksPerPage));
document.getElementById("blockHeight").textContent =
data.blocks.toLocaleString();
document.getElementById("difficulty").textContent = formatDifficulty(
data.difficulty
);
document.getElementById("hashrate").textContent = formatHashrate(
data.networkhashps
);
document.getElementById("connections").textContent = data.connections;
} catch (error) {
console.error("Error loading blockchain info:", error);
document.getElementById("blockHeight").textContent = "Error";
document.getElementById("difficulty").textContent = "Error";
document.getElementById("hashrate").textContent = "Error";
document.getElementById("connections").textContent = "Error";
}
}
// Load recent blocks
async function loadRecentBlocks(page = 1) {
// Prevent multiple simultaneous requests
if (isLoadingBlocks) return;
try {
isLoadingBlocks = true;
currentPage = page;
const response = await fetch(
`${API_BASE}/api/blocks/recent/${blocksPerPage}?page=${page}`
);
const blocks = await response.json();
const tbody = document.getElementById("blocks-list");
tbody.innerHTML = "";
if (blocks.length === 0) {
tbody.innerHTML =
'<tr><td colspan="5" class="loading">No more blocks</td></tr>';
updatePaginationButtons(false, false);
return;
}
blocks.forEach((block) => {
const row = document.createElement("tr");
row.onclick = () => showBlockDetails(block.hash);
row.innerHTML = `
<td><strong>${block.height}</strong></td>
<td><span class="hash" title="${block.hash}">${truncateHash(
block.hash
)}</span></td>
<td>${formatTime(block.time)}</td>
<td>${block.nTx}</td>
<td>${formatBytes(block.size)}</td>
`;
tbody.appendChild(row);
});
// Update page info showing block range
if (blocks.length > 0) {
const highestBlock = blocks[0].height;
const lowestBlock = blocks[blocks.length - 1].height;
const pageInfoText = `Page ${currentPage} of ${maxPage} (Blocks ${highestBlock} - ${lowestBlock})`;
// Update both locations
const pageInfo = document.getElementById('blocks-page-info');
if (pageInfo) {
pageInfo.textContent = pageInfoText;
}
const pageInfoPagination = document.getElementById('blocks-page-info-pagination');
if (pageInfoPagination) {
pageInfoPagination.textContent = pageInfoText;
}
}
// Update pagination controls
renderPagination();
} catch (error) {
console.error("Error loading blocks:", error);
document.getElementById("blocks-list").innerHTML =
'<tr><td colspan="5" class="loading">Error loading blocks</td></tr>';
} finally {
isLoadingBlocks = false;
}
}
// Change page
function changePage(direction) {
const newPage = currentPage + direction;
if (newPage < 1 || newPage > maxPage) return;
loadRecentBlocks(newPage);
window.scrollTo({ top: 0, behavior: "smooth" });
}
// Go to specific page
function goToPage(page) {
if (page < 1 || page > maxPage) return;
loadRecentBlocks(page);
window.scrollTo({ top: 0, behavior: "smooth" });
}
// Go to last page
function goToLastPage() {
goToPage(maxPage);
}
// Jump to page from input
function jumpToPage() {
const input = document.getElementById("page-jump-input");
const page = parseInt(input.value);
if (isNaN(page) || page < 1 || page > maxPage) {
alert(`Please enter a valid page number between 1 and ${maxPage}`);
return;
}
input.value = "";
goToPage(page);
}
// Render pagination controls
function renderPagination() {
const pageNumbersDiv = document.getElementById("page-numbers");
if (!pageNumbersDiv) return;
const pages = [];
// Always show first page
pages.push(1);
// Determine which pages to show around current page
const delta = 2; // Show 2 pages before and after current
const rangeStart = Math.max(2, currentPage - delta);
const rangeEnd = Math.min(maxPage - 1, currentPage + delta);
// Add ellipsis after page 1 if needed
if (rangeStart > 2) {
pages.push('...');
}
// Add pages around current page
for (let i = rangeStart; i <= rangeEnd; i++) {
pages.push(i);
}
// Add ellipsis before last page if needed
if (rangeEnd < maxPage - 1) {
pages.push('...');
}
// Always show last page (if more than 1 page)
if (maxPage > 1) {
pages.push(maxPage);
}
// Build HTML
pageNumbersDiv.innerHTML = pages.map(page => {
if (page === '...') {
return '<span class="page-ellipsis">...</span>';
}
const isActive = page === currentPage;
return `<button class="btn-page-num${isActive ? ' active' : ''}" onclick="goToPage(${page})">${page}</button>`;
}).join('');
// Update button states
const prevBtn = document.getElementById("prev-page");
const nextBtn = document.getElementById("next-page");
const firstBtn = document.getElementById("first-page");
const lastBtn = document.getElementById("last-page");
if (prevBtn) prevBtn.disabled = currentPage <= 1;
if (nextBtn) nextBtn.disabled = currentPage >= maxPage;
if (firstBtn) firstBtn.disabled = currentPage <= 1;
if (lastBtn) lastBtn.disabled = currentPage >= maxPage;
}
// Show block details
async function showBlockDetails(hashOrHeight) {
try {
const response = await fetch(`${API_BASE}/api/block/${hashOrHeight}`);
const block = await response.json();
if (block.error) {
showError(block.error);
return;
}
// Update URL to /block/:hash for bookmarking/sharing
const newPath = `/block/${block.hash}`;
if (window.location.pathname !== newPath) {
window.history.pushState({ blockHash: block.hash }, '', newPath);
}
// Get coinbase message from first transaction
let coinbaseMessage = "";
if (block.tx && block.tx.length > 0) {
const firstTxId = block.tx[0].txid || block.tx[0];
try {
const txResponse = await fetch(`${API_BASE}/api/tx/${firstTxId}`);
const firstTx = await txResponse.json();
if (firstTx.vin && firstTx.vin[0] && firstTx.vin[0].coinbase) {
coinbaseMessage = decodeCoinbase(firstTx.vin[0].coinbase);
}
} catch (e) {
console.log("Could not fetch coinbase message");
}
}
const content = document.getElementById("block-content");
content.innerHTML = `
<div class="detail-row">
<div class="detail-label">Height:</div>
<div class="detail-value">${block.height}</div>
</div>
<div class="detail-row">
<div class="detail-label">Hash:</div>
<div class="detail-value">${block.hash}</div>
</div>
${
coinbaseMessage
? `
<div class="detail-row">
<div class="detail-label">CoinbaseMsg:</div>
<div class="detail-value" style="color: var(--primary); font-weight: 600; font-size: 1.1rem;">"${coinbaseMessage}"</div>
</div>
`
: ""
}
<div class="detail-row">
<div class="detail-label">Confirmations:</div>
<div class="detail-value">${block.isOrphan ? '<span class="status-orphan">ORPHANED</span>' : block.confirmations.toLocaleString()}</div>
</div>
<div class="detail-row">
<div class="detail-label">Timestamp:</div>
<div class="detail-value">${formatTime(block.time)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Size:</div>
<div class="detail-value">${formatBytes(block.size)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Weight:</div>
<div class="detail-value">${block.weight.toLocaleString()}</div>
</div>
<div class="detail-row">
<div class="detail-label">Difficulty:</div>
<div class="detail-value">${block.difficulty.toFixed(8)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Nonce:</div>
<div class="detail-value">${block.nonce}</div>
</div>
<div class="detail-row">
<div class="detail-label">Bits:</div>
<div class="detail-value">${block.bits}</div>
</div>
<div class="detail-row">
<div class="detail-label">Version:</div>
<div class="detail-value">${block.version}</div>
</div>
<div class="detail-row">
<div class="detail-label">Merkle Root:</div>
<div class="detail-value">${block.merkleroot}</div>
</div>
${
block.previousblockhash
? `
<div class="detail-row">
<div class="detail-label">Previous Block:</div>
<div class="detail-value clickable" onclick="showBlockDetails('${
block.previousblockhash
}')">${truncateHash(block.previousblockhash)}</div>
</div>
`
: ""
}
${
block.nextblockhash
? `
<div class="detail-row">
<div class="detail-label">Next Block:</div>
<div class="detail-value clickable" onclick="showBlockDetails('${
block.nextblockhash
}')">${truncateHash(block.nextblockhash)}</div>
</div>
`
: ""
}
<div class="detail-row">
<div class="detail-label">Transactions (${block.tx.length}):</div>
<div class="detail-value">
<div class="tx-list">
${block.tx
.map(
(tx, index) => `
<div class="tx-item" onclick="showTransactionModal('${
tx.txid || tx
}')">
${index + 1}. ${truncateHash(tx.txid || tx)}
</div>
`
)
.join("")}
</div>
</div>
</div>
`;
document.getElementById("blocks-section").style.display = "none";
document.getElementById("search-results").style.display = "none";
document.getElementById("tx-details").style.display = "none";
document.getElementById("block-details").style.display = "block";
const hashrateSection = document.getElementById("hashrate-chart-section");
if (hashrateSection) hashrateSection.style.display = "none";
} catch (error) {
console.error("Error loading block details:", error);
showError("Error loading block details");
}
}
// Show transaction details in dedicated section (for direct links)
async function showTransactionDetails(txid) {
try {
const response = await fetch(`${API_BASE}/api/tx/${txid}`);
const tx = await response.json();
if (tx.error) {
showError(tx.error);
return;
}
// Update URL to /tx/:txid for bookmarking/sharing
const newPath = `/tx/${tx.txid}`;
if (window.location.pathname !== newPath) {
window.history.pushState({ txid: tx.txid }, '', newPath);
}
const content = document.getElementById("tx-content");
content.innerHTML = `
<div class="detail-row">
<div class="detail-label">Transaction ID:</div>
<div class="detail-value">${tx.txid}</div>
</div>
<div class="detail-row">
<div class="detail-label">Block Hash:</div>
<div class="detail-value clickable" onclick="showBlockDetails('${
tx.blockhash
}')">${truncateHash(tx.blockhash)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Block Height:</div>
<div class="detail-value">${tx.blockheight || 'Pending'}</div>
</div>
<div class="detail-row">
<div class="detail-label">Confirmations:</div>
<div class="detail-value">${
tx.isOrphan ? '<span class="status-orphan">ORPHANED</span>' : (tx.confirmations ? tx.confirmations.toLocaleString() : "Unconfirmed")
}</div>
</div>
<div class="detail-row">
<div class="detail-label">Time:</div>
<div class="detail-value">${
tx.time || tx.blocktime
? formatTime(tx.time || tx.blocktime)
: "Pending"
}</div>
</div>
<div class="detail-row">
<div class="detail-label">Size:</div>
<div class="detail-value">${formatBytes(tx.size)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Virtual Size:</div>
<div class="detail-value">${formatBytes(tx.vsize)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Version:</div>
<div class="detail-value">${tx.version}</div>
</div>
${tx.locktime && tx.locktime !== 0 ? `
<div class="detail-row">
<div class="detail-label">Lock Time:</div>
<div class="detail-value">${tx.locktime}</div>
</div>
` : ''}
<div class="detail-row">
<div class="detail-label">Inputs (${tx.vin.length}):</div>
<div class="detail-value">
${tx.vin
.map((input, index) => {
if (input.coinbase) {
return `<div class="tx-io-box tx-input-box">
<div class="tx-io-header">💰 <strong>Input ${index}: Coinbase (Mining Reward)</strong></div>
<div class="tx-io-detail">${truncateHash(input.coinbase, 32)}</div>
</div>`;
}
// Build input display with available data
const hasValue = input.prevout && input.prevout.value !== undefined;
const hasAddress = input.prevout && input.prevout.scriptPubKey && input.prevout.scriptPubKey.address;
return `<div class="tx-io-box tx-input-box">
<div class="tx-io-header">📥 <strong>Input ${index}</strong></div>
${hasAddress ? `<div class="tx-io-address"><strong>From Address:</strong> ${input.prevout.scriptPubKey.address}</div>` : ''}
${hasValue ? `<div class="tx-io-amount"><strong>Amount:</strong> <span class="amount-highlight">${input.prevout.value.toFixed(8)} S256</span></div>` : ''}
<div class="tx-io-reference">
<strong>Source:</strong> <span class="detail-value clickable" onclick="showTransactionModal('${input.txid}')">${truncateHash(input.txid)}</span> [Output #${input.vout !== undefined ? input.vout : 'N/A'}]
</div>
</div>`;
})
.join("")}
</div>
</div>
<div class="detail-row">
<div class="detail-label">Outputs (${tx.vout.length}):</div>
<div class="detail-value">
${tx.vout
.map(
(output, index) => `
<div class="tx-io-box tx-output-box">
<div class="tx-io-header">📤 <strong>Output ${index}</strong></div>
<div class="tx-io-amount"><strong>Amount:</strong> <span class="amount-highlight">${output.value.toFixed(8)} S256</span></div>
${
output.scriptPubKey.address
? `<div class="tx-io-address"><strong>To Address:</strong> ${output.scriptPubKey.address}</div>`
: `<div class="tx-io-detail"><strong>Type:</strong> ${output.scriptPubKey.type}</div>`
}
${output.scriptPubKey.type === 'nonstandard' ? '<div class="badge-nonstandard">⚠️ Non-Standard / Unspendable</div>' : ''}
</div>
`
)
.join("")}
</div>
</div>
`;
document.getElementById("blocks-section").style.display = "none";
document.getElementById("search-results").style.display = "none";
document.getElementById("block-details").style.display = "none";
document.getElementById("address-details").style.display = "none";
document.getElementById("tx-details").style.display = "block";
const hashrateSection = document.getElementById("hashrate-chart-section");
if (hashrateSection) hashrateSection.style.display = "none";
} catch (error) {
console.error("Error loading transaction details:", error);
showError("Error loading transaction details");
}
}
// Show transaction details in modal (for clicks within page)
async function showTransactionModal(txid) {
try {
const response = await fetch(`${API_BASE}/api/tx/${txid}`);
const tx = await response.json();
if (tx.error) {
showError(tx.error);
return;
}
const content = document.getElementById("tx-modal-body");
content.innerHTML = `
<div class="detail-row">
<div class="detail-label">Transaction ID:</div>
<div class="detail-value">${tx.txid}</div>
</div>
<div class="detail-row">
<div class="detail-label">Block Hash:</div>
<div class="detail-value clickable" onclick="closeTxModal(); showBlockDetails('${
tx.blockhash
}')">${truncateHash(tx.blockhash)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Block Height:</div>
<div class="detail-value">${tx.blockheight || 'Pending'}</div>
</div>
<div class="detail-row">
<div class="detail-label">Confirmations:</div>
<div class="detail-value">${
tx.isOrphan ? '<span class="status-orphan">ORPHANED</span>' : (tx.confirmations ? tx.confirmations.toLocaleString() : "Unconfirmed")
}</div>
</div>
<div class="detail-row">
<div class="detail-label">Time:</div>
<div class="detail-value">${
tx.time || tx.blocktime
? formatTime(tx.time || tx.blocktime)
: "Pending"
}</div>
</div>
<div class="detail-row">
<div class="detail-label">Size:</div>
<div class="detail-value">${formatBytes(tx.size)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Virtual Size:</div>
<div class="detail-value">${formatBytes(tx.vsize)}</div>
</div>
<div class="detail-row">
<div class="detail-label">Version:</div>
<div class="detail-value">${tx.version}</div>
</div>
${tx.locktime && tx.locktime !== 0 ? `
<div class="detail-row">
<div class="detail-label">Lock Time:</div>
<div class="detail-value">${tx.locktime}</div>
</div>
` : ''}
<div class="detail-row">
<div class="detail-label">Inputs (${tx.vin.length}):</div>
<div class="detail-value">
${tx.vin
.map((input, index) => {
if (input.coinbase) {
return `<div class="tx-io-box tx-input-box">
<div class="tx-io-header">💰 <strong>Input ${index}: Coinbase (Mining Reward)</strong></div>
<div class="tx-io-detail">${truncateHash(input.coinbase, 32)}</div>
</div>`;
}
// Build input display with available data
const hasValue = input.prevout && input.prevout.value !== undefined;
const hasAddress = input.prevout && input.prevout.scriptPubKey && input.prevout.scriptPubKey.address;
return `<div class="tx-io-box tx-input-box">
<div class="tx-io-header">📥 <strong>Input ${index}</strong></div>
${hasAddress ? `<div class="tx-io-address"><strong>From Address:</strong> ${input.prevout.scriptPubKey.address}</div>` : ''}
${hasValue ? `<div class="tx-io-amount"><strong>Amount:</strong> <span class="amount-highlight">${input.prevout.value.toFixed(8)} S256</span></div>` : ''}
<div class="tx-io-reference">
<strong>Source:</strong> <span class="detail-value clickable" onclick="closeTxModal(); showTransactionDetails('${input.txid}')">${truncateHash(input.txid)}</span> [Output #${input.vout !== undefined ? input.vout : 'N/A'}]
</div>
</div>`;
})
.join("")}
</div>
</div>
<div class="detail-row">
<div class="detail-label">Outputs (${tx.vout.length}):</div>
<div class="detail-value">
${tx.vout
.map(
(output, index) => `
<div class="tx-io-box tx-output-box">
<div class="tx-io-header">📤 <strong>Output ${index}</strong></div>
<div class="tx-io-amount"><strong>Amount:</strong> <span class="amount-highlight">${output.value.toFixed(8)} S256</span></div>
${
output.scriptPubKey.address
? `<div class="tx-io-address"><strong>To Address:</strong> ${output.scriptPubKey.address}</div>`
: `<div class="tx-io-detail"><strong>Type:</strong> ${output.scriptPubKey.type}</div>`
}
${output.scriptPubKey.type === 'nonstandard' ? '<div class="badge-nonstandard">⚠️ Non-Standard / Unspendable</div>' : ''}
</div>
`
)
.join("")}
</div>
</div>
`;
// Show modal
const modal = document.getElementById('tx-modal');
modal.style.display = 'flex';
setTimeout(() => {
modal.classList.add('show');
}, 10);
} catch (error) {
console.error("Error loading transaction details:", error);
showError("Error loading transaction details");
}
}
// Close transaction modal
function closeTxModal() {
const modal = document.getElementById('tx-modal');
modal.classList.remove('show');
setTimeout(() => {
modal.style.display = 'none';
}, 300);
}
// Show address details
async function showAddressDetails(address) {
// Validate address format before querying
if (!validateAddress(address)) {
showError(
"Invalid S256 address format. Valid formats: s2... (bech32) or S... (legacy)"
);
return;
}
try {
const response = await fetch(`${API_BASE}/api/address/${address}`);
const data = await response.json();
if (data.error) {
showError(data.error);
return;
}
// Update URL to /address/:address for bookmarking/sharing
const newPath = `/address/${data.address}`;
if (window.location.pathname !== newPath) {
window.history.pushState({ address: data.address }, '', newPath);
}
const content = document.getElementById("address-content");
content.innerHTML = `
<div class="address-info-card">
<div class="address-info-header">
<h3>Address Information</h3>
</div>
<div class="address-display">
<div class="address-hash">${data.address}</div>
<div class="address-actions">
<button class="btn-action" onclick="copyAddress('${data.address}')">
<span>📋</span> Copy
</button>
<button class="btn-action" onclick="showQRModal('${data.address}')">
<span>📱</span> Show QR Code
</button>
</div>
</div>
</div>
<div class="address-stats-grid top-stats">
<div class="stat-card">
<div class="stat-label">Total Received</div>
<div class="stat-value">${data.received.toFixed(8)} S256</div>
</div>
<div class="stat-card">
<div class="stat-label">Total Sent</div>
<div class="stat-value">${data.sent.toFixed(8)} S256</div>
</div>
<div class="stat-card">
<div class="stat-label">Transaction Count</div>
<div class="stat-value">${data.txCount} transactions</div>
</div>
</div>
<div class="address-stats-grid balance-stats">
<div class="stat-card highlight">
<div class="stat-label">Spendable Balance</div>
<div class="stat-value stat-balance">${data.balance.toFixed(8)} S256</div>
</div>
${data.immatureBalance > 0 ? `
<div class="stat-card highlight">
<div class="stat-label">Immature Balance</div>
<div class="stat-value immature-balance">${data.immatureBalance.toFixed(8)} S256</div>
</div>
` : ''}
<div class="stat-card highlight total">
<div class="stat-label">Total Balance</div>
<div class="stat-value">${(data.balance + (data.immatureBalance || 0)).toFixed(8)} S256</div>
</div>
</div>
<div class="tx-history-section">
<div class="tx-history-header">
<h3>Transaction History</h3>
<div class="tx-header-controls">
<div class="tx-filter-controls">
<button class="filter-btn active" onclick="filterTransactions('all', '${data.address}')">All</button>
<button class="filter-btn" onclick="filterTransactions('recent', '${data.address}')">Recent</button>
</div>
<div class="tx-export-controls">
<button class="export-btn" onclick="exportToCSV('${data.address}')" title="Export to CSV">
<span>📊</span> CSV
</button>
<button class="export-btn" onclick="exportToPDF('${data.address}')" title="Generate PDF Report">
<span>📄</span> PDF
</button>
</div>
</div>
</div>
<div class="tx-history-info" id="tx-history-info"></div>
<div class="tx-table-container">
<table class="tx-table">
<thead>
<tr>
<th>Transaction</th>
<th>Block</th>
<th>Time</th>
<th class="amount-col">Amount</th>
</tr>
</thead>
<tbody id="tx-table-body">
</tbody>
</table>
</div>
<div class="pagination-container" id="pagination-container"></div>
</div>
`;
// Store data for filtering and pagination
window.currentAddressData = data;
window.currentPage = 1;
window.itemsPerPage = 25;
window.currentFilter = 'all';
// Count incoming vs outgoing transactions using server-calculated data
let incomingCount = 0;
let outgoingCount = 0;
data.transactions.forEach(tx => {
if (tx.addressAmount?.direction === 'out') {
outgoingCount++;
} else {
incomingCount++;
}
});
console.log(`✅ Address loaded: ${incomingCount} IN (green), ${outgoingCount} OUT (red) transactions`);
// Render initial page
renderTransactionPage(data.address);
document.getElementById("blocks-section").style.display = "none";
document.getElementById("search-results").style.display = "none";
document.getElementById("block-details").style.display = "none";
document.getElementById("tx-details").style.display = "none";
document.getElementById("address-details").style.display = "block";
const hashrateSection = document.getElementById("hashrate-chart-section");
if (hashrateSection) hashrateSection.style.display = "none";
} catch (error) {
console.error("Error loading address details:", error);
showError("Error loading address details");
}
}
// Note: Transaction amounts are now calculated server-side in tx.addressAmount
// Copy address to clipboard
function copyAddress(address) {
navigator.clipboard.writeText(address).then(() => {
showNotification('Address copied to clipboard!');
}).catch(err => {
console.error('Failed to copy:', err);
showNotification('Failed to copy address');
});
}
// Show QR code modal
function showQRModal(address) {
const modal = document.getElementById('qr-modal');
const qrImage = document.getElementById('qr-code-image');
const addressText = document.getElementById('qr-address-text');
// Generate QR code URL with larger size for better display
const qrUrl = `https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=${encodeURIComponent(address)}`;
qrImage.src = qrUrl;
addressText.textContent = address;