@atomiqlabs/lp-lib 13.0.0-beta.9 → 13.0.0

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