@atomiqlabs/lp-lib 14.0.0-dev.6 → 14.0.0-dev.7

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