@atomiqlabs/lp-lib 15.0.13 → 15.0.14

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