@atomiqlabs/lp-lib 14.0.0-dev.11 → 14.0.0-dev.13

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 (164) 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 +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 +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 +153 -153
  27. package/dist/swaps/SwapHandler.js +160 -160
  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 +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 +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 -648
  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 +104 -104
  59. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +659 -629
  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 +171 -171
  63. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +706 -706
  64. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +26 -26
  65. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +62 -62
  66. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +177 -177
  67. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +861 -861
  68. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +23 -23
  69. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +56 -56
  70. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +41 -41
  71. package/dist/swaps/spv_vault_swap/SpvVault.js +111 -111
  72. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +67 -67
  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 +491 -490
  76. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +52 -52
  77. package/dist/swaps/spv_vault_swap/SpvVaults.js +364 -364
  78. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +51 -51
  79. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +650 -650
  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 +76 -76
  83. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +494 -494
  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/Utils.d.ts +29 -29
  87. package/dist/utils/Utils.js +89 -89
  88. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  89. package/dist/utils/paramcoders/IParamReader.js +2 -2
  90. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  91. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  92. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  93. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  94. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  95. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  96. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  97. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  98. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  99. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  100. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  101. package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -107
  102. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  103. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  104. package/dist/wallets/IBitcoinWallet.d.ts +67 -67
  105. package/dist/wallets/IBitcoinWallet.js +2 -2
  106. package/dist/wallets/ILightningWallet.d.ts +117 -117
  107. package/dist/wallets/ILightningWallet.js +37 -37
  108. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  109. package/dist/wallets/ISpvVaultSigner.js +2 -2
  110. package/package.json +36 -36
  111. package/src/fees/IBtcFeeEstimator.ts +6 -6
  112. package/src/index.ts +53 -53
  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 +118 -118
  122. package/src/storagemanager/StorageManager.ts +78 -78
  123. package/src/swaps/SwapHandler.ts +277 -277
  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 +286 -286
  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 -828
  138. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -141
  139. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +822 -789
  140. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -196
  141. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +879 -879
  142. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +102 -102
  143. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1110 -1110
  144. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +77 -77
  145. package/src/swaps/spv_vault_swap/SpvVault.ts +143 -143
  146. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +225 -225
  147. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +627 -626
  148. package/src/swaps/spv_vault_swap/SpvVaults.ts +435 -435
  149. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
  150. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  151. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +590 -590
  152. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  153. package/src/utils/Utils.ts +104 -104
  154. package/src/utils/paramcoders/IParamReader.ts +7 -7
  155. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  156. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  157. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  158. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  159. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  160. package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -118
  161. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  162. package/src/wallets/IBitcoinWallet.ts +68 -68
  163. package/src/wallets/ILightningWallet.ts +178 -178
  164. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,861 +1,861 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ToBtcLnAbs = void 0;
4
- const ToBtcLnSwapAbs_1 = require("./ToBtcLnSwapAbs");
5
- const SwapHandler_1 = require("../../SwapHandler");
6
- const base_1 = require("@atomiqlabs/base");
7
- const Utils_1 = require("../../../utils/Utils");
8
- const PluginManager_1 = require("../../../plugins/PluginManager");
9
- const crypto_1 = require("crypto");
10
- const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
11
- const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
12
- const ToBtcBaseSwapHandler_1 = require("../ToBtcBaseSwapHandler");
13
- const ILightningWallet_1 = require("../../../wallets/ILightningWallet");
14
- const LightningAssertions_1 = require("../../assertions/LightningAssertions");
15
- /**
16
- * Swap handler handling to BTCLN swaps using submarine swaps
17
- */
18
- class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
19
- constructor(storageDirectory, path, chainData, lightning, swapPricing, config) {
20
- super(storageDirectory, path, chainData, swapPricing, config);
21
- this.activeSubscriptions = new Set();
22
- this.type = SwapHandler_1.SwapHandlerType.TO_BTCLN;
23
- this.swapType = base_1.ChainSwapType.HTLC;
24
- this.exactInAuths = {};
25
- this.lightning = lightning;
26
- this.LightningAssertions = new LightningAssertions_1.LightningAssertions(this.logger, lightning);
27
- const anyConfig = config;
28
- anyConfig.minTsSendCltv = config.gracePeriod + (config.bitcoinBlocktime * config.minSendCltv * config.safetyFactor);
29
- this.config = anyConfig;
30
- this.config.minLnRoutingFeePPM = this.config.minLnRoutingFeePPM || 1000n;
31
- this.config.minLnBaseFee = this.config.minLnBaseFee || 5n;
32
- this.config.exactInExpiry = this.config.exactInExpiry || 10 * 1000;
33
- }
34
- /**
35
- * Cleans up exactIn authorization that are already past their expiry
36
- *
37
- * @protected
38
- */
39
- cleanExpiredExactInAuthorizations() {
40
- for (let key in this.exactInAuths) {
41
- const obj = this.exactInAuths[key];
42
- if (obj.expiry < Date.now()) {
43
- this.logger.info("cleanExpiredExactInAuthorizations(): remove expired authorization, reqId: " + key);
44
- delete this.exactInAuths[key];
45
- }
46
- }
47
- }
48
- async processPastSwap(swap) {
49
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
50
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED) {
51
- //Cancel the swaps where signature is expired
52
- const isSignatureExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
53
- if (isSignatureExpired) {
54
- const isCommitted = await swapContract.isCommited(swap.data);
55
- if (!isCommitted) {
56
- this.swapLogger.info(swap, "processPastSwap(state=SAVED): authorization expired & swap not committed, cancelling swap, invoice: " + swap.pr);
57
- await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CANCELED);
58
- return;
59
- }
60
- else {
61
- this.swapLogger.info(swap, "processPastSwap(state=SAVED): swap committed (detected from processPastSwap), invoice: " + swap.pr);
62
- await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED);
63
- await this.saveSwapData(swap);
64
- }
65
- }
66
- //Cancel the swaps where lightning invoice is expired
67
- const decodedPR = await this.lightning.parsePaymentRequest(swap.pr);
68
- const isInvoiceExpired = decodedPR.expiryEpochMillis < Date.now();
69
- if (isInvoiceExpired) {
70
- this.swapLogger.info(swap, "processPastSwap(state=SAVED): invoice expired, cancel uncommited swap, invoice: " + swap.pr);
71
- await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CANCELED);
72
- return;
73
- }
74
- }
75
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED || swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID) {
76
- //Process swaps in commited & paid state
77
- await this.processInitialized(swap);
78
- }
79
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE) {
80
- //Remove expired swaps (as these can already be unilaterally refunded by the client), so we don't need
81
- // to be able to cooperatively refund them
82
- if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
83
- this.swapLogger.info(swap, "processPastSwap(state=NON_PAYABLE): swap expired, removing swap data, invoice: " + swap.pr);
84
- await this.removeSwapData(swap);
85
- }
86
- }
87
- }
88
- /**
89
- * Checks past swaps, deletes ones that are already expired, and tries to process ones that are committed.
90
- */
91
- async processPastSwaps() {
92
- this.cleanExpiredExactInAuthorizations();
93
- const queriedData = await this.storageManager.query([
94
- {
95
- key: "state",
96
- value: [
97
- ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED,
98
- ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED,
99
- ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID,
100
- ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE
101
- ]
102
- }
103
- ]);
104
- for (let { obj: swap } of queriedData) {
105
- await this.processPastSwap(swap);
106
- }
107
- }
108
- /**
109
- * Tries to claim the swap funds on the SC side, returns false if the swap is already locked (claim tx is already being sent)
110
- *
111
- * @param swap
112
- * @private
113
- * @returns Whether the transaction was successfully sent
114
- */
115
- async tryClaimSwap(swap) {
116
- if (swap.secret == null)
117
- throw new Error("Invalid swap state, needs payment pre-image!");
118
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
119
- //Check if escrow state exists
120
- const isCommited = await swapContract.isCommited(swap.data);
121
- if (!isCommited) {
122
- const status = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
123
- if (status?.type === base_1.SwapCommitStateType.PAID) {
124
- //This is alright, we got the money
125
- swap.txIds ?? (swap.txIds = {});
126
- swap.txIds.claim = await status.getClaimTxId();
127
- await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
128
- return true;
129
- }
130
- else if (status?.type === base_1.SwapCommitStateType.EXPIRED) {
131
- //This means the user was able to refund before we were able to claim, no good
132
- swap.txIds ?? (swap.txIds = {});
133
- swap.txIds.refund = status.getRefundTxId == null ? null : await status.getRefundTxId();
134
- await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
135
- }
136
- this.swapLogger.warn(swap, "processPaymentResult(): tried to claim but escrow doesn't exist anymore," +
137
- " status: " + status +
138
- " invoice: " + swap.pr);
139
- return false;
140
- }
141
- //Set flag that we are sending the transaction already, so we don't end up with race condition
142
- const unlock = swap.lock(swapContract.claimWithSecretTimeout);
143
- if (unlock == null)
144
- return false;
145
- try {
146
- this.swapLogger.debug(swap, "tryClaimSwap(): initiate claim of swap, secret: " + swap.secret);
147
- const success = await swapContract.claimWithSecret(signer, swap.data, swap.secret, false, false, {
148
- waitForConfirmation: true
149
- });
150
- this.swapLogger.info(swap, "tryClaimSwap(): swap claimed successfully, secret: " + swap.secret + " invoice: " + swap.pr);
151
- if (swap.metadata != null)
152
- swap.metadata.times.txClaimed = Date.now();
153
- unlock();
154
- return true;
155
- }
156
- catch (e) {
157
- this.swapLogger.error(swap, "tryClaimSwap(): error occurred claiming swap, secret: " + swap.secret + " invoice: " + swap.pr, e);
158
- return false;
159
- }
160
- }
161
- /**
162
- * Process the result of attempted lightning network payment
163
- *
164
- * @param swap
165
- * @param lnPaymentStatus
166
- */
167
- async processPaymentResult(swap, lnPaymentStatus) {
168
- switch (lnPaymentStatus.status) {
169
- case "pending":
170
- return;
171
- case "failed":
172
- this.swapLogger.info(swap, "processPaymentResult(): invoice payment failed, cancelling swap, invoice: " + swap.pr);
173
- await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE);
174
- await this.saveSwapData(swap);
175
- return;
176
- case "confirmed":
177
- swap.secret = lnPaymentStatus.secret;
178
- swap.setRealNetworkFee(lnPaymentStatus.feeMtokens / 1000n);
179
- this.swapLogger.info(swap, "processPaymentResult(): invoice paid, secret: " + swap.secret + " realRoutingFee: " + swap.realNetworkFee.toString(10) + " invoice: " + swap.pr);
180
- await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID);
181
- await this.saveSwapData(swap);
182
- const success = await this.tryClaimSwap(swap);
183
- if (success)
184
- this.swapLogger.info(swap, "processPaymentResult(): swap claimed successfully, invoice: " + swap.pr);
185
- return;
186
- default:
187
- throw new Error("Invalid lnPaymentStatus");
188
- }
189
- }
190
- /**
191
- * Subscribe to a pending lightning network payment attempt
192
- *
193
- * @param invoiceData
194
- */
195
- subscribeToPayment(invoiceData) {
196
- const paymentHash = invoiceData.lnPaymentHash;
197
- if (this.activeSubscriptions.has(paymentHash))
198
- return false;
199
- this.lightning.waitForPayment(paymentHash).then(result => {
200
- this.swapLogger.info(invoiceData, "subscribeToPayment(): result callback, outcome: " + result.status + " invoice: " + invoiceData.pr);
201
- this.processPaymentResult(invoiceData, result).catch(e => this.swapLogger.error(invoiceData, "subscribeToPayment(): process payment result", e));
202
- this.activeSubscriptions.delete(paymentHash);
203
- });
204
- this.swapLogger.info(invoiceData, "subscribeToPayment(): subscribe to payment outcome, invoice: " + invoiceData.pr);
205
- this.activeSubscriptions.add(paymentHash);
206
- return true;
207
- }
208
- async sendLightningPayment(swap) {
209
- const decodedPR = await this.lightning.parsePaymentRequest(swap.pr);
210
- const expiryTimestamp = swap.data.getExpiry();
211
- const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
212
- //Run checks
213
- const hasEnoughTimeToPay = (expiryTimestamp - currentTimestamp) >= this.config.minTsSendCltv;
214
- if (!hasEnoughTimeToPay)
215
- throw {
216
- code: 90005,
217
- msg: "Not enough time to reliably pay the invoice"
218
- };
219
- const isInvoiceExpired = decodedPR.expiryEpochMillis < Date.now();
220
- if (isInvoiceExpired)
221
- throw {
222
- code: 90006,
223
- msg: "Invoice already expired"
224
- };
225
- //Compute max cltv delta
226
- const maxFee = swap.quotedNetworkFee;
227
- const maxUsableCLTVdelta = (expiryTimestamp - currentTimestamp - this.config.gracePeriod)
228
- / (this.config.bitcoinBlocktime * this.config.safetyFactor);
229
- //Initiate payment
230
- this.swapLogger.info(swap, "sendLightningPayment(): paying lightning network invoice," +
231
- " cltvDelta: " + maxUsableCLTVdelta.toString(10) +
232
- " maxFee: " + maxFee.toString(10) +
233
- " invoice: " + swap.pr);
234
- const blockHeight = await this.lightning.getBlockheight();
235
- try {
236
- await this.lightning.pay({
237
- request: swap.pr,
238
- maxFeeMtokens: maxFee * 1000n,
239
- maxTimeoutHeight: blockHeight + Number(maxUsableCLTVdelta)
240
- });
241
- }
242
- catch (e) {
243
- throw {
244
- code: 90007,
245
- msg: "Failed to initiate invoice payment",
246
- data: {
247
- error: JSON.stringify(e)
248
- }
249
- };
250
- }
251
- if (swap.metadata != null)
252
- swap.metadata.times.payComplete = Date.now();
253
- }
254
- /**
255
- * Begins a lightning network payment attempt, if not attempted already
256
- *
257
- * @param swap
258
- */
259
- async processInitialized(swap) {
260
- //Check if payment was already made
261
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID) {
262
- const success = await this.tryClaimSwap(swap);
263
- if (success)
264
- this.swapLogger.info(swap, "processInitialized(): swap claimed successfully, invoice: " + swap.pr);
265
- return;
266
- }
267
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED) {
268
- if (swap.metadata != null)
269
- swap.metadata.times.payPaymentChecked = Date.now();
270
- let lnPaymentStatus = await this.lightning.getPayment(swap.lnPaymentHash);
271
- if (lnPaymentStatus != null) {
272
- if (lnPaymentStatus.status === "pending") {
273
- //Payment still ongoing, process the result
274
- this.subscribeToPayment(swap);
275
- return;
276
- }
277
- else {
278
- //Payment has already concluded, process the result
279
- await this.processPaymentResult(swap, lnPaymentStatus);
280
- return;
281
- }
282
- }
283
- else {
284
- //Payment not founds, try to process again
285
- await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED);
286
- }
287
- }
288
- if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED) {
289
- await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED);
290
- await this.saveSwapData(swap);
291
- try {
292
- await this.sendLightningPayment(swap);
293
- }
294
- catch (e) {
295
- this.swapLogger.error(swap, "processInitialized(): lightning payment error", e);
296
- if ((0, Utils_1.isDefinedRuntimeError)(e)) {
297
- if (swap.metadata != null)
298
- swap.metadata.payError = e;
299
- await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE);
300
- await this.saveSwapData(swap);
301
- return;
302
- }
303
- else
304
- throw e;
305
- }
306
- this.subscribeToPayment(swap);
307
- return;
308
- }
309
- }
310
- async processInitializeEvent(chainIdentifier, swap, event) {
311
- this.swapLogger.info(swap, "SC: InitializeEvent: swap initialized by the client, invoice: " + swap.pr);
312
- //Only process swaps in SAVED state
313
- if (swap.state !== ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED)
314
- return;
315
- await this.processInitialized(swap);
316
- }
317
- async processClaimEvent(chainIdentifier, swap, event) {
318
- this.swapLogger.info(swap, "SC: ClaimEvent: swap claimed to us, secret: " + event.result + " invoice: " + swap.pr);
319
- await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
320
- }
321
- async processRefundEvent(chainIdentifier, swap, event) {
322
- this.swapLogger.info(swap, "SC: RefundEvent: swap refunded back to the client, invoice: " + swap.pr);
323
- await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
324
- }
325
- /**
326
- * Checks if the amount was supplied in the exactIn request
327
- *
328
- * @param amount
329
- * @param exactIn
330
- * @throws {DefinedRuntimeError} will throw an error if the swap was exactIn, but amount not specified
331
- */
332
- checkAmount(amount, exactIn) {
333
- if (exactIn) {
334
- if (amount == null) {
335
- throw {
336
- code: 20040,
337
- msg: "Invalid request body (amount not specified)!"
338
- };
339
- }
340
- }
341
- }
342
- /**
343
- * Checks if the maxFee parameter is in valid range (>0)
344
- *
345
- * @param maxFee
346
- * @throws {DefinedRuntimeError} will throw an error if the maxFee is zero or negative
347
- */
348
- checkMaxFee(maxFee) {
349
- if (maxFee <= 0) {
350
- throw {
351
- code: 20030,
352
- msg: "Invalid request body (maxFee too low)!"
353
- };
354
- }
355
- }
356
- /**
357
- * Checks and parses a payment request (bolt11 invoice), additionally also checks expiration time of the invoice
358
- *
359
- * @param chainIdentifier
360
- * @param pr
361
- * @throws {DefinedRuntimeError} will throw an error if the pr is invalid, without amount or expired
362
- */
363
- async checkPaymentRequest(chainIdentifier, pr) {
364
- let parsedPR;
365
- try {
366
- parsedPR = await this.lightning.parsePaymentRequest(pr);
367
- }
368
- catch (e) {
369
- throw {
370
- code: 20021,
371
- msg: "Invalid request body (pr - cannot be parsed)"
372
- };
373
- }
374
- if (parsedPR.mtokens == null)
375
- throw {
376
- code: 20022,
377
- msg: "Invalid request body (pr - needs to have amount)"
378
- };
379
- let halfConfidence = false;
380
- if (parsedPR.expiryEpochMillis < Date.now() + ((this.getInitAuthorizationTimeout(chainIdentifier) + (2 * 60)) * 1000)) {
381
- if (!this.config.allowShortExpiry) {
382
- throw {
383
- code: 20020,
384
- msg: "Invalid request body (pr - expired)"
385
- };
386
- }
387
- else if (parsedPR.expiryEpochMillis < Date.now()) {
388
- throw {
389
- code: 20020,
390
- msg: "Invalid request body (pr - expired)"
391
- };
392
- }
393
- halfConfidence = true;
394
- }
395
- return { parsedPR, halfConfidence };
396
- }
397
- /**
398
- * Checks if the request specified too short of an expiry
399
- *
400
- * @param expiryTimestamp
401
- * @param currentTimestamp
402
- * @throws {DefinedRuntimeError} will throw an error if the expiry time is too short
403
- */
404
- checkExpiry(expiryTimestamp, currentTimestamp) {
405
- const expiresTooSoon = (expiryTimestamp - currentTimestamp) < this.config.minTsSendCltv;
406
- if (expiresTooSoon) {
407
- throw {
408
- code: 20001,
409
- msg: "Expiry time too low!"
410
- };
411
- }
412
- }
413
- /**
414
- * Estimates the routing fee & confidence by either probing or routing (if probing fails), the fee is also adjusted
415
- * according to routing fee multiplier, and subject to minimums set in config
416
- *
417
- * @param amountBD
418
- * @param maxFee
419
- * @param expiryTimestamp
420
- * @param currentTimestamp
421
- * @param pr
422
- * @param metadata
423
- * @param abortSignal
424
- * @throws {DefinedRuntimeError} will throw an error if the destination is unreachable
425
- */
426
- async checkAndGetNetworkFee(amountBD, maxFee, expiryTimestamp, currentTimestamp, pr, metadata, abortSignal) {
427
- const maxUsableCLTV = (expiryTimestamp - currentTimestamp - this.config.gracePeriod) / (this.config.bitcoinBlocktime * this.config.safetyFactor);
428
- const blockHeight = await this.lightning.getBlockheight();
429
- abortSignal.throwIfAborted();
430
- metadata.times.blockheightFetched = Date.now();
431
- const maxTimeoutBlockheight = BigInt(blockHeight) + maxUsableCLTV;
432
- const req = {
433
- request: pr,
434
- amountMtokens: amountBD * 1000n,
435
- maxFeeMtokens: maxFee * 1000n,
436
- maxTimeoutHeight: Number(maxTimeoutBlockheight)
437
- };
438
- let probeOrRouteResp = await this.lightning.probe(req);
439
- metadata.times.probeResult = Date.now();
440
- metadata.probeResponse = { ...probeOrRouteResp };
441
- abortSignal.throwIfAborted();
442
- if (probeOrRouteResp == null) {
443
- if (!this.config.allowProbeFailedSwaps)
444
- throw {
445
- code: 20002,
446
- msg: "Cannot route the payment!"
447
- };
448
- const routeResp = await this.lightning.route(req);
449
- metadata.times.routingResult = Date.now();
450
- metadata.routeResponse = { ...routeResp };
451
- abortSignal.throwIfAborted();
452
- if (routeResp == null)
453
- throw {
454
- code: 20002,
455
- msg: "Cannot route the payment!"
456
- };
457
- this.logger.info("checkAndGetNetworkFee(): routing result," +
458
- " destination: " + routeResp.destination +
459
- " confidence: " + routeResp.confidence +
460
- " fee mtokens: " + routeResp.feeMtokens.toString(10));
461
- probeOrRouteResp = routeResp;
462
- }
463
- else {
464
- this.logger.info("checkAndGetNetworkFee(): route probed," +
465
- " destination: " + probeOrRouteResp.destination +
466
- " confidence: " + probeOrRouteResp.confidence +
467
- " fee mtokens: " + probeOrRouteResp.feeMtokens.toString(10));
468
- }
469
- const safeFeeTokens = (probeOrRouteResp.feeMtokens + 999n) / 1000n;
470
- let actualRoutingFee = safeFeeTokens * this.config.routingFeeMultiplier;
471
- const minRoutingFee = (amountBD * this.config.minLnRoutingFeePPM / 1000000n) + this.config.minLnBaseFee;
472
- if (actualRoutingFee < minRoutingFee) {
473
- actualRoutingFee = minRoutingFee;
474
- if (actualRoutingFee > maxFee) {
475
- probeOrRouteResp.confidence = 0;
476
- }
477
- }
478
- if (actualRoutingFee > maxFee) {
479
- actualRoutingFee = maxFee;
480
- }
481
- this.logger.debug("checkAndGetNetworkFee(): network fee calculated, amount: " + amountBD.toString(10) + " fee: " + actualRoutingFee.toString(10));
482
- return {
483
- networkFee: actualRoutingFee,
484
- confidence: probeOrRouteResp.confidence
485
- };
486
- }
487
- /**
488
- * Checks and consumes (deletes & returns) exactIn authorizaton with a specific reqId
489
- *
490
- * @param reqId
491
- * @throws {DefinedRuntimeError} will throw an error if the authorization doesn't exist
492
- */
493
- checkExactInAuthorization(reqId) {
494
- const parsedAuth = this.exactInAuths[reqId];
495
- if (parsedAuth == null) {
496
- throw {
497
- code: 20070,
498
- msg: "Invalid reqId"
499
- };
500
- }
501
- delete this.exactInAuths[reqId];
502
- if (parsedAuth.expiry < Date.now()) {
503
- throw {
504
- code: 20200,
505
- msg: "Authorization already expired!"
506
- };
507
- }
508
- return parsedAuth;
509
- }
510
- /**
511
- * Checks if the newly submitted PR has the same parameters (destination, cltv_delta, routes) as the initial dummy
512
- * invoice sent for exactIn swap quote
513
- *
514
- * @param pr
515
- * @param parsedAuth
516
- * @throws {DefinedRuntimeError} will throw an error if the details don't match
517
- */
518
- async checkPaymentRequestMatchesInitial(pr, parsedAuth) {
519
- const parsedRequest = await this.lightning.parsePaymentRequest(pr);
520
- if (parsedRequest.destination !== parsedAuth.initialInvoice.destination ||
521
- parsedRequest.cltvDelta !== parsedAuth.initialInvoice.cltvDelta ||
522
- parsedRequest.mtokens !== parsedAuth.amount * 1000n) {
523
- throw {
524
- code: 20102,
525
- msg: "Provided PR doesn't match initial!"
526
- };
527
- }
528
- if (!(0, ILightningWallet_1.routesMatch)(parsedRequest.routes, parsedAuth.initialInvoice.routes)) {
529
- throw {
530
- code: 20102,
531
- msg: "Provided PR doesn't match initial (routes)!"
532
- };
533
- }
534
- }
535
- startRestServer(restServer) {
536
- restServer.use(this.path + "/payInvoiceExactIn", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
537
- restServer.post(this.path + "/payInvoiceExactIn", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
538
- /**
539
- * pr: string bolt11 lightning invoice
540
- * reqId: string Identifier of the swap
541
- * feeRate: string Fee rate to use for the init tx
542
- */
543
- const parsedBody = await req.paramReader.getParams({
544
- pr: SchemaVerifier_1.FieldTypeEnum.String,
545
- reqId: SchemaVerifier_1.FieldTypeEnum.String,
546
- feeRate: SchemaVerifier_1.FieldTypeEnum.String
547
- });
548
- if (parsedBody == null) {
549
- throw {
550
- code: 20100,
551
- msg: "Invalid request body"
552
- };
553
- }
554
- const responseStream = res.responseStream;
555
- const abortSignal = responseStream.getAbortSignal();
556
- //Check request params
557
- const parsedAuth = this.checkExactInAuthorization(parsedBody.reqId);
558
- const { parsedPR, halfConfidence } = await this.checkPaymentRequest(parsedAuth.chainIdentifier, parsedBody.pr);
559
- await this.checkPaymentRequestMatchesInitial(parsedBody.pr, parsedAuth);
560
- const metadata = parsedAuth.metadata;
561
- const sequence = base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8));
562
- const { swapContract, signer } = this.getChain(parsedAuth.chainIdentifier);
563
- const claimHash = swapContract.getHashForHtlc(Buffer.from(parsedPR.id, "hex"));
564
- //Create swap data
565
- const payObject = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, parsedAuth.offerer, signer.getAddress(), parsedAuth.token, parsedAuth.total, claimHash.toString("hex"), sequence, parsedAuth.swapExpiry, true, false, 0n, 0n);
566
- metadata.times.swapCreated = Date.now();
567
- //Sign swap data
568
- const prefetchedSignData = parsedAuth.preFetchSignData;
569
- const sigData = await this.getToBtcSignatureData(parsedAuth.chainIdentifier, payObject, req, abortSignal, prefetchedSignData);
570
- metadata.times.swapSigned = Date.now();
571
- //Create swap
572
- const createdSwap = new ToBtcLnSwapAbs_1.ToBtcLnSwapAbs(parsedAuth.chainIdentifier, parsedPR.id, parsedBody.pr, parsedPR.mtokens, parsedAuth.swapFee, parsedAuth.swapFeeInToken, parsedAuth.quotedNetworkFee, parsedAuth.quotedNetworkFeeInToken);
573
- createdSwap.data = payObject;
574
- createdSwap.metadata = metadata;
575
- createdSwap.prefix = sigData.prefix;
576
- createdSwap.timeout = sigData.timeout;
577
- createdSwap.signature = sigData.signature;
578
- createdSwap.feeRate = sigData.feeRate;
579
- await PluginManager_1.PluginManager.swapCreate(createdSwap);
580
- await this.saveSwapData(createdSwap);
581
- this.swapLogger.info(createdSwap, "REST: /payInvoiceExactIn: created exact in swap," +
582
- " reqId: " + parsedBody.reqId +
583
- " mtokens: " + parsedPR.mtokens.toString(10) +
584
- " invoice: " + createdSwap.pr);
585
- await responseStream.writeParamsAndEnd({
586
- code: 20000,
587
- msg: "Success",
588
- data: {
589
- maxFee: parsedAuth.quotedNetworkFeeInToken.toString(10),
590
- swapFee: parsedAuth.swapFeeInToken.toString(10),
591
- total: parsedAuth.total.toString(10),
592
- confidence: halfConfidence ? parsedAuth.confidence / 2000000 : parsedAuth.confidence / 1000000,
593
- address: signer.getAddress(),
594
- routingFeeSats: parsedAuth.quotedNetworkFee.toString(10),
595
- data: payObject.serialize(),
596
- prefix: sigData.prefix,
597
- timeout: sigData.timeout,
598
- signature: sigData.signature
599
- }
600
- });
601
- }));
602
- restServer.use(this.path + "/payInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
603
- restServer.post(this.path + "/payInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
604
- const metadata = { request: {}, times: {} };
605
- const chainIdentifier = req.query.chain ?? this.chains.default;
606
- const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
607
- metadata.times.requestReceived = Date.now();
608
- /**
609
- *Sent initially:
610
- * pr: string bolt11 lightning invoice
611
- * maxFee: string maximum routing fee
612
- * expiryTimestamp: string expiry timestamp of the to be created HTLC, determines how many LN paths can be considered
613
- * token: string Desired token to use
614
- * offerer: string Address of the caller
615
- * exactIn: boolean Whether to do an exact in swap instead of exact out
616
- * amount: string Input amount for exactIn swaps
617
- *
618
- *Sent later:
619
- * feeRate: string Fee rate to use for the init signature
620
- */
621
- const parsedBody = await req.paramReader.getParams({
622
- pr: SchemaVerifier_1.FieldTypeEnum.String,
623
- maxFee: SchemaVerifier_1.FieldTypeEnum.BigInt,
624
- expiryTimestamp: SchemaVerifier_1.FieldTypeEnum.BigInt,
625
- token: (val) => val != null &&
626
- typeof (val) === "string" &&
627
- this.isTokenSupported(chainIdentifier, val) ? val : null,
628
- offerer: (val) => val != null &&
629
- typeof (val) === "string" &&
630
- chainInterface.isValidAddress(val) ? val : null,
631
- exactIn: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
632
- amount: SchemaVerifier_1.FieldTypeEnum.BigIntOptional
633
- });
634
- if (parsedBody == null) {
635
- throw {
636
- code: 20100,
637
- msg: "Invalid request body"
638
- };
639
- }
640
- metadata.request = parsedBody;
641
- const request = {
642
- chainIdentifier,
643
- raw: req,
644
- parsed: parsedBody,
645
- metadata
646
- };
647
- const useToken = parsedBody.token;
648
- const responseStream = res.responseStream;
649
- const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
650
- //Check request params
651
- this.checkAmount(parsedBody.amount, parsedBody.exactIn);
652
- this.checkMaxFee(parsedBody.maxFee);
653
- this.checkExpiry(parsedBody.expiryTimestamp, currentTimestamp);
654
- await this.checkVaultInitialized(chainIdentifier, parsedBody.token);
655
- const { parsedPR, halfConfidence } = await this.checkPaymentRequest(chainIdentifier, parsedBody.pr);
656
- const requestedAmount = {
657
- input: !!parsedBody.exactIn,
658
- amount: !!parsedBody.exactIn ? parsedBody.amount : (parsedPR.mtokens + 999n) / 1000n,
659
- token: useToken
660
- };
661
- const fees = await this.AmountAssertions.preCheckToBtcAmounts(this.type, request, requestedAmount);
662
- metadata.times.requestChecked = Date.now();
663
- //Create abort controller for parallel pre-fetches
664
- const abortController = (0, Utils_1.getAbortController)(responseStream);
665
- //Pre-fetch
666
- const { pricePrefetchPromise, signDataPrefetchPromise } = this.getToBtcPrefetches(chainIdentifier, useToken, responseStream, abortController);
667
- //Check if prior payment has been made
668
- await this.LightningAssertions.checkPriorPayment(parsedPR.id, abortController.signal);
669
- metadata.times.priorPaymentChecked = Date.now();
670
- //Check amounts
671
- const { amountBD, networkFeeData, totalInToken, swapFee, swapFeeInToken, networkFeeInToken } = await this.AmountAssertions.checkToBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, async (amountBD) => {
672
- //Check if we have enough liquidity to process the swap
673
- await this.LightningAssertions.checkLiquidity(amountBD, abortController.signal, true);
674
- metadata.times.liquidityChecked = Date.now();
675
- const maxFee = parsedBody.exactIn ?
676
- await this.swapPricing.getToBtcSwapAmount(parsedBody.maxFee, useToken, chainIdentifier, null, pricePrefetchPromise) :
677
- parsedBody.maxFee;
678
- return await this.checkAndGetNetworkFee(amountBD, maxFee, parsedBody.expiryTimestamp, currentTimestamp, parsedBody.pr, metadata, abortController.signal);
679
- }, abortController.signal);
680
- metadata.times.priceCalculated = Date.now();
681
- //For exactIn swap, just save and wait for the actual invoice to be submitted
682
- if (parsedBody.exactIn) {
683
- const reqId = (0, crypto_1.randomBytes)(32).toString("hex");
684
- this.exactInAuths[reqId] = {
685
- chainIdentifier,
686
- reqId,
687
- expiry: Date.now() + this.config.exactInExpiry,
688
- amount: amountBD,
689
- initialInvoice: parsedPR,
690
- quotedNetworkFeeInToken: networkFeeInToken,
691
- swapFeeInToken,
692
- total: totalInToken,
693
- confidence: networkFeeData.confidence,
694
- quotedNetworkFee: networkFeeData.networkFee,
695
- swapFee,
696
- token: useToken,
697
- swapExpiry: parsedBody.expiryTimestamp,
698
- offerer: parsedBody.offerer,
699
- preFetchSignData: signDataPrefetchPromise != null ? await signDataPrefetchPromise : null,
700
- metadata
701
- };
702
- this.logger.info("REST: /payInvoice: created exact in swap," +
703
- " reqId: " + reqId +
704
- " amount: " + amountBD.toString(10) +
705
- " destination: " + parsedPR.destination);
706
- await responseStream.writeParamsAndEnd({
707
- code: 20000,
708
- msg: "Success",
709
- data: {
710
- amount: amountBD.toString(10),
711
- reqId
712
- }
713
- });
714
- return;
715
- }
716
- const sequence = base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8));
717
- const claimHash = swapContract.getHashForHtlc(Buffer.from(parsedPR.id, "hex"));
718
- //Create swap data
719
- const payObject = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, parsedBody.offerer, signer.getAddress(), useToken, totalInToken, claimHash.toString("hex"), sequence, parsedBody.expiryTimestamp, true, false, 0n, 0n);
720
- abortController.signal.throwIfAborted();
721
- metadata.times.swapCreated = Date.now();
722
- //Sign swap data
723
- const sigData = await this.getToBtcSignatureData(chainIdentifier, payObject, req, abortController.signal, signDataPrefetchPromise);
724
- metadata.times.swapSigned = Date.now();
725
- //Create swap
726
- const createdSwap = new ToBtcLnSwapAbs_1.ToBtcLnSwapAbs(chainIdentifier, parsedPR.id, parsedBody.pr, parsedPR.mtokens, swapFee, swapFeeInToken, networkFeeData.networkFee, networkFeeInToken);
727
- createdSwap.data = payObject;
728
- createdSwap.metadata = metadata;
729
- createdSwap.prefix = sigData.prefix;
730
- createdSwap.timeout = sigData.timeout;
731
- createdSwap.signature = sigData.signature;
732
- createdSwap.feeRate = sigData.feeRate;
733
- await PluginManager_1.PluginManager.swapCreate(createdSwap);
734
- await this.saveSwapData(createdSwap);
735
- this.swapLogger.info(createdSwap, "REST: /payInvoice: created swap," +
736
- " amount: " + amountBD.toString(10) +
737
- " invoice: " + createdSwap.pr);
738
- await responseStream.writeParamsAndEnd({
739
- code: 20000,
740
- msg: "Success",
741
- data: {
742
- maxFee: networkFeeInToken.toString(10),
743
- swapFee: swapFeeInToken.toString(10),
744
- total: totalInToken.toString(10),
745
- confidence: halfConfidence ? networkFeeData.confidence / 2000000 : networkFeeData.confidence / 1000000,
746
- address: signer.getAddress(),
747
- routingFeeSats: networkFeeData.networkFee.toString(10),
748
- data: payObject.serialize(),
749
- prefix: sigData.prefix,
750
- timeout: sigData.timeout,
751
- signature: sigData.signature
752
- }
753
- });
754
- }));
755
- const getRefundAuthorization = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
756
- /**
757
- * paymentHash: string Identifier of the swap
758
- * sequence: BN Sequence identifier of the swap
759
- */
760
- const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
761
- paymentHash: (val) => val != null &&
762
- typeof (val) === "string" &&
763
- val.length === 64 &&
764
- Utils_1.HEX_REGEX.test(val) ? val : null,
765
- sequence: SchemaVerifier_1.FieldTypeEnum.BigInt
766
- });
767
- if (parsedBody == null)
768
- throw {
769
- code: 20100,
770
- msg: "Invalid request body/query (paymentHash/sequence)"
771
- };
772
- this.checkSequence(parsedBody.sequence);
773
- const data = await this.storageManager.getData(parsedBody.paymentHash, parsedBody.sequence);
774
- const isSwapFound = data != null;
775
- if (isSwapFound) {
776
- const { signer, swapContract } = this.getChain(data.chainIdentifier);
777
- if (await swapContract.isExpired(signer.getAddress(), data.data))
778
- throw {
779
- _httpStatus: 200,
780
- code: 20010,
781
- msg: "Payment expired"
782
- };
783
- if (data.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE) {
784
- const refundSigData = await swapContract.getRefundSignature(signer, data.data, this.config.refundAuthorizationTimeout);
785
- //Double check the state after promise result
786
- if (data.state !== ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE)
787
- throw {
788
- code: 20005,
789
- msg: "Not committed"
790
- };
791
- this.swapLogger.info(data, "REST: /getRefundAuthorization: returning refund authorization, because invoice in NON_PAYABLE state, invoice: " + data.pr);
792
- res.status(200).json({
793
- code: 20000,
794
- msg: "Success",
795
- data: {
796
- address: signer.getAddress(),
797
- prefix: refundSigData.prefix,
798
- timeout: refundSigData.timeout,
799
- signature: refundSigData.signature
800
- }
801
- });
802
- return;
803
- }
804
- }
805
- const payment = await this.lightning.getPayment(parsedBody.paymentHash);
806
- if (payment == null)
807
- throw {
808
- _httpStatus: 200,
809
- code: 20007,
810
- msg: "Payment not found"
811
- };
812
- if (payment.status === "pending")
813
- throw {
814
- _httpStatus: 200,
815
- code: 20008,
816
- msg: "Payment in-flight"
817
- };
818
- if (payment.status === "confirmed")
819
- throw {
820
- _httpStatus: 200,
821
- code: 20006,
822
- msg: "Already paid",
823
- data: {
824
- secret: payment.secret
825
- }
826
- };
827
- if (payment.status === "failed")
828
- throw {
829
- _httpStatus: 200,
830
- code: 20010,
831
- msg: "Payment expired",
832
- data: {
833
- reason: payment.failedReason
834
- }
835
- };
836
- });
837
- restServer.post(this.path + '/getRefundAuthorization', getRefundAuthorization);
838
- restServer.get(this.path + '/getRefundAuthorization', getRefundAuthorization);
839
- this.logger.info("started at path: ", this.path);
840
- }
841
- async init() {
842
- await this.loadData(ToBtcLnSwapAbs_1.ToBtcLnSwapAbs);
843
- //Check if all swaps contain a valid amount
844
- for (let { obj: swap } of await this.storageManager.query([])) {
845
- if (swap.amount == null || swap.lnPaymentHash == null) {
846
- const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
847
- swap.amount = (parsedPR.mtokens + 999n) / 1000n;
848
- swap.lnPaymentHash = parsedPR.id;
849
- }
850
- }
851
- this.subscribeToEvents();
852
- await PluginManager_1.PluginManager.serviceInitialize(this);
853
- }
854
- getInfoData() {
855
- return {
856
- minCltv: Number(this.config.minSendCltv),
857
- minTimestampCltv: Number(this.config.minTsSendCltv)
858
- };
859
- }
860
- }
861
- exports.ToBtcLnAbs = ToBtcLnAbs;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ToBtcLnAbs = void 0;
4
+ const ToBtcLnSwapAbs_1 = require("./ToBtcLnSwapAbs");
5
+ const SwapHandler_1 = require("../../SwapHandler");
6
+ const base_1 = require("@atomiqlabs/base");
7
+ const Utils_1 = require("../../../utils/Utils");
8
+ const PluginManager_1 = require("../../../plugins/PluginManager");
9
+ const crypto_1 = require("crypto");
10
+ const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
11
+ const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
12
+ const ToBtcBaseSwapHandler_1 = require("../ToBtcBaseSwapHandler");
13
+ const ILightningWallet_1 = require("../../../wallets/ILightningWallet");
14
+ const LightningAssertions_1 = require("../../assertions/LightningAssertions");
15
+ /**
16
+ * Swap handler handling to BTCLN swaps using submarine swaps
17
+ */
18
+ class ToBtcLnAbs extends ToBtcBaseSwapHandler_1.ToBtcBaseSwapHandler {
19
+ constructor(storageDirectory, path, chainData, lightning, swapPricing, config) {
20
+ super(storageDirectory, path, chainData, swapPricing, config);
21
+ this.activeSubscriptions = new Set();
22
+ this.type = SwapHandler_1.SwapHandlerType.TO_BTCLN;
23
+ this.swapType = base_1.ChainSwapType.HTLC;
24
+ this.exactInAuths = {};
25
+ this.lightning = lightning;
26
+ this.LightningAssertions = new LightningAssertions_1.LightningAssertions(this.logger, lightning);
27
+ const anyConfig = config;
28
+ anyConfig.minTsSendCltv = config.gracePeriod + (config.bitcoinBlocktime * config.minSendCltv * config.safetyFactor);
29
+ this.config = anyConfig;
30
+ this.config.minLnRoutingFeePPM = this.config.minLnRoutingFeePPM || 1000n;
31
+ this.config.minLnBaseFee = this.config.minLnBaseFee || 5n;
32
+ this.config.exactInExpiry = this.config.exactInExpiry || 10 * 1000;
33
+ }
34
+ /**
35
+ * Cleans up exactIn authorization that are already past their expiry
36
+ *
37
+ * @protected
38
+ */
39
+ cleanExpiredExactInAuthorizations() {
40
+ for (let key in this.exactInAuths) {
41
+ const obj = this.exactInAuths[key];
42
+ if (obj.expiry < Date.now()) {
43
+ this.logger.info("cleanExpiredExactInAuthorizations(): remove expired authorization, reqId: " + key);
44
+ delete this.exactInAuths[key];
45
+ }
46
+ }
47
+ }
48
+ async processPastSwap(swap) {
49
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
50
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED) {
51
+ //Cancel the swaps where signature is expired
52
+ const isSignatureExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
53
+ if (isSignatureExpired) {
54
+ const isCommitted = await swapContract.isCommited(swap.data);
55
+ if (!isCommitted) {
56
+ this.swapLogger.info(swap, "processPastSwap(state=SAVED): authorization expired & swap not committed, cancelling swap, invoice: " + swap.pr);
57
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CANCELED);
58
+ return;
59
+ }
60
+ else {
61
+ this.swapLogger.info(swap, "processPastSwap(state=SAVED): swap committed (detected from processPastSwap), invoice: " + swap.pr);
62
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED);
63
+ await this.saveSwapData(swap);
64
+ }
65
+ }
66
+ //Cancel the swaps where lightning invoice is expired
67
+ const decodedPR = await this.lightning.parsePaymentRequest(swap.pr);
68
+ const isInvoiceExpired = decodedPR.expiryEpochMillis < Date.now();
69
+ if (isInvoiceExpired) {
70
+ this.swapLogger.info(swap, "processPastSwap(state=SAVED): invoice expired, cancel uncommited swap, invoice: " + swap.pr);
71
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CANCELED);
72
+ return;
73
+ }
74
+ }
75
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED || swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID) {
76
+ //Process swaps in commited & paid state
77
+ await this.processInitialized(swap);
78
+ }
79
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE) {
80
+ //Remove expired swaps (as these can already be unilaterally refunded by the client), so we don't need
81
+ // to be able to cooperatively refund them
82
+ if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
83
+ this.swapLogger.info(swap, "processPastSwap(state=NON_PAYABLE): swap expired, removing swap data, invoice: " + swap.pr);
84
+ await this.removeSwapData(swap);
85
+ }
86
+ }
87
+ }
88
+ /**
89
+ * Checks past swaps, deletes ones that are already expired, and tries to process ones that are committed.
90
+ */
91
+ async processPastSwaps() {
92
+ this.cleanExpiredExactInAuthorizations();
93
+ const queriedData = await this.storageManager.query([
94
+ {
95
+ key: "state",
96
+ value: [
97
+ ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED,
98
+ ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED,
99
+ ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID,
100
+ ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE
101
+ ]
102
+ }
103
+ ]);
104
+ for (let { obj: swap } of queriedData) {
105
+ await this.processPastSwap(swap);
106
+ }
107
+ }
108
+ /**
109
+ * Tries to claim the swap funds on the SC side, returns false if the swap is already locked (claim tx is already being sent)
110
+ *
111
+ * @param swap
112
+ * @private
113
+ * @returns Whether the transaction was successfully sent
114
+ */
115
+ async tryClaimSwap(swap) {
116
+ if (swap.secret == null)
117
+ throw new Error("Invalid swap state, needs payment pre-image!");
118
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
119
+ //Check if escrow state exists
120
+ const isCommited = await swapContract.isCommited(swap.data);
121
+ if (!isCommited) {
122
+ const status = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
123
+ if (status?.type === base_1.SwapCommitStateType.PAID) {
124
+ //This is alright, we got the money
125
+ swap.txIds ?? (swap.txIds = {});
126
+ swap.txIds.claim = await status.getClaimTxId();
127
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
128
+ return true;
129
+ }
130
+ else if (status?.type === base_1.SwapCommitStateType.EXPIRED) {
131
+ //This means the user was able to refund before we were able to claim, no good
132
+ swap.txIds ?? (swap.txIds = {});
133
+ swap.txIds.refund = status.getRefundTxId == null ? null : await status.getRefundTxId();
134
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
135
+ }
136
+ this.swapLogger.warn(swap, "processPaymentResult(): tried to claim but escrow doesn't exist anymore," +
137
+ " status: " + status +
138
+ " invoice: " + swap.pr);
139
+ return false;
140
+ }
141
+ //Set flag that we are sending the transaction already, so we don't end up with race condition
142
+ const unlock = swap.lock(swapContract.claimWithSecretTimeout);
143
+ if (unlock == null)
144
+ return false;
145
+ try {
146
+ this.swapLogger.debug(swap, "tryClaimSwap(): initiate claim of swap, secret: " + swap.secret);
147
+ const success = await swapContract.claimWithSecret(signer, swap.data, swap.secret, false, false, {
148
+ waitForConfirmation: true
149
+ });
150
+ this.swapLogger.info(swap, "tryClaimSwap(): swap claimed successfully, secret: " + swap.secret + " invoice: " + swap.pr);
151
+ if (swap.metadata != null)
152
+ swap.metadata.times.txClaimed = Date.now();
153
+ unlock();
154
+ return true;
155
+ }
156
+ catch (e) {
157
+ this.swapLogger.error(swap, "tryClaimSwap(): error occurred claiming swap, secret: " + swap.secret + " invoice: " + swap.pr, e);
158
+ return false;
159
+ }
160
+ }
161
+ /**
162
+ * Process the result of attempted lightning network payment
163
+ *
164
+ * @param swap
165
+ * @param lnPaymentStatus
166
+ */
167
+ async processPaymentResult(swap, lnPaymentStatus) {
168
+ switch (lnPaymentStatus.status) {
169
+ case "pending":
170
+ return;
171
+ case "failed":
172
+ this.swapLogger.info(swap, "processPaymentResult(): invoice payment failed, cancelling swap, invoice: " + swap.pr);
173
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE);
174
+ await this.saveSwapData(swap);
175
+ return;
176
+ case "confirmed":
177
+ swap.secret = lnPaymentStatus.secret;
178
+ swap.setRealNetworkFee(lnPaymentStatus.feeMtokens / 1000n);
179
+ this.swapLogger.info(swap, "processPaymentResult(): invoice paid, secret: " + swap.secret + " realRoutingFee: " + swap.realNetworkFee.toString(10) + " invoice: " + swap.pr);
180
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID);
181
+ await this.saveSwapData(swap);
182
+ const success = await this.tryClaimSwap(swap);
183
+ if (success)
184
+ this.swapLogger.info(swap, "processPaymentResult(): swap claimed successfully, invoice: " + swap.pr);
185
+ return;
186
+ default:
187
+ throw new Error("Invalid lnPaymentStatus");
188
+ }
189
+ }
190
+ /**
191
+ * Subscribe to a pending lightning network payment attempt
192
+ *
193
+ * @param invoiceData
194
+ */
195
+ subscribeToPayment(invoiceData) {
196
+ const paymentHash = invoiceData.lnPaymentHash;
197
+ if (this.activeSubscriptions.has(paymentHash))
198
+ return false;
199
+ this.lightning.waitForPayment(paymentHash).then(result => {
200
+ this.swapLogger.info(invoiceData, "subscribeToPayment(): result callback, outcome: " + result.status + " invoice: " + invoiceData.pr);
201
+ this.processPaymentResult(invoiceData, result).catch(e => this.swapLogger.error(invoiceData, "subscribeToPayment(): process payment result", e));
202
+ this.activeSubscriptions.delete(paymentHash);
203
+ });
204
+ this.swapLogger.info(invoiceData, "subscribeToPayment(): subscribe to payment outcome, invoice: " + invoiceData.pr);
205
+ this.activeSubscriptions.add(paymentHash);
206
+ return true;
207
+ }
208
+ async sendLightningPayment(swap) {
209
+ const decodedPR = await this.lightning.parsePaymentRequest(swap.pr);
210
+ const expiryTimestamp = swap.data.getExpiry();
211
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
212
+ //Run checks
213
+ const hasEnoughTimeToPay = (expiryTimestamp - currentTimestamp) >= this.config.minTsSendCltv;
214
+ if (!hasEnoughTimeToPay)
215
+ throw {
216
+ code: 90005,
217
+ msg: "Not enough time to reliably pay the invoice"
218
+ };
219
+ const isInvoiceExpired = decodedPR.expiryEpochMillis < Date.now();
220
+ if (isInvoiceExpired)
221
+ throw {
222
+ code: 90006,
223
+ msg: "Invoice already expired"
224
+ };
225
+ //Compute max cltv delta
226
+ const maxFee = swap.quotedNetworkFee;
227
+ const maxUsableCLTVdelta = (expiryTimestamp - currentTimestamp - this.config.gracePeriod)
228
+ / (this.config.bitcoinBlocktime * this.config.safetyFactor);
229
+ //Initiate payment
230
+ this.swapLogger.info(swap, "sendLightningPayment(): paying lightning network invoice," +
231
+ " cltvDelta: " + maxUsableCLTVdelta.toString(10) +
232
+ " maxFee: " + maxFee.toString(10) +
233
+ " invoice: " + swap.pr);
234
+ const blockHeight = await this.lightning.getBlockheight();
235
+ try {
236
+ await this.lightning.pay({
237
+ request: swap.pr,
238
+ maxFeeMtokens: maxFee * 1000n,
239
+ maxTimeoutHeight: blockHeight + Number(maxUsableCLTVdelta)
240
+ });
241
+ }
242
+ catch (e) {
243
+ throw {
244
+ code: 90007,
245
+ msg: "Failed to initiate invoice payment",
246
+ data: {
247
+ error: JSON.stringify(e)
248
+ }
249
+ };
250
+ }
251
+ if (swap.metadata != null)
252
+ swap.metadata.times.payComplete = Date.now();
253
+ }
254
+ /**
255
+ * Begins a lightning network payment attempt, if not attempted already
256
+ *
257
+ * @param swap
258
+ */
259
+ async processInitialized(swap) {
260
+ //Check if payment was already made
261
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.PAID) {
262
+ const success = await this.tryClaimSwap(swap);
263
+ if (success)
264
+ this.swapLogger.info(swap, "processInitialized(): swap claimed successfully, invoice: " + swap.pr);
265
+ return;
266
+ }
267
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED) {
268
+ if (swap.metadata != null)
269
+ swap.metadata.times.payPaymentChecked = Date.now();
270
+ let lnPaymentStatus = await this.lightning.getPayment(swap.lnPaymentHash);
271
+ if (lnPaymentStatus != null) {
272
+ if (lnPaymentStatus.status === "pending") {
273
+ //Payment still ongoing, process the result
274
+ this.subscribeToPayment(swap);
275
+ return;
276
+ }
277
+ else {
278
+ //Payment has already concluded, process the result
279
+ await this.processPaymentResult(swap, lnPaymentStatus);
280
+ return;
281
+ }
282
+ }
283
+ else {
284
+ //Payment not founds, try to process again
285
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED);
286
+ }
287
+ }
288
+ if (swap.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED) {
289
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.COMMITED);
290
+ await this.saveSwapData(swap);
291
+ try {
292
+ await this.sendLightningPayment(swap);
293
+ }
294
+ catch (e) {
295
+ this.swapLogger.error(swap, "processInitialized(): lightning payment error", e);
296
+ if ((0, Utils_1.isDefinedRuntimeError)(e)) {
297
+ if (swap.metadata != null)
298
+ swap.metadata.payError = e;
299
+ await swap.setState(ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE);
300
+ await this.saveSwapData(swap);
301
+ return;
302
+ }
303
+ else
304
+ throw e;
305
+ }
306
+ this.subscribeToPayment(swap);
307
+ return;
308
+ }
309
+ }
310
+ async processInitializeEvent(chainIdentifier, swap, event) {
311
+ this.swapLogger.info(swap, "SC: InitializeEvent: swap initialized by the client, invoice: " + swap.pr);
312
+ //Only process swaps in SAVED state
313
+ if (swap.state !== ToBtcLnSwapAbs_1.ToBtcLnSwapState.SAVED)
314
+ return;
315
+ await this.processInitialized(swap);
316
+ }
317
+ async processClaimEvent(chainIdentifier, swap, event) {
318
+ this.swapLogger.info(swap, "SC: ClaimEvent: swap claimed to us, secret: " + event.result + " invoice: " + swap.pr);
319
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.CLAIMED);
320
+ }
321
+ async processRefundEvent(chainIdentifier, swap, event) {
322
+ this.swapLogger.info(swap, "SC: RefundEvent: swap refunded back to the client, invoice: " + swap.pr);
323
+ await this.removeSwapData(swap, ToBtcLnSwapAbs_1.ToBtcLnSwapState.REFUNDED);
324
+ }
325
+ /**
326
+ * Checks if the amount was supplied in the exactIn request
327
+ *
328
+ * @param amount
329
+ * @param exactIn
330
+ * @throws {DefinedRuntimeError} will throw an error if the swap was exactIn, but amount not specified
331
+ */
332
+ checkAmount(amount, exactIn) {
333
+ if (exactIn) {
334
+ if (amount == null) {
335
+ throw {
336
+ code: 20040,
337
+ msg: "Invalid request body (amount not specified)!"
338
+ };
339
+ }
340
+ }
341
+ }
342
+ /**
343
+ * Checks if the maxFee parameter is in valid range (>0)
344
+ *
345
+ * @param maxFee
346
+ * @throws {DefinedRuntimeError} will throw an error if the maxFee is zero or negative
347
+ */
348
+ checkMaxFee(maxFee) {
349
+ if (maxFee <= 0) {
350
+ throw {
351
+ code: 20030,
352
+ msg: "Invalid request body (maxFee too low)!"
353
+ };
354
+ }
355
+ }
356
+ /**
357
+ * Checks and parses a payment request (bolt11 invoice), additionally also checks expiration time of the invoice
358
+ *
359
+ * @param chainIdentifier
360
+ * @param pr
361
+ * @throws {DefinedRuntimeError} will throw an error if the pr is invalid, without amount or expired
362
+ */
363
+ async checkPaymentRequest(chainIdentifier, pr) {
364
+ let parsedPR;
365
+ try {
366
+ parsedPR = await this.lightning.parsePaymentRequest(pr);
367
+ }
368
+ catch (e) {
369
+ throw {
370
+ code: 20021,
371
+ msg: "Invalid request body (pr - cannot be parsed)"
372
+ };
373
+ }
374
+ if (parsedPR.mtokens == null)
375
+ throw {
376
+ code: 20022,
377
+ msg: "Invalid request body (pr - needs to have amount)"
378
+ };
379
+ let halfConfidence = false;
380
+ if (parsedPR.expiryEpochMillis < Date.now() + ((this.getInitAuthorizationTimeout(chainIdentifier) + (2 * 60)) * 1000)) {
381
+ if (!this.config.allowShortExpiry) {
382
+ throw {
383
+ code: 20020,
384
+ msg: "Invalid request body (pr - expired)"
385
+ };
386
+ }
387
+ else if (parsedPR.expiryEpochMillis < Date.now()) {
388
+ throw {
389
+ code: 20020,
390
+ msg: "Invalid request body (pr - expired)"
391
+ };
392
+ }
393
+ halfConfidence = true;
394
+ }
395
+ return { parsedPR, halfConfidence };
396
+ }
397
+ /**
398
+ * Checks if the request specified too short of an expiry
399
+ *
400
+ * @param expiryTimestamp
401
+ * @param currentTimestamp
402
+ * @throws {DefinedRuntimeError} will throw an error if the expiry time is too short
403
+ */
404
+ checkExpiry(expiryTimestamp, currentTimestamp) {
405
+ const expiresTooSoon = (expiryTimestamp - currentTimestamp) < this.config.minTsSendCltv;
406
+ if (expiresTooSoon) {
407
+ throw {
408
+ code: 20001,
409
+ msg: "Expiry time too low!"
410
+ };
411
+ }
412
+ }
413
+ /**
414
+ * Estimates the routing fee & confidence by either probing or routing (if probing fails), the fee is also adjusted
415
+ * according to routing fee multiplier, and subject to minimums set in config
416
+ *
417
+ * @param amountBD
418
+ * @param maxFee
419
+ * @param expiryTimestamp
420
+ * @param currentTimestamp
421
+ * @param pr
422
+ * @param metadata
423
+ * @param abortSignal
424
+ * @throws {DefinedRuntimeError} will throw an error if the destination is unreachable
425
+ */
426
+ async checkAndGetNetworkFee(amountBD, maxFee, expiryTimestamp, currentTimestamp, pr, metadata, abortSignal) {
427
+ const maxUsableCLTV = (expiryTimestamp - currentTimestamp - this.config.gracePeriod) / (this.config.bitcoinBlocktime * this.config.safetyFactor);
428
+ const blockHeight = await this.lightning.getBlockheight();
429
+ abortSignal.throwIfAborted();
430
+ metadata.times.blockheightFetched = Date.now();
431
+ const maxTimeoutBlockheight = BigInt(blockHeight) + maxUsableCLTV;
432
+ const req = {
433
+ request: pr,
434
+ amountMtokens: amountBD * 1000n,
435
+ maxFeeMtokens: maxFee * 1000n,
436
+ maxTimeoutHeight: Number(maxTimeoutBlockheight)
437
+ };
438
+ let probeOrRouteResp = await this.lightning.probe(req);
439
+ metadata.times.probeResult = Date.now();
440
+ metadata.probeResponse = { ...probeOrRouteResp };
441
+ abortSignal.throwIfAborted();
442
+ if (probeOrRouteResp == null) {
443
+ if (!this.config.allowProbeFailedSwaps)
444
+ throw {
445
+ code: 20002,
446
+ msg: "Cannot route the payment!"
447
+ };
448
+ const routeResp = await this.lightning.route(req);
449
+ metadata.times.routingResult = Date.now();
450
+ metadata.routeResponse = { ...routeResp };
451
+ abortSignal.throwIfAborted();
452
+ if (routeResp == null)
453
+ throw {
454
+ code: 20002,
455
+ msg: "Cannot route the payment!"
456
+ };
457
+ this.logger.info("checkAndGetNetworkFee(): routing result," +
458
+ " destination: " + routeResp.destination +
459
+ " confidence: " + routeResp.confidence +
460
+ " fee mtokens: " + routeResp.feeMtokens.toString(10));
461
+ probeOrRouteResp = routeResp;
462
+ }
463
+ else {
464
+ this.logger.info("checkAndGetNetworkFee(): route probed," +
465
+ " destination: " + probeOrRouteResp.destination +
466
+ " confidence: " + probeOrRouteResp.confidence +
467
+ " fee mtokens: " + probeOrRouteResp.feeMtokens.toString(10));
468
+ }
469
+ const safeFeeTokens = (probeOrRouteResp.feeMtokens + 999n) / 1000n;
470
+ let actualRoutingFee = safeFeeTokens * this.config.routingFeeMultiplier;
471
+ const minRoutingFee = (amountBD * this.config.minLnRoutingFeePPM / 1000000n) + this.config.minLnBaseFee;
472
+ if (actualRoutingFee < minRoutingFee) {
473
+ actualRoutingFee = minRoutingFee;
474
+ if (actualRoutingFee > maxFee) {
475
+ probeOrRouteResp.confidence = 0;
476
+ }
477
+ }
478
+ if (actualRoutingFee > maxFee) {
479
+ actualRoutingFee = maxFee;
480
+ }
481
+ this.logger.debug("checkAndGetNetworkFee(): network fee calculated, amount: " + amountBD.toString(10) + " fee: " + actualRoutingFee.toString(10));
482
+ return {
483
+ networkFee: actualRoutingFee,
484
+ confidence: probeOrRouteResp.confidence
485
+ };
486
+ }
487
+ /**
488
+ * Checks and consumes (deletes & returns) exactIn authorizaton with a specific reqId
489
+ *
490
+ * @param reqId
491
+ * @throws {DefinedRuntimeError} will throw an error if the authorization doesn't exist
492
+ */
493
+ checkExactInAuthorization(reqId) {
494
+ const parsedAuth = this.exactInAuths[reqId];
495
+ if (parsedAuth == null) {
496
+ throw {
497
+ code: 20070,
498
+ msg: "Invalid reqId"
499
+ };
500
+ }
501
+ delete this.exactInAuths[reqId];
502
+ if (parsedAuth.expiry < Date.now()) {
503
+ throw {
504
+ code: 20200,
505
+ msg: "Authorization already expired!"
506
+ };
507
+ }
508
+ return parsedAuth;
509
+ }
510
+ /**
511
+ * Checks if the newly submitted PR has the same parameters (destination, cltv_delta, routes) as the initial dummy
512
+ * invoice sent for exactIn swap quote
513
+ *
514
+ * @param pr
515
+ * @param parsedAuth
516
+ * @throws {DefinedRuntimeError} will throw an error if the details don't match
517
+ */
518
+ async checkPaymentRequestMatchesInitial(pr, parsedAuth) {
519
+ const parsedRequest = await this.lightning.parsePaymentRequest(pr);
520
+ if (parsedRequest.destination !== parsedAuth.initialInvoice.destination ||
521
+ parsedRequest.cltvDelta !== parsedAuth.initialInvoice.cltvDelta ||
522
+ parsedRequest.mtokens !== parsedAuth.amount * 1000n) {
523
+ throw {
524
+ code: 20102,
525
+ msg: "Provided PR doesn't match initial!"
526
+ };
527
+ }
528
+ if (!(0, ILightningWallet_1.routesMatch)(parsedRequest.routes, parsedAuth.initialInvoice.routes)) {
529
+ throw {
530
+ code: 20102,
531
+ msg: "Provided PR doesn't match initial (routes)!"
532
+ };
533
+ }
534
+ }
535
+ startRestServer(restServer) {
536
+ restServer.use(this.path + "/payInvoiceExactIn", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
537
+ restServer.post(this.path + "/payInvoiceExactIn", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
538
+ /**
539
+ * pr: string bolt11 lightning invoice
540
+ * reqId: string Identifier of the swap
541
+ * feeRate: string Fee rate to use for the init tx
542
+ */
543
+ const parsedBody = await req.paramReader.getParams({
544
+ pr: SchemaVerifier_1.FieldTypeEnum.String,
545
+ reqId: SchemaVerifier_1.FieldTypeEnum.String,
546
+ feeRate: SchemaVerifier_1.FieldTypeEnum.String
547
+ });
548
+ if (parsedBody == null) {
549
+ throw {
550
+ code: 20100,
551
+ msg: "Invalid request body"
552
+ };
553
+ }
554
+ const responseStream = res.responseStream;
555
+ const abortSignal = responseStream.getAbortSignal();
556
+ //Check request params
557
+ const parsedAuth = this.checkExactInAuthorization(parsedBody.reqId);
558
+ const { parsedPR, halfConfidence } = await this.checkPaymentRequest(parsedAuth.chainIdentifier, parsedBody.pr);
559
+ await this.checkPaymentRequestMatchesInitial(parsedBody.pr, parsedAuth);
560
+ const metadata = parsedAuth.metadata;
561
+ const sequence = base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8));
562
+ const { swapContract, signer } = this.getChain(parsedAuth.chainIdentifier);
563
+ const claimHash = swapContract.getHashForHtlc(Buffer.from(parsedPR.id, "hex"));
564
+ //Create swap data
565
+ const payObject = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, parsedAuth.offerer, signer.getAddress(), parsedAuth.token, parsedAuth.total, claimHash.toString("hex"), sequence, parsedAuth.swapExpiry, true, false, 0n, 0n);
566
+ metadata.times.swapCreated = Date.now();
567
+ //Sign swap data
568
+ const prefetchedSignData = parsedAuth.preFetchSignData;
569
+ const sigData = await this.getToBtcSignatureData(parsedAuth.chainIdentifier, payObject, req, abortSignal, prefetchedSignData);
570
+ metadata.times.swapSigned = Date.now();
571
+ //Create swap
572
+ const createdSwap = new ToBtcLnSwapAbs_1.ToBtcLnSwapAbs(parsedAuth.chainIdentifier, parsedPR.id, parsedBody.pr, parsedPR.mtokens, parsedAuth.swapFee, parsedAuth.swapFeeInToken, parsedAuth.quotedNetworkFee, parsedAuth.quotedNetworkFeeInToken);
573
+ createdSwap.data = payObject;
574
+ createdSwap.metadata = metadata;
575
+ createdSwap.prefix = sigData.prefix;
576
+ createdSwap.timeout = sigData.timeout;
577
+ createdSwap.signature = sigData.signature;
578
+ createdSwap.feeRate = sigData.feeRate;
579
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
580
+ await this.saveSwapData(createdSwap);
581
+ this.swapLogger.info(createdSwap, "REST: /payInvoiceExactIn: created exact in swap," +
582
+ " reqId: " + parsedBody.reqId +
583
+ " mtokens: " + parsedPR.mtokens.toString(10) +
584
+ " invoice: " + createdSwap.pr);
585
+ await responseStream.writeParamsAndEnd({
586
+ code: 20000,
587
+ msg: "Success",
588
+ data: {
589
+ maxFee: parsedAuth.quotedNetworkFeeInToken.toString(10),
590
+ swapFee: parsedAuth.swapFeeInToken.toString(10),
591
+ total: parsedAuth.total.toString(10),
592
+ confidence: halfConfidence ? parsedAuth.confidence / 2000000 : parsedAuth.confidence / 1000000,
593
+ address: signer.getAddress(),
594
+ routingFeeSats: parsedAuth.quotedNetworkFee.toString(10),
595
+ data: payObject.serialize(),
596
+ prefix: sigData.prefix,
597
+ timeout: sigData.timeout,
598
+ signature: sigData.signature
599
+ }
600
+ });
601
+ }));
602
+ restServer.use(this.path + "/payInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
603
+ restServer.post(this.path + "/payInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
604
+ const metadata = { request: {}, times: {} };
605
+ const chainIdentifier = req.query.chain ?? this.chains.default;
606
+ const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
607
+ metadata.times.requestReceived = Date.now();
608
+ /**
609
+ *Sent initially:
610
+ * pr: string bolt11 lightning invoice
611
+ * maxFee: string maximum routing fee
612
+ * expiryTimestamp: string expiry timestamp of the to be created HTLC, determines how many LN paths can be considered
613
+ * token: string Desired token to use
614
+ * offerer: string Address of the caller
615
+ * exactIn: boolean Whether to do an exact in swap instead of exact out
616
+ * amount: string Input amount for exactIn swaps
617
+ *
618
+ *Sent later:
619
+ * feeRate: string Fee rate to use for the init signature
620
+ */
621
+ const parsedBody = await req.paramReader.getParams({
622
+ pr: SchemaVerifier_1.FieldTypeEnum.String,
623
+ maxFee: SchemaVerifier_1.FieldTypeEnum.BigInt,
624
+ expiryTimestamp: SchemaVerifier_1.FieldTypeEnum.BigInt,
625
+ token: (val) => val != null &&
626
+ typeof (val) === "string" &&
627
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
628
+ offerer: (val) => val != null &&
629
+ typeof (val) === "string" &&
630
+ chainInterface.isValidAddress(val) ? val : null,
631
+ exactIn: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
632
+ amount: SchemaVerifier_1.FieldTypeEnum.BigIntOptional
633
+ });
634
+ if (parsedBody == null) {
635
+ throw {
636
+ code: 20100,
637
+ msg: "Invalid request body"
638
+ };
639
+ }
640
+ metadata.request = parsedBody;
641
+ const request = {
642
+ chainIdentifier,
643
+ raw: req,
644
+ parsed: parsedBody,
645
+ metadata
646
+ };
647
+ const useToken = parsedBody.token;
648
+ const responseStream = res.responseStream;
649
+ const currentTimestamp = BigInt(Math.floor(Date.now() / 1000));
650
+ //Check request params
651
+ this.checkAmount(parsedBody.amount, parsedBody.exactIn);
652
+ this.checkMaxFee(parsedBody.maxFee);
653
+ this.checkExpiry(parsedBody.expiryTimestamp, currentTimestamp);
654
+ await this.checkVaultInitialized(chainIdentifier, parsedBody.token);
655
+ const { parsedPR, halfConfidence } = await this.checkPaymentRequest(chainIdentifier, parsedBody.pr);
656
+ const requestedAmount = {
657
+ input: !!parsedBody.exactIn,
658
+ amount: !!parsedBody.exactIn ? parsedBody.amount : (parsedPR.mtokens + 999n) / 1000n,
659
+ token: useToken
660
+ };
661
+ const fees = await this.AmountAssertions.preCheckToBtcAmounts(this.type, request, requestedAmount);
662
+ metadata.times.requestChecked = Date.now();
663
+ //Create abort controller for parallel pre-fetches
664
+ const abortController = (0, Utils_1.getAbortController)(responseStream);
665
+ //Pre-fetch
666
+ const { pricePrefetchPromise, signDataPrefetchPromise } = this.getToBtcPrefetches(chainIdentifier, useToken, responseStream, abortController);
667
+ //Check if prior payment has been made
668
+ await this.LightningAssertions.checkPriorPayment(parsedPR.id, abortController.signal);
669
+ metadata.times.priorPaymentChecked = Date.now();
670
+ //Check amounts
671
+ const { amountBD, networkFeeData, totalInToken, swapFee, swapFeeInToken, networkFeeInToken } = await this.AmountAssertions.checkToBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, async (amountBD) => {
672
+ //Check if we have enough liquidity to process the swap
673
+ await this.LightningAssertions.checkLiquidity(amountBD, abortController.signal, true);
674
+ metadata.times.liquidityChecked = Date.now();
675
+ const maxFee = parsedBody.exactIn ?
676
+ await this.swapPricing.getToBtcSwapAmount(parsedBody.maxFee, useToken, chainIdentifier, null, pricePrefetchPromise) :
677
+ parsedBody.maxFee;
678
+ return await this.checkAndGetNetworkFee(amountBD, maxFee, parsedBody.expiryTimestamp, currentTimestamp, parsedBody.pr, metadata, abortController.signal);
679
+ }, abortController.signal);
680
+ metadata.times.priceCalculated = Date.now();
681
+ //For exactIn swap, just save and wait for the actual invoice to be submitted
682
+ if (parsedBody.exactIn) {
683
+ const reqId = (0, crypto_1.randomBytes)(32).toString("hex");
684
+ this.exactInAuths[reqId] = {
685
+ chainIdentifier,
686
+ reqId,
687
+ expiry: Date.now() + this.config.exactInExpiry,
688
+ amount: amountBD,
689
+ initialInvoice: parsedPR,
690
+ quotedNetworkFeeInToken: networkFeeInToken,
691
+ swapFeeInToken,
692
+ total: totalInToken,
693
+ confidence: networkFeeData.confidence,
694
+ quotedNetworkFee: networkFeeData.networkFee,
695
+ swapFee,
696
+ token: useToken,
697
+ swapExpiry: parsedBody.expiryTimestamp,
698
+ offerer: parsedBody.offerer,
699
+ preFetchSignData: signDataPrefetchPromise != null ? await signDataPrefetchPromise : null,
700
+ metadata
701
+ };
702
+ this.logger.info("REST: /payInvoice: created exact in swap," +
703
+ " reqId: " + reqId +
704
+ " amount: " + amountBD.toString(10) +
705
+ " destination: " + parsedPR.destination);
706
+ await responseStream.writeParamsAndEnd({
707
+ code: 20000,
708
+ msg: "Success",
709
+ data: {
710
+ amount: amountBD.toString(10),
711
+ reqId
712
+ }
713
+ });
714
+ return;
715
+ }
716
+ const sequence = base_1.BigIntBufferUtils.fromBuffer((0, crypto_1.randomBytes)(8));
717
+ const claimHash = swapContract.getHashForHtlc(Buffer.from(parsedPR.id, "hex"));
718
+ //Create swap data
719
+ const payObject = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, parsedBody.offerer, signer.getAddress(), useToken, totalInToken, claimHash.toString("hex"), sequence, parsedBody.expiryTimestamp, true, false, 0n, 0n);
720
+ abortController.signal.throwIfAborted();
721
+ metadata.times.swapCreated = Date.now();
722
+ //Sign swap data
723
+ const sigData = await this.getToBtcSignatureData(chainIdentifier, payObject, req, abortController.signal, signDataPrefetchPromise);
724
+ metadata.times.swapSigned = Date.now();
725
+ //Create swap
726
+ const createdSwap = new ToBtcLnSwapAbs_1.ToBtcLnSwapAbs(chainIdentifier, parsedPR.id, parsedBody.pr, parsedPR.mtokens, swapFee, swapFeeInToken, networkFeeData.networkFee, networkFeeInToken);
727
+ createdSwap.data = payObject;
728
+ createdSwap.metadata = metadata;
729
+ createdSwap.prefix = sigData.prefix;
730
+ createdSwap.timeout = sigData.timeout;
731
+ createdSwap.signature = sigData.signature;
732
+ createdSwap.feeRate = sigData.feeRate;
733
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
734
+ await this.saveSwapData(createdSwap);
735
+ this.swapLogger.info(createdSwap, "REST: /payInvoice: created swap," +
736
+ " amount: " + amountBD.toString(10) +
737
+ " invoice: " + createdSwap.pr);
738
+ await responseStream.writeParamsAndEnd({
739
+ code: 20000,
740
+ msg: "Success",
741
+ data: {
742
+ maxFee: networkFeeInToken.toString(10),
743
+ swapFee: swapFeeInToken.toString(10),
744
+ total: totalInToken.toString(10),
745
+ confidence: halfConfidence ? networkFeeData.confidence / 2000000 : networkFeeData.confidence / 1000000,
746
+ address: signer.getAddress(),
747
+ routingFeeSats: networkFeeData.networkFee.toString(10),
748
+ data: payObject.serialize(),
749
+ prefix: sigData.prefix,
750
+ timeout: sigData.timeout,
751
+ signature: sigData.signature
752
+ }
753
+ });
754
+ }));
755
+ const getRefundAuthorization = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
756
+ /**
757
+ * paymentHash: string Identifier of the swap
758
+ * sequence: BN Sequence identifier of the swap
759
+ */
760
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
761
+ paymentHash: (val) => val != null &&
762
+ typeof (val) === "string" &&
763
+ val.length === 64 &&
764
+ Utils_1.HEX_REGEX.test(val) ? val : null,
765
+ sequence: SchemaVerifier_1.FieldTypeEnum.BigInt
766
+ });
767
+ if (parsedBody == null)
768
+ throw {
769
+ code: 20100,
770
+ msg: "Invalid request body/query (paymentHash/sequence)"
771
+ };
772
+ this.checkSequence(parsedBody.sequence);
773
+ const data = await this.storageManager.getData(parsedBody.paymentHash, parsedBody.sequence);
774
+ const isSwapFound = data != null;
775
+ if (isSwapFound) {
776
+ const { signer, swapContract } = this.getChain(data.chainIdentifier);
777
+ if (await swapContract.isExpired(signer.getAddress(), data.data))
778
+ throw {
779
+ _httpStatus: 200,
780
+ code: 20010,
781
+ msg: "Payment expired"
782
+ };
783
+ if (data.state === ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE) {
784
+ const refundSigData = await swapContract.getRefundSignature(signer, data.data, this.config.refundAuthorizationTimeout);
785
+ //Double check the state after promise result
786
+ if (data.state !== ToBtcLnSwapAbs_1.ToBtcLnSwapState.NON_PAYABLE)
787
+ throw {
788
+ code: 20005,
789
+ msg: "Not committed"
790
+ };
791
+ this.swapLogger.info(data, "REST: /getRefundAuthorization: returning refund authorization, because invoice in NON_PAYABLE state, invoice: " + data.pr);
792
+ res.status(200).json({
793
+ code: 20000,
794
+ msg: "Success",
795
+ data: {
796
+ address: signer.getAddress(),
797
+ prefix: refundSigData.prefix,
798
+ timeout: refundSigData.timeout,
799
+ signature: refundSigData.signature
800
+ }
801
+ });
802
+ return;
803
+ }
804
+ }
805
+ const payment = await this.lightning.getPayment(parsedBody.paymentHash);
806
+ if (payment == null)
807
+ throw {
808
+ _httpStatus: 200,
809
+ code: 20007,
810
+ msg: "Payment not found"
811
+ };
812
+ if (payment.status === "pending")
813
+ throw {
814
+ _httpStatus: 200,
815
+ code: 20008,
816
+ msg: "Payment in-flight"
817
+ };
818
+ if (payment.status === "confirmed")
819
+ throw {
820
+ _httpStatus: 200,
821
+ code: 20006,
822
+ msg: "Already paid",
823
+ data: {
824
+ secret: payment.secret
825
+ }
826
+ };
827
+ if (payment.status === "failed")
828
+ throw {
829
+ _httpStatus: 200,
830
+ code: 20010,
831
+ msg: "Payment expired",
832
+ data: {
833
+ reason: payment.failedReason
834
+ }
835
+ };
836
+ });
837
+ restServer.post(this.path + '/getRefundAuthorization', getRefundAuthorization);
838
+ restServer.get(this.path + '/getRefundAuthorization', getRefundAuthorization);
839
+ this.logger.info("started at path: ", this.path);
840
+ }
841
+ async init() {
842
+ await this.loadData(ToBtcLnSwapAbs_1.ToBtcLnSwapAbs);
843
+ //Check if all swaps contain a valid amount
844
+ for (let { obj: swap } of await this.storageManager.query([])) {
845
+ if (swap.amount == null || swap.lnPaymentHash == null) {
846
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
847
+ swap.amount = (parsedPR.mtokens + 999n) / 1000n;
848
+ swap.lnPaymentHash = parsedPR.id;
849
+ }
850
+ }
851
+ this.subscribeToEvents();
852
+ await PluginManager_1.PluginManager.serviceInitialize(this);
853
+ }
854
+ getInfoData() {
855
+ return {
856
+ minCltv: Number(this.config.minSendCltv),
857
+ minTimestampCltv: Number(this.config.minTsSendCltv)
858
+ };
859
+ }
860
+ }
861
+ exports.ToBtcLnAbs = ToBtcLnAbs;