@atomiqlabs/sdk 8.6.6 → 8.6.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.
- package/dist/SmartChainAssets.d.ts +181 -181
- package/dist/SmartChainAssets.js +181 -181
- package/dist/bitcoin/coinselect2/accumulative.d.ts +6 -6
- package/dist/bitcoin/coinselect2/accumulative.js +52 -51
- package/dist/bitcoin/coinselect2/blackjack.d.ts +6 -6
- package/dist/bitcoin/coinselect2/blackjack.js +38 -37
- package/dist/bitcoin/coinselect2/index.d.ts +19 -17
- package/dist/bitcoin/coinselect2/index.js +69 -69
- package/dist/bitcoin/coinselect2/utils.d.ts +77 -75
- package/dist/bitcoin/coinselect2/utils.js +123 -123
- package/dist/bitcoin/wallet/BitcoinWallet.d.ts +130 -128
- package/dist/bitcoin/wallet/BitcoinWallet.js +322 -322
- package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +78 -78
- package/dist/bitcoin/wallet/IBitcoinWallet.js +21 -20
- package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +101 -99
- package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +176 -176
- package/dist/enums/FeeType.d.ts +15 -15
- package/dist/enums/FeeType.js +19 -19
- package/dist/enums/SwapAmountType.d.ts +15 -15
- package/dist/enums/SwapAmountType.js +19 -19
- package/dist/enums/SwapDirection.d.ts +15 -15
- package/dist/enums/SwapDirection.js +19 -19
- package/dist/enums/SwapSide.d.ts +15 -15
- package/dist/enums/SwapSide.js +19 -19
- package/dist/enums/SwapType.d.ts +75 -75
- package/dist/enums/SwapType.js +79 -79
- package/dist/errors/IntermediaryError.d.ts +13 -13
- package/dist/errors/IntermediaryError.js +27 -27
- package/dist/errors/RequestError.d.ts +32 -32
- package/dist/errors/RequestError.js +54 -54
- package/dist/errors/UserError.d.ts +8 -8
- package/dist/errors/UserError.js +16 -16
- package/dist/events/UnifiedSwapEventListener.d.ts +23 -23
- package/dist/events/UnifiedSwapEventListener.js +130 -130
- package/dist/http/HttpUtils.d.ts +27 -27
- package/dist/http/HttpUtils.js +91 -90
- package/dist/http/paramcoders/IParamReader.d.ts +8 -8
- package/dist/http/paramcoders/IParamReader.js +2 -2
- package/dist/http/paramcoders/ParamDecoder.d.ts +44 -42
- package/dist/http/paramcoders/ParamDecoder.js +137 -137
- package/dist/http/paramcoders/ParamEncoder.d.ts +20 -18
- package/dist/http/paramcoders/ParamEncoder.js +36 -36
- package/dist/http/paramcoders/SchemaVerifier.d.ts +26 -26
- package/dist/http/paramcoders/SchemaVerifier.js +145 -145
- package/dist/http/paramcoders/client/ResponseParamDecoder.d.ts +11 -11
- package/dist/http/paramcoders/client/ResponseParamDecoder.js +57 -57
- package/dist/http/paramcoders/client/StreamParamEncoder.d.ts +13 -11
- package/dist/http/paramcoders/client/StreamParamEncoder.js +26 -26
- package/dist/http/paramcoders/client/StreamingFetchPromise.d.ts +16 -16
- package/dist/http/paramcoders/client/StreamingFetchPromise.js +174 -173
- package/dist/index.d.ts +85 -85
- package/dist/index.js +158 -158
- package/dist/intermediaries/Intermediary.d.ts +157 -157
- package/dist/intermediaries/Intermediary.js +142 -142
- package/dist/intermediaries/IntermediaryDiscovery.d.ts +199 -198
- package/dist/intermediaries/IntermediaryDiscovery.js +406 -406
- package/dist/intermediaries/apis/IntermediaryAPI.d.ts +439 -437
- package/dist/intermediaries/apis/IntermediaryAPI.js +603 -603
- package/dist/intermediaries/apis/TrustedIntermediaryAPI.d.ts +155 -155
- package/dist/intermediaries/apis/TrustedIntermediaryAPI.js +137 -137
- package/dist/lnurl/LNURL.d.ts +102 -102
- package/dist/lnurl/LNURL.js +321 -321
- package/dist/prices/RedundantSwapPrice.d.ts +110 -110
- package/dist/prices/RedundantSwapPrice.js +222 -222
- package/dist/prices/SingleSwapPrice.d.ts +34 -34
- package/dist/prices/SingleSwapPrice.js +44 -44
- package/dist/prices/SwapPriceWithChain.d.ts +107 -107
- package/dist/prices/SwapPriceWithChain.js +128 -128
- package/dist/prices/abstract/ICachedSwapPrice.d.ts +28 -28
- package/dist/prices/abstract/ICachedSwapPrice.js +62 -62
- package/dist/prices/abstract/IPriceProvider.d.ts +81 -81
- package/dist/prices/abstract/IPriceProvider.js +74 -74
- package/dist/prices/abstract/ISwapPrice.d.ts +168 -168
- package/dist/prices/abstract/ISwapPrice.js +279 -279
- package/dist/prices/providers/BinancePriceProvider.d.ts +23 -23
- package/dist/prices/providers/BinancePriceProvider.js +30 -30
- package/dist/prices/providers/CoinGeckoPriceProvider.d.ts +23 -23
- package/dist/prices/providers/CoinGeckoPriceProvider.js +29 -29
- package/dist/prices/providers/CoinPaprikaPriceProvider.d.ts +25 -25
- package/dist/prices/providers/CoinPaprikaPriceProvider.js +29 -29
- package/dist/prices/providers/CustomPriceProvider.d.ts +24 -24
- package/dist/prices/providers/CustomPriceProvider.js +35 -35
- package/dist/prices/providers/KrakenPriceProvider.d.ts +38 -38
- package/dist/prices/providers/KrakenPriceProvider.js +45 -45
- package/dist/prices/providers/OKXPriceProvider.d.ts +34 -34
- package/dist/prices/providers/OKXPriceProvider.js +29 -29
- package/dist/prices/providers/abstract/ExchangePriceProvider.d.ts +17 -17
- package/dist/prices/providers/abstract/ExchangePriceProvider.js +21 -21
- package/dist/prices/providers/abstract/HttpPriceProvider.d.ts +7 -7
- package/dist/prices/providers/abstract/HttpPriceProvider.js +12 -12
- package/dist/storage/IUnifiedStorage.d.ts +85 -85
- package/dist/storage/IUnifiedStorage.js +2 -2
- package/dist/storage/UnifiedSwapStorage.d.ts +114 -114
- package/dist/storage/UnifiedSwapStorage.js +116 -116
- package/dist/storage-browser/IndexedDBUnifiedStorage.d.ts +63 -63
- package/dist/storage-browser/IndexedDBUnifiedStorage.js +298 -298
- package/dist/storage-browser/LocalStorageManager.d.ts +49 -49
- package/dist/storage-browser/LocalStorageManager.js +93 -93
- package/dist/swapper/Swapper.d.ts +687 -686
- package/dist/swapper/Swapper.js +1603 -1603
- package/dist/swapper/SwapperFactory.d.ts +135 -135
- package/dist/swapper/SwapperFactory.js +162 -162
- package/dist/swapper/SwapperUtils.d.ts +200 -200
- package/dist/swapper/SwapperUtils.js +467 -467
- package/dist/swapper/SwapperWithChain.d.ts +404 -404
- package/dist/swapper/SwapperWithChain.js +469 -469
- package/dist/swapper/SwapperWithSigner.d.ts +322 -322
- package/dist/swapper/SwapperWithSigner.js +318 -318
- package/dist/swaps/IAddressSwap.d.ts +22 -22
- package/dist/swaps/IAddressSwap.js +14 -13
- package/dist/swaps/IBTCWalletSwap.d.ts +73 -73
- package/dist/swaps/IBTCWalletSwap.js +18 -17
- package/dist/swaps/IClaimableSwap.d.ts +49 -49
- package/dist/swaps/IClaimableSwap.js +15 -14
- package/dist/swaps/IClaimableSwapWrapper.d.ts +15 -15
- package/dist/swaps/IClaimableSwapWrapper.js +2 -2
- package/dist/swaps/IRefundableSwap.d.ts +43 -43
- package/dist/swaps/IRefundableSwap.js +14 -13
- package/dist/swaps/ISwap.d.ts +387 -386
- package/dist/swaps/ISwap.js +346 -346
- package/dist/swaps/ISwapWithGasDrop.d.ts +21 -21
- package/dist/swaps/ISwapWithGasDrop.js +12 -11
- package/dist/swaps/ISwapWrapper.d.ts +285 -283
- package/dist/swaps/ISwapWrapper.js +353 -353
- package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.d.ts +98 -98
- package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.js +126 -126
- package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +135 -133
- package/dist/swaps/escrow_swaps/IEscrowSwap.js +169 -169
- package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +115 -114
- package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +134 -134
- package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +101 -98
- package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +130 -130
- package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +162 -162
- package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +190 -190
- package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.d.ts +58 -58
- package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.js +78 -78
- package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +531 -529
- package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +1285 -1285
- package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +184 -181
- package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +418 -418
- package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +583 -581
- package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +1371 -1371
- package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +228 -225
- package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +506 -506
- package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +458 -458
- package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +1126 -1126
- package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +191 -190
- package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +378 -378
- package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +403 -403
- package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +924 -924
- package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.d.ts +62 -62
- package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +112 -112
- package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.d.ts +127 -125
- package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +256 -256
- package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +242 -241
- package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +520 -520
- package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.d.ts +73 -73
- package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.js +155 -155
- package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +128 -127
- package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +278 -278
- package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +630 -630
- package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +1443 -1443
- package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +214 -213
- package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +756 -756
- package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +261 -261
- package/dist/swaps/trusted/ln/LnForGasSwap.js +511 -511
- package/dist/swaps/trusted/ln/LnForGasWrapper.d.ts +40 -40
- package/dist/swaps/trusted/ln/LnForGasWrapper.js +82 -82
- package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +342 -342
- package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +715 -715
- package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +69 -68
- package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +92 -92
- package/dist/types/AmountData.d.ts +10 -10
- package/dist/types/AmountData.js +2 -2
- package/dist/types/CustomPriceFunction.d.ts +11 -11
- package/dist/types/CustomPriceFunction.js +2 -2
- package/dist/types/PriceInfoType.d.ts +28 -28
- package/dist/types/PriceInfoType.js +57 -56
- package/dist/types/SwapExecutionAction.d.ts +88 -88
- package/dist/types/SwapExecutionAction.js +2 -2
- package/dist/types/SwapStateInfo.d.ts +5 -5
- package/dist/types/SwapStateInfo.js +2 -2
- package/dist/types/SwapWithSigner.d.ts +17 -17
- package/dist/types/SwapWithSigner.js +43 -42
- package/dist/types/Token.d.ts +99 -99
- package/dist/types/Token.js +76 -76
- package/dist/types/TokenAmount.d.ts +69 -69
- package/dist/types/TokenAmount.js +60 -59
- package/dist/types/fees/Fee.d.ts +50 -50
- package/dist/types/fees/Fee.js +2 -2
- package/dist/types/fees/FeeBreakdown.d.ts +11 -11
- package/dist/types/fees/FeeBreakdown.js +2 -2
- package/dist/types/fees/PercentagePPM.d.ts +17 -17
- package/dist/types/fees/PercentagePPM.js +18 -17
- package/dist/types/lnurl/LNURLPay.d.ts +61 -61
- package/dist/types/lnurl/LNURLPay.js +31 -30
- package/dist/types/lnurl/LNURLWithdraw.d.ts +48 -48
- package/dist/types/lnurl/LNURLWithdraw.js +27 -26
- package/dist/types/wallets/LightningInvoiceCreateService.d.ts +24 -24
- package/dist/types/wallets/LightningInvoiceCreateService.js +15 -14
- package/dist/types/wallets/MinimalBitcoinWalletInterface.d.ts +23 -23
- package/dist/types/wallets/MinimalBitcoinWalletInterface.js +2 -2
- package/dist/types/wallets/MinimalLightningNetworkWalletInterface.d.ts +9 -9
- package/dist/types/wallets/MinimalLightningNetworkWalletInterface.js +2 -2
- package/dist/utils/AutomaticClockDriftCorrection.d.ts +1 -1
- package/dist/utils/AutomaticClockDriftCorrection.js +70 -69
- package/dist/utils/BitcoinUtils.d.ts +14 -12
- package/dist/utils/BitcoinUtils.js +102 -101
- package/dist/utils/BitcoinWalletUtils.d.ts +7 -7
- package/dist/utils/BitcoinWalletUtils.js +14 -13
- package/dist/utils/Logger.d.ts +7 -7
- package/dist/utils/Logger.js +12 -11
- package/dist/utils/RetryUtils.d.ts +22 -22
- package/dist/utils/RetryUtils.js +67 -66
- package/dist/utils/SwapUtils.d.ts +88 -88
- package/dist/utils/SwapUtils.js +72 -72
- package/dist/utils/TimeoutUtils.d.ts +17 -17
- package/dist/utils/TimeoutUtils.js +55 -54
- package/dist/utils/TokenUtils.d.ts +19 -19
- package/dist/utils/TokenUtils.js +37 -36
- package/dist/utils/TypeUtils.d.ts +7 -7
- package/dist/utils/TypeUtils.js +2 -2
- package/dist/utils/Utils.d.ts +58 -56
- package/dist/utils/Utils.js +194 -193
- package/package.json +1 -1
|
@@ -1,506 +1,506 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.FromBTCLNAutoWrapper = void 0;
|
|
4
|
-
const bolt11_1 = require("@atomiqlabs/bolt11");
|
|
5
|
-
const base_1 = require("@atomiqlabs/base");
|
|
6
|
-
const buffer_1 = require("buffer");
|
|
7
|
-
const UserError_1 = require("../../../../errors/UserError");
|
|
8
|
-
const IntermediaryError_1 = require("../../../../errors/IntermediaryError");
|
|
9
|
-
const SwapType_1 = require("../../../../enums/SwapType");
|
|
10
|
-
const Utils_1 = require("../../../../utils/Utils");
|
|
11
|
-
const IntermediaryAPI_1 = require("../../../../intermediaries/apis/IntermediaryAPI");
|
|
12
|
-
const RequestError_1 = require("../../../../errors/RequestError");
|
|
13
|
-
const FromBTCLNAutoSwap_1 = require("./FromBTCLNAutoSwap");
|
|
14
|
-
const IFromBTCLNWrapper_1 = require("../IFromBTCLNWrapper");
|
|
15
|
-
const RetryUtils_1 = require("../../../../utils/RetryUtils");
|
|
16
|
-
const sha2_1 = require("@noble/hashes/sha2");
|
|
17
|
-
/**
|
|
18
|
-
* New escrow based (HTLC) swaps for Bitcoin Lightning -> Smart chain swaps not requiring manual settlement on
|
|
19
|
-
* the destination by the user, and instead letting the LP initiate the escrow. Permissionless watchtower network
|
|
20
|
-
* handles the claiming of HTLC, with the swap secret broadcasted over Nostr. Also adds a possibility for the user
|
|
21
|
-
* to receive a native token on the destination chain as part of the swap (a "gas drop" feature).
|
|
22
|
-
*
|
|
23
|
-
* @category Swaps/Lightning → Smart chain
|
|
24
|
-
*/
|
|
25
|
-
class FromBTCLNAutoWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
|
|
26
|
-
/**
|
|
27
|
-
* @param chainIdentifier
|
|
28
|
-
* @param unifiedStorage Storage interface for the current environment
|
|
29
|
-
* @param unifiedChainEvents On-chain event listener
|
|
30
|
-
* @param chain
|
|
31
|
-
* @param contract Underlying contract handling the swaps
|
|
32
|
-
* @param prices Swap pricing handler
|
|
33
|
-
* @param tokens
|
|
34
|
-
* @param swapDataDeserializer Deserializer for SwapData
|
|
35
|
-
* @param lnApi
|
|
36
|
-
* @param messenger
|
|
37
|
-
* @param options
|
|
38
|
-
* @param events Instance to use for emitting events
|
|
39
|
-
*/
|
|
40
|
-
constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, lnApi, messenger, options, events) {
|
|
41
|
-
super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, lnApi, {
|
|
42
|
-
...options,
|
|
43
|
-
safetyFactor: options?.safetyFactor ?? 2,
|
|
44
|
-
bitcoinBlocktime: options?.bitcoinBlocktime ?? 10 * 60,
|
|
45
|
-
unsafeSkipLnNodeCheck: options?.unsafeSkipLnNodeCheck ?? false
|
|
46
|
-
}, events);
|
|
47
|
-
this.TYPE = SwapType_1.SwapType.FROM_BTCLN_AUTO;
|
|
48
|
-
/**
|
|
49
|
-
* @internal
|
|
50
|
-
*/
|
|
51
|
-
this.tickSwapState = [
|
|
52
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_CREATED,
|
|
53
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.QUOTE_SOFT_EXPIRED,
|
|
54
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_PAID,
|
|
55
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED
|
|
56
|
-
];
|
|
57
|
-
/**
|
|
58
|
-
* @internal
|
|
59
|
-
*/
|
|
60
|
-
this._pendingSwapStates = [
|
|
61
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_CREATED,
|
|
62
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.QUOTE_SOFT_EXPIRED,
|
|
63
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_PAID,
|
|
64
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED,
|
|
65
|
-
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.EXPIRED
|
|
66
|
-
];
|
|
67
|
-
/**
|
|
68
|
-
* @internal
|
|
69
|
-
*/
|
|
70
|
-
this._claimableSwapStates = [FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED];
|
|
71
|
-
/**
|
|
72
|
-
* @internal
|
|
73
|
-
*/
|
|
74
|
-
this._swapDeserializer = FromBTCLNAutoSwap_1.FromBTCLNAutoSwap;
|
|
75
|
-
this._messenger = messenger;
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* @inheritDoc
|
|
79
|
-
* @internal
|
|
80
|
-
*/
|
|
81
|
-
async processEventInitialize(swap, event) {
|
|
82
|
-
if (swap._state === FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_PAID || swap._state === FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_CREATED || swap._state === FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.QUOTE_SOFT_EXPIRED) {
|
|
83
|
-
if (swap._data == null) {
|
|
84
|
-
//Obtain data from the initialize event
|
|
85
|
-
const eventData = await event.swapData();
|
|
86
|
-
if (eventData == null) {
|
|
87
|
-
this.logger.error("processEventInitialize(" + swap.getId() + "): Error when fetching swap data for swap, null returned!");
|
|
88
|
-
return false;
|
|
89
|
-
}
|
|
90
|
-
try {
|
|
91
|
-
await swap._saveRealSwapData(eventData, false);
|
|
92
|
-
this.logger.info("processEventInitialize(" + swap.getId() + "): Successfully taken swap data from on-chain event!");
|
|
93
|
-
}
|
|
94
|
-
catch (e) {
|
|
95
|
-
this.logger.error("processEventInitialize(" + swap.getId() + "): Error when saving swap data for swap: ", e);
|
|
96
|
-
return false;
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
if (swap._getEscrowHash() !== event.escrowHash) {
|
|
100
|
-
this.logger.error("processEventInitialize(" + swap.getId() + "): Error when processing event, escrow hashes don't match!");
|
|
101
|
-
return false;
|
|
102
|
-
}
|
|
103
|
-
swap._commitedAt ??= Date.now();
|
|
104
|
-
swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED;
|
|
105
|
-
if (swap.hasSecretPreimage())
|
|
106
|
-
swap._broadcastSecret().catch(e => {
|
|
107
|
-
this.logger.error("processEventInitialize(" + swap.getId() + "): Error when broadcasting swap secret: ", e);
|
|
108
|
-
});
|
|
109
|
-
return true;
|
|
110
|
-
}
|
|
111
|
-
return false;
|
|
112
|
-
}
|
|
113
|
-
/**
|
|
114
|
-
* @inheritDoc
|
|
115
|
-
* @internal
|
|
116
|
-
*/
|
|
117
|
-
processEventClaim(swap, event) {
|
|
118
|
-
if (swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED && swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED) {
|
|
119
|
-
swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED;
|
|
120
|
-
swap._setSwapSecret(event.result);
|
|
121
|
-
return Promise.resolve(true);
|
|
122
|
-
}
|
|
123
|
-
return Promise.resolve(false);
|
|
124
|
-
}
|
|
125
|
-
/**
|
|
126
|
-
* @inheritDoc
|
|
127
|
-
* @internal
|
|
128
|
-
*/
|
|
129
|
-
processEventRefund(swap, event) {
|
|
130
|
-
if (swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED && swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED) {
|
|
131
|
-
swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED;
|
|
132
|
-
return Promise.resolve(true);
|
|
133
|
-
}
|
|
134
|
-
return Promise.resolve(false);
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Pre-fetches claimer (watchtower) bounty data for the swap. Doesn't throw, instead returns null and aborts the
|
|
138
|
-
* provided abortController
|
|
139
|
-
*
|
|
140
|
-
* @param signer Smartchain signer address initiating the swap
|
|
141
|
-
* @param amountData
|
|
142
|
-
* @param options Options as passed to the swap creation function
|
|
143
|
-
* @param abortController
|
|
144
|
-
*
|
|
145
|
-
* @private
|
|
146
|
-
*/
|
|
147
|
-
async preFetchClaimerBounty(signer, amountData, options, abortController) {
|
|
148
|
-
if (options.unsafeZeroWatchtowerFee)
|
|
149
|
-
return 0n;
|
|
150
|
-
const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
|
|
151
|
-
const dummySwapData = await this._contract.createSwapData(base_1.ChainSwapType.HTLC, this._chain.randomAddress(), signer, amountData.token, dummyAmount, this._contract.getHashForHtlc((0, Utils_1.randomBytes)(32)).toString("hex"), this.getRandomSequence(), BigInt(Math.floor(Date.now() / 1000)), false, true, BigInt(Math.floor(Math.random() * 0x10000)), BigInt(Math.floor(Math.random() * 0x10000)));
|
|
152
|
-
try {
|
|
153
|
-
const result = await this._contract.getClaimFee(this._chain.randomAddress(), dummySwapData);
|
|
154
|
-
return result * BigInt(Math.floor(options.feeSafetyFactor * 1000000)) / 1000000n;
|
|
155
|
-
}
|
|
156
|
-
catch (e) {
|
|
157
|
-
abortController.abort(e);
|
|
158
|
-
}
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Verifies response returned from intermediary
|
|
162
|
-
*
|
|
163
|
-
* @param resp Response as returned by the intermediary
|
|
164
|
-
* @param amountData
|
|
165
|
-
* @param lp Intermediary
|
|
166
|
-
* @param options Options as passed to the swap creation function
|
|
167
|
-
* @param decodedPr Decoded bolt11 lightning network invoice
|
|
168
|
-
* @param paymentHash Expected payment hash of the bolt11 lightning network invoice
|
|
169
|
-
* @param claimerBounty Claimer bounty as request by the user
|
|
170
|
-
*
|
|
171
|
-
* @throws {IntermediaryError} in case the response is invalid
|
|
172
|
-
*
|
|
173
|
-
* @private
|
|
174
|
-
*/
|
|
175
|
-
verifyReturnedData(resp, amountData, lp, options, decodedPr, paymentHash, claimerBounty) {
|
|
176
|
-
if (lp.getAddress(this.chainIdentifier) !== resp.intermediaryKey)
|
|
177
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid intermediary address/pubkey");
|
|
178
|
-
if (options.descriptionHash != null && decodedPr.tagsObject.purpose_commit_hash !== options.descriptionHash.toString("hex"))
|
|
179
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid pr returned - description hash");
|
|
180
|
-
if (options.description != null && decodedPr.tagsObject.description !== options.description)
|
|
181
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid pr returned - description");
|
|
182
|
-
if (decodedPr.tagsObject.payment_hash == null ||
|
|
183
|
-
!buffer_1.Buffer.from(decodedPr.tagsObject.payment_hash, "hex").equals(paymentHash))
|
|
184
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid pr returned - payment hash");
|
|
185
|
-
if (decodedPr.millisatoshis == null)
|
|
186
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid pr returned - msat field");
|
|
187
|
-
const amountIn = (BigInt(decodedPr.millisatoshis) + 999n) / 1000n;
|
|
188
|
-
if (resp.btcAmountGas + resp.btcAmountSwap !== amountIn)
|
|
189
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid total btc returned");
|
|
190
|
-
if (resp.gasSwapFeeBtc + resp.swapFeeBtc !== resp.totalFeeBtc)
|
|
191
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid total btc fee returned");
|
|
192
|
-
if (resp.claimerBounty !== claimerBounty)
|
|
193
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid claimer bounty");
|
|
194
|
-
if (resp.totalGas !== options.gasAmount)
|
|
195
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid total gas amount");
|
|
196
|
-
if (!amountData.exactIn) {
|
|
197
|
-
if (resp.total != amountData.amount)
|
|
198
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid amount returned");
|
|
199
|
-
}
|
|
200
|
-
else {
|
|
201
|
-
if (amountIn !== amountData.amount)
|
|
202
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid payment request returned, amount mismatch");
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Returns a newly created Lightning -> Smart chain swap using the HTLC based escrow swap protocol,
|
|
207
|
-
* where watchtowers handle the automatic settlement of the swap on the destination chain. Also allows
|
|
208
|
-
* specifying additional "gas drop" native token that the receipient receives on the destination chain
|
|
209
|
-
* in the `options` argument. The user has to pay a bolt11 invoice on the input lightning network side.
|
|
210
|
-
*
|
|
211
|
-
* @param recipient Recipient's address on the destination chain
|
|
212
|
-
* @param amountData Amount, token and exact input/output data for to swap
|
|
213
|
-
* @param lps An array of intermediaries (LPs) to get the quotes from
|
|
214
|
-
* @param options Optional additional quote options
|
|
215
|
-
* @param additionalParams Optional additional parameters sent to the LP when creating the swap
|
|
216
|
-
* @param abortSignal Abort signal
|
|
217
|
-
* @param preFetches Optional pre-fetches for speeding up the quoting process (mainly used internally)
|
|
218
|
-
*/
|
|
219
|
-
create(recipient, amountData, lps, options, additionalParams, abortSignal, preFetches) {
|
|
220
|
-
if (!this.isInitialized)
|
|
221
|
-
throw new Error("Not initialized, call init() first!");
|
|
222
|
-
const _options = {
|
|
223
|
-
paymentHash: (0, Utils_1.parseHashValueExact32Bytes)(options?.paymentHash, "payment hash"),
|
|
224
|
-
unsafeSkipLnNodeCheck: options?.unsafeSkipLnNodeCheck ?? this._options.unsafeSkipLnNodeCheck,
|
|
225
|
-
gasAmount: this.parseGasAmount(options?.gasAmount),
|
|
226
|
-
feeSafetyFactor: options?.feeSafetyFactor ?? 1.25,
|
|
227
|
-
unsafeZeroWatchtowerFee: options?.unsafeZeroWatchtowerFee ?? false,
|
|
228
|
-
description: options?.description,
|
|
229
|
-
descriptionHash: (0, Utils_1.parseHashValueExact32Bytes)(options?.descriptionHash, "description hash")
|
|
230
|
-
};
|
|
231
|
-
if (amountData.token === this._chain.getNativeCurrencyAddress() && _options.gasAmount !== 0n)
|
|
232
|
-
throw new UserError_1.UserError("Cannot specify `gasAmount` for swaps to a native token!");
|
|
233
|
-
if (_options.description != null && buffer_1.Buffer.byteLength(_options.description, "utf8") > 500)
|
|
234
|
-
throw new UserError_1.UserError("Invalid description length");
|
|
235
|
-
let secret;
|
|
236
|
-
let paymentHash;
|
|
237
|
-
if (_options?.paymentHash != null) {
|
|
238
|
-
paymentHash = _options.paymentHash;
|
|
239
|
-
}
|
|
240
|
-
else {
|
|
241
|
-
({ secret, paymentHash } = this.getSecretAndHash());
|
|
242
|
-
}
|
|
243
|
-
const claimHash = this._contract.getHashForHtlc(paymentHash);
|
|
244
|
-
const nativeTokenAddress = this._chain.getNativeCurrencyAddress();
|
|
245
|
-
const _abortController = (0, Utils_1.extendAbortController)(abortSignal);
|
|
246
|
-
preFetches ??= {};
|
|
247
|
-
const _preFetches = {
|
|
248
|
-
pricePrefetchPromise: preFetches?.pricePrefetchPromise ?? this.preFetchPrice(amountData, _abortController.signal),
|
|
249
|
-
usdPricePrefetchPromise: preFetches?.usdPricePrefetchPromise ?? this.preFetchUsdPrice(_abortController.signal),
|
|
250
|
-
claimerBountyPrefetch: preFetches?.claimerBountyPrefetch ?? this.preFetchClaimerBounty(recipient, amountData, _options, _abortController),
|
|
251
|
-
gasTokenPricePrefetchPromise: _options.gasAmount !== 0n || !_options.unsafeZeroWatchtowerFee ?
|
|
252
|
-
(preFetches.gasTokenPricePrefetchPromise ??= this.preFetchPrice({ token: nativeTokenAddress }, _abortController.signal)) :
|
|
253
|
-
undefined
|
|
254
|
-
};
|
|
255
|
-
return lps.map(lp => {
|
|
256
|
-
return {
|
|
257
|
-
intermediary: lp,
|
|
258
|
-
quote: (async () => {
|
|
259
|
-
if (lp.services[SwapType_1.SwapType.FROM_BTCLN_AUTO] == null)
|
|
260
|
-
throw new Error("LP service for processing from btcln auto swaps not found!");
|
|
261
|
-
const abortController = (0, Utils_1.extendAbortController)(_abortController.signal);
|
|
262
|
-
const liquidityPromise = this.preFetchIntermediaryLiquidity(amountData, lp, abortController);
|
|
263
|
-
const { lnCapacityPromise, resp } = await (0, RetryUtils_1.tryWithRetries)(async (retryCount) => {
|
|
264
|
-
const { lnPublicKey, response } = IntermediaryAPI_1.IntermediaryAPI.initFromBTCLNAuto(this.chainIdentifier, lp.url, {
|
|
265
|
-
paymentHash,
|
|
266
|
-
amount: amountData.amount,
|
|
267
|
-
claimer: recipient,
|
|
268
|
-
token: amountData.token.toString(),
|
|
269
|
-
description: _options.description,
|
|
270
|
-
descriptionHash: _options.descriptionHash,
|
|
271
|
-
exactOut: !amountData.exactIn,
|
|
272
|
-
additionalParams,
|
|
273
|
-
gasToken: this._chain.getNativeCurrencyAddress(),
|
|
274
|
-
gasAmount: _options.gasAmount,
|
|
275
|
-
claimerBounty: (0, Utils_1.throwIfUndefined)(_preFetches.claimerBountyPrefetch)
|
|
276
|
-
}, this._options.postRequestTimeout, abortController.signal, retryCount > 0 ? false : undefined);
|
|
277
|
-
let lnCapacityPromise;
|
|
278
|
-
if (!_options.unsafeSkipLnNodeCheck) {
|
|
279
|
-
lnCapacityPromise = this.preFetchLnCapacity(lnPublicKey);
|
|
280
|
-
}
|
|
281
|
-
else
|
|
282
|
-
lnPublicKey.catch(() => { });
|
|
283
|
-
return {
|
|
284
|
-
lnCapacityPromise,
|
|
285
|
-
resp: await response
|
|
286
|
-
};
|
|
287
|
-
}, undefined, RequestError_1.RequestError, abortController.signal);
|
|
288
|
-
const decodedPr = (0, bolt11_1.decode)(resp.pr);
|
|
289
|
-
if (decodedPr.millisatoshis == null)
|
|
290
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid returned swap invoice, no msat amount field");
|
|
291
|
-
if (decodedPr.timeExpireDate == null)
|
|
292
|
-
throw new IntermediaryError_1.IntermediaryError("Invalid returned swap invoice, no expiry date field");
|
|
293
|
-
const amountIn = (BigInt(decodedPr.millisatoshis) + 999n) / 1000n;
|
|
294
|
-
const claimerBounty = (await _preFetches.claimerBountyPrefetch);
|
|
295
|
-
try {
|
|
296
|
-
this.verifyReturnedData(resp, amountData, lp, _options, decodedPr, paymentHash, claimerBounty);
|
|
297
|
-
const [pricingInfo, gasPricingInfo] = await Promise.all([
|
|
298
|
-
this.verifyReturnedPrice(lp.services[SwapType_1.SwapType.FROM_BTCLN_AUTO], false, resp.btcAmountSwap, resp.total, amountData.token, { swapFeeBtc: resp.swapFeeBtc }, _preFetches.pricePrefetchPromise, _preFetches.usdPricePrefetchPromise, abortController.signal),
|
|
299
|
-
_options.gasAmount === 0n ? Promise.resolve(undefined) : this.verifyReturnedPrice({ ...lp.services[SwapType_1.SwapType.FROM_BTCLN_AUTO], swapBaseFee: 0 }, //Base fee should be charged only on the amount, not on gas
|
|
300
|
-
false, resp.btcAmountGas, resp.totalGas + resp.claimerBounty, nativeTokenAddress, { swapFeeBtc: resp.gasSwapFeeBtc }, _preFetches.gasTokenPricePrefetchPromise, _preFetches.usdPricePrefetchPromise, abortController.signal),
|
|
301
|
-
this.verifyIntermediaryLiquidity(resp.total, (0, Utils_1.throwIfUndefined)(liquidityPromise)),
|
|
302
|
-
_options.unsafeSkipLnNodeCheck ? Promise.resolve() : this.verifyLnNodeCapacity(lp, decodedPr, lnCapacityPromise, abortController.signal)
|
|
303
|
-
]);
|
|
304
|
-
const swapInit = {
|
|
305
|
-
pricingInfo,
|
|
306
|
-
url: lp.url,
|
|
307
|
-
expiry: decodedPr.timeExpireDate * 1000,
|
|
308
|
-
swapFee: resp.swapFee,
|
|
309
|
-
gasSwapFee: resp.gasSwapFee,
|
|
310
|
-
swapFeeBtc: resp.swapFeeBtc,
|
|
311
|
-
gasSwapFeeBtc: resp.gasSwapFeeBtc,
|
|
312
|
-
btcAmountGas: resp.btcAmountGas,
|
|
313
|
-
btcAmountSwap: resp.btcAmountSwap,
|
|
314
|
-
gasPricingInfo,
|
|
315
|
-
initialSwapData: await this._contract.createSwapData(base_1.ChainSwapType.HTLC, lp.getAddress(this.chainIdentifier), recipient, amountData.token, resp.total, claimHash.toString("hex"), this.getRandomSequence(), BigInt(Math.floor(Date.now() / 1000)), false, true, _options.gasAmount + resp.claimerBounty, resp.claimerBounty, nativeTokenAddress),
|
|
316
|
-
pr: resp.pr,
|
|
317
|
-
secret: secret?.toString("hex"),
|
|
318
|
-
exactIn: amountData.exactIn ?? true
|
|
319
|
-
};
|
|
320
|
-
const quote = new FromBTCLNAutoSwap_1.FromBTCLNAutoSwap(this, swapInit);
|
|
321
|
-
return quote;
|
|
322
|
-
}
|
|
323
|
-
catch (e) {
|
|
324
|
-
abortController.abort(e);
|
|
325
|
-
throw e;
|
|
326
|
-
}
|
|
327
|
-
})()
|
|
328
|
-
};
|
|
329
|
-
});
|
|
330
|
-
}
|
|
331
|
-
/**
|
|
332
|
-
* Returns a newly created Lightning -> Smart chain swap using the HTLC based escrow swap protocol,
|
|
333
|
-
* where watchtowers handle the automatic settlement of the swap on the destination chain. Also allows
|
|
334
|
-
* specifying additional "gas drop" native token that the receipient receives on the destination chain
|
|
335
|
-
* in the `options` argument. The swap is created with an LNURL-withdraw link which will be used to pay
|
|
336
|
-
* the generated bolt11 invoice automatically when {@link FromBTCLNSwap.waitForPayment} is called on the
|
|
337
|
-
* swap.
|
|
338
|
-
*
|
|
339
|
-
* @param recipient Recipient's address on the destination chain
|
|
340
|
-
* @param lnurl LNURL-withdraw link to pull the funds from
|
|
341
|
-
* @param amountData Amount, token and exact input/output data for to swap
|
|
342
|
-
* @param lps An array of intermediaries (LPs) to get the quotes from
|
|
343
|
-
* @param options Optional additional quote options
|
|
344
|
-
* @param additionalParams Optional additional parameters sent to the LP when creating the swap
|
|
345
|
-
* @param abortSignal Abort signal
|
|
346
|
-
*/
|
|
347
|
-
async createViaLNURL(recipient, lnurl, amountData, lps, options, additionalParams, abortSignal) {
|
|
348
|
-
if (!this.isInitialized)
|
|
349
|
-
throw new Error("Not initialized, call init() first!");
|
|
350
|
-
const _options = {
|
|
351
|
-
paymentHash: (0, Utils_1.parseHashValueExact32Bytes)(options?.paymentHash, "payment hash"),
|
|
352
|
-
unsafeSkipLnNodeCheck: options?.unsafeSkipLnNodeCheck ?? this._options.unsafeSkipLnNodeCheck,
|
|
353
|
-
gasAmount: this.parseGasAmount(options?.gasAmount),
|
|
354
|
-
feeSafetyFactor: options?.feeSafetyFactor ?? 1.25,
|
|
355
|
-
unsafeZeroWatchtowerFee: options?.unsafeZeroWatchtowerFee ?? false,
|
|
356
|
-
description: options?.description,
|
|
357
|
-
descriptionHash: (0, Utils_1.parseHashValueExact32Bytes)(options?.descriptionHash, "description hash")
|
|
358
|
-
};
|
|
359
|
-
const abortController = (0, Utils_1.extendAbortController)(abortSignal);
|
|
360
|
-
const preFetches = {
|
|
361
|
-
pricePrefetchPromise: this.preFetchPrice(amountData, abortController.signal),
|
|
362
|
-
usdPricePrefetchPromise: this.preFetchUsdPrice(abortController.signal),
|
|
363
|
-
gasTokenPricePrefetchPromise: _options.gasAmount !== 0n || !_options.unsafeZeroWatchtowerFee ?
|
|
364
|
-
this.preFetchPrice({ token: this._chain.getNativeCurrencyAddress() }, abortController.signal) :
|
|
365
|
-
undefined,
|
|
366
|
-
claimerBountyPrefetch: this.preFetchClaimerBounty(recipient, amountData, _options, abortController)
|
|
367
|
-
};
|
|
368
|
-
try {
|
|
369
|
-
const exactOutAmountPromise = !amountData.exactIn ? preFetches.pricePrefetchPromise.then(price => this._prices.getToBtcSwapAmount(this.chainIdentifier, amountData.amount, amountData.token, abortController.signal, price)).catch(e => {
|
|
370
|
-
abortController.abort(e);
|
|
371
|
-
return undefined;
|
|
372
|
-
}) : undefined;
|
|
373
|
-
const withdrawRequest = await this.getLNURLWithdraw(lnurl, abortController.signal);
|
|
374
|
-
const min = BigInt(withdrawRequest.minWithdrawable) / 1000n;
|
|
375
|
-
const max = BigInt(withdrawRequest.maxWithdrawable) / 1000n;
|
|
376
|
-
if (amountData.exactIn) {
|
|
377
|
-
if (amountData.amount < min)
|
|
378
|
-
throw new UserError_1.UserError("Amount less than LNURL-withdraw minimum");
|
|
379
|
-
if (amountData.amount > max)
|
|
380
|
-
throw new UserError_1.UserError("Amount more than LNURL-withdraw maximum");
|
|
381
|
-
}
|
|
382
|
-
else {
|
|
383
|
-
const amount = (await exactOutAmountPromise);
|
|
384
|
-
abortController.signal.throwIfAborted();
|
|
385
|
-
if ((amount * 95n / 100n) < min)
|
|
386
|
-
throw new UserError_1.UserError("Amount less than LNURL-withdraw minimum");
|
|
387
|
-
if ((amount * 105n / 100n) > max)
|
|
388
|
-
throw new UserError_1.UserError("Amount more than LNURL-withdraw maximum");
|
|
389
|
-
}
|
|
390
|
-
return this.create(recipient, amountData, lps, _options, additionalParams, abortSignal, preFetches).map(data => {
|
|
391
|
-
return {
|
|
392
|
-
quote: data.quote.then(quote => {
|
|
393
|
-
quote._setLNURLData(withdrawRequest.url, withdrawRequest.k1, withdrawRequest.callback);
|
|
394
|
-
const amountIn = quote.getInput().rawAmount;
|
|
395
|
-
if (amountIn < min)
|
|
396
|
-
throw new UserError_1.UserError("Amount less than LNURL-withdraw minimum");
|
|
397
|
-
if (amountIn > max)
|
|
398
|
-
throw new UserError_1.UserError("Amount more than LNURL-withdraw maximum");
|
|
399
|
-
return quote;
|
|
400
|
-
}),
|
|
401
|
-
intermediary: data.intermediary
|
|
402
|
-
};
|
|
403
|
-
});
|
|
404
|
-
}
|
|
405
|
-
catch (e) {
|
|
406
|
-
abortController.abort(e);
|
|
407
|
-
throw e;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
/**
|
|
411
|
-
* @inheritDoc
|
|
412
|
-
* @internal
|
|
413
|
-
*/
|
|
414
|
-
async _checkPastSwaps(pastSwaps) {
|
|
415
|
-
const changedSwapSet = new Set();
|
|
416
|
-
const swapExpiredStatus = {};
|
|
417
|
-
const checkStatusSwaps = [];
|
|
418
|
-
await Promise.all(pastSwaps.map(async (pastSwap) => {
|
|
419
|
-
if (pastSwap._shouldCheckIntermediary()) {
|
|
420
|
-
try {
|
|
421
|
-
const result = await pastSwap._checkIntermediaryPaymentReceived(false);
|
|
422
|
-
if (result != null) {
|
|
423
|
-
changedSwapSet.add(pastSwap);
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
catch (e) {
|
|
427
|
-
this.logger.error(`_checkPastSwaps(): Failed to contact LP regarding swap ${pastSwap.getId()}, error: `, e);
|
|
428
|
-
}
|
|
429
|
-
}
|
|
430
|
-
if (pastSwap._shouldFetchExpiryStatus()) {
|
|
431
|
-
//Check expiry
|
|
432
|
-
swapExpiredStatus[pastSwap.getId()] = await pastSwap._verifyQuoteDefinitelyExpired();
|
|
433
|
-
}
|
|
434
|
-
if (pastSwap._shouldFetchOnchainState()) {
|
|
435
|
-
//Add to swaps for which status should be checked
|
|
436
|
-
if (pastSwap._data != null)
|
|
437
|
-
checkStatusSwaps.push(pastSwap);
|
|
438
|
-
}
|
|
439
|
-
}));
|
|
440
|
-
const swapStatuses = await this._contract.getCommitStatuses(checkStatusSwaps.map(val => ({ signer: val._getInitiator(), swapData: val._data })));
|
|
441
|
-
for (let pastSwap of checkStatusSwaps) {
|
|
442
|
-
const shouldSave = await pastSwap._sync(false, swapExpiredStatus[pastSwap.getId()], swapStatuses[pastSwap.getEscrowHash()], true);
|
|
443
|
-
if (shouldSave) {
|
|
444
|
-
changedSwapSet.add(pastSwap);
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
const changedSwaps = [];
|
|
448
|
-
const removeSwaps = [];
|
|
449
|
-
changedSwapSet.forEach(val => {
|
|
450
|
-
if (val.isQuoteExpired()) {
|
|
451
|
-
removeSwaps.push(val);
|
|
452
|
-
}
|
|
453
|
-
else {
|
|
454
|
-
changedSwaps.push(val);
|
|
455
|
-
}
|
|
456
|
-
});
|
|
457
|
-
return {
|
|
458
|
-
changedSwaps,
|
|
459
|
-
removeSwaps
|
|
460
|
-
};
|
|
461
|
-
}
|
|
462
|
-
/**
|
|
463
|
-
* @inheritDoc
|
|
464
|
-
*/
|
|
465
|
-
async recoverFromSwapDataAndState(init, state, lp) {
|
|
466
|
-
const data = init.data;
|
|
467
|
-
let paymentHash = data.getHTLCHashHint();
|
|
468
|
-
let secret;
|
|
469
|
-
if (state.type === base_1.SwapCommitStateType.PAID) {
|
|
470
|
-
secret = await state.getClaimResult();
|
|
471
|
-
paymentHash = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.from(secret, "hex"))).toString("hex");
|
|
472
|
-
}
|
|
473
|
-
const swapInit = {
|
|
474
|
-
pricingInfo: {
|
|
475
|
-
isValid: true,
|
|
476
|
-
satsBaseFee: 0n,
|
|
477
|
-
swapPriceUSatPerToken: 100000000000000n,
|
|
478
|
-
realPriceUSatPerToken: 100000000000000n,
|
|
479
|
-
differencePPM: 0n,
|
|
480
|
-
feePPM: 0n,
|
|
481
|
-
},
|
|
482
|
-
url: lp?.url,
|
|
483
|
-
expiry: 0,
|
|
484
|
-
swapFee: 0n,
|
|
485
|
-
swapFeeBtc: 0n,
|
|
486
|
-
gasSwapFee: 0n,
|
|
487
|
-
gasSwapFeeBtc: 0n,
|
|
488
|
-
initialSwapData: data,
|
|
489
|
-
data,
|
|
490
|
-
pr: paymentHash ?? undefined,
|
|
491
|
-
secret,
|
|
492
|
-
exactIn: false
|
|
493
|
-
};
|
|
494
|
-
const swap = new FromBTCLNAutoSwap_1.FromBTCLNAutoSwap(this, swapInit);
|
|
495
|
-
swap._commitTxId = await init.getInitTxId();
|
|
496
|
-
const blockData = await init.getTxBlock();
|
|
497
|
-
swap.createdAt = blockData.blockTime * 1000;
|
|
498
|
-
swap._commitedAt = blockData.blockTime * 1000;
|
|
499
|
-
swap._setInitiated();
|
|
500
|
-
swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED;
|
|
501
|
-
await swap._sync(false, false, state);
|
|
502
|
-
await swap._save();
|
|
503
|
-
return swap;
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
exports.FromBTCLNAutoWrapper = FromBTCLNAutoWrapper;
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FromBTCLNAutoWrapper = void 0;
|
|
4
|
+
const bolt11_1 = require("@atomiqlabs/bolt11");
|
|
5
|
+
const base_1 = require("@atomiqlabs/base");
|
|
6
|
+
const buffer_1 = require("buffer");
|
|
7
|
+
const UserError_1 = require("../../../../errors/UserError");
|
|
8
|
+
const IntermediaryError_1 = require("../../../../errors/IntermediaryError");
|
|
9
|
+
const SwapType_1 = require("../../../../enums/SwapType");
|
|
10
|
+
const Utils_1 = require("../../../../utils/Utils");
|
|
11
|
+
const IntermediaryAPI_1 = require("../../../../intermediaries/apis/IntermediaryAPI");
|
|
12
|
+
const RequestError_1 = require("../../../../errors/RequestError");
|
|
13
|
+
const FromBTCLNAutoSwap_1 = require("./FromBTCLNAutoSwap");
|
|
14
|
+
const IFromBTCLNWrapper_1 = require("../IFromBTCLNWrapper");
|
|
15
|
+
const RetryUtils_1 = require("../../../../utils/RetryUtils");
|
|
16
|
+
const sha2_1 = require("@noble/hashes/sha2");
|
|
17
|
+
/**
|
|
18
|
+
* New escrow based (HTLC) swaps for Bitcoin Lightning -> Smart chain swaps not requiring manual settlement on
|
|
19
|
+
* the destination by the user, and instead letting the LP initiate the escrow. Permissionless watchtower network
|
|
20
|
+
* handles the claiming of HTLC, with the swap secret broadcasted over Nostr. Also adds a possibility for the user
|
|
21
|
+
* to receive a native token on the destination chain as part of the swap (a "gas drop" feature).
|
|
22
|
+
*
|
|
23
|
+
* @category Swaps/Lightning → Smart chain
|
|
24
|
+
*/
|
|
25
|
+
class FromBTCLNAutoWrapper extends IFromBTCLNWrapper_1.IFromBTCLNWrapper {
|
|
26
|
+
/**
|
|
27
|
+
* @param chainIdentifier
|
|
28
|
+
* @param unifiedStorage Storage interface for the current environment
|
|
29
|
+
* @param unifiedChainEvents On-chain event listener
|
|
30
|
+
* @param chain
|
|
31
|
+
* @param contract Underlying contract handling the swaps
|
|
32
|
+
* @param prices Swap pricing handler
|
|
33
|
+
* @param tokens
|
|
34
|
+
* @param swapDataDeserializer Deserializer for SwapData
|
|
35
|
+
* @param lnApi
|
|
36
|
+
* @param messenger
|
|
37
|
+
* @param options
|
|
38
|
+
* @param events Instance to use for emitting events
|
|
39
|
+
*/
|
|
40
|
+
constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, lnApi, messenger, options, events) {
|
|
41
|
+
super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, contract, prices, tokens, swapDataDeserializer, lnApi, {
|
|
42
|
+
...options,
|
|
43
|
+
safetyFactor: options?.safetyFactor ?? 2,
|
|
44
|
+
bitcoinBlocktime: options?.bitcoinBlocktime ?? 10 * 60,
|
|
45
|
+
unsafeSkipLnNodeCheck: options?.unsafeSkipLnNodeCheck ?? false
|
|
46
|
+
}, events);
|
|
47
|
+
this.TYPE = SwapType_1.SwapType.FROM_BTCLN_AUTO;
|
|
48
|
+
/**
|
|
49
|
+
* @internal
|
|
50
|
+
*/
|
|
51
|
+
this.tickSwapState = [
|
|
52
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_CREATED,
|
|
53
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.QUOTE_SOFT_EXPIRED,
|
|
54
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_PAID,
|
|
55
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED
|
|
56
|
+
];
|
|
57
|
+
/**
|
|
58
|
+
* @internal
|
|
59
|
+
*/
|
|
60
|
+
this._pendingSwapStates = [
|
|
61
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_CREATED,
|
|
62
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.QUOTE_SOFT_EXPIRED,
|
|
63
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_PAID,
|
|
64
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED,
|
|
65
|
+
FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.EXPIRED
|
|
66
|
+
];
|
|
67
|
+
/**
|
|
68
|
+
* @internal
|
|
69
|
+
*/
|
|
70
|
+
this._claimableSwapStates = [FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED];
|
|
71
|
+
/**
|
|
72
|
+
* @internal
|
|
73
|
+
*/
|
|
74
|
+
this._swapDeserializer = FromBTCLNAutoSwap_1.FromBTCLNAutoSwap;
|
|
75
|
+
this._messenger = messenger;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* @inheritDoc
|
|
79
|
+
* @internal
|
|
80
|
+
*/
|
|
81
|
+
async processEventInitialize(swap, event) {
|
|
82
|
+
if (swap._state === FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_PAID || swap._state === FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.PR_CREATED || swap._state === FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.QUOTE_SOFT_EXPIRED) {
|
|
83
|
+
if (swap._data == null) {
|
|
84
|
+
//Obtain data from the initialize event
|
|
85
|
+
const eventData = await event.swapData();
|
|
86
|
+
if (eventData == null) {
|
|
87
|
+
this.logger.error("processEventInitialize(" + swap.getId() + "): Error when fetching swap data for swap, null returned!");
|
|
88
|
+
return false;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
await swap._saveRealSwapData(eventData, false);
|
|
92
|
+
this.logger.info("processEventInitialize(" + swap.getId() + "): Successfully taken swap data from on-chain event!");
|
|
93
|
+
}
|
|
94
|
+
catch (e) {
|
|
95
|
+
this.logger.error("processEventInitialize(" + swap.getId() + "): Error when saving swap data for swap: ", e);
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (swap._getEscrowHash() !== event.escrowHash) {
|
|
100
|
+
this.logger.error("processEventInitialize(" + swap.getId() + "): Error when processing event, escrow hashes don't match!");
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
swap._commitedAt ??= Date.now();
|
|
104
|
+
swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED;
|
|
105
|
+
if (swap.hasSecretPreimage())
|
|
106
|
+
swap._broadcastSecret().catch(e => {
|
|
107
|
+
this.logger.error("processEventInitialize(" + swap.getId() + "): Error when broadcasting swap secret: ", e);
|
|
108
|
+
});
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* @inheritDoc
|
|
115
|
+
* @internal
|
|
116
|
+
*/
|
|
117
|
+
processEventClaim(swap, event) {
|
|
118
|
+
if (swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED && swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED) {
|
|
119
|
+
swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED;
|
|
120
|
+
swap._setSwapSecret(event.result);
|
|
121
|
+
return Promise.resolve(true);
|
|
122
|
+
}
|
|
123
|
+
return Promise.resolve(false);
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* @inheritDoc
|
|
127
|
+
* @internal
|
|
128
|
+
*/
|
|
129
|
+
processEventRefund(swap, event) {
|
|
130
|
+
if (swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_CLAIMED && swap._state !== FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED) {
|
|
131
|
+
swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.FAILED;
|
|
132
|
+
return Promise.resolve(true);
|
|
133
|
+
}
|
|
134
|
+
return Promise.resolve(false);
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Pre-fetches claimer (watchtower) bounty data for the swap. Doesn't throw, instead returns null and aborts the
|
|
138
|
+
* provided abortController
|
|
139
|
+
*
|
|
140
|
+
* @param signer Smartchain signer address initiating the swap
|
|
141
|
+
* @param amountData
|
|
142
|
+
* @param options Options as passed to the swap creation function
|
|
143
|
+
* @param abortController
|
|
144
|
+
*
|
|
145
|
+
* @private
|
|
146
|
+
*/
|
|
147
|
+
async preFetchClaimerBounty(signer, amountData, options, abortController) {
|
|
148
|
+
if (options.unsafeZeroWatchtowerFee)
|
|
149
|
+
return 0n;
|
|
150
|
+
const dummyAmount = BigInt(Math.floor(Math.random() * 0x1000000));
|
|
151
|
+
const dummySwapData = await this._contract.createSwapData(base_1.ChainSwapType.HTLC, this._chain.randomAddress(), signer, amountData.token, dummyAmount, this._contract.getHashForHtlc((0, Utils_1.randomBytes)(32)).toString("hex"), this.getRandomSequence(), BigInt(Math.floor(Date.now() / 1000)), false, true, BigInt(Math.floor(Math.random() * 0x10000)), BigInt(Math.floor(Math.random() * 0x10000)));
|
|
152
|
+
try {
|
|
153
|
+
const result = await this._contract.getClaimFee(this._chain.randomAddress(), dummySwapData);
|
|
154
|
+
return result * BigInt(Math.floor(options.feeSafetyFactor * 1000000)) / 1000000n;
|
|
155
|
+
}
|
|
156
|
+
catch (e) {
|
|
157
|
+
abortController.abort(e);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Verifies response returned from intermediary
|
|
162
|
+
*
|
|
163
|
+
* @param resp Response as returned by the intermediary
|
|
164
|
+
* @param amountData
|
|
165
|
+
* @param lp Intermediary
|
|
166
|
+
* @param options Options as passed to the swap creation function
|
|
167
|
+
* @param decodedPr Decoded bolt11 lightning network invoice
|
|
168
|
+
* @param paymentHash Expected payment hash of the bolt11 lightning network invoice
|
|
169
|
+
* @param claimerBounty Claimer bounty as request by the user
|
|
170
|
+
*
|
|
171
|
+
* @throws {IntermediaryError} in case the response is invalid
|
|
172
|
+
*
|
|
173
|
+
* @private
|
|
174
|
+
*/
|
|
175
|
+
verifyReturnedData(resp, amountData, lp, options, decodedPr, paymentHash, claimerBounty) {
|
|
176
|
+
if (lp.getAddress(this.chainIdentifier) !== resp.intermediaryKey)
|
|
177
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid intermediary address/pubkey");
|
|
178
|
+
if (options.descriptionHash != null && decodedPr.tagsObject.purpose_commit_hash !== options.descriptionHash.toString("hex"))
|
|
179
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid pr returned - description hash");
|
|
180
|
+
if (options.description != null && decodedPr.tagsObject.description !== options.description)
|
|
181
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid pr returned - description");
|
|
182
|
+
if (decodedPr.tagsObject.payment_hash == null ||
|
|
183
|
+
!buffer_1.Buffer.from(decodedPr.tagsObject.payment_hash, "hex").equals(paymentHash))
|
|
184
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid pr returned - payment hash");
|
|
185
|
+
if (decodedPr.millisatoshis == null)
|
|
186
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid pr returned - msat field");
|
|
187
|
+
const amountIn = (BigInt(decodedPr.millisatoshis) + 999n) / 1000n;
|
|
188
|
+
if (resp.btcAmountGas + resp.btcAmountSwap !== amountIn)
|
|
189
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid total btc returned");
|
|
190
|
+
if (resp.gasSwapFeeBtc + resp.swapFeeBtc !== resp.totalFeeBtc)
|
|
191
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid total btc fee returned");
|
|
192
|
+
if (resp.claimerBounty !== claimerBounty)
|
|
193
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid claimer bounty");
|
|
194
|
+
if (resp.totalGas !== options.gasAmount)
|
|
195
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid total gas amount");
|
|
196
|
+
if (!amountData.exactIn) {
|
|
197
|
+
if (resp.total != amountData.amount)
|
|
198
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid amount returned");
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
if (amountIn !== amountData.amount)
|
|
202
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid payment request returned, amount mismatch");
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Returns a newly created Lightning -> Smart chain swap using the HTLC based escrow swap protocol,
|
|
207
|
+
* where watchtowers handle the automatic settlement of the swap on the destination chain. Also allows
|
|
208
|
+
* specifying additional "gas drop" native token that the receipient receives on the destination chain
|
|
209
|
+
* in the `options` argument. The user has to pay a bolt11 invoice on the input lightning network side.
|
|
210
|
+
*
|
|
211
|
+
* @param recipient Recipient's address on the destination chain
|
|
212
|
+
* @param amountData Amount, token and exact input/output data for to swap
|
|
213
|
+
* @param lps An array of intermediaries (LPs) to get the quotes from
|
|
214
|
+
* @param options Optional additional quote options
|
|
215
|
+
* @param additionalParams Optional additional parameters sent to the LP when creating the swap
|
|
216
|
+
* @param abortSignal Abort signal
|
|
217
|
+
* @param preFetches Optional pre-fetches for speeding up the quoting process (mainly used internally)
|
|
218
|
+
*/
|
|
219
|
+
create(recipient, amountData, lps, options, additionalParams, abortSignal, preFetches) {
|
|
220
|
+
if (!this.isInitialized)
|
|
221
|
+
throw new Error("Not initialized, call init() first!");
|
|
222
|
+
const _options = {
|
|
223
|
+
paymentHash: (0, Utils_1.parseHashValueExact32Bytes)(options?.paymentHash, "payment hash"),
|
|
224
|
+
unsafeSkipLnNodeCheck: options?.unsafeSkipLnNodeCheck ?? this._options.unsafeSkipLnNodeCheck,
|
|
225
|
+
gasAmount: this.parseGasAmount(options?.gasAmount),
|
|
226
|
+
feeSafetyFactor: options?.feeSafetyFactor ?? 1.25,
|
|
227
|
+
unsafeZeroWatchtowerFee: options?.unsafeZeroWatchtowerFee ?? false,
|
|
228
|
+
description: options?.description,
|
|
229
|
+
descriptionHash: (0, Utils_1.parseHashValueExact32Bytes)(options?.descriptionHash, "description hash")
|
|
230
|
+
};
|
|
231
|
+
if (amountData.token === this._chain.getNativeCurrencyAddress() && _options.gasAmount !== 0n)
|
|
232
|
+
throw new UserError_1.UserError("Cannot specify `gasAmount` for swaps to a native token!");
|
|
233
|
+
if (_options.description != null && buffer_1.Buffer.byteLength(_options.description, "utf8") > 500)
|
|
234
|
+
throw new UserError_1.UserError("Invalid description length");
|
|
235
|
+
let secret;
|
|
236
|
+
let paymentHash;
|
|
237
|
+
if (_options?.paymentHash != null) {
|
|
238
|
+
paymentHash = _options.paymentHash;
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
({ secret, paymentHash } = this.getSecretAndHash());
|
|
242
|
+
}
|
|
243
|
+
const claimHash = this._contract.getHashForHtlc(paymentHash);
|
|
244
|
+
const nativeTokenAddress = this._chain.getNativeCurrencyAddress();
|
|
245
|
+
const _abortController = (0, Utils_1.extendAbortController)(abortSignal);
|
|
246
|
+
preFetches ??= {};
|
|
247
|
+
const _preFetches = {
|
|
248
|
+
pricePrefetchPromise: preFetches?.pricePrefetchPromise ?? this.preFetchPrice(amountData, _abortController.signal),
|
|
249
|
+
usdPricePrefetchPromise: preFetches?.usdPricePrefetchPromise ?? this.preFetchUsdPrice(_abortController.signal),
|
|
250
|
+
claimerBountyPrefetch: preFetches?.claimerBountyPrefetch ?? this.preFetchClaimerBounty(recipient, amountData, _options, _abortController),
|
|
251
|
+
gasTokenPricePrefetchPromise: _options.gasAmount !== 0n || !_options.unsafeZeroWatchtowerFee ?
|
|
252
|
+
(preFetches.gasTokenPricePrefetchPromise ??= this.preFetchPrice({ token: nativeTokenAddress }, _abortController.signal)) :
|
|
253
|
+
undefined
|
|
254
|
+
};
|
|
255
|
+
return lps.map(lp => {
|
|
256
|
+
return {
|
|
257
|
+
intermediary: lp,
|
|
258
|
+
quote: (async () => {
|
|
259
|
+
if (lp.services[SwapType_1.SwapType.FROM_BTCLN_AUTO] == null)
|
|
260
|
+
throw new Error("LP service for processing from btcln auto swaps not found!");
|
|
261
|
+
const abortController = (0, Utils_1.extendAbortController)(_abortController.signal);
|
|
262
|
+
const liquidityPromise = this.preFetchIntermediaryLiquidity(amountData, lp, abortController);
|
|
263
|
+
const { lnCapacityPromise, resp } = await (0, RetryUtils_1.tryWithRetries)(async (retryCount) => {
|
|
264
|
+
const { lnPublicKey, response } = IntermediaryAPI_1.IntermediaryAPI.initFromBTCLNAuto(this.chainIdentifier, lp.url, {
|
|
265
|
+
paymentHash,
|
|
266
|
+
amount: amountData.amount,
|
|
267
|
+
claimer: recipient,
|
|
268
|
+
token: amountData.token.toString(),
|
|
269
|
+
description: _options.description,
|
|
270
|
+
descriptionHash: _options.descriptionHash,
|
|
271
|
+
exactOut: !amountData.exactIn,
|
|
272
|
+
additionalParams,
|
|
273
|
+
gasToken: this._chain.getNativeCurrencyAddress(),
|
|
274
|
+
gasAmount: _options.gasAmount,
|
|
275
|
+
claimerBounty: (0, Utils_1.throwIfUndefined)(_preFetches.claimerBountyPrefetch)
|
|
276
|
+
}, this._options.postRequestTimeout, abortController.signal, retryCount > 0 ? false : undefined);
|
|
277
|
+
let lnCapacityPromise;
|
|
278
|
+
if (!_options.unsafeSkipLnNodeCheck) {
|
|
279
|
+
lnCapacityPromise = this.preFetchLnCapacity(lnPublicKey);
|
|
280
|
+
}
|
|
281
|
+
else
|
|
282
|
+
lnPublicKey.catch(() => { });
|
|
283
|
+
return {
|
|
284
|
+
lnCapacityPromise,
|
|
285
|
+
resp: await response
|
|
286
|
+
};
|
|
287
|
+
}, undefined, RequestError_1.RequestError, abortController.signal);
|
|
288
|
+
const decodedPr = (0, bolt11_1.decode)(resp.pr);
|
|
289
|
+
if (decodedPr.millisatoshis == null)
|
|
290
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid returned swap invoice, no msat amount field");
|
|
291
|
+
if (decodedPr.timeExpireDate == null)
|
|
292
|
+
throw new IntermediaryError_1.IntermediaryError("Invalid returned swap invoice, no expiry date field");
|
|
293
|
+
const amountIn = (BigInt(decodedPr.millisatoshis) + 999n) / 1000n;
|
|
294
|
+
const claimerBounty = (await _preFetches.claimerBountyPrefetch);
|
|
295
|
+
try {
|
|
296
|
+
this.verifyReturnedData(resp, amountData, lp, _options, decodedPr, paymentHash, claimerBounty);
|
|
297
|
+
const [pricingInfo, gasPricingInfo] = await Promise.all([
|
|
298
|
+
this.verifyReturnedPrice(lp.services[SwapType_1.SwapType.FROM_BTCLN_AUTO], false, resp.btcAmountSwap, resp.total, amountData.token, { swapFeeBtc: resp.swapFeeBtc }, _preFetches.pricePrefetchPromise, _preFetches.usdPricePrefetchPromise, abortController.signal),
|
|
299
|
+
_options.gasAmount === 0n ? Promise.resolve(undefined) : this.verifyReturnedPrice({ ...lp.services[SwapType_1.SwapType.FROM_BTCLN_AUTO], swapBaseFee: 0 }, //Base fee should be charged only on the amount, not on gas
|
|
300
|
+
false, resp.btcAmountGas, resp.totalGas + resp.claimerBounty, nativeTokenAddress, { swapFeeBtc: resp.gasSwapFeeBtc }, _preFetches.gasTokenPricePrefetchPromise, _preFetches.usdPricePrefetchPromise, abortController.signal),
|
|
301
|
+
this.verifyIntermediaryLiquidity(resp.total, (0, Utils_1.throwIfUndefined)(liquidityPromise)),
|
|
302
|
+
_options.unsafeSkipLnNodeCheck ? Promise.resolve() : this.verifyLnNodeCapacity(lp, decodedPr, lnCapacityPromise, abortController.signal)
|
|
303
|
+
]);
|
|
304
|
+
const swapInit = {
|
|
305
|
+
pricingInfo,
|
|
306
|
+
url: lp.url,
|
|
307
|
+
expiry: decodedPr.timeExpireDate * 1000,
|
|
308
|
+
swapFee: resp.swapFee,
|
|
309
|
+
gasSwapFee: resp.gasSwapFee,
|
|
310
|
+
swapFeeBtc: resp.swapFeeBtc,
|
|
311
|
+
gasSwapFeeBtc: resp.gasSwapFeeBtc,
|
|
312
|
+
btcAmountGas: resp.btcAmountGas,
|
|
313
|
+
btcAmountSwap: resp.btcAmountSwap,
|
|
314
|
+
gasPricingInfo,
|
|
315
|
+
initialSwapData: await this._contract.createSwapData(base_1.ChainSwapType.HTLC, lp.getAddress(this.chainIdentifier), recipient, amountData.token, resp.total, claimHash.toString("hex"), this.getRandomSequence(), BigInt(Math.floor(Date.now() / 1000)), false, true, _options.gasAmount + resp.claimerBounty, resp.claimerBounty, nativeTokenAddress),
|
|
316
|
+
pr: resp.pr,
|
|
317
|
+
secret: secret?.toString("hex"),
|
|
318
|
+
exactIn: amountData.exactIn ?? true
|
|
319
|
+
};
|
|
320
|
+
const quote = new FromBTCLNAutoSwap_1.FromBTCLNAutoSwap(this, swapInit);
|
|
321
|
+
return quote;
|
|
322
|
+
}
|
|
323
|
+
catch (e) {
|
|
324
|
+
abortController.abort(e);
|
|
325
|
+
throw e;
|
|
326
|
+
}
|
|
327
|
+
})()
|
|
328
|
+
};
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Returns a newly created Lightning -> Smart chain swap using the HTLC based escrow swap protocol,
|
|
333
|
+
* where watchtowers handle the automatic settlement of the swap on the destination chain. Also allows
|
|
334
|
+
* specifying additional "gas drop" native token that the receipient receives on the destination chain
|
|
335
|
+
* in the `options` argument. The swap is created with an LNURL-withdraw link which will be used to pay
|
|
336
|
+
* the generated bolt11 invoice automatically when {@link FromBTCLNSwap.waitForPayment} is called on the
|
|
337
|
+
* swap.
|
|
338
|
+
*
|
|
339
|
+
* @param recipient Recipient's address on the destination chain
|
|
340
|
+
* @param lnurl LNURL-withdraw link to pull the funds from
|
|
341
|
+
* @param amountData Amount, token and exact input/output data for to swap
|
|
342
|
+
* @param lps An array of intermediaries (LPs) to get the quotes from
|
|
343
|
+
* @param options Optional additional quote options
|
|
344
|
+
* @param additionalParams Optional additional parameters sent to the LP when creating the swap
|
|
345
|
+
* @param abortSignal Abort signal
|
|
346
|
+
*/
|
|
347
|
+
async createViaLNURL(recipient, lnurl, amountData, lps, options, additionalParams, abortSignal) {
|
|
348
|
+
if (!this.isInitialized)
|
|
349
|
+
throw new Error("Not initialized, call init() first!");
|
|
350
|
+
const _options = {
|
|
351
|
+
paymentHash: (0, Utils_1.parseHashValueExact32Bytes)(options?.paymentHash, "payment hash"),
|
|
352
|
+
unsafeSkipLnNodeCheck: options?.unsafeSkipLnNodeCheck ?? this._options.unsafeSkipLnNodeCheck,
|
|
353
|
+
gasAmount: this.parseGasAmount(options?.gasAmount),
|
|
354
|
+
feeSafetyFactor: options?.feeSafetyFactor ?? 1.25,
|
|
355
|
+
unsafeZeroWatchtowerFee: options?.unsafeZeroWatchtowerFee ?? false,
|
|
356
|
+
description: options?.description,
|
|
357
|
+
descriptionHash: (0, Utils_1.parseHashValueExact32Bytes)(options?.descriptionHash, "description hash")
|
|
358
|
+
};
|
|
359
|
+
const abortController = (0, Utils_1.extendAbortController)(abortSignal);
|
|
360
|
+
const preFetches = {
|
|
361
|
+
pricePrefetchPromise: this.preFetchPrice(amountData, abortController.signal),
|
|
362
|
+
usdPricePrefetchPromise: this.preFetchUsdPrice(abortController.signal),
|
|
363
|
+
gasTokenPricePrefetchPromise: _options.gasAmount !== 0n || !_options.unsafeZeroWatchtowerFee ?
|
|
364
|
+
this.preFetchPrice({ token: this._chain.getNativeCurrencyAddress() }, abortController.signal) :
|
|
365
|
+
undefined,
|
|
366
|
+
claimerBountyPrefetch: this.preFetchClaimerBounty(recipient, amountData, _options, abortController)
|
|
367
|
+
};
|
|
368
|
+
try {
|
|
369
|
+
const exactOutAmountPromise = !amountData.exactIn ? preFetches.pricePrefetchPromise.then(price => this._prices.getToBtcSwapAmount(this.chainIdentifier, amountData.amount, amountData.token, abortController.signal, price)).catch(e => {
|
|
370
|
+
abortController.abort(e);
|
|
371
|
+
return undefined;
|
|
372
|
+
}) : undefined;
|
|
373
|
+
const withdrawRequest = await this.getLNURLWithdraw(lnurl, abortController.signal);
|
|
374
|
+
const min = BigInt(withdrawRequest.minWithdrawable) / 1000n;
|
|
375
|
+
const max = BigInt(withdrawRequest.maxWithdrawable) / 1000n;
|
|
376
|
+
if (amountData.exactIn) {
|
|
377
|
+
if (amountData.amount < min)
|
|
378
|
+
throw new UserError_1.UserError("Amount less than LNURL-withdraw minimum");
|
|
379
|
+
if (amountData.amount > max)
|
|
380
|
+
throw new UserError_1.UserError("Amount more than LNURL-withdraw maximum");
|
|
381
|
+
}
|
|
382
|
+
else {
|
|
383
|
+
const amount = (await exactOutAmountPromise);
|
|
384
|
+
abortController.signal.throwIfAborted();
|
|
385
|
+
if ((amount * 95n / 100n) < min)
|
|
386
|
+
throw new UserError_1.UserError("Amount less than LNURL-withdraw minimum");
|
|
387
|
+
if ((amount * 105n / 100n) > max)
|
|
388
|
+
throw new UserError_1.UserError("Amount more than LNURL-withdraw maximum");
|
|
389
|
+
}
|
|
390
|
+
return this.create(recipient, amountData, lps, _options, additionalParams, abortSignal, preFetches).map(data => {
|
|
391
|
+
return {
|
|
392
|
+
quote: data.quote.then(quote => {
|
|
393
|
+
quote._setLNURLData(withdrawRequest.url, withdrawRequest.k1, withdrawRequest.callback);
|
|
394
|
+
const amountIn = quote.getInput().rawAmount;
|
|
395
|
+
if (amountIn < min)
|
|
396
|
+
throw new UserError_1.UserError("Amount less than LNURL-withdraw minimum");
|
|
397
|
+
if (amountIn > max)
|
|
398
|
+
throw new UserError_1.UserError("Amount more than LNURL-withdraw maximum");
|
|
399
|
+
return quote;
|
|
400
|
+
}),
|
|
401
|
+
intermediary: data.intermediary
|
|
402
|
+
};
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
catch (e) {
|
|
406
|
+
abortController.abort(e);
|
|
407
|
+
throw e;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* @inheritDoc
|
|
412
|
+
* @internal
|
|
413
|
+
*/
|
|
414
|
+
async _checkPastSwaps(pastSwaps) {
|
|
415
|
+
const changedSwapSet = new Set();
|
|
416
|
+
const swapExpiredStatus = {};
|
|
417
|
+
const checkStatusSwaps = [];
|
|
418
|
+
await Promise.all(pastSwaps.map(async (pastSwap) => {
|
|
419
|
+
if (pastSwap._shouldCheckIntermediary()) {
|
|
420
|
+
try {
|
|
421
|
+
const result = await pastSwap._checkIntermediaryPaymentReceived(false);
|
|
422
|
+
if (result != null) {
|
|
423
|
+
changedSwapSet.add(pastSwap);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
catch (e) {
|
|
427
|
+
this.logger.error(`_checkPastSwaps(): Failed to contact LP regarding swap ${pastSwap.getId()}, error: `, e);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if (pastSwap._shouldFetchExpiryStatus()) {
|
|
431
|
+
//Check expiry
|
|
432
|
+
swapExpiredStatus[pastSwap.getId()] = await pastSwap._verifyQuoteDefinitelyExpired();
|
|
433
|
+
}
|
|
434
|
+
if (pastSwap._shouldFetchOnchainState()) {
|
|
435
|
+
//Add to swaps for which status should be checked
|
|
436
|
+
if (pastSwap._data != null)
|
|
437
|
+
checkStatusSwaps.push(pastSwap);
|
|
438
|
+
}
|
|
439
|
+
}));
|
|
440
|
+
const swapStatuses = await this._contract.getCommitStatuses(checkStatusSwaps.map(val => ({ signer: val._getInitiator(), swapData: val._data })));
|
|
441
|
+
for (let pastSwap of checkStatusSwaps) {
|
|
442
|
+
const shouldSave = await pastSwap._sync(false, swapExpiredStatus[pastSwap.getId()], swapStatuses[pastSwap.getEscrowHash()], true);
|
|
443
|
+
if (shouldSave) {
|
|
444
|
+
changedSwapSet.add(pastSwap);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
const changedSwaps = [];
|
|
448
|
+
const removeSwaps = [];
|
|
449
|
+
changedSwapSet.forEach(val => {
|
|
450
|
+
if (val.isQuoteExpired()) {
|
|
451
|
+
removeSwaps.push(val);
|
|
452
|
+
}
|
|
453
|
+
else {
|
|
454
|
+
changedSwaps.push(val);
|
|
455
|
+
}
|
|
456
|
+
});
|
|
457
|
+
return {
|
|
458
|
+
changedSwaps,
|
|
459
|
+
removeSwaps
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* @inheritDoc
|
|
464
|
+
*/
|
|
465
|
+
async recoverFromSwapDataAndState(init, state, lp) {
|
|
466
|
+
const data = init.data;
|
|
467
|
+
let paymentHash = data.getHTLCHashHint();
|
|
468
|
+
let secret;
|
|
469
|
+
if (state.type === base_1.SwapCommitStateType.PAID) {
|
|
470
|
+
secret = await state.getClaimResult();
|
|
471
|
+
paymentHash = buffer_1.Buffer.from((0, sha2_1.sha256)(buffer_1.Buffer.from(secret, "hex"))).toString("hex");
|
|
472
|
+
}
|
|
473
|
+
const swapInit = {
|
|
474
|
+
pricingInfo: {
|
|
475
|
+
isValid: true,
|
|
476
|
+
satsBaseFee: 0n,
|
|
477
|
+
swapPriceUSatPerToken: 100000000000000n,
|
|
478
|
+
realPriceUSatPerToken: 100000000000000n,
|
|
479
|
+
differencePPM: 0n,
|
|
480
|
+
feePPM: 0n,
|
|
481
|
+
},
|
|
482
|
+
url: lp?.url,
|
|
483
|
+
expiry: 0,
|
|
484
|
+
swapFee: 0n,
|
|
485
|
+
swapFeeBtc: 0n,
|
|
486
|
+
gasSwapFee: 0n,
|
|
487
|
+
gasSwapFeeBtc: 0n,
|
|
488
|
+
initialSwapData: data,
|
|
489
|
+
data,
|
|
490
|
+
pr: paymentHash ?? undefined,
|
|
491
|
+
secret,
|
|
492
|
+
exactIn: false
|
|
493
|
+
};
|
|
494
|
+
const swap = new FromBTCLNAutoSwap_1.FromBTCLNAutoSwap(this, swapInit);
|
|
495
|
+
swap._commitTxId = await init.getInitTxId();
|
|
496
|
+
const blockData = await init.getTxBlock();
|
|
497
|
+
swap.createdAt = blockData.blockTime * 1000;
|
|
498
|
+
swap._commitedAt = blockData.blockTime * 1000;
|
|
499
|
+
swap._setInitiated();
|
|
500
|
+
swap._state = FromBTCLNAutoSwap_1.FromBTCLNAutoSwapState.CLAIM_COMMITED;
|
|
501
|
+
await swap._sync(false, false, state);
|
|
502
|
+
await swap._save();
|
|
503
|
+
return swap;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
exports.FromBTCLNAutoWrapper = FromBTCLNAutoWrapper;
|