@atomiqlabs/lp-lib 14.0.0-dev.8 → 14.0.0-dev.9
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.
- package/dist/swaps/escrow/EscrowHandlerSwap.js +2 -2
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.d.ts +1 -0
- package/dist/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.js +3 -0
- package/package.json +1 -1
- package/src/swaps/escrow/EscrowHandlerSwap.ts +2 -2
- package/src/swaps/escrow/frombtcln_abstract/FromBtcLnSwapAbs.ts +4 -0
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoInit.d.ts +0 -101
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoInit.js +0 -601
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoInitSwap.d.ts +0 -54
- package/dist/swaps/escrow/frombtcln_autoinit/FromBtcLnAutoInitSwap.js +0 -117
- package/dist/wallets/ISpvVaultWallet.d.ts +0 -42
- package/dist/wallets/ISpvVaultWallet.js +0 -2
|
@@ -41,13 +41,13 @@ class EscrowHandlerSwap extends SwapHandlerSwap_1.SwapHandlerSwap {
|
|
|
41
41
|
* Returns the escrow hash - i.e. hash of the escrow data
|
|
42
42
|
*/
|
|
43
43
|
getEscrowHash() {
|
|
44
|
-
return this.data
|
|
44
|
+
return this.data?.getEscrowHash();
|
|
45
45
|
}
|
|
46
46
|
/**
|
|
47
47
|
* Returns the claim data hash - i.e. hash passed to the claim handler
|
|
48
48
|
*/
|
|
49
49
|
getClaimHash() {
|
|
50
|
-
return this.data
|
|
50
|
+
return this.data?.getClaimHash();
|
|
51
51
|
}
|
|
52
52
|
/**
|
|
53
53
|
* Returns the identification hash of the swap, usually claim data hash, but can be overriden, e.g. for
|
|
@@ -24,6 +24,7 @@ export declare class FromBtcLnSwapAbs<T extends SwapData = SwapData> extends Fro
|
|
|
24
24
|
serialize(): any;
|
|
25
25
|
getToken(): string;
|
|
26
26
|
getOutputAmount(): bigint;
|
|
27
|
+
getClaimHash(): string;
|
|
27
28
|
getIdentifierHash(): string;
|
|
28
29
|
getSequence(): bigint;
|
|
29
30
|
isInitiated(): boolean;
|
package/package.json
CHANGED
|
@@ -55,14 +55,14 @@ export abstract class EscrowHandlerSwap<T extends SwapData = SwapData, S = any>
|
|
|
55
55
|
* Returns the escrow hash - i.e. hash of the escrow data
|
|
56
56
|
*/
|
|
57
57
|
getEscrowHash(): string {
|
|
58
|
-
return this.data
|
|
58
|
+
return this.data?.getEscrowHash();
|
|
59
59
|
}
|
|
60
60
|
|
|
61
61
|
/**
|
|
62
62
|
* Returns the claim data hash - i.e. hash passed to the claim handler
|
|
63
63
|
*/
|
|
64
64
|
getClaimHash(): string {
|
|
65
|
-
return this.data
|
|
65
|
+
return this.data?.getClaimHash();
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
/**
|
|
@@ -114,6 +114,10 @@ export class FromBtcLnSwapAbs<T extends SwapData = SwapData> extends FromBtcBase
|
|
|
114
114
|
return this.totalTokens;
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
+
getClaimHash(): string {
|
|
118
|
+
return this.claimHash;
|
|
119
|
+
}
|
|
120
|
+
|
|
117
121
|
getIdentifierHash(): string {
|
|
118
122
|
return this.lnPaymentHash;
|
|
119
123
|
}
|
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
import { Express } from "express";
|
|
2
|
-
import { FromBtcLnAutoInitSwap, FromBtcLnAutoInitSwapState } from "./FromBtcLnAutoInitSwap";
|
|
3
|
-
import { MultichainData, SwapHandlerType } from "../../SwapHandler";
|
|
4
|
-
import { ISwapPrice } from "../../../prices/ISwapPrice";
|
|
5
|
-
import { ChainSwapType, ClaimEvent, InitializeEvent, RefundEvent, SwapData } from "@atomiqlabs/base";
|
|
6
|
-
import { IIntermediaryStorage } from "../../../storage/IIntermediaryStorage";
|
|
7
|
-
import { FromBtcBaseConfig, FromBtcBaseSwapHandler } from "../FromBtcBaseSwapHandler";
|
|
8
|
-
import { ILightningWallet } from "../../../wallets/ILightningWallet";
|
|
9
|
-
import { LightningAssertions } from "../../assertions/LightningAssertions";
|
|
10
|
-
export type FromBtcLnAutoInitConfig = FromBtcBaseConfig & {
|
|
11
|
-
invoiceTimeoutSeconds?: number;
|
|
12
|
-
minCltv: bigint;
|
|
13
|
-
gracePeriod: bigint;
|
|
14
|
-
};
|
|
15
|
-
export type FromBtcLnAutoInitRequestType = {
|
|
16
|
-
address: string;
|
|
17
|
-
paymentHash: string;
|
|
18
|
-
amount: bigint;
|
|
19
|
-
token: string;
|
|
20
|
-
gasToken: string;
|
|
21
|
-
gasAmount: bigint;
|
|
22
|
-
claimerBounty: bigint;
|
|
23
|
-
descriptionHash?: string;
|
|
24
|
-
exactOut?: boolean;
|
|
25
|
-
};
|
|
26
|
-
/**
|
|
27
|
-
* Swap handler handling from BTCLN swaps using submarine swaps
|
|
28
|
-
*/
|
|
29
|
-
export declare class FromBtcLnAutoInit extends FromBtcBaseSwapHandler<FromBtcLnAutoInitSwap, FromBtcLnAutoInitSwapState> {
|
|
30
|
-
readonly type = SwapHandlerType.FROM_BTCLN;
|
|
31
|
-
readonly swapType = ChainSwapType.HTLC;
|
|
32
|
-
readonly config: FromBtcLnAutoInitConfig;
|
|
33
|
-
readonly lightning: ILightningWallet;
|
|
34
|
-
readonly LightningAssertions: LightningAssertions;
|
|
35
|
-
constructor(storageDirectory: IIntermediaryStorage<FromBtcLnAutoInitSwap>, path: string, chains: MultichainData, lightning: ILightningWallet, swapPricing: ISwapPrice, config: FromBtcLnAutoInitConfig);
|
|
36
|
-
protected processPastSwap(swap: FromBtcLnAutoInitSwap): Promise<"REFUND" | "SETTLE" | null>;
|
|
37
|
-
protected refundSwaps(refundSwaps: FromBtcLnAutoInitSwap[]): Promise<void>;
|
|
38
|
-
protected settleInvoices(swaps: FromBtcLnAutoInitSwap[]): Promise<void>;
|
|
39
|
-
/**
|
|
40
|
-
* Checks past swaps, refunds and deletes ones that are already expired.
|
|
41
|
-
*/
|
|
42
|
-
protected processPastSwaps(): Promise<void>;
|
|
43
|
-
protected processInitializeEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoInitSwap, event: InitializeEvent<SwapData>): Promise<void>;
|
|
44
|
-
protected processClaimEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoInitSwap, event: ClaimEvent<SwapData>): Promise<void>;
|
|
45
|
-
protected processRefundEvent(chainIdentifier: string, savedSwap: FromBtcLnAutoInitSwap, event: RefundEvent<SwapData>): Promise<void>;
|
|
46
|
-
/**
|
|
47
|
-
* Called when lightning HTLC is received, also signs an init transaction on the smart chain side, expiry of the
|
|
48
|
-
* smart chain authorization starts ticking as soon as this HTLC is received
|
|
49
|
-
*
|
|
50
|
-
* @param invoiceData
|
|
51
|
-
* @param invoice
|
|
52
|
-
*/
|
|
53
|
-
private htlcReceived;
|
|
54
|
-
private offerHtlc;
|
|
55
|
-
/**
|
|
56
|
-
* Checks invoice description hash
|
|
57
|
-
*
|
|
58
|
-
* @param descriptionHash
|
|
59
|
-
* @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
|
|
60
|
-
*/
|
|
61
|
-
private checkDescriptionHash;
|
|
62
|
-
/**
|
|
63
|
-
* Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
|
|
64
|
-
*
|
|
65
|
-
* @param responseStream
|
|
66
|
-
*/
|
|
67
|
-
private sendPublicKeyAsync;
|
|
68
|
-
/**
|
|
69
|
-
* Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
|
|
70
|
-
* received (MPP) it returns the lowest of the timeouts
|
|
71
|
-
*
|
|
72
|
-
* @param invoice
|
|
73
|
-
*/
|
|
74
|
-
private getInvoicePaymentsTimeout;
|
|
75
|
-
/**
|
|
76
|
-
* Checks if the received HTLC's CLTV timeout is large enough to still process the swap
|
|
77
|
-
*
|
|
78
|
-
* @param invoice
|
|
79
|
-
* @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
|
|
80
|
-
* @returns expiry timeout in seconds
|
|
81
|
-
*/
|
|
82
|
-
private checkHtlcExpiry;
|
|
83
|
-
/**
|
|
84
|
-
* Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
|
|
85
|
-
*
|
|
86
|
-
* @param invoiceData
|
|
87
|
-
*/
|
|
88
|
-
private cancelSwapAndInvoice;
|
|
89
|
-
/**
|
|
90
|
-
*
|
|
91
|
-
* Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
|
|
92
|
-
*
|
|
93
|
-
* @param paymentHash
|
|
94
|
-
* @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
|
|
95
|
-
* @returns the fetched lightning invoice
|
|
96
|
-
*/
|
|
97
|
-
private checkInvoiceStatus;
|
|
98
|
-
startRestServer(restServer: Express): void;
|
|
99
|
-
init(): Promise<void>;
|
|
100
|
-
getInfoData(): any;
|
|
101
|
-
}
|
|
@@ -1,601 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.FromBtcLnAutoInit = void 0;
|
|
4
|
-
const crypto_1 = require("crypto");
|
|
5
|
-
const FromBtcLnAutoInitSwap_1 = require("./FromBtcLnAutoInitSwap");
|
|
6
|
-
const SwapHandler_1 = require("../../SwapHandler");
|
|
7
|
-
const base_1 = require("@atomiqlabs/base");
|
|
8
|
-
const Utils_1 = require("../../../utils/Utils");
|
|
9
|
-
const PluginManager_1 = require("../../../plugins/PluginManager");
|
|
10
|
-
const SchemaVerifier_1 = require("../../../utils/paramcoders/SchemaVerifier");
|
|
11
|
-
const ServerParamDecoder_1 = require("../../../utils/paramcoders/server/ServerParamDecoder");
|
|
12
|
-
const FromBtcBaseSwapHandler_1 = require("../FromBtcBaseSwapHandler");
|
|
13
|
-
const LightningAssertions_1 = require("../../assertions/LightningAssertions");
|
|
14
|
-
/**
|
|
15
|
-
* Swap handler handling from BTCLN swaps using submarine swaps
|
|
16
|
-
*/
|
|
17
|
-
class FromBtcLnAutoInit extends FromBtcBaseSwapHandler_1.FromBtcBaseSwapHandler {
|
|
18
|
-
constructor(storageDirectory, path, chains, lightning, swapPricing, config) {
|
|
19
|
-
super(storageDirectory, path, chains, swapPricing, config);
|
|
20
|
-
this.type = SwapHandler_1.SwapHandlerType.FROM_BTCLN;
|
|
21
|
-
this.swapType = base_1.ChainSwapType.HTLC;
|
|
22
|
-
this.config = config;
|
|
23
|
-
this.config.invoiceTimeoutSeconds = this.config.invoiceTimeoutSeconds || 90;
|
|
24
|
-
this.lightning = lightning;
|
|
25
|
-
this.LightningAssertions = new LightningAssertions_1.LightningAssertions(this.logger, lightning);
|
|
26
|
-
}
|
|
27
|
-
async processPastSwap(swap) {
|
|
28
|
-
const { swapContract, signer } = this.getChain(swap.chainIdentifier);
|
|
29
|
-
if (swap.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CREATED) {
|
|
30
|
-
//Check if already paid
|
|
31
|
-
const parsedPR = await this.lightning.parsePaymentRequest(swap.pr);
|
|
32
|
-
const invoice = await this.lightning.getInvoice(parsedPR.id);
|
|
33
|
-
const isBeingPaid = invoice.status === "held";
|
|
34
|
-
if (!isBeingPaid) {
|
|
35
|
-
//Not paid
|
|
36
|
-
const isInvoiceExpired = parsedPR.expiryEpochMillis < Date.now();
|
|
37
|
-
if (!isInvoiceExpired)
|
|
38
|
-
return null;
|
|
39
|
-
this.swapLogger.info(swap, "processPastSwap(state=CREATED): swap LN invoice expired, cancelling, invoice: " + swap.pr);
|
|
40
|
-
await this.cancelSwapAndInvoice(swap);
|
|
41
|
-
return null;
|
|
42
|
-
}
|
|
43
|
-
//Adjust the state of the swap and expiry
|
|
44
|
-
try {
|
|
45
|
-
await this.htlcReceived(swap, invoice);
|
|
46
|
-
//Result is either FromBtcLnSwapState.RECEIVED or FromBtcLnSwapState.CANCELED
|
|
47
|
-
}
|
|
48
|
-
catch (e) {
|
|
49
|
-
this.swapLogger.error(swap, "processPastSwap(state=CREATED): htlcReceived error", e);
|
|
50
|
-
}
|
|
51
|
-
return null;
|
|
52
|
-
}
|
|
53
|
-
if (swap.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.RECEIVED) {
|
|
54
|
-
//Adjust the state of the swap and expiry
|
|
55
|
-
try {
|
|
56
|
-
await this.offerHtlc(swap);
|
|
57
|
-
}
|
|
58
|
-
catch (e) {
|
|
59
|
-
this.swapLogger.error(swap, "processPastSwap(state=RECEIVED): offerHtlc error", e);
|
|
60
|
-
}
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
if (swap.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.TXS_SENT) {
|
|
64
|
-
const isAuthorizationExpired = await swapContract.isInitAuthorizationExpired(swap.data, swap);
|
|
65
|
-
if (isAuthorizationExpired) {
|
|
66
|
-
const isCommited = await swapContract.isCommited(swap.data);
|
|
67
|
-
if (!isCommited) {
|
|
68
|
-
this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT): swap not committed before authorization expiry, cancelling the LN invoice, invoice: " + swap.pr);
|
|
69
|
-
await this.cancelSwapAndInvoice(swap);
|
|
70
|
-
return null;
|
|
71
|
-
}
|
|
72
|
-
this.swapLogger.info(swap, "processPastSwap(state=TXS_SENT): swap committed (detected from processPastSwap), invoice: " + swap.pr);
|
|
73
|
-
await swap.setState(FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.COMMITED);
|
|
74
|
-
await this.saveSwapData(swap);
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
if (swap.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.TXS_SENT || swap.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.COMMITED) {
|
|
78
|
-
if (!await swapContract.isExpired(signer.getAddress(), swap.data))
|
|
79
|
-
return null;
|
|
80
|
-
const isCommited = await swapContract.isCommited(swap.data);
|
|
81
|
-
if (isCommited) {
|
|
82
|
-
this.swapLogger.info(swap, "processPastSwap(state=COMMITED): swap timed out, refunding to self, invoice: " + swap.pr);
|
|
83
|
-
return "REFUND";
|
|
84
|
-
}
|
|
85
|
-
this.swapLogger.info(swap, "processPastSwap(state=RECEIVED): swap timed out, cancelling the LN invoice, invoice: " + swap.pr);
|
|
86
|
-
await this.cancelSwapAndInvoice(swap);
|
|
87
|
-
return null;
|
|
88
|
-
}
|
|
89
|
-
if (swap.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CLAIMED)
|
|
90
|
-
return "SETTLE";
|
|
91
|
-
if (swap.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CANCELED)
|
|
92
|
-
await this.cancelSwapAndInvoice(swap);
|
|
93
|
-
}
|
|
94
|
-
async refundSwaps(refundSwaps) {
|
|
95
|
-
for (let refundSwap of refundSwaps) {
|
|
96
|
-
const { swapContract, signer } = this.getChain(refundSwap.chainIdentifier);
|
|
97
|
-
const unlock = refundSwap.lock(swapContract.refundTimeout);
|
|
98
|
-
if (unlock == null)
|
|
99
|
-
continue;
|
|
100
|
-
this.swapLogger.debug(refundSwap, "refundSwaps(): initiate refund of swap");
|
|
101
|
-
await swapContract.refund(signer, refundSwap.data, true, false, { waitForConfirmation: true });
|
|
102
|
-
this.swapLogger.info(refundSwap, "refundsSwaps(): swap refunded, invoice: " + refundSwap.pr);
|
|
103
|
-
await refundSwap.setState(FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.REFUNDED);
|
|
104
|
-
unlock();
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
async settleInvoices(swaps) {
|
|
108
|
-
for (let swap of swaps) {
|
|
109
|
-
try {
|
|
110
|
-
await this.lightning.settleHodlInvoice(swap.secret);
|
|
111
|
-
if (swap.metadata != null)
|
|
112
|
-
swap.metadata.times.htlcSettled = Date.now();
|
|
113
|
-
await this.removeSwapData(swap, FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.SETTLED);
|
|
114
|
-
this.swapLogger.info(swap, "settleInvoices(): invoice settled, secret: " + swap.secret);
|
|
115
|
-
}
|
|
116
|
-
catch (e) {
|
|
117
|
-
this.swapLogger.error(swap, "settleInvoices(): cannot settle invoice", e);
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Checks past swaps, refunds and deletes ones that are already expired.
|
|
123
|
-
*/
|
|
124
|
-
async processPastSwaps() {
|
|
125
|
-
const settleInvoices = [];
|
|
126
|
-
const refundSwaps = [];
|
|
127
|
-
const queriedData = await this.storageManager.query([
|
|
128
|
-
{
|
|
129
|
-
key: "state",
|
|
130
|
-
value: [
|
|
131
|
-
FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CREATED,
|
|
132
|
-
FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.RECEIVED,
|
|
133
|
-
FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.TXS_SENT,
|
|
134
|
-
FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.COMMITED,
|
|
135
|
-
FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CLAIMED,
|
|
136
|
-
FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CANCELED,
|
|
137
|
-
]
|
|
138
|
-
}
|
|
139
|
-
]);
|
|
140
|
-
for (let { obj: swap } of queriedData) {
|
|
141
|
-
switch (await this.processPastSwap(swap)) {
|
|
142
|
-
case "SETTLE":
|
|
143
|
-
settleInvoices.push(swap);
|
|
144
|
-
break;
|
|
145
|
-
case "REFUND":
|
|
146
|
-
refundSwaps.push(swap);
|
|
147
|
-
break;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
await this.refundSwaps(refundSwaps);
|
|
151
|
-
await this.settleInvoices(settleInvoices);
|
|
152
|
-
}
|
|
153
|
-
async processInitializeEvent(chainIdentifier, savedSwap, event) {
|
|
154
|
-
this.swapLogger.info(savedSwap, "SC: InitializeEvent: HTLC initialized by the client, invoice: " + savedSwap.pr);
|
|
155
|
-
if (savedSwap.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.TXS_SENT) {
|
|
156
|
-
await savedSwap.setState(FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.COMMITED);
|
|
157
|
-
await this.saveSwapData(savedSwap);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
async processClaimEvent(chainIdentifier, savedSwap, event) {
|
|
161
|
-
//Claim
|
|
162
|
-
//This is the important part, we need to catch the claim TX, else we may lose money
|
|
163
|
-
const secret = Buffer.from(event.result, "hex");
|
|
164
|
-
const paymentHash = (0, crypto_1.createHash)("sha256").update(secret).digest();
|
|
165
|
-
const secretHex = secret.toString("hex");
|
|
166
|
-
const paymentHashHex = paymentHash.toString("hex");
|
|
167
|
-
if (savedSwap.lnPaymentHash !== paymentHashHex)
|
|
168
|
-
return;
|
|
169
|
-
this.swapLogger.info(savedSwap, "SC: ClaimEvent: swap HTLC successfully claimed by the client, invoice: " + savedSwap.pr);
|
|
170
|
-
try {
|
|
171
|
-
await this.lightning.settleHodlInvoice(secretHex);
|
|
172
|
-
this.swapLogger.info(savedSwap, "SC: ClaimEvent: invoice settled, secret: " + secretHex);
|
|
173
|
-
savedSwap.secret = secretHex;
|
|
174
|
-
if (savedSwap.metadata != null)
|
|
175
|
-
savedSwap.metadata.times.htlcSettled = Date.now();
|
|
176
|
-
await this.removeSwapData(savedSwap, FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.SETTLED);
|
|
177
|
-
}
|
|
178
|
-
catch (e) {
|
|
179
|
-
this.swapLogger.error(savedSwap, "SC: ClaimEvent: cannot settle invoice", e);
|
|
180
|
-
savedSwap.secret = secretHex;
|
|
181
|
-
await savedSwap.setState(FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CLAIMED);
|
|
182
|
-
await this.saveSwapData(savedSwap);
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
async processRefundEvent(chainIdentifier, savedSwap, event) {
|
|
186
|
-
this.swapLogger.info(savedSwap, "SC: RefundEvent: swap refunded to us, invoice: " + savedSwap.pr);
|
|
187
|
-
//We don't cancel the incoming invoice, to make the offender pay for this with locked liquidity
|
|
188
|
-
// await this.lightning.cancelHodlInvoice(savedSwap.lnPaymentHash);
|
|
189
|
-
await this.removeSwapData(savedSwap, FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.REFUNDED);
|
|
190
|
-
}
|
|
191
|
-
/**
|
|
192
|
-
* Called when lightning HTLC is received, also signs an init transaction on the smart chain side, expiry of the
|
|
193
|
-
* smart chain authorization starts ticking as soon as this HTLC is received
|
|
194
|
-
*
|
|
195
|
-
* @param invoiceData
|
|
196
|
-
* @param invoice
|
|
197
|
-
*/
|
|
198
|
-
async htlcReceived(invoiceData, invoice) {
|
|
199
|
-
this.swapLogger.debug(invoiceData, "htlcReceived(): invoice: ", invoice);
|
|
200
|
-
if (invoiceData.metadata != null)
|
|
201
|
-
invoiceData.metadata.times.htlcReceived = Date.now();
|
|
202
|
-
const useToken = invoiceData.token;
|
|
203
|
-
const gasToken = invoiceData.gasToken;
|
|
204
|
-
let expiryTimeout;
|
|
205
|
-
try {
|
|
206
|
-
//Check if HTLC expiry is long enough
|
|
207
|
-
expiryTimeout = await this.checkHtlcExpiry(invoice);
|
|
208
|
-
if (invoiceData.metadata != null)
|
|
209
|
-
invoiceData.metadata.times.htlcTimeoutCalculated = Date.now();
|
|
210
|
-
}
|
|
211
|
-
catch (e) {
|
|
212
|
-
if (invoiceData.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CREATED)
|
|
213
|
-
await this.cancelSwapAndInvoice(invoiceData);
|
|
214
|
-
throw e;
|
|
215
|
-
}
|
|
216
|
-
const { swapContract, signer } = this.getChain(invoiceData.chainIdentifier);
|
|
217
|
-
//Create real swap data
|
|
218
|
-
const swapData = await swapContract.createSwapData(base_1.ChainSwapType.HTLC, signer.getAddress(), invoiceData.claimer, useToken, invoiceData.amountToken, invoiceData.claimHash, 0n, BigInt(Math.floor(Date.now() / 1000)) + expiryTimeout, false, true, invoiceData.amountGasToken + invoiceData.claimerBounty, invoiceData.claimerBounty, invoiceData.gasToken);
|
|
219
|
-
if (invoiceData.metadata != null)
|
|
220
|
-
invoiceData.metadata.times.htlcSwapCreated = Date.now();
|
|
221
|
-
//Important to prevent race condition and issuing 2 signed init messages at the same time
|
|
222
|
-
if (invoiceData.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CREATED) {
|
|
223
|
-
invoiceData.data = swapData;
|
|
224
|
-
invoiceData.signature = null;
|
|
225
|
-
invoiceData.timeout = (BigInt(Math.floor(Date.now() / 1000)) + 120n).toString(10);
|
|
226
|
-
//Setting the state variable is done outside the promise, so is done synchronously
|
|
227
|
-
await invoiceData.setState(FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.RECEIVED);
|
|
228
|
-
await this.saveSwapData(invoiceData);
|
|
229
|
-
}
|
|
230
|
-
await this.offerHtlc(invoiceData);
|
|
231
|
-
}
|
|
232
|
-
async offerHtlc(invoiceData) {
|
|
233
|
-
if (invoiceData.state !== FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.RECEIVED)
|
|
234
|
-
return;
|
|
235
|
-
this.swapLogger.debug(invoiceData, "offerHtlc(): invoice: ", invoiceData.pr);
|
|
236
|
-
if (invoiceData.metadata != null)
|
|
237
|
-
invoiceData.metadata.times.offerHtlc = Date.now();
|
|
238
|
-
const useToken = invoiceData.token;
|
|
239
|
-
const gasToken = invoiceData.gasToken;
|
|
240
|
-
const { swapContract, signer, chainInterface } = this.getChain(invoiceData.chainIdentifier);
|
|
241
|
-
//Create abort controller for parallel fetches
|
|
242
|
-
const abortController = new AbortController();
|
|
243
|
-
//Pre-fetch data
|
|
244
|
-
const balancePrefetch = this.getBalancePrefetch(invoiceData.chainIdentifier, useToken, abortController);
|
|
245
|
-
const gasTokenBalancePrefetch = invoiceData.getTotalOutputGasAmount() === 0n || useToken === gasToken ?
|
|
246
|
-
null : this.getBalancePrefetch(invoiceData.chainIdentifier, gasToken, abortController);
|
|
247
|
-
if (await swapContract.isInitAuthorizationExpired(invoiceData.data, invoiceData)) {
|
|
248
|
-
if (invoiceData.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.RECEIVED && !await swapContract.isCommited(invoiceData.data)) {
|
|
249
|
-
await this.cancelSwapAndInvoice(invoiceData);
|
|
250
|
-
}
|
|
251
|
-
return;
|
|
252
|
-
}
|
|
253
|
-
try {
|
|
254
|
-
//Check if we have enough liquidity to proceed
|
|
255
|
-
if (useToken === gasToken) {
|
|
256
|
-
await this.checkBalance(invoiceData.getTotalOutputAmount() + invoiceData.getTotalOutputGasAmount(), balancePrefetch, abortController.signal);
|
|
257
|
-
}
|
|
258
|
-
else {
|
|
259
|
-
await this.checkBalance(invoiceData.getTotalOutputAmount(), balancePrefetch, abortController.signal);
|
|
260
|
-
await this.checkBalance(invoiceData.getTotalOutputGasAmount(), gasTokenBalancePrefetch, abortController.signal);
|
|
261
|
-
}
|
|
262
|
-
if (invoiceData.metadata != null)
|
|
263
|
-
invoiceData.metadata.times.offerHtlcChecked = Date.now();
|
|
264
|
-
}
|
|
265
|
-
catch (e) {
|
|
266
|
-
if (!abortController.signal.aborted) {
|
|
267
|
-
if (invoiceData.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.RECEIVED)
|
|
268
|
-
await this.cancelSwapAndInvoice(invoiceData);
|
|
269
|
-
}
|
|
270
|
-
throw e;
|
|
271
|
-
}
|
|
272
|
-
const txWithdraw = await swapContract.txsWithdraw(signer.getAddress(), gasToken, invoiceData.data.getTotalDeposit());
|
|
273
|
-
const txInit = await swapContract.txsInit(signer.getAddress(), invoiceData.data, {
|
|
274
|
-
prefix: invoiceData.prefix,
|
|
275
|
-
timeout: invoiceData.timeout,
|
|
276
|
-
signature: invoiceData.signature
|
|
277
|
-
}, true);
|
|
278
|
-
if (invoiceData.state === FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.RECEIVED) {
|
|
279
|
-
//Setting the state variable is done outside the promise, so is done synchronously
|
|
280
|
-
await invoiceData.setState(FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.TXS_SENT);
|
|
281
|
-
await this.saveSwapData(invoiceData);
|
|
282
|
-
await chainInterface.sendAndConfirm(signer, [...txWithdraw, ...txInit], true);
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
/**
|
|
286
|
-
* Checks invoice description hash
|
|
287
|
-
*
|
|
288
|
-
* @param descriptionHash
|
|
289
|
-
* @throws {DefinedRuntimeError} will throw an error if the description hash is invalid
|
|
290
|
-
*/
|
|
291
|
-
checkDescriptionHash(descriptionHash) {
|
|
292
|
-
if (descriptionHash != null) {
|
|
293
|
-
if (typeof (descriptionHash) !== "string" || !Utils_1.HEX_REGEX.test(descriptionHash) || descriptionHash.length !== 64) {
|
|
294
|
-
throw {
|
|
295
|
-
code: 20100,
|
|
296
|
-
msg: "Invalid request body (descriptionHash)"
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
/**
|
|
302
|
-
* Asynchronously sends the LN node's public key to the client, so he can pre-fetch the node's channels from 1ml api
|
|
303
|
-
*
|
|
304
|
-
* @param responseStream
|
|
305
|
-
*/
|
|
306
|
-
sendPublicKeyAsync(responseStream) {
|
|
307
|
-
this.lightning.getIdentityPublicKey().then(publicKey => responseStream.writeParams({
|
|
308
|
-
lnPublicKey: publicKey
|
|
309
|
-
})).catch(e => {
|
|
310
|
-
this.logger.error("sendPublicKeyAsync(): error", e);
|
|
311
|
-
});
|
|
312
|
-
}
|
|
313
|
-
/**
|
|
314
|
-
* Returns the CLTV timeout (blockheight) of the received HTLC corresponding to the invoice. If multiple HTLCs are
|
|
315
|
-
* received (MPP) it returns the lowest of the timeouts
|
|
316
|
-
*
|
|
317
|
-
* @param invoice
|
|
318
|
-
*/
|
|
319
|
-
getInvoicePaymentsTimeout(invoice) {
|
|
320
|
-
let timeout = null;
|
|
321
|
-
invoice.payments.forEach((curr) => {
|
|
322
|
-
if (timeout == null || timeout > curr.timeout)
|
|
323
|
-
timeout = curr.timeout;
|
|
324
|
-
});
|
|
325
|
-
return timeout;
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Checks if the received HTLC's CLTV timeout is large enough to still process the swap
|
|
329
|
-
*
|
|
330
|
-
* @param invoice
|
|
331
|
-
* @throws {DefinedRuntimeError} Will throw if HTLC expires too soon and therefore cannot be processed
|
|
332
|
-
* @returns expiry timeout in seconds
|
|
333
|
-
*/
|
|
334
|
-
async checkHtlcExpiry(invoice) {
|
|
335
|
-
const timeout = this.getInvoicePaymentsTimeout(invoice);
|
|
336
|
-
const current_block_height = await this.lightning.getBlockheight();
|
|
337
|
-
const blockDelta = BigInt(timeout - current_block_height);
|
|
338
|
-
const htlcExpiresTooSoon = blockDelta < this.config.minCltv;
|
|
339
|
-
if (htlcExpiresTooSoon) {
|
|
340
|
-
throw {
|
|
341
|
-
code: 20002,
|
|
342
|
-
msg: "Not enough time to reliably process the swap",
|
|
343
|
-
data: {
|
|
344
|
-
requiredDelta: this.config.minCltv.toString(10),
|
|
345
|
-
actualDelta: blockDelta.toString(10)
|
|
346
|
-
}
|
|
347
|
-
};
|
|
348
|
-
}
|
|
349
|
-
return (this.config.minCltv * this.config.bitcoinBlocktime / this.config.safetyFactor) - this.config.gracePeriod;
|
|
350
|
-
}
|
|
351
|
-
/**
|
|
352
|
-
* Cancels the swap (CANCELED state) & also cancels the LN invoice (including all pending HTLCs)
|
|
353
|
-
*
|
|
354
|
-
* @param invoiceData
|
|
355
|
-
*/
|
|
356
|
-
async cancelSwapAndInvoice(invoiceData) {
|
|
357
|
-
if (invoiceData.state !== FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CREATED)
|
|
358
|
-
return;
|
|
359
|
-
await invoiceData.setState(FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwapState.CANCELED);
|
|
360
|
-
await this.lightning.cancelHodlInvoice(invoiceData.lnPaymentHash);
|
|
361
|
-
await this.removeSwapData(invoiceData);
|
|
362
|
-
this.swapLogger.info(invoiceData, "cancelSwapAndInvoice(): swap removed & invoice cancelled, invoice: ", invoiceData.pr);
|
|
363
|
-
}
|
|
364
|
-
;
|
|
365
|
-
/**
|
|
366
|
-
*
|
|
367
|
-
* Checks if the lightning invoice is in HELD state (htlcs received but yet unclaimed)
|
|
368
|
-
*
|
|
369
|
-
* @param paymentHash
|
|
370
|
-
* @throws {DefinedRuntimeError} Will throw if the lightning invoice is not found, or if it isn't in the HELD state
|
|
371
|
-
* @returns the fetched lightning invoice
|
|
372
|
-
*/
|
|
373
|
-
async checkInvoiceStatus(paymentHash) {
|
|
374
|
-
const invoice = await this.lightning.getInvoice(paymentHash);
|
|
375
|
-
if (invoice == null)
|
|
376
|
-
throw {
|
|
377
|
-
_httpStatus: 200,
|
|
378
|
-
code: 10001,
|
|
379
|
-
msg: "Invoice expired/canceled"
|
|
380
|
-
};
|
|
381
|
-
const arr = invoice.description.split("-");
|
|
382
|
-
let chainIdentifier;
|
|
383
|
-
let address;
|
|
384
|
-
if (arr.length > 1) {
|
|
385
|
-
chainIdentifier = arr[0];
|
|
386
|
-
address = arr[1];
|
|
387
|
-
}
|
|
388
|
-
else {
|
|
389
|
-
chainIdentifier = this.chains.default;
|
|
390
|
-
address = invoice.description;
|
|
391
|
-
}
|
|
392
|
-
const { chainInterface } = this.getChain(chainIdentifier);
|
|
393
|
-
if (!chainInterface.isValidAddress(address))
|
|
394
|
-
throw {
|
|
395
|
-
_httpStatus: 200,
|
|
396
|
-
code: 10001,
|
|
397
|
-
msg: "Invoice expired/canceled"
|
|
398
|
-
};
|
|
399
|
-
switch (invoice.status) {
|
|
400
|
-
case "canceled":
|
|
401
|
-
throw {
|
|
402
|
-
_httpStatus: 200,
|
|
403
|
-
code: 10001,
|
|
404
|
-
msg: "Invoice expired/canceled"
|
|
405
|
-
};
|
|
406
|
-
case "confirmed":
|
|
407
|
-
throw {
|
|
408
|
-
_httpStatus: 200,
|
|
409
|
-
code: 10002,
|
|
410
|
-
msg: "Invoice already paid"
|
|
411
|
-
};
|
|
412
|
-
case "unpaid":
|
|
413
|
-
throw {
|
|
414
|
-
_httpStatus: 200,
|
|
415
|
-
code: 10003,
|
|
416
|
-
msg: "Invoice yet unpaid"
|
|
417
|
-
};
|
|
418
|
-
default:
|
|
419
|
-
return invoice;
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
startRestServer(restServer) {
|
|
423
|
-
restServer.use(this.path + "/createInvoice", (0, ServerParamDecoder_1.serverParamDecoder)(10 * 1000));
|
|
424
|
-
restServer.post(this.path + "/createInvoice", (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
|
|
425
|
-
const metadata = { request: {}, times: {} };
|
|
426
|
-
const chainIdentifier = req.query.chain ?? this.chains.default;
|
|
427
|
-
const { swapContract, signer, chainInterface } = this.getChain(chainIdentifier);
|
|
428
|
-
if (!swapContract.supportsInitWithoutClaimer)
|
|
429
|
-
throw {
|
|
430
|
-
code: 20299,
|
|
431
|
-
msg: "Not supported for " + chainIdentifier
|
|
432
|
-
};
|
|
433
|
-
metadata.times.requestReceived = Date.now();
|
|
434
|
-
/**
|
|
435
|
-
* address: string smart chain address of the recipient
|
|
436
|
-
* paymentHash: string payment hash of the to-be-created invoice
|
|
437
|
-
* amount: string amount (in sats) of the invoice
|
|
438
|
-
* token: string Desired token to swap
|
|
439
|
-
* exactOut: boolean Whether the swap should be an exact out instead of exact in swap
|
|
440
|
-
* descriptionHash: string Description hash of the invoice
|
|
441
|
-
* gasAmount: string Desired amount in gas token to also get
|
|
442
|
-
* gasToken: string
|
|
443
|
-
* claimerBounty: string Desired amount to be left out as a claimer bounty
|
|
444
|
-
*/
|
|
445
|
-
const parsedBody = await req.paramReader.getParams({
|
|
446
|
-
address: (val) => val != null &&
|
|
447
|
-
typeof (val) === "string" &&
|
|
448
|
-
chainInterface.isValidAddress(val) ? val : null,
|
|
449
|
-
paymentHash: (val) => val != null &&
|
|
450
|
-
typeof (val) === "string" &&
|
|
451
|
-
val.length === 64 &&
|
|
452
|
-
Utils_1.HEX_REGEX.test(val) ? val : null,
|
|
453
|
-
amount: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
454
|
-
token: (val) => val != null &&
|
|
455
|
-
typeof (val) === "string" &&
|
|
456
|
-
this.isTokenSupported(chainIdentifier, val) ? val : null,
|
|
457
|
-
descriptionHash: SchemaVerifier_1.FieldTypeEnum.StringOptional,
|
|
458
|
-
exactOut: SchemaVerifier_1.FieldTypeEnum.BooleanOptional,
|
|
459
|
-
gasToken: (val) => val != null &&
|
|
460
|
-
typeof (val) === "string" &&
|
|
461
|
-
chainInterface.isValidToken(val) ? val : null,
|
|
462
|
-
gasAmount: SchemaVerifier_1.FieldTypeEnum.BigInt,
|
|
463
|
-
claimerBounty: SchemaVerifier_1.FieldTypeEnum.BigInt
|
|
464
|
-
});
|
|
465
|
-
if (parsedBody == null)
|
|
466
|
-
throw {
|
|
467
|
-
code: 20100,
|
|
468
|
-
msg: "Invalid request body"
|
|
469
|
-
};
|
|
470
|
-
if (parsedBody.gasToken !== chainInterface.getNativeCurrencyAddress())
|
|
471
|
-
throw {
|
|
472
|
-
code: 20290,
|
|
473
|
-
msg: "Unsupported gas token"
|
|
474
|
-
};
|
|
475
|
-
if (parsedBody.gasAmount < 0)
|
|
476
|
-
throw {
|
|
477
|
-
code: 20291,
|
|
478
|
-
msg: "Invalid gas amount, negative"
|
|
479
|
-
};
|
|
480
|
-
if (parsedBody.claimerBounty < 0)
|
|
481
|
-
throw {
|
|
482
|
-
code: 20292,
|
|
483
|
-
msg: "Invalid claimer bounty, negative"
|
|
484
|
-
};
|
|
485
|
-
metadata.request = parsedBody;
|
|
486
|
-
const requestedAmount = { input: !parsedBody.exactOut, amount: parsedBody.amount, token: parsedBody.token };
|
|
487
|
-
const gasTokenAmount = {
|
|
488
|
-
input: false,
|
|
489
|
-
amount: parsedBody.gasAmount + parsedBody.claimerBounty,
|
|
490
|
-
token: parsedBody.gasToken
|
|
491
|
-
};
|
|
492
|
-
const request = {
|
|
493
|
-
chainIdentifier,
|
|
494
|
-
raw: req,
|
|
495
|
-
parsed: parsedBody,
|
|
496
|
-
metadata
|
|
497
|
-
};
|
|
498
|
-
const useToken = parsedBody.token;
|
|
499
|
-
const gasToken = parsedBody.gasToken;
|
|
500
|
-
//Check request params
|
|
501
|
-
this.checkDescriptionHash(parsedBody.descriptionHash);
|
|
502
|
-
const fees = await this.AmountAssertions.preCheckFromBtcAmounts(this.type, request, requestedAmount, gasTokenAmount);
|
|
503
|
-
metadata.times.requestChecked = Date.now();
|
|
504
|
-
//Create abortController for parallel prefetches
|
|
505
|
-
const responseStream = res.responseStream;
|
|
506
|
-
const abortController = (0, Utils_1.getAbortController)(responseStream);
|
|
507
|
-
//Pre-fetch data
|
|
508
|
-
const { pricePrefetchPromise, gasTokenPricePrefetchPromise } = this.getFromBtcPricePrefetches(chainIdentifier, useToken, gasToken, abortController);
|
|
509
|
-
const balancePrefetch = this.getBalancePrefetch(chainIdentifier, useToken, abortController);
|
|
510
|
-
const gasTokenBalancePrefetch = gasTokenAmount.amount === 0n || useToken === gasToken ?
|
|
511
|
-
null : this.getBalancePrefetch(chainIdentifier, gasToken, abortController);
|
|
512
|
-
const channelsPrefetch = this.LightningAssertions.getChannelsPrefetch(abortController);
|
|
513
|
-
//Asynchronously send the node's public key to the client
|
|
514
|
-
this.sendPublicKeyAsync(responseStream);
|
|
515
|
-
//Check valid amount specified (min/max)
|
|
516
|
-
let { amountBD, swapFee, swapFeeInToken, totalInToken, amountBDgas, gasSwapFee, gasSwapFeeInToken, totalInGasToken } = await this.AmountAssertions.checkFromBtcAmount(this.type, request, { ...requestedAmount, pricePrefetch: pricePrefetchPromise }, fees, abortController.signal, { ...gasTokenAmount, pricePrefetch: gasTokenPricePrefetchPromise });
|
|
517
|
-
metadata.times.priceCalculated = Date.now();
|
|
518
|
-
const totalBtcInput = amountBD + amountBDgas;
|
|
519
|
-
//Check if we have enough funds to honor the request
|
|
520
|
-
if (useToken === gasToken) {
|
|
521
|
-
await this.checkBalance(totalInToken + totalInGasToken, balancePrefetch, abortController.signal);
|
|
522
|
-
}
|
|
523
|
-
else {
|
|
524
|
-
await this.checkBalance(totalInToken, balancePrefetch, abortController.signal);
|
|
525
|
-
await this.checkBalance(totalInGasToken, gasTokenBalancePrefetch, abortController.signal);
|
|
526
|
-
}
|
|
527
|
-
await this.LightningAssertions.checkInboundLiquidity(totalBtcInput, channelsPrefetch, abortController.signal);
|
|
528
|
-
metadata.times.balanceChecked = Date.now();
|
|
529
|
-
//Create swap
|
|
530
|
-
const hodlInvoiceObj = {
|
|
531
|
-
description: chainIdentifier + "-" + parsedBody.address,
|
|
532
|
-
cltvDelta: Number(this.config.minCltv) + 5,
|
|
533
|
-
expiresAt: Date.now() + (this.config.invoiceTimeoutSeconds * 1000),
|
|
534
|
-
id: parsedBody.paymentHash,
|
|
535
|
-
mtokens: totalBtcInput * 1000n,
|
|
536
|
-
descriptionHash: parsedBody.descriptionHash
|
|
537
|
-
};
|
|
538
|
-
metadata.invoiceRequest = hodlInvoiceObj;
|
|
539
|
-
const hodlInvoice = await this.lightning.createHodlInvoice(hodlInvoiceObj);
|
|
540
|
-
abortController.signal.throwIfAborted();
|
|
541
|
-
metadata.times.invoiceCreated = Date.now();
|
|
542
|
-
metadata.invoiceResponse = { ...hodlInvoice };
|
|
543
|
-
totalInGasToken -= parsedBody.claimerBounty;
|
|
544
|
-
const createdSwap = new FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwap(chainIdentifier, hodlInvoice.request, parsedBody.paymentHash, swapContract.getHashForHtlc(Buffer.from(parsedBody.paymentHash, "hex")).toString("hex"), hodlInvoice.mtokens, parsedBody.address, useToken, gasToken, totalInToken, totalInGasToken, swapFee, swapFeeInToken, gasSwapFee, gasSwapFeeInToken, parsedBody.claimerBounty);
|
|
545
|
-
metadata.times.swapCreated = Date.now();
|
|
546
|
-
createdSwap.metadata = metadata;
|
|
547
|
-
await PluginManager_1.PluginManager.swapCreate(createdSwap);
|
|
548
|
-
await this.saveSwapData(createdSwap);
|
|
549
|
-
this.swapLogger.info(createdSwap, "REST: /createInvoice: Created swap invoice: " + hodlInvoice.request + " amount: " + totalBtcInput.toString(10));
|
|
550
|
-
await responseStream.writeParamsAndEnd({
|
|
551
|
-
code: 20000,
|
|
552
|
-
msg: "Success",
|
|
553
|
-
data: {
|
|
554
|
-
intermediaryKey: signer.getAddress(),
|
|
555
|
-
pr: hodlInvoice.request,
|
|
556
|
-
btcAmountSwap: amountBD.toString(10),
|
|
557
|
-
btcAmountGas: amountBDgas.toString(10),
|
|
558
|
-
total: totalInToken.toString(10),
|
|
559
|
-
totalGas: totalInGasToken.toString(10),
|
|
560
|
-
totalFeeBtc: (swapFee + gasSwapFee).toString(10),
|
|
561
|
-
swapFeeBtc: swapFee.toString(10),
|
|
562
|
-
swapFee: swapFeeInToken.toString(10),
|
|
563
|
-
gasSwapFeeBtc: gasSwapFee.toString(10),
|
|
564
|
-
gasSwapFee: gasSwapFeeInToken.toString(10),
|
|
565
|
-
claimerBounty: parsedBody.claimerBounty.toString(10)
|
|
566
|
-
}
|
|
567
|
-
});
|
|
568
|
-
}));
|
|
569
|
-
const getInvoiceStatus = (0, Utils_1.expressHandlerWrapper)(async (req, res) => {
|
|
570
|
-
/**
|
|
571
|
-
* paymentHash: string payment hash of the invoice
|
|
572
|
-
*/
|
|
573
|
-
const parsedBody = (0, SchemaVerifier_1.verifySchema)({ ...req.body, ...req.query }, {
|
|
574
|
-
paymentHash: (val) => val != null &&
|
|
575
|
-
typeof (val) === "string" &&
|
|
576
|
-
val.length === 64 &&
|
|
577
|
-
Utils_1.HEX_REGEX.test(val) ? val : null,
|
|
578
|
-
});
|
|
579
|
-
await this.checkInvoiceStatus(parsedBody.paymentHash);
|
|
580
|
-
res.status(200).json({
|
|
581
|
-
code: 10000,
|
|
582
|
-
msg: "Success"
|
|
583
|
-
});
|
|
584
|
-
});
|
|
585
|
-
restServer.post(this.path + "/getInvoiceStatus", getInvoiceStatus);
|
|
586
|
-
restServer.get(this.path + "/getInvoiceStatus", getInvoiceStatus);
|
|
587
|
-
this.logger.info("started at path: ", this.path);
|
|
588
|
-
}
|
|
589
|
-
async init() {
|
|
590
|
-
await this.loadData(FromBtcLnAutoInitSwap_1.FromBtcLnAutoInitSwap);
|
|
591
|
-
this.subscribeToEvents();
|
|
592
|
-
await PluginManager_1.PluginManager.serviceInitialize(this);
|
|
593
|
-
}
|
|
594
|
-
getInfoData() {
|
|
595
|
-
return {
|
|
596
|
-
minCltv: Number(this.config.minCltv),
|
|
597
|
-
invoiceTimeoutSeconds: this.config.invoiceTimeoutSeconds
|
|
598
|
-
};
|
|
599
|
-
}
|
|
600
|
-
}
|
|
601
|
-
exports.FromBtcLnAutoInit = FromBtcLnAutoInit;
|
|
@@ -1,54 +0,0 @@
|
|
|
1
|
-
import { SwapData } from "@atomiqlabs/base";
|
|
2
|
-
import { FromBtcBaseSwap } from "../FromBtcBaseSwap";
|
|
3
|
-
export declare enum FromBtcLnAutoInitSwapState {
|
|
4
|
-
REFUNDED = -2,
|
|
5
|
-
CANCELED = -1,
|
|
6
|
-
CREATED = 0,
|
|
7
|
-
RECEIVED = 1,
|
|
8
|
-
TXS_SENT = 2,
|
|
9
|
-
COMMITED = 3,
|
|
10
|
-
CLAIMED = 4,
|
|
11
|
-
SETTLED = 5
|
|
12
|
-
}
|
|
13
|
-
export declare class FromBtcLnAutoInitSwap<T extends SwapData = SwapData> extends FromBtcBaseSwap<T, FromBtcLnAutoInitSwapState> {
|
|
14
|
-
readonly pr: string;
|
|
15
|
-
readonly lnPaymentHash: string;
|
|
16
|
-
readonly claimHash: string;
|
|
17
|
-
readonly claimer: string;
|
|
18
|
-
readonly token: string;
|
|
19
|
-
readonly gasToken: string;
|
|
20
|
-
readonly amountToken: bigint;
|
|
21
|
-
readonly amountGasToken: bigint;
|
|
22
|
-
readonly tokenSwapFee: bigint;
|
|
23
|
-
readonly tokenSwapFeeInToken: bigint;
|
|
24
|
-
readonly gasSwapFee: bigint;
|
|
25
|
-
readonly gasSwapFeeInToken: bigint;
|
|
26
|
-
readonly claimerBounty: bigint;
|
|
27
|
-
secret: string;
|
|
28
|
-
constructor(chainIdentifier: string, pr: string, lnPaymentHash: string, claimHash: string, amountMtokens: bigint, claimer: string, token: string, gasToken: string, amountToken: bigint, amountGasToken: bigint, tokenSwapFee: bigint, tokenSwapFeeInToken: bigint, gasSwapFee: bigint, gasSwapFeeInToken: bigint, claimerBounty: bigint);
|
|
29
|
-
constructor(obj: any);
|
|
30
|
-
serialize(): any;
|
|
31
|
-
getIdentifierHash(): string;
|
|
32
|
-
getOutputGasAmount(): bigint;
|
|
33
|
-
getOutputAmount(): bigint;
|
|
34
|
-
getTotalOutputAmount(): bigint;
|
|
35
|
-
getTotalOutputGasAmount(): bigint;
|
|
36
|
-
getSequence(): bigint;
|
|
37
|
-
getSwapFee(): {
|
|
38
|
-
inInputToken: bigint;
|
|
39
|
-
inOutputToken: bigint;
|
|
40
|
-
};
|
|
41
|
-
getTokenSwapFee(): {
|
|
42
|
-
inInputToken: bigint;
|
|
43
|
-
inOutputToken: bigint;
|
|
44
|
-
};
|
|
45
|
-
getGasSwapFee(): {
|
|
46
|
-
inInputToken: bigint;
|
|
47
|
-
inOutputToken: bigint;
|
|
48
|
-
};
|
|
49
|
-
getToken(): string;
|
|
50
|
-
getGasToken(): string;
|
|
51
|
-
isInitiated(): boolean;
|
|
52
|
-
isFailed(): boolean;
|
|
53
|
-
isSuccess(): boolean;
|
|
54
|
-
}
|
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.FromBtcLnAutoInitSwap = exports.FromBtcLnAutoInitSwapState = void 0;
|
|
4
|
-
const index_1 = require("../../../index");
|
|
5
|
-
const FromBtcBaseSwap_1 = require("../FromBtcBaseSwap");
|
|
6
|
-
const Utils_1 = require("../../../utils/Utils");
|
|
7
|
-
var FromBtcLnAutoInitSwapState;
|
|
8
|
-
(function (FromBtcLnAutoInitSwapState) {
|
|
9
|
-
FromBtcLnAutoInitSwapState[FromBtcLnAutoInitSwapState["REFUNDED"] = -2] = "REFUNDED";
|
|
10
|
-
FromBtcLnAutoInitSwapState[FromBtcLnAutoInitSwapState["CANCELED"] = -1] = "CANCELED";
|
|
11
|
-
FromBtcLnAutoInitSwapState[FromBtcLnAutoInitSwapState["CREATED"] = 0] = "CREATED";
|
|
12
|
-
FromBtcLnAutoInitSwapState[FromBtcLnAutoInitSwapState["RECEIVED"] = 1] = "RECEIVED";
|
|
13
|
-
FromBtcLnAutoInitSwapState[FromBtcLnAutoInitSwapState["TXS_SENT"] = 2] = "TXS_SENT";
|
|
14
|
-
FromBtcLnAutoInitSwapState[FromBtcLnAutoInitSwapState["COMMITED"] = 3] = "COMMITED";
|
|
15
|
-
FromBtcLnAutoInitSwapState[FromBtcLnAutoInitSwapState["CLAIMED"] = 4] = "CLAIMED";
|
|
16
|
-
FromBtcLnAutoInitSwapState[FromBtcLnAutoInitSwapState["SETTLED"] = 5] = "SETTLED";
|
|
17
|
-
})(FromBtcLnAutoInitSwapState = exports.FromBtcLnAutoInitSwapState || (exports.FromBtcLnAutoInitSwapState = {}));
|
|
18
|
-
class FromBtcLnAutoInitSwap extends FromBtcBaseSwap_1.FromBtcBaseSwap {
|
|
19
|
-
constructor(chainIdOrObj, pr, lnPaymentHash, claimHash, amountMtokens, claimer, token, gasToken, amountToken, amountGasToken, tokenSwapFee, tokenSwapFeeInToken, gasSwapFee, gasSwapFeeInToken, claimerBounty) {
|
|
20
|
-
if (typeof (chainIdOrObj) === "string") {
|
|
21
|
-
super(chainIdOrObj, (amountMtokens + 999n) / 1000n, tokenSwapFee + gasSwapFee, tokenSwapFeeInToken);
|
|
22
|
-
this.state = FromBtcLnAutoInitSwapState.CREATED;
|
|
23
|
-
this.pr = pr;
|
|
24
|
-
this.lnPaymentHash = lnPaymentHash;
|
|
25
|
-
this.claimHash = claimHash;
|
|
26
|
-
this.claimer = claimer;
|
|
27
|
-
this.token = token;
|
|
28
|
-
this.gasToken = gasToken;
|
|
29
|
-
this.amountToken = amountToken;
|
|
30
|
-
this.amountGasToken = amountGasToken;
|
|
31
|
-
this.tokenSwapFee = tokenSwapFee;
|
|
32
|
-
this.tokenSwapFeeInToken = tokenSwapFeeInToken;
|
|
33
|
-
this.gasSwapFee = gasSwapFee;
|
|
34
|
-
this.gasSwapFeeInToken = gasSwapFeeInToken;
|
|
35
|
-
this.claimerBounty = claimerBounty;
|
|
36
|
-
}
|
|
37
|
-
else {
|
|
38
|
-
super(chainIdOrObj);
|
|
39
|
-
this.pr = chainIdOrObj.pr;
|
|
40
|
-
this.lnPaymentHash = chainIdOrObj.lnPaymentHash;
|
|
41
|
-
this.claimHash = chainIdOrObj.claimHash;
|
|
42
|
-
this.claimer = chainIdOrObj.claimer;
|
|
43
|
-
this.token = chainIdOrObj.token;
|
|
44
|
-
this.gasToken = chainIdOrObj.gasToken;
|
|
45
|
-
this.amountToken = (0, Utils_1.deserializeBN)(chainIdOrObj.amountToken);
|
|
46
|
-
this.amountGasToken = (0, Utils_1.deserializeBN)(chainIdOrObj.amountGasToken);
|
|
47
|
-
this.tokenSwapFee = (0, Utils_1.deserializeBN)(chainIdOrObj.tokenSwapFee);
|
|
48
|
-
this.tokenSwapFeeInToken = (0, Utils_1.deserializeBN)(chainIdOrObj.tokenSwapFeeInToken);
|
|
49
|
-
this.gasSwapFee = (0, Utils_1.deserializeBN)(chainIdOrObj.gasSwapFee);
|
|
50
|
-
this.gasSwapFeeInToken = (0, Utils_1.deserializeBN)(chainIdOrObj.gasSwapFeeInToken);
|
|
51
|
-
this.claimerBounty = (0, Utils_1.deserializeBN)(chainIdOrObj.claimerBounty);
|
|
52
|
-
this.secret = chainIdOrObj.secret;
|
|
53
|
-
}
|
|
54
|
-
this.type = index_1.SwapHandlerType.FROM_BTCLN;
|
|
55
|
-
}
|
|
56
|
-
serialize() {
|
|
57
|
-
const partialSerialized = super.serialize();
|
|
58
|
-
partialSerialized.pr = this.pr;
|
|
59
|
-
partialSerialized.secret = this.secret;
|
|
60
|
-
partialSerialized.lnPaymentHash = this.lnPaymentHash;
|
|
61
|
-
partialSerialized.claimHash = this.claimHash;
|
|
62
|
-
partialSerialized.claimer = this.claimer;
|
|
63
|
-
partialSerialized.token = this.token;
|
|
64
|
-
partialSerialized.gasToken = this.gasToken;
|
|
65
|
-
partialSerialized.amountToken = (0, Utils_1.serializeBN)(this.amountToken);
|
|
66
|
-
partialSerialized.amountGasToken = (0, Utils_1.serializeBN)(this.amountGasToken);
|
|
67
|
-
partialSerialized.tokenSwapFee = (0, Utils_1.serializeBN)(this.tokenSwapFee);
|
|
68
|
-
partialSerialized.tokenSwapFeeInToken = (0, Utils_1.serializeBN)(this.tokenSwapFeeInToken);
|
|
69
|
-
partialSerialized.gasSwapFee = (0, Utils_1.serializeBN)(this.gasSwapFee);
|
|
70
|
-
partialSerialized.gasSwapFeeInToken = (0, Utils_1.serializeBN)(this.gasSwapFeeInToken);
|
|
71
|
-
partialSerialized.claimerBounty = (0, Utils_1.serializeBN)(this.claimerBounty);
|
|
72
|
-
return partialSerialized;
|
|
73
|
-
}
|
|
74
|
-
getIdentifierHash() {
|
|
75
|
-
return this.lnPaymentHash;
|
|
76
|
-
}
|
|
77
|
-
getOutputGasAmount() {
|
|
78
|
-
return this.amountGasToken;
|
|
79
|
-
}
|
|
80
|
-
getOutputAmount() {
|
|
81
|
-
return this.amountToken;
|
|
82
|
-
}
|
|
83
|
-
getTotalOutputAmount() {
|
|
84
|
-
return this.amountToken;
|
|
85
|
-
}
|
|
86
|
-
getTotalOutputGasAmount() {
|
|
87
|
-
return this.amountGasToken + this.claimerBounty;
|
|
88
|
-
}
|
|
89
|
-
getSequence() {
|
|
90
|
-
return 0n;
|
|
91
|
-
}
|
|
92
|
-
getSwapFee() {
|
|
93
|
-
return { inInputToken: this.swapFee, inOutputToken: this.swapFeeInToken };
|
|
94
|
-
}
|
|
95
|
-
getTokenSwapFee() {
|
|
96
|
-
return { inInputToken: this.tokenSwapFee, inOutputToken: this.tokenSwapFeeInToken };
|
|
97
|
-
}
|
|
98
|
-
getGasSwapFee() {
|
|
99
|
-
return { inInputToken: this.gasSwapFee, inOutputToken: this.gasSwapFeeInToken };
|
|
100
|
-
}
|
|
101
|
-
getToken() {
|
|
102
|
-
return this.token;
|
|
103
|
-
}
|
|
104
|
-
getGasToken() {
|
|
105
|
-
return this.gasToken;
|
|
106
|
-
}
|
|
107
|
-
isInitiated() {
|
|
108
|
-
return this.state !== FromBtcLnAutoInitSwapState.CREATED;
|
|
109
|
-
}
|
|
110
|
-
isFailed() {
|
|
111
|
-
return this.state === FromBtcLnAutoInitSwapState.CANCELED || this.state === FromBtcLnAutoInitSwapState.REFUNDED;
|
|
112
|
-
}
|
|
113
|
-
isSuccess() {
|
|
114
|
-
return this.state === FromBtcLnAutoInitSwapState.SETTLED;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
exports.FromBtcLnAutoInitSwap = FromBtcLnAutoInitSwap;
|
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
|
-
import { Command } from "@atomiqlabs/server-base";
|
|
3
|
-
import { Transaction } from "@scure/btc-signer";
|
|
4
|
-
export type BitcoinUtxo = {
|
|
5
|
-
address: string;
|
|
6
|
-
type: "p2wpkh" | "p2sh-p2wpkh" | "p2tr";
|
|
7
|
-
confirmations: number;
|
|
8
|
-
outputScript: Buffer;
|
|
9
|
-
value: number;
|
|
10
|
-
txId: string;
|
|
11
|
-
vout: number;
|
|
12
|
-
};
|
|
13
|
-
export type SignPsbtResponse = {
|
|
14
|
-
psbt: Transaction;
|
|
15
|
-
tx: Transaction;
|
|
16
|
-
raw: string;
|
|
17
|
-
txId: string;
|
|
18
|
-
networkFee: number;
|
|
19
|
-
};
|
|
20
|
-
export interface ISpvVaultSigner {
|
|
21
|
-
init(): Promise<void>;
|
|
22
|
-
isReady(): boolean;
|
|
23
|
-
getStatus(): string;
|
|
24
|
-
getStatusInfo(): Promise<Record<string, string>>;
|
|
25
|
-
getCommands(): Command<any>[];
|
|
26
|
-
getAddressType(): "p2wpkh" | "p2sh-p2wpkh" | "p2tr";
|
|
27
|
-
/**
|
|
28
|
-
* Returns an unused address suitable for receiving
|
|
29
|
-
*/
|
|
30
|
-
getAddress(vaultId: bigint): Promise<string>;
|
|
31
|
-
signPsbt(vaultId: bigint, psbt: Transaction): Promise<SignPsbtResponse>;
|
|
32
|
-
sendRawTransaction(tx: string): Promise<void>;
|
|
33
|
-
getSignedTransaction(destination: string, amount: number, feeRate?: number, nonce?: bigint, maxAllowedFeeRate?: number): Promise<SignPsbtResponse>;
|
|
34
|
-
estimateFee(destination: string, amount: number, feeRate?: number, feeRateMultiplier?: number): Promise<{
|
|
35
|
-
satsPerVbyte: number;
|
|
36
|
-
networkFee: number;
|
|
37
|
-
}>;
|
|
38
|
-
drainAll(destination: string | Buffer, inputs: Omit<BitcoinUtxo, "address">[], feeRate?: number): Promise<SignPsbtResponse>;
|
|
39
|
-
burnAll(inputs: Omit<BitcoinUtxo, "address">[]): Promise<SignPsbtResponse>;
|
|
40
|
-
getBlockheight(): Promise<number>;
|
|
41
|
-
getFeeRate(): Promise<number>;
|
|
42
|
-
}
|