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

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