aboutsummaryrefslogtreecommitdiffstats
path: root/lib/payments.ts
blob: 5650dda49c08479238983d338861733805955341 (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
import config from "$config";
import api from "$lib/api";
import { db, g, gf, s } from "$lib/db";
import {
  broadcastTx,
  btcNetwork,
  deriveAddress,
  deriveAddresses,
  getAddressTxs,
  getAddressUtxos,
  getTxHex,
  getTxStatus,
  hdVersions,
  findLastUsedIndex,
} from "$lib/esplora";
import { HDKey } from "@scure/bip32";
import { generate } from "$lib/invoices";
import ln from "$lib/ln";
import { err, l, warn } from "$lib/logging";
import { handleZap } from "$lib/nostr";
import { notify, nwcNotify } from "$lib/notifications";
import { emit } from "$lib/sockets";
import { squarePayment } from "$lib/square";
import {
  getBalance,
  getCredit,
  tbConfirm,
  tbCredit,
  tbDebit,
  tbRefund,
  tbReverse,
  tbSetBalance,
  tbSetPending,
} from "$lib/tb";
import {
  SATS,
  btc,
  fail,
  fmt,
  formatReceipt,
  getInvoice,
  getPayment,
  getUser,
  link,
  sats,
  sleep,
  t,
} from "$lib/utils";
import { getArkBalance, sendArk } from "$lib/ark";
import { callWebhook } from "$lib/webhooks";
import rpc from "@coinos/rpc";
import { selectUTXO, p2wpkh } from "@scure/btc-signer";
import { bech32 } from "bech32";
import got from "got";
import { v4 } from "uuid";

import { PaymentType } from "$lib/types";
import { P2A_VALUE, getP2AAddress, isP2AOutput, calculateBumpReserve } from "$lib/p2a";
import { buildCpfpSend } from "$lib/cpfp";

const bc = rpc(config.bitcoin);
const lq = rpc(config.liquid);
const { URL } = process.env;

const dust = 547;

const resolveBip353 = async (name: string, domain: string) => {
  const qname = `${name}.user._bitcoin-payment.${domain}`;
  const res = await fetch(
    `https://1.1.1.1/dns-query?name=${qname}&type=TXT`,
    { headers: { accept: "application/dns-json" } },
  );
  const data = await res.json();
  if (!data.AD) return null; // DNSSEC validation failed
  if (!data.Answer?.length) return null;
  for (const ans of data.Answer) {
    const txt = ans.data?.replace(/^"|"$/g, "").replaceAll('" "', "");
    if (txt?.startsWith("bitcoin:")) return txt;
  }
  return null;
};

export const getUserRate = async (user) => {
  const rates = await g("rates");
  const { currency } = user;
  const rate = rates[currency];
  return { rates, rate, currency };
};

export const acquireArkLock = async (hash) => {
  const locked = await db.set(`arklock:${hash}`, "1", { NX: true, EX: 60 });
  if (!locked) fail("Already processed");
};

export const createArkPayment = async ({
  aid,
  uid,
  amount,
  hash,
  rate,
  currency,
  type = PaymentType.ark,
  iid = undefined,
  created = Date.now(),
  mapHashToId = false,
  extraHashMappings = [] as string[],
  extraMultiOps = undefined as ((m: any, p: any) => void) | undefined,
}) => {
  const p = {
    id: v4(),
    aid,
    amount,
    hash,
    confirmed: true,
    rate,
    currency,
    type,
    uid,
    iid,
    created,
  };

  const m = db.multi();
  m.set(`payment:${p.id}`, JSON.stringify(p))
    .lPush(`${aid}:payments`, p.id)
    .set(`${aid}:payments:last`, p.created);

  if (mapHashToId) {
    m.set(`payment:${aid}:${hash}`, JSON.stringify(p.id));
  }

  for (const h of extraHashMappings) {
    m.set(`payment:${aid}:${h}`, JSON.stringify(p.id));
  }

  if (extraMultiOps) extraMultiOps(m, p);

  await m.exec();

  return p;
};

export const debit = async ({
  aid = undefined,
  hash,
  amount,
  fee = 0,
  memo = undefined,
  user,
  type = PaymentType.internal,
  rate = undefined,
}) => {
  amount = Number.parseInt(amount);

  const whitelisted = await db.sIsMember("whitelist", user?.username?.toLowerCase().trim());

  const blacklisted = await db.sIsMember("blacklist", user?.username?.toLowerCase().trim());

  const serverLimit = await g(`${type}:limit`);
  const userLimit = await g("limit");
  const frozen = (await g("hardfreeze")) || ((await g("freeze")) && type !== PaymentType.internal);
  const skipServerLimit = type === PaymentType.fund || type === PaymentType.internal;

  if (frozen || (userLimit != null && amount > userLimit && !whitelisted) || (!skipServerLimit && serverLimit != null && amount > serverLimit)) {
    warn("Blocking", user.username, amount, hash, user.id, type, frozen, userLimit, serverLimit);
    fail("Problem sending payment");
  }

  let ref;
  const { id: uid } = user;
  if (!aid) aid = uid;
  const debitAccount = aid && aid !== uid ? await g(`account:${aid}`) : null;
  const currency = debitAccount?.currency || user.currency;

  const rates = await g("rates");
  if (!rate) rate = rates[currency];

  const invoice = await getInvoice(hash);
  let iid;

  if (invoice) {
    if (invoice.received >= amount && invoice.type !== PaymentType.bolt12)
      fail("Invoice already paid");
    ({ id: iid } = invoice);

    ref = invoice.uid;

    const equivalentRate = invoice.rate * (rates[currency] / rates[invoice.currency]);

    if (Math.abs(invoice.rate / rates[invoice.currency] - 1) < 0.01) {
      rate = equivalentRate;
    } else {
      warn("rate slipped", hash, invoice.rate, equivalentRate);
    }
  }

  const tip = Number.parseInt(invoice?.tip) || null;
  if (tip < 0) fail("Invalid tip");

  if (!amount || amount < 0) fail("Amount must be greater than zero");

  let creditType = type;
  if (creditType === PaymentType.bolt12) creditType = PaymentType.lightning;
  let ourfee: any = [PaymentType.bitcoin, PaymentType.liquid, PaymentType.lightning].includes(type)
    ? Math.round((amount + fee + tip) * config.fee[creditType])
    : 0;

  if (aid !== uid) ourfee = 0;
  const frozenBalance = !blacklisted || whitelisted ? 0 : await getBalance(uid);

  ourfee = await tbDebit(
    aid,
    uid,
    creditType,
    amount || 0,
    tip || 0,
    fee || 0,
    ourfee || 0,
    frozenBalance || 0,
    t(user).insufficientFunds,
  );

  if (ourfee.err) fail(ourfee.err);

  const id = v4();
  const p = {
    id,
    aid,
    amount: -amount,
    fee,
    hash,
    hex: undefined,
    ourfee,
    memo,
    iid,
    uid,
    confirmed: true,
    rate,
    currency,
    type,
    ref,
    tip,
    created: Date.now(),
  };

  await s(`payment:${hash}`, id);
  await s(`payment:${id}`, p);
  await db
    .multi()
    .lPush("payments", id)
    .lPush(`${aid || uid}:payments`, id)
    .set(`${aid || uid}:payments:last`, p.created)
    .exec();

  l(user.username, "sent", type, amount);
  if (![PaymentType.lightning, PaymentType.bolt12].includes(type)) nwcNotify(p);

  return p;
};

export const credit = async ({
  hash,
  amount,
  memo = "",
  ref = "",
  type = PaymentType.internal,
  aid = undefined,
  payment_hash = undefined,
}) => {
  amount = Number.parseInt(amount) || 0;

  let inv = await getInvoice(hash);
  if (!inv && type === PaymentType.bolt12) {
    const { invoices } = await ln.listinvoices({ invstring: hash });
    const { local_offer_id } = invoices[0];
    inv = await getInvoice(local_offer_id);
  }

  if (!inv) {
    await db.sAdd("missing", ref.split(":")[0]);
    return;
  }

  let { path, tip } = inv;
  tip = Number.parseInt(tip) || 0;

  if (!memo) ({ memo } = inv);
  if (memo && memo.length > 5000) fail("memo too long");
  if (amount < 0 || tip < 0) fail("Invalid amount");
  if (type === PaymentType.internal) amount += tip;

  const user = await getUser(inv.uid);
  const { id: uid } = user;
  const creditAccount = aid && aid !== uid ? await g(`account:${aid}`) : null;
  const currency = creditAccount?.currency || user.currency;

  const rates = await g("rates");
  let rate = rates[currency];

  if (!rate) await sleep(1000);
  rate = rates[currency];

  const equivalentRate = inv.rate * (rates[currency] / rates[inv.currency]);

  if (Math.abs(inv.rate / rates[inv.currency] - 1) < 0.01) {
    rate = equivalentRate;
  } else {
    // warn("rate slipped", hash, invoice.rate, equivalentRate);
  }

  const id = v4();
  const p = {
    aid,
    id,
    iid: inv.id,
    hash,
    amount: amount - tip,
    path,
    uid,
    rate,
    currency,
    memo,
    payment_hash,
    ref,
    tip,
    type,
    confirmed: true,
    created: Date.now(),
    items: undefined,
  };

  if ([PaymentType.bitcoin, PaymentType.liquid].includes(type)) inv.pending += amount;
  else {
    inv.received += amount;
    inv.preimage = ref;
    inv.settled = Date.now();
  }

  let balanceKey = "balance";
  if ([PaymentType.bitcoin, PaymentType.liquid].includes(type)) {
    const [txid, vout] = ref.split(":").slice(-2);
    p.confirmed = false;
    balanceKey = "pending";
    await s(`payment:${txid}:${vout}`, id);
  } else {
    await s(`payment:${hash}`, id);
  }

  let creditType = type;
  if (creditType === PaymentType.bolt12) creditType = PaymentType.lightning;
  const isPending = balanceKey === "pending";

  await tbCredit(aid || uid, uid, creditType, amount, isPending);

  await db
    .multi()
    .set(`invoice:${inv.id}`, JSON.stringify(inv))
    .set(`payment:${p.id}`, JSON.stringify(p))
    .lPush(`${aid || uid}:payments`, p.id)
    .set(`${aid || uid}:payments:last`, p.created)
    .exec();

  if (inv.items?.length) {
    formatReceipt(inv.items, inv.currency);
    p.items = inv.items;
  }

  await completePayment(inv, p, user);

  return p;
};

export const completePayment = async (inv, p, user) => {
  const { id, username } = user;
  const aid = p.aid || id;
  const account = aid !== id ? await g(`account:${aid}`) : null;
  const autowithdraw = account?.autowithdraw;
  const threshold = account?.threshold ?? user.threshold;
  const reserve = account?.reserve ?? user.reserve;
  const destination = account?.destination ?? user.destination;

  let withdrawal;
  if (p.confirmed) {
    if (inv.forward && !inv.forwarded) {
      const lockKey = `forward:${inv.id}`;
      const locked = await db.setNX(lockKey, "1");
      if (locked) {
        await db.expire(lockKey, 300);
        try {
          inv.forwarded = true;
          await s(`invoice:${inv.id}`, inv);

          // Skip forward if destination is the same account (not just same user)
          const destInv = await getInvoice(inv.forward).catch(() => null);
          if (destInv?.uid === id && destInv?.aid === aid) return;

          await pay({ amount: p.amount, to: inv.forward, user });
        } catch (e) {
          warn(username, "forward failed", inv.forward, e.message);
        }
      }
    } else if (autowithdraw && p.type !== "ark") {
      try {
        const to = destination.trim();
        const balance = await getBalance(aid);
        const amount = balance - reserve;
        if (balance > threshold) {
          l("initiating autowithdrawal", amount, to, balance, threshold);
          const w = await pay({ aid, amount, to, user });
          withdrawal = {
            amount: fmt(-w.amount),
            link: link(w.id),
          };
        }
      } catch (e) {
        console.log(e);
        withdrawal = { failed: true };
        warn(username, "autowithdraw failed", e.message);
      }
    }
  }

  nwcNotify(p);
  notify(p, user, withdrawal);

  squarePayment(p, user);

  l(username, "received", p.type, p.amount);
  callWebhook(inv, p);
};

const confirmWatchedIncoming = async (address, existing) => {
  existing.confirmed = true;
  const inv = await getInvoice(address);
  if (inv) {
    inv.received += Number.parseInt(inv.pending);
    inv.pending = 0;
    await s(`invoice:${inv.id}`, inv);
  }
  await s(`payment:${existing.id}`, existing);
  await tbConfirm(existing.aid || existing.uid, existing.amount);
  const user = await getUser(existing.uid);
  if (inv) await completePayment(inv, existing, user);
  await db.sRem("watching", address);
};

export const processWatchedTx = async (tx) => {
  const txid = tx.txid;

  for (let vout = 0; vout < tx.vout.length; vout++) {
    const output = tx.vout[vout];
    const address = output.scriptpubkey_address;
    if (!address) continue;
    if (!(await db.sIsMember("watching", address))) continue;

    const invoice = await getInvoice(address);
    if (!invoice) continue;

    const existing = await getPayment(`${txid}:${vout}`);
    if (existing) {
      if (!existing.confirmed && tx.status?.confirmed) {
        await confirmWatchedIncoming(address, existing);
      }
      continue;
    }

    if (output.value < 300) continue;

    const lockKey = `lock:${txid}:${vout}`;
    const locked = await db.setNX(lockKey, "1");
    if (!locked) continue;
    await db.expire(lockKey, 60);

    await credit({
      hash: address,
      amount: output.value,
      ref: `${txid}:${vout}`,
      type: PaymentType.bitcoin,
      aid: invoice.aid,
    });

    if (tx.status?.confirmed) {
      const created = await getPayment(`${txid}:${vout}`);
      if (created && !created.confirmed) {
        await confirmWatchedIncoming(address, created);
      }
    }
  }
};

const pay = async ({ aid = undefined, amount, to, user }) => {
  if (!aid) aid = user.id;
  amount = Number.parseInt(amount) || 0;
  let lnurl;
  let pr;
  if (to.includes("@") && to.includes(".")) {
    const [name, domain] = to.split("@");
    if (URL.includes(domain)) to = name;
    else {
      try {
        const uri = await resolveBip353(name, domain);
        if (uri) {
          const params = new URLSearchParams(uri.split("?")[1]);
          if (params.has("lno")) to = params.get("lno");
          else if (params.has("sp")) to = params.get("sp");
          else if (params.has("lightning")) to = params.get("lightning");
          else {
            const addr = uri.replace("bitcoin:", "").split("?")[0];
            if (addr) to = addr;
          }
        }
      } catch (e) {
        warn("BIP 353 resolution failed, falling back to LNURL", e.message);
      }
      if (to.includes("@")) lnurl = `https://${domain}/.well-known/lnurlp/${name}`;
    }
  } else if (to.startsWith("lnurl")) {
    lnurl = Buffer.from(bech32.fromWords(bech32.decode(to, 20000).words)).toString();
  }

  const recipient = await getUser(to);
  if (recipient)
    return sendInternal({
      amount,
      recipient,
      sender: user,
    });

  if (to.startsWith("ark") || to.startsWith("tark")) {
    const tmpHash = v4();
    const p = await debit({
      hash: tmpHash,
      amount,
      user,
      type: PaymentType.ark,
    });

    try {
      const txid = await sendArk(to, amount);
      p.hash = txid;
      await s(`payment:${p.id}`, p);
      await s(`payment:${txid}`, p.id);

      // Instant vault notification
      try {
        const vaultInfo = await g(`arkaddr:${to}`);
        if (vaultInfo) {
          const { aid: vaultAid, uid: vaultUid } = vaultInfo;
          const isForward = await g(`custodial-ark-invoice:${to}`);
          const vaultOwner = await g(`user:${vaultUid}`);
          const { rate, currency } = await getUserRate(vaultOwner || user);
          const vp = await createArkPayment({
            aid: vaultAid,
            uid: vaultUid,
            amount,
            hash: txid,
            rate,
            currency,
            extraHashMappings: [txid],
          });
          if (!isForward) {
            l("ark pay: instant vault credit", vaultAid, txid);
            emit(vaultUid, "payment", vp);
          }
        }
      } catch (e) {
        warn("ark pay: instant vault notification failed", e.message);
      }
    } catch (e) {
      await reverse(p);
      throw e;
    }

    return p;
  }

  // Check for local invoice before applying external fees
  if (to.startsWith("ln") && !to.startsWith("lnurl") && !to.startsWith("lno")) {
    const localInv = await getInvoice(to).catch(() => null);
    if (localInv) {
      const recipient = await getUser(localInv.uid);
      if (recipient) return sendInternal({ amount, invoice: localInv, recipient, sender: user });
    }
  }

  let fee;
  const ourfee = Math.round(amount * (config.fee.lightning || 0));
  if (lnurl) {
    fee = Math.max(5, Math.round(amount * 0.02));
    amount -= fee + ourfee;
    const { callback } = (await got(lnurl).json()) as any;
    ({ pr } = (await got(`${callback}?amount=${amount * 1000}`).json()) as any);
  } else if (to.startsWith("lno")) {
    const { id: source } = await ln.getinfo();
    const { offer_issuer_id } = await ln.decode(to);
    const { routes } = await ln.getroutes(
      source,
      offer_issuer_id,
      amount * 1000,
      ["auto.localchans", "auto.sourcefree"],
      Math.round(amount * 0.02) * 1000,
      6,
    );
    fee = routes.length
      ? Math.max(5, Math.round((routes[0].path[0].amount_msat - routes[0].amount_msat) / 1000))
      : 0;
    amount -= fee + ourfee;
    const { invoice } = await ln.fetchinvoice(to, amount * 1000);
    pr = invoice;
  } else if (to.startsWith("ln")) {
    fee = Math.max(5, Math.round(amount * 0.02));
    amount -= fee + ourfee;
    pr = to;
  }

  if (pr) return sendLightning({ user, pr, amount, fee });

  return sendOnchain({ aid, amount, address: to, user, subtract: true });
};

export const decode = async (hex) => {
  let type;
  let tx;
  try {
    tx = await bc.decodeRawTransaction(hex);
    type = PaymentType.bitcoin;
  } catch (e) {
    try {
      tx = await lq.decodeRawTransaction(hex);
      type = PaymentType.liquid;
    } catch (e) {
      err("invalid hex", hex);
      fail("unrecognized tx");
    }
  }

  return { tx, type };
};

const inflight = {};

const sendNonCustodial = async (params) => {
  let { aid, hex, rate, user } = params;
  if (!hex) ({ hex } = await build(params));

  const { tx } = await decode(hex);
  let { txid } = tx;

  try {
    if (inflight[txid]) fail("payment in flight");
    inflight[txid] = true;

    const account = await g(`account:${aid}`);
    const nextIndex = account.nextIndex || 0;

    // Build set of own addresses for change detection
    const ownAddresses = new Set<string>();
    for (let i = 0; i <= nextIndex; i++) {
      ownAddresses.add(deriveAddress(account.pubkey, account.fingerprint, i, false).address);
      ownAddresses.add(deriveAddress(account.pubkey, account.fingerprint, i, true).address);
    }

    let totalIn = 0;
    for (const { txid: inputTxid, vout } of tx.vin) {
      const inputHex = await getTxHex(inputTxid);
      const inputTx = await bc.decodeRawTransaction(inputHex);
      totalIn += sats(inputTx.vout[vout].value);
    }

    let total = 0;
    let change = 0;
    for (const {
      scriptPubKey: { address },
      value,
    } of tx.vout) {
      total += sats(value);
      const invoice = await getInvoice(address);
      if (invoice?.aid === aid) fail("Cannot send to internal address");

      if (ownAddresses.has(address)) {
        change += sats(value);
      }
    }

    const fee = totalIn - total;
    const amount = total - change;

    const p = await debit({
      aid,
      hash: txid,
      amount,
      fee,
      rate,
      user,
      type: PaymentType.bitcoin,
    });

    p.hex = hex;
    await s(`payment:${p.id}`, p);

    await broadcastTx(hex);
    await db.sAdd(`inflight:${aid}`, p.id);

    delete inflight[txid];
    return p;
  } catch (e) {
    delete inflight[txid];
    throw e;
  }
};

export const sendOnchain = async (params) => {
  let { aid, hex, rate, user, signed, feeRate } = params;
  if (!aid) aid = user.id;

  // Non-custodial bitcoin account — use esplora
  if (aid !== user.id) {
    return sendNonCustodial(params);
  }

  let buildResult;
  if (!hex) {
    buildResult = await build(params);
    hex = buildResult.hex;
  }

  // CPFP+send path: already signed, needs package submission
  if (buildResult?.signed) {
    const { txid, parentHex, fee, bumpReserve, p2aVout, parentVsize, ourfee, cpfpParentId, cpfpSubsidy } = buildResult;

    try {
      if (inflight[txid]) fail("payment in flight");
      inflight[txid] = true;

      // Submit as package (parent + child) since parent may not be in mempool
      const r = await bc.testMempoolAccept([hex]);
      if (r[0].allowed) {
        await bc.sendRawTransaction(hex);
      } else {
        const pkg = await bc.submitPackage([parentHex, hex]);
        if (!pkg["tx-results"]) fail("package submission failed");
      }

      // Decode to get the send amount
      const decoded = await bc.decodeRawTransaction(hex);
      let amount = 0;
      for (const out of decoded.vout) {
        if (isP2AOutput(out.scriptPubKey.hex)) continue;
        const info = await bc.getAddressInfo(out.scriptPubKey.address);
        if (!info.ismine) amount += sats(out.value);
      }

      const p = await debit({
        aid,
        hash: txid,
        amount,
        fee: fee + bumpReserve,
        rate,
        user,
        type: PaymentType.bitcoin,
      });

      p.fee = fee;
      p.hex = hex;
      (p as any).address = params.address;
      (p as any).bumpReserve = bumpReserve;
      (p as any).p2aVout = p2aVout;
      (p as any).parentVsize = parentVsize;
      (p as any).cpfpParentId = cpfpParentId;
      p.confirmed = false;

      await s(`payment:${p.id}`, p);
      await db.sAdd("outgoing:unconfirmed", p.id);

      delete inflight[txid];
      return p;
    } catch (e) {
      delete inflight[txid];
      throw e;
    }
  }

  const { tx, type } = await decode(hex);
  const node = rpc(config[type]);
  const isBitcoin = type === PaymentType.bitcoin;
  let { txid } = tx;

  try {
    if (inflight[txid]) fail("payment in flight");
    inflight[txid] = true;

    if (!signed) {
      if (config[type].walletpass) await node.walletPassphrase(config[type].walletpass, 300);

      ({ hex } = await node.signRawTransactionWithWallet(
        type === PaymentType.liquid ? await node.blindRawTransaction(hex) : hex,
      ));
    }

    ({ txid } = await node.decodeRawTransaction(hex));

    const r = await node.testMempoolAccept([hex]);
    if (!r[0].allowed) fail("transaction rejected");

    let total = 0;
    let fee = 0;
    let change = 0;
    let p2aVout = -1;

    if (type === PaymentType.liquid) {
      for (const {
        asset,
        scriptPubKey: { address, type },
        value,
      } of tx.vout) {
        if (asset !== config.liquid.btc) fail("only L-BTC supported");
        if (type === "fee") fee = sats(value);
        else {
          total += sats(value);

          if (address) {
            if ((await node.getAddressInfo(address)).ismine) {
              change += sats(value);
            }
          }
        }
      }
    } else {
      let totalIn = 0;
      for await (const { txid, vout } of tx.vin) {
        const hex = await node.getRawTransaction(txid);
        const tx = await node.decodeRawTransaction(hex);
        totalIn += sats(tx.vout[vout].value);
      }

      for (let i = 0; i < tx.vout.length; i++) {
        const { scriptPubKey, value } = tx.vout[i];

        if (isP2AOutput(scriptPubKey.hex)) {
          p2aVout = i;
          continue;
        }

        total += sats(value);
        const invoice = await getInvoice(scriptPubKey.address);
        if (invoice?.aid === aid) fail("Cannot send to internal address");

        if ((await node.getAddressInfo(scriptPubKey.address)).ismine) {
          change += sats(value);
        }
      }

      fee = totalIn - total - (p2aVout >= 0 ? P2A_VALUE : 0);
    }

    const amount = total - change;
    let bumpReserve = buildResult?.bumpReserve || 0;
    let parentVsize = buildResult?.parentVsize || 0;

    // When hex is pre-built, check if the fee rate is still acceptable
    if (isBitcoin && !buildResult) {
      const currentFees: any = await fetch(`${api[type]}/fees/recommended`).then((r) => r.json());
      const minAcceptable = currentFees.hourFee;
      const decoded = await node.decodeRawTransaction(hex);
      const originalRate = fee / decoded.vsize;

      if (originalRate < minAcceptable) {
        // Fee rate is stale — rebuild the tx from scratch
        buildResult = await build(params);
        hex = buildResult.hex;

        ({ hex } = await node.signRawTransactionWithWallet(hex));
        ({ txid } = await node.decodeRawTransaction(hex));

        const r2 = await node.testMempoolAccept([hex]);
        if (!r2[0].allowed) fail("rebuilt transaction rejected");

        bumpReserve = buildResult.bumpReserve || 0;
        parentVsize = buildResult.parentVsize || 0;
        fee = buildResult.fee || 0;
      } else {
        // Original rate still acceptable — honor what was shown to the user
        bumpReserve = Number(params.bumpReserve) || 0;
        parentVsize = Number(params.parentVsize) || 0;
      }
    }

    const p = await debit({
      aid,
      hash: txid,
      amount,
      fee: fee + bumpReserve,
      rate,
      user,
      type,
    });

    p.fee = fee;
    p.hex = hex;
    (p as any).address = params.address;

    if (isBitcoin) {
      p.confirmed = false;
      if (bumpReserve > 0) {
        (p as any).bumpReserve = bumpReserve;
        (p as any).p2aVout = p2aVout;
        (p as any).parentVsize = parentVsize;
      }
    }

    await s(`payment:${p.id}`, p);

    await node.sendRawTransaction(hex);

    if (isBitcoin) {
      await db.sAdd("outgoing:unconfirmed", p.id);
    }

    delete inflight[txid];
    return p;
  } catch (e) {
    delete inflight[txid];
    throw e;
  }
};

export const sendKeysend = async ({
  hash,
  amount,
  pubkey,
  fee = undefined,
  memo = undefined,
  user,
  extratlvs = undefined,
}) => {
  fee = Math.max(Number.parseInt(fee || amount * 0.005), 5);

  let p = await gf(`payment:${hash}`);
  if (p) fail("duplicate keysend");

  p = await debit({
    hash,
    amount,
    fee,
    memo,
    user,
    type: PaymentType.lightning,
  });

  try {
    return await ln.keysend({
      destination: pubkey,
      amount_msat: amount * 1000,
      maxfee: fee * 1000,
      retry_for: 20,
      extratlvs,
    });
  } catch (e) {
    reverse(p);
    throw e;
  }
};

export const sendLightning = async ({ user, pr, amount, fee = undefined, memo = undefined }) => {
  let p;

  if (typeof amount !== "undefined") {
    amount = Number.parseInt(amount);
    if (amount < 0 || amount > SATS || Number.isNaN(amount)) {
      warn("invalid amount", amount);
      fail("Invalid amount");
    }
  }

  let { type, invoice_amount_msat, amount_msat, invoice_node_id, payee } = await ln.decode(pr);
  if (type.includes("bolt12")) {
    amount_msat = invoice_amount_msat;
    payee = invoice_node_id;
  }

  const { channels } = await ln.listpeerchannels();
  const isDirect = channels.some((c) => c.peer_id === payee);
  const minfee = isDirect ? 0 : Math.max(Math.round(amount * 0.005), 5);

  fee = Math.max(Number.parseInt(fee || 0), minfee);
  if (fee < 0) fail("Fee cannot be negative");

  const { pays } = await ln.listpays(pr);
  if (pays.find((p) => p.status === "complete")) fail("Invoice has already been paid");

  if (pays.find((p) => p.status === "pending")) fail("Payment is already underway");

  p = await debit({
    hash: pr,
    amount: amount_msat ? Math.round(amount_msat / 1000) : amount,
    fee,
    memo,
    user,
    type: PaymentType.lightning,
  });

  await db.sAdd("pending", pr);

  l("paying lightning invoice", pr.substr(-8), amount, fee);

  try {
    const r = await ln.xpay({
      invstring: pr.replace(/\s/g, "").toLowerCase(),
      // bolt11: pr.replace(/\s/g, "").toLowerCase(),
      amount_msat: amount_msat ? undefined : amount * 1000,
      maxfee: fee * 1000,
      retry_for: 20,
    });

    try {
      if (!r.failed_parts) p = await finalize(r, p);
    } catch (e) {
      warn("failed to process payment", p.id);
    }
  } catch (e) {
    err("failed to pay", pr.substr(-8));
    reverse(p);
    throw e;
  }

  return p;
};

export const sendInternal = async ({
  amount,
  invoice = undefined,
  memo = undefined,
  recipient,
  sender,
}) => {
  if (!invoice)
    invoice = await generate({
      invoice: { amount, type: "lightning" },
      user: recipient,
    });

  const { hash } = invoice;
  const p = await debit({ hash, amount, memo, user: sender });
  await credit({ hash, amount, memo, ref: sender.id });

  if (invoice.memo?.includes("9734")) {
    const { invoices } = await ln.listinvoices({ invstring: hash });
    const inv = invoices[0];
    inv.payment_preimage = p.id;
    inv.paid_at = Math.floor(Date.now() / 1000);
    handleZap(inv, sender.pubkey).catch(console.log);
  }

  return p;
};

const getAddressType = async (a) => {
  try {
    await bc.getAddressInfo(a);
    return PaymentType.bitcoin;
  } catch (e) {
    try {
      await lq.getAddressInfo(a);
      return PaymentType.liquid;
    } catch (e) {
      fail("unrecognized address");
    }
  }
};

const buildNonCustodial = async ({ aid, amount, address, feeRate, subtract, user: _user }) => {
  const account = await g(`account:${aid}`);
  if (!account?.pubkey) fail("account missing pubkey");

  amount = Number.parseInt(amount);
  if (amount < 0) fail("invalid amount");

  const fees: any = await fetch(`${api[PaymentType.bitcoin]}/fees/recommended`).then((r) =>
    r.json(),
  );

  fees.hourFee = fees.halfHourFee;
  fees.halfHourFee = fees.fastestFee;
  fees.fastestFee = Math.max(Math.ceil(fees.fastestFee * 1.5), 4);

  if (!feeRate) feeRate = fees.halfHourFee;

  const nextIndex = account.nextIndex || 0;

  // Derive all used external + internal addresses and fetch UTXOs
  const externalAddrs = deriveAddresses(account.pubkey, account.fingerprint, nextIndex + 1, false);
  const internalAddrs = deriveAddresses(account.pubkey, account.fingerprint, nextIndex + 1, true);
  const allAddrs = [...externalAddrs, ...internalAddrs];

  const rawUtxos = await getAddressUtxos(allAddrs);
  if (!rawUtxos.length) fail("no UTXOs available");

  // Build address-to-path lookup
  const addrToPath = {};
  for (let i = 0; i <= nextIndex; i++) {
    const { address: extAddr } = deriveAddress(account.pubkey, account.fingerprint, i, false);
    addrToPath[extAddr] = `m/0/${i}`;
    const { address: intAddr } = deriveAddress(account.pubkey, account.fingerprint, i, true);
    addrToPath[intAddr] = `m/1/${i}`;
  }

  // Convert esplora UTXOs to selectUTXO input format
  const keyVersions = account.pubkey.startsWith("tpub") ? hdVersions : undefined;
  const accountKey = HDKey.fromExtendedKey(account.pubkey, keyVersions);

  const utxoInputs = rawUtxos.map((u) => {
    const path = addrToPath[u.address];
    const parts = path.split("/").slice(-2);
    const child = accountKey
      .deriveChild(Number.parseInt(parts[0]))
      .deriveChild(Number.parseInt(parts[1]));
    const payment = p2wpkh(child.publicKey, btcNetwork);

    return {
      txid: u.txid,
      index: u.vout,
      witnessUtxo: {
        amount: BigInt(u.value),
        script: payment.script,
      },
    };
  });

  const balance = await getBalance(aid);
  let ourfee = 0; // Non-custodial accounts don't pay platform fee

  const outputs = [{ address, amount: BigInt(amount) }];

  // Derive a change address (next internal address)
  const { address: changeAddress } = deriveAddress(
    account.pubkey,
    account.fingerprint,
    nextIndex,
    true,
  );

  let selected = selectUTXO(utxoInputs, outputs, "default", {
    changeAddress,
    feePerByte: BigInt(Math.ceil(feeRate)),
    network: btcNetwork,
    createTx: true,
  });

  if (!selected) {
    subtract = true;
    if (amount <= dust) {
      fail(`insufficient funds ⚡️${balance} of ⚡️${amount + dust}`);
    }

    // Try with subtracted fee — send max
    const maxOutputs = [{ address, amount: BigInt(amount) }];
    selected = selectUTXO(utxoInputs, maxOutputs, "all", {
      changeAddress,
      feePerByte: BigInt(Math.ceil(feeRate)),
      network: btcNetwork,
      createTx: true,
    });

    if (!selected) fail("insufficient funds");
  }

  const fee = Number(selected.fee);

  // Build input metadata for client signing
  const inputs = selected.inputs.map((input) => {
    const inputTxid =
      typeof input.txid === "string" ? input.txid : Buffer.from(input.txid).toString("hex");
    const utxo = rawUtxos.find((u) => u.txid === inputTxid && u.vout === input.index);
    const path = utxo ? addrToPath[utxo.address] : undefined;
    return {
      witnessUtxo: {
        amount: Number(input.witnessUtxo.amount),
        script: Buffer.from(input.witnessUtxo.script).toString("hex"),
      },
      path,
    };
  });

  const hex = Buffer.from(selected.tx.toPSBT()).toString("hex");

  return { feeRate, ourfee, fee, fees, hex, inputs, subtract };
};

export const build = async ({ aid, amount, address, feeRate, subtract, user }) => {
  const type = await getAddressType(address);
  if (!aid) aid = user.id;

  // Non-custodial bitcoin account — use esplora
  if (type === PaymentType.bitcoin) {
    const account = await g(`account:${aid}`);
    if (account?.pubkey) {
      return buildNonCustodial({ aid, amount, address, feeRate, subtract, user });
    }
  }

  const node = rpc(config[type]);
  const isBitcoin = type === PaymentType.bitcoin;
  const p2aAddress = isBitcoin ? getP2AAddress() : null;

  amount = Number.parseInt(amount);
  if (amount < 0) fail("invalid amount");

  const fees: any =
    type === PaymentType.liquid
      ? { fastestFee: 0.1, halfHourFee: 0.1, hourFee: 0.1 }
      : await fetch(`${api[type]}/fees/recommended`).then((r) => r.json());

  const rawFastestFee = fees.fastestFee;

  if (isBitcoin) {
    fees.hourFee = fees.halfHourFee;
    fees.halfHourFee = fees.fastestFee;
    fees.fastestFee = Math.max(Math.ceil(fees.fastestFee * 1.5), 4);
  }

  if (!feeRate) {
    feeRate = fees.halfHourFee;
  }

  if (isBitcoin) {
    if (feeRate < 0.1) fail("fee rate too low");
  } else {
    if (feeRate < fees.hourFee) fail("fee rate too low");
  }

  const replaceable = false;

  let outs: any[] = [{ [address]: btc(amount) }];
  if (p2aAddress) outs.push({ [p2aAddress]: btc(P2A_VALUE) });

  if (type === PaymentType.liquid) outs = outs.map((o) => ({ ...o, asset: config.liquid.btc }));

  let raw = await node.createRawTransaction([], outs, 0, replaceable);
  if (isBitcoin) raw = "03000000" + raw.substring(8);

  let fee = 0;
  let tx;
  let bumpReserve = 0;
  let parentVsize = 0;

  // Piggyback on an unconfirmed parent via CPFP if one exists
  if (isBitcoin) {
    try {
      let ourfee = Math.round(amount * config.fee[type]);
      const creditBal = await getCredit(aid, type);
      const covered = Math.min(creditBal, ourfee);
      ourfee -= covered;
      const cpfp = await buildCpfpSend({ address, amount: amount - ourfee, feeRate, fees });
      return { ...cpfp, feeRate, ourfee, fees, inputs: [], subtract, signed: true };
    } catch {}
  }

  try {
    tx = await node.fundRawTransaction(raw, {
      fee_rate: feeRate,
      replaceable,
      subtractFeeFromOutputs: [],
    });

    fee = sats(tx.fee);

    if (isBitcoin) {
      const decoded = await node.decodeRawTransaction(tx.hex);
      parentVsize = decoded.vsize;
      bumpReserve = calculateBumpReserve(feeRate, fees.fastestFee, parentVsize);
    }
  } catch (e) {
    if (e.message.startsWith("Insufficient")) subtract = true;
    else throw e;
  }

  const balance = await getBalance(aid);
  let ourfee = Math.round(amount * config.fee[type]);
  const creditBal = await getCredit(aid, type);
  const covered = Math.min(creditBal, ourfee);
  ourfee -= covered;

  // Full balance withdrawal — skip reserve and P2A, nothing to refund to
  const fullWithdrawal = subtract || amount + fee + ourfee + bumpReserve > balance;

  if (fullWithdrawal) {
    subtract = true;
    bumpReserve = 0;
    feeRate = Math.max(rawFastestFee, 1);

    if (amount <= fee + ourfee + dust) {
      fail(`insufficient funds ⚡️${balance} of ⚡️${amount + fee + ourfee + dust}`);
    }

    outs = [{ [address]: btc(amount - ourfee) }];

    raw = await node.createRawTransaction([], outs, 0, replaceable);
    if (isBitcoin) raw = "03000000" + raw.substring(8);

    tx = await node.fundRawTransaction(raw, {
      fee_rate: feeRate,
      replaceable,
      subtractFeeFromOutputs: [0],
    });

    fee = sats(tx.fee);

    if (isBitcoin) {
      const decoded = await node.decodeRawTransaction(tx.hex);
      parentVsize = decoded.vsize;
    }
  }

  const inputs = [];
  const { vin } = await node.decodeRawTransaction(tx.hex);

  for (const { txid, vout } of vin) {
    const rawTx = await node.getRawTransaction(txid);
    const tx = await node.decodeRawTransaction(rawTx);
    const prevOutput = tx.vout[vout];
    const { address } = prevOutput.scriptPubKey;
    const { hdkeypath: path } = await node.getAddressInfo(address);
    const witnessUtxo = {
      amount: Math.round(prevOutput.value * SATS),
      script: prevOutput.scriptPubKey.hex,
    };
    inputs.push({ witnessUtxo, path });
  }

  return { feeRate, ourfee, fee, fees, hex: tx.hex, inputs, subtract, bumpReserve, parentVsize };
};

export const checkOutgoingConfirmations = async () => {
  try {
    const paymentIds = await db.sMembers("outgoing:unconfirmed");
    for (const pid of paymentIds) {
      try {
        const p = await gf(`payment:${pid}`);
        if (!p) {
          await db.sRem("outgoing:unconfirmed", pid);
          continue;
        }

        if (p.confirmed) {
          await db.sRem("outgoing:unconfirmed", pid);
          continue;
        }

        const txInfo = await bc.getRawTransaction(p.hash, true).catch(() => null);
        if (!txInfo || !txInfo.confirmations || txInfo.confirmations < 1) continue;

        const refundAmount = (p.bumpReserve || 0) - (p.bumpedFee || 0);
        if (refundAmount > 0) {
          await tbRefund(p.uid, refundAmount);
        }

        p.confirmed = true;
        p.bumpReserve = 0;
        await s(`payment:${p.id}`, p);
        await db.sRem("outgoing:unconfirmed", pid);
        emit(p.uid, "payment", p);
        l("outgoing confirmed", p.id, "refunded", refundAmount);
      } catch (e) {
        err("problem checking outgoing confirmation", pid, e.message);
      }
    }
  } catch (e) {
    err("checkOutgoingConfirmations failed", e.message);
  }
};

export const catchUp = async () => {
  try {
    // Check watched addresses for any missed bitcoin transactions
    const watched = await db.sMembers("watching");
    for (const address of watched as any) {
      try {
        const txs = await getAddressTxs(address as string);
        for (const tx of txs as any) {
          await processWatchedTx(tx);
        }
      } catch (e) {
        err("catchUp address check failed", address, e.message);
      }
    }

    // Check custodial outgoing bitcoin tx confirmations
    await checkOutgoingConfirmations();

    // Non-custodial accounts: check pending outgoing payments
    const inflightAccounts = await db.keys("inflight:*");
    for (const key of inflightAccounts) {
      const keyType = await db.type(key);
      if (keyType !== "set") continue;
      const paymentIds = await db.sMembers(key);
      for (const pid of paymentIds) {
        try {
          const p = await gf(`payment:${pid}`);
          if (!p || p.confirmed) {
            await db.sRem(key, pid);
            continue;
          }
          const status = await getTxStatus(p.hash) as any;
          if (status.confirmed) {
            p.confirmed = true;
            await s(`payment:${p.id}`, p);
            await db.sRem(key, pid);
            emit(p.uid, "payment", p);
          }
        } catch (e) {
          err("problem checking inflight payment", e.message);
        }
      }
    }
  } catch (e) {
    err("problem catching up", e.message);
  }
};

export const syncBitcoinVault = async (account, user) => {
  const { id, uid, pubkey, fingerprint } = account;

  let nextIndex = account.nextIndex || 0;
  const lastUsed = await findLastUsedIndex(pubkey, fingerprint);
  if (lastUsed > nextIndex) {
    nextIndex = lastUsed;
    account.nextIndex = nextIndex;
    await s(`account:${id}`, account);
  }

  const count = nextIndex + 1;
  const externalAddrs = deriveAddresses(pubkey, fingerprint, count, false);
  const internalAddrs = deriveAddresses(pubkey, fingerprint, count, true);
  const allAddrs = [...externalAddrs, ...internalAddrs];
  const addressSet = new Set(allAddrs);
  const changeSet = new Set(internalAddrs);

  const utxos = await getAddressUtxos(allAddrs);
  const confirmedUtxos = utxos.filter((u) => u.status.confirmed && u.value >= 300);
  const pendingUtxos = utxos.filter((u) => !u.status.confirmed && u.value >= 300);
  const confirmedTotal = confirmedUtxos.reduce((sum, u) => sum + u.value, 0);
  const pendingTotal = pendingUtxos.reduce((sum, u) => sum + u.value, 0);

  const { rate, currency } = await getUserRate(user);

  const newPayments = [];
  const externalSet = new Set(externalAddrs);

  // Scan pending UTXOs for unconfirmed incoming (external only)
  for (const u of pendingUtxos) {
    if (!externalSet.has(u.address)) continue;

    const ref = `${u.txid}:${u.vout}`;
    const existing = await getPayment(ref);
    if (existing?.aid === id) continue;

    if (existing) {
      existing.aid = id;
      await db
        .multi()
        .set(`payment:${existing.id}`, JSON.stringify(existing))
        .lPush(`${id}:payments`, existing.id)
        .exec();
      continue;
    }

    const p = {
      id: v4(),
      aid: id,
      amount: u.value,
      fee: 0,
      hash: u.address,
      confirmed: false,
      rate,
      currency,
      type: PaymentType.bitcoin,
      uid,
      ref,
      created: Date.now(),
    };

    await db
      .multi()
      .set(`payment:${ref}`, p.id)
      .set(`payment:${p.id}`, JSON.stringify(p))
      .lPush(`${id}:payments`, p.id)
      .set(`${id}:payments:last`, p.created)
      .exec();

    newPayments.push(p);
  }

  // Process all transactions from history (incoming + outgoing)
  const txsById = new Map();
  for (const address of allAddrs) {
    const txs = await getAddressTxs(address);
    for (const tx of txs as any) {
      txsById.set(tx.txid, tx);
    }
  }

  for (const tx of txsById.values()) {
    if (!tx.status?.confirmed) continue;

    let inputsFromUs = 0;
    let outputsToUs = 0;
    let outputsToExternal = 0;
    let totalIn = 0;
    let totalOut = 0;

    for (const vin of tx.vin || []) {
      const prev = vin.prevout;
      if (!prev) continue;
      const value = Number.parseInt(prev.value) || 0;
      totalIn += value;
      if (addressSet.has(prev.scriptpubkey_address)) inputsFromUs += value;
    }

    for (const vout of tx.vout || []) {
      const value = Number.parseInt(vout.value) || 0;
      totalOut += value;
      if (addressSet.has(vout.scriptpubkey_address)) outputsToUs += value;
      if (externalSet.has(vout.scriptpubkey_address)) outputsToExternal += value;
    }

    const created = tx.status?.block_time ? tx.status.block_time * 1000 : Date.now();

    if (inputsFromUs) {
      // Outgoing transaction
      const net = outputsToUs - inputsFromUs;
      if (net >= 0) continue;

      const amount = totalOut - outputsToUs;
      if (amount <= 0) continue;

      const existing = await getPayment(tx.txid);
      if (existing?.aid === id) continue;
      if (existing) {
        existing.aid = id;
        await db
          .multi()
          .set(`payment:${existing.id}`, JSON.stringify(existing))
          .lPush(`${id}:payments`, existing.id)
          .exec();
        continue;
      }

      const fee = Math.max(0, totalIn - totalOut);
      const p = {
        id: v4(),
        aid: id,
        amount: -amount,
        fee,
        hash: tx.txid,
        confirmed: true,
        rate,
        currency,
        type: PaymentType.bitcoin,
        uid,
        created,
      };

      await db
        .multi()
        .set(`payment:${tx.txid}`, p.id)
        .set(`payment:${p.id}`, JSON.stringify(p))
        .lPush(`${id}:payments`, p.id)
        .set(`${id}:payments:last`, p.created)
        .exec();
    } else if (outputsToExternal) {
      // Incoming transaction (to external addresses, not from us)
      for (const vout of tx.vout || []) {
        const value = Number.parseInt(vout.value) || 0;
        if (value < 300) continue;
        if (!externalSet.has(vout.scriptpubkey_address)) continue;

        const voutIndex = tx.vout.indexOf(vout);
        const ref = `${tx.txid}:${voutIndex}`;
        const existing = await getPayment(ref);
        if (existing?.aid === id) {
          if (!existing.confirmed) {
            existing.confirmed = true;
            await s(`payment:${existing.id}`, existing);
          }
          continue;
        }

        if (existing) {
          existing.aid = id;
          existing.confirmed = true;
          await db
            .multi()
            .set(`payment:${existing.id}`, JSON.stringify(existing))
            .lPush(`${id}:payments`, existing.id)
            .exec();
          continue;
        }

        const p = {
          id: v4(),
          aid: id,
          amount: value,
          fee: 0,
          hash: vout.scriptpubkey_address,
          confirmed: true,
          rate,
          currency,
          type: PaymentType.bitcoin,
          uid,
          ref,
          created,
        };

        await db
          .multi()
          .set(`payment:${ref}`, p.id)
          .set(`payment:${p.id}`, JSON.stringify(p))
          .lPush(`${id}:payments`, p.id)
          .set(`${id}:payments:last`, p.created)
          .exec();

        newPayments.push(p);
      }
    }
  }

  return { confirmedTotal, pendingTotal, newPayments };
};

export const importAccountHistory = async (account) => {
  try {
    const user = await getUser(account.uid);
    const { confirmedTotal } = await syncBitcoinVault(account, user);

    await tbSetBalance(account.id, confirmedTotal);
    await tbSetPending(account.id, 0);

    account.importedAt = account.importedAt || Date.now();
    await s(`account:${account.id}`, account);
  } catch (e) {
    console.log(e);
    warn("problem importing account history", e.message, account);
  }
};

export const check = async () => {
  if (process.env.URL.includes("dev")) return;
  try {
    const payments = await db.sMembers("pending");

    for (const pr of payments) {
      if (!pr.startsWith("ln")) {
        await db.sRem("pending", pr);
        continue;
      }
      const p = await getPayment(pr);
      if (!p || Date.now() - p.created < 10000) continue;
      const { pays } = await ln.listpays(pr);

      const failed = !pays.length || pays.every((p) => p.status === "failed");
      const completed = pays.find((p) => p.status === "complete");

      try {
        if (completed) await finalize(completed, p);
        else if (failed) await reverse(p);
      } catch (e) {
        err("failed to finalize", p.id, e.message);
        if (e.message?.includes("already been reversed")) {
          await db.sRem("pending", p.hash);
        }
      }
    }
  } catch (e) {
    err("payment check failed", e.message);
  }

  setTimeout(check, 2000);
};

const finalize = async (r, p) => {
  let { preimage } = r;
  if (!preimage) preimage = r.payment_preimage;
  if (!preimage) fail("missing preimage");

  await db.sRem("pending", p.hash);
  l("payment completed", p.id, r.payment_preimage);
  nwcNotify(p);

  const maxfee = p.fee;
  const { amount_msat, invoice_amount_msat } = await ln.decode(p.hash);
  p.fee = Math.round((r.amount_sent_msat - (amount_msat || invoice_amount_msat)) / 1000);
  p.ref = preimage;

  if (!(await g(`payment:${p.id}`)).ref) {
    await s(`payment:${p.id}`, p);

    l("refunding fee", maxfee, p.fee, maxfee - p.fee, p.ref);
    await tbRefund(p.uid, maxfee - p.fee);
  }

  return p;
};

export const reverse = async (p) => {
  await sleep(Math.floor(Math.random() * (1500 - 500 + 1)) + 500);

  const total = Math.abs(p.amount) + p.fee + p.ourfee;
  const ourfee = p.ourfee || 0;
  const credit = Math.round(total * config.fee[PaymentType.lightning]) - ourfee;

  l("reversing", p.id, p.amount, p.fee, total, ourfee, credit);

  // Check payment still exists before reversing
  const exists = await db.exists(`payment:${p.id}`);
  if (!exists) throw new Error("Payment has already been reversed");

  // TB: restore balance + credits
  await tbReverse(p.uid, total, credit);

  // Redis: clean up payment records
  await db
    .multi()
    .del(`payment:${p.id}`)
    .sRem("pending", p.hash)
    .del(`payment:${p.hash}`)
    .lRem(`${p.uid}:payments`, 0, p.id)
    .lRem("payments", 0, p.id)
    .exec();

  warn("reversed", p.id);
};

const freezeCheck = async () => {
  const funds = await ln.listfunds();
  const lnbalance = Math.round(funds.channels.reduce((a, b) => a + b.our_amount_msat, 0) / 1000);

  const bcbalance = Math.round((await bc.getBalance()) * SATS);
  const { bitcoin } = await lq.getBalance();
  const lqbalance = Math.round(bitcoin * SATS);

  const lnthreshold = await g("lightning:threshold");
  const bcthreshold = await g("bitcoin:threshold");
  const lqthreshold = await g("liquid:threshold");

  await s("lightning:limit", Math.max(lnbalance - lnthreshold, 0));
  await s("bitcoin:limit", Math.max(bcbalance - bcthreshold, 0));
  await s("liquid:limit", Math.max(lqbalance - lqthreshold, 0));

  await s("fund:limit", Math.max(lnbalance - lnthreshold, 0));
  await s("ecash:limit", Math.max(lnbalance - lnthreshold, 0));
  await s("bolt12:limit", Math.max(lnbalance - lnthreshold, 0));

  const arkBalance = getArkBalance();
  if (arkBalance) {
    const arkthreshold = (await g("ark:threshold")) || 0;
    await s("ark:available", arkBalance.available);
    await s("ark:limit", Math.max(arkBalance.available - arkthreshold, 0));
  }

  setTimeout(freezeCheck, 10000);
};
setTimeout(freezeCheck, 10_000);