@buildonspark/issuer-sdk 0.0.13 → 0.0.14

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 (368) hide show
  1. package/dist/{interface → issuer-sdk/src/interface}/wallet-interface.d.ts +2 -0
  2. package/dist/issuer-sdk/src/interface/wallet-interface.js.map +1 -0
  3. package/dist/{issuer-sdk.d.ts → issuer-sdk/src/issuer-sdk.d.ts} +2 -0
  4. package/dist/{issuer-sdk.js → issuer-sdk/src/issuer-sdk.js} +9 -1
  5. package/dist/issuer-sdk/src/issuer-sdk.js.map +1 -0
  6. package/dist/issuer-sdk/src/proto/common.js.map +1 -0
  7. package/dist/issuer-sdk/src/proto/google/protobuf/descriptor.js.map +1 -0
  8. package/dist/issuer-sdk/src/proto/google/protobuf/duration.js.map +1 -0
  9. package/dist/issuer-sdk/src/proto/google/protobuf/empty.js.map +1 -0
  10. package/dist/issuer-sdk/src/proto/google/protobuf/timestamp.js.map +1 -0
  11. package/dist/issuer-sdk/src/proto/mock.js.map +1 -0
  12. package/dist/issuer-sdk/src/proto/spark.js.map +1 -0
  13. package/dist/issuer-sdk/src/proto/spark_authn.js.map +1 -0
  14. package/dist/issuer-sdk/src/proto/validate/validate.js.map +1 -0
  15. package/dist/issuer-sdk/src/services/freeze.js.map +1 -0
  16. package/dist/issuer-sdk/src/services/token-transactions.js.map +1 -0
  17. package/dist/{tests → issuer-sdk/src/tests}/integration/spark.test.js +72 -2
  18. package/dist/issuer-sdk/src/tests/integration/spark.test.js.map +1 -0
  19. package/dist/issuer-sdk/src/utils/constants.js.map +1 -0
  20. package/dist/issuer-sdk/src/utils/token-hashing.js.map +1 -0
  21. package/dist/spark-sdk/src/graphql/client.d.ts +24 -0
  22. package/dist/spark-sdk/src/graphql/client.js +176 -0
  23. package/dist/spark-sdk/src/graphql/client.js.map +1 -0
  24. package/dist/spark-sdk/src/graphql/mutations/CompleteCoopExit.d.ts +1 -0
  25. package/dist/spark-sdk/src/graphql/mutations/CompleteCoopExit.js +19 -0
  26. package/dist/spark-sdk/src/graphql/mutations/CompleteCoopExit.js.map +1 -0
  27. package/dist/spark-sdk/src/graphql/mutations/CompleteLeavesSwap.d.ts +1 -0
  28. package/dist/spark-sdk/src/graphql/mutations/CompleteLeavesSwap.js +17 -0
  29. package/dist/spark-sdk/src/graphql/mutations/CompleteLeavesSwap.js.map +1 -0
  30. package/dist/spark-sdk/src/graphql/mutations/RequestCoopExit.d.ts +1 -0
  31. package/dist/spark-sdk/src/graphql/mutations/RequestCoopExit.js +20 -0
  32. package/dist/spark-sdk/src/graphql/mutations/RequestCoopExit.js.map +1 -0
  33. package/dist/spark-sdk/src/graphql/mutations/RequestLightningReceive.d.ts +1 -0
  34. package/dist/spark-sdk/src/graphql/mutations/RequestLightningReceive.js +26 -0
  35. package/dist/spark-sdk/src/graphql/mutations/RequestLightningReceive.js.map +1 -0
  36. package/dist/spark-sdk/src/graphql/mutations/RequestLightningSend.d.ts +1 -0
  37. package/dist/spark-sdk/src/graphql/mutations/RequestLightningSend.js +18 -0
  38. package/dist/spark-sdk/src/graphql/mutations/RequestLightningSend.js.map +1 -0
  39. package/dist/spark-sdk/src/graphql/mutations/RequestSwapLeaves.d.ts +1 -0
  40. package/dist/spark-sdk/src/graphql/mutations/RequestSwapLeaves.js +24 -0
  41. package/dist/spark-sdk/src/graphql/mutations/RequestSwapLeaves.js.map +1 -0
  42. package/dist/spark-sdk/src/graphql/objects/BitcoinNetwork.d.ts +17 -0
  43. package/dist/spark-sdk/src/graphql/objects/BitcoinNetwork.js +20 -0
  44. package/dist/spark-sdk/src/graphql/objects/BitcoinNetwork.js.map +1 -0
  45. package/dist/spark-sdk/src/graphql/objects/CompleteCoopExitInput.d.ts +7 -0
  46. package/dist/spark-sdk/src/graphql/objects/CompleteCoopExitInput.js +14 -0
  47. package/dist/spark-sdk/src/graphql/objects/CompleteCoopExitInput.js.map +1 -0
  48. package/dist/spark-sdk/src/graphql/objects/CompleteCoopExitOutput.d.ts +7 -0
  49. package/dist/spark-sdk/src/graphql/objects/CompleteCoopExitOutput.js +19 -0
  50. package/dist/spark-sdk/src/graphql/objects/CompleteCoopExitOutput.js.map +1 -0
  51. package/dist/spark-sdk/src/graphql/objects/CompleteLeavesSwapInput.d.ts +8 -0
  52. package/dist/spark-sdk/src/graphql/objects/CompleteLeavesSwapInput.js +16 -0
  53. package/dist/spark-sdk/src/graphql/objects/CompleteLeavesSwapInput.js.map +1 -0
  54. package/dist/spark-sdk/src/graphql/objects/CompleteLeavesSwapOutput.d.ts +7 -0
  55. package/dist/spark-sdk/src/graphql/objects/CompleteLeavesSwapOutput.js +19 -0
  56. package/dist/spark-sdk/src/graphql/objects/CompleteLeavesSwapOutput.js.map +1 -0
  57. package/dist/spark-sdk/src/graphql/objects/CompleteSeedReleaseInput.d.ts +7 -0
  58. package/dist/spark-sdk/src/graphql/objects/CompleteSeedReleaseInput.js +14 -0
  59. package/dist/spark-sdk/src/graphql/objects/CompleteSeedReleaseInput.js.map +1 -0
  60. package/dist/spark-sdk/src/graphql/objects/CompleteSeedReleaseOutput.d.ts +7 -0
  61. package/dist/spark-sdk/src/graphql/objects/CompleteSeedReleaseOutput.js +17 -0
  62. package/dist/spark-sdk/src/graphql/objects/CompleteSeedReleaseOutput.js.map +1 -0
  63. package/dist/spark-sdk/src/graphql/objects/Connection.d.ts +16 -0
  64. package/dist/spark-sdk/src/graphql/objects/Connection.js +56 -0
  65. package/dist/spark-sdk/src/graphql/objects/Connection.js.map +1 -0
  66. package/dist/spark-sdk/src/graphql/objects/CoopExitFeeEstimateInput.d.ts +7 -0
  67. package/dist/spark-sdk/src/graphql/objects/CoopExitFeeEstimateInput.js +14 -0
  68. package/dist/spark-sdk/src/graphql/objects/CoopExitFeeEstimateInput.js.map +1 -0
  69. package/dist/spark-sdk/src/graphql/objects/CoopExitFeeEstimateOutput.d.ts +8 -0
  70. package/dist/spark-sdk/src/graphql/objects/CoopExitFeeEstimateOutput.js +26 -0
  71. package/dist/spark-sdk/src/graphql/objects/CoopExitFeeEstimateOutput.js.map +1 -0
  72. package/dist/spark-sdk/src/graphql/objects/CoopExitRequest.d.ts +32 -0
  73. package/dist/spark-sdk/src/graphql/objects/CoopExitRequest.js +64 -0
  74. package/dist/spark-sdk/src/graphql/objects/CoopExitRequest.js.map +1 -0
  75. package/dist/spark-sdk/src/graphql/objects/CurrencyAmount.d.ts +24 -0
  76. package/dist/spark-sdk/src/graphql/objects/CurrencyAmount.js +30 -0
  77. package/dist/spark-sdk/src/graphql/objects/CurrencyAmount.js.map +1 -0
  78. package/dist/spark-sdk/src/graphql/objects/CurrencyUnit.d.ts +27 -0
  79. package/dist/spark-sdk/src/graphql/objects/CurrencyUnit.js +30 -0
  80. package/dist/spark-sdk/src/graphql/objects/CurrencyUnit.js.map +1 -0
  81. package/dist/spark-sdk/src/graphql/objects/Entity.d.ts +16 -0
  82. package/dist/spark-sdk/src/graphql/objects/Entity.js +165 -0
  83. package/dist/spark-sdk/src/graphql/objects/Entity.js.map +1 -0
  84. package/dist/spark-sdk/src/graphql/objects/GetChallengeInput.d.ts +6 -0
  85. package/dist/spark-sdk/src/graphql/objects/GetChallengeInput.js +12 -0
  86. package/dist/spark-sdk/src/graphql/objects/GetChallengeInput.js.map +1 -0
  87. package/dist/spark-sdk/src/graphql/objects/GetChallengeOutput.d.ts +7 -0
  88. package/dist/spark-sdk/src/graphql/objects/GetChallengeOutput.js +17 -0
  89. package/dist/spark-sdk/src/graphql/objects/GetChallengeOutput.js.map +1 -0
  90. package/dist/spark-sdk/src/graphql/objects/Invoice.d.ts +15 -0
  91. package/dist/spark-sdk/src/graphql/objects/Invoice.js +45 -0
  92. package/dist/spark-sdk/src/graphql/objects/Invoice.js.map +1 -0
  93. package/dist/spark-sdk/src/graphql/objects/Leaf.d.ts +11 -0
  94. package/dist/spark-sdk/src/graphql/objects/Leaf.js +29 -0
  95. package/dist/spark-sdk/src/graphql/objects/Leaf.js.map +1 -0
  96. package/dist/spark-sdk/src/graphql/objects/LeavesSwapFeeEstimateInput.d.ts +6 -0
  97. package/dist/spark-sdk/src/graphql/objects/LeavesSwapFeeEstimateInput.js +12 -0
  98. package/dist/spark-sdk/src/graphql/objects/LeavesSwapFeeEstimateInput.js.map +1 -0
  99. package/dist/spark-sdk/src/graphql/objects/LeavesSwapFeeEstimateOutput.d.ts +8 -0
  100. package/dist/spark-sdk/src/graphql/objects/LeavesSwapFeeEstimateOutput.js +26 -0
  101. package/dist/spark-sdk/src/graphql/objects/LeavesSwapFeeEstimateOutput.js.map +1 -0
  102. package/dist/spark-sdk/src/graphql/objects/LeavesSwapRequest.d.ts +39 -0
  103. package/dist/spark-sdk/src/graphql/objects/LeavesSwapRequest.js +128 -0
  104. package/dist/spark-sdk/src/graphql/objects/LeavesSwapRequest.js.map +1 -0
  105. package/dist/spark-sdk/src/graphql/objects/LightningReceiveFeeEstimateInput.d.ts +8 -0
  106. package/dist/spark-sdk/src/graphql/objects/LightningReceiveFeeEstimateInput.js +15 -0
  107. package/dist/spark-sdk/src/graphql/objects/LightningReceiveFeeEstimateInput.js.map +1 -0
  108. package/dist/spark-sdk/src/graphql/objects/LightningReceiveFeeEstimateOutput.d.ts +8 -0
  109. package/dist/spark-sdk/src/graphql/objects/LightningReceiveFeeEstimateOutput.js +26 -0
  110. package/dist/spark-sdk/src/graphql/objects/LightningReceiveFeeEstimateOutput.js.map +1 -0
  111. package/dist/spark-sdk/src/graphql/objects/LightningReceiveRequest.d.ts +31 -0
  112. package/dist/spark-sdk/src/graphql/objects/LightningReceiveRequest.js +93 -0
  113. package/dist/spark-sdk/src/graphql/objects/LightningReceiveRequest.js.map +1 -0
  114. package/dist/spark-sdk/src/graphql/objects/LightningReceiveRequestStatus.d.ts +18 -0
  115. package/dist/spark-sdk/src/graphql/objects/LightningReceiveRequestStatus.js +21 -0
  116. package/dist/spark-sdk/src/graphql/objects/LightningReceiveRequestStatus.js.map +1 -0
  117. package/dist/spark-sdk/src/graphql/objects/LightningSendFeeEstimateInput.d.ts +6 -0
  118. package/dist/spark-sdk/src/graphql/objects/LightningSendFeeEstimateInput.js +12 -0
  119. package/dist/spark-sdk/src/graphql/objects/LightningSendFeeEstimateInput.js.map +1 -0
  120. package/dist/spark-sdk/src/graphql/objects/LightningSendFeeEstimateOutput.d.ts +8 -0
  121. package/dist/spark-sdk/src/graphql/objects/LightningSendFeeEstimateOutput.js +26 -0
  122. package/dist/spark-sdk/src/graphql/objects/LightningSendFeeEstimateOutput.js.map +1 -0
  123. package/dist/spark-sdk/src/graphql/objects/LightningSendRequest.d.ts +32 -0
  124. package/dist/spark-sdk/src/graphql/objects/LightningSendRequest.js +78 -0
  125. package/dist/spark-sdk/src/graphql/objects/LightningSendRequest.js.map +1 -0
  126. package/dist/spark-sdk/src/graphql/objects/LightningSendRequestStatus.d.ts +15 -0
  127. package/dist/spark-sdk/src/graphql/objects/LightningSendRequestStatus.js +18 -0
  128. package/dist/spark-sdk/src/graphql/objects/LightningSendRequestStatus.js.map +1 -0
  129. package/dist/spark-sdk/src/graphql/objects/NotifyReceiverTransferInput.d.ts +7 -0
  130. package/dist/spark-sdk/src/graphql/objects/NotifyReceiverTransferInput.js +14 -0
  131. package/dist/spark-sdk/src/graphql/objects/NotifyReceiverTransferInput.js.map +1 -0
  132. package/dist/spark-sdk/src/graphql/objects/PageInfo.d.ts +11 -0
  133. package/dist/spark-sdk/src/graphql/objects/PageInfo.js +26 -0
  134. package/dist/spark-sdk/src/graphql/objects/PageInfo.js.map +1 -0
  135. package/dist/spark-sdk/src/graphql/objects/Provider.d.ts +7 -0
  136. package/dist/spark-sdk/src/graphql/objects/Provider.js +14 -0
  137. package/dist/spark-sdk/src/graphql/objects/Provider.js.map +1 -0
  138. package/dist/spark-sdk/src/graphql/objects/RequestCoopExitInput.d.ts +7 -0
  139. package/dist/spark-sdk/src/graphql/objects/RequestCoopExitInput.js +14 -0
  140. package/dist/spark-sdk/src/graphql/objects/RequestCoopExitInput.js.map +1 -0
  141. package/dist/spark-sdk/src/graphql/objects/RequestCoopExitOutput.d.ts +7 -0
  142. package/dist/spark-sdk/src/graphql/objects/RequestCoopExitOutput.js +19 -0
  143. package/dist/spark-sdk/src/graphql/objects/RequestCoopExitOutput.js.map +1 -0
  144. package/dist/spark-sdk/src/graphql/objects/RequestLeavesSwapInput.d.ts +11 -0
  145. package/dist/spark-sdk/src/graphql/objects/RequestLeavesSwapInput.js +22 -0
  146. package/dist/spark-sdk/src/graphql/objects/RequestLeavesSwapInput.js.map +1 -0
  147. package/dist/spark-sdk/src/graphql/objects/RequestLeavesSwapOutput.d.ts +7 -0
  148. package/dist/spark-sdk/src/graphql/objects/RequestLeavesSwapOutput.js +19 -0
  149. package/dist/spark-sdk/src/graphql/objects/RequestLeavesSwapOutput.js.map +1 -0
  150. package/dist/spark-sdk/src/graphql/objects/RequestLightningReceiveInput.d.ts +16 -0
  151. package/dist/spark-sdk/src/graphql/objects/RequestLightningReceiveInput.js +21 -0
  152. package/dist/spark-sdk/src/graphql/objects/RequestLightningReceiveInput.js.map +1 -0
  153. package/dist/spark-sdk/src/graphql/objects/RequestLightningReceiveOutput.d.ts +7 -0
  154. package/dist/spark-sdk/src/graphql/objects/RequestLightningReceiveOutput.js +19 -0
  155. package/dist/spark-sdk/src/graphql/objects/RequestLightningReceiveOutput.js.map +1 -0
  156. package/dist/spark-sdk/src/graphql/objects/RequestLightningSendInput.d.ts +7 -0
  157. package/dist/spark-sdk/src/graphql/objects/RequestLightningSendInput.js +14 -0
  158. package/dist/spark-sdk/src/graphql/objects/RequestLightningSendInput.js.map +1 -0
  159. package/dist/spark-sdk/src/graphql/objects/RequestLightningSendOutput.d.ts +7 -0
  160. package/dist/spark-sdk/src/graphql/objects/RequestLightningSendOutput.js +19 -0
  161. package/dist/spark-sdk/src/graphql/objects/RequestLightningSendOutput.js.map +1 -0
  162. package/dist/spark-sdk/src/graphql/objects/SparkCoopExitRequestStatus.d.ts +11 -0
  163. package/dist/spark-sdk/src/graphql/objects/SparkCoopExitRequestStatus.js +14 -0
  164. package/dist/spark-sdk/src/graphql/objects/SparkCoopExitRequestStatus.js.map +1 -0
  165. package/dist/spark-sdk/src/graphql/objects/SparkLeavesSwapRequestStatus.d.ts +11 -0
  166. package/dist/spark-sdk/src/graphql/objects/SparkLeavesSwapRequestStatus.js +14 -0
  167. package/dist/spark-sdk/src/graphql/objects/SparkLeavesSwapRequestStatus.js.map +1 -0
  168. package/dist/spark-sdk/src/graphql/objects/SparkTransferToLeavesConnection.d.ts +19 -0
  169. package/dist/spark-sdk/src/graphql/objects/SparkTransferToLeavesConnection.js +46 -0
  170. package/dist/spark-sdk/src/graphql/objects/SparkTransferToLeavesConnection.js.map +1 -0
  171. package/dist/spark-sdk/src/graphql/objects/SparkWalletUser.d.ts +21 -0
  172. package/dist/spark-sdk/src/graphql/objects/SparkWalletUser.js +45 -0
  173. package/dist/spark-sdk/src/graphql/objects/SparkWalletUser.js.map +1 -0
  174. package/dist/spark-sdk/src/graphql/objects/StartSeedReleaseInput.d.ts +6 -0
  175. package/dist/spark-sdk/src/graphql/objects/StartSeedReleaseInput.js +12 -0
  176. package/dist/spark-sdk/src/graphql/objects/StartSeedReleaseInput.js.map +1 -0
  177. package/dist/spark-sdk/src/graphql/objects/SwapLeaf.d.ts +9 -0
  178. package/dist/spark-sdk/src/graphql/objects/SwapLeaf.js +23 -0
  179. package/dist/spark-sdk/src/graphql/objects/SwapLeaf.js.map +1 -0
  180. package/dist/spark-sdk/src/graphql/objects/Transfer.d.ts +24 -0
  181. package/dist/spark-sdk/src/graphql/objects/Transfer.js +82 -0
  182. package/dist/spark-sdk/src/graphql/objects/Transfer.js.map +1 -0
  183. package/dist/spark-sdk/src/graphql/objects/UserLeafInput.d.ts +8 -0
  184. package/dist/spark-sdk/src/graphql/objects/UserLeafInput.js +16 -0
  185. package/dist/spark-sdk/src/graphql/objects/UserLeafInput.js.map +1 -0
  186. package/dist/spark-sdk/src/graphql/objects/VerifyChallengeInput.d.ts +10 -0
  187. package/dist/spark-sdk/src/graphql/objects/VerifyChallengeInput.js +20 -0
  188. package/dist/spark-sdk/src/graphql/objects/VerifyChallengeInput.js.map +1 -0
  189. package/dist/spark-sdk/src/graphql/objects/VerifyChallengeOutput.d.ts +7 -0
  190. package/dist/spark-sdk/src/graphql/objects/VerifyChallengeOutput.js +17 -0
  191. package/dist/spark-sdk/src/graphql/objects/VerifyChallengeOutput.js.map +1 -0
  192. package/dist/spark-sdk/src/graphql/objects/WalletUserIdentityPublicKeyInput.d.ts +6 -0
  193. package/dist/spark-sdk/src/graphql/objects/WalletUserIdentityPublicKeyInput.js +12 -0
  194. package/dist/spark-sdk/src/graphql/objects/WalletUserIdentityPublicKeyInput.js.map +1 -0
  195. package/dist/spark-sdk/src/graphql/objects/WalletUserIdentityPublicKeyOutput.d.ts +7 -0
  196. package/dist/spark-sdk/src/graphql/objects/WalletUserIdentityPublicKeyOutput.js +17 -0
  197. package/dist/spark-sdk/src/graphql/objects/WalletUserIdentityPublicKeyOutput.js.map +1 -0
  198. package/dist/spark-sdk/src/graphql/objects/index.d.ts +52 -0
  199. package/dist/spark-sdk/src/graphql/objects/index.js +13 -0
  200. package/dist/spark-sdk/src/graphql/objects/index.js.map +1 -0
  201. package/dist/spark-sdk/src/graphql/queries/CoopExitFeeEstimate.d.ts +1 -0
  202. package/dist/spark-sdk/src/graphql/queries/CoopExitFeeEstimate.js +18 -0
  203. package/dist/spark-sdk/src/graphql/queries/CoopExitFeeEstimate.js.map +1 -0
  204. package/dist/spark-sdk/src/graphql/queries/LightningReceiveFeeEstimate.d.ts +1 -0
  205. package/dist/spark-sdk/src/graphql/queries/LightningReceiveFeeEstimate.js +18 -0
  206. package/dist/spark-sdk/src/graphql/queries/LightningReceiveFeeEstimate.js.map +1 -0
  207. package/dist/spark-sdk/src/graphql/queries/LightningSendFeeEstimate.d.ts +1 -0
  208. package/dist/spark-sdk/src/graphql/queries/LightningSendFeeEstimate.js +16 -0
  209. package/dist/spark-sdk/src/graphql/queries/LightningSendFeeEstimate.js.map +1 -0
  210. package/dist/spark-sdk/src/proto/common.d.ts +58 -0
  211. package/dist/spark-sdk/src/proto/common.js +350 -0
  212. package/dist/spark-sdk/src/proto/common.js.map +1 -0
  213. package/dist/spark-sdk/src/proto/google/protobuf/empty.d.ts +33 -0
  214. package/dist/spark-sdk/src/proto/google/protobuf/empty.js +46 -0
  215. package/dist/spark-sdk/src/proto/google/protobuf/empty.js.map +1 -0
  216. package/dist/spark-sdk/src/proto/google/protobuf/timestamp.d.ts +128 -0
  217. package/dist/spark-sdk/src/proto/google/protobuf/timestamp.js +90 -0
  218. package/dist/spark-sdk/src/proto/google/protobuf/timestamp.js.map +1 -0
  219. package/dist/spark-sdk/src/proto/mock.d.ts +48 -0
  220. package/dist/spark-sdk/src/proto/mock.js +103 -0
  221. package/dist/spark-sdk/src/proto/mock.js.map +1 -0
  222. package/dist/spark-sdk/src/proto/spark.d.ts +1101 -0
  223. package/dist/spark-sdk/src/proto/spark.js +9565 -0
  224. package/dist/spark-sdk/src/proto/spark.js.map +1 -0
  225. package/dist/spark-sdk/src/proto/spark_authn.d.ts +111 -0
  226. package/dist/spark-sdk/src/proto/spark_authn.js +517 -0
  227. package/dist/spark-sdk/src/proto/spark_authn.js.map +1 -0
  228. package/dist/spark-sdk/src/services/config.d.ts +16 -0
  229. package/dist/spark-sdk/src/services/config.js +51 -0
  230. package/dist/spark-sdk/src/services/config.js.map +1 -0
  231. package/dist/spark-sdk/src/services/connection.d.ts +22 -0
  232. package/dist/spark-sdk/src/services/connection.js +180 -0
  233. package/dist/spark-sdk/src/services/connection.js.map +1 -0
  234. package/dist/spark-sdk/src/services/coop-exit.d.ts +20 -0
  235. package/dist/spark-sdk/src/services/coop-exit.js +101 -0
  236. package/dist/spark-sdk/src/services/coop-exit.js.map +1 -0
  237. package/dist/spark-sdk/src/services/deposit.d.ts +21 -0
  238. package/dist/spark-sdk/src/services/deposit.js +214 -0
  239. package/dist/spark-sdk/src/services/deposit.js.map +1 -0
  240. package/dist/spark-sdk/src/services/lightning.d.ts +31 -0
  241. package/dist/spark-sdk/src/services/lightning.js +209 -0
  242. package/dist/spark-sdk/src/services/lightning.js.map +1 -0
  243. package/dist/spark-sdk/src/services/lrc20.d.ts +5 -0
  244. package/dist/spark-sdk/src/services/lrc20.js +27 -0
  245. package/dist/spark-sdk/src/services/lrc20.js.map +1 -0
  246. package/dist/spark-sdk/src/services/token-transactions.d.ts +16 -0
  247. package/dist/spark-sdk/src/services/token-transactions.js +299 -0
  248. package/dist/spark-sdk/src/services/token-transactions.js.map +1 -0
  249. package/dist/spark-sdk/src/services/transfer.d.ts +66 -0
  250. package/dist/spark-sdk/src/services/transfer.js +789 -0
  251. package/dist/spark-sdk/src/services/transfer.js.map +1 -0
  252. package/dist/spark-sdk/src/services/tree-creation.d.ts +29 -0
  253. package/dist/spark-sdk/src/services/tree-creation.js +399 -0
  254. package/dist/spark-sdk/src/services/tree-creation.js.map +1 -0
  255. package/dist/spark-sdk/src/services/wallet-config.d.ts +22 -0
  256. package/dist/spark-sdk/src/services/wallet-config.js +100 -0
  257. package/dist/spark-sdk/src/services/wallet-config.js.map +1 -0
  258. package/dist/spark-sdk/src/signer/signer.d.ts +106 -0
  259. package/dist/spark-sdk/src/signer/signer.js +272 -0
  260. package/dist/spark-sdk/src/signer/signer.js.map +1 -0
  261. package/dist/spark-sdk/src/spark-sdk.d.ts +353 -0
  262. package/dist/spark-sdk/src/spark-sdk.js +1110 -0
  263. package/dist/spark-sdk/src/spark-sdk.js.map +1 -0
  264. package/dist/spark-sdk/src/tests/utils/test-faucet.d.ts +23 -0
  265. package/dist/spark-sdk/src/tests/utils/test-faucet.js +172 -0
  266. package/dist/spark-sdk/src/tests/utils/test-faucet.js.map +1 -0
  267. package/dist/spark-sdk/src/types/grpc.d.ts +6 -0
  268. package/dist/spark-sdk/src/types/grpc.js +2 -0
  269. package/dist/spark-sdk/src/types/grpc.js.map +1 -0
  270. package/dist/spark-sdk/src/types/index.d.ts +3 -0
  271. package/dist/spark-sdk/src/types/index.js +4 -0
  272. package/dist/spark-sdk/src/types/index.js.map +1 -0
  273. package/dist/spark-sdk/src/utils/adaptor-signature.d.ts +7 -0
  274. package/dist/spark-sdk/src/utils/adaptor-signature.js +114 -0
  275. package/dist/spark-sdk/src/utils/adaptor-signature.js.map +1 -0
  276. package/dist/spark-sdk/src/utils/bitcoin.d.ts +12 -0
  277. package/dist/spark-sdk/src/utils/bitcoin.js +87 -0
  278. package/dist/spark-sdk/src/utils/bitcoin.js.map +1 -0
  279. package/dist/spark-sdk/src/utils/crypto.d.ts +1 -0
  280. package/dist/spark-sdk/src/utils/crypto.js +14 -0
  281. package/dist/spark-sdk/src/utils/crypto.js.map +1 -0
  282. package/dist/spark-sdk/src/utils/index.d.ts +12 -0
  283. package/dist/spark-sdk/src/utils/index.js +13 -0
  284. package/dist/spark-sdk/src/utils/index.js.map +1 -0
  285. package/dist/spark-sdk/src/utils/keys.d.ts +9 -0
  286. package/dist/spark-sdk/src/utils/keys.js +72 -0
  287. package/dist/spark-sdk/src/utils/keys.js.map +1 -0
  288. package/dist/spark-sdk/src/utils/mempool.d.ts +1 -0
  289. package/dist/spark-sdk/src/utils/mempool.js +29 -0
  290. package/dist/spark-sdk/src/utils/mempool.js.map +1 -0
  291. package/dist/spark-sdk/src/utils/network.d.ts +36 -0
  292. package/dist/spark-sdk/src/utils/network.js +65 -0
  293. package/dist/spark-sdk/src/utils/network.js.map +1 -0
  294. package/dist/spark-sdk/src/utils/proof.d.ts +1 -0
  295. package/dist/spark-sdk/src/utils/proof.js +12 -0
  296. package/dist/spark-sdk/src/utils/proof.js.map +1 -0
  297. package/dist/spark-sdk/src/utils/response-validation.d.ts +1 -0
  298. package/dist/spark-sdk/src/utils/response-validation.js +16 -0
  299. package/dist/spark-sdk/src/utils/response-validation.js.map +1 -0
  300. package/dist/spark-sdk/src/utils/secret-sharing.d.ts +26 -0
  301. package/dist/spark-sdk/src/utils/secret-sharing.js +174 -0
  302. package/dist/spark-sdk/src/utils/secret-sharing.js.map +1 -0
  303. package/dist/spark-sdk/src/utils/signing.d.ts +12 -0
  304. package/dist/spark-sdk/src/utils/signing.js +67 -0
  305. package/dist/spark-sdk/src/utils/signing.js.map +1 -0
  306. package/dist/spark-sdk/src/utils/token-hashing.d.ts +3 -0
  307. package/dist/spark-sdk/src/utils/token-hashing.js +116 -0
  308. package/dist/spark-sdk/src/utils/token-hashing.js.map +1 -0
  309. package/dist/spark-sdk/src/utils/token-keyshares.d.ts +5 -0
  310. package/dist/spark-sdk/src/utils/token-keyshares.js +17 -0
  311. package/dist/spark-sdk/src/utils/token-keyshares.js.map +1 -0
  312. package/dist/spark-sdk/src/utils/token-transactions.d.ts +5 -0
  313. package/dist/spark-sdk/src/utils/token-transactions.js +40 -0
  314. package/dist/spark-sdk/src/utils/token-transactions.js.map +1 -0
  315. package/dist/spark-sdk/src/utils/transaction.d.ts +6 -0
  316. package/dist/spark-sdk/src/utils/transaction.js +31 -0
  317. package/dist/spark-sdk/src/utils/transaction.js.map +1 -0
  318. package/dist/spark-sdk/src/utils/wasm-wrapper.d.ts +2 -0
  319. package/dist/spark-sdk/src/utils/wasm-wrapper.js +46 -0
  320. package/dist/spark-sdk/src/utils/wasm-wrapper.js.map +1 -0
  321. package/dist/spark-sdk/src/utils/wasm.d.ts +54 -0
  322. package/dist/spark-sdk/src/utils/wasm.js +26 -0
  323. package/dist/spark-sdk/src/utils/wasm.js.map +1 -0
  324. package/package.json +3 -3
  325. package/dist/interface/wallet-interface.js.map +0 -1
  326. package/dist/issuer-sdk.js.map +0 -1
  327. package/dist/proto/common.js.map +0 -1
  328. package/dist/proto/google/protobuf/descriptor.js.map +0 -1
  329. package/dist/proto/google/protobuf/duration.js.map +0 -1
  330. package/dist/proto/google/protobuf/empty.js.map +0 -1
  331. package/dist/proto/google/protobuf/timestamp.js.map +0 -1
  332. package/dist/proto/mock.js.map +0 -1
  333. package/dist/proto/spark.js.map +0 -1
  334. package/dist/proto/spark_authn.js.map +0 -1
  335. package/dist/proto/validate/validate.js.map +0 -1
  336. package/dist/services/freeze.js.map +0 -1
  337. package/dist/services/token-transactions.js.map +0 -1
  338. package/dist/tests/integration/spark.test.js.map +0 -1
  339. package/dist/utils/constants.js.map +0 -1
  340. package/dist/utils/token-hashing.js.map +0 -1
  341. /package/dist/{interface → issuer-sdk/src/interface}/wallet-interface.js +0 -0
  342. /package/dist/{proto → issuer-sdk/src/proto}/common.d.ts +0 -0
  343. /package/dist/{proto → issuer-sdk/src/proto}/common.js +0 -0
  344. /package/dist/{proto → issuer-sdk/src/proto}/google/protobuf/descriptor.d.ts +0 -0
  345. /package/dist/{proto → issuer-sdk/src/proto}/google/protobuf/descriptor.js +0 -0
  346. /package/dist/{proto → issuer-sdk/src/proto}/google/protobuf/duration.d.ts +0 -0
  347. /package/dist/{proto → issuer-sdk/src/proto}/google/protobuf/duration.js +0 -0
  348. /package/dist/{proto → issuer-sdk/src/proto}/google/protobuf/empty.d.ts +0 -0
  349. /package/dist/{proto → issuer-sdk/src/proto}/google/protobuf/empty.js +0 -0
  350. /package/dist/{proto → issuer-sdk/src/proto}/google/protobuf/timestamp.d.ts +0 -0
  351. /package/dist/{proto → issuer-sdk/src/proto}/google/protobuf/timestamp.js +0 -0
  352. /package/dist/{proto → issuer-sdk/src/proto}/mock.d.ts +0 -0
  353. /package/dist/{proto → issuer-sdk/src/proto}/mock.js +0 -0
  354. /package/dist/{proto → issuer-sdk/src/proto}/spark.d.ts +0 -0
  355. /package/dist/{proto → issuer-sdk/src/proto}/spark.js +0 -0
  356. /package/dist/{proto → issuer-sdk/src/proto}/spark_authn.d.ts +0 -0
  357. /package/dist/{proto → issuer-sdk/src/proto}/spark_authn.js +0 -0
  358. /package/dist/{proto → issuer-sdk/src/proto}/validate/validate.d.ts +0 -0
  359. /package/dist/{proto → issuer-sdk/src/proto}/validate/validate.js +0 -0
  360. /package/dist/{services → issuer-sdk/src/services}/freeze.d.ts +0 -0
  361. /package/dist/{services → issuer-sdk/src/services}/freeze.js +0 -0
  362. /package/dist/{services → issuer-sdk/src/services}/token-transactions.d.ts +0 -0
  363. /package/dist/{services → issuer-sdk/src/services}/token-transactions.js +0 -0
  364. /package/dist/{tests → issuer-sdk/src/tests}/integration/spark.test.d.ts +0 -0
  365. /package/dist/{utils → issuer-sdk/src/utils}/constants.d.ts +0 -0
  366. /package/dist/{utils → issuer-sdk/src/utils}/constants.js +0 -0
  367. /package/dist/{utils → issuer-sdk/src/utils}/token-hashing.d.ts +0 -0
  368. /package/dist/{utils → issuer-sdk/src/utils}/token-hashing.js +0 -0
@@ -0,0 +1,1110 @@
1
+ import { bytesToHex, hexToBytes } from "@noble/curves/abstract/utils";
2
+ import { secp256k1 } from "@noble/curves/secp256k1";
3
+ import { Address, OutScript } from "@scure/btc-signer";
4
+ import { sha256 } from "@scure/btc-signer/utils";
5
+ import { decode } from "light-bolt11-decoder";
6
+ import SspClient from "./graphql/client.js";
7
+ import { BitcoinNetwork, } from "./graphql/objects/index.js";
8
+ import { TransferStatus, } from "./proto/spark.js";
9
+ import { WalletConfigService } from "./services/config.js";
10
+ import { ConnectionManager } from "./services/connection.js";
11
+ import { CoopExitService } from "./services/coop-exit.js";
12
+ import { DepositService } from "./services/deposit.js";
13
+ import { LightningService } from "./services/lightning.js";
14
+ import { TokenTransactionService } from "./services/token-transactions.js";
15
+ import { TransferService } from "./services/transfer.js";
16
+ import { validateMnemonic } from "@scure/bip39";
17
+ import { wordlist } from "@scure/bip39/wordlists/english";
18
+ import { Mutex } from "async-mutex";
19
+ import bitcoin from "bitcoinjs-lib";
20
+ import { TreeCreationService, } from "./services/tree-creation.js";
21
+ import { applyAdaptorToSignature, generateAdaptorFromSignature, generateSignatureFromExistingAdaptor, } from "./utils/adaptor-signature.js";
22
+ import { computeTaprootKeyNoScript, getSigHashFromTx, getTxFromRawTxBytes, getTxFromRawTxHex, getTxId, } from "./utils/bitcoin.js";
23
+ import { getNetwork, LRC_WALLET_NETWORK, LRC_WALLET_NETWORK_TYPE, Network, } from "./utils/network.js";
24
+ import { calculateAvailableTokenAmount, checkIfSelectedLeavesAreAvailable, } from "./utils/token-transactions.js";
25
+ import { getNextTransactionSequence } from "./utils/transaction.js";
26
+ import { initWasm } from "./utils/wasm-wrapper.js";
27
+ import { LRCWallet } from "@buildonspark/lrc20-sdk";
28
+ import { broadcastL1Withdrawal } from "./services/lrc20.js";
29
+ import { getMasterHDKeyFromSeed } from "./utils/index.js";
30
+ // Add this constant at the file level
31
+ const MAX_TOKEN_LEAVES = 100;
32
+ /**
33
+ * The SparkWallet class is the primary interface for interacting with the Spark network.
34
+ * It provides methods for creating and managing wallets, handling deposits, executing transfers,
35
+ * and interacting with the Lightning Network.
36
+ */
37
+ export class SparkWallet {
38
+ config;
39
+ connectionManager;
40
+ lrc20Wallet;
41
+ depositService;
42
+ transferService;
43
+ treeCreationService;
44
+ lightningService;
45
+ coopExitService;
46
+ tokenTransactionService;
47
+ claimTransferMutex = new Mutex();
48
+ leavesMutex = new Mutex();
49
+ optimizationInProgress = false;
50
+ sspClient = null;
51
+ wasmModule = null;
52
+ leaves = [];
53
+ tokenLeaves = new Map();
54
+ constructor(options, signer) {
55
+ this.config = new WalletConfigService(options, signer);
56
+ this.connectionManager = new ConnectionManager(this.config);
57
+ this.depositService = new DepositService(this.config, this.connectionManager);
58
+ this.transferService = new TransferService(this.config, this.connectionManager);
59
+ this.treeCreationService = new TreeCreationService(this.config, this.connectionManager);
60
+ this.tokenTransactionService = new TokenTransactionService(this.config, this.connectionManager);
61
+ this.lightningService = new LightningService(this.config, this.connectionManager);
62
+ this.coopExitService = new CoopExitService(this.config, this.connectionManager);
63
+ }
64
+ static async create({ mnemonicOrSeed, signer, options, lrc20WalletApiConfig, }) {
65
+ const wallet = new SparkWallet(options, signer);
66
+ const initResponse = await wallet.initWallet(mnemonicOrSeed, lrc20WalletApiConfig);
67
+ return {
68
+ wallet,
69
+ ...initResponse,
70
+ };
71
+ }
72
+ async initWasm() {
73
+ try {
74
+ this.wasmModule = await initWasm();
75
+ }
76
+ catch (e) {
77
+ console.error("Failed to initialize Wasm module", e);
78
+ }
79
+ }
80
+ async initializeWallet(identityPublicKey) {
81
+ this.sspClient = new SspClient(identityPublicKey);
82
+ await this.connectionManager.createClients();
83
+ await this.initWasm();
84
+ await this.syncWallet();
85
+ }
86
+ async getLeaves() {
87
+ const sparkClient = await this.connectionManager.createSparkClient(this.config.getCoordinatorAddress());
88
+ const leaves = await sparkClient.query_nodes({
89
+ source: {
90
+ $case: "ownerIdentityPubkey",
91
+ ownerIdentityPubkey: await this.config.signer.getIdentityPublicKey(),
92
+ },
93
+ includeParents: false,
94
+ });
95
+ return Object.entries(leaves.nodes)
96
+ .filter(([_, node]) => node.status === "AVAILABLE")
97
+ .map(([_, node]) => node);
98
+ }
99
+ async selectLeaves(targetAmount) {
100
+ if (targetAmount <= 0) {
101
+ throw new Error("Target amount must be positive");
102
+ }
103
+ const leaves = await this.getLeaves();
104
+ if (leaves.length === 0) {
105
+ throw new Error("No owned leaves found");
106
+ }
107
+ leaves.sort((a, b) => b.value - a.value);
108
+ let amount = 0;
109
+ let nodes = [];
110
+ for (const leaf of leaves) {
111
+ if (targetAmount - amount >= leaf.value) {
112
+ amount += leaf.value;
113
+ nodes.push(leaf);
114
+ }
115
+ }
116
+ if (amount !== targetAmount) {
117
+ await this.requestLeavesSwap({ targetAmount });
118
+ amount = 0;
119
+ nodes = [];
120
+ const newLeaves = await this.getLeaves();
121
+ newLeaves.sort((a, b) => b.value - a.value);
122
+ for (const leaf of newLeaves) {
123
+ if (targetAmount - amount >= leaf.value) {
124
+ amount += leaf.value;
125
+ nodes.push(leaf);
126
+ }
127
+ }
128
+ }
129
+ return nodes;
130
+ }
131
+ async selectLeavesForSwap(targetAmount) {
132
+ if (targetAmount == 0) {
133
+ throw new Error("Target amount needs to > 0");
134
+ }
135
+ const leaves = await this.getLeaves();
136
+ leaves.sort((a, b) => a.value - b.value);
137
+ let amount = 0;
138
+ const nodes = [];
139
+ for (const leaf of leaves) {
140
+ if (amount < targetAmount) {
141
+ amount += leaf.value;
142
+ nodes.push(leaf);
143
+ }
144
+ }
145
+ if (amount < targetAmount) {
146
+ throw new Error("Not enough leaves to swap for the target amount");
147
+ }
148
+ return nodes;
149
+ }
150
+ areLeavesInefficient() {
151
+ const totalAmount = this.leaves.reduce((acc, leaf) => acc + leaf.value, 0);
152
+ if (this.leaves.length <= 1) {
153
+ return false;
154
+ }
155
+ const nextLowerPowerOfTwo = 31 - Math.clz32(totalAmount);
156
+ let remainingAmount = totalAmount;
157
+ let optimalLeavesLength = 0;
158
+ for (let i = nextLowerPowerOfTwo; i >= 0; i--) {
159
+ const denomination = 2 ** i;
160
+ while (remainingAmount >= denomination) {
161
+ remainingAmount -= denomination;
162
+ optimalLeavesLength++;
163
+ }
164
+ }
165
+ return this.leaves.length > optimalLeavesLength * 5;
166
+ }
167
+ async optimizeLeaves() {
168
+ if (this.optimizationInProgress || !this.areLeavesInefficient()) {
169
+ return;
170
+ }
171
+ await this.withLeaves(async () => {
172
+ this.optimizationInProgress = true;
173
+ try {
174
+ if (this.leaves.length > 0) {
175
+ await this.requestLeavesSwap({ leaves: this.leaves });
176
+ }
177
+ this.leaves = await this.getLeaves();
178
+ }
179
+ finally {
180
+ this.optimizationInProgress = false;
181
+ }
182
+ });
183
+ }
184
+ async syncWallet() {
185
+ await Promise.all([this.claimTransfers(), this.syncTokenLeaves()]);
186
+ this.leaves = await this.getLeaves();
187
+ await this.config.signer.restoreSigningKeysFromLeafs(this.leaves);
188
+ await this.refreshTimelockNodes();
189
+ this.optimizeLeaves().catch((e) => {
190
+ console.error("Failed to optimize leaves", e);
191
+ });
192
+ }
193
+ async withLeaves(operation) {
194
+ const release = await this.leavesMutex.acquire();
195
+ try {
196
+ return await operation();
197
+ }
198
+ finally {
199
+ release();
200
+ }
201
+ }
202
+ /**
203
+ * Gets the identity public key of the wallet.
204
+ *
205
+ * @returns {Promise<string>} The identity public key as a hex string.
206
+ */
207
+ async getIdentityPublicKey() {
208
+ return bytesToHex(await this.config.signer.getIdentityPublicKey());
209
+ }
210
+ /**
211
+ * Gets the Spark address of the wallet.
212
+ *
213
+ * @returns {Promise<string>} The Spark address as a hex string.
214
+ */
215
+ async getSparkAddress() {
216
+ return bytesToHex(await this.config.signer.getIdentityPublicKey());
217
+ }
218
+ /**
219
+ * Initializes the wallet using either a mnemonic phrase or a raw seed.
220
+ * initWallet will also claim any pending incoming lightning payment, spark transfer,
221
+ * or bitcoin deposit.
222
+ *
223
+ * @param {Uint8Array | string} [mnemonicOrSeed] - (Optional) Either:
224
+ * - A BIP-39 mnemonic phrase as string
225
+ * - A raw seed as Uint8Array or hex string
226
+ * If not provided, generates a new mnemonic and uses it to create a new wallet
227
+ *
228
+ * @returns {Promise<Object>} Object containing:
229
+ * - mnemonic: The mnemonic if one was generated (undefined for raw seed)
230
+ * - balance: The wallet's initial balance in satoshis
231
+ * - tokenBalance: Map of token balances and leaf counts
232
+ * @private
233
+ */
234
+ async initWallet(mnemonicOrSeed, lrc20WalletApiConfig) {
235
+ const returnMnemonic = !mnemonicOrSeed;
236
+ let mnemonic;
237
+ if (!mnemonicOrSeed) {
238
+ mnemonic = await this.config.signer.generateMnemonic();
239
+ mnemonicOrSeed = mnemonic;
240
+ }
241
+ let seed;
242
+ if (typeof mnemonicOrSeed !== "string") {
243
+ seed = mnemonicOrSeed;
244
+ }
245
+ else {
246
+ if (validateMnemonic(mnemonicOrSeed, wordlist)) {
247
+ seed = await this.config.signer.mnemonicToSeed(mnemonicOrSeed);
248
+ }
249
+ else {
250
+ seed = hexToBytes(mnemonicOrSeed);
251
+ }
252
+ }
253
+ await this.initWalletFromSeed(seed);
254
+ if (lrc20WalletApiConfig) {
255
+ const network = this.config.getNetwork();
256
+ const masterPrivateKey = getMasterHDKeyFromSeed(seed, network == Network.REGTEST ? 0 : 1).privateKey;
257
+ this.lrc20Wallet = new LRCWallet(bytesToHex(masterPrivateKey), LRC_WALLET_NETWORK[network], LRC_WALLET_NETWORK_TYPE[network], lrc20WalletApiConfig);
258
+ }
259
+ if (returnMnemonic) {
260
+ return {
261
+ mnemonic,
262
+ };
263
+ }
264
+ return;
265
+ }
266
+ /**
267
+ * Initializes a wallet from a seed.
268
+ *
269
+ * @param {Uint8Array | string} seed - The seed to initialize the wallet from
270
+ * @returns {Promise<string>} The identity public key
271
+ * @private
272
+ */
273
+ async initWalletFromSeed(seed) {
274
+ const identityPublicKey = await this.config.signer.createSparkWalletFromSeed(seed, this.config.getNetwork());
275
+ await this.initializeWallet(identityPublicKey);
276
+ return identityPublicKey;
277
+ }
278
+ /**
279
+ * Requests a swap of leaves to optimize wallet structure.
280
+ *
281
+ * @param {Object} params - Parameters for the leaves swap
282
+ * @param {number} [params.targetAmount] - Target amount for the swap
283
+ * @param {TreeNode[]} [params.leaves] - Specific leaves to swap
284
+ * @returns {Promise<Object>} The completed swap response
285
+ */
286
+ async requestLeavesSwap({ targetAmount, leaves, }) {
287
+ if (targetAmount && targetAmount <= 0) {
288
+ throw new Error("targetAmount must be positive");
289
+ }
290
+ await this.claimTransfers();
291
+ let leavesToSwap;
292
+ if (targetAmount && leaves && leaves.length > 0) {
293
+ if (targetAmount < leaves.reduce((acc, leaf) => acc + leaf.value, 0)) {
294
+ throw new Error("targetAmount is less than the sum of leaves");
295
+ }
296
+ leavesToSwap = leaves;
297
+ }
298
+ else if (targetAmount) {
299
+ leavesToSwap = await this.selectLeavesForSwap(targetAmount);
300
+ }
301
+ else if (leaves && leaves.length > 0) {
302
+ leavesToSwap = leaves;
303
+ }
304
+ else {
305
+ throw new Error("targetAmount or leaves must be provided");
306
+ }
307
+ const leafKeyTweaks = await Promise.all(leavesToSwap.map(async (leaf) => ({
308
+ leaf,
309
+ signingPubKey: await this.config.signer.generatePublicKey(sha256(leaf.id)),
310
+ newSigningPubKey: await this.config.signer.generatePublicKey(),
311
+ })));
312
+ const { transfer, signatureMap } = await this.transferService.sendTransferSignRefund(leafKeyTweaks, await this.config.signer.getSspIdentityPublicKey(this.config.getNetwork()), new Date(Date.now() + 2 * 60 * 1000));
313
+ try {
314
+ if (!transfer.leaves[0]?.leaf) {
315
+ throw new Error("Failed to get leaf");
316
+ }
317
+ const refundSignature = signatureMap.get(transfer.leaves[0].leaf.id);
318
+ if (!refundSignature) {
319
+ throw new Error("Failed to get refund signature");
320
+ }
321
+ const { adaptorPrivateKey, adaptorSignature } = generateAdaptorFromSignature(refundSignature);
322
+ if (!transfer.leaves[0].leaf) {
323
+ throw new Error("Failed to get leaf");
324
+ }
325
+ const userLeaves = [];
326
+ userLeaves.push({
327
+ leaf_id: transfer.leaves[0].leaf.id,
328
+ raw_unsigned_refund_transaction: bytesToHex(transfer.leaves[0].intermediateRefundTx),
329
+ adaptor_added_signature: bytesToHex(adaptorSignature),
330
+ });
331
+ for (let i = 1; i < transfer.leaves.length; i++) {
332
+ const leaf = transfer.leaves[i];
333
+ if (!leaf?.leaf) {
334
+ throw new Error("Failed to get leaf");
335
+ }
336
+ const refundSignature = signatureMap.get(leaf.leaf.id);
337
+ if (!refundSignature) {
338
+ throw new Error("Failed to get refund signature");
339
+ }
340
+ const signature = generateSignatureFromExistingAdaptor(refundSignature, adaptorPrivateKey);
341
+ userLeaves.push({
342
+ leaf_id: leaf.leaf.id,
343
+ raw_unsigned_refund_transaction: bytesToHex(leaf.intermediateRefundTx),
344
+ adaptor_added_signature: bytesToHex(signature),
345
+ });
346
+ }
347
+ const adaptorPubkey = bytesToHex(secp256k1.getPublicKey(adaptorPrivateKey));
348
+ let request = null;
349
+ request = await this.sspClient?.requestLeaveSwap({
350
+ userLeaves,
351
+ adaptorPubkey,
352
+ targetAmountSats: targetAmount ||
353
+ leavesToSwap.reduce((acc, leaf) => acc + leaf.value, 0),
354
+ totalAmountSats: leavesToSwap.reduce((acc, leaf) => acc + leaf.value, 0),
355
+ // TODO: Request fee from SSP
356
+ feeSats: 0,
357
+ });
358
+ if (!request) {
359
+ throw new Error("Failed to request leaves swap. No response returned.");
360
+ }
361
+ const sparkClient = await this.connectionManager.createSparkClient(this.config.getCoordinatorAddress());
362
+ const nodes = await sparkClient.query_nodes({
363
+ source: {
364
+ $case: "nodeIds",
365
+ nodeIds: {
366
+ nodeIds: request.swapLeaves.map((leaf) => leaf.leafId),
367
+ },
368
+ },
369
+ includeParents: false,
370
+ });
371
+ if (Object.values(nodes.nodes).length !== request.swapLeaves.length) {
372
+ throw new Error("Expected same number of nodes as swapLeaves");
373
+ }
374
+ for (const [nodeId, node] of Object.entries(nodes.nodes)) {
375
+ if (!node.nodeTx) {
376
+ throw new Error(`Node tx not found for leaf ${nodeId}`);
377
+ }
378
+ if (!node.verifyingPublicKey) {
379
+ throw new Error(`Node public key not found for leaf ${nodeId}`);
380
+ }
381
+ const leaf = request.swapLeaves.find((leaf) => leaf.leafId === nodeId);
382
+ if (!leaf) {
383
+ throw new Error(`Leaf not found for node ${nodeId}`);
384
+ }
385
+ // @ts-ignore - We do a null check above
386
+ const nodeTx = getTxFromRawTxBytes(node.nodeTx);
387
+ const refundTxBytes = hexToBytes(leaf.rawUnsignedRefundTransaction);
388
+ const refundTx = getTxFromRawTxBytes(refundTxBytes);
389
+ const sighash = getSigHashFromTx(refundTx, 0, nodeTx.getOutput(0));
390
+ const nodePublicKey = node.verifyingPublicKey;
391
+ const taprootKey = computeTaprootKeyNoScript(nodePublicKey.slice(1));
392
+ const adaptorSignatureBytes = hexToBytes(leaf.adaptorSignedSignature);
393
+ applyAdaptorToSignature(taprootKey.slice(1), sighash, adaptorSignatureBytes, adaptorPrivateKey);
394
+ }
395
+ await this.transferService.sendTransferTweakKey(transfer, leafKeyTweaks, signatureMap);
396
+ const completeResponse = await this.sspClient?.completeLeaveSwap({
397
+ adaptorSecretKey: bytesToHex(adaptorPrivateKey),
398
+ userOutboundTransferExternalId: transfer.id,
399
+ leavesSwapRequestId: request.id,
400
+ });
401
+ if (!completeResponse) {
402
+ throw new Error("Failed to complete leaves swap");
403
+ }
404
+ await this.claimTransfers();
405
+ return completeResponse;
406
+ }
407
+ catch (e) {
408
+ await this.cancelAllSenderInitiatedTransfers();
409
+ throw new Error(`Failed to request leaves swap: ${e}`);
410
+ }
411
+ }
412
+ /**
413
+ * Gets all transfers for the wallet.
414
+ *
415
+ * @param {number} [limit=20] - Maximum number of transfers to return
416
+ * @param {number} [offset=0] - Offset for pagination
417
+ * @returns {Promise<QueryAllTransfersResponse>} Response containing the list of transfers
418
+ */
419
+ async getTransfers(limit = 20, offset = 0) {
420
+ return await this.transferService.queryAllTransfers(limit, offset);
421
+ }
422
+ /**
423
+ * Gets the current balance of the wallet.
424
+ * You can use the forceRefetch option to synchronize your wallet and claim any
425
+ * pending incoming lightning payment, spark transfer, or bitcoin deposit before returning the balance.
426
+ *
427
+ * @param {boolean} [forceRefetch=true] - Synchronizes the wallet before returning the balance
428
+ * @returns {Promise<Object>} Object containing:
429
+ * - balance: The wallet's current balance in satoshis
430
+ * - tokenBalances: Map of token balances and leaf counts
431
+ */
432
+ async getBalance(forceRefetch = true) {
433
+ if (forceRefetch) {
434
+ await Promise.all([this.claimTransfers(), this.syncTokenLeaves()]);
435
+ this.leaves = await this.getLeaves();
436
+ }
437
+ const tokenBalances = new Map();
438
+ for (const [tokenPublicKey, leaves] of this.tokenLeaves.entries()) {
439
+ tokenBalances.set(tokenPublicKey, {
440
+ balance: calculateAvailableTokenAmount(leaves),
441
+ });
442
+ }
443
+ return {
444
+ balance: this.leaves.reduce((acc, leaf) => acc + BigInt(leaf.value), 0n),
445
+ tokenBalances,
446
+ };
447
+ }
448
+ // ***** Deposit Flow *****
449
+ /**
450
+ * Generates a new deposit address for receiving bitcoin funds.
451
+ * Note that this function returns a bitcoin address, not a spark address.
452
+ * For Layer 1 Bitcoin deposits, Spark generates Pay to Taproot (P2TR) addresses.
453
+ * These addresses start with "bc1p" and can be used to receive Bitcoin from any wallet.
454
+ *
455
+ * @returns {Promise<string>} A Bitcoin address for depositing funds
456
+ */
457
+ async getDepositAddress() {
458
+ return await this.generateDepositAddress();
459
+ }
460
+ /**
461
+ * Generates a deposit address for receiving funds.
462
+ *
463
+ * @returns {Promise<string>} A deposit address
464
+ * @private
465
+ */
466
+ async generateDepositAddress() {
467
+ const signingPubkey = await this.config.signer.getDepositSigningKey();
468
+ const address = await this.depositService.generateDepositAddress({
469
+ signingPubkey,
470
+ });
471
+ if (!address.depositAddress) {
472
+ throw new Error("Failed to generate deposit address");
473
+ }
474
+ return address.depositAddress.address;
475
+ }
476
+ /**
477
+ * Finalizes a deposit to the wallet.
478
+ *
479
+ * @param {DepositParams} params - Parameters for finalizing the deposit
480
+ * @returns {Promise<TreeNode[] | undefined>} The nodes created from the deposit
481
+ * @private
482
+ */
483
+ async finalizeDeposit({ signingPubKey, verifyingKey, depositTx, vout, }) {
484
+ const response = await this.depositService.createTreeRoot({
485
+ signingPubKey,
486
+ verifyingKey,
487
+ depositTx,
488
+ vout,
489
+ });
490
+ return await this.transferDepositToSelf(response.nodes, signingPubKey);
491
+ }
492
+ /**
493
+ * Gets all unused deposit addresses for the wallet.
494
+ *
495
+ * @returns {Promise<string[]>} The unused deposit addresses
496
+ */
497
+ async getUnusedDepositAddresses() {
498
+ const sparkClient = await this.connectionManager.createSparkClient(this.config.getCoordinatorAddress());
499
+ return (await sparkClient.query_unused_deposit_addresses({
500
+ identityPublicKey: await this.config.signer.getIdentityPublicKey(),
501
+ })).depositAddresses.map((addr) => addr.depositAddress);
502
+ }
503
+ /**
504
+ * Claims a deposit to the wallet.
505
+ *
506
+ * @param {string} txid - The transaction ID of the deposit
507
+ * @returns {Promise<TreeNode[] | undefined>} The nodes resulting from the deposit
508
+ */
509
+ async claimDeposit(txid) {
510
+ const baseUrl = this.config.getNetwork() === Network.REGTEST
511
+ ? "https://regtest-mempool.dev.dev.sparkinfra.net/api"
512
+ : "https://mempool.space/api";
513
+ const auth = btoa("spark-sdk:mCMk1JqlBNtetUNy");
514
+ const headers = {
515
+ "Content-Type": "application/json",
516
+ };
517
+ if (this.config.getNetwork() === Network.REGTEST) {
518
+ headers["Authorization"] = `Basic ${auth}`;
519
+ }
520
+ const response = await fetch(`${baseUrl}/tx/${txid}/hex`, {
521
+ headers,
522
+ });
523
+ const txHex = await response.text();
524
+ if (!/^[0-9A-Fa-f]+$/.test(txHex)) {
525
+ throw new Error("Transaction not found");
526
+ }
527
+ const depositTx = getTxFromRawTxHex(txHex);
528
+ const sparkClient = await this.connectionManager.createSparkClient(this.config.getCoordinatorAddress());
529
+ const unusedDepositAddresses = new Map((await sparkClient.query_unused_deposit_addresses({
530
+ identityPublicKey: await this.config.signer.getIdentityPublicKey(),
531
+ })).depositAddresses.map((addr) => [addr.depositAddress, addr]));
532
+ let depositAddress;
533
+ let vout = 0;
534
+ for (let i = 0; i < depositTx.outputsLength; i++) {
535
+ const output = depositTx.getOutput(i);
536
+ if (!output) {
537
+ continue;
538
+ }
539
+ const parsedScript = OutScript.decode(output.script);
540
+ const address = Address(getNetwork(this.config.getNetwork())).encode(parsedScript);
541
+ if (unusedDepositAddresses.has(address)) {
542
+ vout = i;
543
+ depositAddress = unusedDepositAddresses.get(address);
544
+ break;
545
+ }
546
+ }
547
+ if (!depositAddress) {
548
+ throw new Error("Deposit address not found");
549
+ }
550
+ const nodes = await this.finalizeDeposit({
551
+ signingPubKey: depositAddress.userSigningPublicKey,
552
+ verifyingKey: depositAddress.verifyingPublicKey,
553
+ depositTx,
554
+ vout,
555
+ });
556
+ return nodes;
557
+ }
558
+ /**
559
+ * Transfers deposit to self to claim ownership.
560
+ *
561
+ * @param {TreeNode[]} leaves - The leaves to transfer
562
+ * @param {Uint8Array} signingPubKey - The signing public key
563
+ * @returns {Promise<TreeNode[] | undefined>} The nodes resulting from the transfer
564
+ * @private
565
+ */
566
+ async transferDepositToSelf(leaves, signingPubKey) {
567
+ const leafKeyTweaks = await Promise.all(leaves.map(async (leaf) => ({
568
+ leaf,
569
+ signingPubKey,
570
+ newSigningPubKey: await this.config.signer.generatePublicKey(),
571
+ })));
572
+ await this.transferService.sendTransfer(leafKeyTweaks, await this.config.signer.getIdentityPublicKey());
573
+ const pendingTransfers = await this.transferService.queryPendingTransfers();
574
+ if (pendingTransfers.transfers.length > 0) {
575
+ // @ts-ignore - We check the length, so the first element is guaranteed to exist
576
+ return (await this.claimTransfer(pendingTransfers.transfers[0])).nodes;
577
+ }
578
+ return;
579
+ }
580
+ // ***** Transfer Flow *****
581
+ /**
582
+ * Sends a transfer to another Spark user.
583
+ *
584
+ * @param {TransferParams} params - Parameters for the transfer
585
+ * @param {string} params.receiverSparkAddress - The recipient's Spark address
586
+ * @param {number} params.amountSats - Amount to send in satoshis
587
+ * @returns {Promise<Transfer>} The completed transfer details
588
+ */
589
+ async transfer({ amountSats, receiverSparkAddress }) {
590
+ return await this.withLeaves(async () => {
591
+ const leavesToSend = await this.selectLeaves(amountSats);
592
+ await this.refreshTimelockNodes();
593
+ const leafKeyTweaks = await Promise.all(leavesToSend.map(async (leaf) => ({
594
+ leaf,
595
+ signingPubKey: await this.config.signer.generatePublicKey(sha256(leaf.id)),
596
+ newSigningPubKey: await this.config.signer.generatePublicKey(),
597
+ })));
598
+ const transfer = await this.transferService.sendTransfer(leafKeyTweaks, hexToBytes(receiverSparkAddress));
599
+ const leavesToRemove = new Set(leavesToSend.map((leaf) => leaf.id));
600
+ this.leaves = this.leaves.filter((leaf) => !leavesToRemove.has(leaf.id));
601
+ return transfer;
602
+ });
603
+ }
604
+ /**
605
+ * Internal method to refresh timelock nodes.
606
+ *
607
+ * @param {string} nodeId - The optional ID of the node to refresh. If not provided, all nodes will be checked.
608
+ * @returns {Promise<void>}
609
+ * @private
610
+ */
611
+ async refreshTimelockNodes(nodeId) {
612
+ const nodesToRefresh = [];
613
+ const nodeIds = [];
614
+ if (nodeId) {
615
+ for (const node of this.leaves) {
616
+ if (node.id === nodeId) {
617
+ nodesToRefresh.push(node);
618
+ nodeIds.push(node.id);
619
+ break;
620
+ }
621
+ }
622
+ if (nodesToRefresh.length === 0) {
623
+ throw new Error(`node ${nodeId} not found`);
624
+ }
625
+ }
626
+ else {
627
+ for (const node of this.leaves) {
628
+ const refundTx = getTxFromRawTxBytes(node.refundTx);
629
+ const nextSequence = getNextTransactionSequence(refundTx.getInput(0).sequence);
630
+ const needRefresh = nextSequence <= 0;
631
+ if (needRefresh) {
632
+ nodesToRefresh.push(node);
633
+ nodeIds.push(node.id);
634
+ }
635
+ }
636
+ }
637
+ if (nodesToRefresh.length === 0) {
638
+ return;
639
+ }
640
+ const sparkClient = await this.connectionManager.createSparkClient(this.config.getCoordinatorAddress());
641
+ const nodesResp = await sparkClient.query_nodes({
642
+ source: {
643
+ $case: "nodeIds",
644
+ nodeIds: {
645
+ nodeIds,
646
+ },
647
+ },
648
+ includeParents: true,
649
+ });
650
+ const nodesMap = new Map();
651
+ for (const node of Object.values(nodesResp.nodes)) {
652
+ nodesMap.set(node.id, node);
653
+ }
654
+ for (const node of nodesToRefresh) {
655
+ if (!node.parentNodeId) {
656
+ throw new Error(`node ${node.id} has no parent`);
657
+ }
658
+ const parentNode = nodesMap.get(node.parentNodeId);
659
+ if (!parentNode) {
660
+ throw new Error(`parent node ${node.parentNodeId} not found`);
661
+ }
662
+ const { nodes } = await this.transferService.refreshTimelockNodes([node], parentNode, await this.config.signer.generatePublicKey(sha256(node.id)));
663
+ if (nodes.length !== 1) {
664
+ throw new Error(`expected 1 node, got ${nodes.length}`);
665
+ }
666
+ const newNode = nodes[0];
667
+ if (!newNode) {
668
+ throw new Error("Failed to refresh timelock node");
669
+ }
670
+ this.leaves = this.leaves.filter((leaf) => leaf.id !== node.id);
671
+ this.leaves.push(newNode);
672
+ }
673
+ }
674
+ /**
675
+ * Gets all pending transfers.
676
+ *
677
+ * @returns {Promise<Transfer[]>} The pending transfers
678
+ */
679
+ async getPendingTransfers() {
680
+ return (await this.transferService.queryPendingTransfers()).transfers;
681
+ }
682
+ /**
683
+ * Claims a specific transfer.
684
+ *
685
+ * @param {Transfer} transfer - The transfer to claim
686
+ * @returns {Promise<Object>} The claim result
687
+ */
688
+ async claimTransfer(transfer) {
689
+ return await this.claimTransferMutex.runExclusive(async () => {
690
+ const leafPubKeyMap = await this.transferService.verifyPendingTransfer(transfer);
691
+ let leavesToClaim = [];
692
+ for (const leaf of transfer.leaves) {
693
+ if (leaf.leaf) {
694
+ const leafPubKey = leafPubKeyMap.get(leaf.leaf.id);
695
+ if (leafPubKey) {
696
+ leavesToClaim.push({
697
+ leaf: leaf.leaf,
698
+ signingPubKey: leafPubKey,
699
+ newSigningPubKey: await this.config.signer.generatePublicKey(sha256(leaf.leaf.id)),
700
+ });
701
+ }
702
+ }
703
+ }
704
+ const response = await this.transferService.claimTransfer(transfer, leavesToClaim);
705
+ this.leaves.push(...response.nodes);
706
+ await this.refreshTimelockNodes();
707
+ return response.nodes;
708
+ });
709
+ }
710
+ /**
711
+ * Claims all pending transfers.
712
+ *
713
+ * @returns {Promise<boolean>} True if any transfers were claimed
714
+ */
715
+ async claimTransfers() {
716
+ const transfers = await this.transferService.queryPendingTransfers();
717
+ let claimed = false;
718
+ for (const transfer of transfers.transfers) {
719
+ if (transfer.status !== TransferStatus.TRANSFER_STATUS_SENDER_KEY_TWEAKED &&
720
+ transfer.status !==
721
+ TransferStatus.TRANSFER_STATUS_RECEIVER_KEY_TWEAKED &&
722
+ transfer.status !==
723
+ TransferStatus.TRANSFER_STATUSR_RECEIVER_REFUND_SIGNED) {
724
+ continue;
725
+ }
726
+ await this.claimTransfer(transfer);
727
+ claimed = true;
728
+ }
729
+ return claimed;
730
+ }
731
+ /**
732
+ * Cancels all sender-initiated transfers.
733
+ *
734
+ * @returns {Promise<void>}
735
+ * @private
736
+ */
737
+ async cancelAllSenderInitiatedTransfers() {
738
+ for (const operator of Object.values(this.config.getSigningOperators())) {
739
+ const transfers = await this.transferService.queryPendingTransfersBySender(operator.address);
740
+ for (const transfer of transfers.transfers) {
741
+ if (transfer.status === TransferStatus.TRANSFER_STATUS_SENDER_INITIATED) {
742
+ await this.transferService.cancelSendTransfer(transfer, operator.address);
743
+ }
744
+ }
745
+ }
746
+ }
747
+ // ***** Lightning Flow *****
748
+ /**
749
+ * Creates a Lightning invoice for receiving payments.
750
+ *
751
+ * @param {Object} params - Parameters for the lightning invoice
752
+ * @param {number} params.amountSats - Amount in satoshis
753
+ * @param {string} params.memo - Description for the invoice
754
+ * @param {number} [params.expirySeconds] - Optional expiry time in seconds
755
+ * @returns {Promise<string>} BOLT11 encoded invoice
756
+ */
757
+ async createLightningInvoice({ amountSats, memo, expirySeconds = 60 * 60 * 24 * 30, }) {
758
+ if (!this.sspClient) {
759
+ throw new Error("SSP client not initialized");
760
+ }
761
+ const requestLightningInvoice = async (amountSats, paymentHash, memo) => {
762
+ const network = this.config.getNetwork();
763
+ let bitcoinNetwork = BitcoinNetwork.REGTEST;
764
+ if (network === Network.MAINNET) {
765
+ bitcoinNetwork = BitcoinNetwork.MAINNET;
766
+ }
767
+ else if (network === Network.REGTEST) {
768
+ bitcoinNetwork = BitcoinNetwork.REGTEST;
769
+ }
770
+ const invoice = await this.sspClient.requestLightningReceive({
771
+ amountSats,
772
+ network: bitcoinNetwork,
773
+ paymentHash: bytesToHex(paymentHash),
774
+ expirySecs: expirySeconds,
775
+ memo,
776
+ });
777
+ return invoice?.invoice.encodedEnvoice;
778
+ };
779
+ return this.lightningService.createLightningInvoice({
780
+ amountSats,
781
+ memo,
782
+ invoiceCreator: requestLightningInvoice,
783
+ });
784
+ }
785
+ /**
786
+ * Pays a Lightning invoice.
787
+ *
788
+ * @param {Object} params - Parameters for paying the invoice
789
+ * @param {string} params.invoice - The BOLT11-encoded Lightning invoice to pay
790
+ * @returns {Promise<LightningSendRequest>} The Lightning payment request details
791
+ */
792
+ async payLightningInvoice({ invoice }) {
793
+ return await this.withLeaves(async () => {
794
+ if (!this.sspClient) {
795
+ throw new Error("SSP client not initialized");
796
+ }
797
+ // TODO: Get fee
798
+ const decodedInvoice = decode(invoice);
799
+ const amountSats = Number(decodedInvoice.sections.find((section) => section.name === "amount")
800
+ ?.value) / 1000;
801
+ if (isNaN(amountSats) || amountSats <= 0) {
802
+ throw new Error("Invalid amount");
803
+ }
804
+ const paymentHash = decodedInvoice.sections.find((section) => section.name === "payment_hash")?.value;
805
+ if (!paymentHash) {
806
+ throw new Error("No payment hash found in invoice");
807
+ }
808
+ const leaves = await this.selectLeaves(amountSats);
809
+ await this.refreshTimelockNodes();
810
+ const leavesToSend = await Promise.all(leaves.map(async (leaf) => ({
811
+ leaf,
812
+ signingPubKey: await this.config.signer.generatePublicKey(sha256(leaf.id)),
813
+ newSigningPubKey: await this.config.signer.generatePublicKey(),
814
+ })));
815
+ const swapResponse = await this.lightningService.swapNodesForPreimage({
816
+ leaves: leavesToSend,
817
+ receiverIdentityPubkey: await this.config.signer.getSspIdentityPublicKey(this.config.getNetwork()),
818
+ paymentHash: hexToBytes(paymentHash),
819
+ isInboundPayment: false,
820
+ invoiceString: invoice,
821
+ });
822
+ if (!swapResponse.transfer) {
823
+ throw new Error("Failed to swap nodes for preimage");
824
+ }
825
+ const transfer = await this.transferService.sendTransferTweakKey(swapResponse.transfer, leavesToSend, new Map());
826
+ const sspResponse = await this.sspClient.requestLightningSend({
827
+ encodedInvoice: invoice,
828
+ idempotencyKey: paymentHash,
829
+ });
830
+ if (!sspResponse) {
831
+ throw new Error("Failed to contact SSP");
832
+ }
833
+ const leavesToRemove = new Set(leavesToSend.map((leaf) => leaf.leaf.id));
834
+ this.leaves = this.leaves.filter((leaf) => !leavesToRemove.has(leaf.id));
835
+ return sspResponse;
836
+ });
837
+ }
838
+ /**
839
+ * Gets fee estimate for receiving Lightning payments.
840
+ *
841
+ * @param {LightningReceiveFeeEstimateInput} params - Input parameters for fee estimation
842
+ * @returns {Promise<LightningReceiveFeeEstimateOutput | null>} Fee estimate for receiving Lightning payments
843
+ */
844
+ async getLightningReceiveFeeEstimate({ amountSats, network, }) {
845
+ if (!this.sspClient) {
846
+ throw new Error("SSP client not initialized");
847
+ }
848
+ return await this.sspClient.getLightningReceiveFeeEstimate(amountSats, network);
849
+ }
850
+ /**
851
+ * Gets fee estimate for sending Lightning payments.
852
+ *
853
+ * @param {LightningSendFeeEstimateInput} params - Input parameters for fee estimation
854
+ * @returns {Promise<LightningSendFeeEstimateOutput | null>} Fee estimate for sending Lightning payments
855
+ */
856
+ async getLightningSendFeeEstimate({ encodedInvoice, }) {
857
+ if (!this.sspClient) {
858
+ throw new Error("SSP client not initialized");
859
+ }
860
+ return await this.sspClient.getLightningSendFeeEstimate(encodedInvoice);
861
+ }
862
+ // ***** Tree Creation Flow *****
863
+ /**
864
+ * Generates a deposit address for a tree.
865
+ *
866
+ * @param {number} vout - The vout index
867
+ * @param {Uint8Array} parentSigningPubKey - The parent signing public key
868
+ * @param {Transaction} [parentTx] - Optional parent transaction
869
+ * @param {TreeNode} [parentNode] - Optional parent node
870
+ * @returns {Promise<Object>} Deposit address information
871
+ * @private
872
+ */
873
+ async generateDepositAddressForTree(vout, parentSigningPubKey, parentTx, parentNode) {
874
+ return await this.treeCreationService.generateDepositAddressForTree(vout, parentSigningPubKey, parentTx, parentNode);
875
+ }
876
+ /**
877
+ * Creates a tree structure.
878
+ *
879
+ * @param {number} vout - The vout index
880
+ * @param {DepositAddressTree} root - The root of the tree
881
+ * @param {boolean} createLeaves - Whether to create leaves
882
+ * @param {Transaction} [parentTx] - Optional parent transaction
883
+ * @param {TreeNode} [parentNode] - Optional parent node
884
+ * @returns {Promise<Object>} The created tree
885
+ * @private
886
+ */
887
+ async createTree(vout, root, createLeaves, parentTx, parentNode) {
888
+ return await this.treeCreationService.createTree(vout, root, createLeaves, parentTx, parentNode);
889
+ }
890
+ // ***** Cooperative Exit Flow *****
891
+ /**
892
+ * Initiates a withdrawal to move funds from the Spark network to an on-chain Bitcoin address.
893
+ *
894
+ * @param {Object} params - Parameters for the withdrawal
895
+ * @param {string} params.onchainAddress - The Bitcoin address where the funds should be sent
896
+ * @param {number} [params.targetAmountSats] - The amount in satoshis to withdraw. If not specified, attempts to withdraw all available funds
897
+ * @returns {Promise<CoopExitRequest | null | undefined>} The withdrawal request details, or null/undefined if the request cannot be completed
898
+ */
899
+ async withdraw({ onchainAddress, targetAmountSats, }) {
900
+ return await this.withLeaves(async () => {
901
+ return await this.coopExit(onchainAddress, targetAmountSats);
902
+ });
903
+ }
904
+ /**
905
+ * Internal method to perform a cooperative exit (withdrawal).
906
+ *
907
+ * @param {string} onchainAddress - The Bitcoin address where the funds should be sent
908
+ * @param {number} [targetAmountSats] - The amount in satoshis to withdraw
909
+ * @returns {Promise<Object | null | undefined>} The exit request details
910
+ * @private
911
+ */
912
+ async coopExit(onchainAddress, targetAmountSats) {
913
+ let leavesToSend = [];
914
+ if (targetAmountSats) {
915
+ leavesToSend = await this.selectLeaves(targetAmountSats);
916
+ }
917
+ else {
918
+ leavesToSend = this.leaves.map((leaf) => ({
919
+ ...leaf,
920
+ }));
921
+ }
922
+ const leafKeyTweaks = await Promise.all(leavesToSend.map(async (leaf) => ({
923
+ leaf,
924
+ signingPubKey: await this.config.signer.generatePublicKey(sha256(leaf.id)),
925
+ newSigningPubKey: await this.config.signer.generatePublicKey(),
926
+ })));
927
+ const coopExitRequest = await this.sspClient?.requestCoopExit({
928
+ leafExternalIds: leavesToSend.map((leaf) => leaf.id),
929
+ withdrawalAddress: onchainAddress,
930
+ });
931
+ if (!coopExitRequest?.rawConnectorTransaction) {
932
+ throw new Error("Failed to request coop exit");
933
+ }
934
+ const connectorTx = getTxFromRawTxHex(coopExitRequest.rawConnectorTransaction);
935
+ const coopExitTxId = connectorTx.getInput(0).txid;
936
+ const connectorTxId = getTxId(connectorTx);
937
+ if (!coopExitTxId) {
938
+ throw new Error("Failed to get coop exit tx id");
939
+ }
940
+ const connectorOutputs = [];
941
+ for (let i = 0; i < connectorTx.outputsLength - 1; i++) {
942
+ connectorOutputs.push({
943
+ txid: hexToBytes(connectorTxId),
944
+ index: i,
945
+ });
946
+ }
947
+ const sspPubIdentityKey = await this.config.signer.getSspIdentityPublicKey(this.config.getNetwork());
948
+ const transfer = await this.coopExitService.getConnectorRefundSignatures({
949
+ leaves: leafKeyTweaks,
950
+ exitTxId: coopExitTxId,
951
+ connectorOutputs,
952
+ receiverPubKey: sspPubIdentityKey,
953
+ });
954
+ const completeResponse = await this.sspClient?.completeCoopExit({
955
+ userOutboundTransferExternalId: transfer.transfer.id,
956
+ coopExitRequestId: coopExitRequest.id,
957
+ });
958
+ return completeResponse;
959
+ }
960
+ /**
961
+ * Gets fee estimate for cooperative exit (on-chain withdrawal).
962
+ *
963
+ * @param {CoopExitFeeEstimateInput} params - Input parameters for fee estimation
964
+ * @returns {Promise<CoopExitFeeEstimateOutput | null>} Fee estimate for the withdrawal
965
+ */
966
+ async getCoopExitFeeEstimate({ leafExternalIds, withdrawalAddress, }) {
967
+ if (!this.sspClient) {
968
+ throw new Error("SSP client not initialized");
969
+ }
970
+ return await this.sspClient.getCoopExitFeeEstimate({
971
+ leafExternalIds,
972
+ withdrawalAddress,
973
+ });
974
+ }
975
+ // ***** Token Flow *****
976
+ /**
977
+ * Synchronizes token leaves for the wallet.
978
+ *
979
+ * @returns {Promise<void>}
980
+ * @private
981
+ */
982
+ async syncTokenLeaves() {
983
+ this.tokenLeaves.clear();
984
+ const trackedPublicKeys = await this.config.signer.getTrackedPublicKeys();
985
+ const unsortedTokenLeaves = await this.tokenTransactionService.fetchOwnedTokenLeaves([...trackedPublicKeys, await this.config.signer.getIdentityPublicKey()], []);
986
+ // Group leaves by token key
987
+ const groupedLeaves = new Map();
988
+ unsortedTokenLeaves.forEach((leaf) => {
989
+ const tokenKey = bytesToHex(leaf.leaf.tokenPublicKey);
990
+ const index = leaf.previousTransactionVout;
991
+ if (!groupedLeaves.has(tokenKey)) {
992
+ groupedLeaves.set(tokenKey, []);
993
+ }
994
+ groupedLeaves.get(tokenKey).push({
995
+ ...leaf,
996
+ previousTransactionVout: index,
997
+ });
998
+ });
999
+ this.tokenLeaves = groupedLeaves;
1000
+ }
1001
+ /**
1002
+ * Gets all token balances.
1003
+ *
1004
+ * @returns {Promise<Map<string, { balance: bigint }>>} Map of token balances and leaf counts
1005
+ * @private
1006
+ */
1007
+ async getAllTokenBalances() {
1008
+ await this.syncTokenLeaves();
1009
+ const balances = new Map();
1010
+ for (const [tokenPublicKey, leaves] of this.tokenLeaves.entries()) {
1011
+ balances.set(tokenPublicKey, {
1012
+ balance: calculateAvailableTokenAmount(leaves),
1013
+ });
1014
+ }
1015
+ return balances;
1016
+ }
1017
+ /**
1018
+ * Transfers tokens to another user.
1019
+ *
1020
+ * @param {Object} params - Parameters for the token transfer
1021
+ * @param {string} params.tokenPublicKey - The public key of the token to transfer
1022
+ * @param {bigint} params.tokenAmount - The amount of tokens to transfer
1023
+ * @param {string} params.receiverSparkAddress - The recipient's public key
1024
+ * @param {LeafWithPreviousTransactionData[]} [params.selectedLeaves] - Optional specific leaves to use for the transfer
1025
+ * @returns {Promise<string>} The transaction ID of the token transfer
1026
+ */
1027
+ async transferTokens({ tokenPublicKey, tokenAmount, receiverSparkAddress, selectedLeaves, }) {
1028
+ await this.syncTokenLeaves();
1029
+ if (!this.tokenLeaves.has(tokenPublicKey)) {
1030
+ throw new Error("No token leaves with the given tokenPublicKey");
1031
+ }
1032
+ const tokenPublicKeyBytes = hexToBytes(tokenPublicKey);
1033
+ const receiverSparkAddressBytes = hexToBytes(receiverSparkAddress);
1034
+ if (selectedLeaves) {
1035
+ if (!checkIfSelectedLeavesAreAvailable(selectedLeaves, this.tokenLeaves, tokenPublicKeyBytes)) {
1036
+ throw new Error("One or more selected leaves are not available");
1037
+ }
1038
+ }
1039
+ else {
1040
+ selectedLeaves = this.selectTokenLeaves(tokenPublicKey, tokenAmount);
1041
+ }
1042
+ if (selectedLeaves.length > MAX_TOKEN_LEAVES) {
1043
+ throw new Error("Too many leaves selected");
1044
+ }
1045
+ const tokenTransaction = await this.tokenTransactionService.constructTransferTokenTransaction(selectedLeaves, receiverSparkAddressBytes, tokenPublicKeyBytes, tokenAmount);
1046
+ return await this.tokenTransactionService.broadcastTokenTransaction(tokenTransaction, selectedLeaves.map((leaf) => leaf.leaf.ownerPublicKey), selectedLeaves.map((leaf) => leaf.leaf.revocationPublicKey));
1047
+ }
1048
+ /**
1049
+ * Selects token leaves for a transfer.
1050
+ *
1051
+ * @param {string} tokenPublicKey - The public key of the token
1052
+ * @param {bigint} tokenAmount - The amount of tokens to select leaves for
1053
+ * @returns {LeafWithPreviousTransactionData[]} The selected leaves
1054
+ * @private
1055
+ */
1056
+ selectTokenLeaves(tokenPublicKey, tokenAmount) {
1057
+ return this.tokenTransactionService.selectTokenLeaves(this.tokenLeaves.get(tokenPublicKey), tokenAmount);
1058
+ }
1059
+ async withdrawTokens(tokenPublicKey, receiverPublicKey, leafIds) {
1060
+ if (!this.lrc20Wallet) {
1061
+ throw new Error("LRC20 wallet not initialized");
1062
+ }
1063
+ await this.syncTokenLeaves();
1064
+ let leavesToExit = this.tokenLeaves.get(tokenPublicKey);
1065
+ if (leavesToExit && leafIds) {
1066
+ leavesToExit = leavesToExit.filter(({ leaf }) => leafIds.findIndex((leafId) => leafId == leaf.id) != -1);
1067
+ }
1068
+ if (!leavesToExit) {
1069
+ throw new Error("No leaves to exit");
1070
+ }
1071
+ if (!receiverPublicKey) {
1072
+ receiverPublicKey = await this.getIdentityPublicKey();
1073
+ }
1074
+ try {
1075
+ return await broadcastL1Withdrawal(this.lrc20Wallet, leavesToExit, receiverPublicKey);
1076
+ }
1077
+ catch (err) {
1078
+ if (err.message === "Not enough UTXOs") {
1079
+ console.error("Error: No L1 UTXOs available to cover exit fees. Please send sats to the address associated with your Wallet:", this.lrc20Wallet.p2wpkhAddress);
1080
+ }
1081
+ else {
1082
+ console.error("Unexpected error:", err);
1083
+ }
1084
+ return;
1085
+ }
1086
+ }
1087
+ }
1088
+ /**
1089
+ * Utility function to determine the network from a Bitcoin address.
1090
+ *
1091
+ * @param {string} address - The Bitcoin address
1092
+ * @returns {BitcoinNetwork | null} The detected network or null if not detected
1093
+ */
1094
+ function getNetworkFromAddress(address) {
1095
+ try {
1096
+ const decoded = bitcoin.address.fromBech32(address);
1097
+ // HRP (human-readable part) determines the network
1098
+ if (decoded.prefix === "bc") {
1099
+ return BitcoinNetwork.MAINNET;
1100
+ }
1101
+ else if (decoded.prefix === "bcrt") {
1102
+ return BitcoinNetwork.REGTEST;
1103
+ }
1104
+ }
1105
+ catch (err) {
1106
+ throw new Error("Invalid Bitcoin address");
1107
+ }
1108
+ return null;
1109
+ }
1110
+ //# sourceMappingURL=spark-sdk.js.map