@atomiqlabs/lp-lib 11.0.5 → 12.0.0-beta.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 (100) hide show
  1. package/dist/info/InfoHandler.js +3 -12
  2. package/dist/plugins/IPlugin.d.ts +34 -35
  3. package/dist/plugins/IPlugin.js +7 -8
  4. package/dist/plugins/PluginManager.d.ts +29 -30
  5. package/dist/plugins/PluginManager.js +160 -188
  6. package/dist/prices/BinanceSwapPrice.d.ts +1 -2
  7. package/dist/prices/BinanceSwapPrice.js +56 -70
  8. package/dist/prices/CoinGeckoSwapPrice.d.ts +2 -3
  9. package/dist/prices/CoinGeckoSwapPrice.js +30 -42
  10. package/dist/prices/OKXSwapPrice.d.ts +1 -2
  11. package/dist/prices/OKXSwapPrice.js +56 -70
  12. package/dist/storage/IIntermediaryStorage.d.ts +8 -5
  13. package/dist/storagemanager/IntermediaryStorageManager.d.ts +8 -5
  14. package/dist/storagemanager/IntermediaryStorageManager.js +52 -61
  15. package/dist/storagemanager/StorageManager.js +42 -59
  16. package/dist/swaps/FromBtcBaseSwap.d.ts +7 -8
  17. package/dist/swaps/FromBtcBaseSwap.js +2 -3
  18. package/dist/swaps/FromBtcBaseSwapHandler.d.ts +44 -31
  19. package/dist/swaps/FromBtcBaseSwapHandler.js +217 -196
  20. package/dist/swaps/FromBtcLnBaseSwapHandler.d.ts +1 -2
  21. package/dist/swaps/FromBtcLnBaseSwapHandler.js +13 -24
  22. package/dist/swaps/ISwapPrice.d.ts +4 -5
  23. package/dist/swaps/ISwapPrice.js +8 -30
  24. package/dist/swaps/SwapHandler.d.ts +26 -15
  25. package/dist/swaps/SwapHandler.js +107 -66
  26. package/dist/swaps/SwapHandlerSwap.d.ts +22 -11
  27. package/dist/swaps/SwapHandlerSwap.js +32 -8
  28. package/dist/swaps/ToBtcBaseSwap.d.ts +16 -17
  29. package/dist/swaps/ToBtcBaseSwap.js +4 -4
  30. package/dist/swaps/ToBtcBaseSwapHandler.d.ts +17 -17
  31. package/dist/swaps/ToBtcBaseSwapHandler.js +140 -155
  32. package/dist/swaps/frombtc_abstract/FromBtcAbs.d.ts +8 -15
  33. package/dist/swaps/frombtc_abstract/FromBtcAbs.js +131 -196
  34. package/dist/swaps/frombtc_abstract/FromBtcSwapAbs.d.ts +3 -5
  35. package/dist/swaps/frombtc_abstract/FromBtcSwapAbs.js +4 -4
  36. package/dist/swaps/frombtc_trusted/FromBtcTrusted.d.ts +10 -8
  37. package/dist/swaps/frombtc_trusted/FromBtcTrusted.js +330 -362
  38. package/dist/swaps/frombtc_trusted/FromBtcTrustedSwap.d.ts +10 -10
  39. package/dist/swaps/frombtc_trusted/FromBtcTrustedSwap.js +7 -4
  40. package/dist/swaps/frombtcln_abstract/FromBtcLnAbs.d.ts +8 -8
  41. package/dist/swaps/frombtcln_abstract/FromBtcLnAbs.js +330 -400
  42. package/dist/swaps/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +10 -4
  43. package/dist/swaps/frombtcln_abstract/FromBtcLnSwapAbs.js +36 -6
  44. package/dist/swaps/frombtcln_trusted/FromBtcLnTrusted.d.ts +8 -7
  45. package/dist/swaps/frombtcln_trusted/FromBtcLnTrusted.js +251 -273
  46. package/dist/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +5 -5
  47. package/dist/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.js +7 -5
  48. package/dist/swaps/tobtc_abstract/ToBtcAbs.d.ts +13 -12
  49. package/dist/swaps/tobtc_abstract/ToBtcAbs.js +261 -323
  50. package/dist/swaps/tobtc_abstract/ToBtcSwapAbs.d.ts +4 -4
  51. package/dist/swaps/tobtc_abstract/ToBtcSwapAbs.js +7 -6
  52. package/dist/swaps/tobtcln_abstract/ToBtcLnAbs.d.ts +22 -21
  53. package/dist/swaps/tobtcln_abstract/ToBtcLnAbs.js +398 -453
  54. package/dist/swaps/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +3 -2
  55. package/dist/swaps/tobtcln_abstract/ToBtcLnSwapAbs.js +10 -6
  56. package/dist/utils/Utils.d.ts +2 -3
  57. package/dist/utils/Utils.js +4 -14
  58. package/dist/utils/paramcoders/LegacyParamEncoder.js +3 -14
  59. package/dist/utils/paramcoders/ParamDecoder.js +53 -65
  60. package/dist/utils/paramcoders/SchemaVerifier.d.ts +4 -5
  61. package/dist/utils/paramcoders/SchemaVerifier.js +8 -9
  62. package/dist/utils/paramcoders/server/ServerParamDecoder.js +1 -1
  63. package/dist/utils/paramcoders/server/ServerParamEncoder.js +3 -14
  64. package/dist/wallets/IBitcoinWallet.d.ts +4 -5
  65. package/dist/wallets/ILightningWallet.d.ts +20 -21
  66. package/dist/wallets/ILightningWallet.js +1 -1
  67. package/package.json +4 -6
  68. package/src/plugins/IPlugin.ts +28 -29
  69. package/src/plugins/PluginManager.ts +21 -22
  70. package/src/prices/BinanceSwapPrice.ts +3 -4
  71. package/src/prices/CoinGeckoSwapPrice.ts +4 -5
  72. package/src/prices/OKXSwapPrice.ts +3 -4
  73. package/src/storage/IIntermediaryStorage.ts +4 -5
  74. package/src/storagemanager/IntermediaryStorageManager.ts +17 -9
  75. package/src/swaps/FromBtcBaseSwap.ts +9 -10
  76. package/src/swaps/FromBtcBaseSwapHandler.ts +133 -91
  77. package/src/swaps/FromBtcLnBaseSwapHandler.ts +2 -3
  78. package/src/swaps/ISwapPrice.ts +10 -20
  79. package/src/swaps/SwapHandler.ts +101 -35
  80. package/src/swaps/SwapHandlerSwap.ts +42 -17
  81. package/src/swaps/ToBtcBaseSwap.ts +20 -18
  82. package/src/swaps/ToBtcBaseSwapHandler.ts +33 -33
  83. package/src/swaps/frombtc_abstract/FromBtcAbs.ts +64 -97
  84. package/src/swaps/frombtc_abstract/FromBtcSwapAbs.ts +7 -8
  85. package/src/swaps/frombtc_trusted/FromBtcTrusted.ts +56 -55
  86. package/src/swaps/frombtc_trusted/FromBtcTrustedSwap.ts +28 -21
  87. package/src/swaps/frombtcln_abstract/FromBtcLnAbs.ts +81 -116
  88. package/src/swaps/frombtcln_abstract/FromBtcLnSwapAbs.ts +73 -9
  89. package/src/swaps/frombtcln_trusted/FromBtcLnTrusted.ts +39 -36
  90. package/src/swaps/frombtcln_trusted/FromBtcLnTrustedSwap.ts +26 -12
  91. package/src/swaps/tobtc_abstract/ToBtcAbs.ts +82 -98
  92. package/src/swaps/tobtc_abstract/ToBtcSwapAbs.ts +25 -20
  93. package/src/swaps/tobtcln_abstract/ToBtcLnAbs.ts +106 -118
  94. package/src/swaps/tobtcln_abstract/ToBtcLnSwapAbs.ts +17 -9
  95. package/src/utils/Utils.ts +3 -4
  96. package/src/utils/paramcoders/ParamDecoder.ts +5 -5
  97. package/src/utils/paramcoders/SchemaVerifier.ts +10 -11
  98. package/src/utils/paramcoders/server/ServerParamDecoder.ts +1 -1
  99. package/src/wallets/IBitcoinWallet.ts +4 -5
  100. package/src/wallets/ILightningWallet.ts +21 -22
@@ -1,16 +1,6 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.FromBtcLnTrusted = void 0;
13
- const BN = require("bn.js");
14
4
  const crypto_1 = require("crypto");
15
5
  const FromBtcLnTrustedSwap_1 = require("./FromBtcLnTrustedSwap");
16
6
  const SwapHandler_1 = require("../SwapHandler");
@@ -18,7 +8,6 @@ const Utils_1 = require("../../utils/Utils");
18
8
  const SchemaVerifier_1 = require("../../utils/paramcoders/SchemaVerifier");
19
9
  const PluginManager_1 = require("../../plugins/PluginManager");
20
10
  const FromBtcLnBaseSwapHandler_1 = require("../FromBtcLnBaseSwapHandler");
21
- const ServerParamDecoder_1 = require("../../utils/paramcoders/server/ServerParamDecoder");
22
11
  /**
23
12
  * Swap handler handling from BTCLN swaps using submarine swaps
24
13
  */
@@ -26,13 +15,11 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
26
15
  constructor(storageDirectory, path, chains, lightning, swapPricing, config) {
27
16
  super(storageDirectory, path, chains, lightning, swapPricing);
28
17
  this.type = SwapHandler_1.SwapHandlerType.FROM_BTCLN_TRUSTED;
18
+ this.swapType = null;
29
19
  this.activeSubscriptions = new Map();
30
20
  this.processedTxIds = new Map();
31
21
  this.config = config;
32
22
  this.config.invoiceTimeoutSeconds = this.config.invoiceTimeoutSeconds || 90;
33
- for (let chainId in chains.chains) {
34
- this.allowedTokens[chainId] = new Set([chains.chains[chainId].swapContract.getNativeCurrencyAddress()]);
35
- }
36
23
  }
37
24
  /**
38
25
  * Unsubscribe from the pending lightning network invoice
@@ -54,7 +41,7 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
54
41
  * @param invoiceData
55
42
  */
56
43
  subscribeToInvoice(invoiceData) {
57
- const hash = invoiceData.getHash();
44
+ const hash = invoiceData.getIdentifierHash();
58
45
  //Already subscribed
59
46
  if (this.activeSubscriptions.has(hash))
60
47
  return;
@@ -73,91 +60,83 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
73
60
  * @protected
74
61
  * @returns {Promise<boolean>} Whether the invoice should be cancelled
75
62
  */
76
- processPastSwap(swap) {
77
- return __awaiter(this, void 0, void 0, function* () {
78
- if (swap.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED)
79
- return true;
80
- if (swap.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED)
81
- return true;
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;
104
- }
105
- });
106
- }
107
- cancelInvoices(swaps) {
108
- return __awaiter(this, void 0, void 0, function* () {
109
- for (let swap of swaps) {
110
- //Cancel invoices
63
+ async processPastSwap(swap) {
64
+ if (swap.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED)
65
+ return true;
66
+ if (swap.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED)
67
+ return true;
68
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
69
+ const invoice = await this.lightning.getInvoice(parsedPR.id);
70
+ switch (invoice.status) {
71
+ case "held":
111
72
  try {
112
- const paymentHash = swap.getHash();
113
- yield this.lightning.cancelHodlInvoice(paymentHash);
114
- this.unsubscribeInvoice(paymentHash);
115
- this.swapLogger.info(swap, "cancelInvoices(): invoice cancelled!");
116
- yield this.removeSwapData(swap);
73
+ await this.htlcReceived(swap, invoice);
74
+ //Result is either FromBtcLnTrustedSwapState.RECEIVED or FromBtcLnTrustedSwapState.CANCELED
117
75
  }
118
76
  catch (e) {
119
- this.swapLogger.error(swap, "cancelInvoices(): cannot cancel hodl invoice id", e);
77
+ console.error(e);
78
+ }
79
+ return false;
80
+ case "confirmed":
81
+ return false;
82
+ default:
83
+ const isInvoiceExpired = parsedPR.expiryEpochMillis < Date.now();
84
+ if (isInvoiceExpired) {
85
+ await swap.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED);
86
+ return true;
120
87
  }
88
+ this.subscribeToInvoice(swap);
89
+ return false;
90
+ }
91
+ }
92
+ async cancelInvoices(swaps) {
93
+ for (let swap of swaps) {
94
+ //Cancel invoices
95
+ try {
96
+ const paymentHash = swap.getIdentifierHash();
97
+ await this.lightning.cancelHodlInvoice(paymentHash);
98
+ this.unsubscribeInvoice(paymentHash);
99
+ this.swapLogger.info(swap, "cancelInvoices(): invoice cancelled!");
100
+ await this.removeSwapData(swap);
121
101
  }
122
- });
102
+ catch (e) {
103
+ this.swapLogger.error(swap, "cancelInvoices(): cannot cancel hodl invoice id", e);
104
+ }
105
+ }
123
106
  }
124
107
  /**
125
108
  * Checks past swaps, refunds and deletes ones that are already expired.
126
109
  */
127
- processPastSwaps() {
128
- return __awaiter(this, void 0, void 0, function* () {
129
- const cancelInvoices = [];
130
- const queriedData = yield this.storageManager.query([
131
- {
132
- key: "state",
133
- value: [
134
- FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CREATED,
135
- FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED,
136
- FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SENT,
137
- FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED,
138
- FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED,
139
- FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED,
140
- ]
141
- }
142
- ]);
143
- for (let swap of queriedData) {
144
- if (yield this.processPastSwap(swap))
145
- cancelInvoices.push(swap);
110
+ async processPastSwaps() {
111
+ const cancelInvoices = [];
112
+ const queriedData = await this.storageManager.query([
113
+ {
114
+ key: "state",
115
+ value: [
116
+ FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CREATED,
117
+ FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED,
118
+ FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SENT,
119
+ FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED,
120
+ FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED,
121
+ FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED,
122
+ ]
146
123
  }
147
- yield this.cancelInvoices(cancelInvoices);
148
- });
124
+ ]);
125
+ for (let { obj: swap } of queriedData) {
126
+ if (await this.processPastSwap(swap))
127
+ cancelInvoices.push(swap);
128
+ }
129
+ await this.cancelInvoices(cancelInvoices);
149
130
  }
150
- cancelSwapAndInvoice(swap) {
151
- return __awaiter(this, void 0, void 0, function* () {
152
- if (swap.state !== FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED)
153
- return;
154
- yield swap.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED);
155
- const paymentHash = swap.getHash();
156
- yield this.lightning.cancelHodlInvoice(paymentHash);
157
- this.unsubscribeInvoice(paymentHash);
158
- yield this.removeSwapData(swap);
159
- this.swapLogger.info(swap, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", swap.pr);
160
- });
131
+ async cancelSwapAndInvoice(swap) {
132
+ if (swap.state !== FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED)
133
+ return;
134
+ await swap.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CANCELED);
135
+ const paymentHash = swap.getIdentifierHash();
136
+ await this.lightning.cancelHodlInvoice(paymentHash);
137
+ this.unsubscribeInvoice(paymentHash);
138
+ await this.removeSwapData(swap);
139
+ this.swapLogger.info(swap, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", swap.pr);
161
140
  }
162
141
  /**
163
142
  * Saves the state of received HTLC of the lightning payment
@@ -165,104 +144,102 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
165
144
  * @param invoiceData
166
145
  * @param invoice
167
146
  */
168
- htlcReceived(invoiceData, invoice) {
169
- return __awaiter(this, void 0, void 0, function* () {
170
- const { swapContract, signer } = this.getChain(invoiceData.chainIdentifier);
171
- //Important to prevent race condition and issuing 2 signed init messages at the same time
172
- if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CREATED) {
147
+ async htlcReceived(invoiceData, invoice) {
148
+ const { swapContract, signer } = this.getChain(invoiceData.chainIdentifier);
149
+ //Important to prevent race condition and issuing 2 signed init messages at the same time
150
+ if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CREATED) {
151
+ if (invoiceData.metadata != null)
152
+ invoiceData.metadata.times.htlcReceived = Date.now();
153
+ await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED);
154
+ await this.storageManager.saveData(invoice.id, null, invoiceData);
155
+ }
156
+ if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED) {
157
+ const balance = swapContract.getBalance(signer.getAddress(), invoiceData.token, false);
158
+ try {
159
+ await this.checkBalance(invoiceData.output, balance, null);
173
160
  if (invoiceData.metadata != null)
174
- invoiceData.metadata.times.htlcReceived = Date.now();
175
- yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED);
176
- yield this.storageManager.saveData(invoice.id, null, invoiceData);
161
+ invoiceData.metadata.times.htlcBalanceChecked = Date.now();
177
162
  }
178
- if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED) {
179
- const balance = swapContract.getBalance(signer.getAddress(), swapContract.getNativeCurrencyAddress(), false);
180
- try {
181
- yield this.checkBalance(invoiceData.output, balance, null);
182
- if (invoiceData.metadata != null)
183
- invoiceData.metadata.times.htlcBalanceChecked = Date.now();
184
- }
185
- catch (e) {
186
- yield this.cancelSwapAndInvoice(invoiceData);
187
- throw e;
188
- }
189
- if (invoiceData.state !== FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED)
190
- return;
191
- const txns = yield swapContract.txsTransfer(signer.getAddress(), swapContract.getNativeCurrencyAddress(), invoiceData.output, invoiceData.dstAddress);
192
- let unlock = invoiceData.lock(Infinity);
193
- if (unlock == null)
194
- return;
195
- const result = yield swapContract.sendAndConfirm(signer, txns, true, null, false, (txId, rawTx) => __awaiter(this, void 0, void 0, function* () {
196
- invoiceData.txIds = { init: txId };
197
- invoiceData.scRawTx = rawTx;
198
- if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED) {
199
- yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SENT);
200
- yield this.storageManager.saveData(invoice.id, null, invoiceData);
201
- }
202
- })).catch(e => console.error(e));
203
- if (result == null) {
204
- //Cancel invoice
205
- yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED);
206
- yield this.storageManager.saveData(invoice.id, null, invoiceData);
207
- yield this.lightning.cancelHodlInvoice(invoice.id);
208
- this.unsubscribeInvoice(invoice.id);
209
- yield this.removeSwapData(invoice.id, null);
210
- this.swapLogger.info(invoiceData, "htlcReceived(): transaction sending failed, refunding lightning: ", invoiceData.pr);
211
- throw {
212
- code: 20002,
213
- msg: "Transaction sending failed"
214
- };
215
- }
216
- else {
217
- //Successfully paid
218
- yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED);
219
- yield this.storageManager.saveData(invoice.id, null, invoiceData);
220
- }
221
- unlock();
222
- unlock = null;
163
+ catch (e) {
164
+ await this.cancelSwapAndInvoice(invoiceData);
165
+ throw e;
223
166
  }
224
- if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SENT) {
225
- if (invoiceData.isLocked())
226
- return;
227
- const txStatus = yield swapContract.getTxStatus(invoiceData.scRawTx);
228
- if (txStatus === "not_found") {
229
- //Retry
230
- invoiceData.txIds = { init: null };
231
- invoiceData.scRawTx = null;
232
- yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED);
233
- yield this.storageManager.saveData(invoice.id, null, invoiceData);
234
- }
235
- if (txStatus === "reverted") {
236
- //Cancel invoice
237
- yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED);
238
- yield this.storageManager.saveData(invoice.id, null, invoiceData);
239
- yield this.lightning.cancelHodlInvoice(invoice.id);
240
- this.unsubscribeInvoice(invoice.id);
241
- yield this.removeSwapData(invoice.id, null);
242
- this.swapLogger.info(invoiceData, "htlcReceived(): transaction reverted, refunding lightning: ", invoiceData.pr);
243
- throw {
244
- code: 20002,
245
- msg: "Transaction reverted"
246
- };
247
- }
248
- if (txStatus === "success") {
249
- //Successfully paid
250
- yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED);
251
- yield this.storageManager.saveData(invoice.id, null, invoiceData);
167
+ if (invoiceData.state !== FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED)
168
+ return;
169
+ const txns = await swapContract.txsTransfer(signer.getAddress(), invoiceData.token, invoiceData.output, invoiceData.dstAddress);
170
+ let unlock = invoiceData.lock(Infinity);
171
+ if (unlock == null)
172
+ return;
173
+ const result = await swapContract.sendAndConfirm(signer, txns, true, null, false, async (txId, rawTx) => {
174
+ invoiceData.txIds = { init: txId };
175
+ invoiceData.scRawTx = rawTx;
176
+ if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED) {
177
+ await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SENT);
178
+ await this.storageManager.saveData(invoice.id, null, invoiceData);
252
179
  }
180
+ }).catch(e => console.error(e));
181
+ if (result == null) {
182
+ //Cancel invoice
183
+ await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED);
184
+ await this.storageManager.saveData(invoice.id, null, invoiceData);
185
+ await this.lightning.cancelHodlInvoice(invoice.id);
186
+ this.unsubscribeInvoice(invoice.id);
187
+ await this.removeSwapData(invoice.id, null);
188
+ this.swapLogger.info(invoiceData, "htlcReceived(): transaction sending failed, refunding lightning: ", invoiceData.pr);
189
+ throw {
190
+ code: 20002,
191
+ msg: "Transaction sending failed"
192
+ };
253
193
  }
254
- if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED) {
255
- yield this.lightning.settleHodlInvoice(invoiceData.secret);
256
- if (invoiceData.metadata != null)
257
- invoiceData.metadata.times.htlcSettled = Date.now();
258
- const paymentHash = invoiceData.getHash();
259
- this.processedTxIds.set(paymentHash, invoiceData.txIds.init);
260
- yield invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SETTLED);
261
- this.unsubscribeInvoice(paymentHash);
262
- this.swapLogger.info(invoiceData, "htlcReceived(): invoice settled, invoice: " + invoiceData.pr + " scTxId: " + invoiceData.txIds.init);
263
- yield this.removeSwapData(invoiceData);
194
+ else {
195
+ //Successfully paid
196
+ await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED);
197
+ await this.storageManager.saveData(invoice.id, null, invoiceData);
264
198
  }
265
- });
199
+ unlock();
200
+ unlock = null;
201
+ }
202
+ if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SENT) {
203
+ if (invoiceData.isLocked())
204
+ return;
205
+ const txStatus = await swapContract.getTxStatus(invoiceData.scRawTx);
206
+ if (txStatus === "not_found") {
207
+ //Retry
208
+ invoiceData.txIds = { init: null };
209
+ invoiceData.scRawTx = null;
210
+ await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.RECEIVED);
211
+ await this.storageManager.saveData(invoice.id, null, invoiceData);
212
+ }
213
+ if (txStatus === "reverted") {
214
+ //Cancel invoice
215
+ await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.REFUNDED);
216
+ await this.storageManager.saveData(invoice.id, null, invoiceData);
217
+ await this.lightning.cancelHodlInvoice(invoice.id);
218
+ this.unsubscribeInvoice(invoice.id);
219
+ await this.removeSwapData(invoice.id, null);
220
+ this.swapLogger.info(invoiceData, "htlcReceived(): transaction reverted, refunding lightning: ", invoiceData.pr);
221
+ throw {
222
+ code: 20002,
223
+ msg: "Transaction reverted"
224
+ };
225
+ }
226
+ if (txStatus === "success") {
227
+ //Successfully paid
228
+ await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED);
229
+ await this.storageManager.saveData(invoice.id, null, invoiceData);
230
+ }
231
+ }
232
+ if (invoiceData.state === FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.CONFIRMED) {
233
+ await this.lightning.settleHodlInvoice(invoiceData.secret);
234
+ if (invoiceData.metadata != null)
235
+ invoiceData.metadata.times.htlcSettled = Date.now();
236
+ const paymentHash = invoiceData.getIdentifierHash();
237
+ this.processedTxIds.set(paymentHash, invoiceData.txIds.init);
238
+ await invoiceData.setState(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwapState.SETTLED);
239
+ this.unsubscribeInvoice(paymentHash);
240
+ this.swapLogger.info(invoiceData, "htlcReceived(): invoice settled, invoice: " + invoiceData.pr + " scTxId: " + invoiceData.txIds.init);
241
+ await this.removeSwapData(invoiceData);
242
+ }
266
243
  }
267
244
  /**
268
245
  *
@@ -272,80 +249,83 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
272
249
  * @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
273
250
  * @returns the fetched lightning invoice
274
251
  */
275
- checkInvoiceStatus(paymentHash) {
276
- return __awaiter(this, void 0, void 0, function* () {
277
- const invoice = yield this.lightning.getInvoice(paymentHash);
278
- const isInvoiceFound = invoice != null;
279
- if (!isInvoiceFound)
252
+ async checkInvoiceStatus(paymentHash) {
253
+ const invoice = await this.lightning.getInvoice(paymentHash);
254
+ const isInvoiceFound = invoice != null;
255
+ if (!isInvoiceFound)
256
+ throw {
257
+ _httpStatus: 200,
258
+ code: 10001,
259
+ msg: "Invoice expired/canceled"
260
+ };
261
+ const arr = invoice.description.split("-");
262
+ let chainIdentifier;
263
+ let address;
264
+ if (arr.length > 2 && arr[1] === "GAS") {
265
+ chainIdentifier = arr[0];
266
+ address = arr[2];
267
+ }
268
+ else {
269
+ chainIdentifier = this.chains.default;
270
+ address = invoice.description;
271
+ }
272
+ const { swapContract } = this.getChain(chainIdentifier);
273
+ if (!swapContract.isValidAddress(address))
274
+ throw {
275
+ _httpStatus: 200,
276
+ code: 10001,
277
+ msg: "Invoice expired/canceled"
278
+ };
279
+ switch (invoice.status) {
280
+ case "held":
281
+ return invoice;
282
+ case "canceled":
280
283
  throw {
281
284
  _httpStatus: 200,
282
285
  code: 10001,
283
286
  msg: "Invoice expired/canceled"
284
287
  };
285
- const arr = invoice.description.split("-");
286
- let chainIdentifier;
287
- let address;
288
- if (arr.length > 2 && arr[1] === "GAS") {
289
- chainIdentifier = arr[0];
290
- address = arr[2];
291
- }
292
- else {
293
- chainIdentifier = this.chains.default;
294
- address = invoice.description;
295
- }
296
- const { swapContract } = this.getChain(chainIdentifier);
297
- if (!swapContract.isValidAddress(address))
288
+ case "confirmed":
298
289
  throw {
299
290
  _httpStatus: 200,
300
- code: 10001,
301
- msg: "Invoice expired/canceled"
291
+ code: 10000,
292
+ msg: "Invoice already paid",
293
+ data: {
294
+ txId: this.processedTxIds.get(paymentHash)
295
+ }
302
296
  };
303
- switch (invoice.status) {
304
- case "held":
305
- return invoice;
306
- case "canceled":
307
- throw {
308
- _httpStatus: 200,
309
- code: 10001,
310
- msg: "Invoice expired/canceled"
311
- };
312
- case "confirmed":
313
- throw {
314
- _httpStatus: 200,
315
- code: 10000,
316
- msg: "Invoice already paid",
317
- data: {
318
- txId: this.processedTxIds.get(paymentHash)
319
- }
320
- };
321
- case "unpaid":
322
- throw {
323
- _httpStatus: 200,
324
- code: 10010,
325
- msg: "Invoice yet unpaid"
326
- };
327
- default:
328
- throw new Error("Lightning invoice invalid state!");
329
- }
330
- });
297
+ case "unpaid":
298
+ throw {
299
+ _httpStatus: 200,
300
+ code: 10010,
301
+ msg: "Invoice yet unpaid"
302
+ };
303
+ default:
304
+ throw new Error("Lightning invoice invalid state!");
305
+ }
331
306
  }
332
307
  startRestServer(restServer) {
333
- const createInvoice = (0, Utils_1.expressHandlerWrapper)((req, res) => __awaiter(this, void 0, void 0, function* () {
308
+ const createInvoice = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
334
309
  var _a;
335
310
  const metadata = { request: {}, times: {} };
336
- const chainIdentifier = (_a = req.query.chain) !== null && _a !== void 0 ? _a : this.chains.default;
311
+ const chainIdentifier = req.query.chain ?? this.chains.default;
337
312
  const { swapContract, signer } = this.getChain(chainIdentifier);
338
313
  metadata.times.requestReceived = Date.now();
339
314
  /**
340
315
  * address: string solana address of the recipient
341
316
  * amount: string amount (in lamports/smart chain base units) of the invoice
342
317
  */
343
- const parsedBody = yield req.paramReader.getParams({
318
+ (_a = req.query).token ?? (_a.token = swapContract.getNativeCurrencyAddress());
319
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)(req.query, {
344
320
  address: (val) => val != null &&
345
321
  typeof (val) === "string" &&
346
322
  swapContract.isValidAddress(val) ? val : null,
347
- amount: SchemaVerifier_1.FieldTypeEnum.BN,
348
- exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional
323
+ token: (val) => val != null &&
324
+ typeof (val) === "string" &&
325
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
326
+ amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
327
+ exactIn: (val) => val === "true" ? true :
328
+ (val === "false" || val === undefined) ? false : null
349
329
  });
350
330
  if (parsedBody == null)
351
331
  throw {
@@ -353,22 +333,22 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
353
333
  msg: "Invalid request body"
354
334
  };
355
335
  metadata.request = parsedBody;
356
- const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount };
336
+ const requestedAmount = { input: parsedBody.exactIn, amount: parsedBody.amount };
357
337
  const request = {
358
338
  chainIdentifier,
359
339
  raw: req,
360
340
  parsed: parsedBody,
361
341
  metadata
362
342
  };
363
- const useToken = swapContract.getNativeCurrencyAddress();
343
+ const useToken = parsedBody.token;
364
344
  //Check request params
365
- const fees = yield this.preCheckAmounts(request, requestedAmount, useToken);
345
+ const fees = await this.preCheckAmounts(request, requestedAmount, useToken);
366
346
  metadata.times.requestChecked = Date.now();
367
347
  //Create abortController for parallel prefetches
368
348
  const responseStream = res.responseStream;
369
349
  const abortController = this.getAbortController(responseStream);
370
350
  //Pre-fetch data
371
- const { pricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, abortController);
351
+ const { pricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, useToken, abortController);
372
352
  const balancePrefetch = swapContract.getBalance(signer.getAddress(), useToken, false).catch(e => {
373
353
  this.logger.error("getBalancePrefetch(): balancePrefetch error: ", e);
374
354
  abortController.abort(e);
@@ -376,59 +356,60 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
376
356
  });
377
357
  const channelsPrefetch = this.getChannelsPrefetch(abortController);
378
358
  //Check valid amount specified (min/max)
379
- const { amountBD, swapFee, swapFeeInToken, totalInToken } = yield this.checkFromBtcAmount(request, requestedAmount, fees, useToken, abortController.signal, pricePrefetchPromise);
359
+ const { amountBD, swapFee, swapFeeInToken, totalInToken } = await this.checkFromBtcAmount(request, requestedAmount, fees, useToken, abortController.signal, pricePrefetchPromise);
380
360
  metadata.times.priceCalculated = Date.now();
381
361
  //Check if we have enough funds to honor the request
382
- yield this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
383
- yield this.checkInboundLiquidity(amountBD, channelsPrefetch, abortController.signal);
362
+ await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
363
+ await this.checkInboundLiquidity(amountBD, channelsPrefetch, abortController.signal);
384
364
  metadata.times.balanceChecked = Date.now();
385
365
  const secret = (0, crypto_1.randomBytes)(32);
386
366
  const hash = (0, crypto_1.createHash)("sha256").update(secret).digest();
387
367
  const hodlInvoiceObj = {
388
368
  description: chainIdentifier + "-GAS-" + parsedBody.address,
389
- cltvDelta: this.config.minCltv.add(new BN(5)).toNumber(),
369
+ cltvDelta: Number(this.config.minCltv) + 5,
390
370
  expiresAt: Date.now() + (this.config.invoiceTimeoutSeconds * 1000),
391
371
  id: hash.toString("hex"),
392
- mtokens: amountBD.mul(new BN(1000))
372
+ mtokens: amountBD * 1000n
393
373
  };
394
374
  metadata.invoiceRequest = hodlInvoiceObj;
395
- const hodlInvoice = yield this.lightning.createHodlInvoice(hodlInvoiceObj);
375
+ const hodlInvoice = await this.lightning.createHodlInvoice(hodlInvoiceObj);
396
376
  abortController.signal.throwIfAborted();
397
377
  metadata.times.invoiceCreated = Date.now();
398
- metadata.invoiceResponse = Object.assign({}, hodlInvoice);
378
+ metadata.invoiceResponse = { ...hodlInvoice };
399
379
  console.log("[From BTC-LN: REST.CreateInvoice] hodl invoice created: ", hodlInvoice);
400
- const createdSwap = new FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwap(chainIdentifier, hodlInvoice.request, hodlInvoice.mtokens, swapFee, swapFeeInToken, totalInToken, secret.toString("hex"), parsedBody.address);
380
+ const createdSwap = new FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwap(chainIdentifier, hodlInvoice.request, hodlInvoice.mtokens, swapFee, swapFeeInToken, totalInToken, secret.toString("hex"), parsedBody.address, useToken);
401
381
  metadata.times.swapCreated = Date.now();
402
382
  createdSwap.metadata = metadata;
403
- yield PluginManager_1.PluginManager.swapCreate(createdSwap);
404
- yield this.storageManager.saveData(hash.toString("hex"), null, createdSwap);
383
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
384
+ await this.storageManager.saveData(hash.toString("hex"), null, createdSwap);
405
385
  this.subscribeToInvoice(createdSwap);
406
386
  this.swapLogger.info(createdSwap, "REST: /createInvoice: Created swap invoice: " + hodlInvoice.request + " amount: " + amountBD.toString(10));
407
- yield responseStream.writeParamsAndEnd({
387
+ res.status(200).json({
408
388
  msg: "Success",
409
389
  code: 10000,
410
390
  data: {
411
391
  pr: hodlInvoice.request,
392
+ amountSats: amountBD.toString(10),
393
+ swapFeeSats: swapFee.toString(10),
412
394
  swapFee: swapFeeInToken.toString(10),
413
395
  total: totalInToken.toString(10),
414
396
  intermediaryKey: signer.getAddress()
415
397
  }
416
398
  });
417
- }));
418
- restServer.use(this.path + "/createInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
419
- restServer.post(this.path + "/createInvoice", createInvoice);
420
- const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)((req, res) => __awaiter(this, void 0, void 0, function* () {
399
+ });
400
+ restServer.get(this.path + "/createInvoice", createInvoice);
401
+ const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
421
402
  /**
422
403
  * paymentHash: string payment hash of the invoice
423
404
  */
424
- const parsedBody = (0, SchemaVerifier_1.verifySchema)(Object.assign(Object.assign({}, req.body), req.query), {
405
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
425
406
  paymentHash: (val) => val != null &&
426
407
  typeof (val) === "string" &&
427
408
  val.length === 64 &&
428
409
  Utils_1.HEX_REGEX.test(val) ? val : null,
429
410
  });
430
- yield this.checkInvoiceStatus(parsedBody.paymentHash);
431
- const invoiceData = yield this.storageManager.getData(parsedBody.paymentHash, null);
411
+ await this.checkInvoiceStatus(parsedBody.paymentHash);
412
+ const invoiceData = await this.storageManager.getData(parsedBody.paymentHash, null);
432
413
  if (invoiceData == null)
433
414
  throw {
434
415
  _httpStatus: 200,
@@ -481,36 +462,33 @@ class FromBtcLnTrusted extends FromBtcLnBaseSwapHandler_1.FromBtcLnBaseSwapHandl
481
462
  txId: invoiceData.txIds.init
482
463
  }
483
464
  };
484
- }));
485
- restServer.post(this.path + "/getInvoiceStatus", getInvoiceStatus);
465
+ });
486
466
  restServer.get(this.path + "/getInvoiceStatus", getInvoiceStatus);
487
467
  this.logger.info("started at path: ", this.path);
488
468
  }
489
- init() {
490
- return __awaiter(this, void 0, void 0, function* () {
491
- yield this.storageManager.loadData(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwap);
492
- //Check if all swaps contain a valid amount
493
- for (let swap of yield this.storageManager.query([])) {
494
- if (swap.amount == null) {
495
- const parsedPR = yield this.lightning.parsePaymentRequest(swap.pr);
496
- swap.amount = parsedPR.mtokens.add(new BN(999)).div(new BN(1000));
497
- }
469
+ async init() {
470
+ await this.storageManager.loadData(FromBtcLnTrustedSwap_1.FromBtcLnTrustedSwap);
471
+ //Check if all swaps contain a valid amount
472
+ for (let { obj: swap } of await this.storageManager.query([])) {
473
+ if (swap.amount == null) {
474
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
475
+ swap.amount = (parsedPR.mtokens + 999n) / 1000n;
498
476
  }
499
- yield PluginManager_1.PluginManager.serviceInitialize(this);
500
- });
477
+ }
478
+ await PluginManager_1.PluginManager.serviceInitialize(this);
501
479
  }
502
480
  getInfoData() {
503
481
  return {
504
- minCltv: this.config.minCltv.toNumber()
482
+ minCltv: Number(this.config.minCltv)
505
483
  };
506
484
  }
507
- processClaimEvent(chainIdentifier, event) {
485
+ processClaimEvent(chainIdentifier, swap, event) {
508
486
  return Promise.resolve();
509
487
  }
510
- processInitializeEvent(chainIdentifier, event) {
488
+ processInitializeEvent(chainIdentifier, swap, event) {
511
489
  return Promise.resolve();
512
490
  }
513
- processRefundEvent(chainIdentifier, event) {
491
+ processRefundEvent(chainIdentifier, swap, event) {
514
492
  return Promise.resolve();
515
493
  }
516
494
  }