-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.ts
More file actions
1186 lines (1010 loc) · 43.3 KB
/
index.ts
File metadata and controls
1186 lines (1010 loc) · 43.3 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
import * as lwk from "lwk_wasm"
import {
setWollet, getWollet,
setCurrencyCode, getCurrencyCode,
setPricesFetcher, getPricesFetcher,
setEsploraClient, getEsploraClient,
setBoltzSession, getBoltzSession,
setInvoiceResponse,
setExchangeRate, getExchangeRate,
setWasmReady, isWasmReady,
subscribe
} from './state'
// Constants
const SATOSHIS_PER_BTC: number = 100_000_000;
const RATE_UPDATE_INTERVAL_MS: number = 60_000; // 1 minute
const LOCALSTORAGE_FORM_KEY: string = 'btcpos_setup_form';
// =============================================================================
// Plausible Analytics
// =============================================================================
// Declare plausible function type (loaded from external script)
declare function plausible(eventName: string, options?: { props?: Record<string, string | number> }): void;
function trackEvent(eventName: string, props?: Record<string, string | number>): void {
if (typeof plausible === 'function') {
plausible(eventName, props ? { props } : undefined);
}
}
// Convert satoshi amount to privacy-preserving bucket label
function satoshiBucket(satoshis: number): string {
if (satoshis < 1_000) return '0-1k'; // ~$0-$1 (micro)
if (satoshis < 10_000) return '1k-10k'; // ~$1-$10 (small)
if (satoshis < 100_000) return '10k-100k'; // ~$10-$100 (medium)
if (satoshis < 1_000_000) return '100k-1M'; // ~$100-$1k (large)
return '1M+'; // ~$1k+ (very large)
}
// Network configuration (hardcoded to mainnet)
const network: lwk.Network = lwk.Network.mainnet();
// Esplora/Waterfalls configuration
const MAINNET_WATERFALLS_URL = "https://waterfalls.liquidwebwallet.org/liquid/api";
const TESTNET_WATERFALLS_URL = "https://waterfalls.liquidwebwallet.org/liquidtestnet/api";
const WATERFALLS_RECIPIENT_KEY = "age1xxzrgrfjm3yrwh3u6a7exgrldked0pdauvr3mx870wl6xzrwm5ps8s2h0p";
// Reference to main app container
const app: HTMLElement = document.getElementById('app')!;
// Rate update interval handle
let rateUpdateInterval: number | null = null;
// =============================================================================
// URL-safe Base64 Encoding/Decoding
// =============================================================================
function base64UrlEncode(str: string): string {
const base64 = btoa(str);
return base64
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
}
function base64UrlDecode(str: string): string {
// Add padding back
let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) {
base64 += '=';
}
return atob(base64);
}
// =============================================================================
// Configuration Encoding/Decoding
// =============================================================================
interface POSConfig {
d: string; // descriptor
c: string; // currency code (alpha3)
g?: boolean; // show gear (optional, defaults to false)
n?: boolean; // show note/description (optional, defaults to true)
}
function encodeConfig(descriptor: string, currency: string, showGear: boolean, showDescription: boolean): string {
const config: POSConfig = { d: descriptor, c: currency };
// Only include 'g' if true to keep URL shorter when false (default)
if (showGear) {
config.g = true;
}
// Only include 'n' if false to keep URL shorter when true (default)
if (!showDescription) {
config.n = false;
}
return base64UrlEncode(JSON.stringify(config));
}
function decodeConfig(encoded: string): POSConfig | null {
try {
const json = base64UrlDecode(encoded);
const config = JSON.parse(json) as POSConfig;
if (typeof config.d !== 'string' || typeof config.c !== 'string') {
return null;
}
// Default showGear to false if not present
if (typeof config.g !== 'boolean') {
config.g = false;
}
// Default showDescription to true if not present
if (typeof config.n !== 'boolean') {
config.n = true;
}
return config;
} catch {
return null;
}
}
// =============================================================================
// LocalStorage helpers
// =============================================================================
function saveFormToLocalStorage(descriptor: string, currency: string, showGear: boolean, showDescription: boolean): void {
try {
localStorage.setItem(LOCALSTORAGE_FORM_KEY, JSON.stringify({ descriptor, currency, showGear, showDescription }));
} catch {
// Ignore storage errors
}
}
function loadFormFromLocalStorage(): { descriptor: string; currency: string; showGear: boolean; showDescription: boolean } | null {
try {
const data = localStorage.getItem(LOCALSTORAGE_FORM_KEY);
if (data) {
const parsed = JSON.parse(data);
// Handle old format without showGear
if (typeof parsed.showGear !== 'boolean') {
parsed.showGear = false;
}
// Handle old format without showDescription
if (typeof parsed.showDescription !== 'boolean') {
parsed.showDescription = true;
}
return parsed;
}
} catch {
// Ignore storage errors
}
return null;
}
// =============================================================================
// Template Rendering
// =============================================================================
function renderTemplate(templateId: string): void {
const template = document.getElementById(templateId) as HTMLTemplateElement;
if (!template) {
console.error(`Template ${templateId} not found`);
return;
}
app.innerHTML = '';
app.appendChild(template.content.cloneNode(true));
}
// =============================================================================
// Exchange Rate Fetching
// =============================================================================
async function fetchExchangeRate(): Promise<number | null> {
const currencyCode = getCurrencyCode();
const pricesFetcher = getPricesFetcher();
if (!currencyCode || !pricesFetcher) {
return null;
}
try {
const rates = await pricesFetcher.rates(currencyCode);
const median = rates.median();
return median;
} catch (e) {
console.error('Failed to fetch exchange rate:', e);
return null;
}
}
async function refreshExchangeRate(): Promise<void> {
const median = await fetchExchangeRate();
setExchangeRate(median);
}
function startRateUpdates(immediate: boolean = true): void {
// Fetch immediately (optional)
if (immediate) {
void refreshExchangeRate();
}
// Then fetch every minute
if (rateUpdateInterval) {
clearInterval(rateUpdateInterval);
}
rateUpdateInterval = window.setInterval(() => {
void refreshExchangeRate();
}, RATE_UPDATE_INTERVAL_MS);
}
function stopRateUpdates(): void {
if (rateUpdateInterval) {
clearInterval(rateUpdateInterval);
rateUpdateInterval = null;
}
}
// =============================================================================
// Fiat to Satoshi Conversion
// =============================================================================
function fiatToSatoshis(fiatAmount: number): number {
const rate = getExchangeRate();
if (!rate || rate <= 0) {
return 0;
}
const btcAmount = fiatAmount / rate;
return Math.round(btcAmount * SATOSHIS_PER_BTC);
}
// =============================================================================
// Esplora Client with Waterfalls
// =============================================================================
async function createEsploraClient(): Promise<lwk.EsploraClient> {
const url = network.isMainnet() ? MAINNET_WATERFALLS_URL : TESTNET_WATERFALLS_URL;
const waterfalls = true;
const concurrency = 4;
const utxoOnly = true;
const client = new lwk.EsploraClient(network, url, waterfalls, concurrency, utxoOnly);
// Set the waterfalls server recipient key for encryption
if (waterfalls && (network.isMainnet() || network.isTestnet())) {
await client.setWaterfallsServerRecipient(WATERFALLS_RECIPIENT_KEY);
}
return client;
}
// =============================================================================
// Mnemonic Export (for Boltz recovery)
// =============================================================================
/**
* Downloads the Boltz session mnemonic as a JSON file for swap recovery.
* The file format is compatible with boltz.exchange recovery tool.
* @param dwid - The wallet's DWID to look up the mnemonic
*/
function downloadMnemonicJson(dwid: string): void {
const mnemonicKey = `btcpos-mnemonic-${dwid}`;
const mnemonic = localStorage.getItem(mnemonicKey);
if (!mnemonic) {
console.warn('No mnemonic found for this wallet');
alert('No recovery data available for this wallet.');
return;
}
// Create JSON in Boltz-compatible format
const recoveryData = JSON.stringify({ mnemonic }, null, 0);
// Create and trigger download
const blob = new Blob([recoveryData], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `btcpos-recovery-${dwid}.json`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
console.log('Mnemonic JSON downloaded for recovery');
}
/**
* Sets up a triple-click handler on an element to trigger mnemonic export.
* @param element - The element to attach the handler to
* @param getDwid - Function to get the current DWID
*/
function setupMnemonicExportTrigger(element: HTMLElement, getDwid: () => string | null): void {
let clickCount = 0;
let clickTimer: number | null = null;
const TRIPLE_CLICK_TIMEOUT = 500; // ms
element.addEventListener('click', () => {
clickCount++;
if (clickTimer) {
clearTimeout(clickTimer);
}
if (clickCount === 3) {
clickCount = 0;
const dwid = getDwid();
if (dwid) {
downloadMnemonicJson(dwid);
}
} else {
clickTimer = window.setTimeout(() => {
clickCount = 0;
}, TRIPLE_CLICK_TIMEOUT);
}
});
}
// =============================================================================
// Boltz Session
// =============================================================================
async function createBoltzSession(wollet: lwk.Wollet, esploraClient: lwk.EsploraClient): Promise<lwk.BoltzSession> {
const dwid = wollet.dwid();
const mnemonicKey = `btcpos-mnemonic-${dwid}`;
// Check if mnemonic exists in localStorage
let mnemonic: lwk.Mnemonic;
const storedMnemonic = localStorage.getItem(mnemonicKey);
if (storedMnemonic) {
// Load existing mnemonic
mnemonic = new lwk.Mnemonic(storedMnemonic);
console.log(`Found Boltz mnemonic in localStorage at key ${mnemonicKey}`);
} else {
// Create new random mnemonic and save it
console.log(`No mnemonic found in localStorage at key ${mnemonicKey}, creating new random mnemonic`);
mnemonic = lwk.Mnemonic.fromRandom(12);
localStorage.setItem(mnemonicKey, mnemonic.toString());
}
let boltzSessionBuilder = new lwk.BoltzSessionBuilder(network, esploraClient);
boltzSessionBuilder = boltzSessionBuilder.mnemonic(mnemonic);
boltzSessionBuilder = boltzSessionBuilder.referralId("btcpos");
const session = await boltzSessionBuilder.build();
return session;
}
// =============================================================================
// Setup Page
// =============================================================================
function initSetupPage(): void {
renderTemplate('setup-page-template');
const form = document.getElementById('setup-form') as HTMLFormElement;
const descriptorInput = document.getElementById('descriptor') as HTMLTextAreaElement;
const currencySelect = document.getElementById('currency') as HTMLSelectElement;
const showGearCheckbox = document.getElementById('show-gear') as HTMLInputElement;
const showDescriptionCheckbox = document.getElementById('show-description') as HTMLInputElement;
const generateButton = document.getElementById('generate-link') as HTMLButtonElement;
const messageDiv = document.getElementById('setup-message') as HTMLDivElement;
const wasmStatus = document.getElementById('wasm-status') as HTMLDivElement;
const generatedSection = document.getElementById('generated-link-section') as HTMLDivElement;
const generatedLinkInput = document.getElementById('generated-link') as HTMLInputElement;
const copyButton = document.getElementById('copy-link') as HTMLButtonElement;
const qrImage = document.getElementById('qr-image') as HTMLImageElement;
const qrLink = document.getElementById('qr-link') as HTMLAnchorElement;
const openPosLink = document.getElementById('open-pos-link') as HTMLAnchorElement;
// Load saved form data
const savedForm = loadFormFromLocalStorage();
if (savedForm) {
descriptorInput.value = savedForm.descriptor;
currencySelect.value = savedForm.currency;
showGearCheckbox.checked = savedForm.showGear;
showDescriptionCheckbox.checked = savedForm.showDescription;
}
// Update WASM status
function updateWasmStatus(ready: boolean): void {
const indicator = wasmStatus.querySelector('.status-indicator') as HTMLElement;
const text = wasmStatus.querySelector('.status-text') as HTMLElement;
if (ready) {
indicator.classList.remove('loading');
indicator.classList.add('ready');
text.textContent = 'WASM loaded';
generateButton.disabled = false;
} else {
indicator.classList.add('loading');
indicator.classList.remove('ready');
text.textContent = 'Loading WASM module...';
generateButton.disabled = true;
}
}
// Subscribe to WASM ready state
subscribe('wasm-ready', updateWasmStatus);
updateWasmStatus(isWasmReady());
// Show message
function showMessage(text: string, isError: boolean): void {
messageDiv.textContent = text;
messageDiv.className = 'message ' + (isError ? 'error' : 'success');
}
function clearMessage(): void {
messageDiv.className = 'message';
messageDiv.textContent = '';
}
// Form submission
form.addEventListener('submit', async (e: Event) => {
e.preventDefault();
clearMessage();
const descriptor = descriptorInput.value.trim();
const currency = currencySelect.value;
const showGear = showGearCheckbox.checked;
const showDescription = showDescriptionCheckbox.checked;
if (!descriptor) {
showMessage('Please enter a CT descriptor', true);
return;
}
// Validate descriptor using LWK
try {
generateButton.disabled = true;
generateButton.textContent = 'Validating...';
// This will throw if the descriptor is invalid
const wolletDescriptor = new lwk.WolletDescriptor(descriptor);
const descriptorReEncoded = wolletDescriptor.toString(); // Re-encode desctiptor because aqua/green can give non-multipath longer version
// Check if descriptor matches network
const isMainnet = wolletDescriptor.isMainnet();
const networkIsMainnet = network.isMainnet();
if (isMainnet !== networkIsMainnet) {
showMessage(
`Descriptor is for ${isMainnet ? 'mainnet' : 'testnet'}, but POS is configured for ${networkIsMainnet ? 'mainnet' : 'testnet'}`,
true
);
generateButton.disabled = false;
generateButton.textContent = 'Generate POS Link';
return;
}
// Save form data
saveFormToLocalStorage(descriptorReEncoded, currency, showGear, showDescription);
// Generate the link
const encoded = encodeConfig(descriptorReEncoded, currency, showGear, showDescription);
const baseUrl = window.location.origin + window.location.pathname;
const posLink = `${baseUrl}#${encoded}`;
// Show the generated link
generatedLinkInput.value = posLink;
openPosLink.href = posLink;
// Generate QR code
const qrUri = lwk.stringToQr(posLink);
qrImage.src = qrUri;
qrLink.href = posLink;
generatedSection.hidden = false;
// Track successful POS link generation
trackEvent('Generate POS Link', { currency: currency });
showMessage('POS link generated successfully!', false);
} catch (e) {
showMessage(`Invalid descriptor: ${e}`, true);
} finally {
generateButton.disabled = false;
generateButton.textContent = 'Generate POS Link';
}
});
// Copy link button
copyButton.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(generatedLinkInput.value);
copyButton.textContent = '✓';
setTimeout(() => {
copyButton.textContent = '📋';
}, 2000);
} catch {
// Fallback: select the input
generatedLinkInput.select();
document.execCommand('copy');
}
});
// Open POS link tracking
openPosLink.addEventListener('click', () => {
trackEvent('Open POS');
});
}
// =============================================================================
// POS Page
// =============================================================================
function initPosPage(config: POSConfig): void {
renderTemplate('pos-page-template');
// Save config for returning from receive page
currentPosConfig = config;
// POS state
let currentAmount: string = '0';
let inputMode: 'fiat' | 'sats' = 'fiat';
const currencyAlpha3 = config.c;
// Get DOM elements
const amountDisplay = document.getElementById('amount') as HTMLSpanElement;
const satoshiDisplay = document.getElementById('satoshi-amount') as HTMLSpanElement;
const currencyCodeDisplay = document.getElementById('currency-code') as HTMLSpanElement;
const rateCurrencyDisplay = document.getElementById('rate-currency') as HTMLSpanElement;
const descriptionInput = document.getElementById('description') as HTMLInputElement;
const submitButton = document.getElementById('submit') as HTMLButtonElement;
const walletIdDisplay = document.getElementById('wallet-id') as HTMLSpanElement;
const setupLink = document.getElementById('setup-link') as HTMLAnchorElement;
const wasmStatus = document.getElementById('wasm-status') as HTMLDivElement;
const modeFiatButton = document.getElementById('mode-fiat') as HTMLButtonElement;
const modeSatsButton = document.getElementById('mode-sats') as HTMLButtonElement;
const primaryDisplay = document.getElementById('primary-display') as HTMLDivElement;
const secondaryDisplay = document.getElementById('secondary-display') as HTMLDivElement;
// Show/hide setup gear based on config
if (!config.g) {
setupLink.style.display = 'none';
}
// Show/hide description field based on config
const descriptionSection = descriptionInput.parentElement as HTMLDivElement;
if (!config.n) {
descriptionSection.style.display = 'none';
}
// Set fixed currency
currencyCodeDisplay.textContent = currencyAlpha3;
rateCurrencyDisplay.textContent = currencyAlpha3;
// Setup link to go back
setupLink.addEventListener('click', (e: Event) => {
e.preventDefault();
stopRateUpdates();
history.pushState(null, '', window.location.pathname);
initSetupPage();
});
// Convert satoshis to fiat
function satoshisToFiat(satoshis: number): number {
const rate = getExchangeRate();
if (!rate || rate <= 0) {
return 0;
}
const btcAmount = satoshis / SATOSHIS_PER_BTC;
return btcAmount * rate;
}
// Update display styling based on mode
function updateDisplayStyles(): void {
if (inputMode === 'fiat') {
primaryDisplay.classList.remove('secondary-mode');
primaryDisplay.classList.add('primary-mode');
secondaryDisplay.classList.remove('primary-mode');
secondaryDisplay.classList.add('secondary-mode');
modeFiatButton.classList.add('active');
modeSatsButton.classList.remove('active');
} else {
primaryDisplay.classList.add('secondary-mode');
primaryDisplay.classList.remove('primary-mode');
secondaryDisplay.classList.add('primary-mode');
secondaryDisplay.classList.remove('secondary-mode');
modeFiatButton.classList.remove('active');
modeSatsButton.classList.add('active');
}
}
// Format display
function formatDisplay(): void {
if (currentAmount === '' || currentAmount === '0') {
amountDisplay.textContent = '0.00';
satoshiDisplay.textContent = '0';
return;
}
// Remove leading zeros except if it's just "0" or "0."
if (currentAmount.startsWith('0') && currentAmount.length > 1 && currentAmount[1] !== '.') {
currentAmount = currentAmount.replace(/^0+/, '');
}
const amount = parseFloat(currentAmount);
if (inputMode === 'fiat') {
// Input is fiat, calculate sats
amountDisplay.textContent = currentAmount;
if (!isNaN(amount) && amount > 0) {
const satoshis = fiatToSatoshis(amount);
satoshiDisplay.textContent = satoshis.toLocaleString('en-US');
} else {
satoshiDisplay.textContent = '0';
}
} else {
// Input is sats, calculate fiat
satoshiDisplay.textContent = currentAmount.includes('.')
? currentAmount.split('.')[0]
: currentAmount;
if (!isNaN(amount) && amount > 0) {
const satoshis = Math.floor(amount); // Sats are whole numbers
const fiat = satoshisToFiat(satoshis);
amountDisplay.textContent = fiat.toFixed(2);
} else {
amountDisplay.textContent = '0.00';
}
}
}
// Handle input
function handleInput(value: string): void {
// In sats mode, don't allow decimal points (sats are integers)
if (inputMode === 'sats' && value === '.') {
return;
}
// Prevent multiple decimal points
if (value === '.' && currentAmount.includes('.')) {
return;
}
// Limit decimal places based on mode
if (currentAmount.includes('.')) {
const decimalPart = currentAmount.split('.')[1];
const maxDecimals = inputMode === 'fiat' ? 2 : 0;
if (decimalPart && decimalPart.length >= maxDecimals && value !== '.') {
return;
}
}
// Limit total length
if (currentAmount.length >= 12) {
return;
}
if (currentAmount === '0' && value !== '.') {
currentAmount = value;
} else {
currentAmount += value;
}
formatDisplay();
}
// Handle backspace
function handleBackspace(): void {
if (currentAmount.length <= 1) {
currentAmount = '0';
} else {
currentAmount = currentAmount.slice(0, -1);
}
formatDisplay();
}
// Handle clear
function handleClear(): void {
currentAmount = '0';
formatDisplay();
}
// Get final satoshi amount based on current mode
function getFinalSatoshis(): number {
const amount = parseFloat(currentAmount);
if (isNaN(amount) || amount <= 0) {
return 0;
}
if (inputMode === 'fiat') {
return fiatToSatoshis(amount);
} else {
return Math.floor(amount);
}
}
// Get final fiat amount based on current mode
function getFinalFiat(): number {
const amount = parseFloat(currentAmount);
if (isNaN(amount) || amount <= 0) {
return 0;
}
if (inputMode === 'fiat') {
return amount;
} else {
return satoshisToFiat(Math.floor(amount));
}
}
// Handle submit
async function handleSubmit() {
const satoshis = getFinalSatoshis();
const fiatAmount = getFinalFiat();
const description = descriptionInput.value.trim();
if (satoshis <= 0) {
alert('Please enter a valid amount greater than 0');
return;
}
// Show loading state on button
submitButton.disabled = true;
const originalText = submitButton.textContent;
submitButton.innerHTML = '<span class="button-loading"><span class="spinner"></span>Creating...</span>';
try {
// Invoice data (will be used for Boltz integration later)
const invoiceData = {
fiatAmount: fiatAmount,
currency: currencyAlpha3,
satoshis: satoshis,
description: description || null,
timestamp: new Date().toISOString()
};
console.log('Invoice data:', invoiceData);
const claimAddress = await getClaimAddress();
console.log('Claim address:', claimAddress.toString());
let invoice: lwk.InvoiceResponse;
try {
invoice = await getBoltzSession().invoice(BigInt(satoshis), description, claimAddress);
} catch (invoiceError) {
// Handle preimage hash collision (e.g., two PoS instances open simultaneously)
const errorMessage = String(invoiceError);
if (errorMessage.includes('preimage hash exists already')) {
console.log('Preimage hash collision detected, recreating Boltz session...');
const wollet = getWollet();
const esploraClient = getEsploraClient();
if (!wollet || !esploraClient) {
throw new Error('Wallet or Esplora client not initialized');
}
const newSession = await createBoltzSession(wollet, esploraClient);
setBoltzSession(newSession);
console.log('Boltz session recreated, retrying invoice creation...');
invoice = await newSession.invoice(BigInt(satoshis), description, claimAddress);
} else {
throw invoiceError;
}
}
console.log('Invoice:', invoice.bolt11Invoice().toString());
setInvoiceResponse(invoice);
// Track invoice creation (using bucket for privacy)
trackEvent('Create Invoice', { amount: satoshiBucket(satoshis), currency: currencyAlpha3 });
// Navigate to receive page
initReceivePage(invoice, satoshis, fiatAmount, currencyAlpha3);
// Reset amount for next payment
currentAmount = '0';
} catch (e) {
console.error('Failed to create invoice:', e);
alert(`Failed to create invoice: ${e}`);
// Restore button state
submitButton.disabled = false;
submitButton.textContent = originalText;
}
}
// Remove trailing zeros from a number string (e.g., "123.40" -> "123.4", "123.00" -> "123")
function removeTrailingZeros(numStr: string): string {
if (!numStr.includes('.')) return numStr;
// Remove trailing zeros after decimal point
let result = numStr.replace(/\.?0+$/, '');
// If we removed everything after decimal, result might be empty or just the integer
return result || '0';
}
// Mode toggle handlers
modeFiatButton.addEventListener('click', () => {
if (inputMode !== 'fiat') {
// Convert current sats to fiat
const satoshis = getFinalSatoshis();
inputMode = 'fiat';
if (satoshis > 0) {
const fiat = satoshisToFiat(satoshis);
// Remove trailing zeros so user can continue typing
currentAmount = removeTrailingZeros(fiat.toFixed(2));
} else {
currentAmount = '0';
}
updateDisplayStyles();
formatDisplay();
}
});
modeSatsButton.addEventListener('click', () => {
if (inputMode !== 'sats') {
// Convert current fiat to sats
const satoshis = getFinalSatoshis();
inputMode = 'sats';
currentAmount = satoshis > 0 ? satoshis.toString() : '0';
updateDisplayStyles();
formatDisplay();
}
});
// Keypad event listeners
document.querySelectorAll('.key[data-value]').forEach((button: Element) => {
button.addEventListener('click', () => {
handleInput((button as HTMLButtonElement).dataset.value!);
});
});
document.getElementById('backspace')!.addEventListener('click', handleBackspace);
document.getElementById('clear')!.addEventListener('click', handleClear);
submitButton.addEventListener('click', handleSubmit);
// Keyboard input
document.addEventListener('keydown', (e: KeyboardEvent) => {
if (e.target === descriptionInput) {
return;
}
if (e.key >= '0' && e.key <= '9') {
handleInput(e.key);
} else if (e.key === '.') {
handleInput('.');
} else if (e.key === 'Backspace') {
e.preventDefault();
handleBackspace();
} else if (e.key === 'Escape') {
handleClear();
} else if (e.key === 'Enter') {
handleSubmit();
}
});
// Update status text helper
function updateStatusText(text: string): void {
const statusText = wasmStatus.querySelector('.status-text') as HTMLElement;
if (statusText) {
statusText.textContent = text;
}
}
// Initialize async parts (wallet, esplora client, boltz session, exchange rate)
async function initWalletAsync(): Promise<void> {
try {
// Check if we already have a valid session in state
let esploraClient = getEsploraClient();
let wollet = getWollet();
let boltzSession = getBoltzSession();
// If all components exist and wallet descriptor matches, reuse them
if (esploraClient && wollet && boltzSession) {
const existingDwid = wollet.dwid();
const newDescriptor = new lwk.WolletDescriptor(config.d);
const newWollet = new lwk.Wollet(network, newDescriptor);
const newDwid = newWollet.dwid();
if (existingDwid === newDwid) {
console.log('Reusing existing wallet and Boltz session');
walletIdDisplay.textContent = existingDwid;
// Start rate updates (in case they were stopped)
startRateUpdates();
// Hide loading status
wasmStatus.classList.add('hidden');
return;
}
// Different descriptor, need to reinitialize
console.log('Descriptor changed, reinitializing...');
}
updateStatusText('Creating Esplora client...');
// Create Esplora client with waterfalls
esploraClient = await createEsploraClient();
setEsploraClient(esploraClient);
console.log('Esplora client created with waterfalls');
updateStatusText('Initializing wallet...');
// Create wallet descriptor and wallet
const wolletDescriptor = new lwk.WolletDescriptor(config.d);
wollet = new lwk.Wollet(network, wolletDescriptor);
setWollet(wollet);
// Show full wallet ID at bottom
const dwid = wollet.dwid();
walletIdDisplay.textContent = dwid;
console.log(`Wallet initialized with DWID: ${dwid}`);
// Setup triple-click on wallet ID to export mnemonic for recovery
setupMnemonicExportTrigger(walletIdDisplay, () => wollet.dwid());
// Initialize currency and price fetcher (no async dependencies)
const currencyCode = new lwk.CurrencyCode(currencyAlpha3);
setCurrencyCode(currencyCode);
const pricesFetcher = new lwk.PricesFetcher();
setPricesFetcher(pricesFetcher);
// Start Boltz session creation and rate fetching in parallel
updateStatusText('Creating Boltz session...');
await Promise.all([
// Create Boltz session for lightning swaps
createBoltzSession(wollet, esploraClient).then(session => {
setBoltzSession(session);
console.log('Boltz session created');
}),
// Fetch exchange rate in parallel (doesn't depend on Boltz)
fetchExchangeRate().then(rate => {
setExchangeRate(rate);
console.log('Initial exchange rate fetched');
})
]);
// Start periodic rate updates (first fetch already done above)
startRateUpdates(false);
// Hide loading status
wasmStatus.classList.add('hidden');
console.log('POS fully initialized');
} catch (e) {
console.error('Failed to initialize wallet:', e);
const indicator = wasmStatus.querySelector('.status-indicator') as HTMLElement;
const text = wasmStatus.querySelector('.status-text') as HTMLElement;
indicator.classList.remove('loading');
indicator.classList.add('error');
text.textContent = `Error: ${e}`;
}
}
// Subscribe to rate changes to update display and enable button
subscribe('exchange-rate-changed', (data: unknown) => {
const rate = (typeof data === 'number' && data > 0) ? data : null;
// Update rate display (if present)
const rateValue = document.getElementById('rate-value');
if (rateValue) {
rateValue.textContent = rate
? rate.toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 })
: '--';
}
formatDisplay();
// Enable submit button once we have an exchange rate
const currentRate = getExchangeRate();
if (currentRate && currentRate > 0) {
submitButton.disabled = false;
}
});
// Initialize when WASM is ready
if (isWasmReady()) {
initWalletAsync();
} else {
subscribe('wasm-ready', (ready: boolean) => {
if (ready) {
initWalletAsync();
}
});
}
// Initialize display styles and values
updateDisplayStyles();
formatDisplay();
}
// =============================================================================
// Complete Pay Background Task
// =============================================================================
/**
* Spawn a background task to complete a swap payment
* @param invoice - The InvoiceResponse from Boltz
* @param onComplete - Callback when payment completes
*/
function spawnCompletePay(invoice: lwk.InvoiceResponse, onComplete: (success: boolean) => void): void {
setTimeout(async () => {
try {
console.log("Starting completePay in background...");
const swapId = invoice.swapId();
console.log("Swap ID:", swapId);
const completed = await invoice.completePay();
console.log("completePay finished with result:", completed);
onComplete(completed);
} catch (error) {
console.error("Error in completePay:", error);
onComplete(false);
}
}, 0);
}