aboutsummaryrefslogtreecommitdiffstats
path: root/src/wallet.js
blob: 156d2f4a5fb451992c29f2a5948d57afdd1fd5e6 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
// BIP84 (native segwit, p2wpkh) HD wallet core.
//
// Derivation:  m / 84' / coin' / 0' / chain / index
//   chain 0 = receive (external) addresses
//   chain 1 = change  (internal) addresses
//
// All signing uses witnessUtxo only (script + amount). That is all segwit needs,
// which is what makes offline signing easy: we never have to fetch full previous
// transactions, only the (txid, vout, value, address) of each UTXO.

import { HDKey } from '@scure/bip32';
import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';
import { wordlist } from '@scure/bip39/wordlists/english';
import { hex, base64urlnopad, base32nopad, base58check } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { scrypt } from '@noble/hashes/scrypt';
import { randomBytes } from '@noble/hashes/utils';
import { xchacha20poly1305 } from '@noble/ciphers/chacha.js';
import { utf8ToBytes, bytesToUtf8 } from '@noble/ciphers/utils.js';
import * as btc from '@scure/btc-signer';
import { p2wpkh } from '@scure/btc-signer/payment';
import { concatBytes } from '@scure/btc-signer/utils.js';

import { Api, pool, getBackend, explorerWeb, electrumCandidates, spIndexerUrl } from './api.js';
import { ElectrumApi } from './electrum.js';
import { NostrSync, getSyncConfig, encryptGiftPayload, npubOf } from './nostr.js';
import { isSilentPaymentAddress, decodeSilentPaymentAddress, silentPaymentScripts, silentPaymentPlaceholder, deriveSilentPaymentKeys, encodeSilentPaymentAddress, silentPaymentScan, silentPaymentOutputPrivKey, silentPaymentCandidate, bloomHas } from './silentpay.js';
import { schnorr } from '@noble/curves/secp256k1';

// Resolve a same-origin '/path' WebSocket URL to an absolute ws(s):// URL against
// the page. The regtest backends are proxied through the dev server as relative
// paths (e.g. '/electrum') so the app works from a phone over the LAN/Tailscale;
// absolute URLs (real deployments, tests) pass through untouched.
function absWsUrl(u) {
  if (u && u[0] === '/' && typeof location !== 'undefined') {
    return (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + u;
  }
  return u;
}

// No look-ahead: stop scanning a chain at the first unused address. This wallet
// only ever exposes ONE unused address at a time (freshReceive = first unused;
// there is no "generate another address" button), so used addresses stay
// contiguous and there is never a gap to look past. Keeps scans tiny.
const GAP_LIMIT = 1;

// Extra pause after finding a used address, before querying the next index —
// keeps us gentle on the explorers' rate limits when a wallet has activity.
const USED_HIT_DELAY_MS = 500;

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// Silent-payment catch-up dust limit (sats): the indexer drops tweaks for txs
// whose taproot outputs are all below this, cutting the candidate math on a big
// scan. 0 = receive everything (default, so no small payment is ever missed).
const SP_DUST_LIMIT = 0;

const NETS = {
  mainnet: { net: btc.NETWORK, coin: 0 },
  testnet: { net: btc.TEST_NETWORK, coin: 1 },
  // mutinynet is a signet — same address format / version bytes / coin type as
  // testnet (`tb` HRP); only the chain + servers differ.
  mutinynet: { net: btc.TEST_NETWORK, coin: 1 },
  // Regtest shares testnet's version bytes / coin type; only the bech32 HRP
  // differs (`bcrt`). @scure/btc-signer derives addresses + validates from this.
  regtest: { net: { ...btc.TEST_NETWORK, bech32: 'bcrt' }, coin: 1 },
};

export function newMnemonic(strengthBits = 128) {
  return generateMnemonic(wordlist, strengthBits);
}

// The base localStorage cache key for a wallet identity (xpub, xprv, or
// seed-id) — mirrors Wallet#_cacheKey, so app code can target a specific
// account's cached state (e.g. to wipe it on log-out).
export function cacheKeyFor(id) {
  return 'btc-wallet-cache:' + hex.encode(sha256(new TextEncoder().encode(id))).slice(0, 32);
}

// Account-level xpub for a seed/key without constructing a Wallet — used to
// verify an entered recovery phrase matches a watch-only account before
// upgrading it to spendable.
export function accountXpubFor({ mnemonic, passphrase = '', xprv } = {}, netName = 'mainnet') {
  const { coin } = NETS[netName];
  let acct;
  if (xprv) {
    const node = HDKey.fromExtendedKey(xprv);
    acct = node.depth === 0 ? node.derive(`m/84'/${coin}'/0'`) : node;
  } else {
    acct = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase)).derive(`m/84'/${coin}'/0'`);
  }
  return acct.publicExtendedKey;
}

export function isValidMnemonic(m) {
  try {
    return validateMnemonic(m.trim().replace(/\s+/g, ' '), wordlist);
  } catch {
    return false;
  }
}

export class Wallet {
  constructor() {
    this.mnemonic = '';
    this.passphrase = '';
    this.netName = 'mainnet';

    this.api = new Api('mainnet');
    this.offline = false;

    // Scanned chains: arrays of { chain, index, address, used }
    this.receive = [];
    this.change = [];
    this.addrMap = new Map(); // address -> { chain, index }

    this.utxos = []; // { txid, vout, value, address, chain, index, confirmed }
    this.txs = []; // aggregated history
    this.feeRates = null;
    this.confirmed = 0;
    this.pending = 0;
    // Silent-payment (BIP-352) receiving: outputs we found by scanning the
    // indexer. Kept in their own bucket (one-time taproot keys, not BIP84
    // addresses); { txid, vout, value, confirmed, tweak, xonly, address }.
    this.spUtxos = [];
    this.lastSpScan = 0; // highest block height scanned for silent payments
    this.spScanning = false;

    this.scanning = false;
    this.loaded = false; // true once a scan/snapshot has populated balances once
    this.historyLoading = false; // history is still being fetched in the background
    this._refreshing = false; // a scan/refresh is in flight
    this.nextReceiveIndex = 0;
    this.nextChangeIndex = 0;

    this._account = null;
    this._accountKey = '';
    this._addrCache = new Map();

    // Realtime (mempool.space WebSocket)
    this.live = false;
    this._ws = null;
    this._wsWant = false;
    this._wsRetry = null;
    this._refreshTimer = null;
    this._pollTimer = null;
    this._deepTimer = null; // periodic full-scan safety net
    this._polling = false; // a light poll is in flight
    this._lastPoll = 0; // last frontier poll (throttles the adaptive poll timer)
    this._hbTimer = null; // heartbeat / liveness watchdog
    this._lastMsg = 0; // time of last WS message (incl. pong)
    this._wakeHooked = false;

    // Encrypted cross-device state sync over Nostr.
    this.nostr = new NostrSync();
    this._savedAt = 0;
    this._nostrPubTimer = null;

    this._subs = new Set();
  }

  // --- reactive glue (tiny pub/sub; the UI re-renders on change) ----------
  subscribe(fn) {
    this._subs.add(fn);
    return () => this._subs.delete(fn);
  }
  emit() {
    for (const fn of this._subs) fn(this);
  }

  // --- setup --------------------------------------------------------------
  load({ mnemonic = '', passphrase = '', xpub = '', xprv = '', netName = 'mainnet', offline = false, spFresh = false }) {
    this.stopRealtime();
    // A freshly-generated wallet can't have received silent payments before it
    // existed, so we start its SP watermark at the current tip (no history scan).
    this._spFresh = spFresh;
    this.mnemonic = (mnemonic || '').trim().replace(/\s+/g, ' ');
    this.passphrase = passphrase;
    this.xpub = xpub || '';
    this.xprv = xprv || ''; // spending wallet imported from an extended private key
    this.watchOnly = !!this.xpub && !this.mnemonic && !this.xprv; // view/receive only
    this.netName = netName;
    this.offline = offline;
    this._buildApi();
    this.api.offline = offline;
    this._account = null;
    this._accountKey = null;
    this._addrCache.clear();
    this._reserved = null; // gift coins set aside from spending (lazy-loaded)
    this._reclaimed = null; // gift coins freed for spending but link still live
    this._savedAt = 0;
    try {
      if (this.mnemonic) this.nostr.load(this.mnemonic, this.passphrase);
      else this.nostr.unload();
    } catch {}
    this.reset();
  }

  reset() {
    this.receive = [];
    this.change = [];
    this.addrMap = new Map();
    this.utxos = [];
    this.txs = [];
    this.confirmed = 0;
    this.pending = 0;
    this.spUtxos = [];
    this.lastSpScan = 0;
    this.loaded = false;
    this.nextReceiveIndex = 0;
    this.nextChangeIndex = 0;
  }

  setOffline(off) {
    this.offline = off;
    this.api.offline = off;
    if (off) this.stopRealtime();
    this.emit();
  }

  // Build the data backend for the current setting: Esplora REST (`Api`) or a
  // full Electrum-over-WS server (`ElectrumApi`), which routes its data calls
  // over this wallet's realtime socket via _rpcCall.
  _buildApi() {
    if (getBackend() === 'electrum') {
      this.api = new ElectrumApi({
        call: (m, p) => this._rpcCall(m, p),
        network: this.netCfg.net,
        testnet: this.netName !== 'mainnet',
        explorerWeb: explorerWeb(),
      });
    } else {
      this.api = new Api(this.netName);
    }
    this.api.offline = this.offline;
  }

  // Rebuild the backend against the current settings, then rescan and reconnect
  // realtime (called when the user switches explorer/backend in Settings).
  async reloadExplorer() {
    this.stopRealtime();
    this._buildApi();
    if (this.offline) return;
    // Electrum's data rides the socket, so connect first, then scan.
    if (getBackend() === 'electrum') this.startRealtime();
    try {
      await this.scan();
    } catch {}
    if (getBackend() !== 'electrum') this.startRealtime();
  }

  get netCfg() {
    return NETS[this.netName];
  }

  // --- derivation ---------------------------------------------------------
  account() {
    const { coin } = this.netCfg;
    // Cache key identifies the source so a reload rebuilds when it changes.
    const key = this.watchOnly ? 'pub:' + this.xpub
      : this.xprv ? 'prv:' + this.xprv
      : `${this.netName}|${this.mnemonic}|${this.passphrase}`;
    if (this._account && this._accountKey === key) return this._account;
    let acct;
    if (this.watchOnly) {
      acct = HDKey.fromExtendedKey(this.xpub); // account-level public key
    } else if (this.xprv) {
      // A master xprv (depth 0) needs the BIP84 account path derived from it;
      // an already account-level xprv is used as-is.
      const node = HDKey.fromExtendedKey(this.xprv);
      acct = node.depth === 0 ? node.derive(`m/84'/${coin}'/0'`) : node;
    } else {
      acct = HDKey.fromMasterSeed(mnemonicToSeedSync(this.mnemonic, this.passphrase)).derive(`m/84'/${coin}'/0'`);
    }
    this._account = acct;
    this._accountKey = key;
    this._addrCache.clear();
    return acct;
  }

  // The account-level extended public key (xpub / zpub) for export → watch-only.
  accountXpub() {
    return this.account().publicExtendedKey;
  }

  // BIP-352 scan/spend keys, derived from the master seed (m/352' paths) — so
  // they need the mnemonic (or a depth-0 master xprv); watch-only and account-
  // level imported keys can't do silent payments. Cached per account.
  silentPaymentKeys() {
    if (this.watchOnly) return null;
    const coin = NETS[this.netName].coin;
    const ck = `sp|${this.netName}|${this.mnemonic}|${this.passphrase}|${this.xprv}`;
    if (this._spKeys && this._spKeysKey === ck) return this._spKeys;
    let master = null;
    if (this.mnemonic) master = HDKey.fromMasterSeed(mnemonicToSeedSync(this.mnemonic, this.passphrase));
    else if (this.xprv) { const n = HDKey.fromExtendedKey(this.xprv); if (n.depth === 0) master = n; }
    this._spKeys = master ? deriveSilentPaymentKeys(master, coin) : null;
    this._spKeysKey = ck;
    this._spScanCache = new Map(); // per-tweak scan results are keyed to these keys
    this._spCandCache = new Map();
    return this._spKeys;
  }

  // Scan one tweak's outputs for our payments, memoized by tweak — the EC
  // point-multiplication is the cost, and a tweak's outcome never changes, so
  // repeated mempool pushes (which re-send the same tweaks) stay cheap.
  _spScan(tweakHex, outputs) {
    const keys = this.silentPaymentKeys(); // resets the caches if keys changed
    if (!keys) return [];
    let m = this._spScanCache.get(tweakHex);
    if (m) return m;
    if (this._spScanCache.size > 100000) this._spScanCache.clear(); // bound memory over long sessions
    m = silentPaymentScan({ scanPriv: keys.scanPriv, spendPub: keys.spendPub, tweak: hex.decode(tweakHex), outputs });
    this._spScanCache.set(tweakHex, m);
    return m;
  }

  // Our candidate key for a tweak (for the Bloom pre-filter), memoized likewise.
  _spCandidate(tweakHex) {
    const keys = this.silentPaymentKeys();
    if (!keys) return null;
    let c = this._spCandCache.get(tweakHex);
    if (c) return c;
    if (this._spCandCache.size > 100000) this._spCandCache.clear(); // bound memory over long sessions
    c = silentPaymentCandidate({ scanPriv: keys.scanPriv, spendPub: keys.spendPub, tweak: hex.decode(tweakHex) });
    this._spCandCache.set(tweakHex, c);
    return c;
  }

  // Spawn (once) the scanning worker and keep its keys current. Returns null if
  // workers are unavailable or the embedded bundle is missing — callers then fall
  // back to scanning on the main thread (still cached + yielding).
  _ensureSpWorker() {
    if (this._spWorkerFailed || typeof Worker === 'undefined') return null;
    const keys = this.silentPaymentKeys();
    if (!keys) return null;
    if (!this._spWorker) {
      try {
        const b64 = globalThis.__SP_WORKER__;
        if (!b64) { this._spWorkerFailed = true; return null; }
        const bytes = Uint8Array.from(atob(b64), (ch) => ch.charCodeAt(0));
        const w = new Worker(URL.createObjectURL(new Blob([bytes], { type: 'text/javascript' })));
        this._spPending = new Map();
        this._spReqId = 0;
        w.onmessage = (e) => { const p = this._spPending.get(e.data.id); if (p) { this._spPending.delete(e.data.id); e.data.error ? p.rej(new Error(e.data.error)) : p.res(e.data); } };
        w.onerror = () => { this._spWorkerFailed = true; try { w.terminate(); } catch {} this._spWorker = null; for (const p of this._spPending.values()) p.rej(new Error('sp worker error')); this._spPending.clear(); };
        this._spWorker = w;
        this._spWorkerKeysSig = null;
      } catch { this._spWorkerFailed = true; return null; }
    }
    if (this._spWorkerKeysSig !== this._spKeysKey) {
      this._spWorkerKeysSig = this._spKeysKey;
      this._spWorker.postMessage({ id: ++this._spReqId, op: 'keys', scanPriv: keys.scanPriv, spendPub: keys.spendPub });
    }
    return this._spWorker;
  }

  _spCall(op, data) {
    return new Promise((res, rej) => {
      const id = ++this._spReqId;
      this._spPending.set(id, { res, rej });
      this._spWorker.postMessage({ id, op, ...data });
      setTimeout(() => { if (this._spPending.has(id)) { this._spPending.delete(id); rej(new Error('sp worker timeout')); } }, 30000);
    });
  }

  // Block heights whose Bloom filter might hold one of our outputs (worker if
  // available, else a cached + yielding main-thread loop).
  async _spHitBlocks(blocks) {
    if (!blocks.length) return new Set();
    const w = this._ensureSpWorker();
    if (w) { try { return new Set((await this._spCall('candidates', { blocks })).hits || []); } catch {} }
    const hits = new Set();
    let i = 0;
    for (const b of blocks) {
      if (++i % 8 === 0) await new Promise((r) => setTimeout(r, 0));
      for (const tw of b.tweaks) { if (bloomHas(b.filter, this._spCandidate(tw))) { hits.add(b.height); break; } }
    }
    return hits;
  }

  // Full-scan items → our resolved utxos {txid,vout,value,xonly,tweak} (worker if
  // available, else a cached + yielding main-thread loop).
  async _spScanItems(items) {
    if (!items.length) return [];
    const w = this._ensureSpWorker();
    if (w) { try { return (await this._spCall('scan', { items })).found || []; } catch {} }
    const found = [];
    let i = 0;
    for (const it of items) {
      if (++i % 50 === 0) await new Promise((r) => setTimeout(r, 0));
      const matches = this._spScan(it.tweak, it.outputs.map((o) => o.xonly));
      for (const m of matches) { const o = it.outputs.find((x) => x.xonly === m.output); if (o) found.push({ txid: it.txid, vout: o.vout, value: o.value, xonly: m.output, tweak: m.tweak }); }
    }
    return found;
  }

  // Our silent-payment address (sp1…/tsp1…), or null if this wallet can't do SP.
  silentPaymentAddress() {
    const k = this.silentPaymentKeys();
    return k ? encodeSilentPaymentAddress(k.scanPub, k.spendPub, { testnet: this.netName !== 'mainnet' }) : null;
  }

  // True if addr is a valid on-chain address for this wallet's network.
  isOnchainAddress(addr) {
    try { btc.Address(this.netCfg.net).decode((addr || '').trim()); return true; } catch { return false; }
  }

  // Is SP receiving available here? (we can derive keys AND an indexer is set)
  silentPaymentsAvailable() {
    return !!(this.silentPaymentKeys() && spIndexerUrl(this.netName));
  }

  // Total received via silent payments: { confirmed, pending, count } over the
  // unspent SP outputs we've found.
  spBalance() {
    let confirmed = 0, pending = 0;
    for (const u of this.spUtxos) { if (u.confirmed) confirmed += u.value; else pending += u.value; }
    return { confirmed, pending, count: this.spUtxos.length };
  }

  // Received silent payments as history rows (one per tx; multiple outputs to us
  // sum into one received entry) so they appear in history like normal payments.
  spTxRows() {
    const byTx = new Map();
    for (const u of this.spUtxos) {
      const e = byTx.get(u.txid) || { txid: u.txid, net: 0, confirmed: true, firstSeen: u.firstSeen || Date.now() };
      e.net += u.value;
      if (!u.confirmed) e.confirmed = false;
      e.firstSeen = Math.min(e.firstSeen, u.firstSeen || e.firstSeen);
      byTx.set(u.txid, e);
    }
    return [...byTx.values()].map((e) => ({
      txid: e.txid, net: e.net, fee: 0, vsize: 0, sp: true,
      confirmed: e.confirmed,
      blockTime: e.confirmed ? Math.floor(e.firstSeen / 1000) : 0,
      blockHeight: 0,
      firstSeen: e.firstSeen,
    }));
  }

  // History for display: BIP84 txs + silent-payment receipts, newest first. (SP
  // receipts pay one-time taproot keys, never our BIP84 addresses, so no overlap.)
  get history() {
    const rows = [...this.txs, ...this.spTxRows()];
    rows.sort((a, b) => {
      if (a.confirmed !== b.confirmed) return a.confirmed ? 1 : -1; // pending first
      if (a.confirmed) return (b.blockTime || 0) - (a.blockTime || 0);
      return (b.firstSeen || 0) - (a.firstSeen || 0);
    });
    return rows;
  }

  // The taproot address for an x-only output key (for backend UTXO lookups).
  _spAddress(xonly) {
    return btc.Address(this.netCfg.net).encode(btc.OutScript.decode(btc.OutScript.encode({ type: 'tr', pubkey: hex.decode(xonly) })));
  }

  // Scan the configured SP indexer from the last-scanned height to the tip, find
  // outputs paying our scan/spend keys, and verify each is unspent via the chain
  // backend (the indexer only does discovery). Updates this.spUtxos.
  async scanSilentPayments({ rescan = false, silent = false } = {}) {
    const keys = this.silentPaymentKeys();
    const indexer = spIndexerUrl(this.netName);
    if (!keys || !indexer || this.offline) return { unavailable: true };
    if (this._spScanBusy) return { busy: true };
    // Fresh wallet, never scanned: set the watermark to the current tip instead of
    // scanning all history (nothing predates the wallet). New blocks + mempool
    // arrive via the live push from here on.
    if (this._spFresh && !this.lastSpScan && !rescan) {
      this._spFresh = false;
      try { this.lastSpScan = (await (await fetch(`${indexer}/height`)).json()).height || 0; this.saveCache(); } catch {}
      return { fresh: true };
    }
    this._spScanBusy = true;
    // Only a manual scan shows the visible "Scanning…" state; auto-scans are
    // invisible (setting spScanning for them left the card stuck on "Scanning…").
    if (!silent) { this.spScanning = true; this.emit(); }
    try {
      if (rescan) { this.spUtxos = []; this.lastSpScan = 0; }
      const from = (this.lastSpScan || 0) + 1;
      // Catch-up: per block we get tweaks + a Bloom filter (no outputs). Derive a
      // candidate key per tweak, test the filter, and only fetch the full block on
      // a hit — so most blocks cost just the candidate math, no download/scan.
      const res = await (await fetch(`${indexer}/scan/${from}?dustLimit=${SP_DUST_LIMIT}`)).json();
      const tip = res.tip || 0;
      const have = new Set(this.spUtxos.map((u) => `${u.txid}:${u.vout}`));
      const found = [];
      const hits = await this._spHitBlocks(res.blocks || []);
      for (const block of res.blocks || []) {
        if (!hits.has(block.height)) continue;
        const blk = await (await fetch(`${indexer}/block/${block.height}`)).json();
        for (const f of await this._spScanItems(blk.items || [])) {
          const id = `${f.txid}:${f.vout}`;
          if (have.has(id)) continue;
          have.add(id);
          found.push(f);
        }
      }
      if (tip > this.lastSpScan) this.lastSpScan = tip;
      // Verify newly-found outputs are unspent + get confirmation status.
      for (const f of found) {
        const address = this._spAddress(f.xonly);
        try {
          const us = await this.api.addressUtxos(address);
          const u = us.find((x) => x.txid === f.txid && x.vout === f.vout);
          if (u) this.spUtxos.push({ ...f, address, confirmed: !!(u.status && u.status.confirmed), firstSeen: Date.now() });
        } catch {}
      }
      await this._refreshSpUtxos();
      this._recomputeBalanceFromChains(); // fold found SP value into the displayed balance
      this.saveCache();
      return { found: found.length, scanned: tip };
    } finally {
      this._spScanBusy = false;
      this.spScanning = false;
      this.emit(); // always refresh (balance + clears any "Scanning…")
    }
  }

  // Re-check tracked SP outputs against the backend: drop spent ones, refresh
  // confirmation status.
  async _refreshSpUtxos() {
    const next = [];
    for (const u of this.spUtxos) {
      try {
        const us = await this.api.addressUtxos(u.address);
        const live = us.find((x) => x.txid === u.txid && x.vout === u.vout);
        if (live) next.push({ ...u, confirmed: !!(live.status && live.status.confirmed) });
      } catch { next.push(u); } // backend hiccup: keep as-is
    }
    this.spUtxos = next;
  }

  // Live silent-payment push: subscribe to the indexer's WebSocket so each new
  // block's SP items are scanned on arrival instead of polling. Catches up via a
  // /scan on connect (covers anything missed while disconnected) and reconnects.
  _spConnect() {
    if (this.offline) return;
    const base = spIndexerUrl(this.netName);
    if (!base || !this.silentPaymentKeys()) return;
    const url = base.replace(/^http/, 'ws') + '/ws';
    if (this._spWs && this._spWsUrl === url) return;
    this._spDisconnect();
    this._spWsUrl = url;
    let ws;
    try { ws = new WebSocket(absWsUrl(url)); } catch { return; }
    this._spWs = ws;
    ws.onopen = () => {
      this.spLive = true;
      this.scanSilentPayments({ silent: true }).catch(() => {}); // confirmed catch-up
      // Pending (mempool) catch-up.
      fetch(`${base}/mempool`).then((r) => r.json()).then((d) => this._scanSpMempool(d.items || [])).catch(() => {});
    };
    ws.onmessage = (ev) => {
      let msg;
      try { msg = JSON.parse(typeof ev.data === 'string' ? ev.data : new TextDecoder().decode(ev.data)); } catch { return; }
      if (!msg || !Array.isArray(msg.items)) return;
      if (msg.type === 'block') this._scanSpItems(msg.items, msg.height).catch(() => {});
      else if (msg.type === 'mempool') this._scanSpMempool(msg.items).catch(() => {});
    };
    ws.onerror = () => { try { ws.close(); } catch {} };
    ws.onclose = () => {
      if (this._spWs !== ws) return;
      this.spLive = false; this._spWs = null;
      if (!this.offline) this._spReconnect = setTimeout(() => this._spConnect(), 3000);
    };
  }

  _spDisconnect() {
    clearTimeout(this._spReconnect);
    this.spLive = false;
    const ws = this._spWs;
    this._spWs = null; this._spWsUrl = null;
    if (ws) { try { ws.onclose = null; ws.close(); } catch {} }
  }

  // Scan a confirmed block's pushed items and upsert ours into spUtxos as
  // confirmed (a previously-pending mempool entry is promoted to confirmed).
  async _scanSpItems(items, height) {
    const keys = this.silentPaymentKeys();
    if (!keys) return;
    let changed = false;
    for (const f of await this._spScanItems(items)) {
      const existing = this.spUtxos.find((u) => u.txid === f.txid && u.vout === f.vout);
      if (existing) { if (!existing.confirmed) { existing.confirmed = true; changed = true; } }
      else { this.spUtxos.push({ txid: f.txid, vout: f.vout, value: f.value, xonly: f.xonly, tweak: f.tweak, address: this._spAddress(f.xonly), confirmed: true, firstSeen: Date.now() }); changed = true; }
    }
    if (height && height > this.lastSpScan) this.lastSpScan = height;
    if (changed) this._recomputeBalanceFromChains();
    this.saveCache();
    if (changed) this.emit();
  }

  // Scan the current mempool's pushed items and rebuild our pending (unconfirmed)
  // SP set — so payments show the moment they're broadcast. Confirmed entries are
  // kept; the unconfirmed set is replaced, which also drops vanished/RBF'd ones.
  async _scanSpMempool(items) {
    // Coalesce: pushes arrive faster than a cold (mainnet) scan completes, so
    // keep only the latest set and never run two scans at once.
    this._spMempoolLatest = items;
    if (this._spMempoolBusy) return;
    this._spMempoolBusy = true;
    try {
      if (!this.silentPaymentKeys()) return;
      while (this._spMempoolLatest) {
        const cur = this._spMempoolLatest;
        this._spMempoolLatest = null;
        const priorSeen = new Map(this.spUtxos.map((u) => [`${u.txid}:${u.vout}`, u.firstSeen]));
        const confirmedIds = new Set(this.spUtxos.filter((u) => u.confirmed).map((u) => `${u.txid}:${u.vout}`));
        const pending = [];
        for (const f of await this._spScanItems(cur)) {
          const id = `${f.txid}:${f.vout}`;
          if (confirmedIds.has(id)) continue;
          pending.push({ txid: f.txid, vout: f.vout, value: f.value, xonly: f.xonly, tweak: f.tweak, address: this._spAddress(f.xonly), confirmed: false, firstSeen: priorSeen.get(id) || Date.now() });
        }
        // Re-read confirmed (a block push may have landed during a yield) and drop
        // any pending that just confirmed, so an outpoint never appears twice.
        const confNow = this.spUtxos.filter((u) => u.confirmed);
        const confNowIds = new Set(confNow.map((u) => `${u.txid}:${u.vout}`));
        const oldPendingIds = new Set(this.spUtxos.filter((u) => !u.confirmed).map((u) => `${u.txid}:${u.vout}`));
        const freshPending = pending.filter((p) => !confNowIds.has(`${p.txid}:${p.vout}`));
        // Only emit when our pending set actually changed — the mempool churns
        // constantly, and a no-op emit would re-render and steal input focus.
        const changed = freshPending.length !== oldPendingIds.size || freshPending.some((p) => !oldPendingIds.has(`${p.txid}:${p.vout}`));
        this.spUtxos = [...confNow, ...freshPending];
        if (changed) { this._recomputeBalanceFromChains(); this.saveCache(); this.emit(); }
      }
    } finally {
      this._spMempoolBusy = false;
    }
  }

  node(chain, index) {
    // Relative derivation from the account node (chain/index are non-hardened).
    return this.account().deriveChild(chain).deriveChild(index);
  }

  // Returns { address, script, pubkey }
  derive(chain, index) {
    const cacheKey = `${chain}/${index}`;
    const hit = this._addrCache.get(cacheKey);
    if (hit) return hit;
    const node = this.node(chain, index);
    const pay = p2wpkh(node.publicKey, this.netCfg.net);
    const info = { address: pay.address, script: pay.script, pubkey: node.publicKey, chain, index };
    this._addrCache.set(cacheKey, info);
    return info;
  }

  // Derive a window of addresses on both chains and (re)build addrMap. Used in
  // offline mode where we cannot scan for usage but still must map a UTXO's
  // address back to its derivation path in order to sign it.
  deriveWindow(count) {
    this.addrMap = new Map();
    for (const chain of [0, 1]) {
      for (let i = 0; i < count; i++) {
        const { address } = this.derive(chain, i);
        this.addrMap.set(address, { chain, index: i });
      }
    }
  }

  // --- online scan --------------------------------------------------------
  // Query one address at a time; stop at the first unused one (no look-ahead).
  async scanChain(chain) {
    const found = [];
    let gap = 0;
    let i = 0;
    while (gap < GAP_LIMIT) {
      const { address } = this.derive(chain, i);
      const info = await this.api.addressInfo(address);
      const cs = info.chain_stats || {};
      const ms = info.mempool_stats || {};
      const used = (cs.tx_count || 0) > 0 || (ms.tx_count || 0) > 0;
      const hasMempool = (ms.tx_count || 0) > 0;
      // Balance straight from chain_stats — no need to fetch /utxo just to total.
      const confirmed = (cs.funded_txo_sum || 0) - (cs.spent_txo_sum || 0);
      const pending = (ms.funded_txo_sum || 0) - (ms.spent_txo_sum || 0);
      found.push({ chain, index: i, address, used, confirmed, pending, hasMempool });
      this.addrMap.set(address, { chain, index: i });
      if (used) {
        gap = 0;
        await sleep(USED_HIT_DELAY_MS); // slow down before fetching the next one
      } else {
        gap += 1;
      }
      i++;
    }
    return found;
  }

  // A short signature of the user-visible state, so background ("silent")
  // refreshes only re-render when something actually changed.
  _sig() {
    return JSON.stringify({
      bc: this.confirmed,
      bp: this.pending,
      u: this.utxos.map((u) => `${u.txid}:${u.vout}:${u.value}:${u.confirmed ? 1 : 0}`),
      t: this.txs.map((t) => `${t.txid}:${t.confirmed ? 1 : 0}`),
      r: this.nextReceiveIndex,
      c: this.nextChangeIndex,
    });
  }

  _addrInfo(chain, index) {
    const arr = chain === 0 ? this.receive : this.change;
    return arr.find((a) => a.index === index);
  }

  // Light poll: only check the fresh frontier — the next receive and change
  // address — for new activity. Already-scanned addresses are never re-polled;
  // changes to them (spends) arrive over the WebSocket while connected, and a
  // manual rescan covers anything missed (e.g. address reuse). If the frontier
  // moved, escalate to a full scan once to reconcile.
  async refreshLive() {
    if (this.offline || this._refreshing || this._polling) return;
    this._polling = true;
    this._lastPoll = Date.now(); // any refresh (poll OR socket-open) resets the
    // poll clock, so the two don't both fire back-to-back on load.
    let changed = false;
    try {
      const fresh = []; // frontier addresses found to be active this pass
      for (const chain of [0, 1]) {
        let idx = chain === 0 ? this.nextReceiveIndex : this.nextChangeIndex;
        // Walk forward from the frontier while addresses are used; stop at the
        // first unused one. Never revisits already-passed (cached) addresses.
        for (let guard = 0; guard < 100; guard++) {
          const { address } = this.derive(chain, idx);
          const info = await this.api.addressInfo(address);
          const cs = info.chain_stats || {};
          const ms = info.mempool_stats || {};
          const used = (cs.tx_count || 0) > 0 || (ms.tx_count || 0) > 0;
          const confirmed = (cs.funded_txo_sum || 0) - (cs.spent_txo_sum || 0);
          const pending = (ms.funded_txo_sum || 0) - (ms.spent_txo_sum || 0);

          const arr = chain === 0 ? this.receive : this.change;
          let entry = arr.find((a) => a.index === idx);
          if (!entry) {
            entry = { chain, index: idx, address };
            arr.push(entry);
            this.addrMap.set(address, { chain, index: idx });
          }
          if (entry.used !== used || entry.confirmed !== confirmed || entry.pending !== pending) {
            changed = true;
            if (used) fresh.push({ chain, index: idx, address });
          }
          entry.used = used;
          entry.confirmed = confirmed;
          entry.pending = pending;

          if (!used) break; // frontier still fresh — done with this chain
          idx++;
        }
        if (chain === 0) this.nextReceiveIndex = idx;
        else this.nextChangeIndex = idx;
      }

      // Fetch coins + history for ONLY the newly-active frontier addresses.
      for (const a of fresh) {
        const us = await this.api.addressUtxos(a.address);
        this.utxos = this.utxos.filter((u) => u.address !== a.address);
        for (const u of us) {
          this.utxos.push({
            txid: u.txid,
            vout: u.vout,
            value: u.value,
            address: a.address,
            chain: a.chain,
            index: a.index,
            confirmed: !!u.status.confirmed,
          });
        }
        const list = await this.api.addressTxs(a.address);
        for (const tx of list) {
          const summary = this._txSummary(tx);
          const at = this.txs.findIndex((t) => t.txid === tx.txid);
          // Refresh in place so a tx that has since confirmed loses its pending
          // status — not just append new ones (which left confirmations stale).
          if (at >= 0) this.txs[at] = summary;
          else this.txs.push(summary);
        }
      }

      // Re-verify the addresses that currently hold coins, to catch spends from
      // an already-scanned address (the frontier walk above only looks forward,
      // so a coin spent here — including by a tx broadcast on another device —
      // would otherwise never reconcile without a full rescan).
      if (await this._reconcileHeld()) changed = true;

      if (changed) {
        this.utxos.sort((x, y) => y.value - x.value);
        this._sortTxs();
        this._recomputeBalanceFromChains();
        this.loaded = true;
        this.saveCache();
        this.retrack(); // a new pending coin may have changed the watched set
        this.emit();
      }
    } catch {
      /* transient; next poll/ws retries */
    } finally {
      this._polling = false;
    }
  }

  // Enable/disable fast polling of the fresh receive address — set while the
  // Receive tab is open so a deposit shows near-instantly even if the WS doesn't
  // push it. Toggling on triggers an immediate check.
  setWatchReceive(on) {
    on = !!on;
    if (on === !!this._watchReceive) return; // no change — avoid re-triggering
    this._watchReceive = on;
    if (on) { this._lastReceivePoll = 0; this.pollReceiveFrontier(); }
  }

  // Cheap single-address check of the next receive address. If it has activity,
  // hand off to the full refreshLive (which pulls the coin + history and advances
  // the frontier); otherwise do nothing. One request per call.
  async pollReceiveFrontier() {
    if (this.offline || this._polling || this._refreshing) return;
    const idx = this.nextReceiveIndex;
    const { address } = this.derive(0, idx);
    try {
      const info = await this.api.addressInfo(address);
      const cs = info.chain_stats || {};
      const ms = info.mempool_stats || {};
      const used = (cs.tx_count || 0) > 0 || (ms.tx_count || 0) > 0;
      if (used) await this.refreshLive();
    } catch {
      /* transient; next tick retries */
    }
  }

  // Re-check every address that currently holds a UTXO: refresh its balance from
  // chain/mempool stats and rebuild its UTXOs. This is what reconciles spends
  // (a held coin that's now gone) — confirmed or still in the mempool, regardless
  // of which device broadcast the spending transaction. Returns true if anything
  // changed. Only touches addresses we already know, so it stays cheap.
  async _reconcileHeld() {
    const addrs = [...new Set(this.utxos.map((u) => u.address))];
    let changed = false;
    for (const address of addrs) {
      const p = this.addrMap.get(address);
      if (!p) continue;
      let info;
      try {
        info = await this.api.addressInfo(address);
      } catch {
        continue;
      }
      const cs = info.chain_stats || {};
      const ms = info.mempool_stats || {};
      const confirmed = (cs.funded_txo_sum || 0) - (cs.spent_txo_sum || 0);
      const pending = (ms.funded_txo_sum || 0) - (ms.spent_txo_sum || 0);
      const arr = p.chain === 0 ? this.receive : this.change;
      const entry = arr.find((e) => e.index === p.index);
      if (entry && entry.confirmed === confirmed && entry.pending === pending) continue;

      let us;
      try {
        us = await this.api.addressUtxos(address);
      } catch {
        continue;
      }
      // Derive the entry's balance from the ACTUAL unspent coins, not from
      // get_balance/address-stats: a confirmed coin that's being spent by an
      // unconfirmed tx still shows as "confirmed" there (with a compensating
      // negative unconfirmed), so trusting it would keep a just-spent coin in the
      // headline balance on another device. listunspent excludes spent coins.
      this.utxos = this.utxos.filter((u) => u.address !== address);
      let eConf = 0, ePend = 0;
      for (const u of us) {
        const conf = !!(u.status && u.status.confirmed);
        if (conf) eConf += u.value; else ePend += u.value;
        this.utxos.push({ txid: u.txid, vout: u.vout, value: u.value, address, chain: p.chain, index: p.index, confirmed: conf });
      }
      if (entry) { entry.confirmed = eConf; entry.pending = ePend; }
      // Also refresh this address's tx history so a pending→confirmed transition
      // shows in History on the next poll — not only via the realtime push,
      // which regtest / custom-explorer (non-WS) backends don't have.
      try {
        const list = await this.api.addressTxs(address);
        for (const tx of list) {
          const summary = this._txSummary(tx);
          const at = this.txs.findIndex((t) => t.txid === tx.txid);
          if (at >= 0) this.txs[at] = summary; else this.txs.push(summary);
        }
      } catch {}
      changed = true;
    }
    return changed;
  }

  // Every address the wallet currently knows about (scanned receive + change),
  // sorted by chain then index, for the per-address rescan list in Settings.
  knownAddresses() {
    const mk = (e, chain) => ({ chain, index: e.index, address: e.address, used: !!e.used, balance: (e.confirmed || 0) + (e.pending || 0) });
    return [
      ...this.receive.map((e) => mk(e, 0)),
      ...this.change.map((e) => mk(e, 1)),
    ].sort((a, b) => a.chain - b.chain || a.index - b.index);
  }

  // Re-query a single address and reconcile just its coins/history into state —
  // the targeted alternative to a full rescan, for recovering a deposit to a
  // reused old address. Returns whether the address is used.
  async rescanAddress(chain, index) {
    const { address } = this.derive(chain, index);
    const info = await this.api.addressInfo(address);
    const cs = info.chain_stats || {};
    const ms = info.mempool_stats || {};
    const used = (cs.tx_count || 0) > 0 || (ms.tx_count || 0) > 0;
    const confirmed = (cs.funded_txo_sum || 0) - (cs.spent_txo_sum || 0);
    const pending = (ms.funded_txo_sum || 0) - (ms.spent_txo_sum || 0);

    const arr = chain === 0 ? this.receive : this.change;
    let entry = arr.find((e) => e.index === index);
    if (!entry) { entry = { chain, index, address }; arr.push(entry); arr.sort((a, b) => a.index - b.index); }
    this.addrMap.set(address, { chain, index });
    entry.used = used;
    entry.confirmed = confirmed;
    entry.pending = pending;

    const us = await this.api.addressUtxos(address);
    this.utxos = this.utxos.filter((u) => u.address !== address);
    for (const u of us) this.utxos.push({ txid: u.txid, vout: u.vout, value: u.value, address, chain, index, confirmed: !!u.status.confirmed });

    const list = await this.api.addressTxs(address);
    for (const tx of list) {
      const summary = this._txSummary(tx);
      const at = this.txs.findIndex((t) => t.txid === tx.txid);
      if (at >= 0) this.txs[at] = summary;
      else this.txs.push(summary);
    }

    this.nextReceiveIndex = firstUnused(this.receive);
    this.nextChangeIndex = firstUnused(this.change);
    this.utxos.sort((x, y) => y.value - x.value);
    this._sortTxs();
    this._recomputeBalanceFromChains();
    this.loaded = true;
    this.saveCache();
    this.retrack(); // watch this address over the socket if its coin is pending
    this.emit();
    return used;
  }

  // silent=false: foreground load (shows loading state, always re-renders).
  // silent=true:  background refresh (poll / WS) — no spinner, and only emits
  //               if the visible state changed, so it never disrupts typing.
  async scan({ silent = false } = {}) {
    if (this.offline || this._refreshing) return;
    this._refreshing = true;
    const before = silent ? this._sig() : null;
    if (!silent) {
      this.scanning = true;
      this.emit();
    }
    try {
      const prevBal = `${this.confirmed}|${this.pending}|${this.nextReceiveIndex}|${this.nextChangeIndex}`;
      this.addrMap = new Map();
      // Probe both chains at once — they're independent, so interleaving lets
      // their per-hit delays overlap instead of running back-to-back.
      const [receive, change] = await Promise.all([this.scanChain(0), this.scanChain(1)]);
      this.receive = receive;
      this.change = change;
      this.nextReceiveIndex = firstUnused(this.receive);
      this.nextChangeIndex = firstUnused(this.change);
      this._recomputeBalanceFromChains();

      // Only pull /utxo and /txs (the heavy part) on first load or when the
      // balance/addresses actually changed. Idle polls stay /address-only.
      const balanceChanged =
        `${this.confirmed}|${this.pending}|${this.nextReceiveIndex}|${this.nextChangeIndex}` !== prevBal;
      // Always re-pull history while any tx is still pending, so confirmations
      // get reconciled even when the balance itself hasn't changed (e.g. a
      // received coin that simply moved from mempool to a block).
      const hasPending = this.txs.some((t) => !t.confirmed);
      if (!silent || balanceChanged || !this.loaded || hasPending) {
        // Balance + receive address are already known from the chain_stats above.
        // Show them right away so the wallet looks ready, then keep loading the
        // heavier UTXO set and full history in the background.
        if (!silent) {
          this.loaded = true;
          this.historyLoading = true;
          this.emit();
        }
        if (!silent || !this.feeRates) this.feeRates = await this.api.feeRates();
        await this.refreshUtxos();
        await this.refreshHistory(!silent);
      }
      this.loaded = true;
      this.saveCache();
      this.scanSilentPayments({ silent: true }).catch(() => {}); // fold in any silent-payment receipts
    } finally {
      this._refreshing = false;
      this.historyLoading = false; // clear even if an earlier step threw
      if (!silent) {
        this.scanning = false;
        this.emit();
      } else if (this._sig() !== before) {
        this.emit();
      }
    }
  }

  usedAddresses() {
    return [...this.receive, ...this.change].filter((a) => a.used);
  }

  async refreshUtxos() {
    // An address whose confirmed balance is 0 and which has no mempool activity
    // is fully spent and settled — it cannot hold any UTXOs, so skip the /utxo
    // round-trip for it. In a wallet with history most addresses are spent, so
    // this avoids the bulk of the requests (and the 429s that come with them).
    const used = this.usedAddresses().filter(
      (a) => (a.confirmed || 0) > 0 || a.hasMempool
    );
    const lists = await pool(used, (a) => this.api.addressUtxos(a.address));
    const utxos = [];
    used.forEach((a, idx) => {
      for (const u of lists[idx]) {
        utxos.push({
          txid: u.txid,
          vout: u.vout,
          value: u.value,
          address: a.address,
          chain: a.chain,
          index: a.index,
          confirmed: !!u.status.confirmed,
        });
      }
    });
    utxos.sort((a, b) => b.value - a.value);
    this.utxos = utxos;
  }

  // Summarize a raw esplora tx into our history shape (net to us, fee, status).
  _txSummary(tx) {
    const mine = new Set(this.addrMap.keys());
    let received = 0;
    let sent = 0;
    for (const vin of tx.vin || []) {
      const a = vin.prevout && vin.prevout.scriptpubkey_address;
      if (a && mine.has(a)) sent += vin.prevout.value;
    }
    for (const vout of tx.vout || []) {
      if (vout.scriptpubkey_address && mine.has(vout.scriptpubkey_address)) received += vout.value;
    }
    const confirmed = !!(tx.status && tx.status.confirmed);
    // Preserve when we first saw it pending, so we can later judge a stuck tx.
    const prior = this.txs.find((t) => t.txid === tx.txid);
    // A tx we built + broadcast (local) already has the true net + fee from
    // applySentTx; don't recompute them — a rescan can under-count inputs whose
    // address isn't on the scanned frontier (e.g. a swap-claim coin), which would
    // understate the amount sent. Only the confirmation status changes.
    const local = !!(prior && prior.local);
    return {
      txid: tx.txid,
      net: local ? prior.net : received - sent, // >0 incoming, <0 outgoing
      fee: local && prior.fee ? prior.fee : tx.fee || 0,
      vsize: tx.weight ? Math.ceil(tx.weight / 4) : (prior && prior.vsize) || 0,
      confirmed,
      blockTime: (tx.status && tx.status.block_time) || 0,
      blockHeight: (tx.status && tx.status.block_height) || 0,
      firstSeen: confirmed ? 0 : (prior && prior.firstSeen) || Date.now(),
      local,
    };
  }

  // A pending tx is "stuck" once it's waited ~10 blocks (≈100 min) and its fee
  // rate is below the mempool's current floor (minimumFee) — i.e. it's been
  // purged and won't confirm without a bump (RBF/CPFP). We stop actively
  // monitoring these (no socket slot, no fast poll); the slow reconcile still
  // picks it up if the floor later drops and it confirms after all.
  isStuck(tx) {
    if (!tx || tx.confirmed || !tx.firstSeen || !tx.vsize) return false;
    if (Date.now() - tx.firstSeen < 100 * 60000) return false; // give it ~10 blocks
    const floor = (this.feeRates && this.feeRates.minimumFee) || 1;
    return tx.fee / tx.vsize < floor;
  }
  _stuckTxids() {
    const s = new Set();
    for (const tx of this.txs) if (this.isStuck(tx)) s.add(tx.txid);
    return s;
  }

  _sortTxs() {
    this.txs.sort((a, b) => {
      if (a.confirmed !== b.confirmed) return a.confirmed ? 1 : -1; // pending first
      // Pending txs share blockTime 0, so order them by when we first saw them
      // (newest on top); confirmed txs go by block time (newest on top).
      if (!a.confirmed) return (b.firstSeen || 0) - (a.firstSeen || 0);
      return (b.blockTime || 0) - (a.blockTime || 0);
    });
  }

  // progressive: emit after each address resolves so the History tab fills in
  // as transactions arrive (foreground load) instead of all at once at the end.
  async refreshHistory(progressive = false) {
    const used = this.usedAddresses();
    this.historyLoading = true;
    const seen = new Set(); // txids found in this pass (a tx can touch >1 address)
    try {
      await pool(used, async (a) => {
        const list = await this.api.addressTxs(a.address);
        let added = false;
        for (const tx of list) {
          if (seen.has(tx.txid)) continue;
          seen.add(tx.txid);
          const summary = this._txSummary(tx);
          const at = this.txs.findIndex((t) => t.txid === tx.txid);
          if (at >= 0) this.txs[at] = summary; // refresh confirmations/fee
          else { this.txs.push(summary); added = true; }
        }
        if (added && progressive) {
          this._sortTxs();
          this.emit();
        }
      });
      // Drop anything that no longer appears in any address's history.
      this.txs = this.txs.filter((t) => seen.has(t.txid));
      this._sortTxs();
    } finally {
      this.historyLoading = false;
    }
  }

  // --- balances -----------------------------------------------------------
  // confirmed/pending are plain fields, set from chain_stats during scan (and
  // from UTXOs when restoring an offline snapshot). total is derived.
  get total() {
    return this.confirmed + this.pending;
  }

  // Confirmed coins locked behind unclaimed gift links. The whole source coin is
  // committed until the gift is claimed (our change only comes back in the
  // claimer's tx), so it's already excluded from spending — and from the
  // spendable balance below.
  get lockedValue() {
    const res = this.reservedSet();
    return this.utxos.reduce((s, u) => s + (res.has(utxoId(u)) ? u.value : 0), 0);
  }
  // The spendable headline: confirmed coins plus our own unconfirmed change (the
  // remainder of a spend we just made, so the spend debits immediately), minus
  // anything locked in gifts. Unconfirmed *incoming* receives are NOT counted
  // here — they show as pending until they confirm.
  get spendable() {
    const res = this.reservedSet();
    return this.utxos.reduce((s, u) => {
      if (res.has(utxoId(u))) return s;
      if (u.confirmed || u.chain === 1) return s + u.value;
      return s;
    }, 0) + this.spBalance().confirmed; // confirmed silent-payment receipts are spendable
  }
  // Unconfirmed incoming receives (not our change, not gift-locked) — shown as a
  // separate pending line, kept out of the spendable headline. Includes pending
  // (mempool) silent-payment receipts.
  get pendingIncoming() {
    const res = this.reservedSet();
    return this.utxos.reduce((s, u) => s + ((!u.confirmed && u.chain === 0 && !res.has(utxoId(u))) ? u.value : 0), 0) + this.spBalance().pending;
  }

  _recomputeBalanceFromChains() {
    let c = 0;
    let p = 0;
    for (const a of [...this.receive, ...this.change]) {
      c += a.confirmed || 0;
      p += a.pending || 0;
    }
    const sp = this.spBalance();
    this.confirmed = c + sp.confirmed;
    this.pending = p + sp.pending;
  }

  _recomputeBalanceFromUtxos() {
    const sp = this.spBalance();
    this.confirmed = this.utxos.reduce((s, u) => s + (u.confirmed ? u.value : 0), 0) + sp.confirmed;
    this.pending = this.utxos.reduce((s, u) => s + (u.confirmed ? 0 : u.value), 0) + sp.pending;
  }

  freshReceive() {
    return this.derive(0, this.nextReceiveIndex);
  }
  freshChange() {
    return this.derive(1, this.nextChangeIndex);
  }

  // --- spending -----------------------------------------------------------
  // recipients: [{ address, amount(sats) }]
  // coinIds: optional array of "txid:vout" to force manual coin control.
  // sendMax: drain all selected coins to the single recipient.
  buildTx({ recipients, feeRate, coinIds = null, sendMax = false, noSort = false }) {
    const pool_ = coinIds
      ? this.utxos.filter((u) => coinIds.includes(utxoId(u)))
      : this.utxos.filter((u) => !this.isReserved(utxoId(u))); // skip coins set aside for gifts
    // Received silent-payment outputs are spendable too — one-time taproot keys,
    // signed by sign() with the per-output key. Excluded when paying an sp1…
    // recipient (funding an SP send from a taproot input needs BIP-352 even-Y
    // key handling we don't do yet), so those sends use BIP84 coins.
    // Confirmed SP coins are spendable like any other coin — including to fund a
    // silent payment. Unconfirmed ones are excluded (the sender's tx could be
    // replaced, invalidating our spend).
    const confirmedSp = this.spUtxos.filter((u) => u.confirmed);
    const spPool = coinIds ? confirmedSp.filter((u) => coinIds.includes(utxoId(u))) : confirmedSp.slice();
    if (!pool_.length && !spPool.length) throw new Error('No spendable coins selected.');

    const inputs = [
      ...pool_.map((u) => {
        const { pubkey } = this.derive(u.chain, u.index);
        const pay = p2wpkh(pubkey, this.netCfg.net);
        return {
          ...pay,
          txid: u.txid,
          index: u.vout,
          sequence: 0xfffffffd, // signal opt-in RBF (BIP125) so sends are bumpable
          witnessUtxo: { script: pay.script, amount: BigInt(u.value) },
        };
      }),
      ...spPool.map((u) => ({
        txid: u.txid,
        index: u.vout,
        sequence: 0xfffffffd,
        witnessUtxo: { script: btc.OutScript.encode({ type: 'tr', pubkey: hex.decode(u.xonly) }), amount: BigInt(u.value) },
        // Present so the fee estimator sizes a key-path (64-byte) witness; the
        // value is unused (SP outputs are signed raw in sign(), via tapKeySig).
        tapInternalKey: hex.decode(u.xonly),
      })),
    ];

    const changeAddress = this.freshChange().address;
    const feePerByte = BigInt(Math.max(1, Math.round(feeRate)));

    // Silent payment (sp1…) recipients: the real taproot output can only be
    // derived once coin selection fixes the input set (it commits to every
    // input), so we select against a same-size placeholder taproot output and
    // swap in the derived script afterward.
    const spOuts = []; // { placeholder, scan, spend }
    if (recipients.some((r) => isSilentPaymentAddress(r.address)) && this.watchOnly)
      throw new Error('Silent payments require a wallet with keys.');

    if (sendMax) {
      if (recipients.length !== 1)
        throw new Error('Send-max requires exactly one recipient.');
      // Drain everything: use the recipient as the "change" address with no
      // fixed outputs, so the estimator sends (total − exact fee) to them.
      let dest = recipients[0].address;
      if (isSilentPaymentAddress(dest)) {
        const { scan, spend } = decodeSilentPaymentAddress(dest);
        const placeholder = silentPaymentPlaceholder(0);
        spOuts.push({ placeholder, scan, spend, address: dest });
        dest = btc.Address(this.netCfg.net).encode(btc.OutScript.decode(placeholder));
      }
      const sel = btc.selectUTXO(inputs, [], 'all', {
        changeAddress: dest,
        feePerByte,
        network: this.netCfg.net,
        createTx: true,
        bip69: true,
        disableScriptCheck: true,
      });
      if (!sel || !sel.tx) throw new Error('Fee exceeds balance.');
      if (spOuts.length) this._applySilentPayments(sel.tx, spOuts);
      const sweepSummary = summarize(sel, this.netCfg.net);
      this._tagSilentOutputs(sweepSummary, spOuts);
      return sweepSummary;
    }

    const outputs = recipients.map((r) => {
      if (isSilentPaymentAddress(r.address)) {
        const { scan, spend } = decodeSilentPaymentAddress(r.address);
        const placeholder = silentPaymentPlaceholder(spOuts.length);
        spOuts.push({ placeholder, scan, spend, address: r.address });
        return { script: placeholder, amount: BigInt(r.amount) };
      }
      return { address: r.address, amount: BigInt(r.amount) };
    });
    const strategy = coinIds ? 'all' : 'default';
    const sel = btc.selectUTXO(inputs, outputs, strategy, {
      changeAddress,
      feePerByte,
      network: this.netCfg.net,
      createTx: true,
        // noSort keeps recipients at their given indexes (change appended last) —
        // required when an output's position is protocol-relevant (Ark board
        // funding must sit at vout 0).
        bip69: !noSort,
        disableScriptCheck: true,
    });
    if (!sel || !sel.tx)
      throw new Error('Insufficient funds for amount + fee.');
    if (spOuts.length) this._applySilentPayments(sel.tx, spOuts);
    const summary = summarize(sel, this.netCfg.net);
    this._tagSilentOutputs(summary, spOuts);
    return summary;
  }

  // Mark summary outputs that fund a silent payment with the sp1… address the
  // user actually typed (the on-chain output is a derived one-time taproot addr).
  _tagSilentOutputs(summary, spOuts) {
    for (const s of spOuts) {
      if (!s.derivedAddress) continue;
      const o = summary.outputs.find((o) => o.address === s.derivedAddress && !o.silent);
      if (o) o.silent = s.address;
    }
  }

  // Replace each placeholder silent-payment output in a freshly-selected (still
  // unsigned) tx with its real one-time taproot script, derived from the tx's
  // actual inputs per BIP-352.
  _applySilentPayments(tx, spOuts) {
    const byOutpoint = new Map();
    for (const u of this.utxos) byOutpoint.set(utxoId(u), { u, sp: false });
    for (const u of this.spUtxos) byOutpoint.set(utxoId(u), { u, sp: true });
    const spKeys = this.silentPaymentKeys();
    const inputs = [];
    for (let i = 0; i < tx.inputsLength; i++) {
      const inp = tx.getInput(i);
      const e = byOutpoint.get(`${hex.encode(inp.txid)}:${inp.index}`);
      if (!e) throw new Error('Missing key for a silent payment input.');
      // Our own SP coins can fund a silent payment too — they're taproot inputs
      // whose key is d = spend_priv + t_k (committed to with even Y by the script).
      if (e.sp) {
        if (!spKeys) throw new Error('Missing keys for a silent payment input.');
        inputs.push({ txid: e.u.txid, vout: e.u.vout, priv: silentPaymentOutputPrivKey(spKeys.spendPriv, hex.decode(e.u.tweak)), taproot: true });
      } else {
        inputs.push({ txid: e.u.txid, vout: e.u.vout, priv: this.node(e.u.chain, e.u.index).privateKey });
      }
    }
    const scripts = silentPaymentScripts(inputs, spOuts.map((s) => ({ scan: s.scan, spend: s.spend })));
    spOuts.forEach((s, k) => {
      const ph = hex.encode(s.placeholder);
      const idx = tx.outputs.findIndex((o) => hex.encode(o.script) === ph);
      if (idx < 0) throw new Error('Silent payment output not found after selection.');
      tx.updateOutput(idx, { script: scripts[k], amount: tx.outputs[idx].amount }, true);
      s.derivedAddress = btc.Address(this.netCfg.net).encode(btc.OutScript.decode(scripts[k]));
    });
  }

  // True if a built tx spends any of our still-unconfirmed coins — meaning it
  // can't confirm until that parent (ancestor) transaction confirms first.
  spendsUnconfirmed(tx) {
    const pending = new Set(this.utxos.filter((u) => !u.confirmed).map((u) => utxoId(u)));
    if (!pending.size) return false;
    for (let i = 0; i < tx.inputsLength; i++) {
      const inp = tx.getInput(i);
      if (pending.has(`${hex.encode(inp.txid)}:${inp.index}`)) return true;
    }
    return false;
  }

  // Sign every input of an already-built Transaction. BIP84 inputs sign with the
  // matching HD key; received silent-payment outputs are taproot key-path spends
  // signed manually with d = spend_priv + t_k (the output key is used raw, with
  // no BIP-341 tweak, so btc-signer's auto key-path signing doesn't apply).
  sign(tx) {
    if (this.watchOnly) throw new Error('Watch-only wallet — no keys to sign with.');
    const bip84 = new Map();
    for (const u of this.utxos) bip84.set(utxoId(u), u);
    const sp = new Map();
    for (const u of this.spUtxos) sp.set(utxoId(u), u);
    // Prevout scripts + amounts for any taproot (SP) sighash.
    const prevScripts = [];
    const amounts = [];
    for (let i = 0; i < tx.inputsLength; i++) {
      const w = tx.getInput(i).witnessUtxo;
      prevScripts.push(w.script);
      amounts.push(w.amount);
    }
    const spKeys = sp.size ? this.silentPaymentKeys() : null;
    for (let i = 0; i < tx.inputsLength; i++) {
      const inp = tx.getInput(i);
      const id = `${hex.encode(inp.txid)}:${inp.index}`;
      if (bip84.has(id)) {
        const u = bip84.get(id);
        tx.signIdx(this.node(u.chain, u.index).privateKey, i);
      } else if (sp.has(id)) {
        const u = sp.get(id);
        const d = silentPaymentOutputPrivKey(spKeys.spendPriv, hex.decode(u.tweak));
        const hash = tx.preimageWitnessV1(i, prevScripts, btc.SigHash.DEFAULT, amounts);
        tx.updateInput(i, { tapKeySig: schnorr.sign(hash, d) }, true);
      } else {
        throw new Error(`Cannot find key for input ${id}`);
      }
    }
    tx.finalize();
    return tx.hex;
  }

  async broadcast(hexTx) {
    return this.api.broadcast(hexTx);
  }

  // Parse a raw (signed) transaction hex — used by scan-to-broadcast to show a
  // confirmation (txid + outputs) before relaying someone's exported tx.
  parseRawTx(rawHex) {
    const tx = btc.Transaction.fromRaw(hex.decode(rawHex.trim()), { allowUnknownOutputs: true });
    const network = NETS[this.netName].net;
    const outputs = [];
    let total = 0;
    for (let i = 0; i < tx.outputsLength; i++) {
      const o = tx.getOutput(i);
      total += Number(o.amount);
      let address = '';
      try {
        address = btc.Address(network).encode(btc.OutScript.decode(o.script));
      } catch {}
      outputs.push({ address, value: Number(o.amount) });
    }
    return { txid: tx.id, total, outputs };
  }

  // RBF fee bumping, in three steps so the UI can preview a fee per rate before
  // building: prepareBump() fetches + reconstructs the original (async), then
  // planBump()/buildBump() are pure and reuse that prep.

  // Fetch an unconfirmed outgoing tx and reconstruct what's needed to replace it.
  async prepareBump(origTxid) {
    const orig = await this.api.getTx(origTxid);
    if (orig.status && orig.status.confirmed) throw new Error('Transaction already confirmed.');

    const ins = [];
    let totalIn = 0;
    for (const vin of orig.vin || []) {
      const a = vin.prevout && vin.prevout.scriptpubkey_address;
      const p = a && this.addrMap.get(a);
      if (!p) throw new Error('Can only bump your own transactions.');
      totalIn += vin.prevout.value;
      ins.push({ txid: vin.txid, vout: vin.vout, value: vin.prevout.value, chain: p.chain, index: p.index });
    }

    // Our first change-chain output is the change we'll shrink; the rest are
    // recipients and stay fixed.
    const recipients = [];
    let outTotal = 0;
    let changeSeen = false;
    for (const o of orig.vout || []) {
      outTotal += o.value;
      const p = o.scriptpubkey_address && this.addrMap.get(o.scriptpubkey_address);
      if (p && p.chain === 1 && !changeSeen) { changeSeen = true; continue; }
      recipients.push({ address: o.scriptpubkey_address, value: o.value });
    }
    const usedIds = new Set(ins.map((i) => `${i.txid}:${i.vout}`));
    const spare = this.utxos.filter((u) => u.confirmed && !usedIds.has(utxoId(u)));
    return {
      txid: origTxid,
      ins,
      recipients,
      totalIn,
      recipTotal: recipients.reduce((s, r) => s + r.value, 0),
      oldFee: totalIn - outTotal,
      spare,
    };
  }

  // Pure: pick the fee/change (and any extra inputs) for a given rate.
  planBump(prep, feeRate) {
    const rate = Math.max(1, Math.round(feeRate));
    const DUST = 294; // p2wpkh dust
    const vsizeOf = (nIn, nOut) => 11 + 68 * nIn + 31 * nOut;
    const spare = prep.spare.slice();
    const extra = [];
    const compute = () => {
      const nIn = prep.ins.length + extra.length;
      const inAmt = prep.totalIn + extra.reduce((s, u) => s + u.value, 0);
      let nOut = prep.recipients.length + 1;
      let fee = Math.ceil(vsizeOf(nIn, nOut) * rate);
      let change = inAmt - prep.recipTotal - fee;
      if (change < DUST) { nOut = prep.recipients.length; fee = inAmt - prep.recipTotal; change = 0; }
      const minFee = prep.oldFee + vsizeOf(nIn, nOut); // BIP125 incremental relay
      if (change > 0 && fee < minFee) {
        fee = minFee; change = inAmt - prep.recipTotal - fee;
        if (change < DUST) { fee = inAmt - prep.recipTotal; change = 0; }
      }
      return { fee, change, ok: inAmt - prep.recipTotal >= fee && fee > prep.oldFee };
    };
    let pl = compute();
    while (!pl.ok && spare.length) { extra.push(spare.shift()); pl = compute(); }
    return { fee: pl.fee, change: pl.change, extra, ok: pl.ok, rate };
  }

  // Build + sign the replacement at a rate. Returns { hex, txid, fee, oldFee, ... }.
  buildBump(prep, feeRate) {
    const pl = this.planBump(prep, feeRate);
    if (!pl.ok) throw new Error('Not enough funds to bump at this rate. Try a lower rate or CPFP.');
    const allIns = [...prep.ins, ...pl.extra.map((u) => ({ txid: u.txid, vout: u.vout, value: u.value, chain: u.chain, index: u.index }))];
    const t = new btc.Transaction();
    for (const i of allIns) {
      const pay = p2wpkh(this.derive(i.chain, i.index).pubkey, this.netCfg.net);
      t.addInput({ ...pay, txid: i.txid, index: i.vout, sequence: 0xfffffffd, witnessUtxo: { script: pay.script, amount: BigInt(i.value) } });
    }
    for (const r of prep.recipients) t.addOutputAddress(r.address, BigInt(r.value), this.netCfg.net);
    const changeAddr = this.freshChange().address;
    if (pl.change > 0) t.addOutputAddress(changeAddr, BigInt(pl.change), this.netCfg.net);
    for (let k = 0; k < allIns.length; k++) t.signIdx(this.node(allIns[k].chain, allIns[k].index).privateKey, k);
    t.finalize();

    const outputs = prep.recipients.map((r) => ({ address: r.address, value: r.value }));
    if (pl.change > 0) outputs.push({ address: changeAddr, value: pl.change, change: true });
    return { hex: t.hex, txid: t.id, fee: pl.fee, oldFee: prep.oldFee, feeRate: pl.rate, outputs, replaces: prep.txid };
  }

  // --- gift links (coins backing claimable presigned transactions) ---------
  // A gift coin is either RESERVED (set aside, skipped by coin selection) or
  // RECLAIMED (freed for spending, but its link stays live until the coin is
  // actually spent). Both are "outstanding"; both are persisted per-wallet.
  _giftKey() {
    return this._cacheKey() + ':gift';
  }
  _reclaimedKey() {
    return this._cacheKey() + ':giftfree';
  }
  _loadSet(key) {
    try {
      return new Set(JSON.parse(localStorage.getItem(key) || '[]'));
    } catch {
      return new Set();
    }
  }
  reservedSet() {
    if (!this._reserved) this._reserved = this._loadSet(this._giftKey());
    return this._reserved;
  }
  reclaimedSet() {
    if (!this._reclaimed) this._reclaimed = this._loadSet(this._reclaimedKey());
    return this._reclaimed;
  }
  isReserved(id) {
    return this.reservedSet().has(id);
  }
  _saveReserved() {
    try { localStorage.setItem(this._giftKey(), JSON.stringify([...this.reservedSet()])); } catch {}
  }
  _saveReclaimed() {
    try { localStorage.setItem(this._reclaimedKey(), JSON.stringify([...this.reclaimedSet()])); } catch {}
  }

  // ---- Ark support -------------------------------------------------------
  // Persisted ArkManager state (vtxos, in-flight action checkpoints, movement
  // history — no secrets: vtxo keys are re-derived from the seed).
  _arkKey() { return this._cacheKey() + ':ark'; }
  loadArkState() {
    try { return JSON.parse(localStorage.getItem(this._arkKey()) || 'null'); } catch { return null; }
  }
  saveArkState(state) {
    try { localStorage.setItem(this._arkKey(), JSON.stringify(state)); } catch {}
  }

  // ---- Boltz swap support ----------------------------------------------
  // Persisted swap records (public metadata only — keys/preimage are re-derived
  // deterministically from the seed via swapNode, so nothing secret is stored).
  _swapKey() { return this._cacheKey() + ':swaps'; }
  loadSwaps() {
    try { return JSON.parse(localStorage.getItem(this._swapKey()) || '[]'); } catch { return []; }
  }
  saveSwaps(list) {
    try { localStorage.setItem(this._swapKey(), JSON.stringify(list)); } catch {}
  }
  _swapIdxKey() { return this._cacheKey() + ':swapidx'; }
  // Reserve the next swap index: monotonic + persisted on every call. A reverse/
  // submarine attempt that fails AFTER Boltz created the swap (a later validation
  // throw, a dropped response) still burns its index, so a retry can't reuse the
  // same deterministic preimage (Boltz rejects "swap with this preimage exists").
  // Seeded from saved swaps so existing wallets don't regress.
  nextSwapIndex() {
    const fromSaved = this.loadSwaps().reduce((m, s) => Math.max(m, (s.swapIndex ?? -1) + 1), 0);
    let stored = 0;
    try { stored = parseInt(localStorage.getItem(this._swapIdxKey()) || '0', 10) || 0; } catch {}
    const idx = Math.max(fromSaved, stored);
    try { localStorage.setItem(this._swapIdxKey(), String(idx + 1)); } catch {}
    return idx;
  }
  // Deterministic swap keypair on a dedicated chain (2) so swap keys never
  // collide with receive (0) / change (1). Returns the HDKey node (has
  // privateKey + publicKey, 33-byte compressed).
  swapNode(index) {
    return this.account().deriveChild(2).deriveChild(index);
  }
  // Passive reclaim: free the coin for spending but keep tracking the live link
  // so it can still be revoked later (until the coin is spent).
  unreserve(id) {
    this.reservedSet().delete(id);
    this.reclaimedSet().add(id);
    this._saveReserved();
    this._saveReclaimed();
  }

  // Truly revoke an unclaimed gift: spend its coin back into our own wallet,
  // which double-spends the gift's presigned input so the link can't be claimed
  // once this confirms. Uses a high fee to win any race with a claimer.
  async revokeGift(id, feeRate) {
    const draft = this.buildTx({ recipients: [{ address: this.freshChange().address }], feeRate, coinIds: [id], sendMax: true });
    const hexTx = this.sign(draft.tx);
    const txid = await this.broadcast(hexTx);
    this.reservedSet().delete(id);
    this.reclaimedSet().delete(id);
    this._saveReserved();
    this._saveReclaimed();
    return txid;
  }
  // Outstanding gifts (reserved + reclaimed) whose coin is still unspent; prunes
  // any whose coin has since been claimed/spent. { id, reserved, value }.
  outstandingGifts() {
    const live = new Set(this.utxos.map((u) => utxoId(u)));
    const res = this.reservedSet();
    const rec = this.reclaimedSet();
    let changed = false;
    for (const id of [...res]) if (!live.has(id)) { res.delete(id); changed = true; }
    for (const id of [...rec]) if (!live.has(id)) { rec.delete(id); changed = true; }
    if (changed) { this._saveReserved(); this._saveReclaimed(); }
    return [...new Set([...res, ...rec])].map((id) => ({
      id,
      reserved: res.has(id),
      value: (this.utxos.find((u) => utxoId(u) === id) || {}).value,
    }));
  }

  // Persistent gift records (per account): the shareable link/code + amount, so a
  // gift's link/QR can be re-viewed later and a claimed one identified in history.
  _giftRecordsKey() { return this._cacheKey() + ':giftrec'; }
  giftRecords() {
    if (!this._giftRecords) { try { this._giftRecords = JSON.parse(localStorage.getItem(this._giftRecordsKey()) || '{}'); } catch { this._giftRecords = {}; } }
    return this._giftRecords;
  }
  _saveGiftRecords() { try { localStorage.setItem(this._giftRecordsKey(), JSON.stringify(this.giftRecords())); } catch {} }
  recordGift({ code, locked, amount, claimCode, outpoints }) {
    if (!outpoints || !outpoints.length) return;
    this.giftRecords()[outpoints[0]] = { id: outpoints[0], code, locked: !!locked, amount, claimCode: claimCode || null, outpoints, created: Date.now(), revoked: false };
    this._saveGiftRecords();
  }
  giftLink(id) { return this.giftRecords()[id] || null; }
  markGiftRevoked(id) { const r = this.giftRecords()[id]; if (r) { r.revoked = true; this._saveGiftRecords(); } }
  // Gifts whose coin has been spent and weren't revoked by us → claimed. (Only
  // once scanned, so an un-synced wallet doesn't mislabel everything as claimed.)
  claimedGifts() {
    if (!this.loaded) return [];
    const live = new Set(this.utxos.map((u) => utxoId(u)));
    return Object.values(this.giftRecords())
      .filter((r) => !r.revoked && r.outpoints && !r.outpoints.some((o) => live.has(o)))
      .map((r) => ({ id: r.id, amount: r.amount, locked: r.locked, created: r.created }))
      .sort((a, b) => (b.created || 0) - (a.created || 0));
  }

  // Best-fit coin selection for a gift of `gift` sats (needs gift + a dust
  // change): the smallest single confirmed coin that covers it — one input and
  // the least value locked until claim — else the fewest large coins. Returns
  // the selected UTXOs, or null if confirmed funds are insufficient.
  _selectGiftCoins(gift) {
    const DUST = 294n;
    const need = gift + DUST;
    const avail = this.utxos.filter((u) => !this.isReserved(utxoId(u)) && (u.confirmed || u.chain === 1));
    const single = avail.filter((u) => BigInt(u.value) >= need).sort((a, b) => a.value - b.value)[0];
    if (single) return [single];
    const sel = [];
    let sum = 0n;
    for (const u of [...avail].sort((a, b) => b.value - a.value)) {
      sel.push(u);
      sum += BigInt(u.value);
      if (sum >= need) return sel;
    }
    return null; // insufficient confirmed funds
  }

  // Sats that creating this gift right now would lock (the selected coins'
  // total), or null if confirmed funds are insufficient. Lets the UI warn when
  // the lock would dwarf the gift and offer to split a coin first.
  giftLockPreview(amountSats) {
    const sel = this._selectGiftCoins(BigInt(Math.round(amountSats)));
    return sel ? sel.reduce((s, u) => s + u.value, 0) : null;
  }

  // The coins a gift of this amount would lock: total value + how many inputs.
  // A high input count means a costly-to-claim gift (each input adds to the
  // claimer's fee) — the UI uses it to recommend splitting/consolidating first.
  giftCoinSummary(amountSats) {
    const sel = this._selectGiftCoins(BigInt(Math.round(amountSats)));
    return sel ? { lock: sel.reduce((s, u) => s + u.value, 0), count: sel.length } : null;
  }

  // Number of unreserved spendable coins (for the consolidate prompt/action).
  spendableCoinCount() {
    return this.utxos.filter((u) => !this.isReserved(utxoId(u)) && (u.confirmed || u.chain === 1)).length;
  }

  // Merge all unreserved spendable coins into one, via a max self-send. Leaves
  // the wallet with a single coin so future sends/gifts use one input.
  async consolidate(feeRate) {
    const rate = Math.max(1, Math.round(feeRate));
    const draft = this.buildTx({ recipients: [{ address: this.freshReceive().address }], feeRate: rate, sendMax: true });
    const hex = this.sign(draft.tx);
    await this.broadcast(hex);
    return { txid: draft.tx.id, inputs: draft.inputsCount };
  }

  // Build a signed gift from already-chosen coins. If the gift leaves a viable
  // (>= dust) change, output0 is that change back to us, cryptographically fixed
  // by signing input0 SIGHASH_SINGLE (the rest SIGHASH_NONE) — so our change is
  // locked while the claimer is free to add their own output. If there's no
  // viable change (a whole-balance gift), there's no output at all and every
  // input is SIGHASH_NONE, so the claimer sweeps the entire amount. Reserves the
  // coins; returns { code, amount, reserved } where amount is what the claimer
  // receives before their fee (the gift, or the whole swept sum).
  _buildGiftPsbt(sel, gift) {
    const DUST = 294n;
    const sum = sel.reduce((s, u) => s + BigInt(u.value), 0n);
    const change = sum - gift;
    const keepChange = change >= DUST;
    const sigOf = (i) => (keepChange && i === 0 ? btc.SigHash.SINGLE : btc.SigHash.NONE);
    const t = new btc.Transaction({ allowUnknownOutputs: true });
    sel.forEach((u, i) => {
      const pay = p2wpkh(this.derive(u.chain, u.index).pubkey, this.netCfg.net);
      t.addInput({ ...pay, txid: u.txid, index: u.vout, sighashType: sigOf(i), witnessUtxo: { script: pay.script, amount: BigInt(u.value) } });
    });
    if (keepChange) t.addOutputAddress(this.freshChange().address, change, this.netCfg.net);
    sel.forEach((u, i) => t.signIdx(this.node(u.chain, u.index).privateKey, i, [sigOf(i)]));

    for (const u of sel) this.reservedSet().add(utxoId(u));
    this._saveReserved();
    return { code: base32nopad.encode(_encodeCompactGift(t)), amount: Number(keepChange ? gift : sum), reserved: sel.map(utxoId) };
  }

  // Gift the entire spendable balance: a no-change sweep of all unreserved
  // spendable coins (confirmed, plus our own unconfirmed change). The claimer
  // receives the whole amount minus their claim fee.
  createGiftAll(feeRate) {
    const rate = Math.max(1, Math.round(feeRate));
    const sel = this.utxos.filter((u) => !this.isReserved(utxoId(u)) && (u.confirmed || u.chain === 1));
    if (!sel.length) throw new Error('No coins available to gift.');
    const sum = sel.reduce((s, u) => s + BigInt(u.value), 0n);
    if (sum < BigInt(giftMinimum(rate))) throw new Error('Gift amount is too small.');
    return this._buildGiftPsbt(sel, sum); // change = 0 → no-change sweep
  }

  // Build a gift link from a best-fit coin, locking the least value. No fee is
  // reserved here: the claimer's wallet looks up the fee rate at claim time and
  // subtracts it from the amount.
  createGift(amountSats, feeRate) {
    const gift = BigInt(Math.round(amountSats));
    const rate = Math.max(1, Math.round(feeRate));
    if (gift < BigInt(giftMinimum(rate))) throw new Error('Gift amount is too small.');
    const sel = this._selectGiftCoins(gift);
    if (!sel) throw new Error('Not enough confirmed funds for that gift amount.');
    return this._buildGiftPsbt(sel, gift);
  }

  // Our nostr identity (used to DM a locked gift's claim code to the recipient).
  nostrPubkey() { return (this.nostr && this.nostr.pk) || null; }
  nostrNpub() { const pk = this.nostrPubkey(); return pk ? npubOf(pk) : null; }
  // Send a nostr DM (e.g. a locked gift's claim code) to a recipient pubkey.
  async sendNostrDM(recipientPkHex, text) {
    return this.nostr && this.nostr.sk ? this.nostr.sendDM(recipientPkHex, text) : false;
  }

  // Split + gift in one shot, with no confirmation wait: broadcast a self-send
  // that carves out a gift+dust coin, then build the gift spending that
  // still-unconfirmed carve-out. The funding and the claim form a chain that
  // confirms together; the recipient just sees a pending balance until the
  // split confirms. Lets the sender lock only ~the gift amount (instead of a
  // whole large coin) without waiting for the split to confirm first.
  async createGiftFromSplit(amountSats, feeRate) {
    const gift = Math.round(amountSats);
    const rate = Math.max(1, Math.round(feeRate));
    if (BigInt(gift) < BigInt(giftMinimum(rate))) throw new Error('Gift amount is too small.');
    const DUST = 294;
    const recvIndex = this.nextReceiveIndex;
    const carveAddr = this.derive(0, recvIndex).address;
    const changeIndex = this.nextChangeIndex;

    // Carve out exactly gift + dust to one of our own addresses; the rest comes
    // back as change. buildTx already spends confirmed coins largest-first.
    const draft = this.buildTx({ recipients: [{ address: carveAddr, amount: gift + DUST }], feeRate: rate });
    const carveIdx = draft.outputs.findIndex((o) => o.address === carveAddr);
    if (carveIdx < 0) throw new Error('Could not size the split output.');
    const hexTx = this.sign(draft.tx);
    const splitTxid = draft.tx.id;
    await this.broadcast(hexTx);

    // Wait until the carve-out is actually visible in the mempool before we
    // build the gift on top of it and reserve it. Otherwise a background refresh
    // could rebuild the address from a not-yet-indexed API response, transiently
    // drop the coin, and prune the reservation — risking a double-spend.
    let seen = false;
    for (let i = 0; i < 8 && !seen; i++) {
      await sleep(i === 0 ? 400 : 900);
      try {
        const us = await this.api.addressUtxos(carveAddr);
        seen = us.some((u) => u.txid === splitTxid && u.vout === carveIdx);
      } catch {}
    }
    if (!seen) throw new Error('The split is taking a while to propagate. Once it confirms, create the gift from the new coin.');

    // Reflect the split in our coin set — drop the spent inputs, add the
    // (now mempool-visible) carve-out and change — so balances and gift tracking
    // are correct immediately; a background scan reconciles the rest.
    const spent = new Set();
    for (let i = 0; i < draft.tx.inputsLength; i++) {
      const inp = draft.tx.getInput(i);
      spent.add(`${hex.encode(inp.txid)}:${inp.index}`);
    }
    this.utxos = this.utxos.filter((u) => !spent.has(utxoId(u)));
    this.utxos.push({ txid: splitTxid, vout: carveIdx, value: gift + DUST, address: carveAddr, chain: 0, index: recvIndex, confirmed: false });
    const changeIdx = draft.outputs.findIndex((o, i) => i !== carveIdx);
    if (changeIdx >= 0) {
      const co = draft.outputs[changeIdx];
      this.utxos.push({ txid: splitTxid, vout: changeIdx, value: co.amount, address: co.address, chain: 1, index: changeIndex, confirmed: false });
    }
    this._recomputeBalanceFromUtxos();

    return this._buildGiftPsbt([{ txid: splitTxid, vout: carveIdx, value: gift + DUST, chain: 0, index: recvIndex }], BigInt(gift));
  }

  // --- realtime (mempool.space WebSocket) ---------------------------------
  // Pushes us new mempool/confirmed transactions for our addresses so history
  // and balances update with no polling.
  wsUrl() {
    // Electrum backend (any network): pick the current failover candidate for the
    // active network (rotated on failure). Esplora backend has no push → poll.
    if (getBackend() === 'electrum') {
      if (!this._wsCandidates || !this._wsCandidates.length) { this._wsCandidates = electrumCandidates(this.netName); this._wsCandIdx = 0; }
      const list = this._wsCandidates;
      return list.length ? absWsUrl(list[(this._wsCandIdx || 0) % list.length]) : null;
    }
    return null;
  }

  // What realtime watches: the fresh frontier (next receive + next change), plus
  // any address holding an unconfirmed coin — so a pending deposit's confirmation
  // pushes instantly instead of waiting for a poll. Returns derivation targets
  // ({chain,index}); Electrum/Fulcrum handles many subscriptions, but our watched
  // set is naturally small so we cap generously.
  _watchedTargets() {
    const seen = new Set();
    const out = [];
    const add = (chain, index) => {
      const k = chain + '/' + index;
      if (!seen.has(k)) { seen.add(k); out.push({ chain, index }); }
    };
    add(0, this.nextReceiveIndex);
    add(1, this.nextChangeIndex);
    const stuck = this._stuckTxids();
    for (const u of this.utxos) {
      if (out.length >= 25) break;
      if (!u.confirmed && !stuck.has(u.txid)) add(u.chain, u.index);
    }
    return out;
  }
  watchedAddresses() {
    return this._watchedTargets().map((t) => this.derive(t.chain, t.index).address);
  }
  // Electrum scripthash for one of our addresses: sha256(scriptPubKey), reversed,
  // hex. This is what Fulcrum subscribes on.
  _scripthash(chain, index) {
    const h = sha256(this.derive(chain, index).script);
    h.reverse();
    return hex.encode(h);
  }
  watchedScripthashes() {
    // Also (re)build the scripthash -> derivation map so a data-carrying
    // notification can be credited without re-deriving or hitting REST.
    const map = new Map();
    const shes = this._watchedTargets().map((t) => {
      const sh = this._scripthash(t.chain, t.index);
      map.set(sh, { chain: t.chain, index: t.index, address: this.derive(t.chain, t.index).address });
      return sh;
    });
    this._shToTarget = map;
    return shes;
  }

  // Apply a watcher push directly (no REST). The push carries the matched
  // outputs (vout + value), the confirmed flag, and — when confirmed — the block
  // time. Returns false only if we can't map the scripthash (caller then scans).
  _applyTxNotification(sh, data) {
    const tgt = this._shToTarget && this._shToTarget.get(sh);
    if (!tgt || !data || !Array.isArray(data.outputs)) return false;
    let changed = false;

    // (1) Confirmation of a tx we already track: flip its history row and coins
    // to confirmed. Works for incoming AND outgoing — it only flips flags (no new
    // coin), so there's no overcount risk regardless of chain.
    if (data.confirmed) {
      const tx = this.txs.find((t) => t.txid === data.txid);
      if (tx && !tx.confirmed) {
        tx.confirmed = true;
        if (data.blockTime) tx.blockTime = data.blockTime;
        changed = true;
      }
      for (const o of data.outputs) {
        const u = this.utxos.find((x) => utxoId(x) === `${data.txid}:${o.vout}`);
        if (u && !u.confirmed) {
          u.confirmed = true;
          const e = (u.chain === 0 ? this.receive : this.change).find((a) => a.index === u.index);
          if (e) { e.pending = Math.max(0, (e.pending || 0) - o.value); e.confirmed = (e.confirmed || 0) + o.value; }
          changed = true;
        }
      }
    }

    // (2) New incoming receive (chain 0 only): credit the coin + a pending
    // history row so the balance and "payment received" fire instantly. Change
    // (chain 1) is our own send — its spent input isn't in the push, so crediting
    // it alone would transiently overcount; the backstop poll reconciles it.
    if (tgt.chain === 0) {
      let entry = this.receive.find((e) => e.index === tgt.index);
      if (!entry) {
        entry = { chain: 0, index: tgt.index, address: tgt.address, used: false, confirmed: 0, pending: 0 };
        this.receive.push(entry);
        this.addrMap.set(tgt.address, { chain: 0, index: tgt.index });
      }
      let credited = 0;
      for (const o of data.outputs) {
        if (this.utxos.find((u) => utxoId(u) === `${data.txid}:${o.vout}`)) continue;
        this.utxos.push({ txid: data.txid, vout: o.vout, value: o.value, address: tgt.address, chain: 0, index: tgt.index, confirmed: !!data.confirmed });
        entry.used = true;
        if (data.confirmed) entry.confirmed = (entry.confirmed || 0) + o.value;
        else entry.pending = (entry.pending || 0) + o.value;
        credited += o.value;
        changed = true;
      }
      if (credited > 0 && !this.txs.find((t) => t.txid === data.txid)) {
        this.txs.push({ txid: data.txid, net: credited, fee: 0, vsize: 0, confirmed: !!data.confirmed, blockTime: data.blockTime || 0, blockHeight: 0, firstSeen: data.confirmed ? 0 : Date.now() });
      }
    }

    if (!changed) return true; // nothing new (duplicate push) — handled, no scan
    this.nextReceiveIndex = firstUnused(this.receive);
    this.nextChangeIndex = firstUnused(this.change);
    this.utxos.sort((a, b) => b.value - a.value);
    this._sortTxs();
    this._recomputeBalanceFromUtxos();
    this.loaded = true;
    this.saveCache();
    this.retrack(); // a new frontier address may need subscribing
    this.emit();    // UI updates NOW; the 30s backstop poll fills blockHeight/fee
    return true;
  }

  // Credit an on-chain receive we produced ourselves (a reverse-swap claim) the
  // instant we broadcast it — so the balance + generic "payment received" fire
  // without waiting for the next scan, exactly like the watcher does for inbound
  // payments. `address` must be one of our receive (chain-0) addresses; returns
  // false (caller relies on the scan) if it isn't known or the coin already exists.
  creditReceive({ txid, vout, value, address }) {
    let entry = this.receive.find((e) => e.address === address);
    if (!entry) {
      const info = this.addrMap.get(address);
      if (info && info.chain === 0) entry = this.receive.find((e) => e.index === info.index);
    }
    if (!entry) return false;
    if (this.utxos.find((u) => utxoId(u) === `${txid}:${vout}`)) return false;
    this.utxos.push({ txid, vout, value, address, chain: 0, index: entry.index, confirmed: false });
    entry.used = true;
    entry.pending = (entry.pending || 0) + value;
    if (!this.txs.find((t) => t.txid === txid)) {
      this.txs.push({ txid, net: value, fee: 0, vsize: 0, confirmed: false, blockTime: 0, blockHeight: 0, firstSeen: Date.now() });
    }
    this.nextReceiveIndex = firstUnused(this.receive);
    this.utxos.sort((a, b) => b.value - a.value);
    this._sortTxs();
    this._recomputeBalanceFromUtxos();
    this.loaded = true;
    this.saveCache();
    this.retrack();
    this.emit();
    return true;
  }

  // Optimistically reflect a just-broadcast outgoing tx so the balance and
  // history update instantly instead of waiting for the post-send rescan: drop
  // the spent coins, credit our change as pending, and add a pending history
  // row. The realtime watcher / backstop poll reconciles it (and fills in the
  // confirmation) once the explorer has indexed the tx. `tx` is the finalized
  // btc.Transaction we just signed and broadcast.
  applySentTx(tx) {
    const txid = tx.id;
    if (this.txs.find((t) => t.txid === txid)) return; // already applied
    const byOutpoint = new Map();
    for (const u of this.utxos) byOutpoint.set(utxoId(u), u);

    let inSum = 0;
    const spent = new Set();
    for (let i = 0; i < tx.inputsLength; i++) {
      const inp = tx.getInput(i);
      const id = `${hex.encode(inp.txid)}:${inp.index}`;
      const u = byOutpoint.get(id);
      if (!u) {
        // Not in our current utxo set (e.g. dropped by a concurrent rescan), but
        // we built + signed this tx so the input is ours — count its value from
        // the witness utxo so the spend total isn't undercounted.
        if (inp.witnessUtxo) inSum += Number(inp.witnessUtxo.amount);
        continue;
      }
      inSum += u.value;
      spent.add(id);
      const e = (u.chain === 0 ? this.receive : this.change).find((a) => a.index === u.index);
      if (e) { if (u.confirmed) e.confirmed = Math.max(0, (e.confirmed || 0) - u.value); else e.pending = Math.max(0, (e.pending || 0) - u.value); }
    }
    this.utxos = this.utxos.filter((u) => !spent.has(utxoId(u)));

    let outSum = 0, change = 0;
    for (let i = 0; i < tx.outputsLength; i++) {
      const o = tx.getOutput(i);
      outSum += Number(o.amount);
      let addr;
      try { addr = btc.Address(this.netCfg.net).encode(btc.OutScript.decode(o.script)); } catch {}
      const info = addr && this.addrMap.get(addr);
      if (!info) continue; // recipient output — not ours
      this.utxos.push({ txid, vout: i, value: Number(o.amount), address: addr, chain: info.chain, index: info.index, confirmed: false });
      const e = (info.chain === 0 ? this.receive : this.change).find((a) => a.index === info.index);
      if (e) { e.pending = (e.pending || 0) + Number(o.amount); e.used = true; }
      change += Number(o.amount);
    }

    this.txs.unshift({ txid, net: change - inSum, fee: inSum - outSum, vsize: tx.weight ? Math.ceil(tx.weight / 4) : 0, confirmed: false, blockTime: 0, blockHeight: 0, firstSeen: Date.now(), local: true });
    this.nextReceiveIndex = firstUnused(this.receive);
    this.nextChangeIndex = firstUnused(this.change);
    this.utxos.sort((a, b) => b.value - a.value);
    this._sortTxs();
    this._recomputeBalanceFromUtxos();
    this.loaded = true;
    this.saveCache();
    this.retrack();
    this.emit();
  }

  startRealtime() {
    if (this.offline) return;
    this.stopRealtime();
    this._wsCandidates = null; // rebuild the failover list fresh (picks up config), prefer primary
    this._wsCandIdx = 0;
    // Frontier poll — now purely a safety net. The watcher pushes incoming
    // payments AND confirmations instantly with full data (credited via the WS
    // with no REST), so when the socket is live we poll rarely (~30s) just in
    // case a push was missed. When the socket is DOWN we poll faster: ~5s on the
    // Receive tab (user is actively waiting) or while a coin is unconfirmed, else
    // ~10s. This keeps mempool.space REST (and its 429s) to a trickle.
    this._pollTimer = setInterval(() => {
      if (this.offline) return;
      const stuck = this._stuckTxids();
      const pending = this.utxos.some((u) => !u.confirmed && !stuck.has(u.txid));
      let due;
      if (this.live) {
        due = 30000; // WS handles the real work; this is a backstop only
      } else if (this._watchReceive || pending) {
        due = 5000;  // socket down + actively waiting → poll responsively
      } else {
        due = 10000;
      }
      if (Date.now() - (this._lastPoll || 0) < due) return;
      this._lastPoll = Date.now();
      this.refreshLive();
      // SP receipts arrive via the indexer WebSocket (_spConnect); only poll for
      // them as a fallback when that socket isn't live.
      if (!this.spLive) this.scanSilentPayments({ silent: true }).catch(() => {});
    }, 1000);
    this._spConnect(); // live push of silent-payment receipts
    // No periodic full re-scan: the WS (and the frontier poll above) keep the
    // balance current, and refreshLive's _reconcileHeld catches spends of held
    // coins. The only thing neither covers is a deposit to a reused old address,
    // which is handled on demand via per-address rescan in Settings.
    // Only mempool.space has a live socket; other explorers rely on the poll
    // above (wsUrl returns null → no socket).
    if (typeof WebSocket === 'undefined' || !this.wsUrl()) return;
    this._wsWant = true;

    // Heartbeat: ping every 10s; if nothing comes back (incl. our own pong) for
    // 21s the socket is half-open (died without firing onclose) — recycle it.
    // The trigger is two unanswered pings, so one slow round-trip won't churn,
    // but a silently-dead socket now recovers in ~20s instead of ~45s.
    this._hbTimer = setInterval(() => {
      if (this.offline || !this._ws || this._ws.readyState !== 1) return;
      if (Date.now() - this._lastMsg > 21000) {
        this._reconnectNow();
      } else {
        this._rpcSend('server.ping', []);
      }
    }, 10000);

    // Reconnect + refresh when the tab refocuses or the network returns.
    if (!this._wakeHooked && typeof document !== 'undefined') {
      this._wakeHooked = true;
      const wake = () => {
        if (this.offline || !this._wsWant) return;
        if (!this._ws || this._ws.readyState !== 1) this._reconnectNow();
        this.scan({ silent: true }).catch(() => {});
      };
      document.addEventListener('visibilitychange', () => {
        if (document.visibilityState === 'visible') wake();
      });
      window.addEventListener('online', wake);
    }

    this._connectWs();
  }

  _reconnectNow() {
    clearTimeout(this._wsRetry);
    if (this._ws) {
      try {
        this._ws.onclose = null;
        this._ws.close();
      } catch {}
      this._ws = null;
    }
    // onclose was nulled above so it won't fire — fail in-flight calls here too.
    this._rejectPending('socket recycled');
    this.live = false;
    this._connectWs();
  }

  _connectWs() {
    if (!this._wsWant) return;
    let ws;
    try {
      ws = new WebSocket(this.wsUrl());
    } catch {
      this._scheduleReconnect();
      return;
    }
    this._ws = ws;
    this._wsBuf = '';            // partial-line accumulator (newline-delimited JSON-RPC)
    this._subscribed = new Set(); // scripthashes subscribed on this connection
    this._wsOpenedAt = 0;        // set on open; used to judge a healthy connection for failover
    if (this._rpcId == null) this._rpcId = 0; // monotonic across reconnects (don't alias pending ids)
    ws.onopen = () => {
      this.live = true;
      this._wsOpenedAt = Date.now();
      this._wsBackoff = 0; // healthy again — reset the reconnect backoff
      this._lastMsg = Date.now();
      // Electrum handshake, then subscribe our watched scripthashes.
      this._rpcSend('server.version', ['halwallet', '1.4']);
      // Flush any data calls queued while the socket was down.
      if (this._callQueue && this._callQueue.length) {
        for (const payload of this._callQueue) { try { ws.send(payload); } catch {} }
        this._callQueue = [];
      }
      this.retrack();
      this.emit();
      // The server only pushes activity AFTER we subscribe, so reconcile once on
      // open to catch anything that landed while we were disconnected.
      this.refreshLive().catch(() => {});
    };
    ws.onmessage = (ev) => {
      this._lastMsg = Date.now();
      this._wsBuf += (typeof ev.data === 'string' ? ev.data : new TextDecoder().decode(ev.data));
      // Robustly extract every complete top-level JSON object from the buffer,
      // regardless of framing: newline-delimited (coinos watcher), one-per-frame
      // without a newline (electrs), several concatenated in one frame, or a
      // single object split across frames. Brace-depth scan, string-aware.
      const s = this._wsBuf;
      let depth = 0, inStr = false, esc = false, start = -1, consumed = 0;
      for (let i = 0; i < s.length; i++) {
        const ch = s[i];
        if (inStr) { if (esc) esc = false; else if (ch === '\\') esc = true; else if (ch === '"') inStr = false; continue; }
        if (ch === '"') inStr = true;
        else if (ch === '{') { if (depth === 0) start = i; depth++; }
        else if (ch === '}' && depth > 0) { if (--depth === 0 && start >= 0) { this._handleRpc(s.slice(start, i + 1)); consumed = i + 1; start = -1; } }
      }
      this._wsBuf = s.slice(consumed);
      if (this._wsBuf.length > 1 << 20) this._wsBuf = ''; // runaway guard
    };
    ws.onerror = () => {
      try {
        ws.close();
      } catch {}
    };
    ws.onclose = () => {
      this.live = false;
      this._ws = null;
      // Fail any in-flight data calls so the _rpcCall pump frees its slots
      // immediately; otherwise dead calls hold the pump until they time out and
      // the post-reconnect refresh stalls behind them (~10s of stale UI).
      this._rejectPending('socket closed');
      this.emit();
      this._scheduleReconnect();
    };
  }

  // Send an Electrum JSON-RPC request (fire-and-forget; we react to notifications,
  // not responses). Newline-terminated per the protocol.
  _rpcSend(method, params) {
    if (!this._ws || this._ws.readyState !== 1) return;
    // Coerce to a number defensively: a non-numeric _rpcId serializes id as
    // null, which the response matcher (msg.id != null) drops — silently
    // breaking every data call (and thus reconciles).
    const id = (this._rpcId = (this._rpcId || 0) + 1);
    try {
      this._ws.send(JSON.stringify({ id, method, params }) + '\n');
    } catch {}
    return id;
  }

  // Electrum request/response (used by the ElectrumApi data backend). Resolves
  // when the matching id comes back; queues until the socket is open, and times
  // out so a wedged call can't hang a scan. ids are monotonic for the session so
  // they never alias a fire-and-forget _rpcSend id.
  // Public Electrum entry point. Throttled so a scan doesn't fire a burst that a
  // rate-limited public server would drop — Electrum pipelines requests, so a few
  // in flight is plenty (and fast). Excess calls queue for a free slot.
  _rpcCall(method, params) {
    return new Promise((resolve, reject) => {
      (this._rpcQueue || (this._rpcQueue = [])).push({ method, params, resolve, reject });
      this._rpcPump();
    });
  }
  _rpcPump() {
    if (this._rpcActive == null) this._rpcActive = 0;
    const MAX = 4;
    while (this._rpcActive < MAX && this._rpcQueue && this._rpcQueue.length) {
      const job = this._rpcQueue.shift();
      this._rpcActive++;
      this._rpcSendCall(job.method, job.params).then(job.resolve, job.reject).finally(() => { this._rpcActive--; this._rpcPump(); });
    }
  }
  // The actual request: send, await the matching response, time out, and retry a
  // couple of times on a fresh id (a public server can drop a response or the
  // socket can flap mid-call).
  _rpcSendCall(method, params, attempt = 0) {
    return new Promise((resolve, reject) => {
      if (this.offline) { reject(new Error('offline')); return; }
      const id = (this._rpcId = (this._rpcId || 0) + 1);
      if (!this._pending) this._pending = new Map();
      const timer = setTimeout(() => {
        if (!this._pending.delete(id)) return;
        if (attempt < 2 && !this.offline) this._rpcSendCall(method, params, attempt + 1).then(resolve, reject);
        else reject(new Error('electrum timeout: ' + method));
      }, 12000);
      this._pending.set(id, { resolve, reject, timer });
      const payload = JSON.stringify({ id, method, params }) + '\n';
      if (this._ws && this._ws.readyState === 1) {
        try { this._ws.send(payload); } catch {}
      } else {
        (this._callQueue = this._callQueue || []).push(payload);
      }
    });
  }

  _rejectPending(reason) {
    if (this._pending) {
      for (const { reject, timer } of this._pending.values()) { clearTimeout(timer); try { reject(new Error(reason)); } catch {} }
      this._pending.clear();
    }
    if (this._rpcQueue) {
      for (const job of this._rpcQueue) { try { job.reject(new Error(reason)); } catch {} }
      this._rpcQueue = [];
    }
    this._rpcActive = 0;
  }

  // A notification means a tx touched one of our addresses (a deposit, or a
  // confirmation). If it carries the tx data (our watcher does), credit it
  // instantly with no REST on the critical path; otherwise just trigger a scan.
  _handleRpc(line) {
    let msg;
    try { msg = JSON.parse(line); } catch { return; }
    if (!msg) return;
    // Response to a data call (ElectrumApi backend)?
    if (msg.id != null && this._pending && this._pending.has(msg.id)) {
      const p = this._pending.get(msg.id);
      this._pending.delete(msg.id);
      clearTimeout(p.timer);
      if (msg.error) p.reject(new Error(typeof msg.error === 'string' ? msg.error : (msg.error.message || JSON.stringify(msg.error))));
      else p.resolve(msg.result);
      return;
    }
    // Subscription notification: a tx touched a watched address. Our coinos
    // watcher carries the tx data (credit instantly); a real Electrum server
    // sends only [scripthash, status], so reconcile via the data backend.
    if (msg.method !== 'blockchain.scripthash.subscribe') return;
    const sh = msg.params && msg.params[0];
    if (msg.data && sh && this._applyTxNotification(sh, msg.data)) return;
    this._scheduleRefresh();
  }

  // Subscribe any watched scripthashes not yet subscribed on this connection.
  // Reset on reconnect (_subscribed is cleared in _connectWs), so a fresh socket
  // re-subscribes the full set.
  retrack() {
    if (!this._ws || this._ws.readyState !== 1) return;
    if (!this._subscribed) this._subscribed = new Set();
    for (const sh of this.watchedScripthashes()) {
      if (this._subscribed.has(sh)) continue;
      this._subscribed.add(sh);
      this._rpcSend('blockchain.scripthash.subscribe', [sh]);
    }
  }

  _scheduleReconnect() {
    if (!this._wsWant) return;
    // Electrum failover: if this connection never became healthy (failed to open,
    // or died within a few seconds), advance to the next candidate server.
    if (getBackend() === 'electrum' && this._wsCandidates && this._wsCandidates.length > 1) {
      if (!this._wsOpenedAt || Date.now() - this._wsOpenedAt < 5000) this._wsCandIdx = (this._wsCandIdx || 0) + 1;
    }
    clearTimeout(this._wsRetry);
    // Exponential backoff starting small, so a first attempt that's transiently
    // rejected (e.g. a stale rate-limit) retries in ~0.6s instead of a flat 4s —
    // the wallet reaches Live quickly. Reset to 0 on a successful open.
    this._wsBackoff = Math.min((this._wsBackoff || 0) + 1, 6);
    const delay = Math.min(600 * 2 ** (this._wsBackoff - 1), 15000);
    this._wsRetry = setTimeout(() => this._connectWs(), delay);
  }

  // Debounced: a payment may touch several of our addresses in one go.
  // Reconcile incrementally (frontier only) — never re-scans old coins.
  _scheduleRefresh() {
    clearTimeout(this._refreshTimer);
    this._refreshTimer = setTimeout(async () => {
      try {
        await this.refreshLive();
        this.retrack();
      } catch {}
    }, 400);
  }

  stopRealtime() {
    this._wsWant = false;
    this.live = false;
    this._spDisconnect();
    this._rejectPending('realtime stopped'); // fail any in-flight Electrum data calls
    this._callQueue = [];
    clearTimeout(this._wsRetry);
    clearTimeout(this._refreshTimer);
    clearInterval(this._pollTimer);
    clearInterval(this._deepTimer);
    clearInterval(this._hbTimer);
    clearTimeout(this._nostrPubTimer);
    if (this._ws) {
      try {
        this._ws.onclose = null;
        this._ws.close();
      } catch {}
      this._ws = null;
    }
  }

  // --- local history cache ------------------------------------------------
  // Cache the scanned state in localStorage, keyed by a hash of the seed (the
  // seed itself is never stored). Re-importing the same seed in this browser
  // then shows the last-known balance/history instantly while a fresh scan
  // runs in the background.
  _cacheKey() {
    const id = this.watchOnly ? this.xpub : this.xprv ? this.xprv : `${this.mnemonic}\n${this.passphrase}`;
    const bytes = new TextEncoder().encode(id);
    return 'btc-wallet-cache:' + hex.encode(sha256(bytes)).slice(0, 32);
  }

  // The fresh receive index the "payment received" screen has been shown for.
  // Persisted (and advanced as soon as the celebration appears) so a payment
  // celebrates once and never reappears on a refresh or reopen.
  getReceiveAck() {
    try {
      const v = localStorage.getItem(this._cacheKey() + ':ack');
      return v == null ? null : Number(v);
    } catch {
      return null;
    }
  }

  setReceiveAck(i) {
    try {
      localStorage.setItem(this._cacheKey() + ':ack', String(i));
    } catch {}
  }

  // The serializable wallet state, shared by the localStorage cache and the
  // Nostr sync. savedAt lets us pick the newest copy across devices.
  _snapshot() {
    return {
      v: 1,
      savedAt: Date.now(),
      receive: this.receive,
      change: this.change,
      utxos: this.utxos,
      txs: this.txs,
      nextReceiveIndex: this.nextReceiveIndex,
      nextChangeIndex: this.nextChangeIndex,
      feeRates: this.feeRates,
      spUtxos: this.spUtxos,
      lastSpScan: this.lastSpScan,
    };
  }

  _applySnapshot(d) {
    this.receive = d.receive || [];
    this.change = d.change || [];
    this.utxos = d.utxos || [];
    this.txs = d.txs || [];
    this._sortTxs(); // a cache saved before the firstSeen-ordering fix may be stale
    this.nextReceiveIndex = d.nextReceiveIndex || 0;
    this.nextChangeIndex = d.nextChangeIndex || 0;
    this.feeRates = d.feeRates || this.feeRates;
    this.spUtxos = d.spUtxos || [];
    this.lastSpScan = d.lastSpScan || 0;
    this.addrMap = new Map();
    for (const a of [...this.receive, ...this.change]) {
      this.addrMap.set(a.address, { chain: a.chain, index: a.index });
    }
    this._recomputeBalanceFromChains();
    this._savedAt = d.savedAt || 0;
    this.loaded = true;
  }

  // A cache key derived from the account xpub (not the seed) — the same key a
  // watch-only load of this wallet would use. A full wallet also writes its cache
  // here so that, if the session is wiped and the wallet reopens as watch-only,
  // its balance/history shows instantly instead of needing a rescan.
  _xpubCacheKey() {
    const bytes = new TextEncoder().encode(this.accountXpub());
    return 'btc-wallet-cache:' + hex.encode(sha256(bytes)).slice(0, 32);
  }

  saveCache() {
    const snap = this._snapshot();
    this._savedAt = snap.savedAt;
    try {
      localStorage.setItem(this._cacheKey(), JSON.stringify(snap));
      const xk = this._xpubCacheKey();
      if (xk !== this._cacheKey()) localStorage.setItem(xk, JSON.stringify(snap)); // watch-only mirror
    } catch {}
    // Push to the configured relays too (debounced), so other devices get the
    // update — unless cross-device sync is turned off.
    const sync = getSyncConfig();
    if (!this.offline && sync.enabled) {
      this.nostr.setRelays(sync.relays);
      clearTimeout(this._nostrPubTimer);
      this._nostrPubTimer = setTimeout(() => this.nostr.publish(snap), 2500);
    }
  }

  restoreCache() {
    try {
      let raw = localStorage.getItem(this._cacheKey());
      // A wallet just upgraded from watch-only (seed re-entered) has no seed-keyed
      // cache yet — fall back to the xpub mirror so it shows instantly.
      if (!raw && !this.watchOnly) raw = localStorage.getItem(this._xpubCacheKey());
      if (!raw) return false;
      this._applySnapshot(JSON.parse(raw));
      this.emit();
      return true;
    } catch {
      return false;
    }
  }

  // Pull the latest state from Nostr; apply it if it's newer than what we have.
  // Returns true if state was applied (so the caller can skip a full scan).
  async syncFromNostr() {
    const sync = getSyncConfig();
    if (this.offline || !sync.enabled) return false;
    this.nostr.setRelays(sync.relays);
    let remote;
    try {
      remote = await this.nostr.fetch();
    } catch {
      return false;
    }
    if (!remote) return false;
    if ((remote.savedAt || 0) > (this._savedAt || 0)) {
      this._applySnapshot(remote);
      this.saveCache(); // mirror into localStorage
      this.emit();
      return true;
    }
    // Our local copy is newer (or equal) — push it up so the relay catches up.
    if ((this._savedAt || 0) > (remote.savedAt || 0)) this.saveCache();
    return true; // remote existed, so no full scan needed
  }

  // --- offline snapshot ---------------------------------------------------
  // Exported on the ONLINE device. Contains no secrets — just what an offline
  // signer needs: coins, fee rates, and which addresses are next/fresh.
  exportSnapshot() {
    return {
      app: 'bitcoin-wallet',
      version: 1,
      netName: this.netName,
      exportedAt: new Date().toISOString(),
      feeRates: this.feeRates,
      nextReceiveIndex: this.nextReceiveIndex,
      nextChangeIndex: this.nextChangeIndex,
      utxos: this.utxos.map((u) => ({
        txid: u.txid,
        vout: u.vout,
        value: u.value,
        address: u.address,
        confirmed: u.confirmed,
      })),
    };
  }

  // Imported on the OFFLINE device (which already has the seed loaded).
  importSnapshot(snap) {
    if (!snap || !Array.isArray(snap.utxos))
      throw new Error('Not a valid wallet snapshot file.');
    if (snap.netName && snap.netName !== this.netName)
      throw new Error(
        `Snapshot is for ${snap.netName} but wallet is ${this.netName}.`
      );

    this.feeRates = snap.feeRates || this.feeRates;
    this.nextReceiveIndex = snap.nextReceiveIndex || 0;
    this.nextChangeIndex = snap.nextChangeIndex || 0;

    // Derive a generous window so every UTXO address resolves to a path.
    const maxIdx = snap.utxos.reduce((m, _u) => m, 0);
    const window = Math.max(this.nextReceiveIndex, this.nextChangeIndex, maxIdx) + GAP_LIMIT + 5;
    this.deriveWindow(window);

    const utxos = [];
    const unmatched = [];
    for (const u of snap.utxos) {
      const path = this.addrMap.get(u.address);
      if (!path) {
        unmatched.push(u.address);
        continue;
      }
      utxos.push({
        txid: u.txid,
        vout: u.vout,
        value: u.value,
        address: u.address,
        chain: path.chain,
        index: path.index,
        confirmed: !!u.confirmed,
      });
    }
    utxos.sort((a, b) => b.value - a.value);
    this.utxos = utxos;
    this._recomputeBalanceFromUtxos();
    this.loaded = true;
    this.emit();
    return { imported: utxos.length, unmatched };
  }
}

export function utxoId(u) {
  return `${u.txid}:${u.vout}`;
}

// Watch-only: accept a native-segwit account xpub or zpub and normalize it to
// xpub version bytes (the key material is identical; only the prefix differs),
// so HDKey can load it. Throws on anything else (private keys, wrong type).
const _b58c = base58check(sha256);
const _XPUB_VER = Uint8Array.from([0x04, 0x88, 0xb2, 0x1e]);
const _ZPUB_VER = Uint8Array.from([0x04, 0xb2, 0x47, 0x46]);
const _XPRV_VER = Uint8Array.from([0x04, 0x88, 0xad, 0xe4]);
const _ZPRV_VER = Uint8Array.from([0x04, 0xb2, 0x43, 0x0c]);

// Classify a pasted extended key. xpub/zpub → public (watch-only); xprv/zprv →
// private (spending). Version bytes are normalized to the standard xpub/xprv set
// (key material is identical; only the prefix differs) so HDKey can load it.
// Returns { kind: 'xpub' | 'xprv', key } or throws.
export function parseExtendedKey(s) {
  let data;
  try {
    data = _b58c.decode((s || '').trim());
  } catch {
    throw new Error('Not a valid recovery phrase or key.');
  }
  if (data.length !== 78) throw new Error('Not a valid recovery phrase or key.');
  const ver = hex.encode(data.slice(0, 4));
  let kind, norm;
  if (ver === hex.encode(_XPUB_VER) || ver === hex.encode(_ZPUB_VER)) { kind = 'xpub'; norm = _XPUB_VER; }
  else if (ver === hex.encode(_XPRV_VER) || ver === hex.encode(_ZPRV_VER)) { kind = 'xprv'; norm = _XPRV_VER; }
  else throw new Error('Unrecognized key type — use a native-segwit xpub/zpub or xprv/zprv.');
  const out = new Uint8Array(data);
  out.set(norm, 0);
  const key = _b58c.encode(out);
  try {
    HDKey.fromExtendedKey(key);
  } catch {
    throw new Error('Not a valid extended key.');
  }
  return { kind, key };
}

// Encrypted vault for persisting seed-bearing accounts on this device. Key is
// scrypt(password, salt); payload is XChaCha20-Poly1305 (authenticated, so a
// wrong password fails to decrypt rather than returning garbage). All fields
// are hex so the blob is JSON-serializable for localStorage.
const _SCRYPT = { N: 2 ** 15, r: 8, p: 1, dkLen: 32 };
function _vaultKey(password, salt) {
  return scrypt(utf8ToBytes(password), salt, _SCRYPT);
}
export function encryptVault(obj, password) {
  const salt = randomBytes(16);
  const nonce = randomBytes(24);
  const ct = xchacha20poly1305(_vaultKey(password, salt), nonce).encrypt(utf8ToBytes(JSON.stringify(obj)));
  return { v: 1, salt: hex.encode(salt), nonce: hex.encode(nonce), ct: hex.encode(ct) };
}
export function decryptVault(blob, password) {
  const pt = xchacha20poly1305(_vaultKey(password, hex.decode(blob.salt)), hex.decode(blob.nonce)).decrypt(hex.decode(blob.ct));
  return JSON.parse(bytesToUtf8(pt));
}

// Convert a standard account xpub to a BIP84 zpub for export/interop.
export function xpubToZpub(xpub) {
  const data = new Uint8Array(_b58c.decode(xpub));
  data.set(_ZPUB_VER, 0);
  return _b58c.encode(data);
}

// Gift-link claiming (sender side is Wallet.createGift). A gift code is a
// base64url PSBT: one SIGHASH_SINGLE-signed input + the sender's change output.
// previewGift reports the room available to the claimer (before their fee);
// buildClaimTx adds the claimer's output and finalizes a broadcastable tx.
// Smallest sensible gift at a given fee rate: dust + one claim fee of headroom
// (floored at 546 sats), so the recipient clears dust even if fees climb.
export function giftMinimum(feeRate) {
  const rate = Math.max(1, Math.round(feeRate));
  const claimFee = Math.ceil((11 + 68 + 31 * 2) * rate);
  return Math.max(546, 294 + claimFee);
}

// ---- compact gift codec ----------------------------------------------------
// A gift link used to carry a full PSBT (verbose). The claimer only needs the
// presigned inputs (outpoint, amount, pubkey, signature) and the sender's
// committed change output, so we serialize just those — ~25% smaller, and (via
// base32 + an uppercase /g/ URL) it scans in the QR's denser alphanumeric mode.
// Legacy base64url-PSBT links still claim; _giftTx auto-detects the format.
const GIFT_MAGIC = 0x01;
const _u8 = (n) => Uint8Array.of(n & 0xff);
const _le32 = (n) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, n >>> 0, true); return b; };
const _le64 = (n) => { const b = new Uint8Array(8); new DataView(b.buffer).setBigUint64(0, BigInt(n), true); return b; };

function _encodeCompactGift(tx) {
  const hasChange = tx.outputsLength > 0;
  const parts = [_u8(GIFT_MAGIC), _u8(hasChange ? 1 : 0), _u8(tx.inputsLength)];
  for (let i = 0; i < tx.inputsLength; i++) {
    const inp = tx.getInput(i);
    const [pubkey, sig] = inp.partialSig[0]; // pubkey(33), sig = DER + sighash byte
    parts.push(inp.txid, _le32(inp.index), _le64(inp.witnessUtxo.amount), pubkey, _u8(sig.length), sig);
  }
  if (hasChange) {
    const o = tx.getOutput(0); // p2wpkh change: script = [00 14 <20-byte hash>]
    parts.push(_le64(o.amount), o.script.slice(2));
  }
  return concatBytes(...parts);
}

function _decodeCompactGift(bytes) {
  let p = 0;
  const rd = (n) => bytes.slice(p, (p += n));
  const r32 = () => { const v = new DataView(bytes.buffer, bytes.byteOffset + p, 4).getUint32(0, true); p += 4; return v; };
  const r64 = () => { const v = new DataView(bytes.buffer, bytes.byteOffset + p, 8).getBigUint64(0, true); p += 8; return v; };
  p++; // magic
  const hasChange = !!(bytes[p++] & 1);
  const n = bytes[p++];
  const t = new btc.Transaction({ allowUnknownOutputs: true });
  for (let i = 0; i < n; i++) {
    const txid = rd(32), vout = r32(), amount = r64(), pubkey = rd(33), sigLen = bytes[p++], sig = rd(sigLen);
    const pay = p2wpkh(pubkey, btc.NETWORK); // witness-program .script is network-independent
    // second arg true: re-add an already-signed input without tripping the sign-status guard
    t.addInput({ txid, index: vout, witnessUtxo: { script: pay.script, amount }, sighashType: sig[sig.length - 1], partialSig: [[pubkey, sig]] }, true);
  }
  if (hasChange) {
    const amount = r64();
    const hash = rd(20);
    t.addOutput({ script: concatBytes(_u8(0x00), _u8(0x14), hash), amount }, true);
  }
  return t;
}

// Parse a gift code to a Transaction. New format: base32(compact). Legacy:
// base64url(PSBT). Auto-detected via the compact magic byte.
function _giftTx(code) {
  try {
    const b = base32nopad.decode(code.toUpperCase());
    if (b[0] === GIFT_MAGIC) return _decodeCompactGift(b);
  } catch {}
  return btc.Transaction.fromPSBT(base64urlnopad.decode(code));
}

function _sumInputs(tx) {
  let inAmt = 0n;
  for (let i = 0; i < tx.inputsLength; i++) inAmt += tx.getInput(i).witnessUtxo.amount;
  return inAmt;
}
// The sender's change committed in a gift PSBT, or 0 for a no-change (whole-
// balance) gift that has no outputs at all.
function _giftChange(tx) {
  return tx.outputsLength > 0 ? tx.getOutput(0).amount : 0n;
}
// The gift's funding outpoints (the coins its presigned inputs spend). If any is
// already spent — even by an unconfirmed claim — the gift has been taken and
// re-claiming would be a doomed double-spend. Used to gate the claim screen.
export function giftOutpoints(code) {
  try {
    const tx = _giftTx(code);
    const out = [];
    for (let i = 0; i < tx.inputsLength; i++) {
      const inp = tx.getInput(i);
      out.push({ txid: hex.encode(inp.txid), vout: inp.index });
    }
    return out;
  } catch {
    return [];
  }
}
export function previewGift(code) {
  try {
    const tx = _giftTx(code);
    // room is the full amount the claimer receives (inputs minus our change);
    // the claim fee is subtracted from it at claim time, so report inputs too
    // so the caller can size that fee for this PSBT.
    return { room: Number(_sumInputs(tx) - _giftChange(tx)), inputs: tx.inputsLength };
  } catch {
    return null;
  }
}

export function buildClaimTx(code, toAddress, feeRate, net) {
  const tx = _giftTx(code);
  const room = _sumInputs(tx) - _giftChange(tx);
  const fee = BigInt(Math.max(1, Math.ceil((11 + 68 * tx.inputsLength + 31 * 2) * Math.max(1, Math.round(feeRate)))));
  const out = room - fee;
  if (out < 294n) throw new Error('Gift is too small to claim at this fee rate.');
  tx.addOutputAddress(toAddress, out, net);
  tx.finalize();
  return { hex: tx.hex, txid: tx.id, amount: Number(out), fee: Number(fee) };
}

// A gift locked to a recipient's nostr key. The amount + recipient pubkey are
// public (anyone can see what it is and who it's for), but the claim payload (the
// gift code) is NIP-44-encrypted to the recipient via an ephemeral key — so the
// link can be shared openly yet only the recipient's nostr key can claim it.
const LOCKED_GIFT_VERSION = 1;
// Encrypt the gift's claim payload under a one-time code. The code is delivered
// to the recipient via a nostr DM; the public link carries only the ciphertext.
// Returns { blob (for the /lg/ link), claimCode (to DM) }.
export function lockGift(code, amount, recipientPkHex) {
  const { code: claimCode, ctCode, eph, ctKey } = encryptGiftPayload(code, recipientPkHex);
  const blob = base64urlnopad.encode(new TextEncoder().encode(JSON.stringify({ v: LOCKED_GIFT_VERSION, amount, to: recipientPkHex, ct: ctCode, eph, ctKey })));
  return { blob, claimCode };
}
// The public fields of a locked-gift blob (or null). Decryption needs the code.
export function previewLockedGift(blob) {
  try {
    const o = JSON.parse(new TextDecoder().decode(base64urlnopad.decode(blob)));
    if (o.v === LOCKED_GIFT_VERSION && typeof o.amount === 'number' && o.to && o.ct) return o;
  } catch {}
  return null;
}

function firstUnused(chain) {
  const u = chain.find((a) => !a.used);
  return u ? u.index : chain.length;
}

function summarize(sel, network) {
  const outputs = sel.tx.outputs.map((o) => ({
    address: btc.Address(network).encode(btc.OutScript.decode(o.script)),
    amount: Number(o.amount),
  }));
  return {
    tx: sel.tx,
    fee: Number(sel.fee),
    hasChange: !!sel.change,
    inputsCount: sel.tx.inputsLength,
    outputs,
    weight: sel.weight,
    vsize: Math.ceil(Number(sel.weight) / 4),
  };
}