@atomiqlabs/lp-lib 15.0.2 → 15.0.4

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