@atomiqlabs/sdk 8.7.7 → 8.8.4

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 (339) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +1760 -1760
  3. package/dist/SmartChainAssets.d.ts +181 -181
  4. package/dist/SmartChainAssets.js +181 -181
  5. package/dist/bitcoin/coinselect2/accumulative.d.ts +7 -6
  6. package/dist/bitcoin/coinselect2/accumulative.js +52 -52
  7. package/dist/bitcoin/coinselect2/blackjack.d.ts +7 -6
  8. package/dist/bitcoin/coinselect2/blackjack.js +38 -38
  9. package/dist/bitcoin/coinselect2/index.d.ts +20 -19
  10. package/dist/bitcoin/coinselect2/index.js +69 -69
  11. package/dist/bitcoin/coinselect2/utils.d.ts +82 -77
  12. package/dist/bitcoin/coinselect2/utils.js +158 -123
  13. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +113 -130
  14. package/dist/bitcoin/wallet/BitcoinWallet.js +335 -322
  15. package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +116 -78
  16. package/dist/bitcoin/wallet/IBitcoinWallet.js +21 -21
  17. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +106 -101
  18. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +196 -190
  19. package/dist/enums/FeeType.d.ts +15 -15
  20. package/dist/enums/FeeType.js +19 -19
  21. package/dist/enums/SwapAmountType.d.ts +15 -15
  22. package/dist/enums/SwapAmountType.js +19 -19
  23. package/dist/enums/SwapDirection.d.ts +15 -15
  24. package/dist/enums/SwapDirection.js +19 -19
  25. package/dist/enums/SwapSide.d.ts +15 -15
  26. package/dist/enums/SwapSide.js +19 -19
  27. package/dist/enums/SwapType.d.ts +75 -75
  28. package/dist/enums/SwapType.js +79 -79
  29. package/dist/errors/IntermediaryError.d.ts +13 -13
  30. package/dist/errors/IntermediaryError.js +27 -27
  31. package/dist/errors/RequestError.d.ts +32 -32
  32. package/dist/errors/RequestError.js +54 -54
  33. package/dist/errors/UserError.d.ts +8 -8
  34. package/dist/errors/UserError.js +16 -16
  35. package/dist/events/UnifiedSwapEventListener.d.ts +23 -23
  36. package/dist/events/UnifiedSwapEventListener.js +132 -132
  37. package/dist/http/HttpUtils.d.ts +27 -27
  38. package/dist/http/HttpUtils.js +91 -91
  39. package/dist/http/paramcoders/IParamReader.d.ts +8 -8
  40. package/dist/http/paramcoders/IParamReader.js +2 -2
  41. package/dist/http/paramcoders/ParamDecoder.d.ts +44 -44
  42. package/dist/http/paramcoders/ParamDecoder.js +137 -137
  43. package/dist/http/paramcoders/ParamEncoder.d.ts +20 -20
  44. package/dist/http/paramcoders/ParamEncoder.js +36 -36
  45. package/dist/http/paramcoders/SchemaVerifier.d.ts +26 -26
  46. package/dist/http/paramcoders/SchemaVerifier.js +145 -145
  47. package/dist/http/paramcoders/client/ResponseParamDecoder.d.ts +11 -11
  48. package/dist/http/paramcoders/client/ResponseParamDecoder.js +57 -57
  49. package/dist/http/paramcoders/client/StreamParamEncoder.d.ts +13 -13
  50. package/dist/http/paramcoders/client/StreamParamEncoder.js +26 -26
  51. package/dist/http/paramcoders/client/StreamingFetchPromise.d.ts +16 -16
  52. package/dist/http/paramcoders/client/StreamingFetchPromise.js +174 -174
  53. package/dist/index.d.ts +85 -85
  54. package/dist/index.js +158 -158
  55. package/dist/intermediaries/Intermediary.d.ts +178 -178
  56. package/dist/intermediaries/Intermediary.js +166 -166
  57. package/dist/intermediaries/IntermediaryDiscovery.d.ts +211 -211
  58. package/dist/intermediaries/IntermediaryDiscovery.js +424 -424
  59. package/dist/intermediaries/apis/IntermediaryAPI.d.ts +450 -440
  60. package/dist/intermediaries/apis/IntermediaryAPI.js +618 -603
  61. package/dist/intermediaries/apis/TrustedIntermediaryAPI.d.ts +155 -155
  62. package/dist/intermediaries/apis/TrustedIntermediaryAPI.js +137 -137
  63. package/dist/lnurl/LNURL.d.ts +102 -102
  64. package/dist/lnurl/LNURL.js +321 -321
  65. package/dist/prices/RedundantSwapPrice.d.ts +110 -110
  66. package/dist/prices/RedundantSwapPrice.js +222 -222
  67. package/dist/prices/SingleSwapPrice.d.ts +34 -34
  68. package/dist/prices/SingleSwapPrice.js +44 -44
  69. package/dist/prices/SwapPriceWithChain.d.ts +107 -107
  70. package/dist/prices/SwapPriceWithChain.js +128 -128
  71. package/dist/prices/abstract/ICachedSwapPrice.d.ts +28 -28
  72. package/dist/prices/abstract/ICachedSwapPrice.js +62 -62
  73. package/dist/prices/abstract/IPriceProvider.d.ts +81 -81
  74. package/dist/prices/abstract/IPriceProvider.js +74 -74
  75. package/dist/prices/abstract/ISwapPrice.d.ts +168 -168
  76. package/dist/prices/abstract/ISwapPrice.js +279 -279
  77. package/dist/prices/providers/BinancePriceProvider.d.ts +23 -23
  78. package/dist/prices/providers/BinancePriceProvider.js +30 -30
  79. package/dist/prices/providers/CoinGeckoPriceProvider.d.ts +23 -23
  80. package/dist/prices/providers/CoinGeckoPriceProvider.js +29 -29
  81. package/dist/prices/providers/CoinPaprikaPriceProvider.d.ts +25 -25
  82. package/dist/prices/providers/CoinPaprikaPriceProvider.js +29 -29
  83. package/dist/prices/providers/CustomPriceProvider.d.ts +24 -24
  84. package/dist/prices/providers/CustomPriceProvider.js +35 -35
  85. package/dist/prices/providers/KrakenPriceProvider.d.ts +38 -38
  86. package/dist/prices/providers/KrakenPriceProvider.js +45 -45
  87. package/dist/prices/providers/OKXPriceProvider.d.ts +34 -34
  88. package/dist/prices/providers/OKXPriceProvider.js +29 -29
  89. package/dist/prices/providers/abstract/ExchangePriceProvider.d.ts +17 -17
  90. package/dist/prices/providers/abstract/ExchangePriceProvider.js +21 -21
  91. package/dist/prices/providers/abstract/HttpPriceProvider.d.ts +7 -7
  92. package/dist/prices/providers/abstract/HttpPriceProvider.js +12 -12
  93. package/dist/storage/IUnifiedStorage.d.ts +85 -85
  94. package/dist/storage/IUnifiedStorage.js +2 -2
  95. package/dist/storage/UnifiedSwapStorage.d.ts +114 -114
  96. package/dist/storage/UnifiedSwapStorage.js +116 -116
  97. package/dist/storage-browser/IndexedDBUnifiedStorage.d.ts +63 -63
  98. package/dist/storage-browser/IndexedDBUnifiedStorage.js +298 -298
  99. package/dist/storage-browser/LocalStorageManager.d.ts +49 -49
  100. package/dist/storage-browser/LocalStorageManager.js +93 -93
  101. package/dist/swapper/Swapper.d.ts +732 -692
  102. package/dist/swapper/Swapper.js +1713 -1657
  103. package/dist/swapper/SwapperFactory.d.ts +135 -135
  104. package/dist/swapper/SwapperFactory.js +162 -162
  105. package/dist/swapper/SwapperUtils.d.ts +206 -206
  106. package/dist/swapper/SwapperUtils.js +481 -481
  107. package/dist/swapper/SwapperWithChain.d.ts +404 -404
  108. package/dist/swapper/SwapperWithChain.js +469 -469
  109. package/dist/swapper/SwapperWithSigner.d.ts +322 -322
  110. package/dist/swapper/SwapperWithSigner.js +318 -318
  111. package/dist/swaps/IAddressSwap.d.ts +22 -22
  112. package/dist/swaps/IAddressSwap.js +14 -14
  113. package/dist/swaps/IBTCWalletSwap.d.ts +73 -73
  114. package/dist/swaps/IBTCWalletSwap.js +18 -18
  115. package/dist/swaps/IClaimableSwap.d.ts +49 -49
  116. package/dist/swaps/IClaimableSwap.js +15 -15
  117. package/dist/swaps/IClaimableSwapWrapper.d.ts +15 -15
  118. package/dist/swaps/IClaimableSwapWrapper.js +2 -2
  119. package/dist/swaps/IRefundableSwap.d.ts +43 -43
  120. package/dist/swaps/IRefundableSwap.js +14 -14
  121. package/dist/swaps/ISwap.d.ts +392 -392
  122. package/dist/swaps/ISwap.js +349 -349
  123. package/dist/swaps/ISwapWithGasDrop.d.ts +21 -21
  124. package/dist/swaps/ISwapWithGasDrop.js +12 -12
  125. package/dist/swaps/ISwapWrapper.d.ts +285 -285
  126. package/dist/swaps/ISwapWrapper.js +353 -353
  127. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.d.ts +98 -98
  128. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.js +126 -126
  129. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +139 -139
  130. package/dist/swaps/escrow_swaps/IEscrowSwap.js +170 -170
  131. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +128 -128
  132. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +167 -167
  133. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +105 -105
  134. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +129 -129
  135. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +162 -162
  136. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +190 -190
  137. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.d.ts +64 -64
  138. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.js +82 -82
  139. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +531 -531
  140. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +1285 -1285
  141. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +190 -190
  142. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +432 -432
  143. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +583 -583
  144. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +1371 -1371
  145. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +235 -235
  146. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +525 -525
  147. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +458 -458
  148. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +1126 -1126
  149. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +202 -202
  150. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +406 -406
  151. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +403 -403
  152. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +924 -924
  153. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.d.ts +68 -68
  154. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +117 -117
  155. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.d.ts +127 -127
  156. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +256 -256
  157. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +251 -251
  158. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +536 -536
  159. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.d.ts +73 -73
  160. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.js +155 -155
  161. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +132 -132
  162. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +286 -286
  163. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +637 -631
  164. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +1448 -1444
  165. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +257 -225
  166. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +947 -822
  167. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +261 -261
  168. package/dist/swaps/trusted/ln/LnForGasSwap.js +511 -511
  169. package/dist/swaps/trusted/ln/LnForGasWrapper.d.ts +40 -40
  170. package/dist/swaps/trusted/ln/LnForGasWrapper.js +83 -83
  171. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +342 -342
  172. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +715 -715
  173. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +69 -69
  174. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +93 -93
  175. package/dist/types/AmountData.d.ts +10 -10
  176. package/dist/types/AmountData.js +2 -2
  177. package/dist/types/CustomPriceFunction.d.ts +11 -11
  178. package/dist/types/CustomPriceFunction.js +2 -2
  179. package/dist/types/PriceInfoType.d.ts +28 -28
  180. package/dist/types/PriceInfoType.js +57 -57
  181. package/dist/types/SwapExecutionAction.d.ts +88 -88
  182. package/dist/types/SwapExecutionAction.js +2 -2
  183. package/dist/types/SwapStateInfo.d.ts +5 -5
  184. package/dist/types/SwapStateInfo.js +2 -2
  185. package/dist/types/SwapWithSigner.d.ts +17 -17
  186. package/dist/types/SwapWithSigner.js +43 -43
  187. package/dist/types/Token.d.ts +99 -99
  188. package/dist/types/Token.js +76 -76
  189. package/dist/types/TokenAmount.d.ts +69 -69
  190. package/dist/types/TokenAmount.js +60 -60
  191. package/dist/types/fees/Fee.d.ts +50 -50
  192. package/dist/types/fees/Fee.js +2 -2
  193. package/dist/types/fees/FeeBreakdown.d.ts +11 -11
  194. package/dist/types/fees/FeeBreakdown.js +2 -2
  195. package/dist/types/fees/PercentagePPM.d.ts +17 -17
  196. package/dist/types/fees/PercentagePPM.js +18 -18
  197. package/dist/types/lnurl/LNURLPay.d.ts +61 -61
  198. package/dist/types/lnurl/LNURLPay.js +31 -31
  199. package/dist/types/lnurl/LNURLWithdraw.d.ts +48 -48
  200. package/dist/types/lnurl/LNURLWithdraw.js +27 -27
  201. package/dist/types/wallets/LightningInvoiceCreateService.d.ts +24 -24
  202. package/dist/types/wallets/LightningInvoiceCreateService.js +15 -15
  203. package/dist/types/wallets/MinimalBitcoinWalletInterface.d.ts +23 -23
  204. package/dist/types/wallets/MinimalBitcoinWalletInterface.js +2 -2
  205. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.d.ts +9 -9
  206. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.js +2 -2
  207. package/dist/utils/AutomaticClockDriftCorrection.d.ts +1 -1
  208. package/dist/utils/AutomaticClockDriftCorrection.js +70 -70
  209. package/dist/utils/BitcoinUtils.d.ts +16 -14
  210. package/dist/utils/BitcoinUtils.js +141 -102
  211. package/dist/utils/BitcoinWalletUtils.d.ts +7 -7
  212. package/dist/utils/BitcoinWalletUtils.js +14 -14
  213. package/dist/utils/Logger.d.ts +7 -7
  214. package/dist/utils/Logger.js +12 -12
  215. package/dist/utils/RetryUtils.d.ts +22 -22
  216. package/dist/utils/RetryUtils.js +67 -67
  217. package/dist/utils/SwapUtils.d.ts +88 -88
  218. package/dist/utils/SwapUtils.js +72 -72
  219. package/dist/utils/TimeoutUtils.d.ts +17 -17
  220. package/dist/utils/TimeoutUtils.js +55 -55
  221. package/dist/utils/TokenUtils.d.ts +19 -19
  222. package/dist/utils/TokenUtils.js +37 -37
  223. package/dist/utils/TypeUtils.d.ts +7 -7
  224. package/dist/utils/TypeUtils.js +2 -2
  225. package/dist/utils/Utils.d.ts +67 -67
  226. package/dist/utils/Utils.js +208 -208
  227. package/package.json +43 -43
  228. package/src/SmartChainAssets.ts +186 -186
  229. package/src/bitcoin/coinselect2/accumulative.ts +69 -68
  230. package/src/bitcoin/coinselect2/blackjack.ts +50 -49
  231. package/src/bitcoin/coinselect2/index.ts +93 -92
  232. package/src/bitcoin/coinselect2/utils.ts +236 -195
  233. package/src/bitcoin/wallet/BitcoinWallet.ts +439 -427
  234. package/src/bitcoin/wallet/IBitcoinWallet.ts +140 -99
  235. package/src/bitcoin/wallet/SingleAddressBitcoinWallet.ts +225 -217
  236. package/src/enums/FeeType.ts +15 -15
  237. package/src/enums/SwapAmountType.ts +16 -16
  238. package/src/enums/SwapDirection.ts +15 -15
  239. package/src/enums/SwapSide.ts +16 -16
  240. package/src/enums/SwapType.ts +75 -75
  241. package/src/errors/IntermediaryError.ts +28 -28
  242. package/src/errors/RequestError.ts +64 -64
  243. package/src/errors/UserError.ts +15 -15
  244. package/src/events/UnifiedSwapEventListener.ts +173 -173
  245. package/src/http/HttpUtils.ts +91 -91
  246. package/src/http/paramcoders/IParamReader.ts +9 -9
  247. package/src/http/paramcoders/ParamDecoder.ts +145 -145
  248. package/src/http/paramcoders/ParamEncoder.ts +40 -40
  249. package/src/http/paramcoders/SchemaVerifier.ts +153 -153
  250. package/src/http/paramcoders/client/ResponseParamDecoder.ts +57 -57
  251. package/src/http/paramcoders/client/StreamParamEncoder.ts +28 -28
  252. package/src/http/paramcoders/client/StreamingFetchPromise.ts +192 -192
  253. package/src/index.ts +140 -140
  254. package/src/intermediaries/Intermediary.ts +280 -280
  255. package/src/intermediaries/IntermediaryDiscovery.ts +541 -541
  256. package/src/intermediaries/apis/IntermediaryAPI.ts +963 -947
  257. package/src/intermediaries/apis/TrustedIntermediaryAPI.ts +257 -257
  258. package/src/lnurl/LNURL.ts +402 -402
  259. package/src/prices/RedundantSwapPrice.ts +264 -264
  260. package/src/prices/SingleSwapPrice.ts +50 -50
  261. package/src/prices/SwapPriceWithChain.ts +194 -194
  262. package/src/prices/abstract/ICachedSwapPrice.ts +85 -85
  263. package/src/prices/abstract/IPriceProvider.ts +127 -127
  264. package/src/prices/abstract/ISwapPrice.ts +390 -390
  265. package/src/prices/providers/BinancePriceProvider.ts +48 -48
  266. package/src/prices/providers/CoinGeckoPriceProvider.ts +46 -46
  267. package/src/prices/providers/CoinPaprikaPriceProvider.ts +49 -49
  268. package/src/prices/providers/CustomPriceProvider.ts +40 -40
  269. package/src/prices/providers/KrakenPriceProvider.ts +83 -83
  270. package/src/prices/providers/OKXPriceProvider.ts +59 -59
  271. package/src/prices/providers/abstract/ExchangePriceProvider.ts +31 -31
  272. package/src/prices/providers/abstract/HttpPriceProvider.ts +14 -14
  273. package/src/storage/IUnifiedStorage.ts +95 -95
  274. package/src/storage/UnifiedSwapStorage.ts +141 -141
  275. package/src/storage-browser/IndexedDBUnifiedStorage.ts +350 -350
  276. package/src/storage-browser/LocalStorageManager.ts +106 -106
  277. package/src/swapper/Swapper.ts +2488 -2416
  278. package/src/swapper/SwapperFactory.ts +307 -307
  279. package/src/swapper/SwapperUtils.ts +570 -570
  280. package/src/swapper/SwapperWithChain.ts +707 -707
  281. package/src/swapper/SwapperWithSigner.ts +511 -511
  282. package/src/swaps/IAddressSwap.ts +30 -30
  283. package/src/swaps/IBTCWalletSwap.ts +92 -92
  284. package/src/swaps/IClaimableSwap.ts +65 -65
  285. package/src/swaps/IClaimableSwapWrapper.ts +17 -17
  286. package/src/swaps/IRefundableSwap.ts +58 -58
  287. package/src/swaps/ISwap.ts +703 -703
  288. package/src/swaps/ISwapWithGasDrop.ts +25 -25
  289. package/src/swaps/ISwapWrapper.ts +539 -539
  290. package/src/swaps/escrow_swaps/IEscrowSelfInitSwap.ts +217 -217
  291. package/src/swaps/escrow_swaps/IEscrowSwap.ts +269 -269
  292. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +282 -282
  293. package/src/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.ts +169 -169
  294. package/src/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.ts +300 -300
  295. package/src/swaps/escrow_swaps/frombtc/IFromBTCWrapper.ts +107 -107
  296. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +1473 -1474
  297. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +601 -601
  298. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +1582 -1582
  299. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +750 -750
  300. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +1299 -1299
  301. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +610 -610
  302. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +1096 -1096
  303. package/src/swaps/escrow_swaps/tobtc/IToBTCWrapper.ts +138 -138
  304. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.ts +304 -304
  305. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +786 -786
  306. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.ts +206 -206
  307. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +401 -401
  308. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +1812 -1799
  309. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +1236 -1060
  310. package/src/swaps/trusted/ln/LnForGasSwap.ts +589 -589
  311. package/src/swaps/trusted/ln/LnForGasWrapper.ts +91 -91
  312. package/src/swaps/trusted/onchain/OnchainForGasSwap.ts +862 -862
  313. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +131 -131
  314. package/src/types/AmountData.ts +9 -9
  315. package/src/types/CustomPriceFunction.ts +11 -11
  316. package/src/types/PriceInfoType.ts +66 -66
  317. package/src/types/SwapExecutionAction.ts +99 -99
  318. package/src/types/SwapStateInfo.ts +6 -6
  319. package/src/types/SwapWithSigner.ts +61 -61
  320. package/src/types/Token.ts +163 -163
  321. package/src/types/TokenAmount.ts +132 -132
  322. package/src/types/fees/Fee.ts +56 -56
  323. package/src/types/fees/FeeBreakdown.ts +11 -11
  324. package/src/types/fees/PercentagePPM.ts +26 -26
  325. package/src/types/lnurl/LNURLPay.ts +79 -79
  326. package/src/types/lnurl/LNURLWithdraw.ts +61 -61
  327. package/src/types/wallets/LightningInvoiceCreateService.ts +30 -30
  328. package/src/types/wallets/MinimalBitcoinWalletInterface.ts +21 -21
  329. package/src/types/wallets/MinimalLightningNetworkWalletInterface.ts +9 -9
  330. package/src/utils/AutomaticClockDriftCorrection.ts +71 -71
  331. package/src/utils/BitcoinUtils.ts +132 -91
  332. package/src/utils/BitcoinWalletUtils.ts +15 -15
  333. package/src/utils/Logger.ts +14 -14
  334. package/src/utils/RetryUtils.ts +78 -78
  335. package/src/utils/SwapUtils.ts +99 -99
  336. package/src/utils/TimeoutUtils.ts +49 -49
  337. package/src/utils/TokenUtils.ts +33 -33
  338. package/src/utils/TypeUtils.ts +8 -8
  339. package/src/utils/Utils.ts +212 -212
@@ -1,947 +1,963 @@
1
- import {RequestError} from "../../errors/RequestError";
2
- import {
3
- FieldTypeEnum,
4
- RequestSchemaResult,
5
- verifySchema
6
- } from "../../http/paramcoders/SchemaVerifier";
7
- import {streamingFetchPromise} from "../../http/paramcoders/client/StreamingFetchPromise";
8
- import {extendAbortController, randomBytes} from "../../utils/Utils";
9
- import {httpGet, httpPost} from "../../http/HttpUtils";
10
- import {tryWithRetries} from "../../utils/RetryUtils";
11
-
12
- export type InfoHandlerResponse = {
13
- envelope: string,
14
- chains: {
15
- [chainIdentifier: string]: {
16
- address: string,
17
- signature: string,
18
- contractVersion?: string,
19
- }
20
- }
21
- };
22
-
23
- export enum RefundAuthorizationResponseCodes {
24
- EXPIRED=20010,
25
- REFUND_DATA=20000,
26
- NOT_FOUND=20007,
27
- PENDING=20008,
28
- PAID=20006
29
- }
30
-
31
- export enum PaymentAuthorizationResponseCodes {
32
- AUTH_DATA=10000,
33
- EXPIRED=10001,
34
- PAID=10002,
35
- PENDING=10003,
36
- ALREADY_COMMITTED=10004
37
- }
38
-
39
- export enum InvoiceStatusResponseCodes {
40
- PAID=10000,
41
- EXPIRED=10001,
42
- SETTLED=10002,
43
- PENDING=10003
44
- }
45
-
46
- export type RefundAuthorizationResponse = {
47
- code: RefundAuthorizationResponseCodes.PAID,
48
- msg: string,
49
- data: {
50
- secret?: string,
51
- txId?: string
52
- }
53
- } | {
54
- code: RefundAuthorizationResponseCodes.REFUND_DATA,
55
- msg: string,
56
- data: {
57
- address: string,
58
- prefix: string,
59
- timeout: string,
60
- signature: string
61
- }
62
- } | {
63
- code: Exclude<RefundAuthorizationResponseCodes, RefundAuthorizationResponseCodes.PAID | RefundAuthorizationResponseCodes.REFUND_DATA>,
64
- msg: string
65
- };
66
-
67
- export type PaymentAuthorizationResponse = {
68
- code: PaymentAuthorizationResponseCodes.AUTH_DATA,
69
- msg: string,
70
- data: {
71
- address: string,
72
- data: any,
73
- nonce: number,
74
- prefix: string,
75
- timeout: string,
76
- signature: string
77
- }
78
- } | {
79
- code: Exclude<PaymentAuthorizationResponseCodes, PaymentAuthorizationResponseCodes.AUTH_DATA>,
80
- msg: string
81
- };
82
-
83
- export type InvoiceStatusResponse = {
84
- code: Exclude<InvoiceStatusResponseCodes, InvoiceStatusResponseCodes.PAID>,
85
- msg: string
86
- } | {
87
- code: InvoiceStatusResponseCodes.PAID,
88
- msg: string,
89
- data: {
90
- data: any
91
- }
92
- }
93
-
94
- const SwapResponseSchema = {
95
- data: FieldTypeEnum.Any,
96
-
97
- prefix: FieldTypeEnum.String,
98
- timeout: FieldTypeEnum.String,
99
- signature: FieldTypeEnum.String
100
- } as const;
101
-
102
- export type SwapInit = {
103
- token: string,
104
- additionalParams?: { [name: string]: any }
105
- }
106
-
107
- export type BaseFromBTCSwapInit = SwapInit & {
108
- claimer: string,
109
- amount: bigint,
110
- exactOut: boolean,
111
- feeRate: Promise<string>
112
- };
113
-
114
- export type BaseToBTCSwapInit = SwapInit & {
115
- offerer: string
116
- };
117
-
118
- /////////////////////////
119
- ///// To BTC
120
-
121
- const ToBTCResponseSchema = {
122
- amount: FieldTypeEnum.BigInt,
123
- address: FieldTypeEnum.String,
124
- satsPervByte: FieldTypeEnum.BigInt,
125
- networkFee: FieldTypeEnum.BigInt,
126
- swapFee: FieldTypeEnum.BigInt,
127
- totalFee: FieldTypeEnum.BigInt,
128
- total: FieldTypeEnum.BigInt,
129
- minRequiredExpiry: FieldTypeEnum.BigInt,
130
- ...SwapResponseSchema
131
- } as const;
132
-
133
- export type ToBTCResponseType = RequestSchemaResult<typeof ToBTCResponseSchema>;
134
-
135
- export type ToBTCInit = BaseToBTCSwapInit & {
136
- btcAddress: string,
137
- exactIn: boolean,
138
- amount: bigint,
139
- confirmationTarget: number,
140
- confirmations: number,
141
- nonce: bigint,
142
- feeRate: Promise<string>
143
- }
144
-
145
- /////////////////////////
146
- ///// To BTCLN
147
-
148
- const ToBTCLNResponseSchema = {
149
- maxFee: FieldTypeEnum.BigInt,
150
- swapFee: FieldTypeEnum.BigInt,
151
- total: FieldTypeEnum.BigInt,
152
- confidence: FieldTypeEnum.Number,
153
- address: FieldTypeEnum.String,
154
-
155
- routingFeeSats: FieldTypeEnum.BigInt,
156
- ...SwapResponseSchema
157
- } as const;
158
-
159
- export type ToBTCLNResponseType = RequestSchemaResult<typeof ToBTCLNResponseSchema>;
160
-
161
- export type ToBTCLNInit = BaseToBTCSwapInit & {
162
- pr: string,
163
- maxFee: bigint,
164
- expiryTimestamp: bigint,
165
- feeRate: Promise<string>
166
- };
167
-
168
- const ToBTCLNPrepareExactInSchema = {
169
- amount: FieldTypeEnum.BigInt,
170
- reqId: FieldTypeEnum.String
171
- } as const;
172
-
173
- export type ToBTCLNPrepareExactInResponseType = RequestSchemaResult<typeof ToBTCLNPrepareExactInSchema>;
174
-
175
- export type ToBTCLNPrepareExactIn = BaseToBTCSwapInit & {
176
- pr: string,
177
- amount: bigint,
178
- maxFee: bigint,
179
- expiryTimestamp: bigint
180
- }
181
-
182
- export type ToBTCLNInitExactIn = {
183
- pr: string,
184
- reqId: string,
185
- feeRate: Promise<string>,
186
- additionalParams?: { [name: string]: any }
187
- }
188
-
189
- /////////////////////////
190
- ///// From BTC
191
-
192
- const FromBTCResponseSchema = {
193
- amount: FieldTypeEnum.BigInt,
194
- btcAddress: FieldTypeEnum.String,
195
- address: FieldTypeEnum.String,
196
- swapFee: FieldTypeEnum.BigInt,
197
- total: FieldTypeEnum.BigInt,
198
- confirmations: FieldTypeEnum.Number,
199
- ...SwapResponseSchema
200
- } as const;
201
-
202
- export type FromBTCResponseType = RequestSchemaResult<typeof FromBTCResponseSchema>;
203
-
204
- export type FromBTCInit = BaseFromBTCSwapInit & {
205
- sequence: bigint,
206
- claimerBounty: Promise<{
207
- feePerBlock: bigint,
208
- safetyFactor: bigint,
209
- startTimestamp: bigint,
210
- addBlock: bigint,
211
- addFee: bigint
212
- }>
213
- }
214
-
215
- /////////////////////////
216
- ///// From BTCLN
217
-
218
- const FromBTCLNResponseSchema = {
219
- pr: FieldTypeEnum.String,
220
- swapFee: FieldTypeEnum.BigInt,
221
- total: FieldTypeEnum.BigInt,
222
- intermediaryKey: FieldTypeEnum.String,
223
- securityDeposit: FieldTypeEnum.BigInt
224
- } as const;
225
-
226
- export type FromBTCLNResponseType = RequestSchemaResult<typeof FromBTCLNResponseSchema>;
227
-
228
- export type FromBTCLNInit = BaseFromBTCSwapInit & {
229
- paymentHash: Buffer,
230
- description?: string,
231
- descriptionHash?: Buffer
232
- }
233
-
234
- /////////////////////////
235
- ///// From BTCLN Auto
236
-
237
- const FromBTCLNAutoResponseSchema = {
238
- intermediaryKey: FieldTypeEnum.String,
239
- pr: FieldTypeEnum.String,
240
-
241
- btcAmountSwap: FieldTypeEnum.BigInt,
242
- btcAmountGas: FieldTypeEnum.BigInt,
243
-
244
- total: FieldTypeEnum.BigInt,
245
- totalGas: FieldTypeEnum.BigInt,
246
-
247
- totalFeeBtc: FieldTypeEnum.BigInt,
248
-
249
- swapFeeBtc: FieldTypeEnum.BigInt,
250
- swapFee: FieldTypeEnum.BigInt,
251
-
252
- gasSwapFeeBtc: FieldTypeEnum.BigInt,
253
- gasSwapFee: FieldTypeEnum.BigInt,
254
-
255
- claimerBounty: FieldTypeEnum.BigInt
256
- } as const;
257
-
258
- export type FromBTCLNAutoResponseType = RequestSchemaResult<typeof FromBTCLNAutoResponseSchema>;
259
-
260
- export type FromBTCLNAutoInit = Omit<BaseFromBTCSwapInit, "feeRate"> & {
261
- paymentHash: Buffer,
262
- gasToken: string,
263
- description?: string,
264
- descriptionHash?: Buffer,
265
- gasAmount?: bigint,
266
- claimerBounty?: Promise<bigint>
267
- }
268
-
269
- /////////////////////////
270
- ///// Spv vault from BTC
271
-
272
- const SpvFromBTCPrepareResponseSchema = {
273
- quoteId: FieldTypeEnum.String,
274
- expiry: FieldTypeEnum.Number,
275
-
276
- address: FieldTypeEnum.String,
277
- vaultId: FieldTypeEnum.BigInt,
278
-
279
- vaultBtcAddress: FieldTypeEnum.String,
280
- btcAddress: FieldTypeEnum.String,
281
- btcUtxo: FieldTypeEnum.String,
282
- btcFeeRate: FieldTypeEnum.Number,
283
-
284
- btcAmount: FieldTypeEnum.BigInt,
285
- btcAmountSwap: FieldTypeEnum.BigInt,
286
- btcAmountGas: FieldTypeEnum.BigInt,
287
-
288
- total: FieldTypeEnum.BigInt,
289
- totalGas: FieldTypeEnum.BigInt,
290
-
291
- totalFeeBtc: FieldTypeEnum.BigInt,
292
-
293
- swapFeeBtc: FieldTypeEnum.BigInt,
294
- swapFee: FieldTypeEnum.BigInt,
295
-
296
- gasSwapFeeBtc: FieldTypeEnum.BigInt,
297
- gasSwapFee: FieldTypeEnum.BigInt,
298
-
299
- callerFeeShare: FieldTypeEnum.BigInt,
300
- frontingFeeShare: FieldTypeEnum.BigInt,
301
- executionFeeShare: FieldTypeEnum.BigInt
302
- } as const;
303
-
304
- export type SpvFromBTCPrepareResponseType = RequestSchemaResult<typeof SpvFromBTCPrepareResponseSchema>;
305
-
306
- export type SpvFromBTCPrepare = SwapInit & {
307
- address: string,
308
- amount: bigint,
309
- gasAmount: bigint,
310
- gasToken: string,
311
- exactOut: boolean,
312
- callerFeeRate: Promise<bigint>,
313
- frontingFeeRate: bigint,
314
- stickyAddress?: boolean
315
- }
316
-
317
- const SpvFromBTCInitResponseSchema = {
318
- txId: FieldTypeEnum.String
319
- } as const;
320
-
321
- export type SpvFromBTCInitResponseType = RequestSchemaResult<typeof SpvFromBTCInitResponseSchema>;
322
-
323
- export type SpvFromBTCInit = {
324
- quoteId: string,
325
- psbtHex: string
326
- }
327
-
328
- export class IntermediaryAPI {
329
-
330
- /**
331
- * Returns the information about a specific intermediary
332
- *
333
- * @param baseUrl Base URL of the intermediary
334
- * @param timeout Timeout in milliseconds for the HTTP request
335
- * @param abortSignal
336
- *
337
- * @throws {RequestError} If non-200 http response code is returned
338
- * @throws {Error} If the supplied nonce doesn't match the response
339
- */
340
- static async getIntermediaryInfo(
341
- baseUrl: string,
342
- timeout?: number,
343
- abortSignal?: AbortSignal
344
- ): Promise<InfoHandlerResponse> {
345
- const nonce = randomBytes(32).toString("hex");
346
-
347
- const abortController = extendAbortController(abortSignal);
348
-
349
- //We don't know whether the node supports only POST or also has GET info support enabled
350
- // here we try both, and abort when the first one returns (which should be GET)
351
- const response = await Promise.any([
352
- httpGet<InfoHandlerResponse>(baseUrl+"/info?nonce="+nonce, timeout, abortController.signal),
353
- httpPost<InfoHandlerResponse>(baseUrl+"/info", {
354
- nonce,
355
- }, timeout, abortController.signal)
356
- ]);
357
- abortController.abort();
358
-
359
- const info = JSON.parse(response.envelope);
360
- if(nonce!==info.nonce) throw new Error("Invalid response - nonce");
361
-
362
- return response;
363
- }
364
-
365
- /**
366
- * Returns the information about an outcome of the To BTC swap
367
- *
368
- * @param url URL of the intermediary
369
- * @param paymentHash Payment hash of the swap
370
- * @param sequence Swap's sequence number
371
- * @param timeout Timeout in milliseconds for the HTTP request
372
- * @param abortSignal
373
- *
374
- * @throws {RequestError} If non-200 http response code is returned
375
- */
376
- static async getRefundAuthorization(
377
- url: string,
378
- paymentHash: string,
379
- sequence: bigint,
380
- timeout?: number,
381
- abortSignal?: AbortSignal
382
- ): Promise<RefundAuthorizationResponse> {
383
- return tryWithRetries(() => httpGet<RefundAuthorizationResponse>(
384
- url + "/getRefundAuthorization"+
385
- "?paymentHash=" + encodeURIComponent(paymentHash) +
386
- "&sequence=" + encodeURIComponent(sequence.toString(10)),
387
- timeout,
388
- abortSignal
389
- ), undefined, RequestError, abortSignal);
390
- }
391
-
392
- /**
393
- * Returns the information about the payment of the From BTCLN swaps
394
- *
395
- * @param url URL of the intermediary
396
- * @param paymentHash Payment hash of the swap
397
- * @param timeout Timeout in milliseconds for the HTTP request
398
- * @param abortSignal
399
- *
400
- * @throws {RequestError} If non-200 http response code is returned
401
- */
402
- static async getPaymentAuthorization(
403
- url: string,
404
- paymentHash: string,
405
- timeout?: number,
406
- abortSignal?: AbortSignal
407
- ): Promise<PaymentAuthorizationResponse> {
408
- return tryWithRetries(() => httpGet<PaymentAuthorizationResponse>(
409
- url+"/getInvoicePaymentAuth"+
410
- "?paymentHash="+encodeURIComponent(paymentHash),
411
- timeout,
412
- abortSignal
413
- ), undefined, RequestError, abortSignal);
414
- }
415
-
416
- /**
417
- * Returns the status of the payment of the From BTCLN swaps
418
- *
419
- * @param url URL of the intermediary
420
- * @param paymentHash Payment hash of the swap
421
- * @param timeout Timeout in milliseconds for the HTTP request
422
- * @param abortSignal
423
- *
424
- * @throws {RequestError} If non-200 http response code is returned
425
- */
426
- static async getInvoiceStatus(
427
- url: string,
428
- paymentHash: string,
429
- timeout?: number,
430
- abortSignal?: AbortSignal
431
- ): Promise<InvoiceStatusResponse> {
432
- return tryWithRetries(() => httpGet<InvoiceStatusResponse>(
433
- url+"/getInvoiceStatus"+
434
- "?paymentHash="+encodeURIComponent(paymentHash),
435
- timeout,
436
- abortSignal
437
- ), undefined, RequestError, abortSignal);
438
- }
439
-
440
- /**
441
- * Initiate To BTC swap with an intermediary
442
- *
443
- * @param chainIdentifier
444
- * @param baseUrl Base URL of the intermediary
445
- * @param init Swap initialization parameters
446
- * @param timeout Timeout in milliseconds for the HTTP request
447
- * @param abortSignal
448
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
449
- *
450
- * @throws {RequestError} If non-200 http response code is returned
451
- */
452
- static initToBTC(
453
- chainIdentifier: string,
454
- baseUrl: string,
455
- init: ToBTCInit,
456
- timeout?: number,
457
- abortSignal?: AbortSignal,
458
- streamRequest?: boolean
459
- ): {
460
- signDataPrefetch: Promise<any>,
461
- response: Promise<ToBTCResponseType>
462
- } {
463
- const responseBodyPromise = streamingFetchPromise(baseUrl+"/tobtc/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
464
- ...init.additionalParams,
465
- address: init.btcAddress,
466
- amount: init.amount.toString(10),
467
- exactIn: init.exactIn,
468
- confirmationTarget: init.confirmationTarget,
469
- confirmations: init.confirmations,
470
- nonce: init.nonce.toString(10),
471
- token: init.token,
472
- offerer: init.offerer,
473
- feeRate: init.feeRate
474
- }, {
475
- code: FieldTypeEnum.Number,
476
- msg: FieldTypeEnum.String,
477
- data: FieldTypeEnum.AnyOptional,
478
- signDataPrefetch: FieldTypeEnum.AnyOptional
479
- }, timeout, abortSignal, streamRequest);
480
-
481
- return {
482
- signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
483
- response: responseBodyPromise.then((responseBody) => Promise.all([
484
- responseBody.code,
485
- responseBody.msg,
486
- responseBody.data,
487
- ])).then(([code, msg, data]) => {
488
- if(code!==20000) {
489
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
490
- }
491
- const result = verifySchema(data, ToBTCResponseSchema);
492
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
493
- return result;
494
- })
495
- };
496
- }
497
-
498
- /**
499
- * Initiate From BTC swap with an intermediary
500
- *
501
- * @param chainIdentifier
502
- * @param baseUrl Base URL of the intermediary
503
- * @param depositToken
504
- * @param init Swap initialization parameters
505
- * @param timeout Timeout in milliseconds for the HTTP request
506
- * @param abortSignal
507
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
508
- *
509
- * @throws {RequestError} If non-200 http response code is returned
510
- */
511
- static initFromBTC(
512
- chainIdentifier: string,
513
- baseUrl: string,
514
- depositToken: string,
515
- init: FromBTCInit,
516
- timeout?: number,
517
- abortSignal?: AbortSignal,
518
- streamRequest?: boolean
519
- ): {
520
- signDataPrefetch: Promise<any>,
521
- response: Promise<FromBTCResponseType>
522
- } {
523
- const responseBodyPromise = streamingFetchPromise(
524
- baseUrl+"/frombtc/getAddress?chain="+encodeURIComponent(chainIdentifier)+"&depositToken="+encodeURIComponent(depositToken),
525
- {
526
- ...init.additionalParams,
527
- address: init.claimer,
528
- amount: init.amount.toString(10),
529
- token: init.token,
530
-
531
- exactOut: init.exactOut,
532
- sequence: init.sequence.toString(10),
533
-
534
- claimerBounty: init.claimerBounty.then(claimerBounty => {
535
- return {
536
- feePerBlock: claimerBounty.feePerBlock.toString(10),
537
- safetyFactor: claimerBounty.safetyFactor.toString(10),
538
- startTimestamp: claimerBounty.startTimestamp.toString(10),
539
- addBlock: claimerBounty.addBlock.toString(10),
540
- addFee: claimerBounty.addFee.toString(10)
541
- }
542
- }),
543
- feeRate: init.feeRate
544
- },
545
- {
546
- code: FieldTypeEnum.Number,
547
- msg: FieldTypeEnum.String,
548
- data: FieldTypeEnum.AnyOptional,
549
- signDataPrefetch: FieldTypeEnum.AnyOptional
550
- },
551
- timeout, abortSignal, streamRequest
552
- );
553
-
554
- return {
555
- signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
556
- response: responseBodyPromise.then((responseBody) => Promise.all([
557
- responseBody.code,
558
- responseBody.msg,
559
- responseBody.data,
560
- ])).then(([code, msg, data]) => {
561
- if(code!==20000) {
562
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
563
- }
564
- const result = verifySchema(data, FromBTCResponseSchema);
565
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
566
- return result;
567
- })
568
- };
569
- }
570
-
571
- /**
572
- * Initiate From BTCLN swap with an intermediary
573
- *
574
- * @param chainIdentifier
575
- * @param baseUrl Base URL of the intermediary
576
- * @param depositToken
577
- * @param init Swap initialization parameters
578
- * @param timeout Timeout in milliseconds for the HTTP request
579
- * @param abortSignal
580
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
581
- *
582
- * @throws {RequestError} If non-200 http response code is returned
583
- */
584
- static initFromBTCLN(
585
- chainIdentifier: string,
586
- baseUrl: string,
587
- depositToken: string,
588
- init: FromBTCLNInit,
589
- timeout?: number,
590
- abortSignal?: AbortSignal,
591
- streamRequest?: boolean
592
- ): {
593
- lnPublicKey: Promise<string | null>,
594
- response: Promise<FromBTCLNResponseType>
595
- } {
596
- const responseBodyPromise = streamingFetchPromise(
597
- baseUrl+"/frombtcln/createInvoice?chain="+encodeURIComponent(chainIdentifier)+"&depositToken="+encodeURIComponent(depositToken),
598
- {
599
- ...init.additionalParams,
600
- paymentHash: init.paymentHash.toString("hex"),
601
- amount: init.amount.toString(),
602
- address: init.claimer,
603
- token: init.token,
604
- description: init.description ?? null,
605
- descriptionHash: init.descriptionHash==null ? null : init.descriptionHash.toString("hex"),
606
- exactOut: init.exactOut,
607
- feeRate: init.feeRate
608
- },
609
- {
610
- code: FieldTypeEnum.Number,
611
- msg: FieldTypeEnum.String,
612
- data: FieldTypeEnum.AnyOptional,
613
- lnPublicKey: FieldTypeEnum.StringOptional
614
- },
615
- timeout, abortSignal, streamRequest
616
- );
617
-
618
- return {
619
- lnPublicKey: responseBodyPromise.then(responseBody => responseBody.lnPublicKey),
620
- response: responseBodyPromise.then((responseBody) => Promise.all([
621
- responseBody.code,
622
- responseBody.msg,
623
- responseBody.data,
624
- ])).then(([code, msg, data]) => {
625
- if(code!==20000) {
626
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
627
- }
628
- const result = verifySchema(data, FromBTCLNResponseSchema);
629
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
630
- return result;
631
- })
632
- };
633
- }
634
-
635
- /**
636
- * Initiate From BTCLN swap with auto-initilization by an intermediary
637
- *
638
- * @param chainIdentifier
639
- * @param baseUrl Base URL of the intermediary
640
- * @param init Swap initialization parameters
641
- * @param timeout Timeout in milliseconds for the HTTP request
642
- * @param abortSignal
643
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
644
- *
645
- * @throws {RequestError} If non-200 http response code is returned
646
- */
647
- static initFromBTCLNAuto(
648
- chainIdentifier: string,
649
- baseUrl: string,
650
- init: FromBTCLNAutoInit,
651
- timeout?: number,
652
- abortSignal?: AbortSignal,
653
- streamRequest?: boolean
654
- ): {
655
- lnPublicKey: Promise<string | null>,
656
- response: Promise<FromBTCLNAutoResponseType>
657
- } {
658
- const responseBodyPromise = streamingFetchPromise(
659
- baseUrl+"/frombtcln_auto/createInvoice?chain="+encodeURIComponent(chainIdentifier),
660
- {
661
- ...init.additionalParams,
662
- paymentHash: init.paymentHash.toString("hex"),
663
- amount: init.amount.toString(),
664
- address: init.claimer,
665
- token: init.token,
666
- description: init.description ?? null,
667
- descriptionHash: init.descriptionHash==null ? null : init.descriptionHash.toString("hex"),
668
- exactOut: init.exactOut,
669
- gasToken: init.gasToken,
670
- gasAmount: init.gasAmount?.toString(10) ?? "0",
671
- claimerBounty: init.claimerBounty?.then(val => val.toString(10)) ?? "0"
672
- },
673
- {
674
- code: FieldTypeEnum.Number,
675
- msg: FieldTypeEnum.String,
676
- data: FieldTypeEnum.AnyOptional,
677
- lnPublicKey: FieldTypeEnum.StringOptional
678
- },
679
- timeout, abortSignal, streamRequest
680
- );
681
-
682
- return {
683
- lnPublicKey: responseBodyPromise.then(responseBody => responseBody.lnPublicKey),
684
- response: responseBodyPromise.then((responseBody) => Promise.all([
685
- responseBody.code,
686
- responseBody.msg,
687
- responseBody.data,
688
- ])).then(([code, msg, data]) => {
689
- if(code!==20000) {
690
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
691
- }
692
- const result = verifySchema(data, FromBTCLNAutoResponseSchema);
693
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
694
- return result;
695
- })
696
- };
697
- }
698
-
699
- /**
700
- * Initiate To BTCLN swap with an intermediary
701
- *
702
- * @param chainIdentifier
703
- * @param baseUrl Base URL of the intermediary
704
- * @param init Swap initialization parameters
705
- * @param timeout Timeout in milliseconds for the HTTP request
706
- * @param abortSignal
707
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
708
- *
709
- * @throws {RequestError} If non-200 http response code is returned
710
- */
711
- static initToBTCLN(
712
- chainIdentifier: string,
713
- baseUrl: string,
714
- init: ToBTCLNInit,
715
- timeout?: number,
716
- abortSignal?: AbortSignal,
717
- streamRequest?: boolean
718
- ): {
719
- signDataPrefetch: Promise<any>,
720
- response: Promise<ToBTCLNResponseType>
721
- } {
722
- const responseBodyPromise = streamingFetchPromise(baseUrl+"/tobtcln/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
723
- exactIn: false,
724
- ...init.additionalParams,
725
- pr: init.pr,
726
- maxFee: init.maxFee.toString(10),
727
- expiryTimestamp: init.expiryTimestamp.toString(10),
728
- token: init.token,
729
- offerer: init.offerer,
730
- feeRate: init.feeRate,
731
- amount: null
732
- }, {
733
- code: FieldTypeEnum.Number,
734
- msg: FieldTypeEnum.String,
735
- data: FieldTypeEnum.AnyOptional,
736
- signDataPrefetch: FieldTypeEnum.AnyOptional
737
- }, timeout, abortSignal, streamRequest);
738
-
739
- return {
740
- signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
741
- response: responseBodyPromise.then((responseBody) => Promise.all([
742
- responseBody.code,
743
- responseBody.msg,
744
- responseBody.data,
745
- ])).then(([code, msg, data]) => {
746
- if(code!==20000) {
747
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
748
- }
749
- const result = verifySchema(data, ToBTCLNResponseSchema);
750
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
751
- return result;
752
- })
753
- };
754
- }
755
-
756
- /**
757
- * Initiate To BTCLN exact in swap with an intermediary
758
- *
759
- * @param baseUrl Base URL of the intermediary
760
- * @param init Swap initialization parameters
761
- * @param timeout Timeout in milliseconds for the HTTP request
762
- * @param abortSignal
763
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
764
- *
765
- * @throws {RequestError} If non-200 http response code is returned
766
- */
767
- static async initToBTCLNExactIn(
768
- baseUrl: string,
769
- init: ToBTCLNInitExactIn,
770
- timeout?: number,
771
- abortSignal?: AbortSignal,
772
- streamRequest?: boolean
773
- ): Promise<ToBTCLNResponseType> {
774
- const responseBody = await streamingFetchPromise(baseUrl+"/tobtcln/payInvoiceExactIn", {
775
- ...init.additionalParams,
776
- pr: init.pr,
777
- reqId: init.reqId,
778
- feeRate: init.feeRate
779
- }, {
780
- code: FieldTypeEnum.Number,
781
- msg: FieldTypeEnum.String,
782
- data: FieldTypeEnum.AnyOptional
783
- }, timeout, abortSignal, streamRequest);
784
-
785
- const [code, msg, data] = await Promise.all([
786
- responseBody.code,
787
- responseBody.msg,
788
- responseBody.data,
789
- ])
790
-
791
- if(code!==20000) throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
792
- const result = verifySchema(data, ToBTCLNResponseSchema);
793
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
794
- return result;
795
- }
796
-
797
- /**
798
- * Prepare To BTCLN exact in swap with an intermediary
799
- *
800
- * @param chainIdentifier
801
- * @param baseUrl Base URL of the intermediary
802
- * @param init Swap initialization parameters
803
- * @param timeout Timeout in milliseconds for the HTTP request
804
- * @param abortSignal
805
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
806
- *
807
- * @throws {RequestError} If non-200 http response code is returned
808
- */
809
- static prepareToBTCLNExactIn(
810
- chainIdentifier: string,
811
- baseUrl: string,
812
- init: ToBTCLNPrepareExactIn,
813
- timeout?: number,
814
- abortSignal?: AbortSignal,
815
- streamRequest?: boolean
816
- ): {
817
- signDataPrefetch: Promise<any>,
818
- response: Promise<ToBTCLNPrepareExactInResponseType>
819
- } {
820
- const responseBodyPromise = streamingFetchPromise(baseUrl+"/tobtcln/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
821
- exactIn: true,
822
- ...init.additionalParams,
823
- pr: init.pr,
824
- maxFee: init.maxFee.toString(10),
825
- expiryTimestamp: init.expiryTimestamp.toString(10),
826
- token: init.token,
827
- offerer: init.offerer,
828
- amount: init.amount.toString(10)
829
- }, {
830
- code: FieldTypeEnum.Number,
831
- msg: FieldTypeEnum.String,
832
- data: FieldTypeEnum.AnyOptional,
833
- signDataPrefetch: FieldTypeEnum.AnyOptional
834
- }, timeout, abortSignal, streamRequest);
835
-
836
- return {
837
- signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
838
- response: responseBodyPromise.then((responseBody) => Promise.all([
839
- responseBody.code,
840
- responseBody.msg,
841
- responseBody.data,
842
- ])).then(([code, msg, data]) => {
843
- if(code!==20000) {
844
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
845
- }
846
- const result = verifySchema(data, ToBTCLNPrepareExactInSchema);
847
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
848
- return result;
849
- })
850
- };
851
- }
852
-
853
- /**
854
- * Prepare From BTC swap via new spv vault swaps with an intermediary
855
- *
856
- * @param chainIdentifier
857
- * @param baseUrl Base URL of the intermediary
858
- * @param init Swap initialization parameters
859
- * @param timeout Timeout in milliseconds for the HTTP request
860
- * @param abortSignal
861
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
862
- *
863
- * @throws {RequestError} If non-200 http response code is returned
864
- */
865
- static prepareSpvFromBTC(
866
- chainIdentifier: string,
867
- baseUrl: string,
868
- init: SpvFromBTCPrepare,
869
- timeout?: number,
870
- abortSignal?: AbortSignal,
871
- streamRequest?: boolean
872
- ): Promise<SpvFromBTCPrepareResponseType> {
873
- const responseBodyPromise = streamingFetchPromise(baseUrl+"/frombtc_spv/getQuote?chain="+encodeURIComponent(chainIdentifier), {
874
- exactOut: init.exactOut,
875
- ...init.additionalParams,
876
- address: init.address,
877
- amount: init.amount.toString(10),
878
- token: init.token,
879
- gasAmount: init.gasAmount.toString(10),
880
- gasToken: init.gasToken,
881
- frontingFeeRate: init.frontingFeeRate.toString(10),
882
- callerFeeRate: init.callerFeeRate.then(val => val.toString(10)),
883
- stickyAddress: init.stickyAddress
884
- }, {
885
- code: FieldTypeEnum.Number,
886
- msg: FieldTypeEnum.String,
887
- data: FieldTypeEnum.AnyOptional
888
- }, timeout, abortSignal, streamRequest);
889
-
890
- return responseBodyPromise.then((responseBody) => Promise.all([
891
- responseBody.code,
892
- responseBody.msg,
893
- responseBody.data,
894
- ])).then(([code, msg, data]) => {
895
- if(code!==20000) {
896
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
897
- }
898
- const result = verifySchema(data, SpvFromBTCPrepareResponseSchema);
899
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
900
- return result;
901
- });
902
- }
903
-
904
- /**
905
- * Prepare From BTC swap via new spv vault swaps with an intermediary
906
- *
907
- * @param chainIdentifier
908
- * @param url
909
- * @param init Swap initialization parameters
910
- * @param timeout Timeout in milliseconds for the HTTP request
911
- * @param abortSignal
912
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
913
- *
914
- * @throws {RequestError} If non-200 http response code is returned
915
- */
916
- static initSpvFromBTC(
917
- chainIdentifier: string,
918
- url: string,
919
- init: SpvFromBTCInit,
920
- timeout?: number,
921
- abortSignal?: AbortSignal,
922
- streamRequest?: boolean
923
- ): Promise<SpvFromBTCInitResponseType> {
924
- const responseBodyPromise = streamingFetchPromise(url+"/postQuote?chain="+encodeURIComponent(chainIdentifier), {
925
- quoteId: init.quoteId,
926
- psbtHex: init.psbtHex
927
- }, {
928
- code: FieldTypeEnum.Number,
929
- msg: FieldTypeEnum.String,
930
- data: FieldTypeEnum.AnyOptional
931
- }, timeout, abortSignal, streamRequest);
932
-
933
- return responseBodyPromise.then((responseBody) => Promise.all([
934
- responseBody.code,
935
- responseBody.msg,
936
- responseBody.data,
937
- ])).then(([code, msg, data]) => {
938
- if(code!==20000) {
939
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
940
- }
941
- const result = verifySchema(data, SpvFromBTCInitResponseSchema);
942
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
943
- return result;
944
- });
945
- }
946
-
947
- }
1
+ import {RequestError} from "../../errors/RequestError";
2
+ import {
3
+ FieldTypeEnum,
4
+ RequestSchemaResult,
5
+ verifySchema
6
+ } from "../../http/paramcoders/SchemaVerifier";
7
+ import {streamingFetchPromise} from "../../http/paramcoders/client/StreamingFetchPromise";
8
+ import {extendAbortController, randomBytes} from "../../utils/Utils";
9
+ import {httpGet, httpPost} from "../../http/HttpUtils";
10
+ import {tryWithRetries} from "../../utils/RetryUtils";
11
+
12
+ export type InfoHandlerResponse = {
13
+ envelope: string,
14
+ chains: {
15
+ [chainIdentifier: string]: {
16
+ address: string,
17
+ signature: string,
18
+ contractVersion?: string,
19
+ }
20
+ }
21
+ };
22
+
23
+ export enum RefundAuthorizationResponseCodes {
24
+ EXPIRED=20010,
25
+ REFUND_DATA=20000,
26
+ NOT_FOUND=20007,
27
+ PENDING=20008,
28
+ PAID=20006
29
+ }
30
+
31
+ export enum PaymentAuthorizationResponseCodes {
32
+ AUTH_DATA=10000,
33
+ EXPIRED=10001,
34
+ PAID=10002,
35
+ PENDING=10003,
36
+ ALREADY_COMMITTED=10004
37
+ }
38
+
39
+ export enum InvoiceStatusResponseCodes {
40
+ PAID=10000,
41
+ EXPIRED=10001,
42
+ SETTLED=10002,
43
+ PENDING=10003
44
+ }
45
+
46
+ export type RefundAuthorizationResponse = {
47
+ code: RefundAuthorizationResponseCodes.PAID,
48
+ msg: string,
49
+ data: {
50
+ secret?: string,
51
+ txId?: string
52
+ }
53
+ } | {
54
+ code: RefundAuthorizationResponseCodes.REFUND_DATA,
55
+ msg: string,
56
+ data: {
57
+ address: string,
58
+ prefix: string,
59
+ timeout: string,
60
+ signature: string
61
+ }
62
+ } | {
63
+ code: Exclude<RefundAuthorizationResponseCodes, RefundAuthorizationResponseCodes.PAID | RefundAuthorizationResponseCodes.REFUND_DATA>,
64
+ msg: string
65
+ };
66
+
67
+ export type PaymentAuthorizationResponse = {
68
+ code: PaymentAuthorizationResponseCodes.AUTH_DATA,
69
+ msg: string,
70
+ data: {
71
+ address: string,
72
+ data: any,
73
+ nonce: number,
74
+ prefix: string,
75
+ timeout: string,
76
+ signature: string
77
+ }
78
+ } | {
79
+ code: Exclude<PaymentAuthorizationResponseCodes, PaymentAuthorizationResponseCodes.AUTH_DATA>,
80
+ msg: string
81
+ };
82
+
83
+ export type InvoiceStatusResponse = {
84
+ code: Exclude<InvoiceStatusResponseCodes, InvoiceStatusResponseCodes.PAID>,
85
+ msg: string
86
+ } | {
87
+ code: InvoiceStatusResponseCodes.PAID,
88
+ msg: string,
89
+ data: {
90
+ data: any
91
+ }
92
+ }
93
+
94
+ const SwapResponseSchema = {
95
+ data: FieldTypeEnum.Any,
96
+
97
+ prefix: FieldTypeEnum.String,
98
+ timeout: FieldTypeEnum.String,
99
+ signature: FieldTypeEnum.String
100
+ } as const;
101
+
102
+ export type SwapInit = {
103
+ token: string,
104
+ additionalParams?: { [name: string]: any }
105
+ }
106
+
107
+ export type BaseFromBTCSwapInit = SwapInit & {
108
+ claimer: string,
109
+ amount: bigint,
110
+ exactOut: boolean,
111
+ feeRate: Promise<string>
112
+ };
113
+
114
+ export type BaseToBTCSwapInit = SwapInit & {
115
+ offerer: string
116
+ };
117
+
118
+ /////////////////////////
119
+ ///// To BTC
120
+
121
+ const ToBTCResponseSchema = {
122
+ amount: FieldTypeEnum.BigInt,
123
+ address: FieldTypeEnum.String,
124
+ satsPervByte: FieldTypeEnum.BigInt,
125
+ networkFee: FieldTypeEnum.BigInt,
126
+ swapFee: FieldTypeEnum.BigInt,
127
+ totalFee: FieldTypeEnum.BigInt,
128
+ total: FieldTypeEnum.BigInt,
129
+ minRequiredExpiry: FieldTypeEnum.BigInt,
130
+ ...SwapResponseSchema
131
+ } as const;
132
+
133
+ export type ToBTCResponseType = RequestSchemaResult<typeof ToBTCResponseSchema>;
134
+
135
+ export type ToBTCInit = BaseToBTCSwapInit & {
136
+ btcAddress: string,
137
+ exactIn: boolean,
138
+ amount: bigint,
139
+ confirmationTarget: number,
140
+ confirmations: number,
141
+ nonce: bigint,
142
+ feeRate: Promise<string>
143
+ }
144
+
145
+ /////////////////////////
146
+ ///// To BTCLN
147
+
148
+ const ToBTCLNResponseSchema = {
149
+ maxFee: FieldTypeEnum.BigInt,
150
+ swapFee: FieldTypeEnum.BigInt,
151
+ total: FieldTypeEnum.BigInt,
152
+ confidence: FieldTypeEnum.Number,
153
+ address: FieldTypeEnum.String,
154
+
155
+ routingFeeSats: FieldTypeEnum.BigInt,
156
+ ...SwapResponseSchema
157
+ } as const;
158
+
159
+ export type ToBTCLNResponseType = RequestSchemaResult<typeof ToBTCLNResponseSchema>;
160
+
161
+ export type ToBTCLNInit = BaseToBTCSwapInit & {
162
+ pr: string,
163
+ maxFee: bigint,
164
+ expiryTimestamp: bigint,
165
+ feeRate: Promise<string>
166
+ };
167
+
168
+ const ToBTCLNPrepareExactInSchema = {
169
+ amount: FieldTypeEnum.BigInt,
170
+ reqId: FieldTypeEnum.String
171
+ } as const;
172
+
173
+ export type ToBTCLNPrepareExactInResponseType = RequestSchemaResult<typeof ToBTCLNPrepareExactInSchema>;
174
+
175
+ export type ToBTCLNPrepareExactIn = BaseToBTCSwapInit & {
176
+ pr: string,
177
+ amount: bigint,
178
+ maxFee: bigint,
179
+ expiryTimestamp: bigint
180
+ }
181
+
182
+ export type ToBTCLNInitExactIn = {
183
+ pr: string,
184
+ reqId: string,
185
+ feeRate: Promise<string>,
186
+ additionalParams?: { [name: string]: any }
187
+ }
188
+
189
+ /////////////////////////
190
+ ///// From BTC
191
+
192
+ const FromBTCResponseSchema = {
193
+ amount: FieldTypeEnum.BigInt,
194
+ btcAddress: FieldTypeEnum.String,
195
+ address: FieldTypeEnum.String,
196
+ swapFee: FieldTypeEnum.BigInt,
197
+ total: FieldTypeEnum.BigInt,
198
+ confirmations: FieldTypeEnum.Number,
199
+ ...SwapResponseSchema
200
+ } as const;
201
+
202
+ export type FromBTCResponseType = RequestSchemaResult<typeof FromBTCResponseSchema>;
203
+
204
+ export type FromBTCInit = BaseFromBTCSwapInit & {
205
+ sequence: bigint,
206
+ claimerBounty: Promise<{
207
+ feePerBlock: bigint,
208
+ safetyFactor: bigint,
209
+ startTimestamp: bigint,
210
+ addBlock: bigint,
211
+ addFee: bigint
212
+ }>
213
+ }
214
+
215
+ /////////////////////////
216
+ ///// From BTCLN
217
+
218
+ const FromBTCLNResponseSchema = {
219
+ pr: FieldTypeEnum.String,
220
+ swapFee: FieldTypeEnum.BigInt,
221
+ total: FieldTypeEnum.BigInt,
222
+ intermediaryKey: FieldTypeEnum.String,
223
+ securityDeposit: FieldTypeEnum.BigInt
224
+ } as const;
225
+
226
+ export type FromBTCLNResponseType = RequestSchemaResult<typeof FromBTCLNResponseSchema>;
227
+
228
+ export type FromBTCLNInit = BaseFromBTCSwapInit & {
229
+ paymentHash: Buffer,
230
+ description?: string,
231
+ descriptionHash?: Buffer
232
+ }
233
+
234
+ /////////////////////////
235
+ ///// From BTCLN Auto
236
+
237
+ const FromBTCLNAutoResponseSchema = {
238
+ intermediaryKey: FieldTypeEnum.String,
239
+ pr: FieldTypeEnum.String,
240
+
241
+ btcAmountSwap: FieldTypeEnum.BigInt,
242
+ btcAmountGas: FieldTypeEnum.BigInt,
243
+
244
+ total: FieldTypeEnum.BigInt,
245
+ totalGas: FieldTypeEnum.BigInt,
246
+
247
+ totalFeeBtc: FieldTypeEnum.BigInt,
248
+
249
+ swapFeeBtc: FieldTypeEnum.BigInt,
250
+ swapFee: FieldTypeEnum.BigInt,
251
+
252
+ gasSwapFeeBtc: FieldTypeEnum.BigInt,
253
+ gasSwapFee: FieldTypeEnum.BigInt,
254
+
255
+ claimerBounty: FieldTypeEnum.BigInt
256
+ } as const;
257
+
258
+ export type FromBTCLNAutoResponseType = RequestSchemaResult<typeof FromBTCLNAutoResponseSchema>;
259
+
260
+ export type FromBTCLNAutoInit = Omit<BaseFromBTCSwapInit, "feeRate"> & {
261
+ paymentHash: Buffer,
262
+ gasToken: string,
263
+ description?: string,
264
+ descriptionHash?: Buffer,
265
+ gasAmount?: bigint,
266
+ claimerBounty?: Promise<bigint>
267
+ }
268
+
269
+ /////////////////////////
270
+ ///// Spv vault from BTC
271
+
272
+ const SpvFromBTCPrepareResponseSchema = {
273
+ quoteId: FieldTypeEnum.String,
274
+ expiry: FieldTypeEnum.Number,
275
+
276
+ address: FieldTypeEnum.String,
277
+ vaultId: FieldTypeEnum.BigInt,
278
+
279
+ vaultBtcAddress: FieldTypeEnum.String,
280
+ btcAddress: FieldTypeEnum.String,
281
+ btcUtxo: FieldTypeEnum.String,
282
+ btcFeeRate: FieldTypeEnum.Number,
283
+
284
+ btcAmount: FieldTypeEnum.BigInt,
285
+ btcAmountSwap: FieldTypeEnum.BigInt,
286
+ btcAmountGas: FieldTypeEnum.BigInt,
287
+
288
+ total: FieldTypeEnum.BigInt,
289
+ totalGas: FieldTypeEnum.BigInt,
290
+
291
+ totalFeeBtc: FieldTypeEnum.BigInt,
292
+
293
+ swapFeeBtc: FieldTypeEnum.BigInt,
294
+ swapFee: FieldTypeEnum.BigInt,
295
+
296
+ gasSwapFeeBtc: FieldTypeEnum.BigInt,
297
+ gasSwapFee: FieldTypeEnum.BigInt,
298
+
299
+ callerFeeShare: FieldTypeEnum.BigInt,
300
+ frontingFeeShare: FieldTypeEnum.BigInt,
301
+ executionFeeShare: FieldTypeEnum.BigInt,
302
+
303
+ usedUtxoInputCalculation: FieldTypeEnum.BooleanOptional
304
+ } as const;
305
+
306
+ export type SpvFromBTCPrepareResponseType = RequestSchemaResult<typeof SpvFromBTCPrepareResponseSchema>;
307
+
308
+ export type SpvFromBTCPrepare = SwapInit & {
309
+ address: string,
310
+ amount: Promise<bigint>,
311
+ gasAmount: bigint,
312
+ gasToken: string,
313
+ exactOut: boolean,
314
+ callerFeeRate: Promise<bigint>,
315
+ frontingFeeRate: bigint,
316
+ stickyAddress?: boolean,
317
+ amountUtxos?: Promise<{ value: number, vSize: number, cpfp?: { effectiveVSize: number, effectiveFeeRate: number }}[] | undefined>,
318
+ amountFeeRate?: Promise<number | undefined>
319
+ }
320
+
321
+ const SpvFromBTCInitResponseSchema = {
322
+ txId: FieldTypeEnum.String
323
+ } as const;
324
+
325
+ export type SpvFromBTCInitResponseType = RequestSchemaResult<typeof SpvFromBTCInitResponseSchema>;
326
+
327
+ export type SpvFromBTCInit = {
328
+ quoteId: string,
329
+ psbtHex: string
330
+ }
331
+
332
+ export class IntermediaryAPI {
333
+
334
+ /**
335
+ * Returns the information about a specific intermediary
336
+ *
337
+ * @param baseUrl Base URL of the intermediary
338
+ * @param timeout Timeout in milliseconds for the HTTP request
339
+ * @param abortSignal
340
+ *
341
+ * @throws {RequestError} If non-200 http response code is returned
342
+ * @throws {Error} If the supplied nonce doesn't match the response
343
+ */
344
+ static async getIntermediaryInfo(
345
+ baseUrl: string,
346
+ timeout?: number,
347
+ abortSignal?: AbortSignal
348
+ ): Promise<InfoHandlerResponse> {
349
+ const nonce = randomBytes(32).toString("hex");
350
+
351
+ const abortController = extendAbortController(abortSignal);
352
+
353
+ //We don't know whether the node supports only POST or also has GET info support enabled
354
+ // here we try both, and abort when the first one returns (which should be GET)
355
+ const response = await Promise.any([
356
+ httpGet<InfoHandlerResponse>(baseUrl+"/info?nonce="+nonce, timeout, abortController.signal),
357
+ httpPost<InfoHandlerResponse>(baseUrl+"/info", {
358
+ nonce,
359
+ }, timeout, abortController.signal)
360
+ ]);
361
+ abortController.abort();
362
+
363
+ const info = JSON.parse(response.envelope);
364
+ if(nonce!==info.nonce) throw new Error("Invalid response - nonce");
365
+
366
+ return response;
367
+ }
368
+
369
+ /**
370
+ * Returns the information about an outcome of the To BTC swap
371
+ *
372
+ * @param url URL of the intermediary
373
+ * @param paymentHash Payment hash of the swap
374
+ * @param sequence Swap's sequence number
375
+ * @param timeout Timeout in milliseconds for the HTTP request
376
+ * @param abortSignal
377
+ *
378
+ * @throws {RequestError} If non-200 http response code is returned
379
+ */
380
+ static async getRefundAuthorization(
381
+ url: string,
382
+ paymentHash: string,
383
+ sequence: bigint,
384
+ timeout?: number,
385
+ abortSignal?: AbortSignal
386
+ ): Promise<RefundAuthorizationResponse> {
387
+ return tryWithRetries(() => httpGet<RefundAuthorizationResponse>(
388
+ url + "/getRefundAuthorization"+
389
+ "?paymentHash=" + encodeURIComponent(paymentHash) +
390
+ "&sequence=" + encodeURIComponent(sequence.toString(10)),
391
+ timeout,
392
+ abortSignal
393
+ ), undefined, RequestError, abortSignal);
394
+ }
395
+
396
+ /**
397
+ * Returns the information about the payment of the From BTCLN swaps
398
+ *
399
+ * @param url URL of the intermediary
400
+ * @param paymentHash Payment hash of the swap
401
+ * @param timeout Timeout in milliseconds for the HTTP request
402
+ * @param abortSignal
403
+ *
404
+ * @throws {RequestError} If non-200 http response code is returned
405
+ */
406
+ static async getPaymentAuthorization(
407
+ url: string,
408
+ paymentHash: string,
409
+ timeout?: number,
410
+ abortSignal?: AbortSignal
411
+ ): Promise<PaymentAuthorizationResponse> {
412
+ return tryWithRetries(() => httpGet<PaymentAuthorizationResponse>(
413
+ url+"/getInvoicePaymentAuth"+
414
+ "?paymentHash="+encodeURIComponent(paymentHash),
415
+ timeout,
416
+ abortSignal
417
+ ), undefined, RequestError, abortSignal);
418
+ }
419
+
420
+ /**
421
+ * Returns the status of the payment of the From BTCLN swaps
422
+ *
423
+ * @param url URL of the intermediary
424
+ * @param paymentHash Payment hash of the swap
425
+ * @param timeout Timeout in milliseconds for the HTTP request
426
+ * @param abortSignal
427
+ *
428
+ * @throws {RequestError} If non-200 http response code is returned
429
+ */
430
+ static async getInvoiceStatus(
431
+ url: string,
432
+ paymentHash: string,
433
+ timeout?: number,
434
+ abortSignal?: AbortSignal
435
+ ): Promise<InvoiceStatusResponse> {
436
+ return tryWithRetries(() => httpGet<InvoiceStatusResponse>(
437
+ url+"/getInvoiceStatus"+
438
+ "?paymentHash="+encodeURIComponent(paymentHash),
439
+ timeout,
440
+ abortSignal
441
+ ), undefined, RequestError, abortSignal);
442
+ }
443
+
444
+ /**
445
+ * Initiate To BTC swap with an intermediary
446
+ *
447
+ * @param chainIdentifier
448
+ * @param baseUrl Base URL of the intermediary
449
+ * @param init Swap initialization parameters
450
+ * @param timeout Timeout in milliseconds for the HTTP request
451
+ * @param abortSignal
452
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
453
+ *
454
+ * @throws {RequestError} If non-200 http response code is returned
455
+ */
456
+ static initToBTC(
457
+ chainIdentifier: string,
458
+ baseUrl: string,
459
+ init: ToBTCInit,
460
+ timeout?: number,
461
+ abortSignal?: AbortSignal,
462
+ streamRequest?: boolean
463
+ ): {
464
+ signDataPrefetch: Promise<any>,
465
+ response: Promise<ToBTCResponseType>
466
+ } {
467
+ const responseBodyPromise = streamingFetchPromise(baseUrl+"/tobtc/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
468
+ ...init.additionalParams,
469
+ address: init.btcAddress,
470
+ amount: init.amount.toString(10),
471
+ exactIn: init.exactIn,
472
+ confirmationTarget: init.confirmationTarget,
473
+ confirmations: init.confirmations,
474
+ nonce: init.nonce.toString(10),
475
+ token: init.token,
476
+ offerer: init.offerer,
477
+ feeRate: init.feeRate
478
+ }, {
479
+ code: FieldTypeEnum.Number,
480
+ msg: FieldTypeEnum.String,
481
+ data: FieldTypeEnum.AnyOptional,
482
+ signDataPrefetch: FieldTypeEnum.AnyOptional
483
+ }, timeout, abortSignal, streamRequest);
484
+
485
+ return {
486
+ signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
487
+ response: responseBodyPromise.then((responseBody) => Promise.all([
488
+ responseBody.code,
489
+ responseBody.msg,
490
+ responseBody.data,
491
+ ])).then(([code, msg, data]) => {
492
+ if(code!==20000) {
493
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
494
+ }
495
+ const result = verifySchema(data, ToBTCResponseSchema);
496
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
497
+ return result;
498
+ })
499
+ };
500
+ }
501
+
502
+ /**
503
+ * Initiate From BTC swap with an intermediary
504
+ *
505
+ * @param chainIdentifier
506
+ * @param baseUrl Base URL of the intermediary
507
+ * @param depositToken
508
+ * @param init Swap initialization parameters
509
+ * @param timeout Timeout in milliseconds for the HTTP request
510
+ * @param abortSignal
511
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
512
+ *
513
+ * @throws {RequestError} If non-200 http response code is returned
514
+ */
515
+ static initFromBTC(
516
+ chainIdentifier: string,
517
+ baseUrl: string,
518
+ depositToken: string,
519
+ init: FromBTCInit,
520
+ timeout?: number,
521
+ abortSignal?: AbortSignal,
522
+ streamRequest?: boolean
523
+ ): {
524
+ signDataPrefetch: Promise<any>,
525
+ response: Promise<FromBTCResponseType>
526
+ } {
527
+ const responseBodyPromise = streamingFetchPromise(
528
+ baseUrl+"/frombtc/getAddress?chain="+encodeURIComponent(chainIdentifier)+"&depositToken="+encodeURIComponent(depositToken),
529
+ {
530
+ ...init.additionalParams,
531
+ address: init.claimer,
532
+ amount: init.amount.toString(10),
533
+ token: init.token,
534
+
535
+ exactOut: init.exactOut,
536
+ sequence: init.sequence.toString(10),
537
+
538
+ claimerBounty: init.claimerBounty.then(claimerBounty => {
539
+ return {
540
+ feePerBlock: claimerBounty.feePerBlock.toString(10),
541
+ safetyFactor: claimerBounty.safetyFactor.toString(10),
542
+ startTimestamp: claimerBounty.startTimestamp.toString(10),
543
+ addBlock: claimerBounty.addBlock.toString(10),
544
+ addFee: claimerBounty.addFee.toString(10)
545
+ }
546
+ }),
547
+ feeRate: init.feeRate
548
+ },
549
+ {
550
+ code: FieldTypeEnum.Number,
551
+ msg: FieldTypeEnum.String,
552
+ data: FieldTypeEnum.AnyOptional,
553
+ signDataPrefetch: FieldTypeEnum.AnyOptional
554
+ },
555
+ timeout, abortSignal, streamRequest
556
+ );
557
+
558
+ return {
559
+ signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
560
+ response: responseBodyPromise.then((responseBody) => Promise.all([
561
+ responseBody.code,
562
+ responseBody.msg,
563
+ responseBody.data,
564
+ ])).then(([code, msg, data]) => {
565
+ if(code!==20000) {
566
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
567
+ }
568
+ const result = verifySchema(data, FromBTCResponseSchema);
569
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
570
+ return result;
571
+ })
572
+ };
573
+ }
574
+
575
+ /**
576
+ * Initiate From BTCLN swap with an intermediary
577
+ *
578
+ * @param chainIdentifier
579
+ * @param baseUrl Base URL of the intermediary
580
+ * @param depositToken
581
+ * @param init Swap initialization parameters
582
+ * @param timeout Timeout in milliseconds for the HTTP request
583
+ * @param abortSignal
584
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
585
+ *
586
+ * @throws {RequestError} If non-200 http response code is returned
587
+ */
588
+ static initFromBTCLN(
589
+ chainIdentifier: string,
590
+ baseUrl: string,
591
+ depositToken: string,
592
+ init: FromBTCLNInit,
593
+ timeout?: number,
594
+ abortSignal?: AbortSignal,
595
+ streamRequest?: boolean
596
+ ): {
597
+ lnPublicKey: Promise<string | null>,
598
+ response: Promise<FromBTCLNResponseType>
599
+ } {
600
+ const responseBodyPromise = streamingFetchPromise(
601
+ baseUrl+"/frombtcln/createInvoice?chain="+encodeURIComponent(chainIdentifier)+"&depositToken="+encodeURIComponent(depositToken),
602
+ {
603
+ ...init.additionalParams,
604
+ paymentHash: init.paymentHash.toString("hex"),
605
+ amount: init.amount.toString(),
606
+ address: init.claimer,
607
+ token: init.token,
608
+ description: init.description ?? null,
609
+ descriptionHash: init.descriptionHash==null ? null : init.descriptionHash.toString("hex"),
610
+ exactOut: init.exactOut,
611
+ feeRate: init.feeRate
612
+ },
613
+ {
614
+ code: FieldTypeEnum.Number,
615
+ msg: FieldTypeEnum.String,
616
+ data: FieldTypeEnum.AnyOptional,
617
+ lnPublicKey: FieldTypeEnum.StringOptional
618
+ },
619
+ timeout, abortSignal, streamRequest
620
+ );
621
+
622
+ return {
623
+ lnPublicKey: responseBodyPromise.then(responseBody => responseBody.lnPublicKey),
624
+ response: responseBodyPromise.then((responseBody) => Promise.all([
625
+ responseBody.code,
626
+ responseBody.msg,
627
+ responseBody.data,
628
+ ])).then(([code, msg, data]) => {
629
+ if(code!==20000) {
630
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
631
+ }
632
+ const result = verifySchema(data, FromBTCLNResponseSchema);
633
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
634
+ return result;
635
+ })
636
+ };
637
+ }
638
+
639
+ /**
640
+ * Initiate From BTCLN swap with auto-initilization by an intermediary
641
+ *
642
+ * @param chainIdentifier
643
+ * @param baseUrl Base URL of the intermediary
644
+ * @param init Swap initialization parameters
645
+ * @param timeout Timeout in milliseconds for the HTTP request
646
+ * @param abortSignal
647
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
648
+ *
649
+ * @throws {RequestError} If non-200 http response code is returned
650
+ */
651
+ static initFromBTCLNAuto(
652
+ chainIdentifier: string,
653
+ baseUrl: string,
654
+ init: FromBTCLNAutoInit,
655
+ timeout?: number,
656
+ abortSignal?: AbortSignal,
657
+ streamRequest?: boolean
658
+ ): {
659
+ lnPublicKey: Promise<string | null>,
660
+ response: Promise<FromBTCLNAutoResponseType>
661
+ } {
662
+ const responseBodyPromise = streamingFetchPromise(
663
+ baseUrl+"/frombtcln_auto/createInvoice?chain="+encodeURIComponent(chainIdentifier),
664
+ {
665
+ ...init.additionalParams,
666
+ paymentHash: init.paymentHash.toString("hex"),
667
+ amount: init.amount.toString(),
668
+ address: init.claimer,
669
+ token: init.token,
670
+ description: init.description ?? null,
671
+ descriptionHash: init.descriptionHash==null ? null : init.descriptionHash.toString("hex"),
672
+ exactOut: init.exactOut,
673
+ gasToken: init.gasToken,
674
+ gasAmount: init.gasAmount?.toString(10) ?? "0",
675
+ claimerBounty: init.claimerBounty?.then(val => val.toString(10)) ?? "0"
676
+ },
677
+ {
678
+ code: FieldTypeEnum.Number,
679
+ msg: FieldTypeEnum.String,
680
+ data: FieldTypeEnum.AnyOptional,
681
+ lnPublicKey: FieldTypeEnum.StringOptional
682
+ },
683
+ timeout, abortSignal, streamRequest
684
+ );
685
+
686
+ return {
687
+ lnPublicKey: responseBodyPromise.then(responseBody => responseBody.lnPublicKey),
688
+ response: responseBodyPromise.then((responseBody) => Promise.all([
689
+ responseBody.code,
690
+ responseBody.msg,
691
+ responseBody.data,
692
+ ])).then(([code, msg, data]) => {
693
+ if(code!==20000) {
694
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
695
+ }
696
+ const result = verifySchema(data, FromBTCLNAutoResponseSchema);
697
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
698
+ return result;
699
+ })
700
+ };
701
+ }
702
+
703
+ /**
704
+ * Initiate To BTCLN swap with an intermediary
705
+ *
706
+ * @param chainIdentifier
707
+ * @param baseUrl Base URL of the intermediary
708
+ * @param init Swap initialization parameters
709
+ * @param timeout Timeout in milliseconds for the HTTP request
710
+ * @param abortSignal
711
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
712
+ *
713
+ * @throws {RequestError} If non-200 http response code is returned
714
+ */
715
+ static initToBTCLN(
716
+ chainIdentifier: string,
717
+ baseUrl: string,
718
+ init: ToBTCLNInit,
719
+ timeout?: number,
720
+ abortSignal?: AbortSignal,
721
+ streamRequest?: boolean
722
+ ): {
723
+ signDataPrefetch: Promise<any>,
724
+ response: Promise<ToBTCLNResponseType>
725
+ } {
726
+ const responseBodyPromise = streamingFetchPromise(baseUrl+"/tobtcln/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
727
+ exactIn: false,
728
+ ...init.additionalParams,
729
+ pr: init.pr,
730
+ maxFee: init.maxFee.toString(10),
731
+ expiryTimestamp: init.expiryTimestamp.toString(10),
732
+ token: init.token,
733
+ offerer: init.offerer,
734
+ feeRate: init.feeRate,
735
+ amount: null
736
+ }, {
737
+ code: FieldTypeEnum.Number,
738
+ msg: FieldTypeEnum.String,
739
+ data: FieldTypeEnum.AnyOptional,
740
+ signDataPrefetch: FieldTypeEnum.AnyOptional
741
+ }, timeout, abortSignal, streamRequest);
742
+
743
+ return {
744
+ signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
745
+ response: responseBodyPromise.then((responseBody) => Promise.all([
746
+ responseBody.code,
747
+ responseBody.msg,
748
+ responseBody.data,
749
+ ])).then(([code, msg, data]) => {
750
+ if(code!==20000) {
751
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
752
+ }
753
+ const result = verifySchema(data, ToBTCLNResponseSchema);
754
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
755
+ return result;
756
+ })
757
+ };
758
+ }
759
+
760
+ /**
761
+ * Initiate To BTCLN exact in swap with an intermediary
762
+ *
763
+ * @param baseUrl Base URL of the intermediary
764
+ * @param init Swap initialization parameters
765
+ * @param timeout Timeout in milliseconds for the HTTP request
766
+ * @param abortSignal
767
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
768
+ *
769
+ * @throws {RequestError} If non-200 http response code is returned
770
+ */
771
+ static async initToBTCLNExactIn(
772
+ baseUrl: string,
773
+ init: ToBTCLNInitExactIn,
774
+ timeout?: number,
775
+ abortSignal?: AbortSignal,
776
+ streamRequest?: boolean
777
+ ): Promise<ToBTCLNResponseType> {
778
+ const responseBody = await streamingFetchPromise(baseUrl+"/tobtcln/payInvoiceExactIn", {
779
+ ...init.additionalParams,
780
+ pr: init.pr,
781
+ reqId: init.reqId,
782
+ feeRate: init.feeRate
783
+ }, {
784
+ code: FieldTypeEnum.Number,
785
+ msg: FieldTypeEnum.String,
786
+ data: FieldTypeEnum.AnyOptional
787
+ }, timeout, abortSignal, streamRequest);
788
+
789
+ const [code, msg, data] = await Promise.all([
790
+ responseBody.code,
791
+ responseBody.msg,
792
+ responseBody.data,
793
+ ])
794
+
795
+ if(code!==20000) throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
796
+ const result = verifySchema(data, ToBTCLNResponseSchema);
797
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
798
+ return result;
799
+ }
800
+
801
+ /**
802
+ * Prepare To BTCLN exact in swap with an intermediary
803
+ *
804
+ * @param chainIdentifier
805
+ * @param baseUrl Base URL of the intermediary
806
+ * @param init Swap initialization parameters
807
+ * @param timeout Timeout in milliseconds for the HTTP request
808
+ * @param abortSignal
809
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
810
+ *
811
+ * @throws {RequestError} If non-200 http response code is returned
812
+ */
813
+ static prepareToBTCLNExactIn(
814
+ chainIdentifier: string,
815
+ baseUrl: string,
816
+ init: ToBTCLNPrepareExactIn,
817
+ timeout?: number,
818
+ abortSignal?: AbortSignal,
819
+ streamRequest?: boolean
820
+ ): {
821
+ signDataPrefetch: Promise<any>,
822
+ response: Promise<ToBTCLNPrepareExactInResponseType>
823
+ } {
824
+ const responseBodyPromise = streamingFetchPromise(baseUrl+"/tobtcln/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
825
+ exactIn: true,
826
+ ...init.additionalParams,
827
+ pr: init.pr,
828
+ maxFee: init.maxFee.toString(10),
829
+ expiryTimestamp: init.expiryTimestamp.toString(10),
830
+ token: init.token,
831
+ offerer: init.offerer,
832
+ amount: init.amount.toString(10)
833
+ }, {
834
+ code: FieldTypeEnum.Number,
835
+ msg: FieldTypeEnum.String,
836
+ data: FieldTypeEnum.AnyOptional,
837
+ signDataPrefetch: FieldTypeEnum.AnyOptional
838
+ }, timeout, abortSignal, streamRequest);
839
+
840
+ return {
841
+ signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
842
+ response: responseBodyPromise.then((responseBody) => Promise.all([
843
+ responseBody.code,
844
+ responseBody.msg,
845
+ responseBody.data,
846
+ ])).then(([code, msg, data]) => {
847
+ if(code!==20000) {
848
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
849
+ }
850
+ const result = verifySchema(data, ToBTCLNPrepareExactInSchema);
851
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
852
+ return result;
853
+ })
854
+ };
855
+ }
856
+
857
+ /**
858
+ * Prepare From BTC swap via new spv vault swaps with an intermediary
859
+ *
860
+ * @param chainIdentifier
861
+ * @param baseUrl Base URL of the intermediary
862
+ * @param init Swap initialization parameters
863
+ * @param timeout Timeout in milliseconds for the HTTP request
864
+ * @param abortSignal
865
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
866
+ *
867
+ * @throws {RequestError} If non-200 http response code is returned
868
+ */
869
+ static prepareSpvFromBTC(
870
+ chainIdentifier: string,
871
+ baseUrl: string,
872
+ init: SpvFromBTCPrepare,
873
+ timeout?: number,
874
+ abortSignal?: AbortSignal,
875
+ streamRequest?: boolean
876
+ ): Promise<SpvFromBTCPrepareResponseType> {
877
+ //We need to make sure we only send the amount parameter after the amountUtxos and amountFeeRate resolve
878
+ // this is needed, because in the LP code to maintain backwards compatibility the amountUtxos and amountFeeRate
879
+ // params are checked immediately after the amount param (and other params) are received, if amount were sent
880
+ // first without the amountUtxos or amountFeeRate populated these fields would've been skipped altogether
881
+ const amountPromise = (async () => {
882
+ if(init.amountUtxos!=null) await init.amountUtxos;
883
+ if(init.amountFeeRate!=null) await init.amountFeeRate;
884
+ const amount = await init.amount;
885
+ return amount.toString(10);
886
+ })();
887
+ const responseBodyPromise = streamingFetchPromise(baseUrl+"/frombtc_spv/getQuote?chain="+encodeURIComponent(chainIdentifier), {
888
+ exactOut: init.exactOut,
889
+ ...init.additionalParams,
890
+ address: init.address,
891
+ amount: amountPromise,
892
+ token: init.token,
893
+ gasAmount: init.gasAmount.toString(10),
894
+ gasToken: init.gasToken,
895
+ frontingFeeRate: init.frontingFeeRate.toString(10),
896
+ callerFeeRate: init.callerFeeRate.then(val => val.toString(10)),
897
+ stickyAddress: init.stickyAddress,
898
+ amountUtxos: init.amountUtxos,
899
+ amountFeeRate: init.amountFeeRate
900
+ }, {
901
+ code: FieldTypeEnum.Number,
902
+ msg: FieldTypeEnum.String,
903
+ data: FieldTypeEnum.AnyOptional
904
+ }, timeout, abortSignal, streamRequest);
905
+
906
+ return responseBodyPromise.then((responseBody) => Promise.all([
907
+ responseBody.code,
908
+ responseBody.msg,
909
+ responseBody.data,
910
+ ])).then(([code, msg, data]) => {
911
+ if(code!==20000) {
912
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
913
+ }
914
+ const result = verifySchema(data, SpvFromBTCPrepareResponseSchema);
915
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
916
+ return result;
917
+ });
918
+ }
919
+
920
+ /**
921
+ * Prepare From BTC swap via new spv vault swaps with an intermediary
922
+ *
923
+ * @param chainIdentifier
924
+ * @param url
925
+ * @param init Swap initialization parameters
926
+ * @param timeout Timeout in milliseconds for the HTTP request
927
+ * @param abortSignal
928
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
929
+ *
930
+ * @throws {RequestError} If non-200 http response code is returned
931
+ */
932
+ static initSpvFromBTC(
933
+ chainIdentifier: string,
934
+ url: string,
935
+ init: SpvFromBTCInit,
936
+ timeout?: number,
937
+ abortSignal?: AbortSignal,
938
+ streamRequest?: boolean
939
+ ): Promise<SpvFromBTCInitResponseType> {
940
+ const responseBodyPromise = streamingFetchPromise(url+"/postQuote?chain="+encodeURIComponent(chainIdentifier), {
941
+ quoteId: init.quoteId,
942
+ psbtHex: init.psbtHex
943
+ }, {
944
+ code: FieldTypeEnum.Number,
945
+ msg: FieldTypeEnum.String,
946
+ data: FieldTypeEnum.AnyOptional
947
+ }, timeout, abortSignal, streamRequest);
948
+
949
+ return responseBodyPromise.then((responseBody) => Promise.all([
950
+ responseBody.code,
951
+ responseBody.msg,
952
+ responseBody.data,
953
+ ])).then(([code, msg, data]) => {
954
+ if(code!==20000) {
955
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
956
+ }
957
+ const result = verifySchema(data, SpvFromBTCInitResponseSchema);
958
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
959
+ return result;
960
+ });
961
+ }
962
+
963
+ }