@atomiqlabs/lp-lib 16.1.0 → 16.1.2

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