@atomiqlabs/lp-lib 16.1.2 → 16.2.1

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