@atomiqlabs/lp-lib 17.5.1 → 17.5.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 (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 -730
  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 -710
  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 -892
  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 -897
  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,892 +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
- 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
-
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
+