@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,888 @@
1
+ import {Express, Request, Response} from "express";
2
+ import {createHash} from "crypto";
3
+ import {FromBtcLnAutoSwap, FromBtcLnAutoSwapState} from "./FromBtcLnAutoSwap";
4
+ import {MultichainData, SwapHandlerType} from "../../SwapHandler";
5
+ import {ISwapPrice} from "../../../prices/ISwapPrice";
6
+ import {ChainSwapType, ClaimEvent, InitializeEvent, RefundEvent, SwapCommitStateType, SwapData} from "@atomiqlabs/base";
7
+ import {expressHandlerWrapper, getAbortController, HEX_REGEX, isDefinedRuntimeError} from "../../../utils/Utils";
8
+ import {PluginManager} from "../../../plugins/PluginManager";
9
+ import {IIntermediaryStorage} from "../../../storage/IIntermediaryStorage";
10
+ import {FieldTypeEnum, verifySchema} from "../../../utils/paramcoders/SchemaVerifier";
11
+ import {serverParamDecoder} from "../../../utils/paramcoders/server/ServerParamDecoder";
12
+ import {ServerParamEncoder} from "../../../utils/paramcoders/server/ServerParamEncoder";
13
+ import {IParamReader} from "../../../utils/paramcoders/IParamReader";
14
+ import {FromBtcBaseConfig, FromBtcBaseSwapHandler} from "../FromBtcBaseSwapHandler";
15
+ import {
16
+ HodlInvoiceInit,
17
+ ILightningWallet,
18
+ LightningNetworkChannel,
19
+ LightningNetworkInvoice
20
+ } from "../../../wallets/ILightningWallet";
21
+ import {LightningAssertions} from "../../assertions/LightningAssertions";
22
+
23
+ export type FromBtcLnAutoConfig = FromBtcBaseConfig & {
24
+ maxInflightHtlcs?: number,
25
+ minNativeBalances?: {
26
+ [chainId: string]: bigint
27
+ },
28
+ invoiceTimeoutSeconds?: number,
29
+ minCltv: bigint,
30
+ gracePeriod: bigint,
31
+ gasTokenMax: {[chainId: string]: bigint}
32
+ }
33
+
34
+ export type FromBtcLnAutoRequestType = {
35
+ address: string,
36
+ paymentHash: string,
37
+ amount: bigint,
38
+ token: string,
39
+ gasToken: string,
40
+ gasAmount: bigint,
41
+ claimerBounty: bigint,
42
+ descriptionHash?: string,
43
+ exactOut?: boolean
44
+ }
45
+
46
+ /**
47
+ * Swap handler handling from BTCLN swaps using submarine swaps
48
+ */
49
+ export class FromBtcLnAuto extends FromBtcBaseSwapHandler<FromBtcLnAutoSwap, FromBtcLnAutoSwapState> {
50
+ readonly type = SwapHandlerType.FROM_BTCLN_AUTO;
51
+ readonly swapType = ChainSwapType.HTLC;
52
+
53
+ activeSubscriptions: Set<string> = new Set<string>();
54
+ swapsWithInflighHtlcs: Set<FromBtcLnAutoSwap> = new Set();
55
+
56
+ readonly config: FromBtcLnAutoConfig;
57
+ readonly lightning: ILightningWallet;
58
+ readonly LightningAssertions: LightningAssertions;
59
+
60
+ constructor(
61
+ storageDirectory: IIntermediaryStorage<FromBtcLnAutoSwap>,
62
+ path: string,
63
+ chains: MultichainData,
64
+ lightning: ILightningWallet,
65
+ swapPricing: ISwapPrice,
66
+ config: FromBtcLnAutoConfig
67
+ ) {
68
+ super(storageDirectory, path, chains, swapPricing, config);
69
+ this.config = config;
70
+ this.config.invoiceTimeoutSeconds = this.config.invoiceTimeoutSeconds || 90;
71
+ this.lightning = lightning;
72
+ this.LightningAssertions = new LightningAssertions(this.logger, lightning);
73
+ }
74
+
75
+ protected async processPastSwap(swap: FromBtcLnAutoSwap): Promise<"REFUND" | "SETTLE" | null> {
76
+ const {swapContract, signer} = this.getChain(swap.chainIdentifier);
77
+ if(swap.state===FromBtcLnAutoSwapState.CREATED) {
78
+ //Check if already paid
79
+ const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
80
+ const invoice = await this.lightning.getInvoice(parsedPR.id);
81
+
82
+ const isBeingPaid = invoice.status==="held";
83
+ if(!isBeingPaid) {
84
+ //Not paid
85
+ const isInvoiceExpired = parsedPR.expiryEpochMillis<Date.now();
86
+ if(isInvoiceExpired) {
87
+ this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap LN invoice expired, cancelling, invoice: "+swap.pr);
88
+ await this.cancelSwapAndInvoice(swap);
89
+ return null;
90
+ }
91
+ this.subscribeToInvoice(swap);
92
+ return null;
93
+ }
94
+
95
+ //Adjust the state of the swap and expiry
96
+ try {
97
+ await this.htlcReceived(swap, invoice);
98
+ //Result is either FromBtcLnSwapState.RECEIVED or FromBtcLnSwapState.CANCELED
99
+ } catch (e) {
100
+ this.swapLogger.error(swap, "processPastSwap(state=CREATED): htlcReceived error", e);
101
+ }
102
+
103
+ return null;
104
+ }
105
+
106
+ if(swap.state===FromBtcLnAutoSwapState.RECEIVED) {
107
+ try {
108
+ await this.offerHtlc(swap);
109
+ } catch (e) {
110
+ this.swapLogger.error(swap, "processPastSwap(state=RECEIVED): offerHtlc error", e);
111
+ }
112
+
113
+ return null;
114
+ }
115
+
116
+ if(swap.state===FromBtcLnAutoSwapState.TXS_SENT || swap.state===FromBtcLnAutoSwapState.COMMITED) {
117
+ this.swapsWithInflighHtlcs.add(swap);
118
+
119
+ const onchainStatus = await swapContract.getCommitStatus(signer.getAddress(), swap.data);
120
+ const state: FromBtcLnAutoSwapState = swap.state as FromBtcLnAutoSwapState;
121
+ if(onchainStatus.type===SwapCommitStateType.PAID) {
122
+ //Extract the swap secret
123
+ if(state!==FromBtcLnAutoSwapState.CLAIMED && state!==FromBtcLnAutoSwapState.SETTLED) {
124
+ const secretHex = await onchainStatus.getClaimResult();
125
+ const secret: Buffer = Buffer.from(secretHex, "hex");
126
+ const paymentHash: Buffer = createHash("sha256").update(secret).digest();
127
+ const paymentHashHex = paymentHash.toString("hex");
128
+
129
+ if (swap.lnPaymentHash!==paymentHashHex) {
130
+ //TODO: Possibly fatal failure
131
+ this.swapLogger.error(swap, "processPastSwap(state=TXS_SENT|COMMITED): onchainStatus=PAID, Invalid swap secret specified: "+secretHex+" for paymentHash: "+paymentHashHex);
132
+ return null;
133
+ }
134
+
135
+ swap.secret = secretHex;
136
+ await swap.setState(FromBtcLnAutoSwapState.CLAIMED);
137
+ await this.saveSwapData(swap);
138
+
139
+ this.swapLogger.warn(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap settled (detected from processPastSwap), invoice: "+swap.pr);
140
+
141
+ return "SETTLE";
142
+ }
143
+ return null;
144
+ }
145
+ if(onchainStatus.type===SwapCommitStateType.COMMITED) {
146
+ if(state===FromBtcLnAutoSwapState.TXS_SENT) {
147
+ await swap.setState(FromBtcLnAutoSwapState.COMMITED);
148
+ await this.saveSwapData(swap);
149
+
150
+ this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap committed (detected from processPastSwap), invoice: "+swap.pr);
151
+ }
152
+ return null;
153
+ }
154
+ if(onchainStatus.type===SwapCommitStateType.NOT_COMMITED || onchainStatus.type===SwapCommitStateType.EXPIRED) {
155
+ if(swap.state===FromBtcLnAutoSwapState.TXS_SENT) {
156
+ const isAuthorizationExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
157
+ if(isAuthorizationExpired) {
158
+ this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap not committed before authorization expiry, cancelling the LN invoice, invoice: "+swap.pr);
159
+ await this.cancelSwapAndInvoice(swap);
160
+ return null;
161
+ }
162
+ } else {
163
+ if(await swapContract.isExpired(signer.getAddress(), swap.data)) {
164
+ this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap timed out, refunding to self, invoice: "+swap.pr);
165
+ return "REFUND";
166
+ }
167
+ }
168
+ }
169
+ if(onchainStatus.type===SwapCommitStateType.REFUNDABLE) {
170
+ this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT|COMMITED): swap timed out, refunding to self, invoice: "+swap.pr);
171
+ return "REFUND";
172
+ }
173
+ }
174
+
175
+ if(swap.state===FromBtcLnAutoSwapState.CLAIMED) return "SETTLE";
176
+ if(swap.state===FromBtcLnAutoSwapState.CANCELED) await this.cancelSwapAndInvoice(swap);
177
+ }
178
+
179
+ protected async refundSwaps(refundSwaps: FromBtcLnAutoSwap[]) {
180
+ for(let refundSwap of refundSwaps) {
181
+ const {swapContract, signer} = this.getChain(refundSwap.chainIdentifier);
182
+ const unlock = refundSwap.lock(swapContract.refundTimeout);
183
+ if(unlock==null) continue;
184
+
185
+ this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
186
+ await swapContract.refund(signer, refundSwap.data, true, false, {waitForConfirmation: true});
187
+ this.swapLogger.info(refundSwap, "refundsSwaps(): swap refunded, invoice: "+refundSwap.pr);
188
+
189
+ await refundSwap.setState(FromBtcLnAutoSwapState.REFUNDED);
190
+ unlock();
191
+ }
192
+ }
193
+
194
+ protected async settleInvoices(swaps: FromBtcLnAutoSwap[]) {
195
+ for(let swap of swaps) {
196
+ try {
197
+ await this.lightning.settleHodlInvoice(swap.secret);
198
+ if(swap.metadata!=null) swap.metadata.times.htlcSettled = Date.now();
199
+ await this.removeSwapData(swap, FromBtcLnAutoSwapState.SETTLED);
200
+
201
+ this.swapLogger.info(swap, "settleInvoices(): invoice settled, secret: "+swap.secret);
202
+ } catch (e) {
203
+ this.swapLogger.error(swap, "settleInvoices(): cannot settle invoice", e);
204
+ }
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Checks past swaps, refunds and deletes ones that are already expired.
210
+ */
211
+ protected async processPastSwaps() {
212
+
213
+ const settleInvoices: FromBtcLnAutoSwap[] = [];
214
+ const refundSwaps: FromBtcLnAutoSwap[] = [];
215
+
216
+ const queriedData = await this.storageManager.query([
217
+ {
218
+ key: "state",
219
+ value: [
220
+ FromBtcLnAutoSwapState.CREATED,
221
+ FromBtcLnAutoSwapState.RECEIVED,
222
+ FromBtcLnAutoSwapState.TXS_SENT,
223
+ FromBtcLnAutoSwapState.COMMITED,
224
+ FromBtcLnAutoSwapState.CLAIMED,
225
+ FromBtcLnAutoSwapState.CANCELED,
226
+ ]
227
+ }
228
+ ]);
229
+
230
+ for(let {obj: swap} of queriedData) {
231
+ switch(await this.processPastSwap(swap)) {
232
+ case "SETTLE":
233
+ settleInvoices.push(swap);
234
+ break;
235
+ case "REFUND":
236
+ refundSwaps.push(swap);
237
+ break;
238
+ }
239
+ }
240
+
241
+ await this.refundSwaps(refundSwaps);
242
+ await this.settleInvoices(settleInvoices);
243
+ }
244
+
245
+ protected async processInitializeEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoSwap, event: InitializeEvent<SwapData>): Promise<void> {
246
+ this.swapLogger.info(savedSwap, "SC: InitializeEvent: HTLC initialized by the client, invoice: "+savedSwap.pr);
247
+
248
+ if(savedSwap.state===FromBtcLnAutoSwapState.TXS_SENT) {
249
+ await savedSwap.setState(FromBtcLnAutoSwapState.COMMITED);
250
+ await this.saveSwapData(savedSwap);
251
+ }
252
+ }
253
+
254
+ protected async processClaimEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoSwap, event: ClaimEvent<SwapData>): Promise<void> {
255
+ //Claim
256
+ //This is the important part, we need to catch the claim TX, else we may lose money
257
+ const secret: Buffer = Buffer.from(event.result, "hex");
258
+ const paymentHash: Buffer = createHash("sha256").update(secret).digest();
259
+ const secretHex = secret.toString("hex");
260
+ const paymentHashHex = paymentHash.toString("hex");
261
+
262
+ if (savedSwap.lnPaymentHash!==paymentHashHex) return;
263
+
264
+ this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap HTLC successfully claimed by the client, invoice: "+savedSwap.pr);
265
+
266
+ try {
267
+ await this.lightning.settleHodlInvoice(secretHex);
268
+ this.swapLogger.info(savedSwap, "SC: ClaimEvent: invoice settled, secret: "+secretHex);
269
+ savedSwap.secret = secretHex;
270
+ if(savedSwap.metadata!=null) savedSwap.metadata.times.htlcSettled = Date.now();
271
+ await this.removeSwapData(savedSwap, FromBtcLnAutoSwapState.SETTLED);
272
+ } catch (e) {
273
+ this.swapLogger.error(savedSwap, "SC: ClaimEvent: cannot settle invoice", e);
274
+ savedSwap.secret = secretHex;
275
+ await savedSwap.setState(FromBtcLnAutoSwapState.CLAIMED);
276
+ await this.saveSwapData(savedSwap);
277
+ }
278
+
279
+ }
280
+
281
+ protected async processRefundEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoSwap, event: RefundEvent<SwapData>): Promise<void> {
282
+ this.swapLogger.info(savedSwap, "SC: RefundEvent: swap refunded to us, invoice: "+savedSwap.pr);
283
+
284
+ //We don't cancel the incoming invoice, to make the offender pay for this with locked liquidity
285
+ // await this.lightning.cancelHodlInvoice(savedSwap.lnPaymentHash);
286
+ await this.removeSwapData(savedSwap, FromBtcLnAutoSwapState.REFUNDED)
287
+ }
288
+
289
+ /**
290
+ * Subscribe to a lightning network invoice
291
+ *
292
+ * @param swap
293
+ */
294
+ private subscribeToInvoice(swap: FromBtcLnAutoSwap): boolean {
295
+ const paymentHash = swap.lnPaymentHash;
296
+ if(this.activeSubscriptions.has(paymentHash)) return false;
297
+
298
+ this.lightning.waitForInvoice(paymentHash).then(result => {
299
+ this.swapLogger.info(swap, "subscribeToInvoice(): result callback, outcome: "+result.status+" invoice: "+swap.pr);
300
+ if(result.status==="held")
301
+ this.htlcReceived(swap, result).catch(e => this.swapLogger.error(swap, "subscribeToInvoice(): HTLC received result", e));
302
+ this.activeSubscriptions.delete(paymentHash);
303
+ });
304
+ this.swapLogger.info(swap, "subscribeToInvoice(): subscribe to invoice: "+swap.pr);
305
+
306
+ this.activeSubscriptions.add(paymentHash);
307
+ return true;
308
+ }
309
+
310
+ /**
311
+ * Called when lightning HTLC is received, also signs an init transaction on the smart chain side, expiry of the
312
+ * smart chain authorization starts ticking as soon as this HTLC is received
313
+ *
314
+ * @param invoiceData
315
+ * @param invoice
316
+ */
317
+ private async htlcReceived(invoiceData: FromBtcLnAutoSwap, invoice: LightningNetworkInvoice) {
318
+ if(invoiceData.state!==FromBtcLnAutoSwapState.CREATED) return;
319
+ this.swapLogger.debug(invoiceData, "htlcReceived(): invoice: ", invoice);
320
+ if(invoiceData.metadata!=null) invoiceData.metadata.times.htlcReceived = Date.now();
321
+
322
+ const useToken = invoiceData.token;
323
+
324
+ let expiryTimeout: bigint;
325
+ try {
326
+ //Check if HTLC expiry is long enough
327
+ expiryTimeout = await this.checkHtlcExpiry(invoice);
328
+ if(invoiceData.metadata!=null) invoiceData.metadata.times.htlcTimeoutCalculated = Date.now();
329
+ } catch (e) {
330
+ if(isDefinedRuntimeError(e) && invoiceData.metadata!=null) invoiceData.metadata.htlcReceiveError = e;
331
+ if(invoiceData.state===FromBtcLnAutoSwapState.CREATED) await this.cancelSwapAndInvoice(invoiceData);
332
+ throw e;
333
+ }
334
+
335
+ const {swapContract, signer} = this.getChain(invoiceData.chainIdentifier);
336
+
337
+ //Create real swap data
338
+ const swapData: SwapData = await swapContract.createSwapData(
339
+ ChainSwapType.HTLC,
340
+ signer.getAddress(),
341
+ invoiceData.claimer,
342
+ useToken,
343
+ invoiceData.amountToken,
344
+ invoiceData.claimHash,
345
+ 0n,
346
+ BigInt(Math.floor(Date.now() / 1000)) + expiryTimeout,
347
+ false,
348
+ true,
349
+ invoiceData.amountGasToken + invoiceData.claimerBounty,
350
+ invoiceData.claimerBounty,
351
+ invoiceData.gasToken
352
+ );
353
+ if(invoiceData.metadata!=null) invoiceData.metadata.times.htlcSwapCreated = Date.now();
354
+
355
+ //Important to prevent race condition and issuing 2 signed init messages at the same time
356
+ if(invoiceData.state===FromBtcLnAutoSwapState.CREATED) {
357
+ invoiceData.data = swapData;
358
+ invoiceData.signature = null;
359
+ invoiceData.timeout = (BigInt(Math.floor(Date.now() / 1000)) + 120n).toString(10);
360
+
361
+ //Setting the state variable is done outside the promise, so is done synchronously
362
+ await invoiceData.setState(FromBtcLnAutoSwapState.RECEIVED);
363
+
364
+ await this.saveSwapData(invoiceData);
365
+
366
+ await this.offerHtlc(invoiceData);
367
+ }
368
+ }
369
+
370
+ private async offerHtlc(invoiceData: FromBtcLnAutoSwap) {
371
+ if(invoiceData.state!==FromBtcLnAutoSwapState.RECEIVED) return;
372
+
373
+ try {
374
+ this.checkTooManyInflightHtlcs();
375
+ } catch (e) {
376
+ if(isDefinedRuntimeError(e) && invoiceData.metadata!=null) invoiceData.metadata.htlcOfferError = e;
377
+ if(invoiceData.state===FromBtcLnAutoSwapState.RECEIVED) await this.cancelSwapAndInvoice(invoiceData);
378
+ throw e;
379
+ }
380
+
381
+ this.swapLogger.debug(invoiceData, "offerHtlc(): invoice: ", invoiceData.pr);
382
+ if(invoiceData.metadata!=null) invoiceData.metadata.times.offerHtlc = Date.now();
383
+
384
+ const useToken = invoiceData.token;
385
+ const gasToken = invoiceData.gasToken;
386
+
387
+ const {swapContract, signer, chainInterface} = this.getChain(invoiceData.chainIdentifier);
388
+
389
+ //Create abort controller for parallel fetches
390
+ const abortController = new AbortController();
391
+
392
+ //Minimum reserve of native token to be kept in the wallet
393
+ const minNativeTokenReserve: bigint = this.config.minNativeBalances?.[invoiceData.chainIdentifier] ?? 0n;
394
+
395
+ //Pre-fetch data
396
+ const balancePrefetch: Promise<bigint> = this.getBalancePrefetch(invoiceData.chainIdentifier, useToken, abortController);
397
+ const gasTokenBalancePrefetch: Promise<bigint> = (invoiceData.getTotalOutputGasAmount()===0n && minNativeTokenReserve===0n) || useToken===gasToken ?
398
+ null : this.getBalancePrefetch(invoiceData.chainIdentifier, gasToken, abortController);
399
+
400
+ if(await swapContract.getInitAuthorizationExpiry(invoiceData.data, invoiceData) < Date.now()) {
401
+ if(invoiceData.metadata!=null) invoiceData.metadata.htlcOfferError = "Init authorization expired, before being sent!";
402
+ if(invoiceData.state===FromBtcLnAutoSwapState.RECEIVED) {
403
+ await this.cancelSwapAndInvoice(invoiceData);
404
+ }
405
+ return false;
406
+ }
407
+
408
+ try {
409
+ //Check if we have enough liquidity to proceed
410
+ if(useToken===gasToken) {
411
+ await this.checkBalance(invoiceData.getTotalOutputAmount() + invoiceData.getTotalOutputGasAmount() + minNativeTokenReserve, balancePrefetch, abortController.signal);
412
+ } else {
413
+ await this.checkBalance(invoiceData.getTotalOutputAmount(), balancePrefetch, abortController.signal);
414
+ await this.checkBalance(invoiceData.getTotalOutputGasAmount() + minNativeTokenReserve, gasTokenBalancePrefetch, abortController.signal);
415
+ }
416
+ if(invoiceData.metadata!=null) invoiceData.metadata.times.offerHtlcChecked = Date.now();
417
+ } catch (e) {
418
+ if(!abortController.signal.aborted) {
419
+ if(isDefinedRuntimeError(e) && invoiceData.metadata!=null) invoiceData.metadata.htlcOfferError = e;
420
+ if(invoiceData.state===FromBtcLnAutoSwapState.RECEIVED) await this.cancelSwapAndInvoice(invoiceData);
421
+ }
422
+ throw e;
423
+ }
424
+
425
+ const txWithdraw = await swapContract.txsWithdraw(signer.getAddress(), gasToken, invoiceData.data.getTotalDeposit());
426
+ const txInit = await swapContract.txsInit(signer.getAddress(), invoiceData.data, {
427
+ prefix: invoiceData.prefix,
428
+ timeout: invoiceData.timeout,
429
+ signature: invoiceData.signature
430
+ }, true);
431
+
432
+ if(invoiceData.state===FromBtcLnAutoSwapState.RECEIVED) {
433
+ //Re-check the current HTLC count
434
+ try {
435
+ this.checkTooManyInflightHtlcs();
436
+ } catch (e) {
437
+ if(isDefinedRuntimeError(e) && invoiceData.metadata!=null) invoiceData.metadata.htlcOfferError = e;
438
+ if(invoiceData.state===FromBtcLnAutoSwapState.RECEIVED) await this.cancelSwapAndInvoice(invoiceData);
439
+ throw e;
440
+ }
441
+ this.swapLogger.debug(invoiceData, `offerHtlc(): Sending HTLC offer, current in flight HTLCs: ${this.swapsWithInflighHtlcs.size}, invoice: `, invoiceData.pr);
442
+ this.swapsWithInflighHtlcs.add(invoiceData);
443
+ //Setting the state variable is done outside the promise, so is done synchronously
444
+ await invoiceData.setState(FromBtcLnAutoSwapState.TXS_SENT);
445
+ await this.saveSwapData(invoiceData);
446
+ await chainInterface.sendAndConfirm(signer, [...txWithdraw, ...txInit], true, undefined, true);
447
+ }
448
+
449
+ return true;
450
+ }
451
+
452
+ /**
453
+ * Checks invoice description hash
454
+ *
455
+ * @param descriptionHash
456
+ * @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
457
+ */
458
+ private checkDescriptionHash(descriptionHash: string) {
459
+ if(descriptionHash!=null) {
460
+ if(typeof(descriptionHash)!=="string" || !HEX_REGEX.test(descriptionHash) || descriptionHash.length!==64) {
461
+ throw {
462
+ code: 20100,
463
+ msg: "Invalid request body (descriptionHash)"
464
+ };
465
+ }
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
471
+ *
472
+ * @param responseStream
473
+ */
474
+ private sendPublicKeyAsync(responseStream: ServerParamEncoder) {
475
+ this.lightning.getIdentityPublicKey().then(publicKey => responseStream.writeParams({
476
+ lnPublicKey: publicKey
477
+ })).catch(e => {
478
+ this.logger.error("sendPublicKeyAsync(): error", e);
479
+ });
480
+ }
481
+
482
+ /**
483
+ * Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
484
+ * received (MPP) it returns the lowest of the timeouts
485
+ *
486
+ * @param invoice
487
+ */
488
+ private getInvoicePaymentsTimeout(invoice: LightningNetworkInvoice): number | null {
489
+ let timeout: number = null;
490
+ invoice.payments.forEach((curr) => {
491
+ if (timeout == null || timeout > curr.timeout) timeout = curr.timeout;
492
+ });
493
+ return timeout;
494
+ }
495
+
496
+ /**
497
+ * Checks if the received HTLC's CLTV timeout is large enough to still process the swap
498
+ *
499
+ * @param invoice
500
+ * @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
501
+ * @returns expiry timeout in seconds
502
+ */
503
+ private async checkHtlcExpiry(invoice: LightningNetworkInvoice): Promise<bigint> {
504
+ const timeout: number = this.getInvoicePaymentsTimeout(invoice);
505
+ const current_block_height = await this.lightning.getBlockheight();
506
+
507
+ const blockDelta = BigInt(timeout - current_block_height);
508
+
509
+ const htlcExpiresTooSoon = blockDelta < this.config.minCltv;
510
+ if(htlcExpiresTooSoon) {
511
+ throw {
512
+ code: 20002,
513
+ msg: "Not enough time to reliably process the swap",
514
+ data: {
515
+ requiredDelta: this.config.minCltv.toString(10),
516
+ actualDelta: blockDelta.toString(10)
517
+ }
518
+ };
519
+ }
520
+
521
+ return (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
522
+ }
523
+
524
+ /**
525
+ * Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
526
+ *
527
+ * @param invoiceData
528
+ */
529
+ private async cancelSwapAndInvoice(invoiceData: FromBtcLnAutoSwap): Promise<void> {
530
+ await invoiceData.setState(FromBtcLnAutoSwapState.CANCELED);
531
+ await this.lightning.cancelHodlInvoice(invoiceData.lnPaymentHash);
532
+ await this.removeSwapData(invoiceData);
533
+ this.swapLogger.info(invoiceData, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", invoiceData.pr);
534
+ };
535
+
536
+ /**
537
+ *
538
+ * Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
539
+ *
540
+ * @param paymentHash
541
+ * @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
542
+ * @returns the fetched lightning invoice
543
+ */
544
+ private async checkInvoiceStatus(paymentHash: string): Promise<any> {
545
+ const invoice = await this.lightning.getInvoice(paymentHash);
546
+ if(invoice==null) throw {
547
+ _httpStatus: 200,
548
+ code: 10001,
549
+ msg: "Invoice expired/canceled"
550
+ };
551
+
552
+ const arr = invoice.description.split("-");
553
+ if(arr.length<2) throw {
554
+ _httpStatus: 200,
555
+ code: 10001,
556
+ msg: "Invoice expired/canceled"
557
+ };
558
+ const chainIdentifier = arr[0];
559
+ const address = arr[1];
560
+
561
+ const {chainInterface} = this.getChain(chainIdentifier);
562
+ if(!chainInterface.isValidAddress(address, true)) throw {
563
+ _httpStatus: 200,
564
+ code: 10001,
565
+ msg: "Invoice expired/canceled"
566
+ };
567
+
568
+ switch(invoice.status) {
569
+ case "canceled":
570
+ throw {
571
+ _httpStatus: 200,
572
+ code: 10001,
573
+ msg: "Invoice expired/canceled"
574
+ }
575
+ case "confirmed":
576
+ throw {
577
+ _httpStatus: 200,
578
+ code: 10002,
579
+ msg: "Invoice already paid"
580
+ };
581
+ case "unpaid":
582
+ throw {
583
+ _httpStatus: 200,
584
+ code: 10003,
585
+ msg: "Invoice yet unpaid"
586
+ };
587
+ default:
588
+ return invoice;
589
+ }
590
+ }
591
+
592
+ private checkTooManyInflightHtlcs() {
593
+ if(this.config.maxInflightHtlcs==null) return;
594
+ if(this.swapsWithInflighHtlcs.size>=this.config.maxInflightHtlcs) throw {
595
+ code: 20401,
596
+ msg: "Too many in-flight HTLCs, retry later!"
597
+ }
598
+ }
599
+
600
+ startRestServer(restServer: Express) {
601
+
602
+ restServer.use(this.path+"/createInvoice", serverParamDecoder(10*1000));
603
+ restServer.post(this.path+"/createInvoice", expressHandlerWrapper(async (req: Request & {paramReader: IParamReader}, res: Response & {responseStream: ServerParamEncoder}) => {
604
+ const metadata: {
605
+ request: any,
606
+ invoiceRequest?: any,
607
+ invoiceResponse?: any,
608
+ times: {[key: string]: number}
609
+ } = {request: {}, times: {}};
610
+
611
+ const chainIdentifier = req.query.chain as string;
612
+ const {swapContract, signer, chainInterface} = this.getChain(chainIdentifier);
613
+ if(!swapContract.supportsInitWithoutClaimer) throw {
614
+ code: 20299,
615
+ msg: "Not supported for "+chainIdentifier
616
+ };
617
+
618
+ metadata.times.requestReceived = Date.now();
619
+
620
+ /**
621
+ * address: string smart chain address of the recipient
622
+ * paymentHash: string payment hash of the to-be-created invoice
623
+ * amount: string amount (in sats) of the invoice
624
+ * token: string Desired token to swap
625
+ * exactOut: boolean Whether the swap should be an exact out instead of exact in swap
626
+ * descriptionHash: string Description hash of the invoice
627
+ * gasAmount: string Desired amount in gas token to also get
628
+ * gasToken: string
629
+ * claimerBounty: string Desired amount to be left out as a claimer bounty
630
+ */
631
+ const parsedBody: FromBtcLnAutoRequestType = await req.paramReader.getParams({
632
+ address: (val: string) => val!=null &&
633
+ typeof(val)==="string" &&
634
+ chainInterface.isValidAddress(val, true) ? val : null,
635
+ paymentHash: (val: string) => val!=null &&
636
+ typeof(val)==="string" &&
637
+ val.length===64 &&
638
+ HEX_REGEX.test(val) ? val: null,
639
+ amount: FieldTypeEnum.BigInt,
640
+ token: (val: string) => val!=null &&
641
+ typeof(val)==="string" &&
642
+ this.isTokenSupported(chainIdentifier, val) ? val : null,
643
+ descriptionHash: FieldTypeEnum.StringOptional,
644
+ exactOut: FieldTypeEnum.BooleanOptional,
645
+ gasToken: (val: string) => val!=null &&
646
+ typeof(val)==="string" &&
647
+ chainInterface.isValidToken(val) ? val : null,
648
+ gasAmount: FieldTypeEnum.BigInt,
649
+ claimerBounty: FieldTypeEnum.BigInt
650
+ });
651
+ if(parsedBody==null) throw {
652
+ code: 20100,
653
+ msg: "Invalid request body"
654
+ };
655
+
656
+ if(parsedBody.gasToken!==chainInterface.getNativeCurrencyAddress()) throw {
657
+ code: 20290,
658
+ msg: "Unsupported gas token"
659
+ };
660
+
661
+ if(parsedBody.gasAmount < 0) throw {
662
+ code: 20291,
663
+ msg: "Invalid gas amount, negative"
664
+ };
665
+ if(parsedBody.claimerBounty < 0) throw {
666
+ code: 20292,
667
+ msg: "Invalid claimer bounty, negative"
668
+ };
669
+ metadata.request = parsedBody;
670
+
671
+ const requestedAmount = {input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token};
672
+ const gasTokenAmount = {
673
+ input: false,
674
+ amount: parsedBody.gasAmount + parsedBody.claimerBounty,
675
+ token: parsedBody.gasToken
676
+ } as const;
677
+ const request = {
678
+ chainIdentifier,
679
+ raw: req,
680
+ parsed: parsedBody,
681
+ metadata
682
+ };
683
+ const useToken = parsedBody.token;
684
+ const gasToken = parsedBody.gasToken;
685
+
686
+ //Check request params
687
+ this.checkDescriptionHash(parsedBody.descriptionHash);
688
+ this.checkTooManyInflightHtlcs();
689
+ const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
690
+ metadata.times.requestChecked = Date.now();
691
+
692
+ //Create abortController for parallel prefetches
693
+ const responseStream = res.responseStream;
694
+ const abortController = getAbortController(responseStream);
695
+
696
+ //Minimum reserve of native token to be kept in the wallet
697
+ const minNativeTokenReserve: bigint = this.config.minNativeBalances?.[chainIdentifier] ?? 0n;
698
+
699
+ //Pre-fetch data
700
+ const {
701
+ pricePrefetchPromise,
702
+ gasTokenPricePrefetchPromise
703
+ } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, gasToken, abortController);
704
+ const balancePrefetch: Promise<bigint> = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
705
+ const gasTokenBalancePrefetch: Promise<bigint> = (gasTokenAmount.amount===0n && minNativeTokenReserve==0n) || useToken===gasToken ?
706
+ null : this.getBalancePrefetch(chainIdentifier, gasToken, abortController);
707
+ const channelsPrefetch: Promise<LightningNetworkChannel[]> = this.LightningAssertions.getChannelsPrefetch(abortController);
708
+
709
+ //Asynchronously send the node's public key to the client
710
+ this.sendPublicKeyAsync(responseStream);
711
+
712
+ //Check valid amount specified (min/max)
713
+ let {
714
+ amountBD,
715
+ swapFee,
716
+ swapFeeInToken,
717
+ totalInToken,
718
+ amountBDgas,
719
+ gasSwapFee,
720
+ gasSwapFeeInToken,
721
+ totalInGasToken
722
+ } = await this.AmountAssertions.checkFromBtcAmount(
723
+ this.type, request,
724
+ {...requestedAmount, pricePrefetch: pricePrefetchPromise},
725
+ fees, abortController.signal,
726
+ {...gasTokenAmount, pricePrefetch: gasTokenPricePrefetchPromise}
727
+ );
728
+ metadata.times.priceCalculated = Date.now();
729
+
730
+ const totalBtcInput = amountBD + amountBDgas;
731
+
732
+ //Check if we have enough funds to honor the request
733
+ if(useToken===gasToken) {
734
+ await this.checkBalance(totalInToken + totalInGasToken + minNativeTokenReserve, balancePrefetch, abortController.signal);
735
+ } else {
736
+ await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
737
+ await this.checkBalance(totalInGasToken + minNativeTokenReserve, gasTokenBalancePrefetch, abortController.signal);
738
+ }
739
+ await this.LightningAssertions.checkInboundLiquidity(totalBtcInput, channelsPrefetch, abortController.signal);
740
+ metadata.times.balanceChecked = Date.now();
741
+
742
+ //Create swap
743
+ const hodlInvoiceObj: HodlInvoiceInit = {
744
+ description: chainIdentifier+"-"+parsedBody.address,
745
+ cltvDelta: Number(this.config.minCltv) + 5,
746
+ expiresAt: Date.now()+(this.config.invoiceTimeoutSeconds*1000),
747
+ id: parsedBody.paymentHash,
748
+ mtokens: totalBtcInput * 1000n,
749
+ descriptionHash: parsedBody.descriptionHash
750
+ };
751
+ metadata.invoiceRequest = hodlInvoiceObj;
752
+
753
+ const hodlInvoice = await this.lightning.createHodlInvoice(hodlInvoiceObj);
754
+ abortController.signal.throwIfAborted();
755
+ metadata.times.invoiceCreated = Date.now();
756
+ metadata.invoiceResponse = {...hodlInvoice};
757
+
758
+ totalInGasToken -= parsedBody.claimerBounty;
759
+
760
+ const createdSwap = new FromBtcLnAutoSwap(
761
+ chainIdentifier,
762
+ hodlInvoice.request,
763
+ parsedBody.paymentHash,
764
+ swapContract.getHashForHtlc(Buffer.from(parsedBody.paymentHash, "hex")).toString("hex"),
765
+ hodlInvoice.mtokens,
766
+ parsedBody.address,
767
+ useToken,
768
+ gasToken,
769
+ totalInToken,
770
+ totalInGasToken,
771
+ swapFee,
772
+ swapFeeInToken,
773
+ gasSwapFee,
774
+ gasSwapFeeInToken,
775
+ parsedBody.claimerBounty
776
+ );
777
+ metadata.times.swapCreated = Date.now();
778
+
779
+ createdSwap.metadata = metadata;
780
+
781
+ await PluginManager.swapCreate(createdSwap);
782
+ await this.saveSwapData(createdSwap);
783
+
784
+ this.swapLogger.info(createdSwap, "REST: /createInvoice: Created swap invoice: "+hodlInvoice.request+" amount: "+totalBtcInput.toString(10));
785
+ this.subscribeToInvoice(createdSwap);
786
+
787
+ await responseStream.writeParamsAndEnd({
788
+ code: 20000,
789
+ msg: "Success",
790
+ data: {
791
+ intermediaryKey: signer.getAddress(),
792
+ pr: hodlInvoice.request,
793
+
794
+ btcAmountSwap: amountBD.toString(10),
795
+ btcAmountGas: amountBDgas.toString(10),
796
+
797
+ total: totalInToken.toString(10),
798
+ totalGas: totalInGasToken.toString(10),
799
+
800
+ totalFeeBtc: (swapFee + gasSwapFee).toString(10),
801
+
802
+ swapFeeBtc: swapFee.toString(10),
803
+ swapFee: swapFeeInToken.toString(10),
804
+
805
+ gasSwapFeeBtc: gasSwapFee.toString(10),
806
+ gasSwapFee: gasSwapFeeInToken.toString(10),
807
+
808
+ claimerBounty: parsedBody.claimerBounty.toString(10)
809
+ }
810
+ });
811
+
812
+ }));
813
+
814
+ const getInvoiceStatus = expressHandlerWrapper(async (req, res) => {
815
+ /**
816
+ * paymentHash: string payment hash of the invoice
817
+ */
818
+ const parsedBody = verifySchema({...req.body, ...req.query}, {
819
+ paymentHash: (val: string) => val!=null &&
820
+ typeof(val)==="string" &&
821
+ val.length===64 &&
822
+ HEX_REGEX.test(val) ? val: null,
823
+ });
824
+
825
+ await this.checkInvoiceStatus(parsedBody.paymentHash);
826
+
827
+ const swap: FromBtcLnAutoSwap = await this.storageManager.getData(parsedBody.paymentHash, null);
828
+ if (swap==null) throw {
829
+ _httpStatus: 200,
830
+ code: 10001,
831
+ msg: "Invoice expired/canceled"
832
+ };
833
+
834
+ if (
835
+ swap.state === FromBtcLnAutoSwapState.RECEIVED ||
836
+ swap.state === FromBtcLnAutoSwapState.TXS_SENT ||
837
+ swap.state === FromBtcLnAutoSwapState.COMMITED
838
+ ) {
839
+ res.status(200).json({
840
+ code: 10000,
841
+ msg: "Success",
842
+ data: {
843
+ data: swap.data.serialize()
844
+ }
845
+ });
846
+ } else {
847
+ res.status(200).json({
848
+ code: 10003,
849
+ msg: "Invoice yet unpaid"
850
+ });
851
+ }
852
+
853
+ });
854
+
855
+ restServer.post(this.path+"/getInvoiceStatus", getInvoiceStatus);
856
+ restServer.get(this.path+"/getInvoiceStatus", getInvoiceStatus);
857
+
858
+ this.logger.info("started at path: ", this.path);
859
+ }
860
+
861
+ async init() {
862
+ await this.loadData(FromBtcLnAutoSwap);
863
+ this.subscribeToEvents();
864
+ await PluginManager.serviceInitialize(this);
865
+ }
866
+
867
+ getInfoData(): any {
868
+ const mappedDict = {};
869
+ for(let chainId in this.config.gasTokenMax) {
870
+ mappedDict[chainId] = {
871
+ gasToken: this.getChain(chainId).chainInterface.getNativeCurrencyAddress(),
872
+ max: this.config.gasTokenMax[chainId].toString(10)
873
+ };
874
+ }
875
+ return {
876
+ minCltv: Number(this.config.minCltv),
877
+ invoiceTimeoutSeconds: this.config.invoiceTimeoutSeconds,
878
+ gasTokens: mappedDict
879
+ };
880
+ }
881
+
882
+ protected async removeSwapData(swap: FromBtcLnAutoSwap, ultimateState?: FromBtcLnAutoSwapState) {
883
+ this.swapsWithInflighHtlcs.delete(swap);
884
+ return super.removeSwapData(swap, ultimateState);
885
+ }
886
+
887
+ }
888
+