@atomiqlabs/sdk 8.7.7 → 8.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/api/index.d.ts +1 -0
  2. package/api/index.js +3 -0
  3. package/dist/ApiList.d.ts +37 -0
  4. package/dist/ApiList.js +30 -0
  5. package/dist/api/ApiEndpoints.d.ts +393 -0
  6. package/dist/api/ApiEndpoints.js +2 -0
  7. package/dist/api/ApiParser.d.ts +10 -0
  8. package/dist/api/ApiParser.js +134 -0
  9. package/dist/api/ApiTypes.d.ts +157 -0
  10. package/dist/api/ApiTypes.js +75 -0
  11. package/dist/api/SerializedAction.d.ts +40 -0
  12. package/dist/api/SerializedAction.js +59 -0
  13. package/dist/api/SwapperApi.d.ts +50 -0
  14. package/dist/api/SwapperApi.js +431 -0
  15. package/dist/api/index.d.ts +5 -0
  16. package/dist/api/index.js +24 -0
  17. package/dist/bitcoin/coinselect2/accumulative.d.ts +1 -0
  18. package/dist/bitcoin/coinselect2/accumulative.js +1 -1
  19. package/dist/bitcoin/coinselect2/blackjack.d.ts +1 -0
  20. package/dist/bitcoin/coinselect2/blackjack.js +1 -1
  21. package/dist/bitcoin/coinselect2/index.d.ts +3 -2
  22. package/dist/bitcoin/coinselect2/index.js +2 -2
  23. package/dist/bitcoin/coinselect2/utils.d.ts +7 -2
  24. package/dist/bitcoin/coinselect2/utils.js +45 -10
  25. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +8 -25
  26. package/dist/bitcoin/wallet/BitcoinWallet.js +31 -18
  27. package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +40 -2
  28. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +7 -2
  29. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +10 -4
  30. package/dist/events/UnifiedSwapEventListener.d.ts +4 -3
  31. package/dist/events/UnifiedSwapEventListener.js +8 -2
  32. package/dist/http/HttpUtils.d.ts +4 -2
  33. package/dist/http/HttpUtils.js +10 -4
  34. package/dist/http/paramcoders/client/StreamingFetchPromise.d.ts +2 -1
  35. package/dist/http/paramcoders/client/StreamingFetchPromise.js +3 -2
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.js +1 -0
  38. package/dist/intermediaries/IntermediaryDiscovery.d.ts +7 -2
  39. package/dist/intermediaries/IntermediaryDiscovery.js +4 -4
  40. package/dist/intermediaries/apis/IntermediaryAPI.d.ts +182 -15
  41. package/dist/intermediaries/apis/IntermediaryAPI.js +192 -31
  42. package/dist/intermediaries/auth/SignedKeyBasedAuth.d.ts +14 -0
  43. package/dist/intermediaries/auth/SignedKeyBasedAuth.js +68 -0
  44. package/dist/storage/IUnifiedStorage.d.ts +45 -3
  45. package/dist/storage/UnifiedSwapStorage.d.ts +8 -2
  46. package/dist/storage/UnifiedSwapStorage.js +46 -8
  47. package/dist/swapper/Swapper.d.ts +77 -4
  48. package/dist/swapper/Swapper.js +117 -25
  49. package/dist/swapper/SwapperUtils.d.ts +18 -2
  50. package/dist/swapper/SwapperUtils.js +39 -1
  51. package/dist/swaps/ISwap.d.ts +70 -9
  52. package/dist/swaps/ISwap.js +28 -6
  53. package/dist/swaps/ISwapWrapper.d.ts +11 -1
  54. package/dist/swaps/ISwapWrapper.js +23 -3
  55. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +1 -1
  56. package/dist/swaps/escrow_swaps/IEscrowSwap.js +4 -2
  57. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +2 -1
  58. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +2 -2
  59. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +3 -1
  60. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +3 -2
  61. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +47 -31
  62. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +201 -67
  63. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +3 -1
  64. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +6 -6
  65. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +82 -15
  66. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +304 -98
  67. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +3 -1
  68. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +6 -6
  69. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +75 -42
  70. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +424 -87
  71. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +3 -1
  72. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +7 -7
  73. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +54 -11
  74. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +214 -41
  75. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +2 -1
  76. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +7 -8
  77. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +3 -1
  78. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +5 -5
  79. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +85 -22
  80. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +299 -56
  81. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +41 -7
  82. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +183 -58
  83. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +53 -12
  84. package/dist/swaps/trusted/ln/LnForGasSwap.js +163 -49
  85. package/dist/swaps/trusted/ln/LnForGasWrapper.js +1 -2
  86. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +14 -13
  87. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +30 -47
  88. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +3 -1
  89. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +4 -4
  90. package/dist/types/SwapExecutionAction.d.ts +141 -34
  91. package/dist/types/SwapExecutionAction.js +104 -0
  92. package/dist/types/SwapExecutionStep.d.ts +144 -0
  93. package/dist/types/SwapExecutionStep.js +87 -0
  94. package/dist/types/TokenAmount.d.ts +6 -0
  95. package/dist/types/TokenAmount.js +26 -1
  96. package/dist/utils/BitcoinUtils.d.ts +4 -0
  97. package/dist/utils/BitcoinUtils.js +73 -1
  98. package/dist/utils/BitcoinWalletUtils.d.ts +2 -2
  99. package/dist/utils/Utils.d.ts +3 -1
  100. package/dist/utils/Utils.js +7 -1
  101. package/package.json +7 -4
  102. package/src/api/ApiEndpoints.ts +427 -0
  103. package/src/api/ApiParser.ts +138 -0
  104. package/src/api/ApiTypes.ts +229 -0
  105. package/src/api/SerializedAction.ts +97 -0
  106. package/src/api/SwapperApi.ts +545 -0
  107. package/src/api/index.ts +5 -0
  108. package/src/bitcoin/coinselect2/accumulative.ts +2 -1
  109. package/src/bitcoin/coinselect2/blackjack.ts +2 -1
  110. package/src/bitcoin/coinselect2/index.ts +5 -4
  111. package/src/bitcoin/coinselect2/utils.ts +55 -14
  112. package/src/bitcoin/wallet/BitcoinWallet.ts +69 -57
  113. package/src/bitcoin/wallet/IBitcoinWallet.ts +44 -3
  114. package/src/bitcoin/wallet/SingleAddressBitcoinWallet.ts +12 -4
  115. package/src/events/UnifiedSwapEventListener.ts +11 -3
  116. package/src/http/HttpUtils.ts +10 -4
  117. package/src/http/paramcoders/client/StreamingFetchPromise.ts +4 -2
  118. package/src/index.ts +1 -0
  119. package/src/intermediaries/IntermediaryDiscovery.ts +9 -2
  120. package/src/intermediaries/apis/IntermediaryAPI.ts +335 -35
  121. package/src/intermediaries/auth/SignedKeyBasedAuth.ts +69 -0
  122. package/src/storage/IUnifiedStorage.ts +45 -4
  123. package/src/storage/UnifiedSwapStorage.ts +42 -8
  124. package/src/swapper/Swapper.ts +165 -24
  125. package/src/swapper/SwapperUtils.ts +42 -2
  126. package/src/swaps/ISwap.ts +88 -16
  127. package/src/swaps/ISwapWrapper.ts +28 -3
  128. package/src/swaps/escrow_swaps/IEscrowSwap.ts +5 -3
  129. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +3 -1
  130. package/src/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.ts +4 -1
  131. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +264 -67
  132. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +6 -4
  133. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +390 -89
  134. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +6 -4
  135. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +548 -94
  136. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +7 -5
  137. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +276 -45
  138. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +7 -6
  139. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +5 -3
  140. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +413 -64
  141. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +239 -61
  142. package/src/swaps/trusted/ln/LnForGasSwap.ts +211 -47
  143. package/src/swaps/trusted/ln/LnForGasWrapper.ts +1 -2
  144. package/src/swaps/trusted/onchain/OnchainForGasSwap.ts +32 -51
  145. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +5 -3
  146. package/src/types/SwapExecutionAction.ts +266 -43
  147. package/src/types/SwapExecutionStep.ts +224 -0
  148. package/src/types/TokenAmount.ts +36 -2
  149. package/src/utils/BitcoinUtils.ts +73 -0
  150. package/src/utils/BitcoinWalletUtils.ts +2 -2
  151. package/src/utils/Utils.ts +10 -1
  152. package/src/intermediaries/apis/TrustedIntermediaryAPI.ts +0 -258
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ISwapWrapper = exports.DEFAULT_MAX_PARALLEL_SWAP_SYNCS = exports.DEFAULT_MAX_PARALLEL_SWAP_TICKS = void 0;
4
+ const base_1 = require("@atomiqlabs/base");
4
5
  const events_1 = require("events");
5
6
  const IntermediaryError_1 = require("../errors/IntermediaryError");
6
7
  const Logger_1 = require("../utils/Logger");
@@ -14,7 +15,7 @@ exports.DEFAULT_MAX_PARALLEL_SWAP_SYNCS = 50;
14
15
  * @category Swaps/Base
15
16
  */
16
17
  class ISwapWrapper {
17
- constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, options, events) {
18
+ constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, lpApi, options, events) {
18
19
  /**
19
20
  * Logger instance
20
21
  * @internal
@@ -41,6 +42,7 @@ class ISwapWrapper {
41
42
  this._chain = chain;
42
43
  this._prices = prices;
43
44
  this.events = events || new events_1.EventEmitter();
45
+ this._lpApi = lpApi;
44
46
  this._options = options;
45
47
  this._tokens = tokens;
46
48
  }
@@ -247,8 +249,8 @@ class ISwapWrapper {
247
249
  for (let i = 0; i < pastSwaps.length; i += maxParallelSyncs) {
248
250
  const { removeSwaps, changedSwaps } = await this._checkPastSwaps(pastSwaps.slice(i, i + maxParallelSyncs));
249
251
  if (!noSave) {
250
- await this.unifiedStorage.removeAll(removeSwaps);
251
- await this.unifiedStorage.saveAll(changedSwaps);
252
+ await this.unifiedStorage.removeAll(removeSwaps, true);
253
+ await this.unifiedStorage.saveAll(changedSwaps, true);
252
254
  changedSwaps.forEach(swap => swap._emitEvent());
253
255
  removeSwaps.forEach(swap => swap._emitEvent());
254
256
  }
@@ -349,5 +351,23 @@ class ISwapWrapper {
349
351
  _getPendingSwap(id) {
350
352
  return this.pendingSwaps.get(id)?.deref() ?? null;
351
353
  }
354
+ /**
355
+ * @internal
356
+ */
357
+ async _getSignerAddress(signer) {
358
+ let address = undefined;
359
+ if (signer != null) {
360
+ if (typeof (signer) === "string") {
361
+ address = signer;
362
+ }
363
+ else if ((0, base_1.isAbstractSigner)(signer)) {
364
+ address = signer.getAddress();
365
+ }
366
+ else {
367
+ address = (await this._chain.wrapSigner(signer)).getAddress();
368
+ }
369
+ }
370
+ return address;
371
+ }
352
372
  }
353
373
  exports.ISwapWrapper = ISwapWrapper;
@@ -93,7 +93,7 @@ export declare abstract class IEscrowSwap<T extends ChainType = ChainType, D ext
93
93
  * @param abortSignal
94
94
  * @internal
95
95
  */
96
- protected watchdogWaitTillCommited(intervalSeconds?: number, abortSignal?: AbortSignal): Promise<boolean>;
96
+ protected watchdogWaitTillCommited(intervalSeconds?: number, abortSignal?: AbortSignal): Promise<SwapCommitState | null>;
97
97
  /**
98
98
  * Periodically checks the chain to see whether the swap was finished (claimed or refunded)
99
99
  *
@@ -118,7 +118,7 @@ class IEscrowSwap extends ISwap_1.ISwap {
118
118
  status = await this._contract.getCommitStatus(this._getInitiator(), this._data);
119
119
  if (status?.type === base_1.SwapCommitStateType.NOT_COMMITED &&
120
120
  await this._verifyQuoteDefinitelyExpired())
121
- return false;
121
+ return null;
122
122
  }
123
123
  catch (e) {
124
124
  this.logger.error("watchdogWaitTillCommited(): Error when fetching commit status or signature expiry: ", e);
@@ -126,7 +126,9 @@ class IEscrowSwap extends ISwap_1.ISwap {
126
126
  }
127
127
  if (abortSignal != null)
128
128
  abortSignal.throwIfAborted();
129
- return status?.type !== base_1.SwapCommitStateType.EXPIRED;
129
+ return status?.type === base_1.SwapCommitStateType.EXPIRED
130
+ ? null
131
+ : status;
130
132
  }
131
133
  /**
132
134
  * Periodically checks the chain to see whether the swap was finished (claimed or refunded)
@@ -9,6 +9,7 @@ import { EventEmitter } from "events";
9
9
  import { SwapType } from "../../enums/SwapType";
10
10
  import { IEscrowSwap } from "./IEscrowSwap";
11
11
  import { Intermediary } from "../../intermediaries/Intermediary";
12
+ import { IntermediaryAPI } from "../../intermediaries/apis/IntermediaryAPI";
12
13
  export type IEscrowSwapDefinition<T extends ChainType, W extends IEscrowSwapWrapper<T, any>, S extends IEscrowSwap<T>> = SwapTypeDefinition<T, W, S>;
13
14
  /**
14
15
  * Base class for wrappers of escrow-based swaps (i.e. swaps utilizing PrTLC and HTLC primitives)
@@ -31,7 +32,7 @@ export declare abstract class IEscrowSwapWrapper<T extends ChainType, D extends
31
32
  swapDataConstructor: new (data: any) => T["Data"];
32
33
  };
33
34
  };
34
- constructor(chainIdentifier: string, unifiedStorage: UnifiedSwapStorage<T>, unifiedChainEvents: UnifiedSwapEventListener<T>, chain: T["ChainInterface"], prices: ISwapPrice, tokens: WrapperCtorTokens, options: O, versionedContracts: {
35
+ constructor(chainIdentifier: string, unifiedStorage: UnifiedSwapStorage<T>, unifiedChainEvents: UnifiedSwapEventListener<T>, chain: T["ChainInterface"], prices: ISwapPrice, tokens: WrapperCtorTokens, lpApi: IntermediaryAPI, options: O, versionedContracts: {
35
36
  [version: string]: {
36
37
  swapContract: T["Contract"];
37
38
  swapDataConstructor: new (data: any) => T["Data"];
@@ -9,8 +9,8 @@ const base_1 = require("@atomiqlabs/base");
9
9
  * @category Swaps/Abstract
10
10
  */
11
11
  class IEscrowSwapWrapper extends ISwapWrapper_1.ISwapWrapper {
12
- constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, options, versionedContracts, events) {
13
- super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, options, events);
12
+ constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, lpApi, options, versionedContracts, events) {
13
+ super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, lpApi, options, events);
14
14
  /**
15
15
  * @internal
16
16
  */
@@ -13,6 +13,7 @@ import { Intermediary } from "../../../intermediaries/Intermediary";
13
13
  import { PaymentRequestObject, TagsObject } from "@atomiqlabs/bolt11";
14
14
  import { IEscrowSwap } from "../IEscrowSwap";
15
15
  import { LNURLWithdrawParamsWithUrl } from "../../../types/lnurl/LNURLWithdraw";
16
+ import { IntermediaryAPI } from "../../../intermediaries/apis/IntermediaryAPI";
16
17
  export type IFromBTCLNDefinition<T extends ChainType, W extends IFromBTCLNWrapper<T, any>, S extends IEscrowSwap<T>> = IFromBTCDefinition<T, W, S>;
17
18
  /**
18
19
  * Base class for wrappers of escrow-based Lightning -> Smart chain swaps
@@ -33,6 +34,7 @@ export declare abstract class IFromBTCLNWrapper<T extends ChainType, D extends I
33
34
  * @param tokens
34
35
  * @param versionedContracts
35
36
  * @param lnApi
37
+ * @param lpApi
36
38
  * @param options
37
39
  * @param events Instance to use for emitting events
38
40
  */
@@ -41,7 +43,7 @@ export declare abstract class IFromBTCLNWrapper<T extends ChainType, D extends I
41
43
  swapContract: T["Contract"];
42
44
  swapDataConstructor: new (data: any) => T["Data"];
43
45
  };
44
- }, lnApi: LightningNetworkApi, options: O, events?: EventEmitter<{
46
+ }, lnApi: LightningNetworkApi, lpApi: IntermediaryAPI, options: O, events?: EventEmitter<{
45
47
  swapState: [IEscrowSwap];
46
48
  }>);
47
49
  /**
@@ -23,11 +23,12 @@ class IFromBTCLNWrapper extends IFromBTCWrapper_1.IFromBTCWrapper {
23
23
  * @param tokens
24
24
  * @param versionedContracts
25
25
  * @param lnApi
26
+ * @param lpApi
26
27
  * @param options
27
28
  * @param events Instance to use for emitting events
28
29
  */
29
- constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, versionedContracts, lnApi, options, events) {
30
- super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, options, versionedContracts, events);
30
+ constructor(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, versionedContracts, lnApi, lpApi, options, events) {
31
+ super(chainIdentifier, unifiedStorage, unifiedChainEvents, chain, prices, tokens, lpApi, options, versionedContracts, events);
31
32
  this.lnApi = lnApi;
32
33
  }
33
34
  /**
@@ -13,7 +13,9 @@ import { TokenAmount } from "../../../../types/TokenAmount";
13
13
  import { BtcToken, SCToken } from "../../../../types/Token";
14
14
  import { LoggerType } from "../../../../utils/Logger";
15
15
  import { LNURLWithdraw } from "../../../../types/lnurl/LNURLWithdraw";
16
- import { SwapExecutionAction } from "../../../../types/SwapExecutionAction";
16
+ import { SwapExecutionActionSendToAddress, SwapExecutionActionSignSmartChainTx } from "../../../../types/SwapExecutionAction";
17
+ import { SwapExecutionStepPayment, SwapExecutionStepSettlement } from "../../../../types/SwapExecutionStep";
18
+ import { SwapStateInfo } from "../../../../types/SwapStateInfo";
17
19
  /**
18
20
  * State enum for legacy Lightning -> Smart chain swaps
19
21
  * @category Swaps/Legacy/Lightning → Smart chain
@@ -287,6 +289,31 @@ export declare class FromBTCLNSwap<T extends ChainType = ChainType> extends IFro
287
289
  lightningTxCheckIntervalSeconds?: number;
288
290
  delayBetweenCommitAndClaimSeconds?: number;
289
291
  }): Promise<boolean>;
292
+ /**
293
+ * @internal
294
+ */
295
+ protected _getExecutionStatus(options?: {
296
+ secret?: string;
297
+ }): Promise<{
298
+ steps: [SwapExecutionStepPayment<"LIGHTNING">, SwapExecutionStepSettlement<T["ChainId"], "awaiting_manual">];
299
+ buildCurrentAction: (actionOptions?: {
300
+ skipChecks?: boolean;
301
+ }) => Promise<SwapExecutionActionSendToAddress<true> | SwapExecutionActionSignSmartChainTx<T> | undefined>;
302
+ state: FromBTCLNSwapState;
303
+ }>;
304
+ /**
305
+ * @internal
306
+ */
307
+ private _buildLightningPaymentAction;
308
+ /**
309
+ * @inheritDoc
310
+ * @internal
311
+ */
312
+ _submitExecutionTransactions(txs: (T["SignedTXType"] | string)[], abortSignal?: AbortSignal, requiredStates?: FromBTCLNSwapState[], idempotent?: boolean): Promise<string[]>;
313
+ /**
314
+ * @internal
315
+ */
316
+ private _buildClaimSmartChainTxAction;
290
317
  /**
291
318
  * @inheritDoc
292
319
  *
@@ -297,43 +324,32 @@ export declare class FromBTCLNSwap<T extends ChainType = ChainType> extends IFro
297
324
  * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
298
325
  * was recovered from on-chain data, or the pre-image was generated outside the SDK
299
326
  */
300
- txsExecute(options?: {
327
+ getExecutionAction(options?: {
301
328
  skipChecks?: boolean;
302
329
  secret?: string;
303
- }): Promise<{
304
- name: "Payment";
305
- description: string;
306
- chain: "LIGHTNING";
307
- txs: {
308
- type: "BOLT11_PAYMENT_REQUEST";
309
- address: string;
310
- hyperlink: string;
311
- }[];
312
- }[] | ({
313
- name: "Commit";
314
- description: string;
315
- chain: T["ChainId"];
316
- txs: T["TX"][];
317
- } | {
318
- name: "Claim";
319
- description: string;
320
- chain: T["ChainId"];
321
- txs: T["TX"][];
322
- })[]>;
330
+ }): Promise<SwapExecutionActionSendToAddress<true> | SwapExecutionActionSignSmartChainTx<T> | undefined>;
323
331
  /**
324
332
  * @inheritDoc
325
- *
326
- * @param options
327
- * @param options.skipChecks Skip checks like making sure init signature is still valid and swap
328
- * wasn't commited yet (this is handled on swap creation, if you commit right after quoting, you
329
- * can use `skipChecks=true`)
330
- * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
331
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
332
333
  */
333
- getCurrentActions(options?: {
334
+ getExecutionStatus(options?: {
335
+ skipBuildingAction?: boolean;
334
336
  skipChecks?: boolean;
335
337
  secret?: string;
336
- }): Promise<SwapExecutionAction<T>[]>;
338
+ }): Promise<{
339
+ steps: [
340
+ SwapExecutionStepPayment<"LIGHTNING">,
341
+ SwapExecutionStepSettlement<T["ChainId"], "awaiting_manual">
342
+ ];
343
+ currentAction: SwapExecutionActionSendToAddress<true> | SwapExecutionActionSignSmartChainTx<T> | undefined;
344
+ stateInfo: SwapStateInfo<FromBTCLNSwapState>;
345
+ }>;
346
+ /**
347
+ * @inheritDoc
348
+ */
349
+ getExecutionSteps(): Promise<[
350
+ SwapExecutionStepPayment<"LIGHTNING">,
351
+ SwapExecutionStepSettlement<T["ChainId"], "awaiting_manual">
352
+ ]>;
337
353
  /**
338
354
  * Checks whether the LP received the LN payment and we can continue by committing & claiming the HTLC on-chain
339
355
  *
@@ -497,66 +497,166 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
497
497
  return true;
498
498
  }
499
499
  /**
500
- * @inheritDoc
501
- *
502
- * @param options
503
- * @param options.skipChecks Skip checks like making sure init signature is still valid and swap
504
- * wasn't commited yet (this is handled on swap creation, if you commit right after quoting, you
505
- * can use `skipChecks=true`)
506
- * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
507
- * was recovered from on-chain data, or the pre-image was generated outside the SDK
500
+ * @internal
508
501
  */
509
- async txsExecute(options) {
510
- if (this._state === FromBTCLNSwapState.PR_CREATED) {
511
- if (!await this._verifyQuoteValid())
512
- throw new Error("Quote already expired or close to expiry!");
513
- return [
514
- {
515
- name: "Payment",
516
- description: "Initiates the swap by paying up the lightning network invoice",
517
- chain: "LIGHTNING",
518
- txs: [
519
- {
520
- type: "BOLT11_PAYMENT_REQUEST",
521
- address: this.getAddress(),
522
- hyperlink: this.getHyperlink()
523
- }
524
- ]
502
+ async _getExecutionStatus(options) {
503
+ if (options?.secret != null)
504
+ this.setSecretPreimage(options.secret);
505
+ const state = this._state;
506
+ let lightningPaymentStatus = "inactive";
507
+ let destinationSettlementStatus = "inactive";
508
+ let buildCurrentAction = async () => undefined;
509
+ switch (state) {
510
+ case FromBTCLNSwapState.PR_CREATED: {
511
+ const quoteValid = await this._verifyQuoteValid();
512
+ lightningPaymentStatus = quoteValid ? "awaiting" : "soft_expired";
513
+ if (quoteValid && this.pr != null && this.pr.toLowerCase().startsWith("ln")) {
514
+ buildCurrentAction = this._buildLightningPaymentAction.bind(this);
515
+ }
516
+ break;
517
+ }
518
+ case FromBTCLNSwapState.QUOTE_SOFT_EXPIRED:
519
+ if (this.signatureData == null) {
520
+ lightningPaymentStatus = "soft_expired";
521
+ }
522
+ else {
523
+ lightningPaymentStatus = "received";
524
+ destinationSettlementStatus = "soft_expired";
525
+ }
526
+ break;
527
+ case FromBTCLNSwapState.PR_PAID:
528
+ case FromBTCLNSwapState.CLAIM_COMMITED:
529
+ lightningPaymentStatus = "received";
530
+ destinationSettlementStatus = "awaiting_manual";
531
+ if ((state !== FromBTCLNSwapState.PR_PAID || await this._verifyQuoteValid()) &&
532
+ this.hasSecretPreimage()) {
533
+ buildCurrentAction = this._buildClaimSmartChainTxAction.bind(this);
525
534
  }
526
- ];
535
+ break;
536
+ case FromBTCLNSwapState.CLAIM_CLAIMED:
537
+ lightningPaymentStatus = "confirmed";
538
+ destinationSettlementStatus = "settled";
539
+ break;
540
+ case FromBTCLNSwapState.EXPIRED:
541
+ case FromBTCLNSwapState.FAILED:
542
+ lightningPaymentStatus = "expired";
543
+ destinationSettlementStatus = "expired";
544
+ break;
545
+ case FromBTCLNSwapState.QUOTE_EXPIRED:
546
+ if (this.signatureData == null) {
547
+ lightningPaymentStatus = "expired";
548
+ }
549
+ else {
550
+ lightningPaymentStatus = "expired";
551
+ destinationSettlementStatus = "expired";
552
+ }
553
+ break;
527
554
  }
528
- if (this._state === FromBTCLNSwapState.PR_PAID) {
529
- if (!await this._verifyQuoteValid())
530
- throw new Error("Quote already expired or close to expiry!");
531
- const txsCommit = await this.txsCommit(options?.skipChecks);
532
- const txsClaim = await this._txsClaim(undefined, options?.secret);
533
- return [
555
+ return {
556
+ steps: [
534
557
  {
535
- name: "Commit",
536
- description: `Creates the HTLC escrow on the ${this.chainIdentifier} side`,
537
- chain: this.chainIdentifier,
538
- txs: txsCommit
558
+ type: "Payment",
559
+ side: "source",
560
+ chain: "LIGHTNING",
561
+ title: "Lightning payment",
562
+ description: "Pay the Lightning network invoice to initiate the swap",
563
+ status: lightningPaymentStatus,
564
+ initTxId: this.getInputTxId(),
565
+ settleTxId: lightningPaymentStatus === "confirmed" ? this.getInputTxId() : undefined
539
566
  },
540
567
  {
541
- name: "Claim",
542
- description: `Settles & claims the funds from the HTLC escrow on the ${this.chainIdentifier} side`,
568
+ type: "Settlement",
569
+ side: "destination",
543
570
  chain: this.chainIdentifier,
544
- txs: txsClaim
545
- },
546
- ];
571
+ title: "Destination settlement",
572
+ description: `Manually settle the swap on the ${this.chainIdentifier} side`,
573
+ status: destinationSettlementStatus,
574
+ initTxId: this._commitTxId,
575
+ settleTxId: this._claimTxId
576
+ }
577
+ ],
578
+ buildCurrentAction,
579
+ state
580
+ };
581
+ }
582
+ /**
583
+ * @internal
584
+ */
585
+ async _buildLightningPaymentAction() {
586
+ return {
587
+ type: "SendToAddress",
588
+ name: "Deposit on Lightning",
589
+ description: "Pay the lightning network invoice to initiate the swap",
590
+ chain: "LIGHTNING",
591
+ txs: [{
592
+ type: "BOLT11_PAYMENT_REQUEST",
593
+ address: this.getAddress(),
594
+ hyperlink: this.getHyperlink(),
595
+ amount: this.getInput()
596
+ }],
597
+ waitForTransactions: async (maxWaitTimeSeconds, pollIntervalSeconds, abortSignal) => {
598
+ const abortController = (0, Utils_1.extendAbortController)(abortSignal, maxWaitTimeSeconds, "Timed out waiting for lightning payment");
599
+ const success = await this.waitForPayment(undefined, pollIntervalSeconds, abortController.signal);
600
+ if (!success)
601
+ throw new Error("Quote expired while waiting for Lightning payment");
602
+ return this.getInputTxId();
603
+ }
604
+ };
605
+ }
606
+ /**
607
+ * @inheritDoc
608
+ * @internal
609
+ */
610
+ async _submitExecutionTransactions(txs, abortSignal, requiredStates, idempotent) {
611
+ const parsedTxs = [];
612
+ for (let tx of txs) {
613
+ parsedTxs.push(typeof (tx) === "string" ? await this.wrapper._chain.deserializeSignedTx(tx) : tx);
614
+ }
615
+ if (idempotent) {
616
+ // Handle idempotent calls
617
+ if (this.wrapper._chain.getTxId != null) {
618
+ const txIds = await Promise.all(parsedTxs.map(tx => this.wrapper._chain.getTxId(tx)));
619
+ const foundTxId = txIds.find(txId => this._commitTxId === txId || this._claimTxId === txId);
620
+ if (foundTxId != null)
621
+ return txIds;
622
+ }
623
+ }
624
+ if (requiredStates != null && !requiredStates.includes(this._state))
625
+ throw new Error("Swap state has changed before transactions were submitted!");
626
+ if (this._state === FromBTCLNSwapState.PR_PAID || this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
627
+ if (!await this._verifyQuoteValid())
628
+ throw new Error("Quote is already expired!");
629
+ const txIds = await this.wrapper._chain.sendSignedAndConfirm(parsedTxs, true, abortSignal, false);
630
+ await this.waitTillCommited(abortSignal);
631
+ await this.waitTillClaimed(undefined, abortSignal);
632
+ return txIds;
547
633
  }
548
634
  if (this._state === FromBTCLNSwapState.CLAIM_COMMITED) {
549
- const txsClaim = await this.txsClaim(undefined, options?.secret);
550
- return [
551
- {
552
- name: "Claim",
553
- description: `Settles & claims the funds from the HTLC escrow on the ${this.chainIdentifier} side`,
554
- chain: this.chainIdentifier,
555
- txs: txsClaim
556
- },
557
- ];
635
+ const txIds = await this.wrapper._chain.sendSignedAndConfirm(parsedTxs, true, abortSignal, false);
636
+ await this.waitTillClaimed(undefined, abortSignal);
637
+ return txIds;
558
638
  }
559
- throw new Error("Invalid swap state to obtain execution txns, required PR_CREATED, PR_PAID or CLAIM_COMMITED");
639
+ throw new Error("Invalid swap state for transaction submission!");
640
+ }
641
+ /**
642
+ * @internal
643
+ */
644
+ async _buildClaimSmartChainTxAction(actionOptions) {
645
+ return {
646
+ type: "SignSmartChainTransaction",
647
+ name: "Settle manually",
648
+ description: "Create the HTLC escrow and settle the swap on the destination smart chain",
649
+ chain: this.chainIdentifier,
650
+ txs: await this.prepareTransactions(this.txsCommitAndClaim(actionOptions?.skipChecks, actionOptions?.secret)),
651
+ submitTransactions: async (txs, abortSignal, idempotent) => {
652
+ return this._submitExecutionTransactions(txs, abortSignal, [
653
+ FromBTCLNSwapState.PR_PAID,
654
+ FromBTCLNSwapState.QUOTE_SOFT_EXPIRED,
655
+ FromBTCLNSwapState.CLAIM_COMMITED
656
+ ], idempotent);
657
+ },
658
+ requiredSigner: this._getInitiator()
659
+ };
560
660
  }
561
661
  /**
562
662
  * @inheritDoc
@@ -568,13 +668,27 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
568
668
  * @param options.secret A swap secret to use for the claim transaction, generally only needed if the swap
569
669
  * was recovered from on-chain data, or the pre-image was generated outside the SDK
570
670
  */
571
- async getCurrentActions(options) {
572
- try {
573
- return await this.txsExecute(options);
574
- }
575
- catch (e) {
576
- return [];
577
- }
671
+ async getExecutionAction(options) {
672
+ const executionStatus = await this._getExecutionStatus(options);
673
+ return executionStatus.buildCurrentAction(options);
674
+ }
675
+ /**
676
+ * @inheritDoc
677
+ */
678
+ // TODO: Figure how we gonna trigger an LNURL-withdraw with the execution actions
679
+ async getExecutionStatus(options) {
680
+ const executionStatus = await this._getExecutionStatus(options);
681
+ return {
682
+ steps: executionStatus.steps,
683
+ currentAction: options?.skipBuildingAction ? undefined : await executionStatus.buildCurrentAction(options),
684
+ stateInfo: this._getStateInfo(executionStatus.state)
685
+ };
686
+ }
687
+ /**
688
+ * @inheritDoc
689
+ */
690
+ async getExecutionSteps() {
691
+ return (await this._getExecutionStatus()).steps;
578
692
  }
579
693
  //////////////////////////////
580
694
  //// Payment
@@ -599,7 +713,7 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
599
713
  const paymentHash = this.getPaymentHash();
600
714
  if (paymentHash == null)
601
715
  throw new Error("Failed to check LP payment received, payment hash not known (probably recovered swap?)");
602
- const resp = await IntermediaryAPI_1.IntermediaryAPI.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
716
+ const resp = await this.wrapper._lpApi.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
603
717
  switch (resp.code) {
604
718
  case IntermediaryAPI_1.PaymentAuthorizationResponseCodes.AUTH_DATA:
605
719
  const data = new (this.wrapper._swapDataDeserializer(this._contractVersion))(resp.data.data);
@@ -722,7 +836,7 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
722
836
  throw new Error("Swap payment hash not available, the swap was probably recovered!");
723
837
  let resp = { code: IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING, msg: "" };
724
838
  while (!abortController.signal.aborted && resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING) {
725
- resp = await IntermediaryAPI_1.IntermediaryAPI.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
839
+ resp = await this.wrapper._lpApi.getPaymentAuthorization(this.url, paymentHash.toString("hex"));
726
840
  if (resp.code === IntermediaryAPI_1.PaymentAuthorizationResponseCodes.PENDING)
727
841
  await (0, TimeoutUtils_1.timeoutPromise)(checkIntervalSeconds * 1000, abortController.signal);
728
842
  }
@@ -792,11 +906,13 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
792
906
  this.waitTillState(FromBTCLNSwapState.CLAIM_COMMITED, "gte", abortController.signal).then(() => 0)
793
907
  ]);
794
908
  abortController.abort();
795
- if (result === 0)
909
+ if (result === 0) {
796
910
  this.logger.debug("waitTillCommited(): Resolved from state changed");
797
- if (result === true)
911
+ }
912
+ else if (result != null) {
798
913
  this.logger.debug("waitTillCommited(): Resolved from watchdog - commited");
799
- if (result === false) {
914
+ }
915
+ if (result === null) {
800
916
  this.logger.debug("waitTillCommited(): Resolved from watchdog - signature expired");
801
917
  if (this._state === FromBTCLNSwapState.PR_PAID ||
802
918
  this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
@@ -806,6 +922,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
806
922
  }
807
923
  if (this._state === FromBTCLNSwapState.PR_PAID ||
808
924
  this._state === FromBTCLNSwapState.QUOTE_SOFT_EXPIRED) {
925
+ if (typeof (result) === "object" && result.getInitTxId != null && this._commitTxId == null)
926
+ this._commitTxId = await result.getInitTxId();
809
927
  await this._saveAndEmit(FromBTCLNSwapState.CLAIM_COMMITED);
810
928
  }
811
929
  }
@@ -1208,6 +1326,8 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
1208
1326
  async _forciblySetOnchainState(commitStatus) {
1209
1327
  switch (commitStatus.type) {
1210
1328
  case base_1.SwapCommitStateType.PAID:
1329
+ if (this._commitTxId == null && commitStatus.getInitTxId != null)
1330
+ this._commitTxId = await commitStatus.getInitTxId();
1211
1331
  if (this._claimTxId == null)
1212
1332
  this._claimTxId = await commitStatus.getClaimTxId();
1213
1333
  if (this.secret == null || this.pr == null)
@@ -1215,24 +1335,38 @@ class FromBTCLNSwap extends IFromBTCSelfInitSwap_1.IFromBTCSelfInitSwap {
1215
1335
  this._state = FromBTCLNSwapState.CLAIM_CLAIMED;
1216
1336
  return true;
1217
1337
  case base_1.SwapCommitStateType.NOT_COMMITED:
1218
- if (this._refundTxId == null && commitStatus.getRefundTxId)
1338
+ let changed = false;
1339
+ if (this._commitTxId == null && commitStatus.getInitTxId != null) {
1340
+ this._commitTxId = await commitStatus.getInitTxId();
1341
+ changed = true;
1342
+ }
1343
+ if (this._refundTxId == null && commitStatus.getRefundTxId) {
1219
1344
  this._refundTxId = await commitStatus.getRefundTxId();
1345
+ changed = true;
1346
+ }
1220
1347
  if (this._refundTxId != null) {
1221
1348
  this._state = FromBTCLNSwapState.FAILED;
1222
- return true;
1349
+ changed = true;
1223
1350
  }
1224
- break;
1351
+ return changed;
1225
1352
  case base_1.SwapCommitStateType.EXPIRED:
1353
+ if (this._commitTxId == null && commitStatus.getInitTxId != null)
1354
+ this._commitTxId = await commitStatus.getInitTxId();
1226
1355
  if (this._refundTxId == null && commitStatus.getRefundTxId)
1227
1356
  this._refundTxId = await commitStatus.getRefundTxId();
1228
1357
  this._state = this._refundTxId == null ? FromBTCLNSwapState.QUOTE_EXPIRED : FromBTCLNSwapState.FAILED;
1229
1358
  return true;
1230
1359
  case base_1.SwapCommitStateType.COMMITED:
1360
+ let save = false;
1361
+ if (this._commitTxId == null && commitStatus.getInitTxId != null) {
1362
+ this._commitTxId = await commitStatus.getInitTxId();
1363
+ save = true;
1364
+ }
1231
1365
  if (this._state !== FromBTCLNSwapState.CLAIM_COMMITED && this._state !== FromBTCLNSwapState.EXPIRED) {
1232
1366
  this._state = FromBTCLNSwapState.CLAIM_COMMITED;
1233
- return true;
1367
+ save = true;
1234
1368
  }
1235
- break;
1369
+ return save;
1236
1370
  }
1237
1371
  return false;
1238
1372
  }
@@ -6,6 +6,7 @@ import { ChainType, ClaimEvent, InitializeEvent, LightningNetworkApi, RefundEven
6
6
  import { Intermediary } from "../../../../intermediaries/Intermediary";
7
7
  import { Buffer } from "buffer";
8
8
  import { SwapType } from "../../../../enums/SwapType";
9
+ import { IntermediaryAPI } from "../../../../intermediaries/apis/IntermediaryAPI";
9
10
  import { ISwapPrice } from "../../../../prices/abstract/ISwapPrice";
10
11
  import { EventEmitter } from "events";
11
12
  import { ISwapWrapperOptions, WrapperCtorTokens } from "../../../ISwapWrapper";
@@ -83,6 +84,7 @@ export declare class FromBTCLNWrapper<T extends ChainType> extends IFromBTCLNWra
83
84
  * @param tokens
84
85
  * @param versionedContracts
85
86
  * @param lnApi
87
+ * @param lpApi
86
88
  * @param options
87
89
  * @param events Instance to use for emitting events
88
90
  */
@@ -91,7 +93,7 @@ export declare class FromBTCLNWrapper<T extends ChainType> extends IFromBTCLNWra
91
93
  swapContract: T["Contract"];
92
94
  swapDataConstructor: new (data: any) => T["Data"];
93
95
  };
94
- }, lnApi: LightningNetworkApi, options?: AllOptional<FromBTCLNWrapperOptions>, events?: EventEmitter<{
96
+ }, lnApi: LightningNetworkApi, lpApi: IntermediaryAPI, options?: AllOptional<FromBTCLNWrapperOptions>, events?: EventEmitter<{
95
97
  swapState: [ISwap];
96
98
  }>);
97
99
  /**