@laceio/sdk 0.1.0 → 0.1.1-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 (411) hide show
  1. package/README.md +1 -1
  2. package/dist/{Ed25519PublicKey-lvu1s54U.cjs → Address-AMKTo-dA.cjs} +17150 -61
  3. package/dist/{Ed25519PublicKey-CjnuAYRR.js → Address-_c_-9hLC.js} +16955 -264
  4. package/dist/{Bip32Account-r3KAhCgU.js → Bip32Account-CaW1zC9Y.js} +4 -5
  5. package/dist/{Bip32Account-Cz3h0ZUa.cjs → Bip32Account-DOaGmKpv.cjs} +4 -5
  6. package/dist/Cardano-B-gyqBBD.js +311 -0
  7. package/dist/Cardano-BQ_af0Y3.cjs +322 -0
  8. package/dist/Ed25519PublicKey-B3QcR0J2.cjs +88 -0
  9. package/dist/Ed25519PublicKey-DIE19xHg.js +83 -0
  10. package/dist/InMemoryKeyAgent-Bc_xZY-v.cjs +652 -0
  11. package/dist/InMemoryKeyAgent-D8T3vtXy.js +631 -0
  12. package/dist/{PaymentAddress-DhbtuYb7.cjs → PaymentAddress-B4n1KZMx.cjs} +1 -2
  13. package/dist/{PaymentAddress-xSmGUQ-8.js → PaymentAddress-Cml3EA1n.js} +1 -2
  14. package/dist/Percent-Cfuw5YyL.cjs +11 -0
  15. package/dist/Percent-DpvyJ_93.js +5 -0
  16. package/dist/SodiumBip32Ed25519-BaD-kjyx.cjs +380 -0
  17. package/dist/SodiumBip32Ed25519-DCikAMsl.js +363 -0
  18. package/dist/{TransactionBuilder-CeJTNzm-.cjs → TransactionBuilder-BakTJvsJ.cjs} +59 -89
  19. package/dist/{TransactionBuilder-DGNDM4kt.js → TransactionBuilder-D2ErwVWv.js} +5 -71
  20. package/dist/_md-6zV2Cme0.cjs +684 -0
  21. package/dist/_md-gbUqlhqd.js +399 -0
  22. package/dist/_web-crypto-random-bytes-BvzwTYPG.js +197 -0
  23. package/dist/acc-module-NL_8mEHH.cjs +27654 -0
  24. package/dist/acc-module-ur8CkBd1.js +27624 -0
  25. package/dist/account-call-BDdWqMAY.js +267 -0
  26. package/dist/account-call-BExOpZoo.js +3 -0
  27. package/dist/account-call-CYYoAS1E.cjs +314 -0
  28. package/dist/account-call-Cvj7viaq.cjs +4 -0
  29. package/dist/account-guards-BeKbV9D1.cjs +41 -0
  30. package/dist/account-guards-qnFXuXSE.js +36 -0
  31. package/dist/{activity-type.stable-ClO9j_PH.cjs → activity-type-BPXxdHBP.cjs} +2 -1
  32. package/dist/{activity-type.stable-Ml0SOYv9.js → activity-type-C1geyPsH.js} +2 -1
  33. package/dist/address-OxwXIwbF.js +15502 -0
  34. package/dist/address-book-address-validator-BqYM0Uyp.cjs +41 -0
  35. package/dist/{address-book-address-validator-BhqRfmlL.cjs → address-book-address-validator-CGIcqn5W.cjs} +5 -4
  36. package/dist/{address-book-address-validator-VqIOB8PY.js → address-book-address-validator-FkkYim3z.js} +6 -4
  37. package/dist/address-book-address-validator-RSx2Jozy.js +39 -0
  38. package/dist/address-lECYBd9-.cjs +13043 -0
  39. package/dist/{apply-vkey-witnesses-Ctzk7eye.cjs → apply-vkey-witnesses-1jyczTkw.cjs} +1 -1
  40. package/dist/{apply-vkey-witnesses-Dfo7XfhL.js → apply-vkey-witnesses-Byb40-yJ.js} +1 -1
  41. package/dist/artefact-loader-De9WJH1J.cjs +183 -0
  42. package/dist/artefact-loader-nlsYFjxU.js +160 -0
  43. package/dist/auto-dismiss-failure-on-success-BWJceNXd.cjs +37 -0
  44. package/dist/auto-dismiss-failure-on-success-Bpod-v4r.js +31 -0
  45. package/dist/bip32-EPpcFrpH.cjs +3851 -0
  46. package/dist/{bip32ed25519-D2In8WzR.cjs → bip32ed25519-CRiG-Kjg.cjs} +5 -4
  47. package/dist/{bip32ed25519-qsLH_eWO.js → bip32ed25519-E-fCUZNv.js} +6 -4
  48. package/dist/bip39-DZomfqeY.js +9 -0
  49. package/dist/bip39-MAck9iod.cjs +26 -0
  50. package/dist/bitcoin-data-provider-D0OT_Uiu.cjs +26 -0
  51. package/dist/bitcoin-data-provider-LN_8oamW.js +21 -0
  52. package/dist/bitcoin.cjs +48 -0
  53. package/dist/bitcoin.d.ts +29805 -1
  54. package/dist/bitcoin.js +22 -0
  55. package/dist/{blake2b-BGHUWMsV.js → blake2b-BL-eR5G2.js} +6 -4
  56. package/dist/{blake2b-DspUqw68.cjs → blake2b-Iy324FwH.cjs} +5 -4
  57. package/dist/{blockfrost-tx-submit-provider-BUEOmdvc.js → blockfrost-tx-submit-provider-BHDLgOIE.js} +9 -162
  58. package/dist/{blockfrost-tx-submit-provider-B5dWbdrZ.cjs → blockfrost-tx-submit-provider-BxC19smv.cjs} +7 -171
  59. package/dist/{blockingWithLatestFrom-BhaE7pnA.js → blockingWithLatestFrom-FUfZFEUG.js} +1 -1
  60. package/dist/{blockingWithLatestFrom-DkuT3G2a.cjs → blockingWithLatestFrom-bmCPgA3c.cjs} +1 -1
  61. package/dist/bn-BFq5a4dk.cjs +2553 -0
  62. package/dist/{SodiumBip32Ed25519-BEfo1Q9m.js → browser-D5jRKv_L.js} +4 -401
  63. package/dist/bytes.vo-CziaOsba.js +24 -0
  64. package/dist/bytes.vo-hecRu3YZ.cjs +35 -0
  65. package/dist/{cardano-network-id-to-network-type-PXvn1ycQ.cjs → cardano-network-id-to-network-type-BwG_d6QP.cjs} +1 -1
  66. package/dist/{cardano-network-id-to-network-type-DHgKhDAK.js → cardano-network-id-to-network-type-CYJheetp.js} +1 -1
  67. package/dist/{cardano-network-id.vo-CbNNKd-k.cjs → cardano-network-id.vo-C5VuBXT3.cjs} +2 -2
  68. package/dist/{cardano-network-id.vo-CTYe-Oix.js → cardano-network-id.vo-CeLJqmb_.js} +2 -2
  69. package/dist/{cardano-tx-id.vo-BMwemq5x.js → cardano-tx-id.vo-DJ70NC0-.js} +1 -1
  70. package/dist/{cardano-tx-id.vo-NY-gCOWJ.cjs → cardano-tx-id.vo-lnyO9XaW.cjs} +1 -1
  71. package/dist/cardano.cjs +31 -24
  72. package/dist/cardano.d.ts +27612 -8128
  73. package/dist/cardano.js +21 -13
  74. package/dist/client-Bw2foG5E.cjs +808 -0
  75. package/dist/const-BB3MccLt.js +153 -0
  76. package/dist/{const-BErUlcZw.cjs → const-BWBAzOmN.cjs} +1 -1
  77. package/dist/const-CSWmOyzn.cjs +42 -0
  78. package/dist/{const-Dy8Ctnpd.cjs → const-D3mCkwrM.cjs} +5 -5
  79. package/dist/const-DW7z3R5k.js +13 -0
  80. package/dist/{const-DeUA7zYl.js → const-DbuUHSzR.js} +5 -5
  81. package/dist/const-DgBzKfz6.cjs +31995 -0
  82. package/dist/{const-DVW6DGkZ.js → const-xGSNCtwQ.js} +1 -1
  83. package/dist/contract-2KVxlHyu.cjs +189 -0
  84. package/dist/contract-DjQqqZLo.js +171 -0
  85. package/dist/create-add-accounts-2mQA0ST2.js +102 -0
  86. package/dist/create-add-accounts-B6mR2NMn.cjs +114 -0
  87. package/dist/{delegation-tx-builder-CF0VunDW.cjs → delegation-tx-builder-Cp30jtj9.cjs} +9 -8
  88. package/dist/{delegation-tx-builder-C8LQxU2R.js → delegation-tx-builder-DUMikSTg.js} +9 -7
  89. package/dist/{deregistration-tx-builder-DcUXA3Ls.cjs → deregistration-tx-builder-B-ZeY-dR.cjs} +10 -9
  90. package/dist/{deregistration-tx-builder-BOBPP8m_.js → deregistration-tx-builder-CRLrK99U.js} +10 -8
  91. package/dist/device-commitment-hex.vo-BIUYUNz1.cjs +31 -0
  92. package/dist/device-commitment-hex.vo-D9FsYLn7.js +26 -0
  93. package/dist/device-key-BToCoS4D.js +2394 -0
  94. package/dist/device-key-D6euvxFi.cjs +2489 -0
  95. package/dist/device-readers-BPDz2oqa.js +3 -0
  96. package/dist/device-readers-CVqmvmLZ.js +145 -0
  97. package/dist/device-readers-DzkDMjPn.cjs +7 -0
  98. package/dist/device-readers-XMZMfFvZ.cjs +168 -0
  99. package/dist/dist-B00GN41m.js +141 -0
  100. package/dist/dist-BA1xnF9O.cjs +4413 -0
  101. package/dist/dist-BmHOXLe8.cjs +3814 -0
  102. package/dist/dist-Br0OVXKt.cjs +535 -0
  103. package/dist/dist-C1JK9C1I.cjs +3452 -0
  104. package/dist/dist-DKEViNEI.cjs +1306 -0
  105. package/dist/dist-Dwqx184a.cjs +43175 -0
  106. package/dist/dist-MJof_Ky1.cjs +145 -0
  107. package/dist/dist-p84sVVJ9.cjs +1394 -0
  108. package/dist/{earn-rewards-tx-builder-BRlTueHS.js → earn-rewards-tx-builder-8G_rouIk.js} +9 -7
  109. package/dist/{earn-rewards-tx-builder-RgO0QUY8.cjs → earn-rewards-tx-builder-cOUNV58E.cjs} +9 -8
  110. package/dist/enc-key-circuits-0Dud78IB.js +13 -0
  111. package/dist/enc-key-circuits-yjPHbuo_.cjs +24 -0
  112. package/dist/english-BZ_ebp2-.cjs +2057 -0
  113. package/dist/envelopes-BmL7onAK.cjs +1721 -0
  114. package/dist/envelopes-CfWTR2uy.js +1620 -0
  115. package/dist/errors-BA3b8aVu.cjs +584 -0
  116. package/dist/errors-pkQdxW-7.js +392 -0
  117. package/dist/experimental.cjs +6875 -0
  118. package/dist/experimental.d.ts +63670 -0
  119. package/dist/experimental.js +6725 -0
  120. package/dist/fees-6C2uEWFK.js +653 -0
  121. package/dist/fees-DtC71fOx.cjs +820 -0
  122. package/dist/gated-call-DLC5PBlN.cjs +736 -0
  123. package/dist/gated-call-DQhT7v2J.js +695 -0
  124. package/dist/gated-call-DdNOQh_Z.js +3 -0
  125. package/dist/gated-call-wAB15GtN.cjs +4 -0
  126. package/dist/grant-circuits-BKJrMSNo.cjs +49 -0
  127. package/dist/grant-circuits-D53wmGyr.js +26 -0
  128. package/dist/grant-rules-fYt80KB1.cjs +7114 -0
  129. package/dist/grant-rules-rG1kJq6l.js +6833 -0
  130. package/dist/grant-status-CDmZpx32.js +296 -0
  131. package/dist/grant-status-CQtwjLsA.cjs +337 -0
  132. package/dist/grants-C5wpNvZJ.cjs +266 -0
  133. package/dist/grants-DY3sN9We.cjs +16 -0
  134. package/dist/grants-ngFtS52g.js +213 -0
  135. package/dist/grants-qpXC94Rk.js +4 -0
  136. package/dist/{group-cardano-addresses-by-account-C-1GHUu8.cjs → group-cardano-addresses-by-account-BGOtPV-Y.cjs} +4 -40
  137. package/dist/{group-cardano-addresses-by-account-p4dXmCoj.js → group-cardano-addresses-by-account-TqvESg9x.js} +6 -37
  138. package/dist/{guarded-transaction-signer-DZSGHp1K.js → guarded-transaction-signer-BbVDE9Nn.js} +12 -18
  139. package/dist/{guarded-transaction-signer-BLSezbfV.cjs → guarded-transaction-signer-DTLjAkif.cjs} +26 -26
  140. package/dist/hex-BVtOKJki.cjs +263 -0
  141. package/dist/hex-CGYJPK_Z.js +192 -0
  142. package/dist/http-client-B7_kBTYn.js +155 -0
  143. package/dist/http-client-DYQ_7Rdf.cjs +167 -0
  144. package/dist/identity-DxPhxkZs.js +239 -0
  145. package/dist/identity-y41Yle03.cjs +274 -0
  146. package/dist/in-memory-wallet-integration-5BKiAvPT.js +20861 -0
  147. package/dist/{in-memory-wallet-integration-CUTa68ET.js → in-memory-wallet-integration-BCOqDgbt.js} +10 -107
  148. package/dist/in-memory-wallet-integration-Bi8I9Dso.js +128 -0
  149. package/dist/in-memory-wallet-integration-Bsl2ONua.cjs +239 -0
  150. package/dist/in-memory-wallet-integration-DZ0CAyvY.cjs +20865 -0
  151. package/dist/{in-memory-wallet-integration-Dw_S7amX.cjs → in-memory-wallet-integration-DsFm8gLk.cjs} +21 -112
  152. package/dist/{in-memory-wallet-integration-Z4Bp_DTv.cjs → in-memory-wallet-integration-aW_SF-go.cjs} +8 -5
  153. package/dist/{in-memory-wallet-integration-B6cbAlvD.js → in-memory-wallet-integration-mIEc8EfR.js} +9 -5
  154. package/dist/index.cjs +95 -58
  155. package/dist/index.d.ts +45146 -13439
  156. package/dist/index.js +55 -28
  157. package/dist/{init-CVi8J0zk.cjs → init-5SfWgCYD.cjs} +3 -3
  158. package/dist/{init-Ci7aqWCf2.cjs → init-8NVWbo302.cjs} +2 -2
  159. package/dist/init-B-C7n6u6.js +5 -0
  160. package/dist/{init-BFMWRf-L.js → init-B-ppfGO-.js} +1 -1
  161. package/dist/{init-IiR093Jw.cjs → init-B2OUhY5T.cjs} +2 -2
  162. package/dist/{init-DXnus199.cjs → init-B6Eg_o6G.cjs} +5 -5
  163. package/dist/{init-4hDl5bpr.js → init-BAWMHL1k.js} +2 -2
  164. package/dist/init-BC2CZZOu2.cjs +2002 -0
  165. package/dist/{init-a228hXnS.cjs → init-BF-a2p6E.cjs} +65 -73
  166. package/dist/{init-fFirX8OY.cjs → init-BFxlQAD8.cjs} +1 -1
  167. package/dist/init-BJE1ry0O.js +17 -0
  168. package/dist/{init-BVnI4z2J.js → init-BPKBVOHU.js} +2 -2
  169. package/dist/{init-bdqZBd-o.js → init-BSP_xcpB.js} +2 -2
  170. package/dist/{init-CFNOn3lo.js → init-BSd7mznK.js} +3 -3
  171. package/dist/{init-MjR4swi6.js → init-BUJTT0MN.js} +36 -43
  172. package/dist/init-BUpFzYsD.cjs +143 -0
  173. package/dist/{init-BvpYHyLH.cjs → init-BZ-WyAIL.cjs} +3 -3
  174. package/dist/init-BZdfdLX7.js +422 -0
  175. package/dist/{init-CJeOys1w.cjs → init-B_HWNXMD.cjs} +2 -2
  176. package/dist/init-BbIMt6xU.cjs +6 -0
  177. package/dist/{init-BYdN1aqE.cjs → init-BewG6swt.cjs} +2 -2
  178. package/dist/{init-Tpn9VkFu.cjs → init-BpwlQ6wF.cjs} +1 -1
  179. package/dist/{init-D5-P0HXK.js → init-BtQOzUjX.js} +1 -1
  180. package/dist/{init-BvGz3qUd2.js → init-CCTscPaY2.js} +2 -2
  181. package/dist/{init-D4hPipCD.cjs → init-CH0yyBof.cjs} +1 -1
  182. package/dist/{init-BX0AZAVH2.js → init-CS98M3iD.js} +2 -2
  183. package/dist/init-CaIkrXal.cjs +121 -0
  184. package/dist/init-CkZy4IMf.cjs +107 -0
  185. package/dist/{init-Drr2f_Pr.js → init-CmfcY7SV.js} +1 -1
  186. package/dist/{init-Kf3_OLv6.js → init-CnJAlks_.js} +1 -1
  187. package/dist/{init-Cdjt_z-b.cjs → init-CqqmtAIK.cjs} +4 -4
  188. package/dist/{init-Bb0avZeZ.js → init-Cu2znmIc.js} +5 -5
  189. package/dist/{init-lcaUSOOG.js → init-CwLZXfTl.js} +1 -1
  190. package/dist/init-Cz5LAizN.js +2001 -0
  191. package/dist/init-D4WM3-Mn.cjs +18 -0
  192. package/dist/init-DJzEpODO.js +2373 -0
  193. package/dist/init-DMi2FGpf.cjs +424 -0
  194. package/dist/{init-BTYLMF9F2.cjs → init-DexLSprL2.cjs} +258 -61
  195. package/dist/init-DfKPgD21.js +106 -0
  196. package/dist/init-DgzRsI-C.js +141 -0
  197. package/dist/init-Dj4Cn7-P.js +4789 -0
  198. package/dist/{init-DFwhgert.cjs → init-DnELgrhn.cjs} +1 -1
  199. package/dist/init-DypZuehC.cjs +2374 -0
  200. package/dist/{init-CX_zLXc6.js → init-IBnizp1U.js} +5 -5
  201. package/dist/init-MDKB6tGI2.cjs +4790 -0
  202. package/dist/{init-DbZ5byj42.js → init-TbB38KNt2.js} +258 -60
  203. package/dist/{init-BgrY29gW.js → init-dsYkC_0B.js} +4 -4
  204. package/dist/{init-DvVgKCaP2.cjs → init-kVOOiU0-.cjs} +2 -2
  205. package/dist/{init-B5BsI3DR.cjs → init-kvn5FlPS.cjs} +7 -7
  206. package/dist/init-vfy9DW_E.js +119 -0
  207. package/dist/{init-BE_6Jyc4.js → init-w7xl6LsP.js} +3 -3
  208. package/dist/{init-DEsWVyn5.cjs → init-wgiBUmyW.cjs} +1 -1
  209. package/dist/{is-retriable-error-DWv_ob-f.js → is-retriable-error-CmFR20pe.js} +1 -1
  210. package/dist/{is-retriable-error-Dtb4JGjd.cjs → is-retriable-error-D2yo0_lS.cjs} +1 -1
  211. package/dist/jubjub-authoriser-BBJcD2uC.js +85 -0
  212. package/dist/jubjub-authoriser-BlXt4Z-D.cjs +86 -0
  213. package/dist/key-source-CcLTx8HK.js +2761 -0
  214. package/dist/key-source-D2tTAag-.cjs +806 -0
  215. package/dist/{key-value-store-DTX1quRS.js → key-value-store-DZcNDB3n.js} +1 -1
  216. package/dist/{key-value-store-B-XRIwaM.cjs → key-value-store-Htj4RgMe.cjs} +1 -1
  217. package/dist/keyDerivation-DcKRUCVh.cjs +274 -0
  218. package/dist/keyDerivation-QGesIMbS.js +4077 -0
  219. package/dist/{lace-context-FpU3iG3f.cjs → lace-context-BN0b_ury.cjs} +4 -4
  220. package/dist/{lace-context-BQvvxVLm.js → lace-context-DMRJ87Vg.js} +4 -4
  221. package/dist/lib-BC-62Byh.cjs +2359 -0
  222. package/dist/lib-JYqcAX0c.js +2354 -0
  223. package/dist/midnight-account-id.vo--Vcx34Xk.cjs +10 -0
  224. package/dist/midnight-account-id.vo-BuB8fiVO.js +5 -0
  225. package/dist/midnight-engine-B7D2hbHo.js +5 -0
  226. package/dist/midnight-engine-D5ikN_5F.cjs +6 -0
  227. package/dist/midnight-wallet-BOdFD6SX.cjs +24 -0
  228. package/dist/midnight-wallet-CAqZrNVe.js +18 -0
  229. package/dist/midnight.cjs +1412 -0
  230. package/dist/midnight.d.ts +28609 -0
  231. package/dist/midnight.js +1355 -0
  232. package/dist/modules-cardano-4IgYsKeN.js +999 -0
  233. package/dist/modules-cardano-Baqj2GZH.cjs +1112 -0
  234. package/dist/node-relay-BEtqi_vU.cjs +49 -0
  235. package/dist/node-relay-CkgpDObu.js +48 -0
  236. package/dist/outputs-5qdW8s-f.js +196 -0
  237. package/dist/outputs-BEM1GPMf.cjs +339 -0
  238. package/dist/{SodiumBip32Ed25519-BQUcrQWX.cjs → pbkdf2-B1veireP.cjs} +6 -411
  239. package/dist/pending-operation-CfTUNQVD.cjs +26 -0
  240. package/dist/pending-operation-Ljijb1Uh.js +21 -0
  241. package/dist/providers--Hg9iF5v.cjs +366 -0
  242. package/dist/providers-DQ5_3h2l.js +343 -0
  243. package/dist/redacted-4SJPqt-G.js +81 -0
  244. package/dist/redacted-DwxIDdIF.cjs +86 -0
  245. package/dist/{reselect-DPML1uFN.cjs → reselect-kP4DaAII.cjs} +1 -1
  246. package/dist/{retry-config-oNtfdyrG.cjs → retry-config-BGv5q5QM.cjs} +1 -1
  247. package/dist/{retry-config-VdbuqBsI.js → retry-config-Bu5Yn5ua.js} +1 -1
  248. package/dist/safe-buffer-CqGpSFCQ.js +43 -0
  249. package/dist/safe-buffer-DbXbwhUQ.cjs +48 -0
  250. package/dist/sdk-Bm9-P0L-.cjs +1445 -0
  251. package/dist/sdk-Cf__6dDe.js +1249 -0
  252. package/dist/sdk-init-9TG1ZvHF.cjs +3795 -0
  253. package/dist/sdk-init-Ce3mD-8F.js +1047 -0
  254. package/dist/secret-box-CSmRp6Tt.js +3777 -0
  255. package/dist/secret-box-ZfbYwBgS.cjs +6970 -0
  256. package/dist/send-proof-progress-DtAcrMP6.cjs +33 -0
  257. package/dist/send-proof-progress-Dx2cUz1B.js +22 -0
  258. package/dist/sha2-DaRJZOjk.cjs +390 -0
  259. package/dist/sha2-c4sB6peD.js +378 -0
  260. package/dist/side-effects-C3BhLrdP.js +768 -0
  261. package/dist/side-effects-DG0R-KFc.cjs +804 -0
  262. package/dist/sign-bitcoin-transaction-with-seed-C7vq9om8.js +147 -0
  263. package/dist/sign-bitcoin-transaction-with-seed-Ds1dwzan.cjs +158 -0
  264. package/dist/signer--2I6poMD.js +2 -0
  265. package/dist/signer-CX21Ups_.cjs +121 -0
  266. package/dist/signer-Cnn9q9oY.js +92 -0
  267. package/dist/signer-DbSxjk0F.cjs +7 -0
  268. package/dist/signer-factory-B5oFuUZ-.cjs +130 -0
  269. package/dist/signer-factory-BAt8FPNc.cjs +281 -0
  270. package/dist/signer-factory-BGE4nL4k.js +129 -0
  271. package/dist/signer-factory-C4pgsiJi.js +281 -0
  272. package/dist/{signer-factory-DySc1wRX.cjs → signer-factory-D95jQIPV.cjs} +9 -6
  273. package/dist/{signer-factory-D4HrwFPl.js → signer-factory-PrpsGX-8.js} +10 -6
  274. package/dist/{slice-BZTQgYSs.js → slice-B-xJcuT1.js} +4 -4
  275. package/dist/slice-B4QOYaOG.cjs +105 -0
  276. package/dist/{slice-CtIMw2YT.cjs → slice-B9QKuhi0.cjs} +3 -3
  277. package/dist/{slice-Bhwmqn1p.cjs → slice-Bf4enJKZ.cjs} +8 -8
  278. package/dist/{slice-DaNVz7_l.js → slice-ByNWnxKS.js} +8 -8
  279. package/dist/{slice-C2UDQrdt.js → slice-C1zOeseG.js} +449 -355
  280. package/dist/{slice-DFLyKRm5.cjs → slice-C4toRM6A.cjs} +2 -2
  281. package/dist/{slice-Cx4dULDA.cjs → slice-C8YVv4Qn.cjs} +1 -1
  282. package/dist/{slice-jnpOgiSZ.cjs → slice-CaMfviYu.cjs} +3 -3
  283. package/dist/{slice-DFvrwUur.js → slice-CgeRsYRg.js} +6 -6
  284. package/dist/{slice-zNEspZND.js → slice-D0VzpMbY.js} +2 -2
  285. package/dist/slice-D14F78Ca.js +87 -0
  286. package/dist/slice-DJelVt0i.js +9013 -0
  287. package/dist/{slice-F6A1YKOF.cjs → slice-DLflttAu.cjs} +479 -366
  288. package/dist/{slice-C96EdeY1.js → slice-DcO-iNz2.js} +1 -1
  289. package/dist/{slice-C19quNWM.cjs → slice-DimtxfAT.cjs} +2 -2
  290. package/dist/{slice-KiNoGwD9.js → slice-DlTEqIoI.js} +1 -1
  291. package/dist/{slice-ws8PccRX.js → slice-Dn0WojD7.js} +3 -3
  292. package/dist/{slice-BLSxLmie.cjs → slice-Dongunf7.cjs} +4 -4
  293. package/dist/{slice-B6vPum19.js → slice-DpufJAjJ.js} +2 -2
  294. package/dist/{slice-exhhmucR.cjs → slice-DtitVc9L.cjs} +7 -7
  295. package/dist/slice-RQRLciQc.cjs +9031 -0
  296. package/dist/{slice-Bjj2t2ut.cjs → slice-WMMMc1Xv.cjs} +2 -2
  297. package/dist/slice-a8VuIqzS.cjs +378 -0
  298. package/dist/slice-bRASyM-m.js +354 -0
  299. package/dist/{slice-CBFrgHSH.js → slice-hNyKbDry.js} +3 -3
  300. package/dist/{InMemoryKeyAgent-pyB2gA-N.cjs → src-BayYMIjw.cjs} +20 -8228
  301. package/dist/{InMemoryKeyAgent-D-3HejxN.js → src-CgINPlSx.js} +29 -4811
  302. package/dist/store-AUlTfcI_.js +37 -0
  303. package/dist/store-C7AneHEY.cjs +66 -0
  304. package/dist/submit-BuBCVi-l.cjs +87 -0
  305. package/dist/submit-D37lxFrK.js +70 -0
  306. package/dist/submit-bitcoin-tx-CE0AD-xH.js +983 -0
  307. package/dist/submit-bitcoin-tx-CK10OTfQ.cjs +1049 -0
  308. package/dist/{subtractValueQuantities-DfZg6oiG.js → subtractValueQuantities-BuDJVxq6.js} +3 -22
  309. package/dist/{subtractValueQuantities-C8qDTtgH.cjs → subtractValueQuantities-CqR606HV.cjs} +2 -32
  310. package/dist/{sync-operation-utils-BrQyWFS_.cjs → sync-operation-utils--Z_IQfyW.cjs} +0 -66
  311. package/dist/{sync-operation-utils-CAaCGvEN.js → sync-operation-utils-BimBpvI3.js} +1 -37
  312. package/dist/token-id-mapper-BVau2RXa.js +16 -0
  313. package/dist/token-id-mapper-CSeLzM4o.cjs +18 -0
  314. package/dist/{token-id-mapper-pDaTxpw2.js → token-id-mapper-ClBeIdJR.js} +2 -2
  315. package/dist/{token-id-mapper-DYcd8hhQ.cjs → token-id-mapper-D0wFdbOy.cjs} +2 -2
  316. package/dist/types-46lh8O9r.js +33 -0
  317. package/dist/types-BhhNR1_B.cjs +50 -0
  318. package/dist/types-BhzypKMS.cjs +15 -0
  319. package/dist/types-DTE1ctDB.js +10 -0
  320. package/dist/types-DXSxXGz0.js +12 -0
  321. package/dist/types-Dls6Z5gV.cjs +23 -0
  322. package/dist/{util-P4PX2muj.cjs → util-D1YlKzrc.cjs} +2 -2
  323. package/dist/{util-CQSJU0wT.js → util-DHxtzUzY.js} +2 -2
  324. package/dist/{utils-Bv4OHT4S.cjs → utils-DYf4iZKX.cjs} +7 -1
  325. package/dist/{utils-DrtzChYN.js → utils-DcnoETEP.js} +2 -2
  326. package/dist/utils-Du0YXRcU.cjs +112 -0
  327. package/dist/utils-fF_rnZe3.js +65 -0
  328. package/dist/v8Signatures-ClGpA8mS.cjs +71 -0
  329. package/dist/{vote-delegation-tx-builder-69gOEkCB.cjs → vote-delegation-tx-builder-BjZxCOd3.cjs} +9 -8
  330. package/dist/{vote-delegation-tx-builder-BRJ_pf-c.js → vote-delegation-tx-builder-DRJwPXkD.js} +9 -7
  331. package/dist/watch-FGE4B_Ge.js +13056 -0
  332. package/dist/watch-imlsRZDp.cjs +52207 -0
  333. package/package.json +95 -3
  334. package/dist/Address-4KjeDt_x.cjs +0 -17269
  335. package/dist/Address-_VPkf7Xh.js +0 -17101
  336. package/dist/account-guards.stable-BKyYPj4z.cjs +0 -10
  337. package/dist/account-guards.stable-BdmQ43vC.js +0 -5
  338. package/dist/init-BR9ZIbED.cjs +0 -378
  339. package/dist/init-B_k1RUN_.cjs +0 -21
  340. package/dist/init-Bs3b5ZQH.js +0 -378
  341. package/dist/init-ChfcrHgG2.cjs +0 -4354
  342. package/dist/init-D1uUMMpG.js +0 -19
  343. package/dist/init-DV1OSZiK.js +0 -4352
  344. package/dist/modules-cardano-BINzpXpk.js +0 -5454
  345. package/dist/modules-cardano-Dt8OwoQb.cjs +0 -5640
  346. package/dist/slice-Caf98m0d2.js +0 -107
  347. package/dist/slice-PM6llajQ2.cjs +0 -125
  348. /package/dist/{BigIntMath-CoJWXt1h.cjs → BigIntMath-CBciEQn2.cjs} +0 -0
  349. /package/dist/{BigIntMath-BWUJOsOW.js → BigIntMath-X3EniYDo.js} +0 -0
  350. /package/dist/{ChainId-sdLmlIRk.cjs → ChainId-CNPSU9nn.cjs} +0 -0
  351. /package/dist/{ChainId-CKbm87yQ.js → ChainId-CeoG8Sov.js} +0 -0
  352. /package/dist/{_polyfill-node.process-4fnlkbBi.cjs → _polyfill-node.process-5UxyjoHG.cjs} +0 -0
  353. /package/dist/{account-id.vo-Xpgnu-av.cjs → account-id.vo-DYZBZQsz.cjs} +0 -0
  354. /package/dist/{account-id.vo-DP0BtOoF.js → account-id.vo-KDTWJ-W5.js} +0 -0
  355. /package/dist/{actions-BNagEO6m.cjs → actions-BnHFVSr_.cjs} +0 -0
  356. /package/dist/{actions-BWTyAr7B.js → actions-Cwj0ApZf.js} +0 -0
  357. /package/dist/{asyncoption-po7-RiA5.cjs → asyncoption-CYcZNBRM.cjs} +0 -0
  358. /package/dist/{asyncoption-CzIVH5Y1.js → asyncoption-DZQGfznq.js} +0 -0
  359. /package/dist/{bignum.vo-DhhZ9HP1.js → bignum.vo-Co6tMH2q.js} +0 -0
  360. /package/dist/{bignum.vo-CpkrIXjH.cjs → bignum.vo-Du-bpvar.cjs} +0 -0
  361. /package/dist/{blockchain-network-id.vo-CbgrAY_K.js → blockchain-network-id.vo-C6Jowh8t.js} +0 -0
  362. /package/dist/{blockchain-network-id.vo-5iC6Kffo.cjs → blockchain-network-id.vo-DEQ14dYj.cjs} +0 -0
  363. /package/dist/{composite-signer-factory-DABpCe1_.js → composite-signer-factory-D9RWY-1V.js} +0 -0
  364. /package/dist/{composite-signer-factory-BizuNPP7.cjs → composite-signer-factory-v4Pxn8bA.cjs} +0 -0
  365. /package/dist/{error-ggOihIfv.cjs → error-B6wj9nPv.cjs} +0 -0
  366. /package/dist/{error-DHKO2iS4.js → error-CvEYL98P.js} +0 -0
  367. /package/dist/{esm-browser-DnXNvpcn.cjs → esm-browser-CZbMeVod.cjs} +0 -0
  368. /package/dist/{esm-browser-BBVQuyQv.js → esm-browser-DpAD_RKv.js} +0 -0
  369. /package/dist/{feature-flag-key.vo-DoGK5Bfh.js → feature-flag-key.vo-9reURsOQ.js} +0 -0
  370. /package/dist/{feature-flag-key.vo-CP1Z9s8e.cjs → feature-flag-key.vo-KTIdnzYX.cjs} +0 -0
  371. /package/dist/{first-state-of-status-Bx4-QQ5m.cjs → first-state-of-status-9ICeDNSa.cjs} +0 -0
  372. /package/dist/{first-state-of-status-D7XzEuSa.js → first-state-of-status-BscbKj_t.js} +0 -0
  373. /package/dist/{init-ZX90nEJe2.js → init-B0hAl9w6.js} +0 -0
  374. /package/dist/{init-4319psUJ.cjs → init-BT67pd9x.cjs} +0 -0
  375. /package/dist/{init-AFUM1TSg.js → init-CHk1fvJ2.js} +0 -0
  376. /package/dist/{init-Dt1Xifg_2.cjs → init-CSURGyW_.cjs} +0 -0
  377. /package/dist/{init-CTQ2g6Xt.js → init-DtxxFaCx.js} +0 -0
  378. /package/dist/{init-BNewLCqw.cjs → init-xzZPlQwB.cjs} +0 -0
  379. /package/dist/{is-redux-persist-state-DxJSsvxB.cjs → is-redux-persist-state-C5luvPEH.cjs} +0 -0
  380. /package/dist/{is-redux-persist-state-Bl2n4VMr.js → is-redux-persist-state-CjcqyCoh.js} +0 -0
  381. /package/dist/{isNotNil-CZxBMfL5.js → isNotNil-Be7gCY0m.js} +0 -0
  382. /package/dist/{isNotNil-C_SO1tcC.cjs → isNotNil-CrYIUFry.cjs} +0 -0
  383. /package/dist/{logging-BvMDKgl0.js → logging-BAMMfn5j.js} +0 -0
  384. /package/dist/{logging-Bh9ikph3.cjs → logging-CbxgIX9V.cjs} +0 -0
  385. /package/dist/{metadatum-B-sxBnSY.cjs → metadatum-BGvFqGPt.cjs} +0 -0
  386. /package/dist/{metadatum-Ego4jVas.js → metadatum-BVocMYy_.js} +0 -0
  387. /package/dist/{repo-slice-BzZQUTj8.cjs → repo-slice-BB_W-6OL.cjs} +0 -0
  388. /package/dist/{repo-slice-vCcQJotS.js → repo-slice-BQlssw9M.js} +0 -0
  389. /package/dist/{reselect-BPkMzw3k.js → reselect-JIgawvPe.js} +0 -0
  390. /package/dist/{serializable-BxFUShKY.js → serializable-F7OtYl8d.js} +0 -0
  391. /package/dist/{serializable-DWgkHhv_.cjs → serializable-n3UoxbZc.cjs} +0 -0
  392. /package/dist/{slice-DY-DNtSi.js → slice-5dGBAz6w.js} +0 -0
  393. /package/dist/{slice-BEFoeqgr.cjs → slice-BzJgg9FS.cjs} +0 -0
  394. /package/dist/{src-CPmX4KUh.cjs → src-CeBNkonz.cjs} +0 -0
  395. /package/dist/{src-XOZXPKxe.js → src-Cv1ifqbe.js} +0 -0
  396. /package/dist/{time-CQPt4FdU.js → time-ByoKevdZ.js} +0 -0
  397. /package/dist/{time-Blvoyh9G.cjs → time-qD7edGU0.cjs} +0 -0
  398. /package/dist/{time.vo-Xln4yGBU.js → time.vo-C17-tYq3.js} +0 -0
  399. /package/dist/{time.vo-rwWwJzmP.cjs → time.vo-TmYE-_Y2.cjs} +0 -0
  400. /package/dist/{toEmpty-CzmoZVLN.cjs → toEmpty-Db6V94Mf.cjs} +0 -0
  401. /package/dist/{toEmpty-DzLd-ZCi.js → toEmpty-Djj-QbpI.js} +0 -0
  402. /package/dist/{token-id.vo-l8fuSpem.cjs → token-id.vo-CZ622zcZ.cjs} +0 -0
  403. /package/dist/{token-id.vo-DMKSaMlc.js → token-id.vo-IDI9C_Qm.js} +0 -0
  404. /package/dist/{types-B61DQoFW.js → types-By-XeXWg.js} +0 -0
  405. /package/dist/{types-CUC-Kcqh.cjs → types-Cn6WlQV6.cjs} +0 -0
  406. /package/dist/{util-BV3iGOrz.cjs → util-Cp1h58uD.cjs} +0 -0
  407. /package/dist/{util-BsQKLorV.js → util-DHppXj7U.js} +0 -0
  408. /package/dist/{util-selector-CKIyoAOz.js → util-selector-BWmHpo92.js} +0 -0
  409. /package/dist/{util-selector-C9H5RsNw.cjs → util-selector-glXkO-jR.cjs} +0 -0
  410. /package/dist/{while-active-CNXeLxre.js → while-active-CDBnUlQA.js} +0 -0
  411. /package/dist/{while-active-BsDWSNrO.cjs → while-active-I2TlHtm7.cjs} +0 -0
@@ -0,0 +1,2373 @@
1
+ import "./_polyfill-buffer-patch-JcrfT1gU.js";
2
+ import { n as HexBytes, t as ByteArray } from "./bytes.vo-CziaOsba.js";
3
+ import { G as GrantScopeSalt, K as GrantId, U as validateGrantScope, W as GrantSlot, i as granteePoint, r as circuitScope } from "./grant-rules-rG1kJq6l.js";
4
+ import { i as AccAddress, t as createMidnightProviders } from "./providers-DQ5_3h2l.js";
5
+ import { a as resumeAccountDeployment, i as deployAccount, o as DeviceEpoch, r as resolveUseCounter, s as UseCounter } from "./gated-call-DQhT7v2J.js";
6
+ import { i as accManifest } from "./artefact-loader-nlsYFjxU.js";
7
+ import { n as TokenColor, t as storedGranteeScheme } from "./types-46lh8O9r.js";
8
+ import { A as RecordUnreadableError, C as GrantScopeInvalidError, E as NotAuthorisedError, O as ReadUnavailableError, S as GrantRosterUnsettledError, T as NoAccountError, _ as GrantNotFoundError, b as GrantRevocationPendingError, h as GrantIssueRejectedError, i as AccountNotFoundError, j as RemovalTargetNotFoundError, k as RecordCorruptedError, m as EncryptionKeyMismatchError, n as AccountCreationPendingError, p as DeviceRosterInvalidError, r as AccountExistsError, t as AccountContractMissingError, u as CreationLockMismatchError, w as LastDeviceError, x as GrantRevokedError, y as GrantOriginMissingError } from "./errors-pkQdxW-7.js";
9
+ import { a as isDeviceRegistration, i as isAddressedTo, n as deviceEnvelopes, o as isLaceRecord, r as encodeDevicePublicKey } from "./envelopes-CfWTR2uy.js";
10
+ import { n as ROTATE_ENC_KEY_CIRCUIT, t as APPEND_INBOX_CIRCUIT } from "./enc-key-circuits-0Dud78IB.js";
11
+ import { t as GRANTEE_WITHDRAWAL_CIRCUITS } from "./grant-circuits-D53wmGyr.js";
12
+ import { i as ledger } from "./acc-module-ur8CkBd1.js";
13
+ import { i as resolveLiveReaders, t as assertJoiningDevice } from "./device-readers-CVqmvmLZ.js";
14
+ import { a as prepareIssueGrant, i as originHash, n as grantObjectCommit, o as prepareRevokeAllGrants, s as prepareRevokeGrant, t as deriveGrantId } from "./grants-ngFtS52g.js";
15
+ 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-BDdWqMAY.js";
16
+ import { EMPTY, Observable, catchError, concat, concatMap, defaultIfEmpty, defer, exhaustMap, filter, firstValueFrom, map, merge, mergeMap, of, withLatestFrom } from "rxjs";
17
+ //#region ../../packages/module/passport-account/src/acc/device-circuits.ts
18
+ /**
19
+ * The gated circuits the device flows authorise, named once so the flow
20
+ * that submits a call and the signer that scopes a key session to it
21
+ * agree on the circuit.
22
+ */
23
+ const ADD_DEVICE_CIRCUIT = "add_device_with_jubjub";
24
+ const REMOVE_DEVICE_CIRCUIT = "remove_device_with_jubjub";
25
+ //#endregion
26
+ //#region ../../packages/module/passport-account/src/acc/pending-deployment.ts
27
+ /** Whether a record's pending creation carries the whole deployment, not only its marker. */
28
+ const isPendingDeployment = (pending) => "authorityKey" in pending;
29
+ /**
30
+ * The refusal of a creation that resumes an unfinished one under another
31
+ * lock choice than `recorded`, the one it was started with, which the
32
+ * message names so a retry can repeat it.
33
+ */
34
+ const lockChoiceMismatch = (recorded) => new CreationLockMismatchError(`The unfinished Passport account creation was started with lockAccount ${recorded}; resume it with the same lock choice.`);
35
+ //#endregion
36
+ //#region ../../packages/module/passport-account/src/store/envelope.ts
37
+ /** AES-GCM is specified for 96-bit IVs; each seal draws a fresh one. */
38
+ const IV_LENGTH = 12;
39
+ const utf8 = (value) => new TextEncoder().encode(value);
40
+ /** Whether a stored value has the sealed envelope layout. */
41
+ const isSealedRecord = (value) => {
42
+ if (typeof value !== "object" || value === null) return false;
43
+ const candidate = value;
44
+ return candidate.v === 1 && typeof candidate.iv === "string" && typeof candidate.ciphertext === "string";
45
+ };
46
+ /**
47
+ * Encrypts a record into a {@link SealedRecord} under the given key,
48
+ * marking the envelope pending when asked.
49
+ */
50
+ const sealRecord = async (key, record, { pending = false } = {}) => {
51
+ const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
52
+ const ciphertext = await crypto.subtle.encrypt({
53
+ name: "AES-GCM",
54
+ iv
55
+ }, key, utf8(JSON.stringify(record)));
56
+ return {
57
+ v: 1,
58
+ iv: HexBytes.fromByteArray(iv),
59
+ ciphertext: HexBytes.fromByteArray(new Uint8Array(ciphertext)),
60
+ ...pending ? { pending: true } : {}
61
+ };
62
+ };
63
+ /**
64
+ * Decrypts a {@link SealedRecord} back into the record it sealed. Any
65
+ * failure to open - a tampered ciphertext, a mismatched key, or a
66
+ * malformed envelope - throws RecordCorruptedError.
67
+ */
68
+ const openRecord = async (key, sealed) => {
69
+ try {
70
+ const plaintext = await crypto.subtle.decrypt({
71
+ name: "AES-GCM",
72
+ iv: ByteArray.fromHex(HexBytes(sealed.iv))
73
+ }, key, ByteArray.fromHex(HexBytes(sealed.ciphertext)));
74
+ return JSON.parse(new TextDecoder().decode(plaintext));
75
+ } catch {
76
+ throw new RecordCorruptedError();
77
+ }
78
+ };
79
+ //#endregion
80
+ //#region ../../packages/module/passport-account/src/store/account-record.ts
81
+ const COLLECTION_ID = "passport-account";
82
+ const ACCOUNT_RECORD_KEY = "account";
83
+ /**
84
+ * An {@link AccountRecordStore} over the platform key-value storage,
85
+ * namespaced under its own collection. With a `keyProvider` the record is
86
+ * sealed at rest and only sealed envelopes are readable. What a sealed
87
+ * record reads as without a `keyProvider` is the caller's choice:
88
+ * 'skip' (the default) reads it as undefined, for the ceremony-free
89
+ * restore peek that cannot open it by design; 'error' raises
90
+ * RecordUnreadableError, for the flows where a missing storage key is a
91
+ * persistence misconfiguration that must not look like an absent
92
+ * account. Without a `keyProvider` (the dev authoriser) the record
93
+ * persists in plaintext, which holds no secret once the account is
94
+ * complete; while a creation is unfinished it holds the contract's
95
+ * maintenance authority key (see {@link PassportAccountRecord}), so the
96
+ * dev authoriser is for development and tests only.
97
+ */
98
+ const createAccountRecordStore = (createKeyValueStorage, keyProvider, { onSealedWithoutKey = "skip" } = {}) => {
99
+ const storage = createKeyValueStorage({ collectionId: COLLECTION_ID });
100
+ const open = async (keyOf, value) => isSealedRecord(value) ? openRecord(await keyOf(), value) : void 0;
101
+ const stored = () => storage.getValues([ACCOUNT_RECORD_KEY]).pipe(map(([value]) => value), defaultIfEmpty(void 0));
102
+ const isPending = (record) => record.deployment !== void 0;
103
+ const presenceOf = (value) => {
104
+ if (value === void 0) return "absent";
105
+ return (isSealedRecord(value) ? value.pending === true : isPending(value)) ? "pending" : "complete";
106
+ };
107
+ return {
108
+ read: () => keyProvider ? stored().pipe(concatMap(async (value) => open(keyProvider, value))) : stored().pipe(map((value) => {
109
+ if (!isSealedRecord(value)) return value;
110
+ if (onSealedWithoutKey === "error") throw new RecordUnreadableError();
111
+ })),
112
+ 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),
113
+ presence: () => stored().pipe(map(presenceOf))
114
+ };
115
+ };
116
+ /**
117
+ * The promise view of an {@link AccountRecordStore}, for the flows. A
118
+ * storage that completes without emitting (destroyed mid-flow) reads as
119
+ * absent and writes as done, mirroring the stream contract so a flow
120
+ * never hangs on it.
121
+ */
122
+ const toAccountRecords = (store) => ({
123
+ read: async () => firstValueFrom(store.read(), { defaultValue: void 0 }),
124
+ write: async (record) => firstValueFrom(store.write(record), { defaultValue: void 0 }),
125
+ presence: async () => firstValueFrom(store.presence(), { defaultValue: "absent" })
126
+ });
127
+ //#endregion
128
+ //#region ../../packages/module/passport-account/src/acc/inbox-walk.ts
129
+ const defaultLoadLedger = async () => import("@midnightntwrk/ledger-v9");
130
+ /** The entries the contract holds, in inbox order, the Lace records included. */
131
+ const inboxEntries = (ledgerState) => {
132
+ const entries = [];
133
+ for (let ordinal = 0n; ordinal < ledgerState.inbox_count; ordinal += 1n) if (ledgerState.inbox.member(ordinal)) entries.push(ledgerState.inbox.lookup(ordinal));
134
+ return entries;
135
+ };
136
+ /**
137
+ * The commitment the chain carries for a coin the account received,
138
+ * recomputed with the ledger's own output construction: a contract-owned
139
+ * output of this coin towards the account address, which is exactly what
140
+ * a depositor builds and the contract claims. A description the ledger
141
+ * refuses to commit to is no candidate.
142
+ */
143
+ const toCandidate = ({ ZswapOutput }, address, { coin, entry }) => {
144
+ try {
145
+ return {
146
+ coin,
147
+ commitment: ZswapOutput.newContractOwned({
148
+ type: HexBytes.fromByteArray(coin.color),
149
+ nonce: HexBytes.fromByteArray(coin.nonce),
150
+ value: coin.value
151
+ }, void 0, address).commitment.toLowerCase(),
152
+ entry
153
+ };
154
+ } catch {
155
+ return null;
156
+ }
157
+ };
158
+ /**
159
+ * The tree index of every shielded output the chain created for the
160
+ * account, by commitment, read from the ledger events of the transactions
161
+ * that acted on the contract. A deposit is one such action, so its
162
+ * transaction is among them.
163
+ */
164
+ const receivedOutputs = async (address, indexer) => {
165
+ const actions = await indexer.enumerateContractActions(address);
166
+ const hashes = [...new Set(actions.map((action) => action.txHash))];
167
+ const outputs = await Promise.all(hashes.map(async (hash) => indexer.queryShieldedOutputs(hash)));
168
+ const recipient = address.toLowerCase();
169
+ return new Map(outputs.flat().filter((output) => output.contractAddress === recipient).map((output) => [output.commitment, output.index]));
170
+ };
171
+ /**
172
+ * Walks the account's inbox the way the custody standard prescribes:
173
+ * every entry other than the Lace records, which hold the account keys
174
+ * and the grant bookkeeping rather than coins, is opened with the
175
+ * encryption secrets, each coin that opens is verified by recomputing
176
+ * its commitment and finding it among the outputs the chain created for
177
+ * the account, and the index that output took in the commitment tree is
178
+ * captured with it. Anyone can append any
179
+ * bytes to the inbox, so an entry that does not open, or opens to a coin
180
+ * the chain never created for this account, is skipped as noise and
181
+ * counted, never raised. Two entries describing the same coin, as a
182
+ * re-encryption after a key rotation leaves behind, yield one holding,
183
+ * read from the first entry that described it. An empty inbox, or one
184
+ * with nothing that opens, is answered without loading the ledger or
185
+ * reading the chain's history. A ledger binding that fails to load is a
186
+ * failure of the walk itself, not of any entry, so it is raised rather
187
+ * than reported as an inbox of noise.
188
+ */
189
+ const walkInbox = async ({ address, ledgerState, indexer, openEntries, loadLedger = defaultLoadLedger }) => {
190
+ const entries = inboxEntries(ledgerState).filter((entry) => !isLaceRecord(entry));
191
+ const nothing = (skippedEntries) => ({
192
+ holdings: [],
193
+ holdingEntries: [],
194
+ skippedEntries
195
+ });
196
+ if (entries.length === 0) return nothing(0);
197
+ const coins = await openEntries(entries);
198
+ if (coins.every((coin) => coin === null)) return nothing(entries.length);
199
+ const ledger = await loadLedger();
200
+ const candidates = coins.map((coin, ordinal) => coin && toCandidate(ledger, address, {
201
+ coin,
202
+ entry: entries[ordinal]
203
+ }));
204
+ if (candidates.every((candidate) => candidate === null)) return nothing(entries.length);
205
+ const outputs = await receivedOutputs(address, indexer);
206
+ const holdings = /* @__PURE__ */ new Map();
207
+ const holdingEntries = /* @__PURE__ */ new Map();
208
+ let skippedEntries = 0;
209
+ for (const candidate of candidates) {
210
+ const index = candidate && outputs.get(candidate.commitment);
211
+ if (!candidate || index === void 0) {
212
+ skippedEntries += 1;
213
+ continue;
214
+ }
215
+ if (holdings.has(candidate.commitment)) continue;
216
+ holdings.set(candidate.commitment, {
217
+ color: TokenColor(HexBytes.fromByteArray(candidate.coin.color)),
218
+ value: candidate.coin.value.toString(),
219
+ commitment: candidate.commitment,
220
+ index: Number(index)
221
+ });
222
+ holdingEntries.set(candidate.commitment, candidate.entry);
223
+ }
224
+ return {
225
+ holdings: [...holdings.values()],
226
+ holdingEntries: [...holdingEntries.values()],
227
+ skippedEntries
228
+ };
229
+ };
230
+ //#endregion
231
+ //#region ../../packages/module/passport-account/src/flows/key-session.ts
232
+ /**
233
+ * Runs an operation under a single key ceremony, so a flow that reaches
234
+ * for the device key several times costs one user prompt instead of one
235
+ * per authoriser call. `flow` names the flow for an authoriser that
236
+ * presents it before the ceremony. An authoriser with no interactive
237
+ * ceremony exposes no session, and the operation runs directly. The
238
+ * session function is used detached, so implementations must not rely on
239
+ * `this`.
240
+ */
241
+ const inKeySession = async (authoriser, flow, operation) => {
242
+ const { withKeySession } = authoriser;
243
+ return withKeySession ? withKeySession(operation, flow) : operation();
244
+ };
245
+ //#endregion
246
+ //#region ../../packages/module/passport-account/src/acc/enc-key-rotation.ts
247
+ /** Prepares `rotate_enc_key_with_jubjub` over the raw 32-byte X25519 key `enc_key` is replaced with. */
248
+ const prepareRotateEncKey = (newKey) => ({
249
+ circuit: ROTATE_ENC_KEY_CIRCUIT,
250
+ args: [newKey]
251
+ });
252
+ /** Prepares `append_inbox_with_jubjub` over one inbox entry: a re-encrypted coin or a Lace record. */
253
+ const prepareAppendInbox = (entry) => ({
254
+ circuit: APPEND_INBOX_CIRCUIT,
255
+ args: [entry]
256
+ });
257
+ //#endregion
258
+ //#region ../../packages/module/passport-account/src/flows/rotation.ts
259
+ /**
260
+ * How long an accepted call is given to show in the indexer's view of the
261
+ * ledger, which can lag the block the call landed in.
262
+ */
263
+ const LEDGER_POLL_ATTEMPTS = 30;
264
+ const LEDGER_POLL_DELAY_MS = 1e3;
265
+ const sleep$1 = async (ms) => new Promise((resolve) => {
266
+ setTimeout(resolve, ms);
267
+ });
268
+ /**
269
+ * The encryption key's view members, which a rotation and a read grant's
270
+ * issue need: the re-encryption a rotation moves the holdings through
271
+ * and the sealing a grantee receives the secret by.
272
+ *
273
+ * @throws {@link ReadUnavailableError} when the key offers either not,
274
+ * as a key that only opens entries does.
275
+ */
276
+ const viewCapability = (encryptionKey) => {
277
+ const { reencryptInbox, sealView } = encryptionKey;
278
+ if (!reencryptInbox || !sealView) throw new ReadUnavailableError();
279
+ return {
280
+ reencryptInbox,
281
+ sealView
282
+ };
283
+ };
284
+ /** Resolves this device's reader and device keys, inside the caller's key session. */
285
+ const readLocalDevice = async ({ passportAuthoriser, passportEncryptionKey, passportNetwork }) => ({
286
+ readerPublicKey: await passportEncryptionKey.readerPublicKey(passportNetwork.networkId),
287
+ devicePublicKey: encodeDevicePublicKey(await passportAuthoriser.devicePublicKey())
288
+ });
289
+ /** Reads the inbox and this device's keyring of the account from its ledger. */
290
+ const readAccountInbox = (account, ledgerState, readerPublicKey) => {
291
+ const entries = inboxEntries(ledgerState);
292
+ return {
293
+ entries,
294
+ keyring: {
295
+ account: AccAddress(account),
296
+ encKey: ledgerState.enc_key,
297
+ envelopes: deviceEnvelopes(entries, readerPublicKey)
298
+ }
299
+ };
300
+ };
301
+ /**
302
+ * The device entries the ledger holds, as lowercase hex, less `except`:
303
+ * the devices a rotation may seal the new secret to, which a key session
304
+ * names to the user before it opens.
305
+ *
306
+ * @throws {@link DeviceRosterInvalidError} when there are more than
307
+ * {@link MAX_DEVICE_ENTRIES}, which no signer would accept.
308
+ */
309
+ const liveDeviceEntries = (ledgerState, except) => {
310
+ const entries = [...ledgerState.devices].map((entry) => HexBytes.fromByteArray(entry)).filter((entry) => entry !== except?.toLowerCase());
311
+ if (entries.length > 64) throw new DeviceRosterInvalidError(`The account holds ${entries.length} device entries, more than the 64 a rotation names.`);
312
+ return entries;
313
+ };
314
+ /**
315
+ * The ledger once the indexer reflects a call that advanced the auth
316
+ * nonce past `authNonce`. A chain of gated calls must have each bind the
317
+ * nonce the previous one left behind, which the indexer can serve a
318
+ * moment late.
319
+ *
320
+ * @throws {@link GrantRosterUnsettledError} when the indexer never
321
+ * reflects the call within the polling window.
322
+ */
323
+ const awaitAdvancedLedger = async (indexer, address, authNonce) => {
324
+ for (let attempt = 0; attempt < LEDGER_POLL_ATTEMPTS; attempt++) {
325
+ const ledgerState = await queryAccountLedger(indexer, address);
326
+ if (ledgerState.auth_nonce > authNonce) return ledgerState;
327
+ await sleep$1(LEDGER_POLL_DELAY_MS);
328
+ }
329
+ throw new GrantRosterUnsettledError(`The ledger of ${address} never reflected the accepted call.`);
330
+ };
331
+ /**
332
+ * Starts a chain of gated calls at `start`. Each accepted call reports
333
+ * the counter it advanced this device to, then waits for the indexer to
334
+ * reflect it, so the next call binds the auth nonce it left; the local
335
+ * roster row follows the entry each call leaves it on.
336
+ */
337
+ const callChain = ({ account, start, indexer, seams, onProgress, onAdvanced }) => {
338
+ let current = start;
339
+ const submit = async (call) => {
340
+ const { advancedCounter, localCommitmentHex } = await submitAccountCall({
341
+ circuit: call.circuit,
342
+ args: call.args,
343
+ account,
344
+ localUseCounter: current.localUseCounter,
345
+ ledgerState: current.ledgerState,
346
+ onStage: onProgress
347
+ }, seams);
348
+ const localUseCounter = advancedCounter.toString();
349
+ await onAdvanced(localUseCounter);
350
+ current = {
351
+ ledgerState: await awaitAdvancedLedger(indexer, account.address, current.ledgerState.auth_nonce),
352
+ localUseCounter,
353
+ devices: withRefreshedLocalDevice(current.devices, localCommitmentHex)
354
+ };
355
+ };
356
+ return {
357
+ submit,
358
+ append: async (stage, entries) => {
359
+ if (entries.length > 0) onProgress(stage);
360
+ for (const entry of entries) await submit(prepareAppendInbox(entry));
361
+ },
362
+ position: () => current
363
+ };
364
+ };
365
+ /** The registrations of an inbox, by hex. */
366
+ const registrationsOf = (entries) => new Set(entries.filter(isDeviceRegistration).map((entry) => HexBytes.fromByteArray(entry)));
367
+ /**
368
+ * The roster a rotation seals to: the registrations the live roster key
369
+ * opens, resolved against the ledger's device set so only a registration
370
+ * whose device key derives a live entry counts, and only one whose entry
371
+ * is among `devices`. A registration naming nobody's live device is
372
+ * passed over, and named devices left without a reader, by a conflict or
373
+ * for want of a registration, are reported dropped, see
374
+ * {@link resolveLiveReaders}; this device, sealed to regardless, is never
375
+ * reported dropped. The registration whose live entry is `target`, the
376
+ * entry a removal takes out, is named so no reader paired with its device
377
+ * is sealed to.
378
+ */
379
+ const sealedRoster = async ({ account, encryptionKey, networkId, local, ledgerState, inbox, devices, target, localEntry }) => {
380
+ const registered = (await encryptionKey.openInbox(networkId, inbox.keyring, inbox.entries.filter(isDeviceRegistration))).flatMap((opened) => opened?.kind === "device" ? [opened.device] : []);
381
+ const self = HexBytes.fromByteArray(local.readerPublicKey);
382
+ const { readers, dropped, outside } = resolveLiveReaders({
383
+ scope: {
384
+ address: account.address,
385
+ epoch: ledgerState.device_epoch
386
+ },
387
+ registered,
388
+ isLive: (entryHex) => ledgerState.devices.member(ByteArray.fromHex(HexBytes(entryHex))),
389
+ allowed: new Set(devices),
390
+ target
391
+ });
392
+ const removed = outside.find(({ entryHex }) => entryHex === target);
393
+ return {
394
+ readers: readers.filter(({ reader }) => reader.readerPublicKey !== self).map(({ reader }) => reader),
395
+ dropped: dropped.filter((entry) => entry !== localEntry),
396
+ ...removed ? { removed: {
397
+ devicePublicKey: removed.reader.devicePublicKey,
398
+ epoch: removed.reader.epoch,
399
+ counter: removed.reader.counter
400
+ } } : {}
401
+ };
402
+ };
403
+ /**
404
+ * Rotates the account encryption key to a fresh random secret and
405
+ * re-encrypts every live holding towards it, as the scoped grants
406
+ * standard requires before a read grant is issued and after one is
407
+ * revoked, and as a device removal requires so the removed device reads
408
+ * nothing newer. The holdings are walked with the keyring of the ledger's
409
+ * `enc_key` from the position the chain is at, a keyring this device's
410
+ * envelopes do not open rejecting with EncryptionKeyMismatchError before
411
+ * anything is submitted. The encryption key draws the new secret and
412
+ * seals it, with the roster key, to this device and to every registered
413
+ * device that is enrolled now and among `devices`, and answers the
414
+ * ciphertexts alone: one envelope per device and, when the roster key is
415
+ * fresh, one registration each. Should any registration the live roster
416
+ * key opens land while the rotation runs, as another device's enrolment
417
+ * does, the rotation refuses with DeviceRosterInvalidError before
418
+ * `enc_key` is replaced, so a device enrolled meanwhile is never left
419
+ * without the new key; registrations that open under no roster key are
420
+ * noise and do not stop it. Devices whose registrations conflict are
421
+ * left out and reported in the result. The holdings are
422
+ * re-encrypted towards the new key, the envelopes and registrations are
423
+ * appended, `enc_key` is replaced through `rotate_enc_key_with_jubjub`,
424
+ * and each re-encrypted holding is appended, one gated call each, all in
425
+ * the key session the caller holds. The envelopes land ahead of the
426
+ * rotation, so no device is left without the key the chain then holds;
427
+ * a rotation interrupted after it leaves holdings under the previous
428
+ * key, which every device still opens from its older envelopes and the
429
+ * next rotation re-encrypts. The previous secret is never derived again
430
+ * by anyone: entries sealed towards it stay readable to whoever held it,
431
+ * and nothing newer is.
432
+ */
433
+ const rotateEncKey = async ({ account, encryptionKey, view, local, chain, indexer, networkId, onProgress, devices, rotateRoster, target }) => {
434
+ const { ledgerState } = chain.position();
435
+ const inbox = readAccountInbox(account.address, ledgerState, local.readerPublicKey);
436
+ const { entries, keyring } = inbox;
437
+ const { holdingEntries } = await walkInbox({
438
+ address: account.address,
439
+ ledgerState,
440
+ indexer,
441
+ openEntries: async (coinEntries) => (await encryptionKey.openInbox(networkId, keyring, coinEntries)).map((opened) => opened?.kind === "coin" ? opened.coin : null)
442
+ });
443
+ const { readers, dropped, removed } = await sealedRoster({
444
+ account,
445
+ encryptionKey,
446
+ networkId,
447
+ local,
448
+ ledgerState,
449
+ inbox,
450
+ devices,
451
+ target,
452
+ localEntry: chain.position().devices.find((device) => device.isLocal)?.commitmentHex.toLowerCase()
453
+ });
454
+ const keys = await encryptionKey.createKeys(networkId, {
455
+ devicePublicKey: local.devicePublicKey,
456
+ keyring,
457
+ registrations: entries.filter(isDeviceRegistration),
458
+ readers,
459
+ ...rotateRoster === void 0 ? {} : { rotateRoster },
460
+ ...removed ? { removed } : {}
461
+ });
462
+ const reencrypted = (await view.reencryptInbox(networkId, {
463
+ keyring,
464
+ to: keys.encKey
465
+ }, holdingEntries)).filter((entry) => entry !== null);
466
+ onProgress("rotating");
467
+ for (const entry of [...keys.envelopes, ...keys.registrations]) await chain.submit(prepareAppendInbox(entry));
468
+ const before = registrationsOf(entries);
469
+ const appended = registrationsOf(keys.registrations);
470
+ const landed = inboxEntries(chain.position().ledgerState).filter((entry) => isDeviceRegistration(entry) && !before.has(HexBytes.fromByteArray(entry)) && !appended.has(HexBytes.fromByteArray(entry)));
471
+ 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.`);
472
+ await chain.submit(prepareRotateEncKey(keys.encKey));
473
+ await chain.append("reencrypting", reencrypted);
474
+ return {
475
+ encKey: keys.encKey,
476
+ dropped,
477
+ keyring: {
478
+ account: AccAddress(account.address),
479
+ encKey: keys.encKey,
480
+ envelopes: keys.envelopes.filter((envelope) => isAddressedTo(envelope, local.readerPublicKey))
481
+ }
482
+ };
483
+ };
484
+ /**
485
+ * Seals the live secret of `keyring` to each read grant's read key, with
486
+ * the grant record that keeps each seal on chain for this device. A
487
+ * grant the key refuses to seal to, an expired key session included, is
488
+ * listed unsealed rather than failing a rotation that already landed, or
489
+ * as revocation pending when the key refuses it with
490
+ * GrantRevocationPendingError.
491
+ */
492
+ const sealViews = async ({ view, networkId, keyring, account, targets }) => {
493
+ const sealedEncKey = HexBytes.fromByteArray(keyring.encKey);
494
+ const result = {
495
+ sealed: [],
496
+ unsealed: [],
497
+ revocationPending: [],
498
+ entries: []
499
+ };
500
+ for (const target of targets) {
501
+ let refusal;
502
+ const delivery = await view.sealView(networkId, keyring, {
503
+ ...target,
504
+ account
505
+ }).catch((error) => {
506
+ refusal = error;
507
+ });
508
+ if (!delivery) {
509
+ (refusal instanceof GrantRevocationPendingError ? result.revocationPending : result.unsealed).push(target.grantId);
510
+ continue;
511
+ }
512
+ result.sealed.push({
513
+ ...target,
514
+ seal: HexBytes.fromByteArray(delivery.seal),
515
+ sealedEncKey
516
+ });
517
+ result.entries.push(delivery.entry);
518
+ }
519
+ return result;
520
+ };
521
+ //#endregion
522
+ //#region ../../packages/module/passport-account/src/flows/stored-grants.ts
523
+ /**
524
+ * The slot each stored grant was derived under, keyed by id, as the
525
+ * roster decoder takes them.
526
+ */
527
+ const storedGrantSlots = (stored) => new Map(Object.entries(stored ?? {}).map(([id, { slot }]) => [GrantId(id), GrantSlot(slot)]));
528
+ /**
529
+ * The opening of each stored grant whose object fields were kept, keyed by
530
+ * id, as the roster decoder attaches them. A read grant whose seal this
531
+ * client holds carries it in the opening's view, with the `enc_key` whose
532
+ * secret it seals.
533
+ */
534
+ const storedGrantOpenings = (stored) => new Map(Object.entries(stored ?? {}).flatMap(([id, grant]) => grant.object ? [[GrantId(id), {
535
+ scopeSalt: GrantScopeSalt(grant.scopeSalt),
536
+ granteeScheme: storedGranteeScheme(grant),
537
+ granteePublicKey: grant.granteePublicKey,
538
+ origin: grant.origin,
539
+ color: TokenColor(grant.object.color),
540
+ recipient: grant.object.recipient,
541
+ maxCoinValue: grant.object.maxCoinValue,
542
+ ...grant.view?.seal === void 0 || grant.view.sealedEncKey === void 0 ? {} : { view: {
543
+ readPublicKey: grant.view.readPublicKey,
544
+ seal: grant.view.seal,
545
+ sealedEncKey: grant.view.sealedEncKey
546
+ } }
547
+ }]] : []));
548
+ /**
549
+ * The stored grants with the view of one grant replaced: its read key
550
+ * and, when given, the seal towards it of the secret of `sealedEncKey`.
551
+ */
552
+ const withStoredGrantView = (stored, grantId, view) => {
553
+ const grant = stored[grantId];
554
+ if (!grant) return stored;
555
+ return {
556
+ ...stored,
557
+ [grantId]: {
558
+ ...grant,
559
+ view
560
+ }
561
+ };
562
+ };
563
+ /**
564
+ * The read grants this client holds the read key of and the chain still
565
+ * lists active, other than `except`: the grants a rotation seals the new
566
+ * secret to again. A read grant issued by another client has no stored
567
+ * key here, so it is not among them.
568
+ */
569
+ const liveStoredReadGrants = (stored, roster, except) => {
570
+ const active = new Set(roster.filter((record) => record.active && record.scope.read).map(({ id }) => id));
571
+ return Object.entries(stored ?? {}).flatMap(([id, grant]) => grant.view && active.has(GrantId(id)) && id !== except ? [{
572
+ grantId: GrantId(id),
573
+ readPublicKey: grant.view.readPublicKey
574
+ }] : []);
575
+ };
576
+ /**
577
+ * The active read grants this client holds the read key of whose stored
578
+ * seal does not hold the secret of `encKey`, the ledger's current one:
579
+ * their grantees read nothing newer until a rotation seals to them again
580
+ * or they are issued again. A read grant issued by another client has no
581
+ * stored key here, so it is not among them.
582
+ */
583
+ const unsealedStoredReadGrants = (stored, roster, encKey) => liveStoredReadGrants(stored, roster).filter(({ grantId }) => stored?.[grantId]?.view?.sealedEncKey !== encKey).map(({ grantId }) => grantId);
584
+ /** The stored grants with one more entry, under its grant id. */
585
+ const withStoredGrant = (stored, grantId, grant) => ({
586
+ ...stored,
587
+ [grantId]: grant
588
+ });
589
+ /**
590
+ * The record a completed account persists: its identity, this device's
591
+ * use counter, the grant bookkeeping when there is any, and the roster of
592
+ * devices the account keys were sealed to when it is known. It never
593
+ * carries a deployment, so a write of it completes a pending record.
594
+ */
595
+ const completedRecord = ({ address, bindingVersion }, localUseCounter, { grants }) => ({
596
+ address,
597
+ bindingVersion,
598
+ localUseCounter,
599
+ ...grants ? { grants } : {}
600
+ });
601
+ /**
602
+ * The stored grants with the seals of a rotation applied: each sealed
603
+ * grant's view carries its new seal and the `enc_key` it holds, and each
604
+ * unsealed one keeps its read key alone.
605
+ */
606
+ const withSealedViews = (stored, { sealed, unsealed }) => {
607
+ if (!stored) return stored;
608
+ let next = stored;
609
+ for (const { grantId, readPublicKey, seal, sealedEncKey } of sealed) next = withStoredGrantView(next, grantId, {
610
+ readPublicKey,
611
+ seal,
612
+ sealedEncKey
613
+ });
614
+ for (const grantId of unsealed) {
615
+ const readPublicKey = next[grantId]?.view?.readPublicKey;
616
+ if (readPublicKey !== void 0) next = withStoredGrantView(next, grantId, { readPublicKey });
617
+ }
618
+ return next;
619
+ };
620
+ /** Each grant's parts by id, the later of two parts of a kind winning. */
621
+ const partsByGrant = (parts) => {
622
+ const byGrant = /* @__PURE__ */ new Map();
623
+ for (const part of parts) {
624
+ const held = byGrant.get(part.grantId) ?? {};
625
+ byGrant.set(part.grantId, {
626
+ ...held,
627
+ [part.part]: part
628
+ });
629
+ }
630
+ return byGrant;
631
+ };
632
+ /**
633
+ * Whether a grant's bookkeeping opens its on-chain commitments under the
634
+ * account at `address`: the id derives from the account, the grantee
635
+ * key under its scheme, the origin and the slot, the object commitment
636
+ * from the salt and the object fields, and the read key hashes to the
637
+ * one the contract holds, or is absent for a grant that does not read.
638
+ * Anyone can append any bytes to the inbox, and another client of the
639
+ * account issuing to the same grantee from the same origin lands on the
640
+ * same id with its own salt, so this check, not where the bookkeeping
641
+ * came from, is what makes it trusted.
642
+ */
643
+ const opensOnChain = async (record, fields, address) => {
644
+ try {
645
+ const grantee = {
646
+ scheme: fields.granteeScheme,
647
+ publicKey: fields.granteePublicKey
648
+ };
649
+ const grantId = deriveGrantId({
650
+ contractAddress: ByteArray.fromHex(HexBytes(address)),
651
+ granteePublicKey: granteePoint(grantee),
652
+ originHash: await originHash(fields.origin),
653
+ slot: GrantSlot(fields.slot)
654
+ });
655
+ const encoded = circuitScope({
656
+ grantee,
657
+ operations: [],
658
+ color: TokenColor(fields.object.color),
659
+ recipient: fields.object.recipient,
660
+ maxCoinValue: fields.object.maxCoinValue,
661
+ perCallCap: "0",
662
+ cap: "0",
663
+ expiresAt: null,
664
+ ...fields.readPublicKey === void 0 ? {} : { readPublicKey: fields.readPublicKey }
665
+ });
666
+ 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;
667
+ } catch {
668
+ return false;
669
+ }
670
+ };
671
+ /**
672
+ * The stored grants narrowed to the ones that still open what the chain
673
+ * holds under their id, or undefined once none is left. A grant the
674
+ * chain no longer holds is dropped, and so is one whose kept fields do
675
+ * not open its commitments: the entry an issue wrote before a call that
676
+ * never landed, once another client of the account issued over the same
677
+ * id, or an entry written before the object fields were kept, which
678
+ * cannot be checked. A revoked grant stays in the contract's map as a
679
+ * tombstone, so its slot and salt are kept until a revoke-all clears the
680
+ * map or a new grant overwrites the id.
681
+ */
682
+ const retainStoredGrants = async (stored, roster, address) => {
683
+ if (!stored) return void 0;
684
+ const retained = {};
685
+ for (const record of roster) {
686
+ const grant = stored[record.id];
687
+ if (!grant?.object) continue;
688
+ if (await opensOnChain(record, {
689
+ ...grant,
690
+ granteeScheme: storedGranteeScheme(grant),
691
+ object: grant.object,
692
+ ...grant.view === void 0 ? {} : { readPublicKey: grant.view.readPublicKey }
693
+ }, address)) retained[record.id] = grant;
694
+ }
695
+ return Object.keys(retained).length > 0 ? retained : void 0;
696
+ };
697
+ /**
698
+ * The bookkeeping of grants this device issued, rebuilt from the grant
699
+ * records it opened in the inbox, for the grants the chain still holds:
700
+ * each grant whose parts open its on-chain commitments under this
701
+ * account and origin, with its read key and, when the newest view record
702
+ * holds the seal of the ledger's `enc_key`, that seal. A grant whose
703
+ * parts do not check out, or whose grant or object part is missing, is
704
+ * left out. Undefined when nothing is rebuilt.
705
+ */
706
+ const rebuildStoredGrants = async (parts, roster, scope) => {
707
+ const byGrant = partsByGrant(parts);
708
+ const rebuilt = {};
709
+ for (const record of roster) {
710
+ const held = byGrant.get(record.id);
711
+ if (!held?.grant || !held.object) continue;
712
+ const { grant, object, view } = held;
713
+ if (!await opensOnChain(record, {
714
+ ...grant,
715
+ origin: scope.origin,
716
+ object: object.object
717
+ }, scope.address)) continue;
718
+ const readPublicKey = grant.readPublicKey;
719
+ const isCurrent = view !== void 0 && scope.encKey.startsWith(view.encKeyPrefix);
720
+ rebuilt[record.id] = {
721
+ slot: grant.slot,
722
+ scopeSalt: grant.scopeSalt,
723
+ granteeScheme: grant.granteeScheme,
724
+ granteePublicKey: grant.granteePublicKey,
725
+ origin: scope.origin,
726
+ object: object.object,
727
+ ...readPublicKey === void 0 ? {} : { view: isCurrent ? {
728
+ readPublicKey,
729
+ seal: view.seal,
730
+ sealedEncKey: scope.encKey
731
+ } : { readPublicKey } }
732
+ };
733
+ }
734
+ return Object.keys(rebuilt).length > 0 ? rebuilt : void 0;
735
+ };
736
+ /**
737
+ * The record's bookkeeping with every rebuilt grant it lacks added: what
738
+ * the record holds is kept, so a record that survived is never
739
+ * overwritten by the chain's copy, except for a view whose seal is not of
740
+ * `encKey`, the ledger's current one, when the rebuilt view's seal is:
741
+ * the record write after a rotation can be lost while its seal reached
742
+ * the inbox. Run over the bookkeeping {@link retainStoredGrants} checked,
743
+ * a rebuilt grant takes the place of an entry that did not open.
744
+ */
745
+ const withRebuiltGrants = (stored, rebuilt, encKey) => {
746
+ if (!rebuilt) return stored;
747
+ const merged = {
748
+ ...rebuilt,
749
+ ...stored
750
+ };
751
+ for (const [id, fromChain] of Object.entries(rebuilt)) {
752
+ const held = stored?.[id];
753
+ if (held && held.view?.sealedEncKey !== encKey && fromChain.view?.sealedEncKey === encKey) merged[id] = {
754
+ ...held,
755
+ view: fromChain.view
756
+ };
757
+ }
758
+ return merged;
759
+ };
760
+ //#endregion
761
+ //#region ../../packages/module/passport-account/src/flows/create-account.ts
762
+ /** The initial device entry is inserted at epoch 0 with use counter 0. */
763
+ const INITIAL_DEVICE_EPOCH = DeviceEpoch(0n);
764
+ const INITIAL_USE_COUNTER_VALUE = "0";
765
+ /**
766
+ * The record of a creation left unfinished on this device, read inside
767
+ * the session once presence reported one. A record that opens without a
768
+ * pending deployment, or that this authoriser cannot open, refuses with
769
+ * AccountExistsError: it names an account that must not be created over.
770
+ * A record that carries only the marker of its creation, which a hosted
771
+ * signer shows no flow but the creation, cannot be resumed and is
772
+ * refused, as is one started under another lock choice than
773
+ * `lockAccount`, with CreationLockMismatchError naming the recorded one.
774
+ */
775
+ const pendingRecord = async (accountRecords, lockAccount) => {
776
+ const record = await accountRecords.read();
777
+ if (!record?.deployment) throw new AccountExistsError();
778
+ 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.`);
779
+ if (record.deployment.lockAccount !== lockAccount) throw lockChoiceMismatch(record.deployment.lockAccount);
780
+ return {
781
+ ...record,
782
+ deployment: record.deployment
783
+ };
784
+ };
785
+ /**
786
+ * Runs the deployment: a fresh one, which draws the account keys first,
787
+ * deploys with their `enc_key` and records the pending deployment, with
788
+ * this device's envelope and registration, as soon as the deploy lands
789
+ * so an interruption can be resumed; or the remaining waves of a
790
+ * recorded one, with the key entries it recorded.
791
+ */
792
+ const deploy = async ({ providers, lockAccount, pending, local, context: { seams, accountRecords } }) => {
793
+ const { passportAuthoriser, passportEncryptionKey, passportNetwork } = seams;
794
+ if (pending) return {
795
+ deployed: await resumeAccountDeployment({
796
+ providers,
797
+ authoriser: passportAuthoriser,
798
+ address: pending.address,
799
+ pending: pending.deployment
800
+ }),
801
+ pending: pending.deployment
802
+ };
803
+ const keys = await passportEncryptionKey.createKeys(passportNetwork.networkId, { devicePublicKey: local.devicePublicKey });
804
+ const keyEntries = [...keys.envelopes, ...keys.registrations].map((entry) => HexBytes.fromByteArray(entry));
805
+ const progress = {};
806
+ const deployed = await deployAccount({
807
+ providers,
808
+ authoriser: passportAuthoriser,
809
+ encPublicKey: keys.encKey,
810
+ lockAccount,
811
+ onDeployed: async (address, deployment) => {
812
+ progress.recorded = {
813
+ ...deployment,
814
+ keyEntries
815
+ };
816
+ await accountRecords.write({
817
+ address,
818
+ bindingVersion: accManifest.bindingVersion,
819
+ localUseCounter: INITIAL_USE_COUNTER_VALUE,
820
+ deployment: progress.recorded
821
+ });
822
+ }
823
+ });
824
+ if (!progress.recorded) throw new Error("The deployment landed without reporting its progress.");
825
+ return {
826
+ deployed,
827
+ pending: progress.recorded
828
+ };
829
+ };
830
+ /**
831
+ * Creates a Passport account: the passkey ceremony (implicit in the first
832
+ * authoriser use), the account keys drawn through the encryption key
833
+ * seam, the Account Custody Contract deployment in waves with sponsored
834
+ * fees, the initial device activation, the delivery of the account keys
835
+ * to this device's inbox, and the local persistence of the account
836
+ * record. Every step runs inside one key session, so the whole flow costs
837
+ * a single ceremony rather than one per authoriser call. The flow never
838
+ * holds the encryption secret: the seam draws it at random, seals it to
839
+ * this device's reader key and hands back only its public key, which the
840
+ * constructor takes as `enc_key`, with this device's envelope and its
841
+ * registration under a fresh roster key; once the device is active, both
842
+ * are appended to the inbox, one gated call each, so the account keys
843
+ * live on chain from the start.
844
+ *
845
+ * Progress is reported through `onProgress`: 'deploying' once the
846
+ * authoriser has produced the device key, 'proving' and 'sponsoring' from
847
+ * inside each transaction submission (a transaction proves first, then
848
+ * the sponsor balances it), 'activating' before the activation call and
849
+ * 'recording' before the key entries are appended. The record is written
850
+ * before the promise resolves, so a process that dies right after still
851
+ * recognises the account on next startup.
852
+ *
853
+ * The flow runs to completion once started: cancelling mid-deploy could
854
+ * orphan a contract the sponsor already paid for. The caller's flow gate
855
+ * is what keeps a second request from starting one. Should the process
856
+ * die between waves anyway, the record written when the deploy landed
857
+ * names the contract, what it still needs and the key entries, and the
858
+ * next create request on this device resumes from the operations the
859
+ * chain holds, activates once every wave is in and appends whichever key
860
+ * entry the inbox still lacks; a creation that died after its activation
861
+ * landed resumes from there. A resumed creation finishes exactly as it
862
+ * began, with the keys recorded then: a request under another lock choice
863
+ * than the recorded one is refused with CreationLockMismatchError, and a
864
+ * build pinning other verifier keys than the recorded deployment with
865
+ * CreationArtefactMismatchError, both before any wave. The session names
866
+ * the lock choice, so an authoriser that asks consent first shows it; a
867
+ * hosted signer refuses the same lock mismatch itself, and a resume
868
+ * started from another origin than the creation it resumes.
869
+ *
870
+ * A device already holding a completed account record refuses with
871
+ * AccountExistsError before the ceremony runs: the record is the only
872
+ * pointer to the deployed contract and there is no recovery path, so
873
+ * creating over it would orphan the existing account. Presence is read
874
+ * without opening the record, and it tells a completed record from an
875
+ * unfinished one, so a sealed record blocks the flow without costing a
876
+ * prompt and only a record the flow may resume is opened, inside the
877
+ * session, where it costs no extra prompt.
878
+ */
879
+ const createAccount = async ({ lockAccount }, context) => {
880
+ const { seams, accountRecords, onProgress } = context;
881
+ const presence = await accountRecords.presence();
882
+ if (presence === "complete") throw new AccountExistsError();
883
+ const { passportAuthoriser, passportNetwork, passportProver, passportSponsor } = seams;
884
+ return inKeySession(passportAuthoriser, {
885
+ kind: "create-account",
886
+ lockAccount
887
+ }, async () => {
888
+ const local = await readLocalDevice(seams);
889
+ const pending = presence === "pending" ? await pendingRecord(accountRecords, lockAccount) : void 0;
890
+ onProgress("deploying");
891
+ const { deployed, pending: deployment } = await deploy({
892
+ providers: await createMidnightProviders({
893
+ network: passportNetwork,
894
+ prover: passportProver,
895
+ sponsor: passportSponsor,
896
+ onStage: onProgress
897
+ }),
898
+ lockAccount,
899
+ pending,
900
+ local,
901
+ context
902
+ });
903
+ if (!deployed.isActivated) {
904
+ onProgress("activating");
905
+ await deployed.activate();
906
+ }
907
+ const account = {
908
+ address: deployed.address,
909
+ bindingVersion: accManifest.bindingVersion,
910
+ status: "ready",
911
+ networkId: passportNetwork.networkId
912
+ };
913
+ const startCounter = pending?.localUseCounter ?? INITIAL_USE_COUNTER_VALUE;
914
+ const { indexer, ledgerState } = await readAccountLedger(deployed.address, passportNetwork);
915
+ const held = new Set(inboxEntries(ledgerState).map((entry) => HexBytes.fromByteArray(entry)));
916
+ const chain = callChain({
917
+ account,
918
+ start: {
919
+ ledgerState,
920
+ localUseCounter: startCounter,
921
+ devices: [{
922
+ commitmentHex: await passportAuthoriser.deviceCommitment(AccAddress(deployed.address), INITIAL_DEVICE_EPOCH, UseCounter(BigInt(startCounter))),
923
+ isLocal: true
924
+ }]
925
+ },
926
+ indexer,
927
+ seams,
928
+ onProgress,
929
+ onAdvanced: async (localUseCounter) => accountRecords.write({
930
+ address: account.address,
931
+ bindingVersion: account.bindingVersion,
932
+ localUseCounter,
933
+ deployment
934
+ })
935
+ });
936
+ await chain.append("recording", deployment.keyEntries.filter((entry) => !held.has(entry)).map((entry) => ByteArray.fromHex(HexBytes(entry))));
937
+ const { localUseCounter, devices } = chain.position();
938
+ const counter = localUseCounter ?? startCounter;
939
+ await accountRecords.write(completedRecord(account, counter, {}));
940
+ return {
941
+ account,
942
+ devices,
943
+ localUseCounter: counter,
944
+ grants: [],
945
+ encKey: HexBytes.fromByteArray(ledgerState.enc_key)
946
+ };
947
+ });
948
+ };
949
+ //#endregion
950
+ //#region ../../packages/module/passport-account/src/acc/read-grants.ts
951
+ const NO_SLOTS = /* @__PURE__ */ new Map();
952
+ const NO_OPENINGS = /* @__PURE__ */ new Map();
953
+ /** The slot reported for a grant whose slot this client never learned. */
954
+ const UNKNOWN_SLOT = GrantSlot(0);
955
+ const toNumber = (field, value) => {
956
+ if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`Grant field ${field} exceeds the safe integer range`);
957
+ return Number(value);
958
+ };
959
+ const toOperations = (scope) => {
960
+ const operations = [];
961
+ if (scope.op_withdraw_unshielded) operations.push("withdraw-unshielded");
962
+ if (scope.op_withdraw_shielded) operations.push("withdraw-shielded");
963
+ if (scope.op_withdraw_shielded_to_contract) operations.push("withdraw-shielded-to-contract");
964
+ return operations;
965
+ };
966
+ const toScope = (scope) => ({
967
+ operations: toOperations(scope),
968
+ read: scope.read,
969
+ objectCommit: HexBytes.fromByteArray(scope.object_commit),
970
+ perCallCap: scope.per_call_cap.toString(),
971
+ cap: scope.cap.toString(),
972
+ expiresAt: scope.expires_at === 0n ? null : toNumber("expires_at", scope.expires_at),
973
+ rpCommit: HexBytes.fromByteArray(scope.rp_commit),
974
+ readPkHash: HexBytes.fromByteArray(scope.read_pk_hash),
975
+ window: scope.window_len === 0n ? null : {
976
+ lengthSeconds: toNumber("window_len", scope.window_len),
977
+ cap: scope.window_cap.toString()
978
+ },
979
+ callerCommit: HexBytes.fromByteArray(scope.caller_commit)
980
+ });
981
+ const toRecord = (id, record, { slot, opening }) => ({
982
+ id,
983
+ slot,
984
+ active: record.active,
985
+ epoch: toNumber("epoch", record.epoch),
986
+ generation: toNumber("gen", record.gen),
987
+ issuedAt: toNumber("issued_at", record.issued_at),
988
+ scope: toScope(record.scope),
989
+ spentWindow: {
990
+ start: toNumber("window_start", record.window_start),
991
+ spent: record.window_spent.toString()
992
+ },
993
+ ...opening ? { opening } : {}
994
+ });
995
+ /**
996
+ * Decodes the account's grant roster from the ledger's grants map, in the
997
+ * map's order. Plain fields decode to the read model's numbers and
998
+ * decimal strings, commitments stay as hex, and an expiry or window of
999
+ * zero reads as none. A revoked grant stays in the map as an inactive
1000
+ * tombstone and is listed as such. The contract stores no slot: the
1001
+ * caller supplies the slots of the grants it issued, and a grant issued by
1002
+ * another client of the account reports slot 0. The openings the caller
1003
+ * holds are attached to their grants.
1004
+ */
1005
+ const readGrants = (ledgerState, slots = NO_SLOTS, openings = NO_OPENINGS) => Array.from(ledgerState.grants, ([rawId, record]) => {
1006
+ const id = GrantId(HexBytes.fromByteArray(rawId));
1007
+ return toRecord(id, record, {
1008
+ slot: slots.get(id) ?? UNKNOWN_SLOT,
1009
+ opening: openings.get(id)
1010
+ });
1011
+ });
1012
+ //#endregion
1013
+ //#region ../../packages/module/passport-account/src/flows/devices.ts
1014
+ /**
1015
+ * Contract aborts meaning the removal would leave the account without an
1016
+ * authorising device: the caller rule and the redundant count floor.
1017
+ */
1018
+ const LAST_DEVICE_ABORTS = ["failed assert: cannot remove the authorising device", "failed assert: cannot remove last device"];
1019
+ /**
1020
+ * Types a raw contract abort by the assert message the Account Custody
1021
+ * Contract raises; anything unrecognised passes through unchanged.
1022
+ * An unknown-entry abort on the remove circuit is attributed to the
1023
+ * removal target, not the caller: the circuit checks the caller first,
1024
+ * and the caller's entry was resolved against live ledger state inside
1025
+ * the same gate, so only a mid-flight roll of the caller's own entry
1026
+ * could produce it, while a stale target commitment always does.
1027
+ */
1028
+ const classifyContractAbort$1 = (error, circuit) => {
1029
+ const message = error instanceof Error ? error.message : String(error);
1030
+ if (LAST_DEVICE_ABORTS.some((abort) => message.includes(abort))) return new LastDeviceError(message);
1031
+ if (message.includes("failed assert: unknown device entry")) return circuit === "remove_device_with_jubjub" ? new RemovalTargetNotFoundError(message) : new NotAuthorisedError(message);
1032
+ if (isNotAuthorisedAbort(message)) return new NotAuthorisedError(message);
1033
+ return error;
1034
+ };
1035
+ /**
1036
+ * Whether any read grant of the account is live: its grantees hold the
1037
+ * live account secret, so a device handed the keys while one is live
1038
+ * gets a fresh secret first.
1039
+ */
1040
+ const hasLiveReadGrant = (ledgerState) => readGrants(ledgerState).some((record) => record.active && record.scope.read);
1041
+ /** The devices list with the enrolled commitment appended. */
1042
+ const withDevice = (devices, commitmentHex) => [...devices, {
1043
+ commitmentHex,
1044
+ isLocal: false
1045
+ }];
1046
+ /** The devices list with the revoked commitment dropped. */
1047
+ const withoutDevice = (devices, commitmentHex) => devices.filter((device) => device.commitmentHex !== commitmentHex);
1048
+ /** A device's entry as the call that targets it takes it. */
1049
+ const entryArgument = (commitmentHex) => ByteArray.fromHex(HexBytes(commitmentHex.toLowerCase()));
1050
+ /** The counter the chain left this device at, or the one it started from. */
1051
+ const chainCounter = (chain, input) => chain.position().localUseCounter ?? input.localUseCounter ?? "0";
1052
+ /**
1053
+ * Opens what a device flow runs on inside its key session: the grant
1054
+ * bookkeeping of the record, read where it costs no extra prompt so every
1055
+ * write keeps it, and a chain of gated calls from the ledger read ahead
1056
+ * of the session, each persisting the counter it advanced this device to
1057
+ * before the next call. The bookkeeping is checked against the ledger
1058
+ * first, so an entry that does not open the grant the chain holds under
1059
+ * its id, as one an issue wrote before a call that never landed, is
1060
+ * neither re-sealed to nor kept.
1061
+ */
1062
+ const openDeviceSession = async (input, { ledgerState, indexer }, { seams, accountRecords, onProgress }) => {
1063
+ const { account, devices, localUseCounter } = input;
1064
+ let grants = await retainStoredGrants((await accountRecords.read())?.grants, readGrants(ledgerState), account.address);
1065
+ const write = async (counter) => accountRecords.write(completedRecord(account, counter, { grants }));
1066
+ const chain = callChain({
1067
+ account,
1068
+ start: {
1069
+ ledgerState,
1070
+ localUseCounter,
1071
+ devices
1072
+ },
1073
+ indexer,
1074
+ seams,
1075
+ onProgress,
1076
+ onAdvanced: write
1077
+ });
1078
+ return {
1079
+ grants,
1080
+ chain,
1081
+ keep: async (next) => {
1082
+ grants = next;
1083
+ await write(chainCounter(chain, input));
1084
+ }
1085
+ };
1086
+ };
1087
+ /**
1088
+ * Enrols a new device key on the account. `commitmentHex` carries the new
1089
+ * device's entry commitment, derived out of band by the joining device;
1090
+ * the local device authorises `add_device_with_jubjub` through the
1091
+ * gated-call pattern. The roster gains the commitment on success only,
1092
+ * marked as remote, and the same result moves the local device's own row
1093
+ * to the successor entry the call left it on, so the roster and the use
1094
+ * counter never disagree about where this device stands.
1095
+ *
1096
+ * When `reader` names the joining device's reader and device keys, the
1097
+ * account keys are delivered to it in the same session: its device key
1098
+ * must derive the enrolled commitment at use counter 0 and its reader key
1099
+ * must be one the account seals to, both checked before any prompt. The
1100
+ * encryption key seals the live secret and the roster key to the reader
1101
+ * key, and the envelope and the device's registration under the roster
1102
+ * key are appended to the inbox, one gated call each, ahead of the
1103
+ * enrolment, so an enrolment that lands never leaves the device without
1104
+ * its keys; until it lands the registration names no live entry and a
1105
+ * rotation passes over it. While any read grant is live its grantees
1106
+ * hold the live secret, and one could seal it to the joining reader with
1107
+ * a roster key of its own ahead of the genuine envelope, so the account
1108
+ * keys are rotated first in the same session, with a fresh roster key,
1109
+ * as a removal rotates them, the joining device handed the new secret no
1110
+ * grantee has seen, and the live read grants this client holds the read
1111
+ * key of sealed it after; with no live read grant only enrolled devices
1112
+ * hold the secret, and the live keys are handed over as they are. The
1113
+ * joining device then signs in and reads the holdings with its own
1114
+ * passkey alone. Without `reader` the
1115
+ * device can authorise but reads nothing until some device delivers it
1116
+ * the keys.
1117
+ *
1118
+ * The advanced counter is persisted to the account record after every
1119
+ * call, before the roster is returned, so the next flow rescans from a
1120
+ * fresh anchor. A failure leaves the roster unreturned.
1121
+ *
1122
+ * A rejected authorisation (bad signature, malformed key, or a caller
1123
+ * entry the on-chain set no longer holds) rejects with NotAuthorisedError;
1124
+ * a record whose address holds no live contract rejects with
1125
+ * AccountContractMissingError; joining keys that do not match the entry
1126
+ * reject with DeviceReaderInvalidError. The transactions' proving and
1127
+ * sponsoring stages and 'recording' are reported through `onProgress`.
1128
+ */
1129
+ const addDevice = async ({ reader, ...input }, context) => {
1130
+ const { seams, onProgress } = context;
1131
+ const { account, commitmentHex } = input;
1132
+ const { networkId } = seams.passportNetwork;
1133
+ try {
1134
+ const ledger = await readAccountLedger(account.address, seams.passportNetwork);
1135
+ if (reader) assertJoiningDevice({
1136
+ address: account.address,
1137
+ epoch: ledger.ledgerState.device_epoch
1138
+ }, reader, commitmentHex);
1139
+ const view = reader && hasLiveReadGrant(ledger.ledgerState) ? viewCapability(seams.passportEncryptionKey) : void 0;
1140
+ const devices = view ? liveDeviceEntries(ledger.ledgerState) : void 0;
1141
+ return await inKeySession(seams.passportAuthoriser, {
1142
+ kind: "add-device",
1143
+ commitmentHex,
1144
+ account: AccAddress(account.address),
1145
+ ...reader ? { reader } : {},
1146
+ ...devices ? { devices } : {}
1147
+ }, async () => {
1148
+ const { grants, chain, keep } = await openDeviceSession(input, ledger, context);
1149
+ let rotated;
1150
+ if (reader) {
1151
+ const local = await readLocalDevice(seams);
1152
+ if (view && devices) rotated = await rotateEncKey({
1153
+ account,
1154
+ encryptionKey: seams.passportEncryptionKey,
1155
+ view,
1156
+ local,
1157
+ chain,
1158
+ indexer: ledger.indexer,
1159
+ networkId,
1160
+ onProgress,
1161
+ devices,
1162
+ rotateRoster: true
1163
+ });
1164
+ const delivery = await seams.passportEncryptionKey.sealToDevice(networkId, rotated?.keyring ?? readAccountInbox(account.address, chain.position().ledgerState, local.readerPublicKey).keyring, {
1165
+ ...reader,
1166
+ epoch: ledger.ledgerState.device_epoch,
1167
+ counter: 0n
1168
+ });
1169
+ await chain.append("recording", [delivery.envelope, delivery.registration]);
1170
+ if (view && rotated) {
1171
+ const views = await sealViews({
1172
+ view,
1173
+ networkId,
1174
+ keyring: rotated.keyring,
1175
+ account: AccAddress(account.address),
1176
+ targets: liveStoredReadGrants(grants, readGrants(chain.position().ledgerState))
1177
+ });
1178
+ await keep(withSealedViews(grants, views));
1179
+ await chain.append("recording", views.entries);
1180
+ }
1181
+ }
1182
+ await chain.submit({
1183
+ circuit: ADD_DEVICE_CIRCUIT,
1184
+ args: [entryArgument(commitmentHex)]
1185
+ });
1186
+ return {
1187
+ devices: withDevice(chain.position().devices, commitmentHex),
1188
+ localUseCounter: chainCounter(chain, input),
1189
+ ...rotated ? {
1190
+ encKey: HexBytes.fromByteArray(rotated.encKey),
1191
+ droppedDevices: rotated.dropped
1192
+ } : {}
1193
+ };
1194
+ });
1195
+ } catch (error) {
1196
+ throw classifyContractAbort$1(error, ADD_DEVICE_CIRCUIT);
1197
+ }
1198
+ };
1199
+ /**
1200
+ * Refuses a removal the contract would refuse before any prompt: a
1201
+ * target the on-chain device set does not hold, and the local device,
1202
+ * which cannot remove itself. The rotation a removal runs comes first,
1203
+ * so a removal refused only after it would have cost the target device
1204
+ * its keys for nothing.
1205
+ *
1206
+ * @throws {@link RemovalTargetNotFoundError} when the target is gone.
1207
+ * @throws {@link LastDeviceError} when the target is this device.
1208
+ */
1209
+ const assertRemovable = ({ devices, commitmentHex }, { ledgerState }) => {
1210
+ if (!ledgerState.devices.member(entryArgument(commitmentHex))) throw new RemovalTargetNotFoundError(`The account holds no device entry ${commitmentHex}.`);
1211
+ if (devices.find((device) => device.isLocal)?.commitmentHex.toLowerCase() === commitmentHex.toLowerCase()) throw new LastDeviceError("The device that authorises a removal cannot remove itself.");
1212
+ };
1213
+ /**
1214
+ * Revokes a device key from the account and rotates the account keys so
1215
+ * the removed device reads nothing newer. `commitmentHex` names the
1216
+ * target by its current entry commitment, which is the literal set
1217
+ * element the contract removes; the local device authorises
1218
+ * `remove_device_with_jubjub` through the gated-call pattern.
1219
+ *
1220
+ * Ahead of the removal, in the same session, the encryption key is
1221
+ * rotated with a fresh roster key and sealed only to this device and to
1222
+ * the registered devices whose device key derives a live entry other
1223
+ * than the target, which the key session names to the user before it
1224
+ * opens; the live holdings are re-encrypted towards it, and it is sealed
1225
+ * again to every live read grant this client holds the read key of, each
1226
+ * seal kept on chain in a grant record. The removed device's envelopes
1227
+ * stay in the inbox and keep opening the secrets they held, but none
1228
+ * opens the new one, and the registrations under the old roster key no
1229
+ * longer count, any it planted for itself included. A roster in which
1230
+ * two readers claim one live device, or one reader two, refuses with
1231
+ * DeviceRosterInvalidError rather than guess.
1232
+ *
1233
+ * The roster drops the commitment on success only, and the same result
1234
+ * moves the local device's own row to the successor entry the call left
1235
+ * it on. The advanced counter is persisted to the account record after
1236
+ * every call. The contract's own guards surface as typed errors: a
1237
+ * removal that would strand the account (the authorising device, or the
1238
+ * count floor) rejects with LastDeviceError, a rejected authorisation
1239
+ * (bad signature or malformed key) with NotAuthorisedError, and a target
1240
+ * entry that is no longer in the on-chain set with
1241
+ * RemovalTargetNotFoundError; the target's presence and the local device
1242
+ * are checked before any prompt, and an encryption key that cannot
1243
+ * rotate refuses with ReadUnavailableError before any prompt too. The
1244
+ * rotation's stages, 'recording' and the transactions' proving and
1245
+ * sponsoring are reported through `onProgress`.
1246
+ */
1247
+ const removeDevice = async (input, context) => {
1248
+ const { seams, onProgress } = context;
1249
+ const { account, commitmentHex } = input;
1250
+ const { networkId } = seams.passportNetwork;
1251
+ try {
1252
+ const view = viewCapability(seams.passportEncryptionKey);
1253
+ const ledger = await readAccountLedger(account.address, seams.passportNetwork);
1254
+ assertRemovable(input, ledger);
1255
+ const devices = liveDeviceEntries(ledger.ledgerState, commitmentHex);
1256
+ return await inKeySession(seams.passportAuthoriser, {
1257
+ kind: "remove-device",
1258
+ commitmentHex,
1259
+ account: AccAddress(account.address),
1260
+ devices
1261
+ }, async () => {
1262
+ const { grants, chain, keep } = await openDeviceSession(input, ledger, context);
1263
+ const rotated = await rotateEncKey({
1264
+ account,
1265
+ encryptionKey: seams.passportEncryptionKey,
1266
+ view,
1267
+ local: await readLocalDevice(seams),
1268
+ chain,
1269
+ indexer: ledger.indexer,
1270
+ networkId,
1271
+ onProgress,
1272
+ devices,
1273
+ rotateRoster: true,
1274
+ target: commitmentHex.toLowerCase()
1275
+ });
1276
+ const views = await sealViews({
1277
+ view,
1278
+ networkId,
1279
+ keyring: rotated.keyring,
1280
+ account: AccAddress(account.address),
1281
+ targets: liveStoredReadGrants(grants, readGrants(chain.position().ledgerState))
1282
+ });
1283
+ await keep(withSealedViews(grants, views));
1284
+ await chain.append("recording", views.entries);
1285
+ await chain.submit({
1286
+ circuit: REMOVE_DEVICE_CIRCUIT,
1287
+ args: [entryArgument(commitmentHex)]
1288
+ });
1289
+ return {
1290
+ devices: withoutDevice(chain.position().devices, commitmentHex),
1291
+ localUseCounter: chainCounter(chain, input),
1292
+ encKey: HexBytes.fromByteArray(rotated.encKey),
1293
+ droppedDevices: rotated.dropped
1294
+ };
1295
+ });
1296
+ } catch (error) {
1297
+ throw classifyContractAbort$1(error, REMOVE_DEVICE_CIRCUIT);
1298
+ }
1299
+ };
1300
+ //#endregion
1301
+ //#region ../../packages/module/passport-account/src/flows/grants.ts
1302
+ /** Contract abort naming a grant the grants map does not hold. */
1303
+ const UNKNOWN_GRANT_ABORT = "failed assert: unknown grant";
1304
+ /** Contract abort refusing a revoke over a grant already inactive. */
1305
+ const GRANT_NOT_LIVE_ABORT = "failed assert: grant not live";
1306
+ /** Contract abort refusing an issue over a grant id that is still active. */
1307
+ const GRANT_ACTIVE_ABORT = "failed assert: grant already active";
1308
+ /**
1309
+ * How long an accepted call is given to show in the indexer's view of the
1310
+ * grants map, which can lag the block the call landed in.
1311
+ */
1312
+ const ROSTER_POLL_ATTEMPTS = 30;
1313
+ const ROSTER_POLL_DELAY_MS = 1e3;
1314
+ const MILLISECONDS_PER_SECOND = 1e3;
1315
+ const sleep = async (ms) => new Promise((resolve) => {
1316
+ setTimeout(resolve, ms);
1317
+ });
1318
+ const isActive = (roster, grantId) => roster.some((record) => record.id === grantId && record.active);
1319
+ const activeCount = (roster) => roster.filter((record) => record.active).length;
1320
+ const nowSeconds = () => Math.floor(Date.now() / MILLISECONDS_PER_SECOND);
1321
+ /**
1322
+ * Types a raw contract abort by the assert message the Account Custody
1323
+ * Contract raises; anything unrecognised passes through unchanged. An
1324
+ * unknown-entry abort can only come from the caller check here, since no
1325
+ * grant circuit names a device entry.
1326
+ */
1327
+ const classifyContractAbort = (error) => {
1328
+ const message = error instanceof Error ? error.message : String(error);
1329
+ if (message.includes(UNKNOWN_GRANT_ABORT)) return new GrantNotFoundError(message);
1330
+ if (message.includes(GRANT_NOT_LIVE_ABORT)) return new GrantRevokedError(message);
1331
+ if (message.includes(GRANT_ACTIVE_ABORT)) return new GrantIssueRejectedError(message);
1332
+ if (message.includes("failed assert: unknown device entry") || isNotAuthorisedAbort(message)) return new NotAuthorisedError(message);
1333
+ return error;
1334
+ };
1335
+ /**
1336
+ * Refuses a device whose storage holds no account record before any
1337
+ * ceremony. The gate only runs a call over an account in state, so an
1338
+ * absent record means the storage was cleared underneath it.
1339
+ */
1340
+ const assertRecordPresent = async (accountRecords) => {
1341
+ if (await accountRecords.presence() === "absent") throw new AccountNotFoundError("No Passport account record is stored on this device.");
1342
+ };
1343
+ /**
1344
+ * The stored record of the account a grant call acts on, read inside the
1345
+ * session where it costs no extra prompt. Presence was checked ahead of
1346
+ * the session, so a missing record here vanished in between.
1347
+ */
1348
+ const storedRecord = async (accountRecords) => {
1349
+ const record = await accountRecords.read();
1350
+ if (!record) throw new AccountNotFoundError("No Passport account record is stored on this device.");
1351
+ return record;
1352
+ };
1353
+ /**
1354
+ * The ledger state once the indexer reflects the accepted call, with the
1355
+ * roster read from it. The submission settled in a block, but the
1356
+ * indexer can serve the state from before it for a moment, and a roster
1357
+ * read then would deny the call its own result.
1358
+ *
1359
+ * @throws {@link GrantRosterUnsettledError} when the indexer never
1360
+ * reflects the call within the polling window.
1361
+ */
1362
+ const awaitSettledRoster = async ({ indexer, address, slots, openings, isSettled }) => {
1363
+ for (let attempt = 0; attempt < ROSTER_POLL_ATTEMPTS; attempt++) {
1364
+ const ledgerState = await queryAccountLedger(indexer, address);
1365
+ const roster = readGrants(ledgerState, slots, openings);
1366
+ if (isSettled(roster)) return {
1367
+ ledgerState,
1368
+ roster
1369
+ };
1370
+ await sleep(ROSTER_POLL_DELAY_MS);
1371
+ }
1372
+ throw new GrantRosterUnsettledError(`The grant roster of ${address} never reflected the accepted call.`);
1373
+ };
1374
+ /**
1375
+ * Runs one gated grant call inside a single key session, so the use
1376
+ * counter rescan and the authorisation cost one ceremony rather than one
1377
+ * per authoriser call. A device whose storage holds no record is refused
1378
+ * ahead of the session. The record is read inside it, where it costs no
1379
+ * extra prompt, its grant bookkeeping narrowed to the grants whose kept
1380
+ * fields open what the ledger read before the call holds under their id,
1381
+ * so an entry an issue wrote before a call that never landed is neither
1382
+ * an opening nor a re-seal target. It is rewritten with the advanced
1383
+ * counter and the grant bookkeeping after every call, so a roster is
1384
+ * never published ahead of the record that anchors the next rescan and
1385
+ * names the slots. A call
1386
+ * that keeps its bookkeeping ahead of the submission writes it once more
1387
+ * before it, under the counter the record holds. A call that rotates the
1388
+ * encryption key does so in the same session ahead of its own circuit.
1389
+ * The other live read grants are sealed the new secret right after the
1390
+ * rotation lands, their seals kept in the record and on chain before the
1391
+ * call is submitted, so they keep reading whatever the call's outcome.
1392
+ * Once the roster shows an issued grant active, its bookkeeping is
1393
+ * appended to the inbox, sealed to this device alone, and the grantee of
1394
+ * a read grant is sealed the new secret, the seal kept the same way. The
1395
+ * wait for the indexer is reported as 'confirming' and the appends as
1396
+ * 'recording'. The contract's own aborts surface as typed errors;
1397
+ * anything else, and a failing on-chain status in particular, rejects
1398
+ * unchanged with the counter unmoved.
1399
+ */
1400
+ 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 } }) => {
1401
+ const { networkId } = seams.passportNetwork;
1402
+ const accountAddress = AccAddress(account.address);
1403
+ try {
1404
+ await assertRecordPresent(accountRecords);
1405
+ const rotationDevices = rotation ? liveDeviceEntries(ledgerState) : void 0;
1406
+ return await inKeySession(seams.passportAuthoriser, rotationDevices ? {
1407
+ ...flow,
1408
+ devices: rotationDevices
1409
+ } : flow, async () => {
1410
+ const record = await storedRecord(accountRecords);
1411
+ let stored = nextStoredGrants(await retainStoredGrants(record.grants, listed, account.address));
1412
+ const write = async (counter) => accountRecords.write(completedRecord(account, counter, { grants: stored }));
1413
+ if (writeBeforeCall) await write(record.localUseCounter);
1414
+ const chain = callChain({
1415
+ account,
1416
+ start: {
1417
+ ledgerState,
1418
+ localUseCounter,
1419
+ devices
1420
+ },
1421
+ indexer,
1422
+ seams,
1423
+ onProgress,
1424
+ onAdvanced: write
1425
+ });
1426
+ const counter = () => chain.position().localUseCounter ?? record.localUseCounter;
1427
+ const roster = (state) => readGrants(state, storedGrantSlots(stored), storedGrantOpenings(stored));
1428
+ let rotated;
1429
+ let unsealedGrantIds = [];
1430
+ let revocationPendingGrantIds = [];
1431
+ if (rotation) {
1432
+ rotated = await rotateEncKey({
1433
+ account,
1434
+ encryptionKey: seams.passportEncryptionKey,
1435
+ view: rotation,
1436
+ local: await readLocalDevice(seams),
1437
+ chain,
1438
+ indexer,
1439
+ networkId,
1440
+ onProgress,
1441
+ devices: rotationDevices ?? []
1442
+ });
1443
+ if (reseal) {
1444
+ const views = await sealViews({
1445
+ view: rotation,
1446
+ networkId,
1447
+ keyring: rotated.keyring,
1448
+ account: accountAddress,
1449
+ targets: liveStoredReadGrants(stored, roster(chain.position().ledgerState), reseal.except)
1450
+ });
1451
+ stored = withSealedViews(stored, views);
1452
+ unsealedGrantIds = views.unsealed;
1453
+ revocationPendingGrantIds = views.revocationPending;
1454
+ await write(counter());
1455
+ await chain.append("recording", views.entries);
1456
+ }
1457
+ }
1458
+ await chain.submit(call);
1459
+ onProgress("confirming");
1460
+ const settled = await awaitSettledRoster({
1461
+ indexer,
1462
+ address: account.address,
1463
+ slots: storedGrantSlots(stored),
1464
+ openings: storedGrantOpenings(stored),
1465
+ isSettled
1466
+ });
1467
+ let grants = settled.roster;
1468
+ if (issued) {
1469
+ const entries = await seams.passportEncryptionKey.sealGrant(networkId, accountAddress, issued.bookkeeping);
1470
+ if (rotation && rotated && issued.readPublicKey !== void 0) {
1471
+ const views = await sealViews({
1472
+ view: rotation,
1473
+ networkId,
1474
+ keyring: rotated.keyring,
1475
+ account: accountAddress,
1476
+ targets: [{
1477
+ grantId: issued.bookkeeping.grantId,
1478
+ readPublicKey: issued.readPublicKey
1479
+ }]
1480
+ });
1481
+ stored = withSealedViews(stored, views);
1482
+ unsealedGrantIds = [...unsealedGrantIds, ...views.unsealed];
1483
+ revocationPendingGrantIds = [...revocationPendingGrantIds, ...views.revocationPending];
1484
+ entries.push(...views.entries);
1485
+ await write(counter());
1486
+ grants = roster(settled.ledgerState);
1487
+ }
1488
+ await chain.append("recording", entries);
1489
+ }
1490
+ return {
1491
+ grants,
1492
+ devices: chain.position().devices,
1493
+ localUseCounter: counter(),
1494
+ ...rotated ? {
1495
+ encKey: HexBytes.fromByteArray(rotated.encKey),
1496
+ droppedDevices: rotated.dropped
1497
+ } : {},
1498
+ unsealedGrantIds,
1499
+ revocationPendingGrantIds
1500
+ };
1501
+ });
1502
+ } catch (error) {
1503
+ throw classifyContractAbort(error);
1504
+ }
1505
+ };
1506
+ /**
1507
+ * Refuses a grant its grantee could never spend: one naming a scheme
1508
+ * whose withdrawals the account was deployed without. Installing them
1509
+ * takes a maintenance update, which a locked account can no longer sign
1510
+ * and an unlocked one no longer holds the key for, so the issue is
1511
+ * refused before the owner is asked to authorise it.
1512
+ *
1513
+ * @throws {@link GrantScopeInvalidError} when a withdrawal of the
1514
+ * grantee's scheme is not installed on the account.
1515
+ */
1516
+ const requireGranteeWithdrawals = async (indexer, address, scheme) => {
1517
+ const installed = new Set(await queryAccountOperations(indexer, address));
1518
+ const missing = GRANTEE_WITHDRAWAL_CIRCUITS[scheme].filter((circuit) => !installed.has(circuit));
1519
+ if (missing.length > 0) throw new GrantScopeInvalidError(`the account cannot serve a ${scheme} grantee, it lacks ${missing.join(", ")}`);
1520
+ };
1521
+ /**
1522
+ * Issues a scoped grant to an agent key. The scope is checked against the
1523
+ * rules the contract asserts before any prompt: a shielded operation
1524
+ * needs read, a read grant needs a canonical read public key, a rolling
1525
+ * window is refused because the contract reserves its bounds, and a
1526
+ * grant beyond sixteen active ones is refused as Lace's limit. Each
1527
+ * refusal is a GrantScopeInvalidError or GrantLimitReachedError and costs
1528
+ * no ceremony; a host with no relying party id is refused with
1529
+ * GrantOriginMissingError before the chain is read, and a read grant
1530
+ * with ReadUnavailableError when the encryption key held here cannot
1531
+ * share the viewing secret. The grant id is derived from the account,
1532
+ * the grantee key, the hash of this host's relying party id and the
1533
+ * first slot free for that pair, and the scope salt is drawn fresh; the
1534
+ * local device then authorises `issue_grant_with_jubjub` over the id and
1535
+ * the salted scope digest, which binds the hash of the read key. The key
1536
+ * session is opened with the account, the slot, the salt and the digest
1537
+ * beside the id and the scope, so an authoriser that does not share this
1538
+ * flow's memory can re-derive both before it signs.
1539
+ *
1540
+ * A read grant delivers the account's viewing secret, and read is total:
1541
+ * the grantee sees every shielded holding, current and future, until the
1542
+ * key is rotated again. So the key is rotated first, in the same session:
1543
+ * a fresh random secret is sealed to every device, the live holdings are
1544
+ * re-encrypted towards it, its public key replaces `enc_key`, and only
1545
+ * then is the grant issued, so the grantee reads nothing of the
1546
+ * account's spent history. Right after the rotation lands the new secret
1547
+ * is sealed to every other live read grant this client holds the key of,
1548
+ * so they keep reading even should the issue fail, and once the grant
1549
+ * shows active it is sealed to the grantee's read key; the seals join
1550
+ * the bookkeeping, and the grantee's reaches it through the agent
1551
+ * policy, never the chain. A grantee seal the key seam refuses after the
1552
+ * grant landed leaves the grant active and unsealed, named among the
1553
+ * result's unsealed grants, rather than failing the issue.
1554
+ *
1555
+ * The slot and salt are kept in the account record, since the contract
1556
+ * stores neither, together with the object fields its commitment hides
1557
+ * (colour, recipient and coin bound) and the read key, which the grantee
1558
+ * needs to open it and which reach the roster as the grant's opening.
1559
+ * They are written before the call is submitted: a grant that lands
1560
+ * without its salt could never be opened for its grantee. A call that
1561
+ * never lands leaves a stale entry, which the next sign-in prunes against
1562
+ * the chain and a later issue over the same id overwrites. Once the
1563
+ * grant shows active the same bookkeeping, and each seal, is appended to
1564
+ * the inbox in grant records only this device opens, so a sign-in after
1565
+ * the record is lost rebuilds it. The roster is read back from chain
1566
+ * once the grant shows active in it.
1567
+ *
1568
+ * A grant id the contract still holds active rejects with
1569
+ * GrantIssueRejectedError, and a rejected authorisation with
1570
+ * NotAuthorisedError. The transaction's proving and sponsoring stages,
1571
+ * the rotation, the wait for the indexer and the appends are reported
1572
+ * through `onProgress`.
1573
+ */
1574
+ const issueGrant = async ({ scope, ...input }, context) => {
1575
+ const { rpId, seams } = context;
1576
+ if (rpId === void 0) throw new GrantOriginMissingError();
1577
+ const view = scope.read ? viewCapability(seams.passportEncryptionKey) : null;
1578
+ const { account } = input;
1579
+ const ledger = await readAccountLedger(account.address, seams.passportNetwork);
1580
+ await requireGranteeWithdrawals(ledger.indexer, account.address, scope.grantee.scheme);
1581
+ const roster = readGrants(ledger.ledgerState);
1582
+ validateGrantScope(scope, {
1583
+ nowSeconds: nowSeconds(),
1584
+ grantCount: activeCount(roster)
1585
+ });
1586
+ const { grantId, slot, scopeSalt, scopeDigest, call } = prepareIssueGrant({
1587
+ contractAddress: ByteArray.fromHex(HexBytes(account.address)),
1588
+ scope,
1589
+ originHash: await originHash(rpId),
1590
+ roster
1591
+ });
1592
+ const readPublicKey = view ? scope.readPublicKey : void 0;
1593
+ const object = {
1594
+ color: scope.color,
1595
+ recipient: scope.recipient,
1596
+ maxCoinValue: scope.maxCoinValue
1597
+ };
1598
+ return {
1599
+ grantId,
1600
+ ...await runGrantCall({
1601
+ config: {
1602
+ call,
1603
+ flow: {
1604
+ kind: "issue-grant",
1605
+ grantId,
1606
+ scope,
1607
+ account: AccAddress(account.address),
1608
+ slot,
1609
+ scopeSalt,
1610
+ scopeDigest
1611
+ },
1612
+ nextStoredGrants: (stored) => withStoredGrant(stored, grantId, {
1613
+ slot,
1614
+ scopeSalt,
1615
+ granteeScheme: scope.grantee.scheme,
1616
+ granteePublicKey: scope.grantee.publicKey,
1617
+ origin: rpId,
1618
+ object,
1619
+ ...readPublicKey === void 0 ? {} : { view: { readPublicKey } }
1620
+ }),
1621
+ writeBeforeCall: true,
1622
+ isSettled: (settled) => isActive(settled, grantId),
1623
+ ...view && readPublicKey !== void 0 ? {
1624
+ rotation: view,
1625
+ reseal: { except: grantId }
1626
+ } : {},
1627
+ issued: {
1628
+ bookkeeping: {
1629
+ grantId,
1630
+ slot,
1631
+ scopeSalt,
1632
+ granteeScheme: scope.grantee.scheme,
1633
+ granteePublicKey: scope.grantee.publicKey,
1634
+ object,
1635
+ ...readPublicKey === void 0 ? {} : { readPublicKey }
1636
+ },
1637
+ ...readPublicKey === void 0 ? {} : { readPublicKey }
1638
+ }
1639
+ },
1640
+ input,
1641
+ ledger,
1642
+ roster,
1643
+ context
1644
+ })
1645
+ };
1646
+ };
1647
+ /**
1648
+ * The stored grants with the seal of one grant dropped, its read key
1649
+ * kept: a revoked read grant's seal holds a secret the rotation that
1650
+ * follows retires.
1651
+ */
1652
+ const withoutSeal = (stored, grantId) => {
1653
+ const view = stored?.[grantId]?.view;
1654
+ return stored && view ? withStoredGrantView(stored, grantId, { readPublicKey: view.readPublicKey }) : stored;
1655
+ };
1656
+ /**
1657
+ * Revokes one grant by its id. A grant the chain does not hold is refused
1658
+ * with GrantNotFoundError before any prompt, and one it lists inactive
1659
+ * with GrantRevokedError; the same errors type the contract's own aborts
1660
+ * should the grant vanish or be revoked elsewhere in between. The local
1661
+ * device authorises `revoke_grant_with_jubjub`. The grant stays in the
1662
+ * roster as an inactive tombstone, so its stored slot and salt are kept,
1663
+ * and the roster is read back from chain once the grant shows inactive.
1664
+ *
1665
+ * Revoking a read grant also rotates the encryption key, in the same
1666
+ * session ahead of the revocation: a fresh random secret is sealed to
1667
+ * every device and the live holdings are re-encrypted towards it, so the
1668
+ * revoked grantee keeps what it already read and nothing newer, and
1669
+ * right after the rotation lands the new secret is sealed again to every
1670
+ * other read grant this client holds the read key of, ahead of the
1671
+ * revocation. A read grant is refused with ReadUnavailableError before
1672
+ * any prompt when the encryption key held here cannot re-encrypt and
1673
+ * seal.
1674
+ */
1675
+ const revokeGrant = async ({ grantId, ...input }, context) => {
1676
+ const { account } = input;
1677
+ const ledger = await readAccountLedger(account.address, context.seams.passportNetwork);
1678
+ const roster = readGrants(ledger.ledgerState);
1679
+ const listed = roster.find((record) => record.id === grantId);
1680
+ if (!listed) throw new GrantNotFoundError(`The account at ${account.address} holds no grant ${grantId}.`);
1681
+ if (!listed.active) throw new GrantRevokedError(`The grant ${grantId} of the account at ${account.address} is already revoked.`);
1682
+ const rotation = listed.scope.read ? viewCapability(context.seams.passportEncryptionKey) : void 0;
1683
+ return runGrantCall({
1684
+ config: {
1685
+ call: prepareRevokeGrant(grantId),
1686
+ flow: {
1687
+ kind: "revoke-grant",
1688
+ grantId,
1689
+ account: AccAddress(account.address),
1690
+ ...rotation ? { read: true } : {}
1691
+ },
1692
+ nextStoredGrants: (stored) => rotation ? withoutSeal(stored, grantId) : stored,
1693
+ writeBeforeCall: false,
1694
+ isSettled: (settled) => !isActive(settled, grantId),
1695
+ ...rotation ? {
1696
+ rotation,
1697
+ reseal: { except: grantId }
1698
+ } : {}
1699
+ },
1700
+ input,
1701
+ ledger,
1702
+ roster,
1703
+ context
1704
+ });
1705
+ };
1706
+ /**
1707
+ * Revokes every grant the account has issued: the local device
1708
+ * authorises `revoke_all_grants_with_jubjub`, which clears the grants
1709
+ * map and advances the grant generation. The record's grant bookkeeping
1710
+ * is dropped with the map, and the roster is read back from chain once
1711
+ * it lists nothing, tombstones included. While any read grant is live,
1712
+ * the encryption key is rotated in the same session ahead of the call
1713
+ * and the live holdings are re-encrypted, so no revoked grantee reads
1714
+ * on; with every grant gone there is nobody to re-seal to. The rotation
1715
+ * is refused with ReadUnavailableError before any prompt when the
1716
+ * encryption key held here cannot re-encrypt.
1717
+ */
1718
+ const revokeAllGrants = async (input, context) => {
1719
+ const { account } = input;
1720
+ const ledger = await readAccountLedger(account.address, context.seams.passportNetwork);
1721
+ const roster = readGrants(ledger.ledgerState);
1722
+ const rotation = roster.some((record) => record.active && record.scope.read) ? viewCapability(context.seams.passportEncryptionKey) : void 0;
1723
+ return runGrantCall({
1724
+ config: {
1725
+ call: prepareRevokeAllGrants(),
1726
+ flow: {
1727
+ kind: "revoke-all-grants",
1728
+ account: AccAddress(account.address),
1729
+ ...rotation ? { read: true } : {}
1730
+ },
1731
+ nextStoredGrants: () => void 0,
1732
+ writeBeforeCall: false,
1733
+ isSettled: (settled) => settled.length === 0,
1734
+ ...rotation ? { rotation } : {}
1735
+ },
1736
+ input,
1737
+ ledger,
1738
+ roster,
1739
+ context
1740
+ });
1741
+ };
1742
+ //#endregion
1743
+ //#region ../../packages/module/passport-account/src/flows/holdings.ts
1744
+ /**
1745
+ * Reads the account's shielded holdings from public chain data: the
1746
+ * contract's inbox is walked with the account secrets this device's own
1747
+ * envelopes deliver, the one deriving the ledger's `enc_key` first and
1748
+ * the older ones after it, so a coin a racing sender or an interrupted
1749
+ * rotation left under an earlier key is still found, and each coin that
1750
+ * opens is kept only once its commitment is found among the outputs the
1751
+ * chain created for the account, with the tree index it took. The
1752
+ * envelopes are opened inside one key session, so the walk costs one
1753
+ * ceremony however many entries the inbox holds, and none at all when
1754
+ * it holds no coin to open; only the opened coin descriptions reach this
1755
+ * flow, never a secret. Nothing is written: no record, no chain call.
1756
+ *
1757
+ * A record whose address holds no live contract rejects with
1758
+ * AccountContractMissingError, and an inbox holding no envelope of this
1759
+ * device that opens the ledger's `enc_key` with EncryptionKeyMismatchError
1760
+ * rather than an inbox read as empty. An entry that fails to open or
1761
+ * describes a coin the chain never created is skipped and counted, never
1762
+ * an error; the account keys and grant bookkeeping the inbox also holds
1763
+ * are not coins and are not counted.
1764
+ *
1765
+ * Reports no intermediate stage: the ceremony and the indexer reads all
1766
+ * settle before there is anything to report.
1767
+ */
1768
+ const readShieldedHoldings = async ({ account }, { seams }) => {
1769
+ const { passportAuthoriser, passportEncryptionKey, passportNetwork } = seams;
1770
+ const indexer = createIndexerClient({
1771
+ indexerUrl: passportNetwork.indexerUrl,
1772
+ indexerWsUrl: passportNetwork.indexerWsUrl
1773
+ });
1774
+ const ledgerState = await queryAccountLedger(indexer, account.address);
1775
+ const { holdings, skippedEntries } = await walkInbox({
1776
+ address: account.address,
1777
+ ledgerState,
1778
+ indexer,
1779
+ openEntries: async (entries) => inKeySession(passportAuthoriser, { kind: "read-holdings" }, async () => {
1780
+ const { keyring } = readAccountInbox(account.address, ledgerState, await passportEncryptionKey.readerPublicKey(passportNetwork.networkId));
1781
+ return (await passportEncryptionKey.openInbox(passportNetwork.networkId, keyring, entries)).map((entry) => entry?.kind === "coin" ? entry.coin : null);
1782
+ })
1783
+ });
1784
+ return {
1785
+ holdings,
1786
+ skippedEntries
1787
+ };
1788
+ };
1789
+ //#endregion
1790
+ //#region ../../packages/module/passport-account/src/flows/sign-in.ts
1791
+ /**
1792
+ * The account's whole device roster, read from the on-chain device set.
1793
+ * Entries are opaque rolling commitments, so a remote entry carries no
1794
+ * identity beyond its commitment: only the local device can be named, by
1795
+ * the commitment its own rescan resolved.
1796
+ */
1797
+ const toDeviceRoster = (entries, localCommitmentHex) => Array.from(entries, (entry) => {
1798
+ const commitmentHex = HexBytes.fromByteArray(entry);
1799
+ return {
1800
+ commitmentHex,
1801
+ isLocal: commitmentHex === localCommitmentHex
1802
+ };
1803
+ });
1804
+ /**
1805
+ * Refuses a record whose creation is still unfinished on chain. A record
1806
+ * that carries a pending deployment names a contract that may still miss
1807
+ * verifier keys, its initial device or the entries that deliver the
1808
+ * account keys, which only the create flow can complete; but a creation
1809
+ * that appended its key entries and then died before its final record
1810
+ * write left a usable account behind, and the chain's boot flag and inbox
1811
+ * tell the two apart.
1812
+ */
1813
+ const assertCreationComplete = (record, isActivated, entries) => {
1814
+ const { deployment } = record;
1815
+ if (deployment === void 0) return;
1816
+ const held = new Set(entries.map((entry) => HexBytes.fromByteArray(entry)));
1817
+ 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.`);
1818
+ };
1819
+ /** The grant record parts the Lace records of an inbox opened to. */
1820
+ const grantPartsOf = (opened) => opened.flatMap((entry) => entry?.kind === "grant" ? [entry.record] : []);
1821
+ /**
1822
+ * Recognises an existing Passport account on this device: the passkey
1823
+ * ceremony (implicit in the first authoriser use) proves the device key,
1824
+ * the persisted account record names the Account Custody Contract, the
1825
+ * indexer confirms the contract is live, this device's own envelopes in
1826
+ * the contract's inbox open a secret deriving the `enc_key` the contract
1827
+ * advertises, and the use-counter rescan restores this device's roster
1828
+ * position from the on-chain device set. The account secret is never
1829
+ * read from the record or derived from the passkey: it is random, and
1830
+ * this device reaches it only through an envelope sealed to its reader
1831
+ * key, so a device enrolled with its own passkey signs in without the
1832
+ * record of the device that created the account. The roster is rebuilt
1833
+ * from every entry in the device set, so a device enrolled elsewhere
1834
+ * survives a reload; only the local entry is named, the rest are opaque
1835
+ * commitments. The grant roster is read from the contract's grants map
1836
+ * the same way, with the slots and openings the record kept for the
1837
+ * grants this client issued; a grant the record lacks, as after the
1838
+ * record was lost, is rebuilt from the grant records this device keeps in
1839
+ * the inbox once they open its on-chain commitments under this host's
1840
+ * relying party id, its seal kept only while it holds the live secret.
1841
+ * A grant the record holds is kept only while its fields open the
1842
+ * commitments the chain holds under its id, so an entry an issue wrote
1843
+ * before a call that never landed gives way to the grant another client
1844
+ * of the account issued over the same id, and a rebuilt grant takes its
1845
+ * place when there is one. The live read grants whose kept seal does not
1846
+ * hold the live secret, as after an issue that failed before its seal,
1847
+ * are reported as unsealed.
1848
+ * The devices registered under the live roster key are kept in the
1849
+ * record as the roster the next rotation seals to. The whole chain runs
1850
+ * inside one key session, so it costs a single ceremony rather than one
1851
+ * per authoriser call.
1852
+ *
1853
+ * The healed counter is written back to the persisted record before this
1854
+ * resolves, so the next sign-in rescans from a fresh anchor instead of the
1855
+ * creation-time one. That write also completes a record a creation left
1856
+ * pending after its key entries landed, dropping the deployment and the
1857
+ * authority key it carries, and drops the bookkeeping of grants the chain
1858
+ * no longer holds or whose commitments it does not open. A missing record
1859
+ * raises AccountNotFoundError, a record whose address holds no live
1860
+ * contract raises AccountContractMissingError,
1861
+ * a record whose creation is unfinished on chain raises
1862
+ * AccountCreationPendingError, and an inbox holding no envelope of this
1863
+ * device that opens the live `enc_key`, as for a device never handed the
1864
+ * keys or removed since, raises EncryptionKeyMismatchError before the
1865
+ * rescan runs; rediscovering an account by name service when no record is
1866
+ * persisted is a separate flow and out of scope here.
1867
+ *
1868
+ * signIn reports no intermediate stage: the ceremony, the indexer read and
1869
+ * the rescan all settle before there is anything to report.
1870
+ */
1871
+ const signIn = async ({ seams, accountRecords, rpId }) => {
1872
+ const { passportAuthoriser, passportEncryptionKey, passportNetwork } = seams;
1873
+ return inKeySession(passportAuthoriser, { kind: "sign-in" }, async () => {
1874
+ const local = await readLocalDevice(seams);
1875
+ const record = await accountRecords.read();
1876
+ if (!record) throw new AccountNotFoundError("No Passport account record is stored on this device.");
1877
+ const state = await createIndexerClient({
1878
+ indexerUrl: passportNetwork.indexerUrl,
1879
+ indexerWsUrl: passportNetwork.indexerWsUrl
1880
+ }).queryContractState(record.address);
1881
+ if (!state) throw new AccountContractMissingError(`No live Account Custody Contract found at ${record.address}.`);
1882
+ const ledgerState = ledger(state.data);
1883
+ const { entries, keyring } = readAccountInbox(record.address, ledgerState, local.readerPublicKey);
1884
+ assertCreationComplete(record, ledgerState.booted, entries);
1885
+ if (keyring.envelopes.length === 0) throw new EncryptionKeyMismatchError(`The inbox of the account at ${record.address} holds no envelope for this device.`);
1886
+ const grantParts = grantPartsOf(await passportEncryptionKey.openInbox(passportNetwork.networkId, keyring, entries.filter(isLaceRecord)));
1887
+ const { useCounter, commitmentHex } = await resolveUseCounter({
1888
+ ledgerState,
1889
+ authoriser: passportAuthoriser,
1890
+ address: AccAddress(record.address),
1891
+ knownUseCounter: UseCounter(BigInt(record.localUseCounter))
1892
+ });
1893
+ const devices = toDeviceRoster(ledgerState.devices, commitmentHex);
1894
+ const encKey = HexBytes.fromByteArray(ledgerState.enc_key);
1895
+ const onChain = readGrants(ledgerState);
1896
+ const stored = withRebuiltGrants(await retainStoredGrants(record.grants, onChain, record.address), rpId === void 0 ? void 0 : await rebuildStoredGrants(grantParts, onChain, {
1897
+ address: record.address,
1898
+ origin: rpId,
1899
+ encKey
1900
+ }), encKey);
1901
+ const grants = readGrants(ledgerState, storedGrantSlots(stored), storedGrantOpenings(stored));
1902
+ const localUseCounter = useCounter.toString();
1903
+ await accountRecords.write(completedRecord(record, localUseCounter, { grants: stored }));
1904
+ return {
1905
+ account: {
1906
+ address: record.address,
1907
+ bindingVersion: record.bindingVersion,
1908
+ status: "ready",
1909
+ networkId: passportNetwork.networkId
1910
+ },
1911
+ devices,
1912
+ localUseCounter,
1913
+ grants,
1914
+ encKey,
1915
+ unsealedGrantIds: unsealedStoredReadGrants(stored, onChain, encKey)
1916
+ };
1917
+ });
1918
+ };
1919
+ //#endregion
1920
+ //#region ../../packages/module/passport-account/src/store/dependencies.ts
1921
+ /**
1922
+ * Runs a flow as a cold stream of its events. `run` is invoked once per
1923
+ * subscription with a progress sink that emits synchronously as the flow
1924
+ * reports; the resolution emits 'done' and completes, and a rejection
1925
+ * errors the stream. Unsubscribing only stops delivery: the running
1926
+ * promise is not cancelled, because a flow must run to completion once
1927
+ * started (abandoning it mid-deploy could orphan a sponsored contract).
1928
+ */
1929
+ const observeFlow = (run) => new Observable((subscriber) => {
1930
+ let isDelivering = true;
1931
+ run((stage) => {
1932
+ if (isDelivering) subscriber.next({
1933
+ type: "progress",
1934
+ stage
1935
+ });
1936
+ }).then((result) => {
1937
+ if (!isDelivering) return;
1938
+ subscriber.next({
1939
+ type: "done",
1940
+ result
1941
+ });
1942
+ subscriber.complete();
1943
+ }, (error) => {
1944
+ if (isDelivering) subscriber.error(error);
1945
+ });
1946
+ return () => {
1947
+ isDelivering = false;
1948
+ };
1949
+ });
1950
+ /**
1951
+ * The context a flow runs under, drawn from the side-effect dependency
1952
+ * bag: the five seams, the record store and the relying party id. An
1953
+ * injected store is used as is; otherwise the store is built over the
1954
+ * platform storage and keyed by the authoriser, so a record sealed by one
1955
+ * authoriser is only ever written through it. The sealed-record options
1956
+ * apply to that built store; signIn and the grant flows pass
1957
+ * `onSealedWithoutKey: 'error'` so a sealed record found without a
1958
+ * storage key surfaces as record-unreadable rather than as an absent
1959
+ * account.
1960
+ */
1961
+ const toFlowContext = ({ createKeyValueStorage, passportAuthoriser, passportEncryptionKey, passportNetwork, passportProver, passportSponsor }, onProgress, { store, rpId, ...recordOptions }) => ({
1962
+ seams: {
1963
+ passportAuthoriser,
1964
+ passportEncryptionKey,
1965
+ passportNetwork,
1966
+ passportProver,
1967
+ passportSponsor
1968
+ },
1969
+ accountRecords: toAccountRecords(store ?? createAccountRecordStore(createKeyValueStorage, passportAuthoriser.storageKey, recordOptions)),
1970
+ onProgress,
1971
+ rpId
1972
+ });
1973
+ /**
1974
+ * Maps the platform capabilities passed to `createPassportAccountModule`
1975
+ * onto the `passport-dependency` contract, and exposes the platform-neutral
1976
+ * flows observable-based. The flows are promise functions; wrapping them
1977
+ * here rather than in the side effects is what keeps promise handling out
1978
+ * of the side effects, so they compose the flows as plain streams and stay
1979
+ * testable on a virtual scheduler. The relying party id defaults to the
1980
+ * page's hostname, as the passkey ceremony's does.
1981
+ */
1982
+ const createDependencies = ({ authoriser, encryptionKey, sponsor, prover, network, accountRecordStore, rpId = globalThis.location?.hostname }) => {
1983
+ const host = {
1984
+ store: accountRecordStore,
1985
+ rpId
1986
+ };
1987
+ const recordRequired = {
1988
+ ...host,
1989
+ onSealedWithoutKey: "error"
1990
+ };
1991
+ return {
1992
+ passportAuthoriser: authoriser,
1993
+ passportEncryptionKey: encryptionKey,
1994
+ passportSponsor: sponsor,
1995
+ passportProver: prover,
1996
+ passportNetwork: network,
1997
+ passportFlows: {
1998
+ createAccount: (input, dependencies) => observeFlow(async (onProgress) => createAccount(input, toFlowContext(dependencies, onProgress, host))),
1999
+ signIn: (dependencies) => observeFlow(async (onProgress) => signIn(toFlowContext(dependencies, onProgress, recordRequired))),
2000
+ addDevice: (input, dependencies) => observeFlow(async (onProgress) => addDevice(input, toFlowContext(dependencies, onProgress, host))),
2001
+ removeDevice: (input, dependencies) => observeFlow(async (onProgress) => removeDevice(input, toFlowContext(dependencies, onProgress, host))),
2002
+ issueGrant: (input, dependencies) => observeFlow(async (onProgress) => issueGrant(input, toFlowContext(dependencies, onProgress, recordRequired))),
2003
+ revokeGrant: (input, dependencies) => observeFlow(async (onProgress) => revokeGrant(input, toFlowContext(dependencies, onProgress, recordRequired))),
2004
+ revokeAllGrants: (input, dependencies) => observeFlow(async (onProgress) => revokeAllGrants(input, toFlowContext(dependencies, onProgress, recordRequired))),
2005
+ readShieldedHoldings: (input, dependencies) => observeFlow(async (onProgress) => readShieldedHoldings(input, toFlowContext(dependencies, onProgress, host)))
2006
+ }
2007
+ };
2008
+ };
2009
+ //#endregion
2010
+ //#region ../../packages/module/passport-account/src/store/side-effects/flow-actions.ts
2011
+ /**
2012
+ * The flow error a failure reports: the error's own typed code when it
2013
+ * carries one, otherwise the flow's fallback code.
2014
+ */
2015
+ const toFlowError = (error, fallbackCode) => ({
2016
+ code: error instanceof Object && "code" in error && typeof error.code === "string" ? error.code : fallbackCode,
2017
+ message: error instanceof Error ? error.message : String(error)
2018
+ });
2019
+ /**
2020
+ * Maps a flow's events onto the passport flow state: each stage to
2021
+ * setFlow, the result to its publishing actions followed by
2022
+ * setFlow('ready'), and a failure to its `onFailed` actions followed by
2023
+ * a single setFlowError, so a flow always settles in 'ready' or 'error'.
2024
+ */
2025
+ 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)))));
2026
+ //#endregion
2027
+ //#region ../../packages/module/passport-account/src/store/side-effects/passport-flows.ts
2028
+ /** Flow error code for creation failures that carry no typed code of their own. */
2029
+ const CREATE_ACCOUNT_FALLBACK_ERROR_CODE = "account-create-failed";
2030
+ /** Flow error code for sign-in failures that carry no typed code of their own. */
2031
+ const SIGN_IN_FALLBACK_ERROR_CODE = "account-sign-in-failed";
2032
+ /** Flow error codes for device call failures that carry no typed code of their own. */
2033
+ const ADD_DEVICE_FALLBACK_ERROR_CODE = "device-add-failed";
2034
+ const REMOVE_DEVICE_FALLBACK_ERROR_CODE = "device-remove-failed";
2035
+ /** Flow error codes for grant call failures that carry no typed code of their own. */
2036
+ const ISSUE_GRANT_FALLBACK_ERROR_CODE = "grant-issue-failed";
2037
+ const REVOKE_GRANT_FALLBACK_ERROR_CODE = "grant-revoke-failed";
2038
+ const REVOKE_ALL_GRANTS_FALLBACK_ERROR_CODE = "grant-revoke-all-failed";
2039
+ /** Flow error code for holdings reads that carry no typed code of their own. */
2040
+ const READ_HOLDINGS_FALLBACK_ERROR_CODE = "holdings-read-failed";
2041
+ /**
2042
+ * Flows an account call may start from. 'error' is a settled state, not
2043
+ * an operation in progress, so a call that failed can be retried without
2044
+ * a fresh sign-in ceremony; every other non-ready flow is an operation
2045
+ * left unfinished, whose account and use counter cannot be trusted yet.
2046
+ */
2047
+ const SETTLED_FLOWS = ["error", "ready"];
2048
+ /**
2049
+ * The actions that publish a roster a flow left behind: the devices, then
2050
+ * the counter the local row sits at. Both land ahead of 'ready', in the
2051
+ * order the flows have always published them.
2052
+ */
2053
+ const publishDeviceRoster = (actions) => ({ devices, localUseCounter }) => [actions.passport.setDevices(devices), actions.passport.setLocalUseCounter(localUseCounter)];
2054
+ /**
2055
+ * The actions that publish what a grant call left behind: the device
2056
+ * roster and counter it advanced, the `enc_key` a rotation it ran stepped
2057
+ * the encryption key to and the devices it left without the new key, the
2058
+ * grant roster, then the read grants the
2059
+ * call could not seal the viewing secret to, empty when it sealed all,
2060
+ * and those the signer refused because their revocation is pending.
2061
+ */
2062
+ const publishGrantRoster = (actions) => ({ grants, encKey, unsealedGrantIds, revocationPendingGrantIds, droppedDevices, ...roster }) => [
2063
+ ...publishDeviceRoster(actions)(roster),
2064
+ ...encKey === void 0 ? [] : [actions.passport.setEncKey(encKey)],
2065
+ ...droppedDevices === void 0 ? [] : [actions.passport.setDroppedDevices(droppedDevices)],
2066
+ actions.passport.setGrants(grants),
2067
+ actions.passport.setUnsealedGrantIds(unsealedGrantIds),
2068
+ actions.passport.setRevocationPendingGrantIds(revocationPendingGrantIds)
2069
+ ];
2070
+ /**
2071
+ * The actions that publish an issued grant: the rosters, then the id of
2072
+ * the grant, last so a consumer reacting to it finds the record in state.
2073
+ */
2074
+ const publishIssuedGrant = (actions) => ({ grantId, ...roster }) => [...publishGrantRoster(actions)(roster), actions.passport.setLastIssuedGrantId(grantId)];
2075
+ /**
2076
+ * The actions that publish an account a flow left ready: the account,
2077
+ * its device roster and counter, the `enc_key` its encryption key is
2078
+ * at, then its grant roster.
2079
+ */
2080
+ const publishAccountState = (actions) => ({ account, grants, encKey, ...roster }) => [
2081
+ actions.passport.setAccount(account),
2082
+ ...publishDeviceRoster(actions)(roster),
2083
+ actions.passport.setEncKey(encKey),
2084
+ actions.passport.setGrants(grants)
2085
+ ];
2086
+ /**
2087
+ * The actions that publish an account a sign-in recognised: the account
2088
+ * state, see {@link publishAccountState}, then the read grants whose kept
2089
+ * seal does not hold the live viewing secret, and no grants pending a
2090
+ * revocation, which only a grant call learns from the signer.
2091
+ */
2092
+ const publishRecognisedAccount = (actions) => ({ unsealedGrantIds, ...state }) => [
2093
+ ...publishAccountState(actions)(state),
2094
+ actions.passport.setUnsealedGrantIds(unsealedGrantIds),
2095
+ actions.passport.setRevocationPendingGrantIds([])
2096
+ ];
2097
+ /**
2098
+ * A device or grant call may rotate the account keys before it fails, so
2099
+ * the `enc_key` state holds may be the one rotated away: it is forgotten
2100
+ * until the next sign-in or rotation publishes it again, rather than let
2101
+ * a stale seal pass as current. The read grants an earlier call reported
2102
+ * unsealed or pending revocation were judged against that key, so they
2103
+ * are emptied with it.
2104
+ */
2105
+ const forgetKeyState = (actions) => [
2106
+ actions.passport.clearEncKey(),
2107
+ actions.passport.setUnsealedGrantIds([]),
2108
+ actions.passport.setRevocationPendingGrantIds([])
2109
+ ];
2110
+ /**
2111
+ * The createAccount flow behind the createAccount action, as the actions it
2112
+ * publishes: each reported stage as setFlow, then the created account, its
2113
+ * one-device roster, this device's counter and its empty grant roster,
2114
+ * then 'ready'. The flow itself persists the account record before it
2115
+ * resolves, so the account is never published ahead of the record that
2116
+ * recognises it.
2117
+ */
2118
+ const runCreateAccount = (input, dependencies) => {
2119
+ const { actions, passportFlows } = dependencies;
2120
+ return flowActions(passportFlows.createAccount(input, dependencies), {
2121
+ actions,
2122
+ fallbackCode: CREATE_ACCOUNT_FALLBACK_ERROR_CODE,
2123
+ onDone: publishAccountState(actions)
2124
+ });
2125
+ };
2126
+ /**
2127
+ * The signIn flow behind the signIn action, as the actions it publishes:
2128
+ * the recognised account, its whole device roster, this device's healed
2129
+ * use counter, the grant roster and its unsealed read grants, then
2130
+ * 'ready'. The flow itself persists the healed counter before it
2131
+ * resolves, so the record is never left behind the state it publishes.
2132
+ */
2133
+ const runSignIn = (dependencies) => {
2134
+ const { actions, passportFlows } = dependencies;
2135
+ return flowActions(passportFlows.signIn(dependencies), {
2136
+ actions,
2137
+ fallbackCode: SIGN_IN_FALLBACK_ERROR_CODE,
2138
+ onDone: publishRecognisedAccount(actions)
2139
+ });
2140
+ };
2141
+ /**
2142
+ * The actions that publish what a device call left behind: its roster and
2143
+ * counter, then, when it rotated the account keys, the `enc_key` it
2144
+ * stepped to and the devices it left without the new key.
2145
+ */
2146
+ const publishDeviceCall = (actions) => ({ encKey, droppedDevices, ...roster }) => [
2147
+ ...publishDeviceRoster(actions)(roster),
2148
+ ...encKey === void 0 ? [] : [actions.passport.setEncKey(encKey)],
2149
+ ...droppedDevices === void 0 ? [] : [actions.passport.setDroppedDevices(droppedDevices)]
2150
+ ];
2151
+ /**
2152
+ * The addDevice flow behind its action: what the call left behind, see
2153
+ * {@link publishDeviceCall}, then 'ready'. The joining device's keys
2154
+ * travel with the request when the action names them.
2155
+ */
2156
+ const addDeviceCall = {
2157
+ start: ({ commitmentHex, reader }, input, dependencies) => dependencies.passportFlows.addDevice({
2158
+ commitmentHex,
2159
+ ...reader ? { reader } : {},
2160
+ ...input
2161
+ }, dependencies),
2162
+ onDone: publishDeviceCall,
2163
+ fallbackCode: ADD_DEVICE_FALLBACK_ERROR_CODE,
2164
+ onFailed: forgetKeyState
2165
+ };
2166
+ /**
2167
+ * The removeDevice flow behind its action: what the call left behind, see
2168
+ * {@link publishDeviceCall}, then 'ready'.
2169
+ */
2170
+ const removeDeviceCall = {
2171
+ start: ({ commitmentHex }, input, dependencies) => dependencies.passportFlows.removeDevice({
2172
+ commitmentHex,
2173
+ ...input
2174
+ }, dependencies),
2175
+ onDone: publishDeviceCall,
2176
+ fallbackCode: REMOVE_DEVICE_FALLBACK_ERROR_CODE,
2177
+ onFailed: forgetKeyState
2178
+ };
2179
+ /**
2180
+ * The issueGrant flow behind its action: the rosters the call left
2181
+ * behind and the issued grant's id, then 'ready'.
2182
+ */
2183
+ const issueGrantCall = {
2184
+ start: (scope, input, dependencies) => dependencies.passportFlows.issueGrant({
2185
+ scope,
2186
+ ...input
2187
+ }, dependencies),
2188
+ onDone: publishIssuedGrant,
2189
+ fallbackCode: ISSUE_GRANT_FALLBACK_ERROR_CODE,
2190
+ onFailed: forgetKeyState
2191
+ };
2192
+ /** The revokeGrant flow behind its action: the rosters it left behind, then 'ready'. */
2193
+ const revokeGrantCall = {
2194
+ start: ({ grantId }, input, dependencies) => dependencies.passportFlows.revokeGrant({
2195
+ grantId,
2196
+ ...input
2197
+ }, dependencies),
2198
+ onDone: publishGrantRoster,
2199
+ fallbackCode: REVOKE_GRANT_FALLBACK_ERROR_CODE,
2200
+ onFailed: forgetKeyState
2201
+ };
2202
+ /** The revokeAllGrants flow behind its action: the rosters it left behind, then 'ready'. */
2203
+ const revokeAllGrantsCall = {
2204
+ start: (_payload, input, dependencies) => dependencies.passportFlows.revokeAllGrants(input, dependencies),
2205
+ onDone: publishGrantRoster,
2206
+ fallbackCode: REVOKE_ALL_GRANTS_FALLBACK_ERROR_CODE,
2207
+ onFailed: forgetKeyState
2208
+ };
2209
+ /**
2210
+ * The readShieldedHoldings flow behind its action: the holdings the walk
2211
+ * verified, then 'ready'. The skip count is the flow's to report, not the
2212
+ * store's to keep: a skipped entry is noise the inbox will carry forever.
2213
+ */
2214
+ const readShieldedHoldingsCall = {
2215
+ start: (_payload, input, dependencies) => dependencies.passportFlows.readShieldedHoldings(input, dependencies),
2216
+ onDone: (actions) => ({ holdings }) => [actions.passport.setShieldedHoldings(holdings)],
2217
+ fallbackCode: READ_HOLDINGS_FALLBACK_ERROR_CODE
2218
+ };
2219
+ /**
2220
+ * An account call behind its action, as the actions it publishes: what
2221
+ * the call left behind, then 'ready', or, when it fails, the actions
2222
+ * undoing what state may wrongly claim, then the error. The flow itself
2223
+ * persists the counter before it resolves.
2224
+ *
2225
+ * Requires an account and a settled flow: with no account in state, or
2226
+ * with an operation left unfinished, the flow is never called (so the
2227
+ * chain and the key session are never touched) and the call settles in
2228
+ * 'error' with 'no-account'. The refusal still runs behind the gate, so
2229
+ * it enters 'ceremony' first like any accepted request and clears the
2230
+ * error a previous flow left behind.
2231
+ */
2232
+ const runAccountCall = ({ start, onDone, fallbackCode, onFailed }, { payload, flow, account, devices, localUseCounter }, dependencies) => {
2233
+ const { actions } = dependencies;
2234
+ if (!account || !SETTLED_FLOWS.includes(flow)) return of(actions.passport.setFlowError(toFlowError(new NoAccountError(), fallbackCode)));
2235
+ return flowActions(start(payload, {
2236
+ account,
2237
+ devices,
2238
+ localUseCounter
2239
+ }, dependencies), {
2240
+ actions,
2241
+ fallbackCode,
2242
+ onDone: onDone(actions),
2243
+ ...onFailed ? { onFailed: onFailed(actions) } : {}
2244
+ });
2245
+ };
2246
+ /**
2247
+ * One start per dispatched account call action, each carrying the state
2248
+ * the call needs. State is sampled when the action arrives rather than
2249
+ * when the shared gate starts the call, so a call reads the account,
2250
+ * roster and counter the user acted on.
2251
+ */
2252
+ 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, {
2253
+ payload,
2254
+ flow,
2255
+ account,
2256
+ devices,
2257
+ localUseCounter
2258
+ }, dependencies)));
2259
+ /**
2260
+ * Runs whichever passport flow was requested: {@link runCreateAccount}
2261
+ * behind the createAccount action, {@link runSignIn} behind signIn, and
2262
+ * {@link runAccountCall} behind addDevice, removeDevice, issueGrant,
2263
+ * revokeGrant, revokeAllGrants and readShieldedHoldings.
2264
+ *
2265
+ * Every flow owns the same account record, the same device key and the
2266
+ * same flow state, and each chain call resolves the account's use counter
2267
+ * and auth nonce, so they must never overlap: two calls resolving the same
2268
+ * counter both spend the same entry, one transaction is rejected, and the
2269
+ * loser reports its own failure over state the winner already moved on.
2270
+ * A holdings read spends no entry, but it opens the same key session and
2271
+ * reports through the same flow state, so it runs behind the same gate.
2272
+ * One exhaustMap over the merged starts, rather than one per action,
2273
+ * makes them mutually exclusive: a dispatch arriving while any flow is in
2274
+ * flight emits nothing at all, and the next one is only accepted once the
2275
+ * running flow settles. Dropping it silently is the stance exhaustMap
2276
+ * already took for a repeated dispatch of one action; a flow the user
2277
+ * never saw start is not a failure to report.
2278
+ *
2279
+ * Because only the gate knows which requests it accepted, it also owns
2280
+ * the entry into 'ceremony': the trigger reducers are pure, so a dropped
2281
+ * request cannot overwrite the running flow's state, and setFlow clears
2282
+ * the error a previous flow left behind. The emission is synchronous on
2283
+ * the accepted start, so a consumer sees the ceremony within the same
2284
+ * dispatch cycle as the trigger.
2285
+ *
2286
+ * The flow state cannot carry this guard the other way round: state
2287
+ * reaches a side effect before the action does, and an inner flow is
2288
+ * still subscribed while its own terminal setFlow('ready') is delivered,
2289
+ * so a reducer reading the flow back cannot tell a request the gate will
2290
+ * accept from one it will drop.
2291
+ */
2292
+ const runPassportFlow = ({ passport: { addDevice$, createAccount$, issueGrant$, readShieldedHoldings$, removeDevice$, revokeAllGrants$, revokeGrant$, signIn$ } }, stateObservables, dependencies) => merge(createAccount$.pipe(map(({ payload }) => () => runCreateAccount(payload, dependencies))), signIn$.pipe(map(() => () => runSignIn(dependencies))), accountCallStarts({
2293
+ config: addDeviceCall,
2294
+ trigger$: addDevice$,
2295
+ stateObservables,
2296
+ dependencies
2297
+ }), accountCallStarts({
2298
+ config: removeDeviceCall,
2299
+ trigger$: removeDevice$,
2300
+ stateObservables,
2301
+ dependencies
2302
+ }), accountCallStarts({
2303
+ config: issueGrantCall,
2304
+ trigger$: issueGrant$,
2305
+ stateObservables,
2306
+ dependencies
2307
+ }), accountCallStarts({
2308
+ config: revokeGrantCall,
2309
+ trigger$: revokeGrant$,
2310
+ stateObservables,
2311
+ dependencies
2312
+ }), accountCallStarts({
2313
+ config: revokeAllGrantsCall,
2314
+ trigger$: revokeAllGrants$,
2315
+ stateObservables,
2316
+ dependencies
2317
+ }), accountCallStarts({
2318
+ config: readShieldedHoldingsCall,
2319
+ trigger$: readShieldedHoldings$,
2320
+ stateObservables,
2321
+ dependencies
2322
+ })).pipe(exhaustMap((start) => concat(of(dependencies.actions.passport.setFlow("ceremony")), start())));
2323
+ //#endregion
2324
+ //#region ../../packages/module/passport-account/src/store/side-effects/restore-account.ts
2325
+ /** Whether a stored record names an activated account rather than a deployment in progress. */
2326
+ const isActivatedRecord = (record) => record !== void 0 && record.deployment === void 0;
2327
+ /**
2328
+ * The grant roster of the restored account, read from chain with the
2329
+ * slots the record kept. The read needs no ceremony, but it does need
2330
+ * the indexer: a contract it does not serve, or a read it fails, leaves
2331
+ * the roster empty rather than failing the restore, and the next sign-in
2332
+ * or grant call reads it again.
2333
+ */
2334
+ const restoreGrants = (record, { indexerUrl, indexerWsUrl }, actions) => defer(async () => createIndexerClient({
2335
+ indexerUrl,
2336
+ indexerWsUrl
2337
+ }).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));
2338
+ /**
2339
+ * Rehydrates the persisted account record into the store on startup, so a
2340
+ * returning user's account is recognised without a new passkey ceremony.
2341
+ * Only a record whose activation succeeded is restored, hence status
2342
+ * 'ready'; a record still carrying a pending deployment names no usable
2343
+ * account and is left for the create flow to resume, or for sign-in to
2344
+ * complete once the chain shows it activated. The device set is not
2345
+ * persisted and is rebuilt from chain by the device-management flows; the
2346
+ * grant roster is read from chain here, once the account is published,
2347
+ * so a consumer lists grants without a ceremony. A record sealed by a
2348
+ * passkey authoriser cannot be opened without a ceremony, and a ceremony
2349
+ * cannot run without a user gesture, so no storage key is passed here: a
2350
+ * sealed record reads as absent and the sign-in flow recognises the
2351
+ * account instead.
2352
+ */
2353
+ const restorePassportAccount = (_actionObservables, _stateObservables, { actions, createKeyValueStorage, passportNetwork }) => createAccountRecordStore(createKeyValueStorage).read().pipe(filter(isActivatedRecord), mergeMap((record) => concat(of(actions.passport.setAccount({
2354
+ address: record.address,
2355
+ bindingVersion: record.bindingVersion,
2356
+ status: "ready",
2357
+ networkId: passportNetwork.networkId
2358
+ }), actions.passport.setLocalUseCounter(record.localUseCounter)), restoreGrants(record, passportNetwork, actions))));
2359
+ //#endregion
2360
+ //#region ../../packages/module/passport-account/src/store/init.ts
2361
+ /**
2362
+ * Builds the passport-account module's store initializer for the given
2363
+ * platform capabilities: the mutually exclusive passport flows behind the
2364
+ * createAccount, signIn, addDevice, removeDevice, issueGrant, revokeGrant
2365
+ * and revokeAllGrants actions, and the restore of a previously created
2366
+ * account from its persisted record.
2367
+ */
2368
+ const createInit = (props) => () => ({
2369
+ sideEffects: [runPassportFlow, restorePassportAccount],
2370
+ sideEffectDependencies: createDependencies(props)
2371
+ });
2372
+ //#endregion
2373
+ export { createInit };