@laceio/sdk 0.1.1 → 0.1.2-canary.1

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-X1H9Gze6.cjs} +64 -14
  2. package/dist/{TransactionBuilder-V6aLx4SV.js → TransactionBuilder-bp2aMDhg.js} +23 -15
  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 +16962 -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-Dof_0N_d.cjs} +6 -6
  64. package/dist/{delegation-tx-builder-CGVqlaFE.js → delegation-tx-builder-Dy3-2Auz.js} +5 -5
  65. package/dist/{deregistration-tx-builder-DZGwB4cz.cjs → deregistration-tx-builder-CcLwyFpj.cjs} +6 -6
  66. package/dist/{deregistration-tx-builder-B-CrUyX6.js → deregistration-tx-builder-QkWW_gWl.js} +5 -5
  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-D5sUT5v8.cjs → earn-rewards-tx-builder-BP5JMIKS.cjs} +6 -6
  81. package/dist/{earn-rewards-tx-builder-BDbTDZmD.js → earn-rewards-tx-builder-Cku4BmNU.js} +5 -5
  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 +86279 -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 +37505 -10036
  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-CigestoM.js → init-B3-1ghyx.js} +2 -2
  134. package/dist/init-B8U3ABhS.cjs +107 -0
  135. package/dist/init-BJn-8_hf.js +141 -0
  136. package/dist/init-BPU3j8sT.cjs +6 -0
  137. package/dist/init-BRzH6xu-2.cjs +2797 -0
  138. package/dist/init-BmzfDaKL.js +1142 -0
  139. package/dist/{init-C-jErzp5.cjs → init-BopV9ed4.cjs} +2 -2
  140. package/dist/init-BpHTq2R5.js +105 -0
  141. package/dist/init-BpSITBfF.js +39 -0
  142. package/dist/{init-DX4WyB0R.cjs → init-BrdVzxei.cjs} +3 -3
  143. package/dist/{init-LfyMo-sS.cjs → init-BwkU0ruo.cjs} +2 -2
  144. package/dist/{init-CB__aLD7.cjs → init-C-G32J12.cjs} +2 -2
  145. package/dist/init-C00gw1zi.js +422 -0
  146. package/dist/{init-TkPq_Ny_.js → init-C2RgrfZe.js} +1 -1
  147. package/dist/init-C5mYyFTv.js +3584 -0
  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-Clu8pxwQ.cjs +1181 -0
  157. package/dist/{init-CFYsq82V.js → init-CyAY4Lzl.js} +1 -1
  158. package/dist/{init-BKhH6mVR.cjs → init-D6BxBs7e.cjs} +1 -1
  159. package/dist/init-D8OeObDF.cjs +1141 -0
  160. package/dist/init-D9g1HXYf.cjs +40 -0
  161. package/dist/{init-CNLGJJRx.js → init-DA7zmptx.js} +1 -1
  162. package/dist/{init-DkIc5nqF.cjs → init-DFMiP2ZH.cjs} +1 -1
  163. package/dist/{init-zSzCjoor.js → init-DFjT8YvT.js} +4 -4
  164. package/dist/init-DGjXwWs2.cjs +143 -0
  165. package/dist/init-DHrCbpkW.cjs +121 -0
  166. package/dist/init-DRzJR02G.cjs +3585 -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-DuYENxci.js +17 -0
  171. package/dist/{init-D6DBUsD3.cjs → init-Dv3zKj0r.cjs} +4 -4
  172. package/dist/{init-BtzMZ7Pk.cjs → init-Dy-05ktr.cjs} +1 -1
  173. package/dist/{init-BsCBAGWf.cjs → init-EP0CUWNK.cjs} +2 -2
  174. package/dist/{init-BJVU54pI.cjs → init-EhzD7a8i.cjs} +1 -1
  175. package/dist/{init-w9GEs73W.js → init-Fw89ZmrR.js} +2 -2
  176. package/dist/init-GsT2AEa4.cjs +424 -0
  177. package/dist/{init-Rxohwpmu.js → init-NCjgwCZy.js} +2 -2
  178. package/dist/{init-DxUHsN53.cjs → init-NdhG_VrF.cjs} +6 -6
  179. package/dist/{init-DDdhguVC.js → init-SZ01tARX2.js} +2 -2
  180. package/dist/{init-BAJJzBza.js → init-Y3mkB4XS.js} +2 -2
  181. package/dist/init-c4l6r-o-.js +5 -0
  182. package/dist/{init-Dku4b2lG.js → init-kEfUTuG2.js} +1 -1
  183. package/dist/{init-C7IeJwQR.cjs → init-lzHt4Cli.cjs} +256 -59
  184. package/dist/init-qSEd_Spq.js +1182 -0
  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-D9Gs2j60.cjs +1108 -0
  210. package/dist/modules-cardano-VIM8fKu-.js +995 -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-CmKv6GoG.js → vote-delegation-tx-builder-BsBSDmcX.js} +5 -5
  305. package/dist/{vote-delegation-tx-builder-BpEMSti4.cjs → vote-delegation-tx-builder-DSs8nybk.cjs} +6 -6
  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,2796 @@
1
+ import "./_polyfill-buffer-patch-yNxN4d5E.js";
2
+ import "./codecs-Dc1Krpbt.js";
3
+ import { n as HexBytes, t as ByteArray } from "./bytes.vo-BB7_4JK6.js";
4
+ import { A as OperationNotInstallableError, C as GrantScopeInvalidError, D as MaintenanceUpdateRefusedError, E as MaintenanceAuthorityMismatchError, F as RemovalTargetNotFoundError, M as ReadUnavailableError, N as RecordCorruptedError, O as NoAccountError, P as RecordUnreadableError, S as GrantRosterUnsettledError, T as LastDeviceError, _ as GrantNotFoundError, b as GrantRevocationPendingError, h as GrantIssueRejectedError, i as AccountNotFoundError, k as NotAuthorisedError, m as EncryptionKeyMismatchError, n as AccountCreationPendingError, p as DeviceRosterInvalidError, r as AccountExistsError, s as AuthorityRetiredError, t as AccountContractMissingError, u as CreationLockMismatchError, x as GrantRevokedError, y as GrantOriginMissingError } from "./errors-DSq5wUwt.js";
5
+ import { i as AccAddress, t as createMidnightProviders } from "./providers-WtiSuxFu.js";
6
+ import { a as loadVerifierKeys, c as submitMaintenanceUpdate, d as UseCounter, i as deployAccount, l as planInstallWaves, o as readMaintenanceAuthority, r as resolveUseCounter, s as resumeAccountDeployment, u as DeviceEpoch } from "./gated-call-D-tT7P_t.js";
7
+ import { i as accManifest } from "./artefact-loader-Dik4HIfv.js";
8
+ import { G as GrantScopeSalt, K as GrantId, U as validateGrantScope, W as GrantSlot, i as granteePoint, r as circuitScope } from "./grant-rules-By07_eDi.js";
9
+ import { n as TokenColor, t as storedGranteeScheme } from "./types-BHC12eSa.js";
10
+ import { a as isDeviceRegistration, i as isAddressedTo, n as deviceEnvelopes, o as isLaceRecord, r as encodeDevicePublicKey } from "./envelopes-BGoO_v8m.js";
11
+ import { t as GRANTEE_WITHDRAWAL_CIRCUITS } from "./grant-circuits-Jxb5y1HW.js";
12
+ import { c as maintenanceUpdateOf, p as DEPLOYED_OPERATIONS } from "./submit-DOv8Z0Vf.js";
13
+ import { n as ROTATE_ENC_KEY_CIRCUIT, t as APPEND_INBOX_CIRCUIT } from "./enc-key-circuits-B7BjgUL9.js";
14
+ import { i as ledger } from "./acc-module-Cmj8EsIb.js";
15
+ import { i as resolveLiveReaders, t as assertJoiningDevice } from "./device-readers-CUHYoYOH.js";
16
+ import { a as originHash, c as prepareRevokeGrant, n as deriveGrantId, o as prepareIssueGrant, r as grantObjectCommit, s as prepareRevokeAllGrants } from "./grants-CtofFu-e.js";
17
+ import { a as readAccountLedger, c as createIndexerClient, i as queryAccountOperations, n as isNotAuthorisedAbort, o as submitAccountCall, r as queryAccountLedger, s as withRefreshedLocalDevice } from "./account-call-C3CkDqEC.js";
18
+ import { EMPTY, Observable, catchError, concat, concatMap, defaultIfEmpty, defer, exhaustMap, filter, firstValueFrom, map, merge, mergeMap, of, withLatestFrom } from "rxjs";
19
+ //#region ../../packages/module/passport-account/src/acc/device-circuits.ts
20
+ /**
21
+ * The gated circuits the device flows authorise, named once so the flow
22
+ * that submits a call and the signer that scopes a key session to it
23
+ * agree on the circuit.
24
+ */
25
+ const ADD_DEVICE_CIRCUIT = "add_device_with_jubjub";
26
+ const REMOVE_DEVICE_CIRCUIT = "remove_device_with_jubjub";
27
+ //#endregion
28
+ //#region ../../packages/module/passport-account/src/acc/pending-deployment.ts
29
+ /** Whether a record's pending creation carries the whole deployment, not only its marker. */
30
+ const isPendingDeployment = (pending) => "authorityKey" in pending;
31
+ /**
32
+ * The refusal of a creation that resumes an unfinished one under another
33
+ * lock choice than `recorded`, the one it was started with, which the
34
+ * message names so a retry can repeat it.
35
+ */
36
+ const lockChoiceMismatch = (recorded) => new CreationLockMismatchError(`The unfinished Passport account creation was started with lockAccount ${recorded}; resume it with the same lock choice.`);
37
+ //#endregion
38
+ //#region ../../packages/module/passport-account/src/store/envelope.ts
39
+ /** AES-GCM is specified for 96-bit IVs; each seal draws a fresh one. */
40
+ const IV_LENGTH = 12;
41
+ const utf8 = (value) => new TextEncoder().encode(value);
42
+ /** Whether a stored value has the sealed envelope layout. */
43
+ const isSealedRecord = (value) => {
44
+ if (typeof value !== "object" || value === null) return false;
45
+ const candidate = value;
46
+ return candidate.v === 1 && typeof candidate.iv === "string" && typeof candidate.ciphertext === "string";
47
+ };
48
+ /**
49
+ * Encrypts a record into a {@link SealedRecord} under the given key,
50
+ * marking the envelope pending when asked.
51
+ */
52
+ const sealRecord = async (key, record, { pending = false } = {}) => {
53
+ const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
54
+ const ciphertext = await crypto.subtle.encrypt({
55
+ name: "AES-GCM",
56
+ iv
57
+ }, key, utf8(JSON.stringify(record)));
58
+ return {
59
+ v: 1,
60
+ iv: HexBytes.fromByteArray(iv),
61
+ ciphertext: HexBytes.fromByteArray(new Uint8Array(ciphertext)),
62
+ ...pending ? { pending: true } : {}
63
+ };
64
+ };
65
+ /**
66
+ * Decrypts a {@link SealedRecord} back into the record it sealed. Any
67
+ * failure to open - a tampered ciphertext, a mismatched key, or a
68
+ * malformed envelope - throws RecordCorruptedError.
69
+ */
70
+ const openRecord = async (key, sealed) => {
71
+ try {
72
+ const plaintext = await crypto.subtle.decrypt({
73
+ name: "AES-GCM",
74
+ iv: ByteArray.fromHex(HexBytes(sealed.iv))
75
+ }, key, ByteArray.fromHex(HexBytes(sealed.ciphertext)));
76
+ return JSON.parse(new TextDecoder().decode(plaintext));
77
+ } catch {
78
+ throw new RecordCorruptedError();
79
+ }
80
+ };
81
+ //#endregion
82
+ //#region ../../packages/module/passport-account/src/store/account-record.ts
83
+ const COLLECTION_ID = "passport-account";
84
+ const ACCOUNT_RECORD_KEY = "account";
85
+ /**
86
+ * An {@link AccountRecordStore} over the platform key-value storage,
87
+ * namespaced under its own collection. With a `keyProvider` the record is
88
+ * sealed at rest and only sealed envelopes are readable. What a sealed
89
+ * record reads as without a `keyProvider` is the caller's choice:
90
+ * 'skip' (the default) reads it as undefined, for the ceremony-free
91
+ * restore peek that cannot open it by design; 'error' raises
92
+ * RecordUnreadableError, for the flows where a missing storage key is a
93
+ * persistence misconfiguration that must not look like an absent
94
+ * account. Without a `keyProvider` (the dev authoriser) the record
95
+ * persists in plaintext, which holds no secret once the account is
96
+ * complete; while a creation is unfinished it holds the contract's
97
+ * maintenance authority key (see {@link PassportAccountRecord}), so the
98
+ * dev authoriser is for development and tests only.
99
+ */
100
+ const createAccountRecordStore = (createKeyValueStorage, keyProvider, { onSealedWithoutKey = "skip" } = {}) => {
101
+ const storage = createKeyValueStorage({ collectionId: COLLECTION_ID });
102
+ const open = async (keyOf, value) => isSealedRecord(value) ? openRecord(await keyOf(), value) : void 0;
103
+ const stored = () => storage.getValues([ACCOUNT_RECORD_KEY]).pipe(map(([value]) => value), defaultIfEmpty(void 0));
104
+ const isPending = (record) => record.deployment !== void 0;
105
+ const presenceOf = (value) => {
106
+ if (value === void 0) return "absent";
107
+ return (isSealedRecord(value) ? value.pending === true : isPending(value)) ? "pending" : "complete";
108
+ };
109
+ return {
110
+ read: () => keyProvider ? stored().pipe(concatMap(async (value) => open(keyProvider, value))) : stored().pipe(map((value) => {
111
+ if (!isSealedRecord(value)) return value;
112
+ if (onSealedWithoutKey === "error") throw new RecordUnreadableError();
113
+ })),
114
+ write: (record) => keyProvider ? defer(async () => sealRecord(await keyProvider(), record, { pending: isPending(record) })).pipe(mergeMap((sealed) => storage.setValue(ACCOUNT_RECORD_KEY, sealed))) : storage.setValue(ACCOUNT_RECORD_KEY, record),
115
+ presence: () => stored().pipe(map(presenceOf))
116
+ };
117
+ };
118
+ /**
119
+ * The promise view of an {@link AccountRecordStore}, for the flows. A
120
+ * storage that completes without emitting (destroyed mid-flow) reads as
121
+ * absent and writes as done, mirroring the stream contract so a flow
122
+ * never hangs on it.
123
+ */
124
+ const toAccountRecords = (store) => ({
125
+ read: async () => firstValueFrom(store.read(), { defaultValue: void 0 }),
126
+ write: async (record) => firstValueFrom(store.write(record), { defaultValue: void 0 }),
127
+ presence: async () => firstValueFrom(store.presence(), { defaultValue: "absent" })
128
+ });
129
+ //#endregion
130
+ //#region ../../packages/module/passport-account/src/acc/inbox-walk.ts
131
+ const SCRATCH_BLOCK_TIME = /* @__PURE__ */ new Date(0);
132
+ const defaultLoadLedger = async () => import("@midnightntwrk/ledger-v9");
133
+ /** The entries the contract holds, in inbox order, the Lace records included. */
134
+ const inboxEntries = (ledgerState) => {
135
+ const entries = [];
136
+ for (let ordinal = 0n; ordinal < ledgerState.inbox_count; ordinal += 1n) if (ledgerState.inbox.member(ordinal)) entries.push(ledgerState.inbox.lookup(ordinal));
137
+ return entries;
138
+ };
139
+ /**
140
+ * The commitment the chain carries for a coin the account received,
141
+ * recomputed with the ledger's own output construction: a contract-owned
142
+ * output of this coin towards the account address, which is exactly what
143
+ * a depositor builds and the contract claims. A description the ledger
144
+ * refuses to commit to is no candidate.
145
+ */
146
+ const toCandidate = ({ ZswapOutput }, address, { coin, entry }) => {
147
+ const info = {
148
+ type: HexBytes.fromByteArray(coin.color),
149
+ nonce: HexBytes.fromByteArray(coin.nonce),
150
+ value: coin.value
151
+ };
152
+ try {
153
+ return {
154
+ coin,
155
+ info,
156
+ commitment: ZswapOutput.newContractOwned(info, void 0, address).commitment.toLowerCase(),
157
+ entry
158
+ };
159
+ } catch {
160
+ return null;
161
+ }
162
+ };
163
+ /**
164
+ * The nullifier each held coin's spend reveals, computed with the ledger's
165
+ * own input construction: a contract-owned input of the coin from the
166
+ * account, exactly what the contract builds when it spends one. A
167
+ * contract-owned nullifier binds the coin and the account address alone,
168
+ * never the coin's position, so the inputs are built over a scratch
169
+ * commitment tree holding just these coins rather than the chain's tree.
170
+ */
171
+ const coinNullifiers = ({ ZswapChainState, ZswapInput, ZswapOffer, ZswapOutput }, address, held) => {
172
+ const tree = held.reduce((state, { info }) => state.tryApply(ZswapOffer.fromOutput(ZswapOutput.newContractOwned(info, void 0, address), info.type, info.value))[0], new ZswapChainState()).postBlockUpdate(SCRATCH_BLOCK_TIME, 0n);
173
+ return held.map(({ info }, position) => ZswapInput.newContractOwned({
174
+ ...info,
175
+ mt_index: BigInt(position)
176
+ }, void 0, address, tree).nullifier.toLowerCase());
177
+ };
178
+ /**
179
+ * The shielded outputs the chain created for the account and the
180
+ * nullifiers it recorded, read from the ledger events of the transactions
181
+ * that acted on the contract. A deposit is one such action, so its
182
+ * transaction is among them; so is every spend of a coin the account
183
+ * holds, because only the contract's own call can spend it.
184
+ */
185
+ const chainHistory = async (address, indexer) => {
186
+ const actions = await indexer.enumerateContractActions(address);
187
+ const hashes = [...new Set(actions.map((action) => action.txHash))];
188
+ const events = await Promise.all(hashes.map(async (hash) => indexer.queryShieldedEvents(hash)));
189
+ const recipient = address.toLowerCase();
190
+ return {
191
+ outputs: new Map(events.flatMap(({ outputs }) => outputs).filter((output) => output.contractAddress === recipient).map((output) => [output.commitment, output.index])),
192
+ nullifiers: new Set(events.flatMap(({ nullifiers }) => nullifiers))
193
+ };
194
+ };
195
+ /**
196
+ * Walks the account's inbox the way the custody standard prescribes:
197
+ * every entry other than the Lace records, which hold the account keys
198
+ * and the grant bookkeeping rather than coins, is opened with the
199
+ * encryption secrets, each coin that opens is verified by recomputing
200
+ * its commitment and finding it among the outputs the chain created for
201
+ * the account, and the index that output took in the commitment tree is
202
+ * captured with it. A coin whose nullifier the same history recorded has
203
+ * been spent and is left out; nullifiers of other parties' inputs never
204
+ * match, since a contract-owned nullifier binds the account address.
205
+ * Anyone can append any bytes to the inbox, so an entry that does not open, or opens to a coin
206
+ * the chain never created for this account, is skipped as noise and
207
+ * counted, never raised. Two entries describing the same coin, as a
208
+ * re-encryption after a key rotation leaves behind, yield one holding,
209
+ * read from the first entry that described it. An empty inbox, or one
210
+ * with nothing that opens, is answered without loading the ledger or
211
+ * reading the chain's history. A ledger binding that fails to load is a
212
+ * failure of the walk itself, not of any entry, so it is raised rather
213
+ * than reported as an inbox of noise.
214
+ */
215
+ const walkInbox = async ({ address, ledgerState, indexer, openEntries, loadLedger = defaultLoadLedger }) => {
216
+ const entries = inboxEntries(ledgerState).filter((entry) => !isLaceRecord(entry));
217
+ const nothing = (skippedEntries) => ({
218
+ holdings: [],
219
+ holdingEntries: [],
220
+ skippedEntries
221
+ });
222
+ if (entries.length === 0) return nothing(0);
223
+ const coins = await openEntries(entries);
224
+ if (coins.every((coin) => coin === null)) return nothing(entries.length);
225
+ const ledger = await loadLedger();
226
+ const candidates = coins.map((coin, ordinal) => coin && toCandidate(ledger, address, {
227
+ coin,
228
+ entry: entries[ordinal]
229
+ }));
230
+ if (candidates.every((candidate) => candidate === null)) return nothing(entries.length);
231
+ const { outputs, nullifiers } = await chainHistory(address, indexer);
232
+ const held = /* @__PURE__ */ new Map();
233
+ let skippedEntries = 0;
234
+ for (const candidate of candidates) {
235
+ const index = candidate ? outputs.get(candidate.commitment) : void 0;
236
+ if (!candidate || index === void 0) {
237
+ skippedEntries += 1;
238
+ continue;
239
+ }
240
+ if (!held.has(candidate.commitment)) held.set(candidate.commitment, {
241
+ candidate,
242
+ index
243
+ });
244
+ }
245
+ const confirmed = [...held.values()];
246
+ const spent = nullifiers.size === 0 ? confirmed.map(() => false) : coinNullifiers(ledger, address, confirmed.map(({ candidate }) => candidate)).map((nullifier) => nullifiers.has(nullifier));
247
+ const unspent = confirmed.filter((_, position) => !spent[position]);
248
+ return {
249
+ holdings: unspent.map(({ candidate, index }) => ({
250
+ color: TokenColor(HexBytes.fromByteArray(candidate.coin.color)),
251
+ value: candidate.coin.value.toString(),
252
+ commitment: candidate.commitment,
253
+ index: Number(index)
254
+ })),
255
+ holdingEntries: unspent.map(({ candidate }) => candidate.entry),
256
+ skippedEntries
257
+ };
258
+ };
259
+ //#endregion
260
+ //#region ../../packages/module/passport-account/src/flows/key-session.ts
261
+ /**
262
+ * Runs an operation under a single key ceremony, so a flow that reaches
263
+ * for the device key several times costs one user prompt instead of one
264
+ * per authoriser call. `flow` names the flow for an authoriser that
265
+ * presents it before the ceremony. An authoriser with no interactive
266
+ * ceremony exposes no session, and the operation runs directly. The
267
+ * session function is used detached, so implementations must not rely on
268
+ * `this`.
269
+ */
270
+ const inKeySession = async (authoriser, flow, operation) => {
271
+ const { withKeySession } = authoriser;
272
+ return withKeySession ? withKeySession(operation, flow) : operation();
273
+ };
274
+ //#endregion
275
+ //#region ../../packages/module/passport-account/src/acc/enc-key-rotation.ts
276
+ /** Prepares `rotate_enc_key_with_jubjub` over the raw 32-byte X25519 key `enc_key` is replaced with. */
277
+ const prepareRotateEncKey = (newKey) => ({
278
+ circuit: ROTATE_ENC_KEY_CIRCUIT,
279
+ args: [newKey]
280
+ });
281
+ /** Prepares `append_inbox_with_jubjub` over one inbox entry: a re-encrypted coin or a Lace record. */
282
+ const prepareAppendInbox = (entry) => ({
283
+ circuit: APPEND_INBOX_CIRCUIT,
284
+ args: [entry]
285
+ });
286
+ //#endregion
287
+ //#region ../../packages/module/passport-account/src/flows/rotation.ts
288
+ /**
289
+ * How long an accepted call is given to show in the indexer's view of the
290
+ * ledger, which can lag the block the call landed in.
291
+ */
292
+ const LEDGER_POLL_ATTEMPTS = 30;
293
+ const LEDGER_POLL_DELAY_MS = 1e3;
294
+ const sleep$1 = async (ms) => new Promise((resolve) => {
295
+ setTimeout(resolve, ms);
296
+ });
297
+ /**
298
+ * The encryption key's view members, which a rotation and a read grant's
299
+ * issue need: the re-encryption a rotation moves the holdings through
300
+ * and the sealing a grantee receives the secret by.
301
+ *
302
+ * @throws {@link ReadUnavailableError} when the key offers either not,
303
+ * as a key that only opens entries does.
304
+ */
305
+ const viewCapability = (encryptionKey) => {
306
+ const { reencryptInbox, sealView } = encryptionKey;
307
+ if (!reencryptInbox || !sealView) throw new ReadUnavailableError();
308
+ return {
309
+ reencryptInbox,
310
+ sealView
311
+ };
312
+ };
313
+ /** Resolves this device's reader and device keys, inside the caller's key session. */
314
+ const readLocalDevice = async ({ passportAuthoriser, passportEncryptionKey, passportNetwork }) => ({
315
+ readerPublicKey: await passportEncryptionKey.readerPublicKey(passportNetwork.networkId),
316
+ devicePublicKey: encodeDevicePublicKey(await passportAuthoriser.devicePublicKey())
317
+ });
318
+ /** Reads the inbox and this device's keyring of the account from its ledger. */
319
+ const readAccountInbox = (account, ledgerState, readerPublicKey) => {
320
+ const entries = inboxEntries(ledgerState);
321
+ return {
322
+ entries,
323
+ keyring: {
324
+ account: AccAddress(account),
325
+ encKey: ledgerState.enc_key,
326
+ envelopes: deviceEnvelopes(entries, readerPublicKey)
327
+ }
328
+ };
329
+ };
330
+ /**
331
+ * The device entries the ledger holds, as lowercase hex, less `except`:
332
+ * the devices a rotation may seal the new secret to, which a key session
333
+ * names to the user before it opens.
334
+ *
335
+ * @throws {@link DeviceRosterInvalidError} when there are more than
336
+ * {@link MAX_DEVICE_ENTRIES}, which no signer would accept.
337
+ */
338
+ const liveDeviceEntries = (ledgerState, except) => {
339
+ const entries = [...ledgerState.devices].map((entry) => HexBytes.fromByteArray(entry)).filter((entry) => entry !== except?.toLowerCase());
340
+ if (entries.length > 64) throw new DeviceRosterInvalidError(`The account holds ${entries.length} device entries, more than the 64 a rotation names.`);
341
+ return entries;
342
+ };
343
+ /**
344
+ * The ledger once the indexer reflects a call that advanced the auth
345
+ * nonce past `authNonce`. A chain of gated calls must have each bind the
346
+ * nonce the previous one left behind, which the indexer can serve a
347
+ * moment late.
348
+ *
349
+ * @throws {@link GrantRosterUnsettledError} when the indexer never
350
+ * reflects the call within the polling window.
351
+ */
352
+ const awaitAdvancedLedger = async (indexer, address, authNonce) => {
353
+ for (let attempt = 0; attempt < LEDGER_POLL_ATTEMPTS; attempt++) {
354
+ const ledgerState = await queryAccountLedger(indexer, address);
355
+ if (ledgerState.auth_nonce > authNonce) return ledgerState;
356
+ await sleep$1(LEDGER_POLL_DELAY_MS);
357
+ }
358
+ throw new GrantRosterUnsettledError(`The ledger of ${address} never reflected the accepted call.`);
359
+ };
360
+ /**
361
+ * Starts a chain of gated calls at `start`. Each accepted call reports
362
+ * the counter it advanced this device to, then waits for the indexer to
363
+ * reflect it, so the next call binds the auth nonce it left; the local
364
+ * roster row follows the entry each call leaves it on.
365
+ */
366
+ const callChain = ({ account, start, indexer, seams, onProgress, onAdvanced }) => {
367
+ let current = start;
368
+ const submit = async (call) => {
369
+ const { advancedCounter, localCommitmentHex } = await submitAccountCall({
370
+ circuit: call.circuit,
371
+ args: call.args,
372
+ account,
373
+ localUseCounter: current.localUseCounter,
374
+ ledgerState: current.ledgerState,
375
+ onStage: onProgress
376
+ }, seams);
377
+ const localUseCounter = advancedCounter.toString();
378
+ await onAdvanced(localUseCounter);
379
+ current = {
380
+ ledgerState: await awaitAdvancedLedger(indexer, account.address, current.ledgerState.auth_nonce),
381
+ localUseCounter,
382
+ devices: withRefreshedLocalDevice(current.devices, localCommitmentHex)
383
+ };
384
+ };
385
+ return {
386
+ submit,
387
+ append: async (stage, entries) => {
388
+ if (entries.length > 0) onProgress(stage);
389
+ for (const entry of entries) await submit(prepareAppendInbox(entry));
390
+ },
391
+ position: () => current
392
+ };
393
+ };
394
+ /** The registrations of an inbox, by hex. */
395
+ const registrationsOf = (entries) => new Set(entries.filter(isDeviceRegistration).map((entry) => HexBytes.fromByteArray(entry)));
396
+ /**
397
+ * The roster a rotation seals to: the registrations the live roster key
398
+ * opens, resolved against the ledger's device set so only a registration
399
+ * whose device key derives a live entry counts, and only one whose entry
400
+ * is among `devices`. A registration naming nobody's live device is
401
+ * passed over, and named devices left without a reader, by a conflict or
402
+ * for want of a registration, are reported dropped, see
403
+ * {@link resolveLiveReaders}; this device, sealed to regardless, is never
404
+ * reported dropped. The registration whose live entry is `target`, the
405
+ * entry a removal takes out, is named so no reader paired with its device
406
+ * is sealed to.
407
+ */
408
+ const sealedRoster = async ({ account, encryptionKey, networkId, local, ledgerState, inbox, devices, target, localEntry }) => {
409
+ const registered = (await encryptionKey.openInbox(networkId, inbox.keyring, inbox.entries.filter(isDeviceRegistration))).flatMap((opened) => opened?.kind === "device" ? [opened.device] : []);
410
+ const self = HexBytes.fromByteArray(local.readerPublicKey);
411
+ const { readers, dropped, outside } = resolveLiveReaders({
412
+ scope: {
413
+ address: account.address,
414
+ epoch: ledgerState.device_epoch
415
+ },
416
+ registered,
417
+ isLive: (entryHex) => ledgerState.devices.member(ByteArray.fromHex(HexBytes(entryHex))),
418
+ allowed: new Set(devices),
419
+ target
420
+ });
421
+ const removed = outside.find(({ entryHex }) => entryHex === target);
422
+ return {
423
+ readers: readers.filter(({ reader }) => reader.readerPublicKey !== self).map(({ reader }) => reader),
424
+ dropped: dropped.filter((entry) => entry !== localEntry),
425
+ ...removed ? { removed: {
426
+ devicePublicKey: removed.reader.devicePublicKey,
427
+ epoch: removed.reader.epoch,
428
+ counter: removed.reader.counter
429
+ } } : {}
430
+ };
431
+ };
432
+ /**
433
+ * Rotates the account encryption key to a fresh random secret and
434
+ * re-encrypts every live holding towards it, as the scoped grants
435
+ * standard requires before a read grant is issued and after one is
436
+ * revoked, and as a device removal requires so the removed device reads
437
+ * nothing newer. The holdings are walked with the keyring of the ledger's
438
+ * `enc_key` from the position the chain is at, a keyring this device's
439
+ * envelopes do not open rejecting with EncryptionKeyMismatchError before
440
+ * anything is submitted. The encryption key draws the new secret and
441
+ * seals it, with the roster key, to this device and to every registered
442
+ * device that is enrolled now and among `devices`, and answers the
443
+ * ciphertexts alone: one envelope per device and, when the roster key is
444
+ * fresh, one registration each. Should any registration the live roster
445
+ * key opens land while the rotation runs, as another device's enrolment
446
+ * does, the rotation refuses with DeviceRosterInvalidError before
447
+ * `enc_key` is replaced, so a device enrolled meanwhile is never left
448
+ * without the new key; registrations that open under no roster key are
449
+ * noise and do not stop it. Devices whose registrations conflict are
450
+ * left out and reported in the result. The holdings are
451
+ * re-encrypted towards the new key, the envelopes and registrations are
452
+ * appended, `enc_key` is replaced through `rotate_enc_key_with_jubjub`,
453
+ * and each re-encrypted holding is appended, one gated call each, all in
454
+ * the key session the caller holds. The envelopes land ahead of the
455
+ * rotation, so no device is left without the key the chain then holds;
456
+ * a rotation interrupted after it leaves holdings under the previous
457
+ * key, which every device still opens from its older envelopes and the
458
+ * next rotation re-encrypts. The previous secret is never derived again
459
+ * by anyone: entries sealed towards it stay readable to whoever held it,
460
+ * and nothing newer is.
461
+ */
462
+ const rotateEncKey = async ({ account, encryptionKey, view, local, chain, indexer, networkId, onProgress, devices, rotateRoster, target }) => {
463
+ const { ledgerState } = chain.position();
464
+ const inbox = readAccountInbox(account.address, ledgerState, local.readerPublicKey);
465
+ const { entries, keyring } = inbox;
466
+ const { holdingEntries } = await walkInbox({
467
+ address: account.address,
468
+ ledgerState,
469
+ indexer,
470
+ openEntries: async (coinEntries) => (await encryptionKey.openInbox(networkId, keyring, coinEntries)).map((opened) => opened?.kind === "coin" ? opened.coin : null)
471
+ });
472
+ const { readers, dropped, removed } = await sealedRoster({
473
+ account,
474
+ encryptionKey,
475
+ networkId,
476
+ local,
477
+ ledgerState,
478
+ inbox,
479
+ devices,
480
+ target,
481
+ localEntry: chain.position().devices.find((device) => device.isLocal)?.commitmentHex.toLowerCase()
482
+ });
483
+ const keys = await encryptionKey.createKeys(networkId, {
484
+ devicePublicKey: local.devicePublicKey,
485
+ keyring,
486
+ registrations: entries.filter(isDeviceRegistration),
487
+ readers,
488
+ ...rotateRoster === void 0 ? {} : { rotateRoster },
489
+ ...removed ? { removed } : {}
490
+ });
491
+ const reencrypted = (await view.reencryptInbox(networkId, {
492
+ keyring,
493
+ to: keys.encKey
494
+ }, holdingEntries)).filter((entry) => entry !== null);
495
+ onProgress("rotating");
496
+ for (const entry of [...keys.envelopes, ...keys.registrations]) await chain.submit(prepareAppendInbox(entry));
497
+ const before = registrationsOf(entries);
498
+ const appended = registrationsOf(keys.registrations);
499
+ const landed = inboxEntries(chain.position().ledgerState).filter((entry) => isDeviceRegistration(entry) && !before.has(HexBytes.fromByteArray(entry)) && !appended.has(HexBytes.fromByteArray(entry)));
500
+ if (landed.length > 0 && (await encryptionKey.openInbox(networkId, keyring, landed)).some((opened) => opened?.kind === "device")) throw new DeviceRosterInvalidError(`Registrations landed in the inbox of ${account.address} while its keys rotated; rotate again.`);
501
+ await chain.submit(prepareRotateEncKey(keys.encKey));
502
+ await chain.append("reencrypting", reencrypted);
503
+ return {
504
+ encKey: keys.encKey,
505
+ dropped,
506
+ authority: keys.authority,
507
+ keyring: {
508
+ account: AccAddress(account.address),
509
+ encKey: keys.encKey,
510
+ envelopes: keys.envelopes.filter((envelope) => isAddressedTo(envelope, local.readerPublicKey))
511
+ }
512
+ };
513
+ };
514
+ /**
515
+ * Seals the live secret of `keyring` to each read grant's read key, with
516
+ * the grant record that keeps each seal on chain for this device. A
517
+ * grant the key refuses to seal to, an expired key session included, is
518
+ * listed unsealed rather than failing a rotation that already landed, or
519
+ * as revocation pending when the key refuses it with
520
+ * GrantRevocationPendingError.
521
+ */
522
+ const sealViews = async ({ view, networkId, keyring, account, targets }) => {
523
+ const sealedEncKey = HexBytes.fromByteArray(keyring.encKey);
524
+ const result = {
525
+ sealed: [],
526
+ unsealed: [],
527
+ revocationPending: [],
528
+ entries: []
529
+ };
530
+ for (const target of targets) {
531
+ let refusal;
532
+ const delivery = await view.sealView(networkId, keyring, {
533
+ ...target,
534
+ account
535
+ }).catch((error) => {
536
+ refusal = error;
537
+ });
538
+ if (!delivery) {
539
+ (refusal instanceof GrantRevocationPendingError ? result.revocationPending : result.unsealed).push(target.grantId);
540
+ continue;
541
+ }
542
+ result.sealed.push({
543
+ ...target,
544
+ seal: HexBytes.fromByteArray(delivery.seal),
545
+ sealedEncKey
546
+ });
547
+ result.entries.push(delivery.entry);
548
+ }
549
+ return result;
550
+ };
551
+ //#endregion
552
+ //#region ../../packages/module/passport-account/src/flows/stored-grants.ts
553
+ /**
554
+ * The slot each stored grant was derived under, keyed by id, as the
555
+ * roster decoder takes them.
556
+ */
557
+ const storedGrantSlots = (stored) => new Map(Object.entries(stored ?? {}).map(([id, { slot }]) => [GrantId(id), GrantSlot(slot)]));
558
+ /**
559
+ * The opening of each stored grant whose object fields were kept, keyed by
560
+ * id, as the roster decoder attaches them. A read grant whose seal this
561
+ * client holds carries it in the opening's view, with the `enc_key` whose
562
+ * secret it seals.
563
+ */
564
+ const storedGrantOpenings = (stored) => new Map(Object.entries(stored ?? {}).flatMap(([id, grant]) => grant.object ? [[GrantId(id), {
565
+ scopeSalt: GrantScopeSalt(grant.scopeSalt),
566
+ granteeScheme: storedGranteeScheme(grant),
567
+ granteePublicKey: grant.granteePublicKey,
568
+ origin: grant.origin,
569
+ color: TokenColor(grant.object.color),
570
+ recipient: grant.object.recipient,
571
+ maxCoinValue: grant.object.maxCoinValue,
572
+ ...grant.view?.seal === void 0 || grant.view.sealedEncKey === void 0 ? {} : { view: {
573
+ readPublicKey: grant.view.readPublicKey,
574
+ seal: grant.view.seal,
575
+ sealedEncKey: grant.view.sealedEncKey
576
+ } }
577
+ }]] : []));
578
+ /**
579
+ * The stored grants with the view of one grant replaced: its read key
580
+ * and, when given, the seal towards it of the secret of `sealedEncKey`.
581
+ */
582
+ const withStoredGrantView = (stored, grantId, view) => {
583
+ const grant = stored[grantId];
584
+ if (!grant) return stored;
585
+ return {
586
+ ...stored,
587
+ [grantId]: {
588
+ ...grant,
589
+ view
590
+ }
591
+ };
592
+ };
593
+ /**
594
+ * The read grants this client holds the read key of and the chain still
595
+ * lists active, other than `except`: the grants a rotation seals the new
596
+ * secret to again. A read grant issued by another client has no stored
597
+ * key here, so it is not among them.
598
+ */
599
+ const liveStoredReadGrants = (stored, roster, except) => {
600
+ const active = new Set(roster.filter((record) => record.active && record.scope.read).map(({ id }) => id));
601
+ return Object.entries(stored ?? {}).flatMap(([id, grant]) => grant.view && active.has(GrantId(id)) && id !== except ? [{
602
+ grantId: GrantId(id),
603
+ readPublicKey: grant.view.readPublicKey
604
+ }] : []);
605
+ };
606
+ /**
607
+ * The active read grants this client holds the read key of whose stored
608
+ * seal does not hold the secret of `encKey`, the ledger's current one:
609
+ * their grantees read nothing newer until a rotation seals to them again
610
+ * or they are issued again. A read grant issued by another client has no
611
+ * stored key here, so it is not among them.
612
+ */
613
+ const unsealedStoredReadGrants = (stored, roster, encKey) => liveStoredReadGrants(stored, roster).filter(({ grantId }) => stored?.[grantId]?.view?.sealedEncKey !== encKey).map(({ grantId }) => grantId);
614
+ /** The stored grants with one more entry, under its grant id. */
615
+ const withStoredGrant = (stored, grantId, grant) => ({
616
+ ...stored,
617
+ [grantId]: grant
618
+ });
619
+ /**
620
+ * The record a completed account persists: its identity, this device's
621
+ * use counter, the grant bookkeeping when there is any, and the roster of
622
+ * devices the account keys were sealed to when it is known. It never
623
+ * carries a deployment, so a write of it completes a pending record.
624
+ */
625
+ const completedRecord = ({ address, bindingVersion }, localUseCounter, { grants }) => ({
626
+ address,
627
+ bindingVersion,
628
+ localUseCounter,
629
+ ...grants ? { grants } : {}
630
+ });
631
+ /**
632
+ * The stored grants with the seals of a rotation applied: each sealed
633
+ * grant's view carries its new seal and the `enc_key` it holds, and each
634
+ * unsealed one keeps its read key alone.
635
+ */
636
+ const withSealedViews = (stored, { sealed, unsealed }) => {
637
+ if (!stored) return stored;
638
+ let next = stored;
639
+ for (const { grantId, readPublicKey, seal, sealedEncKey } of sealed) next = withStoredGrantView(next, grantId, {
640
+ readPublicKey,
641
+ seal,
642
+ sealedEncKey
643
+ });
644
+ for (const grantId of unsealed) {
645
+ const readPublicKey = next[grantId]?.view?.readPublicKey;
646
+ if (readPublicKey !== void 0) next = withStoredGrantView(next, grantId, { readPublicKey });
647
+ }
648
+ return next;
649
+ };
650
+ /** Each grant's parts by id, the later of two parts of a kind winning. */
651
+ const partsByGrant = (parts) => {
652
+ const byGrant = /* @__PURE__ */ new Map();
653
+ for (const part of parts) {
654
+ const held = byGrant.get(part.grantId) ?? {};
655
+ byGrant.set(part.grantId, {
656
+ ...held,
657
+ [part.part]: part
658
+ });
659
+ }
660
+ return byGrant;
661
+ };
662
+ /**
663
+ * Whether a grant's bookkeeping opens its on-chain commitments under the
664
+ * account at `address`: the id derives from the account, the grantee
665
+ * key under its scheme, the origin and the slot, the object commitment
666
+ * from the salt and the object fields, and the read key hashes to the
667
+ * one the contract holds, or is absent for a grant that does not read.
668
+ * Anyone can append any bytes to the inbox, and another client of the
669
+ * account issuing to the same grantee from the same origin lands on the
670
+ * same id with its own salt, so this check, not where the bookkeeping
671
+ * came from, is what makes it trusted.
672
+ */
673
+ const opensOnChain = async (record, fields, address) => {
674
+ try {
675
+ const grantee = {
676
+ scheme: fields.granteeScheme,
677
+ publicKey: fields.granteePublicKey
678
+ };
679
+ const grantId = deriveGrantId({
680
+ contractAddress: ByteArray.fromHex(HexBytes(address)),
681
+ granteePublicKey: granteePoint(grantee),
682
+ originHash: await originHash(fields.origin),
683
+ slot: GrantSlot(fields.slot)
684
+ });
685
+ const encoded = circuitScope({
686
+ grantee,
687
+ operations: [],
688
+ color: TokenColor(fields.object.color),
689
+ recipient: fields.object.recipient,
690
+ maxCoinValue: fields.object.maxCoinValue,
691
+ perCallCap: "0",
692
+ cap: "0",
693
+ expiresAt: null,
694
+ ...fields.readPublicKey === void 0 ? {} : { readPublicKey: fields.readPublicKey }
695
+ });
696
+ return grantId === record.id && grantObjectCommit(ByteArray.fromHex(HexBytes(fields.scopeSalt)), encoded) === record.scope.objectCommit && HexBytes.fromByteArray(encoded.readPkHash) === record.scope.readPkHash && fields.readPublicKey !== void 0 === record.scope.read;
697
+ } catch {
698
+ return false;
699
+ }
700
+ };
701
+ /**
702
+ * The stored grants narrowed to the ones that still open what the chain
703
+ * holds under their id, or undefined once none is left. A grant the
704
+ * chain no longer holds is dropped, and so is one whose kept fields do
705
+ * not open its commitments: the entry an issue wrote before a call that
706
+ * never landed, once another client of the account issued over the same
707
+ * id, or an entry written before the object fields were kept, which
708
+ * cannot be checked. A revoked grant stays in the contract's map as a
709
+ * tombstone, so its slot and salt are kept until a revoke-all clears the
710
+ * map or a new grant overwrites the id.
711
+ */
712
+ const retainStoredGrants = async (stored, roster, address) => {
713
+ if (!stored) return void 0;
714
+ const retained = {};
715
+ for (const record of roster) {
716
+ const grant = stored[record.id];
717
+ if (!grant?.object) continue;
718
+ if (await opensOnChain(record, {
719
+ ...grant,
720
+ granteeScheme: storedGranteeScheme(grant),
721
+ object: grant.object,
722
+ ...grant.view === void 0 ? {} : { readPublicKey: grant.view.readPublicKey }
723
+ }, address)) retained[record.id] = grant;
724
+ }
725
+ return Object.keys(retained).length > 0 ? retained : void 0;
726
+ };
727
+ /**
728
+ * The bookkeeping of grants this device issued, rebuilt from the grant
729
+ * records it opened in the inbox, for the grants the chain still holds:
730
+ * each grant whose parts open its on-chain commitments under this
731
+ * account and origin, with its read key and, when the newest view record
732
+ * holds the seal of the ledger's `enc_key`, that seal. A grant whose
733
+ * parts do not check out, or whose grant or object part is missing, is
734
+ * left out. Undefined when nothing is rebuilt.
735
+ */
736
+ const rebuildStoredGrants = async (parts, roster, scope) => {
737
+ const byGrant = partsByGrant(parts);
738
+ const rebuilt = {};
739
+ for (const record of roster) {
740
+ const held = byGrant.get(record.id);
741
+ if (!held?.grant || !held.object) continue;
742
+ const { grant, object, view } = held;
743
+ if (!await opensOnChain(record, {
744
+ ...grant,
745
+ origin: scope.origin,
746
+ object: object.object
747
+ }, scope.address)) continue;
748
+ const readPublicKey = grant.readPublicKey;
749
+ const isCurrent = view !== void 0 && scope.encKey.startsWith(view.encKeyPrefix);
750
+ rebuilt[record.id] = {
751
+ slot: grant.slot,
752
+ scopeSalt: grant.scopeSalt,
753
+ granteeScheme: grant.granteeScheme,
754
+ granteePublicKey: grant.granteePublicKey,
755
+ origin: scope.origin,
756
+ object: object.object,
757
+ ...readPublicKey === void 0 ? {} : { view: isCurrent ? {
758
+ readPublicKey,
759
+ seal: view.seal,
760
+ sealedEncKey: scope.encKey
761
+ } : { readPublicKey } }
762
+ };
763
+ }
764
+ return Object.keys(rebuilt).length > 0 ? rebuilt : void 0;
765
+ };
766
+ /**
767
+ * The record's bookkeeping with every rebuilt grant it lacks added: what
768
+ * the record holds is kept, so a record that survived is never
769
+ * overwritten by the chain's copy, except for a view whose seal is not of
770
+ * `encKey`, the ledger's current one, when the rebuilt view's seal is:
771
+ * the record write after a rotation can be lost while its seal reached
772
+ * the inbox. Run over the bookkeeping {@link retainStoredGrants} checked,
773
+ * a rebuilt grant takes the place of an entry that did not open.
774
+ */
775
+ const withRebuiltGrants = (stored, rebuilt, encKey) => {
776
+ if (!rebuilt) return stored;
777
+ const merged = {
778
+ ...rebuilt,
779
+ ...stored
780
+ };
781
+ for (const [id, fromChain] of Object.entries(rebuilt)) {
782
+ const held = stored?.[id];
783
+ if (held && held.view?.sealedEncKey !== encKey && fromChain.view?.sealedEncKey === encKey) merged[id] = {
784
+ ...held,
785
+ view: fromChain.view
786
+ };
787
+ }
788
+ return merged;
789
+ };
790
+ //#endregion
791
+ //#region ../../packages/module/passport-account/src/flows/create-account.ts
792
+ /** The initial device entry is inserted at epoch 0 with use counter 0. */
793
+ const INITIAL_DEVICE_EPOCH = DeviceEpoch(0n);
794
+ const INITIAL_USE_COUNTER_VALUE = "0";
795
+ /**
796
+ * The record of a creation left unfinished on this device, read inside
797
+ * the session once presence reported one. A record that opens without a
798
+ * pending deployment, or that this authoriser cannot open, refuses with
799
+ * AccountExistsError: it names an account that must not be created over.
800
+ * A record that carries only the marker of its creation, which a hosted
801
+ * signer shows no flow but the creation, cannot be resumed and is
802
+ * refused, as is one started under another lock choice than
803
+ * `lockAccount`, with CreationLockMismatchError naming the recorded one.
804
+ */
805
+ const pendingRecord = async (accountRecords, lockAccount) => {
806
+ const record = await accountRecords.read();
807
+ if (!record?.deployment) throw new AccountExistsError();
808
+ if (!isPendingDeployment(record.deployment)) throw new Error(`The unfinished creation of the account at ${record.address} was read without its deployment, so it cannot be resumed.`);
809
+ if (record.deployment.lockAccount !== lockAccount) throw lockChoiceMismatch(record.deployment.lockAccount);
810
+ return {
811
+ ...record,
812
+ deployment: record.deployment
813
+ };
814
+ };
815
+ /**
816
+ * Runs the deployment: a fresh one, which draws the account keys first,
817
+ * deploys with their `enc_key`, hands an unlocked account's maintenance
818
+ * to the authority their roster key derives, and records the pending
819
+ * deployment, with this device's envelope and registration, as soon as
820
+ * the deploy lands so an interruption can be resumed; or the remaining
821
+ * waves of a recorded one, with the key entries and the handover
822
+ * authority it recorded. Both wait for the fee sponsor to be ready
823
+ * before building each transaction.
824
+ */
825
+ const deploy = async ({ providers, lockAccount, pending, local, context: { seams, accountRecords } }) => {
826
+ const { passportAuthoriser, passportEncryptionKey, passportNetwork, passportSponsor } = seams;
827
+ const sponsorReady = async () => passportSponsor.ready?.();
828
+ if (pending) return {
829
+ deployed: await resumeAccountDeployment({
830
+ providers,
831
+ authoriser: passportAuthoriser,
832
+ address: pending.address,
833
+ pending: pending.deployment,
834
+ sponsorReady
835
+ }),
836
+ pending: pending.deployment
837
+ };
838
+ const keys = await passportEncryptionKey.createKeys(passportNetwork.networkId, { devicePublicKey: local.devicePublicKey });
839
+ const keyEntries = [...keys.envelopes, ...keys.registrations].map((entry) => HexBytes.fromByteArray(entry));
840
+ const progress = {};
841
+ const deployed = await deployAccount({
842
+ providers,
843
+ authoriser: passportAuthoriser,
844
+ encPublicKey: keys.encKey,
845
+ lockAccount,
846
+ handoverAuthority: keys.authority,
847
+ sponsorReady,
848
+ onDeployed: async (address, deployment) => {
849
+ progress.recorded = {
850
+ ...deployment,
851
+ keyEntries
852
+ };
853
+ await accountRecords.write({
854
+ address,
855
+ bindingVersion: accManifest.bindingVersion,
856
+ localUseCounter: INITIAL_USE_COUNTER_VALUE,
857
+ deployment: progress.recorded
858
+ });
859
+ }
860
+ });
861
+ if (!progress.recorded) throw new Error("The deployment landed without reporting its progress.");
862
+ return {
863
+ deployed,
864
+ pending: progress.recorded
865
+ };
866
+ };
867
+ /**
868
+ * Creates a Passport account: the passkey ceremony (implicit in the first
869
+ * authoriser use), the account keys drawn through the encryption key
870
+ * seam, the Account Custody Contract deployment in waves with sponsored
871
+ * fees, the initial device activation, the delivery of the account keys
872
+ * to this device's inbox, and the local persistence of the account
873
+ * record. Every step runs inside one key session, so the whole flow costs
874
+ * a single ceremony rather than one per authoriser call. The flow never
875
+ * holds the encryption secret: the seam draws it at random, seals it to
876
+ * this device's reader key and hands back only its public key, which the
877
+ * constructor takes as `enc_key`, with this device's envelope and its
878
+ * registration under a fresh roster key; once the device is active, both
879
+ * are appended to the inbox, one gated call each, so the account keys
880
+ * live on chain from the start.
881
+ *
882
+ * Progress is reported through `onProgress`: 'deploying' once the
883
+ * authoriser has produced the device key, 'proving' and 'sponsoring' from
884
+ * inside each transaction submission (a transaction proves first, then
885
+ * the sponsor balances it), 'activating' before the activation call and
886
+ * 'recording' before the key entries are appended. The record is written
887
+ * before the promise resolves, so a process that dies right after still
888
+ * recognises the account on next startup.
889
+ *
890
+ * The flow runs to completion once started: cancelling mid-deploy could
891
+ * orphan a contract the sponsor already paid for. The caller's flow gate
892
+ * is what keeps a second request from starting one. Should the process
893
+ * die between waves anyway, the record written when the deploy landed
894
+ * names the contract, what it still needs and the key entries, and the
895
+ * next create request on this device resumes from the operations the
896
+ * chain holds, activates once every wave is in and appends whichever key
897
+ * entry the inbox still lacks; a creation that died after its activation
898
+ * landed resumes from there. A resumed creation finishes exactly as it
899
+ * began, with the keys recorded then: a request under another lock choice
900
+ * than the recorded one is refused with CreationLockMismatchError, and a
901
+ * build pinning other verifier keys than the recorded deployment with
902
+ * CreationArtefactMismatchError, both before any wave. The session names
903
+ * the lock choice, so an authoriser that asks consent first shows it; a
904
+ * hosted signer refuses the same lock mismatch itself, and a resume
905
+ * started from another origin than the creation it resumes.
906
+ *
907
+ * A device already holding a completed account record refuses with
908
+ * AccountExistsError before the ceremony runs: the record is the only
909
+ * pointer to the deployed contract and there is no recovery path, so
910
+ * creating over it would orphan the existing account. Presence is read
911
+ * without opening the record, and it tells a completed record from an
912
+ * unfinished one, so a sealed record blocks the flow without costing a
913
+ * prompt and only a record the flow may resume is opened, inside the
914
+ * session, where it costs no extra prompt.
915
+ */
916
+ const createAccount = async ({ lockAccount }, context) => {
917
+ const { seams, accountRecords, onProgress } = context;
918
+ const presence = await accountRecords.presence();
919
+ if (presence === "complete") throw new AccountExistsError();
920
+ const { passportAuthoriser, passportNetwork, passportProver, passportSponsor } = seams;
921
+ return inKeySession(passportAuthoriser, {
922
+ kind: "create-account",
923
+ lockAccount
924
+ }, async () => {
925
+ const local = await readLocalDevice(seams);
926
+ const pending = presence === "pending" ? await pendingRecord(accountRecords, lockAccount) : void 0;
927
+ onProgress("deploying");
928
+ const { deployed, pending: deployment } = await deploy({
929
+ providers: await createMidnightProviders({
930
+ network: passportNetwork,
931
+ prover: passportProver,
932
+ sponsor: passportSponsor,
933
+ onStage: onProgress
934
+ }),
935
+ lockAccount,
936
+ pending,
937
+ local,
938
+ context
939
+ });
940
+ if (!deployed.isActivated) {
941
+ onProgress("activating");
942
+ await deployed.activate();
943
+ }
944
+ const account = {
945
+ address: deployed.address,
946
+ bindingVersion: accManifest.bindingVersion,
947
+ status: "ready",
948
+ networkId: passportNetwork.networkId
949
+ };
950
+ const startCounter = pending?.localUseCounter ?? INITIAL_USE_COUNTER_VALUE;
951
+ const { indexer, ledgerState } = await readAccountLedger(deployed.address, passportNetwork);
952
+ const held = new Set(inboxEntries(ledgerState).map((entry) => HexBytes.fromByteArray(entry)));
953
+ const chain = callChain({
954
+ account,
955
+ start: {
956
+ ledgerState,
957
+ localUseCounter: startCounter,
958
+ devices: [{
959
+ commitmentHex: await passportAuthoriser.deviceCommitment(AccAddress(deployed.address), INITIAL_DEVICE_EPOCH, UseCounter(BigInt(startCounter))),
960
+ isLocal: true
961
+ }]
962
+ },
963
+ indexer,
964
+ seams,
965
+ onProgress,
966
+ onAdvanced: async (localUseCounter) => accountRecords.write({
967
+ address: account.address,
968
+ bindingVersion: account.bindingVersion,
969
+ localUseCounter,
970
+ deployment
971
+ })
972
+ });
973
+ await chain.append("recording", deployment.keyEntries.filter((entry) => !held.has(entry)).map((entry) => ByteArray.fromHex(HexBytes(entry))));
974
+ const { localUseCounter, devices } = chain.position();
975
+ const counter = localUseCounter ?? startCounter;
976
+ await accountRecords.write(completedRecord(account, counter, {}));
977
+ return {
978
+ account,
979
+ devices,
980
+ localUseCounter: counter,
981
+ grants: [],
982
+ encKey: HexBytes.fromByteArray(ledgerState.enc_key)
983
+ };
984
+ });
985
+ };
986
+ //#endregion
987
+ //#region ../../packages/module/passport-account/src/acc/read-grants.ts
988
+ const NO_SLOTS = /* @__PURE__ */ new Map();
989
+ const NO_OPENINGS = /* @__PURE__ */ new Map();
990
+ /** The slot reported for a grant whose slot this client never learned. */
991
+ const UNKNOWN_SLOT = GrantSlot(0);
992
+ const toNumber = (field, value) => {
993
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`Grant field ${field} exceeds the safe integer range`);
994
+ return Number(value);
995
+ };
996
+ const toOperations = (scope) => {
997
+ const operations = [];
998
+ if (scope.op_withdraw_unshielded) operations.push("withdraw-unshielded");
999
+ if (scope.op_withdraw_shielded) operations.push("withdraw-shielded");
1000
+ if (scope.op_withdraw_shielded_to_contract) operations.push("withdraw-shielded-to-contract");
1001
+ return operations;
1002
+ };
1003
+ const toScope = (scope) => ({
1004
+ operations: toOperations(scope),
1005
+ read: scope.read,
1006
+ objectCommit: HexBytes.fromByteArray(scope.object_commit),
1007
+ perCallCap: scope.per_call_cap.toString(),
1008
+ cap: scope.cap.toString(),
1009
+ expiresAt: scope.expires_at === 0n ? null : toNumber("expires_at", scope.expires_at),
1010
+ rpCommit: HexBytes.fromByteArray(scope.rp_commit),
1011
+ readPkHash: HexBytes.fromByteArray(scope.read_pk_hash),
1012
+ window: scope.window_len === 0n ? null : {
1013
+ lengthSeconds: toNumber("window_len", scope.window_len),
1014
+ cap: scope.window_cap.toString()
1015
+ },
1016
+ callerCommit: HexBytes.fromByteArray(scope.caller_commit)
1017
+ });
1018
+ const toRecord = (id, record, { slot, opening }) => ({
1019
+ id,
1020
+ slot,
1021
+ active: record.active,
1022
+ epoch: toNumber("epoch", record.epoch),
1023
+ generation: toNumber("gen", record.gen),
1024
+ issuedAt: toNumber("issued_at", record.issued_at),
1025
+ scope: toScope(record.scope),
1026
+ spentWindow: {
1027
+ start: toNumber("window_start", record.window_start),
1028
+ spent: record.window_spent.toString()
1029
+ },
1030
+ ...opening ? { opening } : {}
1031
+ });
1032
+ /**
1033
+ * Decodes the account's grant roster from the ledger's grants map, in the
1034
+ * map's order. Plain fields decode to the read model's numbers and
1035
+ * decimal strings, commitments stay as hex, and an expiry or window of
1036
+ * zero reads as none. A revoked grant stays in the map as an inactive
1037
+ * tombstone and is listed as such. The contract stores no slot: the
1038
+ * caller supplies the slots of the grants it issued, and a grant issued by
1039
+ * another client of the account reports slot 0. The openings the caller
1040
+ * holds are attached to their grants.
1041
+ */
1042
+ const readGrants = (ledgerState, slots = NO_SLOTS, openings = NO_OPENINGS) => Array.from(ledgerState.grants, ([rawId, record]) => {
1043
+ const id = GrantId(HexBytes.fromByteArray(rawId));
1044
+ return toRecord(id, record, {
1045
+ slot: slots.get(id) ?? UNKNOWN_SLOT,
1046
+ opening: openings.get(id)
1047
+ });
1048
+ });
1049
+ //#endregion
1050
+ //#region ../../packages/module/passport-account/src/flows/maintenance.ts
1051
+ /** Loads the ledger and the network id the update is built and submitted with. */
1052
+ const importLedgerModules = async () => Promise.all([import("@midnightntwrk/ledger-v9"), import("@midnight-ntwrk/midnight-js-network-id")]);
1053
+ /**
1054
+ * The maintenance authority of the account at `address` as `publicData`
1055
+ * serves it. An update must read its counter through the provider its
1056
+ * submission polls, so a lagging read cannot hand the next update a
1057
+ * counter the chain already moved past.
1058
+ */
1059
+ const authorityOnChain = async (ledger, publicData, address) => readMaintenanceAuthority({
1060
+ providers: { publicDataProvider: publicData },
1061
+ ledger,
1062
+ address
1063
+ });
1064
+ /** The refusal of a key that cannot sign over an account whose authority is live. */
1065
+ const missingSigner = (address) => new MaintenanceUpdateRefusedError(`The encryption key held here cannot sign maintenance updates, so the maintenance authority of the account at ${address} cannot follow its roster.`);
1066
+ /**
1067
+ * Refuses a roster rotation the maintenance authority could not follow,
1068
+ * before any prompt: an encryption key that signs no maintenance update
1069
+ * over an account whose authority is live. A locked account, whose
1070
+ * committee is empty, has no authority to follow.
1071
+ *
1072
+ * @throws {@link MaintenanceUpdateRefusedError} when the key cannot sign
1073
+ * and the account's authority is live.
1074
+ */
1075
+ const assertMaintenanceSigner = async ({ address, indexer, encryptionKey }) => {
1076
+ if (encryptionKey.signMaintenanceUpdate) return;
1077
+ const [ledger] = await importLedgerModules();
1078
+ const { committee } = await authorityOnChain(ledger, indexer, address);
1079
+ if (committee.length > 0) throw missingSigner(address);
1080
+ };
1081
+ /** The refusal of a key that cannot sign the install of missing operations. */
1082
+ const missingInstallSigner = (address) => new MaintenanceUpdateRefusedError(`The encryption key held here cannot sign maintenance updates, so no operation can be installed on the account at ${address}.`);
1083
+ /** The refusal of an install on an account whose authority was retired. */
1084
+ const lockedAccount = (address) => new AuthorityRetiredError(`The account at ${address} is locked: its maintenance authority is retired, so no operation can be installed.`);
1085
+ /**
1086
+ * The one key of a live committee, which some roster key must derive.
1087
+ *
1088
+ * @throws {@link MaintenanceAuthorityMismatchError} when the committee
1089
+ * is not one key.
1090
+ */
1091
+ const soleMember = (address, committee) => {
1092
+ if (committee.length !== 1) throw new MaintenanceAuthorityMismatchError(`The maintenance authority of the account at ${address} is a committee of ${committee.length} keys, not one a roster key derives.`);
1093
+ const [{ tag, value }] = committee;
1094
+ return {
1095
+ tag,
1096
+ value
1097
+ };
1098
+ };
1099
+ /**
1100
+ * Refuses a roster rotation whose move of the maintenance authority would
1101
+ * fail, inside the key session and before anything is submitted: an
1102
+ * unlocked account whose one-key committee no roster key of the keyring
1103
+ * derives. A locked account, whose committee is empty, has no authority
1104
+ * to move. The encryption key answers only whether the keyring holds the
1105
+ * authority; a key that cannot answer leaves the refusal to the move.
1106
+ *
1107
+ * @throws {@link MaintenanceAuthorityMismatchError} when the committee
1108
+ * is not one key some roster key of the keyring derives.
1109
+ */
1110
+ const assertHoldsRosterAuthority = async ({ address, seams, indexer, keyring }) => {
1111
+ const holds = seams.passportEncryptionKey.holdsMaintenanceAuthority;
1112
+ if (!holds) return;
1113
+ const [ledger] = await importLedgerModules();
1114
+ const { committee } = await authorityOnChain(ledger, indexer, address);
1115
+ if (committee.length === 0) return;
1116
+ const authority = soleMember(address, committee);
1117
+ if (!await holds(seams.passportNetwork.networkId, keyring, authority)) throw new MaintenanceAuthorityMismatchError(`No roster key this device holds derives the maintenance authority of the account at ${address}, so the roster cannot rotate.`);
1118
+ };
1119
+ /**
1120
+ * Has the encryption key sign `changes` over the keyring with the roster
1121
+ * key whose authority the chain holds, rebuilds the update as it was
1122
+ * signed and submits it, resolving once the chain shows the advanced
1123
+ * counter.
1124
+ */
1125
+ const signAndSubmit = async ({ ledger, networkId, providers, address, seams, sign, keyring, authority, counter, changes, label }) => {
1126
+ const { signature } = await sign(seams.passportNetwork.networkId, {
1127
+ keyring,
1128
+ authority,
1129
+ counter,
1130
+ changes
1131
+ });
1132
+ await submitMaintenanceUpdate({
1133
+ providers,
1134
+ ledger,
1135
+ address,
1136
+ networkId,
1137
+ update: maintenanceUpdateOf(ledger, {
1138
+ address: keyring.account,
1139
+ counter,
1140
+ changes
1141
+ }),
1142
+ signature,
1143
+ label
1144
+ });
1145
+ };
1146
+ /**
1147
+ * Moves the maintenance authority of an unlocked account to the one the
1148
+ * new live roster key derives, after a rotation drew a fresh roster key,
1149
+ * so a removed device loses its upgrade rights and every device sealed
1150
+ * the new roster key holds them. The authority is read from chain: an
1151
+ * empty committee is a locked account and nothing is submitted. Otherwise
1152
+ * the encryption key signs the replace with the roster key among the
1153
+ * keyring's whose authority the chain holds, the update is rebuilt as it
1154
+ * was signed and submitted, and this resolves once the chain shows the
1155
+ * advanced counter, so the next call runs under the new authority.
1156
+ *
1157
+ * @throws {@link MaintenanceUpdateRefusedError} when the key cannot sign
1158
+ * maintenance updates, or refuses the replace.
1159
+ * @throws {@link MaintenanceAuthorityMismatchError} when the committee
1160
+ * is not one key some roster key of the keyring derives.
1161
+ */
1162
+ const followRosterAuthority = async ({ address, seams, keyring, authority, onProgress }) => {
1163
+ const [ledger, networkId] = await importLedgerModules();
1164
+ const providers = await createMidnightProviders({
1165
+ network: seams.passportNetwork,
1166
+ prover: seams.passportProver,
1167
+ sponsor: seams.passportSponsor,
1168
+ onStage: onProgress
1169
+ });
1170
+ const onChain = await authorityOnChain(ledger, providers.publicDataProvider, address);
1171
+ if (onChain.committee.length === 0) return;
1172
+ const sign = seams.passportEncryptionKey.signMaintenanceUpdate;
1173
+ if (!sign) throw missingSigner(address);
1174
+ await signAndSubmit({
1175
+ ledger,
1176
+ networkId,
1177
+ providers,
1178
+ address,
1179
+ seams,
1180
+ sign,
1181
+ keyring,
1182
+ authority: soleMember(address, onChain.committee),
1183
+ counter: onChain.counter,
1184
+ changes: {
1185
+ kind: "replace-authority",
1186
+ authority
1187
+ },
1188
+ label: "Maintenance authority rotation"
1189
+ });
1190
+ };
1191
+ /**
1192
+ * Refuses an install of missing operations the account's authority
1193
+ * could not sign, before any prompt: a locked account, whose committee
1194
+ * is empty, and an encryption key that signs no maintenance update.
1195
+ *
1196
+ * @throws {@link AuthorityRetiredError} when the account is locked.
1197
+ * @throws {@link MaintenanceUpdateRefusedError} when the key cannot sign.
1198
+ */
1199
+ const assertInstallSigner = async ({ address, indexer, encryptionKey }) => {
1200
+ const [ledger] = await importLedgerModules();
1201
+ const { committee } = await authorityOnChain(ledger, indexer, address);
1202
+ if (committee.length === 0) throw lockedAccount(address);
1203
+ if (!encryptionKey.signMaintenanceUpdate) throw missingInstallSigner(address);
1204
+ };
1205
+ /**
1206
+ * Installs verifier keys on an unlocked account, one maintenance update
1207
+ * per wave, each signed by the encryption key with the roster key whose
1208
+ * authority the chain holds. The authority is read from chain before
1209
+ * every wave, because each applied update advances its counter, and
1210
+ * every wave resolves only once the chain shows the advanced counter, so
1211
+ * this resolves once the chain holds every key. The authority stays the
1212
+ * one that signs: no wave replaces it.
1213
+ *
1214
+ * @throws {@link MaintenanceUpdateRefusedError} when the key cannot sign
1215
+ * maintenance updates, or refuses a verifier key.
1216
+ * @throws {@link AuthorityRetiredError} when the account is locked.
1217
+ * @throws {@link MaintenanceAuthorityMismatchError} when the committee
1218
+ * is not one key some roster key of the keyring derives.
1219
+ */
1220
+ const installVerifierKeys = async ({ address, seams, providers, keyring, waves }) => {
1221
+ const [ledger, networkId] = await importLedgerModules();
1222
+ const sign = seams.passportEncryptionKey.signMaintenanceUpdate;
1223
+ if (!sign) throw missingInstallSigner(address);
1224
+ for (const [index, inserts] of waves.entries()) {
1225
+ const { committee, counter } = await authorityOnChain(ledger, providers.publicDataProvider, address);
1226
+ if (committee.length === 0) throw lockedAccount(address);
1227
+ await signAndSubmit({
1228
+ ledger,
1229
+ networkId,
1230
+ providers,
1231
+ address,
1232
+ seams,
1233
+ sign,
1234
+ keyring,
1235
+ authority: soleMember(address, committee),
1236
+ counter,
1237
+ changes: {
1238
+ kind: "insert-verifier-keys",
1239
+ inserts
1240
+ },
1241
+ label: `Operation install ${index + 1} of ${waves.length}`
1242
+ });
1243
+ }
1244
+ };
1245
+ //#endregion
1246
+ //#region ../../packages/module/passport-account/src/flows/devices.ts
1247
+ /**
1248
+ * Contract aborts meaning the removal would leave the account without an
1249
+ * authorising device: the caller rule and the redundant count floor.
1250
+ */
1251
+ const LAST_DEVICE_ABORTS = ["failed assert: cannot remove the authorising device", "failed assert: cannot remove last device"];
1252
+ /**
1253
+ * Types a raw contract abort by the assert message the Account Custody
1254
+ * Contract raises; anything unrecognised passes through unchanged.
1255
+ * An unknown-entry abort on the remove circuit is attributed to the
1256
+ * removal target, not the caller: the circuit checks the caller first,
1257
+ * and the caller's entry was resolved against live ledger state inside
1258
+ * the same gate, so only a mid-flight roll of the caller's own entry
1259
+ * could produce it, while a stale target commitment always does.
1260
+ */
1261
+ const classifyContractAbort$1 = (error, circuit) => {
1262
+ const message = error instanceof Error ? error.message : String(error);
1263
+ if (LAST_DEVICE_ABORTS.some((abort) => message.includes(abort))) return new LastDeviceError(message);
1264
+ if (message.includes("failed assert: unknown device entry")) return circuit === "remove_device_with_jubjub" ? new RemovalTargetNotFoundError(message) : new NotAuthorisedError(message);
1265
+ if (isNotAuthorisedAbort(message)) return new NotAuthorisedError(message);
1266
+ return error;
1267
+ };
1268
+ /**
1269
+ * Whether any read grant of the account is live: its grantees hold the
1270
+ * live account secret, so a device handed the keys while one is live
1271
+ * gets a fresh secret first.
1272
+ */
1273
+ const hasLiveReadGrant = (ledgerState) => readGrants(ledgerState).some((record) => record.active && record.scope.read);
1274
+ /** The devices list with the enrolled commitment appended. */
1275
+ const withDevice = (devices, commitmentHex) => [...devices, {
1276
+ commitmentHex,
1277
+ isLocal: false
1278
+ }];
1279
+ /** The devices list with the revoked commitment dropped. */
1280
+ const withoutDevice = (devices, commitmentHex) => devices.filter((device) => device.commitmentHex !== commitmentHex);
1281
+ /** A device's entry as the call that targets it takes it. */
1282
+ const entryArgument = (commitmentHex) => ByteArray.fromHex(HexBytes(commitmentHex.toLowerCase()));
1283
+ /**
1284
+ * This device's keyring over the ledger the chain is at: the live secret
1285
+ * and the earlier ones its envelopes deliver.
1286
+ */
1287
+ const keyringAt = (account, chain, local) => readAccountInbox(account.address, chain.position().ledgerState, local.readerPublicKey).keyring;
1288
+ /** The counter the chain left this device at, or the one it started from. */
1289
+ const chainCounter = (chain, input) => chain.position().localUseCounter ?? input.localUseCounter ?? "0";
1290
+ /**
1291
+ * Opens what a device flow runs on inside its key session: the grant
1292
+ * bookkeeping of the record, read where it costs no extra prompt so every
1293
+ * write keeps it, and a chain of gated calls from the ledger read ahead
1294
+ * of the session, each persisting the counter it advanced this device to
1295
+ * before the next call. The bookkeeping is checked against the ledger
1296
+ * first, so an entry that does not open the grant the chain holds under
1297
+ * its id, as one an issue wrote before a call that never landed, is
1298
+ * neither re-sealed to nor kept.
1299
+ */
1300
+ const openDeviceSession = async (input, { ledgerState, indexer }, { seams, accountRecords, onProgress }) => {
1301
+ const { account, devices, localUseCounter } = input;
1302
+ let grants = await retainStoredGrants((await accountRecords.read())?.grants, readGrants(ledgerState), account.address);
1303
+ const write = async (counter) => accountRecords.write(completedRecord(account, counter, { grants }));
1304
+ const chain = callChain({
1305
+ account,
1306
+ start: {
1307
+ ledgerState,
1308
+ localUseCounter,
1309
+ devices
1310
+ },
1311
+ indexer,
1312
+ seams,
1313
+ onProgress,
1314
+ onAdvanced: write
1315
+ });
1316
+ return {
1317
+ grants,
1318
+ chain,
1319
+ keep: async (next) => {
1320
+ grants = next;
1321
+ await write(chainCounter(chain, input));
1322
+ }
1323
+ };
1324
+ };
1325
+ /**
1326
+ * Enrols a new device key on the account. `commitmentHex` carries the new
1327
+ * device's entry commitment, derived out of band by the joining device;
1328
+ * the local device authorises `add_device_with_jubjub` through the
1329
+ * gated-call pattern. The roster gains the commitment on success only,
1330
+ * marked as remote, and the same result moves the local device's own row
1331
+ * to the successor entry the call left it on, so the roster and the use
1332
+ * counter never disagree about where this device stands.
1333
+ *
1334
+ * When `reader` names the joining device's reader and device keys, the
1335
+ * account keys are delivered to it in the same session: its device key
1336
+ * must derive the enrolled commitment at use counter 0 and its reader key
1337
+ * must be one the account seals to, both checked before any prompt. The
1338
+ * encryption key seals the live secret and the roster key to the reader
1339
+ * key, and the envelope and the device's registration under the roster
1340
+ * key are appended to the inbox, one gated call each, ahead of the
1341
+ * enrolment, so an enrolment that lands never leaves the device without
1342
+ * its keys; until it lands the registration names no live entry and a
1343
+ * rotation passes over it. While any read grant is live its grantees
1344
+ * hold the live secret, and one could seal it to the joining reader with
1345
+ * a roster key of its own ahead of the genuine envelope, so the account
1346
+ * keys are rotated first in the same session, with a fresh roster key,
1347
+ * as a removal rotates them, the joining device handed the new secret no
1348
+ * grantee has seen, and the live read grants this client holds the read
1349
+ * key of sealed it after; with no live read grant only enrolled devices
1350
+ * hold the secret, and the live keys are handed over as they are. A
1351
+ * rotation moves the maintenance authority of an unlocked account to the
1352
+ * one the new roster key derives before the keys are handed over, so the
1353
+ * joining device can sign maintenance updates once enrolled; an
1354
+ * encryption key that cannot sign them refuses such an enrolment with
1355
+ * MaintenanceUpdateRefusedError before any prompt, and a device none of
1356
+ * whose roster keys derives the authority on chain refuses it with
1357
+ * MaintenanceAuthorityMismatchError inside the session, before the
1358
+ * rotation. The
1359
+ * joining device then signs in and reads the holdings with its own
1360
+ * passkey alone. Without `reader` the
1361
+ * device can authorise but reads nothing until some device delivers it
1362
+ * the keys.
1363
+ *
1364
+ * The advanced counter is persisted to the account record after every
1365
+ * call, before the roster is returned, so the next flow rescans from a
1366
+ * fresh anchor. A failure leaves the roster unreturned.
1367
+ *
1368
+ * A rejected authorisation (bad signature, malformed key, or a caller
1369
+ * entry the on-chain set no longer holds) rejects with NotAuthorisedError;
1370
+ * a record whose address holds no live contract rejects with
1371
+ * AccountContractMissingError; joining keys that do not match the entry
1372
+ * reject with DeviceReaderInvalidError. The transactions' proving and
1373
+ * sponsoring stages and 'recording' are reported through `onProgress`.
1374
+ */
1375
+ const addDevice = async ({ reader, ...input }, context) => {
1376
+ const { seams, onProgress } = context;
1377
+ const { account, commitmentHex } = input;
1378
+ const { networkId } = seams.passportNetwork;
1379
+ try {
1380
+ const ledger = await readAccountLedger(account.address, seams.passportNetwork);
1381
+ if (reader) assertJoiningDevice({
1382
+ address: account.address,
1383
+ epoch: ledger.ledgerState.device_epoch
1384
+ }, reader, commitmentHex);
1385
+ const view = reader && hasLiveReadGrant(ledger.ledgerState) ? viewCapability(seams.passportEncryptionKey) : void 0;
1386
+ const devices = view ? liveDeviceEntries(ledger.ledgerState) : void 0;
1387
+ if (view) await assertMaintenanceSigner({
1388
+ address: account.address,
1389
+ indexer: ledger.indexer,
1390
+ encryptionKey: seams.passportEncryptionKey
1391
+ });
1392
+ return await inKeySession(seams.passportAuthoriser, {
1393
+ kind: "add-device",
1394
+ commitmentHex,
1395
+ account: AccAddress(account.address),
1396
+ ...reader ? { reader } : {},
1397
+ ...devices ? { devices } : {}
1398
+ }, async () => {
1399
+ const { grants, chain, keep } = await openDeviceSession(input, ledger, context);
1400
+ let rotated;
1401
+ if (reader) {
1402
+ const local = await readLocalDevice(seams);
1403
+ if (view && devices) {
1404
+ await assertHoldsRosterAuthority({
1405
+ address: account.address,
1406
+ seams,
1407
+ indexer: ledger.indexer,
1408
+ keyring: keyringAt(account, chain, local)
1409
+ });
1410
+ rotated = await rotateEncKey({
1411
+ account,
1412
+ encryptionKey: seams.passportEncryptionKey,
1413
+ view,
1414
+ local,
1415
+ chain,
1416
+ indexer: ledger.indexer,
1417
+ networkId,
1418
+ onProgress,
1419
+ devices,
1420
+ rotateRoster: true
1421
+ });
1422
+ await followRosterAuthority({
1423
+ address: account.address,
1424
+ seams,
1425
+ keyring: keyringAt(account, chain, local),
1426
+ authority: rotated.authority,
1427
+ onProgress
1428
+ });
1429
+ }
1430
+ const delivery = await seams.passportEncryptionKey.sealToDevice(networkId, rotated?.keyring ?? keyringAt(account, chain, local), {
1431
+ ...reader,
1432
+ epoch: ledger.ledgerState.device_epoch,
1433
+ counter: 0n
1434
+ });
1435
+ await chain.append("recording", [delivery.envelope, delivery.registration]);
1436
+ if (view && rotated) {
1437
+ const views = await sealViews({
1438
+ view,
1439
+ networkId,
1440
+ keyring: rotated.keyring,
1441
+ account: AccAddress(account.address),
1442
+ targets: liveStoredReadGrants(grants, readGrants(chain.position().ledgerState))
1443
+ });
1444
+ await keep(withSealedViews(grants, views));
1445
+ await chain.append("recording", views.entries);
1446
+ }
1447
+ }
1448
+ await chain.submit({
1449
+ circuit: ADD_DEVICE_CIRCUIT,
1450
+ args: [entryArgument(commitmentHex)]
1451
+ });
1452
+ return {
1453
+ devices: withDevice(chain.position().devices, commitmentHex),
1454
+ localUseCounter: chainCounter(chain, input),
1455
+ ...rotated ? {
1456
+ encKey: HexBytes.fromByteArray(rotated.encKey),
1457
+ droppedDevices: rotated.dropped
1458
+ } : {}
1459
+ };
1460
+ });
1461
+ } catch (error) {
1462
+ throw classifyContractAbort$1(error, ADD_DEVICE_CIRCUIT);
1463
+ }
1464
+ };
1465
+ /**
1466
+ * Refuses a removal the contract would refuse before any prompt: a
1467
+ * target the on-chain device set does not hold, and the local device,
1468
+ * which cannot remove itself. The rotation a removal runs comes first,
1469
+ * so a removal refused only after it would have cost the target device
1470
+ * its keys for nothing.
1471
+ *
1472
+ * @throws {@link RemovalTargetNotFoundError} when the target is gone.
1473
+ * @throws {@link LastDeviceError} when the target is this device.
1474
+ */
1475
+ const assertRemovable = ({ devices, commitmentHex }, { ledgerState }) => {
1476
+ if (!ledgerState.devices.member(entryArgument(commitmentHex))) throw new RemovalTargetNotFoundError(`The account holds no device entry ${commitmentHex}.`);
1477
+ if (devices.find((device) => device.isLocal)?.commitmentHex.toLowerCase() === commitmentHex.toLowerCase()) throw new LastDeviceError("The device that authorises a removal cannot remove itself.");
1478
+ };
1479
+ /**
1480
+ * Revokes a device key from the account and rotates the account keys so
1481
+ * the removed device reads nothing newer. `commitmentHex` names the
1482
+ * target by its current entry commitment, which is the literal set
1483
+ * element the contract removes; the local device authorises
1484
+ * `remove_device_with_jubjub` through the gated-call pattern.
1485
+ *
1486
+ * Ahead of the removal, in the same session, the encryption key is
1487
+ * rotated with a fresh roster key and sealed only to this device and to
1488
+ * the registered devices whose device key derives a live entry other
1489
+ * than the target, which the key session names to the user before it
1490
+ * opens; the live holdings are re-encrypted towards it, and it is sealed
1491
+ * again to every live read grant this client holds the read key of, each
1492
+ * seal kept on chain in a grant record. The removed device's envelopes
1493
+ * stay in the inbox and keep opening the secrets they held, but none
1494
+ * opens the new one, and the registrations under the old roster key no
1495
+ * longer count, any it planted for itself included. Once `enc_key` is
1496
+ * replaced, and before the removal, the maintenance authority of an
1497
+ * unlocked account is moved to the one the new roster key derives, so
1498
+ * the removed device loses its upgrade rights; a locked account has no
1499
+ * authority to move. An encryption key that cannot sign maintenance
1500
+ * updates refuses the removal of a device from an unlocked account with
1501
+ * MaintenanceUpdateRefusedError before any prompt, and a device none of
1502
+ * whose roster keys derives the authority on chain refuses it with
1503
+ * MaintenanceAuthorityMismatchError inside the session, before the
1504
+ * rotation, so nothing is submitted. A roster in which
1505
+ * two readers claim one live device, or one reader two, refuses with
1506
+ * DeviceRosterInvalidError rather than guess.
1507
+ *
1508
+ * The roster drops the commitment on success only, and the same result
1509
+ * moves the local device's own row to the successor entry the call left
1510
+ * it on. The advanced counter is persisted to the account record after
1511
+ * every call. The contract's own guards surface as typed errors: a
1512
+ * removal that would strand the account (the authorising device, or the
1513
+ * count floor) rejects with LastDeviceError, a rejected authorisation
1514
+ * (bad signature or malformed key) with NotAuthorisedError, and a target
1515
+ * entry that is no longer in the on-chain set with
1516
+ * RemovalTargetNotFoundError; the target's presence and the local device
1517
+ * are checked before any prompt, and an encryption key that cannot
1518
+ * rotate refuses with ReadUnavailableError before any prompt too. The
1519
+ * rotation's stages, 'recording' and the transactions' proving and
1520
+ * sponsoring are reported through `onProgress`.
1521
+ */
1522
+ const removeDevice = async (input, context) => {
1523
+ const { seams, onProgress } = context;
1524
+ const { account, commitmentHex } = input;
1525
+ const { networkId } = seams.passportNetwork;
1526
+ try {
1527
+ const view = viewCapability(seams.passportEncryptionKey);
1528
+ const ledger = await readAccountLedger(account.address, seams.passportNetwork);
1529
+ assertRemovable(input, ledger);
1530
+ const devices = liveDeviceEntries(ledger.ledgerState, commitmentHex);
1531
+ await assertMaintenanceSigner({
1532
+ address: account.address,
1533
+ indexer: ledger.indexer,
1534
+ encryptionKey: seams.passportEncryptionKey
1535
+ });
1536
+ return await inKeySession(seams.passportAuthoriser, {
1537
+ kind: "remove-device",
1538
+ commitmentHex,
1539
+ account: AccAddress(account.address),
1540
+ devices
1541
+ }, async () => {
1542
+ const { grants, chain, keep } = await openDeviceSession(input, ledger, context);
1543
+ const local = await readLocalDevice(seams);
1544
+ await assertHoldsRosterAuthority({
1545
+ address: account.address,
1546
+ seams,
1547
+ indexer: ledger.indexer,
1548
+ keyring: keyringAt(account, chain, local)
1549
+ });
1550
+ const rotated = await rotateEncKey({
1551
+ account,
1552
+ encryptionKey: seams.passportEncryptionKey,
1553
+ view,
1554
+ local,
1555
+ chain,
1556
+ indexer: ledger.indexer,
1557
+ networkId,
1558
+ onProgress,
1559
+ devices,
1560
+ rotateRoster: true,
1561
+ target: commitmentHex.toLowerCase()
1562
+ });
1563
+ await followRosterAuthority({
1564
+ address: account.address,
1565
+ seams,
1566
+ keyring: keyringAt(account, chain, local),
1567
+ authority: rotated.authority,
1568
+ onProgress
1569
+ });
1570
+ const views = await sealViews({
1571
+ view,
1572
+ networkId,
1573
+ keyring: rotated.keyring,
1574
+ account: AccAddress(account.address),
1575
+ targets: liveStoredReadGrants(grants, readGrants(chain.position().ledgerState))
1576
+ });
1577
+ await keep(withSealedViews(grants, views));
1578
+ await chain.append("recording", views.entries);
1579
+ await chain.submit({
1580
+ circuit: REMOVE_DEVICE_CIRCUIT,
1581
+ args: [entryArgument(commitmentHex)]
1582
+ });
1583
+ return {
1584
+ devices: withoutDevice(chain.position().devices, commitmentHex),
1585
+ localUseCounter: chainCounter(chain, input),
1586
+ encKey: HexBytes.fromByteArray(rotated.encKey),
1587
+ droppedDevices: rotated.dropped
1588
+ };
1589
+ });
1590
+ } catch (error) {
1591
+ throw classifyContractAbort$1(error, REMOVE_DEVICE_CIRCUIT);
1592
+ }
1593
+ };
1594
+ //#endregion
1595
+ //#region ../../packages/module/passport-account/src/flows/grants.ts
1596
+ /** Contract abort naming a grant the grants map does not hold. */
1597
+ const UNKNOWN_GRANT_ABORT = "failed assert: unknown grant";
1598
+ /** Contract abort refusing a revoke over a grant already inactive. */
1599
+ const GRANT_NOT_LIVE_ABORT = "failed assert: grant not live";
1600
+ /** Contract abort refusing an issue over a grant id that is still active. */
1601
+ const GRANT_ACTIVE_ABORT = "failed assert: grant already active";
1602
+ /**
1603
+ * How long an accepted call is given to show in the indexer's view of the
1604
+ * grants map, which can lag the block the call landed in.
1605
+ */
1606
+ const ROSTER_POLL_ATTEMPTS = 30;
1607
+ const ROSTER_POLL_DELAY_MS = 1e3;
1608
+ const MILLISECONDS_PER_SECOND = 1e3;
1609
+ const sleep = async (ms) => new Promise((resolve) => {
1610
+ setTimeout(resolve, ms);
1611
+ });
1612
+ const isActive = (roster, grantId) => roster.some((record) => record.id === grantId && record.active);
1613
+ const activeCount = (roster) => roster.filter((record) => record.active).length;
1614
+ const nowSeconds = () => Math.floor(Date.now() / MILLISECONDS_PER_SECOND);
1615
+ /**
1616
+ * Types a raw contract abort by the assert message the Account Custody
1617
+ * Contract raises; anything unrecognised passes through unchanged. An
1618
+ * unknown-entry abort can only come from the caller check here, since no
1619
+ * grant circuit names a device entry.
1620
+ */
1621
+ const classifyContractAbort = (error) => {
1622
+ const message = error instanceof Error ? error.message : String(error);
1623
+ if (message.includes(UNKNOWN_GRANT_ABORT)) return new GrantNotFoundError(message);
1624
+ if (message.includes(GRANT_NOT_LIVE_ABORT)) return new GrantRevokedError(message);
1625
+ if (message.includes(GRANT_ACTIVE_ABORT)) return new GrantIssueRejectedError(message);
1626
+ if (message.includes("failed assert: unknown device entry") || isNotAuthorisedAbort(message)) return new NotAuthorisedError(message);
1627
+ return error;
1628
+ };
1629
+ /**
1630
+ * Refuses a device whose storage holds no account record before any
1631
+ * ceremony. The gate only runs a call over an account in state, so an
1632
+ * absent record means the storage was cleared underneath it.
1633
+ */
1634
+ const assertRecordPresent = async (accountRecords) => {
1635
+ if (await accountRecords.presence() === "absent") throw new AccountNotFoundError("No Passport account record is stored on this device.");
1636
+ };
1637
+ /**
1638
+ * The stored record of the account a grant call acts on, read inside the
1639
+ * session where it costs no extra prompt. Presence was checked ahead of
1640
+ * the session, so a missing record here vanished in between.
1641
+ */
1642
+ const storedRecord = async (accountRecords) => {
1643
+ const record = await accountRecords.read();
1644
+ if (!record) throw new AccountNotFoundError("No Passport account record is stored on this device.");
1645
+ return record;
1646
+ };
1647
+ /**
1648
+ * The ledger state once the indexer reflects the accepted call, with the
1649
+ * roster read from it. The submission settled in a block, but the
1650
+ * indexer can serve the state from before it for a moment, and a roster
1651
+ * read then would deny the call its own result.
1652
+ *
1653
+ * @throws {@link GrantRosterUnsettledError} when the indexer never
1654
+ * reflects the call within the polling window.
1655
+ */
1656
+ const awaitSettledRoster = async ({ indexer, address, slots, openings, isSettled }) => {
1657
+ for (let attempt = 0; attempt < ROSTER_POLL_ATTEMPTS; attempt++) {
1658
+ const ledgerState = await queryAccountLedger(indexer, address);
1659
+ const roster = readGrants(ledgerState, slots, openings);
1660
+ if (isSettled(roster)) return {
1661
+ ledgerState,
1662
+ roster
1663
+ };
1664
+ await sleep(ROSTER_POLL_DELAY_MS);
1665
+ }
1666
+ throw new GrantRosterUnsettledError(`The grant roster of ${address} never reflected the accepted call.`);
1667
+ };
1668
+ /**
1669
+ * Runs one gated grant call inside a single key session, so the use
1670
+ * counter rescan and the authorisation cost one ceremony rather than one
1671
+ * per authoriser call. A device whose storage holds no record is refused
1672
+ * ahead of the session. The record is read inside it, where it costs no
1673
+ * extra prompt, its grant bookkeeping narrowed to the grants whose kept
1674
+ * fields open what the ledger read before the call holds under their id,
1675
+ * so an entry an issue wrote before a call that never landed is neither
1676
+ * an opening nor a re-seal target. It is rewritten with the advanced
1677
+ * counter and the grant bookkeeping after every call, so a roster is
1678
+ * never published ahead of the record that anchors the next rescan and
1679
+ * names the slots. A call
1680
+ * that keeps its bookkeeping ahead of the submission writes it once more
1681
+ * before it, under the counter the record holds. A call that rotates the
1682
+ * encryption key does so in the same session ahead of its own circuit.
1683
+ * The other live read grants are sealed the new secret right after the
1684
+ * rotation lands, their seals kept in the record and on chain before the
1685
+ * call is submitted, so they keep reading whatever the call's outcome.
1686
+ * Once the roster shows an issued grant active, its bookkeeping is
1687
+ * appended to the inbox, sealed to this device alone, and the grantee of
1688
+ * a read grant is sealed the new secret, the seal kept the same way. The
1689
+ * wait for the indexer is reported as 'confirming' and the appends as
1690
+ * 'recording'. The contract's own aborts surface as typed errors;
1691
+ * anything else, and a failing on-chain status in particular, rejects
1692
+ * unchanged with the counter unmoved.
1693
+ */
1694
+ const runGrantCall = async ({ config: { call, flow, nextStoredGrants, writeBeforeCall, isSettled, rotation, reseal, issued }, input: { account, devices, localUseCounter }, ledger: { indexer, ledgerState }, roster: listed, context: { seams, accountRecords, onProgress } }) => {
1695
+ const { networkId } = seams.passportNetwork;
1696
+ const accountAddress = AccAddress(account.address);
1697
+ try {
1698
+ await assertRecordPresent(accountRecords);
1699
+ const rotationDevices = rotation ? liveDeviceEntries(ledgerState) : void 0;
1700
+ return await inKeySession(seams.passportAuthoriser, rotationDevices ? {
1701
+ ...flow,
1702
+ devices: rotationDevices
1703
+ } : flow, async () => {
1704
+ const record = await storedRecord(accountRecords);
1705
+ let stored = nextStoredGrants(await retainStoredGrants(record.grants, listed, account.address));
1706
+ const write = async (counter) => accountRecords.write(completedRecord(account, counter, { grants: stored }));
1707
+ if (writeBeforeCall) await write(record.localUseCounter);
1708
+ const chain = callChain({
1709
+ account,
1710
+ start: {
1711
+ ledgerState,
1712
+ localUseCounter,
1713
+ devices
1714
+ },
1715
+ indexer,
1716
+ seams,
1717
+ onProgress,
1718
+ onAdvanced: write
1719
+ });
1720
+ const counter = () => chain.position().localUseCounter ?? record.localUseCounter;
1721
+ const roster = (state) => readGrants(state, storedGrantSlots(stored), storedGrantOpenings(stored));
1722
+ let rotated;
1723
+ let unsealedGrantIds = [];
1724
+ let revocationPendingGrantIds = [];
1725
+ if (rotation) {
1726
+ rotated = await rotateEncKey({
1727
+ account,
1728
+ encryptionKey: seams.passportEncryptionKey,
1729
+ view: rotation,
1730
+ local: await readLocalDevice(seams),
1731
+ chain,
1732
+ indexer,
1733
+ networkId,
1734
+ onProgress,
1735
+ devices: rotationDevices ?? []
1736
+ });
1737
+ if (reseal) {
1738
+ const views = await sealViews({
1739
+ view: rotation,
1740
+ networkId,
1741
+ keyring: rotated.keyring,
1742
+ account: accountAddress,
1743
+ targets: liveStoredReadGrants(stored, roster(chain.position().ledgerState), reseal.except)
1744
+ });
1745
+ stored = withSealedViews(stored, views);
1746
+ unsealedGrantIds = views.unsealed;
1747
+ revocationPendingGrantIds = views.revocationPending;
1748
+ await write(counter());
1749
+ await chain.append("recording", views.entries);
1750
+ }
1751
+ }
1752
+ await chain.submit(call);
1753
+ onProgress("confirming");
1754
+ const settled = await awaitSettledRoster({
1755
+ indexer,
1756
+ address: account.address,
1757
+ slots: storedGrantSlots(stored),
1758
+ openings: storedGrantOpenings(stored),
1759
+ isSettled
1760
+ });
1761
+ let grants = settled.roster;
1762
+ if (issued) {
1763
+ const entries = await seams.passportEncryptionKey.sealGrant(networkId, accountAddress, issued.bookkeeping);
1764
+ if (rotation && rotated && issued.readPublicKey !== void 0) {
1765
+ const views = await sealViews({
1766
+ view: rotation,
1767
+ networkId,
1768
+ keyring: rotated.keyring,
1769
+ account: accountAddress,
1770
+ targets: [{
1771
+ grantId: issued.bookkeeping.grantId,
1772
+ readPublicKey: issued.readPublicKey
1773
+ }]
1774
+ });
1775
+ stored = withSealedViews(stored, views);
1776
+ unsealedGrantIds = [...unsealedGrantIds, ...views.unsealed];
1777
+ revocationPendingGrantIds = [...revocationPendingGrantIds, ...views.revocationPending];
1778
+ entries.push(...views.entries);
1779
+ await write(counter());
1780
+ grants = roster(settled.ledgerState);
1781
+ }
1782
+ await chain.append("recording", entries);
1783
+ }
1784
+ return {
1785
+ grants,
1786
+ devices: chain.position().devices,
1787
+ localUseCounter: counter(),
1788
+ ...rotated ? {
1789
+ encKey: HexBytes.fromByteArray(rotated.encKey),
1790
+ droppedDevices: rotated.dropped
1791
+ } : {},
1792
+ unsealedGrantIds,
1793
+ revocationPendingGrantIds
1794
+ };
1795
+ });
1796
+ } catch (error) {
1797
+ throw classifyContractAbort(error);
1798
+ }
1799
+ };
1800
+ /**
1801
+ * Refuses a grant its grantee could never spend: one naming a scheme
1802
+ * whose withdrawals the account was deployed without. Installing them
1803
+ * takes a maintenance update, which a locked account can no longer sign
1804
+ * and an unlocked one no longer holds the key for, so the issue is
1805
+ * refused before the owner is asked to authorise it.
1806
+ *
1807
+ * @throws {@link GrantScopeInvalidError} when a withdrawal of the
1808
+ * grantee's scheme is not installed on the account.
1809
+ */
1810
+ const requireGranteeWithdrawals = async (indexer, address, scheme) => {
1811
+ const installed = new Set(await queryAccountOperations(indexer, address));
1812
+ const missing = GRANTEE_WITHDRAWAL_CIRCUITS[scheme].filter((circuit) => !installed.has(circuit));
1813
+ if (missing.length > 0) throw new GrantScopeInvalidError(`the account cannot serve a ${scheme} grantee, it lacks ${missing.join(", ")}`);
1814
+ };
1815
+ /**
1816
+ * Issues a scoped grant to an agent key. The scope is checked against the
1817
+ * rules the contract asserts before any prompt: a shielded operation
1818
+ * needs read, a read grant needs a canonical read public key, a rolling
1819
+ * window is refused because the contract reserves its bounds, and a
1820
+ * grant beyond sixteen active ones is refused as Lace's limit. Each
1821
+ * refusal is a GrantScopeInvalidError or GrantLimitReachedError and costs
1822
+ * no ceremony; a host with no relying party id is refused with
1823
+ * GrantOriginMissingError before the chain is read, and a read grant
1824
+ * with ReadUnavailableError when the encryption key held here cannot
1825
+ * share the viewing secret. The grant id is derived from the account,
1826
+ * the grantee key, the hash of this host's relying party id and the
1827
+ * first slot free for that pair, and the scope salt is drawn fresh; the
1828
+ * local device then authorises `issue_grant_with_jubjub` over the id and
1829
+ * the salted scope digest, which binds the hash of the read key. The key
1830
+ * session is opened with the account, the slot, the salt and the digest
1831
+ * beside the id and the scope, so an authoriser that does not share this
1832
+ * flow's memory can re-derive both before it signs.
1833
+ *
1834
+ * A read grant delivers the account's viewing secret, and read is total:
1835
+ * the grantee sees every shielded holding, current and future, until the
1836
+ * key is rotated again. So the key is rotated first, in the same session:
1837
+ * a fresh random secret is sealed to every device, the live holdings are
1838
+ * re-encrypted towards it, its public key replaces `enc_key`, and only
1839
+ * then is the grant issued, so the grantee reads nothing of the
1840
+ * account's spent history. Right after the rotation lands the new secret
1841
+ * is sealed to every other live read grant this client holds the key of,
1842
+ * so they keep reading even should the issue fail, and once the grant
1843
+ * shows active it is sealed to the grantee's read key; the seals join
1844
+ * the bookkeeping, and the grantee's reaches it through the agent
1845
+ * policy, never the chain. A grantee seal the key seam refuses after the
1846
+ * grant landed leaves the grant active and unsealed, named among the
1847
+ * result's unsealed grants, rather than failing the issue.
1848
+ *
1849
+ * The slot and salt are kept in the account record, since the contract
1850
+ * stores neither, together with the object fields its commitment hides
1851
+ * (colour, recipient and coin bound) and the read key, which the grantee
1852
+ * needs to open it and which reach the roster as the grant's opening.
1853
+ * They are written before the call is submitted: a grant that lands
1854
+ * without its salt could never be opened for its grantee. A call that
1855
+ * never lands leaves a stale entry, which the next sign-in prunes against
1856
+ * the chain and a later issue over the same id overwrites. Once the
1857
+ * grant shows active the same bookkeeping, and each seal, is appended to
1858
+ * the inbox in grant records only this device opens, so a sign-in after
1859
+ * the record is lost rebuilds it. The roster is read back from chain
1860
+ * once the grant shows active in it.
1861
+ *
1862
+ * A grant id the contract still holds active rejects with
1863
+ * GrantIssueRejectedError, and a rejected authorisation with
1864
+ * NotAuthorisedError. The transaction's proving and sponsoring stages,
1865
+ * the rotation, the wait for the indexer and the appends are reported
1866
+ * through `onProgress`.
1867
+ */
1868
+ const issueGrant = async ({ scope, ...input }, context) => {
1869
+ const { rpId, seams } = context;
1870
+ if (rpId === void 0) throw new GrantOriginMissingError();
1871
+ const view = scope.read ? viewCapability(seams.passportEncryptionKey) : null;
1872
+ const { account } = input;
1873
+ const ledger = await readAccountLedger(account.address, seams.passportNetwork);
1874
+ await requireGranteeWithdrawals(ledger.indexer, account.address, scope.grantee.scheme);
1875
+ const roster = readGrants(ledger.ledgerState);
1876
+ validateGrantScope(scope, {
1877
+ nowSeconds: nowSeconds(),
1878
+ grantCount: activeCount(roster)
1879
+ });
1880
+ const { grantId, slot, scopeSalt, scopeDigest, call } = prepareIssueGrant({
1881
+ contractAddress: ByteArray.fromHex(HexBytes(account.address)),
1882
+ scope,
1883
+ originHash: await originHash(rpId),
1884
+ roster
1885
+ });
1886
+ const readPublicKey = view ? scope.readPublicKey : void 0;
1887
+ const object = {
1888
+ color: scope.color,
1889
+ recipient: scope.recipient,
1890
+ maxCoinValue: scope.maxCoinValue
1891
+ };
1892
+ return {
1893
+ grantId,
1894
+ ...await runGrantCall({
1895
+ config: {
1896
+ call,
1897
+ flow: {
1898
+ kind: "issue-grant",
1899
+ grantId,
1900
+ scope,
1901
+ account: AccAddress(account.address),
1902
+ slot,
1903
+ scopeSalt,
1904
+ scopeDigest
1905
+ },
1906
+ nextStoredGrants: (stored) => withStoredGrant(stored, grantId, {
1907
+ slot,
1908
+ scopeSalt,
1909
+ granteeScheme: scope.grantee.scheme,
1910
+ granteePublicKey: scope.grantee.publicKey,
1911
+ origin: rpId,
1912
+ object,
1913
+ ...readPublicKey === void 0 ? {} : { view: { readPublicKey } }
1914
+ }),
1915
+ writeBeforeCall: true,
1916
+ isSettled: (settled) => isActive(settled, grantId),
1917
+ ...view && readPublicKey !== void 0 ? {
1918
+ rotation: view,
1919
+ reseal: { except: grantId }
1920
+ } : {},
1921
+ issued: {
1922
+ bookkeeping: {
1923
+ grantId,
1924
+ slot,
1925
+ scopeSalt,
1926
+ granteeScheme: scope.grantee.scheme,
1927
+ granteePublicKey: scope.grantee.publicKey,
1928
+ object,
1929
+ ...readPublicKey === void 0 ? {} : { readPublicKey }
1930
+ },
1931
+ ...readPublicKey === void 0 ? {} : { readPublicKey }
1932
+ }
1933
+ },
1934
+ input,
1935
+ ledger,
1936
+ roster,
1937
+ context
1938
+ })
1939
+ };
1940
+ };
1941
+ /**
1942
+ * The stored grants with the seal of one grant dropped, its read key
1943
+ * kept: a revoked read grant's seal holds a secret the rotation that
1944
+ * follows retires.
1945
+ */
1946
+ const withoutSeal = (stored, grantId) => {
1947
+ const view = stored?.[grantId]?.view;
1948
+ return stored && view ? withStoredGrantView(stored, grantId, { readPublicKey: view.readPublicKey }) : stored;
1949
+ };
1950
+ /**
1951
+ * Revokes one grant by its id. A grant the chain does not hold is refused
1952
+ * with GrantNotFoundError before any prompt, and one it lists inactive
1953
+ * with GrantRevokedError; the same errors type the contract's own aborts
1954
+ * should the grant vanish or be revoked elsewhere in between. The local
1955
+ * device authorises `revoke_grant_with_jubjub`. The grant stays in the
1956
+ * roster as an inactive tombstone, so its stored slot and salt are kept,
1957
+ * and the roster is read back from chain once the grant shows inactive.
1958
+ *
1959
+ * Revoking a read grant also rotates the encryption key, in the same
1960
+ * session ahead of the revocation: a fresh random secret is sealed to
1961
+ * every device and the live holdings are re-encrypted towards it, so the
1962
+ * revoked grantee keeps what it already read and nothing newer, and
1963
+ * right after the rotation lands the new secret is sealed again to every
1964
+ * other read grant this client holds the read key of, ahead of the
1965
+ * revocation. A read grant is refused with ReadUnavailableError before
1966
+ * any prompt when the encryption key held here cannot re-encrypt and
1967
+ * seal.
1968
+ */
1969
+ const revokeGrant = async ({ grantId, ...input }, context) => {
1970
+ const { account } = input;
1971
+ const ledger = await readAccountLedger(account.address, context.seams.passportNetwork);
1972
+ const roster = readGrants(ledger.ledgerState);
1973
+ const listed = roster.find((record) => record.id === grantId);
1974
+ if (!listed) throw new GrantNotFoundError(`The account at ${account.address} holds no grant ${grantId}.`);
1975
+ if (!listed.active) throw new GrantRevokedError(`The grant ${grantId} of the account at ${account.address} is already revoked.`);
1976
+ const rotation = listed.scope.read ? viewCapability(context.seams.passportEncryptionKey) : void 0;
1977
+ return runGrantCall({
1978
+ config: {
1979
+ call: prepareRevokeGrant(grantId),
1980
+ flow: {
1981
+ kind: "revoke-grant",
1982
+ grantId,
1983
+ account: AccAddress(account.address),
1984
+ ...rotation ? { read: true } : {}
1985
+ },
1986
+ nextStoredGrants: (stored) => rotation ? withoutSeal(stored, grantId) : stored,
1987
+ writeBeforeCall: false,
1988
+ isSettled: (settled) => !isActive(settled, grantId),
1989
+ ...rotation ? {
1990
+ rotation,
1991
+ reseal: { except: grantId }
1992
+ } : {}
1993
+ },
1994
+ input,
1995
+ ledger,
1996
+ roster,
1997
+ context
1998
+ });
1999
+ };
2000
+ /**
2001
+ * Revokes every grant the account has issued: the local device
2002
+ * authorises `revoke_all_grants_with_jubjub`, which clears the grants
2003
+ * map and advances the grant generation. The record's grant bookkeeping
2004
+ * is dropped with the map, and the roster is read back from chain once
2005
+ * it lists nothing, tombstones included. While any read grant is live,
2006
+ * the encryption key is rotated in the same session ahead of the call
2007
+ * and the live holdings are re-encrypted, so no revoked grantee reads
2008
+ * on; with every grant gone there is nobody to re-seal to. The rotation
2009
+ * is refused with ReadUnavailableError before any prompt when the
2010
+ * encryption key held here cannot re-encrypt.
2011
+ */
2012
+ const revokeAllGrants = async (input, context) => {
2013
+ const { account } = input;
2014
+ const ledger = await readAccountLedger(account.address, context.seams.passportNetwork);
2015
+ const roster = readGrants(ledger.ledgerState);
2016
+ const rotation = roster.some((record) => record.active && record.scope.read) ? viewCapability(context.seams.passportEncryptionKey) : void 0;
2017
+ return runGrantCall({
2018
+ config: {
2019
+ call: prepareRevokeAllGrants(),
2020
+ flow: {
2021
+ kind: "revoke-all-grants",
2022
+ account: AccAddress(account.address),
2023
+ ...rotation ? { read: true } : {}
2024
+ },
2025
+ nextStoredGrants: () => void 0,
2026
+ writeBeforeCall: false,
2027
+ isSettled: (settled) => settled.length === 0,
2028
+ ...rotation ? { rotation } : {}
2029
+ },
2030
+ input,
2031
+ ledger,
2032
+ roster,
2033
+ context
2034
+ });
2035
+ };
2036
+ //#endregion
2037
+ //#region ../../packages/module/passport-account/src/flows/holdings.ts
2038
+ /**
2039
+ * Reads the account's shielded holdings from public chain data: the
2040
+ * contract's inbox is walked with the account secrets this device's own
2041
+ * envelopes deliver, the one deriving the ledger's `enc_key` first and
2042
+ * the older ones after it, so a coin a racing sender or an interrupted
2043
+ * rotation left under an earlier key is still found, and each coin that
2044
+ * opens is kept only once its commitment is found among the outputs the
2045
+ * chain created for the account, with the tree index it took, and only
2046
+ * while its nullifier is not among those the chain recorded. The
2047
+ * envelopes are opened inside one key session, so the walk costs one
2048
+ * ceremony however many entries the inbox holds, and none at all when
2049
+ * it holds no coin to open; only the opened coin descriptions reach this
2050
+ * flow, never a secret. Nothing is written: no record, no chain call.
2051
+ *
2052
+ * A record whose address holds no live contract rejects with
2053
+ * AccountContractMissingError, and an inbox holding no envelope of this
2054
+ * device that opens the ledger's `enc_key` with EncryptionKeyMismatchError
2055
+ * rather than an inbox read as empty. An entry that fails to open or
2056
+ * describes a coin the chain never created is skipped and counted, never
2057
+ * an error; a coin the account spent is left out without being counted;
2058
+ * the account keys and grant bookkeeping the inbox also holds
2059
+ * are not coins and are not counted.
2060
+ *
2061
+ * Reports no intermediate stage: the ceremony and the indexer reads all
2062
+ * settle before there is anything to report.
2063
+ */
2064
+ const readShieldedHoldings = async ({ account }, { seams }) => {
2065
+ const { passportAuthoriser, passportEncryptionKey, passportNetwork } = seams;
2066
+ const indexer = createIndexerClient({
2067
+ indexerUrl: passportNetwork.indexerUrl,
2068
+ indexerWsUrl: passportNetwork.indexerWsUrl
2069
+ });
2070
+ const ledgerState = await queryAccountLedger(indexer, account.address);
2071
+ const { holdings, skippedEntries } = await walkInbox({
2072
+ address: account.address,
2073
+ ledgerState,
2074
+ indexer,
2075
+ openEntries: async (entries) => inKeySession(passportAuthoriser, { kind: "read-holdings" }, async () => {
2076
+ const { keyring } = readAccountInbox(account.address, ledgerState, await passportEncryptionKey.readerPublicKey(passportNetwork.networkId));
2077
+ return (await passportEncryptionKey.openInbox(passportNetwork.networkId, keyring, entries)).map((entry) => entry?.kind === "coin" ? entry.coin : null);
2078
+ })
2079
+ });
2080
+ return {
2081
+ holdings,
2082
+ skippedEntries
2083
+ };
2084
+ };
2085
+ //#endregion
2086
+ //#region ../../packages/module/passport-account/src/flows/install-operations.ts
2087
+ /**
2088
+ * The requested operations split by whether the account already holds
2089
+ * them, each in installation order, the deployed roster's.
2090
+ *
2091
+ * @throws {@link OperationNotInstallableError} naming every requested
2092
+ * operation outside the deployed roster, or when nothing is requested.
2093
+ */
2094
+ const installableOperations = (requested, installed) => {
2095
+ const outside = requested.filter((operation) => !DEPLOYED_OPERATIONS.includes(operation));
2096
+ if (outside.length > 0) throw new OperationNotInstallableError(`Not operations this module deploys: ${outside.join(", ")}.`);
2097
+ if (requested.length === 0) throw new OperationNotInstallableError("No operation was named to install.");
2098
+ const named = DEPLOYED_OPERATIONS.filter((operation) => requested.includes(operation));
2099
+ return {
2100
+ operations: named.filter((operation) => !installed.includes(operation)),
2101
+ alreadyInstalled: named.filter((operation) => installed.includes(operation))
2102
+ };
2103
+ };
2104
+ /** The inserts of one wave, each operation with the verifier key loaded for it. */
2105
+ const insertsOf = (operations, keys) => operations.map((operation) => {
2106
+ const verifierKey = keys.get(operation);
2107
+ if (!verifierKey) throw new Error(`No verifier key loaded for '${operation}'`);
2108
+ return {
2109
+ operation,
2110
+ verifierKey
2111
+ };
2112
+ });
2113
+ /**
2114
+ * Installs on an unlocked account the verifier keys of operations of the
2115
+ * deployed roster it lacks, so an account created under an earlier
2116
+ * roster gains the circuits added since without a new deployment. Only
2117
+ * operations this module deploys can be installed, never a recovery
2118
+ * circuit or another device arm, and each key is the one pinned for its
2119
+ * operation, which the encryption key checks again before it signs.
2120
+ *
2121
+ * The operations the account holds and its maintenance authority are
2122
+ * read from chain before any prompt: a request naming no operation, or an
2123
+ * operation outside the roster, is refused with
2124
+ * OperationNotInstallableError naming them. Requested operations the
2125
+ * account already holds are skipped, so an install interrupted after some
2126
+ * waves landed is finished by running it again; when it holds every one,
2127
+ * this resolves with nothing submitted and no prompt. Otherwise a locked
2128
+ * account is refused with AuthorityRetiredError, and an encryption key
2129
+ * that cannot sign maintenance updates with
2130
+ * MaintenanceUpdateRefusedError. The verifier
2131
+ * keys are then downloaded against their pins and packed into waves
2132
+ * under the per-transaction budget. In one key session naming the
2133
+ * account and the operations, the keyring is read from the ledger as it
2134
+ * stands then, so a rotation that landed during the downloads is
2135
+ * followed, and the encryption key signs each wave with the roster key
2136
+ * of this device's keyring whose authority the chain holds; an authority none of them derives is refused with
2137
+ * MaintenanceAuthorityMismatchError before anything is submitted. Each
2138
+ * wave waits for the chain to show the advanced counter, so this
2139
+ * resolves once the chain holds every installed key, with the operations
2140
+ * it installed and those it skipped.
2141
+ *
2142
+ * No gated call is made, so the use counter and the record are left as
2143
+ * they are. The transactions' sponsoring stage is reported through
2144
+ * `onProgress`.
2145
+ */
2146
+ const installOperations = async ({ account, operations: requested }, { seams, onProgress }) => {
2147
+ const { address } = account;
2148
+ const { indexerUrl, indexerWsUrl } = seams.passportNetwork;
2149
+ const indexer = createIndexerClient({
2150
+ indexerUrl,
2151
+ indexerWsUrl
2152
+ });
2153
+ const { operations, alreadyInstalled } = installableOperations(requested, await queryAccountOperations(indexer, address));
2154
+ if (operations.length === 0) return {
2155
+ operations,
2156
+ alreadyInstalled
2157
+ };
2158
+ await assertInstallSigner({
2159
+ address,
2160
+ indexer,
2161
+ encryptionKey: seams.passportEncryptionKey
2162
+ });
2163
+ const providers = await createMidnightProviders({
2164
+ network: seams.passportNetwork,
2165
+ prover: seams.passportProver,
2166
+ sponsor: seams.passportSponsor,
2167
+ onStage: onProgress
2168
+ });
2169
+ const { keys, sizes } = await loadVerifierKeys(providers, operations);
2170
+ const waves = planInstallWaves(operations, sizes).map((wave) => insertsOf(wave.operations, keys));
2171
+ return inKeySession(seams.passportAuthoriser, {
2172
+ kind: "install-operations",
2173
+ account: AccAddress(address),
2174
+ operations
2175
+ }, async () => {
2176
+ const { keyring } = readAccountInbox(address, await queryAccountLedger(indexer, address), await seams.passportEncryptionKey.readerPublicKey(seams.passportNetwork.networkId));
2177
+ await installVerifierKeys({
2178
+ address,
2179
+ seams,
2180
+ providers,
2181
+ keyring,
2182
+ waves
2183
+ });
2184
+ return {
2185
+ operations,
2186
+ alreadyInstalled
2187
+ };
2188
+ });
2189
+ };
2190
+ //#endregion
2191
+ //#region ../../packages/module/passport-account/src/flows/sign-in.ts
2192
+ /**
2193
+ * The account's whole device roster, read from the on-chain device set.
2194
+ * Entries are opaque rolling commitments, so a remote entry carries no
2195
+ * identity beyond its commitment: only the local device can be named, by
2196
+ * the commitment its own rescan resolved.
2197
+ */
2198
+ const toDeviceRoster = (entries, localCommitmentHex) => Array.from(entries, (entry) => {
2199
+ const commitmentHex = HexBytes.fromByteArray(entry);
2200
+ return {
2201
+ commitmentHex,
2202
+ isLocal: commitmentHex === localCommitmentHex
2203
+ };
2204
+ });
2205
+ /**
2206
+ * Refuses a record whose creation is still unfinished on chain. A record
2207
+ * that carries a pending deployment names a contract that may still miss
2208
+ * verifier keys, its initial device or the entries that deliver the
2209
+ * account keys, which only the create flow can complete; but a creation
2210
+ * that appended its key entries and then died before its final record
2211
+ * write left a usable account behind, and the chain's boot flag and inbox
2212
+ * tell the two apart.
2213
+ */
2214
+ const assertCreationComplete = (record, isActivated, entries) => {
2215
+ const { deployment } = record;
2216
+ if (deployment === void 0) return;
2217
+ const held = new Set(entries.map((entry) => HexBytes.fromByteArray(entry)));
2218
+ if (!isActivated || deployment.keyEntries.some((entry) => !held.has(entry))) throw new AccountCreationPendingError(`The account at ${record.address} is deployed but not yet ready; resume the creation on this device, from the site that started it.`);
2219
+ };
2220
+ /** The grant record parts the Lace records of an inbox opened to. */
2221
+ const grantPartsOf = (opened) => opened.flatMap((entry) => entry?.kind === "grant" ? [entry.record] : []);
2222
+ /**
2223
+ * Recognises an existing Passport account on this device: the passkey
2224
+ * ceremony (implicit in the first authoriser use) proves the device key,
2225
+ * the persisted account record names the Account Custody Contract, the
2226
+ * indexer confirms the contract is live, this device's own envelopes in
2227
+ * the contract's inbox open a secret deriving the `enc_key` the contract
2228
+ * advertises, and the use-counter rescan restores this device's roster
2229
+ * position from the on-chain device set. The account secret is never
2230
+ * read from the record or derived from the passkey: it is random, and
2231
+ * this device reaches it only through an envelope sealed to its reader
2232
+ * key, so a device enrolled with its own passkey signs in without the
2233
+ * record of the device that created the account. The roster is rebuilt
2234
+ * from every entry in the device set, so a device enrolled elsewhere
2235
+ * survives a reload; only the local entry is named, the rest are opaque
2236
+ * commitments. The grant roster is read from the contract's grants map
2237
+ * the same way, with the slots and openings the record kept for the
2238
+ * grants this client issued; a grant the record lacks, as after the
2239
+ * record was lost, is rebuilt from the grant records this device keeps in
2240
+ * the inbox once they open its on-chain commitments under this host's
2241
+ * relying party id, its seal kept only while it holds the live secret.
2242
+ * A grant the record holds is kept only while its fields open the
2243
+ * commitments the chain holds under its id, so an entry an issue wrote
2244
+ * before a call that never landed gives way to the grant another client
2245
+ * of the account issued over the same id, and a rebuilt grant takes its
2246
+ * place when there is one. The live read grants whose kept seal does not
2247
+ * hold the live secret, as after an issue that failed before its seal,
2248
+ * are reported as unsealed.
2249
+ * The devices registered under the live roster key are kept in the
2250
+ * record as the roster the next rotation seals to. The whole chain runs
2251
+ * inside one key session, so it costs a single ceremony rather than one
2252
+ * per authoriser call.
2253
+ *
2254
+ * The healed counter is written back to the persisted record before this
2255
+ * resolves, so the next sign-in rescans from a fresh anchor instead of the
2256
+ * creation-time one. That write also completes a record a creation left
2257
+ * pending after its key entries landed, dropping the deployment and the
2258
+ * authority key it carries, and drops the bookkeeping of grants the chain
2259
+ * no longer holds or whose commitments it does not open. A missing record
2260
+ * raises AccountNotFoundError, a record whose address holds no live
2261
+ * contract raises AccountContractMissingError,
2262
+ * a record whose creation is unfinished on chain raises
2263
+ * AccountCreationPendingError, and an inbox holding no envelope of this
2264
+ * device that opens the live `enc_key`, as for a device never handed the
2265
+ * keys or removed since, raises EncryptionKeyMismatchError before the
2266
+ * rescan runs; rediscovering an account by name service when no record is
2267
+ * persisted is a separate flow and out of scope here.
2268
+ *
2269
+ * signIn reports no intermediate stage: the ceremony, the indexer read and
2270
+ * the rescan all settle before there is anything to report.
2271
+ */
2272
+ const signIn = async ({ seams, accountRecords, rpId }) => {
2273
+ const { passportAuthoriser, passportEncryptionKey, passportNetwork } = seams;
2274
+ return inKeySession(passportAuthoriser, { kind: "sign-in" }, async () => {
2275
+ const local = await readLocalDevice(seams);
2276
+ const record = await accountRecords.read();
2277
+ if (!record) throw new AccountNotFoundError("No Passport account record is stored on this device.");
2278
+ const state = await createIndexerClient({
2279
+ indexerUrl: passportNetwork.indexerUrl,
2280
+ indexerWsUrl: passportNetwork.indexerWsUrl
2281
+ }).queryContractState(record.address);
2282
+ if (!state) throw new AccountContractMissingError(`No live Account Custody Contract found at ${record.address}.`);
2283
+ const ledgerState = ledger(state.data);
2284
+ const { entries, keyring } = readAccountInbox(record.address, ledgerState, local.readerPublicKey);
2285
+ assertCreationComplete(record, ledgerState.booted, entries);
2286
+ if (keyring.envelopes.length === 0) throw new EncryptionKeyMismatchError(`The inbox of the account at ${record.address} holds no envelope for this device.`);
2287
+ const grantParts = grantPartsOf(await passportEncryptionKey.openInbox(passportNetwork.networkId, keyring, entries.filter(isLaceRecord)));
2288
+ const { useCounter, commitmentHex } = await resolveUseCounter({
2289
+ ledgerState,
2290
+ authoriser: passportAuthoriser,
2291
+ address: AccAddress(record.address),
2292
+ knownUseCounter: UseCounter(BigInt(record.localUseCounter))
2293
+ });
2294
+ const devices = toDeviceRoster(ledgerState.devices, commitmentHex);
2295
+ const encKey = HexBytes.fromByteArray(ledgerState.enc_key);
2296
+ const onChain = readGrants(ledgerState);
2297
+ const stored = withRebuiltGrants(await retainStoredGrants(record.grants, onChain, record.address), rpId === void 0 ? void 0 : await rebuildStoredGrants(grantParts, onChain, {
2298
+ address: record.address,
2299
+ origin: rpId,
2300
+ encKey
2301
+ }), encKey);
2302
+ const grants = readGrants(ledgerState, storedGrantSlots(stored), storedGrantOpenings(stored));
2303
+ const localUseCounter = useCounter.toString();
2304
+ await accountRecords.write(completedRecord(record, localUseCounter, { grants: stored }));
2305
+ return {
2306
+ account: {
2307
+ address: record.address,
2308
+ bindingVersion: record.bindingVersion,
2309
+ status: "ready",
2310
+ networkId: passportNetwork.networkId
2311
+ },
2312
+ devices,
2313
+ localUseCounter,
2314
+ grants,
2315
+ encKey,
2316
+ unsealedGrantIds: unsealedStoredReadGrants(stored, onChain, encKey)
2317
+ };
2318
+ });
2319
+ };
2320
+ //#endregion
2321
+ //#region ../../packages/module/passport-account/src/store/dependencies.ts
2322
+ /**
2323
+ * Runs a flow as a cold stream of its events. `run` is invoked once per
2324
+ * subscription with a progress sink that emits synchronously as the flow
2325
+ * reports; the resolution emits 'done' and completes, and a rejection
2326
+ * errors the stream. Unsubscribing only stops delivery: the running
2327
+ * promise is not cancelled, because a flow must run to completion once
2328
+ * started (abandoning it mid-deploy could orphan a sponsored contract).
2329
+ */
2330
+ const observeFlow = (run) => new Observable((subscriber) => {
2331
+ let isDelivering = true;
2332
+ run((stage) => {
2333
+ if (isDelivering) subscriber.next({
2334
+ type: "progress",
2335
+ stage
2336
+ });
2337
+ }).then((result) => {
2338
+ if (!isDelivering) return;
2339
+ subscriber.next({
2340
+ type: "done",
2341
+ result
2342
+ });
2343
+ subscriber.complete();
2344
+ }, (error) => {
2345
+ if (isDelivering) subscriber.error(error);
2346
+ });
2347
+ return () => {
2348
+ isDelivering = false;
2349
+ };
2350
+ });
2351
+ /**
2352
+ * The context a flow runs under, drawn from the side-effect dependency
2353
+ * bag: the five seams, the record store and the relying party id. An
2354
+ * injected store is used as is; otherwise the store is built over the
2355
+ * platform storage and keyed by the authoriser, so a record sealed by one
2356
+ * authoriser is only ever written through it. The sealed-record options
2357
+ * apply to that built store; signIn and the grant flows pass
2358
+ * `onSealedWithoutKey: 'error'` so a sealed record found without a
2359
+ * storage key surfaces as record-unreadable rather than as an absent
2360
+ * account.
2361
+ */
2362
+ const toFlowContext = ({ createKeyValueStorage, passportAuthoriser, passportEncryptionKey, passportNetwork, passportProver, passportSponsor }, onProgress, { store, rpId, ...recordOptions }) => ({
2363
+ seams: {
2364
+ passportAuthoriser,
2365
+ passportEncryptionKey,
2366
+ passportNetwork,
2367
+ passportProver,
2368
+ passportSponsor
2369
+ },
2370
+ accountRecords: toAccountRecords(store ?? createAccountRecordStore(createKeyValueStorage, passportAuthoriser.storageKey, recordOptions)),
2371
+ onProgress,
2372
+ rpId
2373
+ });
2374
+ /**
2375
+ * Maps the platform capabilities passed to `createPassportAccountModule`
2376
+ * onto the `passport-dependency` contract, and exposes the platform-neutral
2377
+ * flows observable-based. The flows are promise functions; wrapping them
2378
+ * here rather than in the side effects is what keeps promise handling out
2379
+ * of the side effects, so they compose the flows as plain streams and stay
2380
+ * testable on a virtual scheduler. The relying party id defaults to the
2381
+ * page's hostname, as the passkey ceremony's does.
2382
+ */
2383
+ const createDependencies = ({ authoriser, encryptionKey, sponsor, prover, network, accountRecordStore, rpId = globalThis.location?.hostname }) => {
2384
+ const host = {
2385
+ store: accountRecordStore,
2386
+ rpId
2387
+ };
2388
+ const recordRequired = {
2389
+ ...host,
2390
+ onSealedWithoutKey: "error"
2391
+ };
2392
+ return {
2393
+ passportAuthoriser: authoriser,
2394
+ passportEncryptionKey: encryptionKey,
2395
+ passportSponsor: sponsor,
2396
+ passportProver: prover,
2397
+ passportNetwork: network,
2398
+ passportFlows: {
2399
+ createAccount: (input, dependencies) => observeFlow(async (onProgress) => createAccount(input, toFlowContext(dependencies, onProgress, host))),
2400
+ signIn: (dependencies) => observeFlow(async (onProgress) => signIn(toFlowContext(dependencies, onProgress, recordRequired))),
2401
+ addDevice: (input, dependencies) => observeFlow(async (onProgress) => addDevice(input, toFlowContext(dependencies, onProgress, host))),
2402
+ removeDevice: (input, dependencies) => observeFlow(async (onProgress) => removeDevice(input, toFlowContext(dependencies, onProgress, host))),
2403
+ issueGrant: (input, dependencies) => observeFlow(async (onProgress) => issueGrant(input, toFlowContext(dependencies, onProgress, recordRequired))),
2404
+ revokeGrant: (input, dependencies) => observeFlow(async (onProgress) => revokeGrant(input, toFlowContext(dependencies, onProgress, recordRequired))),
2405
+ revokeAllGrants: (input, dependencies) => observeFlow(async (onProgress) => revokeAllGrants(input, toFlowContext(dependencies, onProgress, recordRequired))),
2406
+ readShieldedHoldings: (input, dependencies) => observeFlow(async (onProgress) => readShieldedHoldings(input, toFlowContext(dependencies, onProgress, host))),
2407
+ installOperations: (input, dependencies) => observeFlow(async (onProgress) => installOperations(input, toFlowContext(dependencies, onProgress, host)))
2408
+ }
2409
+ };
2410
+ };
2411
+ //#endregion
2412
+ //#region ../../packages/module/passport-account/src/store/side-effects/flow-actions.ts
2413
+ /**
2414
+ * The flow error a failure reports: the error's own typed code when it
2415
+ * carries one, otherwise the flow's fallback code.
2416
+ */
2417
+ const toFlowError = (error, fallbackCode) => ({
2418
+ code: error instanceof Object && "code" in error && typeof error.code === "string" ? error.code : fallbackCode,
2419
+ message: error instanceof Error ? error.message : String(error)
2420
+ });
2421
+ /**
2422
+ * Maps a flow's events onto the passport flow state: each stage to
2423
+ * setFlow, the result to its publishing actions followed by
2424
+ * setFlow('ready'), and a failure to its `onFailed` actions followed by
2425
+ * a single setFlowError, so a flow always settles in 'ready' or 'error'.
2426
+ */
2427
+ const flowActions = (events$, { actions, fallbackCode, onDone, onFailed = [] }) => events$.pipe(mergeMap((event) => event.type === "progress" ? [actions.passport.setFlow(event.stage)] : [...onDone(event.result), actions.passport.setFlow("ready")]), catchError((error) => of(...onFailed, actions.passport.setFlowError(toFlowError(error, fallbackCode)))));
2428
+ //#endregion
2429
+ //#region ../../packages/module/passport-account/src/store/side-effects/passport-flows.ts
2430
+ /** Flow error code for creation failures that carry no typed code of their own. */
2431
+ const CREATE_ACCOUNT_FALLBACK_ERROR_CODE = "account-create-failed";
2432
+ /** Flow error code for sign-in failures that carry no typed code of their own. */
2433
+ const SIGN_IN_FALLBACK_ERROR_CODE = "account-sign-in-failed";
2434
+ /** Flow error codes for device call failures that carry no typed code of their own. */
2435
+ const ADD_DEVICE_FALLBACK_ERROR_CODE = "device-add-failed";
2436
+ const REMOVE_DEVICE_FALLBACK_ERROR_CODE = "device-remove-failed";
2437
+ /** Flow error codes for grant call failures that carry no typed code of their own. */
2438
+ const ISSUE_GRANT_FALLBACK_ERROR_CODE = "grant-issue-failed";
2439
+ const REVOKE_GRANT_FALLBACK_ERROR_CODE = "grant-revoke-failed";
2440
+ const REVOKE_ALL_GRANTS_FALLBACK_ERROR_CODE = "grant-revoke-all-failed";
2441
+ /** Flow error code for holdings reads that carry no typed code of their own. */
2442
+ const READ_HOLDINGS_FALLBACK_ERROR_CODE = "holdings-read-failed";
2443
+ /** Flow error code for installs that carry no typed code of their own. */
2444
+ const INSTALL_OPERATIONS_FALLBACK_ERROR_CODE = "operations-install-failed";
2445
+ /**
2446
+ * Flows an account call may start from. 'error' is a settled state, not
2447
+ * an operation in progress, so a call that failed can be retried without
2448
+ * a fresh sign-in ceremony; every other non-ready flow is an operation
2449
+ * left unfinished, whose account and use counter cannot be trusted yet.
2450
+ */
2451
+ const SETTLED_FLOWS = ["error", "ready"];
2452
+ /**
2453
+ * The actions that publish a roster a flow left behind: the devices, then
2454
+ * the counter the local row sits at. Both land ahead of 'ready', in the
2455
+ * order the flows have always published them.
2456
+ */
2457
+ const publishDeviceRoster = (actions) => ({ devices, localUseCounter }) => [actions.passport.setDevices(devices), actions.passport.setLocalUseCounter(localUseCounter)];
2458
+ /**
2459
+ * The actions that publish what a grant call left behind: the device
2460
+ * roster and counter it advanced, the `enc_key` a rotation it ran stepped
2461
+ * the encryption key to and the devices it left without the new key, the
2462
+ * grant roster, then the read grants the
2463
+ * call could not seal the viewing secret to, empty when it sealed all,
2464
+ * and those the signer refused because their revocation is pending.
2465
+ */
2466
+ const publishGrantRoster = (actions) => ({ grants, encKey, unsealedGrantIds, revocationPendingGrantIds, droppedDevices, ...roster }) => [
2467
+ ...publishDeviceRoster(actions)(roster),
2468
+ ...encKey === void 0 ? [] : [actions.passport.setEncKey(encKey)],
2469
+ ...droppedDevices === void 0 ? [] : [actions.passport.setDroppedDevices(droppedDevices)],
2470
+ actions.passport.setGrants(grants),
2471
+ actions.passport.setUnsealedGrantIds(unsealedGrantIds),
2472
+ actions.passport.setRevocationPendingGrantIds(revocationPendingGrantIds)
2473
+ ];
2474
+ /**
2475
+ * The actions that publish an issued grant: the rosters, then the id of
2476
+ * the grant, last so a consumer reacting to it finds the record in state.
2477
+ */
2478
+ const publishIssuedGrant = (actions) => ({ grantId, ...roster }) => [...publishGrantRoster(actions)(roster), actions.passport.setLastIssuedGrantId(grantId)];
2479
+ /**
2480
+ * The actions that publish an account a flow left ready: the account,
2481
+ * its device roster and counter, the `enc_key` its encryption key is
2482
+ * at, then its grant roster.
2483
+ */
2484
+ const publishAccountState = (actions) => ({ account, grants, encKey, ...roster }) => [
2485
+ actions.passport.setAccount(account),
2486
+ ...publishDeviceRoster(actions)(roster),
2487
+ actions.passport.setEncKey(encKey),
2488
+ actions.passport.setGrants(grants)
2489
+ ];
2490
+ /**
2491
+ * The actions that publish an account a sign-in recognised: the account
2492
+ * state, see {@link publishAccountState}, then the read grants whose kept
2493
+ * seal does not hold the live viewing secret, and no grants pending a
2494
+ * revocation, which only a grant call learns from the signer.
2495
+ */
2496
+ const publishRecognisedAccount = (actions) => ({ unsealedGrantIds, ...state }) => [
2497
+ ...publishAccountState(actions)(state),
2498
+ actions.passport.setUnsealedGrantIds(unsealedGrantIds),
2499
+ actions.passport.setRevocationPendingGrantIds([])
2500
+ ];
2501
+ /**
2502
+ * A device or grant call may rotate the account keys before it fails, so
2503
+ * the `enc_key` state holds may be the one rotated away: it is forgotten
2504
+ * until the next sign-in or rotation publishes it again, rather than let
2505
+ * a stale seal pass as current. The read grants an earlier call reported
2506
+ * unsealed or pending revocation were judged against that key, so they
2507
+ * are emptied with it.
2508
+ */
2509
+ const forgetKeyState = (actions) => [
2510
+ actions.passport.clearEncKey(),
2511
+ actions.passport.setUnsealedGrantIds([]),
2512
+ actions.passport.setRevocationPendingGrantIds([])
2513
+ ];
2514
+ /**
2515
+ * The createAccount flow behind the createAccount action, as the actions it
2516
+ * publishes: each reported stage as setFlow, then the created account, its
2517
+ * one-device roster, this device's counter and its empty grant roster,
2518
+ * then 'ready'. The flow itself persists the account record before it
2519
+ * resolves, so the account is never published ahead of the record that
2520
+ * recognises it.
2521
+ */
2522
+ const runCreateAccount = (input, dependencies) => {
2523
+ const { actions, passportFlows } = dependencies;
2524
+ return flowActions(passportFlows.createAccount(input, dependencies), {
2525
+ actions,
2526
+ fallbackCode: CREATE_ACCOUNT_FALLBACK_ERROR_CODE,
2527
+ onDone: publishAccountState(actions)
2528
+ });
2529
+ };
2530
+ /**
2531
+ * The signIn flow behind the signIn action, as the actions it publishes:
2532
+ * the recognised account, its whole device roster, this device's healed
2533
+ * use counter, the grant roster and its unsealed read grants, then
2534
+ * 'ready'. The flow itself persists the healed counter before it
2535
+ * resolves, so the record is never left behind the state it publishes.
2536
+ */
2537
+ const runSignIn = (dependencies) => {
2538
+ const { actions, passportFlows } = dependencies;
2539
+ return flowActions(passportFlows.signIn(dependencies), {
2540
+ actions,
2541
+ fallbackCode: SIGN_IN_FALLBACK_ERROR_CODE,
2542
+ onDone: publishRecognisedAccount(actions)
2543
+ });
2544
+ };
2545
+ /**
2546
+ * The actions that publish what a device call left behind: its roster and
2547
+ * counter, then, when it rotated the account keys, the `enc_key` it
2548
+ * stepped to and the devices it left without the new key.
2549
+ */
2550
+ const publishDeviceCall = (actions) => ({ encKey, droppedDevices, ...roster }) => [
2551
+ ...publishDeviceRoster(actions)(roster),
2552
+ ...encKey === void 0 ? [] : [actions.passport.setEncKey(encKey)],
2553
+ ...droppedDevices === void 0 ? [] : [actions.passport.setDroppedDevices(droppedDevices)]
2554
+ ];
2555
+ /**
2556
+ * The addDevice flow behind its action: what the call left behind, see
2557
+ * {@link publishDeviceCall}, then 'ready'. The joining device's keys
2558
+ * travel with the request when the action names them.
2559
+ */
2560
+ const addDeviceCall = {
2561
+ start: ({ commitmentHex, reader }, input, dependencies) => dependencies.passportFlows.addDevice({
2562
+ commitmentHex,
2563
+ ...reader ? { reader } : {},
2564
+ ...input
2565
+ }, dependencies),
2566
+ onDone: publishDeviceCall,
2567
+ fallbackCode: ADD_DEVICE_FALLBACK_ERROR_CODE,
2568
+ onFailed: forgetKeyState
2569
+ };
2570
+ /**
2571
+ * The removeDevice flow behind its action: what the call left behind, see
2572
+ * {@link publishDeviceCall}, then 'ready'.
2573
+ */
2574
+ const removeDeviceCall = {
2575
+ start: ({ commitmentHex }, input, dependencies) => dependencies.passportFlows.removeDevice({
2576
+ commitmentHex,
2577
+ ...input
2578
+ }, dependencies),
2579
+ onDone: publishDeviceCall,
2580
+ fallbackCode: REMOVE_DEVICE_FALLBACK_ERROR_CODE,
2581
+ onFailed: forgetKeyState
2582
+ };
2583
+ /**
2584
+ * The issueGrant flow behind its action: the rosters the call left
2585
+ * behind and the issued grant's id, then 'ready'.
2586
+ */
2587
+ const issueGrantCall = {
2588
+ start: (scope, input, dependencies) => dependencies.passportFlows.issueGrant({
2589
+ scope,
2590
+ ...input
2591
+ }, dependencies),
2592
+ onDone: publishIssuedGrant,
2593
+ fallbackCode: ISSUE_GRANT_FALLBACK_ERROR_CODE,
2594
+ onFailed: forgetKeyState
2595
+ };
2596
+ /** The revokeGrant flow behind its action: the rosters it left behind, then 'ready'. */
2597
+ const revokeGrantCall = {
2598
+ start: ({ grantId }, input, dependencies) => dependencies.passportFlows.revokeGrant({
2599
+ grantId,
2600
+ ...input
2601
+ }, dependencies),
2602
+ onDone: publishGrantRoster,
2603
+ fallbackCode: REVOKE_GRANT_FALLBACK_ERROR_CODE,
2604
+ onFailed: forgetKeyState
2605
+ };
2606
+ /** The revokeAllGrants flow behind its action: the rosters it left behind, then 'ready'. */
2607
+ const revokeAllGrantsCall = {
2608
+ start: (_payload, input, dependencies) => dependencies.passportFlows.revokeAllGrants(input, dependencies),
2609
+ onDone: publishGrantRoster,
2610
+ fallbackCode: REVOKE_ALL_GRANTS_FALLBACK_ERROR_CODE,
2611
+ onFailed: forgetKeyState
2612
+ };
2613
+ /**
2614
+ * The readShieldedHoldings flow behind its action: the holdings the walk
2615
+ * verified, then 'ready'. The skip count is the flow's to report, not the
2616
+ * store's to keep: a skipped entry is noise the inbox will carry forever.
2617
+ */
2618
+ const readShieldedHoldingsCall = {
2619
+ start: (_payload, input, dependencies) => dependencies.passportFlows.readShieldedHoldings(input, dependencies),
2620
+ onDone: (actions) => ({ holdings }) => [actions.passport.setShieldedHoldings(holdings)],
2621
+ fallbackCode: READ_HOLDINGS_FALLBACK_ERROR_CODE
2622
+ };
2623
+ /**
2624
+ * The installOperations flow behind its action, then 'ready'. A landed
2625
+ * install changes nothing state holds, so it publishes nothing of its
2626
+ * own.
2627
+ */
2628
+ const installOperationsCall = {
2629
+ start: ({ operations }, { account }, dependencies) => dependencies.passportFlows.installOperations({
2630
+ account,
2631
+ operations
2632
+ }, dependencies),
2633
+ onDone: () => () => [],
2634
+ fallbackCode: INSTALL_OPERATIONS_FALLBACK_ERROR_CODE
2635
+ };
2636
+ /**
2637
+ * An account call behind its action, as the actions it publishes: what
2638
+ * the call left behind, then 'ready', or, when it fails, the actions
2639
+ * undoing what state may wrongly claim, then the error. The flow itself
2640
+ * persists the counter before it resolves.
2641
+ *
2642
+ * Requires an account and a settled flow: with no account in state, or
2643
+ * with an operation left unfinished, the flow is never called (so the
2644
+ * chain and the key session are never touched) and the call settles in
2645
+ * 'error' with 'no-account'. The refusal still runs behind the gate, so
2646
+ * it enters 'ceremony' first like any accepted request and clears the
2647
+ * error a previous flow left behind.
2648
+ */
2649
+ const runAccountCall = ({ start, onDone, fallbackCode, onFailed }, { payload, flow, account, devices, localUseCounter }, dependencies) => {
2650
+ const { actions } = dependencies;
2651
+ if (!account || !SETTLED_FLOWS.includes(flow)) return of(actions.passport.setFlowError(toFlowError(new NoAccountError(), fallbackCode)));
2652
+ return flowActions(start(payload, {
2653
+ account,
2654
+ devices,
2655
+ localUseCounter
2656
+ }, dependencies), {
2657
+ actions,
2658
+ fallbackCode,
2659
+ onDone: onDone(actions),
2660
+ ...onFailed ? { onFailed: onFailed(actions) } : {}
2661
+ });
2662
+ };
2663
+ /**
2664
+ * One start per dispatched account call action, each carrying the state
2665
+ * the call needs. State is sampled when the action arrives rather than
2666
+ * when the shared gate starts the call, so a call reads the account,
2667
+ * roster and counter the user acted on.
2668
+ */
2669
+ const accountCallStarts = ({ config, trigger$, stateObservables: { passport: { selectAccount$, selectDevices$, selectFlow$, selectLocalUseCounter$ } }, dependencies }) => trigger$.pipe(withLatestFrom(selectFlow$, selectAccount$, selectDevices$, selectLocalUseCounter$), map(([{ payload }, flow, account, devices, localUseCounter]) => () => runAccountCall(config, {
2670
+ payload,
2671
+ flow,
2672
+ account,
2673
+ devices,
2674
+ localUseCounter
2675
+ }, dependencies)));
2676
+ /**
2677
+ * Runs whichever passport flow was requested: {@link runCreateAccount}
2678
+ * behind the createAccount action, {@link runSignIn} behind signIn, and
2679
+ * {@link runAccountCall} behind addDevice, removeDevice, issueGrant,
2680
+ * revokeGrant, revokeAllGrants, readShieldedHoldings and
2681
+ * installOperations.
2682
+ *
2683
+ * Every flow owns the same account record, the same device key and the
2684
+ * same flow state, and each chain call resolves the account's use counter
2685
+ * and auth nonce, so they must never overlap: two calls resolving the same
2686
+ * counter both spend the same entry, one transaction is rejected, and the
2687
+ * loser reports its own failure over state the winner already moved on.
2688
+ * A holdings read spends no entry, but it opens the same key session and
2689
+ * reports through the same flow state, so it runs behind the same gate.
2690
+ * One exhaustMap over the merged starts, rather than one per action,
2691
+ * makes them mutually exclusive: a dispatch arriving while any flow is in
2692
+ * flight emits nothing at all, and the next one is only accepted once the
2693
+ * running flow settles. Dropping it silently is the stance exhaustMap
2694
+ * already took for a repeated dispatch of one action; a flow the user
2695
+ * never saw start is not a failure to report.
2696
+ *
2697
+ * Because only the gate knows which requests it accepted, it also owns
2698
+ * the entry into 'ceremony': the trigger reducers are pure, so a dropped
2699
+ * request cannot overwrite the running flow's state, and setFlow clears
2700
+ * the error a previous flow left behind. The emission is synchronous on
2701
+ * the accepted start, so a consumer sees the ceremony within the same
2702
+ * dispatch cycle as the trigger.
2703
+ *
2704
+ * The flow state cannot carry this guard the other way round: state
2705
+ * reaches a side effect before the action does, and an inner flow is
2706
+ * still subscribed while its own terminal setFlow('ready') is delivered,
2707
+ * so a reducer reading the flow back cannot tell a request the gate will
2708
+ * accept from one it will drop.
2709
+ */
2710
+ const runPassportFlow = ({ passport: { addDevice$, createAccount$, installOperations$, issueGrant$, readShieldedHoldings$, removeDevice$, revokeAllGrants$, revokeGrant$, signIn$ } }, stateObservables, dependencies) => merge(createAccount$.pipe(map(({ payload }) => () => runCreateAccount(payload, dependencies))), signIn$.pipe(map(() => () => runSignIn(dependencies))), accountCallStarts({
2711
+ config: addDeviceCall,
2712
+ trigger$: addDevice$,
2713
+ stateObservables,
2714
+ dependencies
2715
+ }), accountCallStarts({
2716
+ config: removeDeviceCall,
2717
+ trigger$: removeDevice$,
2718
+ stateObservables,
2719
+ dependencies
2720
+ }), accountCallStarts({
2721
+ config: issueGrantCall,
2722
+ trigger$: issueGrant$,
2723
+ stateObservables,
2724
+ dependencies
2725
+ }), accountCallStarts({
2726
+ config: revokeGrantCall,
2727
+ trigger$: revokeGrant$,
2728
+ stateObservables,
2729
+ dependencies
2730
+ }), accountCallStarts({
2731
+ config: revokeAllGrantsCall,
2732
+ trigger$: revokeAllGrants$,
2733
+ stateObservables,
2734
+ dependencies
2735
+ }), accountCallStarts({
2736
+ config: readShieldedHoldingsCall,
2737
+ trigger$: readShieldedHoldings$,
2738
+ stateObservables,
2739
+ dependencies
2740
+ }), accountCallStarts({
2741
+ config: installOperationsCall,
2742
+ trigger$: installOperations$,
2743
+ stateObservables,
2744
+ dependencies
2745
+ })).pipe(exhaustMap((start) => concat(of(dependencies.actions.passport.setFlow("ceremony")), start())));
2746
+ //#endregion
2747
+ //#region ../../packages/module/passport-account/src/store/side-effects/restore-account.ts
2748
+ /** Whether a stored record names an activated account rather than a deployment in progress. */
2749
+ const isActivatedRecord = (record) => record !== void 0 && record.deployment === void 0;
2750
+ /**
2751
+ * The grant roster of the restored account, read from chain with the
2752
+ * slots the record kept. The read needs no ceremony, but it does need
2753
+ * the indexer: a contract it does not serve, or a read it fails, leaves
2754
+ * the roster empty rather than failing the restore, and the next sign-in
2755
+ * or grant call reads it again.
2756
+ */
2757
+ const restoreGrants = (record, { indexerUrl, indexerWsUrl }, actions) => defer(async () => createIndexerClient({
2758
+ indexerUrl,
2759
+ indexerWsUrl
2760
+ }).queryContractState(record.address)).pipe(filter((state) => state !== null && state !== void 0), map((state) => actions.passport.setGrants(readGrants(ledger(state.data), storedGrantSlots(record.grants)))), catchError(() => EMPTY));
2761
+ /**
2762
+ * Rehydrates the persisted account record into the store on startup, so a
2763
+ * returning user's account is recognised without a new passkey ceremony.
2764
+ * Only a record whose activation succeeded is restored, hence status
2765
+ * 'ready'; a record still carrying a pending deployment names no usable
2766
+ * account and is left for the create flow to resume, or for sign-in to
2767
+ * complete once the chain shows it activated. The device set is not
2768
+ * persisted and is rebuilt from chain by the device-management flows; the
2769
+ * grant roster is read from chain here, once the account is published,
2770
+ * so a consumer lists grants without a ceremony. A record sealed by a
2771
+ * passkey authoriser cannot be opened without a ceremony, and a ceremony
2772
+ * cannot run without a user gesture, so no storage key is passed here: a
2773
+ * sealed record reads as absent and the sign-in flow recognises the
2774
+ * account instead.
2775
+ */
2776
+ const restorePassportAccount = (_actionObservables, _stateObservables, { actions, createKeyValueStorage, passportNetwork }) => createAccountRecordStore(createKeyValueStorage).read().pipe(filter(isActivatedRecord), mergeMap((record) => concat(of(actions.passport.setAccount({
2777
+ address: record.address,
2778
+ bindingVersion: record.bindingVersion,
2779
+ status: "ready",
2780
+ networkId: passportNetwork.networkId
2781
+ }), actions.passport.setLocalUseCounter(record.localUseCounter)), restoreGrants(record, passportNetwork, actions))));
2782
+ //#endregion
2783
+ //#region ../../packages/module/passport-account/src/store/init.ts
2784
+ /**
2785
+ * Builds the passport-account module's store initializer for the given
2786
+ * platform capabilities: the mutually exclusive passport flows behind the
2787
+ * createAccount, signIn, addDevice, removeDevice, issueGrant, revokeGrant
2788
+ * and revokeAllGrants actions, and the restore of a previously created
2789
+ * account from its persisted record.
2790
+ */
2791
+ const createInit = (props) => () => ({
2792
+ sideEffects: [runPassportFlow, restorePassportAccount],
2793
+ sideEffectDependencies: createDependencies(props)
2794
+ });
2795
+ //#endregion
2796
+ export { createInit };