@atomiqlabs/lp-lib 17.5.0 → 17.5.1

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