@atomiqlabs/lp-lib 15.0.14 → 16.0.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 (169) hide show
  1. package/LICENSE +201 -201
  2. package/dist/fees/IBtcFeeEstimator.d.ts +3 -3
  3. package/dist/fees/IBtcFeeEstimator.js +2 -2
  4. package/dist/index.d.ts +42 -40
  5. package/dist/index.js +58 -56
  6. package/dist/info/InfoHandler.d.ts +17 -17
  7. package/dist/info/InfoHandler.js +58 -58
  8. package/dist/plugins/IPlugin.d.ts +144 -144
  9. package/dist/plugins/IPlugin.js +34 -34
  10. package/dist/plugins/PluginManager.d.ts +113 -113
  11. package/dist/plugins/PluginManager.js +274 -274
  12. package/dist/prices/BinanceSwapPrice.d.ts +26 -26
  13. package/dist/prices/BinanceSwapPrice.js +92 -92
  14. package/dist/prices/CoinGeckoSwapPrice.d.ts +30 -30
  15. package/dist/prices/CoinGeckoSwapPrice.js +64 -64
  16. package/dist/prices/ISwapPrice.d.ts +43 -43
  17. package/dist/prices/ISwapPrice.js +55 -55
  18. package/dist/prices/OKXSwapPrice.d.ts +26 -26
  19. package/dist/prices/OKXSwapPrice.js +92 -92
  20. package/dist/storage/IIntermediaryStorage.d.ts +18 -18
  21. package/dist/storage/IIntermediaryStorage.js +2 -2
  22. package/dist/storagemanager/IntermediaryStorageManager.d.ts +19 -18
  23. package/dist/storagemanager/IntermediaryStorageManager.js +111 -104
  24. package/dist/storagemanager/StorageManager.d.ts +13 -12
  25. package/dist/storagemanager/StorageManager.js +64 -57
  26. package/dist/swaps/SwapHandler.d.ts +143 -153
  27. package/dist/swaps/SwapHandler.js +151 -157
  28. package/dist/swaps/SwapHandlerSwap.d.ts +79 -79
  29. package/dist/swaps/SwapHandlerSwap.js +78 -78
  30. package/dist/swaps/assertions/AmountAssertions.d.ts +28 -28
  31. package/dist/swaps/assertions/AmountAssertions.js +74 -74
  32. package/dist/swaps/assertions/FromBtcAmountAssertions.d.ts +76 -76
  33. package/dist/swaps/assertions/FromBtcAmountAssertions.js +180 -172
  34. package/dist/swaps/assertions/LightningAssertions.d.ts +44 -44
  35. package/dist/swaps/assertions/LightningAssertions.js +86 -86
  36. package/dist/swaps/assertions/ToBtcAmountAssertions.d.ts +53 -53
  37. package/dist/swaps/assertions/ToBtcAmountAssertions.js +150 -150
  38. package/dist/swaps/escrow/EscrowHandler.d.ts +50 -51
  39. package/dist/swaps/escrow/EscrowHandler.js +149 -158
  40. package/dist/swaps/escrow/EscrowHandlerSwap.d.ts +35 -35
  41. package/dist/swaps/escrow/EscrowHandlerSwap.js +69 -69
  42. package/dist/swaps/escrow/FromBtcBaseSwap.d.ts +14 -14
  43. package/dist/swaps/escrow/FromBtcBaseSwap.js +32 -32
  44. package/dist/swaps/escrow/FromBtcBaseSwapHandler.d.ts +102 -101
  45. package/dist/swaps/escrow/FromBtcBaseSwapHandler.js +210 -207
  46. package/dist/swaps/escrow/ToBtcBaseSwap.d.ts +36 -36
  47. package/dist/swaps/escrow/ToBtcBaseSwap.js +67 -67
  48. package/dist/swaps/escrow/ToBtcBaseSwapHandler.d.ts +53 -53
  49. package/dist/swaps/escrow/ToBtcBaseSwapHandler.js +81 -81
  50. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.d.ts +83 -83
  51. package/dist/swaps/escrow/frombtc_abstract/FromBtcAbs.js +318 -318
  52. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.d.ts +21 -21
  53. package/dist/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.js +50 -50
  54. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.d.ts +107 -107
  55. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.js +673 -673
  56. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +33 -32
  57. package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +91 -88
  58. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.d.ts +118 -0
  59. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.js +724 -0
  60. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.d.ts +55 -0
  61. package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.js +120 -0
  62. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.d.ts +169 -171
  63. package/dist/swaps/escrow/tobtc_abstract/ToBtcAbs.js +735 -718
  64. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.d.ts +28 -28
  65. package/dist/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.js +64 -64
  66. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.d.ts +177 -177
  67. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.js +865 -863
  68. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.d.ts +24 -24
  69. package/dist/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.js +58 -58
  70. package/dist/swaps/spv_vault_swap/SpvVault.d.ts +44 -45
  71. package/dist/swaps/spv_vault_swap/SpvVault.js +145 -145
  72. package/dist/swaps/spv_vault_swap/SpvVaultSwap.d.ts +68 -68
  73. package/dist/swaps/spv_vault_swap/SpvVaultSwap.js +158 -158
  74. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.d.ts +68 -68
  75. package/dist/swaps/spv_vault_swap/SpvVaultSwapHandler.js +530 -528
  76. package/dist/swaps/spv_vault_swap/SpvVaults.d.ts +63 -68
  77. package/dist/swaps/spv_vault_swap/SpvVaults.js +488 -454
  78. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.d.ts +51 -51
  79. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrusted.js +650 -650
  80. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.d.ts +52 -52
  81. package/dist/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.js +118 -118
  82. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.d.ts +76 -76
  83. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.js +492 -493
  84. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.d.ts +34 -34
  85. package/dist/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.js +81 -81
  86. package/dist/utils/BitcoinUtils.d.ts +4 -4
  87. package/dist/utils/BitcoinUtils.js +61 -61
  88. package/dist/utils/Utils.d.ts +29 -29
  89. package/dist/utils/Utils.js +89 -88
  90. package/dist/utils/paramcoders/IParamReader.d.ts +5 -5
  91. package/dist/utils/paramcoders/IParamReader.js +2 -2
  92. package/dist/utils/paramcoders/IParamWriter.d.ts +4 -4
  93. package/dist/utils/paramcoders/IParamWriter.js +2 -2
  94. package/dist/utils/paramcoders/LegacyParamEncoder.d.ts +10 -10
  95. package/dist/utils/paramcoders/LegacyParamEncoder.js +22 -22
  96. package/dist/utils/paramcoders/ParamDecoder.d.ts +25 -25
  97. package/dist/utils/paramcoders/ParamDecoder.js +222 -222
  98. package/dist/utils/paramcoders/ParamEncoder.d.ts +9 -9
  99. package/dist/utils/paramcoders/ParamEncoder.js +22 -22
  100. package/dist/utils/paramcoders/SchemaVerifier.d.ts +21 -21
  101. package/dist/utils/paramcoders/SchemaVerifier.js +84 -84
  102. package/dist/utils/paramcoders/server/ServerParamDecoder.d.ts +8 -8
  103. package/dist/utils/paramcoders/server/ServerParamDecoder.js +107 -105
  104. package/dist/utils/paramcoders/server/ServerParamEncoder.d.ts +11 -11
  105. package/dist/utils/paramcoders/server/ServerParamEncoder.js +65 -65
  106. package/dist/wallets/IBitcoinWallet.d.ts +74 -67
  107. package/dist/wallets/IBitcoinWallet.js +2 -2
  108. package/dist/wallets/ILightningWallet.d.ts +117 -117
  109. package/dist/wallets/ILightningWallet.js +37 -37
  110. package/dist/wallets/ISpvVaultSigner.d.ts +7 -7
  111. package/dist/wallets/ISpvVaultSigner.js +2 -2
  112. package/package.json +36 -36
  113. package/src/fees/IBtcFeeEstimator.ts +6 -6
  114. package/src/index.ts +53 -51
  115. package/src/info/InfoHandler.ts +100 -100
  116. package/src/plugins/IPlugin.ts +174 -174
  117. package/src/plugins/PluginManager.ts +354 -354
  118. package/src/prices/BinanceSwapPrice.ts +113 -113
  119. package/src/prices/CoinGeckoSwapPrice.ts +87 -87
  120. package/src/prices/ISwapPrice.ts +88 -88
  121. package/src/prices/OKXSwapPrice.ts +113 -113
  122. package/src/storage/IIntermediaryStorage.ts +19 -19
  123. package/src/storagemanager/IntermediaryStorageManager.ts +118 -109
  124. package/src/storagemanager/StorageManager.ts +78 -68
  125. package/src/swaps/SwapHandler.ts +252 -272
  126. package/src/swaps/SwapHandlerSwap.ts +141 -141
  127. package/src/swaps/assertions/AmountAssertions.ts +77 -77
  128. package/src/swaps/assertions/FromBtcAmountAssertions.ts +246 -238
  129. package/src/swaps/assertions/LightningAssertions.ts +103 -103
  130. package/src/swaps/assertions/ToBtcAmountAssertions.ts +203 -203
  131. package/src/swaps/escrow/EscrowHandler.ts +171 -179
  132. package/src/swaps/escrow/EscrowHandlerSwap.ts +86 -86
  133. package/src/swaps/escrow/FromBtcBaseSwap.ts +38 -38
  134. package/src/swaps/escrow/FromBtcBaseSwapHandler.ts +286 -283
  135. package/src/swaps/escrow/ToBtcBaseSwap.ts +85 -85
  136. package/src/swaps/escrow/ToBtcBaseSwapHandler.ts +129 -129
  137. package/src/swaps/escrow/frombtc_abstract/FromBtcAbs.ts +452 -452
  138. package/src/swaps/escrow/frombtc_abstract/FromBtcSwapAbs.ts +61 -61
  139. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnAbs.ts +855 -855
  140. package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +141 -137
  141. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAuto.ts +888 -0
  142. package/src/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoSwap.ts +196 -0
  143. package/src/swaps/escrow/tobtc_abstract/ToBtcAbs.ts +909 -890
  144. package/src/swaps/escrow/tobtc_abstract/ToBtcSwapAbs.ts +108 -108
  145. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnAbs.ts +1116 -1112
  146. package/src/swaps/escrow/tobtcln_abstract/ToBtcLnSwapAbs.ts +80 -80
  147. package/src/swaps/spv_vault_swap/SpvVault.ts +178 -178
  148. package/src/swaps/spv_vault_swap/SpvVaultSwap.ts +228 -228
  149. package/src/swaps/spv_vault_swap/SpvVaultSwapHandler.ts +673 -671
  150. package/src/swaps/spv_vault_swap/SpvVaults.ts +565 -526
  151. package/src/swaps/trusted/frombtc_trusted/FromBtcTrusted.ts +747 -747
  152. package/src/swaps/trusted/frombtc_trusted/FromBtcTrustedSwap.ts +185 -185
  153. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrusted.ts +589 -591
  154. package/src/swaps/trusted/frombtcln_trusted/FromBtcLnTrustedSwap.ts +121 -121
  155. package/src/utils/BitcoinUtils.ts +59 -59
  156. package/src/utils/Utils.ts +104 -102
  157. package/src/utils/paramcoders/IParamReader.ts +7 -7
  158. package/src/utils/paramcoders/IParamWriter.ts +8 -8
  159. package/src/utils/paramcoders/LegacyParamEncoder.ts +27 -27
  160. package/src/utils/paramcoders/ParamDecoder.ts +218 -218
  161. package/src/utils/paramcoders/ParamEncoder.ts +29 -29
  162. package/src/utils/paramcoders/SchemaVerifier.ts +96 -96
  163. package/src/utils/paramcoders/server/ServerParamDecoder.ts +118 -115
  164. package/src/utils/paramcoders/server/ServerParamEncoder.ts +75 -75
  165. package/src/wallets/IBitcoinWallet.ts +76 -68
  166. package/src/wallets/ILightningWallet.ts +178 -178
  167. package/src/wallets/ISpvVaultSigner.ts +10 -10
  168. package/dist/wallets/ISpvVaultWallet.d.ts +0 -42
  169. package/dist/wallets/ISpvVaultWallet.js +0 -2
@@ -0,0 +1,724 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FromBtcLnAuto = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const FromBtcLnAutoSwap_1 = require("./FromBtcLnAutoSwap");
6
+ const SwapHandler_1 = require("../../SwapHandler");
7
+ const base_1 = require("@atomiqlabs/base");
8
+ const Utils_1 = require("../../../utils/Utils");
9
+ const PluginManager_1 = require("../../../plugins/PluginManager");
10
+ const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
11
+ const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
12
+ const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
13
+ const LightningAssertions_1 = require("../../assertions/LightningAssertions");
14
+ /**
15
+ * Swap handler handling from BTCLN swaps using submarine swaps
16
+ */
17
+ class FromBtcLnAuto extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
18
+ constructor(storageDirectory, path, chains, lightning, swapPricing, config) {
19
+ super(storageDirectory, path, chains, swapPricing, config);
20
+ this.type = SwapHandler_1.SwapHandlerType.FROM_BTCLN_AUTO;
21
+ this.swapType = base_1.ChainSwapType.HTLC;
22
+ this.activeSubscriptions = new Set();
23
+ this.swapsWithInflighHtlcs = new Set();
24
+ this.config = config;
25
+ this.config.invoiceTimeoutSeconds = this.config.invoiceTimeoutSeconds || 90;
26
+ this.lightning = lightning;
27
+ this.LightningAssertions = new LightningAssertions_1.LightningAssertions(this.logger, lightning);
28
+ }
29
+ async processPastSwap(swap) {
30
+ const { swapContract, signer } = this.getChain(swap.chainIdentifier);
31
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CREATED) {
32
+ //Check if already paid
33
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
34
+ const invoice = await this.lightning.getInvoice(parsedPR.id);
35
+ const isBeingPaid = invoice.status === "held";
36
+ if (!isBeingPaid) {
37
+ //Not paid
38
+ const isInvoiceExpired = parsedPR.expiryEpochMillis < Date.now();
39
+ if (isInvoiceExpired) {
40
+ this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap LN invoice expired, cancelling, invoice: " + swap.pr);
41
+ await this.cancelSwapAndInvoice(swap);
42
+ return null;
43
+ }
44
+ this.subscribeToInvoice(swap);
45
+ return null;
46
+ }
47
+ //Adjust the state of the swap and expiry
48
+ try {
49
+ await this.htlcReceived(swap, invoice);
50
+ //Result is either FromBtcLnSwapState.RECEIVED or FromBtcLnSwapState.CANCELED
51
+ }
52
+ catch (e) {
53
+ this.swapLogger.error(swap, "processPastSwap(state=CREATED): htlcReceived error", e);
54
+ }
55
+ return null;
56
+ }
57
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
58
+ try {
59
+ await this.offerHtlc(swap);
60
+ }
61
+ catch (e) {
62
+ this.swapLogger.error(swap, "processPastSwap(state=RECEIVED): offerHtlc error", e);
63
+ }
64
+ return null;
65
+ }
66
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT || swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED) {
67
+ this.swapsWithInflighHtlcs.add(swap);
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.checkTooManyInflightHtlcs();
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
+ //Minimum reserve of native token to be kept in the wallet
306
+ const minNativeTokenReserve = this.config.minNativeBalances?.[invoiceData.chainIdentifier] ?? 0n;
307
+ //Pre-fetch data
308
+ const balancePrefetch = this.getBalancePrefetch(invoiceData.chainIdentifier, useToken, abortController);
309
+ const gasTokenBalancePrefetch = (invoiceData.getTotalOutputGasAmount() === 0n && minNativeTokenReserve === 0n) || useToken === gasToken ?
310
+ null : this.getBalancePrefetch(invoiceData.chainIdentifier, gasToken, abortController);
311
+ if (await swapContract.getInitAuthorizationExpiry(invoiceData.data, invoiceData) < Date.now()) {
312
+ if (invoiceData.metadata != null)
313
+ invoiceData.metadata.htlcOfferError = "Init authorization expired, before being sent!";
314
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
315
+ await this.cancelSwapAndInvoice(invoiceData);
316
+ }
317
+ return false;
318
+ }
319
+ try {
320
+ //Check if we have enough liquidity to proceed
321
+ if (useToken === gasToken) {
322
+ await this.checkBalance(invoiceData.getTotalOutputAmount() + invoiceData.getTotalOutputGasAmount() + minNativeTokenReserve, balancePrefetch, abortController.signal);
323
+ }
324
+ else {
325
+ await this.checkBalance(invoiceData.getTotalOutputAmount(), balancePrefetch, abortController.signal);
326
+ await this.checkBalance(invoiceData.getTotalOutputGasAmount() + minNativeTokenReserve, gasTokenBalancePrefetch, abortController.signal);
327
+ }
328
+ if (invoiceData.metadata != null)
329
+ invoiceData.metadata.times.offerHtlcChecked = Date.now();
330
+ }
331
+ catch (e) {
332
+ if (!abortController.signal.aborted) {
333
+ if ((0, Utils_1.isDefinedRuntimeError)(e) && invoiceData.metadata != null)
334
+ invoiceData.metadata.htlcOfferError = e;
335
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED)
336
+ await this.cancelSwapAndInvoice(invoiceData);
337
+ }
338
+ throw e;
339
+ }
340
+ const txWithdraw = await swapContract.txsWithdraw(signer.getAddress(), gasToken, invoiceData.data.getTotalDeposit());
341
+ const txInit = await swapContract.txsInit(signer.getAddress(), invoiceData.data, {
342
+ prefix: invoiceData.prefix,
343
+ timeout: invoiceData.timeout,
344
+ signature: invoiceData.signature
345
+ }, true);
346
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED) {
347
+ //Re-check the current HTLC count
348
+ try {
349
+ this.checkTooManyInflightHtlcs();
350
+ }
351
+ catch (e) {
352
+ if ((0, Utils_1.isDefinedRuntimeError)(e) && invoiceData.metadata != null)
353
+ invoiceData.metadata.htlcOfferError = e;
354
+ if (invoiceData.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED)
355
+ await this.cancelSwapAndInvoice(invoiceData);
356
+ throw e;
357
+ }
358
+ this.swapLogger.debug(invoiceData, `offerHtlc(): Sending HTLC offer, current in flight HTLCs: ${this.swapsWithInflighHtlcs.size}, invoice: `, invoiceData.pr);
359
+ this.swapsWithInflighHtlcs.add(invoiceData);
360
+ //Setting the state variable is done outside the promise, so is done synchronously
361
+ await invoiceData.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT);
362
+ await this.saveSwapData(invoiceData);
363
+ await chainInterface.sendAndConfirm(signer, [...txWithdraw, ...txInit], true, undefined, true);
364
+ }
365
+ return true;
366
+ }
367
+ /**
368
+ * Checks invoice description hash
369
+ *
370
+ * @param descriptionHash
371
+ * @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
372
+ */
373
+ checkDescriptionHash(descriptionHash) {
374
+ if (descriptionHash != null) {
375
+ if (typeof (descriptionHash) !== "string" || !Utils_1.HEX_REGEX.test(descriptionHash) || descriptionHash.length !== 64) {
376
+ throw {
377
+ code: 20100,
378
+ msg: "Invalid request body (descriptionHash)"
379
+ };
380
+ }
381
+ }
382
+ }
383
+ /**
384
+ * Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
385
+ *
386
+ * @param responseStream
387
+ */
388
+ sendPublicKeyAsync(responseStream) {
389
+ this.lightning.getIdentityPublicKey().then(publicKey => responseStream.writeParams({
390
+ lnPublicKey: publicKey
391
+ })).catch(e => {
392
+ this.logger.error("sendPublicKeyAsync(): error", e);
393
+ });
394
+ }
395
+ /**
396
+ * Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
397
+ * received (MPP) it returns the lowest of the timeouts
398
+ *
399
+ * @param invoice
400
+ */
401
+ getInvoicePaymentsTimeout(invoice) {
402
+ let timeout = null;
403
+ invoice.payments.forEach((curr) => {
404
+ if (timeout == null || timeout > curr.timeout)
405
+ timeout = curr.timeout;
406
+ });
407
+ return timeout;
408
+ }
409
+ /**
410
+ * Checks if the received HTLC's CLTV timeout is large enough to still process the swap
411
+ *
412
+ * @param invoice
413
+ * @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
414
+ * @returns expiry timeout in seconds
415
+ */
416
+ async checkHtlcExpiry(invoice) {
417
+ const timeout = this.getInvoicePaymentsTimeout(invoice);
418
+ const current_block_height = await this.lightning.getBlockheight();
419
+ const blockDelta = BigInt(timeout - current_block_height);
420
+ const htlcExpiresTooSoon = blockDelta < this.config.minCltv;
421
+ if (htlcExpiresTooSoon) {
422
+ throw {
423
+ code: 20002,
424
+ msg: "Not enough time to reliably process the swap",
425
+ data: {
426
+ requiredDelta: this.config.minCltv.toString(10),
427
+ actualDelta: blockDelta.toString(10)
428
+ }
429
+ };
430
+ }
431
+ return (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
432
+ }
433
+ /**
434
+ * Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
435
+ *
436
+ * @param invoiceData
437
+ */
438
+ async cancelSwapAndInvoice(invoiceData) {
439
+ await invoiceData.setState(FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.CANCELED);
440
+ await this.lightning.cancelHodlInvoice(invoiceData.lnPaymentHash);
441
+ await this.removeSwapData(invoiceData);
442
+ this.swapLogger.info(invoiceData, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", invoiceData.pr);
443
+ }
444
+ ;
445
+ /**
446
+ *
447
+ * Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
448
+ *
449
+ * @param paymentHash
450
+ * @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
451
+ * @returns the fetched lightning invoice
452
+ */
453
+ async checkInvoiceStatus(paymentHash) {
454
+ const invoice = await this.lightning.getInvoice(paymentHash);
455
+ if (invoice == null)
456
+ throw {
457
+ _httpStatus: 200,
458
+ code: 10001,
459
+ msg: "Invoice expired/canceled"
460
+ };
461
+ const arr = invoice.description.split("-");
462
+ if (arr.length < 2)
463
+ throw {
464
+ _httpStatus: 200,
465
+ code: 10001,
466
+ msg: "Invoice expired/canceled"
467
+ };
468
+ const chainIdentifier = arr[0];
469
+ const address = arr[1];
470
+ const { chainInterface } = this.getChain(chainIdentifier);
471
+ if (!chainInterface.isValidAddress(address, true))
472
+ throw {
473
+ _httpStatus: 200,
474
+ code: 10001,
475
+ msg: "Invoice expired/canceled"
476
+ };
477
+ switch (invoice.status) {
478
+ case "canceled":
479
+ throw {
480
+ _httpStatus: 200,
481
+ code: 10001,
482
+ msg: "Invoice expired/canceled"
483
+ };
484
+ case "confirmed":
485
+ throw {
486
+ _httpStatus: 200,
487
+ code: 10002,
488
+ msg: "Invoice already paid"
489
+ };
490
+ case "unpaid":
491
+ throw {
492
+ _httpStatus: 200,
493
+ code: 10003,
494
+ msg: "Invoice yet unpaid"
495
+ };
496
+ default:
497
+ return invoice;
498
+ }
499
+ }
500
+ checkTooManyInflightHtlcs() {
501
+ if (this.config.maxInflightHtlcs == null)
502
+ return;
503
+ if (this.swapsWithInflighHtlcs.size >= this.config.maxInflightHtlcs)
504
+ throw {
505
+ code: 20401,
506
+ msg: "Too many in-flight HTLCs, retry later!"
507
+ };
508
+ }
509
+ startRestServer(restServer) {
510
+ restServer.use(this.path + "/createInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
511
+ restServer.post(this.path + "/createInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
512
+ const metadata = { request: {}, times: {} };
513
+ const chainIdentifier = req.query.chain;
514
+ const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
515
+ if (!swapContract.supportsInitWithoutClaimer)
516
+ throw {
517
+ code: 20299,
518
+ msg: "Not supported for " + chainIdentifier
519
+ };
520
+ metadata.times.requestReceived = Date.now();
521
+ /**
522
+ * address: string smart chain address of the recipient
523
+ * paymentHash: string payment hash of the to-be-created invoice
524
+ * amount: string amount (in sats) of the invoice
525
+ * token: string Desired token to swap
526
+ * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
527
+ * descriptionHash: string Description hash of the invoice
528
+ * gasAmount: string Desired amount in gas token to also get
529
+ * gasToken: string
530
+ * claimerBounty: string Desired amount to be left out as a claimer bounty
531
+ */
532
+ const parsedBody = await req.paramReader.getParams({
533
+ address: (val) => val != null &&
534
+ typeof (val) === "string" &&
535
+ chainInterface.isValidAddress(val, true) ? val : null,
536
+ paymentHash: (val) => val != null &&
537
+ typeof (val) === "string" &&
538
+ val.length === 64 &&
539
+ Utils_1.HEX_REGEX.test(val) ? val : null,
540
+ amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
541
+ token: (val) => val != null &&
542
+ typeof (val) === "string" &&
543
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
544
+ descriptionHash: SchemaVerifier_1.FieldTypeEnum.StringOptional,
545
+ exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
546
+ gasToken: (val) => val != null &&
547
+ typeof (val) === "string" &&
548
+ chainInterface.isValidToken(val) ? val : null,
549
+ gasAmount: SchemaVerifier_1.FieldTypeEnum.BigInt,
550
+ claimerBounty: SchemaVerifier_1.FieldTypeEnum.BigInt
551
+ });
552
+ if (parsedBody == null)
553
+ throw {
554
+ code: 20100,
555
+ msg: "Invalid request body"
556
+ };
557
+ if (parsedBody.gasToken !== chainInterface.getNativeCurrencyAddress())
558
+ throw {
559
+ code: 20290,
560
+ msg: "Unsupported gas token"
561
+ };
562
+ if (parsedBody.gasAmount < 0)
563
+ throw {
564
+ code: 20291,
565
+ msg: "Invalid gas amount, negative"
566
+ };
567
+ if (parsedBody.claimerBounty < 0)
568
+ throw {
569
+ code: 20292,
570
+ msg: "Invalid claimer bounty, negative"
571
+ };
572
+ metadata.request = parsedBody;
573
+ const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
574
+ const gasTokenAmount = {
575
+ input: false,
576
+ amount: parsedBody.gasAmount + parsedBody.claimerBounty,
577
+ token: parsedBody.gasToken
578
+ };
579
+ const request = {
580
+ chainIdentifier,
581
+ raw: req,
582
+ parsed: parsedBody,
583
+ metadata
584
+ };
585
+ const useToken = parsedBody.token;
586
+ const gasToken = parsedBody.gasToken;
587
+ //Check request params
588
+ this.checkDescriptionHash(parsedBody.descriptionHash);
589
+ this.checkTooManyInflightHtlcs();
590
+ const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
591
+ metadata.times.requestChecked = Date.now();
592
+ //Create abortController for parallel prefetches
593
+ const responseStream = res.responseStream;
594
+ const abortController = (0, Utils_1.getAbortController)(responseStream);
595
+ //Minimum reserve of native token to be kept in the wallet
596
+ const minNativeTokenReserve = this.config.minNativeBalances?.[chainIdentifier] ?? 0n;
597
+ //Pre-fetch data
598
+ const { pricePrefetchPromise, gasTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, gasToken, abortController);
599
+ const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
600
+ const gasTokenBalancePrefetch = (gasTokenAmount.amount === 0n && minNativeTokenReserve == 0n) || useToken === gasToken ?
601
+ null : this.getBalancePrefetch(chainIdentifier, gasToken, abortController);
602
+ const channelsPrefetch = this.LightningAssertions.getChannelsPrefetch(abortController);
603
+ //Asynchronously send the node's public key to the client
604
+ this.sendPublicKeyAsync(responseStream);
605
+ //Check valid amount specified (min/max)
606
+ 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 });
607
+ metadata.times.priceCalculated = Date.now();
608
+ const totalBtcInput = amountBD + amountBDgas;
609
+ //Check if we have enough funds to honor the request
610
+ if (useToken === gasToken) {
611
+ await this.checkBalance(totalInToken + totalInGasToken + minNativeTokenReserve, balancePrefetch, abortController.signal);
612
+ }
613
+ else {
614
+ await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
615
+ await this.checkBalance(totalInGasToken + minNativeTokenReserve, gasTokenBalancePrefetch, abortController.signal);
616
+ }
617
+ await this.LightningAssertions.checkInboundLiquidity(totalBtcInput, channelsPrefetch, abortController.signal);
618
+ metadata.times.balanceChecked = Date.now();
619
+ //Create swap
620
+ const hodlInvoiceObj = {
621
+ description: chainIdentifier + "-" + parsedBody.address,
622
+ cltvDelta: Number(this.config.minCltv) + 5,
623
+ expiresAt: Date.now() + (this.config.invoiceTimeoutSeconds * 1000),
624
+ id: parsedBody.paymentHash,
625
+ mtokens: totalBtcInput * 1000n,
626
+ descriptionHash: parsedBody.descriptionHash
627
+ };
628
+ metadata.invoiceRequest = hodlInvoiceObj;
629
+ const hodlInvoice = await this.lightning.createHodlInvoice(hodlInvoiceObj);
630
+ abortController.signal.throwIfAborted();
631
+ metadata.times.invoiceCreated = Date.now();
632
+ metadata.invoiceResponse = { ...hodlInvoice };
633
+ totalInGasToken -= parsedBody.claimerBounty;
634
+ 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);
635
+ metadata.times.swapCreated = Date.now();
636
+ createdSwap.metadata = metadata;
637
+ await PluginManager_1.PluginManager.swapCreate(createdSwap);
638
+ await this.saveSwapData(createdSwap);
639
+ this.swapLogger.info(createdSwap, "REST: /createInvoice: Created swap invoice: " + hodlInvoice.request + " amount: " + totalBtcInput.toString(10));
640
+ this.subscribeToInvoice(createdSwap);
641
+ await responseStream.writeParamsAndEnd({
642
+ code: 20000,
643
+ msg: "Success",
644
+ data: {
645
+ intermediaryKey: signer.getAddress(),
646
+ pr: hodlInvoice.request,
647
+ btcAmountSwap: amountBD.toString(10),
648
+ btcAmountGas: amountBDgas.toString(10),
649
+ total: totalInToken.toString(10),
650
+ totalGas: totalInGasToken.toString(10),
651
+ totalFeeBtc: (swapFee + gasSwapFee).toString(10),
652
+ swapFeeBtc: swapFee.toString(10),
653
+ swapFee: swapFeeInToken.toString(10),
654
+ gasSwapFeeBtc: gasSwapFee.toString(10),
655
+ gasSwapFee: gasSwapFeeInToken.toString(10),
656
+ claimerBounty: parsedBody.claimerBounty.toString(10)
657
+ }
658
+ });
659
+ }));
660
+ const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
661
+ /**
662
+ * paymentHash: string payment hash of the invoice
663
+ */
664
+ const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
665
+ paymentHash: (val) => val != null &&
666
+ typeof (val) === "string" &&
667
+ val.length === 64 &&
668
+ Utils_1.HEX_REGEX.test(val) ? val : null,
669
+ });
670
+ await this.checkInvoiceStatus(parsedBody.paymentHash);
671
+ const swap = await this.storageManager.getData(parsedBody.paymentHash, null);
672
+ if (swap == null)
673
+ throw {
674
+ _httpStatus: 200,
675
+ code: 10001,
676
+ msg: "Invoice expired/canceled"
677
+ };
678
+ if (swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.RECEIVED ||
679
+ swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.TXS_SENT ||
680
+ swap.state === FromBtcLnAutoSwap_1.FromBtcLnAutoSwapState.COMMITED) {
681
+ res.status(200).json({
682
+ code: 10000,
683
+ msg: "Success",
684
+ data: {
685
+ data: swap.data.serialize()
686
+ }
687
+ });
688
+ }
689
+ else {
690
+ res.status(200).json({
691
+ code: 10003,
692
+ msg: "Invoice yet unpaid"
693
+ });
694
+ }
695
+ });
696
+ restServer.post(this.path + "/getInvoiceStatus", getInvoiceStatus);
697
+ restServer.get(this.path + "/getInvoiceStatus", getInvoiceStatus);
698
+ this.logger.info("started at path: ", this.path);
699
+ }
700
+ async init() {
701
+ await this.loadData(FromBtcLnAutoSwap_1.FromBtcLnAutoSwap);
702
+ this.subscribeToEvents();
703
+ await PluginManager_1.PluginManager.serviceInitialize(this);
704
+ }
705
+ getInfoData() {
706
+ const mappedDict = {};
707
+ for (let chainId in this.config.gasTokenMax) {
708
+ mappedDict[chainId] = {
709
+ gasToken: this.getChain(chainId).chainInterface.getNativeCurrencyAddress(),
710
+ max: this.config.gasTokenMax[chainId].toString(10)
711
+ };
712
+ }
713
+ return {
714
+ minCltv: Number(this.config.minCltv),
715
+ invoiceTimeoutSeconds: this.config.invoiceTimeoutSeconds,
716
+ gasTokens: mappedDict
717
+ };
718
+ }
719
+ async removeSwapData(swap, ultimateState) {
720
+ this.swapsWithInflighHtlcs.delete(swap);
721
+ return super.removeSwapData(swap, ultimateState);
722
+ }
723
+ }
724
+ exports.FromBtcLnAuto = FromBtcLnAuto;