-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
6284 lines (5753 loc) · 239 KB
/
Copy pathmain.js
File metadata and controls
6284 lines (5753 loc) · 239 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 dashStatusTimer = null;
let realtimeUnlisten = null;
let isNewWallet = false;
let daemonStartPromise = null;
let sessionPassword = '';
// Which wallet file this app told the daemon to load. The daemon holds one
// wallet at a time and has no endpoint that names it, so the GUI tracks it to
// know whether a password unlocks the loaded wallet or selects a different one.
let loadedWalletName = '';
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 pendingSendFingerprint = null;
let sendArmTimer = null;
let pendingSendIdempotency = null;
const SEND_IDEMPOTENCY_WINDOW_MS = 10 * 60 * 1000;
const SEND_MAX_RETRIES = 2;
// The daemon auto-selects UTXOs for /api/wallet/send. Under rapid sends (spending
// change that hasn't confirmed yet), across a reorg, or when another process shares
// the wallet, it can pick an output the network then rejects as already spent. That
// rejection is definitive — nothing was broadcast — so retrying with a fresh
// idempotency key lets the daemon re-select fresh inputs. Mirrors the exclude-and-retry
// posture of the predict payout service's coin-control path.
//
// Note: the auto-select endpoint does not document a distinct stale-input string (it
// surfaces as a generic build failure); these matchers are a safety net in case the
// daemon bubbles the underlying reason up. Genuine broadcast failures like "not enough
// ring members available" are deliberately NOT matched — retrying wouldn't help.
function isStaleInputError(msg) {
var m = String(msg || '').toLowerCase();
return (
m.indexOf('already spent') >= 0 ||
m.indexOf('key image already') >= 0 ||
m.indexOf('already in mempool') >= 0 ||
m.indexOf('double spend') >= 0 ||
m.indexOf('double-spend') >= 0
);
}
// Transient backpressure from the daemon (HTTP 429). The request was rejected before
// anything was built, so a short backoff + retry with the SAME idempotency key is safe.
function isTransientSendError(msg) {
var m = String(msg || '').toLowerCase();
return (
m.indexOf('send busy') >= 0 ||
m.indexOf('retry later') >= 0 ||
m.indexOf('rate limit') >= 0
);
}
function freshIdempotencyKey() {
var now = Date.now();
return (window.crypto && typeof window.crypto.randomUUID === 'function')
? window.crypto.randomUUID()
: ('send-' + now + '-' + Math.random().toString(16).slice(2));
}
let pendingDeepLink = null;
let dashLastHeight = -1;
let dashLastTxCount = -1;
let dashForceRefresh = false;
let dashPendingEta = 0; // seconds until unconfirmed funds confirm (from balance.pending_unconfirmed_eta)
let peerDetailActiveId = '';
let geoLookupRequested = {};
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_send: 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;
}
async function getDaemonPending() {
try {
var data = await api('/api/wallet/sends');
if (!data || !Array.isArray(data.sends)) return [];
return data.sends.filter(function (s) { return s && s.txid && s.in_mempool; }).map(function (s) {
var memo = (s.recipients && s.recipients[0] && s.recipients[0].memo_hex) || undefined;
return {
txid: s.txid,
amount: (Number(s.total_amount) || 0) + (Number(s.fee) || 0),
block_height: 0,
spent: true,
is_send: true,
is_coinbase: false,
memo_hex: memo
};
});
} catch (_) { return []; }
}
async function mergeWithPending(outputs) {
var local = prunePendingSends(outputs) || [];
var daemon = await getDaemonPending();
var confirmed = {};
outputs.forEach(function (o) { confirmed[o.txid] = true; });
var seen = {};
var pending = [];
daemon.concat(local).forEach(function (p) {
if (!p || !p.txid || seen[p.txid] || confirmed[p.txid]) return;
seen[p.txid] = true;
pending.push(p);
});
if (!pending.length) return outputs;
return pending.concat(outputs);
}
// --- Encrypted user-data store (contacts, notes, and per-wallet caches), keyed by the wallet password ---
function emptyUserData() {
return { contacts: [], txNotes: {}, txCache: [], receivePrefs: {}, peerGeoCache: {}, peerObservationCache: {}, sendLabels: {} };
}
function udObj(x) { return (x && typeof x === 'object' && !Array.isArray(x)) ? x : {}; }
var userData = emptyUserData();
var userDataWallet = '';
var userDataReady = false;
var userDataDirty = false;
var userDataWriting = false;
async function loadUserData() {
userDataReady = false;
userData = emptyUserData();
userDataWallet = activeWalletName;
if (!sessionPassword) return;
try {
var raw = await invoke('read_user_data', { wallet: userDataWallet, password: sessionPassword });
var parsed = {};
try { parsed = JSON.parse(raw) || {}; } catch (_) { parsed = {}; }
userData.contacts = Array.isArray(parsed.contacts) ? parsed.contacts : [];
userData.txNotes = udObj(parsed.txNotes);
userData.txCache = Array.isArray(parsed.txCache) ? parsed.txCache : [];
userData.receivePrefs = udObj(parsed.receivePrefs);
userData.peerGeoCache = udObj(parsed.peerGeoCache);
userData.peerObservationCache = udObj(parsed.peerObservationCache);
userData.sendLabels = udObj(parsed.sendLabels);
userDataReady = true;
} catch (e) {
userDataReady = false;
console.warn('user data load failed:', normalizeError(e));
return;
}
await migrateLegacyUserData();
}
async function migrateLegacyUserData() {
if (!userDataReady) return;
var changed = false;
try {
if (!userData.contacts.length) {
var lb = localStorage.getItem(walletKey('addressBook'));
if (lb) {
var book = JSON.parse(lb);
if (Array.isArray(book) && book.length) { userData.contacts = book; changed = true; }
}
}
} catch (_) {}
try {
var ln = localStorage.getItem('txNotes');
if (ln) {
var notes = JSON.parse(ln) || {};
Object.keys(notes).forEach(function (txid) {
if (userData.txNotes[txid] === undefined) { userData.txNotes[txid] = notes[txid]; changed = true; }
});
}
} catch (_) {}
['txCache'].forEach(function (k) {
try {
var raw = localStorage.getItem(walletKey(k));
if (!raw) return;
var val = JSON.parse(raw);
if (Array.isArray(val) && val.length && (!userData[k] || !userData[k].length)) { userData[k] = val; changed = true; }
} catch (_) {}
});
['receivePrefs', 'peerGeoCache', 'peerObservationCache'].forEach(function (k) {
try {
var raw = localStorage.getItem(walletKey(k));
if (!raw) return;
var val = JSON.parse(raw);
if (val && typeof val === 'object' && Object.keys(val).length && (!userData[k] || !Object.keys(userData[k]).length)) { userData[k] = val; changed = true; }
} catch (_) {}
});
if (!changed) return;
try {
await invoke('write_user_data', { wallet: userDataWallet, password: sessionPassword, contents: JSON.stringify(userData) });
['addressBook', 'txCache', 'receivePrefs', 'peerGeoCache', 'peerObservationCache'].forEach(function (k) {
try { localStorage.removeItem(walletKey(k)); } catch (_) {}
});
try { localStorage.removeItem('txNotes'); } catch (_) {}
} catch (e) {
console.warn('user data migration failed:', normalizeError(e));
}
}
function persistUserData() {
if (!userDataReady || !sessionPassword || !userDataWallet) return;
userDataDirty = true;
if (userDataWriting) return;
flushUserData();
}
function flushUserData() {
if (!userDataDirty) return;
userDataDirty = false;
userDataWriting = true;
var wallet = userDataWallet;
var pw = sessionPassword;
var snapshot = JSON.stringify(userData);
invoke('write_user_data', { wallet: wallet, password: pw, contents: snapshot })
.catch(function (e) { console.warn('user data save failed:', normalizeError(e)); })
.then(function () { userDataWriting = false; if (userDataDirty) flushUserData(); });
}
function resetUserData() {
userData = emptyUserData();
userDataWallet = '';
userDataReady = false;
userDataDirty = false;
userDataWriting = false;
historyOutputs = [];
historyChainHeight = 0;
historyFromCache = false;
historySends = {};
historySendRows = [];
historySendTo = {};
historySendTime = {};
}
function getTxNotes() {
return userData.txNotes || {};
}
function getTxNote(txid) {
return (userData.txNotes && userData.txNotes[txid]) || '';
}
function setTxNote(txid, note) {
note = String(note || '').trim();
if (!userData.txNotes) userData.txNotes = {};
if (note) userData.txNotes[txid] = note; else delete userData.txNotes[txid];
persistUserData();
}
function getTxCache() {
return Array.isArray(userData.txCache) ? userData.txCache : [];
}
function setTxCache(outputs) {
userData.txCache = Array.isArray(outputs) ? outputs : [];
persistUserData();
}
function updateHistoryRowNote(txid, note) {
var list = document.getElementById('history-list');
if (!list) return;
var row = list.querySelector('.history-row[data-txid="' + txid + '"]');
if (!row) return;
note = String(note || '').trim();
var noteEl = row.querySelector('.history-note');
var addEl = row.querySelector('.note-add');
if (note) {
if (noteEl) {
noteEl.textContent = note;
} else {
var el = document.createElement('div');
el.className = 'history-note';
el.textContent = note;
if (addEl) {
addEl.replaceWith(el);
} else {
var txEl = row.querySelector('.history-tx');
if (txEl) row.insertBefore(el, txEl); else row.appendChild(el);
}
}
} else if (noteEl) {
var add = document.createElement('div');
add.className = 'note-add';
add.textContent = '+ add note';
noteEl.replaceWith(add);
}
}
let activeWalletName = 'wallet.dat';
function walletKey(base) {
return base + ':' + activeWalletName;
}
function setActiveWalletName(name) {
if (typeof name === 'string' && name.trim()) {
activeWalletName = name.trim();
}
}
// --- Unlock screen state ---
// Where the shared password form returns to when "Back" is pressed:
// 'choice' (first-run onboarding) or 'unlock' (an existing wallet's unlock view).
var onboardReturnMode = 'choice';
// The current mode of the password screen, so async populate calls don't
// re-show unlock chrome after the user has already navigated to create/import.
var currentPwMode = '';
// Directory that holds the wallet files (learned from the active wallet path).
var unlockWalletDir = '';
function splitPath(fullPath) {
var norm = String(fullPath || '');
var idx = Math.max(norm.lastIndexOf('/'), norm.lastIndexOf('\\'));
if (idx < 0) return { dir: '', file: norm };
return { dir: norm.slice(0, idx + 1), file: norm.slice(idx + 1) };
}
function getWalletRecents() {
try {
var obj = JSON.parse(localStorage.getItem('blocknet.walletRecents') || '{}');
return (obj && typeof obj === 'object') ? obj : {};
} catch (_) {
return {};
}
}
function recordWalletRecency(name) {
if (!name) return;
try {
var recents = getWalletRecents();
recents[name] = Date.now();
localStorage.setItem('blocknet.walletRecents', JSON.stringify(recents));
} catch (_) {}
}
function formatRecency(ts) {
if (!ts) return '';
var diff = Date.now() - ts;
if (diff < 0) return '';
var mins = Math.floor(diff / 60000);
if (mins < 1) return 'just now';
if (mins < 60) return mins + 'm ago';
var hrs = Math.floor(mins / 60);
if (hrs < 24) return hrs + 'h ago';
var days = Math.floor(hrs / 24);
if (days < 30) return days + 'd ago';
var months = Math.floor(days / 30);
if (months < 12) return months + 'mo ago';
return Math.floor(months / 12) + 'y ago';
}
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 (_) {}
try {
var globalNotes = JSON.parse(localStorage.getItem('txNotes') || '{}') || {};
var changed = false;
for (var i = localStorage.length - 1; i >= 0; i--) {
var k = localStorage.key(i);
if (k && k.indexOf('txNotes:') === 0) {
try {
var legacy = JSON.parse(localStorage.getItem(k) || '{}') || {};
Object.keys(legacy).forEach(function (txid) {
if (!globalNotes[txid]) globalNotes[txid] = legacy[txid];
});
} catch (_) {}
localStorage.removeItem(k);
changed = true;
}
}
if (changed) localStorage.setItem('txNotes', JSON.stringify(globalNotes));
} 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);
}
// --- Desktop notifications ---
var notifyReady = false;
var notifyEnabled = true;
var lastPendingUnconfirmed = -1;
var confirmedSeen = null;
var txNotifyTimer = null;
function loadNotifyPref() {
try {
var v = localStorage.getItem('notifyEnabled');
if (v !== null) notifyEnabled = v !== 'false';
} catch (_) {}
}
function saveNotifyPref() {
try { localStorage.setItem('notifyEnabled', notifyEnabled ? 'true' : 'false'); } catch (_) {}
}
async function initNotifications() {
loadNotifyPref();
if (!notifyEnabled) return;
try {
var n = window.__TAURI__ && window.__TAURI__.notification;
if (!n) return;
var granted = await n.isPermissionGranted();
if (!granted) {
var res = await n.requestPermission();
granted = res === 'granted';
}
notifyReady = granted;
} catch (_) {
notifyReady = false;
}
}
function sendDesktopNotification(title, body) {
if (!notifyReady || !notifyEnabled) return;
try {
var n = window.__TAURI__ && window.__TAURI__.notification;
if (n) n.sendNotification({ title: title, body: body });
} catch (_) {}
}
async function pollTxNotifications() {
try {
var bal = null;
try { bal = await api('/api/wallet/balance'); } catch (_) {}
var scanning = !!(bal && bal.scanning);
// Incoming mempool funds are only visible in the balance (pending_unconfirmed),
// not in wallet history, so the pending alert is driven off the balance.
if (bal && !scanning) {
var pu = Number(bal.pending_unconfirmed) || 0;
if (lastPendingUnconfirmed < 0) {
lastPendingUnconfirmed = pu;
} else {
if (pu > lastPendingUnconfirmed) {
sendDesktopNotification('Incoming payment', '+' + formatBNTShort(pu - lastPendingUnconfirmed) + ' BNT pending');
}
lastPendingUnconfirmed = pu;
}
}
// Confirmed incoming payments show up in history as new non-coinbase received
// outputs. The change output of your own send also looks like this, so load
// the sends map and skip recorded-send txids — otherwise sending would ping a
// false "Payment confirmed" when the change confirms.
var data = null;
try { data = await api('/api/wallet/history'); } catch (_) {}
if (data && Array.isArray(data.outputs)) {
// Local sends context — must not touch the shared globals the History view uses.
var sendsCtx = await fetchSendsCtx(0);
var incoming = data.outputs.filter(function (o) {
return o && o.txid && !o.spent && !o.is_coinbase && o.block_height && !sendsCtx.sends[o.txid];
});
var seeding = confirmedSeen === null;
if (seeding) confirmedSeen = {};
incoming.forEach(function (o) {
if (confirmedSeen[o.txid]) return;
confirmedSeen[o.txid] = true;
if (!seeding && !scanning) {
sendDesktopNotification('Payment confirmed', '+' + formatBNTShort(o.amount) + ' BNT confirmed');
}
});
}
} catch (_) {}
}
// --- 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;
}
// Puts the daemon on the wallet the user picked, without restarting it. Every
// wallet file lives in one directory, so the daemon takes any of them by name:
// drop the one it holds, load the requested one. Restarting instead would
// reopen the chain db and redial peers for a change the API already covers.
async function loadOrUnlockWallet(password, walletName) {
const target = walletName || activeWalletName || '';
if (loadedWalletName && target && loadedWalletName !== target) {
await unloadWallet();
}
try {
await loadWalletFile(password, target);
return;
} catch (e) {
const msg = normalizeError(e).toLowerCase();
if (!msg.includes('wallet already loaded')) {
throw e;
}
}
// Already loaded: the password unlocks it. A load that is still in flight
// answers the same way while holding no wallet yet, so treat that as a
// not-ready daemon and let the load finish.
try {
await api('/api/wallet/unlock', { method: 'POST', body: { password } });
if (target) loadedWalletName = target;
return;
} catch (e) {
if (!normalizeError(e).toLowerCase().includes('no wallet loaded')) {
throw e;
}
}
await new Promise(function (r) { setTimeout(r, 1000); });
await loadWalletFile(password, target);
}
async function loadWalletFile(password, walletName) {
const body = { password };
if (walletName) body.filepath = walletName;
await api('/api/wallet/load', { method: 'POST', body: body });
loadedWalletName = walletName || '';
}
// Drops the daemon's wallet so another one can take its place. A daemon with no
// wallet loaded is already in the wanted state, so that error is not a failure.
async function unloadWallet() {
try {
await api('/api/wallet/unload', { method: 'POST' });
} catch (e) {
if (!normalizeError(e).toLowerCase().includes('no wallet loaded')) {
throw e;
}
}
loadedWalletName = '';
}
// --- Formatting ---
function formatBNT(atomic) {
const n = Number(atomic);
if (!isFinite(n)) return '--';
return (n / 100000000).toFixed(8);
}
function formatBNTShort(atomic) {
const n = Number(atomic);
if (!isFinite(n)) return '--';
const val = n / 100000000;
if (val === 0) return '0.00';
if (val < 0.01) return val.toFixed(8);
return val.toFixed(2);
}
function formatEta(secs) {
var mins = Math.round((Number(secs) || 0) / 60);
if (mins < 60) return mins + ' min';
var hrs = Math.floor(mins / 60);
var rem = mins % 60;
return rem ? (hrs + 'h ' + rem + 'm') : (hrs + 'h');
}
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';
}
function formatDuration(ms) {
var s = Math.floor(Math.max(0, ms) / 1000);
var d = Math.floor(s / 86400); s -= d * 86400;
var h = Math.floor(s / 3600); s -= h * 3600;
var m = Math.floor(s / 60); s -= m * 60;
if (d > 0) return d + 'd ' + h + 'h';
if (h > 0) return h + 'h ' + m + 'm';
if (m > 0) return m + 'm ' + s + 's';
return s + 's';
}
function formatHashrate(hs) {
var n = Number(hs) || 0;
if (n < 1000) return n.toFixed(0) + ' H/s';
var units = ['KH/s', 'MH/s', 'GH/s', 'TH/s', 'PH/s'];
var i = -1;
do { n /= 1000; i++; } while (n >= 1000 && i < units.length - 1);
return n.toFixed(2) + ' ' + units[i];
}
function identiconSvg(seedStr, dim) {
var SIZE = 8;
var seed = [0, 0, 0, 0];
var s = String(seedStr || '').toLowerCase();
for (var i = 0; i < s.length; i++) {
seed[i % 4] = ((seed[i % 4] << 5) - seed[i % 4] + s.charCodeAt(i)) | 0;
}
function rand() {
var t = seed[0] ^ (seed[0] << 11);
seed[0] = seed[1]; seed[1] = seed[2]; seed[2] = seed[3];
seed[3] = (seed[3] ^ (seed[3] >>> 19) ^ t ^ (t >>> 8)) | 0;
return (seed[3] >>> 0) / 4294967296;
}
function color() {
var h = Math.floor(rand() * 360);
var sat = rand() * 60 + 40;
var li = (rand() + rand() + rand() + rand()) * 25;
return 'hsl(' + h + ',' + sat.toFixed(0) + '%,' + li.toFixed(0) + '%)';
}
var fg = color(), bg = color(), spot = color();
var cells = [];
var dataW = Math.ceil(SIZE / 2);
for (var y = 0; y < SIZE; y++) {
var row = [];
for (var x = 0; x < dataW; x++) row[x] = Math.floor(rand() * 2.3);
row = row.concat(row.slice(0, SIZE - dataW).reverse());
for (var k = 0; k < SIZE; k++) cells.push(row[k]);
}
var rects = '';
for (var c = 0; c < cells.length; c++) {
if (cells[c] === 0) continue;
rects += '<rect x="' + (c % SIZE) + '" y="' + Math.floor(c / SIZE) + '" width="1" height="1" fill="' + (cells[c] === 1 ? fg : spot) + '"/>';
}
var px = dim || 24;
return '<svg class="identicon" width="' + px + '" height="' + px + '" viewBox="0 0 ' + SIZE + ' ' + SIZE +
'" shape-rendering="crispEdges" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">' +
'<rect width="' + SIZE + '" height="' + SIZE + '" fill="' + bg + '"/>' + rects + '</svg>';
}
// --- 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(); updateCoinControlVisibility(); break;
case 'receive': await loadReceive(); break;
case 'history': await loadHistory(); break;
case 'mining': await loadMining(); break;
case 'network': await loadNetwork(); break;
case 'economics': await loadEconomics(); 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';
}
}
// --- Economics ---
var ECON_INITIAL_REWARD = 72325093035; // 723.25 BNT in atomic units
var ECON_TAIL_EMISSION = 200000000; // 2.0 BNT in atomic units
var ECON_MONTHS_TO_TAIL = 48;
var ECON_DECAY_RATE = 0.75; // per year
function econBlockReward(month) {
if (month >= ECON_MONTHS_TO_TAIL) return ECON_TAIL_EMISSION;
var decay = Math.exp(-ECON_DECAY_RATE * (month / 12));
var reward = (ECON_INITIAL_REWARD - ECON_TAIL_EMISSION) * decay + ECON_TAIL_EMISSION;
return reward < ECON_TAIL_EMISSION ? ECON_TAIL_EMISSION : reward;
}
function econBnt(atomic) {
return ((Number(atomic) || 0) / 100000000).toLocaleString(undefined, { maximumFractionDigits: 2 });
}
async function loadEconomics() {
var statusEl = document.getElementById('economics-status');
if (statusEl) statusEl.style.display = 'none';
function set(id, val) { var el = document.getElementById(id); if (el) el.textContent = val; }
var data;
try {
data = await api('/api/stats');
} catch (e) {
if (statusEl) {
statusEl.className = 'status-message error';
statusEl.textContent = 'Could not load economics: ' + normalizeError(e);
statusEl.style.display = 'block';
}
return;
}
var emitted = Number(data.emitted) || 0;
var remaining = Number(data.remaining) || 0;
var target = Number(data.target_supply) || (emitted + remaining);
var pct = typeof data.pct_emitted === 'number' ? data.pct_emitted : (target > 0 ? (emitted / target) * 100 : 0);
var height = Number(data.height) || 0;
var blocksPerMonth = Number(data.blocks_per_month) || 0;
set('econ-pct', pct.toFixed(2) + '%');
var fill = document.getElementById('econ-supply-fill');
if (fill) fill.style.width = Math.max(0, Math.min(100, pct)).toFixed(2) + '%';
set('econ-emitted', econBnt(emitted) + ' BNT');
set('econ-remaining', econBnt(remaining) + ' BNT');
set('econ-target', econBnt(target));
set('econ-months-to-tail', String(Number(data.months_to_tail) || ECON_MONTHS_TO_TAIL));
set('econ-tail', econBnt(Number(data.tail_emission) || ECON_TAIL_EMISSION));
set('econ-reward', econBnt(data.block_reward) + ' BNT');
set('econ-hashrate', formatHashrate(data.network_hashrate));
set('econ-blocktime', (Number(data.avg_block_time) || 0).toFixed(0) + 's');
set('econ-difficulty', (Number(data.difficulty) || 0).toLocaleString());
set('econ-height', height.toLocaleString());
set('econ-blocks-month', blocksPerMonth.toLocaleString());
var currentMonth = blocksPerMonth > 0 ? (height / blocksPerMonth) : 0;
var chart = document.getElementById('econ-chart');
if (chart) chart.innerHTML = buildEmissionCurve(currentMonth);
}
function buildEmissionCurve(currentMonth) {
var W = 640, H = 240, padL = 52, padR = 16, padT = 22, padB = 28;
var plotW = W - padL - padR, plotH = H - padT - padB;
var maxMonth = ECON_MONTHS_TO_TAIL + 12;
var maxR = ECON_INITIAL_REWARD / 100000000;
function xOf(m) { return padL + (m / maxMonth) * plotW; }
// Linear y-scale from 0 to the initial reward, matching the explorer's
// emission chart. The unit is shown once as a legend above the plot rather
// than repeated on each tick.
function yOf(rBnt) { return padT + (1 - rBnt / maxR) * plotH; }
var pts = [];
for (var m = 0; m <= maxMonth; m += 0.5) {
pts.push(xOf(m).toFixed(1) + ',' + yOf(econBlockReward(m) / 100000000).toFixed(1));
}
// Five evenly-spaced gridlines/ticks, like explorer.go's draw() helper.
var grid = '', ylabels = '';
for (var i = 0; i <= 4; i++) {
var v = maxR * (4 - i) / 4;
var y = yOf(v);
grid += '<line x1="' + padL + '" y1="' + y.toFixed(1) + '" x2="' + (W - padR) + '" y2="' + y.toFixed(1) + '" class="econ-grid"/>';
ylabels += '<text x="' + (padL - 8) + '" y="' + (y + 3).toFixed(1) + '" class="econ-axis" text-anchor="end">' + Math.round(v) + '</text>';
}
var xlabels = '';
[0, 12, 24, 36, 48, 60].forEach(function (mo) {
if (mo > maxMonth) return;
xlabels += '<text x="' + xOf(mo).toFixed(1) + '" y="' + (H - 8) + '" class="econ-axis" text-anchor="middle">' + (mo / 12) + 'y</text>';
});
var tailX = xOf(ECON_MONTHS_TO_TAIL);
var cm = Math.max(0, Math.min(maxMonth, currentMonth));
var curX = xOf(cm), curY = yOf(econBlockReward(cm) / 100000000);
return '<svg viewBox="0 0 ' + W + ' ' + H + '" class="econ-curve" preserveAspectRatio="xMidYMid meet" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Block reward emission curve">' +
grid +
'<line x1="' + tailX.toFixed(1) + '" y1="' + padT + '" x2="' + tailX.toFixed(1) + '" y2="' + (H - padB) + '" class="econ-tailline"/>' +
'<text x="' + tailX.toFixed(1) + '" y="' + (padT - 8) + '" class="econ-axis" text-anchor="middle">tail</text>' +
'<polyline points="' + pts.join(' ') + '" class="econ-line" fill="none"/>' +
'<line x1="' + curX.toFixed(1) + '" y1="' + padT + '" x2="' + curX.toFixed(1) + '" y2="' + (H - padB) + '" class="econ-nowline"/>' +
'<circle cx="' + curX.toFixed(1) + '" cy="' + curY.toFixed(1) + '" r="4" class="econ-nowdot"/>' +
'<text x="' + padL + '" y="' + (padT - 8) + '" class="econ-axis" text-anchor="start">BNT/block</text>' +
ylabels + xlabels +
'</svg>';
}
// --- Dashboard ---
// Lightweight status-panel refresh (chain height, peers, mempool, sync %).
// Cheap enough to run on a fast timer while the dashboard is open so the
// sync readout advances without the user switching views.
async function refreshDashStatus() {
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;
var bestHashEl = document.getElementById('dash-best-hash');
if (bestHashEl) {
var bestHash = String(status.best_hash || '');
bestHashEl.textContent = bestHash ? bestHash.slice(0, 20) + '…' + bestHash.slice(-8) : '--';
bestHashEl.title = bestHash;
}
var totalWorkEl = document.getElementById('dash-total-work');
if (totalWorkEl) totalWorkEl.textContent = (Number(status.total_work) || 0).toLocaleString();
var mempoolBytesEl = document.getElementById('dash-mempool-bytes');
if (mempoolBytesEl) mempoolBytesEl.textContent = formatBytes(status.mempool_bytes);
var identityAgeEl = document.getElementById('dash-identity-age');
if (identityAgeEl) identityAgeEl.textContent = status.identity_age || '--';
const syncLabel = status.syncing
? 'Syncing' + (status.sync_percent ? ' ' + status.sync_percent : '')
: 'Synced';
document.getElementById('dash-syncing').textContent = syncLabel;
const dot = document.getElementById('status-dot');
if (dot) {
dot.className = 'status-dot' + (status.syncing ? ' syncing' : '');
var dotTitle = 'height: ' + heightLabel
+ (status.syncing && status.sync_target ? ' / ' + Number(status.sync_target).toLocaleString() : '');
dot.title = dotTitle;
dot.setAttribute('name', dotTitle);
}
const syncNotice = document.getElementById('dash-sync-notice');
if (syncNotice) {
if (status.syncing) {
const pctPart = status.sync_percent ? ' (' + status.sync_percent + ')' : '';
syncNotice.textContent = 'Syncing blockchain' + pctPart
+ ' — your balance may be incomplete until sync finishes.';
syncNotice.style.display = 'block';
} else {
syncNotice.style.display = 'none';
}
}
} catch (e) {
console.error('Status error:', e);
}
}
var lockedFetchAt = 0;
async function updateLockedFundsPreview(balance) {
var el = document.getElementById('dash-locked');
if (!el) return;
var pending = Number(balance && balance.pending) || 0;
if (pending <= 0) { el.style.display = 'none'; el.dataset.filled = ''; return; }
var now = Date.now();
if (now - lockedFetchAt < 15000 && el.dataset.filled === '1') { el.style.display = ''; return; }
lockedFetchAt = now;
try {
var data = await api('/api/wallet/outputs');
var outs = (data && Array.isArray(data.outputs)) ? data.outputs : [];
var minRemaining = 0;
for (var i = 0; i < outs.length; i++) {
var o = outs[i];
if (!o || o.status !== 'pending') continue;
var needed = o.type === 'coinbase' ? 60 : 10;
var rem = needed - (Number(o.confirmations) || 0);
if (rem < 1) rem = 1;
if (minRemaining === 0 || rem < minRemaining) minRemaining = rem;
}