-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
3836 lines (3460 loc) · 143 KB
/
main.js
File metadata and controls
3836 lines (3460 loc) · 143 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
let currentView = 'dashboard';
let pollInterval = null;
let realtimeUnlisten = null;
let isNewWallet = false;
let daemonStartPromise = null;
let sessionPassword = '';
let resetChainArmed = false;
let resetChainArmTimer = null;
let viewSeedArmed = false;
let viewSeedArmTimer = null;
let isMining = false;
let threadDebounce = null;
let threadUpdatePending = false;
const MINING_DIFFICULTY_WINDOW = 60;
const MINING_DIFFICULTY_REFRESH_MS = 15000;
let miningDifficultySeries = [];
let miningDifficultyTipHeight = -1;
let miningDifficultyLastRefresh = 0;
let miningDifficultyLoading = false;
let qrDismissTimer = null;
let sendArmed = false;
let sendArmTimer = null;
let pendingSendIdempotency = null;
const SEND_IDEMPOTENCY_WINDOW_MS = 10 * 60 * 1000;
let pendingDeepLink = null;
let dashLastHeight = -1;
let dashLastTxCount = -1;
let dashForceRefresh = false;
let peerDetailActiveId = '';
let peerDetailLiveTimer = null;
let navGeneration = 0;
function getPendingSends() {
try { return JSON.parse(localStorage.getItem(walletKey('pendingSends')) || '[]'); } catch (_) { return []; }
}
function savePendingSends(list) {
localStorage.setItem(walletKey('pendingSends'), JSON.stringify(list));
}
function addPendingSend(txid, amount, memo) {
var list = getPendingSends();
if (list.some(function (p) { return p.txid === txid; })) return;
list.push({ txid: txid, amount: amount, block_height: 0, spent: true, is_coinbase: false, memo_hex: memo || undefined });
savePendingSends(list);
}
function prunePendingSends(confirmedOutputs) {
var list = getPendingSends();
if (!list.length) return;
var confirmedTxids = {};
confirmedOutputs.forEach(function (o) { confirmedTxids[o.txid] = true; });
var pruned = list.filter(function (p) { return !confirmedTxids[p.txid]; });
if (pruned.length !== list.length) savePendingSends(pruned);
return pruned;
}
function mergeWithPending(outputs) {
var pending = prunePendingSends(outputs);
if (!pending || !pending.length) return outputs;
return pending.concat(outputs);
}
let activeWalletName = 'wallet.dat';
function walletKey(base) {
return base + ':' + activeWalletName;
}
function setActiveWalletName(name) {
if (typeof name === 'string' && name.trim()) {
activeWalletName = name.trim();
}
}
function migrateLocalStorageKeys() {
// One-time migration: move unnamespaced txCache/addressBook to the active wallet's namespace
try {
var oldTx = localStorage.getItem('txCache');
if (oldTx && !localStorage.getItem(walletKey('txCache'))) {
localStorage.setItem(walletKey('txCache'), oldTx);
}
localStorage.removeItem('txCache');
} catch (_) {}
try {
var oldBook = localStorage.getItem('addressBook');
if (oldBook && !localStorage.getItem(walletKey('addressBook'))) {
localStorage.setItem(walletKey('addressBook'), oldBook);
}
localStorage.removeItem('addressBook');
} catch (_) {}
}
// --- Sound Engine ---
var audioCtx = null;
var masterGain = null;
var soundVolume = 0.8;
var soundMuted = false;
function initAudio() {
if (audioCtx) return;
audioCtx = new (window.AudioContext || window.webkitAudioContext)();
masterGain = audioCtx.createGain();
masterGain.connect(audioCtx.destination);
loadSoundPrefs();
applyVolume();
}
function loadSoundPrefs() {
try {
var v = localStorage.getItem('soundVolume');
if (v !== null) soundVolume = parseFloat(v);
var m = localStorage.getItem('soundMuted');
if (m !== null) soundMuted = m === 'true';
} catch (_) {}
}
function saveSoundPrefs() {
try {
localStorage.setItem('soundVolume', soundVolume.toString());
localStorage.setItem('soundMuted', soundMuted.toString());
} catch (_) {}
}
function applyVolume() {
if (!masterGain) return;
masterGain.gain.setValueAtTime(soundMuted ? 0 : soundVolume, audioCtx.currentTime);
}
function playNote(freq, start, dur, type, vol) {
if (!audioCtx || !masterGain) return;
var osc = audioCtx.createOscillator();
var g = audioCtx.createGain();
osc.type = type || 'sine';
osc.frequency.setValueAtTime(freq, audioCtx.currentTime + start);
g.gain.setValueAtTime(0, audioCtx.currentTime + start);
g.gain.linearRampToValueAtTime(vol || 0.3, audioCtx.currentTime + start + 0.02);
g.gain.linearRampToValueAtTime(0, audioCtx.currentTime + start + dur);
osc.connect(g);
g.connect(masterGain);
osc.start(audioCtx.currentTime + start);
osc.stop(audioCtx.currentTime + start + dur + 0.05);
}
// Intro: gentle ascending arpeggio, C major bright, short and warm
function playIntro() {
initAudio();
// C5 E5 G5 C6 ; soft triangle wave, staggered
playNote(523.25, 0.0, 0.25, 'triangle', 0.18);
playNote(659.25, 0.1, 0.25, 'triangle', 0.16);
playNote(783.99, 0.2, 0.25, 'triangle', 0.14);
playNote(1046.5, 0.3, 0.35, 'sine', 0.12);
}
// Lock: descending, fading, minor feel
function playLock() {
initAudio();
// G5 Eb5 C5 G4 ; descending minor, sine, fading out
playNote(783.99, 0.0, 0.2, 'sine', 0.16);
playNote(622.25, 0.12, 0.2, 'sine', 0.13);
playNote(523.25, 0.24, 0.22, 'sine', 0.10);
playNote(392.00, 0.36, 0.3, 'sine', 0.06);
}
// Unlock / Inbound: bright happy tada ; two quick notes then a resolve
function playTada() {
initAudio();
// G5 C6 E6 ; quick ascending major, triangle+sine layered
playNote(783.99, 0.0, 0.12, 'triangle', 0.2);
playNote(1046.5, 0.08, 0.12, 'triangle', 0.2);
playNote(1318.5, 0.16, 0.3, 'sine', 0.18);
// subtle octave shimmer
playNote(2637.0, 0.18, 0.25, 'sine', 0.04);
}
function invoke(cmd, args) {
return window.__TAURI__.core.invoke(cmd, args);
}
// --- API Client (proxied through Rust, no CORS) ---
async function api(path, opts = {}) {
const result = await invoke('api_call', {
method: opts.method || 'GET',
path: path,
body: opts.body ? JSON.stringify(opts.body) : null,
headers: opts.headers || null,
});
return JSON.parse(result);
}
function normalizeError(error) {
const raw = String(error || '').replace(/^Error:\s*/, '').trim();
if (!raw) return 'Request failed';
try {
const parsed = JSON.parse(raw);
if (parsed && typeof parsed.error === 'string') return parsed.error;
} catch (_) {
// Not JSON, keep original text
}
return raw;
}
async function loadOrUnlockWallet(password) {
try {
await api('/api/wallet/load', {
method: 'POST',
body: { password },
});
return;
} catch (e) {
const msg = normalizeError(e).toLowerCase();
if (msg.includes('wallet already loaded')) {
await api('/api/wallet/unlock', {
method: 'POST',
body: { password },
});
return;
}
throw e;
}
}
// --- Formatting ---
function formatBNT(atomic) {
return (atomic / 100000000).toFixed(8);
}
function formatBNTShort(atomic) {
const val = atomic / 100000000;
if (val === 0) return '0.00';
if (val < 0.01) return val.toFixed(8);
return val.toFixed(2);
}
function formatBytes(bytes) {
if (!bytes || bytes < 0) return '0 B';
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
// --- Navigation ---
var viewStack = [];
function navigate(view) {
if (currentView && currentView !== view) viewStack.push(currentView);
if (viewStack.length > 20) viewStack.splice(0, viewStack.length - 20);
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
document.querySelectorAll('.nav-link').forEach(n => n.classList.remove('active'));
const viewEl = document.getElementById('view-' + view);
const navEl = document.querySelector('[data-view="' + view + '"]');
if (viewEl) viewEl.classList.add('active');
if (navEl) navEl.classList.add('active');
currentView = view;
navGeneration++;
loadView(view, navGeneration);
}
function navigateBack() {
var prev = viewStack.pop() || 'dashboard';
document.querySelectorAll('.view').forEach(v => v.classList.remove('active'));
document.querySelectorAll('.nav-link').forEach(n => n.classList.remove('active'));
var viewEl = document.getElementById('view-' + prev);
var navEl = document.querySelector('[data-view="' + prev + '"]');
if (viewEl) viewEl.classList.add('active');
if (navEl) navEl.classList.add('active');
currentView = prev;
navGeneration++;
loadView(prev, navGeneration);
}
async function loadView(view, gen) {
try {
if (gen !== navGeneration) return;
switch (view) {
case 'dashboard': await loadDashboard(); break;
case 'send': renderAddressBook(); break;
case 'receive': await loadReceive(); break;
case 'history': await loadHistory(); break;
case 'mining': await loadMining(); break;
case 'network': await loadNetwork(); break;
case 'settings': await loadWalletList(); if (gen !== navGeneration) return; await loadVersions(); break;
}
} catch (e) {
if (gen !== navGeneration) return;
console.error('Error loading ' + view + ':', e);
}
}
async function loadVersions() {
var walletEl = document.getElementById('wallet-version-value');
var daemonEl = document.getElementById('daemon-version-value');
if (walletEl) walletEl.textContent = '--';
if (daemonEl) daemonEl.textContent = '--';
try {
var walletVersion = await invoke('get_wallet_version');
if (walletEl) walletEl.textContent = walletVersion ? String(walletVersion).trim() : '--';
} catch (_) {}
try {
var daemonVersion = await invoke('get_daemon_version');
if (daemonEl) daemonEl.textContent = daemonVersion ? String(daemonVersion).trim() : '--';
} catch (_) {
if (daemonEl) daemonEl.textContent = 'unavailable';
}
}
// --- Dashboard ---
async function loadDashboard() {
try {
var walletTitle = String(activeWalletName || 'wallet.dat').replace(/\.dat$/i, '');
var walletNameEl = document.getElementById('dash-wallet-name');
if (walletNameEl) walletNameEl.textContent = walletTitle;
var shortname = '';
try {
var receivePrefsRaw = localStorage.getItem(walletKey('receivePrefs')) || '{}';
var receivePrefs = JSON.parse(receivePrefsRaw);
if (receivePrefs && receivePrefs.handle) shortname = '$' + String(receivePrefs.handle);
} catch (_) {}
var shortEl = document.getElementById('dash-shortname');
if (shortEl) {
if (shortname) {
shortEl.textContent = shortname;
shortEl.dataset.copy = shortname;
delete shortEl.dataset.copyWired;
shortEl.style.display = '';
wireCopyable(shortEl.parentNode || shortEl);
} else {
shortEl.style.display = 'none';
shortEl.textContent = '';
delete shortEl.dataset.copy;
}
}
} catch (_) {}
try {
const status = await api('/api/status');
const heightLabel = status.chain_height.toLocaleString();
document.getElementById('dash-height').textContent = heightLabel;
document.getElementById('dash-peers').textContent = status.peers;
document.getElementById('dash-mempool').textContent = status.mempool_size;
document.getElementById('dash-syncing').textContent = status.syncing ? 'Syncing' : 'Synced';
const dot = document.getElementById('status-dot');
if (dot) {
dot.className = 'status-dot' + (status.syncing ? ' syncing' : '');
dot.title = 'height: ' + heightLabel;
dot.setAttribute('name', 'height: ' + heightLabel);
}
} catch (e) {
console.error('Status error:', e);
}
try {
const balance = await api('/api/wallet/balance');
document.getElementById('dash-balance').textContent = formatBNTShort(balance.spendable);
document.getElementById('dash-pending').textContent = formatBNTShort(balance.pending);
document.getElementById('dash-total').textContent = formatBNTShort(balance.total);
document.getElementById('pending-label').classList.toggle('has-pending', balance.pending > 0);
} catch (e) {
// balance may fail during sync, that's ok
}
try {
var statusHeight = parseInt(document.getElementById('dash-height').textContent.replace(/,/g, '')) || 0;
if (statusHeight !== dashLastHeight || dashForceRefresh) {
dashLastHeight = statusHeight;
dashForceRefresh = false;
var data = await api('/api/wallet/history');
var container = document.getElementById('dash-recent-tx');
var hasOutputsArray = data && Array.isArray(data.outputs);
var outputs = hasOutputsArray ? data.outputs : null;
var fromCache = false;
if (hasOutputsArray) {
try { localStorage.setItem(walletKey('txCache'), JSON.stringify(outputs)); } catch (_) {}
} else {
try { outputs = JSON.parse(localStorage.getItem(walletKey('txCache')) || 'null'); fromCache = true; } catch (_) {}
}
if (outputs) outputs = mergeWithPending(outputs);
if (!outputs || outputs.length === 0) {
container.innerHTML = '<div class="empty">No transactions yet</div>';
dashLastTxCount = 0;
} else {
// Detect new inbound transactions
if (!fromCache) {
var inboundCount = outputs.filter(function (o) { return !o.spent; }).length;
if (dashLastTxCount >= 0 && inboundCount > dashLastTxCount) {
playTada();
}
dashLastTxCount = inboundCount;
}
var sorted = outputs.slice().sort(function (a, b) {
if (!a.block_height && b.block_height) return -1;
if (a.block_height && !b.block_height) return 1;
return b.block_height - a.block_height;
});
var limit = window.innerHeight < 720 ? 3 : 5;
var recent = sorted.slice(0, limit);
container.innerHTML = recent.map(function (o) {
var typeLabel = o.is_coinbase ? 'mining reward' : (o.spent ? 'sent' : 'received');
var memoText = o.memo_hex ? hexToUtf8(o.memo_hex) : '';
return '<div class="recent-tx-row' + (o.spent ? ' spent' : '') + (fromCache ? ' cached' : '') + '" data-txid="' + o.txid + '">' +
'<span class="recent-tx-amount ' + (o.spent ? 'r' : 'g') + '">' +
(o.spent ? '-' : '+') + formatBNTShort(o.amount) + ' BNT' +
'</span>' +
'<span class="recent-tx-type ' + (o.spent ? 'r' : 'g') + '">' + typeLabel + '</span>' +
(memoText ? '<span class="recent-tx-memo d">"' + escapeHtml(memoText) + '"</span>' : '') +
'<span class="recent-tx-block d">' + (o.block_height ? 'Block ' + o.block_height : 'Pending') + '</span>' +
'</div>';
}).join('');
container.querySelectorAll('.recent-tx-row[data-txid]').forEach(function (row) {
row.addEventListener('click', function () { showTxDetail(row.dataset.txid); });
});
if (fromCache) {
container.insertAdjacentHTML('beforeend', '<div class="tx-cache-note d">Cached ; resyncing blockchain</div>');
}
}
}
} catch (e) {
// history may fail during sync
}
}
// --- Receive ---
var receiveAddress = '';
var receivePreferredHandle = null;
var receiveHandleResolveTimer = null;
var requestLinkMode = 'blocknet';
function getReceivePrefs() {
try {
return JSON.parse(localStorage.getItem(walletKey('receivePrefs')) || '{}');
} catch (_) {
return {};
}
}
function saveReceivePrefs(prefs) {
localStorage.setItem(walletKey('receivePrefs'), JSON.stringify(prefs || {}));
}
function normalizeHandleInput(raw) {
var v = String(raw || '').trim();
if (!v) return '';
if (isHandlePrefix(v.charAt(0))) v = v.slice(1).trim();
return v;
}
function getReceiveHandleUriTarget() {
return receivePreferredHandle ? ('$' + receivePreferredHandle) : receiveAddress;
}
function setRequestLinkMode(mode) {
requestLinkMode = mode === 'bntpay' ? 'bntpay' : 'blocknet';
var blockBtn = document.getElementById('request-link-mode-blocknet');
var webBtn = document.getElementById('request-link-mode-bntpay');
if (blockBtn) blockBtn.classList.toggle('active', requestLinkMode === 'blocknet');
if (webBtn) webBtn.classList.toggle('active', requestLinkMode === 'bntpay');
var group = document.getElementById('request-link-group');
if (group && group.style.display !== 'none') {
generatePaymentLink();
}
}
function setReceiveShortnameStatus(html, cls) {
var el = document.getElementById('receive-shortname-status');
if (!el) return;
if (!html) {
el.style.display = 'none';
el.innerHTML = '';
return;
}
el.className = 'send-resolved' + (cls ? ' ' + cls : '');
el.innerHTML = html;
el.style.display = 'block';
}
function renderReceiveAddressAndQr() {
var target = getReceiveHandleUriTarget();
var addrEl = document.getElementById('receive-address');
if (addrEl) {
if (receivePreferredHandle) {
addrEl.innerHTML = '<span class="g">$' + escapeHtml(receivePreferredHandle) + '</span> <span class="d">(resolves to this wallet)</span>';
addrEl.dataset.copy = '$' + receivePreferredHandle;
} else {
addrEl.textContent = receiveAddress || 'Loading...';
addrEl.dataset.copy = receiveAddress || '';
}
delete addrEl.dataset.copyWired;
wireCopyable();
}
if (target && typeof qrcode === 'function') {
var svgHtml = renderQRSvg(target);
document.getElementById('qr-container').innerHTML = svgHtml;
document.getElementById('qr-overlay-inner').innerHTML = svgHtml;
}
}
async function verifyReceiveShortname(handle, persist) {
if (!handle) {
setReceiveShortnameStatus('', '');
return false;
}
setReceiveShortnameStatus('<span class="d">Resolving $' + escapeHtml(handle) + '...</span>');
try {
var data = await resolveHandle(handle);
var sameAddress = String(data.address || '') === String(receiveAddress || '');
if (!data.verified) {
setReceiveShortnameStatus('<span class="resolve-fail">✗ Not verified</span> <span class="d">$' + escapeHtml(handle) + '</span>');
return false;
}
if (!sameAddress) {
setReceiveShortnameStatus(
'<span class="resolve-fail">✗ Resolves elsewhere</span> ' +
'<span class="d">$' + escapeHtml(handle) + ' → ' + escapeHtml(abbrAddr(String(data.address || ''))) + '</span>'
);
return false;
}
setReceiveShortnameStatus('<span class="resolve-ok">✓ $' + escapeHtml(handle) + ' verified for this wallet</span>');
if (persist) {
receivePreferredHandle = handle;
saveReceivePrefs({ handle: handle });
renderReceiveAddressAndQr();
clearPaymentLink();
}
return true;
} catch (e) {
setReceiveShortnameStatus('<span class="resolve-fail">✗ Could not resolve</span> <span class="d">' + escapeHtml(normalizeError(e)) + '</span>');
return false;
}
}
function debouncedVerifyReceiveShortname() {
if (receiveHandleResolveTimer) clearTimeout(receiveHandleResolveTimer);
var input = document.getElementById('receive-shortname');
if (!input) return;
var handle = normalizeHandleInput(input.value);
if (!handle) {
setReceiveShortnameStatus('', '');
return;
}
receiveHandleResolveTimer = setTimeout(function () {
var current = normalizeHandleInput((document.getElementById('receive-shortname').value || ''));
if (current !== handle) return;
verifyReceiveShortname(handle, false);
}, 1800);
}
async function loadReceive() {
const data = await api('/api/wallet/address');
receiveAddress = data.address;
receivePreferredHandle = null;
var prefs = getReceivePrefs();
var input = document.getElementById('receive-shortname');
if (input) input.value = prefs && prefs.handle ? ('$' + prefs.handle) : '';
setReceiveShortnameStatus('', '');
if (prefs && prefs.handle) {
await verifyReceiveShortname(String(prefs.handle), true);
} else {
renderReceiveAddressAndQr();
}
document.getElementById('request-amount').value = '';
document.getElementById('request-memo').value = '';
document.getElementById('request-link-group').style.display = 'none';
setRequestLinkMode(requestLinkMode || 'blocknet');
}
function generatePaymentLink() {
if (!receiveAddress) return;
var amount = (document.getElementById('request-amount').value || '').trim();
var memo = (document.getElementById('request-memo').value || '').trim();
var target = getReceiveHandleUriTarget();
var uri = 'blocknet://' + target;
var params = [];
if (amount && parseFloat(amount) > 0) params.push('amount=' + encodeURIComponent(amount));
if (memo) params.push('memo=' + encodeURIComponent(memo));
if (params.length) uri += '?' + params.join('&');
var webUri = 'https://bntpay.com/' + target;
if (params.length) webUri += '?' + params.join('&');
var shownUri = requestLinkMode === 'bntpay' ? webUri : uri;
var group = document.getElementById('request-link-group');
var linkEl = document.getElementById('request-link');
linkEl.textContent = shownUri;
linkEl.dataset.copy = shownUri;
delete linkEl.dataset.copyWired;
group.style.display = '';
wireCopyable();
if (typeof qrcode === 'function') {
var svgHtml = renderQRSvg(shownUri);
document.getElementById('qr-container').innerHTML = svgHtml;
document.getElementById('qr-overlay-inner').innerHTML = svgHtml;
}
}
function clearPaymentLink() {
var group = document.getElementById('request-link-group');
if (group) group.style.display = 'none';
var target = getReceiveHandleUriTarget();
if (!target) return;
if (typeof qrcode === 'function') {
var svgHtml = renderQRSvg(target);
document.getElementById('qr-container').innerHTML = svgHtml;
document.getElementById('qr-overlay-inner').innerHTML = svgHtml;
}
}
async function saveReceiveShortname() {
var input = document.getElementById('receive-shortname');
if (!input) return;
var handle = normalizeHandleInput(input.value);
if (!handle) {
setReceiveShortnameStatus('<span class="d">Enter a shortname first</span>');
return;
}
await verifyReceiveShortname(handle, true);
}
function clearReceiveShortname() {
receivePreferredHandle = null;
saveReceivePrefs({});
var input = document.getElementById('receive-shortname');
if (input) input.value = '';
setReceiveShortnameStatus('', '');
renderReceiveAddressAndQr();
clearPaymentLink();
}
function renderQRSvg(text) {
var qr = qrcode(0, 'H');
qr.addData(text);
qr.make();
var n = qr.getModuleCount();
var cell = 10;
var quiet = 4 * cell;
var size = n * cell + quiet * 2;
var svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ' + size + ' ' + size + '" shape-rendering="crispEdges">';
svg += '<rect width="' + size + '" height="' + size + '" fill="#af0" rx="6"/>';
for (var r = 0; r < n; r++)
for (var c = 0; c < n; c++)
if (qr.isDark(r, c))
svg += '<rect x="' + (quiet + c * cell) + '" y="' + (quiet + r * cell) + '" width="' + cell + '" height="' + cell + '"/>';
var cx = size / 2, cy = size / 2;
var maxCover = Math.floor(n * 0.18);
var logoR = Math.floor(maxCover / 2) * cell;
var pad = cell;
var boxR = logoR + pad;
svg += '<rect x="' + (cx - boxR) + '" y="' + (cy - boxR) + '" width="' + (boxR * 2) + '" height="' + (boxR * 2) + '" rx="' + (cell * 1.5) + '" fill="#af0"/>';
svg += '<image href="blocknet.svg" x="' + (cx - logoR) + '" y="' + (cy - logoR) + '" width="' + (logoR * 2) + '" height="' + (logoR * 2) + '"/>';
svg += '</svg>';
return svg;
}
function showQROverlay() {
var overlay = document.getElementById('qr-overlay');
overlay.classList.add('visible');
if (qrDismissTimer) clearTimeout(qrDismissTimer);
qrDismissTimer = setTimeout(dismissQROverlay, 10000);
}
function dismissQROverlay() {
var overlay = document.getElementById('qr-overlay');
overlay.classList.remove('visible');
if (qrDismissTimer) { clearTimeout(qrDismissTimer); qrDismissTimer = null; }
}
// --- History ---
async function loadHistory() {
const data = await api('/api/wallet/history');
const container = document.getElementById('history-list');
var hasOutputsArray = data && Array.isArray(data.outputs);
var outputs = hasOutputsArray ? data.outputs : null;
var fromCache = false;
if (hasOutputsArray) {
try { localStorage.setItem(walletKey('txCache'), JSON.stringify(outputs)); } catch (_) {}
} else {
try { outputs = JSON.parse(localStorage.getItem(walletKey('txCache')) || 'null'); fromCache = true; } catch (_) {}
}
if (outputs) outputs = mergeWithPending(outputs);
if (!outputs || outputs.length === 0) {
renderHistoryBalanceSparkline([]);
container.innerHTML = '<div class="empty">No transactions yet</div>';
return;
}
renderHistoryBalanceSparkline(outputs);
// Show newest first
const sorted = outputs.slice().sort(function (a, b) {
if (!a.block_height && b.block_height) return -1;
if (a.block_height && !b.block_height) return 1;
return b.block_height - a.block_height;
});
container.innerHTML = sorted.map(o => {
const typeLabel = o.is_coinbase ? 'mining reward' : (o.spent ? 'sent' : 'received');
return '<div class="history-row' + (o.spent ? ' spent' : '') + '" data-txid="' + o.txid + '">' +
'<div class="history-amount ' + (o.spent ? 'r' : 'g') + '">' +
(o.spent ? '-' : '+') + formatBNT(o.amount) + ' BNT' +
'</div>' +
'<div class="history-meta">' +
(o.block_height
? '<a class="detail-link d" data-block="' + o.block_height + '">Block ' + o.block_height + '</a>'
: '<span class="d">Pending</span>') +
'<span class="' + (o.spent ? 'r' : 'g') + '">' + typeLabel + '</span>' +
'</div>' +
memoHtml(o) +
'<div class="history-tx d">' + copyable(o.txid, o.txid.substring(0, 24) + '...') + '</div>' +
'</div>';
}).join('');
if (fromCache) {
container.insertAdjacentHTML('afterbegin', '<div class="tx-cache-note d">Showing cached history ; resyncing blockchain</div>');
}
wireCopyable(container);
container.querySelectorAll('.history-row[data-txid]').forEach(row => {
row.addEventListener('click', function () { showTxDetail(row.dataset.txid); });
});
container.querySelectorAll('[data-block]').forEach(function (el) {
el.addEventListener('click', function (e) { e.stopPropagation(); showBlockDetail(el.dataset.block); });
});
}
async function exportHistoryCSV() {
var btn = document.getElementById('export-csv-btn');
if (btn.dataset.openPath) {
invoke('open_file', { path: btn.dataset.openPath });
return;
}
btn.disabled = true;
btn.textContent = 'Exporting...';
try {
var data = await api('/api/wallet/history');
var hasOutputsArray = data && Array.isArray(data.outputs);
var outputs = hasOutputsArray ? data.outputs : null;
if (!hasOutputsArray) {
try { outputs = JSON.parse(localStorage.getItem(walletKey('txCache')) || 'null'); } catch (_) {}
}
if (!outputs || outputs.length === 0) {
btn.textContent = 'No data';
setTimeout(function () { btn.disabled = false; btn.textContent = 'Export CSV'; }, 2000);
return;
}
var sorted = outputs.slice().sort(function (a, b) { return b.block_height - a.block_height; });
var lines = ['txid,output_index,amount_bnt,block_height,type,spent,spent_height'];
for (var i = 0; i < sorted.length; i++) {
var o = sorted[i];
var type = o.is_coinbase ? 'mining_reward' : (o.spent ? 'sent' : 'received');
lines.push(
o.txid + ',' +
o.output_index + ',' +
formatBNT(o.amount) + ',' +
o.block_height + ',' +
type + ',' +
o.spent + ',' +
(o.spent_height || '')
);
}
var csv = lines.join('\n');
var now = new Date();
var ts = now.getFullYear().toString() +
String(now.getMonth() + 1).padStart(2, '0') +
String(now.getDate()).padStart(2, '0') +
String(now.getHours()).padStart(2, '0') +
String(now.getMinutes()).padStart(2, '0') +
String(now.getSeconds()).padStart(2, '0');
var savedPath = await invoke('save_file', {
filename: 'blocknet-history-' + ts + '.csv',
contents: csv,
});
btn.textContent = 'Saved to ' + savedPath;
btn.disabled = false;
btn.dataset.openPath = savedPath;
setTimeout(function () {
btn.textContent = 'Export CSV';
delete btn.dataset.openPath;
}, 5000);
} catch (e) {
console.error('CSV export error:', e);
btn.textContent = 'Export failed';
setTimeout(function () { btn.disabled = false; btn.textContent = 'Export CSV'; }, 3000);
}
}
function renderHistoryBalanceSparkline(outputs) {
const root = document.getElementById('history-balance-sparkline');
if (!root) return;
if (!outputs || outputs.length < 2) {
root.innerHTML = '';
return;
}
const sorted = outputs.slice().sort((a, b) => {
const ah = Number(a.block_height || 0);
const bh = Number(b.block_height || 0);
if (ah !== bh) return ah - bh;
return Number(a.output_index || 0) - Number(b.output_index || 0);
});
const series = [{ height: Number(sorted[0].block_height || 0) - 1, value: 0 }];
let running = 0;
for (const out of sorted) {
const amount = Number(out.amount || 0);
running += out.spent ? -amount : amount;
series.push({
height: Number(out.block_height || 0),
value: running,
});
}
if (series.length < 2) {
root.innerHTML = '';
return;
}
const width = 1200;
const height = 280;
const padX = 6;
const padTop = 20;
const padBottom = 12;
const plotWidth = width - (padX * 2);
const plotHeight = height - padTop - padBottom;
const values = series.map(item => item.value);
const min = Math.min(0, Math.min.apply(null, values));
const max = Math.max(0, Math.max.apply(null, values));
const span = max - min || 1;
const baselineY = padTop + ((max - 0) / span) * plotHeight;
const points = series.map((item, i) => {
const x = padX + ((plotWidth * i) / (series.length - 1));
const y = padTop + ((max - item.value) / span) * plotHeight;
return { x, y };
});
const linePath = points.map((p, i) => (i === 0 ? 'M' : 'L') + p.x.toFixed(2) + ',' + p.y.toFixed(2)).join(' ');
const areaToBaselinePath = linePath +
' L' + points[points.length - 1].x.toFixed(2) + ',' + baselineY.toFixed(2) +
' L' + points[0].x.toFixed(2) + ',' + baselineY.toFixed(2) + ' Z';
root.innerHTML =
'<svg viewBox="0 0 ' + width + ' ' + height + '" preserveAspectRatio="none" role="img" aria-label="Balance trend">' +
'<defs>' +
'<clipPath id="history-over-clip"><rect x="0" y="0" width="' + width + '" height="' + baselineY.toFixed(2) + '" /></clipPath>' +
'<clipPath id="history-under-clip"><rect x="0" y="' + baselineY.toFixed(2) + '" width="' + width + '" height="' + (height - baselineY).toFixed(2) + '" /></clipPath>' +
'<linearGradient id="history-over-fill" x1="0" y1="0" x2="0" y2="1">' +
'<stop offset="0%" stop-color="#AF0" stop-opacity="0.22" />' +
'<stop offset="100%" stop-color="#AF0" stop-opacity="0" />' +
'</linearGradient>' +
'<linearGradient id="history-under-fill" x1="0" y1="0" x2="0" y2="1">' +
'<stop offset="0%" stop-color="orangered" stop-opacity="0" />' +
'<stop offset="100%" stop-color="orangered" stop-opacity="0.22" />' +
'</linearGradient>' +
'</defs>' +
'<path d="' + areaToBaselinePath + '" fill="url(#history-over-fill)" clip-path="url(#history-over-clip)" />' +
'<path d="' + areaToBaselinePath + '" fill="url(#history-under-fill)" clip-path="url(#history-under-clip)" />' +
'<path d="' + linePath + '" fill="none" stroke="#AF0" stroke-width="2.2" stroke-linejoin="round" stroke-linecap="round" clip-path="url(#history-over-clip)" />' +
'<path d="' + linePath + '" fill="none" stroke="orangered" stroke-width="2.2" stroke-linejoin="round" stroke-linecap="round" clip-path="url(#history-under-clip)" />' +
'</svg>';
}
// --- Mining ---
async function loadMining() {
// Skip UI refresh while a toggle or thread change is in progress
if (miningToggleBusy) return;
const data = await api('/api/mining');
isMining = data.running;
const indicator = document.getElementById('mining-indicator');
indicator.className = 'mining-indicator' + (data.running ? ' active' : '');
document.getElementById('mining-status').textContent = data.running ? 'Running' : 'Stopped';
if (!threadUpdatePending) {
updateStepperState(data.threads);
}
document.getElementById('mining-hashrate').textContent = data.running
? (data.hashrate || 0).toFixed(2) + ' H/s' : '--';
document.getElementById('mining-blocks').textContent = data.running
? (data.blocks_found || 0) : '--';
const btn = document.getElementById('mining-toggle');
if (!btn.disabled) {
btn.textContent = data.running ? 'Stop Mining' : 'Start Mining';
btn.className = 'mining-toggle-btn' + (data.running ? ' running' : '');
}
await refreshMiningDifficultySparkline();
await loadMiningMempool();
}
async function fetchDifficultyByHeights(heights) {
const results = await Promise.all(heights.map(async (height) => {
try {
const block = await api('/api/block/' + height);
return {
height: Number(block.height),
difficulty: Number(block.difficulty),
};
} catch (_) {
return null;
}
}));
return results
.filter(Boolean)
.filter(item => Number.isFinite(item.height) && Number.isFinite(item.difficulty))
.sort((a, b) => a.height - b.height);
}
function renderMiningDifficultySparkline(series) {
const root = document.getElementById('mining-difficulty-sparkline');
if (!root) return;
if (!series || series.length < 2) {
root.innerHTML = '';
return;
}
const width = 1200;
const height = 280;
const padX = 6;
const padTop = 20;
const padBottom = 12;
const plotWidth = width - (padX * 2);
const plotHeight = height - padTop - padBottom;
const values = series.map(item => item.difficulty);
const min = Math.min.apply(null, values);
const max = Math.max.apply(null, values);
const span = max - min;
const points = series.map((item, i) => {
const x = padX + ((plotWidth * i) / (series.length - 1));
const normalized = span === 0 ? 0.5 : ((item.difficulty - min) / span);
const y = padTop + ((1 - normalized) * plotHeight);
return { x, y };
});
const linePath = points.map((p, i) => (i === 0 ? 'M' : 'L') + p.x.toFixed(2) + ',' + p.y.toFixed(2)).join(' ');
const areaPath = linePath +
' L' + points[points.length - 1].x.toFixed(2) + ',' + (height - 1) +
' L' + points[0].x.toFixed(2) + ',' + (height - 1) + ' Z';
root.innerHTML =
'<svg viewBox="0 0 ' + width + ' ' + height + '" preserveAspectRatio="none" role="img" aria-label="Mining difficulty trend">' +
'<defs>' +
'<linearGradient id="difficulty-fill" x1="0" y1="0" x2="0" y2="1">' +
'<stop offset="0%" stop-color="#AF0" stop-opacity="0.24" />' +
'<stop offset="100%" stop-color="#000" stop-opacity="0" />' +
'</linearGradient>' +
'</defs>' +
'<path d="' + areaPath + '" fill="url(#difficulty-fill)" />' +
'<path d="' + linePath + '" fill="none" stroke="#AF0" stroke-width="2.4" stroke-linejoin="round" stroke-linecap="round" />' +
'</svg>';
}
async function refreshMiningDifficultySparkline() {
const root = document.getElementById('mining-difficulty-sparkline');
if (!root || miningDifficultyLoading) return;
const now = Date.now();
if (miningDifficultySeries.length > 1 && (now - miningDifficultyLastRefresh) < MINING_DIFFICULTY_REFRESH_MS) {
return;
}
miningDifficultyLoading = true;
try {
const status = await api('/api/status');
const tip = Number(status.chain_height || 0);
if (!Number.isFinite(tip) || tip < 0) return;
if (tip === miningDifficultyTipHeight && miningDifficultySeries.length > 1) {
miningDifficultyLastRefresh = now;
renderMiningDifficultySparkline(miningDifficultySeries);
return;
}
let nextSeries = miningDifficultySeries.slice();
if (nextSeries.length > 0 && tip > miningDifficultyTipHeight && (tip - miningDifficultyTipHeight) <= 4) {
const missingHeights = [];