@atomiqlabs/lp-lib 14.0.0-dev.21 → 14.0.0-dev.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/LICENSE +201 -201
  2. package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
  3. package/dist/fees/IBtcFeeEstimator.js +2 -2
  4. package/dist/index.d.ts +42 -42
  5. package/dist/index.js +58 -58
  6. package/dist/info/InfoHandler.d.ts +17 -17
  7. package/dist/info/InfoHandler.js +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 +180 -180
  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 -675
  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 +111 -111
  59. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +684 -684
  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 +863 -863
  68. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +24 -24
  69. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +58 -58
  70. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +40 -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 +492 -492
  76. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +52 -52
  77. package/dist/swaps/spv_vault_swap/SpvVaults.js +394 -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/BitcoinUtils.d.ts +2 -2
  87. package/dist/utils/BitcoinUtils.js +45 -45
  88. package/dist/utils/Utils.d.ts +29 -29
  89. package/dist/utils/Utils.js +89 -89
  90. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  91. package/dist/utils/paramcoders/IParamReader.js +2 -2
  92. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  93. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  94. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  95. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  96. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  97. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  98. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  99. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  100. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  101. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  102. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  103. package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -107
  104. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  105. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  106. package/dist/wallets/IBitcoinWallet.d.ts +67 -67
  107. package/dist/wallets/IBitcoinWallet.js +2 -2
  108. package/dist/wallets/ILightningWallet.d.ts +117 -117
  109. package/dist/wallets/ILightningWallet.js +37 -37
  110. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  111. package/dist/wallets/ISpvVaultSigner.js +2 -2
  112. package/package.json +36 -36
  113. package/src/fees/IBtcFeeEstimator.ts +6 -6
  114. package/src/index.ts +53 -53
  115. package/src/info/InfoHandler.ts +106 -106
  116. package/src/plugins/IPlugin.ts +168 -168
  117. package/src/plugins/PluginManager.ts +336 -336
  118. package/src/prices/BinanceSwapPrice.ts +113 -113
  119. package/src/prices/CoinGeckoSwapPrice.ts +87 -87
  120. package/src/prices/ISwapPrice.ts +88 -88
  121. package/src/prices/OKXSwapPrice.ts +113 -113
  122. package/src/storage/IIntermediaryStorage.ts +19 -19
  123. package/src/storagemanager/IntermediaryStorageManager.ts +118 -118
  124. package/src/storagemanager/StorageManager.ts +78 -78
  125. package/src/swaps/SwapHandler.ts +277 -277
  126. package/src/swaps/SwapHandlerSwap.ts +141 -141
  127. package/src/swaps/assertions/AmountAssertions.ts +76 -76
  128. package/src/swaps/assertions/FromBtcAmountAssertions.ts +246 -246
  129. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  130. package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
  131. package/src/swaps/escrow/EscrowHandler.ts +179 -179
  132. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  133. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  134. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +286 -286
  135. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  136. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  137. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +452 -452
  138. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
  139. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +856 -856
  140. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -141
  141. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +850 -850
  142. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -196
  143. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +879 -879
  144. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +102 -102
  145. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1112 -1112
  146. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +80 -80
  147. package/src/swaps/spv_vault_swap/SpvVault.ts +143 -143
  148. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +225 -225
  149. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +628 -628
  150. package/src/swaps/spv_vault_swap/SpvVaults.ts +469 -435
  151. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
  152. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  153. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +590 -590
  154. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  155. package/src/utils/BitcoinUtils.ts +42 -42
  156. package/src/utils/Utils.ts +104 -104
  157. package/src/utils/paramcoders/IParamReader.ts +7 -7
  158. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  159. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  160. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  161. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  162. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  163. package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -118
  164. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  165. package/src/wallets/IBitcoinWallet.ts +68 -68
  166. package/src/wallets/ILightningWallet.ts +178 -178
  167. package/src/wallets/ISpvVaultSigner.ts +10 -10
@@ -1,684 +1,684 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.FromBtcLnAuto = void 0;
4
- const crypto_1 = require("crypto");
5
- const FromBtcLnAutoSwap_1 = require("./FromBtcLnAutoSwap");
6
- const SwapHandler_1 = require("../../SwapHandler");
7
- const base_1 = require("@atomiqlabs/base");
8
- const Utils_1 = require("../../../utils/Utils");
9
- const PluginManager_1 = require("../../../plugins/PluginManager");
10
- const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
- const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
- const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
13
- const LightningAssertions_1 = require("../../assertions/LightningAssertions");
14
- /**
15
- * Swap handler handling from BTCLN swaps using submarine swaps
16
- */
17
- class FromBtcLnAuto extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
18
- constructor(storageDirectory, path, chains, lightning, swapPricing, config) {
19
- super(storageDirectory, path, chains, swapPricing, config);
20
- this.type = SwapHandler_1.SwapHandlerType.FROM_BTCLN_AUTO;
21
- this.swapType = base_1.ChainSwapType.HTLC;
22
- this.activeSubscriptions = new Set();
23
- this.config = config;
24
- this.config.invoiceTimeoutSeconds = this.config.invoiceTimeoutSeconds || 90;
25
- this.lightning = lightning;
26
- this.LightningAssertions = new LightningAssertions_1.LightningAssertions(this.logger, lightning);
27
- }
28
- async processPastSwap(swap) {
29
- const { swapContract, signer } = this.getChain(swap.chainIdentifier);
30
- if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED) {
31
- //Check if already paid
32
- const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
33
- const invoice = await this.lightning.getInvoice(parsedPR.id);
34
- const isBeingPaid = invoice.status === "held";
35
- if (!isBeingPaid) {
36
- //Not paid
37
- const isInvoiceExpired = parsedPR.expiryEpochMillis < Date.now();
38
- if (isInvoiceExpired) {
39
- this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap LN invoice expired, cancelling, invoice: " + swap.pr);
40
- await this.cancelSwapAndInvoice(swap);
41
- return null;
42
- }
43
- this.subscribeToInvoice(swap);
44
- return null;
45
- }
46
- //Adjust the state of the swap and expiry
47
- try {
48
- await this.htlcReceived(swap, invoice);
49
- //Result is either FromBtcLnSwapState.RECEIVED or FromBtcLnSwapState.CANCELED
50
- }
51
- catch (e) {
52
- this.swapLogger.error(swap, "processPastSwap(state=CREATED): htlcReceived error", e);
53
- }
54
- return null;
55
- }
56
- if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
57
- try {
58
- if (!await this.offerHtlc(swap)) {
59
- //Expired
60
- if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
61
- this.swapLogger.info(swap, "processPastSwap(state=RECEIVED): offer HTLC expired, cancelling invoice: " + swap.pr);
62
- await this.cancelSwapAndInvoice(swap);
63
- }
64
- }
65
- }
66
- catch (e) {
67
- this.swapLogger.error(swap, "processPastSwap(state=RECEIVED): offerHtlc error", e);
68
- }
69
- return null;
70
- }
71
- if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT || swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED) {
72
- const onchainStatus = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
73
- const state = swap.state;
74
- if (onchainStatus.type === base_1.SwapCommitStateType.PAID) {
75
- //Extract the swap secret
76
- if (state !== FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED && state !== FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.SETTLED) {
77
- const secretHex = await onchainStatus.getClaimResult();
78
- const secret = Buffer.from(secretHex, "hex");
79
- const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
80
- const paymentHashHex = paymentHash.toString("hex");
81
- if (swap.lnPaymentHash !== paymentHashHex) {
82
- //TODO: Possibly fatal failure
83
- this.swapLogger.error(swap, "processPastSwap(state=TXS_SENT|COMMITED): onchainStatus=PAID, Invalid swap secret specified: " + secretHex + " for paymentHash: " + paymentHashHex);
84
- return null;
85
- }
86
- swap.secret = secretHex;
87
- await swap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED);
88
- await this.saveSwapData(swap);
89
- this.swapLogger.warn(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap settled (detected from processPastSwap), invoice: " + swap.pr);
90
- return "SETTLE";
91
- }
92
- return null;
93
- }
94
- if (onchainStatus.type === base_1.SwapCommitStateType.COMMITED) {
95
- if (state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT) {
96
- await swap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED);
97
- await this.saveSwapData(swap);
98
- this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap committed (detected from processPastSwap), invoice: " + swap.pr);
99
- }
100
- return null;
101
- }
102
- if (onchainStatus.type === base_1.SwapCommitStateType.NOT_COMMITED || onchainStatus.type === base_1.SwapCommitStateType.EXPIRED) {
103
- if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT) {
104
- const isAuthorizationExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
105
- if (isAuthorizationExpired) {
106
- this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap not committed before authorization expiry, cancelling the LN invoice, invoice: " + swap.pr);
107
- await this.cancelSwapAndInvoice(swap);
108
- return null;
109
- }
110
- }
111
- else {
112
- if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
113
- this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
114
- return "REFUND";
115
- }
116
- }
117
- }
118
- if (onchainStatus.type === base_1.SwapCommitStateType.REFUNDABLE) {
119
- this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
120
- return "REFUND";
121
- }
122
- }
123
- if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED)
124
- return "SETTLE";
125
- if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CANCELED)
126
- await this.cancelSwapAndInvoice(swap);
127
- }
128
- async refundSwaps(refundSwaps) {
129
- for (let refundSwap of refundSwaps) {
130
- const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
131
- const unlock = refundSwap.lock(swapContract.refundTimeout);
132
- if (unlock == null)
133
- continue;
134
- this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
135
- await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
136
- this.swapLogger.info(refundSwap, "refundsSwaps(): swap refunded, invoice: " + refundSwap.pr);
137
- await refundSwap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.REFUNDED);
138
- unlock();
139
- }
140
- }
141
- async settleInvoices(swaps) {
142
- for (let swap of swaps) {
143
- try {
144
- await this.lightning.settleHodlInvoice(swap.secret);
145
- if (swap.metadata != null)
146
- swap.metadata.times.htlcSettled = Date.now();
147
- await this.removeSwapData(swap, FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.SETTLED);
148
- this.swapLogger.info(swap, "settleInvoices(): invoice settled, secret: " + swap.secret);
149
- }
150
- catch (e) {
151
- this.swapLogger.error(swap, "settleInvoices(): cannot settle invoice", e);
152
- }
153
- }
154
- }
155
- /**
156
- * Checks past swaps, refunds and deletes ones that are already expired.
157
- */
158
- async processPastSwaps() {
159
- const settleInvoices = [];
160
- const refundSwaps = [];
161
- const queriedData = await this.storageManager.query([
162
- {
163
- key: "state",
164
- value: [
165
- FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED,
166
- FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED,
167
- FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT,
168
- FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED,
169
- FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED,
170
- FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CANCELED,
171
- ]
172
- }
173
- ]);
174
- for (let { obj: swap } of queriedData) {
175
- switch (await this.processPastSwap(swap)) {
176
- case "SETTLE":
177
- settleInvoices.push(swap);
178
- break;
179
- case "REFUND":
180
- refundSwaps.push(swap);
181
- break;
182
- }
183
- }
184
- await this.refundSwaps(refundSwaps);
185
- await this.settleInvoices(settleInvoices);
186
- }
187
- async processInitializeEvent(chainIdentifier, savedSwap, event) {
188
- this.swapLogger.info(savedSwap, "SC: InitializeEvent: HTLC initialized by the client, invoice: " + savedSwap.pr);
189
- if (savedSwap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT) {
190
- await savedSwap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED);
191
- await this.saveSwapData(savedSwap);
192
- }
193
- }
194
- async processClaimEvent(chainIdentifier, savedSwap, event) {
195
- //Claim
196
- //This is the important part, we need to catch the claim TX, else we may lose money
197
- const secret = Buffer.from(event.result, "hex");
198
- const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
199
- const secretHex = secret.toString("hex");
200
- const paymentHashHex = paymentHash.toString("hex");
201
- if (savedSwap.lnPaymentHash !== paymentHashHex)
202
- return;
203
- this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap HTLC successfully claimed by the client, invoice: " + savedSwap.pr);
204
- try {
205
- await this.lightning.settleHodlInvoice(secretHex);
206
- this.swapLogger.info(savedSwap, "SC: ClaimEvent: invoice settled, secret: " + secretHex);
207
- savedSwap.secret = secretHex;
208
- if (savedSwap.metadata != null)
209
- savedSwap.metadata.times.htlcSettled = Date.now();
210
- await this.removeSwapData(savedSwap, FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.SETTLED);
211
- }
212
- catch (e) {
213
- this.swapLogger.error(savedSwap, "SC: ClaimEvent: cannot settle invoice", e);
214
- savedSwap.secret = secretHex;
215
- await savedSwap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED);
216
- await this.saveSwapData(savedSwap);
217
- }
218
- }
219
- async processRefundEvent(chainIdentifier, savedSwap, event) {
220
- this.swapLogger.info(savedSwap, "SC: RefundEvent: swap refunded to us, invoice: " + savedSwap.pr);
221
- //We don't cancel the incoming invoice, to make the offender pay for this with locked liquidity
222
- // await this.lightning.cancelHodlInvoice(savedSwap.lnPaymentHash);
223
- await this.removeSwapData(savedSwap, FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.REFUNDED);
224
- }
225
- /**
226
- * Subscribe to a lightning network invoice
227
- *
228
- * @param swap
229
- */
230
- subscribeToInvoice(swap) {
231
- const paymentHash = swap.lnPaymentHash;
232
- if (this.activeSubscriptions.has(paymentHash))
233
- return false;
234
- this.lightning.waitForInvoice(paymentHash).then(result => {
235
- this.swapLogger.info(swap, "subscribeToInvoice(): result callback, outcome: " + result.status + " invoice: " + swap.pr);
236
- if (result.status === "held")
237
- this.htlcReceived(swap, result).catch(e => this.swapLogger.error(swap, "subscribeToInvoice(): HTLC received result", e));
238
- this.activeSubscriptions.delete(paymentHash);
239
- });
240
- this.swapLogger.info(swap, "subscribeToInvoice(): subscribe to invoice: " + swap.pr);
241
- this.activeSubscriptions.add(paymentHash);
242
- return true;
243
- }
244
- /**
245
- * Called when lightning HTLC is received, also signs an init transaction on the smart chain side, expiry of the
246
- * smart chain authorization starts ticking as soon as this HTLC is received
247
- *
248
- * @param invoiceData
249
- * @param invoice
250
- */
251
- async htlcReceived(invoiceData, invoice) {
252
- if (invoiceData.state !== FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED)
253
- return;
254
- this.swapLogger.debug(invoiceData, "htlcReceived(): invoice: ", invoice);
255
- if (invoiceData.metadata != null)
256
- invoiceData.metadata.times.htlcReceived = Date.now();
257
- const useToken = invoiceData.token;
258
- const gasToken = invoiceData.gasToken;
259
- let expiryTimeout;
260
- try {
261
- //Check if HTLC expiry is long enough
262
- expiryTimeout = await this.checkHtlcExpiry(invoice);
263
- if (invoiceData.metadata != null)
264
- invoiceData.metadata.times.htlcTimeoutCalculated = Date.now();
265
- }
266
- catch (e) {
267
- if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED)
268
- await this.cancelSwapAndInvoice(invoiceData);
269
- throw e;
270
- }
271
- const { swapContract, signer } = this.getChain(invoiceData.chainIdentifier);
272
- //Create real swap data
273
- const swapData = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, signer.getAddress(), invoiceData.claimer, useToken, invoiceData.amountToken, invoiceData.claimHash, 0n, BigInt(Math.floor(Date.now() / 1000)) + expiryTimeout, false, true, invoiceData.amountGasToken + invoiceData.claimerBounty, invoiceData.claimerBounty, invoiceData.gasToken);
274
- if (invoiceData.metadata != null)
275
- invoiceData.metadata.times.htlcSwapCreated = Date.now();
276
- //Important to prevent race condition and issuing 2 signed init messages at the same time
277
- if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED) {
278
- invoiceData.data = swapData;
279
- invoiceData.signature = null;
280
- invoiceData.timeout = (BigInt(Math.floor(Date.now() / 1000)) + 120n).toString(10);
281
- //Setting the state variable is done outside the promise, so is done synchronously
282
- await invoiceData.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED);
283
- await this.saveSwapData(invoiceData);
284
- await this.offerHtlc(invoiceData);
285
- }
286
- }
287
- async offerHtlc(invoiceData) {
288
- if (invoiceData.state !== FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED)
289
- return;
290
- this.swapLogger.debug(invoiceData, "offerHtlc(): invoice: ", invoiceData.pr);
291
- if (invoiceData.metadata != null)
292
- invoiceData.metadata.times.offerHtlc = Date.now();
293
- const useToken = invoiceData.token;
294
- const gasToken = invoiceData.gasToken;
295
- const { swapContract, signer, chainInterface } = this.getChain(invoiceData.chainIdentifier);
296
- //Create abort controller for parallel fetches
297
- const abortController = new AbortController();
298
- //Pre-fetch data
299
- const balancePrefetch = this.getBalancePrefetch(invoiceData.chainIdentifier, useToken, abortController);
300
- const gasTokenBalancePrefetch = invoiceData.getTotalOutputGasAmount() === 0n || useToken === gasToken ?
301
- null : this.getBalancePrefetch(invoiceData.chainIdentifier, gasToken, abortController);
302
- if (await swapContract.getInitAuthorizationExpiry(invoiceData.data, invoiceData) < Date.now()) {
303
- if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
304
- await this.cancelSwapAndInvoice(invoiceData);
305
- }
306
- return false;
307
- }
308
- try {
309
- //Check if we have enough liquidity to proceed
310
- if (useToken === gasToken) {
311
- await this.checkBalance(invoiceData.getTotalOutputAmount() + invoiceData.getTotalOutputGasAmount(), balancePrefetch, abortController.signal);
312
- }
313
- else {
314
- await this.checkBalance(invoiceData.getTotalOutputAmount(), balancePrefetch, abortController.signal);
315
- await this.checkBalance(invoiceData.getTotalOutputGasAmount(), gasTokenBalancePrefetch, abortController.signal);
316
- }
317
- if (invoiceData.metadata != null)
318
- invoiceData.metadata.times.offerHtlcChecked = Date.now();
319
- }
320
- catch (e) {
321
- if (!abortController.signal.aborted) {
322
- if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED)
323
- await this.cancelSwapAndInvoice(invoiceData);
324
- }
325
- throw e;
326
- }
327
- const txWithdraw = await swapContract.txsWithdraw(signer.getAddress(), gasToken, invoiceData.data.getTotalDeposit());
328
- const txInit = await swapContract.txsInit(signer.getAddress(), invoiceData.data, {
329
- prefix: invoiceData.prefix,
330
- timeout: invoiceData.timeout,
331
- signature: invoiceData.signature
332
- }, true);
333
- if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
334
- //Setting the state variable is done outside the promise, so is done synchronously
335
- await invoiceData.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT);
336
- await this.saveSwapData(invoiceData);
337
- await chainInterface.sendAndConfirm(signer, [...txWithdraw, ...txInit], true, undefined, true);
338
- }
339
- return true;
340
- }
341
- /**
342
- * Checks invoice description hash
343
- *
344
- * @param descriptionHash
345
- * @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
346
- */
347
- checkDescriptionHash(descriptionHash) {
348
- if (descriptionHash != null) {
349
- if (typeof (descriptionHash) !== "string" || !Utils_1.HEX_REGEX.test(descriptionHash) || descriptionHash.length !== 64) {
350
- throw {
351
- code: 20100,
352
- msg: "Invalid request body (descriptionHash)"
353
- };
354
- }
355
- }
356
- }
357
- /**
358
- * Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
359
- *
360
- * @param responseStream
361
- */
362
- sendPublicKeyAsync(responseStream) {
363
- this.lightning.getIdentityPublicKey().then(publicKey => responseStream.writeParams({
364
- lnPublicKey: publicKey
365
- })).catch(e => {
366
- this.logger.error("sendPublicKeyAsync(): error", e);
367
- });
368
- }
369
- /**
370
- * Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
371
- * received (MPP) it returns the lowest of the timeouts
372
- *
373
- * @param invoice
374
- */
375
- getInvoicePaymentsTimeout(invoice) {
376
- let timeout = null;
377
- invoice.payments.forEach((curr) => {
378
- if (timeout == null || timeout > curr.timeout)
379
- timeout = curr.timeout;
380
- });
381
- return timeout;
382
- }
383
- /**
384
- * Checks if the received HTLC's CLTV timeout is large enough to still process the swap
385
- *
386
- * @param invoice
387
- * @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
388
- * @returns expiry timeout in seconds
389
- */
390
- async checkHtlcExpiry(invoice) {
391
- const timeout = this.getInvoicePaymentsTimeout(invoice);
392
- const current_block_height = await this.lightning.getBlockheight();
393
- const blockDelta = BigInt(timeout - current_block_height);
394
- const htlcExpiresTooSoon = blockDelta < this.config.minCltv;
395
- if (htlcExpiresTooSoon) {
396
- throw {
397
- code: 20002,
398
- msg: "Not enough time to reliably process the swap",
399
- data: {
400
- requiredDelta: this.config.minCltv.toString(10),
401
- actualDelta: blockDelta.toString(10)
402
- }
403
- };
404
- }
405
- return (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
406
- }
407
- /**
408
- * Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
409
- *
410
- * @param invoiceData
411
- */
412
- async cancelSwapAndInvoice(invoiceData) {
413
- await invoiceData.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CANCELED);
414
- await this.lightning.cancelHodlInvoice(invoiceData.lnPaymentHash);
415
- await this.removeSwapData(invoiceData);
416
- this.swapLogger.info(invoiceData, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", invoiceData.pr);
417
- }
418
- ;
419
- /**
420
- *
421
- * Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
422
- *
423
- * @param paymentHash
424
- * @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
425
- * @returns the fetched lightning invoice
426
- */
427
- async checkInvoiceStatus(paymentHash) {
428
- const invoice = await this.lightning.getInvoice(paymentHash);
429
- if (invoice == null)
430
- throw {
431
- _httpStatus: 200,
432
- code: 10001,
433
- msg: "Invoice expired/canceled"
434
- };
435
- const arr = invoice.description.split("-");
436
- let chainIdentifier;
437
- let address;
438
- if (arr.length > 1) {
439
- chainIdentifier = arr[0];
440
- address = arr[1];
441
- }
442
- else {
443
- chainIdentifier = this.chains.default;
444
- address = invoice.description;
445
- }
446
- const { chainInterface } = this.getChain(chainIdentifier);
447
- if (!chainInterface.isValidAddress(address))
448
- throw {
449
- _httpStatus: 200,
450
- code: 10001,
451
- msg: "Invoice expired/canceled"
452
- };
453
- switch (invoice.status) {
454
- case "canceled":
455
- throw {
456
- _httpStatus: 200,
457
- code: 10001,
458
- msg: "Invoice expired/canceled"
459
- };
460
- case "confirmed":
461
- throw {
462
- _httpStatus: 200,
463
- code: 10002,
464
- msg: "Invoice already paid"
465
- };
466
- case "unpaid":
467
- throw {
468
- _httpStatus: 200,
469
- code: 10003,
470
- msg: "Invoice yet unpaid"
471
- };
472
- default:
473
- return invoice;
474
- }
475
- }
476
- startRestServer(restServer) {
477
- restServer.use(this.path + "/createInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
478
- restServer.post(this.path + "/createInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
479
- const metadata = { request: {}, times: {} };
480
- const chainIdentifier = req.query.chain ?? this.chains.default;
481
- const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
482
- if (!swapContract.supportsInitWithoutClaimer)
483
- throw {
484
- code: 20299,
485
- msg: "Not supported for " + chainIdentifier
486
- };
487
- metadata.times.requestReceived = Date.now();
488
- /**
489
- * address: string smart chain address of the recipient
490
- * paymentHash: string payment hash of the to-be-created invoice
491
- * amount: string amount (in sats) of the invoice
492
- * token: string Desired token to swap
493
- * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
494
- * descriptionHash: string Description hash of the invoice
495
- * gasAmount: string Desired amount in gas token to also get
496
- * gasToken: string
497
- * claimerBounty: string Desired amount to be left out as a claimer bounty
498
- */
499
- const parsedBody = await req.paramReader.getParams({
500
- address: (val) => val != null &&
501
- typeof (val) === "string" &&
502
- chainInterface.isValidAddress(val) ? val : null,
503
- paymentHash: (val) => val != null &&
504
- typeof (val) === "string" &&
505
- val.length === 64 &&
506
- Utils_1.HEX_REGEX.test(val) ? val : null,
507
- amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
508
- token: (val) => val != null &&
509
- typeof (val) === "string" &&
510
- this.isTokenSupported(chainIdentifier, val) ? val : null,
511
- descriptionHash: SchemaVerifier_1.FieldTypeEnum.StringOptional,
512
- exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
513
- gasToken: (val) => val != null &&
514
- typeof (val) === "string" &&
515
- chainInterface.isValidToken(val) ? val : null,
516
- gasAmount: SchemaVerifier_1.FieldTypeEnum.BigInt,
517
- claimerBounty: SchemaVerifier_1.FieldTypeEnum.BigInt
518
- });
519
- if (parsedBody == null)
520
- throw {
521
- code: 20100,
522
- msg: "Invalid request body"
523
- };
524
- if (parsedBody.gasToken !== chainInterface.getNativeCurrencyAddress())
525
- throw {
526
- code: 20290,
527
- msg: "Unsupported gas token"
528
- };
529
- if (parsedBody.gasAmount < 0)
530
- throw {
531
- code: 20291,
532
- msg: "Invalid gas amount, negative"
533
- };
534
- if (parsedBody.claimerBounty < 0)
535
- throw {
536
- code: 20292,
537
- msg: "Invalid claimer bounty, negative"
538
- };
539
- metadata.request = parsedBody;
540
- const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
541
- const gasTokenAmount = {
542
- input: false,
543
- amount: parsedBody.gasAmount + parsedBody.claimerBounty,
544
- token: parsedBody.gasToken
545
- };
546
- const request = {
547
- chainIdentifier,
548
- raw: req,
549
- parsed: parsedBody,
550
- metadata
551
- };
552
- const useToken = parsedBody.token;
553
- const gasToken = parsedBody.gasToken;
554
- //Check request params
555
- this.checkDescriptionHash(parsedBody.descriptionHash);
556
- const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
557
- metadata.times.requestChecked = Date.now();
558
- //Create abortController for parallel prefetches
559
- const responseStream = res.responseStream;
560
- const abortController = (0, Utils_1.getAbortController)(responseStream);
561
- //Pre-fetch data
562
- const { pricePrefetchPromise, gasTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, gasToken, abortController);
563
- const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
564
- const gasTokenBalancePrefetch = gasTokenAmount.amount === 0n || useToken === gasToken ?
565
- null : this.getBalancePrefetch(chainIdentifier, gasToken, abortController);
566
- const channelsPrefetch = this.LightningAssertions.getChannelsPrefetch(abortController);
567
- //Asynchronously send the node's public key to the client
568
- this.sendPublicKeyAsync(responseStream);
569
- //Check valid amount specified (min/max)
570
- let { amountBD, swapFee, swapFeeInToken, totalInToken, amountBDgas, gasSwapFee, gasSwapFeeInToken, totalInGasToken } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal, { ...gasTokenAmount, pricePrefetch: gasTokenPricePrefetchPromise });
571
- metadata.times.priceCalculated = Date.now();
572
- const totalBtcInput = amountBD + amountBDgas;
573
- //Check if we have enough funds to honor the request
574
- if (useToken === gasToken) {
575
- await this.checkBalance(totalInToken + totalInGasToken, balancePrefetch, abortController.signal);
576
- }
577
- else {
578
- await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
579
- await this.checkBalance(totalInGasToken, gasTokenBalancePrefetch, abortController.signal);
580
- }
581
- await this.LightningAssertions.checkInboundLiquidity(totalBtcInput, channelsPrefetch, abortController.signal);
582
- metadata.times.balanceChecked = Date.now();
583
- //Create swap
584
- const hodlInvoiceObj = {
585
- description: chainIdentifier + "-" + parsedBody.address,
586
- cltvDelta: Number(this.config.minCltv) + 5,
587
- expiresAt: Date.now() + (this.config.invoiceTimeoutSeconds * 1000),
588
- id: parsedBody.paymentHash,
589
- mtokens: totalBtcInput * 1000n,
590
- descriptionHash: parsedBody.descriptionHash
591
- };
592
- metadata.invoiceRequest = hodlInvoiceObj;
593
- const hodlInvoice = await this.lightning.createHodlInvoice(hodlInvoiceObj);
594
- abortController.signal.throwIfAborted();
595
- metadata.times.invoiceCreated = Date.now();
596
- metadata.invoiceResponse = { ...hodlInvoice };
597
- totalInGasToken -= parsedBody.claimerBounty;
598
- const createdSwap = new FromBtcLnAutoSwap_1.FromBtcLnAutoSwap(chainIdentifier, hodlInvoice.request, parsedBody.paymentHash, swapContract.getHashForHtlc(Buffer.from(parsedBody.paymentHash, "hex")).toString("hex"), hodlInvoice.mtokens, parsedBody.address, useToken, gasToken, totalInToken, totalInGasToken, swapFee, swapFeeInToken, gasSwapFee, gasSwapFeeInToken, parsedBody.claimerBounty);
599
- metadata.times.swapCreated = Date.now();
600
- createdSwap.metadata = metadata;
601
- await PluginManager_1.PluginManager.swapCreate(createdSwap);
602
- await this.saveSwapData(createdSwap);
603
- this.swapLogger.info(createdSwap, "REST: /createInvoice: Created swap invoice: " + hodlInvoice.request + " amount: " + totalBtcInput.toString(10));
604
- this.subscribeToInvoice(createdSwap);
605
- await responseStream.writeParamsAndEnd({
606
- code: 20000,
607
- msg: "Success",
608
- data: {
609
- intermediaryKey: signer.getAddress(),
610
- pr: hodlInvoice.request,
611
- btcAmountSwap: amountBD.toString(10),
612
- btcAmountGas: amountBDgas.toString(10),
613
- total: totalInToken.toString(10),
614
- totalGas: totalInGasToken.toString(10),
615
- totalFeeBtc: (swapFee + gasSwapFee).toString(10),
616
- swapFeeBtc: swapFee.toString(10),
617
- swapFee: swapFeeInToken.toString(10),
618
- gasSwapFeeBtc: gasSwapFee.toString(10),
619
- gasSwapFee: gasSwapFeeInToken.toString(10),
620
- claimerBounty: parsedBody.claimerBounty.toString(10)
621
- }
622
- });
623
- }));
624
- const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
625
- /**
626
- * paymentHash: string payment hash of the invoice
627
- */
628
- const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
629
- paymentHash: (val) => val != null &&
630
- typeof (val) === "string" &&
631
- val.length === 64 &&
632
- Utils_1.HEX_REGEX.test(val) ? val : null,
633
- });
634
- await this.checkInvoiceStatus(parsedBody.paymentHash);
635
- const swap = await this.storageManager.getData(parsedBody.paymentHash, null);
636
- if (swap == null)
637
- throw {
638
- _httpStatus: 200,
639
- code: 10001,
640
- msg: "Invoice expired/canceled"
641
- };
642
- if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED ||
643
- swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT ||
644
- swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED) {
645
- res.status(200).json({
646
- code: 10000,
647
- msg: "Success",
648
- data: {
649
- data: swap.data.serialize()
650
- }
651
- });
652
- }
653
- else {
654
- res.status(200).json({
655
- code: 10003,
656
- msg: "Invoice yet unpaid"
657
- });
658
- }
659
- });
660
- restServer.post(this.path + "/getInvoiceStatus", getInvoiceStatus);
661
- restServer.get(this.path + "/getInvoiceStatus", getInvoiceStatus);
662
- this.logger.info("started at path: ", this.path);
663
- }
664
- async init() {
665
- await this.loadData(FromBtcLnAutoSwap_1.FromBtcLnAutoSwap);
666
- this.subscribeToEvents();
667
- await PluginManager_1.PluginManager.serviceInitialize(this);
668
- }
669
- getInfoData() {
670
- const mappedDict = {};
671
- for (let chainId in this.config.gasTokenMax) {
672
- mappedDict[chainId] = {
673
- gasToken: this.getChain(chainId).chainInterface.getNativeCurrencyAddress(),
674
- max: this.config.gasTokenMax[chainId].toString(10)
675
- };
676
- }
677
- return {
678
- minCltv: Number(this.config.minCltv),
679
- invoiceTimeoutSeconds: this.config.invoiceTimeoutSeconds,
680
- gasTokens: mappedDict
681
- };
682
- }
683
- }
684
- exports.FromBtcLnAuto = FromBtcLnAuto;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FromBtcLnAuto = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const FromBtcLnAutoSwap_1 = require("./FromBtcLnAutoSwap");
6
+ const SwapHandler_1 = require("../../SwapHandler");
7
+ const base_1 = require("@atomiqlabs/base");
8
+ const Utils_1 = require("../../../utils/Utils");
9
+ const PluginManager_1 = require("../../../plugins/PluginManager");
10
+ const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
+ const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
+ const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
13
+ const LightningAssertions_1 = require("../../assertions/LightningAssertions");
14
+ /**
15
+ * Swap handler handling from BTCLN swaps using submarine swaps
16
+ */
17
+ class FromBtcLnAuto extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
18
+ constructor(storageDirectory, path, chains, lightning, swapPricing, config) {
19
+ super(storageDirectory, path, chains, swapPricing, config);
20
+ this.type = SwapHandler_1.SwapHandlerType.FROM_BTCLN_AUTO;
21
+ this.swapType = base_1.ChainSwapType.HTLC;
22
+ this.activeSubscriptions = new Set();
23
+ this.config = config;
24
+ this.config.invoiceTimeoutSeconds = this.config.invoiceTimeoutSeconds || 90;
25
+ this.lightning = lightning;
26
+ this.LightningAssertions = new LightningAssertions_1.LightningAssertions(this.logger, lightning);
27
+ }
28
+ async processPastSwap(swap) {
29
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
30
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED) {
31
+ //Check if already paid
32
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
33
+ const invoice = await this.lightning.getInvoice(parsedPR.id);
34
+ const isBeingPaid = invoice.status === "held";
35
+ if (!isBeingPaid) {
36
+ //Not paid
37
+ const isInvoiceExpired = parsedPR.expiryEpochMillis < Date.now();
38
+ if (isInvoiceExpired) {
39
+ this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap LN invoice expired, cancelling, invoice: " + swap.pr);
40
+ await this.cancelSwapAndInvoice(swap);
41
+ return null;
42
+ }
43
+ this.subscribeToInvoice(swap);
44
+ return null;
45
+ }
46
+ //Adjust the state of the swap and expiry
47
+ try {
48
+ await this.htlcReceived(swap, invoice);
49
+ //Result is either FromBtcLnSwapState.RECEIVED or FromBtcLnSwapState.CANCELED
50
+ }
51
+ catch (e) {
52
+ this.swapLogger.error(swap, "processPastSwap(state=CREATED): htlcReceived error", e);
53
+ }
54
+ return null;
55
+ }
56
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
57
+ try {
58
+ if (!await this.offerHtlc(swap)) {
59
+ //Expired
60
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
61
+ this.swapLogger.info(swap, "processPastSwap(state=RECEIVED): offer HTLC expired, cancelling invoice: " + swap.pr);
62
+ await this.cancelSwapAndInvoice(swap);
63
+ }
64
+ }
65
+ }
66
+ catch (e) {
67
+ this.swapLogger.error(swap, "processPastSwap(state=RECEIVED): offerHtlc error", e);
68
+ }
69
+ return null;
70
+ }
71
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT || swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED) {
72
+ const onchainStatus = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
73
+ const state = swap.state;
74
+ if (onchainStatus.type === base_1.SwapCommitStateType.PAID) {
75
+ //Extract the swap secret
76
+ if (state !== FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED && state !== FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.SETTLED) {
77
+ const secretHex = await onchainStatus.getClaimResult();
78
+ const secret = Buffer.from(secretHex, "hex");
79
+ const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
80
+ const paymentHashHex = paymentHash.toString("hex");
81
+ if (swap.lnPaymentHash !== paymentHashHex) {
82
+ //TODO: Possibly fatal failure
83
+ this.swapLogger.error(swap, "processPastSwap(state=TXS_SENT|COMMITED): onchainStatus=PAID, Invalid swap secret specified: " + secretHex + " for paymentHash: " + paymentHashHex);
84
+ return null;
85
+ }
86
+ swap.secret = secretHex;
87
+ await swap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED);
88
+ await this.saveSwapData(swap);
89
+ this.swapLogger.warn(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap settled (detected from processPastSwap), invoice: " + swap.pr);
90
+ return "SETTLE";
91
+ }
92
+ return null;
93
+ }
94
+ if (onchainStatus.type === base_1.SwapCommitStateType.COMMITED) {
95
+ if (state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT) {
96
+ await swap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED);
97
+ await this.saveSwapData(swap);
98
+ this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap committed (detected from processPastSwap), invoice: " + swap.pr);
99
+ }
100
+ return null;
101
+ }
102
+ if (onchainStatus.type === base_1.SwapCommitStateType.NOT_COMMITED || onchainStatus.type === base_1.SwapCommitStateType.EXPIRED) {
103
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT) {
104
+ const isAuthorizationExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
105
+ if (isAuthorizationExpired) {
106
+ this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap not committed before authorization expiry, cancelling the LN invoice, invoice: " + swap.pr);
107
+ await this.cancelSwapAndInvoice(swap);
108
+ return null;
109
+ }
110
+ }
111
+ else {
112
+ if (await swapContract.isExpired(signer.getAddress(), swap.data)) {
113
+ this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
114
+ return "REFUND";
115
+ }
116
+ }
117
+ }
118
+ if (onchainStatus.type === base_1.SwapCommitStateType.REFUNDABLE) {
119
+ this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
120
+ return "REFUND";
121
+ }
122
+ }
123
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED)
124
+ return "SETTLE";
125
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CANCELED)
126
+ await this.cancelSwapAndInvoice(swap);
127
+ }
128
+ async refundSwaps(refundSwaps) {
129
+ for (let refundSwap of refundSwaps) {
130
+ const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
131
+ const unlock = refundSwap.lock(swapContract.refundTimeout);
132
+ if (unlock == null)
133
+ continue;
134
+ this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
135
+ await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
136
+ this.swapLogger.info(refundSwap, "refundsSwaps(): swap refunded, invoice: " + refundSwap.pr);
137
+ await refundSwap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.REFUNDED);
138
+ unlock();
139
+ }
140
+ }
141
+ async settleInvoices(swaps) {
142
+ for (let swap of swaps) {
143
+ try {
144
+ await this.lightning.settleHodlInvoice(swap.secret);
145
+ if (swap.metadata != null)
146
+ swap.metadata.times.htlcSettled = Date.now();
147
+ await this.removeSwapData(swap, FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.SETTLED);
148
+ this.swapLogger.info(swap, "settleInvoices(): invoice settled, secret: " + swap.secret);
149
+ }
150
+ catch (e) {
151
+ this.swapLogger.error(swap, "settleInvoices(): cannot settle invoice", e);
152
+ }
153
+ }
154
+ }
155
+ /**
156
+ * Checks past swaps, refunds and deletes ones that are already expired.
157
+ */
158
+ async processPastSwaps() {
159
+ const settleInvoices = [];
160
+ const refundSwaps = [];
161
+ const queriedData = await this.storageManager.query([
162
+ {
163
+ key: "state",
164
+ value: [
165
+ FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED,
166
+ FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED,
167
+ FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT,
168
+ FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED,
169
+ FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED,
170
+ FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CANCELED,
171
+ ]
172
+ }
173
+ ]);
174
+ for (let { obj: swap } of queriedData) {
175
+ switch (await this.processPastSwap(swap)) {
176
+ case "SETTLE":
177
+ settleInvoices.push(swap);
178
+ break;
179
+ case "REFUND":
180
+ refundSwaps.push(swap);
181
+ break;
182
+ }
183
+ }
184
+ await this.refundSwaps(refundSwaps);
185
+ await this.settleInvoices(settleInvoices);
186
+ }
187
+ async processInitializeEvent(chainIdentifier, savedSwap, event) {
188
+ this.swapLogger.info(savedSwap, "SC: InitializeEvent: HTLC initialized by the client, invoice: " + savedSwap.pr);
189
+ if (savedSwap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT) {
190
+ await savedSwap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED);
191
+ await this.saveSwapData(savedSwap);
192
+ }
193
+ }
194
+ async processClaimEvent(chainIdentifier, savedSwap, event) {
195
+ //Claim
196
+ //This is the important part, we need to catch the claim TX, else we may lose money
197
+ const secret = Buffer.from(event.result, "hex");
198
+ const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
199
+ const secretHex = secret.toString("hex");
200
+ const paymentHashHex = paymentHash.toString("hex");
201
+ if (savedSwap.lnPaymentHash !== paymentHashHex)
202
+ return;
203
+ this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap HTLC successfully claimed by the client, invoice: " + savedSwap.pr);
204
+ try {
205
+ await this.lightning.settleHodlInvoice(secretHex);
206
+ this.swapLogger.info(savedSwap, "SC: ClaimEvent: invoice settled, secret: " + secretHex);
207
+ savedSwap.secret = secretHex;
208
+ if (savedSwap.metadata != null)
209
+ savedSwap.metadata.times.htlcSettled = Date.now();
210
+ await this.removeSwapData(savedSwap, FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.SETTLED);
211
+ }
212
+ catch (e) {
213
+ this.swapLogger.error(savedSwap, "SC: ClaimEvent: cannot settle invoice", e);
214
+ savedSwap.secret = secretHex;
215
+ await savedSwap.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CLAIMED);
216
+ await this.saveSwapData(savedSwap);
217
+ }
218
+ }
219
+ async processRefundEvent(chainIdentifier, savedSwap, event) {
220
+ this.swapLogger.info(savedSwap, "SC: RefundEvent: swap refunded to us, invoice: " + savedSwap.pr);
221
+ //We don't cancel the incoming invoice, to make the offender pay for this with locked liquidity
222
+ // await this.lightning.cancelHodlInvoice(savedSwap.lnPaymentHash);
223
+ await this.removeSwapData(savedSwap, FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.REFUNDED);
224
+ }
225
+ /**
226
+ * Subscribe to a lightning network invoice
227
+ *
228
+ * @param swap
229
+ */
230
+ subscribeToInvoice(swap) {
231
+ const paymentHash = swap.lnPaymentHash;
232
+ if (this.activeSubscriptions.has(paymentHash))
233
+ return false;
234
+ this.lightning.waitForInvoice(paymentHash).then(result => {
235
+ this.swapLogger.info(swap, "subscribeToInvoice(): result callback, outcome: " + result.status + " invoice: " + swap.pr);
236
+ if (result.status === "held")
237
+ this.htlcReceived(swap, result).catch(e => this.swapLogger.error(swap, "subscribeToInvoice(): HTLC received result", e));
238
+ this.activeSubscriptions.delete(paymentHash);
239
+ });
240
+ this.swapLogger.info(swap, "subscribeToInvoice(): subscribe to invoice: " + swap.pr);
241
+ this.activeSubscriptions.add(paymentHash);
242
+ return true;
243
+ }
244
+ /**
245
+ * Called when lightning HTLC is received, also signs an init transaction on the smart chain side, expiry of the
246
+ * smart chain authorization starts ticking as soon as this HTLC is received
247
+ *
248
+ * @param invoiceData
249
+ * @param invoice
250
+ */
251
+ async htlcReceived(invoiceData, invoice) {
252
+ if (invoiceData.state !== FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED)
253
+ return;
254
+ this.swapLogger.debug(invoiceData, "htlcReceived(): invoice: ", invoice);
255
+ if (invoiceData.metadata != null)
256
+ invoiceData.metadata.times.htlcReceived = Date.now();
257
+ const useToken = invoiceData.token;
258
+ const gasToken = invoiceData.gasToken;
259
+ let expiryTimeout;
260
+ try {
261
+ //Check if HTLC expiry is long enough
262
+ expiryTimeout = await this.checkHtlcExpiry(invoice);
263
+ if (invoiceData.metadata != null)
264
+ invoiceData.metadata.times.htlcTimeoutCalculated = Date.now();
265
+ }
266
+ catch (e) {
267
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED)
268
+ await this.cancelSwapAndInvoice(invoiceData);
269
+ throw e;
270
+ }
271
+ const { swapContract, signer } = this.getChain(invoiceData.chainIdentifier);
272
+ //Create real swap data
273
+ const swapData = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, signer.getAddress(), invoiceData.claimer, useToken, invoiceData.amountToken, invoiceData.claimHash, 0n, BigInt(Math.floor(Date.now() / 1000)) + expiryTimeout, false, true, invoiceData.amountGasToken + invoiceData.claimerBounty, invoiceData.claimerBounty, invoiceData.gasToken);
274
+ if (invoiceData.metadata != null)
275
+ invoiceData.metadata.times.htlcSwapCreated = Date.now();
276
+ //Important to prevent race condition and issuing 2 signed init messages at the same time
277
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED) {
278
+ invoiceData.data = swapData;
279
+ invoiceData.signature = null;
280
+ invoiceData.timeout = (BigInt(Math.floor(Date.now() / 1000)) + 120n).toString(10);
281
+ //Setting the state variable is done outside the promise, so is done synchronously
282
+ await invoiceData.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED);
283
+ await this.saveSwapData(invoiceData);
284
+ await this.offerHtlc(invoiceData);
285
+ }
286
+ }
287
+ async offerHtlc(invoiceData) {
288
+ if (invoiceData.state !== FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED)
289
+ return;
290
+ this.swapLogger.debug(invoiceData, "offerHtlc(): invoice: ", invoiceData.pr);
291
+ if (invoiceData.metadata != null)
292
+ invoiceData.metadata.times.offerHtlc = Date.now();
293
+ const useToken = invoiceData.token;
294
+ const gasToken = invoiceData.gasToken;
295
+ const { swapContract, signer, chainInterface } = this.getChain(invoiceData.chainIdentifier);
296
+ //Create abort controller for parallel fetches
297
+ const abortController = new AbortController();
298
+ //Pre-fetch data
299
+ const balancePrefetch = this.getBalancePrefetch(invoiceData.chainIdentifier, useToken, abortController);
300
+ const gasTokenBalancePrefetch = invoiceData.getTotalOutputGasAmount() === 0n || useToken === gasToken ?
301
+ null : this.getBalancePrefetch(invoiceData.chainIdentifier, gasToken, abortController);
302
+ if (await swapContract.getInitAuthorizationExpiry(invoiceData.data, invoiceData) < Date.now()) {
303
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
304
+ await this.cancelSwapAndInvoice(invoiceData);
305
+ }
306
+ return false;
307
+ }
308
+ try {
309
+ //Check if we have enough liquidity to proceed
310
+ if (useToken === gasToken) {
311
+ await this.checkBalance(invoiceData.getTotalOutputAmount() + invoiceData.getTotalOutputGasAmount(), balancePrefetch, abortController.signal);
312
+ }
313
+ else {
314
+ await this.checkBalance(invoiceData.getTotalOutputAmount(), balancePrefetch, abortController.signal);
315
+ await this.checkBalance(invoiceData.getTotalOutputGasAmount(), gasTokenBalancePrefetch, abortController.signal);
316
+ }
317
+ if (invoiceData.metadata != null)
318
+ invoiceData.metadata.times.offerHtlcChecked = Date.now();
319
+ }
320
+ catch (e) {
321
+ if (!abortController.signal.aborted) {
322
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED)
323
+ await this.cancelSwapAndInvoice(invoiceData);
324
+ }
325
+ throw e;
326
+ }
327
+ const txWithdraw = await swapContract.txsWithdraw(signer.getAddress(), gasToken, invoiceData.data.getTotalDeposit());
328
+ const txInit = await swapContract.txsInit(signer.getAddress(), invoiceData.data, {
329
+ prefix: invoiceData.prefix,
330
+ timeout: invoiceData.timeout,
331
+ signature: invoiceData.signature
332
+ }, true);
333
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
334
+ //Setting the state variable is done outside the promise, so is done synchronously
335
+ await invoiceData.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT);
336
+ await this.saveSwapData(invoiceData);
337
+ await chainInterface.sendAndConfirm(signer, [...txWithdraw, ...txInit], true, undefined, true);
338
+ }
339
+ return true;
340
+ }
341
+ /**
342
+ * Checks invoice description hash
343
+ *
344
+ * @param descriptionHash
345
+ * @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
346
+ */
347
+ checkDescriptionHash(descriptionHash) {
348
+ if (descriptionHash != null) {
349
+ if (typeof (descriptionHash) !== "string" || !Utils_1.HEX_REGEX.test(descriptionHash) || descriptionHash.length !== 64) {
350
+ throw {
351
+ code: 20100,
352
+ msg: "Invalid request body (descriptionHash)"
353
+ };
354
+ }
355
+ }
356
+ }
357
+ /**
358
+ * Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
359
+ *
360
+ * @param responseStream
361
+ */
362
+ sendPublicKeyAsync(responseStream) {
363
+ this.lightning.getIdentityPublicKey().then(publicKey => responseStream.writeParams({
364
+ lnPublicKey: publicKey
365
+ })).catch(e => {
366
+ this.logger.error("sendPublicKeyAsync(): error", e);
367
+ });
368
+ }
369
+ /**
370
+ * Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
371
+ * received (MPP) it returns the lowest of the timeouts
372
+ *
373
+ * @param invoice
374
+ */
375
+ getInvoicePaymentsTimeout(invoice) {
376
+ let timeout = null;
377
+ invoice.payments.forEach((curr) => {
378
+ if (timeout == null || timeout > curr.timeout)
379
+ timeout = curr.timeout;
380
+ });
381
+ return timeout;
382
+ }
383
+ /**
384
+ * Checks if the received HTLC's CLTV timeout is large enough to still process the swap
385
+ *
386
+ * @param invoice
387
+ * @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
388
+ * @returns expiry timeout in seconds
389
+ */
390
+ async checkHtlcExpiry(invoice) {
391
+ const timeout = this.getInvoicePaymentsTimeout(invoice);
392
+ const current_block_height = await this.lightning.getBlockheight();
393
+ const blockDelta = BigInt(timeout - current_block_height);
394
+ const htlcExpiresTooSoon = blockDelta < this.config.minCltv;
395
+ if (htlcExpiresTooSoon) {
396
+ throw {
397
+ code: 20002,
398
+ msg: "Not enough time to reliably process the swap",
399
+ data: {
400
+ requiredDelta: this.config.minCltv.toString(10),
401
+ actualDelta: blockDelta.toString(10)
402
+ }
403
+ };
404
+ }
405
+ return (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
406
+ }
407
+ /**
408
+ * Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
409
+ *
410
+ * @param invoiceData
411
+ */
412
+ async cancelSwapAndInvoice(invoiceData) {
413
+ await invoiceData.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CANCELED);
414
+ await this.lightning.cancelHodlInvoice(invoiceData.lnPaymentHash);
415
+ await this.removeSwapData(invoiceData);
416
+ this.swapLogger.info(invoiceData, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", invoiceData.pr);
417
+ }
418
+ ;
419
+ /**
420
+ *
421
+ * Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
422
+ *
423
+ * @param paymentHash
424
+ * @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
425
+ * @returns the fetched lightning invoice
426
+ */
427
+ async checkInvoiceStatus(paymentHash) {
428
+ const invoice = await this.lightning.getInvoice(paymentHash);
429
+ if (invoice == null)
430
+ throw {
431
+ _httpStatus: 200,
432
+ code: 10001,
433
+ msg: "Invoice expired/canceled"
434
+ };
435
+ const arr = invoice.description.split("-");
436
+ let chainIdentifier;
437
+ let address;
438
+ if (arr.length > 1) {
439
+ chainIdentifier = arr[0];
440
+ address = arr[1];
441
+ }
442
+ else {
443
+ chainIdentifier = this.chains.default;
444
+ address = invoice.description;
445
+ }
446
+ const { chainInterface } = this.getChain(chainIdentifier);
447
+ if (!chainInterface.isValidAddress(address))
448
+ throw {
449
+ _httpStatus: 200,
450
+ code: 10001,
451
+ msg: "Invoice expired/canceled"
452
+ };
453
+ switch (invoice.status) {
454
+ case "canceled":
455
+ throw {
456
+ _httpStatus: 200,
457
+ code: 10001,
458
+ msg: "Invoice expired/canceled"
459
+ };
460
+ case "confirmed":
461
+ throw {
462
+ _httpStatus: 200,
463
+ code: 10002,
464
+ msg: "Invoice already paid"
465
+ };
466
+ case "unpaid":
467
+ throw {
468
+ _httpStatus: 200,
469
+ code: 10003,
470
+ msg: "Invoice yet unpaid"
471
+ };
472
+ default:
473
+ return invoice;
474
+ }
475
+ }
476
+ startRestServer(restServer) {
477
+ restServer.use(this.path + "/createInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
478
+ restServer.post(this.path + "/createInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
479
+ const metadata = { request: {}, times: {} };
480
+ const chainIdentifier = req.query.chain ?? this.chains.default;
481
+ const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
482
+ if (!swapContract.supportsInitWithoutClaimer)
483
+ throw {
484
+ code: 20299,
485
+ msg: "Not supported for " + chainIdentifier
486
+ };
487
+ metadata.times.requestReceived = Date.now();
488
+ /**
489
+ * address: string smart chain address of the recipient
490
+ * paymentHash: string payment hash of the to-be-created invoice
491
+ * amount: string amount (in sats) of the invoice
492
+ * token: string Desired token to swap
493
+ * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
494
+ * descriptionHash: string Description hash of the invoice
495
+ * gasAmount: string Desired amount in gas token to also get
496
+ * gasToken: string
497
+ * claimerBounty: string Desired amount to be left out as a claimer bounty
498
+ */
499
+ const parsedBody = await req.paramReader.getParams({
500
+ address: (val) => val != null &&
501
+ typeof (val) === "string" &&
502
+ chainInterface.isValidAddress(val) ? val : null,
503
+ paymentHash: (val) => val != null &&
504
+ typeof (val) === "string" &&
505
+ val.length === 64 &&
506
+ Utils_1.HEX_REGEX.test(val) ? val : null,
507
+ amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
508
+ token: (val) => val != null &&
509
+ typeof (val) === "string" &&
510
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
511
+ descriptionHash: SchemaVerifier_1.FieldTypeEnum.StringOptional,
512
+ exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
513
+ gasToken: (val) => val != null &&
514
+ typeof (val) === "string" &&
515
+ chainInterface.isValidToken(val) ? val : null,
516
+ gasAmount: SchemaVerifier_1.FieldTypeEnum.BigInt,
517
+ claimerBounty: SchemaVerifier_1.FieldTypeEnum.BigInt
518
+ });
519
+ if (parsedBody == null)
520
+ throw {
521
+ code: 20100,
522
+ msg: "Invalid request body"
523
+ };
524
+ if (parsedBody.gasToken !== chainInterface.getNativeCurrencyAddress())
525
+ throw {
526
+ code: 20290,
527
+ msg: "Unsupported gas token"
528
+ };
529
+ if (parsedBody.gasAmount < 0)
530
+ throw {
531
+ code: 20291,
532
+ msg: "Invalid gas amount, negative"
533
+ };
534
+ if (parsedBody.claimerBounty < 0)
535
+ throw {
536
+ code: 20292,
537
+ msg: "Invalid claimer bounty, negative"
538
+ };
539
+ metadata.request = parsedBody;
540
+ const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
541
+ const gasTokenAmount = {
542
+ input: false,
543
+ amount: parsedBody.gasAmount + parsedBody.claimerBounty,
544
+ token: parsedBody.gasToken
545
+ };
546
+ const request = {
547
+ chainIdentifier,
548
+ raw: req,
549
+ parsed: parsedBody,
550
+ metadata
551
+ };
552
+ const useToken = parsedBody.token;
553
+ const gasToken = parsedBody.gasToken;
554
+ //Check request params
555
+ this.checkDescriptionHash(parsedBody.descriptionHash);
556
+ const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
557
+ metadata.times.requestChecked = Date.now();
558
+ //Create abortController for parallel prefetches
559
+ const responseStream = res.responseStream;
560
+ const abortController = (0, Utils_1.getAbortController)(responseStream);
561
+ //Pre-fetch data
562
+ const { pricePrefetchPromise, gasTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, gasToken, abortController);
563
+ const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
564
+ const gasTokenBalancePrefetch = gasTokenAmount.amount === 0n || useToken === gasToken ?
565
+ null : this.getBalancePrefetch(chainIdentifier, gasToken, abortController);
566
+ const channelsPrefetch = this.LightningAssertions.getChannelsPrefetch(abortController);
567
+ //Asynchronously send the node's public key to the client
568
+ this.sendPublicKeyAsync(responseStream);
569
+ //Check valid amount specified (min/max)
570
+ let { amountBD, swapFee, swapFeeInToken, totalInToken, amountBDgas, gasSwapFee, gasSwapFeeInToken, totalInGasToken } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal, { ...gasTokenAmount, pricePrefetch: gasTokenPricePrefetchPromise });
571
+ metadata.times.priceCalculated = Date.now();
572
+ const totalBtcInput = amountBD + amountBDgas;
573
+ //Check if we have enough funds to honor the request
574
+ if (useToken === gasToken) {
575
+ await this.checkBalance(totalInToken + totalInGasToken, balancePrefetch, abortController.signal);
576
+ }
577
+ else {
578
+ await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
579
+ await this.checkBalance(totalInGasToken, gasTokenBalancePrefetch, abortController.signal);
580
+ }
581
+ await this.LightningAssertions.checkInboundLiquidity(totalBtcInput, channelsPrefetch, abortController.signal);
582
+ metadata.times.balanceChecked = Date.now();
583
+ //Create swap
584
+ const hodlInvoiceObj = {
585
+ description: chainIdentifier + "-" + parsedBody.address,
586
+ cltvDelta: Number(this.config.minCltv) + 5,
587
+ expiresAt: Date.now() + (this.config.invoiceTimeoutSeconds * 1000),
588
+ id: parsedBody.paymentHash,
589
+ mtokens: totalBtcInput * 1000n,
590
+ descriptionHash: parsedBody.descriptionHash
591
+ };
592
+ metadata.invoiceRequest = hodlInvoiceObj;
593
+ const hodlInvoice = await this.lightning.createHodlInvoice(hodlInvoiceObj);
594
+ abortController.signal.throwIfAborted();
595
+ metadata.times.invoiceCreated = Date.now();
596
+ metadata.invoiceResponse = { ...hodlInvoice };
597
+ totalInGasToken -= parsedBody.claimerBounty;
598
+ const createdSwap = new FromBtcLnAutoSwap_1.FromBtcLnAutoSwap(chainIdentifier, hodlInvoice.request, parsedBody.paymentHash, swapContract.getHashForHtlc(Buffer.from(parsedBody.paymentHash, "hex")).toString("hex"), hodlInvoice.mtokens, parsedBody.address, useToken, gasToken, totalInToken, totalInGasToken, swapFee, swapFeeInToken, gasSwapFee, gasSwapFeeInToken, parsedBody.claimerBounty);
599
+ metadata.times.swapCreated = Date.now();
600
+ createdSwap.metadata = metadata;
601
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
602
+ await this.saveSwapData(createdSwap);
603
+ this.swapLogger.info(createdSwap, "REST: /createInvoice: Created swap invoice: " + hodlInvoice.request + " amount: " + totalBtcInput.toString(10));
604
+ this.subscribeToInvoice(createdSwap);
605
+ await responseStream.writeParamsAndEnd({
606
+ code: 20000,
607
+ msg: "Success",
608
+ data: {
609
+ intermediaryKey: signer.getAddress(),
610
+ pr: hodlInvoice.request,
611
+ btcAmountSwap: amountBD.toString(10),
612
+ btcAmountGas: amountBDgas.toString(10),
613
+ total: totalInToken.toString(10),
614
+ totalGas: totalInGasToken.toString(10),
615
+ totalFeeBtc: (swapFee + gasSwapFee).toString(10),
616
+ swapFeeBtc: swapFee.toString(10),
617
+ swapFee: swapFeeInToken.toString(10),
618
+ gasSwapFeeBtc: gasSwapFee.toString(10),
619
+ gasSwapFee: gasSwapFeeInToken.toString(10),
620
+ claimerBounty: parsedBody.claimerBounty.toString(10)
621
+ }
622
+ });
623
+ }));
624
+ const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
625
+ /**
626
+ * paymentHash: string payment hash of the invoice
627
+ */
628
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
629
+ paymentHash: (val) => val != null &&
630
+ typeof (val) === "string" &&
631
+ val.length === 64 &&
632
+ Utils_1.HEX_REGEX.test(val) ? val : null,
633
+ });
634
+ await this.checkInvoiceStatus(parsedBody.paymentHash);
635
+ const swap = await this.storageManager.getData(parsedBody.paymentHash, null);
636
+ if (swap == null)
637
+ throw {
638
+ _httpStatus: 200,
639
+ code: 10001,
640
+ msg: "Invoice expired/canceled"
641
+ };
642
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED ||
643
+ swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT ||
644
+ swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED) {
645
+ res.status(200).json({
646
+ code: 10000,
647
+ msg: "Success",
648
+ data: {
649
+ data: swap.data.serialize()
650
+ }
651
+ });
652
+ }
653
+ else {
654
+ res.status(200).json({
655
+ code: 10003,
656
+ msg: "Invoice yet unpaid"
657
+ });
658
+ }
659
+ });
660
+ restServer.post(this.path + "/getInvoiceStatus", getInvoiceStatus);
661
+ restServer.get(this.path + "/getInvoiceStatus", getInvoiceStatus);
662
+ this.logger.info("started at path: ", this.path);
663
+ }
664
+ async init() {
665
+ await this.loadData(FromBtcLnAutoSwap_1.FromBtcLnAutoSwap);
666
+ this.subscribeToEvents();
667
+ await PluginManager_1.PluginManager.serviceInitialize(this);
668
+ }
669
+ getInfoData() {
670
+ const mappedDict = {};
671
+ for (let chainId in this.config.gasTokenMax) {
672
+ mappedDict[chainId] = {
673
+ gasToken: this.getChain(chainId).chainInterface.getNativeCurrencyAddress(),
674
+ max: this.config.gasTokenMax[chainId].toString(10)
675
+ };
676
+ }
677
+ return {
678
+ minCltv: Number(this.config.minCltv),
679
+ invoiceTimeoutSeconds: this.config.invoiceTimeoutSeconds,
680
+ gasTokens: mappedDict
681
+ };
682
+ }
683
+ }
684
+ exports.FromBtcLnAuto = FromBtcLnAuto;