@atomiqlabs/lp-lib 14.0.0-dev.10 → 14.0.0-dev.12

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