@atomiqlabs/lp-lib 17.5.1 → 17.5.2

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 -730
  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 -710
  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 -892
  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 -897
  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,730 +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
- 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;
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;