-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
9325 lines (8233 loc) · 299 KB
/
Copy pathapp.js
File metadata and controls
9325 lines (8233 loc) · 299 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
/*
Bitkit Watch local prototype
Open index.html directly in a browser. No build step is required.
API swap points:
- ADDRESS_API_PROVIDERS below can be replaced with your preferred on-chain providers.
- PRICE_API layer below can be replaced with an internal market data service later.
*/
(() => {
"use strict";
// ---------------------------------------------------------------------------
// Constants and configuration
// ---------------------------------------------------------------------------
const DAY_MS = 24 * 60 * 60 * 1000;
const HOUR_MS = 60 * 60 * 1000;
const CACHE_MAX_AGE_MS = HOUR_MS;
const SATOSHI_DEMO_AUTO_REFRESH_MAX_AGE_MS = HOUR_MS;
const TRANSIENT_MESSAGE_DURATION_MS = 6000;
const BANNER_DISMISS_ANIMATION_MS = 260;
const ONE_YEAR_DAYS = 365;
const HISTORY_DAYS = 120;
const COLLAPSED_TRANSACTION_COUNT = 3;
const TRANSACTION_PAGE_SIZE = 10;
const MAX_PASTED_ADDRESSES = 10;
const MAX_WATCHED_ADDRESSES = 100;
const MAX_WALLETS = 50;
const MAX_TAGS_PER_ADDRESS = 20;
const MAX_ADDRESS_TAG_LENGTH = 48;
const MAX_ADDRESS_INPUT_LENGTH = 4096;
const MAX_TRANSACTIONS_PER_ADDRESS = 1000;
const MAX_TRANSACTION_PAGES = 18;
const MAX_EXPLORER_CONCURRENCY = 3;
const MAX_API_RESPONSE_BYTES = 2 * 1024 * 1024;
const MAX_EXPLORER_TRANSACTION_RESPONSE_BYTES = 8 * 1024 * 1024;
const MAX_WALLET_CARD_CHART_POINTS = 365;
const MAX_STATE_STORAGE_BYTES = 2 * 1024 * 1024;
const MAX_RUNTIME_CACHE_STORAGE_BYTES = 10 * 1024 * 1024;
const HISTORY_AUTO_LOAD_FAILURE_WARNING = "History could not be loaded automatically. Click Refresh to retry.";
const TRUNCATED_ACTIVITY_LIMIT_NOTE = `(max ${MAX_TRANSACTIONS_PER_ADDRESS} newest transactions)`;
const LEGACY_TRUNCATED_ACTIVITY_WARNING_PREFIXES = Object.freeze([
"Address activity exceeds limit.",
"Some address activity exceeds",
]);
const DUST_ACTIVITY_THRESHOLD_SATS = 1000;
const DETAIL_CHART_RANGES = {
"1D": "1 day",
"30D": "30 day",
"1Y": "1 year",
ALL: "All",
};
const STORAGE_KEYS = {
state: "bitkit-vault-state-v1",
stateQuarantine: "bitkit-vault-state-quarantine-v1",
runtimeCache: "bitkit-vault-runtime-cache-v1",
};
const FIGMA_CAPTURE_HASH_KEYS = Object.freeze([
"figmacapture",
"figmaendpoint",
"figmadelay",
"figmaselector",
]);
const DEFAULT_WALLET_NAMES = ["Savings", "Retirement"];
const LEGACY_BUSINESS_WALLET_NAME = "Business";
const SATOSHI_DEMO_KEY = "satoshi-v1";
const SATOSHI_DEMO_NAME = "Satoshi";
const SATOSHI_DEMO_ADDRESSES = [
"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa",
"12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S",
"12c6DSiU4Rq3P4ZxziKxzrL5LmMBrzjrJX",
"1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1",
"1FvzCLoTPGANNjWoUo6jUGuAG3wg1w4YjR",
];
const SATOSHI_DEMO_ADDRESS_KEYS = new Set(
SATOSHI_DEMO_ADDRESSES.map((address) => address.toLowerCase())
);
const SATOSHI_DEMO_ADDRESS_TAGS = Object.freeze({
"1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa": ["genesis", "unspendable"],
});
const BUNDLED_BITCOIN_FACTS = globalThis.BITKIT_VAULT_BITCOIN_FACTS;
const PROBABLE_MNEMONIC_WORD_COUNTS = new Set([12, 15, 18, 21, 24]);
const EXTENDED_PRIVATE_KEY_PREFIXES = Object.freeze([
"xprv",
"yprv",
"zprv",
"Yprv",
"Zprv",
"tprv",
"uprv",
"vprv",
"Uprv",
"Vprv",
]);
const ADDRESS_API_PROVIDERS = [
{ name: "Mempool", baseUrl: "https://mempool.space/api" },
{ name: "Blockstream", baseUrl: "https://blockstream.info/api" },
];
const SUPPORTED_FIAT_CURRENCIES = Object.freeze(["USD", "EUR", "JPY", "GBP", "CNY"]);
const FIAT_DISPLAY_META = Object.freeze({
USD: { prefix: "$", icon: "$", fractionDigits: 2 },
EUR: { prefix: "€", icon: "€", fractionDigits: 2 },
JPY: { prefix: "¥", icon: "¥", fractionDigits: 0 },
GBP: { prefix: "£", icon: "£", fractionDigits: 2 },
CNY: { prefix: "CN¥", icon: "¥", fractionDigits: 2 },
});
const SATOSHI_BAKED_SNAPSHOT = normalizeBakedDemoSnapshot(globalThis.BITKIT_VAULT_SATOSHI_SNAPSHOT);
const FAQ_ITEMS = Object.freeze([
{
icon: "lock",
question: "Does Bitkit Watch hold my keys?",
answer:
"No. Bitkit Watch is watch-only. It never asks for a seed, never imports a private key, and cannot sign on your behalf.",
},
{
icon: "database",
question: "Where does my data live?",
answer:
"On this device, in this browser. Wallet names, watchlists, settings, and cached snapshots stay local until you wipe them.",
},
{
icon: "cloud-off",
question: "Does Synonym get my watchlist?",
answer:
"There is no Bitkit Watch account and no cloud sync. Synonym does not get a hosted profile of your watch-only setup.",
},
{
icon: "plug",
question: "What gets sent to APIs?",
answer:
"Only the public addresses you choose to watch, plus market-data requests needed to price them. Enough to price your stack, not enough to control it.",
},
{
icon: "fast-forward",
question: "Can Bitkit Watch move my bitcoin?",
answer:
"Not a chance. No signing. No custody. No hot wallet tricks. It cannot spend your ₿. Download Bitkit for iOS and Android to intentionally spend your bitcoin.",
},
{
icon: "shield",
question: "How do I stay extra private?",
answer:
"Watch-only is safer, but not invisible. Address lookups still touch public APIs, so use a fresh browser profile, VPN, or Tor when you want more distance.",
},
]);
const DEFAULT_SETTINGS = Object.freeze({
activeWalletId: null,
activeAddressId: null,
displayUnit: "BTC",
fiatCurrency: "USD",
hideDust: true,
bitcoinNotation: "MODERN",
showBackgroundGraphics: true,
});
const DOM_ID_GROUPS = {
header: [
"brandHomeButton",
"vaultHomeButton",
"refreshButton",
"toggleBalancesButton",
"balanceToggleIcon",
"unitDisplayButton",
"unitDisplayButtonLabel",
"settingsButton",
"faqButton",
"headerStatus",
"faqHeaderDivider",
"faqCrumb",
"walletHeaderDivider",
"walletCrumb",
"addressHeaderDivider",
"addressCrumb",
"addressStatusDivider",
"addressCopyStatus",
"addressCrumbTextFull",
"addressCrumbTextShort",
"walletTitleButton",
"walletTitleText",
"walletTitleIcon",
"walletTitleCaret",
"walletDeleteButton",
],
overview: ["walletsOverview", "walletGrid", "overviewFaqButton"],
faq: ["faqView", "faqGrid"],
detail: [
"walletDetail",
"walletSecondarySummary",
"walletPrimarySummary",
"walletTransactions",
"walletTransactionsControls",
"walletTransactionsToggle",
"walletTransactionsLimitNote",
"addressTagsSection",
"addressTagList",
"addressTagForm",
"addressTagInput",
"addressTagFeedback",
"walletAddressesSection",
"walletDetailSidebar",
"walletAddressesKicker",
"walletAddressesHeading",
"walletAddressList",
"walletAddAddressForm",
"walletAddressInput",
"walletAddressEmptyWarning",
"walletAddressFeedback",
"walletChartKicker",
"walletChartTitleSymbol",
"walletChartTitleText",
"walletChartGrowth",
"walletChartTabs",
"walletChartStage",
"walletFactsSection",
"walletFactsText",
"walletFactsButton",
],
modals: [
"chartModal",
"chartModalBackdrop",
"chartModalClose",
"chartModalKicker",
"chartModalTitleSymbol",
"chartModalTitleText",
"chartModalGrowth",
"chartModalTabs",
"chartModalStage",
"settingsModal",
"settingsModalBackdrop",
"settingsModalClose",
"settingsFooterCloseButton",
"settingsClearStorageButton",
"settingsHideDustButton",
"settingsBackgroundGraphicsButton",
"settingsNotationModern",
"settingsNotationClassic",
"settingsFiatIcon",
"settingsFiatNotice",
"settingsFiatUsd",
"settingsFiatEur",
"settingsFiatJpy",
"settingsFiatGbp",
"settingsFiatCny",
"transactionModal",
"transactionModalBackdrop",
"transactionModalClose",
"transactionModalKicker",
"transactionModalBody",
],
shell: ["appBanner", "appBannerText", "appBannerDismiss", "appFooterPrice", "appFooterPriceReference", "appFooterPriceValue"],
};
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
const dom = {};
let bitcoinFacts = [];
let chartResizeFrame = 0;
let headerStatusTimer = 0;
let bannerTimer = 0;
let bannerHideTimer = 0;
let bannerTimerTarget = null;
let addressFeedbackFadeTimer = 0;
let addressFeedbackHideTimer = 0;
let addressCopyTimer = 0;
let overviewDetailPreloadPromise = null;
let activeDetailPreloadPromise = null;
let overviewCardRefreshInProgress = false;
let satoshiDemoIncrementalRefreshPromise = null;
let satoshiDemoIncrementalRefreshGroupId = null;
const StorageLayer = {
buildDefaultState,
loadState,
saveState,
normalizeImportedState,
loadRuntimeCache,
saveRuntimeCache,
clearRuntimeCache,
};
const HISTORY_SCOPE_ORDER = {
SUMMARY: 0,
"30D": 1,
"1Y": 2,
ALL: 3,
};
let state = StorageLayer.loadState();
let runtime = createRuntimeState();
// ---------------------------------------------------------------------------
// Boot
// ---------------------------------------------------------------------------
document.addEventListener("DOMContentLoaded", init);
function init() {
cacheDom();
sanitizeState();
hydrateRuntimeFromCache();
hydrateBakedDemoRuntimeIfNeeded();
bitcoinFacts = normalizeBitcoinFactsPayload(BUNDLED_BITCOIN_FACTS);
ensureCurrentBitcoinFactIndex();
applyRouteFromHash({ replaceInvalid: true, renderAfter: false, preloadDetail: false });
StorageLayer.saveState(state);
bindEvents();
render();
syncViewRoute("replace");
if (state.addresses.length) {
refreshCurrentPriceInBackground();
}
if (state._loadWarning) {
runtime.banner = {
tone: "warning",
text: state._loadWarning,
};
renderBanner();
}
preloadActiveDetailDataIfNeeded();
refreshBundledSatoshiDemoInBackground(getBundledSatoshiDemoGroupId());
}
function createRuntimeState() {
return {
isLoading: false,
isRefreshing: false,
hasLoadedOnce: false,
historyScope: "SUMMARY",
currentPriceUsd: null,
fiatExchangeRates: createDefaultFiatExchangeRates(),
currentPriceFiat: null,
currentPriceFiatCurrency: null,
fiatPriceHistory: new Map(),
fiatIntradayPriceHistory: new Map(),
priceHistory: new Map(),
intradayPriceHistory: new Map(),
historyAvailable: true,
historyMissingDays: 0,
addressSnapshots: [],
partialFailures: [],
approximationMode: false,
banner: null,
headerStatus: "",
headerStatusTone: "default",
copiedAddressId: null,
currentView: "watch",
currentFactIndex: null,
lastFactsWalletId: null,
chartModalOpen: false,
settingsModalOpen: false,
timelineStart: null,
timelineEnd: null,
intradayStart: null,
intradayEnd: null,
editingWalletId: null,
walletNameDraft: "",
transactionVisibleCountByDetailId: {},
selectedTransactionTxid: null,
expandedTechnicalTransactionTxid: null,
loadingTechnicalTransactionTxid: null,
failedTechnicalTransactionTxids: new Set(),
transactionDetailsByTxid: new Map(),
transactionTechnicalAnimationTimer: null,
};
}
function hydrateRuntimeFromCache() {
const cachedRuntime = StorageLayer.loadRuntimeCache(state);
if (!cachedRuntime) {
return;
}
runtime = {
...runtime,
...cachedRuntime,
hasLoadedOnce: cachedRuntime.addressSnapshots.length > 0,
};
if (cachedRuntime.rebuiltTimelines) {
StorageLayer.saveRuntimeCache(runtime);
}
}
function hydrateBakedDemoRuntimeIfNeeded() {
if (!SATOSHI_BAKED_SNAPSHOT || !isFreshSatoshiDemoVault()) {
return false;
}
const bakedRuntime = SATOSHI_BAKED_SNAPSHOT.runtimeCache;
const bakedEntries = state.addresses.filter((entry) =>
Object.prototype.hasOwnProperty.call(SATOSHI_BAKED_SNAPSHOT.balancesByAddress, entry.address)
);
if (!bakedEntries.length) {
return false;
}
const shouldUseBakedDetails =
bakedRuntime &&
(!hasCompleteCachedCoverage(bakedEntries) ||
!hasCompleteDetailCoverage(bakedRuntime.historyScope, bakedEntries));
if (runtime.addressSnapshots.length && !shouldUseBakedDetails) {
return false;
}
const currentPriceUsd = Number.isFinite(bakedRuntime?.currentPriceUsd)
? bakedRuntime.currentPriceUsd
: SATOSHI_BAKED_SNAPSHOT.currentPriceUsd;
const timelineStart = Number.isFinite(bakedRuntime?.timelineStart)
? bakedRuntime.timelineStart
: null;
const timelineEnd = Number.isFinite(bakedRuntime?.timelineEnd)
? bakedRuntime.timelineEnd
: null;
const intradayStart = Number.isFinite(bakedRuntime?.intradayStart)
? bakedRuntime.intradayStart
: null;
const intradayEnd = Number.isFinite(bakedRuntime?.intradayEnd)
? bakedRuntime.intradayEnd
: null;
const snapshots = bakedEntries.map((entry) => {
const bakedSnapshot = bakedRuntime?.snapshotsByAddress.get(entry.address);
if (!bakedSnapshot) {
return PortfolioLayer.buildSummarySnapshot({
entry,
provider: "Baked Demo Cache",
balanceSats: SATOSHI_BAKED_SNAPSHOT.balancesByAddress[entry.address],
currentPriceUsd,
});
}
const txEvents = bakedSnapshot.txEvents;
return {
entry,
provider: bakedSnapshot.provider,
balanceSats: bakedSnapshot.balanceSats,
usdValue: (bakedSnapshot.balanceSats / 1e8) * currentPriceUsd,
txEvents,
balanceTimeline:
bakedSnapshot.balanceTimeline.length || !Number.isFinite(timelineStart) || !Number.isFinite(timelineEnd)
? bakedSnapshot.balanceTimeline
: buildDailyBalanceTimeline(bakedSnapshot.balanceSats, txEvents, timelineStart, timelineEnd),
hourlyBalanceTimeline:
bakedSnapshot.hourlyBalanceTimeline.length ||
!Number.isFinite(intradayStart) ||
!Number.isFinite(intradayEnd)
? bakedSnapshot.hourlyBalanceTimeline
: buildIntervalBalanceTimeline(
bakedSnapshot.balanceSats,
txEvents,
intradayStart,
intradayEnd,
HOUR_MS,
startOfUtcHour,
toHourKey
),
approximate: bakedSnapshot.approximate,
detailScope: bakedSnapshot.detailScope,
};
});
if (!snapshots.length) {
return false;
}
runtime = {
...runtime,
hasLoadedOnce: true,
historyScope: bakedRuntime?.historyScope || "SUMMARY",
currentPriceUsd,
fiatExchangeRates: bakedRuntime?.fiatExchangeRates || runtime.fiatExchangeRates,
priceHistory: bakedRuntime?.priceHistory || runtime.priceHistory,
intradayPriceHistory: bakedRuntime?.intradayPriceHistory || runtime.intradayPriceHistory,
historyAvailable: bakedRuntime?.historyAvailable ?? runtime.historyAvailable,
historyMissingDays: bakedRuntime?.historyMissingDays ?? runtime.historyMissingDays,
addressSnapshots: snapshots,
partialFailures: [],
approximationMode:
Boolean(bakedRuntime?.approximationMode) || snapshots.some((snapshot) => snapshot.approximate),
timelineStart,
timelineEnd,
intradayStart,
intradayEnd,
banner: null,
};
StorageLayer.saveRuntimeCache(runtime);
return true;
}
function normalizeBitcoinFactsPayload(payload) {
const source = Array.isArray(payload) ? payload : payload?.facts;
if (!Array.isArray(source)) {
return [];
}
return uniqueStrings(
source.filter((entry) => typeof entry === "string" && entry.trim()).map((entry) => entry.trim())
);
}
function ensureCurrentBitcoinFactIndex() {
if (!bitcoinFacts.length) {
runtime.currentFactIndex = null;
return;
}
if (
Number.isInteger(runtime.currentFactIndex) &&
runtime.currentFactIndex >= 0 &&
runtime.currentFactIndex < bitcoinFacts.length
) {
return;
}
runtime.currentFactIndex = getRandomBitcoinFactIndex();
}
function getRandomBitcoinFactIndex(excludedIndex = null) {
if (!bitcoinFacts.length) {
return null;
}
if (bitcoinFacts.length === 1) {
return 0;
}
let nextIndex = Math.floor(Math.random() * bitcoinFacts.length);
while (nextIndex === excludedIndex) {
nextIndex = Math.floor(Math.random() * bitcoinFacts.length);
}
return nextIndex;
}
function showNextBitcoinFact() {
if (!bitcoinFacts.length) {
return;
}
runtime.currentFactIndex = getRandomBitcoinFactIndex(runtime.currentFactIndex);
renderBitcoinFactsWidget(getActiveAddress());
}
function createDefaultSettings() {
return { ...DEFAULT_SETTINGS };
}
function createDefaultFiatExchangeRates() {
return new Map([["USD", 1]]);
}
function cacheDom() {
Object.values(DOM_ID_GROUPS)
.flat()
.forEach((id) => {
dom[id] = document.getElementById(id);
});
}
// ---------------------------------------------------------------------------
// Events and actions
// ---------------------------------------------------------------------------
function bindEvents() {
window.addEventListener("hashchange", () => {
applyRouteFromHash({ replaceInvalid: true, renderAfter: true, preloadDetail: true });
});
window.addEventListener("resize", scheduleChartResizeRender);
dom.brandHomeButton.addEventListener("click", openOverview);
dom.vaultHomeButton.addEventListener("click", openOverview);
dom.appBannerDismiss.addEventListener("click", dismissBanner);
dom.refreshButton.addEventListener("click", () => {
refreshCurrentScope({ reason: "manual", allowSkeleton: !runtime.hasLoadedOnce }).catch((error) => {
setBanner("error", `Refresh failed. ${error.message || "Try again later."}`);
render();
});
});
dom.toggleBalancesButton.addEventListener("click", () => {
state.hideBalances = !state.hideBalances;
StorageLayer.saveState(state);
syncBalanceToggle();
render();
});
dom.unitDisplayButton.addEventListener("click", () => {
state.settings.displayUnit = getDisplayUnit() === "BTC" ? "USD" : "BTC";
StorageLayer.saveState(state);
render();
});
dom.overviewFaqButton.addEventListener("click", (event) => {
event.preventDefault();
openFaq();
});
dom.settingsButton.addEventListener("click", openSettingsModal);
dom.faqButton.addEventListener("click", () => {
if (isFaqView()) {
openOverview();
return;
}
openFaq();
});
dom.settingsClearStorageButton.addEventListener("click", clearVault);
dom.addressCrumb.addEventListener("click", copyActiveAddressToClipboard);
dom.addressCrumb.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
copyActiveAddressToClipboard();
}
});
dom.walletGrid.addEventListener("click", (event) => {
const actionTarget = event.target.closest("[data-action]");
if (!actionTarget) {
return;
}
const action = actionTarget.dataset.action;
if (action === "open-wallet") {
openWallet(actionTarget.dataset.walletId);
}
if (action === "create-wallet") {
createWallet();
}
});
dom.walletTitleButton.addEventListener("click", (event) => {
if (runtime.editingWalletId) {
return;
}
const activeWallet = getActiveWallet();
if (!activeWallet) {
return;
}
if (getActiveAddress()) {
openWallet(activeWallet.id);
return;
}
enterWalletRename();
});
dom.walletDeleteButton.addEventListener("click", () => {
const activeWallet = getActiveWallet();
if (activeWallet) {
removeWallet(activeWallet.id);
}
});
dom.walletTitleButton.addEventListener("keydown", (event) => {
if (runtime.editingWalletId) {
return;
}
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
if (getActiveAddress()) {
const activeWallet = getActiveWallet();
if (activeWallet) {
openWallet(activeWallet.id);
}
return;
}
enterWalletRename();
}
});
dom.walletTitleText.addEventListener("input", () => {
if (!runtime.editingWalletId) {
return;
}
const normalized = normalizeWalletName(dom.walletTitleText.textContent || "");
runtime.walletNameDraft = normalized;
if (dom.walletTitleText.textContent !== normalized) {
dom.walletTitleText.textContent = normalized;
placeCaretAtEnd(dom.walletTitleText);
}
});
dom.walletTitleText.addEventListener("keydown", (event) => {
if (!runtime.editingWalletId) {
return;
}
if (isEnterKeyEvent(event)) {
event.preventDefault();
commitWalletRename();
return;
}
if (event.key === "Escape") {
event.preventDefault();
cancelWalletRename();
}
});
dom.walletTitleText.addEventListener("beforeinput", (event) => {
if (!runtime.editingWalletId) {
return;
}
if (event.inputType === "insertParagraph" || event.inputType === "insertLineBreak") {
event.preventDefault();
commitWalletRename();
}
});
dom.walletTitleText.addEventListener("mouseup", () => {
if (runtime.editingWalletId) {
placeCaretAtEnd(dom.walletTitleText);
}
});
dom.walletTitleText.addEventListener("blur", () => {
if (runtime.editingWalletId) {
commitWalletRename({ quiet: true });
}
});
dom.walletTransactionsToggle.addEventListener("click", () => {
const detailKey = getActiveDetailKey();
if (!detailKey) {
return;
}
runtime.transactionVisibleCountByDetailId[detailKey] =
getVisibleTransactionCount(detailKey) + TRANSACTION_PAGE_SIZE;
render();
});
dom.walletTransactions.addEventListener("click", (event) => {
const openButton = event.target.closest("[data-action='open-transaction']");
if (!openButton) {
return;
}
const activeDetailKey = getActiveDetailKey();
if (!activeDetailKey || !openButton.dataset.txid) {
return;
}
openTransactionDetail(activeDetailKey, openButton.dataset.txid);
});
dom.walletAddressList.addEventListener("click", (event) => {
const removeButton = event.target.closest("[data-action='remove-address']");
if (removeButton) {
removeAddress(removeButton.dataset.addressId);
return;
}
const openButton = event.target.closest("[data-action='open-address']");
if (openButton?.dataset.addressId) {
openAddress(openButton.dataset.addressId);
}
});
dom.walletAddAddressForm.addEventListener("submit", async (event) => {
event.preventDefault();
clearAddressFeedback();
const activeWallet = getActiveWallet();
if (!activeWallet) {
return;
}
if (dom.walletAddressInput.value.length > MAX_ADDRESS_INPUT_LENGTH) {
showAddressFeedback(`Paste up to ${MAX_ADDRESS_INPUT_LENGTH} characters at once.`, "error");
return;
}
const parsedAddresses = parseAddressInput(dom.walletAddressInput.value);
if (!parsedAddresses.length) {
showAddressFeedback("Enter a Bitcoin address.", "error");
return;
}
const sensitiveInputCheck = await ValidationLayer.detectSensitiveBitcoinInput(
dom.walletAddressInput.value,
parsedAddresses
);
if (sensitiveInputCheck.detected) {
dom.walletAddAddressForm.reset();
showAddressFeedback(sensitiveInputCheck.message, "error");
render();
return;
}
if (parsedAddresses.length > MAX_PASTED_ADDRESSES) {
showAddressFeedback(`You can add up to ${MAX_PASTED_ADDRESSES} addresses at once.`, "error");
return;
}
const duplicateCheck = classifyAddressBatchDuplicates(parsedAddresses);
if (duplicateCheck.existing.length) {
showAddressFeedback(
duplicateCheck.existing.length === 1
? "That address is already in Bitkit Watch."
: `${duplicateCheck.existing.length} addresses are already in Bitkit Watch.`,
"error"
);
return;
}
if (duplicateCheck.duplicates.length) {
showAddressFeedback(
duplicateCheck.duplicates.length === 1
? "Remove the duplicate address from your pasted list."
: "Remove duplicate addresses from your pasted list.",
"error"
);
return;
}
const addressesToAdd = duplicateCheck.unique;
if (state.addresses.length + addressesToAdd.length > MAX_WATCHED_ADDRESSES) {
showAddressFeedback(`Bitkit Watch supports up to ${MAX_WATCHED_ADDRESSES} addresses.`, "error");
return;
}
showAddressFeedback(
addressesToAdd.length === 1
? "Validating address…"
: `Validating ${addressesToAdd.length} addresses…`,
"success"
);
const validationResults = await Promise.all(
addressesToAdd.map(async (address) => ({
address,
isValid: await ValidationLayer.isValidMainnetBitcoinAddress(address),
}))
);
const invalidAddresses = validationResults.filter((result) => !result.isValid).map((result) => result.address);
if (invalidAddresses.length) {
showAddressFeedback(
invalidAddresses.length === 1
? "Enter a valid Bitcoin mainnet address."
: `${invalidAddresses.length} pasted entries are not valid Bitcoin mainnet addresses.`,
"error"
);
return;
}
const createdAt = new Date().toISOString();
const newEntries = addressesToAdd.map((address) => ({
id: createId("addr"),
address,
tags: [],
groupId: activeWallet.id,
createdAt,
}));
state.addresses.push(...newEntries);
StorageLayer.saveState(state);
dom.walletAddAddressForm.reset();
showAddressFeedback(
newEntries.length === 1
? "Address added. Loading current balance…"
: `${newEntries.length} addresses added. Loading current balances…`,
"success"
);
render();
try {
if (newEntries.length === 1) {
await hydrateAddressAfterAdd(newEntries[0]);
} else {
await hydrateAddressesAfterAdd(newEntries);
}
showAddressFeedback(
newEntries.length === 1
? "Address added to the wallet."
: `${newEntries.length} addresses added to the wallet.`,
"success"
);
} catch (error) {
showAddressFeedback(
`${newEntries.length === 1 ? "Address" : "Addresses"} saved locally, but loading failed. ${
error.message || "Try again later."
}`,
"error"
);
}
});
dom.addressTagForm.addEventListener("submit", (event) => {
event.preventDefault();
addAddressTag();
});
dom.addressTagInput.addEventListener("input", () => {
clearAddressTagFeedback();
});
dom.addressTagList.addEventListener("click", (event) => {
const removeButton = event.target.closest("[data-action='remove-tag']");
if (!removeButton?.dataset.tag) {
return;
}
removeAddressTag(removeButton.dataset.tag);
});
const onChartRangeClick = (event) => {
const button = event.target.closest("[data-range]");
if (!button) {
return;
}
const nextRange = normalizeChartRange(button.dataset.range);
const activeWallet = getActiveWallet();
const activeAddress = getActiveAddress();
const detailView = activeAddress
? getAddressView(activeAddress.id)
: activeWallet
? getWalletView(activeWallet.id)
: null;
if (button.hidden || !getAvailableChartRanges(detailView).has(nextRange)) {
return;
}
if (nextRange === state.selectedRange) {
return;
}
state.selectedRange = nextRange;
StorageLayer.saveState(state);
render();
preloadActiveDetailDataIfNeeded();
};
dom.walletChartTabs.addEventListener("click", onChartRangeClick);
dom.chartModalTabs.addEventListener("click", onChartRangeClick);
dom.walletChartStage.addEventListener("click", openChartModal);
dom.walletChartStage.addEventListener("keydown", (event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
openChartModal();
}
});
dom.chartModalBackdrop.addEventListener("click", closeChartModal);
dom.chartModalClose.addEventListener("click", closeChartModal);
dom.walletFactsButton.addEventListener("click", showNextBitcoinFact);
dom.settingsModalBackdrop.addEventListener("click", closeSettingsModal);
dom.settingsModalClose.addEventListener("click", closeSettingsModal);
dom.settingsFooterCloseButton.addEventListener("click", closeSettingsModal);
dom.settingsHideDustButton.addEventListener("click", () => {
state.settings.hideDust = !state.settings.hideDust;
StorageLayer.saveState(state);
render();
});
dom.settingsBackgroundGraphicsButton.addEventListener("click", () => {
state.settings.showBackgroundGraphics = !state.settings.showBackgroundGraphics;
StorageLayer.saveState(state);
render();
});
[dom.settingsNotationModern, dom.settingsNotationClassic].forEach((input) => {
input.addEventListener("change", () => {
if (!input.checked || !input.dataset.notation) {
return;
}
const nextNotation = normalizeBitcoinNotation(input.dataset.notation);
if (state.settings.bitcoinNotation === nextNotation) {
return;
}
state.settings.bitcoinNotation = nextNotation;
StorageLayer.saveState(state);
render();
});
});
[
dom.settingsFiatUsd,
dom.settingsFiatEur,
dom.settingsFiatJpy,
dom.settingsFiatGbp,
dom.settingsFiatCny,
].forEach((input) => {
input.addEventListener("change", () => {
if (!input.checked || !input.dataset.fiat) {
return;
}
const nextFiat = normalizeFiatCurrency(input.dataset.fiat);
if (state.settings.fiatCurrency === nextFiat) {
return;
}