@atomiqlabs/sdk 8.1.7 → 8.3.1

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 (253) hide show
  1. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +41 -5
  2. package/dist/bitcoin/wallet/BitcoinWallet.js +36 -1
  3. package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +52 -2
  4. package/dist/bitcoin/wallet/IBitcoinWallet.js +2 -1
  5. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +42 -7
  6. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +36 -1
  7. package/dist/enums/FeeType.d.ts +7 -0
  8. package/dist/enums/FeeType.js +7 -0
  9. package/dist/enums/SwapAmountType.d.ts +7 -0
  10. package/dist/enums/SwapAmountType.js +7 -0
  11. package/dist/enums/SwapDirection.d.ts +7 -0
  12. package/dist/enums/SwapDirection.js +7 -0
  13. package/dist/enums/SwapType.d.ts +62 -1
  14. package/dist/enums/SwapType.js +62 -1
  15. package/dist/errors/IntermediaryError.d.ts +4 -0
  16. package/dist/errors/IntermediaryError.js +1 -0
  17. package/dist/errors/RequestError.d.ts +15 -1
  18. package/dist/errors/RequestError.js +8 -0
  19. package/dist/errors/UserError.d.ts +1 -0
  20. package/dist/errors/UserError.js +1 -0
  21. package/dist/index.d.ts +4 -5
  22. package/dist/index.js +3 -4
  23. package/dist/intermediaries/Intermediary.d.ts +57 -10
  24. package/dist/intermediaries/Intermediary.js +37 -10
  25. package/dist/intermediaries/IntermediaryDiscovery.d.ts +55 -22
  26. package/dist/intermediaries/IntermediaryDiscovery.js +35 -22
  27. package/dist/prices/RedundantSwapPrice.d.ts +24 -3
  28. package/dist/prices/RedundantSwapPrice.js +21 -1
  29. package/dist/prices/SingleSwapPrice.d.ts +9 -6
  30. package/dist/prices/SingleSwapPrice.js +10 -7
  31. package/dist/prices/SwapPriceWithChain.d.ts +54 -16
  32. package/dist/prices/SwapPriceWithChain.js +58 -20
  33. package/dist/prices/abstract/ISwapPrice.d.ts +94 -45
  34. package/dist/prices/abstract/ISwapPrice.js +103 -55
  35. package/dist/prices/providers/BinancePriceProvider.d.ts +7 -0
  36. package/dist/prices/providers/BinancePriceProvider.js +7 -0
  37. package/dist/prices/providers/CoinGeckoPriceProvider.d.ts +6 -0
  38. package/dist/prices/providers/CoinGeckoPriceProvider.js +6 -0
  39. package/dist/prices/providers/CoinPaprikaPriceProvider.d.ts +6 -0
  40. package/dist/prices/providers/CoinPaprikaPriceProvider.js +6 -0
  41. package/dist/prices/providers/CustomPriceProvider.d.ts +11 -0
  42. package/dist/prices/providers/CustomPriceProvider.js +11 -0
  43. package/dist/prices/providers/KrakenPriceProvider.d.ts +9 -0
  44. package/dist/prices/providers/KrakenPriceProvider.js +9 -0
  45. package/dist/prices/providers/OKXPriceProvider.d.ts +6 -0
  46. package/dist/prices/providers/OKXPriceProvider.js +6 -0
  47. package/dist/prices/providers/abstract/ExchangePriceProvider.d.ts +3 -0
  48. package/dist/prices/providers/abstract/ExchangePriceProvider.js +3 -0
  49. package/dist/storage/IUnifiedStorage.d.ts +19 -7
  50. package/dist/storage/UnifiedSwapStorage.d.ts +33 -3
  51. package/dist/storage/UnifiedSwapStorage.js +29 -1
  52. package/dist/storage-browser/IndexedDBUnifiedStorage.d.ts +31 -7
  53. package/dist/storage-browser/IndexedDBUnifiedStorage.js +29 -6
  54. package/dist/storage-browser/LocalStorageManager.d.ts +25 -1
  55. package/dist/storage-browser/LocalStorageManager.js +25 -1
  56. package/dist/swapper/Swapper.d.ts +303 -222
  57. package/dist/swapper/Swapper.js +376 -344
  58. package/dist/swapper/SwapperFactory.d.ts +41 -17
  59. package/dist/swapper/SwapperFactory.js +23 -2
  60. package/dist/swapper/SwapperUtils.d.ts +75 -28
  61. package/dist/swapper/SwapperUtils.js +107 -60
  62. package/dist/swapper/SwapperWithChain.d.ts +286 -91
  63. package/dist/swapper/SwapperWithChain.js +218 -64
  64. package/dist/swapper/SwapperWithSigner.d.ts +229 -80
  65. package/dist/swapper/SwapperWithSigner.js +190 -44
  66. package/dist/swaps/IAddressSwap.d.ts +10 -1
  67. package/dist/swaps/IAddressSwap.js +2 -1
  68. package/dist/swaps/IBTCWalletSwap.d.ts +24 -6
  69. package/dist/swaps/IBTCWalletSwap.js +2 -1
  70. package/dist/swaps/IClaimableSwap.d.ts +36 -4
  71. package/dist/swaps/IClaimableSwap.js +2 -1
  72. package/dist/swaps/IClaimableSwapWrapper.d.ts +11 -1
  73. package/dist/swaps/IRefundableSwap.d.ts +29 -3
  74. package/dist/swaps/IRefundableSwap.js +2 -1
  75. package/dist/swaps/ISwap.d.ts +159 -21
  76. package/dist/swaps/ISwap.js +90 -33
  77. package/dist/swaps/ISwapWithGasDrop.d.ts +6 -0
  78. package/dist/swaps/ISwapWithGasDrop.js +1 -0
  79. package/dist/swaps/ISwapWrapper.d.ts +157 -48
  80. package/dist/swaps/ISwapWrapper.js +130 -72
  81. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.d.ts +49 -6
  82. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.js +22 -12
  83. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +65 -12
  84. package/dist/swaps/escrow_swaps/IEscrowSwap.js +38 -19
  85. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +39 -9
  86. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +30 -21
  87. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +31 -15
  88. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +33 -18
  89. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +94 -29
  90. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +90 -27
  91. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.d.ts +22 -9
  92. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.js +24 -11
  93. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +275 -58
  94. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +516 -239
  95. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +76 -25
  96. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +131 -49
  97. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +311 -51
  98. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +542 -193
  99. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +87 -26
  100. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +147 -58
  101. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +209 -53
  102. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +449 -242
  103. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +77 -23
  104. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +116 -46
  105. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +197 -56
  106. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +326 -189
  107. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.d.ts +30 -5
  108. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +44 -19
  109. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.d.ts +60 -19
  110. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +74 -31
  111. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +76 -50
  112. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +106 -101
  113. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.d.ts +36 -13
  114. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.js +65 -19
  115. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +46 -17
  116. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +82 -27
  117. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +328 -92
  118. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +460 -219
  119. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +76 -24
  120. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +244 -124
  121. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +146 -18
  122. package/dist/swaps/trusted/ln/LnForGasSwap.js +173 -43
  123. package/dist/swaps/trusted/ln/LnForGasWrapper.d.ts +29 -10
  124. package/dist/swaps/trusted/ln/LnForGasWrapper.js +30 -11
  125. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +200 -47
  126. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +230 -78
  127. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +34 -12
  128. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +33 -14
  129. package/dist/types/AmountData.d.ts +2 -1
  130. package/dist/types/CustomPriceFunction.d.ts +7 -1
  131. package/dist/types/SwapExecutionAction.d.ts +74 -4
  132. package/dist/types/SwapWithSigner.d.ts +4 -1
  133. package/dist/types/SwapWithSigner.js +5 -2
  134. package/dist/types/Token.d.ts +11 -5
  135. package/dist/types/Token.js +6 -3
  136. package/dist/types/TokenAmount.d.ts +3 -0
  137. package/dist/types/TokenAmount.js +2 -0
  138. package/dist/types/fees/Fee.d.ts +2 -1
  139. package/dist/types/fees/FeeBreakdown.d.ts +2 -1
  140. package/dist/types/fees/PercentagePPM.d.ts +2 -0
  141. package/dist/types/fees/PercentagePPM.js +1 -0
  142. package/dist/types/lnurl/LNURLPay.d.ts +14 -6
  143. package/dist/types/lnurl/LNURLPay.js +6 -2
  144. package/dist/types/lnurl/LNURLWithdraw.d.ts +12 -5
  145. package/dist/types/lnurl/LNURLWithdraw.js +6 -2
  146. package/dist/types/wallets/LightningInvoiceCreateService.d.ts +20 -0
  147. package/dist/types/wallets/LightningInvoiceCreateService.js +15 -0
  148. package/dist/types/wallets/MinimalBitcoinWalletInterface.d.ts +3 -1
  149. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.d.ts +3 -1
  150. package/dist/utils/BitcoinUtils.d.ts +1 -0
  151. package/dist/utils/BitcoinUtils.js +5 -1
  152. package/dist/utils/SwapUtils.d.ts +56 -1
  153. package/dist/utils/SwapUtils.js +53 -1
  154. package/dist/utils/TokenUtils.d.ts +10 -2
  155. package/dist/utils/TokenUtils.js +12 -4
  156. package/package.json +3 -3
  157. package/src/bitcoin/wallet/BitcoinWallet.ts +41 -5
  158. package/src/bitcoin/wallet/IBitcoinWallet.ts +57 -2
  159. package/src/bitcoin/wallet/SingleAddressBitcoinWallet.ts +42 -6
  160. package/src/enums/FeeType.ts +7 -0
  161. package/src/enums/SwapAmountType.ts +7 -0
  162. package/src/enums/SwapDirection.ts +7 -0
  163. package/src/enums/SwapType.ts +62 -2
  164. package/src/errors/IntermediaryError.ts +4 -0
  165. package/src/errors/RequestError.ts +15 -1
  166. package/src/errors/UserError.ts +1 -0
  167. package/src/index.ts +6 -5
  168. package/src/intermediaries/Intermediary.ts +57 -10
  169. package/src/intermediaries/IntermediaryDiscovery.ts +60 -27
  170. package/src/prices/RedundantSwapPrice.ts +24 -4
  171. package/src/prices/SingleSwapPrice.ts +10 -7
  172. package/src/prices/SwapPriceWithChain.ts +59 -21
  173. package/src/prices/abstract/ISwapPrice.ts +114 -65
  174. package/src/prices/providers/BinancePriceProvider.ts +7 -0
  175. package/src/prices/providers/CoinGeckoPriceProvider.ts +6 -0
  176. package/src/prices/providers/CoinPaprikaPriceProvider.ts +6 -0
  177. package/src/prices/providers/CustomPriceProvider.ts +11 -0
  178. package/src/prices/providers/KrakenPriceProvider.ts +9 -0
  179. package/src/prices/providers/OKXPriceProvider.ts +6 -0
  180. package/src/prices/providers/abstract/ExchangePriceProvider.ts +3 -0
  181. package/src/storage/IUnifiedStorage.ts +19 -7
  182. package/src/storage/UnifiedSwapStorage.ts +33 -3
  183. package/src/storage-browser/IndexedDBUnifiedStorage.ts +31 -8
  184. package/src/storage-browser/LocalStorageManager.ts +25 -1
  185. package/src/swapper/Swapper.ts +513 -379
  186. package/src/swapper/SwapperFactory.ts +44 -21
  187. package/src/swapper/SwapperUtils.ts +107 -60
  188. package/src/swapper/SwapperWithChain.ts +320 -81
  189. package/src/swapper/SwapperWithSigner.ts +263 -56
  190. package/src/swaps/IAddressSwap.ts +11 -1
  191. package/src/swaps/IBTCWalletSwap.ts +24 -8
  192. package/src/swaps/IClaimableSwap.ts +39 -4
  193. package/src/swaps/IClaimableSwapWrapper.ts +11 -2
  194. package/src/swaps/IRefundableSwap.ts +32 -3
  195. package/src/swaps/ISwap.ts +221 -82
  196. package/src/swaps/ISwapWithGasDrop.ts +6 -0
  197. package/src/swaps/ISwapWrapper.ts +212 -94
  198. package/src/swaps/escrow_swaps/IEscrowSelfInitSwap.ts +62 -18
  199. package/src/swaps/escrow_swaps/IEscrowSwap.ts +83 -37
  200. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +61 -30
  201. package/src/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.ts +37 -19
  202. package/src/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.ts +120 -51
  203. package/src/swaps/escrow_swaps/frombtc/IFromBTCWrapper.ts +24 -11
  204. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +559 -256
  205. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +155 -61
  206. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +590 -226
  207. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +177 -74
  208. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +470 -243
  209. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +141 -59
  210. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +352 -193
  211. package/src/swaps/escrow_swaps/tobtc/IToBTCWrapper.ts +48 -23
  212. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.ts +86 -39
  213. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +110 -110
  214. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.ts +88 -33
  215. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +101 -31
  216. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +534 -263
  217. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +289 -148
  218. package/src/swaps/trusted/ln/LnForGasSwap.ts +184 -45
  219. package/src/swaps/trusted/ln/LnForGasWrapper.ts +34 -15
  220. package/src/swaps/trusted/onchain/OnchainForGasSwap.ts +260 -86
  221. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +41 -19
  222. package/src/types/AmountData.ts +2 -1
  223. package/src/types/CustomPriceFunction.ts +7 -1
  224. package/src/types/SwapExecutionAction.ts +84 -5
  225. package/src/types/SwapWithSigner.ts +7 -3
  226. package/src/types/Token.ts +12 -5
  227. package/src/types/TokenAmount.ts +3 -0
  228. package/src/types/fees/Fee.ts +2 -1
  229. package/src/types/fees/FeeBreakdown.ts +2 -1
  230. package/src/types/fees/PercentagePPM.ts +2 -0
  231. package/src/types/lnurl/LNURLPay.ts +14 -6
  232. package/src/types/lnurl/LNURLWithdraw.ts +12 -5
  233. package/src/types/wallets/LightningInvoiceCreateService.ts +26 -0
  234. package/src/types/wallets/MinimalBitcoinWalletInterface.ts +3 -1
  235. package/src/types/wallets/MinimalLightningNetworkWalletInterface.ts +3 -1
  236. package/src/utils/BitcoinUtils.ts +5 -0
  237. package/src/utils/SwapUtils.ts +61 -1
  238. package/src/utils/TokenUtils.ts +12 -4
  239. package/dist/bitcoin/BitcoinRpcWithAddressIndex.d.ts +0 -68
  240. package/dist/bitcoin/BitcoinRpcWithAddressIndex.js +0 -2
  241. package/dist/bitcoin/LightningNetworkApi.d.ts +0 -12
  242. package/dist/bitcoin/LightningNetworkApi.js +0 -2
  243. package/dist/bitcoin/mempool/MempoolApi.d.ts +0 -350
  244. package/dist/bitcoin/mempool/MempoolApi.js +0 -311
  245. package/dist/bitcoin/mempool/MempoolBitcoinBlock.d.ts +0 -44
  246. package/dist/bitcoin/mempool/MempoolBitcoinBlock.js +0 -48
  247. package/dist/bitcoin/mempool/MempoolBitcoinRpc.d.ts +0 -119
  248. package/dist/bitcoin/mempool/MempoolBitcoinRpc.js +0 -361
  249. package/dist/bitcoin/mempool/synchronizer/MempoolBtcRelaySynchronizer.d.ts +0 -22
  250. package/dist/bitcoin/mempool/synchronizer/MempoolBtcRelaySynchronizer.js +0 -105
  251. package/dist/errors/PaymentAuthError.d.ts +0 -11
  252. package/dist/errors/PaymentAuthError.js +0 -23
  253. package/src/errors/PaymentAuthError.ts +0 -26
@@ -8,43 +8,51 @@ import {toBigInt} from "../../../../utils/Utils";
8
8
  import {TokenAmount, toTokenAmount} from "../../../../types/TokenAmount";
9
9
  import {BitcoinTokens, BtcToken} from "../../../../types/Token";
10
10
  import {getLogger, LoggerType} from "../../../../utils/Logger";
11
+ import {fromOutputScript} from "../../../../utils/BitcoinUtils";
11
12
 
12
13
 
13
14
  export type ToBTCSwapInit<T extends SwapData> = IToBTCSwapInit<T> & {
14
- address: string;
15
- amount: bigint;
15
+ address?: string;
16
+ amount?: bigint;
16
17
  confirmationTarget: number;
17
18
  satsPerVByte: number;
18
- requiredConfirmations: number;
19
- nonce: bigint;
19
+ requiredConfirmations?: number;
20
+ nonce?: bigint;
20
21
  };
21
22
 
22
23
  export function isToBTCSwapInit<T extends SwapData>(obj: any): obj is ToBTCSwapInit<T> {
23
- return typeof (obj.address) === "string" &&
24
- typeof(obj.amount) === "bigint" &&
24
+ return (obj.address==null || typeof (obj.address) === "string") &&
25
+ (obj.amount==null || typeof(obj.amount) === "bigint") &&
25
26
  typeof (obj.confirmationTarget) === "number" &&
26
27
  typeof (obj.satsPerVByte) === "number" &&
27
- typeof (obj.requiredConfirmations) === "number" &&
28
- typeof (obj.nonce) === "bigint" &&
28
+ (obj.requiredConfirmations==null || typeof (obj.requiredConfirmations) === "number") &&
29
+ (obj.nonce==null || typeof (obj.nonce) === "bigint") &&
29
30
  isIToBTCSwapInit<T>(obj);
30
31
  }
31
32
 
32
33
  /**
33
- * Smart Chain to on-chain BTC swap
34
+ * Escrow based (PrTLC) swap for Smart chains -> Bitcoin
35
+ *
34
36
  * @category Swaps
35
37
  */
36
38
  export class ToBTCSwap<T extends ChainType = ChainType> extends IToBTCSwap<T, ToBTCDefinition<T>> {
39
+ protected readonly TYPE: SwapType.TO_BTC = SwapType.TO_BTC;
40
+ /**
41
+ * @internal
42
+ */
37
43
  protected readonly outputToken: BtcToken<false> = BitcoinTokens.BTC;
38
- protected readonly TYPE = SwapType.TO_BTC;
44
+ /**
45
+ * @internal
46
+ */
39
47
  protected readonly logger: LoggerType;
40
48
 
41
- private readonly address: string;
42
- private readonly amount: bigint;
49
+ private address?: string;
50
+ private amount?: bigint;
43
51
  private readonly confirmationTarget: number;
44
52
  private readonly satsPerVByte: number;
45
53
 
46
- private readonly requiredConfirmations: number;
47
- private readonly nonce: bigint;
54
+ private requiredConfirmations?: number;
55
+ private nonce?: bigint;
48
56
 
49
57
  private txId?: string;
50
58
 
@@ -65,33 +73,68 @@ export class ToBTCSwap<T extends ChainType = ChainType> extends IToBTCSwap<T, To
65
73
  this.nonce = initOrObject.nonce;
66
74
  } else {
67
75
  this.address = initOrObject.address;
68
- this.amount = BigInt(initOrObject.amount);
76
+ this.amount = toBigInt(initOrObject.amount);
69
77
  this.confirmationTarget = initOrObject.confirmationTarget;
70
78
  this.satsPerVByte = initOrObject.satsPerVByte;
71
79
  this.txId = initOrObject.txId;
72
80
 
73
- this.requiredConfirmations = initOrObject.requiredConfirmations ?? this.data.getConfirmationsHint();
74
- this.nonce = toBigInt(initOrObject.nonce) ?? this.data.getNonceHint();
81
+ this.requiredConfirmations = initOrObject.requiredConfirmations ?? this._data.getConfirmationsHint();
82
+ this.nonce = toBigInt(initOrObject.nonce) ?? this._data.getNonceHint();
75
83
  }
76
84
  this.logger = getLogger("ToBTC("+this.getIdentifierHashString()+"): ");
77
85
  this.tryRecomputeSwapPrice();
78
86
  }
79
87
 
88
+ /**
89
+ * @inheritDoc
90
+ * @internal
91
+ */
80
92
  async _setPaymentResult(result: { secret?: string; txId?: string }, check: boolean = false): Promise<boolean> {
81
93
  if(result==null) return false;
82
94
  if(result.txId==null) throw new IntermediaryError("No btc txId returned!");
83
- if(check) {
84
- const btcTx = await this.wrapper.btcRpc.getTransaction(result.txId);
95
+ if(check || this.address==null || this.amount==null || this.nonce==null || this.requiredConfirmations==null) {
96
+ const btcTx = await this.wrapper._btcRpc.getTransaction(result.txId);
85
97
  if(btcTx==null) return false;
86
98
 
87
- const foundVout = btcTx.outs.find(vout => this.data.getClaimHash()===this.wrapper.contract.getHashForOnchain(
88
- Buffer.from(vout.scriptPubKey.hex, "hex"),
89
- BigInt(vout.value),
90
- this.requiredConfirmations,
91
- this.nonce
92
- ).toString("hex"));
93
-
94
- if(foundVout==null) throw new IntermediaryError("Invalid btc txId returned");
99
+ //Extract nonce from tx
100
+ const nonce = this.nonce ?? (BigInt(btcTx.ins[0].sequence) & 0x00FFFFFFn) | (BigInt(btcTx.locktime - 500_000_000) << 24n);
101
+ let requiredConfirmations = this.requiredConfirmations;
102
+
103
+ const foundVout = btcTx.outs.find(vout => {
104
+ if(requiredConfirmations!=null) {
105
+ return this._data.getClaimHash()===this.wrapper._contract.getHashForOnchain(
106
+ Buffer.from(vout.scriptPubKey.hex, "hex"),
107
+ BigInt(vout.value),
108
+ requiredConfirmations,
109
+ nonce
110
+ ).toString("hex");
111
+ } else {
112
+ for(let i=1;i<=20;i++) {
113
+ if(
114
+ this._data.getClaimHash()===this.wrapper._contract.getHashForOnchain(
115
+ Buffer.from(vout.scriptPubKey.hex, "hex"),
116
+ BigInt(vout.value),
117
+ i,
118
+ nonce
119
+ ).toString("hex")
120
+ ) {
121
+ requiredConfirmations = i;
122
+ return true;
123
+ }
124
+ }
125
+ }
126
+ });
127
+
128
+ if(requiredConfirmations==null) this.logger.warn(`_setPaymentResult(): Tried to recover data from bitcoin transaction ${result.txId} data, but wasn't able to!`);
129
+
130
+ if(foundVout!=null) {
131
+ this.nonce = nonce;
132
+ this.address = fromOutputScript(this.wrapper._options.bitcoinNetwork, foundVout.scriptPubKey.hex);
133
+ this.amount = BigInt(foundVout.value);
134
+ this.requiredConfirmations = requiredConfirmations;
135
+ } else {
136
+ if(check) throw new IntermediaryError("Invalid btc txId returned");
137
+ }
95
138
  }
96
139
  this.txId = result.txId;
97
140
  return true;
@@ -101,12 +144,18 @@ export class ToBTCSwap<T extends ChainType = ChainType> extends IToBTCSwap<T, To
101
144
  //////////////////////////////
102
145
  //// Amounts & fees
103
146
 
147
+ /**
148
+ * @inheritDoc
149
+ */
104
150
  getOutputToken(): BtcToken<false> {
105
151
  return BitcoinTokens.BTC;
106
152
  }
107
153
 
154
+ /**
155
+ * @inheritDoc
156
+ */
108
157
  getOutput(): TokenAmount<T["ChainId"], BtcToken<false>> {
109
- return toTokenAmount(this.amount, this.outputToken, this.wrapper.prices, this.pricingInfo);
158
+ return toTokenAmount(this.amount ?? null, this.outputToken, this.wrapper._prices, this.pricingInfo);
110
159
  }
111
160
 
112
161
 
@@ -114,18 +163,21 @@ export class ToBTCSwap<T extends ChainType = ChainType> extends IToBTCSwap<T, To
114
163
  //// Getters & utils
115
164
 
116
165
  /**
117
- * Returns the bitcoin address where the BTC will be sent to
166
+ * @inheritDoc
118
167
  */
119
- getOutputAddress(): string {
120
- return this.address;
168
+ getOutputAddress(): string | null {
169
+ return this.address ?? null;
121
170
  }
122
171
 
172
+ /**
173
+ * @inheritDoc
174
+ */
123
175
  getOutputTxId(): string | null {
124
176
  return this.txId ?? null;
125
177
  }
126
178
 
127
179
  /**
128
- * Returns fee rate of the bitcoin transaction in sats/vB
180
+ * Returns fee rate of the output bitcoin transaction in sats/vB as reported by the intermediary (LP)
129
181
  */
130
182
  getBitcoinFeeRate(): number {
131
183
  return this.satsPerVByte;
@@ -135,11 +187,14 @@ export class ToBTCSwap<T extends ChainType = ChainType> extends IToBTCSwap<T, To
135
187
  //////////////////////////////
136
188
  //// Storage
137
189
 
190
+ /**
191
+ * @inheritDoc
192
+ */
138
193
  serialize(): any {
139
194
  return {
140
195
  ...super.serialize(),
141
196
  address: this.address,
142
- amount: this.amount.toString(10),
197
+ amount: this.amount==null ? null : this.amount.toString(10),
143
198
  confirmationTarget: this.confirmationTarget,
144
199
  satsPerVByte: this.satsPerVByte,
145
200
  nonce: this.nonce==null ? null : this.nonce.toString(10),
@@ -1,6 +1,12 @@
1
1
  import {ToBTCSwap, ToBTCSwapInit} from "./ToBTCSwap";
2
2
  import {IToBTCDefinition, IToBTCWrapper} from "../IToBTCWrapper";
3
- import {BigIntBufferUtils, BitcoinRpc, ChainSwapType, ChainType} from "@atomiqlabs/base";
3
+ import {
4
+ BigIntBufferUtils,
5
+ BitcoinRpc,
6
+ ChainSwapType,
7
+ ChainType,
8
+ SwapCommitState
9
+ } from "@atomiqlabs/base";
4
10
  import {Intermediary, SingleChainReputationType} from "../../../../intermediaries/Intermediary";
5
11
  import {ISwapPrice} from "../../../../prices/abstract/ISwapPrice";
6
12
  import {EventEmitter} from "events";
@@ -20,6 +26,7 @@ import {ISwap} from "../../../ISwap";
20
26
  import {AmountData} from "../../../../types/AmountData";
21
27
  import {tryWithRetries} from "../../../../utils/RetryUtils";
22
28
  import {AllOptional, AllRequired} from "../../../../utils/TypeUtils";
29
+ import {ToBTCSwapState} from "../IToBTCSwap";
23
30
 
24
31
  export type ToBTCOptions = {
25
32
  confirmationTarget?: number,
@@ -39,11 +46,21 @@ export type ToBTCWrapperOptions = ISwapWrapperOptions & {
39
46
 
40
47
  export type ToBTCDefinition<T extends ChainType> = IToBTCDefinition<T, ToBTCWrapper<T>, ToBTCSwap<T>>;
41
48
 
49
+ /**
50
+ * Escrow based (PrTLC) swap for Smart chains -> Bitcoin
51
+ *
52
+ * @category Swaps
53
+ */
42
54
  export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDefinition<T>, ToBTCWrapperOptions> {
43
- public readonly TYPE = SwapType.TO_BTC;
44
- public readonly swapDeserializer = ToBTCSwap;
45
-
46
- readonly btcRpc: BitcoinRpc<any>;
55
+ public readonly TYPE: SwapType.TO_BTC = SwapType.TO_BTC;
56
+ /**
57
+ * @internal
58
+ */
59
+ readonly _swapDeserializer = ToBTCSwap;
60
+ /**
61
+ * @internal
62
+ */
63
+ readonly _btcRpc: BitcoinRpc<any>;
47
64
 
48
65
  /**
49
66
  * @param chainIdentifier
@@ -83,13 +100,15 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
83
100
  },
84
101
  events
85
102
  );
86
- this.btcRpc = btcRpc;
103
+ this._btcRpc = btcRpc;
87
104
  }
88
105
 
89
106
  /**
90
- * Returns randomly generated random escrow nonce to be used for to BTC on-chain swaps
91
- * @private
107
+ * Returns randomly generated random bitcoin transaction nonce to be used for BTC on-chain swaps
108
+ *
92
109
  * @returns Escrow nonce
110
+ *
111
+ * @private
93
112
  */
94
113
  private getRandomNonce(): bigint {
95
114
  const firstPart = BigInt(Math.floor((Date.now()/1000)) - 700000000);
@@ -101,13 +120,15 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
101
120
  * Converts bitcoin address to its corresponding output script
102
121
  *
103
122
  * @param addr Bitcoin address to get the output script for
104
- * @private
123
+ *
105
124
  * @returns Output script as Buffer
106
125
  * @throws {UserError} if invalid address is specified
126
+ *
127
+ * @private
107
128
  */
108
129
  private btcAddressToOutputScript(addr: string): Buffer {
109
130
  try {
110
- return toOutputScript(this.options.bitcoinNetwork, addr);
131
+ return toOutputScript(this._options.bitcoinNetwork, addr);
111
132
  } catch (e) {
112
133
  throw new UserError("Invalid address specified");
113
134
  }
@@ -123,8 +144,10 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
123
144
  * @param options Options as passed to the swap create function
124
145
  * @param data LP's returned parsed swap data
125
146
  * @param hash Payment hash of the swap
126
- * @private
147
+ *
127
148
  * @throws {IntermediaryError} if returned data are not correct
149
+ *
150
+ * @private
128
151
  */
129
152
  private verifyReturnedData(
130
153
  signer: string,
@@ -146,11 +169,11 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
146
169
  const maxAllowedBlockDelta: bigint = BigInt(
147
170
  options.confirmations +
148
171
  options.confirmationTarget +
149
- this.options.maxExpectedOnchainSendGracePeriodBlocks
172
+ this._options.maxExpectedOnchainSendGracePeriodBlocks
150
173
  );
151
174
  const maxAllowedExpiryDelta: bigint = maxAllowedBlockDelta
152
- * BigInt(this.options.maxExpectedOnchainSendSafetyFactor)
153
- * BigInt(this.options.bitcoinBlocktime);
175
+ * BigInt(this._options.maxExpectedOnchainSendSafetyFactor)
176
+ * BigInt(this._options.bitcoinBlocktime);
154
177
  const currentTimestamp: bigint = BigInt(Math.floor(Date.now()/1000));
155
178
  const maxAllowedExpiryTimestamp: bigint = currentTimestamp + maxAllowedExpiryDelta;
156
179
 
@@ -173,19 +196,20 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
173
196
  }
174
197
 
175
198
  /**
176
- * Returns quotes fetched from LPs, paying to an 'address' - a bitcoin address
199
+ * Returns a newly created Smart chain -> Bitcoin swap using the PrTLC based escrow swap protocol,
200
+ * with the passed amount.
177
201
  *
178
- * @param signer Smart-chain signer address initiating the swap
179
- * @param address Bitcoin on-chain address you wish to pay to
180
- * @param amountData Amount of token & amount to swap
181
- * @param lps LPs (liquidity providers) to get the quotes from
182
- * @param options Quote options
183
- * @param additionalParams Additional parameters sent to the LP when creating the swap
184
- * @param abortSignal Abort signal for aborting the process
202
+ * @param signer Source chain signer address initiating the swap
203
+ * @param recipient Recipient bitcoin on-chain address
204
+ * @param amountData Amount, token and exact input/output data for to swap
205
+ * @param lps An array of intermediaries (LPs) to get the quotes from
206
+ * @param options Optional additional quote options
207
+ * @param additionalParams Optional additional parameters sent to the LP when creating the swap
208
+ * @param abortSignal Abort signal
185
209
  */
186
210
  create(
187
211
  signer: string,
188
- address: string,
212
+ recipient: string,
189
213
  amountData: AmountData,
190
214
  lps: Intermediary[],
191
215
  options?: ToBTCOptions,
@@ -202,16 +226,16 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
202
226
  };
203
227
 
204
228
  const nonce: bigint = this.getRandomNonce();
205
- const outputScript: Buffer = this.btcAddressToOutputScript(address);
229
+ const outputScript: Buffer = this.btcAddressToOutputScript(recipient);
206
230
  const _hash: string | undefined = !amountData.exactIn ?
207
- this.contract.getHashForOnchain(outputScript, amountData.amount, _options.confirmations, nonce).toString("hex") :
231
+ this._contract.getHashForOnchain(outputScript, amountData.amount, _options.confirmations, nonce).toString("hex") :
208
232
  undefined;
209
233
 
210
234
  const _abortController = extendAbortController(abortSignal);
211
235
  const pricePreFetchPromise: Promise<bigint | undefined> = this.preFetchPrice(amountData, _abortController.signal);
212
236
  const usdPricePrefetchPromise: Promise<number | undefined> = this.preFetchUsdPrice(_abortController.signal);
213
237
  const feeRatePromise: Promise<string | undefined> = this.preFetchFeeRate(signer, amountData, _hash, _abortController);
214
- const _signDataPromise: Promise<T["PreFetchVerification"] | undefined> | undefined = this.contract.preFetchBlockDataForSignatures==null ?
238
+ const _signDataPromise: Promise<T["PreFetchVerification"] | undefined> | undefined = this._contract.preFetchBlockDataForSignatures==null ?
215
239
  this.preFetchSignData(Promise.resolve(true)) :
216
240
  undefined;
217
241
 
@@ -227,7 +251,7 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
227
251
  try {
228
252
  const {signDataPromise, resp} = await tryWithRetries(async(retryCount) => {
229
253
  const {signDataPrefetch, response} = IntermediaryAPI.initToBTC(this.chainIdentifier, lp.url, {
230
- btcAddress: address,
254
+ btcAddress: recipient,
231
255
  amount: amountData.amount,
232
256
  confirmationTarget: _options.confirmationTarget,
233
257
  confirmations: _options.confirmations,
@@ -237,7 +261,7 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
237
261
  exactIn: amountData.exactIn,
238
262
  feeRate: throwIfUndefined(feeRatePromise),
239
263
  additionalParams
240
- }, this.options.postRequestTimeout, abortController.signal, retryCount>0 ? false : undefined);
264
+ }, this._options.postRequestTimeout, abortController.signal, retryCount>0 ? false : undefined);
241
265
 
242
266
  return {
243
267
  signDataPromise: _signDataPromise ?? this.preFetchSignData(signDataPrefetch),
@@ -245,9 +269,9 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
245
269
  };
246
270
  }, undefined, RequestError, abortController.signal);
247
271
 
248
- let hash: string = _hash ?? this.contract.getHashForOnchain(outputScript, resp.amount, _options.confirmations, nonce).toString("hex");
272
+ let hash: string = _hash ?? this._contract.getHashForOnchain(outputScript, resp.amount, _options.confirmations, nonce).toString("hex");
249
273
 
250
- const data: T["Data"] = new this.swapDataDeserializer(resp.data);
274
+ const data: T["Data"] = new this._swapDataDeserializer(resp.data);
251
275
  data.setOfferer(signer);
252
276
 
253
277
  this.verifyReturnedData(signer, resp, amountData, lp, _options, data, hash);
@@ -278,7 +302,7 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
278
302
  data,
279
303
  networkFee: resp.networkFee,
280
304
  networkFeeBtc,
281
- address,
305
+ address: recipient,
282
306
  amount: resp.amount,
283
307
  confirmationTarget: _options.confirmationTarget,
284
308
  satsPerVByte: Number(resp.satsPervByte),
@@ -296,4 +320,50 @@ export class ToBTCWrapper<T extends ChainType> extends IToBTCWrapper<T, ToBTCDef
296
320
  }
297
321
  });
298
322
  }
323
+
324
+ /**
325
+ * @inheritDoc
326
+ */
327
+ async recoverFromSwapDataAndState(
328
+ init: {data: T["Data"], getInitTxId: () => Promise<string>, getTxBlock: () => Promise<{blockTime: number, blockHeight: number}>},
329
+ state: SwapCommitState,
330
+ lp?: Intermediary
331
+ ): Promise<ToBTCSwap<T> | null> {
332
+ const data = init.data;
333
+
334
+ const swapInit: ToBTCSwapInit<T["Data"]> = {
335
+ pricingInfo: {
336
+ isValid: true,
337
+ satsBaseFee: 0n,
338
+ swapPriceUSatPerToken: 100_000_000_000_000n,
339
+ realPriceUSatPerToken: 100_000_000_000_000n,
340
+ differencePPM: 0n,
341
+ feePPM: 0n,
342
+ },
343
+ url: lp?.url,
344
+ expiry: 0,
345
+ swapFee: 0n,
346
+ swapFeeBtc: 0n,
347
+ confirmationTarget: 1,
348
+ satsPerVByte: 0,
349
+ feeRate: "",
350
+ signatureData: undefined,
351
+ nonce: data.getNonceHint() ?? undefined,
352
+ requiredConfirmations: data.getConfirmationsHint() ?? undefined,
353
+ data,
354
+ networkFee: 0n,
355
+ networkFeeBtc: 0n,
356
+ exactIn: true
357
+ };
358
+ const swap = new ToBTCSwap(this, swapInit);
359
+ swap._commitTxId = await init.getInitTxId();
360
+ const blockData = await init.getTxBlock();
361
+ swap.createdAt = blockData.blockTime * 1000;
362
+ swap._setInitiated();
363
+ swap._state = ToBTCSwapState.COMMITED;
364
+ await swap._sync(false, false, state);
365
+ await swap._save();
366
+ return swap;
367
+ }
368
+
299
369
  }