@atomiqlabs/lp-lib 10.3.11 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/index.d.ts +2 -1
  2. package/dist/index.js +2 -4
  3. package/dist/plugins/IPlugin.d.ts +3 -2
  4. package/dist/plugins/PluginManager.d.ts +3 -2
  5. package/dist/plugins/PluginManager.js +2 -2
  6. package/dist/swaps/FromBtcBaseSwap.d.ts +5 -1
  7. package/dist/swaps/FromBtcBaseSwap.js +20 -0
  8. package/dist/swaps/FromBtcBaseSwapHandler.d.ts +1 -0
  9. package/dist/swaps/FromBtcBaseSwapHandler.js +1 -1
  10. package/dist/swaps/FromBtcLnBaseSwapHandler.d.ts +8 -6
  11. package/dist/swaps/FromBtcLnBaseSwapHandler.js +7 -5
  12. package/dist/swaps/SwapHandler.d.ts +1 -4
  13. package/dist/swaps/SwapHandler.js +1 -2
  14. package/dist/swaps/SwapHandlerSwap.d.ts +4 -0
  15. package/dist/swaps/SwapHandlerSwap.js +9 -1
  16. package/dist/swaps/ToBtcBaseSwap.d.ts +3 -1
  17. package/dist/swaps/ToBtcBaseSwap.js +8 -2
  18. package/dist/swaps/ToBtcBaseSwapHandler.d.ts +1 -0
  19. package/dist/swaps/ToBtcBaseSwapHandler.js +1 -1
  20. package/dist/swaps/frombtc_abstract/FromBtcAbs.d.ts +3 -5
  21. package/dist/swaps/frombtc_abstract/FromBtcAbs.js +18 -25
  22. package/dist/swaps/frombtc_abstract/FromBtcSwapAbs.d.ts +1 -4
  23. package/dist/swaps/frombtc_abstract/FromBtcSwapAbs.js +3 -16
  24. package/dist/swaps/frombtc_trusted/FromBtcTrusted.d.ts +6 -9
  25. package/dist/swaps/frombtc_trusted/FromBtcTrusted.js +238 -137
  26. package/dist/swaps/frombtc_trusted/FromBtcTrustedSwap.d.ts +9 -6
  27. package/dist/swaps/frombtc_trusted/FromBtcTrustedSwap.js +15 -10
  28. package/dist/swaps/frombtcln_abstract/FromBtcLnAbs.d.ts +2 -2
  29. package/dist/swaps/frombtcln_abstract/FromBtcLnAbs.js +42 -62
  30. package/dist/swaps/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +1 -6
  31. package/dist/swaps/frombtcln_abstract/FromBtcLnSwapAbs.js +2 -14
  32. package/dist/swaps/frombtcln_trusted/FromBtcLnTrusted.d.ts +3 -5
  33. package/dist/swaps/frombtcln_trusted/FromBtcLnTrusted.js +64 -80
  34. package/dist/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +1 -2
  35. package/dist/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.js +5 -8
  36. package/dist/swaps/tobtc_abstract/ToBtcAbs.d.ts +5 -125
  37. package/dist/swaps/tobtc_abstract/ToBtcAbs.js +41 -334
  38. package/dist/swaps/tobtc_abstract/ToBtcSwapAbs.d.ts +1 -4
  39. package/dist/swaps/tobtc_abstract/ToBtcSwapAbs.js +2 -11
  40. package/dist/swaps/tobtcln_abstract/ToBtcLnAbs.d.ts +5 -55
  41. package/dist/swaps/tobtcln_abstract/ToBtcLnAbs.js +152 -398
  42. package/dist/swaps/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +1 -6
  43. package/dist/swaps/tobtcln_abstract/ToBtcLnSwapAbs.js +2 -15
  44. package/dist/utils/Utils.d.ts +0 -10
  45. package/dist/utils/Utils.js +1 -34
  46. package/dist/wallets/IBitcoinWallet.d.ts +62 -0
  47. package/dist/wallets/IBitcoinWallet.js +2 -0
  48. package/dist/wallets/ILightningWallet.d.ts +118 -0
  49. package/dist/wallets/ILightningWallet.js +37 -0
  50. package/package.json +4 -9
  51. package/src/index.ts +3 -5
  52. package/src/plugins/IPlugin.ts +4 -2
  53. package/src/plugins/PluginManager.ts +6 -3
  54. package/src/swaps/FromBtcBaseSwap.ts +24 -1
  55. package/src/swaps/FromBtcBaseSwapHandler.ts +6 -2
  56. package/src/swaps/FromBtcLnBaseSwapHandler.ts +22 -6
  57. package/src/swaps/SwapHandler.ts +1 -8
  58. package/src/swaps/SwapHandlerSwap.ts +14 -1
  59. package/src/swaps/ToBtcBaseSwap.ts +12 -3
  60. package/src/swaps/ToBtcBaseSwapHandler.ts +6 -2
  61. package/src/swaps/frombtc_abstract/FromBtcAbs.ts +24 -28
  62. package/src/swaps/frombtc_abstract/FromBtcSwapAbs.ts +3 -18
  63. package/src/swaps/frombtc_trusted/FromBtcTrusted.ts +260 -159
  64. package/src/swaps/frombtc_trusted/FromBtcTrustedSwap.ts +22 -15
  65. package/src/swaps/frombtcln_abstract/FromBtcLnAbs.ts +69 -79
  66. package/src/swaps/frombtcln_abstract/FromBtcLnSwapAbs.ts +3 -20
  67. package/src/swaps/frombtcln_trusted/FromBtcLnTrusted.ts +80 -97
  68. package/src/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.ts +6 -9
  69. package/src/swaps/tobtc_abstract/ToBtcAbs.ts +52 -410
  70. package/src/swaps/tobtc_abstract/ToBtcSwapAbs.ts +3 -18
  71. package/src/swaps/tobtcln_abstract/ToBtcLnAbs.ts +157 -434
  72. package/src/swaps/tobtcln_abstract/ToBtcLnSwapAbs.ts +3 -20
  73. package/src/utils/Utils.ts +0 -31
  74. package/src/wallets/IBitcoinWallet.ts +66 -0
  75. package/src/wallets/ILightningWallet.ts +179 -0
  76. package/dist/fees/OneDollarFeeEstimator.d.ts +0 -16
  77. package/dist/fees/OneDollarFeeEstimator.js +0 -71
  78. package/dist/utils/coinselect2/accumulative.d.ts +0 -6
  79. package/dist/utils/coinselect2/accumulative.js +0 -44
  80. package/dist/utils/coinselect2/blackjack.d.ts +0 -6
  81. package/dist/utils/coinselect2/blackjack.js +0 -41
  82. package/dist/utils/coinselect2/index.d.ts +0 -16
  83. package/dist/utils/coinselect2/index.js +0 -40
  84. package/dist/utils/coinselect2/utils.d.ts +0 -64
  85. package/dist/utils/coinselect2/utils.js +0 -121
  86. package/src/fees/OneDollarFeeEstimator.ts +0 -95
  87. package/src/utils/coinselect2/accumulative.js +0 -32
  88. package/src/utils/coinselect2/accumulative.ts +0 -58
  89. package/src/utils/coinselect2/blackjack.js +0 -29
  90. package/src/utils/coinselect2/blackjack.ts +0 -54
  91. package/src/utils/coinselect2/index.js +0 -16
  92. package/src/utils/coinselect2/index.ts +0 -50
  93. package/src/utils/coinselect2/utils.js +0 -110
  94. package/src/utils/coinselect2/utils.ts +0 -183
@@ -12,8 +12,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.FromBtcLnTrusted = void 0;
13
13
  const BN = require("bn.js");
14
14
  const crypto_1 = require("crypto");
15
- const bolt11 = require("@atomiqlabs/bolt11");
16
- const lightning_1 = require("lightning");
17
15
  const FromBtcLnTrustedSwap_1 = require("./FromBtcLnTrustedSwap");
18
16
  const SwapHandler_1 = require("../SwapHandler");
19
17
  const Utils_1 = require("../../utils/Utils");
@@ -25,8 +23,8 @@ const ServerParamDecoder_1 = require("../../utils/paramcoders/server/ServerParam
25
23
  * Swap handler handling from BTCLN swaps using submarine swaps
26
24
  */
27
25
  class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandler {
28
- constructor(storageDirectory, path, chains, lnd, swapPricing, config) {
29
- super(storageDirectory, path, chains, lnd, swapPricing);
26
+ constructor(storageDirectory, path, chains, lightning, swapPricing, config) {
27
+ super(storageDirectory, path, chains, lightning, swapPricing);
30
28
  this.type = SwapHandler_1.SwapHandlerType.FROM_BTCLN_TRUSTED;
31
29
  this.activeSubscriptions = new Map();
32
30
  this.processedTxIds = new Map();
@@ -43,10 +41,10 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
43
41
  * @private
44
42
  */
45
43
  unsubscribeInvoice(paymentHash) {
46
- const sub = this.activeSubscriptions.get(paymentHash);
47
- if (sub == null)
44
+ const controller = this.activeSubscriptions.get(paymentHash);
45
+ if (controller == null)
48
46
  return false;
49
- sub.removeAllListeners();
47
+ controller.abort("Unsubscribed");
50
48
  this.activeSubscriptions.delete(paymentHash);
51
49
  return true;
52
50
  }
@@ -58,19 +56,16 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
58
56
  subscribeToInvoice(invoiceData) {
59
57
  const hash = invoiceData.getHash();
60
58
  //Already subscribed
61
- if (this.activeSubscriptions.has(invoiceData.getHash()))
59
+ if (this.activeSubscriptions.has(hash))
62
60
  return;
63
- const sub = (0, lightning_1.subscribeToInvoice)({ id: hash, lnd: this.LND });
64
- this.swapLogger.debug(invoiceData, "subscribeToInvoice(): Subscribed to invoice payment");
65
- sub.on('invoice_updated', (invoice) => {
61
+ const abortController = new AbortController();
62
+ this.lightning.waitForInvoice(hash, abortController.signal).then(invoice => {
66
63
  this.swapLogger.debug(invoiceData, "subscribeToInvoice(): invoice_updated: ", invoice);
67
- if (!invoice.is_held)
68
- return;
69
64
  this.htlcReceived(invoiceData, invoice).catch(e => console.error(e));
70
- sub.removeAllListeners();
71
65
  this.activeSubscriptions.delete(hash);
72
66
  });
73
- this.activeSubscriptions.set(hash, sub);
67
+ this.swapLogger.debug(invoiceData, "subscribeToInvoice(): Subscribed to invoice payment");
68
+ this.activeSubscriptions.set(hash, abortController);
74
69
  }
75
70
  /**
76
71
  *
@@ -84,31 +79,29 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
84
79
  return true;
85
80
  if (swap.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED)
86
81
  return true;
87
- const parsedPR = bolt11.decode(swap.pr);
88
- const invoice = yield (0, lightning_1.getInvoice)({
89
- id: parsedPR.tagsObject.payment_hash,
90
- lnd: this.LND
91
- });
92
- if (invoice.is_held) {
93
- //Adjust the state of the swap and expiry
94
- try {
95
- yield this.htlcReceived(swap, invoice);
96
- //Result is either FromBtcLnTrustedSwapState.RECEIVED or FromBtcLnTrustedSwapState.CANCELED
97
- }
98
- catch (e) {
99
- console.error(e);
100
- }
101
- }
102
- else if (!invoice.is_confirmed) {
103
- //Not paid
104
- const isInvoiceExpired = parsedPR.timeExpireDate < Date.now() / 1000;
105
- if (isInvoiceExpired) {
106
- yield swap.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED);
107
- return true;
108
- }
109
- this.subscribeToInvoice(swap);
82
+ const parsedPR = yield this.lightning.parsePaymentRequest(swap.pr);
83
+ const invoice = yield this.lightning.getInvoice(parsedPR.id);
84
+ switch (invoice.status) {
85
+ case "held":
86
+ try {
87
+ yield this.htlcReceived(swap, invoice);
88
+ //Result is either FromBtcLnTrustedSwapState.RECEIVED or FromBtcLnTrustedSwapState.CANCELED
89
+ }
90
+ catch (e) {
91
+ console.error(e);
92
+ }
93
+ return false;
94
+ case "confirmed":
95
+ return false;
96
+ default:
97
+ const isInvoiceExpired = parsedPR.expiryEpochMillis < Date.now();
98
+ if (isInvoiceExpired) {
99
+ yield swap.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED);
100
+ return true;
101
+ }
102
+ this.subscribeToInvoice(swap);
103
+ return false;
110
104
  }
111
- return false;
112
105
  });
113
106
  }
114
107
  cancelInvoices(swaps) {
@@ -117,10 +110,7 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
117
110
  //Cancel invoices
118
111
  try {
119
112
  const paymentHash = swap.getHash();
120
- yield (0, lightning_1.cancelHodlInvoice)({
121
- lnd: this.LND,
122
- id: paymentHash
123
- });
113
+ yield this.lightning.cancelHodlInvoice(paymentHash);
124
114
  this.unsubscribeInvoice(paymentHash);
125
115
  this.swapLogger.info(swap, "cancelInvoices(): invoice cancelled!");
126
116
  yield this.removeSwapData(swap);
@@ -163,10 +153,7 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
163
153
  return;
164
154
  yield swap.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED);
165
155
  const paymentHash = swap.getHash();
166
- yield (0, lightning_1.cancelHodlInvoice)({
167
- id: paymentHash,
168
- lnd: this.LND
169
- });
156
+ yield this.lightning.cancelHodlInvoice(paymentHash);
170
157
  this.unsubscribeInvoice(paymentHash);
171
158
  yield this.removeSwapData(swap);
172
159
  this.swapLogger.info(swap, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", swap.pr);
@@ -230,10 +217,7 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
230
217
  //Cancel invoice
231
218
  yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED);
232
219
  yield this.storageManager.saveData(invoice.id, null, invoiceData);
233
- yield (0, lightning_1.cancelHodlInvoice)({
234
- id: invoice.id,
235
- lnd: this.LND
236
- });
220
+ yield this.lightning.cancelHodlInvoice(invoice.id);
237
221
  this.unsubscribeInvoice(invoice.id);
238
222
  yield this.removeSwapData(invoice.id, null);
239
223
  this.swapLogger.info(invoiceData, "htlcReceived(): transaction reverted, refunding lightning: ", invoiceData.pr);
@@ -249,10 +233,7 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
249
233
  }
250
234
  }
251
235
  if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED) {
252
- yield (0, lightning_1.settleHodlInvoice)({
253
- lnd: this.LND,
254
- secret: invoiceData.secret
255
- });
236
+ yield this.lightning.settleHodlInvoice(invoiceData.secret);
256
237
  if (invoiceData.metadata != null)
257
238
  invoiceData.metadata.times.htlcSettled = Date.now();
258
239
  const paymentHash = invoiceData.getHash();
@@ -274,10 +255,7 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
274
255
  */
275
256
  checkInvoiceStatus(paymentHash) {
276
257
  return __awaiter(this, void 0, void 0, function* () {
277
- const invoice = yield (0, lightning_1.getInvoice)({
278
- id: paymentHash,
279
- lnd: this.LND
280
- });
258
+ const invoice = yield this.lightning.getInvoice(paymentHash);
281
259
  const isInvoiceFound = invoice != null;
282
260
  if (!isInvoiceFound)
283
261
  throw {
@@ -303,32 +281,33 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
303
281
  code: 10001,
304
282
  msg: "Invoice expired/canceled"
305
283
  };
306
- const isBeingPaid = invoice.is_held;
307
- if (!isBeingPaid) {
308
- if (invoice.is_canceled)
284
+ switch (invoice.status) {
285
+ case "held":
286
+ return invoice;
287
+ case "canceled":
309
288
  throw {
310
289
  _httpStatus: 200,
311
290
  code: 10001,
312
291
  msg: "Invoice expired/canceled"
313
292
  };
314
- if (invoice.is_confirmed) {
315
- const scTxId = this.processedTxIds.get(paymentHash);
293
+ case "confirmed":
316
294
  throw {
317
295
  _httpStatus: 200,
318
296
  code: 10000,
319
297
  msg: "Invoice already paid",
320
298
  data: {
321
- txId: scTxId
299
+ txId: this.processedTxIds.get(paymentHash)
322
300
  }
323
301
  };
324
- }
325
- throw {
326
- _httpStatus: 200,
327
- code: 10010,
328
- msg: "Invoice yet unpaid"
329
- };
302
+ case "unpaid":
303
+ throw {
304
+ _httpStatus: 200,
305
+ code: 10010,
306
+ msg: "Invoice yet unpaid"
307
+ };
308
+ default:
309
+ throw new Error("Lightning invoice invalid state!");
330
310
  }
331
- return invoice;
332
311
  });
333
312
  }
334
313
  startRestServer(restServer) {
@@ -388,20 +367,18 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
388
367
  const hash = (0, crypto_1.createHash)("sha256").update(secret).digest();
389
368
  const hodlInvoiceObj = {
390
369
  description: chainIdentifier + "-GAS-" + parsedBody.address,
391
- cltv_delta: this.config.minCltv.add(new BN(5)).toNumber(),
392
- expires_at: new Date(Date.now() + (this.config.invoiceTimeoutSeconds * 1000)).toISOString(),
370
+ cltvDelta: this.config.minCltv.add(new BN(5)).toNumber(),
371
+ expiresAt: Date.now() + (this.config.invoiceTimeoutSeconds * 1000),
393
372
  id: hash.toString("hex"),
394
- mtokens: amountBD.mul(new BN(1000)).toString(10),
395
- lnd: null
373
+ mtokens: amountBD.mul(new BN(1000))
396
374
  };
397
- metadata.invoiceRequest = Object.assign({}, hodlInvoiceObj);
398
- hodlInvoiceObj.lnd = this.LND;
399
- const hodlInvoice = yield (0, lightning_1.createHodlInvoice)(hodlInvoiceObj);
375
+ metadata.invoiceRequest = hodlInvoiceObj;
376
+ const hodlInvoice = yield this.lightning.createHodlInvoice(hodlInvoiceObj);
400
377
  abortController.signal.throwIfAborted();
401
378
  metadata.times.invoiceCreated = Date.now();
402
379
  metadata.invoiceResponse = Object.assign({}, hodlInvoice);
403
380
  console.log("[From BTC-LN: REST.CreateInvoice] hodl invoice created: ", hodlInvoice);
404
- const createdSwap = new FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwap(chainIdentifier, hodlInvoice.request, swapFee, swapFeeInToken, totalInToken, secret.toString("hex"), parsedBody.address);
381
+ const createdSwap = new FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwap(chainIdentifier, hodlInvoice.request, hodlInvoice.mtokens, swapFee, swapFeeInToken, totalInToken, secret.toString("hex"), parsedBody.address);
405
382
  metadata.times.swapCreated = Date.now();
406
383
  createdSwap.metadata = metadata;
407
384
  yield PluginManager_1.PluginManager.swapCreate(createdSwap);
@@ -493,6 +470,13 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
493
470
  init() {
494
471
  return __awaiter(this, void 0, void 0, function* () {
495
472
  yield this.storageManager.loadData(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwap);
473
+ //Check if all swaps contain a valid amount
474
+ for (let swap of yield this.storageManager.query([])) {
475
+ if (swap.amount == null) {
476
+ const parsedPR = yield this.lightning.parsePaymentRequest(swap.pr);
477
+ swap.amount = parsedPR.mtokens.add(new BN(999)).div(new BN(1000));
478
+ }
479
+ }
496
480
  yield PluginManager_1.PluginManager.serviceInitialize(this);
497
481
  });
498
482
  }
@@ -16,12 +16,11 @@ export declare class FromBtcLnTrustedSwap<T extends SwapData = SwapData> extends
16
16
  readonly dstAddress: string;
17
17
  readonly secret: string;
18
18
  scRawTx: string;
19
- constructor(chainIdentifier: string, pr: string, swapFee: BN, swapFeeInToken: BN, output: BN, secret: string, dstAddress: string);
19
+ constructor(chainIdentifier: string, pr: string, inputMtokens: BN, swapFee: BN, swapFeeInToken: BN, output: BN, secret: string, dstAddress: string);
20
20
  constructor(obj: any);
21
21
  getHash(): string;
22
22
  getSequence(): BN;
23
23
  serialize(): any;
24
- getTotalInputAmount(): BN;
25
24
  isFailed(): boolean;
26
25
  isInitiated(): boolean;
27
26
  isSuccess(): boolean;
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FromBtcLnTrustedSwap = exports.FromBtcLnTrustedSwapState = void 0;
4
4
  const BN = require("bn.js");
5
5
  const crypto_1 = require("crypto");
6
- const bolt11 = require("@atomiqlabs/bolt11");
7
6
  const FromBtcBaseSwap_1 = require("../FromBtcBaseSwap");
7
+ const Utils_1 = require("../../utils/Utils");
8
8
  var FromBtcLnTrustedSwapState;
9
9
  (function (FromBtcLnTrustedSwapState) {
10
10
  FromBtcLnTrustedSwapState[FromBtcLnTrustedSwapState["REFUNDED"] = -2] = "REFUNDED";
@@ -16,9 +16,9 @@ var FromBtcLnTrustedSwapState;
16
16
  FromBtcLnTrustedSwapState[FromBtcLnTrustedSwapState["SETTLED"] = 4] = "SETTLED";
17
17
  })(FromBtcLnTrustedSwapState = exports.FromBtcLnTrustedSwapState || (exports.FromBtcLnTrustedSwapState = {}));
18
18
  class FromBtcLnTrustedSwap extends FromBtcBaseSwap_1.FromBtcBaseSwap {
19
- constructor(chainIdOrObj, pr, swapFee, swapFeeInToken, output, secret, dstAddress) {
19
+ constructor(chainIdOrObj, pr, inputMtokens, swapFee, swapFeeInToken, output, secret, dstAddress) {
20
20
  if (typeof (chainIdOrObj) === "string") {
21
- super(chainIdOrObj, swapFee, swapFeeInToken);
21
+ super(chainIdOrObj, inputMtokens.add(new BN(999)).div(new BN(1000)), swapFee, swapFeeInToken);
22
22
  this.state = FromBtcLnTrustedSwapState.CREATED;
23
23
  this.pr = pr;
24
24
  this.output = output;
@@ -28,7 +28,7 @@ class FromBtcLnTrustedSwap extends FromBtcBaseSwap_1.FromBtcBaseSwap {
28
28
  else {
29
29
  super(chainIdOrObj);
30
30
  this.pr = chainIdOrObj.pr;
31
- this.output = new BN(chainIdOrObj.output);
31
+ this.output = (0, Utils_1.deserializeBN)(chainIdOrObj.output);
32
32
  this.secret = chainIdOrObj.secret;
33
33
  this.dstAddress = chainIdOrObj.dstAddress;
34
34
  this.scRawTx = chainIdOrObj.scRawTx;
@@ -44,15 +44,12 @@ class FromBtcLnTrustedSwap extends FromBtcBaseSwap_1.FromBtcBaseSwap {
44
44
  serialize() {
45
45
  const partialSerialized = super.serialize();
46
46
  partialSerialized.pr = this.pr;
47
- partialSerialized.output = this.output.toString(10);
47
+ partialSerialized.output = (0, Utils_1.serializeBN)(this.output);
48
48
  partialSerialized.secret = this.secret;
49
49
  partialSerialized.dstAddress = this.dstAddress;
50
50
  partialSerialized.scRawTx = this.scRawTx;
51
51
  return partialSerialized;
52
52
  }
53
- getTotalInputAmount() {
54
- return new BN(bolt11.decode(this.pr).millisatoshis).add(new BN(999)).div(new BN(1000));
55
- }
56
53
  isFailed() {
57
54
  return this.state === FromBtcLnTrustedSwapState.CANCELED || this.state === FromBtcLnTrustedSwapState.REFUNDED;
58
55
  }
@@ -1,37 +1,22 @@
1
1
  import { Express } from "express";
2
2
  import * as BN from "bn.js";
3
- import * as bitcoin from "bitcoinjs-lib";
4
3
  import { ToBtcSwapAbs, ToBtcSwapState } from "./ToBtcSwapAbs";
5
4
  import { MultichainData, SwapHandlerType } from "../SwapHandler";
6
5
  import { ISwapPrice } from "../ISwapPrice";
7
6
  import { BtcTx, ClaimEvent, InitializeEvent, RefundEvent, SwapData, BitcoinRpc, BtcBlock } from "@atomiqlabs/base";
8
- import { AuthenticatedLnd } from "lightning";
9
7
  import { IIntermediaryStorage } from "../../storage/IIntermediaryStorage";
10
- import { IBtcFeeEstimator } from "../../fees/IBtcFeeEstimator";
11
- import { CoinselectTxInput, CoinselectTxOutput } from "../../utils/coinselect2/utils";
12
8
  import { ToBtcBaseConfig, ToBtcBaseSwapHandler } from "../ToBtcBaseSwapHandler";
13
9
  import { PromiseQueue } from "promise-queue-ts";
14
- type SpendableUtxo = {
15
- address: string;
16
- address_format: string;
17
- confirmation_count: number;
18
- output_script: string;
19
- tokens: number;
20
- transaction_id: string;
21
- transaction_vout: number;
22
- };
10
+ import { IBitcoinWallet } from "../../wallets/IBitcoinWallet";
23
11
  export type ToBtcConfig = ToBtcBaseConfig & {
24
12
  sendSafetyFactor: BN;
25
- bitcoinNetwork: bitcoin.networks.Network;
26
13
  minChainCltv: BN;
27
- networkFeeMultiplierPPM: BN;
14
+ networkFeeMultiplier: number;
28
15
  minConfirmations: number;
29
16
  maxConfirmations: number;
30
17
  maxConfTarget: number;
31
18
  minConfTarget: number;
32
19
  txCheckInterval: number;
33
- feeEstimator?: IBtcFeeEstimator;
34
- onchainReservedPerChannel?: number;
35
20
  };
36
21
  export type ToBtcRequestType = {
37
22
  address: string;
@@ -47,33 +32,15 @@ export type ToBtcRequestType = {
47
32
  * Handler for to BTC swaps, utilizing PTLCs (proof-time locked contracts) using btc relay (on-chain bitcoin SPV)
48
33
  */
49
34
  export declare class ToBtcAbs extends ToBtcBaseSwapHandler<ToBtcSwapAbs, ToBtcSwapState> {
50
- protected readonly CONFIRMATIONS_REQUIRED = 1;
51
- protected readonly ADDRESS_FORMAT_MAP: {
52
- p2wpkh: string;
53
- np2wpkh: string;
54
- p2tr: string;
55
- };
56
- protected readonly LND_CHANGE_OUTPUT_TYPE = "p2tr";
57
- protected readonly UTXO_CACHE_TIMEOUT: number;
58
- protected readonly CHANNEL_COUNT_CACHE_TIMEOUT: number;
59
35
  readonly type = SwapHandlerType.TO_BTC;
60
36
  activeSubscriptions: {
61
37
  [txId: string]: ToBtcSwapAbs;
62
38
  };
63
- cachedUtxos: {
64
- utxos: (CoinselectTxInput & {
65
- confirmations: number;
66
- })[];
67
- timestamp: number;
68
- };
69
- cachedChannelCount: {
70
- count: number;
71
- timestamp: number;
72
- };
73
39
  bitcoinRpc: BitcoinRpc<BtcBlock>;
40
+ bitcoin: IBitcoinWallet;
74
41
  sendBtcQueue: PromiseQueue;
75
42
  readonly config: ToBtcConfig;
76
- constructor(storageDirectory: IIntermediaryStorage<ToBtcSwapAbs>, path: string, chainData: MultichainData, lnd: AuthenticatedLnd, swapPricing: ISwapPrice, bitcoinRpc: BitcoinRpc<BtcBlock>, config: ToBtcConfig);
43
+ constructor(storageDirectory: IIntermediaryStorage<ToBtcSwapAbs>, path: string, chainData: MultichainData, bitcoin: IBitcoinWallet, swapPricing: ISwapPrice, bitcoinRpc: BitcoinRpc<BtcBlock>, config: ToBtcConfig);
77
44
  /**
78
45
  * Returns the payment hash of the swap, takes swap nonce into account. Payment hash is chain-specific.
79
46
  *
@@ -81,61 +48,13 @@ export declare class ToBtcAbs extends ToBtcBaseSwapHandler<ToBtcSwapAbs, ToBtcSw
81
48
  * @param address
82
49
  * @param nonce
83
50
  * @param amount
84
- * @param bitcoinNetwork
85
51
  */
86
52
  private getHash;
87
- /**
88
- * Returns spendable UTXOs, these are either confirmed UTXOs, or unconfirmed ones that are either whitelisted,
89
- * or created by our transactions (and therefore only we could doublespend)
90
- *
91
- * @private
92
- */
93
- protected getSpendableUtxos(): Promise<SpendableUtxo[]>;
94
- /**
95
- * Returns utxo pool to be used by the coinselection algorithm
96
- *
97
- * @private
98
- */
99
- protected getUtxoPool(useCached?: boolean): Promise<(CoinselectTxInput & {
100
- confirmations: number;
101
- })[]>;
102
- /**
103
- * Checks whether a coinselect result leaves enough funds to cover potential lightning anchor transaction fees
104
- *
105
- * @param utxoPool
106
- * @param obj
107
- * @param satsPerVbyte
108
- * @param useCached Whether to use a cached channel count
109
- * @param initialOutputLength
110
- * @private
111
- * @returns true if alright, false if the coinselection doesn't leave enough funds for anchor fees
112
- */
113
- protected isLeavingEnoughForLightningAnchors(utxoPool: CoinselectTxInput[], obj: {
114
- inputs?: CoinselectTxInput[];
115
- outputs?: CoinselectTxOutput[];
116
- }, satsPerVbyte: BN, useCached?: boolean, initialOutputLength?: number): Promise<boolean>;
117
- /**
118
- * Gets the change address from the underlying LND instance
119
- *
120
- * @private
121
- */
122
- protected getChangeAddress(): Promise<string>;
123
- /**
124
- * Computes bitcoin on-chain network fee, takes channel reserve & network fee multiplier into consideration
125
- *
126
- * @param targetAddress Bitcoin address to send the funds to
127
- * @param targetAmount Amount of funds to send to the address
128
- * @param estimate Whether the chain fee should be just estimated and therefore cached utxo set could be used
129
- * @param multiplierPPM Multiplier for the sats/vB returned from the fee estimator in PPM (parts per million)
130
- * @private
131
- * @returns Fee estimate & inputs/outputs to use when constructing transaction, or null in case of not enough funds
132
- */
133
- private getChainFee;
134
53
  /**
135
54
  * Tries to claim the swap after our transaction was confirmed
136
55
  *
137
56
  * @param tx
138
- * @param payment
57
+ * @param swap
139
58
  * @param vout
140
59
  */
141
60
  private tryClaimSwap;
@@ -173,44 +92,6 @@ export declare class ToBtcAbs extends ToBtcBaseSwapHandler<ToBtcSwapAbs, ToBtcSw
173
92
  * @throws DefinedRuntimeError will throw an error in case the actual fee is higher than quoted fee
174
93
  */
175
94
  protected checkCalculatedTxFee(quotedSatsPerVbyte: BN, actualSatsPerVbyte: BN): void;
176
- /**
177
- * Runs sanity check on the calculated fee for the transaction
178
- *
179
- * @param psbt
180
- * @param tx
181
- * @param maxAllowedSatsPerVbyte
182
- * @param actualSatsPerVbyte
183
- * @private
184
- * @throws {Error} Will throw an error if the fee sanity check doesn't pass
185
- */
186
- protected checkPsbtFee(psbt: bitcoin.Psbt, tx: bitcoin.Transaction, maxAllowedSatsPerVbyte: BN, actualSatsPerVbyte: BN): BN;
187
- /**
188
- * Create PSBT for swap payout from coinselection result
189
- *
190
- * @param address
191
- * @param amount
192
- * @param escrowNonce
193
- * @param coinselectResult
194
- * @private
195
- */
196
- private getPsbt;
197
- /**
198
- * Signs provided PSBT and also returns a raw signed transaction
199
- *
200
- * @param psbt
201
- * @private
202
- */
203
- protected signPsbt(psbt: bitcoin.Psbt): Promise<{
204
- psbt: bitcoin.Psbt;
205
- rawTx: string;
206
- }>;
207
- /**
208
- * Sends raw bitcoin transaction
209
- *
210
- * @param rawTx
211
- * @private
212
- */
213
- protected sendRawTransaction(rawTx: string): Promise<void>;
214
95
  /**
215
96
  * Sends a bitcoin transaction to payout BTC for a swap
216
97
  *
@@ -287,4 +168,3 @@ export declare class ToBtcAbs extends ToBtcBaseSwapHandler<ToBtcSwapAbs, ToBtcSw
287
168
  init(): Promise<void>;
288
169
  getInfoData(): any;
289
170
  }
290
- export {};