@laceio/sdk 0.1.1 → 0.1.2-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 (388) hide show
  1. package/dist/{TransactionBuilder-DrB3NVTi.cjs → TransactionBuilder-CCjOn7NA.cjs} +42 -0
  2. package/dist/{TransactionBuilder-V6aLx4SV.js → TransactionBuilder-CIzdw18M.js} +1 -1
  3. package/dist/{_polyfill-buffer-patch-BnPVerlG.cjs → _polyfill-buffer-patch-CM8X7JiY.cjs} +21 -2
  4. package/dist/_polyfill-buffer-patch-yNxN4d5E.js +1467 -0
  5. package/dist/_web-crypto-random-bytes-Bo-GTcRS.js +197 -0
  6. package/dist/acc-module-4iIUv6My.cjs +27654 -0
  7. package/dist/acc-module-Cmj8EsIb.js +27624 -0
  8. package/dist/account-BOQruszJ.js +6 -0
  9. package/dist/account-BUOj4pYJ.cjs +11 -0
  10. package/dist/account-call-7wnopBq0.cjs +5 -0
  11. package/dist/account-call-B9d_2Xwi.js +4 -0
  12. package/dist/account-call-Bd4Rpbvt.cjs +323 -0
  13. package/dist/account-call-C3CkDqEC.js +276 -0
  14. package/dist/account-guards-BtjTGxDZ.cjs +42 -0
  15. package/dist/account-guards-D9Lu5T3W.js +36 -0
  16. package/dist/account-tokens-DvkOFVON.js +16 -0
  17. package/dist/account-tokens-nwcvwLu4.cjs +21 -0
  18. package/dist/{activity-type.stable-BJEfeLxL.cjs → activity-type-Ch6ljxBy.cjs} +2 -1
  19. package/dist/{activity-type.stable-C76_hWd7.js → activity-type-GsJGWs-3.js} +2 -1
  20. package/dist/address-B9ntKL8K.js +13761 -0
  21. package/dist/address-BXp-mY8H.cjs +11270 -0
  22. package/dist/{address-book-address-validator-DIUolI-s.js → address-book-address-validator-0J9XAADH.js} +2 -2
  23. package/dist/address-book-address-validator-DK0dnsRS.cjs +41 -0
  24. package/dist/address-book-address-validator-Di_ywo8M.js +39 -0
  25. package/dist/{address-book-address-validator-DNwQGlOB.cjs → address-book-address-validator-Dte_YQ2L.cjs} +2 -2
  26. package/dist/artefact-loader-BWWYAD7E.cjs +183 -0
  27. package/dist/artefact-loader-Dik4HIfv.js +160 -0
  28. package/dist/auto-dismiss-failure-on-success-C-qoJuid.cjs +37 -0
  29. package/dist/auto-dismiss-failure-on-success-s8MGDEIu.js +31 -0
  30. package/dist/bip32-D6wd_QMn.cjs +3851 -0
  31. package/dist/bitcoin-data-provider-BYPSmuZS.js +21 -0
  32. package/dist/bitcoin-data-provider-w1oEDSU3.cjs +26 -0
  33. package/dist/bitcoin.cjs +45 -0
  34. package/dist/bitcoin.d.ts +29906 -1
  35. package/dist/bitcoin.js +20 -0
  36. package/dist/{blockfrost-tx-submit-provider-DPTrapz-.js → blockfrost-tx-submit-provider-CBWQ0wK9.js} +5 -157
  37. package/dist/{blockfrost-tx-submit-provider-BAIzV5o3.cjs → blockfrost-tx-submit-provider-CLNQ5ycR.cjs} +3 -167
  38. package/dist/bn-d3nSOIf7.cjs +2553 -0
  39. package/dist/browser-B1eMbDwh.js +7468 -0
  40. package/dist/bytes.vo-BB7_4JK6.js +23 -0
  41. package/dist/bytes.vo-BNRquqaO.cjs +34 -0
  42. package/dist/cardano-DfPwhwm-.js +3 -0
  43. package/dist/{cardano-network-id.vo-DSxrFk9S.cjs → cardano-network-id.vo-BEDPn6Li.cjs} +1 -1
  44. package/dist/{cardano-network-id.vo-CK1tNQDg.js → cardano-network-id.vo-Cfpvbod9.js} +1 -1
  45. package/dist/cardano.cjs +22 -18
  46. package/dist/cardano.d.ts +16956 -1716
  47. package/dist/cardano.js +16 -11
  48. package/dist/client-DXBLHk7K.cjs +808 -0
  49. package/dist/codecs-Cswkg7Tm.cjs +4051 -0
  50. package/dist/codecs-Dc1Krpbt.js +3903 -0
  51. package/dist/{const-C84qHkjp.js → const-BJfIK_G-.js} +4 -4
  52. package/dist/const-BhYOdznB.cjs +42 -0
  53. package/dist/const-BsnjG2_Q.cjs +32071 -0
  54. package/dist/const-CUnCl5U0.js +13 -0
  55. package/dist/{const-DXk2tFyv.js → const-CjmfjBP3.js} +1 -1
  56. package/dist/{const-BDEg2Trq.cjs → const-D-eZIS4n.cjs} +4 -4
  57. package/dist/const-D0CbQlo4.js +154 -0
  58. package/dist/{const-BY8B3_0_.cjs → const-iwzZEE_w.cjs} +1 -1
  59. package/dist/contract-1R86jhSw.js +171 -0
  60. package/dist/contract-MKLzYVkW.cjs +189 -0
  61. package/dist/create-add-accounts-Brqk84vF.js +102 -0
  62. package/dist/create-add-accounts-DzXIh7Ot.cjs +114 -0
  63. package/dist/{delegation-tx-builder-CRpLP6jH.cjs → delegation-tx-builder-CCjiakoy.cjs} +6 -6
  64. package/dist/{delegation-tx-builder-CGVqlaFE.js → delegation-tx-builder-DZFjHDS8.js} +5 -5
  65. package/dist/{deregistration-tx-builder-B-CrUyX6.js → deregistration-tx-builder-Bf6xAYp4.js} +5 -5
  66. package/dist/{deregistration-tx-builder-DZGwB4cz.cjs → deregistration-tx-builder-CQP35yex.cjs} +6 -6
  67. package/dist/device-commitment-hex.vo-5wFtQvDS.js +26 -0
  68. package/dist/device-commitment-hex.vo-CT3RmAug.cjs +31 -0
  69. package/dist/device-readers-CUHYoYOH.js +145 -0
  70. package/dist/device-readers-CdxS2btd.cjs +168 -0
  71. package/dist/device-readers-D_JZeNL2.cjs +8 -0
  72. package/dist/device-readers-DwSNCGPP.js +4 -0
  73. package/dist/dist-BMi5ZjEq.cjs +43175 -0
  74. package/dist/dist-BtIq4XFn.cjs +535 -0
  75. package/dist/dist-C3SHC_Ho.cjs +1394 -0
  76. package/dist/dist-CykEjYEX.cjs +3814 -0
  77. package/dist/dist-Dcsxh3be.cjs +3452 -0
  78. package/dist/dist-DqJfSlTd.cjs +4413 -0
  79. package/dist/dist-nTZ70qj7.cjs +1306 -0
  80. package/dist/{earn-rewards-tx-builder-BDbTDZmD.js → earn-rewards-tx-builder-Bsga3yFb.js} +5 -5
  81. package/dist/{earn-rewards-tx-builder-D5sUT5v8.cjs → earn-rewards-tx-builder-GuxofYns.cjs} +6 -6
  82. package/dist/enc-key-circuits-B7BjgUL9.js +13 -0
  83. package/dist/enc-key-circuits-BLrZrBVI.cjs +24 -0
  84. package/dist/english-Byb9M0E_.cjs +2057 -0
  85. package/dist/envelopes-BGoO_v8m.js +1621 -0
  86. package/dist/envelopes-CH25R-DN.cjs +1722 -0
  87. package/dist/errors-BIftM8ZN.cjs +688 -0
  88. package/dist/errors-DSq5wUwt.js +466 -0
  89. package/dist/esm-HBSUQw3w.js +384 -0
  90. package/dist/esm-LZuaZjMf.cjs +389 -0
  91. package/dist/experimental.cjs +7349 -0
  92. package/dist/experimental.d.ts +86273 -0
  93. package/dist/experimental.js +7184 -0
  94. package/dist/gated-call-CDCVZIK-.cjs +5 -0
  95. package/dist/gated-call-D-tT7P_t.js +722 -0
  96. package/dist/gated-call-D_VT2quk.js +4 -0
  97. package/dist/gated-call-DgJm1Mi_.cjs +787 -0
  98. package/dist/grant-circuits-DswmW3nI.cjs +71 -0
  99. package/dist/grant-circuits-Jxb5y1HW.js +42 -0
  100. package/dist/grant-rules-By07_eDi.js +6824 -0
  101. package/dist/grant-rules-BzVTWXS7.cjs +7099 -0
  102. package/dist/grant-spend-B3Md9L0n.js +215 -0
  103. package/dist/grant-spend-oWmzRsjH.cjs +217 -0
  104. package/dist/grant-status-B2y49iIu.js +2688 -0
  105. package/dist/grant-status-DOr3t_u8.cjs +2820 -0
  106. package/dist/grants-2BZ-qEVQ.js +5 -0
  107. package/dist/grants-BPoLSiMt.cjs +18 -0
  108. package/dist/grants-BoI5uwSF.cjs +272 -0
  109. package/dist/grants-CtofFu-e.js +213 -0
  110. package/dist/{group-cardano-addresses-by-account-B533oVXR.cjs → group-cardano-addresses-by-account-Bp0g4wEY.cjs} +3 -39
  111. package/dist/{group-cardano-addresses-by-account-RHKoEskR.js → group-cardano-addresses-by-account-SR8MMrZf.js} +5 -35
  112. package/dist/{guarded-transaction-signer-Bxl6_XNd.cjs → guarded-transaction-signer-MFpPg98D.cjs} +17 -18
  113. package/dist/{guarded-transaction-signer-CpKLj8Kp.js → guarded-transaction-signer-P6Rp1faj.js} +8 -15
  114. package/dist/hex-D9ITYbwt.cjs +263 -0
  115. package/dist/hex-mkXcV3pN.js +191 -0
  116. package/dist/http-client-B3N-TMxu.cjs +167 -0
  117. package/dist/http-client-TRlhDZGh.js +155 -0
  118. package/dist/identity-BMLuufva.cjs +263 -0
  119. package/dist/identity-DII6f-h7.js +233 -0
  120. package/dist/in-memory-wallet-integration-B2xzxORj.cjs +20741 -0
  121. package/dist/in-memory-wallet-integration-CBRiPjLO.js +130 -0
  122. package/dist/in-memory-wallet-integration-CULUB5Tf.cjs +240 -0
  123. package/dist/{in-memory-wallet-integration-D-qn65Kx.js → in-memory-wallet-integration-ChIOirMW.js} +5 -2
  124. package/dist/{in-memory-wallet-integration-Croiuopx.js → in-memory-wallet-integration-CljprQQV.js} +7 -104
  125. package/dist/{in-memory-wallet-integration-DVh9sRXa.cjs → in-memory-wallet-integration-Cm6P8sk6.cjs} +3 -2
  126. package/dist/in-memory-wallet-integration-TM9bBphA.js +20738 -0
  127. package/dist/{in-memory-wallet-integration-CnLYeX4-.cjs → in-memory-wallet-integration-t9I00R_V.cjs} +17 -108
  128. package/dist/index.cjs +84 -47
  129. package/dist/index.d.ts +37496 -10033
  130. package/dist/index.js +52 -24
  131. package/dist/{init-CLHuAMB-.js → init-0zzs9aqU.js} +4 -4
  132. package/dist/{init-U8c9yHYx.cjs → init-5KcGcBb5.cjs} +1 -1
  133. package/dist/init-8v_n8boO.js +1177 -0
  134. package/dist/{init-CigestoM.js → init-B3-1ghyx.js} +2 -2
  135. package/dist/init-B8U3ABhS.cjs +107 -0
  136. package/dist/init-BJn-8_hf.js +141 -0
  137. package/dist/init-BPU3j8sT.cjs +6 -0
  138. package/dist/init-BRzH6xu-2.cjs +2797 -0
  139. package/dist/init-BmzfDaKL.js +1142 -0
  140. package/dist/{init-C-jErzp5.cjs → init-BopV9ed4.cjs} +2 -2
  141. package/dist/init-BpHTq2R5.js +105 -0
  142. package/dist/init-BpSITBfF.js +39 -0
  143. package/dist/{init-DX4WyB0R.cjs → init-BrdVzxei.cjs} +3 -3
  144. package/dist/{init-LfyMo-sS.cjs → init-BwkU0ruo.cjs} +2 -2
  145. package/dist/{init-CB__aLD7.cjs → init-C-G32J12.cjs} +2 -2
  146. package/dist/init-C00gw1zi.js +422 -0
  147. package/dist/{init-TkPq_Ny_.js → init-C2RgrfZe.js} +1 -1
  148. package/dist/{init-DcYY6zMD.js → init-C8URA2OX.js} +1 -1
  149. package/dist/init-CDkRynJa.js +2796 -0
  150. package/dist/{init-Cg9XdAru.js → init-CNM5m7M2.js} +4 -4
  151. package/dist/init-CR7BfztQ.cjs +18 -0
  152. package/dist/{init-CSHwHnfg.cjs → init-CSDpdu0Q.cjs} +2 -2
  153. package/dist/{init-aJHl-7AO.js → init-CX0AMQUn.js} +2 -2
  154. package/dist/{init-FMGDET-9.js → init-CfTbSEKy.js} +259 -60
  155. package/dist/{init-CR6tpw1B.js → init-Cigr_tKx.js} +47 -43
  156. package/dist/init-CuW7rHNA.js +3584 -0
  157. package/dist/{init-CFYsq82V.js → init-CyAY4Lzl.js} +1 -1
  158. package/dist/init-Cz0rz5fU.cjs +3585 -0
  159. package/dist/{init-BKhH6mVR.cjs → init-D6BxBs7e.cjs} +1 -1
  160. package/dist/init-D8OeObDF.cjs +1141 -0
  161. package/dist/init-D9g1HXYf.cjs +40 -0
  162. package/dist/{init-CNLGJJRx.js → init-DA7zmptx.js} +1 -1
  163. package/dist/{init-DkIc5nqF.cjs → init-DFMiP2ZH.cjs} +1 -1
  164. package/dist/{init-zSzCjoor.js → init-DFjT8YvT.js} +4 -4
  165. package/dist/init-DGjXwWs2.cjs +143 -0
  166. package/dist/init-DHrCbpkW.cjs +121 -0
  167. package/dist/{init-B64zCLxG.cjs → init-DUF4ar8P.cjs} +4 -4
  168. package/dist/init-DlqJuHhl.js +119 -0
  169. package/dist/{init-y2Ra0vZP.js → init-Dnsv155v.js} +3 -3
  170. package/dist/init-DrRdf5sZ.cjs +1176 -0
  171. package/dist/init-DuYENxci.js +17 -0
  172. package/dist/{init-D6DBUsD3.cjs → init-Dv3zKj0r.cjs} +4 -4
  173. package/dist/{init-BtzMZ7Pk.cjs → init-Dy-05ktr.cjs} +1 -1
  174. package/dist/{init-BsCBAGWf.cjs → init-EP0CUWNK.cjs} +2 -2
  175. package/dist/{init-BJVU54pI.cjs → init-EhzD7a8i.cjs} +1 -1
  176. package/dist/{init-w9GEs73W.js → init-Fw89ZmrR.js} +2 -2
  177. package/dist/init-GsT2AEa4.cjs +424 -0
  178. package/dist/{init-Rxohwpmu.js → init-NCjgwCZy.js} +2 -2
  179. package/dist/{init-DxUHsN53.cjs → init-NdhG_VrF.cjs} +6 -6
  180. package/dist/{init-DDdhguVC.js → init-SZ01tARX2.js} +2 -2
  181. package/dist/{init-BAJJzBza.js → init-Y3mkB4XS.js} +2 -2
  182. package/dist/init-c4l6r-o-.js +5 -0
  183. package/dist/{init-Dku4b2lG.js → init-kEfUTuG2.js} +1 -1
  184. package/dist/{init-C7IeJwQR.cjs → init-lzHt4Cli.cjs} +256 -59
  185. package/dist/{init-anYu6XB7.cjs → init-rmt7-fQE.cjs} +2 -2
  186. package/dist/{init-C4Bkib9u.cjs → init-zU-_9Gsp.cjs} +67 -65
  187. package/dist/{is-retriable-error-BU0e3hVI.js → is-retriable-error-BUiVJDwH.js} +1 -1
  188. package/dist/{is-retriable-error-CeeuHqDa.cjs → is-retriable-error-Dpt860if.cjs} +1 -1
  189. package/dist/jubjub-authoriser-D7zDXu3V.js +86 -0
  190. package/dist/jubjub-authoriser-Dgu6o3Sv.cjs +87 -0
  191. package/dist/key-source-5oUBFiC7.cjs +583 -0
  192. package/dist/key-source-B08HukZg.js +2550 -0
  193. package/dist/keyDerivation-D3k9XyHg.js +4077 -0
  194. package/dist/keyDerivation-u0nBA93T.cjs +274 -0
  195. package/dist/{lace-context-CZcNHr4M.js → lace-context-BZciB9c7.js} +4 -4
  196. package/dist/{lace-context-fJTDghdp.cjs → lace-context-DgR6vLli.cjs} +4 -4
  197. package/dist/lib--iqvW4O_.js +2354 -0
  198. package/dist/lib-Yk6Upl5D.cjs +2359 -0
  199. package/dist/{libsodium-wrappers-UH0LaOUE.js → libsodium-wrappers-BhbOA8dQ.js} +3 -1647
  200. package/dist/midnight-account-id.vo-0x9X-r3l.cjs +10 -0
  201. package/dist/midnight-account-id.vo-DjCAGcqc.js +5 -0
  202. package/dist/midnight-engine-DpemplKO.js +5 -0
  203. package/dist/midnight-engine-xU1wotne.cjs +6 -0
  204. package/dist/midnight-wallet-DIsAlSn6.js +18 -0
  205. package/dist/midnight-wallet-XTZc2li7.cjs +24 -0
  206. package/dist/midnight.cjs +1408 -0
  207. package/dist/midnight.d.ts +28934 -0
  208. package/dist/midnight.js +1352 -0
  209. package/dist/modules-cardano-B1nDUWqy.js +995 -0
  210. package/dist/modules-cardano-BYeYHrRm.cjs +1108 -0
  211. package/dist/node-relay-DWe1U0w2.cjs +49 -0
  212. package/dist/node-relay-h4i5IlAQ.js +48 -0
  213. package/dist/outputs-Bd2yZVjx.js +720 -0
  214. package/dist/outputs-CJoQBIA2.cjs +990 -0
  215. package/dist/pbkdf2-CIW-oWrm.cjs +1337 -0
  216. package/dist/pending-operation-B0_P78Jo.cjs +26 -0
  217. package/dist/pending-operation-BIS6mpjB.js +21 -0
  218. package/dist/providers-FjhM47BH.cjs +388 -0
  219. package/dist/providers-WtiSuxFu.js +365 -0
  220. package/dist/redacted-BmE2aXqr.js +81 -0
  221. package/dist/redacted-CRZJLS3w.cjs +86 -0
  222. package/dist/{retry-config-DC5IMaH7.cjs → retry-config-BaCfVC1H.cjs} +1 -1
  223. package/dist/{retry-config-BcUmMS--.js → retry-config-Dmgt28wM.js} +1 -1
  224. package/dist/safe-buffer-B_vMqJWU.js +43 -0
  225. package/dist/safe-buffer-DYOwEfHB.cjs +48 -0
  226. package/dist/sdk-Cb-gZnS9.js +1241 -0
  227. package/dist/sdk-DffwmX8b.cjs +1439 -0
  228. package/dist/sdk-init-Bln9rFtn.js +4138 -0
  229. package/dist/sdk-init-CYViTJY_.cjs +3841 -0
  230. package/dist/{seam-cardano-CATqBEyK.js → seam-cardano-B_etH4F4.js} +1 -1
  231. package/dist/{bytes.vo-TgiwogWF.js → secret-box-DUR0ACYz.js} +3 -25
  232. package/dist/{bytes.vo-Ck5u40RA.cjs → secret-box-DrjLZuS1.cjs} +1 -35
  233. package/dist/send-proof-progress-C-ljq1x5.js +30 -0
  234. package/dist/send-proof-progress-vmsaSfbz.cjs +47 -0
  235. package/dist/side-effects-BnqYz7Nl.js +768 -0
  236. package/dist/side-effects-CngaeXi0.cjs +804 -0
  237. package/dist/sign-bitcoin-transaction-with-seed-D4z62-jV.js +147 -0
  238. package/dist/sign-bitcoin-transaction-with-seed-DsLYXnCY.cjs +158 -0
  239. package/dist/signer-3fk8lZtE.cjs +7 -0
  240. package/dist/signer-CsL28DrK.cjs +121 -0
  241. package/dist/signer-DGluibtn.js +92 -0
  242. package/dist/signer-RqB5pu3K.js +2 -0
  243. package/dist/signer-factory-BA7WFJVZ.js +282 -0
  244. package/dist/signer-factory-Cwd6o-lG.cjs +281 -0
  245. package/dist/{signer-factory-9URFliA5.js → signer-factory-DObB55D4.js} +6 -3
  246. package/dist/signer-factory-DhZiE03y.cjs +149 -0
  247. package/dist/{signer-factory-BWGUmnvm.cjs → signer-factory-Ds6G2AZk.cjs} +4 -3
  248. package/dist/signer-factory-hzSRaIw2.js +148 -0
  249. package/dist/{slice-CuHUaPZx.cjs → slice-7G2xxYKJ.cjs} +3 -3
  250. package/dist/{slice-DZmQJNV8.cjs → slice-B4CdYoPu.cjs} +2 -2
  251. package/dist/slice-BPNuHKfw.js +9091 -0
  252. package/dist/{slice-DGcNrbPR.cjs → slice-Bg6HEr3K.cjs} +4 -4
  253. package/dist/{slice-DtaO72qY.cjs → slice-Bs2aMERu.cjs} +3 -3
  254. package/dist/{slice-HeHCv3bl.cjs → slice-C34iOOUH.cjs} +7 -7
  255. package/dist/{slice-Do2R2CYW.cjs → slice-C9TT5KhY.cjs} +6 -6
  256. package/dist/{slice-eIwcwKHI.js → slice-CK07EBCo.js} +4 -4
  257. package/dist/{slice-CnyWevM9.js → slice-CU80pbiu.js} +3 -3
  258. package/dist/{slice-CobanYgn.js → slice-CwyYrh1H.js} +2 -2
  259. package/dist/slice-Czfp6t84.cjs +436 -0
  260. package/dist/{slice-d0p6-xj5.js → slice-D-9aPKG-.js} +6 -6
  261. package/dist/{slice-maaskdUn.js → slice-DBpJ2QGf.js} +6 -6
  262. package/dist/{slice-mxLQ_FeY.cjs → slice-DTZTiJle.cjs} +352 -39
  263. package/dist/{slice-zJ9XVYjZ.js → slice-Da426sf9.js} +1 -1
  264. package/dist/{slice-D11m2EKl.cjs → slice-DayJvMRD.cjs} +1 -1
  265. package/dist/slice-DnBWfA-k.cjs +9109 -0
  266. package/dist/{slice-oqm_r1cS.cjs → slice-DnG-yvpI.cjs} +2 -2
  267. package/dist/{slice-BNu73oBa.js → slice-DyNs7oWp.js} +2 -2
  268. package/dist/{slice-CB4SnzMm.js → slice-GwiiJRoq.js} +3 -3
  269. package/dist/slice-oWnc7YVD.js +412 -0
  270. package/dist/{slice-B2PhoWAg.js → slice-qt0uBExh.js} +325 -37
  271. package/dist/slice-t8Gzj55G2.cjs +106 -0
  272. package/dist/slice-t8Q1cHm-.js +88 -0
  273. package/dist/src-BDzYIksE.cjs +20637 -0
  274. package/dist/src-BFoefPv_.js +20755 -0
  275. package/dist/store-B1Lq3cEf.cjs +66 -0
  276. package/dist/store-DuBG8qh5.js +37 -0
  277. package/dist/submit-Bs77dPn_.cjs +413 -0
  278. package/dist/submit-DOv8Z0Vf.js +336 -0
  279. package/dist/submit-bitcoin-tx-D6oYgH5S.js +983 -0
  280. package/dist/submit-bitcoin-tx-goFuRL7K.cjs +1049 -0
  281. package/dist/{sync-operation-utils-BYXLO80m.js → sync-operation-utils-31iFLExW.js} +2 -38
  282. package/dist/{sync-operation-utils-SdPbwFoD.cjs → sync-operation-utils-COIZ66-I.cjs} +1 -67
  283. package/dist/token-id-mapper-Bnds3xKH.cjs +18 -0
  284. package/dist/{token-id-mapper-DsPAL6Nh.cjs → token-id-mapper-CVyQJUKY.cjs} +2 -2
  285. package/dist/token-id-mapper-CnKHQ8DV.js +16 -0
  286. package/dist/{token-id-mapper-B2ivlLv3.js → token-id-mapper-D29Ggv8h.js} +2 -2
  287. package/dist/tokens-Cevp7rdU.cjs +62 -0
  288. package/dist/tokens-Diw4MLRM.js +44 -0
  289. package/dist/types-B8uiJn-X.js +12 -0
  290. package/dist/types-BHC12eSa.js +33 -0
  291. package/dist/types-CJT6XF2c.js +10 -0
  292. package/dist/types-CLRUYpfe.cjs +23 -0
  293. package/dist/types-Cc3mC8u0.cjs +50 -0
  294. package/dist/types-DWbVZpnF.cjs +15 -0
  295. package/dist/unwrap-provider-result-BZSiwabU.js +32 -0
  296. package/dist/unwrap-provider-result-ZqfBsTkk.cjs +39 -0
  297. package/dist/{util-CGzqQ8IV.cjs → util-Bu4W5lF4.cjs} +1 -1
  298. package/dist/{util-BaLzwa32.js → util-Cp5cZkfK.js} +1 -1
  299. package/dist/{utils-o8aMjfln.js → utils-BfBEUvWA.js} +2 -2
  300. package/dist/utils-DFwzEvbv.js +65 -0
  301. package/dist/{utils-5JvjbqH3.cjs → utils-DsElZgCI.cjs} +7 -1
  302. package/dist/utils-IXxR-Djh.cjs +112 -0
  303. package/dist/v8Signatures-CO_Uloy7.cjs +71 -0
  304. package/dist/{vote-delegation-tx-builder-BpEMSti4.cjs → vote-delegation-tx-builder-BUg1S2Ep.cjs} +6 -6
  305. package/dist/{vote-delegation-tx-builder-CmKv6GoG.js → vote-delegation-tx-builder-C6FiS7zI.js} +5 -5
  306. package/dist/watch-CUEvcP-V.js +21997 -0
  307. package/dist/watch-DMF2s-II.cjs +52281 -0
  308. package/package.json +96 -4
  309. package/dist/account-guards.stable-B1DSSh9D.cjs +0 -10
  310. package/dist/account-guards.stable-JRQ5qx2V.js +0 -5
  311. package/dist/codecs-B7X9pAsK.cjs +0 -1945
  312. package/dist/codecs-CC1Xjntz.js +0 -1882
  313. package/dist/init-Bv53hpLM.js +0 -19
  314. package/dist/init-CRbjI7p1.js +0 -3494
  315. package/dist/init-DAna1KCg.cjs +0 -3495
  316. package/dist/init-DGe47B22.cjs +0 -364
  317. package/dist/init-DMtyvYfC.cjs +0 -21
  318. package/dist/init-TkPDD750.js +0 -363
  319. package/dist/modules-cardano-BDvuL4Xx.js +0 -5248
  320. package/dist/modules-cardano-D2G3De2P.cjs +0 -5432
  321. package/dist/slice-CGVHXHDt.cjs +0 -125
  322. package/dist/slice-DhvF7L6X.js +0 -107
  323. /package/dist/{account-id.vo-LvCBVn5r.cjs → account-id.vo-DwqFjK5u.cjs} +0 -0
  324. /package/dist/{account-id.vo-MYSI7YFm.js → account-id.vo-OPz2v-JZ.js} +0 -0
  325. /package/dist/{actions-DdGbj7c7.cjs → actions-B2BJ4RTy.cjs} +0 -0
  326. /package/dist/{actions-9QSQR-GB.js → actions-iLXdgL5Y.js} +0 -0
  327. /package/dist/{apply-vkey-witnesses-ClZbpk5w.js → apply-vkey-witnesses-BKx3lcs0.js} +0 -0
  328. /package/dist/{apply-vkey-witnesses-CLzVSWxl.cjs → apply-vkey-witnesses-ZnFS0jnJ.cjs} +0 -0
  329. /package/dist/{asyncoption-Cw07zPH7.js → asyncoption-CruEYOBI.js} +0 -0
  330. /package/dist/{asyncoption-DYoGuQfP.cjs → asyncoption-i0VbqVTq.cjs} +0 -0
  331. /package/dist/{bignum.vo-B0rK_PQ1.js → bignum.vo-CEXOIew0.js} +0 -0
  332. /package/dist/{bignum.vo-DsG3kNiZ.cjs → bignum.vo-hx2kuqlA.cjs} +0 -0
  333. /package/dist/{bip32ed25519-1ApqeAZk.cjs → bip32ed25519-B7Yat217.cjs} +0 -0
  334. /package/dist/{bip32ed25519-DetAdGwD.js → bip32ed25519-FQ8qvdcq.js} +0 -0
  335. /package/dist/{blake2b-DOEVc57D.js → blake2b-BiQTw3GC.js} +0 -0
  336. /package/dist/{blake2b-B9tftbvG.cjs → blake2b-DEeVUdKR.cjs} +0 -0
  337. /package/dist/{blockchain-network-id.vo-BXpZhvvQ.cjs → blockchain-network-id.vo-BAKEwGjG.cjs} +0 -0
  338. /package/dist/{blockchain-network-id.vo-DNRkuT5B.js → blockchain-network-id.vo-CiVykuqG.js} +0 -0
  339. /package/dist/{blockingWithLatestFrom-C5wp_uA-.js → blockingWithLatestFrom-Cd8c8EPG.js} +0 -0
  340. /package/dist/{blockingWithLatestFrom-DY8OPg0w.cjs → blockingWithLatestFrom-D8kBPBMX.cjs} +0 -0
  341. /package/dist/{cardano-network-id-to-network-type-CrZfUcyP.js → cardano-network-id-to-network-type-BWwzeEtM.js} +0 -0
  342. /package/dist/{cardano-network-id-to-network-type-BDTF-HmK.cjs → cardano-network-id-to-network-type-C0ufJOyE.cjs} +0 -0
  343. /package/dist/{cardano-tx-id.vo-BPhV-AmZ.cjs → cardano-tx-id.vo-TLjJZHCI.cjs} +0 -0
  344. /package/dist/{cardano-tx-id.vo-DF9NzZXk.js → cardano-tx-id.vo-eVnKuzlm.js} +0 -0
  345. /package/dist/{composite-signer-factory-_46QsNBz.js → composite-signer-factory-CR8YHA1y.js} +0 -0
  346. /package/dist/{composite-signer-factory-BpF1mIYA.cjs → composite-signer-factory-m5cVs9h_.cjs} +0 -0
  347. /package/dist/{error-CNIquqT5.cjs → error-Cb3EnD0u.cjs} +0 -0
  348. /package/dist/{error-BCp9NkPi.js → error-DIZOY2Lw.js} +0 -0
  349. /package/dist/{esm-browser-C93Q-EOI.js → esm-browser-MG97cre9.js} +0 -0
  350. /package/dist/{esm-browser-DTc9IK3D.cjs → esm-browser-bweqfBlL.cjs} +0 -0
  351. /package/dist/{feature-flag-key.vo-ofrB6ZVQ.js → feature-flag-key.vo-DN_-4-sG.js} +0 -0
  352. /package/dist/{feature-flag-key.vo-BPz-ZAp6.cjs → feature-flag-key.vo-RlfHL3hq.cjs} +0 -0
  353. /package/dist/{first-state-of-status-OROkXcRv.cjs → first-state-of-status-CbT7hPa4.cjs} +0 -0
  354. /package/dist/{first-state-of-status-DQnMT3ya.js → first-state-of-status-unPynOuM.js} +0 -0
  355. /package/dist/{init-Es3wHW7D.js → init-829HRYcz.js} +0 -0
  356. /package/dist/{init-CKipPE_c.js → init-A-VyGSNW2.js} +0 -0
  357. /package/dist/{init-DFQQ9dTW.cjs → init-Atisw4x2.cjs} +0 -0
  358. /package/dist/{init-C5CEZ1m0.cjs → init-BFcvPHL-.cjs} +0 -0
  359. /package/dist/{init-IAk_CkGa.cjs → init-BgNobbNq.cjs} +0 -0
  360. /package/dist/{init-cqN3uX2j.js → init-atCFur0v.js} +0 -0
  361. /package/dist/{is-redux-persist-state-CTn3WZVh.cjs → is-redux-persist-state-BCFnSm36.cjs} +0 -0
  362. /package/dist/{is-redux-persist-state-Cxcd0_bM.js → is-redux-persist-state-yBfq0h_E.js} +0 -0
  363. /package/dist/{key-value-store-8cMzeNyG.js → key-value-store--W3SrMaw.js} +0 -0
  364. /package/dist/{key-value-store-DUAepXQf.cjs → key-value-store-C2Xt5Emp.cjs} +0 -0
  365. /package/dist/{repo-slice-WxetRhMY.cjs → repo-slice-7X4AYYVm.cjs} +0 -0
  366. /package/dist/{repo-slice-DwyMhCR1.js → repo-slice-RxFm0zDZ.js} +0 -0
  367. /package/dist/{reselect-CRDqmQY9.cjs → reselect-Bd94u0K-.cjs} +0 -0
  368. /package/dist/{reselect-C06X06oX.js → reselect-CGoLzEPv.js} +0 -0
  369. /package/dist/{serializable-B8GahgE1.js → serializable-BHdKIgk3.js} +0 -0
  370. /package/dist/{serializable-CRdnFaLZ.cjs → serializable-BxHkoPdk.cjs} +0 -0
  371. /package/dist/{slice-D11FHQuQ.cjs → slice-BiRsDKOK.cjs} +0 -0
  372. /package/dist/{slice-Be7hj4Iy.js → slice-Bk0Sv05J.js} +0 -0
  373. /package/dist/{slice-FioKeHtA.cjs → slice-Dqw1ecum.cjs} +0 -0
  374. /package/dist/{slice-B87b52iM.js → slice-obCSLm1x.js} +0 -0
  375. /package/dist/{src-vq1wS9sZ.js → src-BlxEp6Mm.js} +0 -0
  376. /package/dist/{src-BTPIvlDI.cjs → src-Cqp0B2M_.cjs} +0 -0
  377. /package/dist/{time.vo-CQ8pSXz2.cjs → time.vo-D3wWRw9L.cjs} +0 -0
  378. /package/dist/{time.vo-DkYYGYp6.js → time.vo-tNheinXm.js} +0 -0
  379. /package/dist/{toEmpty-CgAl3097.js → toEmpty-8Zax1MPd.js} +0 -0
  380. /package/dist/{toEmpty-DAMmNB5r.cjs → toEmpty-CYAbupM4.cjs} +0 -0
  381. /package/dist/{token-id.vo-ClsroxHO.js → token-id.vo-Bvwhr3ZE.js} +0 -0
  382. /package/dist/{token-id.vo-BxG9TG0O.cjs → token-id.vo-DXv5uS9n.cjs} +0 -0
  383. /package/dist/{util-DxzlYNS5.js → util-C8a4fA9p.js} +0 -0
  384. /package/dist/{util-CmdAhheh.cjs → util-CzeB3hfa.cjs} +0 -0
  385. /package/dist/{util-selector-CcK-GAdE.js → util-selector-BSTsxgne.js} +0 -0
  386. /package/dist/{util-selector-BcAncU4L.cjs → util-selector-BWPH68_l.cjs} +0 -0
  387. /package/dist/{while-active-BpppWuCs.js → while-active-B0lWy_6l.js} +0 -0
  388. /package/dist/{while-active-Dhc2LwOm.cjs → while-active-Dsowp0Fi.cjs} +0 -0
@@ -0,0 +1,3814 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-Br2OG8yv.cjs");
2
+ const require__polyfill_buffer_patch = require("./_polyfill-buffer-patch-CM8X7JiY.cjs");
3
+ require("./bn-d3nSOIf7.cjs");
4
+ require("./client-DXBLHk7K.cjs");
5
+ const require_dist = require("./dist-BMi5ZjEq.cjs");
6
+ const require_v8Signatures = require("./v8Signatures-CO_Uloy7.cjs");
7
+ let rxjs = require("rxjs");
8
+ rxjs = require_rolldown_runtime.__toESM(rxjs);
9
+ let _midnight_ntwrk_ledger_v8 = require("@midnight-ntwrk/ledger-v8");
10
+ _midnight_ntwrk_ledger_v8 = require_rolldown_runtime.__toESM(_midnight_ntwrk_ledger_v8);
11
+ let _midnightntwrk_ledger_v9 = require("@midnightntwrk/ledger-v9");
12
+ _midnightntwrk_ledger_v9 = require_rolldown_runtime.__toESM(_midnightntwrk_ledger_v9);
13
+ //#region ../../packages/module/passport-account/node_modules/effect/dist/esm/internal/matcher.js
14
+ /** @internal */
15
+ const TypeId = /* @__PURE__ */ Symbol.for("@effect/matcher/Matcher");
16
+ const TypeMatcherProto = {
17
+ [TypeId]: {
18
+ _input: require_dist.identity,
19
+ _filters: require_dist.identity,
20
+ _remaining: require_dist.identity,
21
+ _result: require_dist.identity,
22
+ _return: require_dist.identity
23
+ },
24
+ _tag: "TypeMatcher",
25
+ add(_case) {
26
+ return makeTypeMatcher([...this.cases, _case]);
27
+ },
28
+ pipe() {
29
+ return require_dist.pipeArguments(this, arguments);
30
+ }
31
+ };
32
+ function makeTypeMatcher(cases) {
33
+ const matcher = Object.create(TypeMatcherProto);
34
+ matcher.cases = cases;
35
+ return matcher;
36
+ }
37
+ const ValueMatcherProto = {
38
+ [TypeId]: {
39
+ _input: require_dist.identity,
40
+ _filters: require_dist.identity,
41
+ _remaining: require_dist.identity,
42
+ _result: require_dist.identity,
43
+ _provided: require_dist.identity,
44
+ _return: require_dist.identity
45
+ },
46
+ _tag: "ValueMatcher",
47
+ add(_case) {
48
+ if (this.value._tag === "Right") return this;
49
+ if (_case._tag === "When" && _case.guard(this.provided) === true) return makeValueMatcher(this.provided, require_dist.right(_case.evaluate(this.provided)));
50
+ else if (_case._tag === "Not" && _case.guard(this.provided) === false) return makeValueMatcher(this.provided, require_dist.right(_case.evaluate(this.provided)));
51
+ return this;
52
+ },
53
+ pipe() {
54
+ return require_dist.pipeArguments(this, arguments);
55
+ }
56
+ };
57
+ function makeValueMatcher(provided, value) {
58
+ const matcher = Object.create(ValueMatcherProto);
59
+ matcher.provided = provided;
60
+ matcher.value = value;
61
+ return matcher;
62
+ }
63
+ const makeWhen = (guard, evaluate) => ({
64
+ _tag: "When",
65
+ guard,
66
+ evaluate
67
+ });
68
+ const makePredicate = (pattern) => {
69
+ if (typeof pattern === "function") return pattern;
70
+ else if (Array.isArray(pattern)) {
71
+ const predicates = pattern.map(makePredicate);
72
+ const len = predicates.length;
73
+ return (u) => {
74
+ if (!Array.isArray(u)) return false;
75
+ for (let i = 0; i < len; i++) if (predicates[i](u[i]) === false) return false;
76
+ return true;
77
+ };
78
+ } else if (pattern !== null && typeof pattern === "object") {
79
+ const keysAndPredicates = Object.entries(pattern).map(([k, p]) => [k, makePredicate(p)]);
80
+ const len = keysAndPredicates.length;
81
+ return (u) => {
82
+ if (typeof u !== "object" || u === null) return false;
83
+ for (let i = 0; i < len; i++) {
84
+ const [key, predicate] = keysAndPredicates[i];
85
+ if (!(key in u) || predicate(u[key]) === false) return false;
86
+ }
87
+ return true;
88
+ };
89
+ }
90
+ return (u) => u === pattern;
91
+ };
92
+ /** @internal */
93
+ const value$1 = (i) => makeValueMatcher(i, require_dist.left(i));
94
+ /** @internal */
95
+ const when$1 = (pattern, f) => (self) => self.add(makeWhen(makePredicate(pattern), f));
96
+ /** @internal */
97
+ const discriminators$1 = (field) => (fields) => {
98
+ const predicate = makeWhen((arg) => arg != null && arg[field] in fields, (data) => fields[data[field]](data));
99
+ return (self) => self.add(predicate);
100
+ };
101
+ /** @internal */
102
+ const discriminatorsExhaustive$1 = (field) => (fields) => {
103
+ const addCases = discriminators$1(field)(fields);
104
+ return (matcher) => exhaustive$1(addCases(matcher));
105
+ };
106
+ /** @internal */
107
+ const either$1 = (self) => {
108
+ if (self._tag === "ValueMatcher") return self.value;
109
+ const len = self.cases.length;
110
+ if (len === 1) {
111
+ const _case = self.cases[0];
112
+ return (input) => {
113
+ if (_case._tag === "When" && _case.guard(input) === true) return require_dist.right(_case.evaluate(input));
114
+ else if (_case._tag === "Not" && _case.guard(input) === false) return require_dist.right(_case.evaluate(input));
115
+ return require_dist.left(input);
116
+ };
117
+ }
118
+ return (input) => {
119
+ for (let i = 0; i < len; i++) {
120
+ const _case = self.cases[i];
121
+ if (_case._tag === "When" && _case.guard(input) === true) return require_dist.right(_case.evaluate(input));
122
+ else if (_case._tag === "Not" && _case.guard(input) === false) return require_dist.right(_case.evaluate(input));
123
+ }
124
+ return require_dist.left(input);
125
+ };
126
+ };
127
+ const getExhaustiveAbsurdErrorMessage = "effect/Match/exhaustive: absurd";
128
+ /** @internal */
129
+ const exhaustive$1 = (self) => {
130
+ const toEither = either$1(self);
131
+ if (require_dist.isEither(toEither)) {
132
+ if (toEither._tag === "Right") return toEither.right;
133
+ throw new Error(getExhaustiveAbsurdErrorMessage);
134
+ }
135
+ return (u) => {
136
+ const result = toEither(u);
137
+ if (result._tag === "Right") return result.right;
138
+ throw new Error(getExhaustiveAbsurdErrorMessage);
139
+ };
140
+ };
141
+ /**
142
+ * Creates a matcher from a specific value.
143
+ *
144
+ * **Details**
145
+ *
146
+ * This function allows you to define a `Matcher` directly from a given value,
147
+ * rather than from a type. This is useful when working with known values,
148
+ * enabling structured pattern matching on objects, primitives, or any data
149
+ * structure.
150
+ *
151
+ * Once the matcher is created, you can use pattern-matching functions like
152
+ * {@link when} to define how different cases should be handled.
153
+ *
154
+ * **Example** (Matching an Object by Property)
155
+ *
156
+ * ```ts
157
+ * import { Match } from "effect"
158
+ *
159
+ * const input = { name: "John", age: 30 }
160
+ *
161
+ * // Create a matcher for the specific object
162
+ * const result = Match.value(input).pipe(
163
+ * // Match when the 'name' property is "John"
164
+ * Match.when(
165
+ * { name: "John" },
166
+ * (user) => `${user.name} is ${user.age} years old`
167
+ * ),
168
+ * // Provide a fallback if no match is found
169
+ * Match.orElse(() => "Oh, not John")
170
+ * )
171
+ *
172
+ * console.log(result)
173
+ * // Output: "John is 30 years old"
174
+ * ```
175
+ *
176
+ * @see {@link type} for creating a matcher from a specific type.
177
+ *
178
+ * @category Creating a matcher
179
+ * @since 1.0.0
180
+ */
181
+ const value = value$1;
182
+ /**
183
+ * Defines a condition for matching values.
184
+ *
185
+ * **Details**
186
+ *
187
+ * This function enables pattern matching by checking whether a given value
188
+ * satisfies a condition. It supports both direct value comparisons and
189
+ * predicate functions. If the condition is met, the associated function is
190
+ * executed.
191
+ *
192
+ * This function is useful when defining matchers that need to check for
193
+ * specific values or apply logical conditions to determine a match. It works
194
+ * well with structured objects and primitive types.
195
+ *
196
+ * **Example** (Matching with Values and Predicates)
197
+ *
198
+ * ```ts
199
+ * import { Match } from "effect"
200
+ *
201
+ * // Create a matcher for objects with an "age" property
202
+ * const match = Match.type<{ age: number }>().pipe(
203
+ * // Match when age is greater than 18
204
+ * Match.when({ age: (age) => age > 18 }, (user) => `Age: ${user.age}`),
205
+ * // Match when age is exactly 18
206
+ * Match.when({ age: 18 }, () => "You can vote"),
207
+ * // Fallback case for all other ages
208
+ * Match.orElse((user) => `${user.age} is too young`)
209
+ * )
210
+ *
211
+ * console.log(match({ age: 20 }))
212
+ * // Output: "Age: 20"
213
+ *
214
+ * console.log(match({ age: 18 }))
215
+ * // Output: "You can vote"
216
+ *
217
+ * console.log(match({ age: 4 }))
218
+ * // Output: "4 is too young"
219
+ * ```
220
+ *
221
+ * @see {@link whenOr} Use this when multiple patterns should match in a single
222
+ * condition.
223
+ * @see {@link whenAnd} Use this when a value must match all provided patterns.
224
+ * @see {@link orElse} Provides a fallback when no patterns match.
225
+ *
226
+ * @category Defining patterns
227
+ * @since 1.0.0
228
+ */
229
+ const when = when$1;
230
+ /**
231
+ * Matches values based on a discriminator field and **ensures all cases are
232
+ * handled**.
233
+ *
234
+ * **Details*+
235
+ *
236
+ * This function is similar to {@link discriminators}, but **requires that all
237
+ * possible cases** are explicitly handled. It is useful when working with
238
+ * discriminated unions, where a specific field (e.g., `"type"`) determines the
239
+ * shape of an object. Each possible value of the field must have a
240
+ * corresponding handler, ensuring **exhaustiveness checking** at compile time.
241
+ *
242
+ * This function **does not require** `Match.exhaustive` at the end of the
243
+ * pipeline because it enforces exhaustiveness by design.
244
+ *
245
+ * @example
246
+ * ```ts
247
+ * import { Match, pipe } from "effect"
248
+ *
249
+ * const match = pipe(
250
+ * Match.type<{ type: "A"; a: string } | { type: "B"; b: number } | { type: "C"; c: boolean }>(),
251
+ * Match.discriminatorsExhaustive("type")({
252
+ * A: (a) => a.a,
253
+ * B: (b) => b.b,
254
+ * C: (c) => c.c
255
+ * })
256
+ * )
257
+ * ```
258
+ *
259
+ * @category Defining patterns
260
+ * @since 1.0.0
261
+ */
262
+ const discriminatorsExhaustive = discriminatorsExhaustive$1;
263
+ require_dist.isString;
264
+ require_dist.isNumber;
265
+ require_dist.isBoolean;
266
+ require_dist.isUndefined;
267
+ require_dist.isNull;
268
+ require_dist.isBigInt;
269
+ require_dist.isSymbol;
270
+ require_dist.isDate;
271
+ require_dist.isRecord;
272
+ /**
273
+ * The `Match.exhaustive` method finalizes the pattern matching process by
274
+ * ensuring that all possible cases are accounted for. If any case is missing,
275
+ * TypeScript will produce a type error. This is particularly useful when
276
+ * working with unions, as it helps prevent unintended gaps in pattern matching.
277
+ *
278
+ * **Example** (Ensuring All Cases Are Covered)
279
+ *
280
+ * ```ts
281
+ * import { Match } from "effect"
282
+ *
283
+ * // Create a matcher for string or number values
284
+ * const match = Match.type<string | number>().pipe(
285
+ * // Match when the value is a number
286
+ * Match.when(Match.number, (n) => `number: ${n}`),
287
+ * // Mark the match as exhaustive, ensuring all cases are handled
288
+ * // TypeScript will throw an error if any case is missing
289
+ * // @ts-expect-error Type 'string' is not assignable to type 'never'
290
+ * Match.exhaustive
291
+ * )
292
+ * ```
293
+ *
294
+ * @category Completion
295
+ * @since 1.0.0
296
+ */
297
+ const exhaustive = exhaustive$1;
298
+ //#endregion
299
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/UnshieldedWalletAPI.js
300
+ var UnshieldedWalletState = class UnshieldedWalletState {
301
+ /**
302
+ * Wraps a state emission with the capabilities of the variant that produced it.
303
+ *
304
+ * @remarks
305
+ * Call this inside a branch that has narrowed on the emission's `variantTag`, so `variant` and `state` are known to
306
+ * belong together. It is generic over the state type precisely so that pairing is checked.
307
+ */
308
+ static fromVariant = (variant, state) => new UnshieldedWalletState(state.version, state.state, {
309
+ balances: () => variant.coinsAndBalances.getAvailableBalances(state.state),
310
+ totalCoins: () => variant.coinsAndBalances.getTotalCoins(state.state),
311
+ availableCoins: () => variant.coinsAndBalances.getAvailableCoins(state.state),
312
+ pendingCoins: () => variant.coinsAndBalances.getPendingCoins(state.state),
313
+ address: () => variant.keys.getAddress(state.state),
314
+ serialize: () => variant.serialization.serialize(state.state)
315
+ });
316
+ protocolVersion;
317
+ state;
318
+ #projections;
319
+ get balances() {
320
+ return this.#projections.balances();
321
+ }
322
+ get totalCoins() {
323
+ return this.#projections.totalCoins();
324
+ }
325
+ get availableCoins() {
326
+ return this.#projections.availableCoins();
327
+ }
328
+ get pendingCoins() {
329
+ return this.#projections.pendingCoins();
330
+ }
331
+ get address() {
332
+ return this.#projections.address();
333
+ }
334
+ get progress() {
335
+ return this.state.progress;
336
+ }
337
+ constructor(protocolVersion, state, projections) {
338
+ this.protocolVersion = protocolVersion;
339
+ this.state = state;
340
+ this.#projections = projections;
341
+ }
342
+ serialize() {
343
+ return this.#projections.serialize();
344
+ }
345
+ };
346
+ //#endregion
347
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/RunningV2Variant.js
348
+ const progress$1 = (state) => {
349
+ const appliedId = state.progress?.appliedId ?? 0n;
350
+ const sourceGap = (state.progress?.highestTransactionId ?? 0n) - appliedId;
351
+ const applyGap = appliedId - appliedId;
352
+ return [require_dist.ProgressUpdate({
353
+ sourceGap,
354
+ applyGap
355
+ })];
356
+ };
357
+ /**
358
+ * The version signals this variant puts on its state stream.
359
+ *
360
+ * @remarks
361
+ * Two of them, for two different situations. A transition is the ordinary one: the state moved to a version the variant
362
+ * may or may not own, and the runtime decides. The healing emission covers restore: a snapshot taken between the
363
+ * moment sync annotated an out-of-range version and the moment the runtime acted on it comes back with a version this
364
+ * variant does not own and no transition to announce it, so it would sit there forever. Announcing it on the first
365
+ * observation is what forward-migrates such a snapshot.
366
+ */
367
+ const protocolVersionChange$1 = (previous, current, isInitial, activationRange) => {
368
+ const transitioned = previous.protocolVersion != current.protocolVersion;
369
+ const strandedOutsideRange = isInitial && !require_dist.withinRange(current.protocolVersion, activationRange);
370
+ return transitioned || strandedOutsideRange ? [require_dist.VersionChange({ change: require_dist.Version({ version: require_dist.ProtocolVersion(current.protocolVersion) }) })] : [];
371
+ };
372
+ const V2Tag = Symbol("V2");
373
+ var RunningV2Variant = class {
374
+ __polyTag__ = V2Tag;
375
+ #scope;
376
+ #context;
377
+ #v2Context;
378
+ state;
379
+ constructor(scope, context, v2Context) {
380
+ this.#scope = scope;
381
+ this.#context = context;
382
+ this.#v2Context = v2Context;
383
+ this.state = require_dist.fromEffect(context.stateRef.get).pipe(require_dist.flatMap((initialState) => context.stateRef.changes.pipe(require_dist.mapAccum({
384
+ previous: initialState,
385
+ isInitial: true
386
+ }, (seen, current) => [{
387
+ previous: current,
388
+ isInitial: false
389
+ }, [
390
+ seen.previous,
391
+ current,
392
+ seen.isInitial
393
+ ]]))), require_dist.mapConcat(([previous, current, isInitial]) => {
394
+ return [
395
+ require_dist.State({ state: current }),
396
+ ...progress$1(current),
397
+ ...protocolVersionChange$1(previous, current, isInitial, context.activationRange)
398
+ ];
399
+ }));
400
+ }
401
+ startSyncInBackground() {
402
+ return this.startSync().pipe(require_dist.runScoped(require_dist.drain), require_dist.forkScoped, require_dist.provideService(require_dist.Scope, this.#scope));
403
+ }
404
+ startSync() {
405
+ return require_dist.pipe(require_dist.get(this.#context.stateRef), require_dist.fromEffect, require_dist.flatMap((state) => this.#v2Context.syncService.updates(state)), require_dist.mapEffect((update) => {
406
+ return require_dist.updateEffect(this.#context.stateRef, (state) => require_dist.pipe(this.#v2Context.syncCapability.applyUpdate(state, update, this.#context.activationRange), require_dist.toEffect));
407
+ }), require_dist.tapError((error$2) => require_dist.error(error$2)), require_dist.retry(require_dist.pipe(require_dist.exponential(require_dist.seconds(1), 2), require_dist.map$1((delay) => {
408
+ const maxDelay = require_dist.minutes(2);
409
+ const jitter = require_dist.millis(Math.floor(Math.random() * 1e3));
410
+ const delayWithJitter = require_dist.toMillis(delay) + require_dist.toMillis(jitter);
411
+ return require_dist.millis(Math.min(delayWithJitter, require_dist.toMillis(maxDelay)));
412
+ }))));
413
+ }
414
+ balanceFinalizedTransaction(tx) {
415
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
416
+ return require_dist.pipe(this.#v2Context.transactingCapability.balanceFinalizedTransaction(state, tx), require_dist.toEffect);
417
+ });
418
+ }
419
+ balanceUnboundTransaction(tx) {
420
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
421
+ return require_dist.pipe(this.#v2Context.transactingCapability.balanceUnboundTransaction(state, tx), require_dist.toEffect);
422
+ });
423
+ }
424
+ balanceUnprovenTransaction(tx) {
425
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
426
+ return require_dist.pipe(this.#v2Context.transactingCapability.balanceUnprovenTransaction(state, tx), require_dist.toEffect);
427
+ });
428
+ }
429
+ transferTransaction(outputs, ttl) {
430
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
431
+ return require_dist.pipe(this.#v2Context.transactingCapability.makeTransfer(state, outputs, ttl), require_dist.toEffect, require_dist.map$2(({ transaction, newState }) => [transaction, newState]));
432
+ });
433
+ }
434
+ rotateUtxos(guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl) {
435
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
436
+ return require_dist.pipe(this.#v2Context.transactingCapability.rotateUtxos(state, guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl), require_dist.toEffect, require_dist.map$2(({ transaction, newState }) => [transaction, newState]));
437
+ });
438
+ }
439
+ initSwap(desiredInputs, desiredOutputs, ttl) {
440
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
441
+ return require_dist.pipe(this.#v2Context.transactingCapability.initSwap(state, desiredInputs, desiredOutputs, ttl), require_dist.map$2(({ transaction, newState }) => [transaction, newState]));
442
+ });
443
+ }
444
+ signUnprovenTransaction(transaction, signSegment) {
445
+ return this.#v2Context.signingService.sign(transaction, signSegment);
446
+ }
447
+ signUnboundTransaction(transaction, signSegment) {
448
+ return this.#v2Context.signingService.sign(transaction, signSegment);
449
+ }
450
+ revertTransaction(transaction) {
451
+ return require_dist.updateEffect(this.#context.stateRef, (state) => {
452
+ return require_dist.pipe(this.#v2Context.transactingCapability.revertTransaction(state, transaction), require_dist.toEffect);
453
+ });
454
+ }
455
+ serializeState(state) {
456
+ return this.#v2Context.serializationCapability.serialize(state);
457
+ }
458
+ };
459
+ //#endregion
460
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/WalletError.js
461
+ var OtherWalletError$1 = class extends require_dist.TaggedError("Wallet.Other") {};
462
+ var SyncWalletError$1 = class extends require_dist.TaggedError("Wallet.Sync") {};
463
+ var InsufficientFundsError$1 = class extends require_dist.TaggedError("Wallet.InsufficientFunds") {};
464
+ var TransactingError$1 = class extends require_dist.TaggedError("Wallet.Transacting") {};
465
+ var SignError$1 = class extends require_dist.TaggedError("Wallet.Sign") {};
466
+ /**
467
+ * Raised when a signature scheme (`schnorr` vs `ecdsa`) is mixed across an unshielded key, address, or signature.
468
+ * Mismatches are rejected early — at wallet construction or at signature provision — never silently coerced. The `at`
469
+ * field records where the mismatch was caught.
470
+ */
471
+ var SchemeMismatchError = class extends require_dist.TaggedError("Wallet.SchemeMismatch") {};
472
+ var ApplyTransactionError$1 = class extends require_dist.TaggedError("Wallet.ApplyTransaction") {};
473
+ /**
474
+ * Raised when a sync source delivers a transaction the wallet has already folded — an id strictly below its applied
475
+ * cursor — so applying it again would double-count the UTXOs that transaction created or spent.
476
+ *
477
+ * @remarks
478
+ * The id a wallet is served is the indexer's global transaction id filtered to this address, so what reaches it is a
479
+ * strictly increasing but sparse subsequence: "is this past my cursor?" is the only ordering question it can answer,
480
+ * and contiguity is not one of them. An id EQUAL to the cursor is the resume boundary answered inclusively and folds
481
+ * to a no-op rather than to this error; only a strictly lower one is a replay.
482
+ *
483
+ * Nothing is written when it is produced. The fold hands this back in place of a new state, so the running variant
484
+ * never writes its `SubscriptionRef`: the wallet keeps the state and the cursor it had, the sync stream fails, and
485
+ * the retry reopens the subscription at that same unmoved cursor — which is what gives the source the chance to
486
+ * deliver the timeline in order.
487
+ * @example
488
+ * ```ts
489
+ * import { Either } from 'effect';
490
+ *
491
+ * const outcome = capability.applyUpdate(wallet, update, activeRange);
492
+ * if (Either.isLeft(outcome) && outcome.left._tag === 'Wallet.OutOfOrderSyncUpdate') {
493
+ * console.warn(`replayed ${outcome.left.received}, already at ${outcome.left.expected}`);
494
+ * }
495
+ * ```
496
+ */
497
+ var OutOfOrderSyncUpdateError$1 = class extends require_dist.TaggedError("Wallet.OutOfOrderSyncUpdate") {};
498
+ var RollbackUtxoError$1 = class extends require_dist.TaggedError("Wallet.RollbackUtxo") {};
499
+ var SpendUtxoError$1 = class extends require_dist.TaggedError("Wallet.SpendUtxo") {};
500
+ var TransactionHistoryError$1 = class extends require_dist.TaggedError("Wallet.TransactionHistory") {};
501
+ var UtxoNotFoundError$1 = class extends require_dist.TaggedError("UtxoNotFoundError") {};
502
+ //#endregion
503
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/SchemeConsistency.js
504
+ const otherScheme = (kind) => kind === "schnorr" ? "ecdsa" : "schnorr";
505
+ /**
506
+ * Asserts that a {@link PublicKey}'s stored address was derived from its stored verifying key. A `schnorr` address
507
+ * bundled with an `ecdsa` key (or the inverse) is rejected at wallet construction.
508
+ *
509
+ * @param publicKey - The keystore-derived public key bundle to validate.
510
+ * @returns `Right(publicKey)` when the address matches the key; `Left(SchemeMismatchError)` tagged `at: 'construction'`
511
+ * when it does not; or `Left(OtherWalletError)` when the key cannot be decoded at all.
512
+ */
513
+ const assertKeyAddressConsistency$1 = (publicKey) => require_dist.pipe(require_dist.try_$1({
514
+ try: () => (0, _midnightntwrk_ledger_v9.addressFromKey)(publicKey.publicKey),
515
+ catch: (cause) => new OtherWalletError$1({
516
+ message: `Unshielded verifying key could not be decoded as a ${publicKey.publicKey.tag} key.`,
517
+ cause
518
+ })
519
+ }), require_dist.flatMap$4((derivedAddress) => {
520
+ if (derivedAddress === publicKey.addressHex) return require_dist.right(publicKey);
521
+ const supplied = publicKey.publicKey.tag;
522
+ const expected = otherScheme(supplied);
523
+ return require_dist.left(new SchemeMismatchError({
524
+ at: "construction",
525
+ expected,
526
+ supplied,
527
+ message: `Unshielded address does not match its verifying key: the address is derived under the ${expected} scheme but the supplied key is ${supplied}. Signature schemes must not be mixed.`
528
+ }));
529
+ }));
530
+ /**
531
+ * Asserts that a supplied signature shares the scheme of the verifying key it will be checked against. Used at
532
+ * signature-provision time so a `schnorr` signature can never be attached under an `ecdsa` key (or the inverse).
533
+ *
534
+ * @param key - The verifying key the signature must match.
535
+ * @param signature - The supplied signature.
536
+ * @returns `Right(signature)` (unchanged — no coercion) when the schemes match; otherwise `Left(SchemeMismatchError)`
537
+ * tagged `at: 'signature-provision'`, with `expected` = the key's scheme and `supplied` = the signature's scheme.
538
+ */
539
+ const assertSignatureMatchesKey = (key, signature) => {
540
+ if (key.tag === signature.tag) return require_dist.right(signature);
541
+ return require_dist.left(new SchemeMismatchError({
542
+ at: "signature-provision",
543
+ expected: key.tag,
544
+ supplied: signature.tag,
545
+ message: `Signature scheme does not match the signing key: expected a ${key.tag} signature but a ${signature.tag} signature was supplied. Signature schemes must not be mixed.`
546
+ }));
547
+ };
548
+ //#endregion
549
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/SyncProgress.js
550
+ const SyncProgress$1 = { isCompleteWithin(data, maxGap = 50n) {
551
+ const applyLag = BigInt(Math.abs(Number(data.highestTransactionId - data.appliedId)));
552
+ return data.isConnected && applyLag <= maxGap;
553
+ } };
554
+ const createSyncProgress$1 = (params = {}) => {
555
+ const { appliedId = 0n, highestTransactionId = 0n, isConnected = false } = params;
556
+ return {
557
+ appliedId,
558
+ highestTransactionId,
559
+ isConnected,
560
+ isStrictlyComplete() {
561
+ return SyncProgress$1.isCompleteWithin(this, 0n);
562
+ },
563
+ isCompleteWithin(maxGap) {
564
+ return SyncProgress$1.isCompleteWithin(this, maxGap);
565
+ }
566
+ };
567
+ };
568
+ //#endregion
569
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/UnshieldedState.js
570
+ var UtxoWithMeta = class extends require_dist.Class {};
571
+ const UtxoHash$1 = (utxo) => `${utxo.intentHash}#${utxo.outputNo}`;
572
+ /**
573
+ * The first UTXO an update reports as spent that this state holds in neither map.
574
+ *
575
+ * @remarks
576
+ * A spend naming a UTXO the wallet has never held is not noise to absorb: it is the only observable sign that the
577
+ * source delivered a spend ahead of the create it consumes. Absorbed, the create arrives afterwards and puts an
578
+ * already-spent UTXO into the available set, where it will be offered for coin selection and produce a transaction
579
+ * the chain rejects. Reported, the fold fails before the caller's cursor moves, and the retry re-fetches the pair in
580
+ * order.
581
+ * @param state The state the update is being folded into.
582
+ * @param spentUtxos The UTXOs the update reports as spent.
583
+ * @returns The first entry the state does not know, or `Option.none()` when every spend names a UTXO it holds.
584
+ */
585
+ const firstUnknownSpend$1 = (state, spentUtxos) => require_dist.findFirst(spentUtxos, (spent) => {
586
+ const hash = UtxoHash$1(spent.utxo);
587
+ return !require_dist.has(state.availableUtxos, hash) && !require_dist.has(state.pendingUtxos, hash);
588
+ });
589
+ const UnshieldedState$1 = {
590
+ empty: () => ({
591
+ availableUtxos: require_dist.empty$1(),
592
+ pendingUtxos: require_dist.empty$1()
593
+ }),
594
+ restore: (availableUtxos, pendingUtxos) => ({
595
+ availableUtxos: require_dist.fromIterable(availableUtxos.map((utxo) => [UtxoHash$1(utxo.utxo), utxo])),
596
+ pendingUtxos: require_dist.fromIterable(pendingUtxos.map((utxo) => [UtxoHash$1(utxo.utxo), utxo]))
597
+ }),
598
+ spend: (state, utxo) => require_dist.gen$1(function* () {
599
+ const hash = UtxoHash$1(utxo.utxo);
600
+ if (!require_dist.has(state.availableUtxos, hash)) return yield* require_dist.left(new UtxoNotFoundError$1({ utxo: utxo.utxo }));
601
+ return {
602
+ availableUtxos: require_dist.remove(state.availableUtxos, hash),
603
+ pendingUtxos: require_dist.set$1(state.pendingUtxos, hash, utxo)
604
+ };
605
+ }),
606
+ rollbackSpend: (state, utxo) => {
607
+ const hash = UtxoHash$1(utxo.utxo);
608
+ if (!require_dist.has(state.pendingUtxos, hash)) return require_dist.right(state);
609
+ return require_dist.right({
610
+ availableUtxos: require_dist.set$1(state.availableUtxos, hash, utxo),
611
+ pendingUtxos: require_dist.remove(state.pendingUtxos, hash)
612
+ });
613
+ },
614
+ spendByUtxo: (state, utxo) => require_dist.gen$1(function* () {
615
+ const hash = UtxoHash$1(utxo);
616
+ const found = yield* require_dist.fromOption(require_dist.get$2(state.availableUtxos, hash), () => new UtxoNotFoundError$1({ utxo }));
617
+ return yield* UnshieldedState$1.spend(state, found);
618
+ }),
619
+ rollbackSpendByUtxo: (state, utxo) => require_dist.pipe(require_dist.get$2(state.pendingUtxos, UtxoHash$1(utxo)), require_dist.match$1({
620
+ onNone: () => require_dist.right(state),
621
+ onSome: (found) => UnshieldedState$1.rollbackSpend(state, found)
622
+ })),
623
+ applyUpdate: (state, update) => require_dist.gen$1(function* () {
624
+ if (!["SUCCESS", "PARTIAL_SUCCESS"].includes(update.status)) return yield* require_dist.left(new ApplyTransactionError$1({ message: `Invalid status: ${update.status}` }));
625
+ const unknownSpend = firstUnknownSpend$1(state, update.spentUtxos);
626
+ if (require_dist.isSome(unknownSpend)) return yield* require_dist.left(new UtxoNotFoundError$1({ utxo: unknownSpend.value.utxo }));
627
+ return {
628
+ availableUtxos: require_dist.union$1(require_dist.removeMany(state.availableUtxos, update.spentUtxos.map((utxo) => UtxoHash$1(utxo.utxo))), require_dist.fromIterable(update.createdUtxos.map((utxo) => [UtxoHash$1(utxo.utxo), utxo]))),
629
+ pendingUtxos: require_dist.removeMany(state.pendingUtxos, update.spentUtxos.map((utxo) => UtxoHash$1(utxo.utxo)))
630
+ };
631
+ }),
632
+ applyFailedUpdate: (state, update) => require_dist.gen$1(function* () {
633
+ if (update.status !== "FAILURE") return yield* require_dist.left(new ApplyTransactionError$1({ message: `Invalid status: ${update.status}` }));
634
+ const unknownSpend = firstUnknownSpend$1(state, update.spentUtxos);
635
+ if (require_dist.isSome(unknownSpend)) return yield* require_dist.left(new UtxoNotFoundError$1({ utxo: unknownSpend.value.utxo }));
636
+ return {
637
+ availableUtxos: require_dist.union$1(state.availableUtxos, require_dist.fromIterable(update.spentUtxos.map((utxo) => [UtxoHash$1(utxo.utxo), utxo]))),
638
+ pendingUtxos: require_dist.removeMany(state.pendingUtxos, update.spentUtxos.map((utxo) => UtxoHash$1(utxo.utxo)))
639
+ };
640
+ }),
641
+ toArrays: (state) => ({
642
+ availableUtxos: require_dist.toValues(state.availableUtxos),
643
+ pendingUtxos: require_dist.toValues(state.pendingUtxos)
644
+ })
645
+ };
646
+ //#endregion
647
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/CoreWallet.js
648
+ const CoreWallet$1 = {
649
+ init(publicKey, networkId) {
650
+ return {
651
+ state: UnshieldedState$1.empty(),
652
+ publicKey,
653
+ protocolVersion: require_dist.MinSupportedVersion,
654
+ progress: createSyncProgress$1(),
655
+ networkId
656
+ };
657
+ },
658
+ restore(state, publicKey, syncProgress, protocolVersion, networkId) {
659
+ return {
660
+ state,
661
+ publicKey,
662
+ protocolVersion,
663
+ progress: createSyncProgress$1(syncProgress),
664
+ networkId
665
+ };
666
+ },
667
+ updateProgress(wallet, { appliedId, highestTransactionId, isConnected }) {
668
+ const progress = createSyncProgress$1({
669
+ appliedId: appliedId ?? wallet.progress.appliedId,
670
+ highestTransactionId: highestTransactionId ?? wallet.progress.highestTransactionId,
671
+ isConnected: isConnected ?? wallet.progress.isConnected
672
+ });
673
+ return {
674
+ ...wallet,
675
+ progress
676
+ };
677
+ },
678
+ withProtocolVersion(wallet, version) {
679
+ return version > wallet.protocolVersion ? {
680
+ ...wallet,
681
+ protocolVersion: version
682
+ } : wallet;
683
+ },
684
+ applyUpdate(coreWallet, update) {
685
+ return UnshieldedState$1.applyUpdate(coreWallet.state, update).pipe(require_dist.map$6((state) => ({
686
+ ...coreWallet,
687
+ state
688
+ })), require_dist.mapLeft((error) => new ApplyTransactionError$1(error)));
689
+ },
690
+ applyFailedUpdate(coreWallet, update) {
691
+ return UnshieldedState$1.applyFailedUpdate(coreWallet.state, update).pipe(require_dist.map$6((state) => ({
692
+ ...coreWallet,
693
+ state
694
+ })), require_dist.mapLeft((error) => new ApplyTransactionError$1(error)));
695
+ },
696
+ rollbackUtxo(coreWallet, utxo) {
697
+ return UnshieldedState$1.rollbackSpendByUtxo(coreWallet.state, utxo).pipe(require_dist.map$6((state) => ({
698
+ ...coreWallet,
699
+ state
700
+ })), require_dist.mapLeft((error) => new RollbackUtxoError$1(error)));
701
+ },
702
+ spend(coreWallet, utxo) {
703
+ return UnshieldedState$1.spendByUtxo(coreWallet.state, utxo).pipe(require_dist.map$6((state) => ({
704
+ ...coreWallet,
705
+ state
706
+ })), require_dist.mapLeft((error) => new SpendUtxoError$1(error)));
707
+ },
708
+ spendUtxos(wallet, utxos) {
709
+ return require_dist.pipe(utxos, require_dist.reduce(require_dist.right([[], wallet.state]), (acc, utxoToSpend) => acc.pipe(require_dist.flatMap$4(([accUtxos, state]) => UnshieldedState$1.spendByUtxo(state, utxoToSpend).pipe(require_dist.map$6((nextState) => [accUtxos.concat([utxoToSpend]), nextState]), require_dist.mapLeft((error) => new SpendUtxoError$1(error)))))), require_dist.map$6(([spentUtxos, state]) => [spentUtxos, {
710
+ ...wallet,
711
+ state
712
+ }]));
713
+ }
714
+ };
715
+ //#endregion
716
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/Serialization.js
717
+ const makeDefaultV2SerializationCapability = () => {
718
+ const SignatureKindSchema = require_dist.Literal("schnorr", "ecdsa");
719
+ const SignatureVerifyingKeySchema = require_dist.Struct({
720
+ tag: SignatureKindSchema,
721
+ value: require_dist.String$
722
+ });
723
+ const LegacySignatureVerifyingKeySchema = require_dist.transform(require_dist.String$, require_dist.typeSchema(SignatureVerifyingKeySchema), {
724
+ strict: true,
725
+ decode: (value) => ({
726
+ tag: "schnorr",
727
+ value
728
+ }),
729
+ encode: ({ value }) => value
730
+ });
731
+ const UtxoWithMetaSchema = require_dist.Struct({
732
+ utxo: require_dist.Struct({
733
+ value: require_dist.BigInt$,
734
+ owner: require_dist.String$,
735
+ type: require_dist.String$,
736
+ intentHash: require_dist.String$,
737
+ outputNo: require_dist.Number$
738
+ }),
739
+ meta: require_dist.Struct({
740
+ ctime: require_dist.Date$,
741
+ registeredForDustGeneration: require_dist.Boolean$
742
+ })
743
+ });
744
+ const SnapshotSchema = require_dist.Struct({
745
+ publicKey: require_dist.Struct({
746
+ publicKey: require_dist.Union(SignatureVerifyingKeySchema, LegacySignatureVerifyingKeySchema),
747
+ addressHex: require_dist.String$,
748
+ address: require_dist.String$
749
+ }),
750
+ state: require_dist.Struct({
751
+ availableUtxos: require_dist.Array$(UtxoWithMetaSchema),
752
+ pendingUtxos: require_dist.Array$(UtxoWithMetaSchema)
753
+ }),
754
+ protocolVersion: require_dist.BigInt$,
755
+ appliedId: require_dist.optional(require_dist.BigInt$),
756
+ networkId: require_dist.String$
757
+ });
758
+ return {
759
+ serialize: (wallet) => {
760
+ const buildSnapshot = (w) => ({
761
+ publicKey: w.publicKey,
762
+ state: UnshieldedState$1.toArrays(w.state),
763
+ protocolVersion: w.protocolVersion,
764
+ networkId: w.networkId,
765
+ appliedId: w.progress?.appliedId
766
+ });
767
+ return require_dist.pipe(wallet, buildSnapshot, require_dist.encodeSync(SnapshotSchema), JSON.stringify);
768
+ },
769
+ deserialize: (serialized) => require_dist.pipe(serialized, require_dist.decodeUnknownEither(require_dist.parseJson(SnapshotSchema)), require_dist.mapLeft((err) => new OtherWalletError$1(err)), require_dist.flatMap$4((snapshot) => require_dist.pipe(assertKeyAddressConsistency$1(snapshot.publicKey), require_dist.map$6(() => snapshot))), require_dist.map$6((snapshot) => {
770
+ return CoreWallet$1.restore(UnshieldedState$1.restore(snapshot.state.availableUtxos, snapshot.state.pendingUtxos), snapshot.publicKey, {
771
+ highestTransactionId: snapshot.appliedId ?? 0n,
772
+ appliedId: snapshot.appliedId ?? 0n
773
+ }, require_dist.ProtocolVersion(snapshot.protocolVersion), snapshot.networkId);
774
+ }))
775
+ };
776
+ };
777
+ //#endregion
778
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/SyncSchema.js
779
+ const DateFromMillis$1 = require_dist.transform(require_dist.Number$, require_dist.DateFromSelf, {
780
+ strict: true,
781
+ decode: (millis) => new Date(millis),
782
+ encode: (date) => date.getTime()
783
+ });
784
+ const WireUtxoSchema$1 = require_dist.Struct({
785
+ value: require_dist.SafeBigInt,
786
+ owner: require_dist.String$,
787
+ tokenType: require_dist.String$,
788
+ intentHash: require_dist.String$,
789
+ outputIndex: require_dist.Number$,
790
+ ctime: require_dist.Number$,
791
+ registeredForDustGeneration: require_dist.Boolean$
792
+ });
793
+ const UtxoWithMetaSchema$1 = require_dist.transform(WireUtxoSchema$1, require_dist.typeSchema(require_dist.Struct({
794
+ utxo: require_dist.Struct({
795
+ value: require_dist.BigIntSchema,
796
+ owner: require_dist.String$,
797
+ type: require_dist.String$,
798
+ intentHash: require_dist.String$,
799
+ outputNo: require_dist.Number$
800
+ }),
801
+ meta: require_dist.Struct({
802
+ ctime: require_dist.DateFromSelf,
803
+ registeredForDustGeneration: require_dist.Boolean$
804
+ })
805
+ })), {
806
+ strict: true,
807
+ decode: (wire) => ({
808
+ utxo: {
809
+ value: wire.value,
810
+ owner: wire.owner,
811
+ type: wire.tokenType,
812
+ intentHash: wire.intentHash,
813
+ outputNo: wire.outputIndex
814
+ },
815
+ meta: {
816
+ ctime: /* @__PURE__ */ new Date(wire.ctime * 1e3),
817
+ registeredForDustGeneration: wire.registeredForDustGeneration
818
+ }
819
+ }),
820
+ encode: (domain) => ({
821
+ value: domain.utxo.value,
822
+ owner: domain.utxo.owner,
823
+ tokenType: domain.utxo.type,
824
+ intentHash: domain.utxo.intentHash,
825
+ outputIndex: domain.utxo.outputNo,
826
+ ctime: Math.floor(domain.meta.ctime.getTime() / 1e3),
827
+ registeredForDustGeneration: domain.meta.registeredForDustGeneration
828
+ })
829
+ });
830
+ const UnshieldedTransactionSchema$1 = require_dist.Data(require_dist.Struct({
831
+ id: require_dist.Number$,
832
+ hash: require_dist.String$,
833
+ type: require_dist.Literal("RegularTransaction", "SystemTransaction", "BridgeClaimTransaction"),
834
+ protocolVersion: require_dist.Number$,
835
+ identifiers: require_dist.optional(require_dist.Array$(require_dist.String$)),
836
+ block: require_dist.Struct({
837
+ hash: require_dist.String$,
838
+ height: require_dist.Number$,
839
+ timestamp: DateFromMillis$1
840
+ }),
841
+ fees: require_dist.optional(require_dist.Struct({
842
+ paidFees: require_dist.SafeBigInt,
843
+ estimatedFees: require_dist.SafeBigInt
844
+ })),
845
+ transactionResult: require_dist.optional(require_dist.Struct({
846
+ status: require_dist.Literal("SUCCESS", "FAILURE", "PARTIAL_SUCCESS"),
847
+ segments: require_dist.NullOr(require_dist.Array$(require_dist.Struct({
848
+ id: require_dist.Number$,
849
+ success: require_dist.Boolean$
850
+ })))
851
+ }))
852
+ }));
853
+ const UnshieldedUpdateWireSchema$1 = require_dist.Struct({
854
+ type: require_dist.Literal("UnshieldedTransaction"),
855
+ transaction: UnshieldedTransactionSchema$1,
856
+ createdUtxos: require_dist.Array$(UtxoWithMetaSchema$1),
857
+ spentUtxos: require_dist.Array$(UtxoWithMetaSchema$1)
858
+ });
859
+ const UnshieldedUpdateSchema$1 = require_dist.transform(UnshieldedUpdateWireSchema$1, require_dist.typeSchema(require_dist.Struct({
860
+ type: require_dist.Literal("UnshieldedTransaction"),
861
+ transaction: UnshieldedTransactionSchema$1,
862
+ createdUtxos: require_dist.Array$(require_dist.typeSchema(UtxoWithMetaSchema$1)),
863
+ spentUtxos: require_dist.Array$(require_dist.typeSchema(UtxoWithMetaSchema$1)),
864
+ status: require_dist.Literal("SUCCESS", "FAILURE", "PARTIAL_SUCCESS")
865
+ })), {
866
+ strict: true,
867
+ decode: (wire) => {
868
+ const isStatusImplicitlySuccess = ["SystemTransaction", "BridgeClaimTransaction"].includes(wire.transaction.type);
869
+ return {
870
+ ...wire,
871
+ status: isStatusImplicitlySuccess ? "SUCCESS" : wire.transaction.transactionResult.status
872
+ };
873
+ },
874
+ encode: ({ status: _status, ...rest }) => rest
875
+ });
876
+ const ProgressSchema$1 = require_dist.Struct({
877
+ type: require_dist.Literal("UnshieldedTransactionsProgress"),
878
+ highestTransactionId: require_dist.Number$,
879
+ protocolVersion: require_dist.Number$
880
+ });
881
+ const WalletSyncUpdateSchema$1 = require_dist.Union(UnshieldedUpdateSchema$1, ProgressSchema$1);
882
+ const VersionSignalSyncUpdate$1 = { create: (version, highestTransactionId) => {
883
+ return {
884
+ type: "VersionSignal",
885
+ version,
886
+ highestTransactionId
887
+ };
888
+ } };
889
+ //#endregion
890
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/Sync.js
891
+ /**
892
+ * Whether a reported protocol version belongs to a variant later than the one owning `activeRange`.
893
+ *
894
+ * @remarks
895
+ * Unshielded sync is message-at-a-time, so this is the whole of the boundary rule — there is no batch to split into an
896
+ * applied prefix and a deferred suffix, only a yes/no per message. Exported so the indexer and simulator sync
897
+ * capabilities cannot drift apart on the question.
898
+ * @param version The protocol version the source reported for this message.
899
+ * @param activeRange The running variant's half-open activation range.
900
+ * @returns `true` when the message must be left unapplied.
901
+ */
902
+ const isBeyondActiveRange$1 = (version, activeRange) => BigInt(version) >= activeRange[1];
903
+ /**
904
+ * Records an observed protocol version on the state, monotonically.
905
+ *
906
+ * @remarks
907
+ * This is the only thing written when a message is deferred at the boundary, and it is what the runtime watches to
908
+ * decide that the variant must hand over.
909
+ * @param state The state to annotate.
910
+ * @param version The protocol version the source reported.
911
+ * @returns The state carrying the higher of the two versions.
912
+ */
913
+ const annotateVersion$1 = (state, version) => CoreWallet$1.withProtocolVersion(state, require_dist.ProtocolVersion(BigInt(version)));
914
+ /**
915
+ * Splits the chain's protocol version off a progress frame, into a signal of its own.
916
+ *
917
+ * @remarks
918
+ * This is how a wallet nobody pays learns that the chain moved. Ordinarily a version reaches it on a transaction it was
919
+ * served, and it is served only the transactions that touch its own address — so on a chain that crosses a protocol
920
+ * boundary and then pays this address nothing, it would observe no version at all and stay on the variant it was
921
+ * running, with everything built through it routed to that variant's ledger. The progress arm has no such silence:
922
+ * the indexer emits it before its first sleep and keeps emitting it, on an address the chain has never mentioned
923
+ * exactly as on a busy one, and it states the version at the chain's tip.
924
+ *
925
+ * Split off rather than folded in place, because the two things a frame says are governed by different rules. Progress
926
+ * is bookkeeping and always applies. A version may be recorded only when the wallet is level with the far end of this
927
+ * address's timeline, or the hand-over would park the sync cursor in front of history that the next variant would
928
+ * then apply without ever having seen what led to it. Keeping the signal a message of its own leaves that gate
929
+ * exactly where the capability already implements it — and the frame states both halves in one indexed instant, so
930
+ * the version can no longer be read against a timeline end that moved between two separate answers.
931
+ *
932
+ * Two frames are worth no signal. Zero is the source reporting that it has indexed no block yet, not a chain at version
933
+ * zero; read as a version it would be a claim nobody made. And a version at or below the one the wallet already held
934
+ * could only ever be a no-op, because the recorded version never goes backwards — suppressing it is what keeps a
935
+ * settled wallet's progress frames from putting a redundant message on the stream for the rest of its life.
936
+ * @param update The decoded subscription message.
937
+ * @param knownVersion The version the wallet held when this stream opened — a lower bound on what it holds now.
938
+ * @returns The message, followed by the signal when the frame carries a version worth recording.
939
+ */
940
+ const withVersionSignal$1 = (update, knownVersion) => update.type === "UnshieldedTransactionsProgress" && update.protocolVersion !== 0 && BigInt(update.protocolVersion) > knownVersion ? [update, VersionSignalSyncUpdate$1.create(update.protocolVersion, update.highestTransactionId)] : [update];
941
+ const makeDefaultSyncService$1 = (config) => {
942
+ return { updates: (state) => {
943
+ const { indexerClientConnection } = config;
944
+ const webSocketUrlResult = require_dist.createWebSocketUrl(indexerClientConnection.indexerHttpUrl, indexerClientConnection.indexerWsUrl);
945
+ if (require_dist.isLeft(webSocketUrlResult)) return require_dist.fail(new SyncWalletError$1(/* @__PURE__ */ new Error(`Could not derive WebSocket URL from indexer HTTP URL: ${webSocketUrlResult.left.message}`)));
946
+ const indexerWsUrlResult = require_dist.make(webSocketUrlResult.right);
947
+ if (require_dist.isLeft(indexerWsUrlResult)) return require_dist.fail(new SyncWalletError$1(/* @__PURE__ */ new Error(`Invalid indexer WS URL: ${indexerWsUrlResult.left.message}`)));
948
+ const indexerWsUrl = indexerWsUrlResult.right;
949
+ const { appliedId } = state.progress;
950
+ const { address } = state.publicKey;
951
+ return require_dist.pipe(require_dist.UnshieldedTransactions.run({
952
+ address,
953
+ transactionId: Number(appliedId)
954
+ }), require_dist.provideLayer(require_dist.layer({
955
+ url: indexerWsUrl,
956
+ keepAlive: indexerClientConnection.keepAlive
957
+ })), require_dist.mapError((error) => new SyncWalletError$1(error)), require_dist.mapEffect((subscription) => {
958
+ const { unshieldedTransactions } = subscription;
959
+ return require_dist.pipe(require_dist.decodeUnknownEither(WalletSyncUpdateSchema$1)(unshieldedTransactions), require_dist.mapLeft((err) => new SyncWalletError$1(err)), require_dist.toEffect);
960
+ }), require_dist.mapConcat((update) => withVersionSignal$1(update, state.protocolVersion)));
961
+ } };
962
+ };
963
+ /**
964
+ * Folds a version signal: records the chain's version, and nothing else.
965
+ *
966
+ * @remarks
967
+ * The same recording the transaction path makes through {@link annotateVersion}: no cursor moves, no UTXO changes hands.
968
+ * A signal is an observation about the chain, not a piece of it.
969
+ *
970
+ * One situation makes the observation unsafe to record, and it leaves the state exactly as it was. A transaction still
971
+ * unapplied below the address's tip means the hand-over would park the cursor in front of history the next variant
972
+ * would then apply without ever having seen what led to it — and that transaction carries the version itself, so
973
+ * nothing is lost by waiting for it. That is not an error: the next tick asks again.
974
+ *
975
+ * A version at or below the one already recorded needs no guard of its own — `annotateVersion` never goes backwards —
976
+ * so a source briefly answering from a lagging replica cannot drag a wallet back over a boundary.
977
+ * @param state The wallet to record on.
978
+ * @param signal What the chain said, and how far this address's timeline goes.
979
+ * @returns The wallet, annotated or untouched.
980
+ */
981
+ const applyVersionSignal$1 = (state, signal) => require_dist.right(BigInt(signal.highestTransactionId) > state.progress.appliedId ? state : annotateVersion$1(state, signal.version));
982
+ /**
983
+ * Folds a progress frame: moves the far end of the cursor, and nothing else.
984
+ *
985
+ * @remarks
986
+ * A progress message reports how far the source has got with this address, not a transaction. The chain version it also
987
+ * carries is deliberately not read here: the source splits that off into its own `VersionSignal`, which is the only
988
+ * message allowed to annotate, and which alone carries the gate in {@link applyVersionSignal}. Annotating from both
989
+ * places would put the gate on one route and not the other.
990
+ * @param state The wallet to record on.
991
+ * @param progress The frame.
992
+ * @returns The wallet with the far end of its cursor moved and marked connected.
993
+ */
994
+ const applyProgress$1 = (state, progress) => require_dist.right(CoreWallet$1.updateProgress(state, {
995
+ highestTransactionId: BigInt(progress.highestTransactionId),
996
+ isConnected: true
997
+ }));
998
+ /**
999
+ * Classifies a delivered transaction; {@link applyTransaction} acts on the answer.
1000
+ *
1001
+ * @remarks
1002
+ * "Is this past the cursor?" is the only ordering question askable here. The id is the indexer's global transaction id
1003
+ * filtered to this address, so a wallet is served a strictly increasing but SPARSE subsequence of it — consecutive
1004
+ * deliveries routinely skip whole runs of ids belonging to other addresses — and demanding contiguity would reject
1005
+ * every honest stream. What a gap cannot hide is a spend whose create was never folded: `UnshieldedState` refuses a
1006
+ * spend of a UTXO it holds in neither map, and that refusal, not this classification, is what catches a spend
1007
+ * delivered ahead of its create. It happens before the cursor moves, so the retry re-fetches the pair in order.
1008
+ *
1009
+ * Whether the resume cursor the subscription is opened with is inclusive is undocumented, so the transaction it names
1010
+ * may or may not reappear on a reconnect; calling an equal id `redelivered` makes the fold indifferent either way,
1011
+ * exactly as the shielded and dust wallets treat their own boundary event.
1012
+ * @param state The wallet the transaction was delivered to.
1013
+ * @param update The delivered transaction.
1014
+ * @param activeRange The half-open protocol version range the running variant owns.
1015
+ * @returns The placement.
1016
+ */
1017
+ const placeTransaction$1 = (state, update, activeRange) => {
1018
+ const received = BigInt(update.transaction.id);
1019
+ const cursor = state.progress.appliedId;
1020
+ return received < cursor ? "replayed" : received === cursor ? "redelivered" : isBeyondActiveRange$1(update.transaction.protocolVersion, activeRange) ? "deferred" : "applicable";
1021
+ };
1022
+ /**
1023
+ * Folds an applicable transaction: the UTXO changes, then the cursor, the history record and the version.
1024
+ *
1025
+ * @remarks
1026
+ * The history is written only once the fold has succeeded, so a rejected transaction leaves no trace there either.
1027
+ * @param state The wallet to fold into.
1028
+ * @param update The delivered transaction.
1029
+ * @param getContext Where the transaction history lives.
1030
+ * @returns The folded wallet, or the fold's refusal.
1031
+ */
1032
+ const foldTransaction$1 = (state, update, getContext) => {
1033
+ const payload = {
1034
+ createdUtxos: update.createdUtxos,
1035
+ spentUtxos: update.spentUtxos,
1036
+ status: update.status
1037
+ };
1038
+ return (update.status === "FAILURE" ? CoreWallet$1.applyFailedUpdate(state, payload) : CoreWallet$1.applyUpdate(state, payload)).pipe(require_dist.map$6((wallet) => {
1039
+ const advanced = CoreWallet$1.updateProgress(wallet, { appliedId: BigInt(update.transaction.id) });
1040
+ require_dist.runFork(getContext().transactionHistoryService.put(update));
1041
+ return annotateVersion$1(advanced, update.transaction.protocolVersion);
1042
+ }));
1043
+ };
1044
+ /**
1045
+ * Folds a delivered transaction according to its {@link TransactionPlacement}.
1046
+ *
1047
+ * @remarks
1048
+ * - `replayed` is refused with {@link OutOfOrderSyncUpdateError} and nothing is applied: folding a create twice resurrects
1049
+ * a UTXO some later transaction has since spent; folding a spend twice removes one some later transaction
1050
+ * re-created. The state is handed back untouched so the retry can re-fetch in order.
1051
+ * - `redelivered` is a no-op in the strongest sense — the same state comes back: no UTXO change, no cursor movement, no
1052
+ * version annotation, no transaction-history write. All of that was done the first time it arrived.
1053
+ * - `deferred` is the hand-over point. The transaction belongs to the next variant, so NOTHING about it is applied; only
1054
+ * the version is recorded, which is what makes the runtime migrate. Because the cursor did not move, the next
1055
+ * variant re-fetches this very transaction and applies it exactly once.
1056
+ * - `applicable` is folded by {@link foldTransaction}.
1057
+ *
1058
+ * @param state The wallet the transaction was delivered to.
1059
+ * @param update The delivered transaction.
1060
+ * @param activeRange The half-open protocol version range the running variant owns.
1061
+ * @param getContext Where the transaction history lives.
1062
+ * @returns The next wallet, or the refusal.
1063
+ */
1064
+ const applyTransaction$1 = (state, update, activeRange, getContext) => value(placeTransaction$1(state, update, activeRange)).pipe(when("replayed", () => require_dist.left(new OutOfOrderSyncUpdateError$1({
1065
+ message: `Sync source delivered transaction ${update.transaction.id}, below the applied cursor ${state.progress.appliedId}; the state is left untouched so the retry can re-fetch in order`,
1066
+ expected: state.progress.appliedId,
1067
+ received: BigInt(update.transaction.id)
1068
+ }))), when("redelivered", () => require_dist.right(state)), when("deferred", () => require_dist.right(annotateVersion$1(state, update.transaction.protocolVersion))), when("applicable", () => foldTransaction$1(state, update, getContext)), exhaustive);
1069
+ const makeDefaultSyncCapability$1 = (_config, getContext) => {
1070
+ return { applyUpdate: (state, update, activeRange) => value(update).pipe(discriminatorsExhaustive("type")({
1071
+ VersionSignal: (signal) => applyVersionSignal$1(state, signal),
1072
+ UnshieldedTransactionsProgress: (progress) => applyProgress$1(state, progress),
1073
+ UnshieldedTransaction: (transaction) => applyTransaction$1(state, transaction, activeRange, getContext)
1074
+ })) };
1075
+ };
1076
+ //#endregion
1077
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/TransactionOps.js
1078
+ /**
1079
+ * Asserts that `signature` shares the scheme of every input owner authorized in `segment`. Pure and synchronous: a
1080
+ * mismatch short-circuits with a typed `SchemeMismatchError` so a wrong-scheme signature is never attached.
1081
+ */
1082
+ const assertSignatureMatchesSegmentOwners = (transaction, segment, signature) => {
1083
+ const intent = transaction.intents?.get(segment);
1084
+ const owners = [...intent?.guaranteedUnshieldedOffer?.inputs ?? [], ...intent?.fallibleUnshieldedOffer?.inputs ?? []].map((input) => input.owner);
1085
+ const seed = require_dist.right(signature);
1086
+ return require_dist.pipe(owners, require_dist.reduce(seed, (acc, owner) => require_dist.flatMap$4(acc, () => assertSignatureMatchesKey(owner, signature))));
1087
+ };
1088
+ const TransactionOps$1 = {
1089
+ getSignatureData(tx, segment) {
1090
+ if (!tx.intents) return require_dist.left(new TransactingError$1({ message: "Transaction has no intents" }));
1091
+ const intent = tx.intents.get(segment);
1092
+ if (!intent) return require_dist.left(new TransactingError$1({ message: `Intent with segment ${segment} was not found` }));
1093
+ return require_dist.try_$1({
1094
+ try: () => intent.signatureData(segment),
1095
+ catch: (error) => new TransactingError$1({
1096
+ message: "Failed to get offer signature data",
1097
+ cause: error
1098
+ })
1099
+ });
1100
+ },
1101
+ getSegments(transaction) {
1102
+ return transaction.intents?.keys().toArray() ?? [];
1103
+ },
1104
+ findAvailableSegmentId(transaction) {
1105
+ const used = new Set(transaction.intents?.keys() ?? []);
1106
+ return require_dist.pipe(require_dist.range(1, 65535), require_dist.findFirst$1((segmentId) => !used.has(segmentId)));
1107
+ },
1108
+ addSignature(transaction, signature, segment) {
1109
+ return require_dist.gen$1(function* () {
1110
+ if (!transaction.intents || transaction.intents.size === 0) return yield* require_dist.left(new TransactingError$1({ message: "No intents found in the transaction" }));
1111
+ const intent = transaction.intents?.get(segment);
1112
+ if (!intent) return yield* require_dist.left(new TransactingError$1({ message: `Intent with id ${segment} was not found` }));
1113
+ if (TransactionOps$1.isIntentBound(intent)) return yield* require_dist.left(new TransactingError$1({ message: `Intent at segment ${segment} is already bound` }));
1114
+ if (intent.fallibleUnshieldedOffer) intent.fallibleUnshieldedOffer = yield* TransactionOps$1.addSignaturesToOffer(intent.fallibleUnshieldedOffer, signature, segment, "fallible");
1115
+ if (intent.guaranteedUnshieldedOffer) intent.guaranteedUnshieldedOffer = yield* TransactionOps$1.addSignaturesToOffer(intent.guaranteedUnshieldedOffer, signature, segment, "guaranteed");
1116
+ transaction.intents = transaction.intents.set(segment, intent);
1117
+ return transaction;
1118
+ });
1119
+ },
1120
+ collectSignableData(transaction) {
1121
+ return require_dist.all$1(TransactionOps$1.getSegments(transaction).map((segment) => require_dist.map$6(TransactionOps$1.getSignatureData(transaction, segment), (data) => ({
1122
+ segment,
1123
+ data
1124
+ }))));
1125
+ },
1126
+ attachSignatures(transaction, signatures) {
1127
+ return require_dist.gen$1(function* () {
1128
+ yield* require_dist.all$1(signatures.map(({ segment, signature }) => assertSignatureMatchesSegmentOwners(transaction, segment, signature)));
1129
+ const seed = require_dist.right(transaction);
1130
+ return yield* require_dist.pipe(signatures, require_dist.reduce(seed, (acc, { segment, signature }) => require_dist.flatMap$4(acc, (tx) => TransactionOps$1.addSignature(tx, signature, segment))));
1131
+ });
1132
+ },
1133
+ getImbalances(transaction, segment) {
1134
+ const imbalances = transaction.imbalances(segment).entries().filter(([token, value]) => token.tag === "unshielded" && value !== 0n).map(([token, value]) => [token.raw.toString(), value]).toArray();
1135
+ return require_dist.Imbalances.fromEntries(imbalances);
1136
+ },
1137
+ addSignaturesToOffer(offer, signature, segment, offerType) {
1138
+ return require_dist.pipe(offer.inputs, require_dist.map$3((_, i) => offer.signatures.at(i) ?? new _midnightntwrk_ledger_v9.SignatureEnabled(signature)), (signatures) => require_dist.try_$1({
1139
+ try: () => offer.addSignatures(signatures),
1140
+ catch: (error) => new TransactingError$1({
1141
+ message: `Failed to add ${offerType} signature at segment ${segment}`,
1142
+ cause: error
1143
+ })
1144
+ }));
1145
+ },
1146
+ isIntentBound(intent) {
1147
+ return intent.binding.instance === "binding";
1148
+ },
1149
+ extractOwnInputs(transaction, signatureVerifyingKey) {
1150
+ const segments = TransactionOps$1.getSegments(transaction);
1151
+ const ownerAddress = (0, _midnightntwrk_ledger_v9.addressFromKey)(signatureVerifyingKey);
1152
+ const isOwn = (input) => input.owner.tag === signatureVerifyingKey.tag && input.owner.value === signatureVerifyingKey.value;
1153
+ const toUtxo = (input) => ({
1154
+ ...input,
1155
+ owner: ownerAddress
1156
+ });
1157
+ return require_dist.pipe(segments, require_dist.flatMap$2((segment) => {
1158
+ const intent = transaction.intents?.get(segment);
1159
+ if (!intent) return [];
1160
+ const { guaranteedUnshieldedOffer, fallibleUnshieldedOffer } = intent;
1161
+ const ownedInputsfromGuaranteedSection = guaranteedUnshieldedOffer?.inputs ? guaranteedUnshieldedOffer.inputs.filter(isOwn) : [];
1162
+ const ownedInputsfromFallibleSection = fallibleUnshieldedOffer ? fallibleUnshieldedOffer.inputs.filter(isOwn) : [];
1163
+ return [...ownedInputsfromGuaranteedSection, ...ownedInputsfromFallibleSection].map(toUtxo);
1164
+ }));
1165
+ }
1166
+ };
1167
+ //#endregion
1168
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/Transacting.js
1169
+ const GUARANTEED_SEGMENT$1 = 0;
1170
+ const makeDefaultTransactingCapability$1 = (config, getContext) => {
1171
+ return new TransactingCapabilityImplementation$1(config.networkId, () => getContext().coinSelection, () => getContext().coinsAndBalancesCapability, () => getContext().keysCapability, TransactionOps$1);
1172
+ };
1173
+ var TransactingCapabilityImplementation$1 = class {
1174
+ networkId;
1175
+ getCoinSelection;
1176
+ txOps;
1177
+ getCoins;
1178
+ getKeys;
1179
+ constructor(networkId, getCoinSelection, getCoins, getKeys, txOps) {
1180
+ this.getCoins = getCoins;
1181
+ this.networkId = networkId;
1182
+ this.getCoinSelection = getCoinSelection;
1183
+ this.getKeys = getKeys;
1184
+ this.txOps = txOps;
1185
+ }
1186
+ /**
1187
+ * Balances an unbound transaction Note: Unbound transactions are balanced in place and returned
1188
+ *
1189
+ * @param wallet - The wallet to balance the transaction with
1190
+ * @param transaction - The transaction to balance
1191
+ * @returns The balanced transaction and the new wallet state if successful, otherwise an error
1192
+ */
1193
+ balanceUnboundTransaction(wallet, transaction) {
1194
+ return this.#balanceUnboundishTransaction(wallet, transaction);
1195
+ }
1196
+ /**
1197
+ * Balances an unproven transaction Note: This method does the same thing as balanceUnboundTransaction but is provided
1198
+ * for convenience and type safety
1199
+ *
1200
+ * @param wallet - The wallet to balance the transaction with
1201
+ * @param transaction - The transaction to balance
1202
+ * @returns The balanced transaction and the new wallet state if successful, otherwise an error
1203
+ */
1204
+ balanceUnprovenTransaction(wallet, transaction) {
1205
+ return this.#balanceUnboundishTransaction(wallet, transaction);
1206
+ }
1207
+ /**
1208
+ * Balances a bound transaction Note: In bound transactions we can only balance the guaranteed section in intents
1209
+ *
1210
+ * @param wallet - The wallet to balance the transaction with
1211
+ * @param transaction - The transaction to balance
1212
+ * @returns A balancing counterpart transaction (which should be merged with the original transaction ) and the new
1213
+ * wallet state if successful, otherwise an error
1214
+ */
1215
+ balanceFinalizedTransaction(wallet, transaction) {
1216
+ return require_dist.gen$1(this, function* () {
1217
+ const segments = this.txOps.getSegments(transaction);
1218
+ for (const segment of segments) {
1219
+ const intent = transaction.intents?.get(segment);
1220
+ if (!this.txOps.isIntentBound(intent)) return yield* require_dist.left(new TransactingError$1({ message: `Intent with id ${segment} is not bound` }));
1221
+ }
1222
+ const intent = transaction.intents?.get(segments[0]);
1223
+ const imbalances = this.txOps.getImbalances(transaction, GUARANTEED_SEGMENT$1);
1224
+ if (imbalances.size === 0) return [void 0, wallet];
1225
+ const recipe = yield* this.#balanceSegment(wallet, imbalances, require_dist.Imbalances.empty(), this.getCoinSelection());
1226
+ const { newState, offer } = yield* this.#prepareOffer(wallet, recipe);
1227
+ const balancingIntent = _midnightntwrk_ledger_v9.Intent.new(intent.ttl);
1228
+ balancingIntent.guaranteedUnshieldedOffer = offer;
1229
+ const segmentId = require_dist.getOrElse(this.txOps.findAvailableSegmentId(transaction), () => 1);
1230
+ return [_midnightntwrk_ledger_v9.Transaction.fromParts(this.networkId).addIntent({
1231
+ tag: "specific",
1232
+ value: segmentId
1233
+ }, balancingIntent), newState];
1234
+ });
1235
+ }
1236
+ /**
1237
+ * Makes a transfer transaction
1238
+ *
1239
+ * @param wallet - The wallet to make the transfer with
1240
+ * @param outputs - The outputs for the transfer
1241
+ * @param ttl - The TTL for the transaction
1242
+ * @returns The balanced transfer transaction and the new wallet state if successful, otherwise an error
1243
+ */
1244
+ makeTransfer(wallet, outputs, ttl) {
1245
+ return require_dist.gen$1(this, function* () {
1246
+ const { networkId } = this;
1247
+ if (!outputs.every((output) => output.amount > 0n)) return yield* require_dist.left(new TransactingError$1({ message: "The amount of all inputs needs to be positive" }));
1248
+ const ledgerOutputs = outputs.map((output) => {
1249
+ return {
1250
+ value: output.amount,
1251
+ owner: output.receiverAddress.data.toString("hex"),
1252
+ type: output.type
1253
+ };
1254
+ });
1255
+ const recipe = yield* this.#balanceSegment(wallet, require_dist.Imbalances.empty(), require_dist.Imbalances.fromEntries(ledgerOutputs.map((output) => [output.type, output.value])), this.getCoinSelection());
1256
+ const { newState, offer } = yield* this.#prepareOffer(wallet, {
1257
+ inputs: recipe.inputs,
1258
+ outputs: [...recipe.outputs, ...ledgerOutputs]
1259
+ });
1260
+ const intent = _midnightntwrk_ledger_v9.Intent.new(ttl);
1261
+ if (ledgerOutputs.some((output) => output.type === require_dist.Token.night)) intent.fallibleUnshieldedOffer = offer;
1262
+ else intent.guaranteedUnshieldedOffer = offer;
1263
+ return {
1264
+ newState,
1265
+ transaction: _midnightntwrk_ledger_v9.Transaction.fromParts(networkId, void 0, void 0, intent)
1266
+ };
1267
+ });
1268
+ }
1269
+ rotateUtxos(wallet, guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl) {
1270
+ return require_dist.gen$1(this, function* () {
1271
+ const { networkId } = this;
1272
+ if (guaranteedUtxos.length === 0 && fallibleUtxos.length === 0) return yield* require_dist.left(new TransactingError$1({ message: "At least one UTxO must be provided to rotateUtxos" }));
1273
+ const ownerAddress = _midnightntwrk_ledger_v9.addressFromKey(nightVerifyingKey);
1274
+ const makeOffer = (utxos) => {
1275
+ if (utxos.length === 0) return require_dist.none();
1276
+ const inputs = utxos.map(({ utxo }) => ({
1277
+ value: utxo.value,
1278
+ type: utxo.type,
1279
+ intentHash: utxo.intentHash,
1280
+ outputNo: utxo.outputNo,
1281
+ owner: nightVerifyingKey
1282
+ }));
1283
+ const totalValue = require_dist.pipe(utxos, require_dist.map$3(({ utxo }) => utxo.value), require_dist.reduce(0n, (a, b) => a + b));
1284
+ const output = {
1285
+ owner: ownerAddress,
1286
+ type: require_dist.Token.night,
1287
+ value: totalValue
1288
+ };
1289
+ return require_dist.some(_midnightntwrk_ledger_v9.UnshieldedOffer.new(inputs, [output], []));
1290
+ };
1291
+ const allUtxos = [...guaranteedUtxos, ...fallibleUtxos].map(({ utxo }) => utxo);
1292
+ const [, walletAfterBooking] = yield* CoreWallet$1.spendUtxos(wallet, allUtxos);
1293
+ const guaranteedOffer = makeOffer(guaranteedUtxos);
1294
+ const fallibleOffer = makeOffer(fallibleUtxos);
1295
+ const intent = require_dist.pipe(_midnightntwrk_ledger_v9.Intent.new(ttl), (i) => require_dist.match$1(guaranteedOffer, {
1296
+ onNone: () => i,
1297
+ onSome: (offer) => {
1298
+ i.guaranteedUnshieldedOffer = offer;
1299
+ return i;
1300
+ }
1301
+ }), (i) => require_dist.match$1(fallibleOffer, {
1302
+ onNone: () => i,
1303
+ onSome: (offer) => {
1304
+ i.fallibleUnshieldedOffer = offer;
1305
+ return i;
1306
+ }
1307
+ }));
1308
+ return {
1309
+ newState: walletAfterBooking,
1310
+ transaction: _midnightntwrk_ledger_v9.Transaction.fromParts(networkId, void 0, void 0, intent)
1311
+ };
1312
+ });
1313
+ }
1314
+ /**
1315
+ * Initializes a swap transaction
1316
+ *
1317
+ * @param wallet - The wallet to initialize the swap for
1318
+ * @param desiredInputs - The desired inputs for the swap
1319
+ * @param desiredOutputs - The desired outputs for the swap
1320
+ * @param ttl - The TTL for the swap
1321
+ * @returns The initialized swap transaction and the new wallet state if successful, otherwise an error
1322
+ */
1323
+ initSwap(wallet, desiredInputs, desiredOutputs, ttl) {
1324
+ return require_dist.gen$1(this, function* () {
1325
+ const { networkId } = this;
1326
+ if (!desiredOutputs.every((output) => output.amount > 0n)) return yield* require_dist.left(new TransactingError$1({ message: "The amount of all outputs needs to be positive" }));
1327
+ if (!Object.entries(desiredInputs).every(([, amount]) => amount > 0n)) return yield* require_dist.left(new TransactingError$1({ message: "The amount of all inputs needs to be positive" }));
1328
+ const ledgerOutputs = desiredOutputs.map((output) => ({
1329
+ value: output.amount,
1330
+ owner: output.receiverAddress.data.toString("hex"),
1331
+ type: output.type
1332
+ }));
1333
+ const targetImbalances = require_dist.Imbalances.fromEntries(Object.entries(desiredInputs));
1334
+ const recipe = yield* this.#balanceSegment(wallet, require_dist.Imbalances.empty(), targetImbalances, this.getCoinSelection());
1335
+ const { newState, offer } = yield* this.#prepareOffer(wallet, {
1336
+ inputs: recipe.inputs,
1337
+ outputs: [...recipe.outputs, ...ledgerOutputs]
1338
+ });
1339
+ const intent = _midnightntwrk_ledger_v9.Intent.new(ttl);
1340
+ intent.guaranteedUnshieldedOffer = offer;
1341
+ return {
1342
+ newState,
1343
+ transaction: _midnightntwrk_ledger_v9.Transaction.fromParts(networkId, void 0, void 0, intent)
1344
+ };
1345
+ });
1346
+ }
1347
+ /**
1348
+ * Reverts a transaction by rolling back all inputs owned by this wallet
1349
+ *
1350
+ * @param wallet - The wallet to revert the transaction for
1351
+ * @param transaction - The transaction to revert (can be FinalizedTransaction, UnboundTransaction, or
1352
+ * UnprovenTransaction)
1353
+ * @returns The updated wallet with rolled back UTXOs if successful, otherwise an error
1354
+ */
1355
+ revertTransaction(wallet, transaction) {
1356
+ return require_dist.pipe(this.txOps.extractOwnInputs(transaction, wallet.publicKey.publicKey), require_dist.reduce(require_dist.right(wallet), (walletAcc, utxo) => require_dist.pipe(walletAcc, require_dist.flatMap$4((w) => CoreWallet$1.rollbackUtxo(w, utxo)))));
1357
+ }
1358
+ /**
1359
+ * Balances a segment of a transaction
1360
+ *
1361
+ * @param wallet - The wallet to balance the segment for
1362
+ * @param imbalances - The imbalances to balance the segment for
1363
+ * @param targetImbalances - The target imbalances to balance the segment for
1364
+ * @param coinSelection - The coin selection to use for the balance recipe
1365
+ * @returns The balance recipe if successful, otherwise an error
1366
+ */
1367
+ #balanceSegment(wallet, imbalances, targetImbalances, coinSelection) {
1368
+ return require_dist.try_$1({
1369
+ try: () => require_dist.getBalanceRecipe({
1370
+ coins: this.getCoins().getAvailableCoins(wallet).map(({ utxo }) => utxo),
1371
+ initialImbalances: imbalances,
1372
+ feeTokenType: "",
1373
+ transactionCostModel: {
1374
+ inputFeeOverhead: 0n,
1375
+ outputFeeOverhead: 0n
1376
+ },
1377
+ coinSelection,
1378
+ createOutput: (coin) => ({
1379
+ ...coin,
1380
+ owner: wallet.publicKey.addressHex
1381
+ }),
1382
+ isCoinEqual: (a, b) => a.intentHash === b.intentHash && a.outputNo === b.outputNo,
1383
+ targetImbalances
1384
+ }),
1385
+ catch: (err) => {
1386
+ if (err instanceof require_dist.InsufficientFundsError) return new InsufficientFundsError$1({
1387
+ message: "Insufficient funds",
1388
+ tokenType: err.tokenType,
1389
+ amount: imbalances.get(err.tokenType) ?? 0n
1390
+ });
1391
+ else return new OtherWalletError$1({
1392
+ message: "Balancing unshielded segment failed",
1393
+ cause: err
1394
+ });
1395
+ }
1396
+ });
1397
+ }
1398
+ /**
1399
+ * Prepares an offer for a given balance recipe
1400
+ *
1401
+ * @param wallet - The wallet to prepare the offer for
1402
+ * @param balanceRecipe - The balance recipe to prepare the offer for
1403
+ * @returns The prepared offer and the new wallet state if successful, otherwise an error
1404
+ */
1405
+ #prepareOffer(wallet, balanceRecipe) {
1406
+ return require_dist.gen$1(function* () {
1407
+ const [spentInputs, updatedWallet] = yield* CoreWallet$1.spendUtxos(wallet, balanceRecipe.inputs);
1408
+ const { publicKey } = wallet.publicKey;
1409
+ const ledgerInputs = spentInputs.map((input) => ({
1410
+ ...input,
1411
+ intentHash: input.intentHash,
1412
+ owner: publicKey
1413
+ }));
1414
+ return {
1415
+ newState: updatedWallet,
1416
+ offer: yield* require_dist.try_$1({
1417
+ try: () => _midnightntwrk_ledger_v9.UnshieldedOffer.new(ledgerInputs, [...balanceRecipe.outputs], []),
1418
+ catch: (error) => new TransactingError$1({
1419
+ message: "Failed to create counter offer",
1420
+ cause: error
1421
+ })
1422
+ })
1423
+ };
1424
+ });
1425
+ }
1426
+ #mergeOffers(offerA, offerB) {
1427
+ return require_dist.pipe(require_dist.fromNullable(offerB), require_dist.match$1({
1428
+ onNone: () => require_dist.right(offerA),
1429
+ onSome: (offerB) => require_dist.try_$1({
1430
+ try: () => _midnightntwrk_ledger_v9.UnshieldedOffer.new([...offerB.inputs, ...offerA.inputs], [...offerB.outputs, ...offerA.outputs], [...offerB.signatures, ...offerA.signatures]),
1431
+ catch: (error) => new TransactingError$1({
1432
+ message: "Failed to merge offers",
1433
+ cause: error
1434
+ })
1435
+ })
1436
+ }));
1437
+ }
1438
+ /**
1439
+ * Balances an unboundish (unproven or unbound) transaction
1440
+ *
1441
+ * @param wallet - The wallet to balance the transaction with
1442
+ * @param transaction - The transaction to balance
1443
+ * @returns The balanced transaction and the new wallet state if successful, otherwise an error
1444
+ * @todo - https://shielded.atlassian.net/browse/PM-21260
1445
+ */
1446
+ #balanceUnboundishTransaction(wallet, transaction) {
1447
+ return require_dist.gen$1(this, function* () {
1448
+ const segments = this.txOps.getSegments(transaction);
1449
+ if (segments.length === 0) return [void 0, wallet];
1450
+ for (const segment of [...segments, GUARANTEED_SEGMENT$1]) {
1451
+ const imbalances = this.txOps.getImbalances(transaction, segment);
1452
+ if (imbalances.size === 0) continue;
1453
+ const intentSegment = segment === GUARANTEED_SEGMENT$1 ? segments[0] : segment;
1454
+ const intent = transaction.intents?.get(intentSegment);
1455
+ if (!intent) return yield* require_dist.left(new TransactingError$1({ message: `Intent with id ${segment} was not found` }));
1456
+ if (this.txOps.isIntentBound(intent)) return yield* require_dist.left(new TransactingError$1({ message: `Intent with id ${segment} is already bound` }));
1457
+ const recipe = yield* this.#balanceSegment(wallet, imbalances, require_dist.Imbalances.empty(), this.getCoinSelection());
1458
+ const { offer } = yield* this.#prepareOffer(wallet, recipe);
1459
+ const targetOffer = segment !== GUARANTEED_SEGMENT$1 ? intent.fallibleUnshieldedOffer : intent.guaranteedUnshieldedOffer;
1460
+ const mergedOffer = yield* this.#mergeOffers(offer, targetOffer);
1461
+ if (segment !== GUARANTEED_SEGMENT$1) intent.fallibleUnshieldedOffer = mergedOffer;
1462
+ else intent.guaranteedUnshieldedOffer = mergedOffer;
1463
+ transaction.intents = transaction.intents.set(intentSegment, intent);
1464
+ }
1465
+ return [transaction, wallet];
1466
+ });
1467
+ }
1468
+ };
1469
+ //#endregion
1470
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/KeyStore.js
1471
+ require__polyfill_buffer_patch.init__polyfill_buffer_patch();
1472
+ const PublicKey = { fromKeyStore: (keystore) => {
1473
+ return {
1474
+ publicKey: keystore.getPublicKey(),
1475
+ addressHex: keystore.getAddress(),
1476
+ address: keystore.getBech32Address().asString()
1477
+ };
1478
+ } };
1479
+ const createKeystore = (secretKey, networkId) => {
1480
+ const ledgerSigningKey = {
1481
+ tag: secretKey.kind,
1482
+ value: require__polyfill_buffer_patch.import_buffer.Buffer.from(secretKey.secret).toString("hex")
1483
+ };
1484
+ const keystore = {
1485
+ getSecretKey: () => require__polyfill_buffer_patch.import_buffer.Buffer.from(secretKey.secret),
1486
+ getBech32Address: () => {
1487
+ const address = keystore.getAddress();
1488
+ const addressBuffer = require__polyfill_buffer_patch.import_buffer.Buffer.from(address, "hex");
1489
+ return require_dist.UnshieldedAddress.codec.encode(networkId, new require_dist.UnshieldedAddress(addressBuffer));
1490
+ },
1491
+ getPublicKey: () => (0, _midnightntwrk_ledger_v9.signatureVerifyingKey)(ledgerSigningKey),
1492
+ getAddress: () => (0, _midnightntwrk_ledger_v9.addressFromKey)(keystore.getPublicKey()),
1493
+ signData: (data) => (0, _midnightntwrk_ledger_v9.signData)(ledgerSigningKey, data),
1494
+ signDataAsync: (data) => Promise.resolve(keystore.signData(data))
1495
+ };
1496
+ return keystore;
1497
+ };
1498
+ //#endregion
1499
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/Migration.js
1500
+ /**
1501
+ * The migration used when there is no previous wallet at all.
1502
+ *
1503
+ * @remarks
1504
+ * It backs `WalletLike.startEmpty`, which builds a wallet before any key material exists. The resulting state has no
1505
+ * UTXOs and a public key derived from a fixed placeholder seed; it is a scaffold to be replaced by a real start, not
1506
+ * a wallet anybody can transact with. Preserved verbatim from the ledger-v8 implementation so that `startEmpty`
1507
+ * behaves exactly as it did.
1508
+ * @example
1509
+ * ```typescript
1510
+ * const builder = new V2Builder().withDefaults().withMigration(makeEmptyWalletMigration({ networkId }));
1511
+ * ```;
1512
+ *
1513
+ * @param configuration Supplies the network the scaffold state claims to be on.
1514
+ * @returns A migration from `null`.
1515
+ */
1516
+ const makeEmptyWalletMigration$1 = (configuration) => ({ migrate: () => {
1517
+ const seed = require_dist.fromString("0000000000000000000000000000000000000000000000000000000000000001");
1518
+ return require_dist.succeed(CoreWallet$1.init(PublicKey.fromKeyStore(createKeystore({
1519
+ kind: "schnorr",
1520
+ secret: seed
1521
+ }, configuration.networkId)), configuration.networkId));
1522
+ } });
1523
+ /**
1524
+ * The migration across a ledger-version boundary: a structural carry of everything the wallet holds, all of it
1525
+ * spendable.
1526
+ *
1527
+ * @remarks
1528
+ * This is where unshielded parts company with shielded and dust. Those two start the new variant on a **fresh, empty**
1529
+ * state and let the indexer's ledger-v9 replay hand their coins back, because their coins are shielded: re-deriving
1530
+ * them means decrypting events with secret keys that migration, by design, never receives. Unshielded has no such
1531
+ * problem. Its UTXOs are public ledger data that the wallet holds as plain records, so they can simply be rebuilt on
1532
+ * the other side — no replay to wait for, no keys required, and no window in which the wallet reports a zero balance
1533
+ * it does not have.
1534
+ *
1535
+ * So every UTXO crosses, field for field, along with the address, the network, and the protocol version that triggered
1536
+ * the hand-over. **Bookings do not.** A UTXO the previous variant had reserved for a transaction still in flight is
1537
+ * restored as _available_, and the new state crosses with nothing pending, because the transaction that reserved it
1538
+ * cannot exist on this side: the transaction codec moved at the boundary, so a transaction built by the previous
1539
+ * ledger version can never be included in a ledger-v9 block. A booking exists only to stop a UTXO being spent twice
1540
+ * while its transaction might still land, and past the boundary it never can — its reason expires at the boundary
1541
+ * itself. Carrying one over would lock those funds for the wallet's lifetime instead: nothing on this side can
1542
+ * un-book them, because the transaction that would identify them is unreadable to this ledger version, and the
1543
+ * booking outlives serialization.
1544
+ *
1545
+ * Releasing is **exact** here rather than merely eventually consistent. The hand-over fires only once the previous
1546
+ * variant has applied the complete ledger-v8 timeline: a transaction the source reports at or beyond the boundary is
1547
+ * left entirely unapplied and only annotates the version, so everything before it is already folded in, and the
1548
+ * version signal a quiet chain hands over on is recorded only when the wallet is caught up on its own transaction
1549
+ * ids. A ledger-v8 transaction that did land has therefore already confirmed by the time this runs — clearing its own
1550
+ * bookings as it was applied — and whatever is still booked belongs to a transaction that never will land. Even if an
1551
+ * unapplied ledger-v8 event were somehow to reach the new variant afterwards, the release stays safe rather than
1552
+ * merely lucky: {@link UnshieldedState.applyUpdate} removes a confirmed spend from **both** maps, so a
1553
+ * released-then-confirmed UTXO leaves the available set exactly as if it had never been released.
1554
+ *
1555
+ * The one transformation is the verifying key, which gains the scheme tag that ledger-v9 requires and ledger-v8 had no
1556
+ * room for — the same widening the deserializer already performs on legacy snapshots, which is where the `schnorr`
1557
+ * default comes from: ledger-v8 had exactly one signature scheme, so a key that reaches here can only have been a
1558
+ * schnorr key.
1559
+ *
1560
+ * Sync progress is carried **unchanged** — parked, not rewound and not advanced. The boundary transaction was observed
1561
+ * and annotated but deliberately never applied, so the cursor still points just before it; the new variant re-fetches
1562
+ * it from there and applies it exactly once. Rewinding to zero would re-apply history the wallet already holds;
1563
+ * advancing past it would lose the boundary transaction outright.
1564
+ * @returns A migration from a previous-ledger-version wallet.
1565
+ */
1566
+ const makeCrossLedgerMigration = () => ({ migrate: (previousState) => require_dist.succeed(CoreWallet$1.restore(UnshieldedState$1.restore([...Array.from(require_dist.values(previousState.state.availableUtxos), carryUtxo), ...Array.from(require_dist.values(previousState.state.pendingUtxos), carryUtxo)], []), {
1567
+ publicKey: {
1568
+ tag: "schnorr",
1569
+ value: previousState.publicKey.publicKey
1570
+ },
1571
+ addressHex: previousState.publicKey.addressHex,
1572
+ address: previousState.publicKey.address
1573
+ }, {
1574
+ appliedId: previousState.progress.appliedId,
1575
+ highestTransactionId: previousState.progress.highestTransactionId
1576
+ }, require_dist.ProtocolVersion(previousState.protocolVersion), previousState.networkId)) });
1577
+ /**
1578
+ * Rebuilds a previous-version UTXO as one of this version's, field for field — save one.
1579
+ *
1580
+ * @remarks
1581
+ * `registeredForDustGeneration` crosses as `false` rather than as whatever the previous version reported, because the
1582
+ * fork wipes the ledger's Dust generation state outright and its chain-side replay restores generation for
1583
+ * cNIGHT-backed Night only. The node's own fork test states the consequence for everything else: "the fork wipes dust
1584
+ * state ... the registration funds itself from the retroactive DUST its now-generationless NIGHT accrued"
1585
+ * (`util/toolkit/tests/hardfork_e2e.rs`, step 5c).
1586
+ *
1587
+ * The crossing is the only place the wallet's copy of the flag can be brought in line. The indexer reports it as of the
1588
+ * current Dust epoch at read time, so a fresh sync after the v9 fork reads `false` — but it never re-emits a UTxO the
1589
+ * wallet already synced on ledger-v8 with `true`, and there is no ledger-v9 event that would revise it. Flipping it
1590
+ * here is what makes a carried UTxO say what the indexer would say of it today.
1591
+ *
1592
+ * Known limitation: cNIGHT-backed Night _is_ restored chain-side, and reads `false` here until a later sync-time update
1593
+ * says otherwise. It fails closed — a registration built over it claims a fee allowance the ledger does not grant and
1594
+ * is refused rather than mis-submitted.
1595
+ */
1596
+ const carryUtxo = (carried) => new UtxoWithMeta({
1597
+ utxo: {
1598
+ value: carried.utxo.value,
1599
+ owner: carried.utxo.owner,
1600
+ type: carried.utxo.type,
1601
+ intentHash: carried.utxo.intentHash,
1602
+ outputNo: carried.utxo.outputNo
1603
+ },
1604
+ meta: {
1605
+ ctime: carried.meta.ctime,
1606
+ registeredForDustGeneration: false
1607
+ }
1608
+ });
1609
+ //#endregion
1610
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/Signing.js
1611
+ /**
1612
+ * The default signing service: collect each segment's signable data (pure), invoke the async signer once per segment
1613
+ * (sequentially — segment counts are tiny), then attach the signatures (pure, with scheme validation). A signer
1614
+ * rejection or throw is wrapped in a {@link SignError}; a scheme mismatch short-circuits inside `attachSignatures`
1615
+ * before anything is attached, so no partially-signed transaction can escape.
1616
+ */
1617
+ const makeDefaultSigningService$1 = () => ({ sign(transaction, signSegment) {
1618
+ return require_dist.gen(function* () {
1619
+ const segments = yield* require_dist.toEffect(TransactionOps$1.collectSignableData(transaction));
1620
+ const signatures = yield* require_dist.forEach(segments, (segment) => require_dist.pipe(require_dist.tryPromise({
1621
+ try: () => signSegment(segment.data),
1622
+ catch: (cause) => new SignError$1({
1623
+ message: "Signer callback failed",
1624
+ cause
1625
+ })
1626
+ }), require_dist.map$2((signature) => ({
1627
+ segment: segment.segment,
1628
+ signature
1629
+ }))));
1630
+ return yield* require_dist.toEffect(TransactionOps$1.attachSignatures(transaction, signatures));
1631
+ });
1632
+ } });
1633
+ //#endregion
1634
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/CoinsAndBalances.js
1635
+ const calculateBalances$1 = (utxos) => utxos.reduce((acc, { utxo }) => ({
1636
+ ...acc,
1637
+ [utxo.type]: acc[utxo.type] === void 0 ? utxo.value : acc[utxo.type] + utxo.value
1638
+ }), {});
1639
+ const makeDefaultCoinsAndBalancesCapability$1 = () => {
1640
+ const getAvailableBalances = (state) => {
1641
+ return calculateBalances$1(getAvailableCoins(state));
1642
+ };
1643
+ const getPendingBalances = (state) => {
1644
+ return calculateBalances$1(getPendingCoins(state));
1645
+ };
1646
+ const getTotalBalances = (state) => {
1647
+ return require_dist.pipe([getAvailableBalances(state), getPendingBalances(state)], require_dist.mergeWithAccumulator(0n, (a, b) => a + b));
1648
+ };
1649
+ const getAvailableCoins = (state) => UnshieldedState$1.toArrays(state.state).availableUtxos;
1650
+ const getPendingCoins = (state) => UnshieldedState$1.toArrays(state.state).pendingUtxos;
1651
+ const getTotalCoins = (state) => [...getAvailableCoins(state), ...getPendingCoins(state)];
1652
+ return {
1653
+ getAvailableBalances,
1654
+ getPendingBalances,
1655
+ getTotalBalances,
1656
+ getAvailableCoins,
1657
+ getPendingCoins,
1658
+ getTotalCoins
1659
+ };
1660
+ };
1661
+ //#endregion
1662
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/Keys.js
1663
+ require__polyfill_buffer_patch.init__polyfill_buffer_patch();
1664
+ const makeDefaultKeysCapability$1 = () => {
1665
+ return {
1666
+ getPublicKey: (state) => {
1667
+ return state.publicKey.publicKey;
1668
+ },
1669
+ getAddress: (state) => {
1670
+ return new require_dist.UnshieldedAddress(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKey.addressHex, "hex"));
1671
+ }
1672
+ };
1673
+ };
1674
+ //#endregion
1675
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/TransactionHistory.js
1676
+ const UtxoSchema$1 = require_dist.Struct({
1677
+ value: require_dist.SafeBigInt,
1678
+ owner: require_dist.String$,
1679
+ tokenType: require_dist.String$,
1680
+ intentHash: require_dist.String$,
1681
+ outputIndex: require_dist.Number$
1682
+ });
1683
+ const UnshieldedSectionSchema = require_dist.Struct({
1684
+ id: require_dist.Number$,
1685
+ createdUtxos: require_dist.Array$(UtxoSchema$1),
1686
+ spentUtxos: require_dist.Array$(UtxoSchema$1)
1687
+ });
1688
+ const mergeUnshieldedSections = (existing, incoming) => ({
1689
+ ...existing,
1690
+ ...incoming
1691
+ });
1692
+ require_dist.extendEntrySchema({ unshielded: require_dist.optional(UnshieldedSectionSchema) });
1693
+ const convertUpdateToFinalizedInput$1 = ({ transaction, createdUtxos, spentUtxos, status }) => ({
1694
+ hash: transaction.hash,
1695
+ protocolVersion: transaction.protocolVersion,
1696
+ status,
1697
+ identifiers: transaction.identifiers ?? [],
1698
+ timestamp: transaction.block.timestamp,
1699
+ finalizedBlock: {
1700
+ hash: transaction.block.hash,
1701
+ height: transaction.block.height,
1702
+ timestamp: transaction.block.timestamp
1703
+ },
1704
+ unshielded: {
1705
+ id: transaction.id,
1706
+ createdUtxos: createdUtxos.map(({ utxo }) => ({
1707
+ value: utxo.value,
1708
+ owner: utxo.owner,
1709
+ tokenType: utxo.type,
1710
+ intentHash: utxo.intentHash,
1711
+ outputIndex: utxo.outputNo
1712
+ })),
1713
+ spentUtxos: spentUtxos.map(({ utxo }) => ({
1714
+ value: utxo.value,
1715
+ owner: utxo.owner,
1716
+ tokenType: utxo.type,
1717
+ intentHash: utxo.intentHash,
1718
+ outputIndex: utxo.outputNo
1719
+ }))
1720
+ }
1721
+ });
1722
+ const makeDefaultTransactionHistoryService$1 = (config, _getContext) => {
1723
+ const txHistoryStorage = config.txHistoryStorage;
1724
+ return { put: (update) => require_dist.tryPromise({
1725
+ try: () => txHistoryStorage.gotFinalized(convertUpdateToFinalizedInput$1(update)),
1726
+ catch: (e) => new TransactionHistoryError$1({
1727
+ message: "Failed to record finalized history entry",
1728
+ cause: e
1729
+ })
1730
+ }) };
1731
+ };
1732
+ //#endregion
1733
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v2/V2Builder.js
1734
+ var V2Builder = class V2Builder {
1735
+ #buildState;
1736
+ constructor(buildState = {}) {
1737
+ this.#buildState = buildState;
1738
+ }
1739
+ withDefaults() {
1740
+ return this.withSyncDefaults().withSerializationDefaults().withTransactingDefaults().withSigningDefaults().withCoinsAndBalancesDefaults().withTransactionHistoryDefaults().withKeysDefaults().withCoinSelectionDefaults();
1741
+ }
1742
+ withSyncDefaults() {
1743
+ return this.withSync(makeDefaultSyncService$1, makeDefaultSyncCapability$1);
1744
+ }
1745
+ withSync(syncService, syncCapability) {
1746
+ return new V2Builder({
1747
+ ...this.#buildState,
1748
+ syncService,
1749
+ syncCapability
1750
+ });
1751
+ }
1752
+ withSerializationDefaults() {
1753
+ return this.withSerialization(makeDefaultV2SerializationCapability);
1754
+ }
1755
+ withSerialization(serializationCapability) {
1756
+ return new V2Builder({
1757
+ ...this.#buildState,
1758
+ serializationCapability
1759
+ });
1760
+ }
1761
+ withTransactingDefaults() {
1762
+ return this.withTransacting(makeDefaultTransactingCapability$1);
1763
+ }
1764
+ withTransacting(transactingCapability) {
1765
+ return new V2Builder({
1766
+ ...this.#buildState,
1767
+ transactingCapability
1768
+ });
1769
+ }
1770
+ withSigningDefaults() {
1771
+ return this.withSigning(makeDefaultSigningService$1);
1772
+ }
1773
+ withSigning(signingService) {
1774
+ return new V2Builder({
1775
+ ...this.#buildState,
1776
+ signingService
1777
+ });
1778
+ }
1779
+ /**
1780
+ * Configures this variant to start from an empty wallet when there is nothing before it.
1781
+ *
1782
+ * @remarks
1783
+ * The default for a first-registered variant, and what `startEmpty` relies on.
1784
+ * @returns A builder whose previous state is `null`.
1785
+ */
1786
+ withMigrationDefaults() {
1787
+ return this.withMigration((configuration) => makeEmptyWalletMigration$1({ networkId: configuration.networkId }));
1788
+ }
1789
+ /**
1790
+ * Configures how this variant produces its first state from whatever variant preceded it.
1791
+ *
1792
+ * @remarks
1793
+ * The context is a method-level type parameter rather than the builder's own `TContext`, matching `withSync` and
1794
+ * `withKeys` in this file. Binding it to the builder's `TContext` would make the builder invariant in it and break
1795
+ * the partially-configured chains the tests build.
1796
+ * @param migration Produces the strategy from the configuration and the variant context.
1797
+ * @returns A builder whose previous state is whatever the strategy consumes.
1798
+ */
1799
+ withMigration(migration) {
1800
+ const { migration: _replaced, ...capabilities } = this.#buildState;
1801
+ return new V2Builder({
1802
+ ...capabilities,
1803
+ migration
1804
+ });
1805
+ }
1806
+ withCoinSelection(coinSelection) {
1807
+ return new V2Builder({
1808
+ ...this.#buildState,
1809
+ coinSelection
1810
+ });
1811
+ }
1812
+ withCoinSelectionDefaults() {
1813
+ return this.withCoinSelection(() => require_dist.chooseCoin);
1814
+ }
1815
+ withCoinsAndBalancesDefaults() {
1816
+ return this.withCoinsAndBalances(makeDefaultCoinsAndBalancesCapability$1);
1817
+ }
1818
+ withCoinsAndBalances(coinsAndBalancesCapability) {
1819
+ return new V2Builder({
1820
+ ...this.#buildState,
1821
+ coinsAndBalancesCapability
1822
+ });
1823
+ }
1824
+ withTransactionHistoryDefaults() {
1825
+ return this.withTransactionHistory(makeDefaultTransactionHistoryService$1);
1826
+ }
1827
+ withTransactionHistory(transactionHistoryService) {
1828
+ return new V2Builder({
1829
+ ...this.#buildState,
1830
+ transactionHistoryService
1831
+ });
1832
+ }
1833
+ withKeysDefaults() {
1834
+ return this.withKeys(makeDefaultKeysCapability$1);
1835
+ }
1836
+ withKeys(keysCapability) {
1837
+ return new V2Builder({
1838
+ ...this.#buildState,
1839
+ keysCapability
1840
+ });
1841
+ }
1842
+ build(configuration) {
1843
+ const v2Context = this.#buildContextFromBuildState(configuration);
1844
+ const migration = this.#resolveMigration(configuration, () => v2Context);
1845
+ return {
1846
+ __polyTag__: V2Tag,
1847
+ coinsAndBalances: v2Context.coinsAndBalancesCapability,
1848
+ keys: v2Context.keysCapability,
1849
+ serialization: v2Context.serializationCapability,
1850
+ transactionHistory: v2Context.transactionHistoryService,
1851
+ start(context) {
1852
+ return require_dist.gen(function* () {
1853
+ return new RunningV2Variant(yield* require_dist.Scope, context, v2Context);
1854
+ });
1855
+ },
1856
+ migrateState(previousState) {
1857
+ return migration.migrate(previousState).pipe(require_dist.mapError$2((error) => new require_dist.WalletRuntimeError({
1858
+ message: "Failed to migrate unshielded wallet state into this variant",
1859
+ cause: error
1860
+ })));
1861
+ },
1862
+ deserializeState: (serialized) => {
1863
+ return v2Context.serializationCapability.deserialize(serialized);
1864
+ }
1865
+ };
1866
+ }
1867
+ /**
1868
+ * The migration strategy to build with.
1869
+ *
1870
+ * @remarks
1871
+ * An unconfigured builder produces an empty wallet, which is what `startEmpty` asks of a first variant. The nullary
1872
+ * wrapper is what lets the `null`-consuming default stand in for a `TPreviousState`-consuming strategy without a
1873
+ * cast: the argument is simply not passed on.
1874
+ */
1875
+ #resolveMigration(configuration, getContext) {
1876
+ const configured = this.#buildState.migration;
1877
+ return configured === void 0 ? { migrate: () => makeEmptyWalletMigration$1({ networkId: configuration.networkId }).migrate(null) } : configured(configuration, getContext);
1878
+ }
1879
+ #buildContextFromBuildState(configuration) {
1880
+ if (!isBuildStateFull$1(this.#buildState)) throw new Error("Not all components are configured in V2 Builder");
1881
+ const { syncCapability, syncService, transactingCapability, signingService, serializationCapability, coinSelection, coinsAndBalancesCapability, keysCapability, transactionHistoryService } = this.#buildState;
1882
+ const getContext = () => context;
1883
+ const context = {
1884
+ serializationCapability: serializationCapability(configuration, getContext),
1885
+ syncCapability: syncCapability(configuration, getContext),
1886
+ syncService: syncService(configuration, getContext),
1887
+ transactingCapability: transactingCapability(configuration, getContext),
1888
+ signingService: signingService(configuration, getContext),
1889
+ coinsAndBalancesCapability: coinsAndBalancesCapability(configuration, getContext),
1890
+ keysCapability: keysCapability(configuration, getContext),
1891
+ coinSelection: coinSelection(configuration, getContext),
1892
+ transactionHistoryService: transactionHistoryService(configuration, getContext)
1893
+ };
1894
+ return context;
1895
+ }
1896
+ };
1897
+ const isBuildStateFull$1 = (buildState) => {
1898
+ return [
1899
+ "syncService",
1900
+ "syncCapability",
1901
+ "transactingCapability",
1902
+ "signingService",
1903
+ "coinSelection",
1904
+ "serializationCapability",
1905
+ "coinsAndBalancesCapability",
1906
+ "keysCapability",
1907
+ "transactionHistoryService"
1908
+ ].every((key) => typeof buildState[key] == "function");
1909
+ };
1910
+ //#endregion
1911
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/SingleVariantUnshieldedWallet.js
1912
+ function CustomUnshieldedWallet(configuration, builder) {
1913
+ const buildArgs = [configuration];
1914
+ const BaseWallet = require_dist.WalletBuilder.init().withVariant(require_dist.MinSupportedVersion, builder).build(...buildArgs);
1915
+ /** The whole of the protocol timeline: one variant answers for every version this wallet will ever see. */
1916
+ const wholeTimeline = require_dist.epochOf(require_dist.MinSupportedVersion, require_dist.MinSupportedVersion);
1917
+ /** Reads a transaction a caller handed in, which a single-variant wallet accepts at any version. */
1918
+ const carried = (handle) => require_dist.toEffect(require_dist.WalletTransaction.unwrapWithin(handle, wholeTimeline));
1919
+ /** Seals a transaction this wallet built, at the version its one variant answers from. */
1920
+ const seal = (transaction) => require_dist.WalletTransaction.adopt("Unproven", transaction, require_dist.MinSupportedVersion);
1921
+ const sealUnproven = (result) => result === void 0 ? void 0 : seal(result);
1922
+ const sealUnbound = (result) => result === void 0 ? void 0 : require_dist.WalletTransaction.adopt("Unbound", result, require_dist.MinSupportedVersion);
1923
+ return class CustomUnshieldedWalletImplementation extends BaseWallet {
1924
+ static startWithPublicKey(publicKeys) {
1925
+ return CustomUnshieldedWalletImplementation.startFirst(CustomUnshieldedWalletImplementation, CoreWallet$1.init(publicKeys, configuration.networkId));
1926
+ }
1927
+ static restore(serializedState) {
1928
+ const deserialized = CustomUnshieldedWalletImplementation.allVariantsRecord()[V2Tag].variant.deserializeState(serializedState).pipe(require_dist.getOrThrow$1);
1929
+ return CustomUnshieldedWalletImplementation.startFirst(CustomUnshieldedWalletImplementation, deserialized);
1930
+ }
1931
+ state;
1932
+ constructor(runtime, scope) {
1933
+ super(runtime, scope);
1934
+ this.state = this.rawState.pipe(rxjs.map((emission) => UnshieldedWalletState.fromVariant(CustomUnshieldedWalletImplementation.allVariantsRecord()[V2Tag].variant, emission)), rxjs.shareReplay({
1935
+ refCount: true,
1936
+ bufferSize: 1
1937
+ }));
1938
+ }
1939
+ /**
1940
+ * Whether the activation watcher has been registered.
1941
+ *
1942
+ * @remarks
1943
+ * Registration is per wallet, not per `start`: watchers accumulate, so registering on every call would restart sync
1944
+ * once per historical `start` on the next activation. Flipped with `getAndSet` so concurrent `start` calls cannot
1945
+ * both observe it unset.
1946
+ */
1947
+ #watcherRegistered = require_dist.unsafeMake(false);
1948
+ /**
1949
+ * Whether the wallet is currently started.
1950
+ *
1951
+ * @remarks
1952
+ * The unshielded counterpart of the retained start-aux the shielded and dust wallets hold. This wallet is
1953
+ * watch-only — sync needs nothing secret, and signing is supplied per call by the caller — so there is no key to
1954
+ * keep and the restart needs no argument. All the watcher has to know is whether a stopped wallet should be left
1955
+ * stopped, which is what this records; `stop` clears it so a stopped wallet cannot be resurrected by a late
1956
+ * activation.
1957
+ */
1958
+ #started = require_dist.unsafeMake(false);
1959
+ start() {
1960
+ return require_dist.gen(this, function* () {
1961
+ yield* require_dist.set(this.#started, true);
1962
+ if (!(yield* require_dist.getAndSet(this.#watcherRegistered, true))) yield* this.runtime.onVariantActivation({ [V2Tag]: (v2) => require_dist.get$1(this.#started).pipe(require_dist.flatMap$1((started) => started ? v2.startSyncInBackground() : require_dist._void)) });
1963
+ yield* this.runtime.dispatch({ [V2Tag]: (v2) => v2.startSyncInBackground() });
1964
+ }).pipe(require_dist.runPromise$1);
1965
+ }
1966
+ async stop() {
1967
+ require_dist.set(this.#started, false).pipe(require_dist.runSync);
1968
+ await super.stop();
1969
+ }
1970
+ balanceFinalizedTransaction(tx) {
1971
+ return this.runtime.dispatch({ [V2Tag]: (v2) => carried(tx).pipe(require_dist.flatMap$1((unwrapped) => v2.balanceFinalizedTransaction(unwrapped)), require_dist.map$2(sealUnproven)) }).pipe(require_dist.runPromise$1);
1972
+ }
1973
+ balanceUnboundTransaction(tx) {
1974
+ return this.runtime.dispatch({ [V2Tag]: (v2) => carried(tx).pipe(require_dist.flatMap$1((unwrapped) => v2.balanceUnboundTransaction(unwrapped)), require_dist.map$2(sealUnbound)) }).pipe(require_dist.runPromise$1);
1975
+ }
1976
+ balanceUnprovenTransaction(tx) {
1977
+ return this.runtime.dispatch({ [V2Tag]: (v2) => carried(tx).pipe(require_dist.flatMap$1((unwrapped) => v2.balanceUnprovenTransaction(unwrapped)), require_dist.map$2(sealUnproven)) }).pipe(require_dist.runPromise$1);
1978
+ }
1979
+ transferTransaction(outputs, ttl) {
1980
+ return this.runtime.dispatch({ [V2Tag]: (v2) => v2.transferTransaction(outputs, ttl).pipe(require_dist.map$2(seal)) }).pipe(require_dist.runPromise$1);
1981
+ }
1982
+ rotateUtxos(guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl) {
1983
+ return this.runtime.dispatch({ [V2Tag]: (v2) => v2.rotateUtxos(guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl).pipe(require_dist.map$2(seal)) }).pipe(require_dist.runPromise$1);
1984
+ }
1985
+ initSwap(desiredInputs, desiredOutputs, ttl) {
1986
+ return this.runtime.dispatch({ [V2Tag]: (v2) => v2.initSwap(desiredInputs, desiredOutputs, ttl).pipe(require_dist.map$2(seal)) }).pipe(require_dist.runPromise$1);
1987
+ }
1988
+ signUnprovenTransaction(transaction, signSegment) {
1989
+ return this.runtime.dispatch({ [V2Tag]: (v2) => carried(transaction).pipe(require_dist.flatMap$1((unwrapped) => v2.signUnprovenTransaction(unwrapped, signSegment)), require_dist.map$2(seal)) }).pipe(require_dist.runPromise$1);
1990
+ }
1991
+ signUnboundTransaction(transaction, signSegment) {
1992
+ return this.runtime.dispatch({ [V2Tag]: (v2) => carried(transaction).pipe(require_dist.flatMap$1((unwrapped) => v2.signUnboundTransaction(unwrapped, signSegment)), require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unbound", tx, require_dist.MinSupportedVersion))) }).pipe(require_dist.runPromise$1);
1993
+ }
1994
+ revertTransaction(transaction) {
1995
+ return this.runtime.dispatch({ [V2Tag]: (v2) => require_dist.match$2(require_dist.WalletTransaction.unwrapWithin(transaction, wholeTimeline), {
1996
+ onLeft: () => require_dist._void,
1997
+ onRight: (unwrapped) => v2.revertTransaction(unwrapped)
1998
+ }) }).pipe(require_dist.runPromise$1);
1999
+ }
2000
+ waitForSyncedState(allowedGap = 0n) {
2001
+ return rxjs.firstValueFrom(this.state.pipe(rxjs.filter((state) => state.state.progress.isCompleteWithin(allowedGap))));
2002
+ }
2003
+ /**
2004
+ * Serializes the most recent state It's preferable to use [[UnshieldedWalletState.serialize]] instead, to know
2005
+ * exactly, which state is serialized
2006
+ */
2007
+ serializeState() {
2008
+ return rxjs.firstValueFrom(this.state).then((state) => state.serialize());
2009
+ }
2010
+ getAddress() {
2011
+ return rxjs.firstValueFrom(this.state).then((state) => state.address);
2012
+ }
2013
+ };
2014
+ }
2015
+ //#endregion
2016
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/Restore.js
2017
+ var Restore_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
2018
+ UnsupportedSnapshotVersionError: () => UnsupportedSnapshotVersionError,
2019
+ peekProtocolVersion: () => peekProtocolVersion,
2020
+ variantForSnapshot: () => variantForSnapshot
2021
+ });
2022
+ /**
2023
+ * Raised when a snapshot declares a protocol version that no registered variant is able to read.
2024
+ *
2025
+ * @remarks
2026
+ * A wallet built for one range of protocol versions cannot invent a reader for a snapshot written outside it, and
2027
+ * guessing — handing the bytes to whichever variant happens to be registered — would decode them with the wrong
2028
+ * ledger. The version is carried on the error so an application can say which one it was.
2029
+ */
2030
+ var UnsupportedSnapshotVersionError = class extends require_dist.TaggedError("@midnightntwrk/wallet-sdk-unshielded-wallet/Restore/UnsupportedSnapshotVersionError") {};
2031
+ /**
2032
+ * The envelope the peek reads.
2033
+ *
2034
+ * @remarks
2035
+ * Deliberately the smallest possible description of a snapshot: one optional field, every other ignored. It has to read
2036
+ * snapshots written by _any_ variant, including ones whose full schema this build does not have, so it must not
2037
+ * assert anything it does not need. Everything it cannot make sense of is reported as "no version declared", leaving
2038
+ * the real diagnosis to the deserializer that eventually reads the whole thing.
2039
+ */
2040
+ const EnvelopeSchema = require_dist.Struct({ protocolVersion: require_dist.optional(require_dist.ProtocolVersionSchema) });
2041
+ /**
2042
+ * Reads the protocol version a serialized unshielded wallet snapshot declares.
2043
+ *
2044
+ * @param serialized The serialized wallet state.
2045
+ * @returns The declared version, or `Option.none()` when the snapshot declares none or cannot be read at all.
2046
+ */
2047
+ const peekProtocolVersion = (serialized) => require_dist.decodeUnknownOption(require_dist.parseJson(EnvelopeSchema))(serialized).pipe(require_dist.flatMap$3((envelope) => require_dist.fromNullable(envelope.protocolVersion)));
2048
+ /**
2049
+ * Chooses the variant that should read a serialized unshielded wallet snapshot.
2050
+ *
2051
+ * @remarks
2052
+ * A snapshot that declares no version predates snapshots declaring one, and can only have been written by the variant
2053
+ * that shipped before the question arose — the head variant. The same fallback covers an envelope this function
2054
+ * cannot read at all: refusing it here would replace the deserializer's precise error with a vaguer one.
2055
+ * @param serialized The serialized wallet state.
2056
+ * @param variantFor Resolves the variant registered for a protocol version.
2057
+ * @param headVariant The variant a snapshot with no declared version is restored into.
2058
+ * @returns The variant to restore with, or {@link UnsupportedSnapshotVersionError} when the declared version is one no
2059
+ * registered variant owns.
2060
+ */
2061
+ const variantForSnapshot = (serialized, variantFor, headVariant) => require_dist.match$1(peekProtocolVersion(serialized), {
2062
+ onNone: () => require_dist.right(headVariant),
2063
+ onSome: (protocolVersion) => require_dist.fromOption(variantFor(protocolVersion), () => new UnsupportedSnapshotVersionError({
2064
+ message: `No registered variant reads unshielded wallet snapshots of protocol version ${protocolVersion}.`,
2065
+ protocolVersion
2066
+ }))
2067
+ });
2068
+ //#endregion
2069
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/RunningV1Variant.js
2070
+ const progress = (state) => {
2071
+ const appliedId = state.progress?.appliedId ?? 0n;
2072
+ const sourceGap = (state.progress?.highestTransactionId ?? 0n) - appliedId;
2073
+ const applyGap = appliedId - appliedId;
2074
+ return [require_dist.ProgressUpdate({
2075
+ sourceGap,
2076
+ applyGap
2077
+ })];
2078
+ };
2079
+ /**
2080
+ * The version signals this variant puts on its state stream.
2081
+ *
2082
+ * @remarks
2083
+ * Two of them, for two different situations. A transition is the ordinary one: the state moved to a version the variant
2084
+ * may or may not own, and the runtime decides. The healing emission covers restore: a snapshot taken between the
2085
+ * moment sync annotated an out-of-range version and the moment the runtime acted on it comes back with a version this
2086
+ * variant does not own and no transition to announce it, so it would sit there forever. Announcing it on the first
2087
+ * observation is what forward-migrates such a snapshot.
2088
+ */
2089
+ const protocolVersionChange = (previous, current, isInitial, activationRange) => {
2090
+ const transitioned = previous.protocolVersion != current.protocolVersion;
2091
+ const strandedOutsideRange = isInitial && !require_dist.withinRange(current.protocolVersion, activationRange);
2092
+ return transitioned || strandedOutsideRange ? [require_dist.VersionChange({ change: require_dist.Version({ version: require_dist.ProtocolVersion(current.protocolVersion) }) })] : [];
2093
+ };
2094
+ const V1Tag = Symbol("V1");
2095
+ var RunningV1Variant = class {
2096
+ __polyTag__ = V1Tag;
2097
+ #scope;
2098
+ #context;
2099
+ #v1Context;
2100
+ state;
2101
+ constructor(scope, context, v1Context) {
2102
+ this.#scope = scope;
2103
+ this.#context = context;
2104
+ this.#v1Context = v1Context;
2105
+ this.state = require_dist.fromEffect(context.stateRef.get).pipe(require_dist.flatMap((initialState) => context.stateRef.changes.pipe(require_dist.mapAccum({
2106
+ previous: initialState,
2107
+ isInitial: true
2108
+ }, (seen, current) => [{
2109
+ previous: current,
2110
+ isInitial: false
2111
+ }, [
2112
+ seen.previous,
2113
+ current,
2114
+ seen.isInitial
2115
+ ]]))), require_dist.mapConcat(([previous, current, isInitial]) => {
2116
+ return [
2117
+ require_dist.State({ state: current }),
2118
+ ...progress(current),
2119
+ ...protocolVersionChange(previous, current, isInitial, context.activationRange)
2120
+ ];
2121
+ }));
2122
+ }
2123
+ startSyncInBackground() {
2124
+ return this.startSync().pipe(require_dist.runScoped(require_dist.drain), require_dist.forkScoped, require_dist.provideService(require_dist.Scope, this.#scope));
2125
+ }
2126
+ startSync() {
2127
+ return require_dist.pipe(require_dist.get(this.#context.stateRef), require_dist.fromEffect, require_dist.flatMap((state) => this.#v1Context.syncService.updates(state)), require_dist.mapEffect((update) => {
2128
+ return require_dist.updateEffect(this.#context.stateRef, (state) => require_dist.pipe(this.#v1Context.syncCapability.applyUpdate(state, update, this.#context.activationRange), require_dist.toEffect));
2129
+ }), require_dist.tapError((error$1) => require_dist.error(error$1)), require_dist.retry(require_dist.pipe(require_dist.exponential(require_dist.seconds(1), 2), require_dist.map$1((delay) => {
2130
+ const maxDelay = require_dist.minutes(2);
2131
+ const jitter = require_dist.millis(Math.floor(Math.random() * 1e3));
2132
+ const delayWithJitter = require_dist.toMillis(delay) + require_dist.toMillis(jitter);
2133
+ return require_dist.millis(Math.min(delayWithJitter, require_dist.toMillis(maxDelay)));
2134
+ }))));
2135
+ }
2136
+ balanceFinalizedTransaction(tx) {
2137
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
2138
+ return require_dist.pipe(this.#v1Context.transactingCapability.balanceFinalizedTransaction(state, tx), require_dist.toEffect);
2139
+ });
2140
+ }
2141
+ balanceUnboundTransaction(tx) {
2142
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
2143
+ return require_dist.pipe(this.#v1Context.transactingCapability.balanceUnboundTransaction(state, tx), require_dist.toEffect);
2144
+ });
2145
+ }
2146
+ balanceUnprovenTransaction(tx) {
2147
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
2148
+ return require_dist.pipe(this.#v1Context.transactingCapability.balanceUnprovenTransaction(state, tx), require_dist.toEffect);
2149
+ });
2150
+ }
2151
+ transferTransaction(outputs, ttl) {
2152
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
2153
+ return require_dist.pipe(this.#v1Context.transactingCapability.makeTransfer(state, outputs, ttl), require_dist.toEffect, require_dist.map$2(({ transaction, newState }) => [transaction, newState]));
2154
+ });
2155
+ }
2156
+ rotateUtxos(guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl) {
2157
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
2158
+ return require_dist.pipe(this.#v1Context.transactingCapability.rotateUtxos(state, guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl), require_dist.toEffect, require_dist.map$2(({ transaction, newState }) => [transaction, newState]));
2159
+ });
2160
+ }
2161
+ initSwap(desiredInputs, desiredOutputs, ttl) {
2162
+ return require_dist.modifyEffect(this.#context.stateRef, (state) => {
2163
+ return require_dist.pipe(this.#v1Context.transactingCapability.initSwap(state, desiredInputs, desiredOutputs, ttl), require_dist.map$2(({ transaction, newState }) => [transaction, newState]));
2164
+ });
2165
+ }
2166
+ signUnprovenTransaction(transaction, signSegment) {
2167
+ return this.#v1Context.signingService.sign(transaction, signSegment);
2168
+ }
2169
+ signUnboundTransaction(transaction, signSegment) {
2170
+ return this.#v1Context.signingService.sign(transaction, signSegment);
2171
+ }
2172
+ revertTransaction(transaction) {
2173
+ return require_dist.updateEffect(this.#context.stateRef, (state) => {
2174
+ return require_dist.pipe(this.#v1Context.transactingCapability.revertTransaction(state, transaction), require_dist.toEffect);
2175
+ });
2176
+ }
2177
+ serializeState(state) {
2178
+ return this.#v1Context.serializationCapability.serialize(state);
2179
+ }
2180
+ };
2181
+ //#endregion
2182
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/WalletError.js
2183
+ var OtherWalletError = class extends require_dist.TaggedError("Wallet.Other") {};
2184
+ var SyncWalletError = class extends require_dist.TaggedError("Wallet.Sync") {};
2185
+ var InsufficientFundsError = class extends require_dist.TaggedError("Wallet.InsufficientFunds") {};
2186
+ var TransactingError = class extends require_dist.TaggedError("Wallet.Transacting") {};
2187
+ var SignError = class extends require_dist.TaggedError("Wallet.Sign") {};
2188
+ var ApplyTransactionError = class extends require_dist.TaggedError("Wallet.ApplyTransaction") {};
2189
+ /**
2190
+ * Raised when a sync source delivers a transaction the wallet has already folded — an id strictly below its applied
2191
+ * cursor — so applying it again would double-count the UTXOs that transaction created or spent.
2192
+ *
2193
+ * @remarks
2194
+ * The id a wallet is served is the indexer's global transaction id filtered to this address, so what reaches it is a
2195
+ * strictly increasing but sparse subsequence: "is this past my cursor?" is the only ordering question it can answer,
2196
+ * and contiguity is not one of them. An id EQUAL to the cursor is the resume boundary answered inclusively and folds
2197
+ * to a no-op rather than to this error; only a strictly lower one is a replay.
2198
+ *
2199
+ * Nothing is written when it is produced. The fold hands this back in place of a new state, so the running variant
2200
+ * never writes its `SubscriptionRef`: the wallet keeps the state and the cursor it had, the sync stream fails, and
2201
+ * the retry reopens the subscription at that same unmoved cursor — which is what gives the source the chance to
2202
+ * deliver the timeline in order.
2203
+ * @example
2204
+ * ```ts
2205
+ * import { Either } from 'effect';
2206
+ *
2207
+ * const outcome = capability.applyUpdate(wallet, update, activeRange);
2208
+ * if (Either.isLeft(outcome) && outcome.left._tag === 'Wallet.OutOfOrderSyncUpdate') {
2209
+ * console.warn(`replayed ${outcome.left.received}, already at ${outcome.left.expected}`);
2210
+ * }
2211
+ * ```
2212
+ */
2213
+ var OutOfOrderSyncUpdateError = class extends require_dist.TaggedError("Wallet.OutOfOrderSyncUpdate") {};
2214
+ var RollbackUtxoError = class extends require_dist.TaggedError("Wallet.RollbackUtxo") {};
2215
+ var SpendUtxoError = class extends require_dist.TaggedError("Wallet.SpendUtxo") {};
2216
+ var TransactionHistoryError = class extends require_dist.TaggedError("Wallet.TransactionHistory") {};
2217
+ var UtxoNotFoundError = class extends require_dist.TaggedError("UtxoNotFoundError") {};
2218
+ //#endregion
2219
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/SyncProgress.js
2220
+ const SyncProgress = { isCompleteWithin(data, maxGap = 50n) {
2221
+ const applyLag = BigInt(Math.abs(Number(data.highestTransactionId - data.appliedId)));
2222
+ return data.isConnected && applyLag <= maxGap;
2223
+ } };
2224
+ const createSyncProgress = (params = {}) => {
2225
+ const { appliedId = 0n, highestTransactionId = 0n, isConnected = false } = params;
2226
+ return {
2227
+ appliedId,
2228
+ highestTransactionId,
2229
+ isConnected,
2230
+ isStrictlyComplete() {
2231
+ return SyncProgress.isCompleteWithin(this, 0n);
2232
+ },
2233
+ isCompleteWithin(maxGap) {
2234
+ return SyncProgress.isCompleteWithin(this, maxGap);
2235
+ }
2236
+ };
2237
+ };
2238
+ //#endregion
2239
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/UnshieldedState.js
2240
+ const UtxoHash = (utxo) => `${utxo.intentHash}#${utxo.outputNo}`;
2241
+ /**
2242
+ * The first UTXO an update reports as spent that this state holds in neither map.
2243
+ *
2244
+ * @remarks
2245
+ * A spend naming a UTXO the wallet has never held is not noise to absorb: it is the only observable sign that the
2246
+ * source delivered a spend ahead of the create it consumes. Absorbed, the create arrives afterwards and puts an
2247
+ * already-spent UTXO into the available set, where it will be offered for coin selection and produce a transaction
2248
+ * the chain rejects. Reported, the fold fails before the caller's cursor moves, and the retry re-fetches the pair in
2249
+ * order.
2250
+ * @param state The state the update is being folded into.
2251
+ * @param spentUtxos The UTXOs the update reports as spent.
2252
+ * @returns The first entry the state does not know, or `Option.none()` when every spend names a UTXO it holds.
2253
+ */
2254
+ const firstUnknownSpend = (state, spentUtxos) => require_dist.findFirst(spentUtxos, (spent) => {
2255
+ const hash = UtxoHash(spent.utxo);
2256
+ return !require_dist.has(state.availableUtxos, hash) && !require_dist.has(state.pendingUtxos, hash);
2257
+ });
2258
+ const UnshieldedState = {
2259
+ empty: () => ({
2260
+ availableUtxos: require_dist.empty$1(),
2261
+ pendingUtxos: require_dist.empty$1()
2262
+ }),
2263
+ restore: (availableUtxos, pendingUtxos) => ({
2264
+ availableUtxos: require_dist.fromIterable(availableUtxos.map((utxo) => [UtxoHash(utxo.utxo), utxo])),
2265
+ pendingUtxos: require_dist.fromIterable(pendingUtxos.map((utxo) => [UtxoHash(utxo.utxo), utxo]))
2266
+ }),
2267
+ spend: (state, utxo) => require_dist.gen$1(function* () {
2268
+ const hash = UtxoHash(utxo.utxo);
2269
+ if (!require_dist.has(state.availableUtxos, hash)) return yield* require_dist.left(new UtxoNotFoundError({ utxo: utxo.utxo }));
2270
+ return {
2271
+ availableUtxos: require_dist.remove(state.availableUtxos, hash),
2272
+ pendingUtxos: require_dist.set$1(state.pendingUtxos, hash, utxo)
2273
+ };
2274
+ }),
2275
+ rollbackSpend: (state, utxo) => {
2276
+ const hash = UtxoHash(utxo.utxo);
2277
+ if (!require_dist.has(state.pendingUtxos, hash)) return require_dist.right(state);
2278
+ return require_dist.right({
2279
+ availableUtxos: require_dist.set$1(state.availableUtxos, hash, utxo),
2280
+ pendingUtxos: require_dist.remove(state.pendingUtxos, hash)
2281
+ });
2282
+ },
2283
+ spendByUtxo: (state, utxo) => require_dist.gen$1(function* () {
2284
+ const hash = UtxoHash(utxo);
2285
+ const found = yield* require_dist.fromOption(require_dist.get$2(state.availableUtxos, hash), () => new UtxoNotFoundError({ utxo }));
2286
+ return yield* UnshieldedState.spend(state, found);
2287
+ }),
2288
+ rollbackSpendByUtxo: (state, utxo) => require_dist.pipe(require_dist.get$2(state.pendingUtxos, UtxoHash(utxo)), require_dist.match$1({
2289
+ onNone: () => require_dist.right(state),
2290
+ onSome: (found) => UnshieldedState.rollbackSpend(state, found)
2291
+ })),
2292
+ applyUpdate: (state, update) => require_dist.gen$1(function* () {
2293
+ if (!["SUCCESS", "PARTIAL_SUCCESS"].includes(update.status)) return yield* require_dist.left(new ApplyTransactionError({ message: `Invalid status: ${update.status}` }));
2294
+ const unknownSpend = firstUnknownSpend(state, update.spentUtxos);
2295
+ if (require_dist.isSome(unknownSpend)) return yield* require_dist.left(new UtxoNotFoundError({ utxo: unknownSpend.value.utxo }));
2296
+ return {
2297
+ availableUtxos: require_dist.union$1(require_dist.removeMany(state.availableUtxos, update.spentUtxos.map((utxo) => UtxoHash(utxo.utxo))), require_dist.fromIterable(update.createdUtxos.map((utxo) => [UtxoHash(utxo.utxo), utxo]))),
2298
+ pendingUtxos: require_dist.removeMany(state.pendingUtxos, update.spentUtxos.map((utxo) => UtxoHash(utxo.utxo)))
2299
+ };
2300
+ }),
2301
+ applyFailedUpdate: (state, update) => require_dist.gen$1(function* () {
2302
+ if (update.status !== "FAILURE") return yield* require_dist.left(new ApplyTransactionError({ message: `Invalid status: ${update.status}` }));
2303
+ const unknownSpend = firstUnknownSpend(state, update.spentUtxos);
2304
+ if (require_dist.isSome(unknownSpend)) return yield* require_dist.left(new UtxoNotFoundError({ utxo: unknownSpend.value.utxo }));
2305
+ return {
2306
+ availableUtxos: require_dist.union$1(state.availableUtxos, require_dist.fromIterable(update.spentUtxos.map((utxo) => [UtxoHash(utxo.utxo), utxo]))),
2307
+ pendingUtxos: require_dist.removeMany(state.pendingUtxos, update.spentUtxos.map((utxo) => UtxoHash(utxo.utxo)))
2308
+ };
2309
+ }),
2310
+ toArrays: (state) => ({
2311
+ availableUtxos: require_dist.toValues(state.availableUtxos),
2312
+ pendingUtxos: require_dist.toValues(state.pendingUtxos)
2313
+ })
2314
+ };
2315
+ //#endregion
2316
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/CoreWallet.js
2317
+ const CoreWallet = {
2318
+ init(publicKey, networkId) {
2319
+ return {
2320
+ state: UnshieldedState.empty(),
2321
+ publicKey,
2322
+ protocolVersion: require_dist.MinSupportedVersion,
2323
+ progress: createSyncProgress(),
2324
+ networkId
2325
+ };
2326
+ },
2327
+ restore(state, publicKey, syncProgress, protocolVersion, networkId) {
2328
+ return {
2329
+ state,
2330
+ publicKey,
2331
+ protocolVersion,
2332
+ progress: createSyncProgress(syncProgress),
2333
+ networkId
2334
+ };
2335
+ },
2336
+ updateProgress(wallet, { appliedId, highestTransactionId, isConnected }) {
2337
+ const progress = createSyncProgress({
2338
+ appliedId: appliedId ?? wallet.progress.appliedId,
2339
+ highestTransactionId: highestTransactionId ?? wallet.progress.highestTransactionId,
2340
+ isConnected: isConnected ?? wallet.progress.isConnected
2341
+ });
2342
+ return {
2343
+ ...wallet,
2344
+ progress
2345
+ };
2346
+ },
2347
+ withProtocolVersion(wallet, version) {
2348
+ return version > wallet.protocolVersion ? {
2349
+ ...wallet,
2350
+ protocolVersion: version
2351
+ } : wallet;
2352
+ },
2353
+ applyUpdate(coreWallet, update) {
2354
+ return UnshieldedState.applyUpdate(coreWallet.state, update).pipe(require_dist.map$6((state) => ({
2355
+ ...coreWallet,
2356
+ state
2357
+ })), require_dist.mapLeft((error) => new ApplyTransactionError(error)));
2358
+ },
2359
+ applyFailedUpdate(coreWallet, update) {
2360
+ return UnshieldedState.applyFailedUpdate(coreWallet.state, update).pipe(require_dist.map$6((state) => ({
2361
+ ...coreWallet,
2362
+ state
2363
+ })), require_dist.mapLeft((error) => new ApplyTransactionError(error)));
2364
+ },
2365
+ rollbackUtxo(coreWallet, utxo) {
2366
+ return UnshieldedState.rollbackSpendByUtxo(coreWallet.state, utxo).pipe(require_dist.map$6((state) => ({
2367
+ ...coreWallet,
2368
+ state
2369
+ })), require_dist.mapLeft((error) => new RollbackUtxoError(error)));
2370
+ },
2371
+ spend(coreWallet, utxo) {
2372
+ return UnshieldedState.spendByUtxo(coreWallet.state, utxo).pipe(require_dist.map$6((state) => ({
2373
+ ...coreWallet,
2374
+ state
2375
+ })), require_dist.mapLeft((error) => new SpendUtxoError(error)));
2376
+ },
2377
+ spendUtxos(wallet, utxos) {
2378
+ return require_dist.pipe(utxos, require_dist.reduce(require_dist.right([[], wallet.state]), (acc, utxoToSpend) => acc.pipe(require_dist.flatMap$4(([accUtxos, state]) => UnshieldedState.spendByUtxo(state, utxoToSpend).pipe(require_dist.map$6((nextState) => [accUtxos.concat([utxoToSpend]), nextState]), require_dist.mapLeft((error) => new SpendUtxoError(error)))))), require_dist.map$6(([spentUtxos, state]) => [spentUtxos, {
2379
+ ...wallet,
2380
+ state
2381
+ }]));
2382
+ }
2383
+ };
2384
+ //#endregion
2385
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/Serialization.js
2386
+ /**
2387
+ * Asserts that a {@link PublicKey}'s stored address was really derived from its stored verifying key.
2388
+ *
2389
+ * @remarks
2390
+ * Deserialization is a trust boundary — a snapshot is whatever was handed back to the wallet — and the schema alone
2391
+ * cannot catch a spliced key/address pair, since both fields are well-formed strings either way. Deriving one from
2392
+ * the other is what shows they belong together. Deriving also exercises the ledger's key decoder, which traps in wasm
2393
+ * on a malformed key, so the call is wrapped and the boundary fails closed with a typed error rather than letting an
2394
+ * exception escape.
2395
+ *
2396
+ * The ledger-v9 variant makes the same assertion but reports a mismatch as a `SchemeMismatchError`, naming the
2397
+ * signature scheme the address must have been derived under. Ledger-v8 has a single scheme, so there is no scheme to
2398
+ * name and the mismatch is an ordinary wallet error.
2399
+ * @param publicKey - The public-key bundle read out of a snapshot.
2400
+ * @returns `Right(publicKey)` when the address matches the key; otherwise `Left(OtherWalletError)`.
2401
+ */
2402
+ const assertKeyAddressConsistency = (publicKey) => require_dist.pipe(require_dist.try_$1({
2403
+ try: () => (0, _midnight_ntwrk_ledger_v8.addressFromKey)(publicKey.publicKey),
2404
+ catch: (cause) => new OtherWalletError({
2405
+ message: "Unshielded verifying key could not be decoded.",
2406
+ cause
2407
+ })
2408
+ }), require_dist.flatMap$4((derivedAddress) => derivedAddress === publicKey.addressHex ? require_dist.right(publicKey) : require_dist.left(new OtherWalletError({ message: "Unshielded address does not match its verifying key." }))));
2409
+ const makeDefaultV1SerializationCapability = () => {
2410
+ const UtxoWithMetaSchema = require_dist.Struct({
2411
+ utxo: require_dist.Struct({
2412
+ value: require_dist.BigInt$,
2413
+ owner: require_dist.String$,
2414
+ type: require_dist.String$,
2415
+ intentHash: require_dist.String$,
2416
+ outputNo: require_dist.Number$
2417
+ }),
2418
+ meta: require_dist.Struct({
2419
+ ctime: require_dist.Date$,
2420
+ registeredForDustGeneration: require_dist.Boolean$
2421
+ })
2422
+ });
2423
+ const SnapshotSchema = require_dist.Struct({
2424
+ publicKey: require_dist.Struct({
2425
+ publicKey: require_dist.String$,
2426
+ addressHex: require_dist.String$,
2427
+ address: require_dist.String$
2428
+ }),
2429
+ state: require_dist.Struct({
2430
+ availableUtxos: require_dist.Array$(UtxoWithMetaSchema),
2431
+ pendingUtxos: require_dist.Array$(UtxoWithMetaSchema)
2432
+ }),
2433
+ protocolVersion: require_dist.BigInt$,
2434
+ appliedId: require_dist.optional(require_dist.BigInt$),
2435
+ networkId: require_dist.String$
2436
+ });
2437
+ return {
2438
+ serialize: (wallet) => {
2439
+ const buildSnapshot = (w) => ({
2440
+ publicKey: w.publicKey,
2441
+ state: UnshieldedState.toArrays(w.state),
2442
+ protocolVersion: w.protocolVersion,
2443
+ networkId: w.networkId,
2444
+ appliedId: w.progress?.appliedId
2445
+ });
2446
+ return require_dist.pipe(wallet, buildSnapshot, require_dist.encodeSync(SnapshotSchema), JSON.stringify);
2447
+ },
2448
+ deserialize: (serialized) => require_dist.pipe(serialized, require_dist.decodeUnknownEither(require_dist.parseJson(SnapshotSchema)), require_dist.mapLeft((err) => new OtherWalletError(err)), require_dist.flatMap$4((snapshot) => require_dist.pipe(assertKeyAddressConsistency(snapshot.publicKey), require_dist.map$6(() => snapshot))), require_dist.map$6((snapshot) => {
2449
+ return CoreWallet.restore(UnshieldedState.restore(snapshot.state.availableUtxos, snapshot.state.pendingUtxos), snapshot.publicKey, {
2450
+ highestTransactionId: snapshot.appliedId ?? 0n,
2451
+ appliedId: snapshot.appliedId ?? 0n
2452
+ }, require_dist.ProtocolVersion(snapshot.protocolVersion), snapshot.networkId);
2453
+ }))
2454
+ };
2455
+ };
2456
+ //#endregion
2457
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/SyncSchema.js
2458
+ const DateFromMillis = require_dist.transform(require_dist.Number$, require_dist.DateFromSelf, {
2459
+ strict: true,
2460
+ decode: (millis) => new Date(millis),
2461
+ encode: (date) => date.getTime()
2462
+ });
2463
+ const WireUtxoSchema = require_dist.Struct({
2464
+ value: require_dist.SafeBigInt,
2465
+ owner: require_dist.String$,
2466
+ tokenType: require_dist.String$,
2467
+ intentHash: require_dist.String$,
2468
+ outputIndex: require_dist.Number$,
2469
+ ctime: require_dist.Number$,
2470
+ registeredForDustGeneration: require_dist.Boolean$
2471
+ });
2472
+ const UtxoWithMetaSchema = require_dist.transform(WireUtxoSchema, require_dist.typeSchema(require_dist.Struct({
2473
+ utxo: require_dist.Struct({
2474
+ value: require_dist.BigIntSchema,
2475
+ owner: require_dist.String$,
2476
+ type: require_dist.String$,
2477
+ intentHash: require_dist.String$,
2478
+ outputNo: require_dist.Number$
2479
+ }),
2480
+ meta: require_dist.Struct({
2481
+ ctime: require_dist.DateFromSelf,
2482
+ registeredForDustGeneration: require_dist.Boolean$
2483
+ })
2484
+ })), {
2485
+ strict: true,
2486
+ decode: (wire) => ({
2487
+ utxo: {
2488
+ value: wire.value,
2489
+ owner: wire.owner,
2490
+ type: wire.tokenType,
2491
+ intentHash: wire.intentHash,
2492
+ outputNo: wire.outputIndex
2493
+ },
2494
+ meta: {
2495
+ ctime: /* @__PURE__ */ new Date(wire.ctime * 1e3),
2496
+ registeredForDustGeneration: wire.registeredForDustGeneration
2497
+ }
2498
+ }),
2499
+ encode: (domain) => ({
2500
+ value: domain.utxo.value,
2501
+ owner: domain.utxo.owner,
2502
+ tokenType: domain.utxo.type,
2503
+ intentHash: domain.utxo.intentHash,
2504
+ outputIndex: domain.utxo.outputNo,
2505
+ ctime: Math.floor(domain.meta.ctime.getTime() / 1e3),
2506
+ registeredForDustGeneration: domain.meta.registeredForDustGeneration
2507
+ })
2508
+ });
2509
+ const UnshieldedTransactionSchema = require_dist.Data(require_dist.Struct({
2510
+ id: require_dist.Number$,
2511
+ hash: require_dist.String$,
2512
+ type: require_dist.Literal("RegularTransaction", "SystemTransaction", "BridgeClaimTransaction"),
2513
+ protocolVersion: require_dist.Number$,
2514
+ identifiers: require_dist.optional(require_dist.Array$(require_dist.String$)),
2515
+ block: require_dist.Struct({
2516
+ hash: require_dist.String$,
2517
+ height: require_dist.Number$,
2518
+ timestamp: DateFromMillis
2519
+ }),
2520
+ fees: require_dist.optional(require_dist.Struct({
2521
+ paidFees: require_dist.SafeBigInt,
2522
+ estimatedFees: require_dist.SafeBigInt
2523
+ })),
2524
+ transactionResult: require_dist.optional(require_dist.Struct({
2525
+ status: require_dist.Literal("SUCCESS", "FAILURE", "PARTIAL_SUCCESS"),
2526
+ segments: require_dist.NullOr(require_dist.Array$(require_dist.Struct({
2527
+ id: require_dist.Number$,
2528
+ success: require_dist.Boolean$
2529
+ })))
2530
+ }))
2531
+ }));
2532
+ const UnshieldedUpdateWireSchema = require_dist.Struct({
2533
+ type: require_dist.Literal("UnshieldedTransaction"),
2534
+ transaction: UnshieldedTransactionSchema,
2535
+ createdUtxos: require_dist.Array$(UtxoWithMetaSchema),
2536
+ spentUtxos: require_dist.Array$(UtxoWithMetaSchema)
2537
+ });
2538
+ const UnshieldedUpdateSchema = require_dist.transform(UnshieldedUpdateWireSchema, require_dist.typeSchema(require_dist.Struct({
2539
+ type: require_dist.Literal("UnshieldedTransaction"),
2540
+ transaction: UnshieldedTransactionSchema,
2541
+ createdUtxos: require_dist.Array$(require_dist.typeSchema(UtxoWithMetaSchema)),
2542
+ spentUtxos: require_dist.Array$(require_dist.typeSchema(UtxoWithMetaSchema)),
2543
+ status: require_dist.Literal("SUCCESS", "FAILURE", "PARTIAL_SUCCESS")
2544
+ })), {
2545
+ strict: true,
2546
+ decode: (wire) => {
2547
+ const isStatusImplicitlySuccess = ["SystemTransaction", "BridgeClaimTransaction"].includes(wire.transaction.type);
2548
+ return {
2549
+ ...wire,
2550
+ status: isStatusImplicitlySuccess ? "SUCCESS" : wire.transaction.transactionResult.status
2551
+ };
2552
+ },
2553
+ encode: ({ status: _status, ...rest }) => rest
2554
+ });
2555
+ const ProgressSchema = require_dist.Struct({
2556
+ type: require_dist.Literal("UnshieldedTransactionsProgress"),
2557
+ highestTransactionId: require_dist.Number$,
2558
+ protocolVersion: require_dist.Number$
2559
+ });
2560
+ const WalletSyncUpdateSchema = require_dist.Union(UnshieldedUpdateSchema, ProgressSchema);
2561
+ const VersionSignalSyncUpdate = { create: (version, highestTransactionId) => {
2562
+ return {
2563
+ type: "VersionSignal",
2564
+ version,
2565
+ highestTransactionId
2566
+ };
2567
+ } };
2568
+ //#endregion
2569
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/Sync.js
2570
+ /**
2571
+ * Whether a reported protocol version belongs to a variant later than the one owning `activeRange`.
2572
+ *
2573
+ * @remarks
2574
+ * Unshielded sync is message-at-a-time, so this is the whole of the boundary rule — there is no batch to split into an
2575
+ * applied prefix and a deferred suffix, only a yes/no per message. Exported so the indexer and simulator sync
2576
+ * capabilities cannot drift apart on the question.
2577
+ * @param version The protocol version the source reported for this message.
2578
+ * @param activeRange The running variant's half-open activation range.
2579
+ * @returns `true` when the message must be left unapplied.
2580
+ */
2581
+ const isBeyondActiveRange = (version, activeRange) => BigInt(version) >= activeRange[1];
2582
+ /**
2583
+ * Records an observed protocol version on the state, monotonically.
2584
+ *
2585
+ * @remarks
2586
+ * This is the only thing written when a message is deferred at the boundary, and it is what the runtime watches to
2587
+ * decide that the variant must hand over.
2588
+ * @param state The state to annotate.
2589
+ * @param version The protocol version the source reported.
2590
+ * @returns The state carrying the higher of the two versions.
2591
+ */
2592
+ const annotateVersion = (state, version) => CoreWallet.withProtocolVersion(state, require_dist.ProtocolVersion(BigInt(version)));
2593
+ /**
2594
+ * Splits the chain's protocol version off a progress frame, into a signal of its own.
2595
+ *
2596
+ * @remarks
2597
+ * This is how a wallet nobody pays learns that the chain moved. Ordinarily a version reaches it on a transaction it was
2598
+ * served, and it is served only the transactions that touch its own address — so on a chain that crosses a protocol
2599
+ * boundary and then pays this address nothing, it would observe no version at all and stay on the variant it was
2600
+ * running, with everything built through it routed to that variant's ledger. The progress arm has no such silence:
2601
+ * the indexer emits it before its first sleep and keeps emitting it, on an address the chain has never mentioned
2602
+ * exactly as on a busy one, and it states the version at the chain's tip.
2603
+ *
2604
+ * Split off rather than folded in place, because the two things a frame says are governed by different rules. Progress
2605
+ * is bookkeeping and always applies. A version may be recorded only when the wallet is level with the far end of this
2606
+ * address's timeline, or the hand-over would park the sync cursor in front of history that the next variant would
2607
+ * then apply without ever having seen what led to it. Keeping the signal a message of its own leaves that gate
2608
+ * exactly where the capability already implements it — and the frame states both halves in one indexed instant, so
2609
+ * the version can no longer be read against a timeline end that moved between two separate answers.
2610
+ *
2611
+ * Two frames are worth no signal. Zero is the source reporting that it has indexed no block yet, not a chain at version
2612
+ * zero; read as a version it would be a claim nobody made. And a version at or below the one the wallet already held
2613
+ * could only ever be a no-op, because the recorded version never goes backwards — suppressing it is what keeps a
2614
+ * settled wallet's progress frames from putting a redundant message on the stream for the rest of its life.
2615
+ * @param update The decoded subscription message.
2616
+ * @param knownVersion The version the wallet held when this stream opened — a lower bound on what it holds now.
2617
+ * @returns The message, followed by the signal when the frame carries a version worth recording.
2618
+ */
2619
+ const withVersionSignal = (update, knownVersion) => update.type === "UnshieldedTransactionsProgress" && update.protocolVersion !== 0 && BigInt(update.protocolVersion) > knownVersion ? [update, VersionSignalSyncUpdate.create(update.protocolVersion, update.highestTransactionId)] : [update];
2620
+ const makeDefaultSyncService = (config) => {
2621
+ return { updates: (state) => {
2622
+ const { indexerClientConnection } = config;
2623
+ const webSocketUrlResult = require_dist.createWebSocketUrl(indexerClientConnection.indexerHttpUrl, indexerClientConnection.indexerWsUrl);
2624
+ if (require_dist.isLeft(webSocketUrlResult)) return require_dist.fail(new SyncWalletError(/* @__PURE__ */ new Error(`Could not derive WebSocket URL from indexer HTTP URL: ${webSocketUrlResult.left.message}`)));
2625
+ const indexerWsUrlResult = require_dist.make(webSocketUrlResult.right);
2626
+ if (require_dist.isLeft(indexerWsUrlResult)) return require_dist.fail(new SyncWalletError(/* @__PURE__ */ new Error(`Invalid indexer WS URL: ${indexerWsUrlResult.left.message}`)));
2627
+ const indexerWsUrl = indexerWsUrlResult.right;
2628
+ const { appliedId } = state.progress;
2629
+ const { address } = state.publicKey;
2630
+ return require_dist.pipe(require_dist.UnshieldedTransactions.run({
2631
+ address,
2632
+ transactionId: Number(appliedId)
2633
+ }), require_dist.provideLayer(require_dist.layer({
2634
+ url: indexerWsUrl,
2635
+ keepAlive: indexerClientConnection.keepAlive
2636
+ })), require_dist.mapError((error) => new SyncWalletError(error)), require_dist.mapEffect((subscription) => {
2637
+ const { unshieldedTransactions } = subscription;
2638
+ return require_dist.pipe(require_dist.decodeUnknownEither(WalletSyncUpdateSchema)(unshieldedTransactions), require_dist.mapLeft((err) => new SyncWalletError(err)), require_dist.toEffect);
2639
+ }), require_dist.mapConcat((update) => withVersionSignal(update, state.protocolVersion)));
2640
+ } };
2641
+ };
2642
+ /**
2643
+ * Folds a version signal: records the chain's version, and nothing else.
2644
+ *
2645
+ * @remarks
2646
+ * The same recording the transaction path makes through {@link annotateVersion}: no cursor moves, no UTXO changes hands.
2647
+ * A signal is an observation about the chain, not a piece of it.
2648
+ *
2649
+ * One situation makes the observation unsafe to record, and it leaves the state exactly as it was. A transaction still
2650
+ * unapplied below the address's tip means the hand-over would park the cursor in front of history the next variant
2651
+ * would then apply without ever having seen what led to it — and that transaction carries the version itself, so
2652
+ * nothing is lost by waiting for it. That is not an error: the next tick asks again.
2653
+ *
2654
+ * A version at or below the one already recorded needs no guard of its own — `annotateVersion` never goes backwards —
2655
+ * so a source briefly answering from a lagging replica cannot drag a wallet back over a boundary.
2656
+ * @param state The wallet to record on.
2657
+ * @param signal What the chain said, and how far this address's timeline goes.
2658
+ * @returns The wallet, annotated or untouched.
2659
+ */
2660
+ const applyVersionSignal = (state, signal) => require_dist.right(BigInt(signal.highestTransactionId) > state.progress.appliedId ? state : annotateVersion(state, signal.version));
2661
+ /**
2662
+ * Folds a progress frame: moves the far end of the cursor, and nothing else.
2663
+ *
2664
+ * @remarks
2665
+ * A progress message reports how far the source has got with this address, not a transaction. The chain version it also
2666
+ * carries is deliberately not read here: the source splits that off into its own `VersionSignal`, which is the only
2667
+ * message allowed to annotate, and which alone carries the gate in {@link applyVersionSignal}. Annotating from both
2668
+ * places would put the gate on one route and not the other.
2669
+ * @param state The wallet to record on.
2670
+ * @param progress The frame.
2671
+ * @returns The wallet with the far end of its cursor moved and marked connected.
2672
+ */
2673
+ const applyProgress = (state, progress) => require_dist.right(CoreWallet.updateProgress(state, {
2674
+ highestTransactionId: BigInt(progress.highestTransactionId),
2675
+ isConnected: true
2676
+ }));
2677
+ /**
2678
+ * Classifies a delivered transaction; {@link applyTransaction} acts on the answer.
2679
+ *
2680
+ * @remarks
2681
+ * "Is this past the cursor?" is the only ordering question askable here. The id is the indexer's global transaction id
2682
+ * filtered to this address, so a wallet is served a strictly increasing but SPARSE subsequence of it — consecutive
2683
+ * deliveries routinely skip whole runs of ids belonging to other addresses — and demanding contiguity would reject
2684
+ * every honest stream. What a gap cannot hide is a spend whose create was never folded: `UnshieldedState` refuses a
2685
+ * spend of a UTXO it holds in neither map, and that refusal, not this classification, is what catches a spend
2686
+ * delivered ahead of its create. It happens before the cursor moves, so the retry re-fetches the pair in order.
2687
+ *
2688
+ * Whether the resume cursor the subscription is opened with is inclusive is undocumented, so the transaction it names
2689
+ * may or may not reappear on a reconnect; calling an equal id `redelivered` makes the fold indifferent either way,
2690
+ * exactly as the shielded and dust wallets treat their own boundary event.
2691
+ * @param state The wallet the transaction was delivered to.
2692
+ * @param update The delivered transaction.
2693
+ * @param activeRange The half-open protocol version range the running variant owns.
2694
+ * @returns The placement.
2695
+ */
2696
+ const placeTransaction = (state, update, activeRange) => {
2697
+ const received = BigInt(update.transaction.id);
2698
+ const cursor = state.progress.appliedId;
2699
+ return received < cursor ? "replayed" : received === cursor ? "redelivered" : isBeyondActiveRange(update.transaction.protocolVersion, activeRange) ? "deferred" : "applicable";
2700
+ };
2701
+ /**
2702
+ * Folds an applicable transaction: the UTXO changes, then the cursor, the history record and the version.
2703
+ *
2704
+ * @remarks
2705
+ * The history is written only once the fold has succeeded, so a rejected transaction leaves no trace there either.
2706
+ * @param state The wallet to fold into.
2707
+ * @param update The delivered transaction.
2708
+ * @param getContext Where the transaction history lives.
2709
+ * @returns The folded wallet, or the fold's refusal.
2710
+ */
2711
+ const foldTransaction = (state, update, getContext) => {
2712
+ const payload = {
2713
+ createdUtxos: update.createdUtxos,
2714
+ spentUtxos: update.spentUtxos,
2715
+ status: update.status
2716
+ };
2717
+ return (update.status === "FAILURE" ? CoreWallet.applyFailedUpdate(state, payload) : CoreWallet.applyUpdate(state, payload)).pipe(require_dist.map$6((wallet) => {
2718
+ const advanced = CoreWallet.updateProgress(wallet, { appliedId: BigInt(update.transaction.id) });
2719
+ require_dist.runFork(getContext().transactionHistoryService.put(update));
2720
+ return annotateVersion(advanced, update.transaction.protocolVersion);
2721
+ }));
2722
+ };
2723
+ /**
2724
+ * Folds a delivered transaction according to its {@link TransactionPlacement}.
2725
+ *
2726
+ * @remarks
2727
+ * - `replayed` is refused with {@link OutOfOrderSyncUpdateError} and nothing is applied: folding a create twice resurrects
2728
+ * a UTXO some later transaction has since spent; folding a spend twice removes one some later transaction
2729
+ * re-created. The state is handed back untouched so the retry can re-fetch in order.
2730
+ * - `redelivered` is a no-op in the strongest sense — the same state comes back: no UTXO change, no cursor movement, no
2731
+ * version annotation, no transaction-history write. All of that was done the first time it arrived.
2732
+ * - `deferred` is the hand-over point. The transaction belongs to the next variant, so NOTHING about it is applied; only
2733
+ * the version is recorded, which is what makes the runtime migrate. Because the cursor did not move, the next
2734
+ * variant re-fetches this very transaction and applies it exactly once.
2735
+ * - `applicable` is folded by {@link foldTransaction}.
2736
+ *
2737
+ * @param state The wallet the transaction was delivered to.
2738
+ * @param update The delivered transaction.
2739
+ * @param activeRange The half-open protocol version range the running variant owns.
2740
+ * @param getContext Where the transaction history lives.
2741
+ * @returns The next wallet, or the refusal.
2742
+ */
2743
+ const applyTransaction = (state, update, activeRange, getContext) => value(placeTransaction(state, update, activeRange)).pipe(when("replayed", () => require_dist.left(new OutOfOrderSyncUpdateError({
2744
+ message: `Sync source delivered transaction ${update.transaction.id}, below the applied cursor ${state.progress.appliedId}; the state is left untouched so the retry can re-fetch in order`,
2745
+ expected: state.progress.appliedId,
2746
+ received: BigInt(update.transaction.id)
2747
+ }))), when("redelivered", () => require_dist.right(state)), when("deferred", () => require_dist.right(annotateVersion(state, update.transaction.protocolVersion))), when("applicable", () => foldTransaction(state, update, getContext)), exhaustive);
2748
+ const makeDefaultSyncCapability = (_config, getContext) => {
2749
+ return { applyUpdate: (state, update, activeRange) => value(update).pipe(discriminatorsExhaustive("type")({
2750
+ VersionSignal: (signal) => applyVersionSignal(state, signal),
2751
+ UnshieldedTransactionsProgress: (progress) => applyProgress(state, progress),
2752
+ UnshieldedTransaction: (transaction) => applyTransaction(state, transaction, activeRange, getContext)
2753
+ })) };
2754
+ };
2755
+ //#endregion
2756
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/TransactionOps.js
2757
+ const TransactionOps = {
2758
+ getSignatureData(tx, segment) {
2759
+ if (!tx.intents) return require_dist.left(new TransactingError({ message: "Transaction has no intents" }));
2760
+ const intent = tx.intents.get(segment);
2761
+ if (!intent) return require_dist.left(new TransactingError({ message: `Intent with segment ${segment} was not found` }));
2762
+ return require_dist.try_$1({
2763
+ try: () => intent.signatureData(segment),
2764
+ catch: (error) => new TransactingError({
2765
+ message: "Failed to get offer signature data",
2766
+ cause: error
2767
+ })
2768
+ });
2769
+ },
2770
+ getSegments(transaction) {
2771
+ return transaction.intents?.keys().toArray() ?? [];
2772
+ },
2773
+ findAvailableSegmentId(transaction) {
2774
+ const used = new Set(transaction.intents?.keys() ?? []);
2775
+ return require_dist.pipe(require_dist.range(1, 65535), require_dist.findFirst$1((segmentId) => !used.has(segmentId)));
2776
+ },
2777
+ addSignature(transaction, signature, segment) {
2778
+ return require_dist.gen$1(function* () {
2779
+ if (!transaction.intents || transaction.intents.size === 0) return yield* require_dist.left(new TransactingError({ message: "No intents found in the transaction" }));
2780
+ const intent = transaction.intents?.get(segment);
2781
+ if (!intent) return yield* require_dist.left(new TransactingError({ message: `Intent with id ${segment} was not found` }));
2782
+ if (TransactionOps.isIntentBound(intent)) return yield* require_dist.left(new TransactingError({ message: `Intent at segment ${segment} is already bound` }));
2783
+ if (intent.fallibleUnshieldedOffer) intent.fallibleUnshieldedOffer = yield* TransactionOps.addSignaturesToOffer(intent.fallibleUnshieldedOffer, signature, segment, "fallible");
2784
+ if (intent.guaranteedUnshieldedOffer) intent.guaranteedUnshieldedOffer = yield* TransactionOps.addSignaturesToOffer(intent.guaranteedUnshieldedOffer, signature, segment, "guaranteed");
2785
+ transaction.intents = transaction.intents.set(segment, intent);
2786
+ return transaction;
2787
+ });
2788
+ },
2789
+ collectSignableData(transaction) {
2790
+ return require_dist.all$1(TransactionOps.getSegments(transaction).map((segment) => require_dist.map$6(TransactionOps.getSignatureData(transaction, segment), (data) => ({
2791
+ segment,
2792
+ data
2793
+ }))));
2794
+ },
2795
+ attachSignatures(transaction, signatures) {
2796
+ const seed = require_dist.right(transaction);
2797
+ return require_dist.pipe(signatures, require_dist.reduce(seed, (acc, { segment, signature }) => require_dist.flatMap$4(acc, (tx) => TransactionOps.addSignature(tx, signature, segment))));
2798
+ },
2799
+ getImbalances(transaction, segment) {
2800
+ const imbalances = transaction.imbalances(segment).entries().filter(([token, value]) => token.tag === "unshielded" && value !== 0n).map(([token, value]) => [token.raw.toString(), value]).toArray();
2801
+ return require_dist.Imbalances.fromEntries(imbalances);
2802
+ },
2803
+ addSignaturesToOffer(offer, signature, segment, offerType) {
2804
+ return require_dist.pipe(offer.inputs, require_dist.map$3((_, i) => offer.signatures.at(i) ?? signature), (signatures) => require_dist.try_$1({
2805
+ try: () => offer.addSignatures(signatures),
2806
+ catch: (error) => new TransactingError({
2807
+ message: `Failed to add ${offerType} signature at segment ${segment}`,
2808
+ cause: error
2809
+ })
2810
+ }));
2811
+ },
2812
+ isIntentBound(intent) {
2813
+ return intent.binding.instance === "binding";
2814
+ },
2815
+ extractOwnInputs(transaction, signatureVerifyingKey) {
2816
+ const segments = TransactionOps.getSegments(transaction);
2817
+ const ownerAddress = (0, _midnight_ntwrk_ledger_v8.addressFromKey)(signatureVerifyingKey);
2818
+ const toUtxo = (input) => ({
2819
+ ...input,
2820
+ owner: ownerAddress
2821
+ });
2822
+ return require_dist.pipe(segments, require_dist.flatMap$2((segment) => {
2823
+ const intent = transaction.intents?.get(segment);
2824
+ if (!intent) return [];
2825
+ const { guaranteedUnshieldedOffer, fallibleUnshieldedOffer } = intent;
2826
+ const ownedInputsfromGuaranteedSection = guaranteedUnshieldedOffer?.inputs ? guaranteedUnshieldedOffer.inputs.filter((input) => input.owner === signatureVerifyingKey) : [];
2827
+ const ownedInputsfromFallibleSection = fallibleUnshieldedOffer ? fallibleUnshieldedOffer.inputs.filter((input) => input.owner === signatureVerifyingKey) : [];
2828
+ return [...ownedInputsfromGuaranteedSection, ...ownedInputsfromFallibleSection].map(toUtxo);
2829
+ }));
2830
+ }
2831
+ };
2832
+ //#endregion
2833
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/Transacting.js
2834
+ const GUARANTEED_SEGMENT = 0;
2835
+ const makeDefaultTransactingCapability = (config, getContext) => {
2836
+ return new TransactingCapabilityImplementation(config.networkId, () => getContext().coinSelection, () => getContext().coinsAndBalancesCapability, () => getContext().keysCapability, TransactionOps);
2837
+ };
2838
+ var TransactingCapabilityImplementation = class {
2839
+ networkId;
2840
+ getCoinSelection;
2841
+ txOps;
2842
+ getCoins;
2843
+ getKeys;
2844
+ constructor(networkId, getCoinSelection, getCoins, getKeys, txOps) {
2845
+ this.getCoins = getCoins;
2846
+ this.networkId = networkId;
2847
+ this.getCoinSelection = getCoinSelection;
2848
+ this.getKeys = getKeys;
2849
+ this.txOps = txOps;
2850
+ }
2851
+ /**
2852
+ * Balances an unbound transaction Note: Unbound transactions are balanced in place and returned
2853
+ *
2854
+ * @param wallet - The wallet to balance the transaction with
2855
+ * @param transaction - The transaction to balance
2856
+ * @returns The balanced transaction and the new wallet state if successful, otherwise an error
2857
+ */
2858
+ balanceUnboundTransaction(wallet, transaction) {
2859
+ return this.#balanceUnboundishTransaction(wallet, transaction);
2860
+ }
2861
+ /**
2862
+ * Balances an unproven transaction Note: This method does the same thing as balanceUnboundTransaction but is provided
2863
+ * for convenience and type safety
2864
+ *
2865
+ * @param wallet - The wallet to balance the transaction with
2866
+ * @param transaction - The transaction to balance
2867
+ * @returns The balanced transaction and the new wallet state if successful, otherwise an error
2868
+ */
2869
+ balanceUnprovenTransaction(wallet, transaction) {
2870
+ return this.#balanceUnboundishTransaction(wallet, transaction);
2871
+ }
2872
+ /**
2873
+ * Balances a bound transaction Note: In bound transactions we can only balance the guaranteed section in intents
2874
+ *
2875
+ * @param wallet - The wallet to balance the transaction with
2876
+ * @param transaction - The transaction to balance
2877
+ * @returns A balancing counterpart transaction (which should be merged with the original transaction ) and the new
2878
+ * wallet state if successful, otherwise an error
2879
+ */
2880
+ balanceFinalizedTransaction(wallet, transaction) {
2881
+ return require_dist.gen$1(this, function* () {
2882
+ const segments = this.txOps.getSegments(transaction);
2883
+ for (const segment of segments) {
2884
+ const intent = transaction.intents?.get(segment);
2885
+ if (!this.txOps.isIntentBound(intent)) return yield* require_dist.left(new TransactingError({ message: `Intent with id ${segment} is not bound` }));
2886
+ }
2887
+ const intent = transaction.intents?.get(segments[0]);
2888
+ const imbalances = this.txOps.getImbalances(transaction, GUARANTEED_SEGMENT);
2889
+ if (imbalances.size === 0) return [void 0, wallet];
2890
+ const recipe = yield* this.#balanceSegment(wallet, imbalances, require_dist.Imbalances.empty(), this.getCoinSelection());
2891
+ const { newState, offer } = yield* this.#prepareOffer(wallet, recipe);
2892
+ const balancingIntent = _midnight_ntwrk_ledger_v8.Intent.new(intent.ttl);
2893
+ balancingIntent.guaranteedUnshieldedOffer = offer;
2894
+ const segmentId = require_dist.getOrElse(this.txOps.findAvailableSegmentId(transaction), () => 1);
2895
+ return [_midnight_ntwrk_ledger_v8.Transaction.fromParts(this.networkId).addIntent({
2896
+ tag: "specific",
2897
+ value: segmentId
2898
+ }, balancingIntent), newState];
2899
+ });
2900
+ }
2901
+ /**
2902
+ * Makes a transfer transaction
2903
+ *
2904
+ * @param wallet - The wallet to make the transfer with
2905
+ * @param outputs - The outputs for the transfer
2906
+ * @param ttl - The TTL for the transaction
2907
+ * @returns The balanced transfer transaction and the new wallet state if successful, otherwise an error
2908
+ */
2909
+ makeTransfer(wallet, outputs, ttl) {
2910
+ return require_dist.gen$1(this, function* () {
2911
+ const { networkId } = this;
2912
+ if (!outputs.every((output) => output.amount > 0n)) return yield* require_dist.left(new TransactingError({ message: "The amount of all inputs needs to be positive" }));
2913
+ const ledgerOutputs = outputs.map((output) => {
2914
+ return {
2915
+ value: output.amount,
2916
+ owner: output.receiverAddress.data.toString("hex"),
2917
+ type: output.type
2918
+ };
2919
+ });
2920
+ const recipe = yield* this.#balanceSegment(wallet, require_dist.Imbalances.empty(), require_dist.Imbalances.fromEntries(ledgerOutputs.map((output) => [output.type, output.value])), this.getCoinSelection());
2921
+ const { newState, offer } = yield* this.#prepareOffer(wallet, {
2922
+ inputs: recipe.inputs,
2923
+ outputs: [...recipe.outputs, ...ledgerOutputs]
2924
+ });
2925
+ const intent = _midnight_ntwrk_ledger_v8.Intent.new(ttl);
2926
+ if (ledgerOutputs.some((output) => output.type === require_dist.Token.night)) intent.fallibleUnshieldedOffer = offer;
2927
+ else intent.guaranteedUnshieldedOffer = offer;
2928
+ return {
2929
+ newState,
2930
+ transaction: _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, void 0, void 0, intent)
2931
+ };
2932
+ });
2933
+ }
2934
+ rotateUtxos(wallet, guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl) {
2935
+ return require_dist.gen$1(this, function* () {
2936
+ const { networkId } = this;
2937
+ if (guaranteedUtxos.length === 0 && fallibleUtxos.length === 0) return yield* require_dist.left(new TransactingError({ message: "At least one UTxO must be provided to rotateUtxos" }));
2938
+ const ownerAddress = _midnight_ntwrk_ledger_v8.addressFromKey(nightVerifyingKey);
2939
+ const makeOffer = (utxos) => {
2940
+ if (utxos.length === 0) return require_dist.none();
2941
+ const inputs = utxos.map(({ utxo }) => ({
2942
+ value: utxo.value,
2943
+ type: utxo.type,
2944
+ intentHash: utxo.intentHash,
2945
+ outputNo: utxo.outputNo,
2946
+ owner: nightVerifyingKey
2947
+ }));
2948
+ const totalValue = require_dist.pipe(utxos, require_dist.map$3(({ utxo }) => utxo.value), require_dist.reduce(0n, (a, b) => a + b));
2949
+ const output = {
2950
+ owner: ownerAddress,
2951
+ type: require_dist.Token.night,
2952
+ value: totalValue
2953
+ };
2954
+ return require_dist.some(_midnight_ntwrk_ledger_v8.UnshieldedOffer.new(inputs, [output], []));
2955
+ };
2956
+ const allUtxos = [...guaranteedUtxos, ...fallibleUtxos].map(({ utxo }) => utxo);
2957
+ const [, walletAfterBooking] = yield* CoreWallet.spendUtxos(wallet, allUtxos);
2958
+ const guaranteedOffer = makeOffer(guaranteedUtxos);
2959
+ const fallibleOffer = makeOffer(fallibleUtxos);
2960
+ const intent = require_dist.pipe(_midnight_ntwrk_ledger_v8.Intent.new(ttl), (i) => require_dist.match$1(guaranteedOffer, {
2961
+ onNone: () => i,
2962
+ onSome: (offer) => {
2963
+ i.guaranteedUnshieldedOffer = offer;
2964
+ return i;
2965
+ }
2966
+ }), (i) => require_dist.match$1(fallibleOffer, {
2967
+ onNone: () => i,
2968
+ onSome: (offer) => {
2969
+ i.fallibleUnshieldedOffer = offer;
2970
+ return i;
2971
+ }
2972
+ }));
2973
+ return {
2974
+ newState: walletAfterBooking,
2975
+ transaction: _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, void 0, void 0, intent)
2976
+ };
2977
+ });
2978
+ }
2979
+ /**
2980
+ * Initializes a swap transaction
2981
+ *
2982
+ * @param wallet - The wallet to initialize the swap for
2983
+ * @param desiredInputs - The desired inputs for the swap
2984
+ * @param desiredOutputs - The desired outputs for the swap
2985
+ * @param ttl - The TTL for the swap
2986
+ * @returns The initialized swap transaction and the new wallet state if successful, otherwise an error
2987
+ */
2988
+ initSwap(wallet, desiredInputs, desiredOutputs, ttl) {
2989
+ return require_dist.gen$1(this, function* () {
2990
+ const { networkId } = this;
2991
+ if (!desiredOutputs.every((output) => output.amount > 0n)) return yield* require_dist.left(new TransactingError({ message: "The amount of all outputs needs to be positive" }));
2992
+ if (!Object.entries(desiredInputs).every(([, amount]) => amount > 0n)) return yield* require_dist.left(new TransactingError({ message: "The amount of all inputs needs to be positive" }));
2993
+ const ledgerOutputs = desiredOutputs.map((output) => ({
2994
+ value: output.amount,
2995
+ owner: output.receiverAddress.data.toString("hex"),
2996
+ type: output.type
2997
+ }));
2998
+ const targetImbalances = require_dist.Imbalances.fromEntries(Object.entries(desiredInputs));
2999
+ const recipe = yield* this.#balanceSegment(wallet, require_dist.Imbalances.empty(), targetImbalances, this.getCoinSelection());
3000
+ const { newState, offer } = yield* this.#prepareOffer(wallet, {
3001
+ inputs: recipe.inputs,
3002
+ outputs: [...recipe.outputs, ...ledgerOutputs]
3003
+ });
3004
+ const intent = _midnight_ntwrk_ledger_v8.Intent.new(ttl);
3005
+ intent.guaranteedUnshieldedOffer = offer;
3006
+ return {
3007
+ newState,
3008
+ transaction: _midnight_ntwrk_ledger_v8.Transaction.fromParts(networkId, void 0, void 0, intent)
3009
+ };
3010
+ });
3011
+ }
3012
+ /**
3013
+ * Reverts a transaction by rolling back all inputs owned by this wallet
3014
+ *
3015
+ * @param wallet - The wallet to revert the transaction for
3016
+ * @param transaction - The transaction to revert (can be FinalizedTransaction, UnboundTransaction, or
3017
+ * UnprovenTransaction)
3018
+ * @returns The updated wallet with rolled back UTXOs if successful, otherwise an error
3019
+ */
3020
+ revertTransaction(wallet, transaction) {
3021
+ return require_dist.pipe(this.txOps.extractOwnInputs(transaction, wallet.publicKey.publicKey), require_dist.reduce(require_dist.right(wallet), (walletAcc, utxo) => require_dist.pipe(walletAcc, require_dist.flatMap$4((w) => CoreWallet.rollbackUtxo(w, utxo)))));
3022
+ }
3023
+ /**
3024
+ * Balances a segment of a transaction
3025
+ *
3026
+ * @param wallet - The wallet to balance the segment for
3027
+ * @param imbalances - The imbalances to balance the segment for
3028
+ * @param targetImbalances - The target imbalances to balance the segment for
3029
+ * @param coinSelection - The coin selection to use for the balance recipe
3030
+ * @returns The balance recipe if successful, otherwise an error
3031
+ */
3032
+ #balanceSegment(wallet, imbalances, targetImbalances, coinSelection) {
3033
+ return require_dist.try_$1({
3034
+ try: () => require_dist.getBalanceRecipe({
3035
+ coins: this.getCoins().getAvailableCoins(wallet).map(({ utxo }) => utxo),
3036
+ initialImbalances: imbalances,
3037
+ feeTokenType: "",
3038
+ transactionCostModel: {
3039
+ inputFeeOverhead: 0n,
3040
+ outputFeeOverhead: 0n
3041
+ },
3042
+ coinSelection,
3043
+ createOutput: (coin) => ({
3044
+ ...coin,
3045
+ owner: wallet.publicKey.addressHex
3046
+ }),
3047
+ isCoinEqual: (a, b) => a.intentHash === b.intentHash && a.outputNo === b.outputNo,
3048
+ targetImbalances
3049
+ }),
3050
+ catch: (err) => {
3051
+ if (err instanceof require_dist.InsufficientFundsError) return new InsufficientFundsError({
3052
+ message: "Insufficient funds",
3053
+ tokenType: err.tokenType,
3054
+ amount: imbalances.get(err.tokenType) ?? 0n
3055
+ });
3056
+ else return new OtherWalletError({
3057
+ message: "Balancing unshielded segment failed",
3058
+ cause: err
3059
+ });
3060
+ }
3061
+ });
3062
+ }
3063
+ /**
3064
+ * Prepares an offer for a given balance recipe
3065
+ *
3066
+ * @param wallet - The wallet to prepare the offer for
3067
+ * @param balanceRecipe - The balance recipe to prepare the offer for
3068
+ * @returns The prepared offer and the new wallet state if successful, otherwise an error
3069
+ */
3070
+ #prepareOffer(wallet, balanceRecipe) {
3071
+ return require_dist.gen$1(function* () {
3072
+ const [spentInputs, updatedWallet] = yield* CoreWallet.spendUtxos(wallet, balanceRecipe.inputs);
3073
+ const { publicKey } = wallet.publicKey;
3074
+ const ledgerInputs = spentInputs.map((input) => ({
3075
+ ...input,
3076
+ intentHash: input.intentHash,
3077
+ owner: publicKey
3078
+ }));
3079
+ return {
3080
+ newState: updatedWallet,
3081
+ offer: yield* require_dist.try_$1({
3082
+ try: () => _midnight_ntwrk_ledger_v8.UnshieldedOffer.new(ledgerInputs, [...balanceRecipe.outputs], []),
3083
+ catch: (error) => new TransactingError({
3084
+ message: "Failed to create counter offer",
3085
+ cause: error
3086
+ })
3087
+ })
3088
+ };
3089
+ });
3090
+ }
3091
+ #mergeOffers(offerA, offerB) {
3092
+ return require_dist.pipe(require_dist.fromNullable(offerB), require_dist.match$1({
3093
+ onNone: () => require_dist.right(offerA),
3094
+ onSome: (offerB) => require_dist.try_$1({
3095
+ try: () => _midnight_ntwrk_ledger_v8.UnshieldedOffer.new([...offerB.inputs, ...offerA.inputs], [...offerB.outputs, ...offerA.outputs], [...offerB.signatures, ...offerA.signatures]),
3096
+ catch: (error) => new TransactingError({
3097
+ message: "Failed to merge offers",
3098
+ cause: error
3099
+ })
3100
+ })
3101
+ }));
3102
+ }
3103
+ /**
3104
+ * Balances an unboundish (unproven or unbound) transaction
3105
+ *
3106
+ * @param wallet - The wallet to balance the transaction with
3107
+ * @param transaction - The transaction to balance
3108
+ * @returns The balanced transaction and the new wallet state if successful, otherwise an error
3109
+ * @todo - https://shielded.atlassian.net/browse/PM-21260
3110
+ */
3111
+ #balanceUnboundishTransaction(wallet, transaction) {
3112
+ return require_dist.gen$1(this, function* () {
3113
+ const segments = this.txOps.getSegments(transaction);
3114
+ if (segments.length === 0) return [void 0, wallet];
3115
+ for (const segment of [...segments, GUARANTEED_SEGMENT]) {
3116
+ const imbalances = this.txOps.getImbalances(transaction, segment);
3117
+ if (imbalances.size === 0) continue;
3118
+ const intentSegment = segment === GUARANTEED_SEGMENT ? segments[0] : segment;
3119
+ const intent = transaction.intents?.get(intentSegment);
3120
+ if (!intent) return yield* require_dist.left(new TransactingError({ message: `Intent with id ${segment} was not found` }));
3121
+ if (this.txOps.isIntentBound(intent)) return yield* require_dist.left(new TransactingError({ message: `Intent with id ${segment} is already bound` }));
3122
+ const recipe = yield* this.#balanceSegment(wallet, imbalances, require_dist.Imbalances.empty(), this.getCoinSelection());
3123
+ const { offer } = yield* this.#prepareOffer(wallet, recipe);
3124
+ const targetOffer = segment !== GUARANTEED_SEGMENT ? intent.fallibleUnshieldedOffer : intent.guaranteedUnshieldedOffer;
3125
+ const mergedOffer = yield* this.#mergeOffers(offer, targetOffer);
3126
+ if (segment !== GUARANTEED_SEGMENT) intent.fallibleUnshieldedOffer = mergedOffer;
3127
+ else intent.guaranteedUnshieldedOffer = mergedOffer;
3128
+ transaction.intents = transaction.intents.set(intentSegment, intent);
3129
+ }
3130
+ return [transaction, wallet];
3131
+ });
3132
+ }
3133
+ };
3134
+ //#endregion
3135
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/KeyStore.js
3136
+ require__polyfill_buffer_patch.init__polyfill_buffer_patch();
3137
+ const PublicKey$1 = { fromKeyStore: (keystore) => {
3138
+ return {
3139
+ publicKey: keystore.getPublicKey(),
3140
+ addressHex: keystore.getAddress(),
3141
+ address: keystore.getBech32Address().asString()
3142
+ };
3143
+ } };
3144
+ const createKeystore$1 = (secretKey, networkId) => {
3145
+ const keystore = {
3146
+ getSecretKey: () => require__polyfill_buffer_patch.import_buffer.Buffer.from(secretKey),
3147
+ getBech32Address: () => {
3148
+ const address = keystore.getAddress();
3149
+ const addressBuffer = require__polyfill_buffer_patch.import_buffer.Buffer.from(address, "hex");
3150
+ return require_dist.UnshieldedAddress.codec.encode(networkId, new require_dist.UnshieldedAddress(addressBuffer));
3151
+ },
3152
+ getPublicKey: () => (0, _midnight_ntwrk_ledger_v8.signatureVerifyingKey)(keystore.getSecretKey().toString("hex")),
3153
+ getAddress: () => (0, _midnight_ntwrk_ledger_v8.addressFromKey)(keystore.getPublicKey()),
3154
+ signData: (data) => (0, _midnight_ntwrk_ledger_v8.signData)(keystore.getSecretKey().toString("hex"), data),
3155
+ signDataAsync: (data) => Promise.resolve(keystore.signData(data))
3156
+ };
3157
+ return keystore;
3158
+ };
3159
+ //#endregion
3160
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/Migration.js
3161
+ /**
3162
+ * The migration used when there is no previous wallet at all.
3163
+ *
3164
+ * @remarks
3165
+ * It backs `WalletLike.startEmpty`, which builds a wallet before any key material exists. The resulting state has no
3166
+ * UTXOs and a public key derived from a fixed placeholder seed; it is a scaffold to be replaced by a real start, not
3167
+ * a wallet anybody can transact with. Preserved verbatim from the ledger-v8 implementation so that `startEmpty`
3168
+ * behaves exactly as it did.
3169
+ * @example
3170
+ * ```typescript
3171
+ * const builder = new V2Builder().withDefaults().withMigration(makeEmptyWalletMigration({ networkId }));
3172
+ * ```;
3173
+ *
3174
+ * @param configuration Supplies the network the scaffold state claims to be on.
3175
+ * @returns A migration from `null`.
3176
+ */
3177
+ const makeEmptyWalletMigration = (configuration) => ({ migrate: () => {
3178
+ const seed = require_dist.fromString("0000000000000000000000000000000000000000000000000000000000000001");
3179
+ return require_dist.succeed(CoreWallet.init(PublicKey$1.fromKeyStore(createKeystore$1(seed, configuration.networkId)), configuration.networkId));
3180
+ } });
3181
+ //#endregion
3182
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/Signing.js
3183
+ /**
3184
+ * The default signing service: collect each segment's signable data (pure), invoke the async signer once per segment
3185
+ * (sequentially — segment counts are tiny), then attach the signatures (pure). A signer rejection or throw is wrapped
3186
+ * in a {@link SignError}.
3187
+ */
3188
+ const makeDefaultSigningService = () => ({ sign(transaction, signSegment) {
3189
+ return require_dist.gen(function* () {
3190
+ const segments = yield* require_dist.toEffect(TransactionOps.collectSignableData(transaction));
3191
+ const signatures = yield* require_dist.forEach(segments, (segment) => require_dist.pipe(require_dist.tryPromise({
3192
+ try: () => signSegment(segment.data),
3193
+ catch: (cause) => new SignError({
3194
+ message: "Signer callback failed",
3195
+ cause
3196
+ })
3197
+ }), require_dist.map$2((signature) => ({
3198
+ segment: segment.segment,
3199
+ signature
3200
+ }))));
3201
+ return yield* require_dist.toEffect(TransactionOps.attachSignatures(transaction, signatures));
3202
+ });
3203
+ } });
3204
+ //#endregion
3205
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/CoinsAndBalances.js
3206
+ const calculateBalances = (utxos) => utxos.reduce((acc, { utxo }) => ({
3207
+ ...acc,
3208
+ [utxo.type]: acc[utxo.type] === void 0 ? utxo.value : acc[utxo.type] + utxo.value
3209
+ }), {});
3210
+ const makeDefaultCoinsAndBalancesCapability = () => {
3211
+ const getAvailableBalances = (state) => {
3212
+ return calculateBalances(getAvailableCoins(state));
3213
+ };
3214
+ const getPendingBalances = (state) => {
3215
+ return calculateBalances(getPendingCoins(state));
3216
+ };
3217
+ const getTotalBalances = (state) => {
3218
+ return require_dist.pipe([getAvailableBalances(state), getPendingBalances(state)], require_dist.mergeWithAccumulator(0n, (a, b) => a + b));
3219
+ };
3220
+ const getAvailableCoins = (state) => UnshieldedState.toArrays(state.state).availableUtxos;
3221
+ const getPendingCoins = (state) => UnshieldedState.toArrays(state.state).pendingUtxos;
3222
+ const getTotalCoins = (state) => [...getAvailableCoins(state), ...getPendingCoins(state)];
3223
+ return {
3224
+ getAvailableBalances,
3225
+ getPendingBalances,
3226
+ getTotalBalances,
3227
+ getAvailableCoins,
3228
+ getPendingCoins,
3229
+ getTotalCoins
3230
+ };
3231
+ };
3232
+ //#endregion
3233
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/Keys.js
3234
+ require__polyfill_buffer_patch.init__polyfill_buffer_patch();
3235
+ const makeDefaultKeysCapability = () => {
3236
+ return {
3237
+ getPublicKey: (state) => {
3238
+ return state.publicKey.publicKey;
3239
+ },
3240
+ getAddress: (state) => {
3241
+ return new require_dist.UnshieldedAddress(require__polyfill_buffer_patch.import_buffer.Buffer.from(state.publicKey.addressHex, "hex"));
3242
+ }
3243
+ };
3244
+ };
3245
+ //#endregion
3246
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/TransactionHistory.js
3247
+ const UtxoSchema = require_dist.Struct({
3248
+ value: require_dist.SafeBigInt,
3249
+ owner: require_dist.String$,
3250
+ tokenType: require_dist.String$,
3251
+ intentHash: require_dist.String$,
3252
+ outputIndex: require_dist.Number$
3253
+ });
3254
+ const UnshieldedSectionSchema$1 = require_dist.Struct({
3255
+ id: require_dist.Number$,
3256
+ createdUtxos: require_dist.Array$(UtxoSchema),
3257
+ spentUtxos: require_dist.Array$(UtxoSchema)
3258
+ });
3259
+ require_dist.extendEntrySchema({ unshielded: require_dist.optional(UnshieldedSectionSchema$1) });
3260
+ const convertUpdateToFinalizedInput = ({ transaction, createdUtxos, spentUtxos, status }) => ({
3261
+ hash: transaction.hash,
3262
+ protocolVersion: transaction.protocolVersion,
3263
+ status,
3264
+ identifiers: transaction.identifiers ?? [],
3265
+ timestamp: transaction.block.timestamp,
3266
+ finalizedBlock: {
3267
+ hash: transaction.block.hash,
3268
+ height: transaction.block.height,
3269
+ timestamp: transaction.block.timestamp
3270
+ },
3271
+ unshielded: {
3272
+ id: transaction.id,
3273
+ createdUtxos: createdUtxos.map(({ utxo }) => ({
3274
+ value: utxo.value,
3275
+ owner: utxo.owner,
3276
+ tokenType: utxo.type,
3277
+ intentHash: utxo.intentHash,
3278
+ outputIndex: utxo.outputNo
3279
+ })),
3280
+ spentUtxos: spentUtxos.map(({ utxo }) => ({
3281
+ value: utxo.value,
3282
+ owner: utxo.owner,
3283
+ tokenType: utxo.type,
3284
+ intentHash: utxo.intentHash,
3285
+ outputIndex: utxo.outputNo
3286
+ }))
3287
+ }
3288
+ });
3289
+ const makeDefaultTransactionHistoryService = (config, _getContext) => {
3290
+ const txHistoryStorage = config.txHistoryStorage;
3291
+ return { put: (update) => require_dist.tryPromise({
3292
+ try: () => txHistoryStorage.gotFinalized(convertUpdateToFinalizedInput(update)),
3293
+ catch: (e) => new TransactionHistoryError({
3294
+ message: "Failed to record finalized history entry",
3295
+ cause: e
3296
+ })
3297
+ }) };
3298
+ };
3299
+ //#endregion
3300
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/v1/V1Builder.js
3301
+ var V1Builder = class V1Builder {
3302
+ #buildState;
3303
+ constructor(buildState = {}) {
3304
+ this.#buildState = buildState;
3305
+ }
3306
+ withDefaults() {
3307
+ return this.withSyncDefaults().withSerializationDefaults().withTransactingDefaults().withSigningDefaults().withCoinsAndBalancesDefaults().withTransactionHistoryDefaults().withKeysDefaults().withCoinSelectionDefaults();
3308
+ }
3309
+ withSyncDefaults() {
3310
+ return this.withSync(makeDefaultSyncService, makeDefaultSyncCapability);
3311
+ }
3312
+ withSync(syncService, syncCapability) {
3313
+ return new V1Builder({
3314
+ ...this.#buildState,
3315
+ syncService,
3316
+ syncCapability
3317
+ });
3318
+ }
3319
+ withSerializationDefaults() {
3320
+ return this.withSerialization(makeDefaultV1SerializationCapability);
3321
+ }
3322
+ withSerialization(serializationCapability) {
3323
+ return new V1Builder({
3324
+ ...this.#buildState,
3325
+ serializationCapability
3326
+ });
3327
+ }
3328
+ withTransactingDefaults() {
3329
+ return this.withTransacting(makeDefaultTransactingCapability);
3330
+ }
3331
+ withTransacting(transactingCapability) {
3332
+ return new V1Builder({
3333
+ ...this.#buildState,
3334
+ transactingCapability
3335
+ });
3336
+ }
3337
+ withSigningDefaults() {
3338
+ return this.withSigning(makeDefaultSigningService);
3339
+ }
3340
+ withSigning(signingService) {
3341
+ return new V1Builder({
3342
+ ...this.#buildState,
3343
+ signingService
3344
+ });
3345
+ }
3346
+ /**
3347
+ * Configures this variant to start from an empty wallet when there is nothing before it.
3348
+ *
3349
+ * @remarks
3350
+ * The default for a first-registered variant, and what `startEmpty` relies on.
3351
+ * @returns A builder whose previous state is `null`.
3352
+ */
3353
+ withMigrationDefaults() {
3354
+ return this.withMigration((configuration) => makeEmptyWalletMigration({ networkId: configuration.networkId }));
3355
+ }
3356
+ /**
3357
+ * Configures how this variant produces its first state from whatever variant preceded it.
3358
+ *
3359
+ * @remarks
3360
+ * The context is a method-level type parameter rather than the builder's own `TContext`, matching `withSync` and
3361
+ * `withKeys` in this file. Binding it to the builder's `TContext` would make the builder invariant in it and break
3362
+ * the partially-configured chains the tests build.
3363
+ * @param migration Produces the strategy from the configuration and the variant context.
3364
+ * @returns A builder whose previous state is whatever the strategy consumes.
3365
+ */
3366
+ withMigration(migration) {
3367
+ const { migration: _replaced, ...capabilities } = this.#buildState;
3368
+ return new V1Builder({
3369
+ ...capabilities,
3370
+ migration
3371
+ });
3372
+ }
3373
+ withCoinSelection(coinSelection) {
3374
+ return new V1Builder({
3375
+ ...this.#buildState,
3376
+ coinSelection
3377
+ });
3378
+ }
3379
+ withCoinSelectionDefaults() {
3380
+ return this.withCoinSelection(() => require_dist.chooseCoin);
3381
+ }
3382
+ withCoinsAndBalancesDefaults() {
3383
+ return this.withCoinsAndBalances(makeDefaultCoinsAndBalancesCapability);
3384
+ }
3385
+ withCoinsAndBalances(coinsAndBalancesCapability) {
3386
+ return new V1Builder({
3387
+ ...this.#buildState,
3388
+ coinsAndBalancesCapability
3389
+ });
3390
+ }
3391
+ withTransactionHistoryDefaults() {
3392
+ return this.withTransactionHistory(makeDefaultTransactionHistoryService);
3393
+ }
3394
+ withTransactionHistory(transactionHistoryService) {
3395
+ return new V1Builder({
3396
+ ...this.#buildState,
3397
+ transactionHistoryService
3398
+ });
3399
+ }
3400
+ withKeysDefaults() {
3401
+ return this.withKeys(makeDefaultKeysCapability);
3402
+ }
3403
+ withKeys(keysCapability) {
3404
+ return new V1Builder({
3405
+ ...this.#buildState,
3406
+ keysCapability
3407
+ });
3408
+ }
3409
+ build(configuration) {
3410
+ const v1Context = this.#buildContextFromBuildState(configuration);
3411
+ const migration = this.#resolveMigration(configuration, () => v1Context);
3412
+ return {
3413
+ __polyTag__: V1Tag,
3414
+ coinsAndBalances: v1Context.coinsAndBalancesCapability,
3415
+ keys: v1Context.keysCapability,
3416
+ serialization: v1Context.serializationCapability,
3417
+ transactionHistory: v1Context.transactionHistoryService,
3418
+ start(context) {
3419
+ return require_dist.gen(function* () {
3420
+ return new RunningV1Variant(yield* require_dist.Scope, context, v1Context);
3421
+ });
3422
+ },
3423
+ migrateState(previousState) {
3424
+ return migration.migrate(previousState).pipe(require_dist.mapError$2((error) => new require_dist.WalletRuntimeError({
3425
+ message: "Failed to migrate unshielded wallet state into this variant",
3426
+ cause: error
3427
+ })));
3428
+ },
3429
+ deserializeState: (serialized) => {
3430
+ return v1Context.serializationCapability.deserialize(serialized);
3431
+ }
3432
+ };
3433
+ }
3434
+ /**
3435
+ * The migration strategy to build with.
3436
+ *
3437
+ * @remarks
3438
+ * An unconfigured builder produces an empty wallet, which is what `startEmpty` asks of a first variant. The nullary
3439
+ * wrapper is what lets the `null`-consuming default stand in for a `TPreviousState`-consuming strategy without a
3440
+ * cast: the argument is simply not passed on.
3441
+ */
3442
+ #resolveMigration(configuration, getContext) {
3443
+ const configured = this.#buildState.migration;
3444
+ return configured === void 0 ? { migrate: () => makeEmptyWalletMigration({ networkId: configuration.networkId }).migrate(null) } : configured(configuration, getContext);
3445
+ }
3446
+ #buildContextFromBuildState(configuration) {
3447
+ if (!isBuildStateFull(this.#buildState)) throw new Error("Not all components are configured in V2 Builder");
3448
+ const { syncCapability, syncService, transactingCapability, signingService, serializationCapability, coinSelection, coinsAndBalancesCapability, keysCapability, transactionHistoryService } = this.#buildState;
3449
+ const getContext = () => context;
3450
+ const context = {
3451
+ serializationCapability: serializationCapability(configuration, getContext),
3452
+ syncCapability: syncCapability(configuration, getContext),
3453
+ syncService: syncService(configuration, getContext),
3454
+ transactingCapability: transactingCapability(configuration, getContext),
3455
+ signingService: signingService(configuration, getContext),
3456
+ coinsAndBalancesCapability: coinsAndBalancesCapability(configuration, getContext),
3457
+ keysCapability: keysCapability(configuration, getContext),
3458
+ coinSelection: coinSelection(configuration, getContext),
3459
+ transactionHistoryService: transactionHistoryService(configuration, getContext)
3460
+ };
3461
+ return context;
3462
+ }
3463
+ };
3464
+ const isBuildStateFull = (buildState) => {
3465
+ return [
3466
+ "syncService",
3467
+ "syncCapability",
3468
+ "transactingCapability",
3469
+ "signingService",
3470
+ "coinSelection",
3471
+ "serializationCapability",
3472
+ "coinsAndBalancesCapability",
3473
+ "keysCapability",
3474
+ "transactionHistoryService"
3475
+ ].every((key) => typeof buildState[key] == "function");
3476
+ };
3477
+ //#endregion
3478
+ //#region ../../packages/module/passport-account/node_modules/@midnightntwrk/wallet-sdk-unshielded-wallet/dist/UnshieldedWallet.js
3479
+ /**
3480
+ * The same identity, as ledger-v8 has it.
3481
+ *
3482
+ * @remarks
3483
+ * Unshielded's one genuine version break, and the whole of it. A ledger-v9 verifying key is a `{tag, value}` record
3484
+ * naming a signature scheme; a ledger-v8 one is the bare hex, with no room to name anything, because that ledger
3485
+ * version had exactly one scheme. So a schnorr identity narrows losslessly — dropping a tag whose value was never in
3486
+ * doubt — and the cross-ledger migration widens it back on the way over, which is where its `schnorr` default comes
3487
+ * from.
3488
+ *
3489
+ * An ecdsa identity does not narrow at all, and `None` says so rather than dropping the tag and producing a ledger-v8
3490
+ * wallet claiming an identity it does not have: an ecdsa key derives a _different_ address, and the migration back
3491
+ * would relabel it `schnorr`, so the round trip is not merely lossy but wrong. The address itself is a scheme-less
3492
+ * hash and is carried, not re-derived, which is why the schnorr narrowing needs no ledger call at all.
3493
+ * @param publicKey The identity in ledger-v9's shape.
3494
+ * @returns The same identity as ledger-v8 has it, or `None` when that version cannot express it.
3495
+ */
3496
+ const asV1PublicKey = (publicKey) => publicKey.publicKey.tag === "schnorr" ? require_dist.some({
3497
+ publicKey: publicKey.publicKey.value,
3498
+ addressHex: publicKey.addressHex,
3499
+ address: publicKey.address
3500
+ }) : require_dist.none();
3501
+ /**
3502
+ * Builds an unshielded wallet class over a variant either side of a protocol boundary.
3503
+ *
3504
+ * @remarks
3505
+ * The boundary is `configuration.forks.v9` and nothing else: the V1 variant is registered from the minimum supported
3506
+ * version and the ledger-v9 one from the fork version, so the version at which the runtime hands over and the version
3507
+ * at which each variant stops applying are the same number, taken from one place.
3508
+ *
3509
+ * Each variant is built from its own configuration — see {@link SelfConfiguredUnshieldedVariant}.
3510
+ * @example
3511
+ * ```typescript
3512
+ * const Wallet = CustomForkingUnshieldedWallet(
3513
+ * { networkId, forks },
3514
+ * { builder: new V1Builder().withDefaults(), configuration: v1Configuration },
3515
+ * { builder: new V2Builder().withDefaults().withMigration(...), configuration: v2Configuration },
3516
+ * );
3517
+ * const wallet = Wallet.startWithPublicKey(publicKey);
3518
+ * ```;
3519
+ *
3520
+ * @param configuration What the wallet layer needs: the network, and where the boundary lies.
3521
+ * @param v1 The variant that reads the chain below the boundary, with the configuration it is built from.
3522
+ * @param v2 The variant that reads it from the boundary, with the configuration it is built from.
3523
+ * @returns The wallet class.
3524
+ */
3525
+ function CustomForkingUnshieldedWallet(configuration, v1, v2) {
3526
+ const v1Builder = v1.builder;
3527
+ const v2Builder = v2.builder;
3528
+ const BaseWallet = require_dist.WalletBuilder.init().withVariant(require_dist.MinSupportedVersion, v1Builder, v1.configuration).withVariant(configuration.forks.v9, v2Builder, v2.configuration).build();
3529
+ const variants = BaseWallet.allVariantsRecord();
3530
+ /**
3531
+ * The protocol versions each variant owns, and the version a transaction it builds is stamped with.
3532
+ *
3533
+ * @remarks
3534
+ * The stamp is the floor of the variant's epoch: every decision it is later read for asks which side of the boundary
3535
+ * the bytes belong to, and the floor answers that the same way as any other version in the same epoch.
3536
+ */
3537
+ const v8Epoch = require_dist.epochOf(require_dist.MinSupportedVersion, configuration.forks.v9);
3538
+ const v9Epoch = require_dist.epochOf(configuration.forks.v9, configuration.forks.v9);
3539
+ const [v8Stamp] = v8Epoch;
3540
+ const [v9Stamp] = v9Epoch;
3541
+ /** Reads a transaction built before the boundary, refusing one built after it. */
3542
+ const v8Tx = (handle) => require_dist.toEffect(require_dist.WalletTransaction.unwrapWithin(handle, v8Epoch));
3543
+ /** Reads a transaction built from the boundary, refusing one built before it. */
3544
+ const v9Tx = (handle) => require_dist.toEffect(require_dist.WalletTransaction.unwrapWithin(handle, v9Epoch));
3545
+ /** Seals a balancing result, which is absent when the wallet had nothing of its own to add. */
3546
+ const sealV8 = (result) => result === void 0 ? void 0 : require_dist.WalletTransaction.adopt("Unproven", result, v8Stamp);
3547
+ const sealV9 = (result) => result === void 0 ? void 0 : require_dist.WalletTransaction.adopt("Unproven", result, v9Stamp);
3548
+ /**
3549
+ * Adapts the caller's signer to ledger-v8's signature shape.
3550
+ *
3551
+ * @remarks
3552
+ * The SDK's signing callback speaks ledger-v9's signature — a scheme and its bytes — because that is the shape an
3553
+ * application writes against once. What ledger-v8 reads is the bytes alone, and only of the one scheme it has, so a
3554
+ * signer that answers with any other is refused by name here rather than at the WASM boundary.
3555
+ */
3556
+ const loweredSigner = (signSegment) => (data) => signSegment(data).then((signature) => require_dist.getOrThrowWith(require_v8Signatures.lowerSignature(signature), (error) => error));
3557
+ /**
3558
+ * How long a start waits for the chain to say which version it is on.
3559
+ *
3560
+ * @remarks
3561
+ * Short, because what is being bought is small: the alternative to an answer is the hand-over this wallet has always
3562
+ * done, which costs one migration and no correctness on a chain that produces messages. It is a ceiling rather than
3563
+ * a typical cost — an unreachable indexer refuses a connection long before this — and it exists so that a probe
3564
+ * which neither answers nor fails cannot hold a start open indefinitely.
3565
+ */
3566
+ const probeTimeout = require_dist.seconds(5);
3567
+ /**
3568
+ * The variant the chain's current version belongs to, or nothing.
3569
+ *
3570
+ * @remarks
3571
+ * Nothing covers every way the question can fail to produce an answer, and they are deliberately not distinguished:
3572
+ * no probe configured, a probe that rejected, a probe that outlived the wallet's patience, or a version no
3573
+ * registered variant claims. Each means the same thing to a caller — start where a wallet with no history starts —
3574
+ * and none of them is a reason to fail.
3575
+ */
3576
+ const probedStart = configuration.chainVersionProbe === void 0 ? require_dist.succeedNone : require_dist.pipe(require_dist.tryPromise(configuration.chainVersionProbe), require_dist.timeout(probeTimeout), require_dist.map$2((version) => require_dist.map$5(BaseWallet.variantFor(version), (variant) => ({
3577
+ version,
3578
+ variant
3579
+ }))), require_dist.orElseSucceed(() => require_dist.none()));
3580
+ /**
3581
+ * A fresh state of the variant a probed start begins at, recording the version the chain reported.
3582
+ *
3583
+ * @remarks
3584
+ * Built exactly as the head-variant boot path builds its own — the identity, in the shape that variant holds it — and
3585
+ * then annotated with the observed version, which is what keeps a variant from starting outside its own activation
3586
+ * range and signalling backwards on sight.
3587
+ * @param variant The variant the chain's version resolved to.
3588
+ * @param publicKey The identity in the shape this wallet's API speaks.
3589
+ * @param v1PublicKey The same identity as ledger-v8 has it, which is only reached when that variant is the one chosen
3590
+ * — and only a schnorr identity ever gets here at all.
3591
+ */
3592
+ const freshStateAt = (variant, publicKey, v1PublicKey, version) => require_dist.getVersionedVariantTag(variant) === V2Tag ? CoreWallet$1.withProtocolVersion(CoreWallet$1.init(publicKey, configuration.networkId), version) : CoreWallet.withProtocolVersion(CoreWallet.init(v1PublicKey, configuration.networkId), version);
3593
+ return class ForkingUnshieldedWalletImplementation extends BaseWallet {
3594
+ static configuration = configuration;
3595
+ static startWithPublicKey(publicKey) {
3596
+ return require_dist.match$1(asV1PublicKey(publicKey), {
3597
+ onSome: (v1PublicKey) => require_dist.pipe(probedStart, require_dist.map$2(require_dist.match$1({
3598
+ onNone: () => ForkingUnshieldedWalletImplementation.startFirst(ForkingUnshieldedWalletImplementation, CoreWallet.init(v1PublicKey, configuration.networkId)),
3599
+ onSome: ({ version, variant }) => ForkingUnshieldedWalletImplementation.startAtVariant(ForkingUnshieldedWalletImplementation, variant, freshStateAt(variant, publicKey, v1PublicKey, version))
3600
+ })), require_dist.runPromise$1),
3601
+ onNone: () => Promise.resolve(ForkingUnshieldedWalletImplementation.startAtVariant(ForkingUnshieldedWalletImplementation, variants[V2Tag], CoreWallet$1.withProtocolVersion(CoreWallet$1.init(publicKey, configuration.networkId), configuration.forks.v9)))
3602
+ });
3603
+ }
3604
+ static tryRestore(serializedState) {
3605
+ return variantForSnapshot(serializedState, (version) => ForkingUnshieldedWalletImplementation.variantFor(version), require_dist.head(ForkingUnshieldedWalletImplementation.allVariants())).pipe(require_dist.flatMap$4((variant) => {
3606
+ const deserialized = variant.variant.deserializeState(serializedState);
3607
+ return require_dist.map$6(deserialized, (state) => ForkingUnshieldedWalletImplementation.startAtVariant(ForkingUnshieldedWalletImplementation, variant, state));
3608
+ }));
3609
+ }
3610
+ static restore(serializedState) {
3611
+ return require_dist.getOrThrow$1(ForkingUnshieldedWalletImplementation.tryRestore(serializedState));
3612
+ }
3613
+ state;
3614
+ /**
3615
+ * Whether the activation watcher has been registered.
3616
+ *
3617
+ * @remarks
3618
+ * Registration is per wallet, not per `start`: watchers accumulate, so registering on every call would restart sync
3619
+ * once per historical `start` on the next activation. Flipped with `getAndSet` so concurrent `start` calls cannot
3620
+ * both observe it unset.
3621
+ */
3622
+ #watcherRegistered = require_dist.unsafeMake(false);
3623
+ /**
3624
+ * Whether the wallet is currently started.
3625
+ *
3626
+ * @remarks
3627
+ * The unshielded counterpart of the retained start material the shielded and dust wallets hold. This wallet is
3628
+ * watch-only — sync needs nothing secret, and signing is supplied per call by the caller — so there is no key to
3629
+ * keep and the restart needs no argument. All the watcher has to know is whether a stopped wallet should be left
3630
+ * stopped, which is what this records; `stop` clears it so a stopped wallet cannot be resurrected by a late
3631
+ * activation.
3632
+ */
3633
+ #started = require_dist.unsafeMake(false);
3634
+ constructor(runtime, scope) {
3635
+ super(runtime, scope);
3636
+ this.state = this.rawState.pipe(rxjs.map((emission) => emission.variantTag === V2Tag ? UnshieldedWalletState.fromVariant(variants[V2Tag].variant, emission) : UnshieldedWalletState.fromVariant(variants[V1Tag].variant, emission)), rxjs.shareReplay({
3637
+ refCount: true,
3638
+ bufferSize: 1
3639
+ }));
3640
+ }
3641
+ /**
3642
+ * Starts background synchronization on whichever variant is current.
3643
+ *
3644
+ * @remarks
3645
+ * Takes no argument, on either side of the boundary, and that is the shape of the whole wallet: an unshielded
3646
+ * wallet watches an address, and an address is public. A migration therefore strands nothing — the new variant is
3647
+ * simply told to start, exactly as the old one was.
3648
+ */
3649
+ start() {
3650
+ return require_dist.gen(this, function* () {
3651
+ yield* require_dist.set(this.#started, true);
3652
+ if (!(yield* require_dist.getAndSet(this.#watcherRegistered, true))) yield* this.runtime.onVariantActivation({
3653
+ [V1Tag]: (v1) => this.#resumeSyncOn(v1),
3654
+ [V2Tag]: (v2) => this.#resumeSyncOn(v2)
3655
+ });
3656
+ yield* this.runtime.dispatch({
3657
+ [V1Tag]: (v1) => v1.startSyncInBackground(),
3658
+ [V2Tag]: (v2) => v2.startSyncInBackground()
3659
+ });
3660
+ }).pipe(require_dist.runPromise$1);
3661
+ }
3662
+ /** Starts synchronization on a variant that has just become current, unless the wallet has been stopped. */
3663
+ #resumeSyncOn(running) {
3664
+ return require_dist.get$1(this.#started).pipe(require_dist.flatMap$1((started) => started ? running.startSyncInBackground() : require_dist._void));
3665
+ }
3666
+ async stop() {
3667
+ require_dist.set(this.#started, false).pipe(require_dist.runSync);
3668
+ await super.stop();
3669
+ }
3670
+ balanceFinalizedTransaction(tx) {
3671
+ return this.runtime.dispatch({
3672
+ [V1Tag]: (v1) => v8Tx(tx).pipe(require_dist.flatMap$1((unwrapped) => v1.balanceFinalizedTransaction(unwrapped)), require_dist.map$2(sealV8)),
3673
+ [V2Tag]: (v2) => v9Tx(tx).pipe(require_dist.flatMap$1((unwrapped) => v2.balanceFinalizedTransaction(unwrapped)), require_dist.map$2(sealV9))
3674
+ }).pipe(require_dist.runPromise$1);
3675
+ }
3676
+ /**
3677
+ * Balances an unbound transaction, which happens in place rather than by producing a second transaction.
3678
+ *
3679
+ * @returns The transaction with this wallet's inputs added, or nothing when it needed none.
3680
+ */
3681
+ balanceUnboundTransaction(tx) {
3682
+ return this.runtime.dispatch({
3683
+ [V1Tag]: (v1) => v8Tx(tx).pipe(require_dist.flatMap$1((unwrapped) => v1.balanceUnboundTransaction(unwrapped)), require_dist.map$2((result) => result === void 0 ? void 0 : require_dist.WalletTransaction.adopt("Unbound", result, v8Stamp))),
3684
+ [V2Tag]: (v2) => v9Tx(tx).pipe(require_dist.flatMap$1((unwrapped) => v2.balanceUnboundTransaction(unwrapped)), require_dist.map$2((result) => result === void 0 ? void 0 : require_dist.WalletTransaction.adopt("Unbound", result, v9Stamp)))
3685
+ }).pipe(require_dist.runPromise$1);
3686
+ }
3687
+ balanceUnprovenTransaction(tx) {
3688
+ return this.runtime.dispatch({
3689
+ [V1Tag]: (v1) => v8Tx(tx).pipe(require_dist.flatMap$1((unwrapped) => v1.balanceUnprovenTransaction(unwrapped)), require_dist.map$2(sealV8)),
3690
+ [V2Tag]: (v2) => v9Tx(tx).pipe(require_dist.flatMap$1((unwrapped) => v2.balanceUnprovenTransaction(unwrapped)), require_dist.map$2(sealV9))
3691
+ }).pipe(require_dist.runPromise$1);
3692
+ }
3693
+ transferTransaction(outputs, ttl) {
3694
+ return this.runtime.dispatch({
3695
+ [V1Tag]: (v1) => v1.transferTransaction(outputs, ttl).pipe(require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unproven", tx, v8Stamp))),
3696
+ [V2Tag]: (v2) => v2.transferTransaction(outputs, ttl).pipe(require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unproven", tx, v9Stamp)))
3697
+ }).pipe(require_dist.runPromise$1);
3698
+ }
3699
+ rotateUtxos(guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl) {
3700
+ return this.runtime.dispatch({
3701
+ [V1Tag]: (v1) => require_dist.toEffect(require_v8Signatures.lowerSignatureVerifyingKey(nightVerifyingKey)).pipe(require_dist.flatMap$1((key) => v1.rotateUtxos(guaranteedUtxos, fallibleUtxos, key, ttl)), require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unproven", tx, v8Stamp))),
3702
+ [V2Tag]: (v2) => v2.rotateUtxos(guaranteedUtxos, fallibleUtxos, nightVerifyingKey, ttl).pipe(require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unproven", tx, v9Stamp)))
3703
+ }).pipe(require_dist.runPromise$1);
3704
+ }
3705
+ initSwap(desiredInputs, desiredOutputs, ttl) {
3706
+ return this.runtime.dispatch({
3707
+ [V1Tag]: (v1) => v1.initSwap(desiredInputs, desiredOutputs, ttl).pipe(require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unproven", tx, v8Stamp))),
3708
+ [V2Tag]: (v2) => v2.initSwap(desiredInputs, desiredOutputs, ttl).pipe(require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unproven", tx, v9Stamp)))
3709
+ }).pipe(require_dist.runPromise$1);
3710
+ }
3711
+ signUnprovenTransaction(transaction, signSegment) {
3712
+ return this.runtime.dispatch({
3713
+ [V1Tag]: (v1) => v8Tx(transaction).pipe(require_dist.flatMap$1((unwrapped) => v1.signUnprovenTransaction(unwrapped, loweredSigner(signSegment))), require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unproven", tx, v8Stamp))),
3714
+ [V2Tag]: (v2) => v9Tx(transaction).pipe(require_dist.flatMap$1((unwrapped) => v2.signUnprovenTransaction(unwrapped, signSegment)), require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unproven", tx, v9Stamp)))
3715
+ }).pipe(require_dist.runPromise$1);
3716
+ }
3717
+ signUnboundTransaction(transaction, signSegment) {
3718
+ return this.runtime.dispatch({
3719
+ [V1Tag]: (v1) => v8Tx(transaction).pipe(require_dist.flatMap$1((unwrapped) => v1.signUnboundTransaction(unwrapped, loweredSigner(signSegment))), require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unbound", tx, v8Stamp))),
3720
+ [V2Tag]: (v2) => v9Tx(transaction).pipe(require_dist.flatMap$1((unwrapped) => v2.signUnboundTransaction(unwrapped, signSegment)), require_dist.map$2((tx) => require_dist.WalletTransaction.adopt("Unbound", tx, v9Stamp)))
3721
+ }).pipe(require_dist.runPromise$1);
3722
+ }
3723
+ /**
3724
+ * Un-books the UTxOs a transaction of this wallet's had reserved, returning them to the available set.
3725
+ *
3726
+ * @remarks
3727
+ * A transaction built on the other side of the boundary has nothing booked in the running variant to release, so
3728
+ * this resolves having done nothing. That is a fact about the crossing rather than an assumption made here:
3729
+ * {@link Migration.makeCrossLedgerMigration} restores every UTxO the V1 variant had booked as _available_,
3730
+ * precisely because a ledger-v8 transaction can never be included past the boundary — so by the time the
3731
+ * ledger-v9 variant is running, no ledger-v8 handle is holding anything. Doing nothing is therefore the whole of
3732
+ * the correct behaviour, not a release quietly skipped.
3733
+ *
3734
+ * It is also the one place a version mismatch is not an error: the facade reverts all three wallets together when a
3735
+ * submission fails, and a refusal here would strand that whole path over a transaction this wallet was never
3736
+ * holding anything for.
3737
+ * @param transaction The transaction to un-book.
3738
+ */
3739
+ revertTransaction(transaction) {
3740
+ return this.runtime.dispatch({
3741
+ [V1Tag]: (v1) => require_dist.match$2(require_dist.WalletTransaction.unwrapWithin(transaction, v8Epoch), {
3742
+ onLeft: () => require_dist._void,
3743
+ onRight: (unwrapped) => v1.revertTransaction(unwrapped)
3744
+ }),
3745
+ [V2Tag]: (v2) => require_dist.match$2(require_dist.WalletTransaction.unwrapWithin(transaction, v9Epoch), {
3746
+ onLeft: () => require_dist._void,
3747
+ onRight: (unwrapped) => v2.revertTransaction(unwrapped)
3748
+ })
3749
+ }).pipe(require_dist.runPromise$1);
3750
+ }
3751
+ waitForSyncedState(allowedGap = 0n) {
3752
+ return rxjs.firstValueFrom(this.state.pipe(rxjs.filter((state) => state.state.progress.isCompleteWithin(allowedGap))));
3753
+ }
3754
+ /**
3755
+ * Serializes the most recent state. It's preferable to use [[UnshieldedWalletState.serialize]] instead, to know
3756
+ * exactly which state is serialized.
3757
+ */
3758
+ serializeState() {
3759
+ return rxjs.firstValueFrom(this.state).then((state) => state.serialize());
3760
+ }
3761
+ getAddress() {
3762
+ return rxjs.firstValueFrom(this.state).then((state) => state.address);
3763
+ }
3764
+ };
3765
+ }
3766
+ /**
3767
+ * Builds the unshielded wallet this package ships: the default variant either side of `configuration.forks.v9`.
3768
+ *
3769
+ * @remarks
3770
+ * Both variants read the chain through the indexer's unshielded-transaction subscription and record transaction history
3771
+ * in the same storage, and both are built from the same application configuration, because what they ask for is
3772
+ * identical — unshielded sync carries no ledger object in either direction, only public UTXO records as JSON.
3773
+ *
3774
+ * Transacting, synchronization, balances, coins, addresses, serialization, restore and reverting all work on both
3775
+ * sides: each variant builds with its own ledger version, and what it produces says which version built it.
3776
+ *
3777
+ * **The chain is asked where it is before a variant is chosen.** The indexer this wallet already syncs from answers
3778
+ * which protocol version the chain is on, so a start on a chain past the boundary begins on V2 rather than handing
3779
+ * over immediately. An application that would rather ask something else — a cache, a value it already holds —
3780
+ * supplies its own `chainVersionProbe`; one whose chain cannot be reached loses nothing, because the answer is
3781
+ * best-effort and its absence is the behaviour this wallet had before.
3782
+ * @param configuration What the wallet and both its variants are built from, including where the boundary lies.
3783
+ * @returns The wallet class.
3784
+ */
3785
+ function UnshieldedWallet(configuration) {
3786
+ return CustomForkingUnshieldedWallet({
3787
+ ...configuration,
3788
+ chainVersionProbe: configuration.chainVersionProbe ?? require_dist.makeIndexerChainVersionProbe(configuration)
3789
+ }, {
3790
+ builder: new V1Builder().withDefaults(),
3791
+ configuration
3792
+ }, {
3793
+ builder: new V2Builder().withDefaults().withMigration(() => makeCrossLedgerMigration()),
3794
+ configuration
3795
+ });
3796
+ }
3797
+ //#endregion
3798
+ exports.CustomForkingUnshieldedWallet = CustomForkingUnshieldedWallet;
3799
+ exports.CustomUnshieldedWallet = CustomUnshieldedWallet;
3800
+ exports.PublicKey = PublicKey;
3801
+ Object.defineProperty(exports, "UnshieldedRestore", {
3802
+ enumerable: true,
3803
+ get: function() {
3804
+ return Restore_exports;
3805
+ }
3806
+ });
3807
+ exports.UnshieldedSectionSchema = UnshieldedSectionSchema;
3808
+ exports.UnshieldedSectionSchema$1 = UnshieldedSectionSchema;
3809
+ exports.UnshieldedWallet = UnshieldedWallet;
3810
+ exports.UnshieldedWalletState = UnshieldedWalletState;
3811
+ exports.asV1PublicKey = asV1PublicKey;
3812
+ exports.createKeystore = createKeystore;
3813
+ exports.mergeUnshieldedSections = mergeUnshieldedSections;
3814
+ exports.mergeUnshieldedSections$1 = mergeUnshieldedSections;