@atomiqlabs/sdk 8.9.1 → 8.9.2

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 (366) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +1760 -1760
  3. package/api/index.d.ts +1 -1
  4. package/api/index.js +3 -3
  5. package/dist/ApiList.d.ts +37 -37
  6. package/dist/ApiList.js +30 -30
  7. package/dist/SmartChainAssets.d.ts +181 -181
  8. package/dist/SmartChainAssets.js +181 -181
  9. package/dist/api/ApiEndpoints.d.ts +393 -393
  10. package/dist/api/ApiEndpoints.js +2 -2
  11. package/dist/api/ApiParser.d.ts +10 -10
  12. package/dist/api/ApiParser.js +134 -134
  13. package/dist/api/ApiTypes.d.ts +157 -157
  14. package/dist/api/ApiTypes.js +75 -75
  15. package/dist/api/SerializedAction.d.ts +40 -40
  16. package/dist/api/SerializedAction.js +59 -59
  17. package/dist/api/SwapperApi.d.ts +50 -50
  18. package/dist/api/SwapperApi.js +431 -431
  19. package/dist/api/index.d.ts +5 -5
  20. package/dist/api/index.js +24 -24
  21. package/dist/bitcoin/coinselect2/accumulative.d.ts +7 -7
  22. package/dist/bitcoin/coinselect2/accumulative.js +52 -52
  23. package/dist/bitcoin/coinselect2/blackjack.d.ts +7 -7
  24. package/dist/bitcoin/coinselect2/blackjack.js +38 -38
  25. package/dist/bitcoin/coinselect2/index.d.ts +20 -20
  26. package/dist/bitcoin/coinselect2/index.js +69 -69
  27. package/dist/bitcoin/coinselect2/utils.d.ts +82 -82
  28. package/dist/bitcoin/coinselect2/utils.js +158 -158
  29. package/dist/bitcoin/wallet/BitcoinWallet.d.ts +113 -113
  30. package/dist/bitcoin/wallet/BitcoinWallet.js +335 -335
  31. package/dist/bitcoin/wallet/IBitcoinWallet.d.ts +116 -116
  32. package/dist/bitcoin/wallet/IBitcoinWallet.js +21 -21
  33. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.d.ts +106 -106
  34. package/dist/bitcoin/wallet/SingleAddressBitcoinWallet.js +196 -196
  35. package/dist/enums/FeeType.d.ts +15 -15
  36. package/dist/enums/FeeType.js +19 -19
  37. package/dist/enums/SwapAmountType.d.ts +15 -15
  38. package/dist/enums/SwapAmountType.js +19 -19
  39. package/dist/enums/SwapDirection.d.ts +15 -15
  40. package/dist/enums/SwapDirection.js +19 -19
  41. package/dist/enums/SwapSide.d.ts +15 -15
  42. package/dist/enums/SwapSide.js +19 -19
  43. package/dist/enums/SwapType.d.ts +75 -75
  44. package/dist/enums/SwapType.js +79 -79
  45. package/dist/errors/IntermediaryError.d.ts +13 -13
  46. package/dist/errors/IntermediaryError.js +27 -27
  47. package/dist/errors/RequestError.d.ts +32 -32
  48. package/dist/errors/RequestError.js +54 -54
  49. package/dist/errors/UserError.d.ts +8 -8
  50. package/dist/errors/UserError.js +16 -16
  51. package/dist/events/UnifiedSwapEventListener.d.ts +24 -24
  52. package/dist/events/UnifiedSwapEventListener.js +138 -138
  53. package/dist/http/HttpUtils.d.ts +29 -29
  54. package/dist/http/HttpUtils.js +97 -97
  55. package/dist/http/paramcoders/IParamReader.d.ts +8 -8
  56. package/dist/http/paramcoders/IParamReader.js +2 -2
  57. package/dist/http/paramcoders/ParamDecoder.d.ts +44 -44
  58. package/dist/http/paramcoders/ParamDecoder.js +137 -137
  59. package/dist/http/paramcoders/ParamEncoder.d.ts +20 -20
  60. package/dist/http/paramcoders/ParamEncoder.js +36 -36
  61. package/dist/http/paramcoders/SchemaVerifier.d.ts +26 -26
  62. package/dist/http/paramcoders/SchemaVerifier.js +145 -145
  63. package/dist/http/paramcoders/client/ResponseParamDecoder.d.ts +11 -11
  64. package/dist/http/paramcoders/client/ResponseParamDecoder.js +57 -57
  65. package/dist/http/paramcoders/client/StreamParamEncoder.d.ts +13 -13
  66. package/dist/http/paramcoders/client/StreamParamEncoder.js +26 -26
  67. package/dist/http/paramcoders/client/StreamingFetchPromise.d.ts +17 -17
  68. package/dist/http/paramcoders/client/StreamingFetchPromise.js +175 -175
  69. package/dist/index.d.ts +86 -86
  70. package/dist/index.js +159 -159
  71. package/dist/intermediaries/Intermediary.d.ts +178 -178
  72. package/dist/intermediaries/Intermediary.js +166 -166
  73. package/dist/intermediaries/IntermediaryDiscovery.d.ts +216 -216
  74. package/dist/intermediaries/IntermediaryDiscovery.js +424 -424
  75. package/dist/intermediaries/apis/IntermediaryAPI.d.ts +607 -607
  76. package/dist/intermediaries/apis/IntermediaryAPI.js +764 -764
  77. package/dist/intermediaries/apis/TrustedIntermediaryAPI.d.ts +155 -155
  78. package/dist/intermediaries/apis/TrustedIntermediaryAPI.js +137 -137
  79. package/dist/intermediaries/auth/SignedKeyBasedAuth.d.ts +14 -14
  80. package/dist/intermediaries/auth/SignedKeyBasedAuth.js +68 -68
  81. package/dist/lnurl/LNURL.d.ts +102 -102
  82. package/dist/lnurl/LNURL.js +321 -321
  83. package/dist/prices/RedundantSwapPrice.d.ts +110 -110
  84. package/dist/prices/RedundantSwapPrice.js +222 -222
  85. package/dist/prices/SingleSwapPrice.d.ts +34 -34
  86. package/dist/prices/SingleSwapPrice.js +44 -44
  87. package/dist/prices/SwapPriceWithChain.d.ts +107 -107
  88. package/dist/prices/SwapPriceWithChain.js +128 -128
  89. package/dist/prices/abstract/ICachedSwapPrice.d.ts +28 -28
  90. package/dist/prices/abstract/ICachedSwapPrice.js +62 -62
  91. package/dist/prices/abstract/IPriceProvider.d.ts +81 -81
  92. package/dist/prices/abstract/IPriceProvider.js +74 -74
  93. package/dist/prices/abstract/ISwapPrice.d.ts +168 -168
  94. package/dist/prices/abstract/ISwapPrice.js +279 -279
  95. package/dist/prices/providers/BinancePriceProvider.d.ts +23 -23
  96. package/dist/prices/providers/BinancePriceProvider.js +30 -30
  97. package/dist/prices/providers/CoinGeckoPriceProvider.d.ts +23 -23
  98. package/dist/prices/providers/CoinGeckoPriceProvider.js +29 -29
  99. package/dist/prices/providers/CoinPaprikaPriceProvider.d.ts +25 -25
  100. package/dist/prices/providers/CoinPaprikaPriceProvider.js +29 -29
  101. package/dist/prices/providers/CustomPriceProvider.d.ts +24 -24
  102. package/dist/prices/providers/CustomPriceProvider.js +35 -35
  103. package/dist/prices/providers/KrakenPriceProvider.d.ts +38 -38
  104. package/dist/prices/providers/KrakenPriceProvider.js +45 -45
  105. package/dist/prices/providers/OKXPriceProvider.d.ts +34 -34
  106. package/dist/prices/providers/OKXPriceProvider.js +29 -29
  107. package/dist/prices/providers/abstract/ExchangePriceProvider.d.ts +17 -17
  108. package/dist/prices/providers/abstract/ExchangePriceProvider.js +21 -21
  109. package/dist/prices/providers/abstract/HttpPriceProvider.d.ts +7 -7
  110. package/dist/prices/providers/abstract/HttpPriceProvider.js +12 -12
  111. package/dist/storage/IUnifiedStorage.d.ts +127 -127
  112. package/dist/storage/IUnifiedStorage.js +2 -2
  113. package/dist/storage/UnifiedSwapStorage.d.ts +120 -120
  114. package/dist/storage/UnifiedSwapStorage.js +154 -154
  115. package/dist/storage-browser/IndexedDBUnifiedStorage.d.ts +63 -63
  116. package/dist/storage-browser/IndexedDBUnifiedStorage.js +298 -298
  117. package/dist/storage-browser/LocalStorageManager.d.ts +49 -49
  118. package/dist/storage-browser/LocalStorageManager.js +93 -93
  119. package/dist/swapper/Swapper.d.ts +765 -770
  120. package/dist/swapper/Swapper.js +1749 -1758
  121. package/dist/swapper/SwapperFactory.d.ts +135 -135
  122. package/dist/swapper/SwapperFactory.js +162 -162
  123. package/dist/swapper/SwapperUtils.d.ts +222 -222
  124. package/dist/swapper/SwapperUtils.js +519 -519
  125. package/dist/swapper/SwapperWithChain.d.ts +404 -404
  126. package/dist/swapper/SwapperWithChain.js +469 -469
  127. package/dist/swapper/SwapperWithSigner.d.ts +322 -322
  128. package/dist/swapper/SwapperWithSigner.js +318 -318
  129. package/dist/swaps/IAddressSwap.d.ts +22 -22
  130. package/dist/swaps/IAddressSwap.js +14 -14
  131. package/dist/swaps/IBTCWalletSwap.d.ts +73 -73
  132. package/dist/swaps/IBTCWalletSwap.js +18 -18
  133. package/dist/swaps/IClaimableSwap.d.ts +49 -49
  134. package/dist/swaps/IClaimableSwap.js +15 -15
  135. package/dist/swaps/IClaimableSwapWrapper.d.ts +15 -15
  136. package/dist/swaps/IClaimableSwapWrapper.js +2 -2
  137. package/dist/swaps/IRefundableSwap.d.ts +43 -43
  138. package/dist/swaps/IRefundableSwap.js +14 -14
  139. package/dist/swaps/ISwap.d.ts +453 -453
  140. package/dist/swaps/ISwap.js +371 -371
  141. package/dist/swaps/ISwapWithGasDrop.d.ts +21 -21
  142. package/dist/swaps/ISwapWithGasDrop.js +12 -12
  143. package/dist/swaps/ISwapWrapper.d.ts +295 -295
  144. package/dist/swaps/ISwapWrapper.js +373 -373
  145. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.d.ts +98 -98
  146. package/dist/swaps/escrow_swaps/IEscrowSelfInitSwap.js +126 -126
  147. package/dist/swaps/escrow_swaps/IEscrowSwap.d.ts +139 -139
  148. package/dist/swaps/escrow_swaps/IEscrowSwap.js +172 -172
  149. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.d.ts +129 -129
  150. package/dist/swaps/escrow_swaps/IEscrowSwapWrapper.js +167 -167
  151. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.d.ts +107 -107
  152. package/dist/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.js +130 -130
  153. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.d.ts +162 -162
  154. package/dist/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.js +190 -190
  155. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.d.ts +64 -64
  156. package/dist/swaps/escrow_swaps/frombtc/IFromBTCWrapper.js +82 -82
  157. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.d.ts +547 -547
  158. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.js +1419 -1419
  159. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.d.ts +192 -192
  160. package/dist/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.js +432 -432
  161. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.d.ts +650 -650
  162. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.js +1577 -1577
  163. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.d.ts +237 -237
  164. package/dist/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.js +525 -525
  165. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.d.ts +491 -491
  166. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.js +1463 -1463
  167. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.d.ts +204 -204
  168. package/dist/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.js +406 -406
  169. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.d.ts +446 -446
  170. package/dist/swaps/escrow_swaps/tobtc/IToBTCSwap.js +1097 -1097
  171. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.d.ts +68 -68
  172. package/dist/swaps/escrow_swaps/tobtc/IToBTCWrapper.js +117 -117
  173. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.d.ts +127 -127
  174. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.js +256 -256
  175. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.d.ts +252 -252
  176. package/dist/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.js +535 -535
  177. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.d.ts +73 -73
  178. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.js +155 -155
  179. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.d.ts +134 -134
  180. package/dist/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.js +286 -286
  181. package/dist/swaps/spv_swaps/SpvFromBTCSwap.d.ts +694 -694
  182. package/dist/swaps/spv_swaps/SpvFromBTCSwap.js +1687 -1687
  183. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.d.ts +259 -259
  184. package/dist/swaps/spv_swaps/SpvFromBTCWrapper.js +947 -947
  185. package/dist/swaps/trusted/ln/LnForGasSwap.d.ts +302 -302
  186. package/dist/swaps/trusted/ln/LnForGasSwap.js +625 -625
  187. package/dist/swaps/trusted/ln/LnForGasWrapper.d.ts +40 -40
  188. package/dist/swaps/trusted/ln/LnForGasWrapper.js +82 -82
  189. package/dist/swaps/trusted/onchain/OnchainForGasSwap.d.ts +343 -343
  190. package/dist/swaps/trusted/onchain/OnchainForGasSwap.js +698 -698
  191. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.d.ts +71 -71
  192. package/dist/swaps/trusted/onchain/OnchainForGasWrapper.js +93 -93
  193. package/dist/types/AmountData.d.ts +10 -10
  194. package/dist/types/AmountData.js +2 -2
  195. package/dist/types/CustomPriceFunction.d.ts +11 -11
  196. package/dist/types/CustomPriceFunction.js +2 -2
  197. package/dist/types/PriceInfoType.d.ts +28 -28
  198. package/dist/types/PriceInfoType.js +57 -57
  199. package/dist/types/SwapExecutionAction.d.ts +195 -195
  200. package/dist/types/SwapExecutionAction.js +106 -106
  201. package/dist/types/SwapExecutionStep.d.ts +144 -144
  202. package/dist/types/SwapExecutionStep.js +87 -87
  203. package/dist/types/SwapStateInfo.d.ts +5 -5
  204. package/dist/types/SwapStateInfo.js +2 -2
  205. package/dist/types/SwapWithSigner.d.ts +17 -17
  206. package/dist/types/SwapWithSigner.js +43 -43
  207. package/dist/types/Token.d.ts +99 -99
  208. package/dist/types/Token.js +76 -76
  209. package/dist/types/TokenAmount.d.ts +75 -75
  210. package/dist/types/TokenAmount.js +85 -85
  211. package/dist/types/fees/Fee.d.ts +50 -50
  212. package/dist/types/fees/Fee.js +2 -2
  213. package/dist/types/fees/FeeBreakdown.d.ts +11 -11
  214. package/dist/types/fees/FeeBreakdown.js +2 -2
  215. package/dist/types/fees/PercentagePPM.d.ts +17 -17
  216. package/dist/types/fees/PercentagePPM.js +18 -18
  217. package/dist/types/lnurl/LNURLPay.d.ts +61 -61
  218. package/dist/types/lnurl/LNURLPay.js +31 -31
  219. package/dist/types/lnurl/LNURLWithdraw.d.ts +48 -48
  220. package/dist/types/lnurl/LNURLWithdraw.js +27 -27
  221. package/dist/types/wallets/LightningInvoiceCreateService.d.ts +24 -24
  222. package/dist/types/wallets/LightningInvoiceCreateService.js +15 -15
  223. package/dist/types/wallets/MinimalBitcoinWalletInterface.d.ts +23 -23
  224. package/dist/types/wallets/MinimalBitcoinWalletInterface.js +2 -2
  225. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.d.ts +9 -9
  226. package/dist/types/wallets/MinimalLightningNetworkWalletInterface.js +2 -2
  227. package/dist/utils/AutomaticClockDriftCorrection.d.ts +1 -1
  228. package/dist/utils/AutomaticClockDriftCorrection.js +70 -70
  229. package/dist/utils/BitcoinUtils.d.ts +18 -18
  230. package/dist/utils/BitcoinUtils.js +174 -174
  231. package/dist/utils/BitcoinWalletUtils.d.ts +7 -7
  232. package/dist/utils/BitcoinWalletUtils.js +14 -14
  233. package/dist/utils/Logger.d.ts +7 -7
  234. package/dist/utils/Logger.js +12 -12
  235. package/dist/utils/RetryUtils.d.ts +22 -22
  236. package/dist/utils/RetryUtils.js +67 -67
  237. package/dist/utils/SwapUtils.d.ts +88 -88
  238. package/dist/utils/SwapUtils.js +72 -72
  239. package/dist/utils/TimeoutUtils.d.ts +17 -17
  240. package/dist/utils/TimeoutUtils.js +55 -55
  241. package/dist/utils/TokenUtils.d.ts +19 -19
  242. package/dist/utils/TokenUtils.js +37 -37
  243. package/dist/utils/TypeUtils.d.ts +7 -7
  244. package/dist/utils/TypeUtils.js +2 -2
  245. package/dist/utils/Utils.d.ts +69 -69
  246. package/dist/utils/Utils.js +214 -214
  247. package/package.json +46 -46
  248. package/src/SmartChainAssets.ts +186 -186
  249. package/src/api/ApiEndpoints.ts +427 -427
  250. package/src/api/ApiParser.ts +138 -138
  251. package/src/api/ApiTypes.ts +229 -229
  252. package/src/api/SerializedAction.ts +97 -97
  253. package/src/api/SwapperApi.ts +545 -545
  254. package/src/api/index.ts +5 -5
  255. package/src/bitcoin/coinselect2/accumulative.ts +69 -69
  256. package/src/bitcoin/coinselect2/blackjack.ts +50 -50
  257. package/src/bitcoin/coinselect2/index.ts +93 -93
  258. package/src/bitcoin/coinselect2/utils.ts +236 -236
  259. package/src/bitcoin/wallet/BitcoinWallet.ts +439 -439
  260. package/src/bitcoin/wallet/IBitcoinWallet.ts +140 -140
  261. package/src/bitcoin/wallet/SingleAddressBitcoinWallet.ts +225 -225
  262. package/src/enums/FeeType.ts +15 -15
  263. package/src/enums/SwapAmountType.ts +16 -16
  264. package/src/enums/SwapDirection.ts +15 -15
  265. package/src/enums/SwapSide.ts +16 -16
  266. package/src/enums/SwapType.ts +75 -75
  267. package/src/errors/IntermediaryError.ts +28 -28
  268. package/src/errors/RequestError.ts +64 -64
  269. package/src/errors/UserError.ts +15 -15
  270. package/src/events/UnifiedSwapEventListener.ts +181 -181
  271. package/src/http/HttpUtils.ts +97 -97
  272. package/src/http/paramcoders/IParamReader.ts +9 -9
  273. package/src/http/paramcoders/ParamDecoder.ts +145 -145
  274. package/src/http/paramcoders/ParamEncoder.ts +40 -40
  275. package/src/http/paramcoders/SchemaVerifier.ts +153 -153
  276. package/src/http/paramcoders/client/ResponseParamDecoder.ts +57 -57
  277. package/src/http/paramcoders/client/StreamParamEncoder.ts +28 -28
  278. package/src/http/paramcoders/client/StreamingFetchPromise.ts +194 -194
  279. package/src/index.ts +141 -141
  280. package/src/intermediaries/Intermediary.ts +280 -280
  281. package/src/intermediaries/IntermediaryDiscovery.ts +548 -548
  282. package/src/intermediaries/apis/IntermediaryAPI.ts +1247 -1247
  283. package/src/intermediaries/auth/SignedKeyBasedAuth.ts +69 -69
  284. package/src/lnurl/LNURL.ts +402 -402
  285. package/src/prices/RedundantSwapPrice.ts +264 -264
  286. package/src/prices/SingleSwapPrice.ts +50 -50
  287. package/src/prices/SwapPriceWithChain.ts +194 -194
  288. package/src/prices/abstract/ICachedSwapPrice.ts +85 -85
  289. package/src/prices/abstract/IPriceProvider.ts +127 -127
  290. package/src/prices/abstract/ISwapPrice.ts +390 -390
  291. package/src/prices/providers/BinancePriceProvider.ts +48 -48
  292. package/src/prices/providers/CoinGeckoPriceProvider.ts +46 -46
  293. package/src/prices/providers/CoinPaprikaPriceProvider.ts +49 -49
  294. package/src/prices/providers/CustomPriceProvider.ts +40 -40
  295. package/src/prices/providers/KrakenPriceProvider.ts +83 -83
  296. package/src/prices/providers/OKXPriceProvider.ts +59 -59
  297. package/src/prices/providers/abstract/ExchangePriceProvider.ts +31 -31
  298. package/src/prices/providers/abstract/HttpPriceProvider.ts +14 -14
  299. package/src/storage/IUnifiedStorage.ts +136 -136
  300. package/src/storage/UnifiedSwapStorage.ts +175 -175
  301. package/src/storage-browser/IndexedDBUnifiedStorage.ts +350 -350
  302. package/src/storage-browser/LocalStorageManager.ts +106 -106
  303. package/src/swapper/Swapper.ts +2557 -2570
  304. package/src/swapper/SwapperFactory.ts +307 -307
  305. package/src/swapper/SwapperUtils.ts +610 -610
  306. package/src/swapper/SwapperWithChain.ts +707 -707
  307. package/src/swapper/SwapperWithSigner.ts +511 -511
  308. package/src/swaps/IAddressSwap.ts +30 -30
  309. package/src/swaps/IBTCWalletSwap.ts +92 -92
  310. package/src/swaps/IClaimableSwap.ts +65 -65
  311. package/src/swaps/IClaimableSwapWrapper.ts +17 -17
  312. package/src/swaps/IRefundableSwap.ts +58 -58
  313. package/src/swaps/ISwap.ts +775 -775
  314. package/src/swaps/ISwapWithGasDrop.ts +25 -25
  315. package/src/swaps/ISwapWrapper.ts +564 -564
  316. package/src/swaps/escrow_swaps/IEscrowSelfInitSwap.ts +217 -217
  317. package/src/swaps/escrow_swaps/IEscrowSwap.ts +271 -271
  318. package/src/swaps/escrow_swaps/IEscrowSwapWrapper.ts +284 -284
  319. package/src/swaps/escrow_swaps/frombtc/IFromBTCLNWrapper.ts +172 -172
  320. package/src/swaps/escrow_swaps/frombtc/IFromBTCSelfInitSwap.ts +300 -300
  321. package/src/swaps/escrow_swaps/frombtc/IFromBTCWrapper.ts +107 -107
  322. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNSwap.ts +1670 -1671
  323. package/src/swaps/escrow_swaps/frombtc/ln/FromBTCLNWrapper.ts +603 -603
  324. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoSwap.ts +1883 -1883
  325. package/src/swaps/escrow_swaps/frombtc/ln_auto/FromBTCLNAutoWrapper.ts +752 -752
  326. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCSwap.ts +1753 -1753
  327. package/src/swaps/escrow_swaps/frombtc/onchain/FromBTCWrapper.ts +612 -612
  328. package/src/swaps/escrow_swaps/tobtc/IToBTCSwap.ts +1327 -1327
  329. package/src/swaps/escrow_swaps/tobtc/IToBTCWrapper.ts +138 -138
  330. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNSwap.ts +304 -304
  331. package/src/swaps/escrow_swaps/tobtc/ln/ToBTCLNWrapper.ts +787 -787
  332. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCSwap.ts +206 -206
  333. package/src/swaps/escrow_swaps/tobtc/onchain/ToBTCWrapper.ts +403 -403
  334. package/src/swaps/spv_swaps/SpvFromBTCSwap.ts +2148 -2148
  335. package/src/swaps/spv_swaps/SpvFromBTCWrapper.ts +1238 -1238
  336. package/src/swaps/trusted/ln/LnForGasSwap.ts +753 -753
  337. package/src/swaps/trusted/ln/LnForGasWrapper.ts +90 -90
  338. package/src/swaps/trusted/onchain/OnchainForGasSwap.ts +843 -843
  339. package/src/swaps/trusted/onchain/OnchainForGasWrapper.ts +133 -133
  340. package/src/types/AmountData.ts +9 -9
  341. package/src/types/CustomPriceFunction.ts +11 -11
  342. package/src/types/PriceInfoType.ts +66 -66
  343. package/src/types/SwapExecutionAction.ts +323 -323
  344. package/src/types/SwapExecutionStep.ts +224 -224
  345. package/src/types/SwapStateInfo.ts +6 -6
  346. package/src/types/SwapWithSigner.ts +61 -61
  347. package/src/types/Token.ts +163 -163
  348. package/src/types/TokenAmount.ts +167 -167
  349. package/src/types/fees/Fee.ts +56 -56
  350. package/src/types/fees/FeeBreakdown.ts +11 -11
  351. package/src/types/fees/PercentagePPM.ts +26 -26
  352. package/src/types/lnurl/LNURLPay.ts +79 -79
  353. package/src/types/lnurl/LNURLWithdraw.ts +61 -61
  354. package/src/types/wallets/LightningInvoiceCreateService.ts +30 -30
  355. package/src/types/wallets/MinimalBitcoinWalletInterface.ts +21 -21
  356. package/src/types/wallets/MinimalLightningNetworkWalletInterface.ts +9 -9
  357. package/src/utils/AutomaticClockDriftCorrection.ts +71 -71
  358. package/src/utils/BitcoinUtils.ts +164 -164
  359. package/src/utils/BitcoinWalletUtils.ts +15 -15
  360. package/src/utils/Logger.ts +14 -14
  361. package/src/utils/RetryUtils.ts +78 -78
  362. package/src/utils/SwapUtils.ts +99 -99
  363. package/src/utils/TimeoutUtils.ts +49 -49
  364. package/src/utils/TokenUtils.ts +33 -33
  365. package/src/utils/TypeUtils.ts +8 -8
  366. package/src/utils/Utils.ts +221 -221
@@ -1,1247 +1,1247 @@
1
- import {RequestError} from "../../errors/RequestError";
2
- import {
3
- FieldTypeEnum, RequestSchema,
4
- RequestSchemaResult, RequestSchemaResultPromise,
5
- verifySchema
6
- } from "../../http/paramcoders/SchemaVerifier";
7
- import {RequestBody, 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
- /////////////////////////
333
- ///// Trusted from BTCLN
334
-
335
- export enum TrustedInvoiceStatusResponseCodes {
336
- EXPIRED=10001,
337
- PAID=10000,
338
- AWAIT_PAYMENT=10010,
339
- PENDING=10011,
340
- TX_SENT=10012
341
- }
342
-
343
- export type TrustedInvoiceStatusResponse = {
344
- code: TrustedInvoiceStatusResponseCodes.TX_SENT | TrustedInvoiceStatusResponseCodes.PAID,
345
- msg: string,
346
- data: {
347
- txId: string
348
- }
349
- } | {
350
- code: Exclude<TrustedInvoiceStatusResponseCodes, TrustedInvoiceStatusResponseCodes.TX_SENT | TrustedInvoiceStatusResponseCodes.PAID>,
351
- msg: string
352
- };
353
-
354
- export type TrustedFromBTCLNInit = {
355
- address: string,
356
- amount: bigint,
357
- token: string
358
- };
359
-
360
- const TrustedFromBTCLNResponseSchema = {
361
- pr: FieldTypeEnum.String,
362
- swapFee: FieldTypeEnum.BigInt,
363
- swapFeeSats: FieldTypeEnum.BigInt,
364
- total: FieldTypeEnum.BigInt
365
- } as const;
366
-
367
- export type TrustedFromBTCLNResponseType = RequestSchemaResult<typeof TrustedFromBTCLNResponseSchema>;
368
-
369
- /////////////////////////
370
- ///// Trusted from BTC
371
-
372
- export enum TrustedAddressStatusResponseCodes {
373
- EXPIRED=10001,
374
- PAID=10000,
375
- AWAIT_PAYMENT=10010,
376
- AWAIT_CONFIRMATION=10011,
377
- PENDING=10013,
378
- TX_SENT=10012,
379
- REFUNDED=10014,
380
- DOUBLE_SPENT=10015,
381
- REFUNDABLE=10016
382
- }
383
-
384
- export type TrustedAddressStatusResponse = {
385
- code: TrustedAddressStatusResponseCodes.TX_SENT | TrustedAddressStatusResponseCodes.PAID,
386
- msg: string,
387
- data: {
388
- adjustedAmount: string,
389
- adjustedTotal: string,
390
- adjustedFee?: string,
391
- adjustedFeeSats?: string,
392
- txId: string,
393
- scTxId: string
394
- }
395
- } | {
396
- code: TrustedAddressStatusResponseCodes.AWAIT_CONFIRMATION | TrustedAddressStatusResponseCodes.PENDING,
397
- msg: string,
398
- data: {
399
- adjustedAmount: string,
400
- adjustedTotal: string,
401
- adjustedFee?: string,
402
- adjustedFeeSats?: string,
403
- txId: string
404
- }
405
- } | {
406
- code: TrustedAddressStatusResponseCodes.REFUNDABLE,
407
- msg: string,
408
- data: {
409
- adjustedAmount: string
410
- }
411
- } | {
412
- code: TrustedAddressStatusResponseCodes.REFUNDED | TrustedAddressStatusResponseCodes.DOUBLE_SPENT,
413
- msg: string,
414
- data: {
415
- txId: string
416
- }
417
- } | {
418
- code: TrustedAddressStatusResponseCodes.AWAIT_PAYMENT | TrustedAddressStatusResponseCodes.EXPIRED,
419
- msg: string
420
- };
421
-
422
- export type TrustedFromBTCInit = {
423
- address: string,
424
- amount: bigint,
425
- token: string,
426
- refundAddress?: string
427
- };
428
-
429
- const TrustedFromBTCResponseSchema = {
430
- paymentHash: FieldTypeEnum.String,
431
- sequence: FieldTypeEnum.BigInt,
432
- btcAddress: FieldTypeEnum.String,
433
- amountSats: FieldTypeEnum.BigInt,
434
- swapFeeSats: FieldTypeEnum.BigInt,
435
- swapFee: FieldTypeEnum.BigInt,
436
- total: FieldTypeEnum.BigInt,
437
- intermediaryKey: FieldTypeEnum.String,
438
- recommendedFee: FieldTypeEnum.Number,
439
- expiresAt: FieldTypeEnum.Number
440
- } as const;
441
-
442
- export type TrustedFromBTCResponseType = RequestSchemaResult<typeof TrustedFromBTCResponseSchema>;
443
-
444
- export class IntermediaryAPI {
445
-
446
- requestHeaders?: (type: "GET" | "POST", url: string, body?: any) => Record<string, string>;
447
-
448
- constructor(requestHeaders?: (type: "GET" | "POST", url: string, body?: any) => Record<string, string>) {
449
- this.requestHeaders = requestHeaders;
450
- }
451
-
452
- httpGet<T>(url: string, timeout?: number, abortSignal?: AbortSignal, allowNon200: boolean = false): Promise<T> {
453
- const headers = this.requestHeaders==null ? {} : this.requestHeaders("GET", url);
454
- return httpGet(url, timeout, abortSignal, allowNon200, headers);
455
- }
456
-
457
- httpPost<T>(url: string, body: any, timeout?: number, abortSignal?: AbortSignal): Promise<T> {
458
- const headers = this.requestHeaders==null ? {} : this.requestHeaders("POST", url, body);
459
- return httpPost(url, body, timeout, abortSignal, headers);
460
- }
461
-
462
- streamingFetchPromise<T extends RequestSchema>(
463
- url: string,
464
- body: RequestBody,
465
- schema: T,
466
- timeout?: number,
467
- signal?: AbortSignal,
468
- streamRequest?: boolean
469
- ): Promise<RequestSchemaResultPromise<T>> {
470
- const headers = this.requestHeaders==null ? {} : this.requestHeaders("POST", url);
471
- return streamingFetchPromise(url, body, schema, timeout, signal, streamRequest, headers);
472
- }
473
-
474
- /**
475
- * Returns the information about a specific intermediary
476
- *
477
- * @param baseUrl Base URL of the intermediary
478
- * @param timeout Timeout in milliseconds for the HTTP request
479
- * @param abortSignal
480
- *
481
- * @throws {RequestError} If non-200 http response code is returned
482
- * @throws {Error} If the supplied nonce doesn't match the response
483
- */
484
- async getIntermediaryInfo(
485
- baseUrl: string,
486
- timeout?: number,
487
- abortSignal?: AbortSignal
488
- ): Promise<InfoHandlerResponse> {
489
- const nonce = randomBytes(32).toString("hex");
490
-
491
- const abortController = extendAbortController(abortSignal);
492
-
493
- //We don't know whether the node supports only POST or also has GET info support enabled
494
- // here we try both, and abort when the first one returns (which should be GET)
495
- const response = await Promise.any([
496
- this.httpGet<InfoHandlerResponse>(baseUrl+"/info?nonce="+nonce, timeout, abortController.signal),
497
- this.httpPost<InfoHandlerResponse>(baseUrl+"/info", {
498
- nonce,
499
- }, timeout, abortController.signal)
500
- ]);
501
- abortController.abort();
502
-
503
- const info = JSON.parse(response.envelope);
504
- if(nonce!==info.nonce) throw new Error("Invalid response - nonce");
505
-
506
- return response;
507
- }
508
-
509
- /**
510
- * Returns the information about an outcome of the To BTC swap
511
- *
512
- * @param url URL of the intermediary
513
- * @param paymentHash Payment hash of the swap
514
- * @param sequence Swap's sequence number
515
- * @param timeout Timeout in milliseconds for the HTTP request
516
- * @param abortSignal
517
- *
518
- * @throws {RequestError} If non-200 http response code is returned
519
- */
520
- async getRefundAuthorization(
521
- url: string,
522
- paymentHash: string,
523
- sequence: bigint,
524
- timeout?: number,
525
- abortSignal?: AbortSignal
526
- ): Promise<RefundAuthorizationResponse> {
527
- return tryWithRetries(() => this.httpGet<RefundAuthorizationResponse>(
528
- url + "/getRefundAuthorization"+
529
- "?paymentHash=" + encodeURIComponent(paymentHash) +
530
- "&sequence=" + encodeURIComponent(sequence.toString(10)),
531
- timeout,
532
- abortSignal
533
- ), undefined, RequestError, abortSignal);
534
- }
535
-
536
- /**
537
- * Returns the information about the payment of the From BTCLN swaps
538
- *
539
- * @param url URL of the intermediary
540
- * @param paymentHash Payment hash of the swap
541
- * @param timeout Timeout in milliseconds for the HTTP request
542
- * @param abortSignal
543
- *
544
- * @throws {RequestError} If non-200 http response code is returned
545
- */
546
- async getPaymentAuthorization(
547
- url: string,
548
- paymentHash: string,
549
- timeout?: number,
550
- abortSignal?: AbortSignal
551
- ): Promise<PaymentAuthorizationResponse> {
552
- return tryWithRetries(() => this.httpGet<PaymentAuthorizationResponse>(
553
- url+"/getInvoicePaymentAuth"+
554
- "?paymentHash="+encodeURIComponent(paymentHash),
555
- timeout,
556
- abortSignal
557
- ), undefined, RequestError, abortSignal);
558
- }
559
-
560
- /**
561
- * Returns the status of the payment of the From BTCLN swaps
562
- *
563
- * @param url URL of the intermediary
564
- * @param paymentHash Payment hash of the swap
565
- * @param timeout Timeout in milliseconds for the HTTP request
566
- * @param abortSignal
567
- *
568
- * @throws {RequestError} If non-200 http response code is returned
569
- */
570
- async getInvoiceStatus(
571
- url: string,
572
- paymentHash: string,
573
- timeout?: number,
574
- abortSignal?: AbortSignal
575
- ): Promise<InvoiceStatusResponse> {
576
- return tryWithRetries(() => this.httpGet<InvoiceStatusResponse>(
577
- url+"/getInvoiceStatus"+
578
- "?paymentHash="+encodeURIComponent(paymentHash),
579
- timeout,
580
- abortSignal
581
- ), undefined, RequestError, abortSignal);
582
- }
583
-
584
- /**
585
- * Initiate To BTC swap with an intermediary
586
- *
587
- * @param chainIdentifier
588
- * @param baseUrl Base URL of the intermediary
589
- * @param init Swap initialization parameters
590
- * @param timeout Timeout in milliseconds for the HTTP request
591
- * @param abortSignal
592
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
593
- *
594
- * @throws {RequestError} If non-200 http response code is returned
595
- */
596
- initToBTC(
597
- chainIdentifier: string,
598
- baseUrl: string,
599
- init: ToBTCInit,
600
- timeout?: number,
601
- abortSignal?: AbortSignal,
602
- streamRequest?: boolean
603
- ): {
604
- signDataPrefetch: Promise<any>,
605
- response: Promise<ToBTCResponseType>
606
- } {
607
- const responseBodyPromise = this.streamingFetchPromise(baseUrl+"/tobtc/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
608
- ...init.additionalParams,
609
- address: init.btcAddress,
610
- amount: init.amount.toString(10),
611
- exactIn: init.exactIn,
612
- confirmationTarget: init.confirmationTarget,
613
- confirmations: init.confirmations,
614
- nonce: init.nonce.toString(10),
615
- token: init.token,
616
- offerer: init.offerer,
617
- feeRate: init.feeRate
618
- }, {
619
- code: FieldTypeEnum.Number,
620
- msg: FieldTypeEnum.String,
621
- data: FieldTypeEnum.AnyOptional,
622
- signDataPrefetch: FieldTypeEnum.AnyOptional
623
- }, timeout, abortSignal, streamRequest);
624
-
625
- return {
626
- signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
627
- response: responseBodyPromise.then((responseBody) => Promise.all([
628
- responseBody.code,
629
- responseBody.msg,
630
- responseBody.data,
631
- ])).then(([code, msg, data]) => {
632
- if(code!==20000) {
633
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
634
- }
635
- const result = verifySchema(data, ToBTCResponseSchema);
636
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
637
- return result;
638
- })
639
- };
640
- }
641
-
642
- /**
643
- * Initiate From BTC swap with an intermediary
644
- *
645
- * @param chainIdentifier
646
- * @param baseUrl Base URL of the intermediary
647
- * @param depositToken
648
- * @param init Swap initialization parameters
649
- * @param timeout Timeout in milliseconds for the HTTP request
650
- * @param abortSignal
651
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
652
- *
653
- * @throws {RequestError} If non-200 http response code is returned
654
- */
655
- initFromBTC(
656
- chainIdentifier: string,
657
- baseUrl: string,
658
- depositToken: string,
659
- init: FromBTCInit,
660
- timeout?: number,
661
- abortSignal?: AbortSignal,
662
- streamRequest?: boolean
663
- ): {
664
- signDataPrefetch: Promise<any>,
665
- response: Promise<FromBTCResponseType>
666
- } {
667
- const responseBodyPromise = this.streamingFetchPromise(
668
- baseUrl+"/frombtc/getAddress?chain="+encodeURIComponent(chainIdentifier)+"&depositToken="+encodeURIComponent(depositToken),
669
- {
670
- ...init.additionalParams,
671
- address: init.claimer,
672
- amount: init.amount.toString(10),
673
- token: init.token,
674
-
675
- exactOut: init.exactOut,
676
- sequence: init.sequence.toString(10),
677
-
678
- claimerBounty: init.claimerBounty.then(claimerBounty => {
679
- return {
680
- feePerBlock: claimerBounty.feePerBlock.toString(10),
681
- safetyFactor: claimerBounty.safetyFactor.toString(10),
682
- startTimestamp: claimerBounty.startTimestamp.toString(10),
683
- addBlock: claimerBounty.addBlock.toString(10),
684
- addFee: claimerBounty.addFee.toString(10)
685
- }
686
- }),
687
- feeRate: init.feeRate
688
- },
689
- {
690
- code: FieldTypeEnum.Number,
691
- msg: FieldTypeEnum.String,
692
- data: FieldTypeEnum.AnyOptional,
693
- signDataPrefetch: FieldTypeEnum.AnyOptional
694
- },
695
- timeout, abortSignal, streamRequest
696
- );
697
-
698
- return {
699
- signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
700
- response: responseBodyPromise.then((responseBody) => Promise.all([
701
- responseBody.code,
702
- responseBody.msg,
703
- responseBody.data,
704
- ])).then(([code, msg, data]) => {
705
- if(code!==20000) {
706
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
707
- }
708
- const result = verifySchema(data, FromBTCResponseSchema);
709
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
710
- return result;
711
- })
712
- };
713
- }
714
-
715
- /**
716
- * Initiate From BTCLN swap with an intermediary
717
- *
718
- * @param chainIdentifier
719
- * @param baseUrl Base URL of the intermediary
720
- * @param depositToken
721
- * @param init Swap initialization parameters
722
- * @param timeout Timeout in milliseconds for the HTTP request
723
- * @param abortSignal
724
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
725
- *
726
- * @throws {RequestError} If non-200 http response code is returned
727
- */
728
- initFromBTCLN(
729
- chainIdentifier: string,
730
- baseUrl: string,
731
- depositToken: string,
732
- init: FromBTCLNInit,
733
- timeout?: number,
734
- abortSignal?: AbortSignal,
735
- streamRequest?: boolean
736
- ): {
737
- lnPublicKey: Promise<string | null>,
738
- response: Promise<FromBTCLNResponseType>
739
- } {
740
- const responseBodyPromise = this.streamingFetchPromise(
741
- baseUrl+"/frombtcln/createInvoice?chain="+encodeURIComponent(chainIdentifier)+"&depositToken="+encodeURIComponent(depositToken),
742
- {
743
- ...init.additionalParams,
744
- paymentHash: init.paymentHash.toString("hex"),
745
- amount: init.amount.toString(),
746
- address: init.claimer,
747
- token: init.token,
748
- description: init.description ?? null,
749
- descriptionHash: init.descriptionHash==null ? null : init.descriptionHash.toString("hex"),
750
- exactOut: init.exactOut,
751
- feeRate: init.feeRate
752
- },
753
- {
754
- code: FieldTypeEnum.Number,
755
- msg: FieldTypeEnum.String,
756
- data: FieldTypeEnum.AnyOptional,
757
- lnPublicKey: FieldTypeEnum.StringOptional
758
- },
759
- timeout, abortSignal, streamRequest
760
- );
761
-
762
- return {
763
- lnPublicKey: responseBodyPromise.then(responseBody => responseBody.lnPublicKey),
764
- response: responseBodyPromise.then((responseBody) => Promise.all([
765
- responseBody.code,
766
- responseBody.msg,
767
- responseBody.data,
768
- ])).then(([code, msg, data]) => {
769
- if(code!==20000) {
770
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
771
- }
772
- const result = verifySchema(data, FromBTCLNResponseSchema);
773
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
774
- return result;
775
- })
776
- };
777
- }
778
-
779
- /**
780
- * Initiate From BTCLN swap with auto-initilization by an intermediary
781
- *
782
- * @param chainIdentifier
783
- * @param baseUrl Base URL of the intermediary
784
- * @param init Swap initialization parameters
785
- * @param timeout Timeout in milliseconds for the HTTP request
786
- * @param abortSignal
787
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
788
- *
789
- * @throws {RequestError} If non-200 http response code is returned
790
- */
791
- initFromBTCLNAuto(
792
- chainIdentifier: string,
793
- baseUrl: string,
794
- init: FromBTCLNAutoInit,
795
- timeout?: number,
796
- abortSignal?: AbortSignal,
797
- streamRequest?: boolean
798
- ): {
799
- lnPublicKey: Promise<string | null>,
800
- response: Promise<FromBTCLNAutoResponseType>
801
- } {
802
- const responseBodyPromise = this.streamingFetchPromise(
803
- baseUrl+"/frombtcln_auto/createInvoice?chain="+encodeURIComponent(chainIdentifier),
804
- {
805
- ...init.additionalParams,
806
- paymentHash: init.paymentHash.toString("hex"),
807
- amount: init.amount.toString(),
808
- address: init.claimer,
809
- token: init.token,
810
- description: init.description ?? null,
811
- descriptionHash: init.descriptionHash==null ? null : init.descriptionHash.toString("hex"),
812
- exactOut: init.exactOut,
813
- gasToken: init.gasToken,
814
- gasAmount: init.gasAmount?.toString(10) ?? "0",
815
- claimerBounty: init.claimerBounty?.then(val => val.toString(10)) ?? "0"
816
- },
817
- {
818
- code: FieldTypeEnum.Number,
819
- msg: FieldTypeEnum.String,
820
- data: FieldTypeEnum.AnyOptional,
821
- lnPublicKey: FieldTypeEnum.StringOptional
822
- },
823
- timeout, abortSignal, streamRequest
824
- );
825
-
826
- return {
827
- lnPublicKey: responseBodyPromise.then(responseBody => responseBody.lnPublicKey),
828
- response: responseBodyPromise.then((responseBody) => Promise.all([
829
- responseBody.code,
830
- responseBody.msg,
831
- responseBody.data,
832
- ])).then(([code, msg, data]) => {
833
- if(code!==20000) {
834
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
835
- }
836
- const result = verifySchema(data, FromBTCLNAutoResponseSchema);
837
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
838
- return result;
839
- })
840
- };
841
- }
842
-
843
- /**
844
- * Initiate To BTCLN swap with an intermediary
845
- *
846
- * @param chainIdentifier
847
- * @param baseUrl Base URL of the intermediary
848
- * @param init Swap initialization parameters
849
- * @param timeout Timeout in milliseconds for the HTTP request
850
- * @param abortSignal
851
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
852
- *
853
- * @throws {RequestError} If non-200 http response code is returned
854
- */
855
- initToBTCLN(
856
- chainIdentifier: string,
857
- baseUrl: string,
858
- init: ToBTCLNInit,
859
- timeout?: number,
860
- abortSignal?: AbortSignal,
861
- streamRequest?: boolean
862
- ): {
863
- signDataPrefetch: Promise<any>,
864
- response: Promise<ToBTCLNResponseType>
865
- } {
866
- const responseBodyPromise = this.streamingFetchPromise(baseUrl+"/tobtcln/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
867
- exactIn: false,
868
- ...init.additionalParams,
869
- pr: init.pr,
870
- maxFee: init.maxFee.toString(10),
871
- expiryTimestamp: init.expiryTimestamp.toString(10),
872
- token: init.token,
873
- offerer: init.offerer,
874
- feeRate: init.feeRate,
875
- amount: null
876
- }, {
877
- code: FieldTypeEnum.Number,
878
- msg: FieldTypeEnum.String,
879
- data: FieldTypeEnum.AnyOptional,
880
- signDataPrefetch: FieldTypeEnum.AnyOptional
881
- }, timeout, abortSignal, streamRequest);
882
-
883
- return {
884
- signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
885
- response: responseBodyPromise.then((responseBody) => Promise.all([
886
- responseBody.code,
887
- responseBody.msg,
888
- responseBody.data,
889
- ])).then(([code, msg, data]) => {
890
- if(code!==20000) {
891
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
892
- }
893
- const result = verifySchema(data, ToBTCLNResponseSchema);
894
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
895
- return result;
896
- })
897
- };
898
- }
899
-
900
- /**
901
- * Initiate To BTCLN exact in swap with an intermediary
902
- *
903
- * @param baseUrl Base URL of the intermediary
904
- * @param init Swap initialization parameters
905
- * @param timeout Timeout in milliseconds for the HTTP request
906
- * @param abortSignal
907
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
908
- *
909
- * @throws {RequestError} If non-200 http response code is returned
910
- */
911
- async initToBTCLNExactIn(
912
- baseUrl: string,
913
- init: ToBTCLNInitExactIn,
914
- timeout?: number,
915
- abortSignal?: AbortSignal,
916
- streamRequest?: boolean
917
- ): Promise<ToBTCLNResponseType> {
918
- const responseBody = await this.streamingFetchPromise(baseUrl+"/tobtcln/payInvoiceExactIn", {
919
- ...init.additionalParams,
920
- pr: init.pr,
921
- reqId: init.reqId,
922
- feeRate: init.feeRate
923
- }, {
924
- code: FieldTypeEnum.Number,
925
- msg: FieldTypeEnum.String,
926
- data: FieldTypeEnum.AnyOptional
927
- }, timeout, abortSignal, streamRequest);
928
-
929
- const [code, msg, data] = await Promise.all([
930
- responseBody.code,
931
- responseBody.msg,
932
- responseBody.data,
933
- ])
934
-
935
- if(code!==20000) throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
936
- const result = verifySchema(data, ToBTCLNResponseSchema);
937
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
938
- return result;
939
- }
940
-
941
- /**
942
- * Prepare To BTCLN exact in swap with an intermediary
943
- *
944
- * @param chainIdentifier
945
- * @param baseUrl Base URL of the intermediary
946
- * @param init Swap initialization parameters
947
- * @param timeout Timeout in milliseconds for the HTTP request
948
- * @param abortSignal
949
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
950
- *
951
- * @throws {RequestError} If non-200 http response code is returned
952
- */
953
- prepareToBTCLNExactIn(
954
- chainIdentifier: string,
955
- baseUrl: string,
956
- init: ToBTCLNPrepareExactIn,
957
- timeout?: number,
958
- abortSignal?: AbortSignal,
959
- streamRequest?: boolean
960
- ): {
961
- signDataPrefetch: Promise<any>,
962
- response: Promise<ToBTCLNPrepareExactInResponseType>
963
- } {
964
- const responseBodyPromise = this.streamingFetchPromise(baseUrl+"/tobtcln/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
965
- exactIn: true,
966
- ...init.additionalParams,
967
- pr: init.pr,
968
- maxFee: init.maxFee.toString(10),
969
- expiryTimestamp: init.expiryTimestamp.toString(10),
970
- token: init.token,
971
- offerer: init.offerer,
972
- amount: init.amount.toString(10)
973
- }, {
974
- code: FieldTypeEnum.Number,
975
- msg: FieldTypeEnum.String,
976
- data: FieldTypeEnum.AnyOptional,
977
- signDataPrefetch: FieldTypeEnum.AnyOptional
978
- }, timeout, abortSignal, streamRequest);
979
-
980
- return {
981
- signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
982
- response: responseBodyPromise.then((responseBody) => Promise.all([
983
- responseBody.code,
984
- responseBody.msg,
985
- responseBody.data,
986
- ])).then(([code, msg, data]) => {
987
- if(code!==20000) {
988
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
989
- }
990
- const result = verifySchema(data, ToBTCLNPrepareExactInSchema);
991
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
992
- return result;
993
- })
994
- };
995
- }
996
-
997
- /**
998
- * Prepare From BTC swap via new spv vault swaps with an intermediary
999
- *
1000
- * @param chainIdentifier
1001
- * @param baseUrl Base URL of the intermediary
1002
- * @param init Swap initialization parameters
1003
- * @param timeout Timeout in milliseconds for the HTTP request
1004
- * @param abortSignal
1005
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
1006
- *
1007
- * @throws {RequestError} If non-200 http response code is returned
1008
- */
1009
- prepareSpvFromBTC(
1010
- chainIdentifier: string,
1011
- baseUrl: string,
1012
- init: SpvFromBTCPrepare,
1013
- timeout?: number,
1014
- abortSignal?: AbortSignal,
1015
- streamRequest?: boolean
1016
- ): Promise<SpvFromBTCPrepareResponseType> {
1017
- //We need to make sure we only send the amount parameter after the amountUtxos and amountFeeRate resolve
1018
- // this is needed, because in the LP code to maintain backwards compatibility the amountUtxos and amountFeeRate
1019
- // params are checked immediately after the amount param (and other params) are received, if amount were sent
1020
- // first without the amountUtxos or amountFeeRate populated these fields would've been skipped altogether
1021
- const amountPromise = (async () => {
1022
- if(init.amountUtxos!=null) await init.amountUtxos;
1023
- if(init.amountFeeRate!=null) await init.amountFeeRate;
1024
- const amount = await init.amount;
1025
- return amount.toString(10);
1026
- })();
1027
- const responseBodyPromise = this.streamingFetchPromise(baseUrl+"/frombtc_spv/getQuote?chain="+encodeURIComponent(chainIdentifier), {
1028
- exactOut: init.exactOut,
1029
- ...init.additionalParams,
1030
- address: init.address,
1031
- amount: amountPromise,
1032
- token: init.token,
1033
- gasAmount: init.gasAmount.toString(10),
1034
- gasToken: init.gasToken,
1035
- frontingFeeRate: init.frontingFeeRate.toString(10),
1036
- callerFeeRate: init.callerFeeRate.then(val => val.toString(10)),
1037
- stickyAddress: init.stickyAddress,
1038
- amountUtxos: init.amountUtxos,
1039
- amountFeeRate: init.amountFeeRate
1040
- }, {
1041
- code: FieldTypeEnum.Number,
1042
- msg: FieldTypeEnum.String,
1043
- data: FieldTypeEnum.AnyOptional
1044
- }, timeout, abortSignal, streamRequest);
1045
-
1046
- return responseBodyPromise.then((responseBody) => Promise.all([
1047
- responseBody.code,
1048
- responseBody.msg,
1049
- responseBody.data,
1050
- ])).then(([code, msg, data]) => {
1051
- if(code!==20000) {
1052
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
1053
- }
1054
- const result = verifySchema(data, SpvFromBTCPrepareResponseSchema);
1055
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
1056
- return result;
1057
- });
1058
- }
1059
-
1060
- /**
1061
- * Prepare From BTC swap via new spv vault swaps with an intermediary
1062
- *
1063
- * @param chainIdentifier
1064
- * @param url
1065
- * @param init Swap initialization parameters
1066
- * @param timeout Timeout in milliseconds for the HTTP request
1067
- * @param abortSignal
1068
- * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
1069
- *
1070
- * @throws {RequestError} If non-200 http response code is returned
1071
- */
1072
- initSpvFromBTC(
1073
- chainIdentifier: string,
1074
- url: string,
1075
- init: SpvFromBTCInit,
1076
- timeout?: number,
1077
- abortSignal?: AbortSignal,
1078
- streamRequest?: boolean
1079
- ): Promise<SpvFromBTCInitResponseType> {
1080
- const responseBodyPromise = this.streamingFetchPromise(url+"/postQuote?chain="+encodeURIComponent(chainIdentifier), {
1081
- quoteId: init.quoteId,
1082
- psbtHex: init.psbtHex
1083
- }, {
1084
- code: FieldTypeEnum.Number,
1085
- msg: FieldTypeEnum.String,
1086
- data: FieldTypeEnum.AnyOptional
1087
- }, timeout, abortSignal, streamRequest);
1088
-
1089
- return responseBodyPromise.then((responseBody) => Promise.all([
1090
- responseBody.code,
1091
- responseBody.msg,
1092
- responseBody.data,
1093
- ])).then(([code, msg, data]) => {
1094
- if(code!==20000) {
1095
- throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
1096
- }
1097
- const result = verifySchema(data, SpvFromBTCInitResponseSchema);
1098
- if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
1099
- return result;
1100
- });
1101
- }
1102
-
1103
-
1104
- /**
1105
- * Fetches the invoice status from the intermediary node
1106
- *
1107
- * @param url Url of the trusted intermediary
1108
- * @param paymentHash Payment hash of the lightning invoice
1109
- * @param timeout Timeout in milliseconds
1110
- * @param abortSignal
1111
- * @throws {RequestError} if non-200 http response is returned
1112
- */
1113
- async getTrustedInvoiceStatus(
1114
- url: string,
1115
- paymentHash: string,
1116
- timeout?: number,
1117
- abortSignal?: AbortSignal
1118
- ): Promise<TrustedInvoiceStatusResponse> {
1119
- return tryWithRetries(() => this.httpGet<TrustedInvoiceStatusResponse>(
1120
- url+"/getInvoiceStatus?paymentHash="+encodeURIComponent(paymentHash),
1121
- timeout, abortSignal
1122
- ), undefined, RequestError, abortSignal);
1123
- }
1124
-
1125
- /**
1126
- * Initiate a trusted swap from BTCLN to SC native currency, retries!
1127
- *
1128
- * @param chainIdentifier
1129
- * @param baseUrl Base url of the trusted swap intermediary
1130
- * @param init Initialization parameters
1131
- * @param timeout Timeout in milliseconds for the request
1132
- * @param abortSignal
1133
- * @throws {RequestError} If the response is non-200
1134
- */
1135
- async initTrustedFromBTCLN(
1136
- chainIdentifier: string,
1137
- baseUrl: string,
1138
- init: TrustedFromBTCLNInit,
1139
- timeout?: number,
1140
- abortSignal?: AbortSignal
1141
- ): Promise<TrustedFromBTCLNResponseType> {
1142
- const resp = await tryWithRetries(
1143
- () => this.httpGet<{code: number, msg: string, data?: any}>(
1144
- baseUrl+"/lnforgas/createInvoice" +
1145
- "?address="+encodeURIComponent(init.address) +
1146
- "&amount="+encodeURIComponent(init.amount.toString(10))+
1147
- "&chain="+encodeURIComponent(chainIdentifier)+
1148
- "&token="+encodeURIComponent(init.token),
1149
- timeout,
1150
- abortSignal
1151
- ), undefined, RequestError, abortSignal
1152
- );
1153
-
1154
- if(resp.code!==10000) throw RequestError.parse(JSON.stringify(resp), 400);
1155
- const res = verifySchema(resp.data, TrustedFromBTCLNResponseSchema);
1156
- if(res==null) throw new Error("Invalid response returned from LP");
1157
- return res;
1158
- }
1159
-
1160
- /**
1161
- * Fetches the address status from the intermediary node
1162
- *
1163
- * @param url Url of the trusted intermediary
1164
- * @param paymentHash Payment hash of the swap
1165
- * @param sequence Sequence number of the swap
1166
- * @param timeout Timeout in milliseconds
1167
- * @param abortSignal
1168
- * @throws {RequestError} if non-200 http response is returned
1169
- */
1170
- async getTrustedAddressStatus(
1171
- url: string,
1172
- paymentHash: string,
1173
- sequence: bigint,
1174
- timeout?: number,
1175
- abortSignal?: AbortSignal
1176
- ): Promise<TrustedAddressStatusResponse> {
1177
- return tryWithRetries(() => this.httpGet<TrustedAddressStatusResponse>(
1178
- url+"/getAddressStatus?paymentHash="+encodeURIComponent(paymentHash)+"&sequence="+encodeURIComponent(sequence.toString(10)),
1179
- timeout, abortSignal
1180
- ), undefined, RequestError, abortSignal);
1181
- }
1182
-
1183
- /**
1184
- * Sets the refund address for an on-chain gas swap
1185
- *
1186
- * @param url Url of the trusted intermediary
1187
- * @param paymentHash Payment hash of the swap
1188
- * @param sequence Sequence number of the swap
1189
- * @param refundAddress Refund address to set for the swap
1190
- * @param timeout Timeout in milliseconds
1191
- * @param abortSignal
1192
- * @throws {RequestError} if non-200 http response is returned
1193
- */
1194
- async setTrustedRefundAddress(
1195
- url: string,
1196
- paymentHash: string,
1197
- sequence: bigint,
1198
- refundAddress: string,
1199
- timeout?: number,
1200
- abortSignal?: AbortSignal
1201
- ): Promise<void> {
1202
- return tryWithRetries(() => this.httpGet<void>(
1203
- url+"/setRefundAddress" +
1204
- "?paymentHash="+encodeURIComponent(paymentHash)+
1205
- "&sequence="+encodeURIComponent(sequence.toString(10))+
1206
- "&refundAddress="+encodeURIComponent(refundAddress),
1207
- timeout, abortSignal
1208
- ), undefined, RequestError, abortSignal);
1209
- }
1210
-
1211
- /**
1212
- * Initiate a trusted swap from BTC to SC native currency, retries!
1213
- *
1214
- * @param chainIdentifier
1215
- * @param baseUrl Base url of the trusted swap intermediary
1216
- * @param init Initialization parameters
1217
- * @param timeout Timeout in milliseconds for the request
1218
- * @param abortSignal
1219
- * @throws {RequestError} If the response is non-200
1220
- */
1221
- async initTrustedFromBTC(
1222
- chainIdentifier: string,
1223
- baseUrl: string,
1224
- init: TrustedFromBTCInit,
1225
- timeout?: number,
1226
- abortSignal?: AbortSignal
1227
- ): Promise<TrustedFromBTCResponseType> {
1228
- const resp = await tryWithRetries(
1229
- () => this.httpGet<{code: number, msg: string, data?: any}>(
1230
- baseUrl+"/frombtc_trusted/getAddress?chain="+encodeURIComponent(chainIdentifier)+
1231
- "&address="+encodeURIComponent(init.address)+
1232
- "&amount="+encodeURIComponent(init.amount.toString(10))+
1233
- (init.refundAddress==null ? "" : "&refundAddress="+encodeURIComponent(init.refundAddress))+
1234
- "&exactIn=true"+
1235
- "&token="+encodeURIComponent(init.token),
1236
- timeout,
1237
- abortSignal
1238
- ), undefined, RequestError, abortSignal
1239
- );
1240
-
1241
- if(resp.code!==10000) throw RequestError.parse(JSON.stringify(resp), 400);
1242
- const res = verifySchema(resp.data, TrustedFromBTCResponseSchema);
1243
- if(res==null) throw new Error("Invalid response returned from LP");
1244
- return res;
1245
- }
1246
-
1247
- }
1
+ import {RequestError} from "../../errors/RequestError";
2
+ import {
3
+ FieldTypeEnum, RequestSchema,
4
+ RequestSchemaResult, RequestSchemaResultPromise,
5
+ verifySchema
6
+ } from "../../http/paramcoders/SchemaVerifier";
7
+ import {RequestBody, 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
+ /////////////////////////
333
+ ///// Trusted from BTCLN
334
+
335
+ export enum TrustedInvoiceStatusResponseCodes {
336
+ EXPIRED=10001,
337
+ PAID=10000,
338
+ AWAIT_PAYMENT=10010,
339
+ PENDING=10011,
340
+ TX_SENT=10012
341
+ }
342
+
343
+ export type TrustedInvoiceStatusResponse = {
344
+ code: TrustedInvoiceStatusResponseCodes.TX_SENT | TrustedInvoiceStatusResponseCodes.PAID,
345
+ msg: string,
346
+ data: {
347
+ txId: string
348
+ }
349
+ } | {
350
+ code: Exclude<TrustedInvoiceStatusResponseCodes, TrustedInvoiceStatusResponseCodes.TX_SENT | TrustedInvoiceStatusResponseCodes.PAID>,
351
+ msg: string
352
+ };
353
+
354
+ export type TrustedFromBTCLNInit = {
355
+ address: string,
356
+ amount: bigint,
357
+ token: string
358
+ };
359
+
360
+ const TrustedFromBTCLNResponseSchema = {
361
+ pr: FieldTypeEnum.String,
362
+ swapFee: FieldTypeEnum.BigInt,
363
+ swapFeeSats: FieldTypeEnum.BigInt,
364
+ total: FieldTypeEnum.BigInt
365
+ } as const;
366
+
367
+ export type TrustedFromBTCLNResponseType = RequestSchemaResult<typeof TrustedFromBTCLNResponseSchema>;
368
+
369
+ /////////////////////////
370
+ ///// Trusted from BTC
371
+
372
+ export enum TrustedAddressStatusResponseCodes {
373
+ EXPIRED=10001,
374
+ PAID=10000,
375
+ AWAIT_PAYMENT=10010,
376
+ AWAIT_CONFIRMATION=10011,
377
+ PENDING=10013,
378
+ TX_SENT=10012,
379
+ REFUNDED=10014,
380
+ DOUBLE_SPENT=10015,
381
+ REFUNDABLE=10016
382
+ }
383
+
384
+ export type TrustedAddressStatusResponse = {
385
+ code: TrustedAddressStatusResponseCodes.TX_SENT | TrustedAddressStatusResponseCodes.PAID,
386
+ msg: string,
387
+ data: {
388
+ adjustedAmount: string,
389
+ adjustedTotal: string,
390
+ adjustedFee?: string,
391
+ adjustedFeeSats?: string,
392
+ txId: string,
393
+ scTxId: string
394
+ }
395
+ } | {
396
+ code: TrustedAddressStatusResponseCodes.AWAIT_CONFIRMATION | TrustedAddressStatusResponseCodes.PENDING,
397
+ msg: string,
398
+ data: {
399
+ adjustedAmount: string,
400
+ adjustedTotal: string,
401
+ adjustedFee?: string,
402
+ adjustedFeeSats?: string,
403
+ txId: string
404
+ }
405
+ } | {
406
+ code: TrustedAddressStatusResponseCodes.REFUNDABLE,
407
+ msg: string,
408
+ data: {
409
+ adjustedAmount: string
410
+ }
411
+ } | {
412
+ code: TrustedAddressStatusResponseCodes.REFUNDED | TrustedAddressStatusResponseCodes.DOUBLE_SPENT,
413
+ msg: string,
414
+ data: {
415
+ txId: string
416
+ }
417
+ } | {
418
+ code: TrustedAddressStatusResponseCodes.AWAIT_PAYMENT | TrustedAddressStatusResponseCodes.EXPIRED,
419
+ msg: string
420
+ };
421
+
422
+ export type TrustedFromBTCInit = {
423
+ address: string,
424
+ amount: bigint,
425
+ token: string,
426
+ refundAddress?: string
427
+ };
428
+
429
+ const TrustedFromBTCResponseSchema = {
430
+ paymentHash: FieldTypeEnum.String,
431
+ sequence: FieldTypeEnum.BigInt,
432
+ btcAddress: FieldTypeEnum.String,
433
+ amountSats: FieldTypeEnum.BigInt,
434
+ swapFeeSats: FieldTypeEnum.BigInt,
435
+ swapFee: FieldTypeEnum.BigInt,
436
+ total: FieldTypeEnum.BigInt,
437
+ intermediaryKey: FieldTypeEnum.String,
438
+ recommendedFee: FieldTypeEnum.Number,
439
+ expiresAt: FieldTypeEnum.Number
440
+ } as const;
441
+
442
+ export type TrustedFromBTCResponseType = RequestSchemaResult<typeof TrustedFromBTCResponseSchema>;
443
+
444
+ export class IntermediaryAPI {
445
+
446
+ requestHeaders?: (type: "GET" | "POST", url: string, body?: any) => Record<string, string>;
447
+
448
+ constructor(requestHeaders?: (type: "GET" | "POST", url: string, body?: any) => Record<string, string>) {
449
+ this.requestHeaders = requestHeaders;
450
+ }
451
+
452
+ httpGet<T>(url: string, timeout?: number, abortSignal?: AbortSignal, allowNon200: boolean = false): Promise<T> {
453
+ const headers = this.requestHeaders==null ? {} : this.requestHeaders("GET", url);
454
+ return httpGet(url, timeout, abortSignal, allowNon200, headers);
455
+ }
456
+
457
+ httpPost<T>(url: string, body: any, timeout?: number, abortSignal?: AbortSignal): Promise<T> {
458
+ const headers = this.requestHeaders==null ? {} : this.requestHeaders("POST", url, body);
459
+ return httpPost(url, body, timeout, abortSignal, headers);
460
+ }
461
+
462
+ streamingFetchPromise<T extends RequestSchema>(
463
+ url: string,
464
+ body: RequestBody,
465
+ schema: T,
466
+ timeout?: number,
467
+ signal?: AbortSignal,
468
+ streamRequest?: boolean
469
+ ): Promise<RequestSchemaResultPromise<T>> {
470
+ const headers = this.requestHeaders==null ? {} : this.requestHeaders("POST", url);
471
+ return streamingFetchPromise(url, body, schema, timeout, signal, streamRequest, headers);
472
+ }
473
+
474
+ /**
475
+ * Returns the information about a specific intermediary
476
+ *
477
+ * @param baseUrl Base URL of the intermediary
478
+ * @param timeout Timeout in milliseconds for the HTTP request
479
+ * @param abortSignal
480
+ *
481
+ * @throws {RequestError} If non-200 http response code is returned
482
+ * @throws {Error} If the supplied nonce doesn't match the response
483
+ */
484
+ async getIntermediaryInfo(
485
+ baseUrl: string,
486
+ timeout?: number,
487
+ abortSignal?: AbortSignal
488
+ ): Promise<InfoHandlerResponse> {
489
+ const nonce = randomBytes(32).toString("hex");
490
+
491
+ const abortController = extendAbortController(abortSignal);
492
+
493
+ //We don't know whether the node supports only POST or also has GET info support enabled
494
+ // here we try both, and abort when the first one returns (which should be GET)
495
+ const response = await Promise.any([
496
+ this.httpGet<InfoHandlerResponse>(baseUrl+"/info?nonce="+nonce, timeout, abortController.signal),
497
+ this.httpPost<InfoHandlerResponse>(baseUrl+"/info", {
498
+ nonce,
499
+ }, timeout, abortController.signal)
500
+ ]);
501
+ abortController.abort();
502
+
503
+ const info = JSON.parse(response.envelope);
504
+ if(nonce!==info.nonce) throw new Error("Invalid response - nonce");
505
+
506
+ return response;
507
+ }
508
+
509
+ /**
510
+ * Returns the information about an outcome of the To BTC swap
511
+ *
512
+ * @param url URL of the intermediary
513
+ * @param paymentHash Payment hash of the swap
514
+ * @param sequence Swap's sequence number
515
+ * @param timeout Timeout in milliseconds for the HTTP request
516
+ * @param abortSignal
517
+ *
518
+ * @throws {RequestError} If non-200 http response code is returned
519
+ */
520
+ async getRefundAuthorization(
521
+ url: string,
522
+ paymentHash: string,
523
+ sequence: bigint,
524
+ timeout?: number,
525
+ abortSignal?: AbortSignal
526
+ ): Promise<RefundAuthorizationResponse> {
527
+ return tryWithRetries(() => this.httpGet<RefundAuthorizationResponse>(
528
+ url + "/getRefundAuthorization"+
529
+ "?paymentHash=" + encodeURIComponent(paymentHash) +
530
+ "&sequence=" + encodeURIComponent(sequence.toString(10)),
531
+ timeout,
532
+ abortSignal
533
+ ), undefined, RequestError, abortSignal);
534
+ }
535
+
536
+ /**
537
+ * Returns the information about the payment of the From BTCLN swaps
538
+ *
539
+ * @param url URL of the intermediary
540
+ * @param paymentHash Payment hash of the swap
541
+ * @param timeout Timeout in milliseconds for the HTTP request
542
+ * @param abortSignal
543
+ *
544
+ * @throws {RequestError} If non-200 http response code is returned
545
+ */
546
+ async getPaymentAuthorization(
547
+ url: string,
548
+ paymentHash: string,
549
+ timeout?: number,
550
+ abortSignal?: AbortSignal
551
+ ): Promise<PaymentAuthorizationResponse> {
552
+ return tryWithRetries(() => this.httpGet<PaymentAuthorizationResponse>(
553
+ url+"/getInvoicePaymentAuth"+
554
+ "?paymentHash="+encodeURIComponent(paymentHash),
555
+ timeout,
556
+ abortSignal
557
+ ), undefined, RequestError, abortSignal);
558
+ }
559
+
560
+ /**
561
+ * Returns the status of the payment of the From BTCLN swaps
562
+ *
563
+ * @param url URL of the intermediary
564
+ * @param paymentHash Payment hash of the swap
565
+ * @param timeout Timeout in milliseconds for the HTTP request
566
+ * @param abortSignal
567
+ *
568
+ * @throws {RequestError} If non-200 http response code is returned
569
+ */
570
+ async getInvoiceStatus(
571
+ url: string,
572
+ paymentHash: string,
573
+ timeout?: number,
574
+ abortSignal?: AbortSignal
575
+ ): Promise<InvoiceStatusResponse> {
576
+ return tryWithRetries(() => this.httpGet<InvoiceStatusResponse>(
577
+ url+"/getInvoiceStatus"+
578
+ "?paymentHash="+encodeURIComponent(paymentHash),
579
+ timeout,
580
+ abortSignal
581
+ ), undefined, RequestError, abortSignal);
582
+ }
583
+
584
+ /**
585
+ * Initiate To BTC swap with an intermediary
586
+ *
587
+ * @param chainIdentifier
588
+ * @param baseUrl Base URL of the intermediary
589
+ * @param init Swap initialization parameters
590
+ * @param timeout Timeout in milliseconds for the HTTP request
591
+ * @param abortSignal
592
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
593
+ *
594
+ * @throws {RequestError} If non-200 http response code is returned
595
+ */
596
+ initToBTC(
597
+ chainIdentifier: string,
598
+ baseUrl: string,
599
+ init: ToBTCInit,
600
+ timeout?: number,
601
+ abortSignal?: AbortSignal,
602
+ streamRequest?: boolean
603
+ ): {
604
+ signDataPrefetch: Promise<any>,
605
+ response: Promise<ToBTCResponseType>
606
+ } {
607
+ const responseBodyPromise = this.streamingFetchPromise(baseUrl+"/tobtc/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
608
+ ...init.additionalParams,
609
+ address: init.btcAddress,
610
+ amount: init.amount.toString(10),
611
+ exactIn: init.exactIn,
612
+ confirmationTarget: init.confirmationTarget,
613
+ confirmations: init.confirmations,
614
+ nonce: init.nonce.toString(10),
615
+ token: init.token,
616
+ offerer: init.offerer,
617
+ feeRate: init.feeRate
618
+ }, {
619
+ code: FieldTypeEnum.Number,
620
+ msg: FieldTypeEnum.String,
621
+ data: FieldTypeEnum.AnyOptional,
622
+ signDataPrefetch: FieldTypeEnum.AnyOptional
623
+ }, timeout, abortSignal, streamRequest);
624
+
625
+ return {
626
+ signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
627
+ response: responseBodyPromise.then((responseBody) => Promise.all([
628
+ responseBody.code,
629
+ responseBody.msg,
630
+ responseBody.data,
631
+ ])).then(([code, msg, data]) => {
632
+ if(code!==20000) {
633
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
634
+ }
635
+ const result = verifySchema(data, ToBTCResponseSchema);
636
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
637
+ return result;
638
+ })
639
+ };
640
+ }
641
+
642
+ /**
643
+ * Initiate From BTC swap with an intermediary
644
+ *
645
+ * @param chainIdentifier
646
+ * @param baseUrl Base URL of the intermediary
647
+ * @param depositToken
648
+ * @param init Swap initialization parameters
649
+ * @param timeout Timeout in milliseconds for the HTTP request
650
+ * @param abortSignal
651
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
652
+ *
653
+ * @throws {RequestError} If non-200 http response code is returned
654
+ */
655
+ initFromBTC(
656
+ chainIdentifier: string,
657
+ baseUrl: string,
658
+ depositToken: string,
659
+ init: FromBTCInit,
660
+ timeout?: number,
661
+ abortSignal?: AbortSignal,
662
+ streamRequest?: boolean
663
+ ): {
664
+ signDataPrefetch: Promise<any>,
665
+ response: Promise<FromBTCResponseType>
666
+ } {
667
+ const responseBodyPromise = this.streamingFetchPromise(
668
+ baseUrl+"/frombtc/getAddress?chain="+encodeURIComponent(chainIdentifier)+"&depositToken="+encodeURIComponent(depositToken),
669
+ {
670
+ ...init.additionalParams,
671
+ address: init.claimer,
672
+ amount: init.amount.toString(10),
673
+ token: init.token,
674
+
675
+ exactOut: init.exactOut,
676
+ sequence: init.sequence.toString(10),
677
+
678
+ claimerBounty: init.claimerBounty.then(claimerBounty => {
679
+ return {
680
+ feePerBlock: claimerBounty.feePerBlock.toString(10),
681
+ safetyFactor: claimerBounty.safetyFactor.toString(10),
682
+ startTimestamp: claimerBounty.startTimestamp.toString(10),
683
+ addBlock: claimerBounty.addBlock.toString(10),
684
+ addFee: claimerBounty.addFee.toString(10)
685
+ }
686
+ }),
687
+ feeRate: init.feeRate
688
+ },
689
+ {
690
+ code: FieldTypeEnum.Number,
691
+ msg: FieldTypeEnum.String,
692
+ data: FieldTypeEnum.AnyOptional,
693
+ signDataPrefetch: FieldTypeEnum.AnyOptional
694
+ },
695
+ timeout, abortSignal, streamRequest
696
+ );
697
+
698
+ return {
699
+ signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
700
+ response: responseBodyPromise.then((responseBody) => Promise.all([
701
+ responseBody.code,
702
+ responseBody.msg,
703
+ responseBody.data,
704
+ ])).then(([code, msg, data]) => {
705
+ if(code!==20000) {
706
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
707
+ }
708
+ const result = verifySchema(data, FromBTCResponseSchema);
709
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
710
+ return result;
711
+ })
712
+ };
713
+ }
714
+
715
+ /**
716
+ * Initiate From BTCLN swap with an intermediary
717
+ *
718
+ * @param chainIdentifier
719
+ * @param baseUrl Base URL of the intermediary
720
+ * @param depositToken
721
+ * @param init Swap initialization parameters
722
+ * @param timeout Timeout in milliseconds for the HTTP request
723
+ * @param abortSignal
724
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
725
+ *
726
+ * @throws {RequestError} If non-200 http response code is returned
727
+ */
728
+ initFromBTCLN(
729
+ chainIdentifier: string,
730
+ baseUrl: string,
731
+ depositToken: string,
732
+ init: FromBTCLNInit,
733
+ timeout?: number,
734
+ abortSignal?: AbortSignal,
735
+ streamRequest?: boolean
736
+ ): {
737
+ lnPublicKey: Promise<string | null>,
738
+ response: Promise<FromBTCLNResponseType>
739
+ } {
740
+ const responseBodyPromise = this.streamingFetchPromise(
741
+ baseUrl+"/frombtcln/createInvoice?chain="+encodeURIComponent(chainIdentifier)+"&depositToken="+encodeURIComponent(depositToken),
742
+ {
743
+ ...init.additionalParams,
744
+ paymentHash: init.paymentHash.toString("hex"),
745
+ amount: init.amount.toString(),
746
+ address: init.claimer,
747
+ token: init.token,
748
+ description: init.description ?? null,
749
+ descriptionHash: init.descriptionHash==null ? null : init.descriptionHash.toString("hex"),
750
+ exactOut: init.exactOut,
751
+ feeRate: init.feeRate
752
+ },
753
+ {
754
+ code: FieldTypeEnum.Number,
755
+ msg: FieldTypeEnum.String,
756
+ data: FieldTypeEnum.AnyOptional,
757
+ lnPublicKey: FieldTypeEnum.StringOptional
758
+ },
759
+ timeout, abortSignal, streamRequest
760
+ );
761
+
762
+ return {
763
+ lnPublicKey: responseBodyPromise.then(responseBody => responseBody.lnPublicKey),
764
+ response: responseBodyPromise.then((responseBody) => Promise.all([
765
+ responseBody.code,
766
+ responseBody.msg,
767
+ responseBody.data,
768
+ ])).then(([code, msg, data]) => {
769
+ if(code!==20000) {
770
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
771
+ }
772
+ const result = verifySchema(data, FromBTCLNResponseSchema);
773
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
774
+ return result;
775
+ })
776
+ };
777
+ }
778
+
779
+ /**
780
+ * Initiate From BTCLN swap with auto-initilization by an intermediary
781
+ *
782
+ * @param chainIdentifier
783
+ * @param baseUrl Base URL of the intermediary
784
+ * @param init Swap initialization parameters
785
+ * @param timeout Timeout in milliseconds for the HTTP request
786
+ * @param abortSignal
787
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
788
+ *
789
+ * @throws {RequestError} If non-200 http response code is returned
790
+ */
791
+ initFromBTCLNAuto(
792
+ chainIdentifier: string,
793
+ baseUrl: string,
794
+ init: FromBTCLNAutoInit,
795
+ timeout?: number,
796
+ abortSignal?: AbortSignal,
797
+ streamRequest?: boolean
798
+ ): {
799
+ lnPublicKey: Promise<string | null>,
800
+ response: Promise<FromBTCLNAutoResponseType>
801
+ } {
802
+ const responseBodyPromise = this.streamingFetchPromise(
803
+ baseUrl+"/frombtcln_auto/createInvoice?chain="+encodeURIComponent(chainIdentifier),
804
+ {
805
+ ...init.additionalParams,
806
+ paymentHash: init.paymentHash.toString("hex"),
807
+ amount: init.amount.toString(),
808
+ address: init.claimer,
809
+ token: init.token,
810
+ description: init.description ?? null,
811
+ descriptionHash: init.descriptionHash==null ? null : init.descriptionHash.toString("hex"),
812
+ exactOut: init.exactOut,
813
+ gasToken: init.gasToken,
814
+ gasAmount: init.gasAmount?.toString(10) ?? "0",
815
+ claimerBounty: init.claimerBounty?.then(val => val.toString(10)) ?? "0"
816
+ },
817
+ {
818
+ code: FieldTypeEnum.Number,
819
+ msg: FieldTypeEnum.String,
820
+ data: FieldTypeEnum.AnyOptional,
821
+ lnPublicKey: FieldTypeEnum.StringOptional
822
+ },
823
+ timeout, abortSignal, streamRequest
824
+ );
825
+
826
+ return {
827
+ lnPublicKey: responseBodyPromise.then(responseBody => responseBody.lnPublicKey),
828
+ response: responseBodyPromise.then((responseBody) => Promise.all([
829
+ responseBody.code,
830
+ responseBody.msg,
831
+ responseBody.data,
832
+ ])).then(([code, msg, data]) => {
833
+ if(code!==20000) {
834
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
835
+ }
836
+ const result = verifySchema(data, FromBTCLNAutoResponseSchema);
837
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
838
+ return result;
839
+ })
840
+ };
841
+ }
842
+
843
+ /**
844
+ * Initiate To BTCLN swap with an intermediary
845
+ *
846
+ * @param chainIdentifier
847
+ * @param baseUrl Base URL of the intermediary
848
+ * @param init Swap initialization parameters
849
+ * @param timeout Timeout in milliseconds for the HTTP request
850
+ * @param abortSignal
851
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
852
+ *
853
+ * @throws {RequestError} If non-200 http response code is returned
854
+ */
855
+ initToBTCLN(
856
+ chainIdentifier: string,
857
+ baseUrl: string,
858
+ init: ToBTCLNInit,
859
+ timeout?: number,
860
+ abortSignal?: AbortSignal,
861
+ streamRequest?: boolean
862
+ ): {
863
+ signDataPrefetch: Promise<any>,
864
+ response: Promise<ToBTCLNResponseType>
865
+ } {
866
+ const responseBodyPromise = this.streamingFetchPromise(baseUrl+"/tobtcln/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
867
+ exactIn: false,
868
+ ...init.additionalParams,
869
+ pr: init.pr,
870
+ maxFee: init.maxFee.toString(10),
871
+ expiryTimestamp: init.expiryTimestamp.toString(10),
872
+ token: init.token,
873
+ offerer: init.offerer,
874
+ feeRate: init.feeRate,
875
+ amount: null
876
+ }, {
877
+ code: FieldTypeEnum.Number,
878
+ msg: FieldTypeEnum.String,
879
+ data: FieldTypeEnum.AnyOptional,
880
+ signDataPrefetch: FieldTypeEnum.AnyOptional
881
+ }, timeout, abortSignal, streamRequest);
882
+
883
+ return {
884
+ signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
885
+ response: responseBodyPromise.then((responseBody) => Promise.all([
886
+ responseBody.code,
887
+ responseBody.msg,
888
+ responseBody.data,
889
+ ])).then(([code, msg, data]) => {
890
+ if(code!==20000) {
891
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
892
+ }
893
+ const result = verifySchema(data, ToBTCLNResponseSchema);
894
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
895
+ return result;
896
+ })
897
+ };
898
+ }
899
+
900
+ /**
901
+ * Initiate To BTCLN exact in swap with an intermediary
902
+ *
903
+ * @param baseUrl Base URL of the intermediary
904
+ * @param init Swap initialization parameters
905
+ * @param timeout Timeout in milliseconds for the HTTP request
906
+ * @param abortSignal
907
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
908
+ *
909
+ * @throws {RequestError} If non-200 http response code is returned
910
+ */
911
+ async initToBTCLNExactIn(
912
+ baseUrl: string,
913
+ init: ToBTCLNInitExactIn,
914
+ timeout?: number,
915
+ abortSignal?: AbortSignal,
916
+ streamRequest?: boolean
917
+ ): Promise<ToBTCLNResponseType> {
918
+ const responseBody = await this.streamingFetchPromise(baseUrl+"/tobtcln/payInvoiceExactIn", {
919
+ ...init.additionalParams,
920
+ pr: init.pr,
921
+ reqId: init.reqId,
922
+ feeRate: init.feeRate
923
+ }, {
924
+ code: FieldTypeEnum.Number,
925
+ msg: FieldTypeEnum.String,
926
+ data: FieldTypeEnum.AnyOptional
927
+ }, timeout, abortSignal, streamRequest);
928
+
929
+ const [code, msg, data] = await Promise.all([
930
+ responseBody.code,
931
+ responseBody.msg,
932
+ responseBody.data,
933
+ ])
934
+
935
+ if(code!==20000) throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
936
+ const result = verifySchema(data, ToBTCLNResponseSchema);
937
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
938
+ return result;
939
+ }
940
+
941
+ /**
942
+ * Prepare To BTCLN exact in swap with an intermediary
943
+ *
944
+ * @param chainIdentifier
945
+ * @param baseUrl Base URL of the intermediary
946
+ * @param init Swap initialization parameters
947
+ * @param timeout Timeout in milliseconds for the HTTP request
948
+ * @param abortSignal
949
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
950
+ *
951
+ * @throws {RequestError} If non-200 http response code is returned
952
+ */
953
+ prepareToBTCLNExactIn(
954
+ chainIdentifier: string,
955
+ baseUrl: string,
956
+ init: ToBTCLNPrepareExactIn,
957
+ timeout?: number,
958
+ abortSignal?: AbortSignal,
959
+ streamRequest?: boolean
960
+ ): {
961
+ signDataPrefetch: Promise<any>,
962
+ response: Promise<ToBTCLNPrepareExactInResponseType>
963
+ } {
964
+ const responseBodyPromise = this.streamingFetchPromise(baseUrl+"/tobtcln/payInvoice?chain="+encodeURIComponent(chainIdentifier), {
965
+ exactIn: true,
966
+ ...init.additionalParams,
967
+ pr: init.pr,
968
+ maxFee: init.maxFee.toString(10),
969
+ expiryTimestamp: init.expiryTimestamp.toString(10),
970
+ token: init.token,
971
+ offerer: init.offerer,
972
+ amount: init.amount.toString(10)
973
+ }, {
974
+ code: FieldTypeEnum.Number,
975
+ msg: FieldTypeEnum.String,
976
+ data: FieldTypeEnum.AnyOptional,
977
+ signDataPrefetch: FieldTypeEnum.AnyOptional
978
+ }, timeout, abortSignal, streamRequest);
979
+
980
+ return {
981
+ signDataPrefetch: responseBodyPromise.then(responseBody => responseBody.signDataPrefetch),
982
+ response: responseBodyPromise.then((responseBody) => Promise.all([
983
+ responseBody.code,
984
+ responseBody.msg,
985
+ responseBody.data,
986
+ ])).then(([code, msg, data]) => {
987
+ if(code!==20000) {
988
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
989
+ }
990
+ const result = verifySchema(data, ToBTCLNPrepareExactInSchema);
991
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
992
+ return result;
993
+ })
994
+ };
995
+ }
996
+
997
+ /**
998
+ * Prepare From BTC swap via new spv vault swaps with an intermediary
999
+ *
1000
+ * @param chainIdentifier
1001
+ * @param baseUrl Base URL of the intermediary
1002
+ * @param init Swap initialization parameters
1003
+ * @param timeout Timeout in milliseconds for the HTTP request
1004
+ * @param abortSignal
1005
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
1006
+ *
1007
+ * @throws {RequestError} If non-200 http response code is returned
1008
+ */
1009
+ prepareSpvFromBTC(
1010
+ chainIdentifier: string,
1011
+ baseUrl: string,
1012
+ init: SpvFromBTCPrepare,
1013
+ timeout?: number,
1014
+ abortSignal?: AbortSignal,
1015
+ streamRequest?: boolean
1016
+ ): Promise<SpvFromBTCPrepareResponseType> {
1017
+ //We need to make sure we only send the amount parameter after the amountUtxos and amountFeeRate resolve
1018
+ // this is needed, because in the LP code to maintain backwards compatibility the amountUtxos and amountFeeRate
1019
+ // params are checked immediately after the amount param (and other params) are received, if amount were sent
1020
+ // first without the amountUtxos or amountFeeRate populated these fields would've been skipped altogether
1021
+ const amountPromise = (async () => {
1022
+ if(init.amountUtxos!=null) await init.amountUtxos;
1023
+ if(init.amountFeeRate!=null) await init.amountFeeRate;
1024
+ const amount = await init.amount;
1025
+ return amount.toString(10);
1026
+ })();
1027
+ const responseBodyPromise = this.streamingFetchPromise(baseUrl+"/frombtc_spv/getQuote?chain="+encodeURIComponent(chainIdentifier), {
1028
+ exactOut: init.exactOut,
1029
+ ...init.additionalParams,
1030
+ address: init.address,
1031
+ amount: amountPromise,
1032
+ token: init.token,
1033
+ gasAmount: init.gasAmount.toString(10),
1034
+ gasToken: init.gasToken,
1035
+ frontingFeeRate: init.frontingFeeRate.toString(10),
1036
+ callerFeeRate: init.callerFeeRate.then(val => val.toString(10)),
1037
+ stickyAddress: init.stickyAddress,
1038
+ amountUtxos: init.amountUtxos,
1039
+ amountFeeRate: init.amountFeeRate
1040
+ }, {
1041
+ code: FieldTypeEnum.Number,
1042
+ msg: FieldTypeEnum.String,
1043
+ data: FieldTypeEnum.AnyOptional
1044
+ }, timeout, abortSignal, streamRequest);
1045
+
1046
+ return responseBodyPromise.then((responseBody) => Promise.all([
1047
+ responseBody.code,
1048
+ responseBody.msg,
1049
+ responseBody.data,
1050
+ ])).then(([code, msg, data]) => {
1051
+ if(code!==20000) {
1052
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
1053
+ }
1054
+ const result = verifySchema(data, SpvFromBTCPrepareResponseSchema);
1055
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
1056
+ return result;
1057
+ });
1058
+ }
1059
+
1060
+ /**
1061
+ * Prepare From BTC swap via new spv vault swaps with an intermediary
1062
+ *
1063
+ * @param chainIdentifier
1064
+ * @param url
1065
+ * @param init Swap initialization parameters
1066
+ * @param timeout Timeout in milliseconds for the HTTP request
1067
+ * @param abortSignal
1068
+ * @param streamRequest Whether to force streaming (or not streaming) the request, default is autodetect
1069
+ *
1070
+ * @throws {RequestError} If non-200 http response code is returned
1071
+ */
1072
+ initSpvFromBTC(
1073
+ chainIdentifier: string,
1074
+ url: string,
1075
+ init: SpvFromBTCInit,
1076
+ timeout?: number,
1077
+ abortSignal?: AbortSignal,
1078
+ streamRequest?: boolean
1079
+ ): Promise<SpvFromBTCInitResponseType> {
1080
+ const responseBodyPromise = this.streamingFetchPromise(url+"/postQuote?chain="+encodeURIComponent(chainIdentifier), {
1081
+ quoteId: init.quoteId,
1082
+ psbtHex: init.psbtHex
1083
+ }, {
1084
+ code: FieldTypeEnum.Number,
1085
+ msg: FieldTypeEnum.String,
1086
+ data: FieldTypeEnum.AnyOptional
1087
+ }, timeout, abortSignal, streamRequest);
1088
+
1089
+ return responseBodyPromise.then((responseBody) => Promise.all([
1090
+ responseBody.code,
1091
+ responseBody.msg,
1092
+ responseBody.data,
1093
+ ])).then(([code, msg, data]) => {
1094
+ if(code!==20000) {
1095
+ throw RequestError.parse(JSON.stringify({code, msg, data}), 400);
1096
+ }
1097
+ const result = verifySchema(data, SpvFromBTCInitResponseSchema);
1098
+ if(result==null) throw new RequestError("Cannot parse the response with the expected schema", 200);
1099
+ return result;
1100
+ });
1101
+ }
1102
+
1103
+
1104
+ /**
1105
+ * Fetches the invoice status from the intermediary node
1106
+ *
1107
+ * @param url Url of the trusted intermediary
1108
+ * @param paymentHash Payment hash of the lightning invoice
1109
+ * @param timeout Timeout in milliseconds
1110
+ * @param abortSignal
1111
+ * @throws {RequestError} if non-200 http response is returned
1112
+ */
1113
+ async getTrustedInvoiceStatus(
1114
+ url: string,
1115
+ paymentHash: string,
1116
+ timeout?: number,
1117
+ abortSignal?: AbortSignal
1118
+ ): Promise<TrustedInvoiceStatusResponse> {
1119
+ return tryWithRetries(() => this.httpGet<TrustedInvoiceStatusResponse>(
1120
+ url+"/getInvoiceStatus?paymentHash="+encodeURIComponent(paymentHash),
1121
+ timeout, abortSignal
1122
+ ), undefined, RequestError, abortSignal);
1123
+ }
1124
+
1125
+ /**
1126
+ * Initiate a trusted swap from BTCLN to SC native currency, retries!
1127
+ *
1128
+ * @param chainIdentifier
1129
+ * @param baseUrl Base url of the trusted swap intermediary
1130
+ * @param init Initialization parameters
1131
+ * @param timeout Timeout in milliseconds for the request
1132
+ * @param abortSignal
1133
+ * @throws {RequestError} If the response is non-200
1134
+ */
1135
+ async initTrustedFromBTCLN(
1136
+ chainIdentifier: string,
1137
+ baseUrl: string,
1138
+ init: TrustedFromBTCLNInit,
1139
+ timeout?: number,
1140
+ abortSignal?: AbortSignal
1141
+ ): Promise<TrustedFromBTCLNResponseType> {
1142
+ const resp = await tryWithRetries(
1143
+ () => this.httpGet<{code: number, msg: string, data?: any}>(
1144
+ baseUrl+"/lnforgas/createInvoice" +
1145
+ "?address="+encodeURIComponent(init.address) +
1146
+ "&amount="+encodeURIComponent(init.amount.toString(10))+
1147
+ "&chain="+encodeURIComponent(chainIdentifier)+
1148
+ "&token="+encodeURIComponent(init.token),
1149
+ timeout,
1150
+ abortSignal
1151
+ ), undefined, RequestError, abortSignal
1152
+ );
1153
+
1154
+ if(resp.code!==10000) throw RequestError.parse(JSON.stringify(resp), 400);
1155
+ const res = verifySchema(resp.data, TrustedFromBTCLNResponseSchema);
1156
+ if(res==null) throw new Error("Invalid response returned from LP");
1157
+ return res;
1158
+ }
1159
+
1160
+ /**
1161
+ * Fetches the address status from the intermediary node
1162
+ *
1163
+ * @param url Url of the trusted intermediary
1164
+ * @param paymentHash Payment hash of the swap
1165
+ * @param sequence Sequence number of the swap
1166
+ * @param timeout Timeout in milliseconds
1167
+ * @param abortSignal
1168
+ * @throws {RequestError} if non-200 http response is returned
1169
+ */
1170
+ async getTrustedAddressStatus(
1171
+ url: string,
1172
+ paymentHash: string,
1173
+ sequence: bigint,
1174
+ timeout?: number,
1175
+ abortSignal?: AbortSignal
1176
+ ): Promise<TrustedAddressStatusResponse> {
1177
+ return tryWithRetries(() => this.httpGet<TrustedAddressStatusResponse>(
1178
+ url+"/getAddressStatus?paymentHash="+encodeURIComponent(paymentHash)+"&sequence="+encodeURIComponent(sequence.toString(10)),
1179
+ timeout, abortSignal
1180
+ ), undefined, RequestError, abortSignal);
1181
+ }
1182
+
1183
+ /**
1184
+ * Sets the refund address for an on-chain gas swap
1185
+ *
1186
+ * @param url Url of the trusted intermediary
1187
+ * @param paymentHash Payment hash of the swap
1188
+ * @param sequence Sequence number of the swap
1189
+ * @param refundAddress Refund address to set for the swap
1190
+ * @param timeout Timeout in milliseconds
1191
+ * @param abortSignal
1192
+ * @throws {RequestError} if non-200 http response is returned
1193
+ */
1194
+ async setTrustedRefundAddress(
1195
+ url: string,
1196
+ paymentHash: string,
1197
+ sequence: bigint,
1198
+ refundAddress: string,
1199
+ timeout?: number,
1200
+ abortSignal?: AbortSignal
1201
+ ): Promise<void> {
1202
+ return tryWithRetries(() => this.httpGet<void>(
1203
+ url+"/setRefundAddress" +
1204
+ "?paymentHash="+encodeURIComponent(paymentHash)+
1205
+ "&sequence="+encodeURIComponent(sequence.toString(10))+
1206
+ "&refundAddress="+encodeURIComponent(refundAddress),
1207
+ timeout, abortSignal
1208
+ ), undefined, RequestError, abortSignal);
1209
+ }
1210
+
1211
+ /**
1212
+ * Initiate a trusted swap from BTC to SC native currency, retries!
1213
+ *
1214
+ * @param chainIdentifier
1215
+ * @param baseUrl Base url of the trusted swap intermediary
1216
+ * @param init Initialization parameters
1217
+ * @param timeout Timeout in milliseconds for the request
1218
+ * @param abortSignal
1219
+ * @throws {RequestError} If the response is non-200
1220
+ */
1221
+ async initTrustedFromBTC(
1222
+ chainIdentifier: string,
1223
+ baseUrl: string,
1224
+ init: TrustedFromBTCInit,
1225
+ timeout?: number,
1226
+ abortSignal?: AbortSignal
1227
+ ): Promise<TrustedFromBTCResponseType> {
1228
+ const resp = await tryWithRetries(
1229
+ () => this.httpGet<{code: number, msg: string, data?: any}>(
1230
+ baseUrl+"/frombtc_trusted/getAddress?chain="+encodeURIComponent(chainIdentifier)+
1231
+ "&address="+encodeURIComponent(init.address)+
1232
+ "&amount="+encodeURIComponent(init.amount.toString(10))+
1233
+ (init.refundAddress==null ? "" : "&refundAddress="+encodeURIComponent(init.refundAddress))+
1234
+ "&exactIn=true"+
1235
+ "&token="+encodeURIComponent(init.token),
1236
+ timeout,
1237
+ abortSignal
1238
+ ), undefined, RequestError, abortSignal
1239
+ );
1240
+
1241
+ if(resp.code!==10000) throw RequestError.parse(JSON.stringify(resp), 400);
1242
+ const res = verifySchema(resp.data, TrustedFromBTCResponseSchema);
1243
+ if(res==null) throw new Error("Invalid response returned from LP");
1244
+ return res;
1245
+ }
1246
+
1247
+ }