@atomiqlabs/lp-lib 17.4.1 → 17.5.1

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