@buildonspark/issuer-sdk 0.0.13 → 0.0.15

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