@atomiqlabs/lp-lib 15.0.14 → 16.0.0

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