@laceio/sdk 0.1.0 → 0.1.1-canary.0

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