@laceio/sdk 0.1.0 → 0.1.1-canary.0

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 (408) hide show
  1. package/dist/{Ed25519PublicKey-lvu1s54U.cjs → Address-AMKTo-dA.cjs} +17150 -61
  2. package/dist/{Ed25519PublicKey-CjnuAYRR.js → Address-_c_-9hLC.js} +16955 -264
  3. package/dist/{Bip32Account-r3KAhCgU.js → Bip32Account-CaW1zC9Y.js} +4 -5
  4. package/dist/{Bip32Account-Cz3h0ZUa.cjs → Bip32Account-DOaGmKpv.cjs} +4 -5
  5. package/dist/Cardano-B-gyqBBD.js +311 -0
  6. package/dist/Cardano-BQ_af0Y3.cjs +322 -0
  7. package/dist/Ed25519PublicKey-B3QcR0J2.cjs +88 -0
  8. package/dist/Ed25519PublicKey-DIE19xHg.js +83 -0
  9. package/dist/InMemoryKeyAgent-Bc_xZY-v.cjs +652 -0
  10. package/dist/InMemoryKeyAgent-D8T3vtXy.js +631 -0
  11. package/dist/{PaymentAddress-DhbtuYb7.cjs → PaymentAddress-B4n1KZMx.cjs} +1 -2
  12. package/dist/{PaymentAddress-xSmGUQ-8.js → PaymentAddress-Cml3EA1n.js} +1 -2
  13. package/dist/Percent-Cfuw5YyL.cjs +11 -0
  14. package/dist/Percent-DpvyJ_93.js +5 -0
  15. package/dist/SodiumBip32Ed25519-BaD-kjyx.cjs +380 -0
  16. package/dist/SodiumBip32Ed25519-DCikAMsl.js +363 -0
  17. package/dist/{TransactionBuilder-CeJTNzm-.cjs → TransactionBuilder-BakTJvsJ.cjs} +59 -89
  18. package/dist/{TransactionBuilder-DGNDM4kt.js → TransactionBuilder-D2ErwVWv.js} +5 -71
  19. package/dist/_md-6zV2Cme0.cjs +684 -0
  20. package/dist/_md-gbUqlhqd.js +399 -0
  21. package/dist/_web-crypto-random-bytes-BvzwTYPG.js +197 -0
  22. package/dist/acc-module-NL_8mEHH.cjs +27654 -0
  23. package/dist/acc-module-ur8CkBd1.js +27624 -0
  24. package/dist/account-call-B7cF8ly4.cjs +293 -0
  25. package/dist/account-call-BF4rBcNw.js +3 -0
  26. package/dist/account-call-CoCq3V55.js +252 -0
  27. package/dist/account-call-DFcD257E.cjs +4 -0
  28. package/dist/account-guards-BeKbV9D1.cjs +41 -0
  29. package/dist/account-guards-qnFXuXSE.js +36 -0
  30. package/dist/{activity-type.stable-ClO9j_PH.cjs → activity-type-BPXxdHBP.cjs} +2 -1
  31. package/dist/{activity-type.stable-Ml0SOYv9.js → activity-type-C1geyPsH.js} +2 -1
  32. package/dist/address-OxwXIwbF.js +15502 -0
  33. package/dist/address-book-address-validator-BqYM0Uyp.cjs +41 -0
  34. package/dist/{address-book-address-validator-BhqRfmlL.cjs → address-book-address-validator-CGIcqn5W.cjs} +5 -4
  35. package/dist/{address-book-address-validator-VqIOB8PY.js → address-book-address-validator-FkkYim3z.js} +6 -4
  36. package/dist/address-book-address-validator-RSx2Jozy.js +39 -0
  37. package/dist/address-lECYBd9-.cjs +13043 -0
  38. package/dist/{apply-vkey-witnesses-Ctzk7eye.cjs → apply-vkey-witnesses-1jyczTkw.cjs} +1 -1
  39. package/dist/{apply-vkey-witnesses-Dfo7XfhL.js → apply-vkey-witnesses-Byb40-yJ.js} +1 -1
  40. package/dist/artefact-loader-Cqc9eSkL.cjs +182 -0
  41. package/dist/artefact-loader-D0T2f6F7.js +159 -0
  42. package/dist/auto-dismiss-failure-on-success-BWJceNXd.cjs +37 -0
  43. package/dist/auto-dismiss-failure-on-success-Bpod-v4r.js +31 -0
  44. package/dist/bip32-EPpcFrpH.cjs +3851 -0
  45. package/dist/{bip32ed25519-D2In8WzR.cjs → bip32ed25519-CRiG-Kjg.cjs} +5 -4
  46. package/dist/{bip32ed25519-qsLH_eWO.js → bip32ed25519-E-fCUZNv.js} +6 -4
  47. package/dist/bip39-DZomfqeY.js +9 -0
  48. package/dist/bip39-MAck9iod.cjs +26 -0
  49. package/dist/bitcoin-data-provider-D0OT_Uiu.cjs +26 -0
  50. package/dist/bitcoin-data-provider-LN_8oamW.js +21 -0
  51. package/dist/bitcoin.cjs +48 -0
  52. package/dist/bitcoin.d.ts +29805 -1
  53. package/dist/bitcoin.js +22 -0
  54. package/dist/{blake2b-BGHUWMsV.js → blake2b-BL-eR5G2.js} +6 -4
  55. package/dist/{blake2b-DspUqw68.cjs → blake2b-Iy324FwH.cjs} +5 -4
  56. package/dist/{blockfrost-tx-submit-provider-BUEOmdvc.js → blockfrost-tx-submit-provider-BHDLgOIE.js} +9 -162
  57. package/dist/{blockfrost-tx-submit-provider-B5dWbdrZ.cjs → blockfrost-tx-submit-provider-BxC19smv.cjs} +7 -171
  58. package/dist/{blockingWithLatestFrom-BhaE7pnA.js → blockingWithLatestFrom-FUfZFEUG.js} +1 -1
  59. package/dist/{blockingWithLatestFrom-DkuT3G2a.cjs → blockingWithLatestFrom-bmCPgA3c.cjs} +1 -1
  60. package/dist/bn-BFq5a4dk.cjs +2553 -0
  61. package/dist/{SodiumBip32Ed25519-BEfo1Q9m.js → browser-D5jRKv_L.js} +4 -401
  62. package/dist/bytes.vo-CziaOsba.js +24 -0
  63. package/dist/bytes.vo-hecRu3YZ.cjs +35 -0
  64. package/dist/{cardano-network-id-to-network-type-PXvn1ycQ.cjs → cardano-network-id-to-network-type-BwG_d6QP.cjs} +1 -1
  65. package/dist/{cardano-network-id-to-network-type-DHgKhDAK.js → cardano-network-id-to-network-type-CYJheetp.js} +1 -1
  66. package/dist/{cardano-network-id.vo-CbNNKd-k.cjs → cardano-network-id.vo-C5VuBXT3.cjs} +2 -2
  67. package/dist/{cardano-network-id.vo-CTYe-Oix.js → cardano-network-id.vo-CeLJqmb_.js} +2 -2
  68. package/dist/{cardano-tx-id.vo-BMwemq5x.js → cardano-tx-id.vo-DJ70NC0-.js} +1 -1
  69. package/dist/{cardano-tx-id.vo-NY-gCOWJ.cjs → cardano-tx-id.vo-lnyO9XaW.cjs} +1 -1
  70. package/dist/cardano.cjs +31 -24
  71. package/dist/cardano.d.ts +27602 -8121
  72. package/dist/cardano.js +21 -13
  73. package/dist/client-Bw2foG5E.cjs +808 -0
  74. package/dist/const-BB3MccLt.js +153 -0
  75. package/dist/{const-BErUlcZw.cjs → const-BWBAzOmN.cjs} +1 -1
  76. package/dist/const-CSWmOyzn.cjs +42 -0
  77. package/dist/{const-Dy8Ctnpd.cjs → const-D3mCkwrM.cjs} +5 -5
  78. package/dist/const-DW7z3R5k.js +13 -0
  79. package/dist/{const-DeUA7zYl.js → const-DbuUHSzR.js} +5 -5
  80. package/dist/const-DgBzKfz6.cjs +31995 -0
  81. package/dist/{const-DVW6DGkZ.js → const-xGSNCtwQ.js} +1 -1
  82. package/dist/contract-BsIGhsYa.js +171 -0
  83. package/dist/contract-DD6CGnpB.cjs +189 -0
  84. package/dist/create-add-accounts-2mQA0ST2.js +102 -0
  85. package/dist/create-add-accounts-B6mR2NMn.cjs +114 -0
  86. package/dist/{delegation-tx-builder-CF0VunDW.cjs → delegation-tx-builder-Cp30jtj9.cjs} +9 -8
  87. package/dist/{delegation-tx-builder-C8LQxU2R.js → delegation-tx-builder-DUMikSTg.js} +9 -7
  88. package/dist/{deregistration-tx-builder-DcUXA3Ls.cjs → deregistration-tx-builder-B-ZeY-dR.cjs} +10 -9
  89. package/dist/{deregistration-tx-builder-BOBPP8m_.js → deregistration-tx-builder-CRLrK99U.js} +10 -8
  90. package/dist/device-commitment-hex.vo-BIUYUNz1.cjs +31 -0
  91. package/dist/device-commitment-hex.vo-D9FsYLn7.js +26 -0
  92. package/dist/device-key-BToCoS4D.js +2394 -0
  93. package/dist/device-key-D6euvxFi.cjs +2489 -0
  94. package/dist/device-readers-BHJeNR8I.js +3 -0
  95. package/dist/device-readers-Dw7uTNM5.cjs +167 -0
  96. package/dist/device-readers-b4g2j3QL.js +144 -0
  97. package/dist/device-readers-cxcJcWq5.cjs +7 -0
  98. package/dist/dist-B00GN41m.js +141 -0
  99. package/dist/dist-BA1xnF9O.cjs +4413 -0
  100. package/dist/dist-BmHOXLe8.cjs +3814 -0
  101. package/dist/dist-Br0OVXKt.cjs +535 -0
  102. package/dist/dist-C1JK9C1I.cjs +3452 -0
  103. package/dist/dist-DKEViNEI.cjs +1306 -0
  104. package/dist/dist-Dwqx184a.cjs +43175 -0
  105. package/dist/dist-MJof_Ky1.cjs +145 -0
  106. package/dist/dist-p84sVVJ9.cjs +1394 -0
  107. package/dist/{earn-rewards-tx-builder-BRlTueHS.js → earn-rewards-tx-builder-8G_rouIk.js} +9 -7
  108. package/dist/{earn-rewards-tx-builder-RgO0QUY8.cjs → earn-rewards-tx-builder-cOUNV58E.cjs} +9 -8
  109. package/dist/enc-key-circuits-0Dud78IB.js +13 -0
  110. package/dist/enc-key-circuits-yjPHbuo_.cjs +24 -0
  111. package/dist/english-BZ_ebp2-.cjs +2057 -0
  112. package/dist/envelopes-B3QCzo5p.js +2658 -0
  113. package/dist/envelopes-BdE1xlgz.cjs +2777 -0
  114. package/dist/errors-BA3b8aVu.cjs +584 -0
  115. package/dist/errors-pkQdxW-7.js +392 -0
  116. package/dist/experimental.cjs +6820 -0
  117. package/dist/experimental.d.ts +63552 -0
  118. package/dist/experimental.js +6670 -0
  119. package/dist/fees-6C2uEWFK.js +653 -0
  120. package/dist/fees-DtC71fOx.cjs +820 -0
  121. package/dist/gated-call-BrPjKolT.js +3 -0
  122. package/dist/gated-call-CcsuW9L5.js +691 -0
  123. package/dist/gated-call-DdDrxEq5.cjs +732 -0
  124. package/dist/gated-call-Dk7PazhG.cjs +4 -0
  125. package/dist/grant-rules-B7eDuD5G.cjs +5468 -0
  126. package/dist/grant-rules-qLrKUIR3.js +5217 -0
  127. package/dist/grant-status-CDmZpx32.js +296 -0
  128. package/dist/grant-status-CQtwjLsA.cjs +337 -0
  129. package/dist/grants-Bnb-3Hkv.cjs +16 -0
  130. package/dist/grants-CIb6nOV7.cjs +273 -0
  131. package/dist/grants-CYY0AquW.js +202 -0
  132. package/dist/grants-DOsFSotP.js +4 -0
  133. package/dist/{group-cardano-addresses-by-account-C-1GHUu8.cjs → group-cardano-addresses-by-account-BGOtPV-Y.cjs} +4 -40
  134. package/dist/{group-cardano-addresses-by-account-p4dXmCoj.js → group-cardano-addresses-by-account-TqvESg9x.js} +6 -37
  135. package/dist/{guarded-transaction-signer-DZSGHp1K.js → guarded-transaction-signer-BbVDE9Nn.js} +12 -18
  136. package/dist/{guarded-transaction-signer-BLSezbfV.cjs → guarded-transaction-signer-DTLjAkif.cjs} +26 -26
  137. package/dist/hex-BVtOKJki.cjs +263 -0
  138. package/dist/hex-CGYJPK_Z.js +192 -0
  139. package/dist/http-client-B7_kBTYn.js +155 -0
  140. package/dist/http-client-DYQ_7Rdf.cjs +167 -0
  141. package/dist/identity-DxPhxkZs.js +239 -0
  142. package/dist/identity-y41Yle03.cjs +274 -0
  143. package/dist/in-memory-wallet-integration-5BKiAvPT.js +20861 -0
  144. package/dist/{in-memory-wallet-integration-CUTa68ET.js → in-memory-wallet-integration-BCOqDgbt.js} +10 -107
  145. package/dist/in-memory-wallet-integration-Bi8I9Dso.js +128 -0
  146. package/dist/in-memory-wallet-integration-Bsl2ONua.cjs +239 -0
  147. package/dist/in-memory-wallet-integration-DZ0CAyvY.cjs +20865 -0
  148. package/dist/{in-memory-wallet-integration-Dw_S7amX.cjs → in-memory-wallet-integration-DsFm8gLk.cjs} +21 -112
  149. package/dist/{in-memory-wallet-integration-Z4Bp_DTv.cjs → in-memory-wallet-integration-aW_SF-go.cjs} +8 -5
  150. package/dist/{in-memory-wallet-integration-B6cbAlvD.js → in-memory-wallet-integration-mIEc8EfR.js} +9 -5
  151. package/dist/index.cjs +95 -58
  152. package/dist/index.d.ts +45152 -13448
  153. package/dist/index.js +55 -28
  154. package/dist/{init-CVi8J0zk.cjs → init-5SfWgCYD.cjs} +3 -3
  155. package/dist/{init-Ci7aqWCf2.cjs → init-8NVWbo302.cjs} +2 -2
  156. package/dist/init-B-C7n6u6.js +5 -0
  157. package/dist/{init-BFMWRf-L.js → init-B-ppfGO-.js} +1 -1
  158. package/dist/{init-IiR093Jw.cjs → init-B2OUhY5T.cjs} +2 -2
  159. package/dist/{init-DXnus199.cjs → init-B6Eg_o6G.cjs} +5 -5
  160. package/dist/{init-4hDl5bpr.js → init-BAWMHL1k.js} +2 -2
  161. package/dist/init-BC2CZZOu2.cjs +2002 -0
  162. package/dist/{init-a228hXnS.cjs → init-BF-a2p6E.cjs} +65 -73
  163. package/dist/{init-fFirX8OY.cjs → init-BFxlQAD8.cjs} +1 -1
  164. package/dist/init-BJE1ry0O.js +17 -0
  165. package/dist/{init-BVnI4z2J.js → init-BPKBVOHU.js} +2 -2
  166. package/dist/{init-bdqZBd-o.js → init-BSP_xcpB.js} +2 -2
  167. package/dist/{init-CFNOn3lo.js → init-BSd7mznK.js} +3 -3
  168. package/dist/{init-MjR4swi6.js → init-BUJTT0MN.js} +36 -43
  169. package/dist/init-BUpFzYsD.cjs +143 -0
  170. package/dist/{init-BvpYHyLH.cjs → init-BZ-WyAIL.cjs} +3 -3
  171. package/dist/init-BZdfdLX7.js +422 -0
  172. package/dist/{init-CJeOys1w.cjs → init-B_HWNXMD.cjs} +2 -2
  173. package/dist/init-BbIMt6xU.cjs +6 -0
  174. package/dist/{init-BYdN1aqE.cjs → init-BewG6swt.cjs} +2 -2
  175. package/dist/{init-BX0AZAVH2.js → init-Bilqsbng.js} +2 -2
  176. package/dist/{init-Tpn9VkFu.cjs → init-BpwlQ6wF.cjs} +1 -1
  177. package/dist/{init-D5-P0HXK.js → init-BtQOzUjX.js} +1 -1
  178. package/dist/{init-BvGz3qUd2.js → init-CCTscPaY2.js} +2 -2
  179. package/dist/{init-D4hPipCD.cjs → init-CH0yyBof.cjs} +1 -1
  180. package/dist/init-CaIkrXal.cjs +121 -0
  181. package/dist/init-CkZy4IMf.cjs +107 -0
  182. package/dist/{init-Drr2f_Pr.js → init-CmfcY7SV.js} +1 -1
  183. package/dist/{init-Kf3_OLv6.js → init-CnJAlks_.js} +1 -1
  184. package/dist/{init-Cdjt_z-b.cjs → init-CqqmtAIK.cjs} +4 -4
  185. package/dist/{init-Bb0avZeZ.js → init-Cu2znmIc.js} +5 -5
  186. package/dist/init-Cz5LAizN.js +2001 -0
  187. package/dist/init-D4WM3-Mn.cjs +18 -0
  188. package/dist/init-DMi2FGpf.cjs +424 -0
  189. package/dist/{init-lcaUSOOG.js → init-DPTJohPd.js} +1 -1
  190. package/dist/{init-BTYLMF9F2.cjs → init-DexLSprL2.cjs} +258 -61
  191. package/dist/init-DfKPgD21.js +106 -0
  192. package/dist/init-DgzRsI-C.js +141 -0
  193. package/dist/init-Dj4Cn7-P.js +4789 -0
  194. package/dist/init-DktAnYI0.cjs +2354 -0
  195. package/dist/{init-DFwhgert.cjs → init-DmyuM9Lo.cjs} +1 -1
  196. package/dist/{init-CX_zLXc6.js → init-IBnizp1U.js} +5 -5
  197. package/dist/init-MDKB6tGI2.cjs +4790 -0
  198. package/dist/{init-DbZ5byj42.js → init-TbB38KNt2.js} +258 -60
  199. package/dist/init-X6m_cqDy.js +2353 -0
  200. package/dist/{init-DvVgKCaP2.cjs → init-bzvl1JhF.cjs} +2 -2
  201. package/dist/{init-BgrY29gW.js → init-dsYkC_0B.js} +4 -4
  202. package/dist/{init-B5BsI3DR.cjs → init-kvn5FlPS.cjs} +7 -7
  203. package/dist/init-vfy9DW_E.js +119 -0
  204. package/dist/{init-BE_6Jyc4.js → init-w7xl6LsP.js} +3 -3
  205. package/dist/{init-DEsWVyn5.cjs → init-wgiBUmyW.cjs} +1 -1
  206. package/dist/{is-retriable-error-DWv_ob-f.js → is-retriable-error-CmFR20pe.js} +1 -1
  207. package/dist/{is-retriable-error-Dtb4JGjd.cjs → is-retriable-error-D2yo0_lS.cjs} +1 -1
  208. package/dist/jubjub-authoriser-A2c8vmkN.js +84 -0
  209. package/dist/jubjub-authoriser-D3ZDgzcF.cjs +85 -0
  210. package/dist/key-source-CcLTx8HK.js +2761 -0
  211. package/dist/key-source-D2tTAag-.cjs +806 -0
  212. package/dist/{key-value-store-DTX1quRS.js → key-value-store-DZcNDB3n.js} +1 -1
  213. package/dist/{key-value-store-B-XRIwaM.cjs → key-value-store-Htj4RgMe.cjs} +1 -1
  214. package/dist/keyDerivation-DcKRUCVh.cjs +274 -0
  215. package/dist/keyDerivation-QGesIMbS.js +4077 -0
  216. package/dist/{lace-context-FpU3iG3f.cjs → lace-context-BN0b_ury.cjs} +4 -4
  217. package/dist/{lace-context-BQvvxVLm.js → lace-context-DMRJ87Vg.js} +4 -4
  218. package/dist/lib-BC-62Byh.cjs +2359 -0
  219. package/dist/lib-JYqcAX0c.js +2354 -0
  220. package/dist/midnight-account-id.vo--Vcx34Xk.cjs +10 -0
  221. package/dist/midnight-account-id.vo-BuB8fiVO.js +5 -0
  222. package/dist/midnight-engine-B7D2hbHo.js +5 -0
  223. package/dist/midnight-engine-D5ikN_5F.cjs +6 -0
  224. package/dist/midnight-wallet-BOdFD6SX.cjs +24 -0
  225. package/dist/midnight-wallet-CAqZrNVe.js +18 -0
  226. package/dist/midnight.cjs +1412 -0
  227. package/dist/midnight.d.ts +28609 -0
  228. package/dist/midnight.js +1355 -0
  229. package/dist/modules-cardano-BiL9hoM3.js +996 -0
  230. package/dist/modules-cardano-UeXks3sd.cjs +1109 -0
  231. package/dist/node-relay-BOuvdZvC.cjs +49 -0
  232. package/dist/node-relay-CLtc5n1v.js +48 -0
  233. package/dist/outputs-5qdW8s-f.js +196 -0
  234. package/dist/outputs-BEM1GPMf.cjs +339 -0
  235. package/dist/{SodiumBip32Ed25519-BQUcrQWX.cjs → pbkdf2-B1veireP.cjs} +6 -411
  236. package/dist/pending-operation-CfTUNQVD.cjs +26 -0
  237. package/dist/pending-operation-Ljijb1Uh.js +21 -0
  238. package/dist/providers-1on_fwJO.cjs +364 -0
  239. package/dist/providers-C1MsxfMA.js +341 -0
  240. package/dist/redacted-4SJPqt-G.js +81 -0
  241. package/dist/redacted-DwxIDdIF.cjs +86 -0
  242. package/dist/{reselect-DPML1uFN.cjs → reselect-kP4DaAII.cjs} +1 -1
  243. package/dist/{retry-config-oNtfdyrG.cjs → retry-config-BGv5q5QM.cjs} +1 -1
  244. package/dist/{retry-config-VdbuqBsI.js → retry-config-Bu5Yn5ua.js} +1 -1
  245. package/dist/safe-buffer-CqGpSFCQ.js +43 -0
  246. package/dist/safe-buffer-DbXbwhUQ.cjs +48 -0
  247. package/dist/sdk-1SRu8Ype.cjs +1445 -0
  248. package/dist/sdk-BneJm7ey.js +1249 -0
  249. package/dist/sdk-init-9TG1ZvHF.cjs +3795 -0
  250. package/dist/sdk-init-Ce3mD-8F.js +1047 -0
  251. package/dist/secret-box-CSmRp6Tt.js +3777 -0
  252. package/dist/secret-box-ZfbYwBgS.cjs +6970 -0
  253. package/dist/send-proof-progress-DtAcrMP6.cjs +33 -0
  254. package/dist/send-proof-progress-Dx2cUz1B.js +22 -0
  255. package/dist/sha2-DaRJZOjk.cjs +390 -0
  256. package/dist/sha2-c4sB6peD.js +378 -0
  257. package/dist/side-effects-C3BhLrdP.js +768 -0
  258. package/dist/side-effects-DG0R-KFc.cjs +804 -0
  259. package/dist/sign-bitcoin-transaction-with-seed-C7vq9om8.js +147 -0
  260. package/dist/sign-bitcoin-transaction-with-seed-Ds1dwzan.cjs +158 -0
  261. package/dist/signer--2I6poMD.js +2 -0
  262. package/dist/signer-CX21Ups_.cjs +121 -0
  263. package/dist/signer-Cnn9q9oY.js +92 -0
  264. package/dist/signer-DbSxjk0F.cjs +7 -0
  265. package/dist/signer-factory-B5oFuUZ-.cjs +130 -0
  266. package/dist/signer-factory-BAt8FPNc.cjs +281 -0
  267. package/dist/signer-factory-BGE4nL4k.js +129 -0
  268. package/dist/signer-factory-C4pgsiJi.js +281 -0
  269. package/dist/{signer-factory-DySc1wRX.cjs → signer-factory-D95jQIPV.cjs} +9 -6
  270. package/dist/{signer-factory-D4HrwFPl.js → signer-factory-PrpsGX-8.js} +10 -6
  271. package/dist/{slice-BZTQgYSs.js → slice-B-xJcuT1.js} +4 -4
  272. package/dist/slice-B4QOYaOG.cjs +105 -0
  273. package/dist/{slice-CtIMw2YT.cjs → slice-B9QKuhi0.cjs} +3 -3
  274. package/dist/slice-BKnGkAkd.cjs +9031 -0
  275. package/dist/{slice-Bhwmqn1p.cjs → slice-Bf4enJKZ.cjs} +8 -8
  276. package/dist/{slice-DaNVz7_l.js → slice-ByNWnxKS.js} +8 -8
  277. package/dist/{slice-C2UDQrdt.js → slice-C1zOeseG.js} +449 -355
  278. package/dist/{slice-DFLyKRm5.cjs → slice-C4toRM6A.cjs} +2 -2
  279. package/dist/{slice-Cx4dULDA.cjs → slice-C8YVv4Qn.cjs} +1 -1
  280. package/dist/{slice-jnpOgiSZ.cjs → slice-CaMfviYu.cjs} +3 -3
  281. package/dist/{slice-DFvrwUur.js → slice-CgeRsYRg.js} +6 -6
  282. package/dist/slice-Cwt8jShq.js +9013 -0
  283. package/dist/{slice-zNEspZND.js → slice-D0VzpMbY.js} +2 -2
  284. package/dist/slice-D14F78Ca.js +87 -0
  285. package/dist/{slice-F6A1YKOF.cjs → slice-DLflttAu.cjs} +479 -366
  286. package/dist/{slice-C96EdeY1.js → slice-DcO-iNz2.js} +1 -1
  287. package/dist/{slice-C19quNWM.cjs → slice-DimtxfAT.cjs} +2 -2
  288. package/dist/{slice-KiNoGwD9.js → slice-DlTEqIoI.js} +1 -1
  289. package/dist/{slice-ws8PccRX.js → slice-Dn0WojD7.js} +3 -3
  290. package/dist/{slice-BLSxLmie.cjs → slice-Dongunf7.cjs} +4 -4
  291. package/dist/{slice-B6vPum19.js → slice-DpufJAjJ.js} +2 -2
  292. package/dist/{slice-exhhmucR.cjs → slice-DtitVc9L.cjs} +7 -7
  293. package/dist/{slice-Bjj2t2ut.cjs → slice-WMMMc1Xv.cjs} +2 -2
  294. package/dist/slice-a8VuIqzS.cjs +378 -0
  295. package/dist/slice-bRASyM-m.js +354 -0
  296. package/dist/{slice-CBFrgHSH.js → slice-hNyKbDry.js} +3 -3
  297. package/dist/{InMemoryKeyAgent-pyB2gA-N.cjs → src-BayYMIjw.cjs} +20 -8228
  298. package/dist/{InMemoryKeyAgent-D-3HejxN.js → src-CgINPlSx.js} +29 -4811
  299. package/dist/store-AUlTfcI_.js +37 -0
  300. package/dist/store-C7AneHEY.cjs +66 -0
  301. package/dist/submit-BuBCVi-l.cjs +87 -0
  302. package/dist/submit-D37lxFrK.js +70 -0
  303. package/dist/submit-bitcoin-tx-DFLnhidO.js +983 -0
  304. package/dist/submit-bitcoin-tx-sih2hSfb.cjs +1049 -0
  305. package/dist/{subtractValueQuantities-DfZg6oiG.js → subtractValueQuantities-BuDJVxq6.js} +3 -22
  306. package/dist/{subtractValueQuantities-C8qDTtgH.cjs → subtractValueQuantities-CqR606HV.cjs} +2 -32
  307. package/dist/{sync-operation-utils-BrQyWFS_.cjs → sync-operation-utils--Z_IQfyW.cjs} +0 -66
  308. package/dist/{sync-operation-utils-CAaCGvEN.js → sync-operation-utils-BimBpvI3.js} +1 -37
  309. package/dist/token-color.vo-CItgoOjw.js +26 -0
  310. package/dist/token-color.vo-Ca4hUXfh.cjs +37 -0
  311. package/dist/token-id-mapper-BVau2RXa.js +16 -0
  312. package/dist/token-id-mapper-CSeLzM4o.cjs +18 -0
  313. package/dist/{token-id-mapper-pDaTxpw2.js → token-id-mapper-ClBeIdJR.js} +2 -2
  314. package/dist/{token-id-mapper-DYcd8hhQ.cjs → token-id-mapper-D0wFdbOy.cjs} +2 -2
  315. package/dist/types-BhzypKMS.cjs +15 -0
  316. package/dist/types-DTE1ctDB.js +10 -0
  317. package/dist/types-DXSxXGz0.js +12 -0
  318. package/dist/types-Dls6Z5gV.cjs +23 -0
  319. package/dist/{util-P4PX2muj.cjs → util-D1YlKzrc.cjs} +2 -2
  320. package/dist/{util-CQSJU0wT.js → util-DHxtzUzY.js} +2 -2
  321. package/dist/{utils-Bv4OHT4S.cjs → utils-DYf4iZKX.cjs} +7 -1
  322. package/dist/{utils-DrtzChYN.js → utils-DcnoETEP.js} +2 -2
  323. package/dist/utils-Du0YXRcU.cjs +112 -0
  324. package/dist/utils-fF_rnZe3.js +65 -0
  325. package/dist/v8Signatures-ClGpA8mS.cjs +71 -0
  326. package/dist/{vote-delegation-tx-builder-69gOEkCB.cjs → vote-delegation-tx-builder-BjZxCOd3.cjs} +9 -8
  327. package/dist/{vote-delegation-tx-builder-BRJ_pf-c.js → vote-delegation-tx-builder-DRJwPXkD.js} +9 -7
  328. package/dist/watch-FGE4B_Ge.js +13056 -0
  329. package/dist/watch-imlsRZDp.cjs +52207 -0
  330. package/package.json +95 -3
  331. package/dist/Address-4KjeDt_x.cjs +0 -17269
  332. package/dist/Address-_VPkf7Xh.js +0 -17101
  333. package/dist/account-guards.stable-BKyYPj4z.cjs +0 -10
  334. package/dist/account-guards.stable-BdmQ43vC.js +0 -5
  335. package/dist/init-BR9ZIbED.cjs +0 -378
  336. package/dist/init-B_k1RUN_.cjs +0 -21
  337. package/dist/init-Bs3b5ZQH.js +0 -378
  338. package/dist/init-ChfcrHgG2.cjs +0 -4354
  339. package/dist/init-D1uUMMpG.js +0 -19
  340. package/dist/init-DV1OSZiK.js +0 -4352
  341. package/dist/modules-cardano-BINzpXpk.js +0 -5454
  342. package/dist/modules-cardano-Dt8OwoQb.cjs +0 -5640
  343. package/dist/slice-Caf98m0d2.js +0 -107
  344. package/dist/slice-PM6llajQ2.cjs +0 -125
  345. /package/dist/{BigIntMath-CoJWXt1h.cjs → BigIntMath-CBciEQn2.cjs} +0 -0
  346. /package/dist/{BigIntMath-BWUJOsOW.js → BigIntMath-X3EniYDo.js} +0 -0
  347. /package/dist/{ChainId-sdLmlIRk.cjs → ChainId-CNPSU9nn.cjs} +0 -0
  348. /package/dist/{ChainId-CKbm87yQ.js → ChainId-CeoG8Sov.js} +0 -0
  349. /package/dist/{_polyfill-node.process-4fnlkbBi.cjs → _polyfill-node.process-5UxyjoHG.cjs} +0 -0
  350. /package/dist/{account-id.vo-Xpgnu-av.cjs → account-id.vo-DYZBZQsz.cjs} +0 -0
  351. /package/dist/{account-id.vo-DP0BtOoF.js → account-id.vo-KDTWJ-W5.js} +0 -0
  352. /package/dist/{actions-BNagEO6m.cjs → actions-BnHFVSr_.cjs} +0 -0
  353. /package/dist/{actions-BWTyAr7B.js → actions-Cwj0ApZf.js} +0 -0
  354. /package/dist/{asyncoption-po7-RiA5.cjs → asyncoption-CYcZNBRM.cjs} +0 -0
  355. /package/dist/{asyncoption-CzIVH5Y1.js → asyncoption-DZQGfznq.js} +0 -0
  356. /package/dist/{bignum.vo-DhhZ9HP1.js → bignum.vo-Co6tMH2q.js} +0 -0
  357. /package/dist/{bignum.vo-CpkrIXjH.cjs → bignum.vo-Du-bpvar.cjs} +0 -0
  358. /package/dist/{blockchain-network-id.vo-CbgrAY_K.js → blockchain-network-id.vo-C6Jowh8t.js} +0 -0
  359. /package/dist/{blockchain-network-id.vo-5iC6Kffo.cjs → blockchain-network-id.vo-DEQ14dYj.cjs} +0 -0
  360. /package/dist/{composite-signer-factory-DABpCe1_.js → composite-signer-factory-D9RWY-1V.js} +0 -0
  361. /package/dist/{composite-signer-factory-BizuNPP7.cjs → composite-signer-factory-v4Pxn8bA.cjs} +0 -0
  362. /package/dist/{error-ggOihIfv.cjs → error-B6wj9nPv.cjs} +0 -0
  363. /package/dist/{error-DHKO2iS4.js → error-CvEYL98P.js} +0 -0
  364. /package/dist/{esm-browser-DnXNvpcn.cjs → esm-browser-CZbMeVod.cjs} +0 -0
  365. /package/dist/{esm-browser-BBVQuyQv.js → esm-browser-DpAD_RKv.js} +0 -0
  366. /package/dist/{feature-flag-key.vo-DoGK5Bfh.js → feature-flag-key.vo-9reURsOQ.js} +0 -0
  367. /package/dist/{feature-flag-key.vo-CP1Z9s8e.cjs → feature-flag-key.vo-KTIdnzYX.cjs} +0 -0
  368. /package/dist/{first-state-of-status-Bx4-QQ5m.cjs → first-state-of-status-9ICeDNSa.cjs} +0 -0
  369. /package/dist/{first-state-of-status-D7XzEuSa.js → first-state-of-status-BscbKj_t.js} +0 -0
  370. /package/dist/{init-4319psUJ.cjs → init-BT67pd9x.cjs} +0 -0
  371. /package/dist/{init-AFUM1TSg.js → init-CHk1fvJ2.js} +0 -0
  372. /package/dist/{init-ZX90nEJe2.js → init-DIyNx6DZ.js} +0 -0
  373. /package/dist/{init-CTQ2g6Xt.js → init-DtxxFaCx.js} +0 -0
  374. /package/dist/{init-Dt1Xifg_2.cjs → init-J8QobR93.cjs} +0 -0
  375. /package/dist/{init-BNewLCqw.cjs → init-xzZPlQwB.cjs} +0 -0
  376. /package/dist/{is-redux-persist-state-DxJSsvxB.cjs → is-redux-persist-state-C5luvPEH.cjs} +0 -0
  377. /package/dist/{is-redux-persist-state-Bl2n4VMr.js → is-redux-persist-state-CjcqyCoh.js} +0 -0
  378. /package/dist/{isNotNil-CZxBMfL5.js → isNotNil-Be7gCY0m.js} +0 -0
  379. /package/dist/{isNotNil-C_SO1tcC.cjs → isNotNil-CrYIUFry.cjs} +0 -0
  380. /package/dist/{logging-BvMDKgl0.js → logging-BAMMfn5j.js} +0 -0
  381. /package/dist/{logging-Bh9ikph3.cjs → logging-CbxgIX9V.cjs} +0 -0
  382. /package/dist/{metadatum-B-sxBnSY.cjs → metadatum-BGvFqGPt.cjs} +0 -0
  383. /package/dist/{metadatum-Ego4jVas.js → metadatum-BVocMYy_.js} +0 -0
  384. /package/dist/{repo-slice-BzZQUTj8.cjs → repo-slice-BB_W-6OL.cjs} +0 -0
  385. /package/dist/{repo-slice-vCcQJotS.js → repo-slice-BQlssw9M.js} +0 -0
  386. /package/dist/{reselect-BPkMzw3k.js → reselect-JIgawvPe.js} +0 -0
  387. /package/dist/{serializable-BxFUShKY.js → serializable-F7OtYl8d.js} +0 -0
  388. /package/dist/{serializable-DWgkHhv_.cjs → serializable-n3UoxbZc.cjs} +0 -0
  389. /package/dist/{slice-DY-DNtSi.js → slice-5dGBAz6w.js} +0 -0
  390. /package/dist/{slice-BEFoeqgr.cjs → slice-BzJgg9FS.cjs} +0 -0
  391. /package/dist/{src-CPmX4KUh.cjs → src-CeBNkonz.cjs} +0 -0
  392. /package/dist/{src-XOZXPKxe.js → src-Cv1ifqbe.js} +0 -0
  393. /package/dist/{time-CQPt4FdU.js → time-ByoKevdZ.js} +0 -0
  394. /package/dist/{time-Blvoyh9G.cjs → time-qD7edGU0.cjs} +0 -0
  395. /package/dist/{time.vo-Xln4yGBU.js → time.vo-C17-tYq3.js} +0 -0
  396. /package/dist/{time.vo-rwWwJzmP.cjs → time.vo-TmYE-_Y2.cjs} +0 -0
  397. /package/dist/{toEmpty-CzmoZVLN.cjs → toEmpty-Db6V94Mf.cjs} +0 -0
  398. /package/dist/{toEmpty-DzLd-ZCi.js → toEmpty-Djj-QbpI.js} +0 -0
  399. /package/dist/{token-id.vo-l8fuSpem.cjs → token-id.vo-CZ622zcZ.cjs} +0 -0
  400. /package/dist/{token-id.vo-DMKSaMlc.js → token-id.vo-IDI9C_Qm.js} +0 -0
  401. /package/dist/{types-B61DQoFW.js → types-By-XeXWg.js} +0 -0
  402. /package/dist/{types-CUC-Kcqh.cjs → types-Cn6WlQV6.cjs} +0 -0
  403. /package/dist/{util-BV3iGOrz.cjs → util-Cp1h58uD.cjs} +0 -0
  404. /package/dist/{util-BsQKLorV.js → util-DHppXj7U.js} +0 -0
  405. /package/dist/{util-selector-CKIyoAOz.js → util-selector-BWmHpo92.js} +0 -0
  406. /package/dist/{util-selector-C9H5RsNw.cjs → util-selector-glXkO-jR.cjs} +0 -0
  407. /package/dist/{while-active-CNXeLxre.js → while-active-CDBnUlQA.js} +0 -0
  408. /package/dist/{while-active-BsDWSNrO.cjs → while-active-I2TlHtm7.cjs} +0 -0
@@ -0,0 +1,3795 @@
1
+ const require_chunk = require("./chunk-9hOWP6kD.cjs");
2
+ const require_equals = require("./equals-3gajbRxE.cjs");
3
+ const require__polyfill_buffer_patch = require("./_polyfill-buffer-patch-BycQkEkK.cjs");
4
+ require("./serializable-n3UoxbZc.cjs");
5
+ const require_Percent = require("./Percent-Cfuw5YyL.cjs");
6
+ require("./pbkdf2-B1veireP.cjs");
7
+ require("./safe-buffer-DbXbwhUQ.cjs");
8
+ require("./secret-box-ZfbYwBgS.cjs");
9
+ const require_bytes_vo = require("./bytes.vo-hecRu3YZ.cjs");
10
+ const require_time_vo = require("./time.vo-TmYE-_Y2.cjs");
11
+ const require_bignum_vo = require("./bignum.vo-Du-bpvar.cjs");
12
+ const require_auto_dismiss_failure_on_success = require("./auto-dismiss-failure-on-success-BWJceNXd.cjs");
13
+ require("./retry-config-BGv5q5QM.cjs");
14
+ const require_activity_type = require("./activity-type-BPXxdHBP.cjs");
15
+ const require_token_id_vo = require("./token-id.vo-CZ622zcZ.cjs");
16
+ const require_types = require("./types-BhzypKMS.cjs");
17
+ require("./bn-BFq5a4dk.cjs");
18
+ const require_const = require("./const-DgBzKfz6.cjs");
19
+ const require_watch = require("./watch-imlsRZDp.cjs");
20
+ const require_slice = require("./slice-a8VuIqzS.cjs");
21
+ const require_utils = require("./utils-Du0YXRcU.cjs");
22
+ const require_midnight_wallet = require("./midnight-wallet-BOdFD6SX.cjs");
23
+ const require_dist = require("./dist-Br0OVXKt.cjs");
24
+ require("./client-Bw2foG5E.cjs");
25
+ const require_send_proof_progress = require("./send-proof-progress-DtAcrMP6.cjs");
26
+ let rxjs = require("rxjs");
27
+ rxjs = require_chunk.__toESM(rxjs);
28
+ let lodash_isEqual = require("lodash/isEqual.js");
29
+ lodash_isEqual = require_chunk.__toESM(lodash_isEqual);
30
+ let _midnight_ntwrk_ledger_v8 = require("@midnight-ntwrk/ledger-v8");
31
+ _midnight_ntwrk_ledger_v8 = require_chunk.__toESM(_midnight_ntwrk_ledger_v8);
32
+ //#region ../../packages/contract/midnight-context/src/value-objects/midnight-address.vo.ts
33
+ const MidnightShieldedAddress = (address) => address;
34
+ const MidnightUnshieldedAddress = (address) => address;
35
+ const MidnightDustAddress = (address) => address;
36
+ //#endregion
37
+ //#region ../../packages/contract/midnight-context/src/value-objects/serialised-wallet-state.vo.ts
38
+ /**
39
+ * Either encoding. Production only ever constructs this from the SDK's
40
+ * verbatim JSON; the hex form comes back from storage on older profiles.
41
+ */
42
+ const SerialisedWalletState = (value) => value;
43
+ /**
44
+ * A heuristic over the values we actually persist, not a parse: hex and JSON
45
+ * overlap (`12345678` is both), so nothing can separate them in general. Every
46
+ * blob written here opens with `{`; `[` is headroom for a serialiser that
47
+ * returns a top-level array. Anything else reads as hex, and a wrong guess
48
+ * costs a rebuild from seed, which the restore path already handles.
49
+ *
50
+ * First character only: matching hex across the whole payload cost ~2500ms
51
+ * against 10k documents of 100k characters, against ~8ms here, and was
52
+ * case-sensitive so it missed uppercase hex besides.
53
+ */
54
+ const isVerbatimJson = (value) => value.startsWith("{") || value.startsWith("[");
55
+ SerialisedWalletState.toJSON = (value) => isVerbatimJson(value) ? value : require_bytes_vo.HexBytes.toUTF8(value);
56
+ //#endregion
57
+ //#region ../../packages/contract/midnight-context/src/midnight-accounts.ts
58
+ /** Two account lists are the same run of accounts when their ids line up in
59
+ * order — the identity the account stream re-emits on. */
60
+ const sameAccounts = (accounts1, accounts2) => {
61
+ if (accounts1.length !== accounts2.length) return false;
62
+ for (let index = 0; index < accounts1.length; index++) if (accounts1[index].accountId !== accounts2[index].accountId) return false;
63
+ return true;
64
+ };
65
+ /**
66
+ * The in-memory Midnight accounts on the active Midnight network, as a stream
67
+ * that only re-emits when the run of account ids actually changes. Emits an
68
+ * empty list while the wallet repo is migrating, so a consumer never acts on a
69
+ * half-migrated repo. Nothing is emitted until a Midnight network is registered.
70
+ */
71
+ const midnightAccounts$ = (state) => (0, rxjs.combineLatest)([
72
+ state.wallets.selectActiveNetworkAccounts$,
73
+ state.midnightContext.selectMidnightBlockchainNetworkId$.pipe((0, rxjs.filter)(Boolean)),
74
+ state.wallets.selectIsWalletRepoMigrating$
75
+ ]).pipe((0, rxjs.map)(([accounts, activeNetwork, isWalletRepoMigrating]) => isWalletRepoMigrating ? [] : accounts.filter(require_utils.isInMemoryMidnightAccount).filter((account) => account.blockchainNetworkId === activeNetwork)), (0, rxjs.distinctUntilChanged)(sameAccounts));
76
+ //#endregion
77
+ //#region ../../packages/contract/midnight-context/src/register-midnight-blockchain-networks.ts
78
+ /**
79
+ * Registers the Midnight networks with the global network store once, the
80
+ * first time it reports Midnight absent. Every loadout with Midnight accounts
81
+ * needs this: `wallets.selectActiveNetworkAccounts` drops the accounts of an
82
+ * unregistered blockchain. The registration lands a tick after this decides,
83
+ * so it sets the networks only while Midnight still has none: a network the
84
+ * consumer selected in between keeps precedence.
85
+ *
86
+ * An existing Midnight account pins the testnet selection to its own network,
87
+ * so a profile created before the network store existed keeps syncing where
88
+ * its account lives; otherwise the default testnet is selected.
89
+ */
90
+ const registerMidnightBlockchainNetworks = (_, { network: { selectBlockchainNetworks$ }, midnightContext: { selectDefaultTestNetNetworkId$ }, wallets: { selectAll$ } }, { actions }) => selectBlockchainNetworks$.pipe((0, rxjs.filter)((blockchainNetworks) => !blockchainNetworks?.Midnight), (0, rxjs.withLatestFrom)(selectDefaultTestNetNetworkId$, selectAll$.pipe((0, rxjs.map)((allWallets) => allWallets.flatMap((wallet) => wallet.accounts)))), (0, rxjs.map)(([, defaultTestNetNetworkId, accounts]) => {
91
+ const existingMidnightAccount = accounts.find((account) => account.blockchainName === "Midnight");
92
+ const testnetNetworkId = existingMidnightAccount ? existingMidnightAccount.blockchainSpecific.networkId : defaultTestNetNetworkId;
93
+ return actions.network.registerBlockchainNetworks({
94
+ blockchain: "Midnight",
95
+ mainnet: require_const.MidnightNetworkId("mainnet"),
96
+ testnet: require_const.MidnightNetworkId(testnetNetworkId)
97
+ });
98
+ }));
99
+ //#endregion
100
+ //#region ../../packages/lib/vendor/src/midnight-facade-reservations.ts
101
+ const NO_BALANCING_TRANSACTION = "No balancing transaction was created. Please check your transaction.";
102
+ const releasingOnFailure = async (build) => {
103
+ const releases = [];
104
+ const reserve = (transaction, holder) => {
105
+ if (transaction) releases.push(async () => holder.revertTransaction(transaction));
106
+ return transaction;
107
+ };
108
+ try {
109
+ return await build(reserve);
110
+ } catch (error) {
111
+ await Promise.allSettled(releases.map(async (release) => release()));
112
+ throw error;
113
+ }
114
+ };
115
+ const merge$2 = (first, second) => first && second ? first.merge(second) : first ?? second;
116
+ const kindsToBalance = (tokenKindsToBalance = "all") => {
117
+ const kinds = tokenKindsToBalance === "all" ? [
118
+ "shielded",
119
+ "unshielded",
120
+ "dust"
121
+ ] : tokenKindsToBalance;
122
+ return {
123
+ dust: kinds.includes("dust"),
124
+ shielded: kinds.includes("shielded"),
125
+ unshielded: kinds.includes("unshielded")
126
+ };
127
+ };
128
+ /**
129
+ * The wallet SDK's multi-step builds over `facade`, releasing the coins the
130
+ * completed steps reserved when a later step fails. The wallet SDK keeps
131
+ * them, and its caller gets an error with no recipe to release. Each build
132
+ * takes the same steps over the same sub-wallets as its `WalletFacade`
133
+ * namesake and returns the same recipe.
134
+ */
135
+ const withReservationRelease = (facade) => ({
136
+ balanceFinalizedTransaction: async (transaction, { shieldedSecretKeys, dustSecretKey }, { ttl, tokenKindsToBalance }) => releasingOnFailure(async (reserve) => {
137
+ const balance = kindsToBalance(tokenKindsToBalance);
138
+ const unshieldedBalancing = balance.unshielded ? reserve(await facade.unshielded.balanceFinalizedTransaction(transaction), facade.unshielded) : void 0;
139
+ const tokenBalancing = merge$2(balance.shielded ? reserve(await facade.shielded.balanceTransaction(shieldedSecretKeys, transaction), facade.shielded) : void 0, unshieldedBalancing);
140
+ const balancingTransaction = merge$2(tokenBalancing, balance.dust ? await facade.dust.balanceTransactions(dustSecretKey, tokenBalancing ? [transaction, tokenBalancing] : [transaction], ttl) : void 0);
141
+ if (!balancingTransaction) throw new Error(NO_BALANCING_TRANSACTION);
142
+ return {
143
+ type: "FINALIZED_TRANSACTION",
144
+ originalTransaction: transaction,
145
+ balancingTransaction
146
+ };
147
+ }),
148
+ balanceUnboundTransaction: async (transaction, { shieldedSecretKeys, dustSecretKey }, { ttl, tokenKindsToBalance }) => releasingOnFailure(async (reserve) => {
149
+ const balance = kindsToBalance(tokenKindsToBalance);
150
+ const shieldedBalancing = balance.shielded ? reserve(await facade.shielded.balanceTransaction(shieldedSecretKeys, transaction), facade.shielded) : void 0;
151
+ const balancedUnshielded = balance.unshielded ? await facade.unshielded.balanceUnboundTransaction(transaction) : void 0;
152
+ const baseTransaction = balancedUnshielded ?? transaction;
153
+ const balancingTransaction = merge$2(shieldedBalancing, balance.dust ? await facade.dust.balanceTransactions(dustSecretKey, shieldedBalancing ? [baseTransaction, shieldedBalancing] : [baseTransaction], ttl) : void 0);
154
+ if (!balancingTransaction && !balancedUnshielded) throw new Error(NO_BALANCING_TRANSACTION);
155
+ return {
156
+ type: "UNBOUND_TRANSACTION",
157
+ baseTransaction,
158
+ balancingTransaction: balancingTransaction ?? void 0
159
+ };
160
+ }),
161
+ transferTransaction: async (outputs, { shieldedSecretKeys, dustSecretKey }, { ttl, payFees = true }) => releasingOnFailure(async (reserve) => {
162
+ const shieldedOutputs = outputs.flatMap((output) => output.type === "shielded" ? output.outputs : []);
163
+ const unshieldedOutputs = outputs.flatMap((output) => output.type === "unshielded" ? output.outputs : []);
164
+ if (unshieldedOutputs.length === 0 && shieldedOutputs.length === 0) throw new Error("At least one shielded or unshielded output is required.");
165
+ const transfer = merge$2(shieldedOutputs.length > 0 ? reserve(await facade.shielded.transferTransaction(shieldedSecretKeys, shieldedOutputs), facade.shielded) : void 0, unshieldedOutputs.length > 0 ? reserve(await facade.unshielded.transferTransaction(unshieldedOutputs, ttl), facade.unshielded) : void 0);
166
+ if (!transfer) throw new Error("Unexpected transaction state.");
167
+ return {
168
+ type: "UNPROVEN_TRANSACTION",
169
+ transaction: merge$2(transfer, payFees ? await facade.dust.balanceTransactions(dustSecretKey, [transfer], ttl) : void 0) ?? transfer
170
+ };
171
+ }),
172
+ initSwap: async ({ desiredInputs, desiredOutputs }, { shieldedSecretKeys, dustSecretKey }, { ttl, payFees = false }) => releasingOnFailure(async (reserve) => {
173
+ const { shielded: shieldedInputs, unshielded: unshieldedInputs } = desiredInputs;
174
+ const shieldedOutputs = desiredOutputs.flatMap((output) => output.type === "shielded" ? output.outputs : []);
175
+ const unshieldedOutputs = desiredOutputs.flatMap((output) => output.type === "unshielded" ? output.outputs : []);
176
+ const hasShieldedPart = !!shieldedInputs && Object.keys(shieldedInputs).length > 0 || shieldedOutputs.length > 0;
177
+ const hasUnshieldedPart = !!unshieldedInputs && Object.keys(unshieldedInputs).length > 0 || unshieldedOutputs.length > 0;
178
+ if (!hasShieldedPart && !hasUnshieldedPart) throw new Error("At least one shielded or unshielded swap is required.");
179
+ const swap = merge$2(hasShieldedPart && shieldedInputs !== void 0 ? reserve(await facade.shielded.initSwap(shieldedSecretKeys, shieldedInputs, shieldedOutputs), facade.shielded) : void 0, hasUnshieldedPart && unshieldedInputs !== void 0 ? reserve(await facade.unshielded.initSwap(unshieldedInputs, unshieldedOutputs, ttl), facade.unshielded) : void 0);
180
+ if (!swap) throw new Error("Unexpected transaction state.");
181
+ return {
182
+ type: "UNPROVEN_TRANSACTION",
183
+ transaction: merge$2(swap, payFees ? await facade.dust.balanceTransactions(dustSecretKey, [swap], ttl) : void 0) ?? swap
184
+ };
185
+ })
186
+ });
187
+ //#endregion
188
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/CoreWallet.js
189
+ const PublicKey = { fromSecretKey: (secretKey) => {
190
+ return { publicKey: secretKey.publicKey };
191
+ } };
192
+ const CoreWallet$1 = {
193
+ init(localState, secretKey, networkId) {
194
+ return CoreWallet$1.empty(localState, PublicKey.fromSecretKey(secretKey), networkId);
195
+ },
196
+ initEmpty(dustParameters, secretKey, networkId) {
197
+ return CoreWallet$1.empty(new _midnight_ntwrk_ledger_v8.DustLocalState(dustParameters), PublicKey.fromSecretKey(secretKey), networkId);
198
+ },
199
+ empty(localState, publicKey, networkId) {
200
+ return {
201
+ state: localState,
202
+ publicKey,
203
+ networkId,
204
+ pendingDust: [],
205
+ progress: require_const.createSyncProgress(),
206
+ protocolVersion: require_const.MinSupportedVersion
207
+ };
208
+ },
209
+ restore(localState, publicKey, pendingTokens, syncProgress, protocolVersion, networkId) {
210
+ return {
211
+ state: localState,
212
+ publicKey,
213
+ networkId,
214
+ pendingDust: pendingTokens,
215
+ progress: require_const.createSyncProgress(syncProgress),
216
+ protocolVersion: require_const.ProtocolVersion(protocolVersion)
217
+ };
218
+ },
219
+ applyEventsWithChanges(wallet, secretKey, events, currentTime) {
220
+ const stateWithChanges = wallet.state.replayEventsWithChanges(secretKey, events);
221
+ const updatedState = stateWithChanges.state.processTtls(currentTime);
222
+ const availableNonces = updatedState.utxos.map((utxo) => utxo.nonce);
223
+ return [{
224
+ ...wallet,
225
+ state: updatedState,
226
+ pendingDust: wallet.pendingDust.filter((t) => availableNonces.includes(t.nonce))
227
+ }, stateWithChanges.changes];
228
+ },
229
+ applyFailed(wallet, tx) {
230
+ const pendingSpendsMap = CoreWallet$1.pendingDustToMap(wallet.pendingDust);
231
+ const [updatedState, removedNullifiers] = require_const.pipe(require_const.pipe([...tx.intents?.values() ?? []], require_const.flatMap$3((intent) => {
232
+ const spendTime = intent.dustActions?.ctime;
233
+ return (intent.dustActions?.spends ?? []).map((spend) => ({
234
+ spend,
235
+ spendTime
236
+ }));
237
+ }), require_const.filterMap$1(({ spend, spendTime }) => require_const.pipe(require_const.fromNullable(pendingSpendsMap.get(spend.oldNullifier)), require_const.map$8(() => ({
238
+ spend,
239
+ spendTime
240
+ }))))), require_const.reduce$3([wallet.state, []], ([state, removed], { spend, spendTime }) => [state.processTtls(require_watch.addSeconds(spendTime, wallet.state.params.dustGracePeriodSeconds)), require_const.append$1(removed, spend.oldNullifier)]));
241
+ return {
242
+ ...wallet,
243
+ state: updatedState,
244
+ pendingDust: wallet.pendingDust.filter((coin) => !removedNullifiers.includes(coin.nullifier))
245
+ };
246
+ },
247
+ revertTransaction(wallet, tx) {
248
+ return CoreWallet$1.applyFailed(wallet, tx);
249
+ },
250
+ updateProgress(wallet, { appliedIndex, highestRelevantWalletIndex, highestIndex, highestRelevantIndex, isConnected }) {
251
+ const updatedProgress = require_const.createSyncProgress({
252
+ appliedIndex: appliedIndex ?? wallet.progress.appliedIndex,
253
+ highestRelevantWalletIndex: highestRelevantWalletIndex ?? wallet.progress.highestRelevantWalletIndex,
254
+ highestIndex: highestIndex ?? wallet.progress.highestIndex,
255
+ highestRelevantIndex: highestRelevantIndex ?? wallet.progress.highestRelevantIndex,
256
+ isConnected: isConnected ?? wallet.progress.isConnected
257
+ });
258
+ return {
259
+ ...wallet,
260
+ progress: updatedProgress
261
+ };
262
+ },
263
+ spendCoins(wallet, secretKey, coins, currentTime) {
264
+ const [output, newState, newPending] = require_const.pipe(coins, require_const.reduce$3([
265
+ [],
266
+ wallet.state,
267
+ wallet.pendingDust
268
+ ], ([spends, localState, pending], { token: coinToSpend, value: takeFee }) => {
269
+ const [newState, dustSpend] = localState.spend(secretKey, coinToSpend, takeFee, currentTime);
270
+ const newPending = [...pending, {
271
+ ...coinToSpend,
272
+ nullifier: dustSpend.oldNullifier
273
+ }];
274
+ return [
275
+ require_const.append$1(spends, dustSpend),
276
+ newState,
277
+ newPending
278
+ ];
279
+ }));
280
+ return [output, {
281
+ ...wallet,
282
+ state: newState,
283
+ pendingDust: newPending
284
+ }];
285
+ },
286
+ pendingDustToMap(coins) {
287
+ return new Map(coins.map(({ nullifier, ...coins }) => [nullifier, coins]));
288
+ }
289
+ };
290
+ //#endregion
291
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/WalletError.js
292
+ var OtherWalletError$1 = class extends require_const.TaggedError("Wallet.Other") {};
293
+ var SyncWalletError$1 = class extends require_const.TaggedError("Wallet.Sync") {};
294
+ var TransactingError = class extends require_const.TaggedError("Wallet.Transacting") {};
295
+ var InsufficientFundsError$1 = class extends require_const.TaggedError("Wallet.InsufficientFunds") {};
296
+ var TransactionHistoryError$1 = class extends require_const.TaggedError("Wallet.TransactionHistory") {};
297
+ //#endregion
298
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/RunningV1Variant.js
299
+ const progress$1 = (state) => {
300
+ const appliedIndex = state.progress?.appliedIndex ?? 0n;
301
+ const highestRelevantWalletIndex = state.progress?.highestRelevantWalletIndex ?? 0n;
302
+ const sourceGap = (state.progress?.highestIndex ?? 0n) - (state.progress?.highestRelevantIndex ?? 0n);
303
+ const applyGap = highestRelevantWalletIndex - appliedIndex;
304
+ return [require_watch.ProgressUpdate({
305
+ sourceGap,
306
+ applyGap
307
+ })];
308
+ };
309
+ const protocolVersionChange$1 = (previous, current) => {
310
+ return previous.protocolVersion != current.protocolVersion ? [require_watch.VersionChange({ change: require_watch.Version({ version: require_const.ProtocolVersion(current.protocolVersion) }) })] : [];
311
+ };
312
+ const V1Tag$1 = Symbol("V1");
313
+ var RunningV1Variant$1 = class {
314
+ __polyTag__ = V1Tag$1;
315
+ #scope;
316
+ #context;
317
+ #v1Context;
318
+ state;
319
+ constructor(scope, context, v1Context) {
320
+ this.#scope = scope;
321
+ this.#context = context;
322
+ this.#v1Context = v1Context;
323
+ this.state = require_watch.fromEffect(context.stateRef.get).pipe(require_watch.flatMap((initialState) => context.stateRef.changes.pipe(require_watch.mapAccum(initialState, (previous, current) => {
324
+ return [current, [previous, current]];
325
+ }))), require_watch.mapConcat(([previous, current]) => {
326
+ return [
327
+ require_watch.State({ state: current }),
328
+ ...progress$1(current),
329
+ ...protocolVersionChange$1(previous, current)
330
+ ];
331
+ }));
332
+ }
333
+ startSyncInBackground(startAux) {
334
+ return this.startSync(startAux).pipe(require_watch.runScoped(require_watch.drain), require_const.forkScoped, require_const.provideService(require_const.Scope, this.#scope));
335
+ }
336
+ startSync(startAux) {
337
+ return require_const.pipe(require_watch.get(this.#context.stateRef), require_watch.fromEffect, require_watch.flatMap((state) => this.#v1Context.syncService.updates(state, startAux)), require_watch.mapEffect((update) => require_watch.modifyEffect(this.#context.stateRef, (state) => require_const.try_({
338
+ try: () => {
339
+ const [newState, changesResult] = this.#v1Context.syncCapability.applyUpdate(state, update);
340
+ return [changesResult, newState];
341
+ },
342
+ catch: (err) => new OtherWalletError$1({
343
+ message: "Error while applying sync update",
344
+ cause: err
345
+ })
346
+ })).pipe(require_const.flatMap(({ changes, protocolVersion }) => changes.length === 0 ? require_const._void : require_const.pipe(require_const.forEach(changes, (change) => require_const.pipe(this.#v1Context.transactionHistoryService.getTransactionDetails(change.source), require_const.flatMap((metadata) => this.#v1Context.transactionHistoryService.put(change, metadata, protocolVersion)), require_const.catchAllCause((cause) => require_watch.error("Error processing tx history metadata", cause))), {
347
+ discard: true,
348
+ concurrency: "unbounded"
349
+ }), require_const.forkScoped)), require_const.provideService(require_const.Scope, this.#scope))), require_watch.tapError((error$2) => require_watch.error(error$2)), require_watch.retry(require_const.pipe(require_watch.exponential(require_const.seconds(1), 2), require_watch.map$1((delay) => {
350
+ const maxDelay = require_const.minutes(2);
351
+ const jitter = require_const.millis(Math.floor(Math.random() * 1e3));
352
+ const delayWithJitter = require_const.toMillis(delay) + require_const.toMillis(jitter);
353
+ return require_const.millis(Math.min(delayWithJitter, require_const.toMillis(maxDelay)));
354
+ }))));
355
+ }
356
+ createDustGenerationTransaction(currentTime, ttl, nightUtxos, nightVerifyingKey, dustReceiverAddress) {
357
+ if (nightUtxos.some((utxo) => utxo.type !== (0, _midnight_ntwrk_ledger_v8.nativeToken)().raw)) return require_const.fail$1(new OtherWalletError$1({ message: "Token of a non-Night type received" }));
358
+ return require_const.gen(this, function* () {
359
+ const currentState = yield* require_watch.get(this.#context.stateRef);
360
+ const blockData = yield* this.#v1Context.syncService.blockData();
361
+ const resolvedTime = currentTime ?? blockData.timestamp;
362
+ const utxosWithDustValue = this.#v1Context.coinsAndBalancesCapability.estimateDustGeneration(currentState, nightUtxos, resolvedTime);
363
+ return yield* this.#v1Context.transactingCapability.createDustGenerationTransaction(resolvedTime, ttl, utxosWithDustValue, nightVerifyingKey, dustReceiverAddress).pipe(require_watch.toEffect);
364
+ });
365
+ }
366
+ splitNightUtxosForDustRegistration(currentTime, nightUtxos, isRegistration) {
367
+ if (nightUtxos.some((utxo) => utxo.type !== (0, _midnight_ntwrk_ledger_v8.nativeToken)().raw)) return require_const.fail$1(new OtherWalletError$1({ message: "Token of a non-Night type received" }));
368
+ return require_const.gen(this, function* () {
369
+ const currentState = yield* require_watch.get(this.#context.stateRef);
370
+ const utxosWithDustValue = this.#v1Context.coinsAndBalancesCapability.estimateDustGeneration(currentState, nightUtxos, currentTime);
371
+ return this.#v1Context.transactingCapability.splitNightUtxosForDustRegistration(utxosWithDustValue, isRegistration);
372
+ });
373
+ }
374
+ attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment) {
375
+ return this.#v1Context.transactingCapability.attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment).pipe(require_watch.toEffect);
376
+ }
377
+ addDustGenerationSignature(transaction, signature) {
378
+ return this.#v1Context.transactingCapability.addDustGenerationSignature(transaction, signature).pipe(require_watch.toEffect);
379
+ }
380
+ addDustRegistrationSignature(transaction, signature) {
381
+ return this.#v1Context.transactingCapability.addDustRegistrationSignature(transaction, signature).pipe(require_watch.toEffect);
382
+ }
383
+ calculateFee(transactions) {
384
+ return require_const.pipe(this.#v1Context.syncService.blockData(), require_const.map((blockData) => require_const.pipe(transactions, require_const.map$6((transaction) => this.#v1Context.transactingCapability.calculateFee(transaction, blockData.ledgerParameters)), require_watch.sumBigInt)));
385
+ }
386
+ estimateFee(secretKey, transactions, ttl, currentTime) {
387
+ return require_const.pipe(require_const.all([require_watch.get(this.#context.stateRef), this.#v1Context.syncService.blockData()]), require_const.flatMap(([state, blockData]) => require_const.pipe(this.#v1Context.transactingCapability.estimateFee(secretKey, state, transactions, ttl, currentTime ?? blockData.timestamp, blockData.ledgerParameters), require_watch.toEffect)));
388
+ }
389
+ balanceTransactions(secretKey, transactions, ttl, currentTime) {
390
+ return require_watch.modifyEffect(this.#context.stateRef, (state) => {
391
+ return require_const.pipe(this.#v1Context.syncService.blockData(), require_const.flatMap((blockData) => this.#v1Context.transactingCapability.balanceTransactions(secretKey, state, transactions, ttl, currentTime ?? blockData.timestamp, blockData.ledgerParameters)));
392
+ });
393
+ }
394
+ revertTransaction(transaction) {
395
+ return require_watch.updateEffect(this.#context.stateRef, (state) => {
396
+ return require_const.pipe(this.#v1Context.transactingCapability.revertTransaction(state, transaction), require_watch.toEffect);
397
+ });
398
+ }
399
+ };
400
+ //#endregion
401
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Serialization.js
402
+ require__polyfill_buffer_patch.init__polyfill_buffer_patch();
403
+ const StateSchema$1 = require_const.declare((input) => input instanceof _midnight_ntwrk_ledger_v8.DustLocalState).annotations({ identifier: "ledger.DustLocalState" });
404
+ const Uint8ArraySchema$2 = require_const.declare((input) => input instanceof Uint8Array).annotations({ identifier: "Uint8Array" });
405
+ const StateFromUInt8Array$1 = require_const.asSchema(require_const.transformOrFail(Uint8ArraySchema$2, StateSchema$1, {
406
+ encode: (state) => {
407
+ return require_const.try_({
408
+ try: () => {
409
+ return state.serialize();
410
+ },
411
+ catch: (err) => {
412
+ return new require_const.Unexpected(err, "Could not serialize local state");
413
+ }
414
+ });
415
+ },
416
+ decode: (bytes) => require_const.try_({
417
+ try: () => _midnight_ntwrk_ledger_v8.DustLocalState.deserialize(bytes),
418
+ catch: (err) => {
419
+ return new require_const.Unexpected(err, "Could not deserialize local state");
420
+ }
421
+ })
422
+ }));
423
+ const HexedState$1 = require_const.pipe(require_const.Uint8ArrayFromHex, require_const.compose(StateFromUInt8Array$1));
424
+ const SnapshotSchema = require_const.Struct({
425
+ publicKey: require_const.Struct({ publicKey: require_const.BigInt$ }),
426
+ state: HexedState$1,
427
+ protocolVersion: require_const.BigInt$,
428
+ networkId: require_const.String$,
429
+ offset: require_const.optional(require_const.BigInt$)
430
+ });
431
+ const makeDefaultV1SerializationCapability$1 = () => {
432
+ return {
433
+ serialize: (wallet) => {
434
+ const buildSnapshot = (w) => ({
435
+ publicKey: w.publicKey,
436
+ state: w.state,
437
+ protocolVersion: w.protocolVersion,
438
+ networkId: w.networkId,
439
+ offset: w.progress?.appliedIndex
440
+ });
441
+ return require_const.pipe(wallet, buildSnapshot, require_const.encodeSync(SnapshotSchema), JSON.stringify);
442
+ },
443
+ deserialize: (aux, serialized) => {
444
+ return require_const.pipe(serialized, require_const.decodeUnknownEither(require_const.parseJson(SnapshotSchema)), require_const.mapLeft((err) => new OtherWalletError$1({
445
+ message: "Error while deserializing snapshot",
446
+ cause: err
447
+ })), require_const.flatMap$4((snapshot) => require_const.try_$1({
448
+ try: () => CoreWallet$1.restore(snapshot.state, snapshot.publicKey, [], {
449
+ appliedIndex: snapshot.offset ?? 0n,
450
+ highestRelevantWalletIndex: 0n,
451
+ highestIndex: 0n,
452
+ highestRelevantIndex: 0n
453
+ }, snapshot.protocolVersion, snapshot.networkId),
454
+ catch: (err) => new OtherWalletError$1({
455
+ message: "Error while restoring core wallet",
456
+ cause: err
457
+ })
458
+ })));
459
+ }
460
+ };
461
+ };
462
+ //#endregion
463
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Sync.js
464
+ const LedgerEventSchema$1 = require_const.declare((input) => input instanceof _midnight_ntwrk_ledger_v8.Event).annotations({ identifier: "ledger.Event" });
465
+ const LedgerEventFromUInt8Array = require_const.asSchema(require_const.transformOrFail(Uint8ArraySchema$2, LedgerEventSchema$1, {
466
+ encode: (e) => require_const.try_({
467
+ try: () => e.serialize(),
468
+ catch: (err) => new require_const.Unexpected(err, "Could not serialize Ledger Event")
469
+ }),
470
+ decode: (bytes) => require_const.try_({
471
+ try: () => _midnight_ntwrk_ledger_v8.Event.deserialize(bytes),
472
+ catch: (err) => new require_const.Unexpected(err, "Could not deserialize Ledger Event")
473
+ })
474
+ }));
475
+ const HexedEvent = require_const.pipe(require_const.Uint8ArrayFromHex, require_const.compose(LedgerEventFromUInt8Array));
476
+ const SyncEventsUpdateSchema = require_const.Struct({
477
+ id: require_const.Number$,
478
+ raw: HexedEvent,
479
+ maxId: require_const.Number$
480
+ });
481
+ const WalletSyncUpdate$1 = { create: (updates, secretKey, timestamp) => {
482
+ return {
483
+ updates,
484
+ secretKey,
485
+ timestamp
486
+ };
487
+ } };
488
+ const makeDefaultSyncService = (config) => {
489
+ const indexerSyncService = makeIndexerSyncService(config);
490
+ return {
491
+ updates: (state, secretKey) => {
492
+ const batchSize = config.batchUpdates?.size ?? 10;
493
+ const batchTimeout = require_const.millis(config.batchUpdates?.timeout ?? 1);
494
+ const batchSpacing = config.batchUpdates?.spacing ?? 4;
495
+ return require_const.pipe(indexerSyncService.subscribeWallet(state), require_watch.groupedWithin(batchSize, batchTimeout), require_watch.map(require_const.toArray), require_watch.map((data) => WalletSyncUpdate$1.create(data, secretKey, /* @__PURE__ */ new Date())), batchSpacing > 0 ? require_watch.schedule(require_watch.spaced(require_const.millis(batchSpacing))) : (eventsStream) => eventsStream, require_watch.provideSomeLayer(indexerSyncService.connectionLayer()));
496
+ },
497
+ blockData: () => {
498
+ return require_const.gen(function* () {
499
+ return (yield* (yield* require_watch.BlockHash)({ offset: null })).block;
500
+ }).pipe(require_const.provide(indexerSyncService.queryClient()), require_const.scoped$1, require_const.catchAll((err) => require_const.fail$1(new OtherWalletError$1({
501
+ message: `Encountered unexpected error: ${err.message}`,
502
+ cause: err
503
+ }))), require_const.flatMap((blockData) => {
504
+ if (!blockData) throw new OtherWalletError$1({ message: "Unable to fetch block data" });
505
+ return require_watch.ledgerTry(() => ({
506
+ hash: blockData.hash,
507
+ height: blockData.height,
508
+ ledgerParameters: _midnight_ntwrk_ledger_v8.LedgerParameters.deserialize(require__polyfill_buffer_patch.import_buffer.Buffer.from(blockData.ledgerParameters, "hex")),
509
+ timestamp: new Date(blockData.timestamp)
510
+ }));
511
+ }));
512
+ }
513
+ };
514
+ };
515
+ const makeIndexerSyncService = (config) => {
516
+ return {
517
+ queryClient() {
518
+ return require_const.pipe(require_watch.layer$1({ url: config.indexerClientConnection.indexerHttpUrl }), require_const.mapError((error) => new OtherWalletError$1(error)));
519
+ },
520
+ connectionLayer() {
521
+ const { indexerClientConnection } = config;
522
+ return require_watch.createWebSocketUrl(indexerClientConnection.indexerHttpUrl, indexerClientConnection.indexerWsUrl).pipe(require_const.flatMap$4((url) => require_watch.make(url)), require_const.match$4({
523
+ onLeft: (error) => require_const.fail(error),
524
+ onRight: (url) => require_watch.layer({
525
+ url,
526
+ keepAlive: indexerClientConnection.keepAlive
527
+ })
528
+ }), require_const.mapError((e) => new SyncWalletError$1({
529
+ message: "Failed to to obtain correct indexer URLs",
530
+ cause: e
531
+ })));
532
+ },
533
+ subscribeWallet(state) {
534
+ const { appliedIndex } = state.progress;
535
+ const bufferSize = config.indexerClientConnection.bufferSize ?? 1e4;
536
+ const resumeThreshold = config.indexerClientConnection.resumeThreshold ?? 100;
537
+ const resumeFrom = appliedIndex - 1n;
538
+ return require_const.pipe(require_watch.DustLedgerEvents.runWithBackpressure({
539
+ bufferSize,
540
+ resumeThreshold,
541
+ from: resumeFrom,
542
+ variables: (cursor) => ({ id: cursor < 0n ? null : Number(cursor) }),
543
+ key: (r) => BigInt(r.dustLedgerEvents.id)
544
+ }), require_watch.mapEffect((subscription) => require_const.pipe(require_const.decodeUnknownEither(SyncEventsUpdateSchema)(subscription.dustLedgerEvents), require_const.mapLeft((err) => new SyncWalletError$1(err)), require_watch.toEffect)), require_watch.mapError((error) => new SyncWalletError$1(error)));
545
+ }
546
+ };
547
+ };
548
+ const makeDefaultSyncCapability = () => {
549
+ return { applyUpdate(state, wrappedUpdate) {
550
+ const { updates, secretKey } = wrappedUpdate;
551
+ if (updates.length === 0) return [state, {
552
+ changes: [],
553
+ protocolVersion: Number(state.protocolVersion)
554
+ }];
555
+ const appliedIndex = state.progress.appliedIndex;
556
+ const freshUpdates = updates.filter((u) => BigInt(u.id) > appliedIndex);
557
+ const highestRelevantWalletIndex = BigInt(updates.at(-1).maxId);
558
+ const [newState, changes] = freshUpdates.length === 0 ? [state, []] : CoreWallet$1.applyEventsWithChanges(state, secretKey, freshUpdates.map((u) => u.raw), wrappedUpdate.timestamp);
559
+ const updatedState = CoreWallet$1.updateProgress(newState, {
560
+ appliedIndex: freshUpdates.length === 0 ? appliedIndex : BigInt(freshUpdates.at(-1).id),
561
+ highestRelevantWalletIndex,
562
+ isConnected: true
563
+ });
564
+ return [updatedState, {
565
+ changes,
566
+ protocolVersion: Number(updatedState.protocolVersion)
567
+ }];
568
+ } };
569
+ };
570
+ //#endregion
571
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/TransactionHistory.js
572
+ const DustUtxoInfoSchema = require_const.Struct({
573
+ initialValue: require_const.BigInt$,
574
+ nonce: require_const.BigInt$,
575
+ seq: require_const.Number$,
576
+ backingNight: require_const.String$,
577
+ mtIndex: require_const.BigInt$
578
+ });
579
+ const DustSectionSchema = require_const.Struct({
580
+ receivedUtxos: require_const.Array$(DustUtxoInfoSchema),
581
+ spentUtxos: require_const.Array$(DustUtxoInfoSchema)
582
+ });
583
+ require_const.Struct({
584
+ hash: require_const.TransactionHashSchema,
585
+ protocolVersion: require_const.Number$,
586
+ status: require_const.TransactionHistoryStatusSchema,
587
+ dust: DustSectionSchema
588
+ });
589
+ const utxoEquals = require_const.equivalence(DustUtxoInfoSchema);
590
+ const mergeDustSections = (existing, incoming) => ({
591
+ receivedUtxos: require_const.unionWith$1(existing.receivedUtxos, incoming.receivedUtxos, utxoEquals),
592
+ spentUtxos: require_const.unionWith$1(existing.spentUtxos, incoming.spentUtxos, utxoEquals)
593
+ });
594
+ const convertQualifiedDustOutput = (utxo) => ({
595
+ initialValue: utxo.initialValue,
596
+ nonce: utxo.nonce,
597
+ seq: utxo.seq,
598
+ backingNight: utxo.backingNight,
599
+ mtIndex: utxo.mtIndex
600
+ });
601
+ const convertUpdateToStorageEntry$1 = (changes, metadata, protocolVersion) => ({
602
+ hash: changes.source,
603
+ protocolVersion,
604
+ status: metadata.status,
605
+ dust: {
606
+ receivedUtxos: changes.receivedUtxos.map(convertQualifiedDustOutput),
607
+ spentUtxos: changes.spentUtxos.map(convertQualifiedDustOutput)
608
+ }
609
+ });
610
+ const upsertDustEntry = (txHistoryStorage, entry) => require_const.tryPromise({
611
+ try: () => txHistoryStorage.upsert(entry),
612
+ catch: (e) => new TransactionHistoryError$1({
613
+ message: `Failed to upsert history entry for ${entry.hash}`,
614
+ cause: e
615
+ })
616
+ });
617
+ const makeDefaultTransactionHistoryService$1 = (config, _getContext) => {
618
+ const txHistoryStorage = config.txHistoryStorage;
619
+ const queryClientLayer = require_watch.layer$1({ url: config.indexerClientConnection.indexerHttpUrl });
620
+ return {
621
+ put: (changes, metadata, protocolVersion) => {
622
+ return upsertDustEntry(txHistoryStorage, convertUpdateToStorageEntry$1(changes, metadata, protocolVersion));
623
+ },
624
+ getTransactionDetails: (hash) => require_const.gen(function* () {
625
+ const tx = (yield* (yield* require_watch.TransactionHistoryDetail)({ transactionHash: hash })).transactions[0];
626
+ const rawStatus = tx.__typename === "RegularTransaction" ? tx.transactionResult.status : void 0;
627
+ const status = rawStatus === "FAILURE" || rawStatus === "PARTIAL_SUCCESS" ? rawStatus : "SUCCESS";
628
+ return {
629
+ hash: tx.hash,
630
+ timestamp: tx.block.timestamp,
631
+ status
632
+ };
633
+ }).pipe(require_const.provide(queryClientLayer), require_const.scoped$1, require_const.retry(require_watch.exponential(require_const.seconds(1)).pipe(require_watch.compose(require_watch.recurs(3)))), require_const.mapError$1((cause) => new TransactionHistoryError$1({
634
+ message: `Failed to fetch transaction metadata for ${hash}`,
635
+ cause
636
+ })))
637
+ };
638
+ };
639
+ //#endregion
640
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Keys.js
641
+ const makeDefaultKeysCapability$1 = () => {
642
+ return {
643
+ getPublicKey: (state) => {
644
+ return state.publicKey.publicKey;
645
+ },
646
+ getAddress: (state) => {
647
+ return new require_dist.DustAddress(state.publicKey.publicKey);
648
+ }
649
+ };
650
+ };
651
+ //#endregion
652
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/CoinsAndBalances.js
653
+ const chooseCoin = (coins) => coins.filter((coin) => coin.value > 0n).toSorted((a, b) => Number(a.value - b.value)).at(0);
654
+ const FAKE_NONCE = "0".repeat(64);
655
+ const makeDefaultCoinsAndBalancesCapability$1 = (_config, getContext) => {
656
+ const getWalletBalance = (state, time) => {
657
+ return state.state.walletBalance(time);
658
+ };
659
+ const getGenerationInfo = (state, coin) => {
660
+ const info = state.state.generationInfo(coin);
661
+ return info && info.dtime ? {
662
+ ...info,
663
+ dtime: /* @__PURE__ */ new Date(+info.dtime)
664
+ } : info;
665
+ };
666
+ const resolveTime = (state, time) => time ?? state.state.syncTime;
667
+ const toFullInfo = (state, coins, time) => coins.flatMap((coin) => {
668
+ const genInfo = getGenerationInfo(state, coin);
669
+ return genInfo ? [{
670
+ token: coin,
671
+ ...getFullDustInfo(state.state.params, genInfo, coin, time)
672
+ }] : [];
673
+ });
674
+ const availableDustTokens = (state) => {
675
+ const pendingSpends = new Set([...state.pendingDust.values()].map((coin) => coin.nonce));
676
+ return require_const.pipe(state.state.utxos, require_const.filter$2((coin) => !pendingSpends.has(coin.nonce)));
677
+ };
678
+ const getAvailableCoins = (state, time) => toFullInfo(state, availableDustTokens(state), resolveTime(state, time));
679
+ const getPendingCoins = (state, time) => toFullInfo(state, state.pendingDust, resolveTime(state, time));
680
+ const getTotalCoins = (state, time) => {
681
+ const effectiveTime = resolveTime(state, time);
682
+ return [...getAvailableCoins(state, effectiveTime), ...getPendingCoins(state, effectiveTime)];
683
+ };
684
+ const getAvailableCoinsWithGeneratedDust = (state, currentTime) => getAvailableCoins(state, currentTime).map((info) => ({
685
+ token: info.token,
686
+ value: info.generatedNow
687
+ }));
688
+ const getFullDustInfo = (parameters, genInfo, coin, currentTime) => {
689
+ const generatedValue = _midnight_ntwrk_ledger_v8.updatedValue(coin.ctime, coin.initialValue, genInfo, currentTime, parameters);
690
+ return {
691
+ dtime: genInfo.dtime,
692
+ maxCap: genInfo.value * parameters.nightDustRatio,
693
+ maxCapReachedAt: require_watch.addSeconds(coin.ctime, parameters.timeToCapSeconds),
694
+ generatedNow: generatedValue,
695
+ rate: genInfo.value * parameters.generationDecayRate
696
+ };
697
+ };
698
+ const estimateDustGeneration = (state, nightUtxos, currentTime) => {
699
+ const dustPublicKey = getContext().keysCapability.getPublicKey(state);
700
+ return require_const.pipe(nightUtxos, require_const.map$6((utxo) => {
701
+ const genInfo = fakeGenerationInfo(utxo, dustPublicKey);
702
+ const fakeDustCoin = fakeDustToken(dustPublicKey, utxo);
703
+ return {
704
+ utxo,
705
+ dust: getFullDustInfo(state.state.params, genInfo, fakeDustCoin, currentTime)
706
+ };
707
+ }));
708
+ };
709
+ /** Create a fake generation info for a given Utxo. It allows to estimate the Dust generation from it */
710
+ const fakeGenerationInfo = (utxo, dustPublicKey) => {
711
+ return {
712
+ value: utxo.value,
713
+ owner: dustPublicKey,
714
+ nonce: FAKE_NONCE,
715
+ dtime: void 0
716
+ };
717
+ };
718
+ /** Create a fake dust coin for a given Utxo. It allows to estimate full details of the Dust generation from it */
719
+ const fakeDustToken = (dustPublicKey, utxo) => ({
720
+ initialValue: 0n,
721
+ owner: dustPublicKey,
722
+ nonce: 0n,
723
+ seq: 0,
724
+ ctime: utxo.ctime,
725
+ backingNight: "",
726
+ mtIndex: 0n
727
+ });
728
+ const splitNightUtxos = (utxos) => {
729
+ const [guaranteed, fallible] = require_const.pipe(utxos, require_const.sort(require_const.pipe(require_const.bigint, require_const.reverse, require_const.mapInput$1((coin) => coin.dust.generatedNow))), require_const.splitAt$1(1));
730
+ return {
731
+ guaranteed,
732
+ fallible
733
+ };
734
+ };
735
+ return {
736
+ getWalletBalance,
737
+ getAvailableCoins,
738
+ getPendingCoins,
739
+ getTotalCoins,
740
+ getAvailableCoinsWithGeneratedDust,
741
+ getGenerationInfo,
742
+ estimateDustGeneration,
743
+ splitNightUtxos
744
+ };
745
+ };
746
+ //#endregion
747
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Utils.js
748
+ const SignatureMarker = {
749
+ signature: "signature",
750
+ signatureErased: "signature-erased"
751
+ };
752
+ const ProofMarker = {
753
+ proof: "proof",
754
+ preProof: "pre-proof",
755
+ noProof: "no-proof"
756
+ };
757
+ const BindingMarker = {
758
+ binding: "binding",
759
+ preBinding: "pre-binding",
760
+ noBinding: "no-binding"
761
+ };
762
+ //#endregion
763
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/Transacting.js
764
+ const makeDefaultTransactingCapability$1 = (config, getContext) => {
765
+ return new TransactingCapabilityImplementation$1(config.networkId, config.costParameters, () => getContext().coinSelection, () => getContext().coinsAndBalancesCapability, () => getContext().keysCapability);
766
+ };
767
+ /**
768
+ * Distributes the fee across multiple inputs, draining smaller inputs first when the fee exceeds any single input's
769
+ * value. Finds the next available intent segment id in a transaction.
770
+ *
771
+ * Fallible intent segments occupy the range `[1, 65535]`; segment `0` is reserved for the guaranteed section and is
772
+ * never returned.
773
+ *
774
+ * @param transaction - Transaction whose intent map is inspected.
775
+ * @returns `Some(segmentId)` with the lowest unused id, or `None` if all 65535 fallible segments are taken.
776
+ */
777
+ const findAvailableSegmentId = (transaction) => {
778
+ const used = new Set(transaction.intents?.keys() ?? []);
779
+ return require_const.pipe(require_const.range$1(1, 65535), require_const.findFirst$2((segmentId) => !used.has(segmentId)));
780
+ };
781
+ /**
782
+ * Distributes the fee across multiple inputs, draining smaller inputs first when the fee exceeds any single input's
783
+ * value.
784
+ */
785
+ const distributeFeeAcrossInputs = (inputs, fee) => inputs.reduce(({ result, remaining }, input) => {
786
+ const deduction = remaining >= input.value ? input.value : remaining;
787
+ return {
788
+ result: [...result, {
789
+ ...input,
790
+ value: deduction
791
+ }],
792
+ remaining: remaining - deduction
793
+ };
794
+ }, {
795
+ result: [],
796
+ remaining: fee
797
+ }).result;
798
+ var TransactingCapabilityImplementation$1 = class TransactingCapabilityImplementation$1 {
799
+ networkId;
800
+ costParams;
801
+ getCoinSelection;
802
+ getCoins;
803
+ getKeys;
804
+ constructor(networkId, costParams, getCoinSelection, getCoins, getKeys) {
805
+ this.getCoins = getCoins;
806
+ this.networkId = networkId;
807
+ this.costParams = costParams;
808
+ this.getCoinSelection = getCoinSelection;
809
+ this.getKeys = getKeys;
810
+ }
811
+ createDustGenerationTransaction(currentTime, ttl, nightUtxos, nightVerifyingKey, dustReceiverAddress) {
812
+ const makeOffer = (utxos) => {
813
+ if (utxos.length === 0) return require_const.none();
814
+ const totalValue = require_const.pipe(utxos, require_const.map$7((coin) => coin.utxo.value), require_const.sumAll);
815
+ const inputs = utxos.map(({ utxo }) => ({
816
+ ...utxo,
817
+ owner: nightVerifyingKey
818
+ }));
819
+ const output = {
820
+ owner: (0, _midnight_ntwrk_ledger_v8.addressFromKey)(nightVerifyingKey),
821
+ type: (0, _midnight_ntwrk_ledger_v8.nativeToken)().raw,
822
+ value: totalValue
823
+ };
824
+ return require_const.some(_midnight_ntwrk_ledger_v8.UnshieldedOffer.new(inputs, [output], []));
825
+ };
826
+ return require_const.gen$1(this, function* () {
827
+ const receiver = dustReceiverAddress ? dustReceiverAddress.data : void 0;
828
+ return yield* require_watch.ledgerTry(() => {
829
+ const network = this.networkId;
830
+ const splitResult = this.getCoins().splitNightUtxos(nightUtxos);
831
+ const feePayment = receiver ? require_const.pipe(splitResult.guaranteed, require_const.filter$3((coin) => !coin.utxo.registeredForDustGeneration), require_const.map$7((coin) => coin.dust.generatedNow), require_const.sumAll) : 0n;
832
+ const maybeGuaranteedOffer = makeOffer(splitResult.guaranteed);
833
+ const maybeFallibleOffer = makeOffer(splitResult.fallible);
834
+ const dustRegistration = new _midnight_ntwrk_ledger_v8.DustRegistration(SignatureMarker.signature, nightVerifyingKey, receiver, feePayment);
835
+ const dustActions = new _midnight_ntwrk_ledger_v8.DustActions(SignatureMarker.signature, ProofMarker.preProof, currentTime, [], [dustRegistration]);
836
+ const intent = require_const.pipe(_midnight_ntwrk_ledger_v8.Intent.new(ttl), (intent) => require_const.match$3(maybeGuaranteedOffer, {
837
+ onNone: () => intent,
838
+ onSome: (guaranteedOffer) => {
839
+ intent.guaranteedUnshieldedOffer = guaranteedOffer;
840
+ return intent;
841
+ }
842
+ }), (intent) => require_const.match$3(maybeFallibleOffer, {
843
+ onNone: () => intent,
844
+ onSome: (fallibleOffer) => {
845
+ intent.fallibleUnshieldedOffer = fallibleOffer;
846
+ return intent;
847
+ }
848
+ }), (intent) => {
849
+ intent.dustActions = dustActions;
850
+ return intent;
851
+ });
852
+ return _midnight_ntwrk_ledger_v8.Transaction.fromParts(network, void 0, void 0, intent);
853
+ });
854
+ });
855
+ }
856
+ splitNightUtxosForDustRegistration(utxosWithDustValue, isRegistration) {
857
+ const splitResult = this.getCoins().splitNightUtxos(utxosWithDustValue);
858
+ const feePayment = isRegistration ? require_const.pipe(splitResult.guaranteed, require_const.filter$3((coin) => !coin.utxo.registeredForDustGeneration), require_const.map$7((coin) => coin.dust.generatedNow), require_const.sumAll) : 0n;
859
+ return {
860
+ guaranteedUtxos: splitResult.guaranteed,
861
+ fallibleUtxos: splitResult.fallible,
862
+ feePayment
863
+ };
864
+ }
865
+ attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment) {
866
+ return require_const.gen$1(this, function* () {
867
+ const intent = transaction.intents?.get(1);
868
+ if (!intent) return yield* require_const.left(new TransactingError({ message: "No intent found at segment 1; expected an intent built by rotateUtxos" }));
869
+ if (intent.dustActions !== void 0 && intent.dustActions.registrations.length > 0) return yield* require_const.left(new TransactingError({ message: "Intent at segment 1 already has a dust registration attached" }));
870
+ return yield* require_watch.ledgerTry(() => {
871
+ const receiver = dustReceiverAddress ? dustReceiverAddress.data : void 0;
872
+ const dustRegistration = new _midnight_ntwrk_ledger_v8.DustRegistration(SignatureMarker.signature, nightVerifyingKey, receiver, feePayment);
873
+ const dustActions = new _midnight_ntwrk_ledger_v8.DustActions(SignatureMarker.signature, ProofMarker.preProof, currentTime, [], [dustRegistration]);
874
+ const newIntent = _midnight_ntwrk_ledger_v8.Intent.deserialize(SignatureMarker.signature, ProofMarker.preProof, BindingMarker.preBinding, intent.serialize());
875
+ newIntent.dustActions = dustActions;
876
+ const newTransaction = _midnight_ntwrk_ledger_v8.Transaction.deserialize(SignatureMarker.signature, ProofMarker.preProof, BindingMarker.preBinding, transaction.serialize());
877
+ newTransaction.intents = newTransaction.intents.set(1, newIntent);
878
+ return newTransaction;
879
+ });
880
+ });
881
+ }
882
+ addDustRegistrationSignature(transaction, signatureData) {
883
+ return require_const.gen$1(this, function* () {
884
+ const intent = transaction.intents?.get(1);
885
+ if (!intent) return yield* require_const.left(new TransactingError({ message: "No intent found in the transaction intents with segment = 1" }));
886
+ const { dustActions } = intent;
887
+ if (!dustActions) return yield* require_const.left(new TransactingError({ message: "No dustActions found in intent" }));
888
+ const [registration, ...restRegistrations] = dustActions.registrations;
889
+ if (!registration) return yield* require_const.left(new TransactingError({ message: "No registrations found in dustActions" }));
890
+ return yield* require_watch.ledgerTry(() => {
891
+ const signature = new _midnight_ntwrk_ledger_v8.SignatureEnabled(signatureData);
892
+ const registrationWithSignature = new _midnight_ntwrk_ledger_v8.DustRegistration(signature.instance, registration.nightKey, registration.dustAddress, registration.allowFeePayment, signature);
893
+ const newDustActions = new _midnight_ntwrk_ledger_v8.DustActions(signature.instance, ProofMarker.preProof, dustActions.ctime, dustActions.spends, [registrationWithSignature, ...restRegistrations]);
894
+ const newIntent = _midnight_ntwrk_ledger_v8.Intent.deserialize(signature.instance, ProofMarker.preProof, BindingMarker.preBinding, intent.serialize());
895
+ newIntent.dustActions = newDustActions;
896
+ const newTransaction = _midnight_ntwrk_ledger_v8.Transaction.deserialize(signature.instance, ProofMarker.preProof, BindingMarker.preBinding, transaction.serialize());
897
+ newTransaction.intents = newTransaction.intents.set(1, newIntent);
898
+ return newTransaction;
899
+ });
900
+ });
901
+ }
902
+ addDustGenerationSignature(transaction, signatureData) {
903
+ return require_const.gen$1(this, function* () {
904
+ const intent = transaction.intents?.get(1);
905
+ if (!intent) return yield* require_const.left(new TransactingError({ message: "No intent found in the transaction intents with segment = 1" }));
906
+ const { dustActions, guaranteedUnshieldedOffer, fallibleUnshieldedOffer } = intent;
907
+ if (!dustActions) return yield* require_const.left(new TransactingError({ message: "No dustActions found in intent" }));
908
+ if (!guaranteedUnshieldedOffer) return yield* require_const.left(new TransactingError({ message: "No guaranteedUnshieldedOffer found in intent" }));
909
+ const [registration, ...restRegistrations] = dustActions.registrations;
910
+ if (!registration) return yield* require_const.left(new TransactingError({ message: "No registrations found in dustActions" }));
911
+ return yield* require_watch.ledgerTry(() => {
912
+ const signature = new _midnight_ntwrk_ledger_v8.SignatureEnabled(signatureData);
913
+ const registrationWithSignature = new _midnight_ntwrk_ledger_v8.DustRegistration(signature.instance, registration.nightKey, registration.dustAddress, registration.allowFeePayment, signature);
914
+ const newDustActions = new _midnight_ntwrk_ledger_v8.DustActions(signature.instance, ProofMarker.preProof, dustActions.ctime, dustActions.spends, [registrationWithSignature, ...restRegistrations]);
915
+ const newIntent = _midnight_ntwrk_ledger_v8.Intent.deserialize(signature.instance, ProofMarker.preProof, BindingMarker.preBinding, intent.serialize());
916
+ newIntent.dustActions = newDustActions;
917
+ const inputsLen = guaranteedUnshieldedOffer.inputs.length;
918
+ const signatures = [];
919
+ for (let i = 0; i < inputsLen; ++i) signatures.push(guaranteedUnshieldedOffer.signatures.at(i) ?? signatureData);
920
+ newIntent.guaranteedUnshieldedOffer = guaranteedUnshieldedOffer.addSignatures(signatures);
921
+ if (fallibleUnshieldedOffer) {
922
+ const inputsLen = fallibleUnshieldedOffer.inputs.length;
923
+ const signatures = [];
924
+ for (let i = 0; i < inputsLen; ++i) signatures.push(fallibleUnshieldedOffer.signatures.at(i) ?? signatureData);
925
+ newIntent.fallibleUnshieldedOffer = fallibleUnshieldedOffer.addSignatures(signatures);
926
+ }
927
+ const newTransaction = _midnight_ntwrk_ledger_v8.Transaction.deserialize(signature.instance, ProofMarker.preProof, BindingMarker.preBinding, transaction.serialize());
928
+ newTransaction.intents = newTransaction.intents.set(1, newIntent);
929
+ return newTransaction;
930
+ });
931
+ });
932
+ }
933
+ calculateFee(transaction, ledgerParams) {
934
+ return transaction.feesWithMargin(ledgerParams, this.costParams.feeBlocksMargin) + (this.costParams.additionalFeeOverhead ?? 0n);
935
+ }
936
+ dryRunFee(recipeInputs, transactions, secretKey, state, ttl, currentTime, ledgerParams) {
937
+ const network = this.networkId;
938
+ const [spends] = CoreWallet$1.spendCoins(state, secretKey, recipeInputs, currentTime);
939
+ const intent = _midnight_ntwrk_ledger_v8.Intent.new(ttl);
940
+ intent.dustActions = new _midnight_ntwrk_ledger_v8.DustActions(SignatureMarker.signature, ProofMarker.preProof, currentTime, [...spends], []);
941
+ const [first, ...rest] = transactions.map((tx) => tx.eraseProofs());
942
+ const mergedExisting = first ? rest.reduce((acc, tx) => acc.merge(tx), first) : void 0;
943
+ const segmentId = mergedExisting ? require_const.getOrElse(findAvailableSegmentId(mergedExisting), () => 1) : 1;
944
+ const erasedBalancing = _midnight_ntwrk_ledger_v8.Transaction.fromParts(network).addIntent({
945
+ tag: "specific",
946
+ value: segmentId
947
+ }, intent).eraseProofs();
948
+ const mergedTx = mergedExisting ? mergedExisting.merge(erasedBalancing) : erasedBalancing;
949
+ return this.calculateFee(mergedTx, ledgerParams);
950
+ }
951
+ static feeImbalance(transaction, totalFee) {
952
+ const [_, imbalance] = transaction.imbalances(0, totalFee).entries().find(([tt, _]) => tt.tag === "dust") ?? [];
953
+ return imbalance ?? 0n;
954
+ }
955
+ computeBalancingRecipe(secretKey, state, transactions, ttl, currentTime, ledgerParams) {
956
+ const initialFees = transactions.reduce((total, transaction) => total + TransactingCapabilityImplementation$1.feeImbalance(transaction, this.calculateFee(transaction, ledgerParams)), 0n);
957
+ const dust = this.getCoins().getAvailableCoinsWithGeneratedDust(state, currentTime);
958
+ return require_const.pipe(require_const.iterate({
959
+ currentFee: initialFees,
960
+ recipeInputs: [],
961
+ converged: false
962
+ }, {
963
+ while: (s) => !s.converged,
964
+ body: ({ currentFee }) => require_const.try_({
965
+ try: () => {
966
+ const recipeInputs = require_watch.getBalanceRecipe({
967
+ coins: dust.map((coin) => ({
968
+ type: "dust",
969
+ value: coin.value,
970
+ token: coin.token
971
+ })),
972
+ initialImbalances: require_watch.Imbalances.fromEntry("dust", currentFee),
973
+ feeTokenType: "dust",
974
+ coinSelection: this.getCoinSelection(),
975
+ transactionCostModel: {
976
+ inputFeeOverhead: 0n,
977
+ outputFeeOverhead: 0n
978
+ },
979
+ createOutput: (coin) => coin,
980
+ isCoinEqual: (a, b) => a.token.nonce === b.token.nonce
981
+ }).inputs.map(({ token, value }) => ({
982
+ token,
983
+ value
984
+ }));
985
+ const newFee = this.dryRunFee(recipeInputs, transactions, secretKey, state, ttl, currentTime, ledgerParams);
986
+ return {
987
+ currentFee: newFee,
988
+ recipeInputs,
989
+ converged: newFee <= recipeInputs.reduce((sum, input) => sum + input.value, 0n)
990
+ };
991
+ },
992
+ catch: (err) => {
993
+ if (err instanceof require_watch.InsufficientFundsError) return new InsufficientFundsError$1({
994
+ message: err.message,
995
+ tokenType: err.tokenType
996
+ });
997
+ else return new OtherWalletError$1({
998
+ message: err instanceof Error ? err.message : "Dust balancing failed",
999
+ cause: err
1000
+ });
1001
+ }
1002
+ })
1003
+ }), require_const.either, require_const.runSync, require_const.map$9(({ currentFee, recipeInputs }) => ({
1004
+ fee: currentFee,
1005
+ recipeInputs: distributeFeeAcrossInputs(recipeInputs, currentFee)
1006
+ })));
1007
+ }
1008
+ estimateFee(secretKey, state, transactions, ttl, currentTime, ledgerParams) {
1009
+ return require_const.pipe(this.computeBalancingRecipe(secretKey, state, transactions, ttl, currentTime, ledgerParams), require_const.map$9(({ fee }) => fee));
1010
+ }
1011
+ balanceTransactions(secretKey, state, transactions, ttl, currentTime, ledgerParams) {
1012
+ const networkId = this.networkId;
1013
+ return require_const.pipe(this.computeBalancingRecipe(secretKey, state, transactions, ttl, currentTime, ledgerParams), require_const.flatMap$4(({ recipeInputs }) => {
1014
+ return require_watch.ledgerTry(() => {
1015
+ const intent = _midnight_ntwrk_ledger_v8.Intent.new(ttl);
1016
+ const [spends, updatedState] = CoreWallet$1.spendCoins(state, secretKey, recipeInputs, currentTime);
1017
+ intent.dustActions = new _midnight_ntwrk_ledger_v8.DustActions(SignatureMarker.signature, ProofMarker.preProof, currentTime, [...spends], []);
1018
+ const [first, ...rest] = transactions.map((tx) => tx.eraseProofs());
1019
+ const mergedExisting = first ? rest.reduce((acc, tx) => acc.merge(tx), first) : void 0;
1020
+ const segmentId = mergedExisting ? require_const.getOrElse(findAvailableSegmentId(mergedExisting), () => 1) : 1;
1021
+ return [_midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId).addIntent({
1022
+ tag: "specific",
1023
+ value: segmentId
1024
+ }, intent), updatedState];
1025
+ });
1026
+ }));
1027
+ }
1028
+ revertTransaction(state, transaction) {
1029
+ return require_const.try_$1({
1030
+ try: () => CoreWallet$1.revertTransaction(state, transaction),
1031
+ catch: (err) => {
1032
+ return new OtherWalletError$1({
1033
+ message: `Error while reverting transaction ${transaction.identifiers().at(0)}`,
1034
+ cause: err
1035
+ });
1036
+ }
1037
+ });
1038
+ }
1039
+ };
1040
+ //#endregion
1041
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/v1/V1Builder.js
1042
+ var V1Builder$1 = class V1Builder$1 {
1043
+ #buildState;
1044
+ constructor(buildState = {}) {
1045
+ this.#buildState = buildState;
1046
+ }
1047
+ withDefaults() {
1048
+ return this.withDefaultTransactionType().withSyncDefaults().withSerializationDefaults().withTransactingDefaults().withCoinsAndBalancesDefaults().withTransactionHistoryDefaults().withKeysDefaults().withCoinSelectionDefaults();
1049
+ }
1050
+ withTransactionType() {
1051
+ return new V1Builder$1({
1052
+ ...this.#buildState,
1053
+ transactingCapability: void 0
1054
+ });
1055
+ }
1056
+ withDefaultTransactionType() {
1057
+ return this.withTransactionType();
1058
+ }
1059
+ withSyncDefaults() {
1060
+ return this.withSync(makeDefaultSyncService, makeDefaultSyncCapability);
1061
+ }
1062
+ withSync(syncService, syncCapability) {
1063
+ return new V1Builder$1({
1064
+ ...this.#buildState,
1065
+ syncService,
1066
+ syncCapability
1067
+ });
1068
+ }
1069
+ withSerializationDefaults() {
1070
+ return this.withSerialization(makeDefaultV1SerializationCapability$1);
1071
+ }
1072
+ withSerialization(serializationCapability) {
1073
+ return new V1Builder$1({
1074
+ ...this.#buildState,
1075
+ serializationCapability
1076
+ });
1077
+ }
1078
+ withTransactingDefaults() {
1079
+ return this.withTransacting(makeDefaultTransactingCapability$1);
1080
+ }
1081
+ withTransacting(transactingCapability) {
1082
+ return new V1Builder$1({
1083
+ ...this.#buildState,
1084
+ transactingCapability
1085
+ });
1086
+ }
1087
+ withCoinSelection(coinSelection) {
1088
+ return new V1Builder$1({
1089
+ ...this.#buildState,
1090
+ coinSelection
1091
+ });
1092
+ }
1093
+ withCoinSelectionDefaults() {
1094
+ return this.withCoinSelection(() => chooseCoin);
1095
+ }
1096
+ withCoinsAndBalancesDefaults() {
1097
+ return this.withCoinsAndBalances(makeDefaultCoinsAndBalancesCapability$1);
1098
+ }
1099
+ withCoinsAndBalances(coinsAndBalancesCapability) {
1100
+ return new V1Builder$1({
1101
+ ...this.#buildState,
1102
+ coinsAndBalancesCapability
1103
+ });
1104
+ }
1105
+ withTransactionHistoryDefaults() {
1106
+ return this.withTransactionHistory(makeDefaultTransactionHistoryService$1);
1107
+ }
1108
+ withTransactionHistory(transactionHistoryService) {
1109
+ return new V1Builder$1({
1110
+ ...this.#buildState,
1111
+ transactionHistoryService
1112
+ });
1113
+ }
1114
+ withKeysDefaults() {
1115
+ return this.withKeys(makeDefaultKeysCapability$1);
1116
+ }
1117
+ withKeys(keysCapability) {
1118
+ return new V1Builder$1({
1119
+ ...this.#buildState,
1120
+ keysCapability
1121
+ });
1122
+ }
1123
+ build(configuration) {
1124
+ const v1Context = this.#buildContextFromBuildState(configuration);
1125
+ return {
1126
+ __polyTag__: V1Tag$1,
1127
+ coinsAndBalances: v1Context.coinsAndBalancesCapability,
1128
+ keys: v1Context.keysCapability,
1129
+ serialization: v1Context.serializationCapability,
1130
+ transactionHistory: v1Context.transactionHistoryService,
1131
+ start(context) {
1132
+ return require_const.gen(function* () {
1133
+ return new RunningV1Variant$1(yield* require_const.Scope, context, v1Context);
1134
+ });
1135
+ },
1136
+ migrateState(prevState) {
1137
+ return require_const.succeed(prevState);
1138
+ },
1139
+ deserializeState: (serialized) => {
1140
+ return v1Context.serializationCapability.deserialize(null, serialized);
1141
+ }
1142
+ };
1143
+ }
1144
+ #buildContextFromBuildState(configuration) {
1145
+ if (!isBuildStateFull$1(this.#buildState)) throw new Error("Not all components are configured in V1 Builder");
1146
+ const { syncCapability, syncService, transactingCapability, serializationCapability, coinSelection, coinsAndBalancesCapability, keysCapability, transactionHistoryService } = this.#buildState;
1147
+ const getContext = () => context;
1148
+ const context = {
1149
+ serializationCapability: serializationCapability(configuration, getContext),
1150
+ syncCapability: syncCapability(configuration, getContext),
1151
+ syncService: syncService(configuration, getContext),
1152
+ transactingCapability: transactingCapability(configuration, getContext),
1153
+ coinsAndBalancesCapability: coinsAndBalancesCapability(configuration, getContext),
1154
+ keysCapability: keysCapability(configuration, getContext),
1155
+ coinSelection: coinSelection(configuration, getContext),
1156
+ transactionHistoryService: transactionHistoryService(configuration, getContext)
1157
+ };
1158
+ return context;
1159
+ }
1160
+ };
1161
+ const isBuildStateFull$1 = (buildState) => {
1162
+ return [
1163
+ "syncService",
1164
+ "syncCapability",
1165
+ "transactingCapability",
1166
+ "coinSelection",
1167
+ "serializationCapability",
1168
+ "coinsAndBalancesCapability",
1169
+ "keysCapability",
1170
+ "transactionHistoryService"
1171
+ ].every((key) => typeof buildState[key] == "function");
1172
+ };
1173
+ //#endregion
1174
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-dust-wallet/dist/DustWallet.js
1175
+ var DustWalletState = class DustWalletState {
1176
+ static mapState = (variant) => (state) => {
1177
+ const { serialization, coinsAndBalances, keys } = variant;
1178
+ const { transactionHistory } = variant;
1179
+ return new DustWalletState(state, {
1180
+ serialization,
1181
+ coinsAndBalances,
1182
+ keys
1183
+ }, { transactionHistory });
1184
+ };
1185
+ protocolVersion;
1186
+ state;
1187
+ capabilities;
1188
+ services;
1189
+ get totalCoins() {
1190
+ return this.capabilities.coinsAndBalances.getTotalCoins(this.state);
1191
+ }
1192
+ get availableCoins() {
1193
+ return this.capabilities.coinsAndBalances.getAvailableCoins(this.state);
1194
+ }
1195
+ get pendingCoins() {
1196
+ return this.capabilities.coinsAndBalances.getPendingCoins(this.state);
1197
+ }
1198
+ get publicKey() {
1199
+ return this.capabilities.keys.getPublicKey(this.state);
1200
+ }
1201
+ get address() {
1202
+ return this.capabilities.keys.getAddress(this.state);
1203
+ }
1204
+ get progress() {
1205
+ return this.state.progress;
1206
+ }
1207
+ constructor(state, capabilities, services) {
1208
+ this.protocolVersion = state.version;
1209
+ this.state = state.state;
1210
+ this.capabilities = capabilities;
1211
+ this.services = services;
1212
+ }
1213
+ balance(time) {
1214
+ return this.capabilities.coinsAndBalances.getWalletBalance(this.state, time);
1215
+ }
1216
+ estimateDustGeneration(nightUtxos, currentTime) {
1217
+ return this.capabilities.coinsAndBalances.estimateDustGeneration(this.state, nightUtxos, currentTime);
1218
+ }
1219
+ serialize() {
1220
+ return this.capabilities.serialization.serialize(this.state);
1221
+ }
1222
+ };
1223
+ function DustWallet(configuration) {
1224
+ return CustomDustWallet(configuration, new V1Builder$1().withDefaults());
1225
+ }
1226
+ function CustomDustWallet(configuration, builder) {
1227
+ const buildArgs = [configuration];
1228
+ const BaseWallet = require_watch.WalletBuilder.init().withVariant(require_const.MinSupportedVersion, builder).build(...buildArgs);
1229
+ return class CustomDustWalletImplementation extends BaseWallet {
1230
+ static startWithSeed(seed, dustParameters) {
1231
+ const dustSecretKey = _midnight_ntwrk_ledger_v8.DustSecretKey.fromSeed(seed);
1232
+ return CustomDustWalletImplementation.startFirst(CustomDustWalletImplementation, CoreWallet$1.initEmpty(dustParameters, dustSecretKey, CustomDustWalletImplementation.configuration.networkId));
1233
+ }
1234
+ static startWithSecretKey(secretKey, dustParameters) {
1235
+ return CustomDustWalletImplementation.startFirst(CustomDustWalletImplementation, CoreWallet$1.initEmpty(dustParameters, secretKey, CustomDustWalletImplementation.configuration.networkId));
1236
+ }
1237
+ static restore(serializedState) {
1238
+ const deserialized = CustomDustWalletImplementation.allVariantsRecord()[V1Tag$1].variant.deserializeState(serializedState).pipe(require_const.getOrThrow$1);
1239
+ return CustomDustWalletImplementation.startFirst(CustomDustWalletImplementation, deserialized);
1240
+ }
1241
+ state;
1242
+ constructor(runtime, scope) {
1243
+ super(runtime, scope);
1244
+ this.state = this.rawState.pipe(rxjs.map(DustWalletState.mapState(CustomDustWalletImplementation.allVariantsRecord()[V1Tag$1].variant)), rxjs.shareReplay({
1245
+ refCount: true,
1246
+ bufferSize: 1
1247
+ }));
1248
+ }
1249
+ start(secretKey) {
1250
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.startSyncInBackground(secretKey) }).pipe(require_const.runPromise);
1251
+ }
1252
+ async createDustGenerationTransaction(currentTime, ttl, nightUtxos, nightVerifyingKey, dustReceiverAddress) {
1253
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.createDustGenerationTransaction(currentTime, ttl, nightUtxos, nightVerifyingKey, dustReceiverAddress) }).pipe(require_const.runPromise);
1254
+ }
1255
+ async splitNightUtxosForDustRegistration(currentTime, nightUtxos, isRegistration) {
1256
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.splitNightUtxosForDustRegistration(currentTime, nightUtxos, isRegistration) }).pipe(require_const.runPromise);
1257
+ }
1258
+ async attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment) {
1259
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.attachDustRegistration(transaction, currentTime, nightVerifyingKey, dustReceiverAddress, feePayment) }).pipe(require_const.runPromise);
1260
+ }
1261
+ addDustGenerationSignature(transaction, signature) {
1262
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.addDustGenerationSignature(transaction, signature) }).pipe(require_const.runPromise);
1263
+ }
1264
+ addDustRegistrationSignature(transaction, signature) {
1265
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.addDustRegistrationSignature(transaction, signature) }).pipe(require_const.runPromise);
1266
+ }
1267
+ calculateFee(transactions) {
1268
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.calculateFee(transactions) }).pipe(require_const.runPromise);
1269
+ }
1270
+ estimateFee(secretKey, transactions, ttl, currentTime) {
1271
+ const effectiveTtl = ttl ?? new Date(Date.now() + 3600 * 1e3);
1272
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.estimateFee(secretKey, transactions, effectiveTtl, currentTime) }).pipe(require_const.runPromise);
1273
+ }
1274
+ balanceTransactions(secretKey, transactions, ttl, currentTime) {
1275
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.balanceTransactions(secretKey, transactions, ttl, currentTime) }).pipe(require_const.runPromise);
1276
+ }
1277
+ revertTransaction(transaction) {
1278
+ return this.runtime.dispatch({ [V1Tag$1]: (v1) => v1.revertTransaction(transaction) }).pipe(require_const.runPromise);
1279
+ }
1280
+ waitForSyncedState(allowedGap = 0n) {
1281
+ return rxjs.firstValueFrom(this.state.pipe(rxjs.filter((state) => state.state.progress.isCompleteWithin(allowedGap))));
1282
+ }
1283
+ async waitForGeneratedDust(nightUtxos, requiredAmount, clock, opts) {
1284
+ if (nightUtxos.length === 0) throw Error("At least one Night UTXO is required.");
1285
+ if (requiredAmount <= 0n) return;
1286
+ const timeoutMs = opts?.timeoutMs ?? 3e5;
1287
+ await rxjs.firstValueFrom(rxjs.combineLatest([this.state, rxjs.timer(0, 1e3)]).pipe(rxjs.filter(([dustState]) => {
1288
+ return dustState.estimateDustGeneration(nightUtxos, clock.now()).filter((u) => !u.utxo.registeredForDustGeneration).reduce((max, u) => u.dust.generatedNow > max ? u.dust.generatedNow : max, 0n) >= requiredAmount;
1289
+ }), rxjs.timeout({ first: timeoutMs })));
1290
+ }
1291
+ serializeState() {
1292
+ return rxjs.firstValueFrom(this.state).then((state) => state.serialize());
1293
+ }
1294
+ getAddress() {
1295
+ return rxjs.firstValueFrom(this.state).then((state) => state.address);
1296
+ }
1297
+ };
1298
+ }
1299
+ //#endregion
1300
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/WalletError.js
1301
+ const WalletError = {
1302
+ other(err) {
1303
+ let message;
1304
+ if (err) if (typeof err == "object" && "message" in err) message = String(err.message);
1305
+ else if (typeof err == "string") message = err;
1306
+ else message = "";
1307
+ else message = "";
1308
+ return new OtherWalletError({
1309
+ message: `Other wallet error: ${message}`,
1310
+ cause: err
1311
+ });
1312
+ },
1313
+ submission(err) {
1314
+ return new SubmissionError({
1315
+ message: `Transaction submission error: ${err && typeof err == "object" && "message" in err ? String(err.message) : ""}`,
1316
+ cause: err
1317
+ });
1318
+ }
1319
+ };
1320
+ var OtherWalletError = class extends require_const.TaggedError("Wallet.Other") {};
1321
+ var SyncWalletError = class extends require_const.TaggedError("Wallet.Sync") {};
1322
+ var SubmissionError = class extends require_const.TaggedError("Wallet.SubmissionWalletError") {};
1323
+ var InsufficientFundsError = class extends require_const.TaggedError("Wallet.InsufficientFunds") {};
1324
+ var InvalidCoinHashesError = class extends require_const.TaggedError("Wallet.InvalidCoinHashes") {};
1325
+ var TransactionHistoryError = class extends require_const.TaggedError("Wallet.TransactionHistory") {};
1326
+ //#endregion
1327
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/RunningV1Variant.js
1328
+ const progress = (state) => {
1329
+ const appliedIndex = state.progress?.appliedIndex ?? 0n;
1330
+ const highestRelevantWalletIndex = state.progress?.highestRelevantWalletIndex ?? 0n;
1331
+ const sourceGap = (state.progress?.highestIndex ?? 0n) - (state.progress?.highestRelevantIndex ?? 0n);
1332
+ const applyGap = highestRelevantWalletIndex - appliedIndex;
1333
+ return [require_watch.ProgressUpdate({
1334
+ sourceGap,
1335
+ applyGap
1336
+ })];
1337
+ };
1338
+ const protocolVersionChange = (previous, current) => {
1339
+ return previous.protocolVersion != current.protocolVersion ? [require_watch.VersionChange({ change: require_watch.Version({ version: require_const.ProtocolVersion(current.protocolVersion) }) })] : [];
1340
+ };
1341
+ const V1Tag = Symbol("V1");
1342
+ var RunningV1Variant = class {
1343
+ __polyTag__ = V1Tag;
1344
+ #scope;
1345
+ #context;
1346
+ #v1Context;
1347
+ state;
1348
+ constructor(scope, context, v1Context) {
1349
+ this.#scope = scope;
1350
+ this.#context = context;
1351
+ this.#v1Context = v1Context;
1352
+ this.state = require_watch.fromEffect(context.stateRef.get).pipe(require_watch.flatMap((initialState) => context.stateRef.changes.pipe(require_watch.mapAccum(initialState, (previous, current) => {
1353
+ return [current, [previous, current]];
1354
+ }))), require_watch.mapConcat(([previous, current]) => {
1355
+ return [
1356
+ require_watch.State({ state: current }),
1357
+ ...progress(current),
1358
+ ...protocolVersionChange(previous, current)
1359
+ ];
1360
+ }));
1361
+ }
1362
+ startSyncInBackground(startAux) {
1363
+ return this.startSync(startAux).pipe(require_watch.runScoped(require_watch.drain), require_const.forkScoped, require_const.provideService(require_const.Scope, this.#scope));
1364
+ }
1365
+ startSync(startAux) {
1366
+ return require_const.pipe(require_watch.get(this.#context.stateRef), require_watch.fromEffect, require_watch.flatMap((state) => this.#v1Context.syncService.updates(state, startAux)), require_watch.mapEffect((update) => require_watch.modifyEffect(this.#context.stateRef, (state) => require_const.try_({
1367
+ try: () => {
1368
+ const [newState, changesResult] = this.#v1Context.syncCapability.applyUpdate(state, update);
1369
+ return [changesResult, newState];
1370
+ },
1371
+ catch: (err) => new OtherWalletError({
1372
+ message: "Error while applying sync update",
1373
+ cause: err
1374
+ })
1375
+ })).pipe(require_const.flatMap(({ changes, protocolVersion }) => changes.length === 0 ? require_const._void : require_const.pipe(require_const.forEach(changes, (change) => require_const.pipe(this.#v1Context.transactionHistoryService.getTransactionDetails(change.source), require_const.flatMap((metadata) => this.#v1Context.transactionHistoryService.put(change, metadata, protocolVersion)), require_const.catchAllCause((cause) => require_watch.error("Error processing tx history metadata", cause))), {
1376
+ discard: true,
1377
+ concurrency: "unbounded"
1378
+ }), require_const.forkScoped)), require_const.provideService(require_const.Scope, this.#scope))), require_watch.tapError((error$1) => require_watch.error(error$1)), require_watch.retry(require_const.pipe(require_watch.exponential(require_const.seconds(1), 2), require_watch.map$1((delay) => {
1379
+ const maxDelay = require_const.minutes(2);
1380
+ const jitter = require_const.millis(Math.floor(Math.random() * 1e3));
1381
+ const delayWithJitter = require_const.toMillis(delay) + require_const.toMillis(jitter);
1382
+ return require_const.millis(Math.min(delayWithJitter, require_const.toMillis(maxDelay)));
1383
+ }))));
1384
+ }
1385
+ balanceTransaction(secretKeys, tx) {
1386
+ return require_watch.modifyEffect(this.#context.stateRef, (state) => {
1387
+ return require_const.pipe(this.#v1Context.transactingCapability.balanceTransaction(secretKeys, state, tx), require_watch.toEffect);
1388
+ });
1389
+ }
1390
+ transferTransaction(secretKeys, outputs) {
1391
+ return require_watch.modifyEffect(this.#context.stateRef, (state) => {
1392
+ return require_const.pipe(this.#v1Context.transactingCapability.makeTransfer(secretKeys, state, outputs), require_watch.toEffect);
1393
+ });
1394
+ }
1395
+ initSwap(secretKeys, desiredInputs, desiredOutputs) {
1396
+ return require_watch.modifyEffect(this.#context.stateRef, (state) => {
1397
+ return require_const.pipe(this.#v1Context.transactingCapability.initSwap(secretKeys, state, desiredInputs, desiredOutputs), require_watch.toEffect);
1398
+ });
1399
+ }
1400
+ revertTransaction(transaction) {
1401
+ return require_watch.updateEffect(this.#context.stateRef, (state) => {
1402
+ return require_const.pipe(this.#v1Context.transactingCapability.revertTransaction(state, transaction), require_watch.toEffect);
1403
+ });
1404
+ }
1405
+ serializeState(state) {
1406
+ return this.#v1Context.serializationCapability.serialize(state);
1407
+ }
1408
+ };
1409
+ //#endregion
1410
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/CoreWallet.js
1411
+ const PublicKeys = { fromSecretKeys: (secretKeys) => {
1412
+ return {
1413
+ coinPublicKey: secretKeys.coinPublicKey,
1414
+ encryptionPublicKey: secretKeys.encryptionPublicKey
1415
+ };
1416
+ } };
1417
+ const CoinHashesMap = {
1418
+ empty: {},
1419
+ pickAllCoins(state) {
1420
+ return [...state.coins, ...state.pendingOutputs.values().map(([coin]) => coin)];
1421
+ },
1422
+ assertValid(map, state) {
1423
+ const coins = CoinHashesMap.pickAllCoins(state);
1424
+ const coinNonces = new Set(require_const.map$7(coins, (coin) => coin.nonce));
1425
+ const definedNonces = new Set(Object.keys(map));
1426
+ const missingNonces = coinNonces.difference(definedNonces);
1427
+ return missingNonces.size === 0 ? require_const.void_$2 : require_const.left(missingNonces);
1428
+ },
1429
+ updateWithCoins(secretKeys, existing, coins) {
1430
+ return require_const.fromIterableWith(coins, (coin) => [coin.nonce, existing[coin.nonce] ?? {
1431
+ commitment: _midnight_ntwrk_ledger_v8.coinCommitment(coin, secretKeys.coinPublicKey),
1432
+ nullifier: _midnight_ntwrk_ledger_v8.coinNullifier(coin, secretKeys.coinSecretKey)
1433
+ }]);
1434
+ },
1435
+ updateWithNewCoins(secretKeys, existing, coins) {
1436
+ const newMap = CoinHashesMap.updateWithCoins(secretKeys, CoinHashesMap.empty, coins);
1437
+ return require_const.union$2(existing, newMap, (a) => a);
1438
+ },
1439
+ init(secretKeys, coins) {
1440
+ return CoinHashesMap.updateWithCoins(secretKeys, {}, coins);
1441
+ }
1442
+ };
1443
+ const CoreWallet = {
1444
+ init(localState, secretKeys, networkId) {
1445
+ return {
1446
+ state: localState,
1447
+ publicKeys: PublicKeys.fromSecretKeys(secretKeys),
1448
+ networkId,
1449
+ coinHashes: CoinHashesMap.init(secretKeys, CoinHashesMap.pickAllCoins(localState)),
1450
+ progress: require_const.createSyncProgress(),
1451
+ protocolVersion: require_const.MinSupportedVersion
1452
+ };
1453
+ },
1454
+ empty(publicKeys, networkId) {
1455
+ return {
1456
+ state: new _midnight_ntwrk_ledger_v8.ZswapLocalState(),
1457
+ publicKeys,
1458
+ networkId,
1459
+ coinHashes: CoinHashesMap.empty,
1460
+ progress: require_const.createSyncProgress(),
1461
+ protocolVersion: require_const.MinSupportedVersion
1462
+ };
1463
+ },
1464
+ restore(localState, secretKeys, syncProgress, protocolVersion, networkId) {
1465
+ return {
1466
+ state: localState,
1467
+ publicKeys: PublicKeys.fromSecretKeys(secretKeys),
1468
+ networkId,
1469
+ coinHashes: CoinHashesMap.init(secretKeys, CoinHashesMap.pickAllCoins(localState)),
1470
+ progress: require_const.createSyncProgress(syncProgress),
1471
+ protocolVersion: require_const.ProtocolVersion(protocolVersion)
1472
+ };
1473
+ },
1474
+ restoreWithCoinHashes(publicKeys, localState, coinHashes, syncProgress, protocolVersion, networkId) {
1475
+ return CoinHashesMap.assertValid(coinHashes, localState).pipe(require_const.mapBoth$3({
1476
+ onLeft: (missingNonces) => new InvalidCoinHashesError({
1477
+ message: "Missing coin hashes for coins present in the state",
1478
+ missingNonces
1479
+ }),
1480
+ onRight: () => ({
1481
+ state: localState,
1482
+ publicKeys,
1483
+ networkId,
1484
+ coinHashes,
1485
+ progress: require_const.createSyncProgress(syncProgress),
1486
+ protocolVersion: require_const.ProtocolVersion(protocolVersion)
1487
+ })
1488
+ }));
1489
+ },
1490
+ initEmpty(keys, networkId) {
1491
+ return this.empty(PublicKeys.fromSecretKeys(keys), networkId);
1492
+ },
1493
+ applyCollapsedUpdate(wallet, collapsed) {
1494
+ const newState = wallet.state.applyCollapsedUpdate(collapsed);
1495
+ return {
1496
+ ...wallet,
1497
+ state: newState
1498
+ };
1499
+ },
1500
+ apply(wallet, secretKeys, offer) {
1501
+ const newState = wallet.state.apply(secretKeys, offer);
1502
+ const newCoinHashes = CoinHashesMap.updateWithCoins(secretKeys, wallet.coinHashes, CoinHashesMap.pickAllCoins(newState));
1503
+ return {
1504
+ ...wallet,
1505
+ state: newState,
1506
+ coinHashes: newCoinHashes
1507
+ };
1508
+ },
1509
+ replayEventsWithChanges(wallet, secretKeys, events) {
1510
+ const stateWithChanges = wallet.state.replayEventsWithChanges(secretKeys, events);
1511
+ const newState = stateWithChanges.state;
1512
+ const newCoinHashes = CoinHashesMap.updateWithCoins(secretKeys, wallet.coinHashes, CoinHashesMap.pickAllCoins(newState));
1513
+ return [{
1514
+ ...wallet,
1515
+ state: newState,
1516
+ coinHashes: newCoinHashes
1517
+ }, stateWithChanges.changes];
1518
+ },
1519
+ updateProgress(wallet, { appliedIndex, highestRelevantWalletIndex, highestIndex, highestRelevantIndex, isConnected }) {
1520
+ const updatedProgress = require_const.createSyncProgress({
1521
+ appliedIndex: appliedIndex ?? wallet.progress.appliedIndex,
1522
+ highestRelevantWalletIndex: highestRelevantWalletIndex ?? wallet.progress.highestRelevantWalletIndex,
1523
+ highestIndex: highestIndex ?? wallet.progress.highestIndex,
1524
+ highestRelevantIndex: highestRelevantIndex ?? wallet.progress.highestRelevantIndex,
1525
+ isConnected: isConnected ?? wallet.progress.isConnected
1526
+ });
1527
+ return {
1528
+ ...wallet,
1529
+ progress: updatedProgress
1530
+ };
1531
+ },
1532
+ addTransaction(wallet, _tx) {
1533
+ return wallet;
1534
+ },
1535
+ revertTransaction(wallet, tx) {
1536
+ const newState = wallet.state.revertTransaction(tx);
1537
+ return {
1538
+ ...wallet,
1539
+ state: newState
1540
+ };
1541
+ },
1542
+ updateTxHistory(wallet, _newTxs) {
1543
+ return wallet;
1544
+ },
1545
+ spendCoins(wallet, secretKeys, coins, segment) {
1546
+ const [offers, newLocalState] = require_const.pipe(coins, require_const.reduce$3([[], wallet.state], ([accOffers, localState], coinToSpend) => {
1547
+ const [nextState, newInput] = localState.spend(secretKeys, coinToSpend, segment);
1548
+ const inputOffer = _midnight_ntwrk_ledger_v8.ZswapOffer.fromInput(newInput, coinToSpend.type, coinToSpend.value);
1549
+ return [accOffers.concat([inputOffer]), nextState];
1550
+ }));
1551
+ return [offers, {
1552
+ ...wallet,
1553
+ state: newLocalState
1554
+ }];
1555
+ },
1556
+ watchCoins(wallet, secretKeys, coins) {
1557
+ const newLocalState = coins.reduce((localState, coin) => localState.watchFor(wallet.publicKeys.coinPublicKey, coin), wallet.state);
1558
+ const newCoinHashes = CoinHashesMap.updateWithNewCoins(secretKeys, wallet.coinHashes, coins);
1559
+ return {
1560
+ ...wallet,
1561
+ state: newLocalState,
1562
+ coinHashes: newCoinHashes
1563
+ };
1564
+ }
1565
+ };
1566
+ //#endregion
1567
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/Serialization.js
1568
+ const StateSchema = require_const.declare((input) => input instanceof _midnight_ntwrk_ledger_v8.ZswapLocalState).annotations({ identifier: "ledger.ZswapLocalState" });
1569
+ const Uint8ArraySchema$1 = require_const.declare((input) => input instanceof Uint8Array).annotations({ identifier: "Uint8Array" });
1570
+ const StateFromUInt8Array = () => require_const.asSchema(require_const.transformOrFail(Uint8ArraySchema$1, StateSchema, {
1571
+ encode: (state) => {
1572
+ return require_const.try_({
1573
+ try: () => {
1574
+ return state.serialize();
1575
+ },
1576
+ catch: (err) => {
1577
+ return new require_const.Unexpected(err, "Could not serialize local state");
1578
+ }
1579
+ });
1580
+ },
1581
+ decode: (bytes) => require_const.try_({
1582
+ try: () => _midnight_ntwrk_ledger_v8.ZswapLocalState.deserialize(bytes),
1583
+ catch: (err) => {
1584
+ return new require_const.Unexpected(err, "Could not deserialize local state");
1585
+ }
1586
+ })
1587
+ }));
1588
+ const HexedState = () => require_const.pipe(require_const.Uint8ArrayFromHex, require_const.compose(StateFromUInt8Array()));
1589
+ const makeDefaultV1SerializationCapability = () => {
1590
+ const SnapshotSchema = require_const.Struct({
1591
+ publicKeys: require_const.Struct({
1592
+ coinPublicKey: require_const.String$,
1593
+ encryptionPublicKey: require_const.String$
1594
+ }),
1595
+ state: HexedState(),
1596
+ protocolVersion: require_const.BigInt$,
1597
+ offset: require_const.optional(require_const.BigInt$),
1598
+ networkId: require_const.String$,
1599
+ coinHashes: require_const.Record({
1600
+ key: require_const.String$,
1601
+ value: require_const.Struct({
1602
+ nullifier: require_const.String$,
1603
+ commitment: require_const.String$
1604
+ })
1605
+ })
1606
+ });
1607
+ return {
1608
+ serialize: (wallet) => {
1609
+ const buildSnapshot = (w) => ({
1610
+ publicKeys: w.publicKeys,
1611
+ state: w.state,
1612
+ protocolVersion: w.protocolVersion,
1613
+ networkId: w.networkId,
1614
+ offset: w.progress?.appliedIndex,
1615
+ coinHashes: w.coinHashes
1616
+ });
1617
+ return require_const.pipe(wallet, buildSnapshot, require_const.encodeSync(SnapshotSchema), JSON.stringify);
1618
+ },
1619
+ deserialize: (aux, serialized) => {
1620
+ return require_const.pipe(serialized, require_const.decodeUnknownEither(require_const.parseJson(SnapshotSchema)), require_const.mapLeft((err) => WalletError.other(err)), require_const.flatMap$4((snapshot) => CoreWallet.restoreWithCoinHashes(snapshot.publicKeys, snapshot.state, snapshot.coinHashes, {
1621
+ appliedIndex: snapshot.offset ?? 0n,
1622
+ highestRelevantWalletIndex: 0n,
1623
+ highestIndex: 0n,
1624
+ highestRelevantIndex: 0n,
1625
+ isConnected: false
1626
+ }, snapshot.protocolVersion, snapshot.networkId)));
1627
+ }
1628
+ };
1629
+ };
1630
+ //#endregion
1631
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/Sync.js
1632
+ const Uint8ArraySchema = require_const.declare((input) => input instanceof Uint8Array).annotations({ identifier: "Uint8Array" });
1633
+ const WalletSyncUpdate = { create: (updates, secretKeys) => {
1634
+ return {
1635
+ updates,
1636
+ secretKeys
1637
+ };
1638
+ } };
1639
+ const LedgerEventSchema = require_const.declare((input) => input instanceof _midnight_ntwrk_ledger_v8.Event).annotations({ identifier: "ledger.Event" });
1640
+ const LedgerEventFromUint8Array = require_const.transformOrFail(Uint8ArraySchema, LedgerEventSchema, {
1641
+ encode: (event) => require_const.try_({
1642
+ try: () => event.serialize(),
1643
+ catch: (error) => new require_const.Unexpected(error, "Could not serialize ledger event")
1644
+ }),
1645
+ decode: (bytes) => require_const.try_({
1646
+ try: () => _midnight_ntwrk_ledger_v8.Event.deserialize(bytes),
1647
+ catch: (error) => new require_const.Unexpected(error, "Could not deserialize ledger event")
1648
+ })
1649
+ });
1650
+ const HexedLedgerEvent = require_const.pipe(require_const.Uint8ArrayFromHex, require_const.compose(LedgerEventFromUint8Array));
1651
+ const EventsSyncUpdatePayload = require_const.Struct({
1652
+ id: require_const.Number$,
1653
+ raw: require_const.String$,
1654
+ protocolVersion: require_const.Number$,
1655
+ maxId: require_const.Number$
1656
+ });
1657
+ const EventsSyncUpdate = require_const.TaggedStruct("EventsSyncUpdate", {
1658
+ id: require_const.Number$,
1659
+ protocolVersion: require_const.Number$,
1660
+ maxId: require_const.Number$,
1661
+ event: LedgerEventSchema
1662
+ });
1663
+ const EventsSyncUpdateFromPayload = require_const.transformOrFail(EventsSyncUpdatePayload, EventsSyncUpdate, {
1664
+ decode: (input) => require_const.pipe(require_const.decodeUnknownEither(HexedLedgerEvent)(input.raw), require_const.map$9((event) => ({
1665
+ _tag: "EventsSyncUpdate",
1666
+ id: input.id,
1667
+ protocolVersion: input.protocolVersion,
1668
+ maxId: input.maxId,
1669
+ event
1670
+ })), require_const.mapLeft((error) => new require_const.Unexpected(error, "Failed to decode ledger event payload")), require_watch.toEffect),
1671
+ encode: (output) => require_const.pipe(require_const.encodeEither(HexedLedgerEvent)(output.event), require_const.map$9((raw) => ({
1672
+ id: output.id,
1673
+ raw,
1674
+ protocolVersion: output.protocolVersion,
1675
+ maxId: output.maxId
1676
+ })), require_const.mapLeft((error) => new require_const.Unexpected(error, "Failed to encode ledger event payload")), require_watch.toEffect)
1677
+ });
1678
+ const makeEventsSyncService = (config) => {
1679
+ return { updates: (state, secretKeys) => {
1680
+ const { indexerClientConnection } = config;
1681
+ const webSocketUrlResult = require_watch.createWebSocketUrl(indexerClientConnection.indexerHttpUrl, indexerClientConnection.indexerWsUrl);
1682
+ if (require_const.isLeft(webSocketUrlResult)) return require_watch.fail(new SyncWalletError(/* @__PURE__ */ new Error(`Could not derive WebSocket URL from indexer HTTP URL: ${webSocketUrlResult.left.message}`)));
1683
+ const indexerWsUrlResult = require_watch.make(webSocketUrlResult.right);
1684
+ if (require_const.isLeft(indexerWsUrlResult)) return require_watch.fail(new SyncWalletError(/* @__PURE__ */ new Error(`Invalid indexer WS URL: ${indexerWsUrlResult.left.message}`)));
1685
+ const indexerWsUrl = indexerWsUrlResult.right;
1686
+ const resumeFrom = (state.progress?.appliedIndex ?? 0n) - 1n;
1687
+ const batchSize = config.batchUpdates?.size ?? 10;
1688
+ const batchTimeout = require_const.millis(config.batchUpdates?.timeout ?? 1);
1689
+ const batchSpacing = config.batchUpdates?.spacing ?? 4;
1690
+ const bufferSize = config.indexerClientConnection.bufferSize ?? 1e4;
1691
+ const resumeThreshold = config.indexerClientConnection.resumeThreshold ?? 100;
1692
+ const eventsStream = require_const.pipe(require_watch.ZswapEvents.runWithBackpressure({
1693
+ bufferSize,
1694
+ resumeThreshold,
1695
+ from: resumeFrom,
1696
+ variables: (cursor) => ({ id: cursor < 0n ? null : Number(cursor) }),
1697
+ key: (r) => BigInt(r.zswapLedgerEvents.id)
1698
+ }), require_watch.provideLayer(require_watch.layer({
1699
+ url: indexerWsUrl,
1700
+ keepAlive: config.indexerClientConnection.keepAlive
1701
+ })), require_watch.mapError((error) => new SyncWalletError(error)), require_watch.mapEffect((subscription) => require_const.pipe(subscription.zswapLedgerEvents, require_const.decodeUnknownEither(EventsSyncUpdateFromPayload), require_const.mapLeft((err) => new SyncWalletError(err)), require_watch.toEffect)), require_watch.groupedWithin(batchSize, batchTimeout), require_watch.map(require_const.toArray), require_watch.map((data) => WalletSyncUpdate.create(data, secretKeys)));
1702
+ return batchSpacing > 0 ? require_watch.schedule(eventsStream, require_watch.spaced(require_const.millis(batchSpacing))) : eventsStream;
1703
+ } };
1704
+ };
1705
+ const makeEventsSyncCapability = () => {
1706
+ return { applyUpdate: (state, wrappedUpdate) => {
1707
+ if (wrappedUpdate.updates.length === 0) return [state, {
1708
+ changes: [],
1709
+ protocolVersion: Number(state.protocolVersion)
1710
+ }];
1711
+ const appliedIndex = state.progress?.appliedIndex ?? 0n;
1712
+ const freshUpdates = wrappedUpdate.updates.filter((u) => BigInt(u.id) > appliedIndex);
1713
+ const lastUpdate = wrappedUpdate.updates.at(-1);
1714
+ const highestRelevantWalletIndex = BigInt(lastUpdate.maxId);
1715
+ const [newState, newChanges] = freshUpdates.length === 0 ? [state, []] : CoreWallet.replayEventsWithChanges(state, wrappedUpdate.secretKeys, freshUpdates.map((u) => u.event));
1716
+ return [CoreWallet.updateProgress(newState, {
1717
+ highestRelevantWalletIndex,
1718
+ appliedIndex: freshUpdates.length === 0 ? appliedIndex : BigInt(freshUpdates.at(-1).id),
1719
+ isConnected: true
1720
+ }), {
1721
+ changes: newChanges,
1722
+ protocolVersion: lastUpdate.protocolVersion
1723
+ }];
1724
+ } };
1725
+ };
1726
+ //#endregion
1727
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/TransactionImbalances.js
1728
+ const ShieldedCostModel = {
1729
+ inputFeeOverhead: 0n,
1730
+ outputFeeOverhead: 0n
1731
+ };
1732
+ const TransactionImbalances = new class {
1733
+ empty = () => {
1734
+ return {
1735
+ guaranteed: require_watch.Imbalances.empty(),
1736
+ fallible: /* @__PURE__ */ new Map()
1737
+ };
1738
+ };
1739
+ areBalanced = (imbalances) => {
1740
+ const areGuaranteedAllZeroes = imbalances.guaranteed.entries().every(([, value]) => value === 0n);
1741
+ const areFallibleAllZeroes = Array.from(imbalances.fallible.values()).every((segmentImbalances) => segmentImbalances.entries().every(([, value]) => value === 0n));
1742
+ return areGuaranteedAllZeroes && areFallibleAllZeroes;
1743
+ };
1744
+ }();
1745
+ //#endregion
1746
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/TransactionOps.js
1747
+ const TransactionOps = new class {
1748
+ default = {
1749
+ getImbalances(tx) {
1750
+ return TransactionOps.shared.getImbalances(tx);
1751
+ },
1752
+ id(tx) {
1753
+ return tx.identifiers().at(0);
1754
+ }
1755
+ };
1756
+ proofErased = {
1757
+ getImbalances(tx) {
1758
+ return TransactionOps.shared.getImbalances(tx);
1759
+ },
1760
+ id(tx) {
1761
+ return tx.identifiers().at(0);
1762
+ }
1763
+ };
1764
+ unproven = {
1765
+ getImbalances(tx) {
1766
+ return TransactionOps.shared.getImbalances(tx);
1767
+ },
1768
+ id(tx) {
1769
+ return tx.identifiers().at(0);
1770
+ }
1771
+ };
1772
+ shared = {
1773
+ getImbalances(tx) {
1774
+ return {
1775
+ guaranteed: TransactionOps.shared.getGuaranteedImbalances(tx),
1776
+ fallible: TransactionOps.shared.getFallibleImbalances(tx)
1777
+ };
1778
+ },
1779
+ getGuaranteedImbalances: (tx) => {
1780
+ const rawGuaranteedImbalances = tx.imbalances(0).entries().filter(([token]) => token.tag === "shielded").map(([token, value]) => {
1781
+ return [token.raw, value];
1782
+ });
1783
+ return require_watch.Imbalances.fromEntries(rawGuaranteedImbalances);
1784
+ },
1785
+ getFallibleImbalances: (tx) => {
1786
+ const fallibleImbalances = Array.from(tx.fallibleOffer?.keys() ?? []).flatMap((segment) => {
1787
+ const rawImbalances = tx.imbalances(segment).entries().filter(([token]) => token.tag === "shielded").map(([token, value]) => {
1788
+ return [token.raw, value];
1789
+ });
1790
+ return [[segment, require_watch.Imbalances.fromEntries(rawImbalances)]];
1791
+ });
1792
+ return new Map(fallibleImbalances);
1793
+ }
1794
+ };
1795
+ }();
1796
+ //#endregion
1797
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/Transacting.js
1798
+ const makeDefaultTransactingCapability = (config, getContext) => {
1799
+ return new TransactingCapabilityImplementation(config.networkId, () => getContext().coinSelection, () => getContext().coinsAndBalancesCapability, () => getContext().keysCapability, TransactionOps.default);
1800
+ };
1801
+ var TransactingCapabilityImplementation = class {
1802
+ networkId;
1803
+ getCoinSelection;
1804
+ txOps;
1805
+ getCoins;
1806
+ getKeys;
1807
+ constructor(networkId, getCoinSelection, getCoins, getKeys, txOps) {
1808
+ this.getCoins = getCoins;
1809
+ this.networkId = networkId;
1810
+ this.getCoinSelection = getCoinSelection;
1811
+ this.getKeys = getKeys;
1812
+ this.txOps = txOps;
1813
+ }
1814
+ balanceTransaction(secretKeys, state, tx) {
1815
+ return require_const.gen$1(this, function* () {
1816
+ const coinSelection = this.getCoinSelection();
1817
+ const initialImbalances = this.txOps.getImbalances(tx);
1818
+ if (TransactionImbalances.areBalanced(initialImbalances)) return [void 0, state];
1819
+ const { newState: afterFallible, fallibleOffers } = yield* this.balanceFallibleSection(secretKeys, state, initialImbalances, coinSelection);
1820
+ const { newState: afterGuaranteed, offer: guaranteed } = yield* this.#balanceGuaranteedSection(secretKeys, afterFallible, initialImbalances, coinSelection, require_watch.Imbalances.empty());
1821
+ return [Array.from(fallibleOffers.entries()).reduce((tx, [segment, offer]) => tx.addZswapOffer({
1822
+ tag: "specific",
1823
+ value: segment
1824
+ }, offer), _midnight_ntwrk_ledger_v8.Transaction.fromParts(this.networkId, guaranteed)), afterGuaranteed];
1825
+ });
1826
+ }
1827
+ makeTransfer(secretKeys, state, transfers) {
1828
+ return require_const.gen$1(this, function* () {
1829
+ const positiveTransfers = yield* require_const.pipe(transfers, require_const.filter$2((t) => t.amount > 0n), require_const.match$2({
1830
+ onEmpty: () => require_const.left(new OtherWalletError({ message: "The amount needs to be positive" })),
1831
+ onNonEmpty: (nonEmpty) => require_const.right(nonEmpty)
1832
+ }));
1833
+ const networkId = this.networkId;
1834
+ const { initialOffersAndCoins, selfCoins } = yield* this.#processDesiredOutputs(state, positiveTransfers);
1835
+ const offerToBalance = require_const.pipe(initialOffersAndCoins, require_const.map$6((o) => o.outputOffer), require_watch.fold((a, b) => a.merge(b)));
1836
+ const unprovenTxToBalance = _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, offerToBalance);
1837
+ const imbalances = TransactionOps.unproven.getImbalances(unprovenTxToBalance);
1838
+ const { offer, newState } = yield* this.#balanceGuaranteedSection(secretKeys, state, imbalances, this.getCoinSelection(), require_watch.Imbalances.empty());
1839
+ const finalState = CoreWallet.watchCoins(newState, secretKeys, selfCoins);
1840
+ return [unprovenTxToBalance.merge(_midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, offer)), finalState];
1841
+ });
1842
+ }
1843
+ initSwap(secretKeys, state, desiredInputs, desiredOutputs) {
1844
+ return require_const.gen$1(this, function* () {
1845
+ if (!desiredOutputs.every((output) => output.amount > 0n)) return yield* require_const.left(new OtherWalletError({ message: "The amount needs to be positive" }));
1846
+ if (!Object.entries(desiredInputs).every(([, amount]) => amount > 0n)) return yield* require_const.left(new OtherWalletError({ message: "The input amounts need to be positive" }));
1847
+ const outputsParseResult = yield* this.#processDesiredOutputsPossiblyEmpty(state, desiredOutputs);
1848
+ const inputsParseResult = require_watch.Imbalances.fromEntries(require_const.toEntries(desiredInputs));
1849
+ const networkId = this.networkId;
1850
+ const { offer, newState } = yield* this.#balanceGuaranteedSection(secretKeys, state, TransactionImbalances.empty(), this.getCoinSelection(), inputsParseResult);
1851
+ const finalState = CoreWallet.watchCoins(newState, secretKeys, outputsParseResult.selfCoins);
1852
+ const balancingTx = _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, offer);
1853
+ return [outputsParseResult.unprovenTxToBalance ? outputsParseResult.unprovenTxToBalance.merge(balancingTx) : balancingTx, finalState];
1854
+ });
1855
+ }
1856
+ revertTransaction(state, transaction) {
1857
+ return require_const.try_$1({
1858
+ try: () => {
1859
+ return CoreWallet.revertTransaction(state, transaction);
1860
+ },
1861
+ catch: (err) => {
1862
+ return new OtherWalletError({
1863
+ message: `Error while reverting transaction ${transaction.identifiers().at(0)}`,
1864
+ cause: err
1865
+ });
1866
+ }
1867
+ });
1868
+ }
1869
+ #prepareOffer(secretKeys, state, recipe, segment) {
1870
+ const [inputOffers, stateAfterSpends] = CoreWallet.spendCoins(state, secretKeys, recipe.inputs, segment);
1871
+ const stateAfterWatches = CoreWallet.watchCoins(stateAfterSpends, secretKeys, recipe.outputs);
1872
+ const outputOffers = recipe.outputs.map((coin) => {
1873
+ const output = _midnight_ntwrk_ledger_v8.ZswapOutput.new(coin, segment, this.getKeys().getCoinPublicKey(state).toHexString(), this.getKeys().getEncryptionPublicKey(state).toHexString());
1874
+ return _midnight_ntwrk_ledger_v8.ZswapOffer.fromOutput(output, coin.type, coin.value);
1875
+ });
1876
+ return require_const.pipe(require_const.appendAll$1(inputOffers, outputOffers), require_const.match$2({
1877
+ onEmpty: () => require_const.none(),
1878
+ onNonEmpty: (nonEmpty) => require_const.pipe(nonEmpty, require_watch.fold((a, b) => a.merge(b)), require_const.some)
1879
+ }), require_const.map$8((offer) => ({
1880
+ offer,
1881
+ newState: stateAfterWatches
1882
+ })));
1883
+ }
1884
+ balanceFallibleSection(secretKeys, state, imbalances, coinSelection) {
1885
+ return Array.from(imbalances.fallible.entries()).reduce((acc, [segment, segmentImbalances]) => require_const.flatMap$4(acc, ({ fallibleOffers, newState }) => require_const.pipe(require_const.try_$1({
1886
+ try: () => {
1887
+ const fallibleBalanceRecipe = require_watch.getBalanceRecipe({
1888
+ coins: this.getCoins().getAvailableCoins(newState).map((c) => c.coin),
1889
+ initialImbalances: segmentImbalances,
1890
+ transactionCostModel: ShieldedCostModel,
1891
+ feeTokenType: "",
1892
+ coinSelection,
1893
+ createOutput: (coin) => _midnight_ntwrk_ledger_v8.createShieldedCoinInfo(coin.type, coin.value),
1894
+ isCoinEqual: (a, b) => a.type === b.type && a.value === b.value
1895
+ });
1896
+ return this.#prepareOffer(secretKeys, newState, fallibleBalanceRecipe, segment);
1897
+ },
1898
+ catch: (err) => {
1899
+ if (err instanceof require_watch.InsufficientFundsError) return new InsufficientFundsError({
1900
+ message: `Insufficient funds for fallible segment ${segment}`,
1901
+ tokenType: err.tokenType,
1902
+ amount: segmentImbalances.get(err.tokenType) ?? 0n
1903
+ });
1904
+ return new OtherWalletError({
1905
+ message: `Balancing fallible segment ${segment} failed`,
1906
+ cause: err
1907
+ });
1908
+ }
1909
+ }), require_const.map$9(require_const.match$3({
1910
+ onNone: () => ({
1911
+ fallibleOffers,
1912
+ newState
1913
+ }),
1914
+ onSome: (res) => ({
1915
+ fallibleOffers: new Map([...fallibleOffers, [segment, res.offer]]),
1916
+ newState: res.newState
1917
+ })
1918
+ })))), require_const.right({
1919
+ fallibleOffers: /* @__PURE__ */ new Map(),
1920
+ newState: state
1921
+ }));
1922
+ }
1923
+ #balanceGuaranteedSection(secretKeys, state, imbalances, coinSelection, targetImbalances) {
1924
+ return require_const.gen$1(this, function* () {
1925
+ const balanceRecipe = yield* require_const.try_$1({
1926
+ try: () => require_watch.getBalanceRecipe({
1927
+ coins: this.getCoins().getAvailableCoins(state).map((c) => c.coin),
1928
+ initialImbalances: imbalances.guaranteed,
1929
+ transactionCostModel: ShieldedCostModel,
1930
+ feeTokenType: "",
1931
+ coinSelection,
1932
+ createOutput: (coin) => _midnight_ntwrk_ledger_v8.createShieldedCoinInfo(coin.type, coin.value),
1933
+ isCoinEqual: (a, b) => a.nonce === b.nonce,
1934
+ targetImbalances
1935
+ }),
1936
+ catch: (err) => {
1937
+ if (err instanceof require_watch.InsufficientFundsError) return new InsufficientFundsError({
1938
+ message: "Insufficient funds",
1939
+ tokenType: err.tokenType,
1940
+ amount: imbalances.guaranteed.get(err.tokenType) ?? 0n
1941
+ });
1942
+ else return new OtherWalletError({
1943
+ message: "Balancing guaranteed section failed",
1944
+ cause: err
1945
+ });
1946
+ }
1947
+ });
1948
+ return require_const.pipe(this.#prepareOffer(secretKeys, state, balanceRecipe, 0), require_const.match$3({
1949
+ onNone: () => ({
1950
+ offer: void 0,
1951
+ newState: state
1952
+ }),
1953
+ onSome: (result) => result
1954
+ }));
1955
+ });
1956
+ }
1957
+ #processDesiredOutputs(state, transfers) {
1958
+ return require_const.try_$1({
1959
+ try: () => {
1960
+ const initialOffersAndCoins = require_const.pipe(transfers, require_const.map$6((transfer) => {
1961
+ const { receiverAddress, type, amount } = transfer;
1962
+ const coin = _midnight_ntwrk_ledger_v8.createShieldedCoinInfo(type, amount);
1963
+ const output = _midnight_ntwrk_ledger_v8.ZswapOutput.new(coin, 0, receiverAddress.coinPublicKey.toHexString(), receiverAddress.encryptionPublicKey.toHexString());
1964
+ return {
1965
+ coin,
1966
+ outputOffer: _midnight_ntwrk_ledger_v8.ZswapOffer.fromOutput(output, type, amount),
1967
+ isForSelf: receiverAddress.coinPublicKey.equals(this.getKeys().getCoinPublicKey(state))
1968
+ };
1969
+ }));
1970
+ return {
1971
+ initialOffersAndCoins,
1972
+ selfCoins: require_const.flatMap$3(initialOffersAndCoins, ({ coin, isForSelf }) => {
1973
+ if (isForSelf) return [coin];
1974
+ else return [];
1975
+ })
1976
+ };
1977
+ },
1978
+ catch: (err) => {
1979
+ return new OtherWalletError({
1980
+ message: "Failed to process desired outputs",
1981
+ cause: err
1982
+ });
1983
+ }
1984
+ });
1985
+ }
1986
+ #processDesiredOutputsPossiblyEmpty(state, desiredOutputs) {
1987
+ return require_const.pipe(desiredOutputs, require_const.match$2({
1988
+ onEmpty: () => {
1989
+ return require_const.right({
1990
+ imbalances: TransactionImbalances.empty(),
1991
+ selfCoins: [],
1992
+ unprovenTxToBalance: null
1993
+ });
1994
+ },
1995
+ onNonEmpty: (desiredOutputs) => {
1996
+ return require_const.pipe(this.#processDesiredOutputs(state, desiredOutputs), require_const.map$9(({ initialOffersAndCoins, selfCoins }) => {
1997
+ const networkId = this.networkId;
1998
+ const offerToBalance = require_const.pipe(initialOffersAndCoins, require_const.map$6((o) => o.outputOffer), require_watch.fold((a, b) => a.merge(b)));
1999
+ const unprovenTxToBalance = _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, offerToBalance);
2000
+ return {
2001
+ imbalances: TransactionOps.unproven.getImbalances(unprovenTxToBalance),
2002
+ selfCoins,
2003
+ unprovenTxToBalance
2004
+ };
2005
+ }));
2006
+ }
2007
+ }));
2008
+ }
2009
+ };
2010
+ //#endregion
2011
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/CoinsAndBalances.js
2012
+ const calculateBalances = (coins) => coins.reduce((acc, { coin }) => ({
2013
+ ...acc,
2014
+ [coin.type]: acc[coin.type] === void 0 ? coin.value : acc[coin.type] + coin.value
2015
+ }), {});
2016
+ const makeDefaultCoinsAndBalancesCapability = () => {
2017
+ const getAvailableBalances = (state) => {
2018
+ return calculateBalances(getAvailableCoins(state));
2019
+ };
2020
+ const getPendingBalances = (state) => {
2021
+ return calculateBalances(getPendingCoins(state));
2022
+ };
2023
+ const getTotalBalances = (state) => {
2024
+ return require_const.pipe([getAvailableBalances(state), getPendingBalances(state)], require_watch.mergeWithAccumulator(0n, (a, b) => a + b));
2025
+ };
2026
+ const getAvailableCoins = (state) => {
2027
+ const pendingSpends = new Set([...state.state.pendingSpends.values()].map(([coin]) => coin.nonce));
2028
+ return require_const.pipe([...state.state.coins], require_const.filter$2((coin) => !pendingSpends.has(coin.nonce)), require_const.map$6((coin) => {
2029
+ return {
2030
+ coin,
2031
+ commitment: state.coinHashes[coin.nonce].commitment,
2032
+ nullifier: state.coinHashes[coin.nonce].nullifier
2033
+ };
2034
+ }));
2035
+ };
2036
+ const getPendingCoins = (state) => require_const.pipe([...state.state.pendingOutputs.values()], require_const.map$6(([coin, ttl]) => ({
2037
+ coin,
2038
+ ttl,
2039
+ commitment: state.coinHashes[coin.nonce].commitment,
2040
+ nullifier: state.coinHashes[coin.nonce].nullifier
2041
+ })));
2042
+ const getTotalCoins = (state) => [...getAvailableCoins(state), ...getPendingCoins(state)];
2043
+ return {
2044
+ getAvailableBalances,
2045
+ getPendingBalances,
2046
+ getTotalBalances,
2047
+ getAvailableCoins,
2048
+ getPendingCoins,
2049
+ getTotalCoins
2050
+ };
2051
+ };
2052
+ //#endregion
2053
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/Keys.js
2054
+ require__polyfill_buffer_patch.init__polyfill_buffer_patch();
2055
+ const makeDefaultKeysCapability = () => {
2056
+ return {
2057
+ getCoinPublicKey: (state) => {
2058
+ return new require_dist.ShieldedCoinPublicKey(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKeys.coinPublicKey, "hex"));
2059
+ },
2060
+ getEncryptionPublicKey: (state) => {
2061
+ return new require_dist.ShieldedEncryptionPublicKey(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKeys.encryptionPublicKey, "hex"));
2062
+ },
2063
+ getAddress: (state) => {
2064
+ return new require_dist.ShieldedAddress(new require_dist.ShieldedCoinPublicKey(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKeys.coinPublicKey, "hex")), new require_dist.ShieldedEncryptionPublicKey(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKeys.encryptionPublicKey, "hex")));
2065
+ }
2066
+ };
2067
+ };
2068
+ //#endregion
2069
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/TransactionHistory.js
2070
+ const QualifiedShieldedCoinInfoSchema = require_const.Struct({
2071
+ type: require_const.String$,
2072
+ nonce: require_const.String$,
2073
+ value: require_const.BigInt$,
2074
+ mtIndex: require_const.BigInt$
2075
+ });
2076
+ const ShieldedSectionSchema = require_const.Struct({
2077
+ receivedCoins: require_const.Array$(QualifiedShieldedCoinInfoSchema),
2078
+ spentCoins: require_const.Array$(QualifiedShieldedCoinInfoSchema)
2079
+ });
2080
+ require_const.Struct({
2081
+ hash: require_const.TransactionHashSchema,
2082
+ protocolVersion: require_const.Number$,
2083
+ status: require_const.TransactionHistoryStatusSchema,
2084
+ shielded: ShieldedSectionSchema
2085
+ });
2086
+ const coinEquals = require_const.equivalence(QualifiedShieldedCoinInfoSchema);
2087
+ const mergeShieldedSections = (existing, incoming) => ({
2088
+ receivedCoins: require_const.unionWith$1(existing.receivedCoins, incoming.receivedCoins, coinEquals),
2089
+ spentCoins: require_const.unionWith$1(existing.spentCoins, incoming.spentCoins, coinEquals)
2090
+ });
2091
+ const convertUpdateToStorageEntry = (changes, metadata, protocolVersion) => ({
2092
+ hash: changes.source,
2093
+ protocolVersion,
2094
+ status: metadata.status,
2095
+ shielded: {
2096
+ receivedCoins: changes.receivedCoins.map(({ mt_index, ...rest }) => ({
2097
+ ...rest,
2098
+ mtIndex: mt_index
2099
+ })),
2100
+ spentCoins: changes.spentCoins.map(({ mt_index, ...rest }) => ({
2101
+ ...rest,
2102
+ mtIndex: mt_index
2103
+ }))
2104
+ }
2105
+ });
2106
+ const upsertShieldedEntry = (txHistoryStorage, entry) => require_const.tryPromise({
2107
+ try: () => txHistoryStorage.upsert(entry),
2108
+ catch: (e) => new TransactionHistoryError({
2109
+ message: `Failed to upsert history entry for ${entry.hash}`,
2110
+ cause: e
2111
+ })
2112
+ });
2113
+ const makeDefaultTransactionHistoryService = (config, _getContext) => {
2114
+ const txHistoryStorage = config.txHistoryStorage;
2115
+ const queryClientLayer = require_watch.layer$1({ url: config.indexerClientConnection.indexerHttpUrl });
2116
+ return {
2117
+ put: (changes, metadata, protocolVersion) => {
2118
+ return upsertShieldedEntry(txHistoryStorage, convertUpdateToStorageEntry(changes, metadata, protocolVersion));
2119
+ },
2120
+ getTransactionDetails: (hash) => require_const.gen(function* () {
2121
+ const tx = (yield* (yield* require_watch.TransactionHistoryDetail)({ transactionHash: hash })).transactions[0];
2122
+ const rawStatus = tx.__typename === "RegularTransaction" ? tx.transactionResult.status : void 0;
2123
+ const status = rawStatus === "FAILURE" || rawStatus === "PARTIAL_SUCCESS" ? rawStatus : "SUCCESS";
2124
+ return {
2125
+ hash: tx.hash,
2126
+ timestamp: tx.block.timestamp,
2127
+ status
2128
+ };
2129
+ }).pipe(require_const.provide(queryClientLayer), require_const.scoped$1, require_const.retry(require_watch.exponential(require_const.seconds(1)).pipe(require_watch.compose(require_watch.recurs(3)))), require_const.mapError$1((cause) => new TransactionHistoryError({
2130
+ message: `Failed to fetch transaction metadata for ${hash}`,
2131
+ cause
2132
+ })))
2133
+ };
2134
+ };
2135
+ //#endregion
2136
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/v1/V1Builder.js
2137
+ var V1Builder = class V1Builder {
2138
+ #buildState;
2139
+ constructor(buildState = {}) {
2140
+ this.#buildState = buildState;
2141
+ }
2142
+ withDefaults() {
2143
+ return this.withDefaultTransactionType().withSyncDefaults().withSerializationDefaults().withTransactingDefaults().withCoinsAndBalancesDefaults().withTransactionHistoryDefaults().withKeysDefaults().withCoinSelectionDefaults();
2144
+ }
2145
+ withTransactionType() {
2146
+ return new V1Builder({
2147
+ ...this.#buildState,
2148
+ transactingCapability: void 0,
2149
+ transactionHistoryService: void 0
2150
+ });
2151
+ }
2152
+ withDefaultTransactionType() {
2153
+ return this.withTransactionType();
2154
+ }
2155
+ withSyncDefaults() {
2156
+ return this.withSync(makeEventsSyncService, makeEventsSyncCapability);
2157
+ }
2158
+ withSync(syncService, syncCapability) {
2159
+ return new V1Builder({
2160
+ ...this.#buildState,
2161
+ syncService,
2162
+ syncCapability
2163
+ });
2164
+ }
2165
+ withSerializationDefaults() {
2166
+ return this.withSerialization(makeDefaultV1SerializationCapability);
2167
+ }
2168
+ withSerialization(serializationCapability) {
2169
+ return new V1Builder({
2170
+ ...this.#buildState,
2171
+ serializationCapability
2172
+ });
2173
+ }
2174
+ withTransactingDefaults() {
2175
+ return this.withTransacting(makeDefaultTransactingCapability);
2176
+ }
2177
+ withTransacting(transactingCapability) {
2178
+ return new V1Builder({
2179
+ ...this.#buildState,
2180
+ transactingCapability
2181
+ });
2182
+ }
2183
+ withCoinSelection(coinSelection) {
2184
+ return new V1Builder({
2185
+ ...this.#buildState,
2186
+ coinSelection
2187
+ });
2188
+ }
2189
+ withCoinSelectionDefaults() {
2190
+ return this.withCoinSelection(() => require_watch.chooseCoin);
2191
+ }
2192
+ withCoinsAndBalancesDefaults() {
2193
+ return this.withCoinsAndBalances(makeDefaultCoinsAndBalancesCapability);
2194
+ }
2195
+ withCoinsAndBalances(coinsAndBalancesCapability) {
2196
+ return new V1Builder({
2197
+ ...this.#buildState,
2198
+ coinsAndBalancesCapability
2199
+ });
2200
+ }
2201
+ withTransactionHistoryDefaults() {
2202
+ return this.withTransactionHistory(makeDefaultTransactionHistoryService);
2203
+ }
2204
+ withTransactionHistory(transactionHistoryService) {
2205
+ return new V1Builder({
2206
+ ...this.#buildState,
2207
+ transactionHistoryService
2208
+ });
2209
+ }
2210
+ withKeysDefaults() {
2211
+ return this.withKeys(makeDefaultKeysCapability);
2212
+ }
2213
+ withKeys(keysCapability) {
2214
+ return new V1Builder({
2215
+ ...this.#buildState,
2216
+ keysCapability
2217
+ });
2218
+ }
2219
+ build(configuration) {
2220
+ const v1Context = this.#buildContextFromBuildState(configuration);
2221
+ const { networkId } = configuration;
2222
+ return {
2223
+ __polyTag__: V1Tag,
2224
+ coinsAndBalances: v1Context.coinsAndBalancesCapability,
2225
+ keys: v1Context.keysCapability,
2226
+ serialization: v1Context.serializationCapability,
2227
+ transactionHistory: v1Context.transactionHistoryService,
2228
+ start(context) {
2229
+ return require_const.gen(function* () {
2230
+ return new RunningV1Variant(yield* require_const.Scope, context, v1Context);
2231
+ });
2232
+ },
2233
+ migrateState(_previousState) {
2234
+ const seed = require_const.fromString("0000000000000000000000000000000000000000000000000000000000000001");
2235
+ return require_const.succeed(CoreWallet.empty(PublicKeys.fromSecretKeys(_midnight_ntwrk_ledger_v8.ZswapSecretKeys.fromSeed(seed)), networkId));
2236
+ },
2237
+ deserializeState: (serialized) => {
2238
+ return v1Context.serializationCapability.deserialize(null, serialized);
2239
+ }
2240
+ };
2241
+ }
2242
+ #buildContextFromBuildState(configuration) {
2243
+ if (!isBuildStateFull(this.#buildState)) throw new Error("Not all components are configured in V1 Builder");
2244
+ const { syncCapability, syncService, transactingCapability, serializationCapability, coinSelection, coinsAndBalancesCapability, keysCapability, transactionHistoryService } = this.#buildState;
2245
+ const getContext = () => context;
2246
+ const context = {
2247
+ serializationCapability: serializationCapability(configuration, getContext),
2248
+ syncCapability: syncCapability(configuration, getContext),
2249
+ syncService: syncService(configuration, getContext),
2250
+ transactingCapability: transactingCapability(configuration, getContext),
2251
+ coinsAndBalancesCapability: coinsAndBalancesCapability(configuration, getContext),
2252
+ keysCapability: keysCapability(configuration, getContext),
2253
+ coinSelection: coinSelection(configuration, getContext),
2254
+ transactionHistoryService: transactionHistoryService(configuration, getContext)
2255
+ };
2256
+ return context;
2257
+ }
2258
+ };
2259
+ const isBuildStateFull = (buildState) => {
2260
+ return [
2261
+ "syncService",
2262
+ "syncCapability",
2263
+ "transactingCapability",
2264
+ "coinSelection",
2265
+ "serializationCapability",
2266
+ "coinsAndBalancesCapability",
2267
+ "keysCapability",
2268
+ "transactionHistoryService"
2269
+ ].every((key) => typeof buildState[key] == "function");
2270
+ };
2271
+ //#endregion
2272
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-shielded/dist/ShieldedWallet.js
2273
+ var ShieldedWalletState = class ShieldedWalletState {
2274
+ static mapState = (variant) => (state) => {
2275
+ const { serialization, coinsAndBalances, keys } = variant;
2276
+ const { transactionHistory } = variant;
2277
+ return new ShieldedWalletState(state, {
2278
+ serialization,
2279
+ coinsAndBalances,
2280
+ keys
2281
+ }, { transactionHistory });
2282
+ };
2283
+ protocolVersion;
2284
+ state;
2285
+ capabilities;
2286
+ services;
2287
+ get balances() {
2288
+ return this.capabilities.coinsAndBalances.getAvailableBalances(this.state);
2289
+ }
2290
+ get totalCoins() {
2291
+ return this.capabilities.coinsAndBalances.getTotalCoins(this.state);
2292
+ }
2293
+ get availableCoins() {
2294
+ return this.capabilities.coinsAndBalances.getAvailableCoins(this.state);
2295
+ }
2296
+ get pendingCoins() {
2297
+ return this.capabilities.coinsAndBalances.getPendingCoins(this.state);
2298
+ }
2299
+ get coinPublicKey() {
2300
+ return this.capabilities.keys.getCoinPublicKey(this.state);
2301
+ }
2302
+ get encryptionPublicKey() {
2303
+ return this.capabilities.keys.getEncryptionPublicKey(this.state);
2304
+ }
2305
+ get address() {
2306
+ return this.capabilities.keys.getAddress(this.state);
2307
+ }
2308
+ get progress() {
2309
+ return this.state.progress;
2310
+ }
2311
+ constructor(state, capabilities, services) {
2312
+ this.protocolVersion = state.version;
2313
+ this.state = state.state;
2314
+ this.capabilities = capabilities;
2315
+ this.services = services;
2316
+ }
2317
+ serialize() {
2318
+ return this.capabilities.serialization.serialize(this.state);
2319
+ }
2320
+ };
2321
+ function ShieldedWallet(configuration) {
2322
+ return CustomShieldedWallet(configuration, new V1Builder().withDefaults());
2323
+ }
2324
+ function CustomShieldedWallet(configuration, builder) {
2325
+ const buildArgs = [configuration];
2326
+ const BaseWallet = require_watch.WalletBuilder.init().withVariant(require_const.MinSupportedVersion, builder).build(...buildArgs);
2327
+ return class CustomShieldedWalletImplementation extends BaseWallet {
2328
+ static startWithSecretKeys(secretKeys) {
2329
+ return CustomShieldedWalletImplementation.startFirst(CustomShieldedWalletImplementation, CoreWallet.initEmpty(secretKeys, CustomShieldedWalletImplementation.configuration.networkId));
2330
+ }
2331
+ static startWithSeed(seed) {
2332
+ const secretKeys = _midnight_ntwrk_ledger_v8.ZswapSecretKeys.fromSeed(seed);
2333
+ return CustomShieldedWalletImplementation.startWithSecretKeys(secretKeys);
2334
+ }
2335
+ static restore(serializedState) {
2336
+ const deserialized = CustomShieldedWalletImplementation.allVariantsRecord()[V1Tag].variant.deserializeState(serializedState).pipe(require_const.getOrThrow$1);
2337
+ return CustomShieldedWalletImplementation.startFirst(CustomShieldedWalletImplementation, deserialized);
2338
+ }
2339
+ state;
2340
+ constructor(runtime, scope) {
2341
+ super(runtime, scope);
2342
+ this.state = this.rawState.pipe(rxjs.map(ShieldedWalletState.mapState(CustomShieldedWalletImplementation.allVariantsRecord()[V1Tag].variant)), rxjs.shareReplay({
2343
+ refCount: true,
2344
+ bufferSize: 1
2345
+ }));
2346
+ }
2347
+ start(secretKeys) {
2348
+ return this.runtime.dispatch({ [V1Tag]: (v1) => v1.startSyncInBackground(secretKeys) }).pipe(require_const.runPromise);
2349
+ }
2350
+ balanceTransaction(secretKeys, tx) {
2351
+ return this.runtime.dispatch({ [V1Tag]: (v1) => v1.balanceTransaction(secretKeys, tx) }).pipe(require_const.runPromise);
2352
+ }
2353
+ transferTransaction(secretKeys, outputs) {
2354
+ return this.runtime.dispatch({ [V1Tag]: (v1) => v1.transferTransaction(secretKeys, outputs) }).pipe(require_const.runPromise);
2355
+ }
2356
+ initSwap(secretKeys, desiredInputs, desiredOutputs) {
2357
+ return this.runtime.dispatch({ [V1Tag]: (v1) => v1.initSwap(secretKeys, desiredInputs, desiredOutputs) }).pipe(require_const.runPromise);
2358
+ }
2359
+ revertTransaction(transaction) {
2360
+ return this.runtime.dispatch({ [V1Tag]: (v1) => v1.revertTransaction(transaction) }).pipe(require_const.runPromise);
2361
+ }
2362
+ waitForSyncedState(allowedGap = 0n) {
2363
+ return rxjs.firstValueFrom(this.state.pipe(rxjs.filter((state) => state.state.progress.isCompleteWithin(allowedGap))));
2364
+ }
2365
+ /**
2366
+ * Serializes the most recent state It's preferable to use [[ShieldedWalletState.serialize]] instead, to know
2367
+ * exactly, which state is serialized
2368
+ */
2369
+ serializeState() {
2370
+ return rxjs.firstValueFrom(this.state).then((state) => state.serialize());
2371
+ }
2372
+ getAddress() {
2373
+ return rxjs.firstValueFrom(this.state).then((state) => state.address);
2374
+ }
2375
+ };
2376
+ }
2377
+ //#endregion
2378
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-facade/dist/transaction.js
2379
+ const finalizedTransactionTrait = {
2380
+ areAllTxIdsIncluded(tx, txIds) {
2381
+ const txIdsSet = require_const.fromIterable$1(tx.identifiers());
2382
+ const expectedIdSet = require_const.fromIterable$1(txIds);
2383
+ return require_const.isSubset(txIdsSet, expectedIdSet);
2384
+ },
2385
+ deserialize(serialized) {
2386
+ return _midnight_ntwrk_ledger_v8.Transaction.deserialize("signature", "proof", "binding", serialized);
2387
+ },
2388
+ firstId(tx) {
2389
+ return tx.identifiers()[0];
2390
+ },
2391
+ hasTTLExpired(tx, creationTime, now) {
2392
+ const defaultShieldedGracePeriod = _midnight_ntwrk_ledger_v8.LedgerParameters.initialParameters().dust.dustGracePeriodSeconds;
2393
+ const intentTTLs = require_const.pipe(tx.intents?.values().toArray() ?? [], require_const.map$6((i) => i.ttl), require_const.filterMap$1(require_const.make));
2394
+ const hasDustPayments = require_const.pipe(tx.intents?.values().toArray() ?? [], require_const.flatMap$3((i) => i.dustActions?.spends ?? []), require_const.isNonEmptyArray);
2395
+ const hasShieldedOffers = tx.guaranteedOffer != null || (tx.fallibleOffer?.size ?? 0) == 0;
2396
+ const maybeShieldedTTL = hasDustPayments || hasShieldedOffers ? require_const.pipe(creationTime, require_const.addDuration(require_const.seconds(Number(defaultShieldedGracePeriod))), require_const.of$2) : require_const.empty$3();
2397
+ return require_const.pipe(intentTTLs, require_const.appendAll$1(maybeShieldedTTL), (arr) => require_const.isNonEmptyReadonlyArray(arr) ? require_const.some(require_const.min(arr, require_const.mapInput$1(require_const.Date, require_const.toDate))) : require_const.none(), require_const.match$3({
2398
+ onNone: () => false,
2399
+ onSome: (finalTTL) => require_const.distance(finalTTL, now) > 0
2400
+ }));
2401
+ },
2402
+ ids(tx) {
2403
+ return tx.identifiers();
2404
+ },
2405
+ isOneIncludedInOther(tx, otherTx) {
2406
+ const txIds = require_const.fromIterable$1(tx.identifiers());
2407
+ const otherTxIds = require_const.fromIterable$1(otherTx.identifiers());
2408
+ const smallerSize = require_const.min$1(require_const.number)(require_const.size(txIds), require_const.size(otherTxIds));
2409
+ const intersection$1 = require_const.intersection(txIds, otherTxIds);
2410
+ return require_const.size(intersection$1) == smallerSize;
2411
+ },
2412
+ isTx(tx) {
2413
+ return tx instanceof _midnight_ntwrk_ledger_v8.Transaction;
2414
+ },
2415
+ serialize(tx) {
2416
+ return tx.serialize();
2417
+ }
2418
+ };
2419
+ //#endregion
2420
+ //#region ../../node_modules/@midnightntwrk/wallet-sdk-facade/dist/index.js
2421
+ /**
2422
+ * Full entry schema for transaction history — common fields + all wallet sections. Pass this to
2423
+ * `InMemoryTransactionHistoryStorage` to enable serialize/restore.
2424
+ */
2425
+ const WalletEntrySchema = require_const.Struct({
2426
+ ...require_const.TransactionHistoryCommonSchema.fields,
2427
+ shielded: require_const.optional(ShieldedSectionSchema),
2428
+ unshielded: require_const.optional(require_watch.UnshieldedSectionSchema),
2429
+ dust: require_const.optional(DustSectionSchema)
2430
+ });
2431
+ const mergeWalletEntries = (existing, incoming) => ({
2432
+ ...existing,
2433
+ ...incoming,
2434
+ ...existing.shielded !== void 0 && incoming.shielded !== void 0 ? { shielded: mergeShieldedSections(existing.shielded, incoming.shielded) } : {},
2435
+ ...existing.unshielded !== void 0 && incoming.unshielded !== void 0 ? { unshielded: {
2436
+ ...existing.unshielded,
2437
+ ...incoming.unshielded
2438
+ } } : {},
2439
+ ...existing.dust !== void 0 && incoming.dust !== void 0 ? { dust: mergeDustSections(existing.dust, incoming.dust) } : {}
2440
+ });
2441
+ const isWalletEntry = require_const.is(WalletEntrySchema);
2442
+ const TokenKindsToBalance = new class {
2443
+ allTokenKinds = [
2444
+ "shielded",
2445
+ "unshielded",
2446
+ "dust"
2447
+ ];
2448
+ toFlags = (tokenKinds) => {
2449
+ return require_const.pipe(tokenKinds, (kinds) => kinds === "all" ? this.allTokenKinds : kinds, (kinds) => ({
2450
+ shouldBalanceUnshielded: kinds.includes("unshielded"),
2451
+ shouldBalanceShielded: kinds.includes("shielded"),
2452
+ shouldBalanceDust: kinds.includes("dust")
2453
+ }));
2454
+ };
2455
+ }();
2456
+ const BalancingRecipe = {
2457
+ isRecipe: (value) => {
2458
+ return typeof value === "object" && value !== null && "type" in value && typeof value.type === "string" && [
2459
+ "FINALIZED_TRANSACTION",
2460
+ "UNBOUND_TRANSACTION",
2461
+ "UNPROVEN_TRANSACTION"
2462
+ ].includes(value.type);
2463
+ },
2464
+ getTransactions: (recipe) => {
2465
+ switch (recipe.type) {
2466
+ case "FINALIZED_TRANSACTION": return [recipe.originalTransaction, recipe.balancingTransaction];
2467
+ case "UNBOUND_TRANSACTION": {
2468
+ const balancingPart = recipe.balancingTransaction ? [recipe.balancingTransaction] : [];
2469
+ return [recipe.baseTransaction, ...balancingPart];
2470
+ }
2471
+ case "UNPROVEN_TRANSACTION": return [recipe.transaction];
2472
+ }
2473
+ }
2474
+ };
2475
+ var FacadeState = class {
2476
+ shielded;
2477
+ unshielded;
2478
+ dust;
2479
+ pending;
2480
+ get isSynced() {
2481
+ return this.shielded.state.progress.isStrictlyComplete() && this.dust.state.progress.isStrictlyComplete() && this.unshielded.progress.isStrictlyComplete();
2482
+ }
2483
+ constructor(shielded, unshielded, dust, pending) {
2484
+ this.shielded = shielded;
2485
+ this.unshielded = unshielded;
2486
+ this.dust = dust;
2487
+ this.pending = pending;
2488
+ }
2489
+ };
2490
+ const DEFAULT_TTL_MS = 3600 * 1e3;
2491
+ var WalletFacade = class WalletFacade {
2492
+ static makeDefaultSubmissionService(config) {
2493
+ return require_watch.makeDefaultSubmissionService(config);
2494
+ }
2495
+ static makeDefaultPendingTransactionsService(config) {
2496
+ return require_watch.PendingTransactionsServiceImpl.init({
2497
+ configuration: config,
2498
+ txTrait: finalizedTransactionTrait
2499
+ });
2500
+ }
2501
+ static makeDefaultProvingService(config) {
2502
+ if (config.provingServerUrl) return require_watch.makeDefaultProvingService({ provingServerUrl: config.provingServerUrl });
2503
+ else throw new Error("Missing required configuration: 'provingServerUrl' must be set in config, or provide a custom provingService in init parameters.");
2504
+ }
2505
+ /**
2506
+ * Fetches the current Terms and Conditions from the network indexer.
2507
+ *
2508
+ * This is a static, pre-initialization utility — no wallet instance is required. Wallet builders should call this
2509
+ * before or independently of wallet initialization to display the current T&C to end users and obtain the hash for
2510
+ * content verification.
2511
+ *
2512
+ * The returned `hash` is the hex-encoded SHA-256 hash of the document at `url`. Wallet builders are responsible for
2513
+ * fetching and rendering the document content via `url` in whatever manner suits their application.
2514
+ *
2515
+ * @param configuration - An object with an `indexerClientConnection.indexerHttpUrl`. Any wallet configuration that
2516
+ * satisfies {@link FetchTermsAndConditionsConfiguration} can be passed directly.
2517
+ * @returns A promise resolving to the current {@link TermsAndConditions}, or rejecting if no Terms and Conditions have
2518
+ * been set on the network yet.
2519
+ */
2520
+ static async fetchTermsAndConditions(configuration) {
2521
+ const tc = (await require_watch.runPromise(require_watch.FetchTermsAndConditions, {}, { url: configuration.indexerClientConnection.indexerHttpUrl })).block?.systemParameters?.termsAndConditions;
2522
+ if (!tc) throw new Error("Terms and Conditions are not currently set on the network.");
2523
+ return tc;
2524
+ }
2525
+ /**
2526
+ * Default initialization for {@link WalletFacade}. It is a static method, which takes an object holding configuration
2527
+ * and initialization of necessary components. Specifically - it requires following fields:
2528
+ *
2529
+ * - `configuration` - holding a configuration, which needs to extend {@link DefaultConfiguration} - this way allows to
2530
+ * convey use-case-specific settings in the same way, as the SDK works by default
2531
+ * - `shielded` - a function taking the configuration and returning shielded wallet (or a promise with such)
2532
+ * implementing {@link ShieldedWalletAPI}
2533
+ * - `unshielded` - a function taking the configuration and returning unshielded wallet (or a promise with such)
2534
+ * implementing {@link UnshieldedWalletAPI}
2535
+ * - `dust` - a function taking the configuration and returning Dust wallet (or a promise with such) implementing
2536
+ * {@link DustWalletAPI} There are some optional services/abstractions to provide, too. If not provided - default
2537
+ * implementations will be used, each of them is initialized by a function taking the configuration and returning
2538
+ * proper implementation (wrapped in a {@link Promise} or not).
2539
+ * - `submissionService` - needs to implement {@link SubmissionService} for a {@link ledger.FinalizedTransaction} to
2540
+ * submit transactions to the network, default uses Node RPC connection
2541
+ * - `pendingTransactionsService` - needs to implement {@link PendingTransactionsService} for a
2542
+ * {@link ledger.FinalizedTransaction} to keep track of pending transactions, default uses in-memory implementation
2543
+ * - `provingService` - needs to implement {@link ProvingService} to prove it, default uses proving server
2544
+ * - `clock` - needs to implement {@link Clock.Clock} for getting current time, default uses system clock
2545
+ */
2546
+ static async init(initParams) {
2547
+ const submissionService = await Promise.resolve(initParams.submissionService ? initParams.submissionService(initParams.configuration) : WalletFacade.makeDefaultSubmissionService(initParams.configuration));
2548
+ const pendingTransactionsService = await Promise.resolve(initParams.pendingTransactionsService ? initParams.pendingTransactionsService(initParams.configuration) : WalletFacade.makeDefaultPendingTransactionsService(initParams.configuration));
2549
+ const provingService = await Promise.resolve(initParams.provingService ? initParams.provingService(initParams.configuration) : WalletFacade.makeDefaultProvingService(initParams.configuration));
2550
+ const shielded = await Promise.resolve(initParams.shielded(initParams.configuration));
2551
+ const unshielded = await Promise.resolve(initParams.unshielded(initParams.configuration));
2552
+ const dust = await Promise.resolve(initParams.dust(initParams.configuration));
2553
+ const clock = await Promise.resolve(initParams.clock ? initParams.clock(initParams.configuration) : require_watch.systemClock);
2554
+ return new WalletFacade(shielded, unshielded, dust, submissionService, pendingTransactionsService, provingService, initParams.configuration.txHistoryStorage, clock);
2555
+ }
2556
+ shielded;
2557
+ unshielded;
2558
+ dust;
2559
+ submissionService;
2560
+ pendingTransactionsService;
2561
+ provingService;
2562
+ #txHistoryStorage;
2563
+ clock;
2564
+ #pendingSubscription;
2565
+ /**
2566
+ * Constructor is private on purpose - much of initialization of the facade is potentially asynchronous, and adding
2567
+ * new parameters is a breaking change to the users Use {@link WalletFacade.init} instead
2568
+ *
2569
+ * @private
2570
+ */
2571
+ constructor(shieldedWallet, unshieldedWallet, dustWallet, submissionService, pendingTransactionsService, provingService, txHistoryStorage, clock = require_watch.systemClock) {
2572
+ this.shielded = shieldedWallet;
2573
+ this.unshielded = unshieldedWallet;
2574
+ this.dust = dustWallet;
2575
+ this.submissionService = submissionService;
2576
+ this.pendingTransactionsService = pendingTransactionsService;
2577
+ this.provingService = provingService;
2578
+ this.#txHistoryStorage = txHistoryStorage;
2579
+ this.clock = clock;
2580
+ this.#pendingSubscription = this.pendingTransactionsService.state().pipe((0, rxjs.concatMap)((pending) => require_watch.allFailed(pending)), (0, rxjs.concatMap)((item) => this.revert(item.tx))).subscribe();
2581
+ }
2582
+ defaultTtl() {
2583
+ return new Date(this.clock.now().getTime() + DEFAULT_TTL_MS);
2584
+ }
2585
+ mergeUnprovenTransactions(a, b) {
2586
+ if (a && b) return a.merge(b);
2587
+ return a ?? b;
2588
+ }
2589
+ async createDustActionTransaction(action, nightUtxos, nightVerifyingKey, signDustRegistration) {
2590
+ const ttl = this.defaultTtl();
2591
+ const now = this.clock.now();
2592
+ const isRegistration = action.type === "registration";
2593
+ const dustReceiverAddress = isRegistration ? action.dustReceiverAddress : void 0;
2594
+ const split = await this.dust.splitNightUtxosForDustRegistration(now, nightUtxos.map(({ utxo, meta }) => ({
2595
+ ...utxo,
2596
+ ctime: meta.ctime,
2597
+ registeredForDustGeneration: meta.registeredForDustGeneration
2598
+ })), isRegistration);
2599
+ const toUnshieldedUtxoWithMeta = (u) => ({
2600
+ utxo: {
2601
+ value: u.utxo.value,
2602
+ type: u.utxo.type,
2603
+ owner: u.utxo.owner,
2604
+ intentHash: u.utxo.intentHash,
2605
+ outputNo: u.utxo.outputNo
2606
+ },
2607
+ meta: {
2608
+ ctime: u.utxo.ctime,
2609
+ registeredForDustGeneration: u.utxo.registeredForDustGeneration
2610
+ }
2611
+ });
2612
+ const guaranteedForUnshielded = split.guaranteedUtxos.map(toUnshieldedUtxoWithMeta);
2613
+ const fallibleForUnshielded = split.fallibleUtxos.map(toUnshieldedUtxoWithMeta);
2614
+ const txWithOffers = await this.unshielded.rotateUtxos(guaranteedForUnshielded, fallibleForUnshielded, nightVerifyingKey, ttl);
2615
+ let txWithDustActions;
2616
+ try {
2617
+ txWithDustActions = await this.dust.attachDustRegistration(txWithOffers, now, nightVerifyingKey, dustReceiverAddress, split.feePayment);
2618
+ } catch (error) {
2619
+ await this.unshielded.revertTransaction(txWithOffers);
2620
+ throw error;
2621
+ }
2622
+ const hasUnregisteredGuaranteed = split.guaranteedUtxos.some((u) => !u.utxo.registeredForDustGeneration);
2623
+ if (isRegistration && hasUnregisteredGuaranteed) {
2624
+ const fee = await this.dust.calculateFee([txWithDustActions]);
2625
+ if (split.feePayment < fee) {
2626
+ await this.unshielded.revertTransaction(txWithOffers);
2627
+ throw Error(`Insufficient generated dust to cover registration fee (have ${split.feePayment}, need ${fee}). Use WalletFacade.waitForGeneratedDust(utxos, ${fee}) before retrying.`);
2628
+ }
2629
+ }
2630
+ try {
2631
+ const signedRecipe = await this.signRecipe({
2632
+ type: "UNPROVEN_TRANSACTION",
2633
+ transaction: txWithDustActions
2634
+ }, signDustRegistration);
2635
+ if (signedRecipe.type !== "UNPROVEN_TRANSACTION") throw Error("signRecipe returned unexpected recipe type for dust action transaction.");
2636
+ return signedRecipe.transaction;
2637
+ } catch (error) {
2638
+ await this.unshielded.revertTransaction(txWithOffers);
2639
+ throw error;
2640
+ }
2641
+ }
2642
+ state() {
2643
+ return (0, rxjs.combineLatest)([
2644
+ this.shielded.state,
2645
+ this.unshielded.state,
2646
+ this.dust.state,
2647
+ this.pendingTransactionsService.state()
2648
+ ]).pipe((0, rxjs.map)(([shieldedState, unshieldedState, dustState, pending]) => new FacadeState(shieldedState, unshieldedState, dustState, pending)));
2649
+ }
2650
+ async waitForSyncedState() {
2651
+ const [shieldedState, unshieldedState, dustState, pending] = await Promise.all([
2652
+ this.shielded.waitForSyncedState(),
2653
+ this.unshielded.waitForSyncedState(),
2654
+ this.dust.waitForSyncedState(),
2655
+ (0, rxjs.firstValueFrom)(this.pendingTransactionsService.state())
2656
+ ]);
2657
+ return new FacadeState(shieldedState, unshieldedState, dustState, pending);
2658
+ }
2659
+ async submitTransaction(tx) {
2660
+ try {
2661
+ await this.pendingTransactionsService.addPendingTransaction(tx);
2662
+ await this.submissionService.submitTransaction(tx, "Finalized");
2663
+ return tx.identifiers().at(-1);
2664
+ } catch (error) {
2665
+ await this.revert(tx);
2666
+ throw error;
2667
+ }
2668
+ }
2669
+ async balanceFinalizedTransaction(tx, secretKeys, options) {
2670
+ const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2671
+ const { ttl, tokenKindsToBalance = "all" } = options;
2672
+ const { shouldBalanceDust, shouldBalanceShielded, shouldBalanceUnshielded } = TokenKindsToBalance.toFlags(tokenKindsToBalance);
2673
+ const unshieldedBalancingTx = shouldBalanceUnshielded ? await this.unshielded.balanceFinalizedTransaction(tx) : void 0;
2674
+ const shieldedBalancingTx = shouldBalanceShielded ? await this.shielded.balanceTransaction(shieldedSecretKeys, tx) : void 0;
2675
+ const mergedBalancingTx = this.mergeUnprovenTransactions(shieldedBalancingTx, unshieldedBalancingTx);
2676
+ const feeBalancingTx = shouldBalanceDust ? await this.dust.balanceTransactions(dustSecretKey, mergedBalancingTx ? [tx, mergedBalancingTx] : [tx], ttl) : void 0;
2677
+ const balancingTx = this.mergeUnprovenTransactions(mergedBalancingTx, feeBalancingTx);
2678
+ if (!balancingTx) throw new Error("No balancing transaction was created. Please check your transaction.");
2679
+ return {
2680
+ type: "FINALIZED_TRANSACTION",
2681
+ originalTransaction: tx,
2682
+ balancingTransaction: balancingTx
2683
+ };
2684
+ }
2685
+ async balanceUnboundTransaction(tx, secretKeys, options) {
2686
+ const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2687
+ const { ttl, tokenKindsToBalance = "all" } = options;
2688
+ const { shouldBalanceDust, shouldBalanceShielded, shouldBalanceUnshielded } = TokenKindsToBalance.toFlags(tokenKindsToBalance);
2689
+ const shieldedBalancingTx = shouldBalanceShielded ? await this.shielded.balanceTransaction(shieldedSecretKeys, tx) : void 0;
2690
+ const balancedUnshieldedTx = shouldBalanceUnshielded ? await this.unshielded.balanceUnboundTransaction(tx) : void 0;
2691
+ const baseTx = balancedUnshieldedTx ?? tx;
2692
+ const feeBalancingTransaction = shouldBalanceDust ? await this.dust.balanceTransactions(dustSecretKey, shieldedBalancingTx ? [baseTx, shieldedBalancingTx] : [baseTx], ttl) : void 0;
2693
+ const balancingTransaction = this.mergeUnprovenTransactions(shieldedBalancingTx, feeBalancingTransaction);
2694
+ if (!balancingTransaction && !balancedUnshieldedTx) throw new Error("No balancing transaction was created. Please check your transaction.");
2695
+ return {
2696
+ type: "UNBOUND_TRANSACTION",
2697
+ baseTransaction: baseTx,
2698
+ balancingTransaction: balancingTransaction ?? void 0
2699
+ };
2700
+ }
2701
+ async balanceUnprovenTransaction(tx, secretKeys, options) {
2702
+ const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2703
+ const { ttl, tokenKindsToBalance = "all" } = options;
2704
+ const { shouldBalanceDust, shouldBalanceShielded, shouldBalanceUnshielded } = TokenKindsToBalance.toFlags(tokenKindsToBalance);
2705
+ const shieldedBalancingTx = shouldBalanceShielded ? await this.shielded.balanceTransaction(shieldedSecretKeys, tx) : void 0;
2706
+ const baseTx = (shouldBalanceUnshielded ? await this.unshielded.balanceUnprovenTransaction(tx) : void 0) ?? tx;
2707
+ const mergedTx = this.mergeUnprovenTransactions(baseTx, shieldedBalancingTx);
2708
+ const feeBalancingTx = shouldBalanceDust ? await this.dust.balanceTransactions(dustSecretKey, [mergedTx], ttl) : void 0;
2709
+ return {
2710
+ type: "UNPROVEN_TRANSACTION",
2711
+ transaction: this.mergeUnprovenTransactions(mergedTx, feeBalancingTx)
2712
+ };
2713
+ }
2714
+ async finalizeRecipe(recipe) {
2715
+ return Promise.resolve(recipe).then(async (recipe) => {
2716
+ switch (recipe.type) {
2717
+ case "FINALIZED_TRANSACTION": {
2718
+ const finalizedBalancing = await this.finalizeTransaction(recipe.balancingTransaction);
2719
+ return recipe.originalTransaction.merge(finalizedBalancing);
2720
+ }
2721
+ case "UNBOUND_TRANSACTION": {
2722
+ const finalizedBalancingTx = recipe.balancingTransaction ? await this.finalizeTransaction(recipe.balancingTransaction) : void 0;
2723
+ const finalizedTransaction = recipe.baseTransaction.bind();
2724
+ return finalizedBalancingTx ? finalizedTransaction.merge(finalizedBalancingTx) : finalizedTransaction;
2725
+ }
2726
+ case "UNPROVEN_TRANSACTION": return await this.finalizeTransaction(recipe.transaction);
2727
+ }
2728
+ }).then(async (finalizedTx) => {
2729
+ await this.pendingTransactionsService.addPendingTransaction(finalizedTx);
2730
+ return finalizedTx;
2731
+ });
2732
+ }
2733
+ async signRecipe(recipe, signSegment) {
2734
+ switch (recipe.type) {
2735
+ case "FINALIZED_TRANSACTION": {
2736
+ const signedBalancingTx = await this.signUnprovenTransaction(recipe.balancingTransaction, signSegment);
2737
+ const withDustSig = await this.#signDustRegistrationIfPresent(signedBalancingTx, signSegment);
2738
+ return {
2739
+ type: "FINALIZED_TRANSACTION",
2740
+ originalTransaction: recipe.originalTransaction,
2741
+ balancingTransaction: withDustSig
2742
+ };
2743
+ }
2744
+ case "UNBOUND_TRANSACTION": {
2745
+ const signedBalancingTx = recipe.balancingTransaction ? await this.signUnprovenTransaction(recipe.balancingTransaction, signSegment).then((tx) => this.#signDustRegistrationIfPresent(tx, signSegment)) : void 0;
2746
+ return {
2747
+ type: "UNBOUND_TRANSACTION",
2748
+ baseTransaction: await this.signUnboundTransaction(recipe.baseTransaction, signSegment),
2749
+ balancingTransaction: signedBalancingTx
2750
+ };
2751
+ }
2752
+ case "UNPROVEN_TRANSACTION": {
2753
+ const signedTx = await this.signUnprovenTransaction(recipe.transaction, signSegment);
2754
+ return {
2755
+ type: "UNPROVEN_TRANSACTION",
2756
+ transaction: await this.#signDustRegistrationIfPresent(signedTx, signSegment)
2757
+ };
2758
+ }
2759
+ }
2760
+ }
2761
+ async #signDustRegistrationIfPresent(tx, signSegment) {
2762
+ const intent = tx.intents?.get(1);
2763
+ const registrations = intent?.dustActions?.registrations ?? [];
2764
+ if (!intent || registrations.length === 0) return tx;
2765
+ const signature = signSegment(intent.signatureData(1));
2766
+ return await this.dust.addDustRegistrationSignature(tx, signature);
2767
+ }
2768
+ async signUnprovenTransaction(tx, signSegment) {
2769
+ return await this.unshielded.signUnprovenTransaction(tx, signSegment);
2770
+ }
2771
+ async signUnboundTransaction(tx, signSegment) {
2772
+ return await this.unshielded.signUnboundTransaction(tx, signSegment);
2773
+ }
2774
+ async finalizeTransaction(tx) {
2775
+ try {
2776
+ const finalizedTx = (await this.provingService.prove(tx)).bind();
2777
+ await this.pendingTransactionsService.addPendingTransaction(finalizedTx);
2778
+ return finalizedTx;
2779
+ } catch (error) {
2780
+ await Promise.allSettled([
2781
+ this.shielded.revertTransaction(tx),
2782
+ this.unshielded.revertTransaction(tx),
2783
+ this.dust.revertTransaction(tx)
2784
+ ]);
2785
+ throw error;
2786
+ }
2787
+ }
2788
+ /** Estimates the fee for the given transaction only. This lacks the fees of the balancing transaction. */
2789
+ async calculateTransactionFee(tx) {
2790
+ return await this.dust.calculateFee([tx]);
2791
+ }
2792
+ /** Calculates the total fee for the given transaction plus the fee of the balancing transaction. */
2793
+ async estimateTransactionFee(tx, secretKey, options) {
2794
+ const ttl = options?.ttl ?? this.defaultTtl();
2795
+ return await this.dust.estimateFee(secretKey, [tx], ttl, options?.currentTime);
2796
+ }
2797
+ async transferTransaction(outputs, secretKeys, options) {
2798
+ const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2799
+ const { ttl, payFees = true } = options;
2800
+ const unshieldedOutputs = outputs.filter((output) => output.type === "unshielded").flatMap((output) => output.outputs);
2801
+ const shieldedOutputs = outputs.filter((output) => output.type === "shielded").flatMap((output) => output.outputs);
2802
+ if (unshieldedOutputs.length === 0 && shieldedOutputs.length === 0) throw Error("At least one shielded or unshielded output is required.");
2803
+ const shieldedTx = shieldedOutputs.length > 0 ? await this.shielded.transferTransaction(shieldedSecretKeys, shieldedOutputs) : void 0;
2804
+ const unshieldedTx = unshieldedOutputs.length > 0 ? await this.unshielded.transferTransaction(unshieldedOutputs, ttl) : void 0;
2805
+ const mergedTxs = this.mergeUnprovenTransactions(shieldedTx, unshieldedTx);
2806
+ const feeBalancingTx = payFees ? await this.dust.balanceTransactions(dustSecretKey, [mergedTxs], ttl) : void 0;
2807
+ return {
2808
+ type: "UNPROVEN_TRANSACTION",
2809
+ transaction: this.mergeUnprovenTransactions(mergedTxs, feeBalancingTx)
2810
+ };
2811
+ }
2812
+ /**
2813
+ * Provides estimate of the fee of issuing registration transaction with provided UTxOs
2814
+ *
2815
+ * @param nightUtxos - Night UTxOs to use for the registration
2816
+ * @returns And object informing about fee at the moment, as well as estimation of dust generation of the UTxO(s),
2817
+ * that would be used for paying the fee. These include data that allows to compute when the fee could be paid
2818
+ */
2819
+ async estimateRegistration(nightUtxos) {
2820
+ const now = this.clock.now();
2821
+ const dustState = await this.dust.waitForSyncedState();
2822
+ const dustGenerationEstimations = require_const.pipe(nightUtxos, require_const.map$6(({ utxo, meta }) => ({
2823
+ ...utxo,
2824
+ ctime: meta.ctime,
2825
+ registeredForDustGeneration: meta.registeredForDustGeneration
2826
+ })), (utxosWithMeta) => dustState.estimateDustGeneration(utxosWithMeta, now), (estimatedUtxos) => dustState.capabilities.coinsAndBalances.splitNightUtxos(estimatedUtxos), (split) => split.guaranteed);
2827
+ const fakeSigningKey = _midnight_ntwrk_ledger_v8.sampleSigningKey();
2828
+ const fakeVerifyingKey = _midnight_ntwrk_ledger_v8.signatureVerifyingKey(fakeSigningKey);
2829
+ const ttl = this.defaultTtl();
2830
+ const fakeUnsignedTx = await this.dust.createDustGenerationTransaction(void 0, ttl, nightUtxos.map(({ utxo, meta }) => ({
2831
+ ...utxo,
2832
+ ctime: meta.ctime,
2833
+ registeredForDustGeneration: meta.registeredForDustGeneration
2834
+ })), fakeVerifyingKey, dustState.address);
2835
+ const intent = fakeUnsignedTx.intents?.get(1);
2836
+ if (!intent) throw Error("Dust generation transaction is missing intent segment 1.");
2837
+ const signatureData = intent.signatureData(1);
2838
+ const signature = _midnight_ntwrk_ledger_v8.signData(fakeSigningKey, signatureData);
2839
+ const finalizedFakeTx = (await this.dust.addDustGenerationSignature(fakeUnsignedTx, signature)).mockProve().bind();
2840
+ return {
2841
+ fee: await this.calculateTransactionFee(finalizedFakeTx),
2842
+ dustGenerationEstimations
2843
+ };
2844
+ }
2845
+ async initSwap(desiredInputs, desiredOutputs, secretKeys, options) {
2846
+ const { shieldedSecretKeys, dustSecretKey } = secretKeys;
2847
+ const { ttl, payFees = false } = options;
2848
+ const { shielded: shieldedInputs, unshielded: unshieldedInputs } = desiredInputs;
2849
+ const shieldedOutputs = desiredOutputs.filter((output) => output.type === "shielded").flatMap((output) => output.outputs);
2850
+ const unshieldedOutputs = desiredOutputs.filter((output) => output.type === "unshielded").flatMap((output) => output.outputs);
2851
+ const hasShieldedPart = shieldedInputs && Object.keys(shieldedInputs).length > 0 || shieldedOutputs.length > 0;
2852
+ const hasUnshieldedPart = unshieldedInputs && Object.keys(unshieldedInputs).length > 0 || unshieldedOutputs.length > 0;
2853
+ if (!hasShieldedPart && !hasUnshieldedPart) throw Error("At least one shielded or unshielded swap is required.");
2854
+ const shieldedTx = hasShieldedPart && shieldedInputs !== void 0 ? await this.shielded.initSwap(shieldedSecretKeys, shieldedInputs, shieldedOutputs) : void 0;
2855
+ const unshieldedTx = hasUnshieldedPart && unshieldedInputs !== void 0 ? await this.unshielded.initSwap(unshieldedInputs, unshieldedOutputs, ttl) : void 0;
2856
+ const combinedTx = this.mergeUnprovenTransactions(shieldedTx, unshieldedTx);
2857
+ if (!combinedTx) throw Error("Unexpected transaction state.");
2858
+ const feeBalancingTx = payFees ? await this.dust.balanceTransactions(dustSecretKey, [combinedTx], ttl) : void 0;
2859
+ return {
2860
+ type: "UNPROVEN_TRANSACTION",
2861
+ transaction: this.mergeUnprovenTransactions(combinedTx, feeBalancingTx)
2862
+ };
2863
+ }
2864
+ async registerNightUtxosForDustGeneration(nightUtxos, nightVerifyingKey, signDustRegistration, dustReceiverAddress) {
2865
+ if (nightUtxos.length === 0) throw Error("At least one Night UTXO is required.");
2866
+ const receiverAddress = dustReceiverAddress ?? await this.dust.getAddress();
2867
+ return {
2868
+ type: "UNPROVEN_TRANSACTION",
2869
+ transaction: await this.createDustActionTransaction({
2870
+ type: "registration",
2871
+ dustReceiverAddress: receiverAddress
2872
+ }, nightUtxos, nightVerifyingKey, signDustRegistration)
2873
+ };
2874
+ }
2875
+ /**
2876
+ * Waits until the dust projected to be generated by the given Night UTxOs reaches `requiredAmount`, re-checking every
2877
+ * second. Pair with {@link estimateRegistration} to pick `requiredAmount`, then call before
2878
+ * {@link registerNightUtxosForDustGeneration} so the registration covers its own fee.
2879
+ *
2880
+ * @param nightUtxos - Night UTxOs to project generation for; the same set passed to the registration.
2881
+ * @param requiredAmount - Dust threshold to wait for. Resolves immediately if `<= 0n`.
2882
+ * @param opts.timeoutMs - Deadline, in ms, for the threshold to be reached. Rejects otherwise. Default `300_000`.
2883
+ * @throws If `nightUtxos` is empty, or if `requiredAmount` is not reached within `opts.timeoutMs`.
2884
+ */
2885
+ async waitForGeneratedDust(nightUtxos, requiredAmount, opts) {
2886
+ await this.dust.waitForGeneratedDust(nightUtxos.map(({ utxo, meta }) => ({
2887
+ ...utxo,
2888
+ ctime: meta.ctime,
2889
+ registeredForDustGeneration: meta.registeredForDustGeneration
2890
+ })), requiredAmount, this.clock, opts);
2891
+ }
2892
+ async deregisterFromDustGeneration(nightUtxos, nightVerifyingKey, signDustRegistration) {
2893
+ return {
2894
+ type: "UNPROVEN_TRANSACTION",
2895
+ transaction: await this.createDustActionTransaction({ type: "deregistration" }, nightUtxos, nightVerifyingKey, signDustRegistration)
2896
+ };
2897
+ }
2898
+ async revert(txOrRecipe) {
2899
+ const transactionsToRevert = BalancingRecipe.isRecipe(txOrRecipe) ? BalancingRecipe.getTransactions(txOrRecipe) : [txOrRecipe];
2900
+ await Promise.all(transactionsToRevert.map((tx) => this.revertTransaction(tx)));
2901
+ }
2902
+ async revertTransaction(tx) {
2903
+ await Promise.all([
2904
+ this.shielded.revertTransaction(tx),
2905
+ this.unshielded.revertTransaction(tx),
2906
+ this.dust.revertTransaction(tx)
2907
+ ]).then(() => this.pendingTransactionsService.clear(tx));
2908
+ }
2909
+ async start(shieldedSecretKeys, dustSecretKey) {
2910
+ await Promise.all([
2911
+ this.shielded.start(shieldedSecretKeys),
2912
+ this.unshielded.start(),
2913
+ this.dust.start(dustSecretKey),
2914
+ this.pendingTransactionsService.start()
2915
+ ]);
2916
+ }
2917
+ async stop() {
2918
+ await Promise.all([
2919
+ this.shielded.stop(),
2920
+ this.unshielded.stop(),
2921
+ this.dust.stop(),
2922
+ this.submissionService.close(),
2923
+ this.pendingTransactionsService.stop(),
2924
+ Promise.resolve(this.#pendingSubscription?.unsubscribe())
2925
+ ]);
2926
+ }
2927
+ async queryTxHistoryByHash(hash) {
2928
+ const raw = await this.#txHistoryStorage.get(hash);
2929
+ return raw && isWalletEntry(raw) ? raw : void 0;
2930
+ }
2931
+ async getAllFromTxHistory() {
2932
+ return [...await this.#txHistoryStorage.getAll()];
2933
+ }
2934
+ };
2935
+ //#endregion
2936
+ //#region ../../packages/module/midnight-sync/src/store/compute-sync-ratio.ts
2937
+ const computeConnectedSyncRatio = (applied, highest, isConnected) => isConnected && applied === 0n && highest === 0n ? require_Percent.Percent(1) : computeSyncRatio(applied, highest);
2938
+ const computeSyncRatio = (applied, highest) => {
2939
+ if (highest === 0n) {
2940
+ if (applied === 0n) return require_Percent.Percent(0);
2941
+ const ratio = 1 - 1 / (1 + Number(applied) / 1e3);
2942
+ return require_Percent.Percent(Math.min(.99, ratio));
2943
+ }
2944
+ return require_Percent.Percent(Math.min(1, Number(applied) / Number(highest)));
2945
+ };
2946
+ //#endregion
2947
+ //#region ../../packages/module/midnight-sync/src/store/dependencies.ts
2948
+ /**
2949
+ * Wraps keyManager.keys$ with recovery for AuthenticationCancelledError.
2950
+ * If the user cancels the auth prompt, waits for keys to become available
2951
+ * from another source (e.g., an unlock triggered by a different flow)
2952
+ * and retries.
2953
+ */
2954
+ const keysWithAuthCancelledRecovery$ = (keyManager) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.catchError)((error) => {
2955
+ if (!(error instanceof require_types.AuthenticationCancelledError)) return (0, rxjs.throwError)(() => error);
2956
+ return keyManager.areKeysAvailable$.pipe((0, rxjs.filter)((available) => available), (0, rxjs.take)(1), (0, rxjs.switchMap)(() => keyManager.keys$.pipe((0, rxjs.take)(1))));
2957
+ }));
2958
+ const STATE_SERIALISATION_THROTTLE_TIME = require_time_vo.Milliseconds(5e3);
2959
+ const DEFAULT_BATCH_UPDATES = {
2960
+ size: 12,
2961
+ spacing: 4
2962
+ };
2963
+ /**
2964
+ * Restore accepts the legacy `unshieldedTxHistory` key so profiles written
2965
+ * before the persisted key was renamed load without a resync; the next persist
2966
+ * rewrites the doc under `txHistory`, migrating it lazily.
2967
+ */
2968
+ const readPersistedTxHistory = (serializedState) => serializedState.txHistory ?? serializedState.unshieldedTxHistory;
2969
+ /**
2970
+ * djb2 over the serialized states. The previous-persist comparator must not
2971
+ * RETAIN the inputs: keeping the raw serialized strings would pin ~10MB per
2972
+ * synced wallet in service worker memory between persist cycles.
2973
+ */
2974
+ const fingerprintOf = (parts) => {
2975
+ let hash = 5381;
2976
+ for (const part of parts) for (let index = 0; index < part.length; index += 1) {
2977
+ hash = hash * 33 ^ part.charCodeAt(index);
2978
+ hash |= 0;
2979
+ }
2980
+ return `${hash}:${parts.map((part) => part.length).join(":")}`;
2981
+ };
2982
+ const getAccountWalletInstance = async ({ account, config, getTemenosLedgerIndexerUrl, store, keyManager }, logger, { createAttestedProver, batchUpdates = DEFAULT_BATCH_UPDATES }) => {
2983
+ const walletState = await (0, rxjs.firstValueFrom)(store.get(String(account.accountId)).pipe((0, rxjs.defaultIfEmpty)(void 0)));
2984
+ const indexerClientConnection = {
2985
+ indexerHttpUrl: config.indexerAddress,
2986
+ indexerWsUrl: require_utils.convertHttpUrlToWebsocket(config.indexerAddress),
2987
+ keepAlive: 15e3
2988
+ };
2989
+ const { networkId } = account.blockchainSpecific;
2990
+ const proofServerUrl = require_const.getProofServerEndpoint(config.proofServer);
2991
+ if (!proofServerUrl) throw new Error(`Cannot start Midnight wallet: proof server mode "${config.proofServer.kind}" has no HTTP endpoint`);
2992
+ require_const.assertProofServerRouting(config.proofServer, !!createAttestedProver);
2993
+ const createAccess = (onProgress) => config.proofServer.kind === "tee-delegated" && createAttestedProver ? require_watch.createAttestedProofServerAccess(createAttestedProver({
2994
+ networkId,
2995
+ proofServerApiUrl: config.proofServer.url,
2996
+ getLedgerIndexerUrl: async () => {
2997
+ if (!getTemenosLedgerIndexerUrl) throw new Error("Temenos attestation requires a ledger indexer resolver");
2998
+ return getTemenosLedgerIndexerUrl();
2999
+ }
3000
+ }), onProgress) : require_watch.createProofServerAccess(require_watch.createHttpProofServerTransport(proofServerUrl));
3001
+ const proofServer = require_watch.createScopedProofServerAccess(createAccess);
3002
+ const { finalizeRecipe } = proofServer;
3003
+ const configuration = {
3004
+ costParameters: {
3005
+ additionalFeeOverhead: 300000000000000n,
3006
+ feeBlocksMargin: 5
3007
+ },
3008
+ networkId,
3009
+ batchUpdates,
3010
+ indexerClientConnection,
3011
+ relayURL: new URL(require_utils.convertHttpUrlToWebsocket(config.nodeAddress)),
3012
+ txHistoryStorage: new require_const.InMemoryTransactionHistoryStorage(WalletEntrySchema, mergeWalletEntries)
3013
+ };
3014
+ if (walletState) {
3015
+ const { dust, shielded, unshielded } = walletState.serializedState;
3016
+ let restoredTxHistoryStorage;
3017
+ try {
3018
+ restoredTxHistoryStorage = require_const.InMemoryTransactionHistoryStorage.restore(SerialisedWalletState.toJSON(readPersistedTxHistory(walletState.serializedState)), WalletEntrySchema, mergeWalletEntries);
3019
+ } catch (error) {
3020
+ logger.warn(`Discarding unreadable persisted Midnight wallet state for account ${account.accountId}; rebuilding from seed`, error instanceof Error ? error.message : String(error));
3021
+ await (0, rxjs.firstValueFrom)(store.removeWhere((state) => state.accountId === account.accountId).pipe((0, rxjs.defaultIfEmpty)(void 0), (0, rxjs.catchError)((wipeError) => {
3022
+ logger.error(`Failed to discard unreadable Midnight wallet state for account ${account.accountId}`, wipeError);
3023
+ return (0, rxjs.of)(void 0);
3024
+ })));
3025
+ }
3026
+ if (restoredTxHistoryStorage) {
3027
+ configuration.txHistoryStorage = restoredTxHistoryStorage;
3028
+ return {
3029
+ walletFacade: await WalletFacade.init({
3030
+ configuration,
3031
+ provingService: () => proofServer.provingService,
3032
+ shielded: (config) => ShieldedWallet(config).restore(SerialisedWalletState.toJSON(shielded)),
3033
+ unshielded: (config) => require_watch.UnshieldedWallet(config).restore(SerialisedWalletState.toJSON(unshielded)),
3034
+ dust: (config) => DustWallet(config).restore(SerialisedWalletState.toJSON(dust))
3035
+ }),
3036
+ txHistoryStorage: restoredTxHistoryStorage,
3037
+ proofServerTransport: proofServer.transport,
3038
+ finalizeRecipe
3039
+ };
3040
+ }
3041
+ }
3042
+ const { walletKeys: { dustKeyBuffer, zswapKeyBuffer }, unshieldedKeystore } = await (0, rxjs.firstValueFrom)(keysWithAuthCancelledRecovery$(keyManager));
3043
+ const dustParameters = _midnight_ntwrk_ledger_v8.LedgerParameters.initialParameters().dust;
3044
+ const txHistoryStorage = new require_const.InMemoryTransactionHistoryStorage(WalletEntrySchema, mergeWalletEntries);
3045
+ configuration.txHistoryStorage = txHistoryStorage;
3046
+ return {
3047
+ walletFacade: await WalletFacade.init({
3048
+ configuration,
3049
+ provingService: () => proofServer.provingService,
3050
+ shielded: (config) => ShieldedWallet(config).startWithSeed(zswapKeyBuffer),
3051
+ unshielded: (config) => require_watch.UnshieldedWallet(config).startWithPublicKey(require_watch.PublicKey.fromKeyStore(unshieldedKeystore)),
3052
+ dust: (config) => DustWallet(config).startWithSeed(dustKeyBuffer, dustParameters)
3053
+ }),
3054
+ txHistoryStorage,
3055
+ proofServerTransport: proofServer.transport,
3056
+ finalizeRecipe
3057
+ };
3058
+ };
3059
+ /**
3060
+ * Creates an observable MidnightWallet from wallet instances.
3061
+ *
3062
+ * The nightVerifyingKey is obtained from the wallet state, which works
3063
+ * for both restored and new wallets.
3064
+ */
3065
+ const createAccountObservableMidnightWallet = ({ account, keyManager, walletFacade, haltPersistence, proofServerTransport, finalizeRecipe }) => {
3066
+ const { networkId } = account.blockchainSpecific;
3067
+ const state$ = walletFacade.state().pipe((0, rxjs.shareReplay)({
3068
+ bufferSize: 1,
3069
+ refCount: true
3070
+ }));
3071
+ const releasing = withReservationRelease(walletFacade);
3072
+ return state$.pipe((0, rxjs.take)(1), (0, rxjs.map)((initialState) => {
3073
+ const nightVerifyingKey = initialState.unshielded.capabilities.keys.getPublicKey(initialState.unshielded.state);
3074
+ return {
3075
+ accountId: account.accountId,
3076
+ areKeysAvailable$: keyManager.areKeysAvailable$,
3077
+ networkId,
3078
+ nightVerifyingKey,
3079
+ proofServerTransport,
3080
+ walletId: account.walletId,
3081
+ address$: state$.pipe((0, rxjs.map)(({ dust, shielded, unshielded }) => ({
3082
+ dust: MidnightDustAddress(require_dist.DustAddress.codec.encode(networkId, dust.capabilities.keys.getAddress(dust.state)).asString()),
3083
+ shielded: MidnightShieldedAddress(require_dist.ShieldedAddress.codec.encode(networkId, shielded.address).asString()),
3084
+ unshielded: MidnightUnshieldedAddress(require_dist.UnshieldedAddress.codec.encode(networkId, unshielded.address).asString())
3085
+ })), (0, rxjs.distinctUntilChanged)(require_equals.deepEquals)),
3086
+ coinsByTokenType$: state$.pipe((0, rxjs.map)(({ shielded, unshielded }) => {
3087
+ const shieldedCoins = {};
3088
+ const unshieldedCoins = {};
3089
+ for (const { coin } of shielded.totalCoins) {
3090
+ const previousCoinsList = shieldedCoins[coin.type] || [];
3091
+ shieldedCoins[coin.type] = previousCoinsList.concat({
3092
+ status: "mt_index" in coin ? "available" : "pending",
3093
+ value: require_bignum_vo.BigNumber(coin.value)
3094
+ });
3095
+ }
3096
+ const parseUnshieldedCoins = (status, coins) => {
3097
+ for (const { meta, utxo } of coins) {
3098
+ const tokenType = require_utils.toUnshieldedTokenType(utxo.type, networkId);
3099
+ unshieldedCoins[tokenType] = (unshieldedCoins[tokenType] || []).concat({
3100
+ status,
3101
+ value: require_bignum_vo.BigNumber(utxo.value),
3102
+ registeredForDustGeneration: meta.registeredForDustGeneration,
3103
+ ownerAddress: utxo.owner
3104
+ });
3105
+ }
3106
+ };
3107
+ parseUnshieldedCoins("pending", unshielded.pendingCoins);
3108
+ parseUnshieldedCoins("available", unshielded.availableCoins);
3109
+ return {
3110
+ shielded: shieldedCoins,
3111
+ unshielded: unshieldedCoins
3112
+ };
3113
+ }), (0, rxjs.distinctUntilChanged)(require_equals.deepEquals)),
3114
+ syncProgress$: state$.pipe((0, rxjs.map)(({ dust, shielded, unshielded }) => ({
3115
+ dust: computeConnectedSyncRatio(dust.state.progress.appliedIndex, dust.state.progress.highestRelevantWalletIndex, dust.state.progress.isConnected),
3116
+ shielded: computeConnectedSyncRatio(shielded.state.progress.appliedIndex, shielded.state.progress.highestRelevantWalletIndex, shielded.state.progress.isConnected),
3117
+ unshielded: computeConnectedSyncRatio(unshielded.state.progress.appliedId, unshielded.state.progress.highestTransactionId, unshielded.state.progress.isConnected),
3118
+ isStrictlyComplete: {
3119
+ dust: dust.state.progress.isStrictlyComplete(),
3120
+ shielded: shielded.state.progress.isStrictlyComplete(),
3121
+ unshielded: unshielded.state.progress.isStrictlyComplete()
3122
+ }
3123
+ })), (0, rxjs.distinctUntilChanged)(require_equals.deepEquals)),
3124
+ transactionHistory$: state$.pipe((0, rxjs.throttleTime)(500, void 0, {
3125
+ leading: true,
3126
+ trailing: true
3127
+ }), (0, rxjs.switchMap)(() => (0, rxjs.from)(walletFacade.getAllFromTxHistory())), (0, rxjs.distinctUntilChanged)(require_equals.deepEquals)),
3128
+ balanceFinalizedTransaction: (tx, { ttl, tokenKindsToBalance }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(releasing.balanceFinalizedTransaction(tx, {
3129
+ shieldedSecretKeys: zswapSecretKeys,
3130
+ dustSecretKey
3131
+ }, {
3132
+ ttl,
3133
+ tokenKindsToBalance
3134
+ })))),
3135
+ balanceUnboundTransaction: (tx, { ttl, tokenKindsToBalance }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(releasing.balanceUnboundTransaction(tx, {
3136
+ shieldedSecretKeys: zswapSecretKeys,
3137
+ dustSecretKey
3138
+ }, {
3139
+ ttl,
3140
+ tokenKindsToBalance
3141
+ })))),
3142
+ balanceUnprovenTransaction: (tx, { ttl, tokenKindsToBalance }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(walletFacade.balanceUnprovenTransaction(tx, {
3143
+ shieldedSecretKeys: zswapSecretKeys,
3144
+ dustSecretKey
3145
+ }, {
3146
+ ttl,
3147
+ tokenKindsToBalance
3148
+ })))),
3149
+ calculateTransactionFee: (tx) => (0, rxjs.from)(walletFacade.calculateTransactionFee(tx)),
3150
+ estimateTransactionFee: (tx, options) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey } }) => (0, rxjs.from)(walletFacade.estimateTransactionFee(tx, dustSecretKey, options)))),
3151
+ deregisterFromDustGeneration: (nightUtxos) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ unshieldedKeystore }) => (0, rxjs.from)(walletFacade.deregisterFromDustGeneration(nightUtxos, unshieldedKeystore.getPublicKey(), (data) => unshieldedKeystore.signData(data))))),
3152
+ getTransactionHistoryEntryByHash: (hash) => (0, rxjs.from)(walletFacade.queryTxHistoryByHash(hash)),
3153
+ finalizeRecipe: (recipe, onProgress) => (0, rxjs.defer)(async () => finalizeRecipe(walletFacade, recipe, onProgress)),
3154
+ finalizeTransaction: (recipe) => (0, rxjs.from)(walletFacade.finalizeTransaction(recipe)),
3155
+ registerNightUtxosForDustGeneration: (nightUtxos, dustAddress) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ unshieldedKeystore }) => (0, rxjs.from)(walletFacade.registerNightUtxosForDustGeneration(nightUtxos, unshieldedKeystore.getPublicKey(), (data) => unshieldedKeystore.signData(data), dustAddress)))),
3156
+ revert: (recipe) => (0, rxjs.from)(walletFacade.revert(recipe)),
3157
+ state: () => state$,
3158
+ stop: () => {
3159
+ haltPersistence();
3160
+ return (0, rxjs.from)(walletFacade.stop());
3161
+ },
3162
+ signUnprovenTransaction: (tx) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ unshieldedKeystore }) => (0, rxjs.from)(walletFacade.signUnprovenTransaction(tx, (data) => unshieldedKeystore.signData(data))))),
3163
+ signRecipe: (recipe) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ unshieldedKeystore }) => (0, rxjs.from)(walletFacade.signRecipe(recipe, (data) => unshieldedKeystore.signData(data))))),
3164
+ signData: (data) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.map)(({ unshieldedKeystore }) => ({
3165
+ signature: unshieldedKeystore.signData(data),
3166
+ verifyingKey: unshieldedKeystore.getPublicKey()
3167
+ }))),
3168
+ submitTransaction: (tx) => (0, rxjs.from)(walletFacade.submitTransaction(tx)),
3169
+ transferTransaction: (outputs, { ttl, payFees }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(releasing.transferTransaction(outputs, {
3170
+ shieldedSecretKeys: zswapSecretKeys,
3171
+ dustSecretKey
3172
+ }, {
3173
+ ttl,
3174
+ payFees
3175
+ })))),
3176
+ initSwap: (desiredInputs, desiredOutputs, { ttl, payFees }) => keyManager.keys$.pipe((0, rxjs.take)(1), (0, rxjs.switchMap)(({ walletKeys: { dustSecretKey, zswapSecretKeys } }) => (0, rxjs.from)(releasing.initSwap({
3177
+ desiredInputs,
3178
+ desiredOutputs
3179
+ }, {
3180
+ shieldedSecretKeys: zswapSecretKeys,
3181
+ dustSecretKey
3182
+ }, {
3183
+ ttl,
3184
+ payFees
3185
+ }))))
3186
+ };
3187
+ }));
3188
+ };
3189
+ /**
3190
+ * Creates and manages the lifecycle of Midnight SDK wallet instances.
3191
+ *
3192
+ * Lifecycle:
3193
+ * - Creates all 3 wallets (Unshielded, Shielded, Dust) via getAccountWalletInstance
3194
+ * - Starts UnshieldedWallet immediately (no keys needed)
3195
+ * - Starts ShieldedWallet and DustWallet once account keys become available
3196
+ * (one auth prompt; sync then runs for the wallet's lifetime, surviving
3197
+ * the key manager's idle zeroization — see the start step below)
3198
+ * - DustWallet is never stopped once started
3199
+ * (SDK limitation: stop() closes Effect runtime, breaking calculateFee)
3200
+ * - On unsubscribe: stops all wallets and clears the sync key copy
3201
+ */
3202
+ const createAndManageWallets = (props, { logger }, options) => {
3203
+ const { keyManager, account, store } = props;
3204
+ return new rxjs.Observable((subscriber) => {
3205
+ let walletFacade = null;
3206
+ let syncSecretKeys = null;
3207
+ let syncDustSecretKey = null;
3208
+ let syncStartSubscription = null;
3209
+ let persistSubscription = null;
3210
+ let isDestroyed = false;
3211
+ let isPersistenceHalted = false;
3212
+ const init = async () => {
3213
+ const { walletFacade: facade, txHistoryStorage, proofServerTransport, finalizeRecipe } = await getAccountWalletInstance(props, logger, options);
3214
+ if (isDestroyed) {
3215
+ facade.stop();
3216
+ return;
3217
+ }
3218
+ walletFacade = facade;
3219
+ await walletFacade.unshielded.start();
3220
+ syncStartSubscription = keysWithAuthCancelledRecovery$(keyManager).pipe((0, rxjs.switchMap)((keys) => {
3221
+ if (!walletFacade) return (0, rxjs.from)(Promise.resolve());
3222
+ syncSecretKeys = _midnight_ntwrk_ledger_v8.ZswapSecretKeys.fromSeed(keys.walletKeys.zswapKeyBuffer);
3223
+ syncDustSecretKey = _midnight_ntwrk_ledger_v8.DustSecretKey.fromSeed(keys.walletKeys.dustKeyBuffer);
3224
+ const facade = walletFacade;
3225
+ const syncKeys = syncSecretKeys;
3226
+ const dustSyncKey = syncDustSecretKey;
3227
+ return (0, rxjs.from)((async () => {
3228
+ const failures = [];
3229
+ try {
3230
+ await facade.shielded.start(syncKeys);
3231
+ } catch (error) {
3232
+ logger.error(`Midnight shielded wallet failed to start for account ${account.accountId}:`, error);
3233
+ failures.push(error);
3234
+ }
3235
+ try {
3236
+ await facade.dust.start(dustSyncKey);
3237
+ } catch (error) {
3238
+ logger.error(`Midnight dust wallet failed to start for account ${account.accountId}:`, error);
3239
+ failures.push(error);
3240
+ }
3241
+ if (failures.length > 0) throw failures[0];
3242
+ })());
3243
+ })).subscribe({ error: (error) => {
3244
+ logger.error(`Wallet sync start error for account ${account.accountId}:`, error);
3245
+ subscriber.error(error);
3246
+ } });
3247
+ let lastPersistedFingerprint;
3248
+ const persistOnce = async () => {
3249
+ const [dust, shielded, unshielded, txHistory] = (await (0, rxjs.firstValueFrom)((0, rxjs.zip)((0, rxjs.from)(walletFacade.dust.serializeState()), (0, rxjs.from)(walletFacade.shielded.serializeState()), (0, rxjs.from)(walletFacade.unshielded.serializeState()), (0, rxjs.from)(txHistoryStorage.serialize())))).map(SerialisedWalletState);
3250
+ const fingerprint = fingerprintOf([
3251
+ dust,
3252
+ shielded,
3253
+ unshielded,
3254
+ txHistory
3255
+ ]);
3256
+ if (fingerprint === lastPersistedFingerprint) return;
3257
+ if (isPersistenceHalted || isDestroyed) return;
3258
+ await (0, rxjs.firstValueFrom)(store.upsert({
3259
+ serializedState: {
3260
+ dust,
3261
+ shielded,
3262
+ unshielded,
3263
+ txHistory
3264
+ },
3265
+ accountId: account.accountId,
3266
+ walletId: account.walletId,
3267
+ networkId: account.blockchainSpecific.networkId
3268
+ }).pipe((0, rxjs.defaultIfEmpty)(void 0)));
3269
+ lastPersistedFingerprint = fingerprint;
3270
+ };
3271
+ persistSubscription = walletFacade.state().pipe((0, rxjs.throttleTime)(STATE_SERIALISATION_THROTTLE_TIME, void 0, {
3272
+ leading: true,
3273
+ trailing: true
3274
+ }), (0, rxjs.exhaustMap)(() => (0, rxjs.from)(persistOnce()).pipe((0, rxjs.catchError)((error) => {
3275
+ logger.error(`Failed to persist wallet state for account ${account.accountId}:`, error);
3276
+ return (0, rxjs.of)(void 0);
3277
+ })))).subscribe();
3278
+ subscriber.next({
3279
+ walletFacade,
3280
+ haltPersistence: () => {
3281
+ isPersistenceHalted = true;
3282
+ },
3283
+ proofServerTransport,
3284
+ finalizeRecipe
3285
+ });
3286
+ };
3287
+ init().catch((error) => {
3288
+ subscriber.error(error);
3289
+ });
3290
+ return () => {
3291
+ isDestroyed = true;
3292
+ syncStartSubscription?.unsubscribe();
3293
+ persistSubscription?.unsubscribe();
3294
+ if (walletFacade) walletFacade.stop().catch(() => void 0).finally(() => {
3295
+ syncSecretKeys?.clear();
3296
+ syncDustSecretKey?.clear();
3297
+ });
3298
+ };
3299
+ });
3300
+ };
3301
+ /**
3302
+ * Starts a Midnight account wallet with full lifecycle management.
3303
+ *
3304
+ * Creates SDK wallets, manages their start/stop lifecycle, and converts
3305
+ * to the MidnightWallet interface used by the rest of the application.
3306
+ */
3307
+ const createStartMidnightAccountWallet = (dependencies, options) => (props) => createAndManageWallets(props, dependencies, options).pipe((0, rxjs.switchMap)(({ walletFacade, haltPersistence, proofServerTransport, finalizeRecipe }) => createAccountObservableMidnightWallet({
3308
+ account: props.account,
3309
+ keyManager: props.keyManager,
3310
+ walletFacade,
3311
+ haltPersistence,
3312
+ proofServerTransport,
3313
+ finalizeRecipe
3314
+ })));
3315
+ /**
3316
+ * The engine's side-effect dependencies. The attested prover is the
3317
+ * loadout's: the app proves through the bundled Temenos deployment, which a
3318
+ * headless loadout does not ship.
3319
+ */
3320
+ const createMidnightSideEffectDependencies = (options = {}) => ({ runtime }, dependencies) => {
3321
+ const midnightWallets$ = require_midnight_wallet.midnightWalletsForRuntime(runtime);
3322
+ return {
3323
+ midnightWallets$,
3324
+ teeAttestationProgress$: require_send_proof_progress.teeAttestationProgress$,
3325
+ getMidnightWalletByAccountId: (accountId) => midnightWallets$.pipe((0, rxjs.take)(1), (0, rxjs.map)((wallets) => wallets[accountId]), (0, rxjs.switchMap)((wallet) => wallet ? (0, rxjs.of)(wallet) : (0, rxjs.throwError)(() => /* @__PURE__ */ new Error(`Could not load midnight wallet for account ${accountId}`)))),
3326
+ stopAllMidnightWallets: () => {
3327
+ const walletsArray = Object.values(midnightWallets$.value);
3328
+ midnightWallets$.next({});
3329
+ if (walletsArray.length === 0) return (0, rxjs.of)(void 0);
3330
+ return (0, rxjs.forkJoin)(walletsArray.map((wallet) => wallet.stop())).pipe((0, rxjs.map)(() => void 0));
3331
+ },
3332
+ stopMidnightWallet: (accountId) => {
3333
+ const wallet = midnightWallets$.value[accountId];
3334
+ if (!wallet) return (0, rxjs.of)(void 0);
3335
+ const { [accountId]: _, ...remaining } = midnightWallets$.value;
3336
+ midnightWallets$.next(remaining);
3337
+ return wallet.stop().pipe((0, rxjs.map)(() => void 0));
3338
+ },
3339
+ startMidnightAccountWallet: createStartMidnightAccountWallet(dependencies, options)
3340
+ };
3341
+ };
3342
+ //#endregion
3343
+ //#region ../../packages/module/midnight-sync/src/store/utils/activities.ts
3344
+ const toBigInt = (v) => typeof v === "bigint" ? v : BigInt(v);
3345
+ const buildTokenBalanceChangesFromUtxos = (createdUtxos, spentUtxos, networkId) => {
3346
+ const changesByToken = /* @__PURE__ */ new Map();
3347
+ for (const u of createdUtxos) {
3348
+ const tokenId = require_token_id_vo.TokenId(require_utils.toUnshieldedTokenType(u.tokenType, networkId));
3349
+ const existing = changesByToken.get(tokenId);
3350
+ const value = toBigInt(u.value);
3351
+ changesByToken.set(tokenId, {
3352
+ tokenId,
3353
+ amount: existing ? existing.amount + value : value
3354
+ });
3355
+ }
3356
+ for (const u of spentUtxos) {
3357
+ const tokenId = require_token_id_vo.TokenId(require_utils.toUnshieldedTokenType(u.tokenType, networkId));
3358
+ const existing = changesByToken.get(tokenId);
3359
+ const value = toBigInt(u.value);
3360
+ changesByToken.set(tokenId, {
3361
+ tokenId,
3362
+ amount: existing ? existing.amount - value : -value
3363
+ });
3364
+ }
3365
+ return [...changesByToken.values()].filter(({ amount }) => amount !== 0n).map(({ tokenId, amount }) => ({
3366
+ tokenId,
3367
+ amount: require_bignum_vo.BigNumber(amount)
3368
+ }));
3369
+ };
3370
+ const getAddressFromUtxos = (createdUtxos, spentUtxos) => {
3371
+ return (createdUtxos[0] ?? spentUtxos[0])?.owner ?? "";
3372
+ };
3373
+ /**
3374
+ * Whether the wallet took part in an unshielded movement in this transaction —
3375
+ * the gate for surfacing it as an activity. True for unshielded and mixed sends,
3376
+ * and for dust designation (which rotates night UTxOs into the unshielded
3377
+ * section). False for shielded-only entries: their values are encrypted and
3378
+ * unreadable, and the fee-dust they spend never lands in the unshielded section,
3379
+ * so surfacing them would only produce an empty/unknown row.
3380
+ */
3381
+ const entryHasUnshieldedActivity = (entry) => (entry.unshielded?.createdUtxos.length ?? 0) > 0 || (entry.unshielded?.spentUtxos.length ?? 0) > 0;
3382
+ const mapStatusToActivityType = (status, tokenBalanceChanges) => {
3383
+ switch (status) {
3384
+ case "SUCCESS":
3385
+ case "PARTIAL_SUCCESS": return !tokenBalanceChanges?.length || tokenBalanceChanges.some(({ amount }) => BigInt(amount) > 0n) ? require_activity_type.ActivityType.Receive : require_activity_type.ActivityType.Send;
3386
+ case "FAILURE": return require_activity_type.ActivityType.Failed;
3387
+ }
3388
+ };
3389
+ /**
3390
+ * Resolves the activity type and displayed token amounts for a transaction's
3391
+ * unshielded section. A transaction that moved unshielded value but nets to zero
3392
+ * is a self-transfer — a plain self-send, or a dust designation, which rotates
3393
+ * NIGHT back to the owner — so it is surfaced as {@link ActivityType.Self}.
3394
+ * No amount is shown: no value left the wallet, and the intended amount is not
3395
+ * recoverable (a self output is indistinguishable from change). Failures keep
3396
+ * their Failed type regardless.
3397
+ */
3398
+ const deriveUnshieldedActivity = ({ status, createdUtxos, spentUtxos, networkId }) => {
3399
+ const netChanges = buildTokenBalanceChangesFromUtxos(createdUtxos, spentUtxos, networkId);
3400
+ if (status !== "FAILURE" && netChanges.length === 0 && (createdUtxos.length > 0 || spentUtxos.length > 0)) return {
3401
+ type: require_activity_type.ActivityType.Self,
3402
+ tokenBalanceChanges: []
3403
+ };
3404
+ return {
3405
+ type: mapStatusToActivityType(status, netChanges),
3406
+ tokenBalanceChanges: netChanges
3407
+ };
3408
+ };
3409
+ const formatFee = (fees) => fees === null || fees === void 0 ? "0" : String(fees);
3410
+ //#endregion
3411
+ //#region ../../packages/module/midnight-sync/src/store/side-effects/activities.ts
3412
+ const mapTxHistoryEntryToActivity = ({ accountId, txHistoryEntry, networkId }) => {
3413
+ const { hash, timestamp, status } = txHistoryEntry;
3414
+ const { type, tokenBalanceChanges } = deriveUnshieldedActivity({
3415
+ status,
3416
+ createdUtxos: txHistoryEntry.unshielded?.createdUtxos ?? [],
3417
+ spentUtxos: txHistoryEntry.unshielded?.spentUtxos ?? [],
3418
+ networkId
3419
+ });
3420
+ return {
3421
+ accountId,
3422
+ activityId: hash,
3423
+ type,
3424
+ timestamp: require_time_vo.Timestamp(timestamp?.getTime() ?? 0),
3425
+ tokenBalanceChanges
3426
+ };
3427
+ };
3428
+ const mapTxHistoryEntryToActivityDetail = ({ accountId, txHistoryEntry, networkId }) => {
3429
+ const createdUtxos = txHistoryEntry.unshielded?.createdUtxos ?? [];
3430
+ const spentUtxos = txHistoryEntry.unshielded?.spentUtxos ?? [];
3431
+ const activity = mapTxHistoryEntryToActivity({
3432
+ accountId,
3433
+ txHistoryEntry,
3434
+ networkId
3435
+ });
3436
+ const address = getAddressFromUtxos(createdUtxos, spentUtxos);
3437
+ return {
3438
+ ...activity,
3439
+ address,
3440
+ fee: formatFee(txHistoryEntry.fees)
3441
+ };
3442
+ };
3443
+ /**
3444
+ * Whether confirmed rows with no unshielded section are shown. They carry no
3445
+ * readable value or date, so they render as amount-less "unknown" / 1970 rows;
3446
+ * hiding them is the default and the flag restores the earlier behaviour while
3447
+ * the product decision is open.
3448
+ */
3449
+ const showShieldedOnlyRows$ = (stateObservables) => stateObservables.features.selectLoadedFeatures$.pipe((0, rxjs.map)((loaded) => loaded.featureFlags.some((flag) => flag.key === require_watch.FEATURE_FLAG_MIDNIGHT_SHIELDED_ACTIVITY_ROWS)), (0, rxjs.distinctUntilChanged)());
3450
+ const updateActivities = (_, stateObservables, { actions, midnightWallets$ }) => midnightWallets$.pipe((0, rxjs.scan)((accumulator, wallets) => ({
3451
+ current: wallets,
3452
+ added: Object.values(wallets).filter((w) => !(w.accountId in accumulator.current))
3453
+ }), {
3454
+ current: {},
3455
+ added: []
3456
+ }), (0, rxjs.mergeMap)(({ added }) => added), (0, rxjs.mergeMap)((wallet) => (0, rxjs.combineLatest)([wallet.transactionHistory$, showShieldedOnlyRows$(stateObservables)]).pipe((0, rxjs.map)(([transactionHistory, showShieldedOnlyRows]) => ({
3457
+ activities: transactionHistory.filter((entry) => showShieldedOnlyRows || entryHasUnshieldedActivity(entry)).map((txHistoryEntry) => mapTxHistoryEntryToActivity({
3458
+ accountId: wallet.accountId,
3459
+ txHistoryEntry,
3460
+ networkId: wallet.networkId
3461
+ })),
3462
+ suppressedActivityIds: showShieldedOnlyRows ? [] : transactionHistory.filter((entry) => !entryHasUnshieldedActivity(entry)).map((entry) => entry.hash)
3463
+ })), (0, rxjs.mergeMap)(({ activities, suppressedActivityIds }) => [
3464
+ actions.activities.upsertActivities({
3465
+ accountId: wallet.accountId,
3466
+ activities
3467
+ }),
3468
+ ...suppressedActivityIds.length > 0 ? [actions.activities.removeActivities({
3469
+ accountId: wallet.accountId,
3470
+ activityIds: suppressedActivityIds
3471
+ })] : [],
3472
+ actions.activities.setHasLoadedOldestEntry({
3473
+ accountId: wallet.accountId,
3474
+ hasLoadedOldestEntry: true
3475
+ }),
3476
+ actions.activities.setDesiredLoadedActivitiesCount({
3477
+ accountId: wallet.accountId,
3478
+ desiredLoadedActivitiesCount: activities.length
3479
+ })
3480
+ ]), (0, rxjs.takeUntil)(midnightWallets$.pipe((0, rxjs.filter)((wallets) => !(wallet.accountId in wallets)))))));
3481
+ const loadActivityDetails = ({ activities: { loadActivityDetails$ } }, _, { actions, getMidnightWalletByAccountId, logger }) => loadActivityDetails$.pipe((0, rxjs.filter)(({ payload: { blockchainName } }) => blockchainName === "Midnight"), (0, rxjs.map)((action) => action.payload.activity), (0, rxjs.switchMap)(({ activityId, accountId }) => getMidnightWalletByAccountId(accountId).pipe((0, rxjs.switchMap)((wallet) => wallet.getTransactionHistoryEntryByHash(activityId).pipe((0, rxjs.map)((txHistoryEntry) => {
3482
+ if (!txHistoryEntry) return actions.activities.setActivityDetails({ activityDetails: void 0 });
3483
+ return actions.activities.setActivityDetails({ activityDetails: mapTxHistoryEntryToActivityDetail({
3484
+ accountId: wallet.accountId,
3485
+ txHistoryEntry,
3486
+ networkId: wallet.networkId
3487
+ }) });
3488
+ }), (0, rxjs.catchError)((error) => {
3489
+ logger.error("Failed to load Midnight activity details", error);
3490
+ return rxjs.EMPTY;
3491
+ }))), (0, rxjs.catchError)(() => rxjs.EMPTY))));
3492
+ //#endregion
3493
+ //#region ../../packages/module/midnight-sync/src/store/side-effects/proof-server-kill-switch.ts
3494
+ /** Persist the fallback when a selected provider is disabled or no longer
3495
+ * belongs to the source-controlled catalogue. Notify once per affected batch. */
3496
+ const migrateUnavailableProofServerSelection = (_, { midnightContext: { selectUnavailableProofServerNetworks$, selectNetworksConfig$, selectNetworksConfigFeatureFlagsOverrides$ } }, { actions }) => selectUnavailableProofServerNetworks$.pipe((0, rxjs.distinctUntilChanged)(lodash_isEqual.default), (0, rxjs.filter)((networkIds) => networkIds.length > 0), (0, rxjs.withLatestFrom)(selectNetworksConfig$, selectNetworksConfigFeatureFlagsOverrides$), (0, rxjs.mergeMap)(([networkIds, networksConfig, featureFlagsOverrides]) => (0, rxjs.from)([...networkIds.map((networkId) => actions.midnightContext.setUserNetworkConfigOverride({
3497
+ networkId,
3498
+ config: networksConfig[networkId],
3499
+ featureFlagsOverrides: featureFlagsOverrides[networkId] ?? {}
3500
+ })), actions.ui.showToast({
3501
+ text: "midnight.proof-server.unavailable",
3502
+ color: "neutral",
3503
+ duration: 8,
3504
+ leftIcon: {
3505
+ name: "AlertTriangle",
3506
+ size: 20
3507
+ }
3508
+ })])));
3509
+ //#endregion
3510
+ //#region ../../packages/module/midnight-sync/src/store/side-effects/resync.ts
3511
+ const withMidnightAccounts = (makeSideEffect) => (actionObservables, stateObservables, dependencies) => makeSideEffect(midnightAccounts$(stateObservables))(actionObservables, stateObservables, dependencies);
3512
+ const requestResyncWallet = withMidnightAccounts((midnightAccount$) => ({ midnightSync: { requestResync$ } }, _, { actions }) => (0, rxjs.merge)(requestResync$.pipe((0, rxjs.withLatestFrom)(midnightAccount$), (0, rxjs.switchMap)(([_, accounts]) => {
3513
+ return (0, rxjs.from)([...accounts.map(({ accountId }) => actions.sync.addSyncOperation({
3514
+ accountId,
3515
+ operation: {
3516
+ operationId: `${accountId}-midnight-sync`,
3517
+ status: "Pending",
3518
+ description: "sync.operation.midnight-resync",
3519
+ startedAt: require_time_vo.Timestamp(Date.now())
3520
+ }
3521
+ })), actions.midnightSync.resync()]);
3522
+ }))));
3523
+ const createClearWalletStateOnResync = (store) => withMidnightAccounts((midnightAccounts$) => ({ midnightSync: { resync$ } }, _, { actions, stopAllMidnightWallets, logger }) => resync$.pipe((0, rxjs.withLatestFrom)(midnightAccounts$), (0, rxjs.switchMap)(([_, midnightAccounts]) => stopAllMidnightWallets().pipe((0, rxjs.catchError)((error) => {
3524
+ logger.error("Midnight resync: stop failed", error);
3525
+ return (0, rxjs.of)(void 0);
3526
+ }), (0, rxjs.switchMap)(() => store.clear().pipe((0, rxjs.defaultIfEmpty)(void 0), (0, rxjs.catchError)((error) => {
3527
+ logger.error("Midnight resync: state wipe failed", error);
3528
+ return (0, rxjs.of)(void 0);
3529
+ }))), (0, rxjs.switchMap)(() => [...midnightAccounts.flatMap(({ accountId }) => [
3530
+ actions.addresses.resetAddresses({ accountId }),
3531
+ actions.tokens.resetAccountTokens({ accountId }),
3532
+ actions.activities.resetActivities({ accountId }),
3533
+ actions.midnightContext.resetAccountDust({ accountId })
3534
+ ]), actions.midnightSync.restartWalletWatch()])))));
3535
+ /**
3536
+ * Side-effect that triggers a Midnight wallet resync whenever the config change
3537
+ * is made with a feature flag override and the wallet is unlocked.
3538
+ */
3539
+ const resyncWalletOnConfigChangeFromFeatureFlags = withMidnightAccounts((midnightAccounts$) => (_, { appLock: { isUnlocked$ }, midnightContext: { selectCurrentNetwork$, selectNetworksConfigFeatureFlagsOverrides$ } }, { actions }) => {
3540
+ return selectNetworksConfigFeatureFlagsOverrides$.pipe((0, rxjs.withLatestFrom)(isUnlocked$), (0, rxjs.filter)(([_, isUnlocked]) => isUnlocked), (0, rxjs.switchMap)(() => selectCurrentNetwork$.pipe((0, rxjs.take)(1))), (0, rxjs.map)(({ config }) => config), (0, rxjs.distinctUntilChanged)(require_equals.deepEquals)).pipe((0, rxjs.withLatestFrom)(midnightAccounts$), (0, rxjs.switchMap)(([_, midnightAccounts]) => (0, rxjs.from)([...midnightAccounts.map(({ accountId }) => actions.sync.addSyncOperation({
3541
+ accountId,
3542
+ operation: {
3543
+ operationId: `${accountId}-midnight-sync`,
3544
+ status: "Pending",
3545
+ description: "sync.operation.midnight-resync",
3546
+ startedAt: require_time_vo.Timestamp(Date.now())
3547
+ }
3548
+ })), actions.midnightSync.resync()])));
3549
+ });
3550
+ const createDeleteWalletSideEffect = (storage) => ({ wallets: { removeWallet$ } }, { wallets: { selectAll$ } }, { stopMidnightWallet, actions, logger }) => removeWallet$.pipe((0, rxjs.withLatestFrom)(selectAll$.pipe((0, rxjs.map)((wallets) => wallets.filter(require_utils.hasMidnightAccount)))), (0, rxjs.switchMap)(([{ payload }, midnightWallets]) => {
3551
+ const walletId = typeof payload === "string" ? payload : payload.walletId;
3552
+ const targetWallet = midnightWallets.find((w) => w.walletId === walletId);
3553
+ if (!targetWallet) return rxjs.EMPTY;
3554
+ const allMidnightAccounts = targetWallet.accounts.filter(require_utils.isInMemoryMidnightAccount);
3555
+ return (allMidnightAccounts.length > 0 ? (0, rxjs.forkJoin)(allMidnightAccounts.map(({ accountId }) => stopMidnightWallet(accountId))) : (0, rxjs.of)([])).pipe((0, rxjs.switchMap)(() => storage.removeWhere((wallet) => wallet.walletId === walletId).pipe((0, rxjs.defaultIfEmpty)(void 0), (0, rxjs.catchError)((error) => {
3556
+ logger.error("Midnight delete wallet: state wipe failed", error);
3557
+ return (0, rxjs.of)(void 0);
3558
+ }))), (0, rxjs.mergeMap)(() => allMidnightAccounts.flatMap(({ accountId }) => [
3559
+ actions.addresses.resetAddresses({ accountId }),
3560
+ actions.tokens.resetAccountTokens({ accountId }),
3561
+ actions.activities.resetActivities({ accountId })
3562
+ ])));
3563
+ }));
3564
+ /**
3565
+ * Stops one Midnight account's wallet, wipes that account's persisted SDK
3566
+ * state, then emits the actions that clear every redux cache the wiped state
3567
+ * fed. Scoped to a single account, unlike `createClearWalletStateOnResync`,
3568
+ * which wipes the whole chain.
3569
+ *
3570
+ * A step that errors or completes without emitting is handed to
3571
+ * `onStepFailure`: return an observable that emits to carry on with the next
3572
+ * step, or one that errors to abort the reset with that error.
3573
+ */
3574
+ const stopAndWipeAccountState$ = ({ accountId, actions, store, stop$, onStepFailure }) => stop$.pipe((0, rxjs.take)(1), (0, rxjs.throwIfEmpty)(() => /* @__PURE__ */ new Error("Midnight account stop did not acknowledge completion")), (0, rxjs.catchError)((error) => onStepFailure("stop", error)), (0, rxjs.switchMap)(() => store.removeWhere((wallet) => wallet?.accountId === accountId).pipe((0, rxjs.throwIfEmpty)(() => /* @__PURE__ */ new Error("Midnight account storage wipe did not acknowledge completion")), (0, rxjs.catchError)((error) => onStepFailure("wipe", error)))), (0, rxjs.mergeMap)(() => [
3575
+ actions.addresses.resetAddresses({ accountId }),
3576
+ actions.tokens.resetAccountTokens({ accountId }),
3577
+ actions.activities.resetActivities({ accountId }),
3578
+ actions.midnightContext.resetAccountDust({ accountId }),
3579
+ actions.sync.resetAccountSyncStatus({ accountId })
3580
+ ]));
3581
+ /**
3582
+ * The extension's per-account "reset sync state": stops and wipes the account,
3583
+ * then reloads the app so every engine restarts from empty state. Stop and wipe
3584
+ * failures are logged and the reset carries on, because the reload is what
3585
+ * recovers the account.
3586
+ *
3587
+ * The reload is emitted LAST, after the storage write settles: sequencing it
3588
+ * inside this chain (rather than firing it from a separate UI tap) is what stops
3589
+ * a hard reload from preempting the wipe and leaving the old SDK document to
3590
+ * restore from.
3591
+ */
3592
+ const createResetSyncStateSideEffect = (store) => withMidnightAccounts((midnightAccounts$) => ({ midnightContext: { resetSyncState$ } }, _, { actions, stopMidnightWallet, logger }) => resetSyncState$.pipe((0, rxjs.withLatestFrom)(midnightAccounts$), (0, rxjs.switchMap)(([{ payload }, midnightAccounts]) => {
3593
+ const account = midnightAccounts.find(({ accountId }) => accountId === payload.accountId);
3594
+ if (!account) return rxjs.EMPTY;
3595
+ const { accountId } = account;
3596
+ return (0, rxjs.concat)(stopAndWipeAccountState$({
3597
+ accountId,
3598
+ actions,
3599
+ store,
3600
+ stop$: stopMidnightWallet(accountId),
3601
+ onStepFailure: (step, error) => {
3602
+ logger.error(`Midnight reset sync state: ${step} failed`, error);
3603
+ return (0, rxjs.of)(void 0);
3604
+ }
3605
+ }), (0, rxjs.of)(actions.app.reloadApplication()));
3606
+ })));
3607
+ /**
3608
+ * The headless per-account "reset sync state": stops and wipes the account,
3609
+ * then restarts that account's watcher in place, since a headless runtime has
3610
+ * no application to reload. The account's sync operation reads Pending while
3611
+ * the reset runs and Failed if a stop or wipe fails, so the caller can observe
3612
+ * the outcome and retry.
3613
+ */
3614
+ const createHeadlessResetSyncStateSideEffect = (store) => withMidnightAccounts((midnightAccounts$) => ({ midnightContext: { resetSyncState$ } }, _, { actions, stopMidnightWallet, logger }) => resetSyncState$.pipe((0, rxjs.withLatestFrom)(midnightAccounts$), (0, rxjs.groupBy)(([{ payload }]) => payload.accountId), (0, rxjs.mergeMap)((requests$) => requests$.pipe((0, rxjs.exhaustMap)(([{ payload }, midnightAccounts]) => {
3615
+ const account = midnightAccounts.find(({ accountId }) => accountId === payload.accountId);
3616
+ if (!account) return rxjs.EMPTY;
3617
+ const { accountId } = account;
3618
+ const pendingOperation = () => actions.sync.addSyncOperation({
3619
+ accountId,
3620
+ operation: {
3621
+ operationId: `${accountId}-midnight-sync`,
3622
+ status: "Pending",
3623
+ description: "sync.operation.midnight-resync",
3624
+ startedAt: require_time_vo.Timestamp(Date.now())
3625
+ }
3626
+ });
3627
+ const stop$ = (0, rxjs.merge)((0, rxjs.of)(void 0), requests$).pipe((0, rxjs.switchMap)(() => (0, rxjs.defer)(() => stopMidnightWallet(accountId)).pipe((0, rxjs.throwIfEmpty)(() => /* @__PURE__ */ new Error("Midnight account stop did not acknowledge completion")))));
3628
+ return (0, rxjs.concat)((0, rxjs.of)(pendingOperation()), stopAndWipeAccountState$({
3629
+ accountId,
3630
+ actions,
3631
+ store,
3632
+ stop$,
3633
+ onStepFailure: (step, error) => {
3634
+ logger.error(`Midnight reset sync state: ${step} failed`, error);
3635
+ return (0, rxjs.throwError)(() => error);
3636
+ }
3637
+ }), (0, rxjs.defer)(() => (0, rxjs.of)(pendingOperation(), actions.midnightSync.restartAccountWatch({ accountId })))).pipe((0, rxjs.catchError)((error) => {
3638
+ logger.error("Midnight account resync failed", error);
3639
+ const failedAt = require_time_vo.Timestamp(Date.now());
3640
+ return (0, rxjs.of)(actions.sync.addSyncOperation({
3641
+ accountId,
3642
+ operation: {
3643
+ operationId: `${accountId}-midnight-sync`,
3644
+ status: "Failed",
3645
+ description: "sync.operation.midnight-resync",
3646
+ error: "sync.error.midnight-sync-failed",
3647
+ startedAt: failedAt,
3648
+ failedAt
3649
+ }
3650
+ }));
3651
+ }));
3652
+ })))));
3653
+ //#endregion
3654
+ //#region ../../packages/module/midnight-sync/src/store/side-effects/sync-failure.ts
3655
+ /**
3656
+ * Dismiss a Midnight account's sync failure once its own sync recovers.
3657
+ *
3658
+ * The `completeSyncOperation` for `${accountId}-midnight-sync` is the
3659
+ * "recovered" signal, whichever route got there — transparent retry, the
3660
+ * failure's tap-to-retry `restartWalletWatch`, or the resubscription `whileActive`
3661
+ * performs on unlock.
3662
+ *
3663
+ * Keyed per-account, so no lookup is needed: a completion for a sibling Midnight
3664
+ * account (or a Cardano/Bitcoin one) maps to a different, non-existent
3665
+ * MidnightSyncFailureId and no-ops, leaving a still-broken account's failure in
3666
+ * place until its OWN sync completes.
3667
+ */
3668
+ const autoDismissMidnightSyncFailureOnSyncSuccess = ({ sync: { completeSyncOperation$ } }, { failures: { selectFailureById$ } }) => completeSyncOperation$.pipe((0, rxjs.map)(({ payload }) => require_watch.MidnightSyncFailureId(payload.accountId)), require_auto_dismiss_failure_on_success.autoDismissFailureOnSuccess(selectFailureById$));
3669
+ /**
3670
+ * On resume, clear the sync failure for every Midnight account.
3671
+ *
3672
+ * Complements the per-account recovery dismissal above by clearing a stale error
3673
+ * immediately, rather than leaving it on screen for the length of the first sync
3674
+ * after unlock. No restart is dispatched: `watchMidnightAccounts` ends its pipe
3675
+ * with `whileActive`, so resuming already resubscribes every account watcher.
3676
+ * Accounts with no failure are a no-op.
3677
+ */
3678
+ const autoDismissMidnightSyncFailureOnResume = (_, { wallets: { selectAll$ }, failures: { selectFailureById$ } }, { walletResumed$ }) => walletResumed$.pipe((0, rxjs.withLatestFrom)(selectAll$), (0, rxjs.mergeMap)(([, wallets]) => (0, rxjs.from)(wallets.flatMap((wallet) => wallet.accounts).filter(require_utils.isInMemoryMidnightAccount).map((account) => require_watch.MidnightSyncFailureId(account.accountId)))), require_auto_dismiss_failure_on_success.autoDismissFailureOnSuccess(selectFailureById$));
3679
+ //#endregion
3680
+ //#region ../../packages/module/midnight-sync/src/store/side-effects/tee-attestation-progress.ts
3681
+ /**
3682
+ * Forwards attested-proving progress from the dependency-level stream into
3683
+ * redux, where the send-flow checklist UI reads it. Pure mapping — the
3684
+ * events originate inside the proving service (ADR 19).
3685
+ */
3686
+ const watchTeeAttestationProgress = (_actionObservables, _stateObservables, { actions, teeAttestationProgress$ }) => teeAttestationProgress$.pipe((0, rxjs.map)((event) => event.type === "begin" ? actions.midnightContext.teeAttestationProgressStarted(event) : actions.midnightContext.teeAttestationProgressUpdated(event)));
3687
+ /**
3688
+ * Clears the previous run's checklist as soon as a new Midnight transaction
3689
+ * starts building, so a redone send never opens the
3690
+ * processing screen with stale step results. The attested proving service's
3691
+ * `reset` then rebuilds the pending checklist when verification actually
3692
+ * begins. The signer owns confirmation resets. Submit must not clear the
3693
+ * completed checklist while the transaction is being submitted.
3694
+ */
3695
+ const clearTeeAttestationProgressOnNewTx = ({ txExecutor: { txPhaseRequested$ } }, _stateObservables, { actions }) => txPhaseRequested$.pipe((0, rxjs.filter)(({ payload: { config } }) => config.params.blockchainName === "Midnight" && config.type === "buildTx"), (0, rxjs.map)(() => actions.midnightContext.teeAttestationProgressCleared()));
3696
+ //#endregion
3697
+ //#region ../../packages/module/midnight-sync/src/store/side-effects/index.ts
3698
+ /**
3699
+ * The engine's side effects plus the ones a loadout adds over the same
3700
+ * persisted wallet-state storage. The engine set reads only the contracts
3701
+ * the engine itself depends on; a loadout decides what else it can run.
3702
+ */
3703
+ const createInitializeSideEffects = (loadoutSideEffects) => () => [(actionObservables, stateObservables, dependencies) => {
3704
+ const midnightStateStorage = dependencies.createCollectionStorage({
3705
+ collectionId: "midnightWalletState",
3706
+ computeDocId: (wallet) => String(wallet.accountId)
3707
+ });
3708
+ return (0, rxjs.merge)(...[
3709
+ updateActivities,
3710
+ loadActivityDetails,
3711
+ createDeleteWalletSideEffect(midnightStateStorage),
3712
+ createClearWalletStateOnResync(midnightStateStorage),
3713
+ requestResyncWallet,
3714
+ autoDismissMidnightSyncFailureOnResume,
3715
+ autoDismissMidnightSyncFailureOnSyncSuccess,
3716
+ require_watch.watchMidnightAccounts(midnightStateStorage, require_watch.watchMidnightAccount),
3717
+ ...loadoutSideEffects(midnightStateStorage)
3718
+ ].map((sideEffect) => sideEffect(actionObservables, stateObservables, dependencies)));
3719
+ }];
3720
+ createInitializeSideEffects((storage) => [
3721
+ createResetSyncStateSideEffect(storage),
3722
+ resyncWalletOnConfigChangeFromFeatureFlags,
3723
+ migrateUnavailableProofServerSelection,
3724
+ watchTeeAttestationProgress,
3725
+ clearTeeAttestationProgressOnNewTx
3726
+ ]);
3727
+ //#endregion
3728
+ //#region ../../packages/module/midnight-sync/src/store/side-effects/network-config.ts
3729
+ /**
3730
+ * Applies a loadout's supported networks and default proof servers right
3731
+ * after the first action the store handles, which redux-persist dispatches
3732
+ * while the store is created. Both therefore hold before the store is handed
3733
+ * out and before any side effect starts: a side effect would land a tick
3734
+ * later, and a network selected in between would be checked against the
3735
+ * contract's full list.
3736
+ */
3737
+ const createApplyNetworkDefaultsMiddleware = ({ supportedNetworkIds, defaultProofServers }) => {
3738
+ const { setDefaultProofServers, setSupportedNetworksIds } = require_slice.midnightContextActions.midnightContext;
3739
+ return (store) => (next) => {
3740
+ let pending = [...supportedNetworkIds ? [setSupportedNetworksIds(supportedNetworkIds)] : [], ...defaultProofServers ? [setDefaultProofServers(defaultProofServers)] : []];
3741
+ return (action) => {
3742
+ const result = next(action);
3743
+ const defaults = pending;
3744
+ pending = [];
3745
+ for (const defaultAction of defaults) store.dispatch(defaultAction);
3746
+ return result;
3747
+ };
3748
+ };
3749
+ };
3750
+ /**
3751
+ * Applies a loadout's endpoint choices as user overrides on startup, so they
3752
+ * take precedence over the contract defaults and the feature-flag values
3753
+ * without a settings UI to enter them through.
3754
+ */
3755
+ const createApplyNetworkConfigOverrides = (overrides) => (_, { midnightContext: { selectNetworksConfig$, selectNetworksConfigFeatureFlagsOverrides$ } }, { actions }) => (0, rxjs.zip)(selectNetworksConfig$.pipe((0, rxjs.take)(1)), selectNetworksConfigFeatureFlagsOverrides$.pipe((0, rxjs.take)(1))).pipe((0, rxjs.mergeMap)(([networksConfig, featureFlagsOverrides]) => Object.entries(overrides).map(([networkId, override]) => actions.midnightContext.setUserNetworkConfigOverride({
3756
+ networkId,
3757
+ config: {
3758
+ ...networksConfig[networkId],
3759
+ ...override
3760
+ },
3761
+ featureFlagsOverrides: featureFlagsOverrides[networkId]
3762
+ }))));
3763
+ //#endregion
3764
+ //#region ../../packages/module/midnight-sync/src/store/sdk-init.ts
3765
+ const assertDefaultTestnetConfigured = (config) => {
3766
+ const networkId = config?.defaultMidnightTestnetNetworkId;
3767
+ if (!networkId || !require_const.MidnightSDKTestNetworkId.includes(networkId)) throw new Error(`createLaceWallet needs config.defaultMidnightTestnetNetworkId, the Midnight testnet a wallet starts on: one of ${require_const.MidnightSDKTestNetworkId.join(", ")}; got ${String(networkId)}`);
3768
+ };
3769
+ const createSdkStoreInit = ({ auth, batchUpdates, createAttestedProver, networks = {}, supportedNetworkIds, defaultProofServers }) => {
3770
+ const initializeSideEffects = createInitializeSideEffects((storage) => [
3771
+ registerMidnightBlockchainNetworks,
3772
+ createApplyNetworkConfigOverrides(networks),
3773
+ createHeadlessResetSyncStateSideEffect(storage)
3774
+ ]);
3775
+ const initializeDependencies = createMidnightSideEffectDependencies({
3776
+ batchUpdates,
3777
+ createAttestedProver
3778
+ });
3779
+ return (props, dependencies) => {
3780
+ assertDefaultTestnetConfigured(props.runtime.config);
3781
+ return {
3782
+ middleware: [createApplyNetworkDefaultsMiddleware({
3783
+ supportedNetworkIds,
3784
+ defaultProofServers
3785
+ })],
3786
+ sideEffects: initializeSideEffects(props, dependencies),
3787
+ sideEffectDependencies: {
3788
+ ...initializeDependencies(props, dependencies),
3789
+ ...auth
3790
+ }
3791
+ };
3792
+ };
3793
+ };
3794
+ //#endregion
3795
+ exports.createSdkStoreInit = createSdkStoreInit;