@laceio/sdk 0.1.1-canary.3 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (386) hide show
  1. package/dist/{TransactionBuilder-CCjOn7NA.cjs → TransactionBuilder-DrB3NVTi.cjs} +0 -42
  2. package/dist/{TransactionBuilder-CIzdw18M.js → TransactionBuilder-V6aLx4SV.js} +1 -1
  3. package/dist/{_polyfill-buffer-patch-CM8X7JiY.cjs → _polyfill-buffer-patch-BnPVerlG.cjs} +2 -21
  4. package/dist/account-guards.stable-B1DSSh9D.cjs +10 -0
  5. package/dist/account-guards.stable-JRQ5qx2V.js +5 -0
  6. package/dist/{activity-type-Ch6ljxBy.cjs → activity-type.stable-BJEfeLxL.cjs} +1 -2
  7. package/dist/{activity-type-GsJGWs-3.js → activity-type.stable-C76_hWd7.js} +1 -2
  8. package/dist/{address-book-address-validator-0J9XAADH.js → address-book-address-validator-DIUolI-s.js} +2 -2
  9. package/dist/{address-book-address-validator-Dte_YQ2L.cjs → address-book-address-validator-DNwQGlOB.cjs} +2 -2
  10. package/dist/bitcoin.cjs +0 -45
  11. package/dist/bitcoin.d.ts +1 -29906
  12. package/dist/bitcoin.js +0 -20
  13. package/dist/{blockfrost-tx-submit-provider-CLNQ5ycR.cjs → blockfrost-tx-submit-provider-BAIzV5o3.cjs} +167 -3
  14. package/dist/{blockfrost-tx-submit-provider-CBWQ0wK9.js → blockfrost-tx-submit-provider-DPTrapz-.js} +157 -5
  15. package/dist/{secret-box-DrjLZuS1.cjs → bytes.vo-Ck5u40RA.cjs} +35 -1
  16. package/dist/{secret-box-DUR0ACYz.js → bytes.vo-TgiwogWF.js} +25 -3
  17. package/dist/{cardano-network-id.vo-Cfpvbod9.js → cardano-network-id.vo-CK1tNQDg.js} +1 -1
  18. package/dist/{cardano-network-id.vo-BEDPn6Li.cjs → cardano-network-id.vo-DSxrFk9S.cjs} +1 -1
  19. package/dist/cardano.cjs +18 -22
  20. package/dist/cardano.d.ts +3774 -18959
  21. package/dist/cardano.js +11 -16
  22. package/dist/codecs-B7X9pAsK.cjs +1945 -0
  23. package/dist/codecs-CC1Xjntz.js +1882 -0
  24. package/dist/{const-D-eZIS4n.cjs → const-BDEg2Trq.cjs} +4 -4
  25. package/dist/{const-iwzZEE_w.cjs → const-BY8B3_0_.cjs} +1 -1
  26. package/dist/{const-BJfIK_G-.js → const-C84qHkjp.js} +4 -4
  27. package/dist/{const-CjmfjBP3.js → const-DXk2tFyv.js} +1 -1
  28. package/dist/{delegation-tx-builder-DZFjHDS8.js → delegation-tx-builder-CGVqlaFE.js} +5 -5
  29. package/dist/{delegation-tx-builder-CCjiakoy.cjs → delegation-tx-builder-CRpLP6jH.cjs} +6 -6
  30. package/dist/{deregistration-tx-builder-Bf6xAYp4.js → deregistration-tx-builder-B-CrUyX6.js} +5 -5
  31. package/dist/{deregistration-tx-builder-CQP35yex.cjs → deregistration-tx-builder-DZGwB4cz.cjs} +6 -6
  32. package/dist/{earn-rewards-tx-builder-Bsga3yFb.js → earn-rewards-tx-builder-BDbTDZmD.js} +5 -5
  33. package/dist/{earn-rewards-tx-builder-GuxofYns.cjs → earn-rewards-tx-builder-D5sUT5v8.cjs} +6 -6
  34. package/dist/{group-cardano-addresses-by-account-Bp0g4wEY.cjs → group-cardano-addresses-by-account-B533oVXR.cjs} +39 -3
  35. package/dist/{group-cardano-addresses-by-account-SR8MMrZf.js → group-cardano-addresses-by-account-RHKoEskR.js} +35 -5
  36. package/dist/{guarded-transaction-signer-MFpPg98D.cjs → guarded-transaction-signer-Bxl6_XNd.cjs} +18 -17
  37. package/dist/{guarded-transaction-signer-P6Rp1faj.js → guarded-transaction-signer-CpKLj8Kp.js} +15 -8
  38. package/dist/{in-memory-wallet-integration-t9I00R_V.cjs → in-memory-wallet-integration-CnLYeX4-.cjs} +108 -17
  39. package/dist/{in-memory-wallet-integration-CljprQQV.js → in-memory-wallet-integration-Croiuopx.js} +104 -7
  40. package/dist/{in-memory-wallet-integration-ChIOirMW.js → in-memory-wallet-integration-D-qn65Kx.js} +2 -5
  41. package/dist/{in-memory-wallet-integration-Cm6P8sk6.cjs → in-memory-wallet-integration-DVh9sRXa.cjs} +2 -3
  42. package/dist/index.cjs +47 -84
  43. package/dist/index.d.ts +13480 -40888
  44. package/dist/index.js +24 -52
  45. package/dist/{init-DUF4ar8P.cjs → init-B64zCLxG.cjs} +4 -4
  46. package/dist/{init-Y3mkB4XS.js → init-BAJJzBza.js} +2 -2
  47. package/dist/{init-EhzD7a8i.cjs → init-BJVU54pI.cjs} +1 -1
  48. package/dist/{init-D6BxBs7e.cjs → init-BKhH6mVR.cjs} +1 -1
  49. package/dist/{init-EP0CUWNK.cjs → init-BsCBAGWf.cjs} +2 -2
  50. package/dist/{init-Dy-05ktr.cjs → init-BtzMZ7Pk.cjs} +1 -1
  51. package/dist/init-Bv53hpLM.js +19 -0
  52. package/dist/{init-BopV9ed4.cjs → init-C-jErzp5.cjs} +2 -2
  53. package/dist/{init-Bp9GsPS_.cjs → init-C4Bkib9u.cjs} +56 -46
  54. package/dist/{init-lzHt4Cli.cjs → init-C7IeJwQR.cjs} +59 -256
  55. package/dist/{init-C-G32J12.cjs → init-CB__aLD7.cjs} +2 -2
  56. package/dist/{init-CyAY4Lzl.js → init-CFYsq82V.js} +1 -1
  57. package/dist/{init-0zzs9aqU.js → init-CLHuAMB-.js} +4 -4
  58. package/dist/{init-DA7zmptx.js → init-CNLGJJRx.js} +1 -1
  59. package/dist/{init-DS5qN63m.js → init-CR6tpw1B.js} +32 -24
  60. package/dist/init-CRbjI7p1.js +3494 -0
  61. package/dist/{init-CSDpdu0Q.cjs → init-CSHwHnfg.cjs} +2 -2
  62. package/dist/{init-CNM5m7M2.js → init-Cg9XdAru.js} +4 -4
  63. package/dist/{init-B3-1ghyx.js → init-CigestoM.js} +2 -2
  64. package/dist/{init-Dv3zKj0r.cjs → init-D6DBUsD3.cjs} +4 -4
  65. package/dist/init-DAna1KCg.cjs +3495 -0
  66. package/dist/{init-D74mn8nH2.js → init-DDdhguVC.js} +2 -2
  67. package/dist/init-DGe47B22.cjs +364 -0
  68. package/dist/init-DMtyvYfC.cjs +21 -0
  69. package/dist/{init-BrdVzxei.cjs → init-DX4WyB0R.cjs} +3 -3
  70. package/dist/{init-C8URA2OX.js → init-DcYY6zMD.js} +1 -1
  71. package/dist/{init-DFMiP2ZH.cjs → init-DkIc5nqF.cjs} +1 -1
  72. package/dist/{init-kEfUTuG2.js → init-Dku4b2lG.js} +1 -1
  73. package/dist/{init-NdhG_VrF.cjs → init-DxUHsN53.cjs} +6 -6
  74. package/dist/{init-CfTbSEKy.js → init-FMGDET-9.js} +60 -259
  75. package/dist/{init-DrkOb-wd.cjs → init-LfyMo-sS.cjs} +2 -2
  76. package/dist/{init-NCjgwCZy.js → init-Rxohwpmu.js} +2 -2
  77. package/dist/init-TkPDD750.js +363 -0
  78. package/dist/{init-C2RgrfZe.js → init-TkPq_Ny_.js} +1 -1
  79. package/dist/{init-5KcGcBb5.cjs → init-U8c9yHYx.cjs} +1 -1
  80. package/dist/{init-CX0AMQUn.js → init-aJHl-7AO.js} +2 -2
  81. package/dist/{init-rmt7-fQE.cjs → init-anYu6XB7.cjs} +2 -2
  82. package/dist/{init-Fw89ZmrR.js → init-w9GEs73W.js} +2 -2
  83. package/dist/{init-Dnsv155v.js → init-y2Ra0vZP.js} +3 -3
  84. package/dist/{init-DFjT8YvT.js → init-zSzCjoor.js} +4 -4
  85. package/dist/{is-retriable-error-BUiVJDwH.js → is-retriable-error-BU0e3hVI.js} +1 -1
  86. package/dist/{is-retriable-error-Dpt860if.cjs → is-retriable-error-CeeuHqDa.cjs} +1 -1
  87. package/dist/{lace-context-BZciB9c7.js → lace-context-CZcNHr4M.js} +4 -4
  88. package/dist/{lace-context-DgR6vLli.cjs → lace-context-fJTDghdp.cjs} +4 -4
  89. package/dist/{libsodium-wrappers-BhbOA8dQ.js → libsodium-wrappers-UH0LaOUE.js} +1647 -3
  90. package/dist/modules-cardano-BDvuL4Xx.js +5248 -0
  91. package/dist/modules-cardano-D2G3De2P.cjs +5432 -0
  92. package/dist/{retry-config-Dmgt28wM.js → retry-config-BcUmMS--.js} +1 -1
  93. package/dist/{retry-config-BaCfVC1H.cjs → retry-config-DC5IMaH7.cjs} +1 -1
  94. package/dist/{seam-cardano-B_etH4F4.js → seam-cardano-CATqBEyK.js} +1 -1
  95. package/dist/{signer-factory-DObB55D4.js → signer-factory-9URFliA5.js} +3 -6
  96. package/dist/{signer-factory-Ds6G2AZk.cjs → signer-factory-BWGUmnvm.cjs} +3 -4
  97. package/dist/{slice-qt0uBExh.js → slice-B2PhoWAg.js} +37 -325
  98. package/dist/{slice-DyNs7oWp.js → slice-BNu73oBa.js} +2 -2
  99. package/dist/{slice-GwiiJRoq.js → slice-CB4SnzMm.js} +3 -3
  100. package/dist/slice-CGVHXHDt.cjs +125 -0
  101. package/dist/{slice-CU80pbiu.js → slice-CnyWevM9.js} +3 -3
  102. package/dist/{slice-CwyYrh1H.js → slice-CobanYgn.js} +2 -2
  103. package/dist/{slice-7G2xxYKJ.cjs → slice-CuHUaPZx.cjs} +3 -3
  104. package/dist/{slice-DayJvMRD.cjs → slice-D11m2EKl.cjs} +1 -1
  105. package/dist/{slice-Bg6HEr3K.cjs → slice-DGcNrbPR.cjs} +4 -4
  106. package/dist/{slice-B4CdYoPu.cjs → slice-DZmQJNV8.cjs} +2 -2
  107. package/dist/slice-DhvF7L6X.js +107 -0
  108. package/dist/{slice-C9TT5KhY.cjs → slice-Do2R2CYW.cjs} +6 -6
  109. package/dist/{slice-Bs2aMERu.cjs → slice-DtaO72qY.cjs} +3 -3
  110. package/dist/{slice-C34iOOUH.cjs → slice-HeHCv3bl.cjs} +7 -7
  111. package/dist/{slice-D-9aPKG-.js → slice-d0p6-xj5.js} +6 -6
  112. package/dist/{slice-CK07EBCo.js → slice-eIwcwKHI.js} +4 -4
  113. package/dist/{slice-DBpJ2QGf.js → slice-maaskdUn.js} +6 -6
  114. package/dist/{slice-DTZTiJle.cjs → slice-mxLQ_FeY.cjs} +39 -352
  115. package/dist/{slice-DnG-yvpI.cjs → slice-oqm_r1cS.cjs} +2 -2
  116. package/dist/{slice-Da426sf9.js → slice-zJ9XVYjZ.js} +1 -1
  117. package/dist/{sync-operation-utils-31iFLExW.js → sync-operation-utils-BYXLO80m.js} +38 -2
  118. package/dist/{sync-operation-utils-COIZ66-I.cjs → sync-operation-utils-SdPbwFoD.cjs} +67 -1
  119. package/dist/{token-id-mapper-D29Ggv8h.js → token-id-mapper-B2ivlLv3.js} +2 -2
  120. package/dist/{token-id-mapper-CVyQJUKY.cjs → token-id-mapper-DsPAL6Nh.cjs} +2 -2
  121. package/dist/{util-Cp5cZkfK.js → util-BaLzwa32.js} +1 -1
  122. package/dist/{util-Bu4W5lF4.cjs → util-CGzqQ8IV.cjs} +1 -1
  123. package/dist/{utils-DsElZgCI.cjs → utils-5JvjbqH3.cjs} +1 -7
  124. package/dist/{utils-BfBEUvWA.js → utils-o8aMjfln.js} +2 -2
  125. package/dist/{vote-delegation-tx-builder-BUg1S2Ep.cjs → vote-delegation-tx-builder-BpEMSti4.cjs} +6 -6
  126. package/dist/{vote-delegation-tx-builder-C6FiS7zI.js → vote-delegation-tx-builder-CmKv6GoG.js} +5 -5
  127. package/package.json +4 -96
  128. package/dist/_polyfill-buffer-patch-yNxN4d5E.js +0 -1467
  129. package/dist/_web-crypto-random-bytes-Bo-GTcRS.js +0 -197
  130. package/dist/acc-module-4iIUv6My.cjs +0 -27654
  131. package/dist/acc-module-Cmj8EsIb.js +0 -27624
  132. package/dist/account-BOQruszJ.js +0 -6
  133. package/dist/account-BUOj4pYJ.cjs +0 -11
  134. package/dist/account-call-D68oF6bh.js +0 -267
  135. package/dist/account-call-DIIa2rK_.cjs +0 -314
  136. package/dist/account-call-NgLhYein.cjs +0 -4
  137. package/dist/account-call-n-Nkp35e.js +0 -3
  138. package/dist/account-guards-BtjTGxDZ.cjs +0 -42
  139. package/dist/account-guards-D9Lu5T3W.js +0 -36
  140. package/dist/account-tokens-DvkOFVON.js +0 -16
  141. package/dist/account-tokens-nwcvwLu4.cjs +0 -21
  142. package/dist/address-B9ntKL8K.js +0 -13761
  143. package/dist/address-BXp-mY8H.cjs +0 -11270
  144. package/dist/address-book-address-validator-DK0dnsRS.cjs +0 -41
  145. package/dist/address-book-address-validator-Di_ywo8M.js +0 -39
  146. package/dist/artefact-loader-54uK5RAa.js +0 -160
  147. package/dist/artefact-loader-DZPYrq-6.cjs +0 -183
  148. package/dist/auto-dismiss-failure-on-success-C-qoJuid.cjs +0 -37
  149. package/dist/auto-dismiss-failure-on-success-s8MGDEIu.js +0 -31
  150. package/dist/bip32-D6wd_QMn.cjs +0 -3851
  151. package/dist/bitcoin-data-provider-BYPSmuZS.js +0 -21
  152. package/dist/bitcoin-data-provider-w1oEDSU3.cjs +0 -26
  153. package/dist/bn-d3nSOIf7.cjs +0 -2553
  154. package/dist/browser-B1eMbDwh.js +0 -7468
  155. package/dist/bytes.vo-BB7_4JK6.js +0 -23
  156. package/dist/bytes.vo-BNRquqaO.cjs +0 -34
  157. package/dist/cardano-DfPwhwm-.js +0 -3
  158. package/dist/client-DXBLHk7K.cjs +0 -808
  159. package/dist/codecs-Cswkg7Tm.cjs +0 -4051
  160. package/dist/codecs-Dc1Krpbt.js +0 -3903
  161. package/dist/const-BhYOdznB.cjs +0 -42
  162. package/dist/const-BsnjG2_Q.cjs +0 -32071
  163. package/dist/const-CUnCl5U0.js +0 -13
  164. package/dist/const-D0CbQlo4.js +0 -154
  165. package/dist/contract-BD_312b0.js +0 -171
  166. package/dist/contract-DevBp9u8.cjs +0 -189
  167. package/dist/create-add-accounts-Brqk84vF.js +0 -102
  168. package/dist/create-add-accounts-DzXIh7Ot.cjs +0 -114
  169. package/dist/device-commitment-hex.vo-5wFtQvDS.js +0 -26
  170. package/dist/device-commitment-hex.vo-CT3RmAug.cjs +0 -31
  171. package/dist/device-readers-70i7tQqU.cjs +0 -8
  172. package/dist/device-readers-B7--ezKM.js +0 -4
  173. package/dist/device-readers-BWOmz9eD.js +0 -145
  174. package/dist/device-readers-CIgYZN7f.cjs +0 -168
  175. package/dist/dist-BMi5ZjEq.cjs +0 -43175
  176. package/dist/dist-BtIq4XFn.cjs +0 -535
  177. package/dist/dist-C3SHC_Ho.cjs +0 -1394
  178. package/dist/dist-CykEjYEX.cjs +0 -3814
  179. package/dist/dist-Dcsxh3be.cjs +0 -3452
  180. package/dist/dist-DqJfSlTd.cjs +0 -4413
  181. package/dist/dist-nTZ70qj7.cjs +0 -1306
  182. package/dist/enc-key-circuits-C8fGAMEF.cjs +0 -24
  183. package/dist/enc-key-circuits-DA2Xs3vZ.js +0 -13
  184. package/dist/english-Byb9M0E_.cjs +0 -2057
  185. package/dist/envelopes-BkH1Qdxk.js +0 -1620
  186. package/dist/envelopes-ETZEJS_O.cjs +0 -1721
  187. package/dist/errors-BZ8hnhCM.cjs +0 -584
  188. package/dist/errors-DIJTAsLa.js +0 -392
  189. package/dist/esm-HBSUQw3w.js +0 -384
  190. package/dist/esm-LZuaZjMf.cjs +0 -389
  191. package/dist/experimental.cjs +0 -7075
  192. package/dist/experimental.d.ts +0 -85525
  193. package/dist/experimental.js +0 -6917
  194. package/dist/gated-call-Boy6rXdC.js +0 -3
  195. package/dist/gated-call-DJWY299W.cjs +0 -736
  196. package/dist/gated-call-DjoRPqn1.js +0 -695
  197. package/dist/gated-call-SomdJ5nj.cjs +0 -4
  198. package/dist/grant-circuits-_1x--moV.cjs +0 -49
  199. package/dist/grant-circuits-swuzEdUl.js +0 -26
  200. package/dist/grant-rules-7Zqi_3BN.cjs +0 -7114
  201. package/dist/grant-rules-_xJHAT2M.js +0 -6833
  202. package/dist/grant-status-B2y49iIu.js +0 -2688
  203. package/dist/grant-status-DOr3t_u8.cjs +0 -2820
  204. package/dist/grants--b0LQQzZ.cjs +0 -266
  205. package/dist/grants-BIs6qm3b.js +0 -213
  206. package/dist/grants-CSgfYlOO.js +0 -5
  207. package/dist/grants-D61131nK.cjs +0 -17
  208. package/dist/hex-D9ITYbwt.cjs +0 -263
  209. package/dist/hex-mkXcV3pN.js +0 -191
  210. package/dist/http-client-B3N-TMxu.cjs +0 -167
  211. package/dist/http-client-TRlhDZGh.js +0 -155
  212. package/dist/identity-BMLuufva.cjs +0 -263
  213. package/dist/identity-DII6f-h7.js +0 -233
  214. package/dist/in-memory-wallet-integration-B2xzxORj.cjs +0 -20741
  215. package/dist/in-memory-wallet-integration-CBRiPjLO.js +0 -130
  216. package/dist/in-memory-wallet-integration-CULUB5Tf.cjs +0 -240
  217. package/dist/in-memory-wallet-integration-TM9bBphA.js +0 -20738
  218. package/dist/init-8v_n8boO.js +0 -1177
  219. package/dist/init-B5X_sGj9.cjs +0 -6
  220. package/dist/init-B8U3ABhS.cjs +0 -107
  221. package/dist/init-BJn-8_hf.js +0 -141
  222. package/dist/init-BmzfDaKL.js +0 -1142
  223. package/dist/init-BpHTq2R5.js +0 -105
  224. package/dist/init-BpSITBfF.js +0 -39
  225. package/dist/init-C00gw1zi.js +0 -422
  226. package/dist/init-CR7BfztQ.cjs +0 -18
  227. package/dist/init-Cp8EJGbm.js +0 -5
  228. package/dist/init-CuW7rHNA.js +0 -3584
  229. package/dist/init-Cz0rz5fU.cjs +0 -3585
  230. package/dist/init-D8OeObDF.cjs +0 -1141
  231. package/dist/init-D9g1HXYf.cjs +0 -40
  232. package/dist/init-DGjXwWs2.cjs +0 -143
  233. package/dist/init-DHrCbpkW.cjs +0 -121
  234. package/dist/init-DU5yYX5u.js +0 -2374
  235. package/dist/init-DlqJuHhl.js +0 -119
  236. package/dist/init-DrRdf5sZ.cjs +0 -1176
  237. package/dist/init-DuYENxci.js +0 -17
  238. package/dist/init-GsT2AEa4.cjs +0 -424
  239. package/dist/init-ZjNDDC-T.cjs +0 -2375
  240. package/dist/jubjub-authoriser-BxE3oN2y.js +0 -86
  241. package/dist/jubjub-authoriser-C6SDEP9I.cjs +0 -87
  242. package/dist/key-source-5oUBFiC7.cjs +0 -583
  243. package/dist/key-source-B08HukZg.js +0 -2550
  244. package/dist/keyDerivation-D3k9XyHg.js +0 -4077
  245. package/dist/keyDerivation-u0nBA93T.cjs +0 -274
  246. package/dist/lib--iqvW4O_.js +0 -2354
  247. package/dist/lib-Yk6Upl5D.cjs +0 -2359
  248. package/dist/midnight-account-id.vo-0x9X-r3l.cjs +0 -10
  249. package/dist/midnight-account-id.vo-DjCAGcqc.js +0 -5
  250. package/dist/midnight-engine-DpemplKO.js +0 -5
  251. package/dist/midnight-engine-xU1wotne.cjs +0 -6
  252. package/dist/midnight-wallet-DIsAlSn6.js +0 -18
  253. package/dist/midnight-wallet-XTZc2li7.cjs +0 -24
  254. package/dist/midnight.cjs +0 -1408
  255. package/dist/midnight.d.ts +0 -28934
  256. package/dist/midnight.js +0 -1352
  257. package/dist/modules-cardano-BrS68BbA.js +0 -995
  258. package/dist/modules-cardano-D843LvB0.cjs +0 -1108
  259. package/dist/node-relay-Cv0cNknM.js +0 -48
  260. package/dist/node-relay-DblH5fKv.cjs +0 -49
  261. package/dist/outputs-Bd2yZVjx.js +0 -720
  262. package/dist/outputs-CJoQBIA2.cjs +0 -990
  263. package/dist/pbkdf2-CIW-oWrm.cjs +0 -1337
  264. package/dist/pending-operation-B0_P78Jo.cjs +0 -26
  265. package/dist/pending-operation-BIS6mpjB.js +0 -21
  266. package/dist/providers-BLgJ0uQs.cjs +0 -366
  267. package/dist/providers-CwnT4vEE.js +0 -343
  268. package/dist/redacted-BmE2aXqr.js +0 -81
  269. package/dist/redacted-CRZJLS3w.cjs +0 -86
  270. package/dist/safe-buffer-B_vMqJWU.js +0 -43
  271. package/dist/safe-buffer-DYOwEfHB.cjs +0 -48
  272. package/dist/sdk-Dd0MKXFz.cjs +0 -1439
  273. package/dist/sdk-_yO75IHD.js +0 -1241
  274. package/dist/sdk-init-CYViTJY_.cjs +0 -3841
  275. package/dist/sdk-init-OMHyOGOK.js +0 -4138
  276. package/dist/send-proof-progress-C-ljq1x5.js +0 -30
  277. package/dist/send-proof-progress-vmsaSfbz.cjs +0 -47
  278. package/dist/side-effects-BnqYz7Nl.js +0 -768
  279. package/dist/side-effects-CngaeXi0.cjs +0 -804
  280. package/dist/sign-bitcoin-transaction-with-seed-D4z62-jV.js +0 -147
  281. package/dist/sign-bitcoin-transaction-with-seed-DsLYXnCY.cjs +0 -158
  282. package/dist/signer-3fk8lZtE.cjs +0 -7
  283. package/dist/signer-CsL28DrK.cjs +0 -121
  284. package/dist/signer-DGluibtn.js +0 -92
  285. package/dist/signer-RqB5pu3K.js +0 -2
  286. package/dist/signer-factory-BA7WFJVZ.js +0 -282
  287. package/dist/signer-factory-Cwd6o-lG.cjs +0 -281
  288. package/dist/signer-factory-DhZiE03y.cjs +0 -149
  289. package/dist/signer-factory-hzSRaIw2.js +0 -148
  290. package/dist/slice-BPNuHKfw.js +0 -9091
  291. package/dist/slice-CxKWDuBP.js +0 -87
  292. package/dist/slice-Czfp6t84.cjs +0 -436
  293. package/dist/slice-DnBWfA-k.cjs +0 -9109
  294. package/dist/slice-HjLXJyQG2.cjs +0 -105
  295. package/dist/slice-oWnc7YVD.js +0 -412
  296. package/dist/src-BDzYIksE.cjs +0 -20637
  297. package/dist/src-BFoefPv_.js +0 -20755
  298. package/dist/store-B1Lq3cEf.cjs +0 -66
  299. package/dist/store-DuBG8qh5.js +0 -37
  300. package/dist/submit-BBYjnZu8.cjs +0 -87
  301. package/dist/submit-D_yxYM_T.js +0 -70
  302. package/dist/submit-bitcoin-tx-BG3Gemov.js +0 -983
  303. package/dist/submit-bitcoin-tx-Y0CtvFN7.cjs +0 -1049
  304. package/dist/token-id-mapper-Bnds3xKH.cjs +0 -18
  305. package/dist/token-id-mapper-CnKHQ8DV.js +0 -16
  306. package/dist/tokens-Cevp7rdU.cjs +0 -62
  307. package/dist/tokens-Diw4MLRM.js +0 -44
  308. package/dist/types-B8uiJn-X.js +0 -12
  309. package/dist/types-CJT6XF2c.js +0 -10
  310. package/dist/types-CLRUYpfe.cjs +0 -23
  311. package/dist/types-DWbVZpnF.cjs +0 -15
  312. package/dist/types-T0cjaR75.js +0 -33
  313. package/dist/types-Zj78LtYu.cjs +0 -50
  314. package/dist/unwrap-provider-result-BZSiwabU.js +0 -32
  315. package/dist/unwrap-provider-result-ZqfBsTkk.cjs +0 -39
  316. package/dist/utils-DFwzEvbv.js +0 -65
  317. package/dist/utils-IXxR-Djh.cjs +0 -112
  318. package/dist/v8Signatures-CO_Uloy7.cjs +0 -71
  319. package/dist/watch-D-RoItM5.js +0 -21997
  320. package/dist/watch-DMF2s-II.cjs +0 -52281
  321. /package/dist/{account-id.vo-DwqFjK5u.cjs → account-id.vo-LvCBVn5r.cjs} +0 -0
  322. /package/dist/{account-id.vo-OPz2v-JZ.js → account-id.vo-MYSI7YFm.js} +0 -0
  323. /package/dist/{actions-iLXdgL5Y.js → actions-9QSQR-GB.js} +0 -0
  324. /package/dist/{actions-B2BJ4RTy.cjs → actions-DdGbj7c7.cjs} +0 -0
  325. /package/dist/{apply-vkey-witnesses-ZnFS0jnJ.cjs → apply-vkey-witnesses-CLzVSWxl.cjs} +0 -0
  326. /package/dist/{apply-vkey-witnesses-BKx3lcs0.js → apply-vkey-witnesses-ClZbpk5w.js} +0 -0
  327. /package/dist/{asyncoption-CruEYOBI.js → asyncoption-Cw07zPH7.js} +0 -0
  328. /package/dist/{asyncoption-i0VbqVTq.cjs → asyncoption-DYoGuQfP.cjs} +0 -0
  329. /package/dist/{bignum.vo-CEXOIew0.js → bignum.vo-B0rK_PQ1.js} +0 -0
  330. /package/dist/{bignum.vo-hx2kuqlA.cjs → bignum.vo-DsG3kNiZ.cjs} +0 -0
  331. /package/dist/{bip32ed25519-B7Yat217.cjs → bip32ed25519-1ApqeAZk.cjs} +0 -0
  332. /package/dist/{bip32ed25519-FQ8qvdcq.js → bip32ed25519-DetAdGwD.js} +0 -0
  333. /package/dist/{blake2b-DEeVUdKR.cjs → blake2b-B9tftbvG.cjs} +0 -0
  334. /package/dist/{blake2b-BiQTw3GC.js → blake2b-DOEVc57D.js} +0 -0
  335. /package/dist/{blockchain-network-id.vo-BAKEwGjG.cjs → blockchain-network-id.vo-BXpZhvvQ.cjs} +0 -0
  336. /package/dist/{blockchain-network-id.vo-CiVykuqG.js → blockchain-network-id.vo-DNRkuT5B.js} +0 -0
  337. /package/dist/{blockingWithLatestFrom-Cd8c8EPG.js → blockingWithLatestFrom-C5wp_uA-.js} +0 -0
  338. /package/dist/{blockingWithLatestFrom-D8kBPBMX.cjs → blockingWithLatestFrom-DY8OPg0w.cjs} +0 -0
  339. /package/dist/{cardano-network-id-to-network-type-C0ufJOyE.cjs → cardano-network-id-to-network-type-BDTF-HmK.cjs} +0 -0
  340. /package/dist/{cardano-network-id-to-network-type-BWwzeEtM.js → cardano-network-id-to-network-type-CrZfUcyP.js} +0 -0
  341. /package/dist/{cardano-tx-id.vo-TLjJZHCI.cjs → cardano-tx-id.vo-BPhV-AmZ.cjs} +0 -0
  342. /package/dist/{cardano-tx-id.vo-eVnKuzlm.js → cardano-tx-id.vo-DF9NzZXk.js} +0 -0
  343. /package/dist/{composite-signer-factory-m5cVs9h_.cjs → composite-signer-factory-BpF1mIYA.cjs} +0 -0
  344. /package/dist/{composite-signer-factory-CR8YHA1y.js → composite-signer-factory-_46QsNBz.js} +0 -0
  345. /package/dist/{error-DIZOY2Lw.js → error-BCp9NkPi.js} +0 -0
  346. /package/dist/{error-Cb3EnD0u.cjs → error-CNIquqT5.cjs} +0 -0
  347. /package/dist/{esm-browser-MG97cre9.js → esm-browser-C93Q-EOI.js} +0 -0
  348. /package/dist/{esm-browser-bweqfBlL.cjs → esm-browser-DTc9IK3D.cjs} +0 -0
  349. /package/dist/{feature-flag-key.vo-RlfHL3hq.cjs → feature-flag-key.vo-BPz-ZAp6.cjs} +0 -0
  350. /package/dist/{feature-flag-key.vo-DN_-4-sG.js → feature-flag-key.vo-ofrB6ZVQ.js} +0 -0
  351. /package/dist/{first-state-of-status-unPynOuM.js → first-state-of-status-DQnMT3ya.js} +0 -0
  352. /package/dist/{first-state-of-status-CbT7hPa4.cjs → first-state-of-status-OROkXcRv.cjs} +0 -0
  353. /package/dist/{init-zUoRG_EC2.cjs → init-C5CEZ1m0.cjs} +0 -0
  354. /package/dist/{init-DHaMxHM1.js → init-CKipPE_c.js} +0 -0
  355. /package/dist/{init-Atisw4x2.cjs → init-DFQQ9dTW.cjs} +0 -0
  356. /package/dist/{init-829HRYcz.js → init-Es3wHW7D.js} +0 -0
  357. /package/dist/{init-BgNobbNq.cjs → init-IAk_CkGa.cjs} +0 -0
  358. /package/dist/{init-atCFur0v.js → init-cqN3uX2j.js} +0 -0
  359. /package/dist/{is-redux-persist-state-BCFnSm36.cjs → is-redux-persist-state-CTn3WZVh.cjs} +0 -0
  360. /package/dist/{is-redux-persist-state-yBfq0h_E.js → is-redux-persist-state-Cxcd0_bM.js} +0 -0
  361. /package/dist/{key-value-store--W3SrMaw.js → key-value-store-8cMzeNyG.js} +0 -0
  362. /package/dist/{key-value-store-C2Xt5Emp.cjs → key-value-store-DUAepXQf.cjs} +0 -0
  363. /package/dist/{repo-slice-RxFm0zDZ.js → repo-slice-DwyMhCR1.js} +0 -0
  364. /package/dist/{repo-slice-7X4AYYVm.cjs → repo-slice-WxetRhMY.cjs} +0 -0
  365. /package/dist/{reselect-CGoLzEPv.js → reselect-C06X06oX.js} +0 -0
  366. /package/dist/{reselect-Bd94u0K-.cjs → reselect-CRDqmQY9.cjs} +0 -0
  367. /package/dist/{serializable-BHdKIgk3.js → serializable-B8GahgE1.js} +0 -0
  368. /package/dist/{serializable-BxHkoPdk.cjs → serializable-CRdnFaLZ.cjs} +0 -0
  369. /package/dist/{slice-obCSLm1x.js → slice-B87b52iM.js} +0 -0
  370. /package/dist/{slice-Bk0Sv05J.js → slice-Be7hj4Iy.js} +0 -0
  371. /package/dist/{slice-BiRsDKOK.cjs → slice-D11FHQuQ.cjs} +0 -0
  372. /package/dist/{slice-Dqw1ecum.cjs → slice-FioKeHtA.cjs} +0 -0
  373. /package/dist/{src-Cqp0B2M_.cjs → src-BTPIvlDI.cjs} +0 -0
  374. /package/dist/{src-BlxEp6Mm.js → src-vq1wS9sZ.js} +0 -0
  375. /package/dist/{time.vo-D3wWRw9L.cjs → time.vo-CQ8pSXz2.cjs} +0 -0
  376. /package/dist/{time.vo-tNheinXm.js → time.vo-DkYYGYp6.js} +0 -0
  377. /package/dist/{toEmpty-8Zax1MPd.js → toEmpty-CgAl3097.js} +0 -0
  378. /package/dist/{toEmpty-CYAbupM4.cjs → toEmpty-DAMmNB5r.cjs} +0 -0
  379. /package/dist/{token-id.vo-DXv5uS9n.cjs → token-id.vo-BxG9TG0O.cjs} +0 -0
  380. /package/dist/{token-id.vo-Bvwhr3ZE.js → token-id.vo-ClsroxHO.js} +0 -0
  381. /package/dist/{util-CzeB3hfa.cjs → util-CmdAhheh.cjs} +0 -0
  382. /package/dist/{util-C8a4fA9p.js → util-DxzlYNS5.js} +0 -0
  383. /package/dist/{util-selector-BWPH68_l.cjs → util-selector-BcAncU4L.cjs} +0 -0
  384. /package/dist/{util-selector-BSTsxgne.js → util-selector-CcK-GAdE.js} +0 -0
  385. /package/dist/{while-active-B0lWy_6l.js → while-active-BpppWuCs.js} +0 -0
  386. /package/dist/{while-active-Dsowp0Fi.cjs → while-active-Dhc2LwOm.cjs} +0 -0
@@ -1,2375 +0,0 @@
1
- require("./rolldown-runtime-Br2OG8yv.cjs");
2
- require("./_polyfill-buffer-patch-CM8X7JiY.cjs");
3
- require("./codecs-Cswkg7Tm.cjs");
4
- const require_bytes_vo = require("./bytes.vo-BNRquqaO.cjs");
5
- const require_grant_rules = require("./grant-rules-7Zqi_3BN.cjs");
6
- const require_providers = require("./providers-BLgJ0uQs.cjs");
7
- const require_gated_call = require("./gated-call-DJWY299W.cjs");
8
- const require_artefact_loader = require("./artefact-loader-DZPYrq-6.cjs");
9
- const require_types = require("./types-Zj78LtYu.cjs");
10
- const require_errors = require("./errors-BZ8hnhCM.cjs");
11
- const require_envelopes = require("./envelopes-ETZEJS_O.cjs");
12
- const require_enc_key_circuits = require("./enc-key-circuits-C8fGAMEF.cjs");
13
- const require_grant_circuits = require("./grant-circuits-_1x--moV.cjs");
14
- const require_acc_module = require("./acc-module-4iIUv6My.cjs");
15
- const require_device_readers = require("./device-readers-CIgYZN7f.cjs");
16
- const require_grants = require("./grants--b0LQQzZ.cjs");
17
- const require_account_call = require("./account-call-DIIa2rK_.cjs");
18
- let rxjs = require("rxjs");
19
- //#region ../../packages/module/passport-account/src/acc/device-circuits.ts
20
- /**
21
- * The gated circuits the device flows authorise, named once so the flow
22
- * that submits a call and the signer that scopes a key session to it
23
- * agree on the circuit.
24
- */
25
- const ADD_DEVICE_CIRCUIT = "add_device_with_jubjub";
26
- const REMOVE_DEVICE_CIRCUIT = "remove_device_with_jubjub";
27
- //#endregion
28
- //#region ../../packages/module/passport-account/src/acc/pending-deployment.ts
29
- /** Whether a record's pending creation carries the whole deployment, not only its marker. */
30
- const isPendingDeployment = (pending) => "authorityKey" in pending;
31
- /**
32
- * The refusal of a creation that resumes an unfinished one under another
33
- * lock choice than `recorded`, the one it was started with, which the
34
- * message names so a retry can repeat it.
35
- */
36
- const lockChoiceMismatch = (recorded) => new require_errors.CreationLockMismatchError(`The unfinished Passport account creation was started with lockAccount ${recorded}; resume it with the same lock choice.`);
37
- //#endregion
38
- //#region ../../packages/module/passport-account/src/store/envelope.ts
39
- /** AES-GCM is specified for 96-bit IVs; each seal draws a fresh one. */
40
- const IV_LENGTH = 12;
41
- const utf8 = (value) => new TextEncoder().encode(value);
42
- /** Whether a stored value has the sealed envelope layout. */
43
- const isSealedRecord = (value) => {
44
- if (typeof value !== "object" || value === null) return false;
45
- const candidate = value;
46
- return candidate.v === 1 && typeof candidate.iv === "string" && typeof candidate.ciphertext === "string";
47
- };
48
- /**
49
- * Encrypts a record into a {@link SealedRecord} under the given key,
50
- * marking the envelope pending when asked.
51
- */
52
- const sealRecord = async (key, record, { pending = false } = {}) => {
53
- const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
54
- const ciphertext = await crypto.subtle.encrypt({
55
- name: "AES-GCM",
56
- iv
57
- }, key, utf8(JSON.stringify(record)));
58
- return {
59
- v: 1,
60
- iv: require_bytes_vo.HexBytes.fromByteArray(iv),
61
- ciphertext: require_bytes_vo.HexBytes.fromByteArray(new Uint8Array(ciphertext)),
62
- ...pending ? { pending: true } : {}
63
- };
64
- };
65
- /**
66
- * Decrypts a {@link SealedRecord} back into the record it sealed. Any
67
- * failure to open - a tampered ciphertext, a mismatched key, or a
68
- * malformed envelope - throws RecordCorruptedError.
69
- */
70
- const openRecord = async (key, sealed) => {
71
- try {
72
- const plaintext = await crypto.subtle.decrypt({
73
- name: "AES-GCM",
74
- iv: require_bytes_vo.ByteArray.fromHex(require_bytes_vo.HexBytes(sealed.iv))
75
- }, key, require_bytes_vo.ByteArray.fromHex(require_bytes_vo.HexBytes(sealed.ciphertext)));
76
- return JSON.parse(new TextDecoder().decode(plaintext));
77
- } catch {
78
- throw new require_errors.RecordCorruptedError();
79
- }
80
- };
81
- //#endregion
82
- //#region ../../packages/module/passport-account/src/store/account-record.ts
83
- const COLLECTION_ID = "passport-account";
84
- const ACCOUNT_RECORD_KEY = "account";
85
- /**
86
- * An {@link AccountRecordStore} over the platform key-value storage,
87
- * namespaced under its own collection. With a `keyProvider` the record is
88
- * sealed at rest and only sealed envelopes are readable. What a sealed
89
- * record reads as without a `keyProvider` is the caller's choice:
90
- * 'skip' (the default) reads it as undefined, for the ceremony-free
91
- * restore peek that cannot open it by design; 'error' raises
92
- * RecordUnreadableError, for the flows where a missing storage key is a
93
- * persistence misconfiguration that must not look like an absent
94
- * account. Without a `keyProvider` (the dev authoriser) the record
95
- * persists in plaintext, which holds no secret once the account is
96
- * complete; while a creation is unfinished it holds the contract's
97
- * maintenance authority key (see {@link PassportAccountRecord}), so the
98
- * dev authoriser is for development and tests only.
99
- */
100
- const createAccountRecordStore = (createKeyValueStorage, keyProvider, { onSealedWithoutKey = "skip" } = {}) => {
101
- const storage = createKeyValueStorage({ collectionId: COLLECTION_ID });
102
- const open = async (keyOf, value) => isSealedRecord(value) ? openRecord(await keyOf(), value) : void 0;
103
- const stored = () => storage.getValues([ACCOUNT_RECORD_KEY]).pipe((0, rxjs.map)(([value]) => value), (0, rxjs.defaultIfEmpty)(void 0));
104
- const isPending = (record) => record.deployment !== void 0;
105
- const presenceOf = (value) => {
106
- if (value === void 0) return "absent";
107
- return (isSealedRecord(value) ? value.pending === true : isPending(value)) ? "pending" : "complete";
108
- };
109
- return {
110
- read: () => keyProvider ? stored().pipe((0, rxjs.concatMap)(async (value) => open(keyProvider, value))) : stored().pipe((0, rxjs.map)((value) => {
111
- if (!isSealedRecord(value)) return value;
112
- if (onSealedWithoutKey === "error") throw new require_errors.RecordUnreadableError();
113
- })),
114
- 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),
115
- presence: () => stored().pipe((0, rxjs.map)(presenceOf))
116
- };
117
- };
118
- /**
119
- * The promise view of an {@link AccountRecordStore}, for the flows. A
120
- * storage that completes without emitting (destroyed mid-flow) reads as
121
- * absent and writes as done, mirroring the stream contract so a flow
122
- * never hangs on it.
123
- */
124
- const toAccountRecords = (store) => ({
125
- read: async () => (0, rxjs.firstValueFrom)(store.read(), { defaultValue: void 0 }),
126
- write: async (record) => (0, rxjs.firstValueFrom)(store.write(record), { defaultValue: void 0 }),
127
- presence: async () => (0, rxjs.firstValueFrom)(store.presence(), { defaultValue: "absent" })
128
- });
129
- //#endregion
130
- //#region ../../packages/module/passport-account/src/acc/inbox-walk.ts
131
- const defaultLoadLedger = async () => import("@midnightntwrk/ledger-v9");
132
- /** The entries the contract holds, in inbox order, the Lace records included. */
133
- const inboxEntries = (ledgerState) => {
134
- const entries = [];
135
- for (let ordinal = 0n; ordinal < ledgerState.inbox_count; ordinal += 1n) if (ledgerState.inbox.member(ordinal)) entries.push(ledgerState.inbox.lookup(ordinal));
136
- return entries;
137
- };
138
- /**
139
- * The commitment the chain carries for a coin the account received,
140
- * recomputed with the ledger's own output construction: a contract-owned
141
- * output of this coin towards the account address, which is exactly what
142
- * a depositor builds and the contract claims. A description the ledger
143
- * refuses to commit to is no candidate.
144
- */
145
- const toCandidate = ({ ZswapOutput }, address, { coin, entry }) => {
146
- try {
147
- return {
148
- coin,
149
- commitment: ZswapOutput.newContractOwned({
150
- type: require_bytes_vo.HexBytes.fromByteArray(coin.color),
151
- nonce: require_bytes_vo.HexBytes.fromByteArray(coin.nonce),
152
- value: coin.value
153
- }, void 0, address).commitment.toLowerCase(),
154
- entry
155
- };
156
- } catch {
157
- return null;
158
- }
159
- };
160
- /**
161
- * The tree index of every shielded output the chain created for the
162
- * account, by commitment, read from the ledger events of the transactions
163
- * that acted on the contract. A deposit is one such action, so its
164
- * transaction is among them.
165
- */
166
- const receivedOutputs = async (address, indexer) => {
167
- const actions = await indexer.enumerateContractActions(address);
168
- const hashes = [...new Set(actions.map((action) => action.txHash))];
169
- const outputs = await Promise.all(hashes.map(async (hash) => indexer.queryShieldedOutputs(hash)));
170
- const recipient = address.toLowerCase();
171
- return new Map(outputs.flat().filter((output) => output.contractAddress === recipient).map((output) => [output.commitment, output.index]));
172
- };
173
- /**
174
- * Walks the account's inbox the way the custody standard prescribes:
175
- * every entry other than the Lace records, which hold the account keys
176
- * and the grant bookkeeping rather than coins, is opened with the
177
- * encryption secrets, each coin that opens is verified by recomputing
178
- * its commitment and finding it among the outputs the chain created for
179
- * the account, and the index that output took in the commitment tree is
180
- * captured with it. Anyone can append any
181
- * bytes to the inbox, so an entry that does not open, or opens to a coin
182
- * the chain never created for this account, is skipped as noise and
183
- * counted, never raised. Two entries describing the same coin, as a
184
- * re-encryption after a key rotation leaves behind, yield one holding,
185
- * read from the first entry that described it. An empty inbox, or one
186
- * with nothing that opens, is answered without loading the ledger or
187
- * reading the chain's history. A ledger binding that fails to load is a
188
- * failure of the walk itself, not of any entry, so it is raised rather
189
- * than reported as an inbox of noise.
190
- */
191
- const walkInbox = async ({ address, ledgerState, indexer, openEntries, loadLedger = defaultLoadLedger }) => {
192
- const entries = inboxEntries(ledgerState).filter((entry) => !require_envelopes.isLaceRecord(entry));
193
- const nothing = (skippedEntries) => ({
194
- holdings: [],
195
- holdingEntries: [],
196
- skippedEntries
197
- });
198
- if (entries.length === 0) return nothing(0);
199
- const coins = await openEntries(entries);
200
- if (coins.every((coin) => coin === null)) return nothing(entries.length);
201
- const ledger = await loadLedger();
202
- const candidates = coins.map((coin, ordinal) => coin && toCandidate(ledger, address, {
203
- coin,
204
- entry: entries[ordinal]
205
- }));
206
- if (candidates.every((candidate) => candidate === null)) return nothing(entries.length);
207
- const outputs = await receivedOutputs(address, indexer);
208
- const holdings = /* @__PURE__ */ new Map();
209
- const holdingEntries = /* @__PURE__ */ new Map();
210
- let skippedEntries = 0;
211
- for (const candidate of candidates) {
212
- const index = candidate && outputs.get(candidate.commitment);
213
- if (!candidate || index === void 0) {
214
- skippedEntries += 1;
215
- continue;
216
- }
217
- if (holdings.has(candidate.commitment)) continue;
218
- holdings.set(candidate.commitment, {
219
- color: require_types.TokenColor(require_bytes_vo.HexBytes.fromByteArray(candidate.coin.color)),
220
- value: candidate.coin.value.toString(),
221
- commitment: candidate.commitment,
222
- index: Number(index)
223
- });
224
- holdingEntries.set(candidate.commitment, candidate.entry);
225
- }
226
- return {
227
- holdings: [...holdings.values()],
228
- holdingEntries: [...holdingEntries.values()],
229
- skippedEntries
230
- };
231
- };
232
- //#endregion
233
- //#region ../../packages/module/passport-account/src/flows/key-session.ts
234
- /**
235
- * Runs an operation under a single key ceremony, so a flow that reaches
236
- * for the device key several times costs one user prompt instead of one
237
- * per authoriser call. `flow` names the flow for an authoriser that
238
- * presents it before the ceremony. An authoriser with no interactive
239
- * ceremony exposes no session, and the operation runs directly. The
240
- * session function is used detached, so implementations must not rely on
241
- * `this`.
242
- */
243
- const inKeySession = async (authoriser, flow, operation) => {
244
- const { withKeySession } = authoriser;
245
- return withKeySession ? withKeySession(operation, flow) : operation();
246
- };
247
- //#endregion
248
- //#region ../../packages/module/passport-account/src/acc/enc-key-rotation.ts
249
- /** Prepares `rotate_enc_key_with_jubjub` over the raw 32-byte X25519 key `enc_key` is replaced with. */
250
- const prepareRotateEncKey = (newKey) => ({
251
- circuit: require_enc_key_circuits.ROTATE_ENC_KEY_CIRCUIT,
252
- args: [newKey]
253
- });
254
- /** Prepares `append_inbox_with_jubjub` over one inbox entry: a re-encrypted coin or a Lace record. */
255
- const prepareAppendInbox = (entry) => ({
256
- circuit: require_enc_key_circuits.APPEND_INBOX_CIRCUIT,
257
- args: [entry]
258
- });
259
- //#endregion
260
- //#region ../../packages/module/passport-account/src/flows/rotation.ts
261
- /**
262
- * How long an accepted call is given to show in the indexer's view of the
263
- * ledger, which can lag the block the call landed in.
264
- */
265
- const LEDGER_POLL_ATTEMPTS = 30;
266
- const LEDGER_POLL_DELAY_MS = 1e3;
267
- const sleep$1 = async (ms) => new Promise((resolve) => {
268
- setTimeout(resolve, ms);
269
- });
270
- /**
271
- * The encryption key's view members, which a rotation and a read grant's
272
- * issue need: the re-encryption a rotation moves the holdings through
273
- * and the sealing a grantee receives the secret by.
274
- *
275
- * @throws {@link ReadUnavailableError} when the key offers either not,
276
- * as a key that only opens entries does.
277
- */
278
- const viewCapability = (encryptionKey) => {
279
- const { reencryptInbox, sealView } = encryptionKey;
280
- if (!reencryptInbox || !sealView) throw new require_errors.ReadUnavailableError();
281
- return {
282
- reencryptInbox,
283
- sealView
284
- };
285
- };
286
- /** Resolves this device's reader and device keys, inside the caller's key session. */
287
- const readLocalDevice = async ({ passportAuthoriser, passportEncryptionKey, passportNetwork }) => ({
288
- readerPublicKey: await passportEncryptionKey.readerPublicKey(passportNetwork.networkId),
289
- devicePublicKey: require_envelopes.encodeDevicePublicKey(await passportAuthoriser.devicePublicKey())
290
- });
291
- /** Reads the inbox and this device's keyring of the account from its ledger. */
292
- const readAccountInbox = (account, ledgerState, readerPublicKey) => {
293
- const entries = inboxEntries(ledgerState);
294
- return {
295
- entries,
296
- keyring: {
297
- account: require_providers.AccAddress(account),
298
- encKey: ledgerState.enc_key,
299
- envelopes: require_envelopes.deviceEnvelopes(entries, readerPublicKey)
300
- }
301
- };
302
- };
303
- /**
304
- * The device entries the ledger holds, as lowercase hex, less `except`:
305
- * the devices a rotation may seal the new secret to, which a key session
306
- * names to the user before it opens.
307
- *
308
- * @throws {@link DeviceRosterInvalidError} when there are more than
309
- * {@link MAX_DEVICE_ENTRIES}, which no signer would accept.
310
- */
311
- const liveDeviceEntries = (ledgerState, except) => {
312
- const entries = [...ledgerState.devices].map((entry) => require_bytes_vo.HexBytes.fromByteArray(entry)).filter((entry) => entry !== except?.toLowerCase());
313
- if (entries.length > 64) throw new require_errors.DeviceRosterInvalidError(`The account holds ${entries.length} device entries, more than the 64 a rotation names.`);
314
- return entries;
315
- };
316
- /**
317
- * The ledger once the indexer reflects a call that advanced the auth
318
- * nonce past `authNonce`. A chain of gated calls must have each bind the
319
- * nonce the previous one left behind, which the indexer can serve a
320
- * moment late.
321
- *
322
- * @throws {@link GrantRosterUnsettledError} when the indexer never
323
- * reflects the call within the polling window.
324
- */
325
- const awaitAdvancedLedger = async (indexer, address, authNonce) => {
326
- for (let attempt = 0; attempt < LEDGER_POLL_ATTEMPTS; attempt++) {
327
- const ledgerState = await require_account_call.queryAccountLedger(indexer, address);
328
- if (ledgerState.auth_nonce > authNonce) return ledgerState;
329
- await sleep$1(LEDGER_POLL_DELAY_MS);
330
- }
331
- throw new require_errors.GrantRosterUnsettledError(`The ledger of ${address} never reflected the accepted call.`);
332
- };
333
- /**
334
- * Starts a chain of gated calls at `start`. Each accepted call reports
335
- * the counter it advanced this device to, then waits for the indexer to
336
- * reflect it, so the next call binds the auth nonce it left; the local
337
- * roster row follows the entry each call leaves it on.
338
- */
339
- const callChain = ({ account, start, indexer, seams, onProgress, onAdvanced }) => {
340
- let current = start;
341
- const submit = async (call) => {
342
- const { advancedCounter, localCommitmentHex } = await require_account_call.submitAccountCall({
343
- circuit: call.circuit,
344
- args: call.args,
345
- account,
346
- localUseCounter: current.localUseCounter,
347
- ledgerState: current.ledgerState,
348
- onStage: onProgress
349
- }, seams);
350
- const localUseCounter = advancedCounter.toString();
351
- await onAdvanced(localUseCounter);
352
- current = {
353
- ledgerState: await awaitAdvancedLedger(indexer, account.address, current.ledgerState.auth_nonce),
354
- localUseCounter,
355
- devices: require_account_call.withRefreshedLocalDevice(current.devices, localCommitmentHex)
356
- };
357
- };
358
- return {
359
- submit,
360
- append: async (stage, entries) => {
361
- if (entries.length > 0) onProgress(stage);
362
- for (const entry of entries) await submit(prepareAppendInbox(entry));
363
- },
364
- position: () => current
365
- };
366
- };
367
- /** The registrations of an inbox, by hex. */
368
- const registrationsOf = (entries) => new Set(entries.filter(require_envelopes.isDeviceRegistration).map((entry) => require_bytes_vo.HexBytes.fromByteArray(entry)));
369
- /**
370
- * The roster a rotation seals to: the registrations the live roster key
371
- * opens, resolved against the ledger's device set so only a registration
372
- * whose device key derives a live entry counts, and only one whose entry
373
- * is among `devices`. A registration naming nobody's live device is
374
- * passed over, and named devices left without a reader, by a conflict or
375
- * for want of a registration, are reported dropped, see
376
- * {@link resolveLiveReaders}; this device, sealed to regardless, is never
377
- * reported dropped. The registration whose live entry is `target`, the
378
- * entry a removal takes out, is named so no reader paired with its device
379
- * is sealed to.
380
- */
381
- const sealedRoster = async ({ account, encryptionKey, networkId, local, ledgerState, inbox, devices, target, localEntry }) => {
382
- const registered = (await encryptionKey.openInbox(networkId, inbox.keyring, inbox.entries.filter(require_envelopes.isDeviceRegistration))).flatMap((opened) => opened?.kind === "device" ? [opened.device] : []);
383
- const self = require_bytes_vo.HexBytes.fromByteArray(local.readerPublicKey);
384
- const { readers, dropped, outside } = require_device_readers.resolveLiveReaders({
385
- scope: {
386
- address: account.address,
387
- epoch: ledgerState.device_epoch
388
- },
389
- registered,
390
- isLive: (entryHex) => ledgerState.devices.member(require_bytes_vo.ByteArray.fromHex(require_bytes_vo.HexBytes(entryHex))),
391
- allowed: new Set(devices),
392
- target
393
- });
394
- const removed = outside.find(({ entryHex }) => entryHex === target);
395
- return {
396
- readers: readers.filter(({ reader }) => reader.readerPublicKey !== self).map(({ reader }) => reader),
397
- dropped: dropped.filter((entry) => entry !== localEntry),
398
- ...removed ? { removed: {
399
- devicePublicKey: removed.reader.devicePublicKey,
400
- epoch: removed.reader.epoch,
401
- counter: removed.reader.counter
402
- } } : {}
403
- };
404
- };
405
- /**
406
- * Rotates the account encryption key to a fresh random secret and
407
- * re-encrypts every live holding towards it, as the scoped grants
408
- * standard requires before a read grant is issued and after one is
409
- * revoked, and as a device removal requires so the removed device reads
410
- * nothing newer. The holdings are walked with the keyring of the ledger's
411
- * `enc_key` from the position the chain is at, a keyring this device's
412
- * envelopes do not open rejecting with EncryptionKeyMismatchError before
413
- * anything is submitted. The encryption key draws the new secret and
414
- * seals it, with the roster key, to this device and to every registered
415
- * device that is enrolled now and among `devices`, and answers the
416
- * ciphertexts alone: one envelope per device and, when the roster key is
417
- * fresh, one registration each. Should any registration the live roster
418
- * key opens land while the rotation runs, as another device's enrolment
419
- * does, the rotation refuses with DeviceRosterInvalidError before
420
- * `enc_key` is replaced, so a device enrolled meanwhile is never left
421
- * without the new key; registrations that open under no roster key are
422
- * noise and do not stop it. Devices whose registrations conflict are
423
- * left out and reported in the result. The holdings are
424
- * re-encrypted towards the new key, the envelopes and registrations are
425
- * appended, `enc_key` is replaced through `rotate_enc_key_with_jubjub`,
426
- * and each re-encrypted holding is appended, one gated call each, all in
427
- * the key session the caller holds. The envelopes land ahead of the
428
- * rotation, so no device is left without the key the chain then holds;
429
- * a rotation interrupted after it leaves holdings under the previous
430
- * key, which every device still opens from its older envelopes and the
431
- * next rotation re-encrypts. The previous secret is never derived again
432
- * by anyone: entries sealed towards it stay readable to whoever held it,
433
- * and nothing newer is.
434
- */
435
- const rotateEncKey = async ({ account, encryptionKey, view, local, chain, indexer, networkId, onProgress, devices, rotateRoster, target }) => {
436
- const { ledgerState } = chain.position();
437
- const inbox = readAccountInbox(account.address, ledgerState, local.readerPublicKey);
438
- const { entries, keyring } = inbox;
439
- const { holdingEntries } = await walkInbox({
440
- address: account.address,
441
- ledgerState,
442
- indexer,
443
- openEntries: async (coinEntries) => (await encryptionKey.openInbox(networkId, keyring, coinEntries)).map((opened) => opened?.kind === "coin" ? opened.coin : null)
444
- });
445
- const { readers, dropped, removed } = await sealedRoster({
446
- account,
447
- encryptionKey,
448
- networkId,
449
- local,
450
- ledgerState,
451
- inbox,
452
- devices,
453
- target,
454
- localEntry: chain.position().devices.find((device) => device.isLocal)?.commitmentHex.toLowerCase()
455
- });
456
- const keys = await encryptionKey.createKeys(networkId, {
457
- devicePublicKey: local.devicePublicKey,
458
- keyring,
459
- registrations: entries.filter(require_envelopes.isDeviceRegistration),
460
- readers,
461
- ...rotateRoster === void 0 ? {} : { rotateRoster },
462
- ...removed ? { removed } : {}
463
- });
464
- const reencrypted = (await view.reencryptInbox(networkId, {
465
- keyring,
466
- to: keys.encKey
467
- }, holdingEntries)).filter((entry) => entry !== null);
468
- onProgress("rotating");
469
- for (const entry of [...keys.envelopes, ...keys.registrations]) await chain.submit(prepareAppendInbox(entry));
470
- const before = registrationsOf(entries);
471
- const appended = registrationsOf(keys.registrations);
472
- 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)));
473
- 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.`);
474
- await chain.submit(prepareRotateEncKey(keys.encKey));
475
- await chain.append("reencrypting", reencrypted);
476
- return {
477
- encKey: keys.encKey,
478
- dropped,
479
- keyring: {
480
- account: require_providers.AccAddress(account.address),
481
- encKey: keys.encKey,
482
- envelopes: keys.envelopes.filter((envelope) => require_envelopes.isAddressedTo(envelope, local.readerPublicKey))
483
- }
484
- };
485
- };
486
- /**
487
- * Seals the live secret of `keyring` to each read grant's read key, with
488
- * the grant record that keeps each seal on chain for this device. A
489
- * grant the key refuses to seal to, an expired key session included, is
490
- * listed unsealed rather than failing a rotation that already landed, or
491
- * as revocation pending when the key refuses it with
492
- * GrantRevocationPendingError.
493
- */
494
- const sealViews = async ({ view, networkId, keyring, account, targets }) => {
495
- const sealedEncKey = require_bytes_vo.HexBytes.fromByteArray(keyring.encKey);
496
- const result = {
497
- sealed: [],
498
- unsealed: [],
499
- revocationPending: [],
500
- entries: []
501
- };
502
- for (const target of targets) {
503
- let refusal;
504
- const delivery = await view.sealView(networkId, keyring, {
505
- ...target,
506
- account
507
- }).catch((error) => {
508
- refusal = error;
509
- });
510
- if (!delivery) {
511
- (refusal instanceof require_errors.GrantRevocationPendingError ? result.revocationPending : result.unsealed).push(target.grantId);
512
- continue;
513
- }
514
- result.sealed.push({
515
- ...target,
516
- seal: require_bytes_vo.HexBytes.fromByteArray(delivery.seal),
517
- sealedEncKey
518
- });
519
- result.entries.push(delivery.entry);
520
- }
521
- return result;
522
- };
523
- //#endregion
524
- //#region ../../packages/module/passport-account/src/flows/stored-grants.ts
525
- /**
526
- * The slot each stored grant was derived under, keyed by id, as the
527
- * roster decoder takes them.
528
- */
529
- const storedGrantSlots = (stored) => new Map(Object.entries(stored ?? {}).map(([id, { slot }]) => [require_grant_rules.GrantId(id), require_grant_rules.GrantSlot(slot)]));
530
- /**
531
- * The opening of each stored grant whose object fields were kept, keyed by
532
- * id, as the roster decoder attaches them. A read grant whose seal this
533
- * client holds carries it in the opening's view, with the `enc_key` whose
534
- * secret it seals.
535
- */
536
- const storedGrantOpenings = (stored) => new Map(Object.entries(stored ?? {}).flatMap(([id, grant]) => grant.object ? [[require_grant_rules.GrantId(id), {
537
- scopeSalt: require_grant_rules.GrantScopeSalt(grant.scopeSalt),
538
- granteeScheme: require_types.storedGranteeScheme(grant),
539
- granteePublicKey: grant.granteePublicKey,
540
- origin: grant.origin,
541
- color: require_types.TokenColor(grant.object.color),
542
- recipient: grant.object.recipient,
543
- maxCoinValue: grant.object.maxCoinValue,
544
- ...grant.view?.seal === void 0 || grant.view.sealedEncKey === void 0 ? {} : { view: {
545
- readPublicKey: grant.view.readPublicKey,
546
- seal: grant.view.seal,
547
- sealedEncKey: grant.view.sealedEncKey
548
- } }
549
- }]] : []));
550
- /**
551
- * The stored grants with the view of one grant replaced: its read key
552
- * and, when given, the seal towards it of the secret of `sealedEncKey`.
553
- */
554
- const withStoredGrantView = (stored, grantId, view) => {
555
- const grant = stored[grantId];
556
- if (!grant) return stored;
557
- return {
558
- ...stored,
559
- [grantId]: {
560
- ...grant,
561
- view
562
- }
563
- };
564
- };
565
- /**
566
- * The read grants this client holds the read key of and the chain still
567
- * lists active, other than `except`: the grants a rotation seals the new
568
- * secret to again. A read grant issued by another client has no stored
569
- * key here, so it is not among them.
570
- */
571
- const liveStoredReadGrants = (stored, roster, except) => {
572
- const active = new Set(roster.filter((record) => record.active && record.scope.read).map(({ id }) => id));
573
- return Object.entries(stored ?? {}).flatMap(([id, grant]) => grant.view && active.has(require_grant_rules.GrantId(id)) && id !== except ? [{
574
- grantId: require_grant_rules.GrantId(id),
575
- readPublicKey: grant.view.readPublicKey
576
- }] : []);
577
- };
578
- /**
579
- * The active read grants this client holds the read key of whose stored
580
- * seal does not hold the secret of `encKey`, the ledger's current one:
581
- * their grantees read nothing newer until a rotation seals to them again
582
- * or they are issued again. A read grant issued by another client has no
583
- * stored key here, so it is not among them.
584
- */
585
- const unsealedStoredReadGrants = (stored, roster, encKey) => liveStoredReadGrants(stored, roster).filter(({ grantId }) => stored?.[grantId]?.view?.sealedEncKey !== encKey).map(({ grantId }) => grantId);
586
- /** The stored grants with one more entry, under its grant id. */
587
- const withStoredGrant = (stored, grantId, grant) => ({
588
- ...stored,
589
- [grantId]: grant
590
- });
591
- /**
592
- * The record a completed account persists: its identity, this device's
593
- * use counter, the grant bookkeeping when there is any, and the roster of
594
- * devices the account keys were sealed to when it is known. It never
595
- * carries a deployment, so a write of it completes a pending record.
596
- */
597
- const completedRecord = ({ address, bindingVersion }, localUseCounter, { grants }) => ({
598
- address,
599
- bindingVersion,
600
- localUseCounter,
601
- ...grants ? { grants } : {}
602
- });
603
- /**
604
- * The stored grants with the seals of a rotation applied: each sealed
605
- * grant's view carries its new seal and the `enc_key` it holds, and each
606
- * unsealed one keeps its read key alone.
607
- */
608
- const withSealedViews = (stored, { sealed, unsealed }) => {
609
- if (!stored) return stored;
610
- let next = stored;
611
- for (const { grantId, readPublicKey, seal, sealedEncKey } of sealed) next = withStoredGrantView(next, grantId, {
612
- readPublicKey,
613
- seal,
614
- sealedEncKey
615
- });
616
- for (const grantId of unsealed) {
617
- const readPublicKey = next[grantId]?.view?.readPublicKey;
618
- if (readPublicKey !== void 0) next = withStoredGrantView(next, grantId, { readPublicKey });
619
- }
620
- return next;
621
- };
622
- /** Each grant's parts by id, the later of two parts of a kind winning. */
623
- const partsByGrant = (parts) => {
624
- const byGrant = /* @__PURE__ */ new Map();
625
- for (const part of parts) {
626
- const held = byGrant.get(part.grantId) ?? {};
627
- byGrant.set(part.grantId, {
628
- ...held,
629
- [part.part]: part
630
- });
631
- }
632
- return byGrant;
633
- };
634
- /**
635
- * Whether a grant's bookkeeping opens its on-chain commitments under the
636
- * account at `address`: the id derives from the account, the grantee
637
- * key under its scheme, the origin and the slot, the object commitment
638
- * from the salt and the object fields, and the read key hashes to the
639
- * one the contract holds, or is absent for a grant that does not read.
640
- * Anyone can append any bytes to the inbox, and another client of the
641
- * account issuing to the same grantee from the same origin lands on the
642
- * same id with its own salt, so this check, not where the bookkeeping
643
- * came from, is what makes it trusted.
644
- */
645
- const opensOnChain = async (record, fields, address) => {
646
- try {
647
- const grantee = {
648
- scheme: fields.granteeScheme,
649
- publicKey: fields.granteePublicKey
650
- };
651
- const grantId = require_grants.deriveGrantId({
652
- contractAddress: require_bytes_vo.ByteArray.fromHex(require_bytes_vo.HexBytes(address)),
653
- granteePublicKey: require_grant_rules.granteePoint(grantee),
654
- originHash: await require_grants.originHash(fields.origin),
655
- slot: require_grant_rules.GrantSlot(fields.slot)
656
- });
657
- const encoded = require_grant_rules.circuitScope({
658
- grantee,
659
- operations: [],
660
- color: require_types.TokenColor(fields.object.color),
661
- recipient: fields.object.recipient,
662
- maxCoinValue: fields.object.maxCoinValue,
663
- perCallCap: "0",
664
- cap: "0",
665
- expiresAt: null,
666
- ...fields.readPublicKey === void 0 ? {} : { readPublicKey: fields.readPublicKey }
667
- });
668
- 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;
669
- } catch {
670
- return false;
671
- }
672
- };
673
- /**
674
- * The stored grants narrowed to the ones that still open what the chain
675
- * holds under their id, or undefined once none is left. A grant the
676
- * chain no longer holds is dropped, and so is one whose kept fields do
677
- * not open its commitments: the entry an issue wrote before a call that
678
- * never landed, once another client of the account issued over the same
679
- * id, or an entry written before the object fields were kept, which
680
- * cannot be checked. A revoked grant stays in the contract's map as a
681
- * tombstone, so its slot and salt are kept until a revoke-all clears the
682
- * map or a new grant overwrites the id.
683
- */
684
- const retainStoredGrants = async (stored, roster, address) => {
685
- if (!stored) return void 0;
686
- const retained = {};
687
- for (const record of roster) {
688
- const grant = stored[record.id];
689
- if (!grant?.object) continue;
690
- if (await opensOnChain(record, {
691
- ...grant,
692
- granteeScheme: require_types.storedGranteeScheme(grant),
693
- object: grant.object,
694
- ...grant.view === void 0 ? {} : { readPublicKey: grant.view.readPublicKey }
695
- }, address)) retained[record.id] = grant;
696
- }
697
- return Object.keys(retained).length > 0 ? retained : void 0;
698
- };
699
- /**
700
- * The bookkeeping of grants this device issued, rebuilt from the grant
701
- * records it opened in the inbox, for the grants the chain still holds:
702
- * each grant whose parts open its on-chain commitments under this
703
- * account and origin, with its read key and, when the newest view record
704
- * holds the seal of the ledger's `enc_key`, that seal. A grant whose
705
- * parts do not check out, or whose grant or object part is missing, is
706
- * left out. Undefined when nothing is rebuilt.
707
- */
708
- const rebuildStoredGrants = async (parts, roster, scope) => {
709
- const byGrant = partsByGrant(parts);
710
- const rebuilt = {};
711
- for (const record of roster) {
712
- const held = byGrant.get(record.id);
713
- if (!held?.grant || !held.object) continue;
714
- const { grant, object, view } = held;
715
- if (!await opensOnChain(record, {
716
- ...grant,
717
- origin: scope.origin,
718
- object: object.object
719
- }, scope.address)) continue;
720
- const readPublicKey = grant.readPublicKey;
721
- const isCurrent = view !== void 0 && scope.encKey.startsWith(view.encKeyPrefix);
722
- rebuilt[record.id] = {
723
- slot: grant.slot,
724
- scopeSalt: grant.scopeSalt,
725
- granteeScheme: grant.granteeScheme,
726
- granteePublicKey: grant.granteePublicKey,
727
- origin: scope.origin,
728
- object: object.object,
729
- ...readPublicKey === void 0 ? {} : { view: isCurrent ? {
730
- readPublicKey,
731
- seal: view.seal,
732
- sealedEncKey: scope.encKey
733
- } : { readPublicKey } }
734
- };
735
- }
736
- return Object.keys(rebuilt).length > 0 ? rebuilt : void 0;
737
- };
738
- /**
739
- * The record's bookkeeping with every rebuilt grant it lacks added: what
740
- * the record holds is kept, so a record that survived is never
741
- * overwritten by the chain's copy, except for a view whose seal is not of
742
- * `encKey`, the ledger's current one, when the rebuilt view's seal is:
743
- * the record write after a rotation can be lost while its seal reached
744
- * the inbox. Run over the bookkeeping {@link retainStoredGrants} checked,
745
- * a rebuilt grant takes the place of an entry that did not open.
746
- */
747
- const withRebuiltGrants = (stored, rebuilt, encKey) => {
748
- if (!rebuilt) return stored;
749
- const merged = {
750
- ...rebuilt,
751
- ...stored
752
- };
753
- for (const [id, fromChain] of Object.entries(rebuilt)) {
754
- const held = stored?.[id];
755
- if (held && held.view?.sealedEncKey !== encKey && fromChain.view?.sealedEncKey === encKey) merged[id] = {
756
- ...held,
757
- view: fromChain.view
758
- };
759
- }
760
- return merged;
761
- };
762
- //#endregion
763
- //#region ../../packages/module/passport-account/src/flows/create-account.ts
764
- /** The initial device entry is inserted at epoch 0 with use counter 0. */
765
- const INITIAL_DEVICE_EPOCH = require_gated_call.DeviceEpoch(0n);
766
- const INITIAL_USE_COUNTER_VALUE = "0";
767
- /**
768
- * The record of a creation left unfinished on this device, read inside
769
- * the session once presence reported one. A record that opens without a
770
- * pending deployment, or that this authoriser cannot open, refuses with
771
- * AccountExistsError: it names an account that must not be created over.
772
- * A record that carries only the marker of its creation, which a hosted
773
- * signer shows no flow but the creation, cannot be resumed and is
774
- * refused, as is one started under another lock choice than
775
- * `lockAccount`, with CreationLockMismatchError naming the recorded one.
776
- */
777
- const pendingRecord = async (accountRecords, lockAccount) => {
778
- const record = await accountRecords.read();
779
- if (!record?.deployment) throw new require_errors.AccountExistsError();
780
- 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.`);
781
- if (record.deployment.lockAccount !== lockAccount) throw lockChoiceMismatch(record.deployment.lockAccount);
782
- return {
783
- ...record,
784
- deployment: record.deployment
785
- };
786
- };
787
- /**
788
- * Runs the deployment: a fresh one, which draws the account keys first,
789
- * deploys with their `enc_key` and records the pending deployment, with
790
- * this device's envelope and registration, as soon as the deploy lands
791
- * so an interruption can be resumed; or the remaining waves of a
792
- * recorded one, with the key entries it recorded.
793
- */
794
- const deploy = async ({ providers, lockAccount, pending, local, context: { seams, accountRecords } }) => {
795
- const { passportAuthoriser, passportEncryptionKey, passportNetwork } = seams;
796
- if (pending) return {
797
- deployed: await require_gated_call.resumeAccountDeployment({
798
- providers,
799
- authoriser: passportAuthoriser,
800
- address: pending.address,
801
- pending: pending.deployment
802
- }),
803
- pending: pending.deployment
804
- };
805
- const keys = await passportEncryptionKey.createKeys(passportNetwork.networkId, { devicePublicKey: local.devicePublicKey });
806
- const keyEntries = [...keys.envelopes, ...keys.registrations].map((entry) => require_bytes_vo.HexBytes.fromByteArray(entry));
807
- const progress = {};
808
- const deployed = await require_gated_call.deployAccount({
809
- providers,
810
- authoriser: passportAuthoriser,
811
- encPublicKey: keys.encKey,
812
- lockAccount,
813
- onDeployed: async (address, deployment) => {
814
- progress.recorded = {
815
- ...deployment,
816
- keyEntries
817
- };
818
- await accountRecords.write({
819
- address,
820
- bindingVersion: require_artefact_loader.accManifest.bindingVersion,
821
- localUseCounter: INITIAL_USE_COUNTER_VALUE,
822
- deployment: progress.recorded
823
- });
824
- }
825
- });
826
- if (!progress.recorded) throw new Error("The deployment landed without reporting its progress.");
827
- return {
828
- deployed,
829
- pending: progress.recorded
830
- };
831
- };
832
- /**
833
- * Creates a Passport account: the passkey ceremony (implicit in the first
834
- * authoriser use), the account keys drawn through the encryption key
835
- * seam, the Account Custody Contract deployment in waves with sponsored
836
- * fees, the initial device activation, the delivery of the account keys
837
- * to this device's inbox, and the local persistence of the account
838
- * record. Every step runs inside one key session, so the whole flow costs
839
- * a single ceremony rather than one per authoriser call. The flow never
840
- * holds the encryption secret: the seam draws it at random, seals it to
841
- * this device's reader key and hands back only its public key, which the
842
- * constructor takes as `enc_key`, with this device's envelope and its
843
- * registration under a fresh roster key; once the device is active, both
844
- * are appended to the inbox, one gated call each, so the account keys
845
- * live on chain from the start.
846
- *
847
- * Progress is reported through `onProgress`: 'deploying' once the
848
- * authoriser has produced the device key, 'proving' and 'sponsoring' from
849
- * inside each transaction submission (a transaction proves first, then
850
- * the sponsor balances it), 'activating' before the activation call and
851
- * 'recording' before the key entries are appended. The record is written
852
- * before the promise resolves, so a process that dies right after still
853
- * recognises the account on next startup.
854
- *
855
- * The flow runs to completion once started: cancelling mid-deploy could
856
- * orphan a contract the sponsor already paid for. The caller's flow gate
857
- * is what keeps a second request from starting one. Should the process
858
- * die between waves anyway, the record written when the deploy landed
859
- * names the contract, what it still needs and the key entries, and the
860
- * next create request on this device resumes from the operations the
861
- * chain holds, activates once every wave is in and appends whichever key
862
- * entry the inbox still lacks; a creation that died after its activation
863
- * landed resumes from there. A resumed creation finishes exactly as it
864
- * began, with the keys recorded then: a request under another lock choice
865
- * than the recorded one is refused with CreationLockMismatchError, and a
866
- * build pinning other verifier keys than the recorded deployment with
867
- * CreationArtefactMismatchError, both before any wave. The session names
868
- * the lock choice, so an authoriser that asks consent first shows it; a
869
- * hosted signer refuses the same lock mismatch itself, and a resume
870
- * started from another origin than the creation it resumes.
871
- *
872
- * A device already holding a completed account record refuses with
873
- * AccountExistsError before the ceremony runs: the record is the only
874
- * pointer to the deployed contract and there is no recovery path, so
875
- * creating over it would orphan the existing account. Presence is read
876
- * without opening the record, and it tells a completed record from an
877
- * unfinished one, so a sealed record blocks the flow without costing a
878
- * prompt and only a record the flow may resume is opened, inside the
879
- * session, where it costs no extra prompt.
880
- */
881
- const createAccount = async ({ lockAccount }, context) => {
882
- const { seams, accountRecords, onProgress } = context;
883
- const presence = await accountRecords.presence();
884
- if (presence === "complete") throw new require_errors.AccountExistsError();
885
- const { passportAuthoriser, passportNetwork, passportProver, passportSponsor } = seams;
886
- return inKeySession(passportAuthoriser, {
887
- kind: "create-account",
888
- lockAccount
889
- }, async () => {
890
- const local = await readLocalDevice(seams);
891
- const pending = presence === "pending" ? await pendingRecord(accountRecords, lockAccount) : void 0;
892
- onProgress("deploying");
893
- const { deployed, pending: deployment } = await deploy({
894
- providers: await require_providers.createMidnightProviders({
895
- network: passportNetwork,
896
- prover: passportProver,
897
- sponsor: passportSponsor,
898
- onStage: onProgress
899
- }),
900
- lockAccount,
901
- pending,
902
- local,
903
- context
904
- });
905
- if (!deployed.isActivated) {
906
- onProgress("activating");
907
- await deployed.activate();
908
- }
909
- const account = {
910
- address: deployed.address,
911
- bindingVersion: require_artefact_loader.accManifest.bindingVersion,
912
- status: "ready",
913
- networkId: passportNetwork.networkId
914
- };
915
- const startCounter = pending?.localUseCounter ?? INITIAL_USE_COUNTER_VALUE;
916
- const { indexer, ledgerState } = await require_account_call.readAccountLedger(deployed.address, passportNetwork);
917
- const held = new Set(inboxEntries(ledgerState).map((entry) => require_bytes_vo.HexBytes.fromByteArray(entry)));
918
- const chain = callChain({
919
- account,
920
- start: {
921
- ledgerState,
922
- localUseCounter: startCounter,
923
- devices: [{
924
- commitmentHex: await passportAuthoriser.deviceCommitment(require_providers.AccAddress(deployed.address), INITIAL_DEVICE_EPOCH, require_gated_call.UseCounter(BigInt(startCounter))),
925
- isLocal: true
926
- }]
927
- },
928
- indexer,
929
- seams,
930
- onProgress,
931
- onAdvanced: async (localUseCounter) => accountRecords.write({
932
- address: account.address,
933
- bindingVersion: account.bindingVersion,
934
- localUseCounter,
935
- deployment
936
- })
937
- });
938
- await chain.append("recording", deployment.keyEntries.filter((entry) => !held.has(entry)).map((entry) => require_bytes_vo.ByteArray.fromHex(require_bytes_vo.HexBytes(entry))));
939
- const { localUseCounter, devices } = chain.position();
940
- const counter = localUseCounter ?? startCounter;
941
- await accountRecords.write(completedRecord(account, counter, {}));
942
- return {
943
- account,
944
- devices,
945
- localUseCounter: counter,
946
- grants: [],
947
- encKey: require_bytes_vo.HexBytes.fromByteArray(ledgerState.enc_key)
948
- };
949
- });
950
- };
951
- //#endregion
952
- //#region ../../packages/module/passport-account/src/acc/read-grants.ts
953
- const NO_SLOTS = /* @__PURE__ */ new Map();
954
- const NO_OPENINGS = /* @__PURE__ */ new Map();
955
- /** The slot reported for a grant whose slot this client never learned. */
956
- const UNKNOWN_SLOT = require_grant_rules.GrantSlot(0);
957
- const toNumber = (field, value) => {
958
- if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new Error(`Grant field ${field} exceeds the safe integer range`);
959
- return Number(value);
960
- };
961
- const toOperations = (scope) => {
962
- const operations = [];
963
- if (scope.op_withdraw_unshielded) operations.push("withdraw-unshielded");
964
- if (scope.op_withdraw_shielded) operations.push("withdraw-shielded");
965
- if (scope.op_withdraw_shielded_to_contract) operations.push("withdraw-shielded-to-contract");
966
- return operations;
967
- };
968
- const toScope = (scope) => ({
969
- operations: toOperations(scope),
970
- read: scope.read,
971
- objectCommit: require_bytes_vo.HexBytes.fromByteArray(scope.object_commit),
972
- perCallCap: scope.per_call_cap.toString(),
973
- cap: scope.cap.toString(),
974
- expiresAt: scope.expires_at === 0n ? null : toNumber("expires_at", scope.expires_at),
975
- rpCommit: require_bytes_vo.HexBytes.fromByteArray(scope.rp_commit),
976
- readPkHash: require_bytes_vo.HexBytes.fromByteArray(scope.read_pk_hash),
977
- window: scope.window_len === 0n ? null : {
978
- lengthSeconds: toNumber("window_len", scope.window_len),
979
- cap: scope.window_cap.toString()
980
- },
981
- callerCommit: require_bytes_vo.HexBytes.fromByteArray(scope.caller_commit)
982
- });
983
- const toRecord = (id, record, { slot, opening }) => ({
984
- id,
985
- slot,
986
- active: record.active,
987
- epoch: toNumber("epoch", record.epoch),
988
- generation: toNumber("gen", record.gen),
989
- issuedAt: toNumber("issued_at", record.issued_at),
990
- scope: toScope(record.scope),
991
- spentWindow: {
992
- start: toNumber("window_start", record.window_start),
993
- spent: record.window_spent.toString()
994
- },
995
- ...opening ? { opening } : {}
996
- });
997
- /**
998
- * Decodes the account's grant roster from the ledger's grants map, in the
999
- * map's order. Plain fields decode to the read model's numbers and
1000
- * decimal strings, commitments stay as hex, and an expiry or window of
1001
- * zero reads as none. A revoked grant stays in the map as an inactive
1002
- * tombstone and is listed as such. The contract stores no slot: the
1003
- * caller supplies the slots of the grants it issued, and a grant issued by
1004
- * another client of the account reports slot 0. The openings the caller
1005
- * holds are attached to their grants.
1006
- */
1007
- const readGrants = (ledgerState, slots = NO_SLOTS, openings = NO_OPENINGS) => Array.from(ledgerState.grants, ([rawId, record]) => {
1008
- const id = require_grant_rules.GrantId(require_bytes_vo.HexBytes.fromByteArray(rawId));
1009
- return toRecord(id, record, {
1010
- slot: slots.get(id) ?? UNKNOWN_SLOT,
1011
- opening: openings.get(id)
1012
- });
1013
- });
1014
- //#endregion
1015
- //#region ../../packages/module/passport-account/src/flows/devices.ts
1016
- /**
1017
- * Contract aborts meaning the removal would leave the account without an
1018
- * authorising device: the caller rule and the redundant count floor.
1019
- */
1020
- const LAST_DEVICE_ABORTS = ["failed assert: cannot remove the authorising device", "failed assert: cannot remove last device"];
1021
- /**
1022
- * Types a raw contract abort by the assert message the Account Custody
1023
- * Contract raises; anything unrecognised passes through unchanged.
1024
- * An unknown-entry abort on the remove circuit is attributed to the
1025
- * removal target, not the caller: the circuit checks the caller first,
1026
- * and the caller's entry was resolved against live ledger state inside
1027
- * the same gate, so only a mid-flight roll of the caller's own entry
1028
- * could produce it, while a stale target commitment always does.
1029
- */
1030
- const classifyContractAbort$1 = (error, circuit) => {
1031
- const message = error instanceof Error ? error.message : String(error);
1032
- if (LAST_DEVICE_ABORTS.some((abort) => message.includes(abort))) return new require_errors.LastDeviceError(message);
1033
- if (message.includes("failed assert: unknown device entry")) return circuit === "remove_device_with_jubjub" ? new require_errors.RemovalTargetNotFoundError(message) : new require_errors.NotAuthorisedError(message);
1034
- if (require_account_call.isNotAuthorisedAbort(message)) return new require_errors.NotAuthorisedError(message);
1035
- return error;
1036
- };
1037
- /**
1038
- * Whether any read grant of the account is live: its grantees hold the
1039
- * live account secret, so a device handed the keys while one is live
1040
- * gets a fresh secret first.
1041
- */
1042
- const hasLiveReadGrant = (ledgerState) => readGrants(ledgerState).some((record) => record.active && record.scope.read);
1043
- /** The devices list with the enrolled commitment appended. */
1044
- const withDevice = (devices, commitmentHex) => [...devices, {
1045
- commitmentHex,
1046
- isLocal: false
1047
- }];
1048
- /** The devices list with the revoked commitment dropped. */
1049
- const withoutDevice = (devices, commitmentHex) => devices.filter((device) => device.commitmentHex !== commitmentHex);
1050
- /** A device's entry as the call that targets it takes it. */
1051
- const entryArgument = (commitmentHex) => require_bytes_vo.ByteArray.fromHex(require_bytes_vo.HexBytes(commitmentHex.toLowerCase()));
1052
- /** The counter the chain left this device at, or the one it started from. */
1053
- const chainCounter = (chain, input) => chain.position().localUseCounter ?? input.localUseCounter ?? "0";
1054
- /**
1055
- * Opens what a device flow runs on inside its key session: the grant
1056
- * bookkeeping of the record, read where it costs no extra prompt so every
1057
- * write keeps it, and a chain of gated calls from the ledger read ahead
1058
- * of the session, each persisting the counter it advanced this device to
1059
- * before the next call. The bookkeeping is checked against the ledger
1060
- * first, so an entry that does not open the grant the chain holds under
1061
- * its id, as one an issue wrote before a call that never landed, is
1062
- * neither re-sealed to nor kept.
1063
- */
1064
- const openDeviceSession = async (input, { ledgerState, indexer }, { seams, accountRecords, onProgress }) => {
1065
- const { account, devices, localUseCounter } = input;
1066
- let grants = await retainStoredGrants((await accountRecords.read())?.grants, readGrants(ledgerState), account.address);
1067
- const write = async (counter) => accountRecords.write(completedRecord(account, counter, { grants }));
1068
- const chain = callChain({
1069
- account,
1070
- start: {
1071
- ledgerState,
1072
- localUseCounter,
1073
- devices
1074
- },
1075
- indexer,
1076
- seams,
1077
- onProgress,
1078
- onAdvanced: write
1079
- });
1080
- return {
1081
- grants,
1082
- chain,
1083
- keep: async (next) => {
1084
- grants = next;
1085
- await write(chainCounter(chain, input));
1086
- }
1087
- };
1088
- };
1089
- /**
1090
- * Enrols a new device key on the account. `commitmentHex` carries the new
1091
- * device's entry commitment, derived out of band by the joining device;
1092
- * the local device authorises `add_device_with_jubjub` through the
1093
- * gated-call pattern. The roster gains the commitment on success only,
1094
- * marked as remote, and the same result moves the local device's own row
1095
- * to the successor entry the call left it on, so the roster and the use
1096
- * counter never disagree about where this device stands.
1097
- *
1098
- * When `reader` names the joining device's reader and device keys, the
1099
- * account keys are delivered to it in the same session: its device key
1100
- * must derive the enrolled commitment at use counter 0 and its reader key
1101
- * must be one the account seals to, both checked before any prompt. The
1102
- * encryption key seals the live secret and the roster key to the reader
1103
- * key, and the envelope and the device's registration under the roster
1104
- * key are appended to the inbox, one gated call each, ahead of the
1105
- * enrolment, so an enrolment that lands never leaves the device without
1106
- * its keys; until it lands the registration names no live entry and a
1107
- * rotation passes over it. While any read grant is live its grantees
1108
- * hold the live secret, and one could seal it to the joining reader with
1109
- * a roster key of its own ahead of the genuine envelope, so the account
1110
- * keys are rotated first in the same session, with a fresh roster key,
1111
- * as a removal rotates them, the joining device handed the new secret no
1112
- * grantee has seen, and the live read grants this client holds the read
1113
- * key of sealed it after; with no live read grant only enrolled devices
1114
- * hold the secret, and the live keys are handed over as they are. The
1115
- * joining device then signs in and reads the holdings with its own
1116
- * passkey alone. Without `reader` the
1117
- * device can authorise but reads nothing until some device delivers it
1118
- * the keys.
1119
- *
1120
- * The advanced counter is persisted to the account record after every
1121
- * call, before the roster is returned, so the next flow rescans from a
1122
- * fresh anchor. A failure leaves the roster unreturned.
1123
- *
1124
- * A rejected authorisation (bad signature, malformed key, or a caller
1125
- * entry the on-chain set no longer holds) rejects with NotAuthorisedError;
1126
- * a record whose address holds no live contract rejects with
1127
- * AccountContractMissingError; joining keys that do not match the entry
1128
- * reject with DeviceReaderInvalidError. The transactions' proving and
1129
- * sponsoring stages and 'recording' are reported through `onProgress`.
1130
- */
1131
- const addDevice = async ({ reader, ...input }, context) => {
1132
- const { seams, onProgress } = context;
1133
- const { account, commitmentHex } = input;
1134
- const { networkId } = seams.passportNetwork;
1135
- try {
1136
- const ledger = await require_account_call.readAccountLedger(account.address, seams.passportNetwork);
1137
- if (reader) require_device_readers.assertJoiningDevice({
1138
- address: account.address,
1139
- epoch: ledger.ledgerState.device_epoch
1140
- }, reader, commitmentHex);
1141
- const view = reader && hasLiveReadGrant(ledger.ledgerState) ? viewCapability(seams.passportEncryptionKey) : void 0;
1142
- const devices = view ? liveDeviceEntries(ledger.ledgerState) : void 0;
1143
- return await inKeySession(seams.passportAuthoriser, {
1144
- kind: "add-device",
1145
- commitmentHex,
1146
- account: require_providers.AccAddress(account.address),
1147
- ...reader ? { reader } : {},
1148
- ...devices ? { devices } : {}
1149
- }, async () => {
1150
- const { grants, chain, keep } = await openDeviceSession(input, ledger, context);
1151
- let rotated;
1152
- if (reader) {
1153
- const local = await readLocalDevice(seams);
1154
- if (view && devices) rotated = await rotateEncKey({
1155
- account,
1156
- encryptionKey: seams.passportEncryptionKey,
1157
- view,
1158
- local,
1159
- chain,
1160
- indexer: ledger.indexer,
1161
- networkId,
1162
- onProgress,
1163
- devices,
1164
- rotateRoster: true
1165
- });
1166
- const delivery = await seams.passportEncryptionKey.sealToDevice(networkId, rotated?.keyring ?? readAccountInbox(account.address, chain.position().ledgerState, local.readerPublicKey).keyring, {
1167
- ...reader,
1168
- epoch: ledger.ledgerState.device_epoch,
1169
- counter: 0n
1170
- });
1171
- await chain.append("recording", [delivery.envelope, delivery.registration]);
1172
- if (view && rotated) {
1173
- const views = await sealViews({
1174
- view,
1175
- networkId,
1176
- keyring: rotated.keyring,
1177
- account: require_providers.AccAddress(account.address),
1178
- targets: liveStoredReadGrants(grants, readGrants(chain.position().ledgerState))
1179
- });
1180
- await keep(withSealedViews(grants, views));
1181
- await chain.append("recording", views.entries);
1182
- }
1183
- }
1184
- await chain.submit({
1185
- circuit: ADD_DEVICE_CIRCUIT,
1186
- args: [entryArgument(commitmentHex)]
1187
- });
1188
- return {
1189
- devices: withDevice(chain.position().devices, commitmentHex),
1190
- localUseCounter: chainCounter(chain, input),
1191
- ...rotated ? {
1192
- encKey: require_bytes_vo.HexBytes.fromByteArray(rotated.encKey),
1193
- droppedDevices: rotated.dropped
1194
- } : {}
1195
- };
1196
- });
1197
- } catch (error) {
1198
- throw classifyContractAbort$1(error, ADD_DEVICE_CIRCUIT);
1199
- }
1200
- };
1201
- /**
1202
- * Refuses a removal the contract would refuse before any prompt: a
1203
- * target the on-chain device set does not hold, and the local device,
1204
- * which cannot remove itself. The rotation a removal runs comes first,
1205
- * so a removal refused only after it would have cost the target device
1206
- * its keys for nothing.
1207
- *
1208
- * @throws {@link RemovalTargetNotFoundError} when the target is gone.
1209
- * @throws {@link LastDeviceError} when the target is this device.
1210
- */
1211
- const assertRemovable = ({ devices, commitmentHex }, { ledgerState }) => {
1212
- if (!ledgerState.devices.member(entryArgument(commitmentHex))) throw new require_errors.RemovalTargetNotFoundError(`The account holds no device entry ${commitmentHex}.`);
1213
- if (devices.find((device) => device.isLocal)?.commitmentHex.toLowerCase() === commitmentHex.toLowerCase()) throw new require_errors.LastDeviceError("The device that authorises a removal cannot remove itself.");
1214
- };
1215
- /**
1216
- * Revokes a device key from the account and rotates the account keys so
1217
- * the removed device reads nothing newer. `commitmentHex` names the
1218
- * target by its current entry commitment, which is the literal set
1219
- * element the contract removes; the local device authorises
1220
- * `remove_device_with_jubjub` through the gated-call pattern.
1221
- *
1222
- * Ahead of the removal, in the same session, the encryption key is
1223
- * rotated with a fresh roster key and sealed only to this device and to
1224
- * the registered devices whose device key derives a live entry other
1225
- * than the target, which the key session names to the user before it
1226
- * opens; the live holdings are re-encrypted towards it, and it is sealed
1227
- * again to every live read grant this client holds the read key of, each
1228
- * seal kept on chain in a grant record. The removed device's envelopes
1229
- * stay in the inbox and keep opening the secrets they held, but none
1230
- * opens the new one, and the registrations under the old roster key no
1231
- * longer count, any it planted for itself included. A roster in which
1232
- * two readers claim one live device, or one reader two, refuses with
1233
- * DeviceRosterInvalidError rather than guess.
1234
- *
1235
- * The roster drops the commitment on success only, and the same result
1236
- * moves the local device's own row to the successor entry the call left
1237
- * it on. The advanced counter is persisted to the account record after
1238
- * every call. The contract's own guards surface as typed errors: a
1239
- * removal that would strand the account (the authorising device, or the
1240
- * count floor) rejects with LastDeviceError, a rejected authorisation
1241
- * (bad signature or malformed key) with NotAuthorisedError, and a target
1242
- * entry that is no longer in the on-chain set with
1243
- * RemovalTargetNotFoundError; the target's presence and the local device
1244
- * are checked before any prompt, and an encryption key that cannot
1245
- * rotate refuses with ReadUnavailableError before any prompt too. The
1246
- * rotation's stages, 'recording' and the transactions' proving and
1247
- * sponsoring are reported through `onProgress`.
1248
- */
1249
- const removeDevice = async (input, context) => {
1250
- const { seams, onProgress } = context;
1251
- const { account, commitmentHex } = input;
1252
- const { networkId } = seams.passportNetwork;
1253
- try {
1254
- const view = viewCapability(seams.passportEncryptionKey);
1255
- const ledger = await require_account_call.readAccountLedger(account.address, seams.passportNetwork);
1256
- assertRemovable(input, ledger);
1257
- const devices = liveDeviceEntries(ledger.ledgerState, commitmentHex);
1258
- return await inKeySession(seams.passportAuthoriser, {
1259
- kind: "remove-device",
1260
- commitmentHex,
1261
- account: require_providers.AccAddress(account.address),
1262
- devices
1263
- }, async () => {
1264
- const { grants, chain, keep } = await openDeviceSession(input, ledger, context);
1265
- const rotated = await rotateEncKey({
1266
- account,
1267
- encryptionKey: seams.passportEncryptionKey,
1268
- view,
1269
- local: await readLocalDevice(seams),
1270
- chain,
1271
- indexer: ledger.indexer,
1272
- networkId,
1273
- onProgress,
1274
- devices,
1275
- rotateRoster: true,
1276
- target: commitmentHex.toLowerCase()
1277
- });
1278
- const views = await sealViews({
1279
- view,
1280
- networkId,
1281
- keyring: rotated.keyring,
1282
- account: require_providers.AccAddress(account.address),
1283
- targets: liveStoredReadGrants(grants, readGrants(chain.position().ledgerState))
1284
- });
1285
- await keep(withSealedViews(grants, views));
1286
- await chain.append("recording", views.entries);
1287
- await chain.submit({
1288
- circuit: REMOVE_DEVICE_CIRCUIT,
1289
- args: [entryArgument(commitmentHex)]
1290
- });
1291
- return {
1292
- devices: withoutDevice(chain.position().devices, commitmentHex),
1293
- localUseCounter: chainCounter(chain, input),
1294
- encKey: require_bytes_vo.HexBytes.fromByteArray(rotated.encKey),
1295
- droppedDevices: rotated.dropped
1296
- };
1297
- });
1298
- } catch (error) {
1299
- throw classifyContractAbort$1(error, REMOVE_DEVICE_CIRCUIT);
1300
- }
1301
- };
1302
- //#endregion
1303
- //#region ../../packages/module/passport-account/src/flows/grants.ts
1304
- /** Contract abort naming a grant the grants map does not hold. */
1305
- const UNKNOWN_GRANT_ABORT = "failed assert: unknown grant";
1306
- /** Contract abort refusing a revoke over a grant already inactive. */
1307
- const GRANT_NOT_LIVE_ABORT = "failed assert: grant not live";
1308
- /** Contract abort refusing an issue over a grant id that is still active. */
1309
- const GRANT_ACTIVE_ABORT = "failed assert: grant already active";
1310
- /**
1311
- * How long an accepted call is given to show in the indexer's view of the
1312
- * grants map, which can lag the block the call landed in.
1313
- */
1314
- const ROSTER_POLL_ATTEMPTS = 30;
1315
- const ROSTER_POLL_DELAY_MS = 1e3;
1316
- const MILLISECONDS_PER_SECOND = 1e3;
1317
- const sleep = async (ms) => new Promise((resolve) => {
1318
- setTimeout(resolve, ms);
1319
- });
1320
- const isActive = (roster, grantId) => roster.some((record) => record.id === grantId && record.active);
1321
- const activeCount = (roster) => roster.filter((record) => record.active).length;
1322
- const nowSeconds = () => Math.floor(Date.now() / MILLISECONDS_PER_SECOND);
1323
- /**
1324
- * Types a raw contract abort by the assert message the Account Custody
1325
- * Contract raises; anything unrecognised passes through unchanged. An
1326
- * unknown-entry abort can only come from the caller check here, since no
1327
- * grant circuit names a device entry.
1328
- */
1329
- const classifyContractAbort = (error) => {
1330
- const message = error instanceof Error ? error.message : String(error);
1331
- if (message.includes(UNKNOWN_GRANT_ABORT)) return new require_errors.GrantNotFoundError(message);
1332
- if (message.includes(GRANT_NOT_LIVE_ABORT)) return new require_errors.GrantRevokedError(message);
1333
- if (message.includes(GRANT_ACTIVE_ABORT)) return new require_errors.GrantIssueRejectedError(message);
1334
- if (message.includes("failed assert: unknown device entry") || require_account_call.isNotAuthorisedAbort(message)) return new require_errors.NotAuthorisedError(message);
1335
- return error;
1336
- };
1337
- /**
1338
- * Refuses a device whose storage holds no account record before any
1339
- * ceremony. The gate only runs a call over an account in state, so an
1340
- * absent record means the storage was cleared underneath it.
1341
- */
1342
- const assertRecordPresent = async (accountRecords) => {
1343
- if (await accountRecords.presence() === "absent") throw new require_errors.AccountNotFoundError("No Passport account record is stored on this device.");
1344
- };
1345
- /**
1346
- * The stored record of the account a grant call acts on, read inside the
1347
- * session where it costs no extra prompt. Presence was checked ahead of
1348
- * the session, so a missing record here vanished in between.
1349
- */
1350
- const storedRecord = async (accountRecords) => {
1351
- const record = await accountRecords.read();
1352
- if (!record) throw new require_errors.AccountNotFoundError("No Passport account record is stored on this device.");
1353
- return record;
1354
- };
1355
- /**
1356
- * The ledger state once the indexer reflects the accepted call, with the
1357
- * roster read from it. The submission settled in a block, but the
1358
- * indexer can serve the state from before it for a moment, and a roster
1359
- * read then would deny the call its own result.
1360
- *
1361
- * @throws {@link GrantRosterUnsettledError} when the indexer never
1362
- * reflects the call within the polling window.
1363
- */
1364
- const awaitSettledRoster = async ({ indexer, address, slots, openings, isSettled }) => {
1365
- for (let attempt = 0; attempt < ROSTER_POLL_ATTEMPTS; attempt++) {
1366
- const ledgerState = await require_account_call.queryAccountLedger(indexer, address);
1367
- const roster = readGrants(ledgerState, slots, openings);
1368
- if (isSettled(roster)) return {
1369
- ledgerState,
1370
- roster
1371
- };
1372
- await sleep(ROSTER_POLL_DELAY_MS);
1373
- }
1374
- throw new require_errors.GrantRosterUnsettledError(`The grant roster of ${address} never reflected the accepted call.`);
1375
- };
1376
- /**
1377
- * Runs one gated grant call inside a single key session, so the use
1378
- * counter rescan and the authorisation cost one ceremony rather than one
1379
- * per authoriser call. A device whose storage holds no record is refused
1380
- * ahead of the session. The record is read inside it, where it costs no
1381
- * extra prompt, its grant bookkeeping narrowed to the grants whose kept
1382
- * fields open what the ledger read before the call holds under their id,
1383
- * so an entry an issue wrote before a call that never landed is neither
1384
- * an opening nor a re-seal target. It is rewritten with the advanced
1385
- * counter and the grant bookkeeping after every call, so a roster is
1386
- * never published ahead of the record that anchors the next rescan and
1387
- * names the slots. A call
1388
- * that keeps its bookkeeping ahead of the submission writes it once more
1389
- * before it, under the counter the record holds. A call that rotates the
1390
- * encryption key does so in the same session ahead of its own circuit.
1391
- * The other live read grants are sealed the new secret right after the
1392
- * rotation lands, their seals kept in the record and on chain before the
1393
- * call is submitted, so they keep reading whatever the call's outcome.
1394
- * Once the roster shows an issued grant active, its bookkeeping is
1395
- * appended to the inbox, sealed to this device alone, and the grantee of
1396
- * a read grant is sealed the new secret, the seal kept the same way. The
1397
- * wait for the indexer is reported as 'confirming' and the appends as
1398
- * 'recording'. The contract's own aborts surface as typed errors;
1399
- * anything else, and a failing on-chain status in particular, rejects
1400
- * unchanged with the counter unmoved.
1401
- */
1402
- 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 } }) => {
1403
- const { networkId } = seams.passportNetwork;
1404
- const accountAddress = require_providers.AccAddress(account.address);
1405
- try {
1406
- await assertRecordPresent(accountRecords);
1407
- const rotationDevices = rotation ? liveDeviceEntries(ledgerState) : void 0;
1408
- return await inKeySession(seams.passportAuthoriser, rotationDevices ? {
1409
- ...flow,
1410
- devices: rotationDevices
1411
- } : flow, async () => {
1412
- const record = await storedRecord(accountRecords);
1413
- let stored = nextStoredGrants(await retainStoredGrants(record.grants, listed, account.address));
1414
- const write = async (counter) => accountRecords.write(completedRecord(account, counter, { grants: stored }));
1415
- if (writeBeforeCall) await write(record.localUseCounter);
1416
- const chain = callChain({
1417
- account,
1418
- start: {
1419
- ledgerState,
1420
- localUseCounter,
1421
- devices
1422
- },
1423
- indexer,
1424
- seams,
1425
- onProgress,
1426
- onAdvanced: write
1427
- });
1428
- const counter = () => chain.position().localUseCounter ?? record.localUseCounter;
1429
- const roster = (state) => readGrants(state, storedGrantSlots(stored), storedGrantOpenings(stored));
1430
- let rotated;
1431
- let unsealedGrantIds = [];
1432
- let revocationPendingGrantIds = [];
1433
- if (rotation) {
1434
- rotated = await rotateEncKey({
1435
- account,
1436
- encryptionKey: seams.passportEncryptionKey,
1437
- view: rotation,
1438
- local: await readLocalDevice(seams),
1439
- chain,
1440
- indexer,
1441
- networkId,
1442
- onProgress,
1443
- devices: rotationDevices ?? []
1444
- });
1445
- if (reseal) {
1446
- const views = await sealViews({
1447
- view: rotation,
1448
- networkId,
1449
- keyring: rotated.keyring,
1450
- account: accountAddress,
1451
- targets: liveStoredReadGrants(stored, roster(chain.position().ledgerState), reseal.except)
1452
- });
1453
- stored = withSealedViews(stored, views);
1454
- unsealedGrantIds = views.unsealed;
1455
- revocationPendingGrantIds = views.revocationPending;
1456
- await write(counter());
1457
- await chain.append("recording", views.entries);
1458
- }
1459
- }
1460
- await chain.submit(call);
1461
- onProgress("confirming");
1462
- const settled = await awaitSettledRoster({
1463
- indexer,
1464
- address: account.address,
1465
- slots: storedGrantSlots(stored),
1466
- openings: storedGrantOpenings(stored),
1467
- isSettled
1468
- });
1469
- let grants = settled.roster;
1470
- if (issued) {
1471
- const entries = await seams.passportEncryptionKey.sealGrant(networkId, accountAddress, issued.bookkeeping);
1472
- if (rotation && rotated && issued.readPublicKey !== void 0) {
1473
- const views = await sealViews({
1474
- view: rotation,
1475
- networkId,
1476
- keyring: rotated.keyring,
1477
- account: accountAddress,
1478
- targets: [{
1479
- grantId: issued.bookkeeping.grantId,
1480
- readPublicKey: issued.readPublicKey
1481
- }]
1482
- });
1483
- stored = withSealedViews(stored, views);
1484
- unsealedGrantIds = [...unsealedGrantIds, ...views.unsealed];
1485
- revocationPendingGrantIds = [...revocationPendingGrantIds, ...views.revocationPending];
1486
- entries.push(...views.entries);
1487
- await write(counter());
1488
- grants = roster(settled.ledgerState);
1489
- }
1490
- await chain.append("recording", entries);
1491
- }
1492
- return {
1493
- grants,
1494
- devices: chain.position().devices,
1495
- localUseCounter: counter(),
1496
- ...rotated ? {
1497
- encKey: require_bytes_vo.HexBytes.fromByteArray(rotated.encKey),
1498
- droppedDevices: rotated.dropped
1499
- } : {},
1500
- unsealedGrantIds,
1501
- revocationPendingGrantIds
1502
- };
1503
- });
1504
- } catch (error) {
1505
- throw classifyContractAbort(error);
1506
- }
1507
- };
1508
- /**
1509
- * Refuses a grant its grantee could never spend: one naming a scheme
1510
- * whose withdrawals the account was deployed without. Installing them
1511
- * takes a maintenance update, which a locked account can no longer sign
1512
- * and an unlocked one no longer holds the key for, so the issue is
1513
- * refused before the owner is asked to authorise it.
1514
- *
1515
- * @throws {@link GrantScopeInvalidError} when a withdrawal of the
1516
- * grantee's scheme is not installed on the account.
1517
- */
1518
- const requireGranteeWithdrawals = async (indexer, address, scheme) => {
1519
- const installed = new Set(await require_account_call.queryAccountOperations(indexer, address));
1520
- const missing = require_grant_circuits.GRANTEE_WITHDRAWAL_CIRCUITS[scheme].filter((circuit) => !installed.has(circuit));
1521
- if (missing.length > 0) throw new require_errors.GrantScopeInvalidError(`the account cannot serve a ${scheme} grantee, it lacks ${missing.join(", ")}`);
1522
- };
1523
- /**
1524
- * Issues a scoped grant to an agent key. The scope is checked against the
1525
- * rules the contract asserts before any prompt: a shielded operation
1526
- * needs read, a read grant needs a canonical read public key, a rolling
1527
- * window is refused because the contract reserves its bounds, and a
1528
- * grant beyond sixteen active ones is refused as Lace's limit. Each
1529
- * refusal is a GrantScopeInvalidError or GrantLimitReachedError and costs
1530
- * no ceremony; a host with no relying party id is refused with
1531
- * GrantOriginMissingError before the chain is read, and a read grant
1532
- * with ReadUnavailableError when the encryption key held here cannot
1533
- * share the viewing secret. The grant id is derived from the account,
1534
- * the grantee key, the hash of this host's relying party id and the
1535
- * first slot free for that pair, and the scope salt is drawn fresh; the
1536
- * local device then authorises `issue_grant_with_jubjub` over the id and
1537
- * the salted scope digest, which binds the hash of the read key. The key
1538
- * session is opened with the account, the slot, the salt and the digest
1539
- * beside the id and the scope, so an authoriser that does not share this
1540
- * flow's memory can re-derive both before it signs.
1541
- *
1542
- * A read grant delivers the account's viewing secret, and read is total:
1543
- * the grantee sees every shielded holding, current and future, until the
1544
- * key is rotated again. So the key is rotated first, in the same session:
1545
- * a fresh random secret is sealed to every device, the live holdings are
1546
- * re-encrypted towards it, its public key replaces `enc_key`, and only
1547
- * then is the grant issued, so the grantee reads nothing of the
1548
- * account's spent history. Right after the rotation lands the new secret
1549
- * is sealed to every other live read grant this client holds the key of,
1550
- * so they keep reading even should the issue fail, and once the grant
1551
- * shows active it is sealed to the grantee's read key; the seals join
1552
- * the bookkeeping, and the grantee's reaches it through the agent
1553
- * policy, never the chain. A grantee seal the key seam refuses after the
1554
- * grant landed leaves the grant active and unsealed, named among the
1555
- * result's unsealed grants, rather than failing the issue.
1556
- *
1557
- * The slot and salt are kept in the account record, since the contract
1558
- * stores neither, together with the object fields its commitment hides
1559
- * (colour, recipient and coin bound) and the read key, which the grantee
1560
- * needs to open it and which reach the roster as the grant's opening.
1561
- * They are written before the call is submitted: a grant that lands
1562
- * without its salt could never be opened for its grantee. A call that
1563
- * never lands leaves a stale entry, which the next sign-in prunes against
1564
- * the chain and a later issue over the same id overwrites. Once the
1565
- * grant shows active the same bookkeeping, and each seal, is appended to
1566
- * the inbox in grant records only this device opens, so a sign-in after
1567
- * the record is lost rebuilds it. The roster is read back from chain
1568
- * once the grant shows active in it.
1569
- *
1570
- * A grant id the contract still holds active rejects with
1571
- * GrantIssueRejectedError, and a rejected authorisation with
1572
- * NotAuthorisedError. The transaction's proving and sponsoring stages,
1573
- * the rotation, the wait for the indexer and the appends are reported
1574
- * through `onProgress`.
1575
- */
1576
- const issueGrant = async ({ scope, ...input }, context) => {
1577
- const { rpId, seams } = context;
1578
- if (rpId === void 0) throw new require_errors.GrantOriginMissingError();
1579
- const view = scope.read ? viewCapability(seams.passportEncryptionKey) : null;
1580
- const { account } = input;
1581
- const ledger = await require_account_call.readAccountLedger(account.address, seams.passportNetwork);
1582
- await requireGranteeWithdrawals(ledger.indexer, account.address, scope.grantee.scheme);
1583
- const roster = readGrants(ledger.ledgerState);
1584
- require_grant_rules.validateGrantScope(scope, {
1585
- nowSeconds: nowSeconds(),
1586
- grantCount: activeCount(roster)
1587
- });
1588
- const { grantId, slot, scopeSalt, scopeDigest, call } = require_grants.prepareIssueGrant({
1589
- contractAddress: require_bytes_vo.ByteArray.fromHex(require_bytes_vo.HexBytes(account.address)),
1590
- scope,
1591
- originHash: await require_grants.originHash(rpId),
1592
- roster
1593
- });
1594
- const readPublicKey = view ? scope.readPublicKey : void 0;
1595
- const object = {
1596
- color: scope.color,
1597
- recipient: scope.recipient,
1598
- maxCoinValue: scope.maxCoinValue
1599
- };
1600
- return {
1601
- grantId,
1602
- ...await runGrantCall({
1603
- config: {
1604
- call,
1605
- flow: {
1606
- kind: "issue-grant",
1607
- grantId,
1608
- scope,
1609
- account: require_providers.AccAddress(account.address),
1610
- slot,
1611
- scopeSalt,
1612
- scopeDigest
1613
- },
1614
- nextStoredGrants: (stored) => withStoredGrant(stored, grantId, {
1615
- slot,
1616
- scopeSalt,
1617
- granteeScheme: scope.grantee.scheme,
1618
- granteePublicKey: scope.grantee.publicKey,
1619
- origin: rpId,
1620
- object,
1621
- ...readPublicKey === void 0 ? {} : { view: { readPublicKey } }
1622
- }),
1623
- writeBeforeCall: true,
1624
- isSettled: (settled) => isActive(settled, grantId),
1625
- ...view && readPublicKey !== void 0 ? {
1626
- rotation: view,
1627
- reseal: { except: grantId }
1628
- } : {},
1629
- issued: {
1630
- bookkeeping: {
1631
- grantId,
1632
- slot,
1633
- scopeSalt,
1634
- granteeScheme: scope.grantee.scheme,
1635
- granteePublicKey: scope.grantee.publicKey,
1636
- object,
1637
- ...readPublicKey === void 0 ? {} : { readPublicKey }
1638
- },
1639
- ...readPublicKey === void 0 ? {} : { readPublicKey }
1640
- }
1641
- },
1642
- input,
1643
- ledger,
1644
- roster,
1645
- context
1646
- })
1647
- };
1648
- };
1649
- /**
1650
- * The stored grants with the seal of one grant dropped, its read key
1651
- * kept: a revoked read grant's seal holds a secret the rotation that
1652
- * follows retires.
1653
- */
1654
- const withoutSeal = (stored, grantId) => {
1655
- const view = stored?.[grantId]?.view;
1656
- return stored && view ? withStoredGrantView(stored, grantId, { readPublicKey: view.readPublicKey }) : stored;
1657
- };
1658
- /**
1659
- * Revokes one grant by its id. A grant the chain does not hold is refused
1660
- * with GrantNotFoundError before any prompt, and one it lists inactive
1661
- * with GrantRevokedError; the same errors type the contract's own aborts
1662
- * should the grant vanish or be revoked elsewhere in between. The local
1663
- * device authorises `revoke_grant_with_jubjub`. The grant stays in the
1664
- * roster as an inactive tombstone, so its stored slot and salt are kept,
1665
- * and the roster is read back from chain once the grant shows inactive.
1666
- *
1667
- * Revoking a read grant also rotates the encryption key, in the same
1668
- * session ahead of the revocation: a fresh random secret is sealed to
1669
- * every device and the live holdings are re-encrypted towards it, so the
1670
- * revoked grantee keeps what it already read and nothing newer, and
1671
- * right after the rotation lands the new secret is sealed again to every
1672
- * other read grant this client holds the read key of, ahead of the
1673
- * revocation. A read grant is refused with ReadUnavailableError before
1674
- * any prompt when the encryption key held here cannot re-encrypt and
1675
- * seal.
1676
- */
1677
- const revokeGrant = async ({ grantId, ...input }, context) => {
1678
- const { account } = input;
1679
- const ledger = await require_account_call.readAccountLedger(account.address, context.seams.passportNetwork);
1680
- const roster = readGrants(ledger.ledgerState);
1681
- const listed = roster.find((record) => record.id === grantId);
1682
- if (!listed) throw new require_errors.GrantNotFoundError(`The account at ${account.address} holds no grant ${grantId}.`);
1683
- if (!listed.active) throw new require_errors.GrantRevokedError(`The grant ${grantId} of the account at ${account.address} is already revoked.`);
1684
- const rotation = listed.scope.read ? viewCapability(context.seams.passportEncryptionKey) : void 0;
1685
- return runGrantCall({
1686
- config: {
1687
- call: require_grants.prepareRevokeGrant(grantId),
1688
- flow: {
1689
- kind: "revoke-grant",
1690
- grantId,
1691
- account: require_providers.AccAddress(account.address),
1692
- ...rotation ? { read: true } : {}
1693
- },
1694
- nextStoredGrants: (stored) => rotation ? withoutSeal(stored, grantId) : stored,
1695
- writeBeforeCall: false,
1696
- isSettled: (settled) => !isActive(settled, grantId),
1697
- ...rotation ? {
1698
- rotation,
1699
- reseal: { except: grantId }
1700
- } : {}
1701
- },
1702
- input,
1703
- ledger,
1704
- roster,
1705
- context
1706
- });
1707
- };
1708
- /**
1709
- * Revokes every grant the account has issued: the local device
1710
- * authorises `revoke_all_grants_with_jubjub`, which clears the grants
1711
- * map and advances the grant generation. The record's grant bookkeeping
1712
- * is dropped with the map, and the roster is read back from chain once
1713
- * it lists nothing, tombstones included. While any read grant is live,
1714
- * the encryption key is rotated in the same session ahead of the call
1715
- * and the live holdings are re-encrypted, so no revoked grantee reads
1716
- * on; with every grant gone there is nobody to re-seal to. The rotation
1717
- * is refused with ReadUnavailableError before any prompt when the
1718
- * encryption key held here cannot re-encrypt.
1719
- */
1720
- const revokeAllGrants = async (input, context) => {
1721
- const { account } = input;
1722
- const ledger = await require_account_call.readAccountLedger(account.address, context.seams.passportNetwork);
1723
- const roster = readGrants(ledger.ledgerState);
1724
- const rotation = roster.some((record) => record.active && record.scope.read) ? viewCapability(context.seams.passportEncryptionKey) : void 0;
1725
- return runGrantCall({
1726
- config: {
1727
- call: require_grants.prepareRevokeAllGrants(),
1728
- flow: {
1729
- kind: "revoke-all-grants",
1730
- account: require_providers.AccAddress(account.address),
1731
- ...rotation ? { read: true } : {}
1732
- },
1733
- nextStoredGrants: () => void 0,
1734
- writeBeforeCall: false,
1735
- isSettled: (settled) => settled.length === 0,
1736
- ...rotation ? { rotation } : {}
1737
- },
1738
- input,
1739
- ledger,
1740
- roster,
1741
- context
1742
- });
1743
- };
1744
- //#endregion
1745
- //#region ../../packages/module/passport-account/src/flows/holdings.ts
1746
- /**
1747
- * Reads the account's shielded holdings from public chain data: the
1748
- * contract's inbox is walked with the account secrets this device's own
1749
- * envelopes deliver, the one deriving the ledger's `enc_key` first and
1750
- * the older ones after it, so a coin a racing sender or an interrupted
1751
- * rotation left under an earlier key is still found, and each coin that
1752
- * opens is kept only once its commitment is found among the outputs the
1753
- * chain created for the account, with the tree index it took. The
1754
- * envelopes are opened inside one key session, so the walk costs one
1755
- * ceremony however many entries the inbox holds, and none at all when
1756
- * it holds no coin to open; only the opened coin descriptions reach this
1757
- * flow, never a secret. Nothing is written: no record, no chain call.
1758
- *
1759
- * A record whose address holds no live contract rejects with
1760
- * AccountContractMissingError, and an inbox holding no envelope of this
1761
- * device that opens the ledger's `enc_key` with EncryptionKeyMismatchError
1762
- * rather than an inbox read as empty. An entry that fails to open or
1763
- * describes a coin the chain never created is skipped and counted, never
1764
- * an error; the account keys and grant bookkeeping the inbox also holds
1765
- * are not coins and are not counted.
1766
- *
1767
- * Reports no intermediate stage: the ceremony and the indexer reads all
1768
- * settle before there is anything to report.
1769
- */
1770
- const readShieldedHoldings = async ({ account }, { seams }) => {
1771
- const { passportAuthoriser, passportEncryptionKey, passportNetwork } = seams;
1772
- const indexer = require_account_call.createIndexerClient({
1773
- indexerUrl: passportNetwork.indexerUrl,
1774
- indexerWsUrl: passportNetwork.indexerWsUrl
1775
- });
1776
- const ledgerState = await require_account_call.queryAccountLedger(indexer, account.address);
1777
- const { holdings, skippedEntries } = await walkInbox({
1778
- address: account.address,
1779
- ledgerState,
1780
- indexer,
1781
- openEntries: async (entries) => inKeySession(passportAuthoriser, { kind: "read-holdings" }, async () => {
1782
- const { keyring } = readAccountInbox(account.address, ledgerState, await passportEncryptionKey.readerPublicKey(passportNetwork.networkId));
1783
- return (await passportEncryptionKey.openInbox(passportNetwork.networkId, keyring, entries)).map((entry) => entry?.kind === "coin" ? entry.coin : null);
1784
- })
1785
- });
1786
- return {
1787
- holdings,
1788
- skippedEntries
1789
- };
1790
- };
1791
- //#endregion
1792
- //#region ../../packages/module/passport-account/src/flows/sign-in.ts
1793
- /**
1794
- * The account's whole device roster, read from the on-chain device set.
1795
- * Entries are opaque rolling commitments, so a remote entry carries no
1796
- * identity beyond its commitment: only the local device can be named, by
1797
- * the commitment its own rescan resolved.
1798
- */
1799
- const toDeviceRoster = (entries, localCommitmentHex) => Array.from(entries, (entry) => {
1800
- const commitmentHex = require_bytes_vo.HexBytes.fromByteArray(entry);
1801
- return {
1802
- commitmentHex,
1803
- isLocal: commitmentHex === localCommitmentHex
1804
- };
1805
- });
1806
- /**
1807
- * Refuses a record whose creation is still unfinished on chain. A record
1808
- * that carries a pending deployment names a contract that may still miss
1809
- * verifier keys, its initial device or the entries that deliver the
1810
- * account keys, which only the create flow can complete; but a creation
1811
- * that appended its key entries and then died before its final record
1812
- * write left a usable account behind, and the chain's boot flag and inbox
1813
- * tell the two apart.
1814
- */
1815
- const assertCreationComplete = (record, isActivated, entries) => {
1816
- const { deployment } = record;
1817
- if (deployment === void 0) return;
1818
- const held = new Set(entries.map((entry) => require_bytes_vo.HexBytes.fromByteArray(entry)));
1819
- 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.`);
1820
- };
1821
- /** The grant record parts the Lace records of an inbox opened to. */
1822
- const grantPartsOf = (opened) => opened.flatMap((entry) => entry?.kind === "grant" ? [entry.record] : []);
1823
- /**
1824
- * Recognises an existing Passport account on this device: the passkey
1825
- * ceremony (implicit in the first authoriser use) proves the device key,
1826
- * the persisted account record names the Account Custody Contract, the
1827
- * indexer confirms the contract is live, this device's own envelopes in
1828
- * the contract's inbox open a secret deriving the `enc_key` the contract
1829
- * advertises, and the use-counter rescan restores this device's roster
1830
- * position from the on-chain device set. The account secret is never
1831
- * read from the record or derived from the passkey: it is random, and
1832
- * this device reaches it only through an envelope sealed to its reader
1833
- * key, so a device enrolled with its own passkey signs in without the
1834
- * record of the device that created the account. The roster is rebuilt
1835
- * from every entry in the device set, so a device enrolled elsewhere
1836
- * survives a reload; only the local entry is named, the rest are opaque
1837
- * commitments. The grant roster is read from the contract's grants map
1838
- * the same way, with the slots and openings the record kept for the
1839
- * grants this client issued; a grant the record lacks, as after the
1840
- * record was lost, is rebuilt from the grant records this device keeps in
1841
- * the inbox once they open its on-chain commitments under this host's
1842
- * relying party id, its seal kept only while it holds the live secret.
1843
- * A grant the record holds is kept only while its fields open the
1844
- * commitments the chain holds under its id, so an entry an issue wrote
1845
- * before a call that never landed gives way to the grant another client
1846
- * of the account issued over the same id, and a rebuilt grant takes its
1847
- * place when there is one. The live read grants whose kept seal does not
1848
- * hold the live secret, as after an issue that failed before its seal,
1849
- * are reported as unsealed.
1850
- * The devices registered under the live roster key are kept in the
1851
- * record as the roster the next rotation seals to. The whole chain runs
1852
- * inside one key session, so it costs a single ceremony rather than one
1853
- * per authoriser call.
1854
- *
1855
- * The healed counter is written back to the persisted record before this
1856
- * resolves, so the next sign-in rescans from a fresh anchor instead of the
1857
- * creation-time one. That write also completes a record a creation left
1858
- * pending after its key entries landed, dropping the deployment and the
1859
- * authority key it carries, and drops the bookkeeping of grants the chain
1860
- * no longer holds or whose commitments it does not open. A missing record
1861
- * raises AccountNotFoundError, a record whose address holds no live
1862
- * contract raises AccountContractMissingError,
1863
- * a record whose creation is unfinished on chain raises
1864
- * AccountCreationPendingError, and an inbox holding no envelope of this
1865
- * device that opens the live `enc_key`, as for a device never handed the
1866
- * keys or removed since, raises EncryptionKeyMismatchError before the
1867
- * rescan runs; rediscovering an account by name service when no record is
1868
- * persisted is a separate flow and out of scope here.
1869
- *
1870
- * signIn reports no intermediate stage: the ceremony, the indexer read and
1871
- * the rescan all settle before there is anything to report.
1872
- */
1873
- const signIn = async ({ seams, accountRecords, rpId }) => {
1874
- const { passportAuthoriser, passportEncryptionKey, passportNetwork } = seams;
1875
- return inKeySession(passportAuthoriser, { kind: "sign-in" }, async () => {
1876
- const local = await readLocalDevice(seams);
1877
- const record = await accountRecords.read();
1878
- if (!record) throw new require_errors.AccountNotFoundError("No Passport account record is stored on this device.");
1879
- const state = await require_account_call.createIndexerClient({
1880
- indexerUrl: passportNetwork.indexerUrl,
1881
- indexerWsUrl: passportNetwork.indexerWsUrl
1882
- }).queryContractState(record.address);
1883
- if (!state) throw new require_errors.AccountContractMissingError(`No live Account Custody Contract found at ${record.address}.`);
1884
- const ledgerState = require_acc_module.ledger(state.data);
1885
- const { entries, keyring } = readAccountInbox(record.address, ledgerState, local.readerPublicKey);
1886
- assertCreationComplete(record, ledgerState.booted, entries);
1887
- if (keyring.envelopes.length === 0) throw new require_errors.EncryptionKeyMismatchError(`The inbox of the account at ${record.address} holds no envelope for this device.`);
1888
- const grantParts = grantPartsOf(await passportEncryptionKey.openInbox(passportNetwork.networkId, keyring, entries.filter(require_envelopes.isLaceRecord)));
1889
- const { useCounter, commitmentHex } = await require_gated_call.resolveUseCounter({
1890
- ledgerState,
1891
- authoriser: passportAuthoriser,
1892
- address: require_providers.AccAddress(record.address),
1893
- knownUseCounter: require_gated_call.UseCounter(BigInt(record.localUseCounter))
1894
- });
1895
- const devices = toDeviceRoster(ledgerState.devices, commitmentHex);
1896
- const encKey = require_bytes_vo.HexBytes.fromByteArray(ledgerState.enc_key);
1897
- const onChain = readGrants(ledgerState);
1898
- const stored = withRebuiltGrants(await retainStoredGrants(record.grants, onChain, record.address), rpId === void 0 ? void 0 : await rebuildStoredGrants(grantParts, onChain, {
1899
- address: record.address,
1900
- origin: rpId,
1901
- encKey
1902
- }), encKey);
1903
- const grants = readGrants(ledgerState, storedGrantSlots(stored), storedGrantOpenings(stored));
1904
- const localUseCounter = useCounter.toString();
1905
- await accountRecords.write(completedRecord(record, localUseCounter, { grants: stored }));
1906
- return {
1907
- account: {
1908
- address: record.address,
1909
- bindingVersion: record.bindingVersion,
1910
- status: "ready",
1911
- networkId: passportNetwork.networkId
1912
- },
1913
- devices,
1914
- localUseCounter,
1915
- grants,
1916
- encKey,
1917
- unsealedGrantIds: unsealedStoredReadGrants(stored, onChain, encKey)
1918
- };
1919
- });
1920
- };
1921
- //#endregion
1922
- //#region ../../packages/module/passport-account/src/store/dependencies.ts
1923
- /**
1924
- * Runs a flow as a cold stream of its events. `run` is invoked once per
1925
- * subscription with a progress sink that emits synchronously as the flow
1926
- * reports; the resolution emits 'done' and completes, and a rejection
1927
- * errors the stream. Unsubscribing only stops delivery: the running
1928
- * promise is not cancelled, because a flow must run to completion once
1929
- * started (abandoning it mid-deploy could orphan a sponsored contract).
1930
- */
1931
- const observeFlow = (run) => new rxjs.Observable((subscriber) => {
1932
- let isDelivering = true;
1933
- run((stage) => {
1934
- if (isDelivering) subscriber.next({
1935
- type: "progress",
1936
- stage
1937
- });
1938
- }).then((result) => {
1939
- if (!isDelivering) return;
1940
- subscriber.next({
1941
- type: "done",
1942
- result
1943
- });
1944
- subscriber.complete();
1945
- }, (error) => {
1946
- if (isDelivering) subscriber.error(error);
1947
- });
1948
- return () => {
1949
- isDelivering = false;
1950
- };
1951
- });
1952
- /**
1953
- * The context a flow runs under, drawn from the side-effect dependency
1954
- * bag: the five seams, the record store and the relying party id. An
1955
- * injected store is used as is; otherwise the store is built over the
1956
- * platform storage and keyed by the authoriser, so a record sealed by one
1957
- * authoriser is only ever written through it. The sealed-record options
1958
- * apply to that built store; signIn and the grant flows pass
1959
- * `onSealedWithoutKey: 'error'` so a sealed record found without a
1960
- * storage key surfaces as record-unreadable rather than as an absent
1961
- * account.
1962
- */
1963
- const toFlowContext = ({ createKeyValueStorage, passportAuthoriser, passportEncryptionKey, passportNetwork, passportProver, passportSponsor }, onProgress, { store, rpId, ...recordOptions }) => ({
1964
- seams: {
1965
- passportAuthoriser,
1966
- passportEncryptionKey,
1967
- passportNetwork,
1968
- passportProver,
1969
- passportSponsor
1970
- },
1971
- accountRecords: toAccountRecords(store ?? createAccountRecordStore(createKeyValueStorage, passportAuthoriser.storageKey, recordOptions)),
1972
- onProgress,
1973
- rpId
1974
- });
1975
- /**
1976
- * Maps the platform capabilities passed to `createPassportAccountModule`
1977
- * onto the `passport-dependency` contract, and exposes the platform-neutral
1978
- * flows observable-based. The flows are promise functions; wrapping them
1979
- * here rather than in the side effects is what keeps promise handling out
1980
- * of the side effects, so they compose the flows as plain streams and stay
1981
- * testable on a virtual scheduler. The relying party id defaults to the
1982
- * page's hostname, as the passkey ceremony's does.
1983
- */
1984
- const createDependencies = ({ authoriser, encryptionKey, sponsor, prover, network, accountRecordStore, rpId = globalThis.location?.hostname }) => {
1985
- const host = {
1986
- store: accountRecordStore,
1987
- rpId
1988
- };
1989
- const recordRequired = {
1990
- ...host,
1991
- onSealedWithoutKey: "error"
1992
- };
1993
- return {
1994
- passportAuthoriser: authoriser,
1995
- passportEncryptionKey: encryptionKey,
1996
- passportSponsor: sponsor,
1997
- passportProver: prover,
1998
- passportNetwork: network,
1999
- passportFlows: {
2000
- createAccount: (input, dependencies) => observeFlow(async (onProgress) => createAccount(input, toFlowContext(dependencies, onProgress, host))),
2001
- signIn: (dependencies) => observeFlow(async (onProgress) => signIn(toFlowContext(dependencies, onProgress, recordRequired))),
2002
- addDevice: (input, dependencies) => observeFlow(async (onProgress) => addDevice(input, toFlowContext(dependencies, onProgress, host))),
2003
- removeDevice: (input, dependencies) => observeFlow(async (onProgress) => removeDevice(input, toFlowContext(dependencies, onProgress, host))),
2004
- issueGrant: (input, dependencies) => observeFlow(async (onProgress) => issueGrant(input, toFlowContext(dependencies, onProgress, recordRequired))),
2005
- revokeGrant: (input, dependencies) => observeFlow(async (onProgress) => revokeGrant(input, toFlowContext(dependencies, onProgress, recordRequired))),
2006
- revokeAllGrants: (input, dependencies) => observeFlow(async (onProgress) => revokeAllGrants(input, toFlowContext(dependencies, onProgress, recordRequired))),
2007
- readShieldedHoldings: (input, dependencies) => observeFlow(async (onProgress) => readShieldedHoldings(input, toFlowContext(dependencies, onProgress, host)))
2008
- }
2009
- };
2010
- };
2011
- //#endregion
2012
- //#region ../../packages/module/passport-account/src/store/side-effects/flow-actions.ts
2013
- /**
2014
- * The flow error a failure reports: the error's own typed code when it
2015
- * carries one, otherwise the flow's fallback code.
2016
- */
2017
- const toFlowError = (error, fallbackCode) => ({
2018
- code: error instanceof Object && "code" in error && typeof error.code === "string" ? error.code : fallbackCode,
2019
- message: error instanceof Error ? error.message : String(error)
2020
- });
2021
- /**
2022
- * Maps a flow's events onto the passport flow state: each stage to
2023
- * setFlow, the result to its publishing actions followed by
2024
- * setFlow('ready'), and a failure to its `onFailed` actions followed by
2025
- * a single setFlowError, so a flow always settles in 'ready' or 'error'.
2026
- */
2027
- 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)))));
2028
- //#endregion
2029
- //#region ../../packages/module/passport-account/src/store/side-effects/passport-flows.ts
2030
- /** Flow error code for creation failures that carry no typed code of their own. */
2031
- const CREATE_ACCOUNT_FALLBACK_ERROR_CODE = "account-create-failed";
2032
- /** Flow error code for sign-in failures that carry no typed code of their own. */
2033
- const SIGN_IN_FALLBACK_ERROR_CODE = "account-sign-in-failed";
2034
- /** Flow error codes for device call failures that carry no typed code of their own. */
2035
- const ADD_DEVICE_FALLBACK_ERROR_CODE = "device-add-failed";
2036
- const REMOVE_DEVICE_FALLBACK_ERROR_CODE = "device-remove-failed";
2037
- /** Flow error codes for grant call failures that carry no typed code of their own. */
2038
- const ISSUE_GRANT_FALLBACK_ERROR_CODE = "grant-issue-failed";
2039
- const REVOKE_GRANT_FALLBACK_ERROR_CODE = "grant-revoke-failed";
2040
- const REVOKE_ALL_GRANTS_FALLBACK_ERROR_CODE = "grant-revoke-all-failed";
2041
- /** Flow error code for holdings reads that carry no typed code of their own. */
2042
- const READ_HOLDINGS_FALLBACK_ERROR_CODE = "holdings-read-failed";
2043
- /**
2044
- * Flows an account call may start from. 'error' is a settled state, not
2045
- * an operation in progress, so a call that failed can be retried without
2046
- * a fresh sign-in ceremony; every other non-ready flow is an operation
2047
- * left unfinished, whose account and use counter cannot be trusted yet.
2048
- */
2049
- const SETTLED_FLOWS = ["error", "ready"];
2050
- /**
2051
- * The actions that publish a roster a flow left behind: the devices, then
2052
- * the counter the local row sits at. Both land ahead of 'ready', in the
2053
- * order the flows have always published them.
2054
- */
2055
- const publishDeviceRoster = (actions) => ({ devices, localUseCounter }) => [actions.passport.setDevices(devices), actions.passport.setLocalUseCounter(localUseCounter)];
2056
- /**
2057
- * The actions that publish what a grant call left behind: the device
2058
- * roster and counter it advanced, the `enc_key` a rotation it ran stepped
2059
- * the encryption key to and the devices it left without the new key, the
2060
- * grant roster, then the read grants the
2061
- * call could not seal the viewing secret to, empty when it sealed all,
2062
- * and those the signer refused because their revocation is pending.
2063
- */
2064
- const publishGrantRoster = (actions) => ({ grants, encKey, unsealedGrantIds, revocationPendingGrantIds, droppedDevices, ...roster }) => [
2065
- ...publishDeviceRoster(actions)(roster),
2066
- ...encKey === void 0 ? [] : [actions.passport.setEncKey(encKey)],
2067
- ...droppedDevices === void 0 ? [] : [actions.passport.setDroppedDevices(droppedDevices)],
2068
- actions.passport.setGrants(grants),
2069
- actions.passport.setUnsealedGrantIds(unsealedGrantIds),
2070
- actions.passport.setRevocationPendingGrantIds(revocationPendingGrantIds)
2071
- ];
2072
- /**
2073
- * The actions that publish an issued grant: the rosters, then the id of
2074
- * the grant, last so a consumer reacting to it finds the record in state.
2075
- */
2076
- const publishIssuedGrant = (actions) => ({ grantId, ...roster }) => [...publishGrantRoster(actions)(roster), actions.passport.setLastIssuedGrantId(grantId)];
2077
- /**
2078
- * The actions that publish an account a flow left ready: the account,
2079
- * its device roster and counter, the `enc_key` its encryption key is
2080
- * at, then its grant roster.
2081
- */
2082
- const publishAccountState = (actions) => ({ account, grants, encKey, ...roster }) => [
2083
- actions.passport.setAccount(account),
2084
- ...publishDeviceRoster(actions)(roster),
2085
- actions.passport.setEncKey(encKey),
2086
- actions.passport.setGrants(grants)
2087
- ];
2088
- /**
2089
- * The actions that publish an account a sign-in recognised: the account
2090
- * state, see {@link publishAccountState}, then the read grants whose kept
2091
- * seal does not hold the live viewing secret, and no grants pending a
2092
- * revocation, which only a grant call learns from the signer.
2093
- */
2094
- const publishRecognisedAccount = (actions) => ({ unsealedGrantIds, ...state }) => [
2095
- ...publishAccountState(actions)(state),
2096
- actions.passport.setUnsealedGrantIds(unsealedGrantIds),
2097
- actions.passport.setRevocationPendingGrantIds([])
2098
- ];
2099
- /**
2100
- * A device or grant call may rotate the account keys before it fails, so
2101
- * the `enc_key` state holds may be the one rotated away: it is forgotten
2102
- * until the next sign-in or rotation publishes it again, rather than let
2103
- * a stale seal pass as current. The read grants an earlier call reported
2104
- * unsealed or pending revocation were judged against that key, so they
2105
- * are emptied with it.
2106
- */
2107
- const forgetKeyState = (actions) => [
2108
- actions.passport.clearEncKey(),
2109
- actions.passport.setUnsealedGrantIds([]),
2110
- actions.passport.setRevocationPendingGrantIds([])
2111
- ];
2112
- /**
2113
- * The createAccount flow behind the createAccount action, as the actions it
2114
- * publishes: each reported stage as setFlow, then the created account, its
2115
- * one-device roster, this device's counter and its empty grant roster,
2116
- * then 'ready'. The flow itself persists the account record before it
2117
- * resolves, so the account is never published ahead of the record that
2118
- * recognises it.
2119
- */
2120
- const runCreateAccount = (input, dependencies) => {
2121
- const { actions, passportFlows } = dependencies;
2122
- return flowActions(passportFlows.createAccount(input, dependencies), {
2123
- actions,
2124
- fallbackCode: CREATE_ACCOUNT_FALLBACK_ERROR_CODE,
2125
- onDone: publishAccountState(actions)
2126
- });
2127
- };
2128
- /**
2129
- * The signIn flow behind the signIn action, as the actions it publishes:
2130
- * the recognised account, its whole device roster, this device's healed
2131
- * use counter, the grant roster and its unsealed read grants, then
2132
- * 'ready'. The flow itself persists the healed counter before it
2133
- * resolves, so the record is never left behind the state it publishes.
2134
- */
2135
- const runSignIn = (dependencies) => {
2136
- const { actions, passportFlows } = dependencies;
2137
- return flowActions(passportFlows.signIn(dependencies), {
2138
- actions,
2139
- fallbackCode: SIGN_IN_FALLBACK_ERROR_CODE,
2140
- onDone: publishRecognisedAccount(actions)
2141
- });
2142
- };
2143
- /**
2144
- * The actions that publish what a device call left behind: its roster and
2145
- * counter, then, when it rotated the account keys, the `enc_key` it
2146
- * stepped to and the devices it left without the new key.
2147
- */
2148
- const publishDeviceCall = (actions) => ({ encKey, droppedDevices, ...roster }) => [
2149
- ...publishDeviceRoster(actions)(roster),
2150
- ...encKey === void 0 ? [] : [actions.passport.setEncKey(encKey)],
2151
- ...droppedDevices === void 0 ? [] : [actions.passport.setDroppedDevices(droppedDevices)]
2152
- ];
2153
- /**
2154
- * The addDevice flow behind its action: what the call left behind, see
2155
- * {@link publishDeviceCall}, then 'ready'. The joining device's keys
2156
- * travel with the request when the action names them.
2157
- */
2158
- const addDeviceCall = {
2159
- start: ({ commitmentHex, reader }, input, dependencies) => dependencies.passportFlows.addDevice({
2160
- commitmentHex,
2161
- ...reader ? { reader } : {},
2162
- ...input
2163
- }, dependencies),
2164
- onDone: publishDeviceCall,
2165
- fallbackCode: ADD_DEVICE_FALLBACK_ERROR_CODE,
2166
- onFailed: forgetKeyState
2167
- };
2168
- /**
2169
- * The removeDevice flow behind its action: what the call left behind, see
2170
- * {@link publishDeviceCall}, then 'ready'.
2171
- */
2172
- const removeDeviceCall = {
2173
- start: ({ commitmentHex }, input, dependencies) => dependencies.passportFlows.removeDevice({
2174
- commitmentHex,
2175
- ...input
2176
- }, dependencies),
2177
- onDone: publishDeviceCall,
2178
- fallbackCode: REMOVE_DEVICE_FALLBACK_ERROR_CODE,
2179
- onFailed: forgetKeyState
2180
- };
2181
- /**
2182
- * The issueGrant flow behind its action: the rosters the call left
2183
- * behind and the issued grant's id, then 'ready'.
2184
- */
2185
- const issueGrantCall = {
2186
- start: (scope, input, dependencies) => dependencies.passportFlows.issueGrant({
2187
- scope,
2188
- ...input
2189
- }, dependencies),
2190
- onDone: publishIssuedGrant,
2191
- fallbackCode: ISSUE_GRANT_FALLBACK_ERROR_CODE,
2192
- onFailed: forgetKeyState
2193
- };
2194
- /** The revokeGrant flow behind its action: the rosters it left behind, then 'ready'. */
2195
- const revokeGrantCall = {
2196
- start: ({ grantId }, input, dependencies) => dependencies.passportFlows.revokeGrant({
2197
- grantId,
2198
- ...input
2199
- }, dependencies),
2200
- onDone: publishGrantRoster,
2201
- fallbackCode: REVOKE_GRANT_FALLBACK_ERROR_CODE,
2202
- onFailed: forgetKeyState
2203
- };
2204
- /** The revokeAllGrants flow behind its action: the rosters it left behind, then 'ready'. */
2205
- const revokeAllGrantsCall = {
2206
- start: (_payload, input, dependencies) => dependencies.passportFlows.revokeAllGrants(input, dependencies),
2207
- onDone: publishGrantRoster,
2208
- fallbackCode: REVOKE_ALL_GRANTS_FALLBACK_ERROR_CODE,
2209
- onFailed: forgetKeyState
2210
- };
2211
- /**
2212
- * The readShieldedHoldings flow behind its action: the holdings the walk
2213
- * verified, then 'ready'. The skip count is the flow's to report, not the
2214
- * store's to keep: a skipped entry is noise the inbox will carry forever.
2215
- */
2216
- const readShieldedHoldingsCall = {
2217
- start: (_payload, input, dependencies) => dependencies.passportFlows.readShieldedHoldings(input, dependencies),
2218
- onDone: (actions) => ({ holdings }) => [actions.passport.setShieldedHoldings(holdings)],
2219
- fallbackCode: READ_HOLDINGS_FALLBACK_ERROR_CODE
2220
- };
2221
- /**
2222
- * An account call behind its action, as the actions it publishes: what
2223
- * the call left behind, then 'ready', or, when it fails, the actions
2224
- * undoing what state may wrongly claim, then the error. The flow itself
2225
- * persists the counter before it resolves.
2226
- *
2227
- * Requires an account and a settled flow: with no account in state, or
2228
- * with an operation left unfinished, the flow is never called (so the
2229
- * chain and the key session are never touched) and the call settles in
2230
- * 'error' with 'no-account'. The refusal still runs behind the gate, so
2231
- * it enters 'ceremony' first like any accepted request and clears the
2232
- * error a previous flow left behind.
2233
- */
2234
- const runAccountCall = ({ start, onDone, fallbackCode, onFailed }, { payload, flow, account, devices, localUseCounter }, dependencies) => {
2235
- const { actions } = dependencies;
2236
- if (!account || !SETTLED_FLOWS.includes(flow)) return (0, rxjs.of)(actions.passport.setFlowError(toFlowError(new require_errors.NoAccountError(), fallbackCode)));
2237
- return flowActions(start(payload, {
2238
- account,
2239
- devices,
2240
- localUseCounter
2241
- }, dependencies), {
2242
- actions,
2243
- fallbackCode,
2244
- onDone: onDone(actions),
2245
- ...onFailed ? { onFailed: onFailed(actions) } : {}
2246
- });
2247
- };
2248
- /**
2249
- * One start per dispatched account call action, each carrying the state
2250
- * the call needs. State is sampled when the action arrives rather than
2251
- * when the shared gate starts the call, so a call reads the account,
2252
- * roster and counter the user acted on.
2253
- */
2254
- 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, {
2255
- payload,
2256
- flow,
2257
- account,
2258
- devices,
2259
- localUseCounter
2260
- }, dependencies)));
2261
- /**
2262
- * Runs whichever passport flow was requested: {@link runCreateAccount}
2263
- * behind the createAccount action, {@link runSignIn} behind signIn, and
2264
- * {@link runAccountCall} behind addDevice, removeDevice, issueGrant,
2265
- * revokeGrant, revokeAllGrants and readShieldedHoldings.
2266
- *
2267
- * Every flow owns the same account record, the same device key and the
2268
- * same flow state, and each chain call resolves the account's use counter
2269
- * and auth nonce, so they must never overlap: two calls resolving the same
2270
- * counter both spend the same entry, one transaction is rejected, and the
2271
- * loser reports its own failure over state the winner already moved on.
2272
- * A holdings read spends no entry, but it opens the same key session and
2273
- * reports through the same flow state, so it runs behind the same gate.
2274
- * One exhaustMap over the merged starts, rather than one per action,
2275
- * makes them mutually exclusive: a dispatch arriving while any flow is in
2276
- * flight emits nothing at all, and the next one is only accepted once the
2277
- * running flow settles. Dropping it silently is the stance exhaustMap
2278
- * already took for a repeated dispatch of one action; a flow the user
2279
- * never saw start is not a failure to report.
2280
- *
2281
- * Because only the gate knows which requests it accepted, it also owns
2282
- * the entry into 'ceremony': the trigger reducers are pure, so a dropped
2283
- * request cannot overwrite the running flow's state, and setFlow clears
2284
- * the error a previous flow left behind. The emission is synchronous on
2285
- * the accepted start, so a consumer sees the ceremony within the same
2286
- * dispatch cycle as the trigger.
2287
- *
2288
- * The flow state cannot carry this guard the other way round: state
2289
- * reaches a side effect before the action does, and an inner flow is
2290
- * still subscribed while its own terminal setFlow('ready') is delivered,
2291
- * so a reducer reading the flow back cannot tell a request the gate will
2292
- * accept from one it will drop.
2293
- */
2294
- 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({
2295
- config: addDeviceCall,
2296
- trigger$: addDevice$,
2297
- stateObservables,
2298
- dependencies
2299
- }), accountCallStarts({
2300
- config: removeDeviceCall,
2301
- trigger$: removeDevice$,
2302
- stateObservables,
2303
- dependencies
2304
- }), accountCallStarts({
2305
- config: issueGrantCall,
2306
- trigger$: issueGrant$,
2307
- stateObservables,
2308
- dependencies
2309
- }), accountCallStarts({
2310
- config: revokeGrantCall,
2311
- trigger$: revokeGrant$,
2312
- stateObservables,
2313
- dependencies
2314
- }), accountCallStarts({
2315
- config: revokeAllGrantsCall,
2316
- trigger$: revokeAllGrants$,
2317
- stateObservables,
2318
- dependencies
2319
- }), accountCallStarts({
2320
- config: readShieldedHoldingsCall,
2321
- trigger$: readShieldedHoldings$,
2322
- stateObservables,
2323
- dependencies
2324
- })).pipe((0, rxjs.exhaustMap)((start) => (0, rxjs.concat)((0, rxjs.of)(dependencies.actions.passport.setFlow("ceremony")), start())));
2325
- //#endregion
2326
- //#region ../../packages/module/passport-account/src/store/side-effects/restore-account.ts
2327
- /** Whether a stored record names an activated account rather than a deployment in progress. */
2328
- const isActivatedRecord = (record) => record !== void 0 && record.deployment === void 0;
2329
- /**
2330
- * The grant roster of the restored account, read from chain with the
2331
- * slots the record kept. The read needs no ceremony, but it does need
2332
- * the indexer: a contract it does not serve, or a read it fails, leaves
2333
- * the roster empty rather than failing the restore, and the next sign-in
2334
- * or grant call reads it again.
2335
- */
2336
- const restoreGrants = (record, { indexerUrl, indexerWsUrl }, actions) => (0, rxjs.defer)(async () => require_account_call.createIndexerClient({
2337
- indexerUrl,
2338
- indexerWsUrl
2339
- }).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));
2340
- /**
2341
- * Rehydrates the persisted account record into the store on startup, so a
2342
- * returning user's account is recognised without a new passkey ceremony.
2343
- * Only a record whose activation succeeded is restored, hence status
2344
- * 'ready'; a record still carrying a pending deployment names no usable
2345
- * account and is left for the create flow to resume, or for sign-in to
2346
- * complete once the chain shows it activated. The device set is not
2347
- * persisted and is rebuilt from chain by the device-management flows; the
2348
- * grant roster is read from chain here, once the account is published,
2349
- * so a consumer lists grants without a ceremony. A record sealed by a
2350
- * passkey authoriser cannot be opened without a ceremony, and a ceremony
2351
- * cannot run without a user gesture, so no storage key is passed here: a
2352
- * sealed record reads as absent and the sign-in flow recognises the
2353
- * account instead.
2354
- */
2355
- 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({
2356
- address: record.address,
2357
- bindingVersion: record.bindingVersion,
2358
- status: "ready",
2359
- networkId: passportNetwork.networkId
2360
- }), actions.passport.setLocalUseCounter(record.localUseCounter)), restoreGrants(record, passportNetwork, actions))));
2361
- //#endregion
2362
- //#region ../../packages/module/passport-account/src/store/init.ts
2363
- /**
2364
- * Builds the passport-account module's store initializer for the given
2365
- * platform capabilities: the mutually exclusive passport flows behind the
2366
- * createAccount, signIn, addDevice, removeDevice, issueGrant, revokeGrant
2367
- * and revokeAllGrants actions, and the restore of a previously created
2368
- * account from its persisted record.
2369
- */
2370
- const createInit = (props) => () => ({
2371
- sideEffects: [runPassportFlow, restorePassportAccount],
2372
- sideEffectDependencies: createDependencies(props)
2373
- });
2374
- //#endregion
2375
- exports.createInit = createInit;