@seams/wallet 0.24.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (543) hide show
  1. package/dist/.build-inputs.sha256 +1 -1
  2. package/dist/esm/SeamsWeb/operations/tempo/executeEvmFamilyTransaction.js +1 -0
  3. package/dist/esm/SeamsWeb/publicApi/near.js +22 -11
  4. package/dist/esm/SeamsWeb/walletIframe/client/evmFamilyCommands.js +1 -0
  5. package/dist/esm/SeamsWeb/walletIframe/client/nearCommands.js +9 -10
  6. package/dist/esm/SeamsWeb/walletIframe/client/overlay/overlay-styles.js +73 -39
  7. package/dist/esm/SeamsWeb/walletIframe/client/router.js +61 -38
  8. package/dist/esm/SeamsWeb/walletIframe/host/auth-menu/domain.js +1 -0
  9. package/dist/esm/SeamsWeb/walletIframe/host/surface-measurement-reporter.js +1 -0
  10. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/AuthMenuSurface.js +1 -1
  11. package/dist/esm/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.js +28 -0
  12. package/dist/esm/SeamsWeb/walletIframe/shared/messages.js +6 -0
  13. package/dist/esm/core/indexedDB/seamsWalletDB/repositories.js +8 -1
  14. package/dist/esm/core/rpcClients/near/NearClient.js +7 -0
  15. package/dist/esm/core/rpcClients/relayer/walletSessionAuthorizationStatus.js +7 -0
  16. package/dist/esm/core/signingEngine/flows/signNear/signTransactions.js +3 -0
  17. package/dist/esm/core/signingEngine/nearTransactionSubmission.js +89 -0
  18. package/dist/esm/core/signingEngine/uiConfirm/ui/confirm-surface-resize.js +2 -2
  19. package/dist/esm/core/signingEngine/uiConfirm/ui/preact/ReviewDisclosure.js +7 -1
  20. package/dist/esm/core/signingEngine/uiConfirm/ui/preact/mountConfirmationSurface.js +123 -14
  21. package/dist/esm/core/ui/messages.js +12 -0
  22. package/dist/esm/react/components/AccountMenuButton/AccountMenuButtonMock.js +5 -7
  23. package/dist/esm/react/components/AccountMenuButton/AccountMenuButtonView.js +21 -5
  24. package/dist/esm/react/components/AccountMenuButton/AccountMenuModal.js +66 -0
  25. package/dist/esm/react/components/AccountMenuButton/AccountsSection.css +18 -11
  26. package/dist/esm/react/components/AccountMenuButton/AuthenticationMethodRow.js +5 -11
  27. package/dist/esm/react/components/AccountMenuButton/ExportKeysSection.css +17 -15
  28. package/dist/esm/react/components/AccountMenuButton/LinkedDevicesModal.css +156 -106
  29. package/dist/esm/react/components/AccountMenuButton/MenuItem.css +37 -29
  30. package/dist/esm/react/components/AccountMenuButton/ProfileDropdown.css +53 -21
  31. package/dist/esm/react/components/AccountMenuButton/TransactionSettingsSection.css +124 -82
  32. package/dist/esm/react/components/AccountMenuButton/UserAccountButton.css +45 -27
  33. package/dist/esm/react/components/AccountMenuButton/WalletSettingsLayout.css +115 -93
  34. package/dist/esm/react/components/AccountMenuButton/Web3AuthProfileButton.css +179 -92
  35. package/dist/esm/react/components/AccountMenuButton/hooks/useProfileState.js +62 -49
  36. package/dist/esm/react/components/AccountMenuButton/icons/HoverArrowIcon.css +36 -12
  37. package/dist/esm/react/components/AccountMenuButton/icons/HoverArrowIcon.js +10 -2
  38. package/dist/esm/react/components/AccountMenuButton/icons/Icon.css +10 -0
  39. package/dist/esm/react/components/AccountMenuButton/icons/LogOutIcon2.js +15 -16
  40. package/dist/esm/react/components/AccountMenuButton/icons/SpinnerIcon.js +12 -18
  41. package/dist/esm/react/components/AccountMenuButton/icons/TouchIcon.css +3 -3
  42. package/dist/esm/react/components/AccountMenuButton/icons/TouchIcon.js +11 -5
  43. package/dist/esm/react/components/AccountMenuButton/icons/lucideIcon.js +20 -6
  44. package/dist/esm/react/components/AccountMenuButton/index.js +18 -42
  45. package/dist/esm/react/components/ExternalNearWalletIcon.js +32 -0
  46. package/dist/esm/react/components/FingerprintIcon.js +13 -19
  47. package/dist/esm/react/components/HostedSeamsAuthMenu/SeamsAuthMenuMock.js +13 -2
  48. package/dist/esm/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.css +182 -0
  49. package/dist/esm/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.js +315 -0
  50. package/dist/esm/react/components/HostedSeamsAuthMenu/shell.js +20 -5
  51. package/dist/esm/react/components/QRCodeIcon.js +37 -43
  52. package/dist/esm/react/components/QRCodeScanner.css +65 -60
  53. package/dist/esm/react/components/ShowQRCode.css +145 -40
  54. package/dist/esm/react/components/ShowQRCode.js +27 -37
  55. package/dist/esm/react/components/externalWalletBrandImages.js +7 -0
  56. package/dist/esm/react/components/theme/Theme.css +67 -0
  57. package/dist/esm/react/components/theme/ThemeProvider.js +6 -6
  58. package/dist/esm/react/externalEvm.js +11 -4
  59. package/dist/esm/react/externalNear.js +15 -10
  60. package/dist/esm/react/externalWalletPicker.css +117 -0
  61. package/dist/esm/react/index.js +3 -2
  62. package/dist/esm/react/styles/styles.css +2148 -550
  63. package/dist/esm/react/styles.css +7 -1
  64. package/dist/esm/react/transactionReview/TransactionReviewHost.js +3 -0
  65. package/dist/esm/react/transactionReview/boundCalls.js +31 -26
  66. package/dist/esm/sdk/{ConfirmationDrawer-CTaGM1AE.js → ConfirmationDrawer-AZruQmhP.js} +1 -1
  67. package/dist/esm/sdk/NonceCoordinator-3YhmDTS5.js +1 -0
  68. package/dist/{public/sdk/SeamsWordmark-CFpsGoLw.js → esm/sdk/SeamsWordmark-DwvPx2UA.js} +1 -1
  69. package/dist/esm/sdk/accountLifecycle-6DHYWf0v.js +1 -0
  70. package/dist/esm/sdk/actions-DrtSTGus.js +1 -0
  71. package/dist/esm/sdk/activeWalletSession-BJ4B-nJo.js +1 -0
  72. package/dist/esm/sdk/adapters-d9yh1bdC.js +1 -0
  73. package/dist/esm/sdk/appearance-DL7c6bML.js +1 -0
  74. package/dist/esm/sdk/appearance-token-vars-BJydfWT_.js +1 -0
  75. package/dist/esm/sdk/canonicalPrimitives-Jd3i_Ngz.js +1 -0
  76. package/dist/esm/sdk/chains-B72I4PDH.js +1 -0
  77. package/dist/esm/sdk/challengeDelivery-Dj9HrjW9.js +1 -0
  78. package/dist/esm/sdk/clientSessionPersistenceState-BCkJAYSz.js +1 -0
  79. package/dist/esm/sdk/{collectAuthenticationCredentialForChallengeB64u-kLIxmw3V.js → collectAuthenticationCredentialForChallengeB64u-I4wq8OGq.js} +1 -1
  80. package/dist/esm/sdk/{commitQueue-Bs23Rs57.js → commitQueue-CYruPlkm.js} +1 -1
  81. package/dist/esm/sdk/configBuilder-CSwJrmcR.js +1 -0
  82. package/dist/esm/sdk/configuration-DBEc3bsj.js +1 -0
  83. package/dist/esm/sdk/confirm-ui-nU6ymgiv.js +2 -0
  84. package/dist/esm/sdk/confirmTypes-BvVtQs-M.js +1 -0
  85. package/dist/esm/sdk/device-linking-DiCNt3iA.js +1 -0
  86. package/dist/esm/sdk/deviceLinkApproval-CfEiotVt.js +2 -0
  87. package/dist/esm/sdk/digestEncoding-CqNXPZY9.js +1 -0
  88. package/dist/esm/sdk/{chains-gV2K9gA4.js → digests-BIaE0DMd.js} +1 -1
  89. package/dist/esm/sdk/{display-BXjW58UF.js → display-D0EPmU4w.js} +1 -1
  90. package/dist/esm/sdk/ecdsaCapabilityManifest-DAJEVjlP.js +1 -0
  91. package/dist/esm/sdk/{ecdsaChainTarget-DbLthshF.js → ecdsaChainTarget-Bm5X4k-V.js} +1 -1
  92. package/dist/esm/sdk/ecdsaDerivationClientWasm-AYOJgTJm.js +1 -0
  93. package/dist/esm/sdk/ecdsaDerivationExport-DJKOzDbS.js +1 -0
  94. package/dist/esm/sdk/{ecdsaWalletRecords-BgcXXCZy.js → ecdsaWalletRecords-WLyq414E.js} +1 -1
  95. package/dist/esm/sdk/emailOtpEcdsaDerivationIdentity-HFQXc1Yw.js +1 -0
  96. package/dist/esm/sdk/{enrichDisplayModelWithAbi-CudPUW0T.js → enrichDisplayModelWithAbi-O6Mw4i2E.js} +1 -1
  97. package/dist/esm/sdk/errors-BJBDbwHk.js +1 -0
  98. package/dist/esm/sdk/{evmCryptoWasm-DacbCVNM.js → evmCryptoWasm-BUPb4hBH.js} +1 -1
  99. package/dist/esm/sdk/{export-viewer-host-DsWOvc0t.js → export-viewer-host-BtrKVXxu.js} +1 -1
  100. package/dist/esm/sdk/exportKeypairOperation-CGE9ZU1m.js +1 -0
  101. package/dist/esm/sdk/helpers-Dubwo5uK.js +1 -0
  102. package/dist/esm/sdk/host-DayrOrgm.js +1 -0
  103. package/dist/esm/sdk/icons-BlMXolHv.js +1 -0
  104. package/dist/esm/sdk/indexedDB-C4SDsyOG.js +1 -0
  105. package/dist/esm/sdk/intentDigest-HvRsBQ1z.js +1 -0
  106. package/dist/esm/sdk/keyMaterialEnvelope-Dm2ZEilb.js +1 -0
  107. package/dist/esm/sdk/{lanes-C7OvAK_L.js → lanes-BU-fGqY4.js} +1 -1
  108. package/dist/esm/sdk/localOnly-BATWJj78.js +1 -0
  109. package/dist/{public/sdk/mountExportPrivateKeySurface-CV1KrFWg.js → esm/sdk/mountExportPrivateKeySurface-CyHU8bVc.js} +1 -1
  110. package/dist/esm/sdk/{mountRecoveryCodeBackupSurface-CVXU1zzl.js → mountRecoveryCodeBackupSurface-C7aglQxf.js} +1 -1
  111. package/dist/esm/sdk/nearEd25519YaoMaterialActivation-BfXmy3Jr.js +1 -0
  112. package/dist/esm/sdk/nearEd25519YaoSigningPreparation-DHNk0F8e.js +1 -0
  113. package/dist/esm/sdk/nearRpcResults-CeHdqaS4.js +1 -0
  114. package/dist/esm/sdk/{nonceLaneKeys-BS4fek17.js → nonceLaneKeys-BF_UpvIy.js} +1 -1
  115. package/dist/esm/sdk/{normalization-BN-2VWZf.js → normalization-Df9fZWJC.js} +1 -1
  116. package/dist/esm/sdk/operationFingerprint-Bas59T7L.js +1 -0
  117. package/dist/esm/sdk/participants-BXdREC5k.js +1 -0
  118. package/dist/{public/sdk/pendingWalletRecoveryCodeBackup-lr1oISjL.js → esm/sdk/pendingWalletRecoveryCodeBackup-Cjx-X-pP.js} +1 -1
  119. package/dist/esm/sdk/presignaturePool-BbvqRWYw.js +1 -0
  120. package/dist/{public/sdk/presignatures-B9GrGx0L.js → esm/sdk/presignatures-BCeq56DG.js} +1 -1
  121. package/dist/esm/sdk/recovery-entrypoint-DJbMDC_m.js +1 -0
  122. package/dist/esm/sdk/recoveryAuthorization-CQsjb8Tm.js +1 -0
  123. package/dist/esm/sdk/registration-CNLUYN-p.js +1 -0
  124. package/dist/esm/sdk/registration-HSwOHZOo.js +1 -0
  125. package/dist/esm/sdk/{registrationAccounts-BHikxS5q.js → registrationAccounts-4r74gX1l.js} +1 -1
  126. package/dist/esm/sdk/registrationIntent-Do1tD1V7.js +1 -0
  127. package/dist/esm/sdk/registrationSignerPlan-DK2b3N_p.js +1 -0
  128. package/dist/esm/sdk/requireStepUpAuth-COqCGb1i.js +1 -0
  129. package/dist/esm/sdk/resealedEnvelopeResult-B1p5UkYg.js +1 -0
  130. package/dist/esm/sdk/routerAbNormalSigning-D-UZmCBS.js +1 -0
  131. package/dist/esm/sdk/runtime-auth-BCoj7_-G.js +1 -0
  132. package/dist/esm/sdk/runtime-device-link-DAsq5tGT.js +1 -0
  133. package/dist/esm/sdk/runtime-ecdsa-tempo-CVh_Vwl6.js +1 -0
  134. package/dist/esm/sdk/runtime-email-otp-BxSKK9AG.js +1 -0
  135. package/dist/esm/sdk/runtime-export-BWnQXMzT.js +1 -0
  136. package/dist/esm/sdk/runtime-near-CuzPZrDS.js +1 -0
  137. package/dist/esm/sdk/runtime-preferences-B-nDWlm3.js +1 -0
  138. package/dist/esm/sdk/runtime-recovery-DpOdEJ8N.js +1 -0
  139. package/dist/esm/sdk/runtime-recovery-codes-DeUjQsxZ.js +1 -0
  140. package/dist/esm/sdk/runtimeContext-5JcewRo3.js +6 -0
  141. package/dist/esm/sdk/secp256k1-CE7-q9Sn.js +1 -0
  142. package/dist/esm/sdk/sessionObservationRevision-JOvVF4Hf.js +1 -0
  143. package/dist/esm/sdk/signEvmFamily-BY5jlZEG.js +1 -0
  144. package/dist/esm/sdk/{signEvmFamilyWithUiConfirmForTempo-BMfC2sc2.js → signEvmFamilyWithUiConfirmForTempo-CrMIAXUe.js} +1 -1
  145. package/dist/esm/sdk/{signEvmWithUiConfirm-BNkupz3z.js → signEvmWithUiConfirm-CGrLtMV6.js} +1 -1
  146. package/dist/esm/sdk/signNear-DMpJFkwF.js +1 -0
  147. package/dist/esm/sdk/{signatureUses-DrqCoN12.js → signatureUses-kSrUHSSH.js} +1 -1
  148. package/dist/esm/sdk/signerSlot-D2RZnb27.js +1 -0
  149. package/dist/esm/sdk/{signingFlow-BVvteILM.js → signingFlow-BcetvUeS.js} +2 -2
  150. package/dist/esm/sdk/signingQueue-dMFOFOP5.js +1 -0
  151. package/dist/esm/sdk/surface-measurement-reporter-DXsvq401.js +1 -0
  152. package/dist/esm/sdk/thresholdEcdsa-CqR1fFA-.js +1 -0
  153. package/dist/esm/sdk/{trace-CGNqO1FV.js → trace--mRP2OQc.js} +1 -1
  154. package/dist/esm/sdk/{transaction-activity-DPq9RTh5.js → transaction-activity-DCzHGg3b.js} +1 -1
  155. package/dist/esm/sdk/transactionReview-CGIlI835.js +1 -0
  156. package/dist/esm/sdk/{transactionReviewAdmission--8tDis7M.js → transactionReviewAdmission-Cf_qUZJt.js} +1 -1
  157. package/dist/{public/sdk/transactionState-BS1VLT7B.js → esm/sdk/transactionState-29T9xfvL.js} +1 -1
  158. package/dist/esm/sdk/tx-confirm-ui.js +173 -18
  159. package/dist/esm/sdk/{types-DdzuHlAQ.js → types-f7dyj5N6.js} +1 -1
  160. package/dist/esm/sdk/unlockedEd25519ExportRootCapability-yzxQjIFd.js +1 -0
  161. package/dist/esm/sdk/voiceid-host.js +1 -1
  162. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  163. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  164. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  165. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  166. package/dist/esm/sdk/wallet-recovery-BZB2Vu3X.js +1 -0
  167. package/dist/esm/sdk/wallet-ui.css +1 -1
  168. package/dist/esm/sdk/walletAuthMethodRecord-DLBB5fez.js +1 -0
  169. package/dist/esm/sdk/walletAuthority-BTGAuOi8.js +1 -0
  170. package/dist/esm/sdk/walletCapabilityBindings-D5YYB7nN.js +1 -0
  171. package/dist/esm/sdk/walletCustodyEcdsaContinuity-C31YQ9av.js +1 -0
  172. package/dist/esm/sdk/walletCustodyOperation-DimzAbCB.js +1 -0
  173. package/dist/esm/sdk/walletDbName-Ca0rCq5r.js +1 -0
  174. package/dist/esm/sdk/walletOwnershipGeneration-CgjCtPrV.js +1 -0
  175. package/dist/esm/sdk/walletRecoveryAdminProof-CvSYbyg5.js +1 -0
  176. package/dist/esm/sdk/walletRecoveryCommit-Cc2LAkCS.js +1 -0
  177. package/dist/esm/sdk/walletRegistrationSetupPrewarm-CEvGKQSg.js +1 -0
  178. package/dist/esm/sdk/{walletSessionAuthorizationProjection-BJgnZaBc.js → walletSessionAuthorizationProjection-BzUH6gHV.js} +1 -1
  179. package/dist/esm/sdk/walletSessionAuthorizationStatus-DG7DPcgR.js +1 -0
  180. package/dist/esm/sdk/{walletSessionAuthorizationStore-zkxcMdSp.js → walletSessionAuthorizationStore-B9Vwkshr.js} +1 -1
  181. package/dist/esm/sdk/warmSessionHydration-B-A5Tdx7.js +1 -0
  182. package/dist/{public/sdk/webauthnP256-BvTL8nq4.js → esm/sdk/webauthnP256-BsQQPurm.js} +1 -1
  183. package/dist/esm/shared-ts/src/near/nearClient.js +1 -1
  184. package/dist/esm/shared-ts/src/utils/errors.js +56 -3
  185. package/dist/esm/shared-ts/src/utils/index.js +1 -1
  186. package/dist/esm/voiceid-host.js +1 -1
  187. package/dist/public/headers.manifest.json +1 -1
  188. package/dist/public/sdk/{ConfirmationDrawer-CTaGM1AE.js → ConfirmationDrawer-AZruQmhP.js} +1 -1
  189. package/dist/public/sdk/NonceCoordinator-3YhmDTS5.js +1 -0
  190. package/dist/{esm/sdk/SeamsWordmark-CFpsGoLw.js → public/sdk/SeamsWordmark-DwvPx2UA.js} +1 -1
  191. package/dist/public/sdk/accountLifecycle-6DHYWf0v.js +1 -0
  192. package/dist/public/sdk/actions-DrtSTGus.js +1 -0
  193. package/dist/public/sdk/activeWalletSession-BJ4B-nJo.js +1 -0
  194. package/dist/public/sdk/adapters-d9yh1bdC.js +1 -0
  195. package/dist/public/sdk/appearance-DL7c6bML.js +1 -0
  196. package/dist/public/sdk/appearance-token-vars-BJydfWT_.js +1 -0
  197. package/dist/public/sdk/canonicalPrimitives-Jd3i_Ngz.js +1 -0
  198. package/dist/public/sdk/chains-B72I4PDH.js +1 -0
  199. package/dist/public/sdk/challengeDelivery-Dj9HrjW9.js +1 -0
  200. package/dist/public/sdk/clientSessionPersistenceState-BCkJAYSz.js +1 -0
  201. package/dist/public/sdk/{collectAuthenticationCredentialForChallengeB64u-kLIxmw3V.js → collectAuthenticationCredentialForChallengeB64u-I4wq8OGq.js} +1 -1
  202. package/dist/public/sdk/{commitQueue-Bs23Rs57.js → commitQueue-CYruPlkm.js} +1 -1
  203. package/dist/public/sdk/configBuilder-CSwJrmcR.js +1 -0
  204. package/dist/public/sdk/configuration-DBEc3bsj.js +1 -0
  205. package/dist/public/sdk/confirm-ui-nU6ymgiv.js +2 -0
  206. package/dist/public/sdk/confirmTypes-BvVtQs-M.js +1 -0
  207. package/dist/public/sdk/device-linking-DiCNt3iA.js +1 -0
  208. package/dist/public/sdk/deviceLinkApproval-CfEiotVt.js +2 -0
  209. package/dist/public/sdk/digestEncoding-CqNXPZY9.js +1 -0
  210. package/dist/public/sdk/{chains-gV2K9gA4.js → digests-BIaE0DMd.js} +1 -1
  211. package/dist/public/sdk/{display-BXjW58UF.js → display-D0EPmU4w.js} +1 -1
  212. package/dist/public/sdk/ecdsaCapabilityManifest-DAJEVjlP.js +1 -0
  213. package/dist/public/sdk/{ecdsaChainTarget-DbLthshF.js → ecdsaChainTarget-Bm5X4k-V.js} +1 -1
  214. package/dist/public/sdk/ecdsaDerivationClientWasm-AYOJgTJm.js +1 -0
  215. package/dist/public/sdk/ecdsaDerivationExport-DJKOzDbS.js +1 -0
  216. package/dist/public/sdk/{ecdsaWalletRecords-BgcXXCZy.js → ecdsaWalletRecords-WLyq414E.js} +1 -1
  217. package/dist/public/sdk/emailOtpEcdsaDerivationIdentity-HFQXc1Yw.js +1 -0
  218. package/dist/public/sdk/{enrichDisplayModelWithAbi-CudPUW0T.js → enrichDisplayModelWithAbi-O6Mw4i2E.js} +1 -1
  219. package/dist/public/sdk/errors-BJBDbwHk.js +1 -0
  220. package/dist/public/sdk/{evmCryptoWasm-DacbCVNM.js → evmCryptoWasm-BUPb4hBH.js} +1 -1
  221. package/dist/public/sdk/{export-viewer-host-DsWOvc0t.js → export-viewer-host-BtrKVXxu.js} +1 -1
  222. package/dist/public/sdk/exportKeypairOperation-CGE9ZU1m.js +1 -0
  223. package/dist/public/sdk/helpers-Dubwo5uK.js +1 -0
  224. package/dist/public/sdk/host-DayrOrgm.js +1 -0
  225. package/dist/public/sdk/icons-BlMXolHv.js +1 -0
  226. package/dist/public/sdk/indexedDB-C4SDsyOG.js +1 -0
  227. package/dist/public/sdk/intentDigest-HvRsBQ1z.js +1 -0
  228. package/dist/public/sdk/keyMaterialEnvelope-Dm2ZEilb.js +1 -0
  229. package/dist/public/sdk/{lanes-C7OvAK_L.js → lanes-BU-fGqY4.js} +1 -1
  230. package/dist/public/sdk/localOnly-BATWJj78.js +1 -0
  231. package/dist/{esm/sdk/mountExportPrivateKeySurface-CV1KrFWg.js → public/sdk/mountExportPrivateKeySurface-CyHU8bVc.js} +1 -1
  232. package/dist/public/sdk/{mountRecoveryCodeBackupSurface-CVXU1zzl.js → mountRecoveryCodeBackupSurface-C7aglQxf.js} +1 -1
  233. package/dist/public/sdk/nearEd25519YaoMaterialActivation-BfXmy3Jr.js +1 -0
  234. package/dist/public/sdk/nearEd25519YaoSigningPreparation-DHNk0F8e.js +1 -0
  235. package/dist/public/sdk/nearRpcResults-CeHdqaS4.js +1 -0
  236. package/dist/public/sdk/{nonceLaneKeys-BS4fek17.js → nonceLaneKeys-BF_UpvIy.js} +1 -1
  237. package/dist/public/sdk/{normalization-BN-2VWZf.js → normalization-Df9fZWJC.js} +1 -1
  238. package/dist/public/sdk/operationFingerprint-Bas59T7L.js +1 -0
  239. package/dist/public/sdk/participants-BXdREC5k.js +1 -0
  240. package/dist/{esm/sdk/pendingWalletRecoveryCodeBackup-lr1oISjL.js → public/sdk/pendingWalletRecoveryCodeBackup-Cjx-X-pP.js} +1 -1
  241. package/dist/public/sdk/presignaturePool-BbvqRWYw.js +1 -0
  242. package/dist/{esm/sdk/presignatures-B9GrGx0L.js → public/sdk/presignatures-BCeq56DG.js} +1 -1
  243. package/dist/public/sdk/recovery-entrypoint-DJbMDC_m.js +1 -0
  244. package/dist/public/sdk/recoveryAuthorization-CQsjb8Tm.js +1 -0
  245. package/dist/public/sdk/registration-CNLUYN-p.js +1 -0
  246. package/dist/public/sdk/registration-HSwOHZOo.js +1 -0
  247. package/dist/public/sdk/{registrationAccounts-BHikxS5q.js → registrationAccounts-4r74gX1l.js} +1 -1
  248. package/dist/public/sdk/registrationIntent-Do1tD1V7.js +1 -0
  249. package/dist/public/sdk/registrationSignerPlan-DK2b3N_p.js +1 -0
  250. package/dist/public/sdk/requireStepUpAuth-COqCGb1i.js +1 -0
  251. package/dist/public/sdk/resealedEnvelopeResult-B1p5UkYg.js +1 -0
  252. package/dist/public/sdk/routerAbNormalSigning-D-UZmCBS.js +1 -0
  253. package/dist/public/sdk/runtime-auth-BCoj7_-G.js +1 -0
  254. package/dist/public/sdk/runtime-device-link-DAsq5tGT.js +1 -0
  255. package/dist/public/sdk/runtime-ecdsa-tempo-CVh_Vwl6.js +1 -0
  256. package/dist/public/sdk/runtime-email-otp-BxSKK9AG.js +1 -0
  257. package/dist/public/sdk/runtime-export-BWnQXMzT.js +1 -0
  258. package/dist/public/sdk/runtime-near-CuzPZrDS.js +1 -0
  259. package/dist/public/sdk/runtime-preferences-B-nDWlm3.js +1 -0
  260. package/dist/public/sdk/runtime-recovery-DpOdEJ8N.js +1 -0
  261. package/dist/public/sdk/runtime-recovery-codes-DeUjQsxZ.js +1 -0
  262. package/dist/public/sdk/runtimeContext-5JcewRo3.js +6 -0
  263. package/dist/public/sdk/secp256k1-CE7-q9Sn.js +1 -0
  264. package/dist/public/sdk/sessionObservationRevision-JOvVF4Hf.js +1 -0
  265. package/dist/public/sdk/signEvmFamily-BY5jlZEG.js +1 -0
  266. package/dist/public/sdk/{signEvmFamilyWithUiConfirmForTempo-BMfC2sc2.js → signEvmFamilyWithUiConfirmForTempo-CrMIAXUe.js} +1 -1
  267. package/dist/public/sdk/{signEvmWithUiConfirm-BNkupz3z.js → signEvmWithUiConfirm-CGrLtMV6.js} +1 -1
  268. package/dist/public/sdk/signNear-DMpJFkwF.js +1 -0
  269. package/dist/public/sdk/{signatureUses-DrqCoN12.js → signatureUses-kSrUHSSH.js} +1 -1
  270. package/dist/public/sdk/signerSlot-D2RZnb27.js +1 -0
  271. package/dist/public/sdk/{signingFlow-BVvteILM.js → signingFlow-BcetvUeS.js} +2 -2
  272. package/dist/public/sdk/signingQueue-dMFOFOP5.js +1 -0
  273. package/dist/public/sdk/surface-measurement-reporter-DXsvq401.js +1 -0
  274. package/dist/public/sdk/thresholdEcdsa-CqR1fFA-.js +1 -0
  275. package/dist/public/sdk/{trace-CGNqO1FV.js → trace--mRP2OQc.js} +1 -1
  276. package/dist/public/sdk/{transaction-activity-DPq9RTh5.js → transaction-activity-DCzHGg3b.js} +1 -1
  277. package/dist/public/sdk/transactionReview-CGIlI835.js +1 -0
  278. package/dist/public/sdk/{transactionReviewAdmission--8tDis7M.js → transactionReviewAdmission-Cf_qUZJt.js} +1 -1
  279. package/dist/{esm/sdk/transactionState-BS1VLT7B.js → public/sdk/transactionState-29T9xfvL.js} +1 -1
  280. package/dist/public/sdk/tx-confirm-ui.js +173 -18
  281. package/dist/public/sdk/{types-DdzuHlAQ.js → types-f7dyj5N6.js} +1 -1
  282. package/dist/public/sdk/unlockedEd25519ExportRootCapability-yzxQjIFd.js +1 -0
  283. package/dist/public/sdk/voiceid-host.js +1 -1
  284. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  285. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  286. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  287. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  288. package/dist/public/sdk/wallet-recovery-BZB2Vu3X.js +1 -0
  289. package/dist/public/sdk/wallet-ui.css +1 -1
  290. package/dist/public/sdk/walletAuthMethodRecord-DLBB5fez.js +1 -0
  291. package/dist/public/sdk/walletAuthority-BTGAuOi8.js +1 -0
  292. package/dist/public/sdk/walletCapabilityBindings-D5YYB7nN.js +1 -0
  293. package/dist/public/sdk/walletCustodyEcdsaContinuity-C31YQ9av.js +1 -0
  294. package/dist/public/sdk/walletCustodyOperation-DimzAbCB.js +1 -0
  295. package/dist/public/sdk/walletDbName-Ca0rCq5r.js +1 -0
  296. package/dist/public/sdk/walletOwnershipGeneration-CgjCtPrV.js +1 -0
  297. package/dist/public/sdk/walletRecoveryAdminProof-CvSYbyg5.js +1 -0
  298. package/dist/public/sdk/walletRecoveryCommit-Cc2LAkCS.js +1 -0
  299. package/dist/public/sdk/walletRegistrationSetupPrewarm-CEvGKQSg.js +1 -0
  300. package/dist/public/sdk/{walletSessionAuthorizationProjection-BJgnZaBc.js → walletSessionAuthorizationProjection-BzUH6gHV.js} +1 -1
  301. package/dist/public/sdk/walletSessionAuthorizationStatus-DG7DPcgR.js +1 -0
  302. package/dist/public/sdk/{walletSessionAuthorizationStore-zkxcMdSp.js → walletSessionAuthorizationStore-B9Vwkshr.js} +1 -1
  303. package/dist/public/sdk/warmSessionHydration-B-A5Tdx7.js +1 -0
  304. package/dist/{esm/sdk/webauthnP256-BvTL8nq4.js → public/sdk/webauthnP256-BsQQPurm.js} +1 -1
  305. package/dist/public/wallet-assets.manifest.json +476 -260
  306. package/dist/public/wallet-service/index.html +4 -4
  307. package/dist/types/shared-ts/src/utils/errors.d.ts +1 -0
  308. package/dist/types/wallet/src/SeamsWeb/operations/authMethods/passkey/exactPasskeyAuthority.d.ts +24 -0
  309. package/dist/types/wallet/src/SeamsWeb/operations/devices/walletHostOwnerAuthority.d.ts +2 -0
  310. package/dist/types/wallet/src/SeamsWeb/publicApi/types.d.ts +3 -0
  311. package/dist/types/wallet/src/SeamsWeb/walletIframe/client/router.d.ts +2 -0
  312. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/WalletHostRuntime.d.ts +1 -0
  313. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/createDeviceDomain.d.ts +2 -1
  314. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/deviceLinkApproval.d.ts +27 -0
  315. package/dist/types/wallet/src/SeamsWeb/walletIframe/host/ui/auth-menu/mountAuthMenuSurface.d.ts +1 -0
  316. package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/messages.d.ts +4 -1
  317. package/dist/types/wallet/src/core/authMethods/hostPlugin.d.ts +1 -0
  318. package/dist/types/wallet/src/core/authMethods/plugins.d.ts +4 -0
  319. package/dist/types/wallet/src/core/indexedDB/seamsWalletDB/recoveredEd25519Authority.d.ts +8 -0
  320. package/dist/types/wallet/src/core/indexedDB/seamsWalletDB/repositories.d.ts +1 -0
  321. package/dist/types/wallet/src/core/rpcClients/near/NearClient.d.ts +13 -0
  322. package/dist/types/wallet/src/core/rpcClients/relayer/walletSessionAuthorizationStatus.d.ts +2 -0
  323. package/dist/types/wallet/src/core/signingEngine/nearTransactionSubmission.d.ts +24 -0
  324. package/dist/types/wallet/src/core/signingEngine/session/persistence/walletSessionAuthorizationProjection.d.ts +1 -0
  325. package/dist/types/wallet/src/core/signingEngine/uiConfirm/transactionReviewAdmission.d.ts +2 -0
  326. package/dist/types/wallet/src/core/types/linkDevice.d.ts +4 -5
  327. package/dist/types/wallet/src/core/types/sdkSentEvents.d.ts +2 -0
  328. package/dist/types/wallet/src/core/types/seams.d.ts +15 -3
  329. package/dist/types/wallet/src/core/ui/messages.d.ts +1 -1
  330. package/dist/types/wallet/src/index.d.ts +1 -1
  331. package/dist/types/wallet/src/react/components/AccountMenuButton/AccountMenuButtonMock.d.ts +11 -2
  332. package/dist/types/wallet/src/react/components/AccountMenuButton/AccountMenuButtonView.d.ts +2 -1
  333. package/dist/types/wallet/src/react/components/AccountMenuButton/AccountMenuModal.d.ts +9 -0
  334. package/dist/types/wallet/src/react/components/AccountMenuButton/hooks/useProfileState.d.ts +13 -5
  335. package/dist/types/wallet/src/react/components/AccountMenuButton/icons/HoverArrowIcon.d.ts +2 -1
  336. package/dist/types/wallet/src/react/components/AccountMenuButton/icons/lucideIcon.d.ts +1 -1
  337. package/dist/types/wallet/src/react/components/AccountMenuButton/types.d.ts +19 -3
  338. package/dist/types/wallet/src/react/components/ExternalNearWalletIcon.d.ts +5 -0
  339. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/WalletConnectorMenu.d.ts +31 -0
  340. package/dist/types/wallet/src/react/components/HostedSeamsAuthMenu/types.d.ts +4 -0
  341. package/dist/types/wallet/src/react/components/ShowQRCode.d.ts +1 -1
  342. package/dist/types/wallet/src/react/components/externalWalletBrandImages.d.ts +3 -0
  343. package/dist/types/wallet/src/react/components/theme/design-tokens.d.ts +2 -0
  344. package/dist/types/wallet/src/react/externalNear.d.ts +3 -23
  345. package/dist/types/wallet/src/react/index.d.ts +3 -1
  346. package/dist/types/wallet/src/react/transactionReview/boundCalls.d.ts +7 -0
  347. package/dist/types/wallet/src/voiceid-host.d.ts +1 -1
  348. package/package.json +1 -1
  349. package/dist/esm/react/externalNear.css +0 -90
  350. package/dist/esm/sdk/NonceCoordinator-Bti1HQPo.js +0 -1
  351. package/dist/esm/sdk/accountLifecycle-B98g9zN9.js +0 -1
  352. package/dist/esm/sdk/actions-GYsSR2Q2.js +0 -1
  353. package/dist/esm/sdk/activeWalletSession-H9JBdHyQ.js +0 -1
  354. package/dist/esm/sdk/adapters-D5MZ5NG5.js +0 -2
  355. package/dist/esm/sdk/appearance-DVFno9Tv.js +0 -1
  356. package/dist/esm/sdk/appearance-token-vars-CgYTfCKg.js +0 -1
  357. package/dist/esm/sdk/canonicalPrimitives-B6YMrI3W.js +0 -1
  358. package/dist/esm/sdk/challengeDelivery-FW9gYyr0.js +0 -1
  359. package/dist/esm/sdk/clientSessionPersistenceState-BPYK9PYV.js +0 -1
  360. package/dist/esm/sdk/configBuilder-DrxXNUpV.js +0 -1
  361. package/dist/esm/sdk/configuration-CAqANpTI.js +0 -1
  362. package/dist/esm/sdk/ecdsaCapabilityManifest--FjbES8k.js +0 -1
  363. package/dist/esm/sdk/ecdsaDerivationClientWasm-7Rp4TmYE.js +0 -1
  364. package/dist/esm/sdk/ecdsaDerivationExport-dInN7N6e.js +0 -1
  365. package/dist/esm/sdk/emailOtpEcdsaDerivationIdentity-CIh9IPai.js +0 -1
  366. package/dist/esm/sdk/errors-ADOZT8oV.js +0 -1
  367. package/dist/esm/sdk/exportKeypairOperation-BazJvSov.js +0 -1
  368. package/dist/esm/sdk/helpers-CXqXyyCU.js +0 -1
  369. package/dist/esm/sdk/host-C0Is56lU.js +0 -1
  370. package/dist/esm/sdk/icons-DyndJzSh.js +0 -1
  371. package/dist/esm/sdk/indexedDB-C1odKEC6.js +0 -1
  372. package/dist/esm/sdk/intentDigest-BMXki7yB.js +0 -1
  373. package/dist/esm/sdk/keyMaterialEnvelope-B-Q5KTJC.js +0 -1
  374. package/dist/esm/sdk/localOnly-BB3Rx3J6.js +0 -1
  375. package/dist/esm/sdk/nearEd25519YaoMaterialActivation-D9cdMKIZ.js +0 -1
  376. package/dist/esm/sdk/nearEd25519YaoSigningPreparation-D_Jvj7ht.js +0 -1
  377. package/dist/esm/sdk/operationFingerprint-Bn0lUYlm.js +0 -1
  378. package/dist/esm/sdk/presignaturePool-CultzkOG.js +0 -1
  379. package/dist/esm/sdk/recovery-entrypoint-QBvJBngm.js +0 -1
  380. package/dist/esm/sdk/recoveryAuthorization-DB-zxeHq.js +0 -1
  381. package/dist/esm/sdk/registration-CM5a7WYO.js +0 -1
  382. package/dist/esm/sdk/registration-Hv0xi7-L.js +0 -1
  383. package/dist/esm/sdk/registrationIntent-DTs2SR9E.js +0 -1
  384. package/dist/esm/sdk/registrationSignerPlan-CgbFVsAp.js +0 -1
  385. package/dist/esm/sdk/requireStepUpAuth-B7tC4MrA.js +0 -1
  386. package/dist/esm/sdk/resealedEnvelopeResult--iCVt_Bh.js +0 -1
  387. package/dist/esm/sdk/routerAbNormalSigning-Div3lZWV.js +0 -1
  388. package/dist/esm/sdk/runtime-auth-CVw1KoVD.js +0 -1
  389. package/dist/esm/sdk/runtime-device-link-Dp0YMZTQ.js +0 -1
  390. package/dist/esm/sdk/runtime-ecdsa-tempo-DEIjIgEO.js +0 -1
  391. package/dist/esm/sdk/runtime-email-otp-gsr_FsQn.js +0 -1
  392. package/dist/esm/sdk/runtime-export-upMPrZ4V.js +0 -1
  393. package/dist/esm/sdk/runtime-near-B64Hn3nc.js +0 -1
  394. package/dist/esm/sdk/runtime-preferences-CULdHkbg.js +0 -1
  395. package/dist/esm/sdk/runtime-recovery-D2saBaJy.js +0 -1
  396. package/dist/esm/sdk/runtime-recovery-codes-Bvc0IXMJ.js +0 -1
  397. package/dist/esm/sdk/runtimeContext-CNFJjcns.js +0 -6
  398. package/dist/esm/sdk/secp256k1-BGVlx50C.js +0 -1
  399. package/dist/esm/sdk/sessionObservationRevision-84ZzJ-fC.js +0 -1
  400. package/dist/esm/sdk/signEvmFamily-PjwUc5MT.js +0 -1
  401. package/dist/esm/sdk/signNear-r8VCOoTh.js +0 -1
  402. package/dist/esm/sdk/signerSlot-D4ZOuK7e.js +0 -1
  403. package/dist/esm/sdk/signingQueue-BJzOrwDq.js +0 -1
  404. package/dist/esm/sdk/surface-measurement-reporter-NUm_54LH.js +0 -1
  405. package/dist/esm/sdk/thresholdEcdsa-tnY83qyG.js +0 -1
  406. package/dist/esm/sdk/transactionReview-DSGnpreN.js +0 -1
  407. package/dist/esm/sdk/unlockedEd25519ExportRootCapability-D43rvO9a.js +0 -1
  408. package/dist/esm/sdk/wallet-recovery-BjIQdOha.js +0 -1
  409. package/dist/esm/sdk/walletAuthMethodRecord-yIqCeE-o.js +0 -1
  410. package/dist/esm/sdk/walletCapabilityBindings-CUPk3mVH.js +0 -1
  411. package/dist/esm/sdk/walletCustodyEcdsaContinuity-DlOBCmwb.js +0 -1
  412. package/dist/esm/sdk/walletCustodyOperation-DzPcxEBS.js +0 -1
  413. package/dist/esm/sdk/walletDbName-DDJXrgA5.js +0 -1
  414. package/dist/esm/sdk/walletOwnershipGeneration-DI9ogcXF.js +0 -1
  415. package/dist/esm/sdk/walletRecoveryAdminProof-BJxmg3f7.js +0 -1
  416. package/dist/esm/sdk/walletRecoveryCommit-B7WsdR7y.js +0 -1
  417. package/dist/esm/sdk/walletRegistrationSetupPrewarm-CEJCj78c.js +0 -1
  418. package/dist/esm/sdk/walletSessionAuthorizationStatus-98G3Qji8.js +0 -1
  419. package/dist/esm/sdk/warmSessionHydration-DqZyfi1h.js +0 -1
  420. package/dist/public/sdk/NonceCoordinator-Bti1HQPo.js +0 -1
  421. package/dist/public/sdk/accountLifecycle-B98g9zN9.js +0 -1
  422. package/dist/public/sdk/actions-GYsSR2Q2.js +0 -1
  423. package/dist/public/sdk/activeWalletSession-H9JBdHyQ.js +0 -1
  424. package/dist/public/sdk/adapters-D5MZ5NG5.js +0 -2
  425. package/dist/public/sdk/appearance-DVFno9Tv.js +0 -1
  426. package/dist/public/sdk/appearance-token-vars-CgYTfCKg.js +0 -1
  427. package/dist/public/sdk/canonicalPrimitives-B6YMrI3W.js +0 -1
  428. package/dist/public/sdk/challengeDelivery-FW9gYyr0.js +0 -1
  429. package/dist/public/sdk/clientSessionPersistenceState-BPYK9PYV.js +0 -1
  430. package/dist/public/sdk/configBuilder-DrxXNUpV.js +0 -1
  431. package/dist/public/sdk/configuration-CAqANpTI.js +0 -1
  432. package/dist/public/sdk/ecdsaCapabilityManifest--FjbES8k.js +0 -1
  433. package/dist/public/sdk/ecdsaDerivationClientWasm-7Rp4TmYE.js +0 -1
  434. package/dist/public/sdk/ecdsaDerivationExport-dInN7N6e.js +0 -1
  435. package/dist/public/sdk/emailOtpEcdsaDerivationIdentity-CIh9IPai.js +0 -1
  436. package/dist/public/sdk/errors-ADOZT8oV.js +0 -1
  437. package/dist/public/sdk/exportKeypairOperation-BazJvSov.js +0 -1
  438. package/dist/public/sdk/helpers-CXqXyyCU.js +0 -1
  439. package/dist/public/sdk/host-C0Is56lU.js +0 -1
  440. package/dist/public/sdk/icons-DyndJzSh.js +0 -1
  441. package/dist/public/sdk/indexedDB-C1odKEC6.js +0 -1
  442. package/dist/public/sdk/intentDigest-BMXki7yB.js +0 -1
  443. package/dist/public/sdk/keyMaterialEnvelope-B-Q5KTJC.js +0 -1
  444. package/dist/public/sdk/localOnly-BB3Rx3J6.js +0 -1
  445. package/dist/public/sdk/nearEd25519YaoMaterialActivation-D9cdMKIZ.js +0 -1
  446. package/dist/public/sdk/nearEd25519YaoSigningPreparation-D_Jvj7ht.js +0 -1
  447. package/dist/public/sdk/operationFingerprint-Bn0lUYlm.js +0 -1
  448. package/dist/public/sdk/presignaturePool-CultzkOG.js +0 -1
  449. package/dist/public/sdk/recovery-entrypoint-QBvJBngm.js +0 -1
  450. package/dist/public/sdk/recoveryAuthorization-DB-zxeHq.js +0 -1
  451. package/dist/public/sdk/registration-CM5a7WYO.js +0 -1
  452. package/dist/public/sdk/registration-Hv0xi7-L.js +0 -1
  453. package/dist/public/sdk/registrationIntent-DTs2SR9E.js +0 -1
  454. package/dist/public/sdk/registrationSignerPlan-CgbFVsAp.js +0 -1
  455. package/dist/public/sdk/requireStepUpAuth-B7tC4MrA.js +0 -1
  456. package/dist/public/sdk/resealedEnvelopeResult--iCVt_Bh.js +0 -1
  457. package/dist/public/sdk/routerAbNormalSigning-Div3lZWV.js +0 -1
  458. package/dist/public/sdk/runtime-auth-CVw1KoVD.js +0 -1
  459. package/dist/public/sdk/runtime-device-link-Dp0YMZTQ.js +0 -1
  460. package/dist/public/sdk/runtime-ecdsa-tempo-DEIjIgEO.js +0 -1
  461. package/dist/public/sdk/runtime-email-otp-gsr_FsQn.js +0 -1
  462. package/dist/public/sdk/runtime-export-upMPrZ4V.js +0 -1
  463. package/dist/public/sdk/runtime-near-B64Hn3nc.js +0 -1
  464. package/dist/public/sdk/runtime-preferences-CULdHkbg.js +0 -1
  465. package/dist/public/sdk/runtime-recovery-D2saBaJy.js +0 -1
  466. package/dist/public/sdk/runtime-recovery-codes-Bvc0IXMJ.js +0 -1
  467. package/dist/public/sdk/runtimeContext-CNFJjcns.js +0 -6
  468. package/dist/public/sdk/secp256k1-BGVlx50C.js +0 -1
  469. package/dist/public/sdk/sessionObservationRevision-84ZzJ-fC.js +0 -1
  470. package/dist/public/sdk/signEvmFamily-PjwUc5MT.js +0 -1
  471. package/dist/public/sdk/signNear-r8VCOoTh.js +0 -1
  472. package/dist/public/sdk/signerSlot-D4ZOuK7e.js +0 -1
  473. package/dist/public/sdk/signingQueue-BJzOrwDq.js +0 -1
  474. package/dist/public/sdk/surface-measurement-reporter-NUm_54LH.js +0 -1
  475. package/dist/public/sdk/thresholdEcdsa-tnY83qyG.js +0 -1
  476. package/dist/public/sdk/transactionReview-DSGnpreN.js +0 -1
  477. package/dist/public/sdk/unlockedEd25519ExportRootCapability-D43rvO9a.js +0 -1
  478. package/dist/public/sdk/wallet-recovery-BjIQdOha.js +0 -1
  479. package/dist/public/sdk/walletAuthMethodRecord-yIqCeE-o.js +0 -1
  480. package/dist/public/sdk/walletCapabilityBindings-CUPk3mVH.js +0 -1
  481. package/dist/public/sdk/walletCustodyEcdsaContinuity-DlOBCmwb.js +0 -1
  482. package/dist/public/sdk/walletCustodyOperation-DzPcxEBS.js +0 -1
  483. package/dist/public/sdk/walletDbName-DDJXrgA5.js +0 -1
  484. package/dist/public/sdk/walletOwnershipGeneration-DI9ogcXF.js +0 -1
  485. package/dist/public/sdk/walletRecoveryAdminProof-BJxmg3f7.js +0 -1
  486. package/dist/public/sdk/walletRecoveryCommit-B7WsdR7y.js +0 -1
  487. package/dist/public/sdk/walletRegistrationSetupPrewarm-CEJCj78c.js +0 -1
  488. package/dist/public/sdk/walletSessionAuthorizationStatus-98G3Qji8.js +0 -1
  489. package/dist/public/sdk/warmSessionHydration-DqZyfi1h.js +0 -1
  490. /package/dist/esm/sdk/{accountIds-D5NI31F2.js → accountIds-CW2BP-d9.js} +0 -0
  491. /package/dist/esm/sdk/{authenticatorOptions-EF_Rps52.js → authenticatorOptions-WCDKYRux.js} +0 -0
  492. /package/dist/esm/sdk/{authorizationAdmission-DbhNiY3X.js → authorizationAdmission-28jo_IVJ.js} +0 -0
  493. /package/dist/esm/sdk/{browser-B2RI00tM.js → browser-CKS7Tq2r.js} +0 -0
  494. /package/dist/esm/sdk/{bytes-DVe42j_r.js → bytes-DXo6uALR.js} +0 -0
  495. /package/dist/esm/sdk/{canonicalSignerErrorCode-AwNMAn8S.js → canonicalSignerErrorCode-CX5PBpkt.js} +0 -0
  496. /package/dist/esm/sdk/{capabilityKinds-BzrNeEyO.js → capabilityKinds-DVlGMspk.js} +0 -0
  497. /package/dist/esm/sdk/{configHelpers-BNqoU2cv.js → configHelpers-CXDY3bKC.js} +0 -0
  498. /package/dist/esm/sdk/{csp-stylesheet-DeuiM0Mo.js → csp-stylesheet-DUSqfXvZ.js} +0 -0
  499. /package/dist/esm/sdk/{events-1dzC4Ocx.js → events-D6l0_ugy.js} +0 -0
  500. /package/dist/esm/sdk/{executeWorkerOperation-B-9JuL55.js → executeWorkerOperation-C9FOCCR7.js} +0 -0
  501. /package/dist/esm/sdk/{jsonRpc-CHutSlC9.js → jsonRpc-BVDv1wfm.js} +0 -0
  502. /package/dist/esm/sdk/{keccak-C9kCkZem.js → keccak-mS0Mejjx.js} +0 -0
  503. /package/dist/esm/sdk/{normalization-DtruiNPw.js → normalization-B3i1-rPQ.js} +0 -0
  504. /package/dist/esm/sdk/{prfCache-8Wm3etlV.js → prfCache-DEHaUPSW.js} +0 -0
  505. /package/dist/esm/sdk/{profileAccountProjection-D01e10UY.js → profileAccountProjection-C5sNt-s2.js} +0 -0
  506. /package/dist/esm/sdk/{promptText-Bz3YRl9D.js → promptText-bcKcsSka.js} +0 -0
  507. /package/dist/esm/sdk/{registrationAuthMethodInput-BvbWl0y_.js → registrationAuthMethodInput-BR1WVbK3.js} +0 -0
  508. /package/dist/esm/sdk/{sdkSentEvents-DUht3AOD.js → sdkSentEvents-DjOlKtdW.js} +0 -0
  509. /package/dist/esm/sdk/{shared-DcHtE-D-.js → shared-CkHhXgFB.js} +0 -0
  510. /package/dist/esm/sdk/{signer-worker-DlK58rEA.js → signer-worker-BNodGJKY.js} +0 -0
  511. /package/dist/esm/sdk/{signerDomain-D-EUTlLK.js → signerDomain-BAsLT3XN.js} +0 -0
  512. /package/dist/esm/sdk/{signingSessionSeal-DqbjG8c8.js → signingSessionSeal-BFOBKj-J.js} +0 -0
  513. /package/dist/esm/sdk/{types-fJKfUgTi.js → types-C4OErbBf.js} +0 -0
  514. /package/dist/esm/sdk/{walletIframeIdentity-Cz82I_Uh.js → walletIframeIdentity-CpgyEnKg.js} +0 -0
  515. /package/dist/esm/sdk/{walletSessionFailure-CLUIF3Eh.js → walletSessionFailure-CxsVtroW.js} +0 -0
  516. /package/dist/esm/sdk/{webauthnPromptCoordinator-CU9ag7vz.js → webauthnPromptCoordinator-npsSRD51.js} +0 -0
  517. /package/dist/public/sdk/{accountIds-D5NI31F2.js → accountIds-CW2BP-d9.js} +0 -0
  518. /package/dist/public/sdk/{authenticatorOptions-EF_Rps52.js → authenticatorOptions-WCDKYRux.js} +0 -0
  519. /package/dist/public/sdk/{authorizationAdmission-DbhNiY3X.js → authorizationAdmission-28jo_IVJ.js} +0 -0
  520. /package/dist/public/sdk/{browser-B2RI00tM.js → browser-CKS7Tq2r.js} +0 -0
  521. /package/dist/public/sdk/{bytes-DVe42j_r.js → bytes-DXo6uALR.js} +0 -0
  522. /package/dist/public/sdk/{canonicalSignerErrorCode-AwNMAn8S.js → canonicalSignerErrorCode-CX5PBpkt.js} +0 -0
  523. /package/dist/public/sdk/{capabilityKinds-BzrNeEyO.js → capabilityKinds-DVlGMspk.js} +0 -0
  524. /package/dist/public/sdk/{configHelpers-BNqoU2cv.js → configHelpers-CXDY3bKC.js} +0 -0
  525. /package/dist/public/sdk/{csp-stylesheet-DeuiM0Mo.js → csp-stylesheet-DUSqfXvZ.js} +0 -0
  526. /package/dist/public/sdk/{events-1dzC4Ocx.js → events-D6l0_ugy.js} +0 -0
  527. /package/dist/public/sdk/{executeWorkerOperation-B-9JuL55.js → executeWorkerOperation-C9FOCCR7.js} +0 -0
  528. /package/dist/public/sdk/{jsonRpc-CHutSlC9.js → jsonRpc-BVDv1wfm.js} +0 -0
  529. /package/dist/public/sdk/{keccak-C9kCkZem.js → keccak-mS0Mejjx.js} +0 -0
  530. /package/dist/public/sdk/{normalization-DtruiNPw.js → normalization-B3i1-rPQ.js} +0 -0
  531. /package/dist/public/sdk/{prfCache-8Wm3etlV.js → prfCache-DEHaUPSW.js} +0 -0
  532. /package/dist/public/sdk/{profileAccountProjection-D01e10UY.js → profileAccountProjection-C5sNt-s2.js} +0 -0
  533. /package/dist/public/sdk/{promptText-Bz3YRl9D.js → promptText-bcKcsSka.js} +0 -0
  534. /package/dist/public/sdk/{registrationAuthMethodInput-BvbWl0y_.js → registrationAuthMethodInput-BR1WVbK3.js} +0 -0
  535. /package/dist/public/sdk/{sdkSentEvents-DUht3AOD.js → sdkSentEvents-DjOlKtdW.js} +0 -0
  536. /package/dist/public/sdk/{shared-DcHtE-D-.js → shared-CkHhXgFB.js} +0 -0
  537. /package/dist/public/sdk/{signer-worker-DlK58rEA.js → signer-worker-BNodGJKY.js} +0 -0
  538. /package/dist/public/sdk/{signerDomain-D-EUTlLK.js → signerDomain-BAsLT3XN.js} +0 -0
  539. /package/dist/public/sdk/{signingSessionSeal-DqbjG8c8.js → signingSessionSeal-BFOBKj-J.js} +0 -0
  540. /package/dist/public/sdk/{types-fJKfUgTi.js → types-C4OErbBf.js} +0 -0
  541. /package/dist/public/sdk/{walletIframeIdentity-Cz82I_Uh.js → walletIframeIdentity-CpgyEnKg.js} +0 -0
  542. /package/dist/public/sdk/{walletSessionFailure-CLUIF3Eh.js → walletSessionFailure-CxsVtroW.js} +0 -0
  543. /package/dist/public/sdk/{webauthnPromptCoordinator-CU9ag7vz.js → webauthnPromptCoordinator-npsSRD51.js} +0 -0
@@ -1 +0,0 @@
1
- import{A as e,C as t,E as n,I as r,M as i,N as a,O as o,T as s,V as c,c as l,g as u,i as d,j as f,k as p,r as m,s as h}from"./domainIds-t1lp25yU.js";import{D as g,c as _,d as v,j as y,k as b,l as ee,u as te}from"./chains-gV2K9gA4.js";import{D as x,G as ne,H as re,K as ie,V as ae,W as S,X as oe,a as se}from"./activeWalletSession-H9JBdHyQ.js";import{i as C,r as ce}from"./base64-BmKR3UqU.js";import{r as le}from"./secureRandomId-8LSc91aN.js";import{s as ue,t as de}from"./walletDbName-DDJXrgA5.js";import{l as fe}from"./capabilityKinds-BzrNeEyO.js";import{a as pe,n as me,r as he}from"./canonicalPrimitives-B6YMrI3W.js";import{r as ge}from"./signerDomain-D-EUTlLK.js";import{Ft as _e,W as ve,j as ye,k as be}from"./registrationIntent-DTs2SR9E.js";import{a as w,i as T,n as xe}from"./presignatures-B9GrGx0L.js";import{a as Se,c as Ce}from"./ecdsaChainTarget-DbLthshF.js";import{a as E,i as we,n as Te,o as Ee,r as D,s as De,t as O}from"./normalization-BN-2VWZf.js";import{i as Oe,n as ke,r as Ae,t as je}from"./keyMaterialEnvelope-B-Q5KTJC.js";import{t as Me}from"./accountIds-D5NI31F2.js";import{D as Ne,G as Pe,K as Fe,T as Ie,W as Le,Z as Re,_ as ze,ct as Be,h as Ve,it as He,m as Ue,ot as We,p as Ge,rt as Ke,x as k,y as qe}from"./walletCapabilityBindings-CUPk3mVH.js";import{Ft as Je,Jt as Ye,Lt as Xe,Pt as Ze,Qt as Qe,St as $e,T as et,Vt as tt,Zt as nt,dn as rt,ft as it,zt as at}from"./emailOtpEcdsaDerivationIdentity-CIh9IPai.js";import{i as ot,r as A}from"./walletAuthMethodRecord-yIqCeE-o.js";import{i as st,o as ct,t as lt}from"./signerSlot-D4ZOuK7e.js";import{A as ut,C as dt,I as ft,P as pt,_ as mt,c as ht,n as gt,s as _t,t as vt,v as yt}from"./ecdsaCapabilityManifest--FjbES8k.js";import{v as bt}from"./sdkSentEvents-DUht3AOD.js";import{$ as xt,A as St,B as Ct,C as wt,D as Tt,E as Et,F as Dt,G as Ot,H as kt,I as At,J as jt,K as Mt,L as Nt,M as Pt,N as Ft,O as It,P as Lt,Q as Rt,R as zt,S as Bt,T as Vt,U as Ht,V as Ut,W as Wt,X as Gt,Y as Kt,Z as qt,_ as Jt,at as Yt,b as j,c as Xt,ct as Zt,d as Qt,dt as $t,et as en,f as tn,g as nn,h as rn,it as an,j as on,k as sn,l as cn,lt as ln,m as un,nt as dn,o as fn,ot as pn,p as mn,q as hn,r as gn,rt as _n,s as vn,st as yn,tt as bn,u as xn,v as M,w as N,x as P,y as Sn,z as Cn}from"./walletOwnershipGeneration-DI9ogcXF.js";import{a as wn,i as Tn,n as En,r as Dn}from"./walletSessionAuthorizationStore-zkxcMdSp.js";import{_ as On,b as F,u as kn,v as An}from"./nonceLaneKeys-BS4fek17.js";function jn(e){return _({domain:`seams/wallet/ordinary-authority-material-seal-aad/v1`,authorityId:String(e.authorityId),walletId:String(e.walletId),walletAuthMethodId:String(e.walletAuthMethodId),packageSetDigestB64u:String(e.packageSetDigestB64u),targetFactor:e.targetFactor,keyFamily:e.keyFamily,materialActivation:e.materialActivation})}function Mn(e){let t=b(e,`linked signer material record`);if(t.kind!==`wallet_authority_linked_signer_material_v1`)throw Error(`linked signer material record kind is invalid`);if(t.keyFamily!==`ed25519`&&t.keyFamily!==`ecdsa_secp256k1`)throw Error(`linked signer material keyFamily is invalid`);let r=[`kind`,`authorityId`,`walletAuthMethodId`,`activationId`,`keyFamily`,`materialActivation`,`sealedMaterialB64u`,`sealedMaterialDigestB64u`,`packageSetDigestB64u`,`targetFactor`,`publicFacts`];zn(t,t.keyFamily===`ecdsa_secp256k1`?[...r,`ecdsaThresholdKeyId`]:r,`linked signer material record`);let i=Rn(o(t.authorityId),`authorityId`),a=Rn(n(t.walletAuthMethodId),`walletAuthMethodId`),s=Rn(u(t.materialActivation),`materialActivation`),c=g(t.activationId,`activationId`,`must be a non-empty canonical string`);if(s.activationId!==c)throw Error(`linked signer material activationId does not match materialActivation`);let l=Ln(t.sealedMaterialB64u,`sealedMaterialB64u`),d=he(t.sealedMaterialDigestB64u),f=he(t.packageSetDigestB64u),p=Pn(t.targetFactor);if(p.walletAuthMethodId!==a)throw Error(`linked signer material target factor auth method differs from record`);if(t.keyFamily===`ed25519`){let e=Fn(t.publicFacts,s);return{kind:`wallet_authority_linked_signer_material_v1`,authorityId:i,walletAuthMethodId:a,activationId:s.activationId,keyFamily:`ed25519`,materialActivation:s,sealedMaterialB64u:l,sealedMaterialDigestB64u:d,packageSetDigestB64u:f,targetFactor:p,publicFacts:e}}let m=ft(t.ecdsaThresholdKeyId),h=In(t.publicFacts,s);if(h.ecdsaThresholdKeyId!==m)throw Error(`linked signer material ECDSA threshold key id differs from public facts`);return{kind:`wallet_authority_linked_signer_material_v1`,authorityId:i,walletAuthMethodId:a,activationId:s.activationId,keyFamily:`ecdsa_secp256k1`,ecdsaThresholdKeyId:m,materialActivation:s,sealedMaterialB64u:l,sealedMaterialDigestB64u:d,packageSetDigestB64u:f,targetFactor:p,publicFacts:h}}async function Nn(e){let t=e.record;if(t.authorityId!==e.expected.authorityId||t.walletAuthMethodId!==e.expected.walletAuthMethodId||t.keyFamily!==e.expected.keyFamily||!d(t.materialActivation,e.expected.materialActivation))return{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`identity_mismatch`};if(!Bn(t.targetFactor,e.expected.targetFactor))return{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`target_factor_mismatch`};if(t.packageSetDigestB64u!==e.expected.packageSetDigestB64u)return{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`package_digest_mismatch`};if(e.factorSecret.byteLength!==32)return{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`factor_secret_invalid`};let n;try{n=ce(t.sealedMaterialB64u)}catch{return{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`sealed_material_invalid`}}if(n.length<29)return n.fill(0),{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`sealed_material_invalid`};if(await pe(n)!==t.sealedMaterialDigestB64u)return n.fill(0),{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`sealed_material_digest_mismatch`};let r=new TextEncoder,i=r.encode(jn(e.expected)),a=await ee(i),o=n.slice(0,12),s=n.slice(12);try{let n=await globalThis.crypto.subtle.importKey(`raw`,e.factorSecret,{name:`HKDF`},!1,[`deriveKey`]),c=await globalThis.crypto.subtle.deriveKey({name:`HKDF`,hash:`SHA-256`,salt:a,info:r.encode(`seams/wallet/ordinary-authority-material-seal/v1`)},n,{name:`AES-GCM`,length:256},!1,[`decrypt`]),l=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:`AES-GCM`,iv:o,additionalData:i},c,s));return t.keyFamily===`ed25519`?{kind:`opened_wallet_authority_linked_signer_material_v1`,authorityId:t.authorityId,walletAuthMethodId:t.walletAuthMethodId,keyFamily:`ed25519`,materialActivation:t.materialActivation,publicFacts:t.publicFacts,material:l}:{kind:`opened_wallet_authority_linked_signer_material_v1`,authorityId:t.authorityId,walletAuthMethodId:t.walletAuthMethodId,keyFamily:`ecdsa_secp256k1`,materialActivation:t.materialActivation,publicFacts:t.publicFacts,material:l}}catch{return{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`sealed_material_authentication_failed`}}finally{n.fill(0),i.fill(0),a.fill(0),o.fill(0),s.fill(0)}}function Pn(e){let t=b(e,`linked signer material target factor`);if(t.kind===`passkey`)return zn(t,[`kind`,`walletAuthMethodId`,`verificationDigestB64u`,`rpId`,`credentialIdB64u`],`linked signer material passkey target factor`),{kind:`passkey`,walletAuthMethodId:Rn(n(t.walletAuthMethodId),`targetFactor.walletAuthMethodId`),verificationDigestB64u:he(t.verificationDigestB64u),rpId:Rn(a(t.rpId),`targetFactor.rpId`),credentialIdB64u:Ln(Rn(i(t.credentialIdB64u),`targetFactor.credentialIdB64u`),`targetFactor.credentialIdB64u`)};if(t.kind===`email_otp`){zn(t,[`kind`,`walletAuthMethodId`,`verificationDigestB64u`,`emailHashHex`,`registrationAuthorityId`],`linked signer material email target factor`);let e=g(t.emailHashHex,`targetFactor.emailHashHex`,`must be a non-empty canonical string`);if(!/^[0-9a-f]{64}$/.test(e))throw Error(`targetFactor.emailHashHex is invalid`);return{kind:`email_otp`,walletAuthMethodId:Rn(n(t.walletAuthMethodId),`targetFactor.walletAuthMethodId`),verificationDigestB64u:he(t.verificationDigestB64u),emailHashHex:e,registrationAuthorityId:g(t.registrationAuthorityId,`targetFactor.registrationAuthorityId`,`must be a non-empty canonical string`)}}throw Error(`linked signer material target factor kind is invalid`)}function Fn(e,t){let n=b(e,`linked signer material Ed25519 public facts`);if(zn(n,[`keyFamily`,`participantIds`,`targetBinding`,`applicationBinding`,`activationReceipt`],`linked signer material Ed25519 public facts`),n.keyFamily!==`ed25519`)throw Error(`linked signer material Ed25519 public facts family is invalid`);let r=Le(n.activationReceipt),i=Fe(n.targetBinding),a=Pe(n.applicationBinding);if(!d(t,rt(r.material_activation)))throw Error(`linked signer material Ed25519 receipt activation differs`);return{keyFamily:`ed25519`,participantIds:Re(n.participantIds),targetBinding:i,applicationBinding:a,activationReceipt:r}}function In(e,t){let n=b(e,`linked signer material ECDSA public facts`);if(zn(n,[`keyFamily`,`ecdsaThresholdKeyId`,`activationReceipt`],`linked signer material ECDSA public facts`),n.keyFamily!==`ecdsa_secp256k1`)throw Error(`linked signer material ECDSA public facts family is invalid`);let r=Ne(n.activationReceipt);if(!d(t,r.binding.target.activation))throw Error(`linked signer material ECDSA receipt activation differs`);return{keyFamily:`ecdsa_secp256k1`,ecdsaThresholdKeyId:ft(n.ecdsaThresholdKeyId),activationReceipt:r}}function Ln(e,t){if(typeof e!=`string`||e.length===0||!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} must be canonical non-empty base64url`);let n=ce(e);if(n.length===0||C(n)!==e)throw n.fill(0),Error(`${t} must be canonical non-empty base64url`);return n.fill(0),e}function Rn(e,t){if(!e.ok)throw Error(`${t}: ${e.error.message}`);return e.value}function zn(e,t,n){let r=Object.keys(e);if(r.length!==t.length||t.some(e=>!r.includes(e)))throw Error(`${n} fields are invalid`)}function Bn(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`?e.walletAuthMethodId===t.walletAuthMethodId&&e.verificationDigestB64u===t.verificationDigestB64u&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u:!1;case`email_otp`:return t.kind===`email_otp`?e.walletAuthMethodId===t.walletAuthMethodId&&e.verificationDigestB64u===t.verificationDigestB64u&&e.emailHashHex===t.emailHashHex&&e.registrationAuthorityId===t.registrationAuthorityId:!1;default:return Vn(e)}}function Vn(e){throw Error(`unsupported linked authority material target factor: ${String(e)}`)}const Hn=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,Un=Object.freeze(Array.from(Hn).reduce((e,t,n)=>(e[t]=n,e),{}));function Wn(e){if(!e)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<48||n>57)return!1}return!0}function Gn(e){if(e.byteLength!==20)throw Error(`Email OTP recovery key bytes must be exactly 20 bytes`);let t=0,n=0,r=``;for(let i=0;i<e.byteLength;i++)for(t=t<<8|e[i],n+=8;n>=5;)n-=5,r+=Hn[t>>n&31],t&=(1<<n)-1;return r}function I(e){let t=qn(e),n=[],r=0;for(let e=0;e<8;e++)n.push(t.slice(r,r+4)),r+=4;return n.join(`-`)}function Kn(e){if(e.length!==10)throw Error(`Email OTP recovery code set must contain 10 keys`);return[I(e[0]),I(e[1]),I(e[2]),I(e[3]),I(e[4]),I(e[5]),I(e[6]),I(e[7]),I(e[8]),I(e[9])]}function qn(e){let t=String(e||``).replace(/[\s-]/g,``).toUpperCase();if(t.length!==32)throw Error(`Email OTP recovery key must be 32 Crockford Base32 characters`);if(Wn(t))throw Error(`Email OTP recovery key must not be decimal-only`);for(let e=0;e<t.length;e++)if(Un[t[e]]===void 0)throw Error(`Email OTP recovery key contains unsupported characters`);return t}function Jn(e){let t=qn(e),n=new Uint8Array(20),r=0,i=0,a=0;for(let e=0;e<t.length;e++)r=r<<5|Un[t[e]],i+=5,i>=8&&(i-=8,n[a]=r>>i&255,r&=(1<<i)-1,a+=1);return n}function Yn(e){return e.kind===`evm`?`evm:eip155:${e.chainId}`:`tempo:${e.chainId}`}function Xn(e){return e.kind===`evm`?{kind:`evm`,namespace:`eip155`,chainId:e.chainId,...e.networkSlug?{networkSlug:e.networkSlug}:{}}:{kind:`tempo`,chainId:e.chainId,...e.networkSlug?{networkSlug:e.networkSlug}:{}}}function Zn(e){let t=e.keyTargets.map(e=>({keyHandle:e.keyHandle,chainTarget:Xn(e.chainTarget),targetKey:Yn(e.chainTarget)})).sort((e,t)=>{let n=`${e.keyHandle}:${e.targetKey}`,r=`${t.keyHandle}:${t.targetKey}`;return n.localeCompare(r)});return _({version:`wallet-ecdsa-key-facts-inventory:v1`,walletId:e.walletId,rpId:e.rpId,keyTargets:t,...e.runtimePolicyScope?{runtimePolicyScope:e.runtimePolicyScope}:{},serverNonceB64u:e.serverNonceB64u})}async function Qn(e){return C(await te(Zn(e)))}const $n=`x-seams-trace-id`,er=/^[0-9a-f]{32}$/;function tr(e){return e==null||e===``?{ok:!1,reason:`missing`,message:`Router trace ID is missing`}:typeof e!=`string`||!er.test(e)?{ok:!1,reason:`invalid`,message:`Router trace ID must be 32 lowercase hexadecimal characters`}:{ok:!0,value:{kind:`router_ab_trace_context_v1`,value:e}}}function nr(){let e=new Uint8Array(16);globalThis.crypto.getRandomValues(e);let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return{kind:`router_ab_trace_context_v1`,value:t}}var rr=class extends Error{code;details;constructor(e){super(e.message),this.name=`SignerLifecycleError`,this.code=e.code,this.details=e.details||{}}};function ir(e,t){let n=c(e);if(!n)throw new rr({code:`signer_lifecycle_invalid_input`,message:`${t} is required`,details:{label:t}});return n}function ar(e,t){if(e==null)return;let n=r(e);if(n==null||!Number.isSafeInteger(n)||n<1)throw new rr({code:`signer_lifecycle_invalid_input`,message:`${t} must be an integer >= 1`,details:{label:t,value:e}});return n}function or(e,t){let n=ar(e,t);if(n==null)throw new rr({code:`signer_lifecycle_invalid_input`,message:`${t} is required`,details:{label:t}});return n}function sr(e){for(let t=1;t<1e3;t+=1)if(!e.has(t))return t;throw new rr({code:`signer_lifecycle_no_available_slot`,message:`No available account signer slot`})}function cr(e){let t=e.metadata?.signerMaterialFingerprint;return typeof t==`string`?t.trim():``}function lr(e){let t=ir(e.expectedFingerprint,`activationPolicy.materialFingerprint`),n=cr(e.existingSigner);if(!n)throw new rr({code:`signer_lifecycle_missing_material_fingerprint`,message:`Existing signer ${e.existingSigner.signerId} is missing signer material fingerprint`,details:{signerId:e.existingSigner.signerId}});if(n!==t)throw new rr({code:`signer_lifecycle_material_mismatch`,message:`Existing signer material mismatch for ${e.existingSigner.signerId}`,details:{signerId:e.existingSigner.signerId,expectedFingerprint:t,existingFingerprint:n}})}function ur(e){let t=ir(e.signer.signerId,`signerId`),n=ir(e.signer.signerKind,`signerKind`);ir(e.signer.signerAuthMethod,`signerAuthMethod`),ir(e.signer.signerSource,`signerSource`);let r=Array.isArray(e.activeSigners)?e.activeSigners:[],i=r.find(e=>e.signerId===t),a=ar(e.preferredSlot,`preferredSlot`);if(e.activationPolicy.mode===`reuse_existing`){if(ir(e.activationPolicy.signerId,`activationPolicy.signerId`),e.activationPolicy.signerId!==t)throw new rr({code:`signer_lifecycle_invalid_input`,message:`reuse_existing activation policy signerId must match signer.signerId`,details:{policySignerId:e.activationPolicy.signerId,signerId:t}});ir(e.activationPolicy.materialFingerprint,`activationPolicy.materialFingerprint`)}if(e.activationPolicy.mode===`replace_slot`||e.activationPolicy.mode===`replace_profile_chain_kind`){if(e.activationPolicy.replacedSignerKind!==n)throw new rr({code:`signer_lifecycle_invalid_input`,message:`replacement activation policy signer kind must match signer.signerKind`,details:{signerKind:n,replacedSignerKind:e.activationPolicy.replacedSignerKind}});ir(e.activationPolicy.revocationReason,`activationPolicy.revocationReason`)}if(i)return e.activationPolicy.mode===`reuse_existing`&&lr({existingSigner:i,expectedFingerprint:e.activationPolicy.materialFingerprint}),{signerSlot:or(i.signerSlot,`signerSlot`)};if(e.activationPolicy.mode===`reuse_existing`){let e=r.find(e=>e.signerKind===n);if(e)throw new rr({code:`signer_lifecycle_duplicate_registration`,message:`Duplicate account registration for ${n}: existing signer ${e.signerId} differs from ${t}`,details:{signerKind:n,signerId:t,conflictingSignerId:e.signerId}})}if(e.activationPolicy.mode===`fail_if_occupied`){let t=or(e.activationPolicy.signerSlot,`signerSlot`),n=r.find(e=>e.signerSlot===t);if(n)throw new rr({code:`signer_lifecycle_slot_occupied`,message:`Active signer slot ${t} is already occupied`,details:{signerSlot:t,occupantSignerId:n.signerId}});return{signerSlot:t}}if(e.activationPolicy.mode===`replace_slot`||e.activationPolicy.mode===`replace_profile_chain_kind`)return{signerSlot:or(e.activationPolicy.signerSlot,`signerSlot`)};let o=new Set(r.map(e=>e.signerSlot));return{signerSlot:a&&!o.has(a)?a:sr(o)}}function dr(e){if(typeof e!=`object`||!e)return null;let t=typeof e.profileId==`string`?String(e.profileId).trim():``;if(!t)return null;let n=Number(e.activeSignerSlot);if(!Number.isSafeInteger(n)||n<1)return null;let r=we(e.scope);return r==null?{profileId:t,activeSignerSlot:n}:{profileId:t,activeSignerSlot:n,scope:r}}function fr(e){return{kind:e.kind,registrationCeremonyId:e.registrationCeremonyId,idempotencyKey:e.idempotencyKey,walletId:e.walletId,walletAuthMethodId:e.walletAuthMethodId,signedSetup:e.signedSetup,auth:e.auth,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs}}function pr(e,t){if(t.application_binding.wallet_id!==e.walletId)throw Error(`NEAR continuation wallet mismatch`);return{...fr(e),operation:`near_provisioning`,signerPlanKind:e.signerPlanKind,phase:`planned`,admissionRequest:t,baseCustodyCommit:e.localMaterial.custodyCommit}}function mr(e,t,n){try{let r=$r(JSON.parse(e),[`executeRequestJson`,`applicationBindingDigestB64u`,`nonceB64u`,`ciphertextB64u`]);if(!r)return!1;let i=L(r.get(`executeRequestJson`));if(!i||!L(r.get(`applicationBindingDigestB64u`))||!L(r.get(`nonceB64u`))||!L(r.get(`ciphertextB64u`)))return!1;let a=He(JSON.parse(i));return a.ok&&Be(a.value.binding,t.binding)&&t.binding.lifecycle.lifecycle_id===n.scope.lifecycle_id&&t.binding.lifecycle.account_id===n.scope.account_id}catch{return!1}}function hr(e,t,n){if(!mr(n,t,e.admissionRequest))throw Error(`Invalid NEAR registration execution checkpoint`);return{...fr(e),operation:`near_provisioning`,signerPlanKind:e.signerPlanKind,phase:`execution_prepared`,admissionRequest:e.admissionRequest,baseCustodyCommit:e.baseCustodyCommit,admissionReceipt:t,checkpointJson:n,updatedAtMs:Math.max(Date.now(),e.updatedAtMs)}}const gr=`pending_wallet_registration_commit_v1:`;function _r(e){return`${gr}${e.registrationCeremonyId}:${e.operation}`}function vr(e){let t=Cr(e);return{key:_r({registrationCeremonyId:t.registration_ceremony_id,operation:t.operation}),value:t}}function yr(e){let t=$r(e,[`key`,`value`]);if(!t)return null;let n=t.get(`key`);if(typeof n!=`string`||!n.startsWith(gr))return null;let r=wr(t.get(`value`));return r&&_r({registrationCeremonyId:r.registration_ceremony_id,operation:r.operation})===n?r:null}async function br(e){let t=z(e,`value`),n=$r(z(t,`record`),[`kind`,`operation`,`signerPlanKind`,`registrationCeremonyId`,`idempotencyKey`,`walletId`,`walletAuthMethodId`,`signedSetup`,`auth`,`createdAtMs`,`updatedAtMs`,`localMaterial`]);if(!n||n.get(`operation`)!==`registration_activate`||n.get(`signerPlanKind`)!==`near_ed25519_and_evm_family_ecdsa`)return null;let r=Mr(n.get(`localMaterial`));if(!r||!Fr(r))return null;let i=Tr({...Object.fromEntries(n),localMaterial:{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:r.custodyCommit,ecdsa:r.ecdsa}});if(!i||i.operation!==`registration_activate`||z(e,`key`)!==_r(i)||z(t,`wallet_id`)!==i.walletId||z(t,`wallet_auth_method_id`)!==i.walletAuthMethodId||z(t,`registration_ceremony_id`)!==i.registrationCeremonyId||z(t,`operation`)!==i.operation||z(t,`updated_at_ms`)!==i.updatedAtMs)return null;let a=r.ed25519.activationReference,o=await v([`wallet-registration-near-provisioning`,i.registrationCeremonyId,a.lifecycle_id,a.session_id.map(xr).join(``)].join(`:`)),s=Tr({...fr(i),operation:`near_provisioning`,phase:`joined`,signerPlanKind:i.signerPlanKind,idempotencyKey:`wallet-registration-near-provisioning:${o}`,localMaterial:{keyFamilies:[`ed25519`],custodyCommit:r.ed25519.custodyCommit,ed25519:{activationReference:a,localMaterial:r.ed25519.localMaterial,metadata:r.ed25519.metadata}}});return!s||s.operation!==`near_provisioning`||s.phase!==`joined`?null:{original:e,activation:i,near:s}}function xr(e){return e.toString(16).padStart(2,`0`)}function Sr(e){return e}function Cr(e){let t=Sr(e);return{registration_ceremony_id:t.registrationCeremonyId,operation:t.operation,wallet_id:t.walletId,wallet_auth_method_id:t.walletAuthMethodId,updated_at_ms:t.updatedAtMs,record:t}}function wr(e){let t=$r(e,[`registration_ceremony_id`,`operation`,`wallet_id`,`wallet_auth_method_id`,`updated_at_ms`,`record`]);if(!t)return null;let n=Tr(t.get(`record`));return!n||t.get(`registration_ceremony_id`)!==n.registrationCeremonyId||t.get(`operation`)!==n.operation||t.get(`wallet_id`)!==n.walletId||t.get(`wallet_auth_method_id`)!==n.walletAuthMethodId||t.get(`updated_at_ms`)!==n.updatedAtMs?null:{registration_ceremony_id:n.registrationCeremonyId,operation:n.operation,wallet_id:n.walletId,wallet_auth_method_id:n.walletAuthMethodId,updated_at_ms:n.updatedAtMs,record:n}}function Tr(e){let t=ei(e,[`kind`,`operation`,`signerPlanKind`,`registrationCeremonyId`,`idempotencyKey`,`walletId`,`walletAuthMethodId`,`signedSetup`,`auth`,`localMaterial`,`phase`,`admissionRequest`,`admissionReceipt`,`baseCustodyCommit`,`checkpointJson`,`completion`,`createdAtMs`,`updatedAtMs`]);if(!t||t.get(`kind`)!==`pending_wallet_registration_commit_v1`||t.has(`completion`)&&t.get(`phase`)!==`joined`)return null;let r=Dr(t.get(`operation`)),i=Or(t.get(`signerPlanKind`)),a=L(t.get(`registrationCeremonyId`)),o=L(t.get(`idempotencyKey`)),s=L(t.get(`signedSetup`)),c=p(t.get(`walletId`)),l=n(t.get(`walletAuthMethodId`)),u=Qr(kr(),t.get(`auth`)),d=Mr(t.get(`localMaterial`)),f=Zr(t.get(`createdAtMs`)),m=Zr(t.get(`updatedAtMs`));if(r!==`registration_activate`&&r!==`near_provisioning`||i===null||a===null||o===null||s===null||!c.ok||!l.ok||!u||f===null||m===null||m<f)return null;let h={kind:`pending_wallet_registration_commit_v1`,registrationCeremonyId:a,idempotencyKey:o,walletId:c.value,walletAuthMethodId:l.value,signedSetup:s,auth:u,createdAtMs:f,updatedAtMs:m},g=t.get(`phase`);if(r===`near_provisioning`&&(g===`planned`||g===`execution_prepared`)){let e=We(t.get(`admissionRequest`)),n=Ur(t.get(`baseCustodyCommit`));if(i!==`near_ed25519_and_evm_family_ecdsa`||t.has(`localMaterial`)||!e.ok||e.value.application_binding.wallet_id!==c.value||!n||n.keySet!==`evm_family_ecdsa_v1`||n.walletId!==c.value||!n.establishedCustody)return null;if(g===`planned`)return t.has(`admissionReceipt`)||t.has(`checkpointJson`)?null:{...h,operation:r,signerPlanKind:i,phase:g,admissionRequest:e.value,baseCustodyCommit:{...n,keySet:`evm_family_ecdsa_v1`}};let a=Ke(t.get(`admissionReceipt`)),o=L(t.get(`checkpointJson`));return!a.ok||!o||!mr(o,a.value,e.value)?null:{...h,operation:r,signerPlanKind:i,phase:g,admissionRequest:e.value,baseCustodyCommit:{...n,keySet:`evm_family_ecdsa_v1`},admissionReceipt:a.value,checkpointJson:o}}if(!d||d.custodyCommit.walletId!==c.value||t.has(`admissionRequest`)||t.has(`admissionReceipt`)||t.has(`baseCustodyCommit`)||t.has(`checkpointJson`)||Fr(d)&&d.ed25519.custodyCommit.walletId!==c.value)return null;if(r===`registration_activate`)return g!==void 0||i===`near_ed25519`?null:Pr(d)?{kind:`pending_wallet_registration_commit_v1`,operation:r,signerPlanKind:i,registrationCeremonyId:a,idempotencyKey:o,walletId:c.value,walletAuthMethodId:l.value,signedSetup:s,auth:u,localMaterial:d,createdAtMs:f,updatedAtMs:m}:null;if(r===`near_provisioning`){if(g!==void 0&&g!==`joined`||i!==`near_ed25519`&&i!==`near_ed25519_and_evm_family_ecdsa`||!Nr(d))return null;let e={kind:`sealed_material`},n=t.get(`completion`);if(n!==void 0){let t=ei(n,[`kind`,`prepared`]);if(!t)return null;switch(t.get(`kind`)){case`sealed_material`:if(t.has(`prepared`))return null;break;case`encrypted_checkpoint`:{let n=t.get(`prepared`);if(z(n,`phase`)!==`execution_prepared`)return null;let r=Tr(n);if(!r||r.phase!==`execution_prepared`||r.registrationCeremonyId!==a||r.walletId!==c.value||r.walletAuthMethodId!==l.value||r.signedSetup!==s||i!==r.signerPlanKind)return null;e={kind:`encrypted_checkpoint`,prepared:r};break}default:return null}}return{kind:`pending_wallet_registration_commit_v1`,operation:r,phase:`joined`,completion:e,signerPlanKind:i,registrationCeremonyId:a,idempotencyKey:o,walletId:c.value,walletAuthMethodId:l.value,signedSetup:s,auth:u,localMaterial:d,createdAtMs:f,updatedAtMs:m}}return null}function Er(e,t){if(e.operation!==t.operation||e.walletId!==t.walletId||e.walletAuthMethodId!==t.walletAuthMethodId||t.authority.walletId!==e.walletId||t.authority.bindingId!==e.walletAuthMethodId)throw Error(`pending wallet registration commit identity does not match projection`);if(e.auth.kind===`passkey`){if(!Je(t.authority)||t.authority.factor.credentialIdB64u!==e.auth.credentialIdB64u||t.authority.verifier.rpId!==e.auth.rpId)throw Error(`pending passkey registration authority does not match projection`);return}if(!Ze(t.authority))throw Error(`pending Email OTP registration authority does not match projection`);if(t.authority.factor.providerUserId!==e.auth.providerSubject||t.authority.verifier.emailHashHex.length===0)throw Error(`pending Email OTP registration factor does not match projection`)}function Dr(e){return e===`registration_activate`||e===`near_provisioning`?e:null}function Or(e){return e===`near_ed25519`||e===`evm_family_ecdsa`||e===`near_ed25519_and_evm_family_ecdsa`?e:null}function kr(){return ie(`kind`,[S({kind:re(`passkey`),rpId:ne(a),credentialIdB64u:ne(i),transports:R(Ar)}),S({kind:re(`email_otp`),email:ne(s),registrationAuthorityId:ne(h),providerSubject:ne(l),enrollment:jr()})])}function Ar(e){let t=ti(e);if(!t)return null;let n=[],r=new Set;for(let e of t){let t=L(e);if(t===null||r.has(t))return null;r.add(t),n.push(t)}return n}function jr(){let e=R(L);return S({enrollmentSealKeyVersion:e,serverSealedFactorCiphertextB64u:e,clientUnlockPublicKeyB64u:e,unlockKeyVersion:e})}function Mr(e){let t=ti(z(e,`keyFamilies`));if(!t)return null;if(t.length===1&&t[0]===`ecdsa_secp256k1`){let t=$r(e,[`keyFamilies`,`custodyCommit`,`ecdsa`]);if(!t)return null;let n=Ur(t.get(`custodyCommit`)),r=Qr(Br(),t.get(`ecdsa`));return n&&Wr(n,`evm_family_ecdsa_v1`)&&r?{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:n,ecdsa:r}:null}if(t.length===1&&t[0]===`ed25519`){let t=$r(e,[`keyFamilies`,`custodyCommit`,`ed25519`]);if(!t)return null;let n=Ur(t.get(`custodyCommit`)),r=Qr(Lr(),t.get(`ed25519`));return n&&Wr(n,`near_ed25519_v1`)&&r?{keyFamilies:[`ed25519`],custodyCommit:n,ed25519:r}:null}if(t.length===2&&t[0]===`ed25519`&&t[1]===`ecdsa_secp256k1`){let t=$r(e,[`keyFamilies`,`custodyCommit`,`ed25519`,`ecdsa`]);if(!t)return null;let n=Ur(t.get(`custodyCommit`)),r=Qr(Rr(),t.get(`ed25519`)),i=Qr(Br(),t.get(`ecdsa`));return n&&Wr(n,`evm_family_ecdsa_v1`)&&r&&i?{keyFamilies:[`ed25519`,`ecdsa_secp256k1`],custodyCommit:n,ed25519:r,ecdsa:i}:null}return null}function Nr(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ed25519`}function Pr(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ecdsa_secp256k1`}function Fr(e){return e.keyFamilies.length===2&&e.keyFamilies[0]===`ed25519`&&e.keyFamilies[1]===`ecdsa_secp256k1`}function Ir(){let e=R(L);return{activationReference:Hr(),localMaterial:S({b64u:e,nonceB64u:e,applicationBindingDigestB64u:e}),metadata:zr()}}function Lr(){return S(Ir())}function Rr(){return S({...Ir(),custodyCommit:R(e=>{let t=Ur(e);return t&&Wr(t,`near_ed25519_v1`)?t:null})})}function zr(){let e=R(L);return S({materialActivation:ne(u),registeredPublicKeyB64u:e,signingWorkerVerifyingShareB64u:e,stateEpoch:R(Xr),signingWorkerId:e,participantIds:(e,t)=>{let n=ti(e);if(!n||n.length!==2||n.some(e=>Zr(e)===null))throw Error(`${t} is invalid`);return[Number(n[0]),Number(n[1])]},nearEd25519SigningKeyId:e,signerSlot:R(Zr)})}function Br(){return S({activationJournalId:me,clientActivation:it,activationRequestDigestB64u:he})}function Vr(){let e=R(L),t=(e,t)=>{if(!Number.isSafeInteger(e)||Number(e)<0)throw Error(`${t} is invalid`);return Number(e)};return S({contextBinding32B64u:e,derivationClientSharePublicKey33B64u:e,clientVerifyingShare33B64u:e,relayerPublicKey33B64u:e,groupPublicKey33B64u:e,ethereumAddress:e,clientShareRetryCounter:t,relayerShareRetryCounter:t})}function Hr(){return S({kind:re(`router_ab_ed25519_yao_activation_reference_v1`),lifecycle_id:R(L),session_id:(e,t)=>{let n=ti(e);if(!n||n.length!==32)throw Error(`${t} is invalid`);let r=[];for(let e of n){if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`${t} is invalid`);r.push(e)}return r}})}function Ur(e){let t=ei(e,[`walletId`,`keySet`,`keyManifestDigestB64u`,`establishedCustody`,`recoveryBackupAcknowledged`,`recoveryReplacementEnvelope`,`registeredPublicKeyB64u`,`clientRootPublicKey33B64u`,`ecdsaPublicFacts`]);if(!t||!t.has(`walletId`)||!t.has(`keySet`)||!t.has(`keyManifestDigestB64u`))return null;let n=L(t.get(`walletId`)),r=L(t.get(`keySet`)),i=L(t.get(`keyManifestDigestB64u`));if(!n||!r||!i||r!==`near_ed25519_v1`&&r!==`evm_family_ecdsa_v1`)return null;let a=t.get(`recoveryBackupAcknowledged`);if(a!==void 0&&a!==!0)return null;let o=t.get(`establishedCustody`),s=o===void 0?void 0:Gr(o);if(o!==void 0&&!s)return null;let c=t.get(`recoveryReplacementEnvelope`),l=c===void 0?void 0:Qr(Jr(),c);if(c!==void 0&&!l)return null;let u=t.get(`registeredPublicKeyB64u`),d=u===void 0?void 0:L(u);if(u!==void 0&&!d)return null;let f=t.get(`clientRootPublicKey33B64u`),p=f===void 0?void 0:L(f);if(f!==void 0&&!p)return null;let m=t.get(`ecdsaPublicFacts`),h=m===void 0?void 0:Qr(Vr(),m);return m!==void 0&&!h?null:{walletId:n,keySet:r,keyManifestDigestB64u:i,...s?{establishedCustody:s}:{},...a===!0?{recoveryBackupAcknowledged:!0}:{},...l?{recoveryReplacementEnvelope:l}:{},...d?{registeredPublicKeyB64u:d}:{},...p?{clientRootPublicKey33B64u:p}:{},...h?{ecdsaPublicFacts:h}:{}}}function Wr(e,t){return e.keySet===t}function Gr(e){let t=[`envelopeId`,`envelopeBindingJson`,`envelopeNonceB64u`,`sealedCustodySecretB64u`,`envelopeAadHashB64u`,`envelopeCiphertextDigestB64u`,`recoveryManifestKekWraps`,`recoveryCodeLocators`,`recoveryEntryNonceB64u`,`recoveryEntryCiphertextB64u`,`recoveryEntryAadHashB64u`],n=ei(e,t);if(!n||t.some(e=>e!==`recoveryCodeLocators`&&!n.has(e)))return null;let r=[L(n.get(`envelopeId`)),L(n.get(`envelopeBindingJson`)),L(n.get(`envelopeNonceB64u`)),L(n.get(`sealedCustodySecretB64u`)),L(n.get(`envelopeAadHashB64u`)),L(n.get(`envelopeCiphertextDigestB64u`)),L(n.get(`recoveryEntryNonceB64u`)),L(n.get(`recoveryEntryCiphertextB64u`)),L(n.get(`recoveryEntryAadHashB64u`))];if(r.some(e=>e===null))return null;let i=ti(n.get(`recoveryManifestKekWraps`));if(!i)return null;let a=i.map(e=>Qr(Kr(),e));if(a.some(e=>e===null))return null;let o=a.filter(Yr),s;if(n.has(`recoveryCodeLocators`)){let e=ti(n.get(`recoveryCodeLocators`));if(!e)return null;let t=e.map(e=>Qr(qr(),e));if(t.some(e=>e===null))return null;s=t.filter(Yr)}return{envelopeId:r[0],envelopeBindingJson:r[1],envelopeNonceB64u:r[2],sealedCustodySecretB64u:r[3],envelopeAadHashB64u:r[4],envelopeCiphertextDigestB64u:r[5],recoveryManifestKekWraps:o,...s?{recoveryCodeLocators:s}:{},recoveryEntryNonceB64u:r[6],recoveryEntryCiphertextB64u:r[7],recoveryEntryAadHashB64u:r[8]}}function Kr(){let e=R(L);return S({recoveryKeyId:e,nonceB64u:e,ciphertextB64u:e,aadHashB64u:e})}function qr(){let e=R(L);return S({locatorB64u:e,recoveryKeyId:e})}function Jr(){let e=R(L);return S({envelopeId:e,envelopeBindingJson:e,envelopeNonceB64u:e,sealedCustodySecretB64u:e,envelopeAadHashB64u:e,envelopeCiphertextDigestB64u:e})}function Yr(e){return e!==null}function L(e){return typeof e==`string`&&e.length>0&&e.trim()===e&&!m(e)?e:null}function Xr(e){let t=L(e);return t&&/^[1-9][0-9]*$/u.test(t)?t:null}function Zr(e){return Number.isSafeInteger(e)&&Number(e)>0?Number(e):null}function Qr(e,t){try{return e(t,`journal`)}catch{return null}}function R(e){return(t,n)=>{let r=e(t);if(r===null)throw Error(`${n} is invalid`);return r}}function $r(e,t){let n=ei(e,t);return n&&n.size===t.length?n:null}function ei(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return null;let n=Object.keys(e);if(n.some(e=>!t.includes(e)))return null;let r=new Map;for(let t of n)r.set(t,Reflect.get(e,t));return r}function z(e,t){if(!(typeof e!=`object`||!e||Array.isArray(e)))return Reflect.get(e,t)}function ti(e){return Array.isArray(e)?e:null}function ni(e,t){return e.kind===t.kind&&e.signer.kind===t.signer.kind&&e.signer.keyFamily===t.signer.keyFamily&&e.signer.walletId===t.signer.walletId&&e.signer.walletKeyId===t.signer.walletKeyId&&e.signer.registeredPublicKeyB64u===t.signer.registeredPublicKeyB64u&&d(e.materialActivation,t.materialActivation)}function ri(e,t){return e.kind===t.kind&&e.signer.kind===t.signer.kind&&e.signer.keyFamily===t.signer.keyFamily&&e.signer.walletId===t.signer.walletId&&e.signer.walletKeyId===t.signer.walletKeyId&&e.signer.thresholdPublicKey33B64u===t.signer.thresholdPublicKey33B64u&&e.signer.evmAddress===t.signer.evmAddress&&d(e.materialActivation,t.materialActivation)}async function ii(e){let t=String(e.keySetId||``).trim();if(!/^(near_ed25519|evm_family_ecdsa):\S+$/.test(t))throw Error(`wallet recovery key-set id is invalid`);return me(`wallet-recovery-key-v1:${C(await te(_({domain:`seams/wallet-recovery/key-lifecycle/v1`,reservationId:e.reservationId,keySetId:t})))}`)}function ai(e){if(typeof e!=`string`||e.length===0||e.length>512||e.trim()!==e||m(e))throw Error(`recovery code reservation id must be a compact opaque identifier`);return e}function oi(e){return e.kind===`passkey`?si(e):ci(e)}function si(e){let t={version:`wallet_recovery_committed_projection_v1`,storeVersion:y(e.storeVersion,`storeVersion`,`is invalid`),walletId:e.walletId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,authority:e.authority,kind:`passkey`,authMethod:e.authMethod,target:{kind:`passkey`,rpId:e.authMethod.rpId,credentialIdB64u:e.authMethod.credentialIdB64u}};return mi(t),t}function ci(e){let t={version:`wallet_recovery_committed_projection_v1`,storeVersion:y(e.storeVersion,`storeVersion`,`is invalid`),walletId:e.walletId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,authority:e.authority,kind:`google_email_otp`,authMethod:e.authMethod,target:{kind:`google_email_otp`,provider:`google`,providerSubject:e.providerSubject,emailHashHex:Si(e.emailHashHex),registrationAuthorityId:y(e.registrationAuthorityId,`registrationAuthorityId`,`is invalid`),enrollment:fi(e.enrollment)}};return mi(t),t}async function li(e,t){let r=hi(e);if(r.version!==`wallet_recovery_committed_projection_v1`)throw Error(`wallet recovery committed projection version is invalid`);if(r.kind!==t.kind)throw Error(`wallet recovery committed projection target changed`);let i=xi(p(r.walletId),`walletId`),a=xi(f(r.recoveryOperationId),`recoveryOperationId`),s=xi(fe(r.targetDeviceId),`targetDeviceId`),c=xi(o(r.targetAuthorityId),`targetAuthorityId`),l=xi(n(r.targetWalletAuthMethodId),`targetWalletAuthMethodId`),u=k(r.authority);if(!u.ok)throw Error(`wallet recovery authority projection is invalid`);let d=u.value;if(d.state!==`active`||!ze(d)||!await Ie(d))throw Error(`wallet recovery authority projection digest or lifecycle is invalid`);let m=A(r.authMethod);if(!m||m.status!==`active`)throw Error(`wallet recovery auth method projection is invalid`);let h={version:`wallet_recovery_committed_projection_v1`,storeVersion:y(r.storeVersion,`storeVersion`,`is invalid`),walletId:i,recoveryOperationId:a,targetDeviceId:s,targetAuthorityId:c,targetWalletAuthMethodId:l,authority:d};if(t.kind===`passkey`){if(m.kind!==`passkey`)throw Error(`wallet recovery target method family changed`);let e=ui(r.target),n={...h,kind:`passkey`,authMethod:m,target:e};return pi(n,t),mi(n),n}if(m.kind!==`email_otp`)throw Error(`wallet recovery target method family changed`);let g=di(r.target),_={...h,kind:`google_email_otp`,authMethod:m,target:g};return pi(_,t),mi(_),_}function ui(e){let t=gi(e);if(t.kind!==`passkey`)throw Error(`wallet recovery passkey target is invalid`);return{kind:`passkey`,rpId:xi(a(t.rpId),`target.rpId`),credentialIdB64u:xi(i(t.credentialIdB64u),`target.credentialIdB64u`)}}function di(e){let t=_i(e);if(t.kind!==`google_email_otp`||t.provider!==`google`)throw Error(`wallet recovery Google Email OTP target is invalid`);return{kind:`google_email_otp`,provider:`google`,providerSubject:xi(l(t.providerSubject),`target.providerSubject`),emailHashHex:Si(t.emailHashHex),registrationAuthorityId:y(t.registrationAuthorityId,`target.registrationAuthorityId`,`is invalid`),enrollment:fi(t.enrollment)}}function fi(e){let t=vi(e);if(t.kind!==`email_otp_enrollment_reference_v1`)throw Error(`wallet recovery Email OTP enrollment is invalid`);return{kind:`email_otp_enrollment_reference_v1`,enrollmentId:y(t.enrollmentId,`enrollment.enrollmentId`,`is invalid`),enrollmentSealKeyVersion:y(t.enrollmentSealKeyVersion,`enrollment.enrollmentSealKeyVersion`,`is invalid`)}}function pi(e,t){if(e.kind!==t.kind||e.walletId!==t.walletId||e.recoveryOperationId!==t.recoveryOperationId||e.targetDeviceId!==t.targetDeviceId||e.targetAuthorityId!==t.targetAuthorityId||e.targetWalletAuthMethodId!==t.targetWalletAuthMethodId)throw Error(`wallet recovery committed projection identity changed`);if(e.kind===`passkey`&&t.kind===`passkey`){if(e.target.rpId!==t.rpId||e.target.credentialIdB64u!==t.credentialIdB64u)throw Error(`wallet recovery passkey target changed`);return}if(e.kind!==`google_email_otp`||t.kind!==`google_email_otp`)throw Error(`wallet recovery target identity changed`);if(e.target.providerSubject!==t.providerSubject||e.target.emailHashHex!==t.emailHashHex||e.target.registrationAuthorityId!==t.registrationAuthorityId||e.target.enrollment.enrollmentId!==t.enrollment.enrollmentId||e.target.enrollment.enrollmentSealKeyVersion!==t.enrollment.enrollmentSealKeyVersion)throw Error(`wallet recovery Google Email OTP target changed`)}function mi(e){if(e.authority.walletId!==e.walletId||e.authority.authorityId!==e.targetAuthorityId||e.authority.principal.deviceId!==e.targetDeviceId||e.authority.provenance.kind!==`wallet_recovery`||e.authority.provenance.recoveryOperationId!==e.recoveryOperationId||e.authority.provenance.continuityAuthorityId===e.targetAuthorityId||e.authMethod.walletId!==e.walletId||e.authMethod.walletAuthorityId!==e.targetAuthorityId||e.authMethod.walletAuthMethodId!==e.targetWalletAuthMethodId||e.authMethod.status!==`active`)throw Error(`wallet recovery committed projection relations are invalid`);if(e.kind===`passkey`){if(e.authMethod.kind!==`passkey`||e.target.rpId!==e.authMethod.rpId||e.target.credentialIdB64u!==e.authMethod.credentialIdB64u)throw Error(`wallet recovery passkey projection relations are invalid`);return}if(e.authMethod.kind!==`email_otp`||e.target.emailHashHex!==e.authMethod.emailHashHex||e.target.registrationAuthorityId!==e.authMethod.registrationAuthorityId)throw Error(`wallet recovery Google Email OTP projection relations are invalid`)}function hi(e){let t=yi(e);if(t===null)throw Error(`wallet recovery committed projection must be an object`);return bi(t,[`version`,`kind`,`storeVersion`,`walletId`,`recoveryOperationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`authority`,`authMethod`,`target`],`wallet recovery committed projection`),{version:Reflect.get(t,`version`),kind:Reflect.get(t,`kind`),storeVersion:Reflect.get(t,`storeVersion`),walletId:Reflect.get(t,`walletId`),recoveryOperationId:Reflect.get(t,`recoveryOperationId`),targetDeviceId:Reflect.get(t,`targetDeviceId`),targetAuthorityId:Reflect.get(t,`targetAuthorityId`),targetWalletAuthMethodId:Reflect.get(t,`targetWalletAuthMethodId`),authority:Reflect.get(t,`authority`),authMethod:Reflect.get(t,`authMethod`),target:Reflect.get(t,`target`)}}function gi(e){let t=yi(e);if(t===null)throw Error(`wallet recovery passkey target must be an object`);return bi(t,[`kind`,`rpId`,`credentialIdB64u`],`wallet recovery passkey target`),{kind:Reflect.get(t,`kind`),rpId:Reflect.get(t,`rpId`),credentialIdB64u:Reflect.get(t,`credentialIdB64u`)}}function _i(e){let t=yi(e);if(t===null)throw Error(`wallet recovery Google Email OTP target must be an object`);return bi(t,[`kind`,`provider`,`providerSubject`,`emailHashHex`,`registrationAuthorityId`,`enrollment`],`wallet recovery Google Email OTP target`),{kind:Reflect.get(t,`kind`),provider:Reflect.get(t,`provider`),providerSubject:Reflect.get(t,`providerSubject`),emailHashHex:Reflect.get(t,`emailHashHex`),registrationAuthorityId:Reflect.get(t,`registrationAuthorityId`),enrollment:Reflect.get(t,`enrollment`)}}function vi(e){let t=yi(e);if(t===null)throw Error(`wallet recovery Email OTP enrollment must be an object`);return bi(t,[`kind`,`enrollmentId`,`enrollmentSealKeyVersion`],`wallet recovery Email OTP enrollment`),{kind:Reflect.get(t,`kind`),enrollmentId:Reflect.get(t,`enrollmentId`),enrollmentSealKeyVersion:Reflect.get(t,`enrollmentSealKeyVersion`)}}function yi(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function bi(e,t,n){let r=new Set(t),i=Object.keys(e);if(i.length!==t.length||i.some(e=>!r.has(e)))throw Error(`${n} contains unexpected fields`)}function xi(e,t){if(!e.ok)throw Error(`${t} is invalid`);return e.value}function Si(e){let t=y(e,`emailHashHex`,`is invalid`);if(!/^[0-9a-f]{64}$/.test(t))throw Error(`emailHashHex is invalid`);return t}const Ci=`pending_wallet_recovery_commit_v1`,wi=`${Ci}:`,Ti=[`version`,`kind`,`storeVersion`,`walletId`,`recoveryOperationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`authority`,`authMethod`,`target`],Ei=[`version`,`walletAuthMethodId`,`walletId`,`walletAuthorityId`,`kind`,`status`,`createdAtMs`,`updatedAtMs`,`rpId`,`credentialIdB64u`,`credentialPublicKeyB64u`,`counter`,`activatedAtMs`],Di=[`version`,`walletAuthMethodId`,`walletId`,`walletAuthorityId`,`kind`,`status`,`createdAtMs`,`updatedAtMs`,`emailHashHex`,`registrationAuthorityId`,`activatedAtMs`],Oi=[`kind`,`rpId`,`credentialIdB64u`],ki=[`kind`,`providerSubject`,`emailHashHex`,`registrationAuthorityId`,`enrollment`],Ai=[`kind`,`provider`,`providerSubject`,`emailHashHex`,`registrationAuthorityId`,`enrollment`],ji=[`kind`,`enrollmentId`,`enrollmentSealKeyVersion`];function Mi(e,t){return e.recoveryOperationId===t.recoveryOperationId&&e.walletId===t.walletId&&e.reservationId===t.reservationId&&e.targetDeviceId===t.targetDeviceId&&e.targetAuthorityId===t.targetAuthorityId&&e.targetWalletAuthMethodId===t.targetWalletAuthMethodId&&e.target.kind===t.target.kind&&(e.target.kind===`passkey`?t.target.kind===`passkey`&&e.target.rpId===t.target.rpId&&e.target.credentialIdB64u===t.target.credentialIdB64u:t.target.kind===`google_email_otp`&&e.target.providerSubject===t.target.providerSubject&&e.target.emailHashHex===t.target.emailHashHex&&e.target.registrationAuthorityId===t.target.registrationAuthorityId&&e.target.enrollment.enrollmentId===t.target.enrollment.enrollmentId&&e.target.enrollment.enrollmentSealKeyVersion===t.target.enrollment.enrollmentSealKeyVersion)&&e.createdAtMs===t.createdAtMs}function Ni(e){return`${wi}${String(e)}`}function B(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return null;let n=Object.keys(e);if(n.length!==t.length||n.some(e=>!t.includes(e)))return null;let r=new Map;for(let t of n)r.set(t,Reflect.get(e,t));return r}function Pi(e,t){if(!(typeof e!=`object`||!e||Array.isArray(e)))return Reflect.get(e,t)}function Fi(e){return typeof e!=`string`||e.length===0||e.trim()!==e?null:e}function Ii(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function Li(e){try{return ai(e)}catch{return null}}function Ri(e){return typeof CryptoKey<`u`&&e instanceof CryptoKey&&e.type===`secret`&&e.extractable===!1&&e.algorithm.name===`AES-GCM`&&e.usages.includes(`encrypt`)&&e.usages.includes(`decrypt`)}function zi(e){let t=B(e,[`kind`,`key`,`iv`,`ciphertext`]);if(!t)return null;let n=t.get(`key`),r=t.get(`iv`),i=t.get(`ciphertext`);return t.get(`kind`)!==`wallet_recovery_encrypted_material_v1`||!Ri(n)||!(r instanceof Uint8Array)||r.byteLength!==12||!(i instanceof Uint8Array)||i.byteLength===0?null:{kind:`wallet_recovery_encrypted_material_v1`,key:n,iv:r,ciphertext:i}}function Bi(e){let t=B(e,[`kind`,`enrollmentId`,`enrollmentSealKeyVersion`]);if(!t||t.get(`kind`)!==`email_otp_enrollment_reference_v1`)return null;let n=Fi(t.get(`enrollmentId`)),r=Fi(t.get(`enrollmentSealKeyVersion`));return!n||!r?null:{kind:`email_otp_enrollment_reference_v1`,enrollmentId:n,enrollmentSealKeyVersion:r}}function Vi(e){let t=Pi(e,`kind`);if(t===`passkey`){let t=B(e,Oi);if(!t)return null;let n=a(t.get(`rpId`)),r=i(t.get(`credentialIdB64u`));return n.ok&&r.ok?{kind:`passkey`,rpId:n.value,credentialIdB64u:r.value}:null}if(t!==`google_email_otp`)return null;let n=B(e,ki);if(!n)return null;let r=n.get(`emailHashHex`);if(typeof r!=`string`||!/^[0-9a-f]{64}$/.test(r))return null;let o=l(n.get(`providerSubject`)),s=Fi(n.get(`registrationAuthorityId`)),c=Bi(n.get(`enrollment`));return o.ok&&s&&c?{kind:`google_email_otp`,providerSubject:o.value,emailHashHex:r,registrationAuthorityId:s,enrollment:c}:null}function Hi(e){return e.target.kind===`passkey`?{kind:`passkey`,walletId:e.walletId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,rpId:e.target.rpId,credentialIdB64u:e.target.credentialIdB64u}:{kind:`google_email_otp`,walletId:e.walletId,recoveryOperationId:e.recoveryOperationId,targetDeviceId:e.targetDeviceId,targetAuthorityId:e.targetAuthorityId,targetWalletAuthMethodId:e.targetWalletAuthMethodId,providerSubject:e.target.providerSubject,emailHashHex:e.target.emailHashHex,registrationAuthorityId:e.target.registrationAuthorityId,enrollment:e.target.enrollment}}async function Ui(e){let t=[`kind`,`version`,`stage`,`recoveryOperationId`,`walletId`,`reservationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`target`,`localMaterial`,`createdAtMs`,`updatedAtMs`],r=Pi(e,`stage`),i=r===`server_promoted`?[...t,`projection`]:r===`awaiting_server_promotion`?t:null;if(!i)return null;let a=B(e,i);if(!a||a.get(`kind`)!==Ci||a.get(`version`)!==1)return null;let s=f(a.get(`recoveryOperationId`)),c=p(a.get(`walletId`)),l=Li(a.get(`reservationId`)),u=fe(a.get(`targetDeviceId`)),d=o(a.get(`targetAuthorityId`)),m=n(a.get(`targetWalletAuthMethodId`)),h=Vi(a.get(`target`)),g=zi(a.get(`localMaterial`)),_=Ii(a.get(`createdAtMs`)),v=Ii(a.get(`updatedAtMs`));if(!s.ok||!c.ok||!l||!u.ok||!d.ok||!m.ok||!h||!g||_===null||v===null||v<_)return null;if(r===`awaiting_server_promotion`)return{kind:Ci,version:1,stage:r,recoveryOperationId:s.value,walletId:c.value,reservationId:l,targetDeviceId:u.value,targetAuthorityId:d.value,targetWalletAuthMethodId:m.value,target:h,localMaterial:g,createdAtMs:_,updatedAtMs:v};let y={kind:Ci,version:1,recoveryOperationId:s.value,walletId:c.value,reservationId:l,targetDeviceId:u.value,targetAuthorityId:d.value,targetWalletAuthMethodId:m.value,target:h,localMaterial:g,createdAtMs:_,updatedAtMs:v},b;try{b=await li(a.get(`projection`),Hi(y))}catch{return null}return b.kind===h.kind&&(b.kind===`passkey`&&h.kind===`passkey`||b.kind===`google_email_otp`&&h.kind===`google_email_otp`)?{kind:Ci,version:1,stage:`server_promoted`,recoveryOperationId:y.recoveryOperationId,walletId:y.walletId,reservationId:y.reservationId,targetDeviceId:y.targetDeviceId,targetAuthorityId:y.targetAuthorityId,targetWalletAuthMethodId:y.targetWalletAuthMethodId,target:h,localMaterial:y.localMaterial,createdAtMs:y.createdAtMs,updatedAtMs:y.updatedAtMs,projection:b}:null}async function Wi(e){let t=await Ui(e);if(!t)throw Error(`pending wallet recovery commit is invalid`);return t}async function Gi(e){let t=await Wi(e),n={recovery_operation_id:t.recoveryOperationId,stage:t.stage,wallet_id:t.walletId,target_authority_id:t.targetAuthorityId,target_wallet_auth_method_id:t.targetWalletAuthMethodId,updated_at_ms:t.updatedAtMs,record:t};return{key:Ni(t.recoveryOperationId),value:n}}async function Ki(e){let t=B(e,[`key`,`value`]);if(!t)return null;let n=t.get(`key`);if(typeof n!=`string`||!n.startsWith(wi))return null;let r=B(t.get(`value`),[`recovery_operation_id`,`stage`,`wallet_id`,`target_authority_id`,`target_wallet_auth_method_id`,`updated_at_ms`,`record`]);if(!r)return null;let i=await Ui(r.get(`record`));return!i||n!==Ni(i.recoveryOperationId)||r.get(`recovery_operation_id`)!==i.recoveryOperationId||r.get(`stage`)!==i.stage||r.get(`wallet_id`)!==i.walletId||r.get(`target_authority_id`)!==i.targetAuthorityId||r.get(`target_wallet_auth_method_id`)!==i.targetWalletAuthMethodId||r.get(`updated_at_ms`)!==i.updatedAtMs?null:{recovery_operation_id:i.recoveryOperationId,stage:i.stage,wallet_id:i.walletId,target_authority_id:i.targetAuthorityId,target_wallet_auth_method_id:i.targetWalletAuthMethodId,updated_at_ms:i.updatedAtMs,record:i}}function qi(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function Ji(e,t){return e.kind===t.kind&&qi(e.iv,t.iv)&&qi(e.ciphertext,t.ciphertext)}function Yi(e,t){let n=B(e,ji);return n!==null&&n.get(`kind`)===t.kind&&n.get(`enrollmentId`)===t.enrollmentId&&n.get(`enrollmentSealKeyVersion`)===t.enrollmentSealKeyVersion}function Xi(e,t,n){let r=B(e,Oi);return r!==null&&r.get(`kind`)===`passkey`&&r.get(`rpId`)===t&&r.get(`credentialIdB64u`)===n}function Zi(e,t){if(t.kind===`passkey`)return Xi(e,t.rpId,t.credentialIdB64u);let n=B(e,ki);return n!==null&&n.get(`kind`)===t.kind&&n.get(`providerSubject`)===t.providerSubject&&n.get(`emailHashHex`)===t.emailHashHex&&n.get(`registrationAuthorityId`)===t.registrationAuthorityId&&Yi(n.get(`enrollment`),t.enrollment)}function Qi(e,t){if(t.kind===`passkey`)return Xi(e,t.rpId,t.credentialIdB64u);let n=B(e,Ai);return n!==null&&n.get(`kind`)===t.kind&&n.get(`provider`)===`google`&&n.get(`providerSubject`)===t.providerSubject&&n.get(`emailHashHex`)===t.emailHashHex&&n.get(`registrationAuthorityId`)===t.registrationAuthorityId&&Yi(n.get(`enrollment`),t.enrollment)}function $i(e,t){let n=B(e,t.kind===`passkey`?Ei:Di);if(!n||n.get(`version`)!==t.version||n.get(`walletAuthMethodId`)!==t.walletAuthMethodId||n.get(`walletId`)!==t.walletId||n.get(`walletAuthorityId`)!==t.walletAuthorityId||n.get(`status`)!==t.status||n.get(`createdAtMs`)!==t.createdAtMs||n.get(`updatedAtMs`)!==t.updatedAtMs||n.get(`activatedAtMs`)!==t.activatedAtMs)return!1;if(t.kind===`passkey`){if(n.get(`kind`)!==t.kind||n.get(`rpId`)!==t.rpId||n.get(`credentialIdB64u`)!==t.credentialIdB64u||n.get(`credentialPublicKeyB64u`)!==t.credentialPublicKeyB64u||n.get(`counter`)!==t.counter)return!1}else if(n.get(`kind`)!==t.kind||n.get(`emailHashHex`)!==t.emailHashHex||n.get(`registrationAuthorityId`)!==t.registrationAuthorityId)return!1;let r=A(e);return r!==null&&ot(r,t)}function ea(e,t){let n=B(e,Ti);if(n===null||n.get(`version`)!==t.version||n.get(`kind`)!==t.kind||n.get(`storeVersion`)!==t.storeVersion||n.get(`walletId`)!==t.walletId||n.get(`recoveryOperationId`)!==t.recoveryOperationId||n.get(`targetDeviceId`)!==t.targetDeviceId||n.get(`targetAuthorityId`)!==t.targetAuthorityId||n.get(`targetWalletAuthMethodId`)!==t.targetWalletAuthMethodId)return!1;let r=k(n.get(`authority`));return!r.ok||r.value.state!==`active`||!ze(r.value)?!1:ta(r.value,t.authority)&&$i(n.get(`authMethod`),t.authMethod)&&Qi(n.get(`target`),t.target)}function ta(e,t){return e.kind===t.kind&&e.authorityId===t.authorityId&&e.walletId===t.walletId&&e.principal.kind===t.principal.kind&&e.principal.deviceId===t.principal.deviceId&&e.provenance.kind===t.provenance.kind&&e.provenance.recoveryOperationId===t.provenance.recoveryOperationId&&e.provenance.continuityAuthorityId===t.provenance.continuityAuthorityId&&na(e.permissions,t.permissions)&&ra(e.signerActivations,t.signerActivations)&&e.signerActivationSetDigestB64u===t.signerActivationSetDigestB64u&&e.authorityDigestB64u===t.authorityDigestB64u&&e.revocationEpoch===t.revocationEpoch&&e.createdAtMs===t.createdAtMs&&e.updatedAtMs===t.updatedAtMs&&e.state===t.state&&e.activatedAtMs===t.activatedAtMs}function na(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function ra(e,t){if(e.kind!==t.kind||e.keyFamilies.length!==t.keyFamilies.length||e.keyFamilies.some((e,n)=>e!==t.keyFamilies[n]))return!1;if(e.keyFamilies.length===1){let n=e.keyFamilies[0];switch(n){case`ed25519`:return t.keyFamilies[0]===`ed25519`&&e.ed25519!==void 0&&t.ed25519!==void 0&&ni(e.ed25519,t.ed25519);case`ecdsa_secp256k1`:return t.keyFamilies[0]===`ecdsa_secp256k1`&&e.ecdsa!==void 0&&t.ecdsa!==void 0&&ri(e.ecdsa,t.ecdsa);default:return ia(n)}}return e.keyFamilies.length!==2||e.keyFamilies[0]!==`ed25519`||e.keyFamilies[1]!==`ecdsa_secp256k1`||t.keyFamilies.length!==2||t.keyFamilies[0]!==`ed25519`||t.keyFamilies[1]!==`ecdsa_secp256k1`||e.ed25519===void 0||t.ed25519===void 0||e.ecdsa===void 0||t.ecdsa===void 0?!1:ni(e.ed25519,t.ed25519)&&ri(e.ecdsa,t.ecdsa)}function ia(e){throw Error(`unsupported pending recovery signer family: ${String(e)}`)}function aa(e,t){if(e.get(`kind`)!==t.kind||e.get(`version`)!==t.version||e.get(`stage`)!==t.stage||e.get(`recoveryOperationId`)!==t.recoveryOperationId||e.get(`walletId`)!==t.walletId||e.get(`reservationId`)!==t.reservationId||e.get(`targetDeviceId`)!==t.targetDeviceId||e.get(`targetAuthorityId`)!==t.targetAuthorityId||e.get(`targetWalletAuthMethodId`)!==t.targetWalletAuthMethodId||e.get(`createdAtMs`)!==t.createdAtMs||e.get(`updatedAtMs`)!==t.updatedAtMs)return!1;let n=zi(e.get(`localMaterial`));if(n===null||!Ji(n,t.localMaterial)||!Zi(e.get(`target`),t.target))return!1;switch(t.stage){case`awaiting_server_promotion`:return!0;case`server_promoted`:return ea(e.get(`projection`),t.projection);default:return oa(t)}}function oa(e){throw Error(`unsupported pending wallet recovery branch`)}function sa(e,t){let n=B(e,[`key`,`value`]);if(!n||n.get(`key`)!==t.key)return!1;let r=B(n.get(`value`),[`recovery_operation_id`,`stage`,`wallet_id`,`target_authority_id`,`target_wallet_auth_method_id`,`updated_at_ms`,`record`]);if(!r)return!1;let i=t.value;if(r.get(`recovery_operation_id`)!==i.recovery_operation_id||r.get(`stage`)!==i.stage||r.get(`wallet_id`)!==i.wallet_id||r.get(`target_authority_id`)!==i.target_authority_id||r.get(`target_wallet_auth_method_id`)!==i.target_wallet_auth_method_id||r.get(`updated_at_ms`)!==i.updated_at_ms)return!1;let a=i.record,o=[`kind`,`version`,`stage`,`recoveryOperationId`,`walletId`,`reservationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`target`,`localMaterial`,`createdAtMs`,`updatedAtMs`],s=a.stage===`server_promoted`?[...o,`projection`]:o,c=B(r.get(`record`),s);return c!==null&&aa(c,a)}async function V(e,t,n){return he(C(await te(_({category:e,...qt(t),detail:n}))))}async function ca(e,t){return{kind:`exact_record_conflict`,conflictDigest:await V(`journal_constraint_conflict`,e,H(t))}}function la(){return me(le(`ecdsa-persistence-retry`,16,`ECDSA persistence retry correlations`))}function H(e){return e instanceof Error?e.message:String(e)}function ua(e){return e instanceof DOMException&&e.name===`ConstraintError`}async function da(e,t){return await e.store(Bt).index(T.walletId).getAll(t)}async function fa(e){return await e.store(M).getAll()}async function pa(e,t){return await e.store(j).index(T.capabilityWalletAuthorityState).getAll([...bn(t),`active`])}function ma(e,t){return d(e.manifest.activation.materialActivation,t)&&d(e.manifest.durableMaterial.materialActivation,t)&&d(e.material.binding.materialActivation,t)}function ha(e){switch(e.kind){case`missing`:case`retired`:return{kind:`missing`};case`exact_binding_mismatch`:return{kind:`binding_mismatch`};case`exact_record_conflict`:case`corrupt`:return{kind:`corrupt`};case`persistence_unavailable`:return{kind:`persistence_unavailable`}}return Vt(e)}async function ga(e,t){let n=await e.store(Bt).get(bn(t));if(n===void 0)return await _a(e,t);let r;try{r=hn(n)}catch(e){return{kind:`corrupt`,detail:H(e)}}if(!dn(r.selector,t))return{kind:`exact_binding_mismatch`,detail:`current ECDSA pointer belongs to a different exact authority`};let i=await e.store(j).get(r.manifestId);if(i===void 0)return{kind:`exact_record_conflict`,detail:`current ECDSA pointer references a missing manifest`};let a;try{a=Wt(i)}catch(e){return{kind:`corrupt`,detail:H(e)}}if(!dn(a.selector,t))return{kind:`exact_binding_mismatch`,detail:`current ECDSA manifest belongs to a different exact authority`};if(a.manifest.identity.manifestId!==r.manifestId||a.manifest.identity.manifestRevision!==r.manifestRevision)return{kind:`exact_record_conflict`,detail:`current ECDSA pointer does not match its manifest identity`};if(a.state===`replaced`)return{kind:`retired`,manifest:a.manifest};let o=await pa(e,t);if(o.length!==1)return{kind:`exact_record_conflict`,detail:`exact ECDSA authority has multiple current manifests`};let s;try{s=Wt(o[0])}catch(e){return{kind:`corrupt`,detail:H(e)}}if(s.state!==`active`||s.manifest.identity.manifestId!==r.manifestId)return{kind:`exact_record_conflict`,detail:`exact ECDSA current index disagrees with its pointer`};let c=await e.store(P).get(a.manifest.durableMaterial.durableMaterialRef);if(c===void 0)return{kind:`missing`,subject:`material`,detail:`active ECDSA manifest is missing its ready material`};let l;try{l=Mt(c,a.activeProof)}catch(e){return{kind:`corrupt`,detail:H(e)}}if(!Cn(l,a.manifest))return{kind:`exact_binding_mismatch`,detail:`active ECDSA material does not match its manifest`};let u=await e.store(N).get(l.sealingKeyId);if(u===void 0)return{kind:`missing`,subject:`material`,detail:`active ECDSA material is missing its sealing key`};try{if(jt(u).keyId!==l.sealingKeyId)return{kind:`exact_binding_mismatch`,detail:`active ECDSA material sealing key id does not match`}}catch(e){return{kind:`corrupt`,detail:H(e)}}return await Tt(l.ciphertextB64u)===l.binding.ciphertextDigest?{kind:`active`,manifest:a.manifest,material:l}:{kind:`corrupt`,detail:`active ECDSA material ciphertext digest is invalid`}}async function _a(e,t){let n=await e.store(j).index(T.capabilityWallet).getAll([String(t.capability),String(t.authority.walletId)]);if(n.length===0)return{kind:`missing`,subject:`capability`,detail:`no ECDSA capability manifest exists`};let r=!1,i=!1,a=!1;for(let e of n){let n;try{n=Wt(e)}catch(e){return{kind:`corrupt`,detail:H(e)}}if(dn(n.selector,t)){i=!0;continue}r=!0,n.selector.authority.walletAuthMethodId===t.authority.walletAuthMethodId&&(a=!0)}return i?{kind:`exact_record_conflict`,detail:`exact ECDSA authority has manifest history without a current pointer`}:a?{kind:`exact_binding_mismatch`,detail:`ECDSA capability exists for this method under a different authority digest`}:r?{kind:`missing`,subject:`capability`,detail:`no ECDSA capability manifest exists for this exact authority`}:{kind:`missing`,subject:`capability`,detail:`no exact ECDSA capability manifest exists`}}function va(e,t,n){let r=t.activationBinding;return yn(e.signer.authority,r.signer.authority)&&on(e.signer.scope,r.signer.scope)&&e.signer.walletId===r.signer.walletId&&e.signer.capability===r.signer.capability&&e.signer.materialOwner===r.signer.materialOwner&&e.signer.signingRootId===r.signer.signingRootId&&e.signer.signingRootVersion===r.signer.signingRootVersion&&Ft(e.signer.registeredPublicFacts,t.registeredPublicFacts)&&At(e.activation.serverActivation,n)&&d(e.activation.materialActivation,rt(n.serverActivationReceipt.protocolReceipt.ecdsa_activation.material_activation))&&e.durableMaterial.bindingDigest===r.bindingDigest&&e.durableMaterial.durableMaterialRef===r.durableMaterialRef&&Lt(e.durableMaterial.roleLocalBinding,r.roleLocalBinding)&&Dt(e.durableMaterial.roleLocalPublicFacts,t.roleLocalPublicFacts)&&$e(e.durableMaterial.routerAbEcdsaDerivationNormalSigning,t.routerAbEcdsaDerivationNormalSigning)&&Gt(e.durableMaterial.runtimePolicyScope,oe(t.runtimePolicyScope))}var U=class extends Error{kind;constructor(e,t){super(t),this.name=`FinalizationControlError`,this.kind=e}};function ya(e){return{target_manifest:e.targetManifest,signer:{capability:e.signer.capability,signer_id:e.signer.signerId,wallet_id:e.signer.walletId,authority:e.signer.authority,scope:e.signer.scope,material_owner:e.signer.materialOwner,signing_root_id:e.signer.signingRootId,signing_root_version:e.signer.signingRootVersion},role_local_binding:e.roleLocalBinding,binding_digest:e.bindingDigest,durable_material_ref:e.durableMaterialRef}}function ba(e){return`activationBinding`in e?{version:1,stage:`activation_prepared`,journal_id:e.journalId,expected_manifest:e.expectedManifest,activation_command:{kind:`ecdsa_server_activation_command`,correlationId:e.journalId,expectedGeneration:e.expectedGeneration,requestDigest:e.requestDigest,canonicalRequest:e.canonicalRequest},activation_binding:ya(e.activationBinding),created_at:e.createdAt}:{version:1,stage:`activation_prepared`,journal_id:e.journalId,expected_manifest:e.expectedManifest,activation_command:e.activationCommand,activation_binding:ya(e.candidate.activationBinding),created_at:e.createdAt}}function xa(e){return e.kind===`server_activation_committed`?Sa(e.candidate.activationBinding,e.serverActivation):Sa({targetManifest:e.identity,signer:e.signer,roleLocalBinding:e.durableMaterial.roleLocalBinding,bindingDigest:e.durableMaterial.bindingDigest,durableMaterialRef:e.durableMaterial.durableMaterialRef},e.activation.serverActivation)}function Sa(e,t){return{version:1,stage:`activation_ready`,activation_binding:ya(e),server_activation:t}}function Ca(e){return{activation_binding:e.activationBinding,server_activation:e.serverActivation,registered_public_facts:e.activeManifest.signer.registeredPublicFacts,role_local_public_facts:e.durableMaterial.roleLocalPublicFacts,router_ab_ecdsa_derivation_normal_signing:e.durableMaterial.routerAbEcdsaDerivationNormalSigning,runtime_policy_scope:e.durableMaterial.runtimePolicyScope,ciphertext_digest:e.durableMaterial.ciphertextDigest,committed_at:e.activeManifest.committedAt}}function wa(e,t){return{record_version:Sn,manifest_id:e.activeManifest.identity.manifestId,manifest_revision:e.activeManifest.identity.manifestRevision,...qt(xt(e.activeManifest)),manifest_state:t}}function Ta(e){return{...wa(e,`active`),active_proof:Ca(e)}}function Ea(e,t){return{...wa(e,`replaced`),active_proof:Ca(e),replacement_proof:Ca(t)}}async function Da(e){let t=_t({activationBinding:e.activationBinding,serverCommit:e.serverCommit}),n=nt(le(`ecdsa-material-sealing-key`,32,`ECDSA material sealing key identities`)),r=await zt(),i=await Nt({key:r,stateBlobB64u:e.readyStateBlobB64u,aadProjection:Sa(e.activationBinding,t)}),a=gt({activationBinding:e.activationBinding,serverActivation:t,routerAbEcdsaDerivationNormalSigning:e.routerAbEcdsaDerivationNormalSigning,roleLocalPublicFacts:e.roleLocalPublicFacts,ciphertextDigest:Ye(i.digestB64u),runtimePolicyScope:e.runtimePolicyScope}),o=yt({binding:a,sealingKeyId:n,iv12B64u:i.iv12B64u,ciphertextB64u:i.ciphertextB64u}),s=vt({activationBinding:e.activationBinding,serverActivation:t,registeredPublicFacts:e.registeredPublicFacts,durableMaterial:a,committedAt:e.committedAt});return{activationBinding:e.activationBinding,serverActivation:t,sealingKey:r,readyMaterial:o,activeManifest:s,roleLocalMaterialRef:{kind:`ecdsa_role_local_persisted_material_ref_v1`,durableMaterialRef:o.binding.durableMaterialRef,bindingDigest:o.binding.bindingDigest,materialActivation:o.binding.materialActivation}}}async function Oa(e,t){let n=xt(t.activeManifest),r=e.store(Bt),i=await r.get(bn(n)),a=await pa(e,n);if(i!==void 0||a.length!==0)throw new U(`exact_record_conflict`,`ECDSA custody import found an existing active manifest`);let o={activationBinding:t.activationBinding,serverActivation:t.serverActivation,durableMaterial:t.readyMaterial.binding,activeManifest:t.activeManifest,committedAt:t.activeManifest.committedAt};await e.store(N).add(pn(t.readyMaterial.sealingKeyId,t.sealingKey)),await e.store(P).add(an(t.readyMaterial,t.activeManifest)),await e.store(j).add(Ta(o)),await r.put(Yt(t.activeManifest))}function ka(e){let t=Ut(Ca({activationBinding:e.committedJournal.candidate.activationBinding,serverActivation:e.committedJournal.serverActivation,durableMaterial:e.readyMaterial.binding,activeManifest:e.activeManifest,committedAt:e.activeManifest.committedAt}));if(!St(t.activeManifest,e.activeManifest)||!Pt(t.durableMaterial,e.readyMaterial.binding))throw Error(`ECDSA finalization input does not describe one exact active manifest`);return t}function Aa(e,t,n){switch(e.kind){case`no_current_manifest`:if(t!==void 0)throw new U(`exact_record_conflict`,`initial ECDSA activation found an existing current pointer`);return null;case`exact_manifest`:{if(t===void 0)throw new U(`exact_record_conflict`,`replacement ECDSA activation is missing its expected current pointer`);let r;try{r=hn(t)}catch(e){throw new U(`corrupt`,H(e))}if(!dn(r.selector,n)||r.manifestId!==e.manifestId||r.manifestRevision!==e.manifestRevision)throw new U(`exact_record_conflict`,`replacement ECDSA activation pointer CAS did not match`);return r}}return Vt(e)}async function ja(e,t){let n=t.store(M),r=await n.get(e.journalId);if(r===void 0)return{kind:`missing`};let i;try{i=Ht(r)}catch{return{kind:`corrupt`}}if(i.journal.journalId!==e.journalId)return{kind:`corrupt`};switch(i.journal.kind){case`server_activation_committed`:return{kind:`server_activation_committed`};case`activation_prepared`:return sn(i.journal,e)?(await t.store(N).delete(i.journal.candidate.encryptedPending.sealingKeyId),await n.delete(i.journal.journalId),{kind:`cancelled`}):{kind:`exact_record_conflict`}}return Vt(i.journal)}function Ma(e,t){return e.runTransaction([j,Bt,P,N],`readwrite`,e=>Oa(e,t))}async function Na(e,t,n){let r=_t({activationBinding:t.activationBinding,serverCommit:t.serverCommit}),i=en(t.activationBinding.signer),a=await e.lookup(i);if(a.kind===`active`)return va(a.manifest,t,r)?{kind:`committed`,manifest:a.manifest,material:a.material}:{kind:`exact_record_conflict`,selector:i,conflictDigest:await V(`custody_import_conflict`,i,`ECDSA custody import conflicts with the active manifest`)};try{let e=await Da(t);return await n(e),{kind:`committed`,manifest:e.activeManifest,material:e.readyMaterial}}catch(n){if(n instanceof U||ua(n)){let a=await e.lookup(i);return a.kind===`active`&&va(a.manifest,t,r)?{kind:`committed`,manifest:a.manifest,material:a.material}:{kind:`exact_record_conflict`,selector:i,conflictDigest:await V(`custody_import_conflict`,i,H(n))}}return{kind:`corrupt`,selector:i,corruptionDigest:await V(`custody_import_corrupt`,i,H(n))}}}var Pa=class{manager;constructor(e=xe){this.manager=e}async admitClientPresignature(e){if(!Jt())return{kind:`persistence_unavailable`};let t=$t(e.poolIdentity),n=pt(e.durableMaterialRef);if(!cn(n,t)||e.groupPublicKey33.length!==33||e.bigR33.length!==33)return{kind:`persistence_unavailable`};let r=tn(e.createdAtMs,`createdAtMs`),i=tn(e.expiresAtMs,`expiresAtMs`);if(r>Date.now()+3e5||i<=r||i>r+7776e6)return{kind:`persistence_unavailable`};let a=String(e.presignatureId||``).trim();if(!a||e.plaintext97.length!==97)return{kind:`persistence_unavailable`};let o;try{o=await this.lookupByMaterialRef(n)}catch{return{kind:`persistence_unavailable`}}if(o.kind!==`active`||!fn(o.material,t,n))return{kind:`persistence_unavailable`};let s;try{s=await this.readMaterialSealingKey(o.material.sealingKeyId)}catch{return{kind:`persistence_unavailable`}}if(!s)return{kind:`persistence_unavailable`};let c=Qt(le(`ecdsa-client-presignature`,32,`ECDSA durable presignature record`)),l=ut(C(e.groupPublicKey33)),u=ut(C(e.bigR33)),d={kind:`sealed_available_client_presignature_v1`,recordId:c,poolIdentity:t,durableMaterialRef:n,presignatureId:a,groupPublicKey33B64u:l,bigR33B64u:u,createdAtMs:r,expiresAtMs:i,sealingKeyId:o.material.sealingKeyId},f;try{f=await Xt({key:s,plaintext97:e.plaintext97,metadata:d})}catch{return e.plaintext97.fill(0),{kind:`persistence_unavailable`}}let p={kind:`sealed_available_client_presignature_v1`,record_id:c,pool_identity:t,pool_identity_key:Zt(t),wallet_id:t.walletId,material_activation_id:t.materialActivationId,durable_material_ref:n,presignature_id:a,group_public_key33_b64u:l,big_r33_b64u:u,created_at_ms:r,expires_at_ms:i,sealed:{kind:`ecdsa_activation_aes_gcm_v1`,sealing_key_id:o.material.sealingKeyId,iv12_b64u:f.iv12B64u,ciphertext_b64u:f.ciphertextB64u,ciphertext_digest_b64u:f.ciphertextDigestB64u}};try{let e=await this.manager.runTransaction([wt,P,w.appState],`readwrite`,async e=>{if(await gn(e,t.walletId,t.ownershipGeneration),(await rn(e,t,Date.now())).length>=5)return{kind:`capacity_full`};let r=await e.store(P).get(n.durableMaterialRef);if(r===void 0)return{kind:`persistence_unavailable`};try{let e=Ot(r),i=b(r,`ECDSA role-local material row`);if(e.durableMaterialRef!==n.durableMaterialRef||e.bindingDigest!==n.bindingDigest||e.selector.capability!==o.manifest.signer.capability||String(e.selector.authority.walletId)!==t.walletId||nt(i.sealing_key_id)!==o.material.sealingKeyId)return{kind:`persistence_unavailable`}}catch{return{kind:`persistence_unavailable`}}return await e.store(wt).put(p),{kind:`stored`}},{durability:`strict`});return e.kind===`stored`?{kind:`stored`,metadata:d}:e}catch{return{kind:`persistence_ambiguous`}}}async listAvailableClientPresignatures(e){if(!Jt())return[];let t=$t(e),n=Date.now();try{return await this.manager.runTransaction([wt,w.appState],`readwrite`,async e=>(await gn(e,t.walletId,t.ownershipGeneration),(await rn(e,t,n)).map(xn).sort((e,t)=>e.createdAtMs-t.createdAtMs)))}catch{return[]}}async takeClientPresignature(e){if(!Jt())return{kind:`persistence_unavailable`};let t=Qt(e.recordId),n=$t(e.poolIdentity),r;try{let e=await this.manager.runTransaction([wt,w.appState],`readwrite`,async e=>{let r=e.store(wt);await gn(e,n.walletId,n.ownershipGeneration);let i=await r.get(t);if(i===void 0)return{kind:`claimed_elsewhere`};let a;try{a=mn(i)}catch{let e=un(i);return e&&await r.delete(e),{kind:`corrupt`}}return ln(a.pool_identity,n)?a.expires_at_ms<=Date.now()?(await r.delete(t),{kind:`expired`}):(await r.delete(t),{kind:`claimed`,row:a}):(await r.delete(t),{kind:`binding_rejected`})},{durability:`strict`});if(e.kind!==`claimed`)return{kind:e.kind};r=e.row}catch{return{kind:`persistence_unavailable`}}let i;try{i=await this.lookupByMaterialRef(r.durable_material_ref)}catch{return{kind:`persistence_unavailable`}}if(i.kind!==`active`||!fn(i.material,n,r.durable_material_ref)||i.material.sealingKeyId!==r.sealed.sealing_key_id)return{kind:`binding_rejected`};let a;try{a=await this.readMaterialSealingKey(r.sealed.sealing_key_id)}catch{return{kind:`persistence_unavailable`}}if(!a)return{kind:`corrupt`};let o=xn(r);try{return{kind:`opened`,metadata:o,plaintext97:await vn({key:a,metadata:o,sealed:r.sealed})}}catch{return{kind:`corrupt`}}}async deleteClientPresignature(e){let t=Qt(e.recordId),n=$t(e.poolIdentity);await this.manager.runTransaction([wt],`readwrite`,async e=>{let r=e.store(wt),i=await r.get(t);i!==void 0&&ln(mn(i).pool_identity,n)&&await r.delete(t)})}async listActiveWalletCapabilitySubjects(e){let t=p(e);if(!t.ok)return{kind:`invalid_current_state`};let n;try{n=await this.manager.runTransaction([Bt],`readonly`,e=>da(e,t.value))}catch{return{kind:`persistence_unavailable`}}let r=[];try{for(let e of n){let n=hn(e);n.selector.authority.walletId===t.value&&r.push(n.selector)}}catch{return{kind:`invalid_current_state`}}let i=[];for(let e of r){let t=await this.lookup(e);if(t.kind===`persistence_unavailable`)return{kind:`persistence_unavailable`};if(t.kind!==`active`)return{kind:`invalid_current_state`};i.push({capability:t.manifest.signer.capability,authority:t.manifest.signer.authority,ecdsaThresholdKeyId:t.manifest.durableMaterial.roleLocalBinding.ecdsaThresholdKeyId})}return{kind:`resolved`,subjects:i}}async listWalletActivationJournalSelectors(e){let t=p(e);if(!t.ok)return{kind:`invalid_current_state`};let n;try{n=await this.manager.runTransaction([M],`readonly`,fa)}catch{return{kind:`persistence_unavailable`}}let r=[];try{for(let e of n){let n=Ht(e).journal.candidate.activationBinding.signer;n.authority.walletId===t.value&&r.push(en(n))}}catch{return{kind:`invalid_current_state`}}return{kind:`resolved`,selectors:r}}async prepareActivation(e){let t=en(e.activationBinding.signer);try{let t=nt(le(`ecdsa-material-key`,32,`ECDSA activation material sealing key`)),n=await zt(),r=await Nt({key:n,stateBlobB64u:e.pendingPayloadB64u,aadProjection:ba(e)}),i=Et({preparation:e,encryptedPending:ht({sealingKeyId:t,iv12B64u:r.iv12B64u,ciphertextB64u:r.ciphertextB64u,ciphertextDigest:Qe(r.digestB64u)})});return await this.manager.runTransaction([N,M],`readwrite`,async e=>{await e.store(N).add(pn(t,n)),await e.store(M).add(_n(i))}),{kind:`stored`,journal:i}}catch(e){return ua(e)?await ca(t,e):e instanceof DOMException&&e.name===`OperationError`?{kind:`corrupt`,corruptionDigest:await V(`journal_encryption_failed`,t,H(e))}:e instanceof Error&&!(e instanceof DOMException)?{kind:`corrupt`,corruptionDigest:await V(`journal_preparation_invalid`,t,e.message)}:{kind:`persistence_unavailable`,retryCorrelation:la()}}}async recordServerActivation(e){let t;try{t=mt(e)}catch(t){return{kind:`corrupt`,corruptionDigest:await V(`server_activation_commit_corrupt`,Rt(e.preparedJournal),H(t))}}return await this.putActivationJournal(t)}async putActivationJournal(e){let t;try{if(t=kt(e),await Tt(t.candidate.encryptedPending.ciphertextB64u)!==t.candidate.encryptedPending.ciphertextDigest)throw Error(`ECDSA pending material ciphertext digest is invalid`)}catch(t){return{kind:`corrupt`,corruptionDigest:await V(`journal_input_corrupt`,Rt(e),H(t))}}let n=Rt(t);try{let e=await this.readMaterialSealingKey(t.candidate.encryptedPending.sealingKeyId);if(!e)throw new U(`corrupt`,`ECDSA activation journal references a missing sealing key`);return await It({key:e,iv12B64u:t.candidate.encryptedPending.iv12B64u,ciphertextB64u:t.candidate.encryptedPending.ciphertextB64u,aadProjection:ba(t)}),await this.manager.runTransaction([N,M],`readwrite`,async e=>{let r=await e.store(N).get(t.candidate.encryptedPending.sealingKeyId);if(r===void 0)throw new U(`corrupt`,`ECDSA activation journal references a missing sealing key`);try{jt(r)}catch(e){throw new U(`corrupt`,H(e))}let i=e.store(M),a=await i.get(t.journalId);if(a===void 0)throw new U(`exact_record_conflict`,`ECDSA committed activation is missing its prepared journal`);let o;try{o=Ht(a)}catch(e){throw new U(`corrupt`,H(e))}if(!dn(o.selector,n)||o.journal.kind===`activation_prepared`&&!sn(o.journal,Kt(t))||o.journal.kind===`server_activation_committed`&&!sn(o.journal,t))throw new U(`exact_record_conflict`,`ECDSA activation journal conflicts with its existing correlation`);await i.put(_n(t))}),{kind:`stored`,journal:t}}catch(e){if(e instanceof U){let t=await V(e.kind===`corrupt`?`journal_corrupt`:`journal_conflict`,n,e.message);return e.kind===`corrupt`?{kind:`corrupt`,corruptionDigest:t}:{kind:`exact_record_conflict`,conflictDigest:t}}return ua(e)?await ca(n,e):e instanceof DOMException&&e.name===`OperationError`?{kind:`corrupt`,corruptionDigest:await V(`journal_ciphertext_corrupt`,n,H(e))}:{kind:`persistence_unavailable`,retryCorrelation:la()}}}async readActivationJournal(e){let t=me(e);try{let e=await this.manager.runTransaction([M],`readonly`,async e=>await e.store(M).get(t));if(e===void 0)return{kind:`missing`};try{let n=Ht(e);return n.journal.journalId===t?{kind:`found`,journal:n.journal}:{kind:`corrupt`}}catch{return{kind:`corrupt`}}}catch{return{kind:`persistence_unavailable`}}}async discoverActivationJournal(e){let t;try{t=Ct(e)}catch{return{kind:`corrupt`}}try{let e=await this.manager.runTransaction([M],`readonly`,async e=>await e.store(M).index(T.capabilityWalletAuthority).get(bn(t)));if(e===void 0)return{kind:`missing`};try{let n=Ht(e);return dn(n.selector,t)?{kind:`found`,journal:n.journal}:{kind:`corrupt`}}catch{return{kind:`corrupt`}}}catch{return{kind:`persistence_unavailable`}}}async cancelPreparedActivation(e){try{return await this.manager.runTransaction([N,M],`readwrite`,ja.bind(void 0,e))}catch{return{kind:`persistence_unavailable`}}}async openPreparedActivation(e){let t=await this.readActivationJournal(e);if(t.kind!==`found`)return t;let n=t.journal.candidate.encryptedPending;try{if(await Tt(n.ciphertextB64u)!==n.ciphertextDigest)return{kind:`corrupt`};let e=await this.readMaterialSealingKey(n.sealingKeyId);return e?{kind:`found`,journal:t.journal,pendingPayloadB64u:await It({key:e,iv12B64u:n.iv12B64u,ciphertextB64u:n.ciphertextB64u,aadProjection:ba(t.journal)})}:{kind:`corrupt`}}catch{return{kind:`corrupt`}}}async lookup(e){let t=Ct(e),n;try{n=await this.manager.runTransaction([j,Bt,P,N],`readonly`,async e=>await ga(e,t))}catch{return{kind:`persistence_unavailable`,selector:t,retryCorrelation:la()}}switch(n.kind){case`active`:return n;case`retired`:return n;case`missing`:return{kind:`missing`,selector:t,subject:n.subject};case`exact_binding_mismatch`:return{kind:`exact_binding_mismatch`,selector:t,failureDigest:await V(n.kind,t,n.detail)};case`exact_record_conflict`:return{kind:`exact_record_conflict`,selector:t,conflictDigest:await V(n.kind,t,n.detail)};case`corrupt`:return{kind:`corrupt`,selector:t,corruptionDigest:await V(n.kind,t,n.detail)}}return Vt(n)}async lookupByMaterialActivation(e){let t=p(e.walletId),n=u(e.materialActivation),r=n.ok?n.value.capability:e.materialActivation.capability;if(!t.ok||!n.ok)return{kind:`corrupt`,capability:r};let i=t.value,a=n.value,o;try{o=await this.manager.runTransaction([Bt],`readonly`,async e=>await da(e,i))}catch{return{kind:`persistence_unavailable`,capability:r}}let s=[];try{for(let e of o){let t=hn(e);t.selector.authority.walletId===i&&s.push(t.selector)}}catch{return{kind:`corrupt`,capability:r}}if(s.length===0)return{kind:`missing`,subject:`capability`,capability:r};let c=[];for(let e of s){let t=await this.lookup(e);switch(t.kind){case`active`:ma(t,a)&&c.push(t);break;case`retired`:break;case`missing`:return{kind:`missing`,subject:t.subject,capability:r};case`exact_binding_mismatch`:case`exact_record_conflict`:case`corrupt`:case`persistence_unavailable`:return{kind:t.kind,capability:r}}}let l=e.authority;if(l){let e=c.filter(e=>yn(e.manifest.signer.authority,l));return e.length>1?{kind:`exact_record_conflict`,capability:r}:e[0]??{kind:`exact_binding_mismatch`,capability:r}}return c.length>1?{kind:`ambiguous_authority`,capability:r,authorities:c.map(e=>e.manifest.signer.authority)}:c[0]??{kind:`exact_binding_mismatch`,capability:r}}async openActiveMaterial(e){let t=Ct(e),n=await this.lookup(t);return n.kind===`active`?await this.openActiveMaterialLookup(n):n}async lookupByMaterialRef(e){let t=pt(e),n=t.materialActivation.capability,r;try{r=await this.manager.runTransaction([P],`readonly`,async e=>await e.store(P).get(t.durableMaterialRef))}catch{return{kind:`persistence_unavailable`,capability:n}}if(r===void 0)return await this.lookupMissingMaterialByRef(t);let i;try{i=Ot(r)}catch{return{kind:`corrupt`,capability:n}}if(i.durableMaterialRef!==t.durableMaterialRef||i.bindingDigest!==t.bindingDigest)return{kind:`exact_binding_mismatch`,capability:n};let a=await this.lookup(i.selector);switch(a.kind){case`active`:return a.manifest.durableMaterial.durableMaterialRef!==t.durableMaterialRef||a.manifest.durableMaterial.bindingDigest!==t.bindingDigest||!ma(a,t.materialActivation)?{kind:`exact_binding_mismatch`,capability:n}:a;case`retired`:return a;case`missing`:return{kind:`missing`,subject:a.subject,capability:n};case`exact_binding_mismatch`:case`exact_record_conflict`:case`corrupt`:case`persistence_unavailable`:return{kind:a.kind,capability:n}}return Vt(a)}async lookupMissingMaterialByRef(e){let t=e.materialActivation.capability,n;try{n=await this.manager.runTransaction([j],`readonly`,async e=>await e.store(j).getAll())}catch{return{kind:`persistence_unavailable`,capability:t}}let r=[],i=!1;for(let a of n){let n;try{n=Wt(a)}catch{return{kind:`corrupt`,capability:t}}let o=n.activeProof.durableMaterial;if(o.durableMaterialRef===e.durableMaterialRef){if(o.bindingDigest!==e.bindingDigest||!d(o.materialActivation,e.materialActivation)){i=!0;continue}r.push(n)}}if(r.length>1)return{kind:`exact_record_conflict`,capability:t};let[a]=r;return a?a.state===`replaced`?{kind:`retired`,manifest:a.manifest}:{kind:`missing`,subject:`material`,capability:t}:i?{kind:`exact_binding_mismatch`,capability:t}:{kind:`missing`,subject:`material`,capability:t}}async openActiveMaterialLookup(e){let t=xt(e.manifest);try{if(await Tt(e.material.ciphertextB64u)!==e.material.binding.ciphertextDigest)throw Error(`active ECDSA material ciphertext digest is invalid`);let t=await this.readMaterialSealingKey(e.material.sealingKeyId);if(!t)throw Error(`active ECDSA material sealing key is missing`);return{kind:`active`,manifest:e.manifest,readyStateBlobB64u:await It({key:t,iv12B64u:e.material.iv12B64u,ciphertextB64u:e.material.ciphertextB64u,aadProjection:xa(e.manifest)})}}catch(e){return{kind:`corrupt`,selector:t,corruptionDigest:await V(`active_material_open_corrupt`,t,H(e))}}}async openActiveMaterialByRef(e){let t;try{t=await this.lookupByMaterialRef(e)}catch{return{kind:`corrupt`}}if(t.kind!==`active`)return ha(t);let n=await this.openActiveMaterialLookup(t);return n.kind===`active`?n:ha(n)}async sealAndFinalizeActivation(e){let t=Rt(e.committedJournal);try{let t=kt(e.committedJournal),n=t.candidate.encryptedPending.sealingKeyId,r=await this.readMaterialSealingKey(n);if(!r)throw Error(`ECDSA activation material sealing key is missing`);let i=await Nt({key:r,stateBlobB64u:e.readyStateBlobB64u,aadProjection:xa(t)}),a=gt({activationBinding:t.candidate.activationBinding,serverActivation:t.serverActivation,routerAbEcdsaDerivationNormalSigning:e.routerAbEcdsaDerivationNormalSigning,roleLocalPublicFacts:dt(e.roleLocalPublicFacts),ciphertextDigest:Ye(i.digestB64u),runtimePolicyScope:e.runtimePolicyScope}),o=yt({binding:a,sealingKeyId:n,iv12B64u:i.iv12B64u,ciphertextB64u:i.ciphertextB64u}),s=vt({activationBinding:t.candidate.activationBinding,serverActivation:t.serverActivation,registeredPublicFacts:e.registeredPublicFacts,durableMaterial:a,committedAt:e.committedAt});return await this.finalizeActivation({committedJournal:t,readyMaterial:o,activeManifest:s})}catch(e){return{kind:`corrupt`,selector:t,corruptionDigest:await V(`activation_seal_corrupt`,t,H(e))}}}async importCommittedWalletCustodyActivation(e){return await Na(this,e,e=>Ma(this.manager,e))}async persistPreparedWalletCustodyEcdsaContinuity(e){await Ma(this.manager,e)}async readMaterialSealingKey(e){let t=nt(e),n=await this.manager.runTransaction([N],`readonly`,async e=>await e.store(N).get(t));if(n===void 0)return null;let r=jt(n);if(r.keyId!==t)throw Error(`ECDSA material sealing key row identity is inconsistent`);return r.key}async finalizeActivation(e){let t;try{t=ka(e)}catch(t){let n=Rt(e.committedJournal);return{kind:`corrupt`,selector:n,corruptionDigest:await V(`finalization_input_corrupt`,n,H(t))}}let n=xt(t.activeManifest);try{if(await Tt(e.readyMaterial.ciphertextB64u)!==e.readyMaterial.binding.ciphertextDigest)throw new U(`corrupt`,`ECDSA ready material ciphertext digest is invalid`);let r=await this.readMaterialSealingKey(e.readyMaterial.sealingKeyId);if(!r)throw new U(`corrupt`,`ECDSA ready material sealing key is missing`);return await It({key:r,iv12B64u:e.readyMaterial.iv12B64u,ciphertextB64u:e.readyMaterial.ciphertextB64u,aadProjection:xa(e.committedJournal)}),await this.manager.runTransaction([j,Bt,P,M,N,wt],`readwrite`,async r=>{await Fa(r,e,t,n)}),{kind:`committed`,manifest:t.activeManifest,material:e.readyMaterial}}catch(e){if(e instanceof U){let t=await V(e.kind===`corrupt`?`finalization_corrupt`:`finalization_conflict`,n,e.message);return e.kind===`corrupt`?{kind:`corrupt`,selector:n,corruptionDigest:t}:{kind:`exact_record_conflict`,selector:n,conflictDigest:t}}return ua(e)?{kind:`exact_record_conflict`,selector:n,conflictDigest:await V(`finalization_constraint_conflict`,n,H(e))}:{kind:`persistence_unavailable`,selector:n,retryCorrelation:la()}}}};async function Fa(e,t,n,r){let i=e.store(M),a=await i.get(t.committedJournal.journalId);if(a===void 0)throw new U(`exact_record_conflict`,`ECDSA finalization is missing its durable activation journal`);let o;try{o=Ht(a)}catch(e){throw new U(`corrupt`,H(e))}if(o.journal.kind!==`server_activation_committed`||!dn(o.selector,r)||!sn(o.journal,t.committedJournal))throw new U(`exact_record_conflict`,`ECDSA finalization journal does not match its committed activation`);let s=await e.store(N).get(t.readyMaterial.sealingKeyId);if(s===void 0)throw new U(`corrupt`,`ECDSA finalization is missing its material sealing key`);try{jt(s)}catch(e){throw new U(`corrupt`,H(e))}let c=e.store(Bt),l=await c.get(bn(r)),u=t.committedJournal.expectedManifest,d=Aa(u,l,r),f=await pa(e,r),p=null,m=null;if(d===null){if(f.length!==0)throw new U(`exact_record_conflict`,`initial ECDSA activation found an unpointed active manifest`)}else{if(f.length!==1)throw new U(`exact_record_conflict`,`replacement ECDSA activation found conflicting current manifests`);let n;try{n=Wt(f[0])}catch(e){throw new U(`corrupt`,H(e))}if(n.state!==`active`||n.manifest.identity.manifestId!==d.manifestId)throw new U(`exact_record_conflict`,`replacement ECDSA activation current manifest does not match its pointer`);if(t.committedJournal.activationCommand.expectedGeneration.kind!==`exact_generation`||n.activeProof.serverActivation.serverGeneration!==t.committedJournal.activationCommand.expectedGeneration.serverGeneration)throw new U(`exact_record_conflict`,`replacement ECDSA activation server generation CAS did not match`);let r=await e.store(P).get(n.manifest.durableMaterial.durableMaterialRef);if(r===void 0)throw new U(`corrupt`,`replacement ECDSA activation is missing prior material`);try{let e=Mt(r,n.activeProof);if(!Cn(e,n.manifest))throw Error(`prior ECDSA material does not match its active manifest`);if(e.sealingKeyId===t.readyMaterial.sealingKeyId)throw Error(`replacement ECDSA activation must use a fresh material sealing key`);m=e.sealingKeyId}catch(e){throw new U(`corrupt`,H(e))}p=n.activeProof}let h=e.store(j),g=e.store(P);if(p){if(!m)throw new U(`corrupt`,`replacement ECDSA activation is missing its prior sealing key identity`);await nn(e,String(p.durableMaterial.materialActivation.materialOwner),String(p.durableMaterial.materialActivation.activationId)),await h.put(Ea(p,n)),await g.delete(p.durableMaterial.durableMaterialRef),await e.store(N).delete(m)}await g.add(an(t.readyMaterial,n.activeManifest)),await h.add(Ta(n)),await c.put(Yt(n.activeManifest)),await i.delete(t.committedJournal.journalId)}const Ia=`ed25519_yao_public_capability_references_v1`,La=`ed25519_yao_public_capability_lanes_v1`,Ra=`ed25519YaoPublicCapabilityReferencesV1`,za=`ed25519YaoPublicCapabilityLanesV1`;async function Ba(e,t){let n={walletId:t.walletId,nearAccountId:t.nearAccountId,thresholdSessionId:t.thresholdSessionId,runtimePolicyScope:t.runtimePolicyScope,materialActivation:t.materialActivation};await e.upsert(n),await e.upsertLane(t)}function Va(e,t,n){let r=Object.keys(e).sort(),i=[...t].sort();if(r.length!==i.length||r.some((e,t)=>e!==i[t]))throw Error(`${n} contains unexpected fields`)}function Ha(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return e}function Ua(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a positive integer`);return e}function Wa(e,t){let r=b(e,t),i=g(r.kind,`${t}.kind`,`must be a non-empty normalized string`);switch(i){case`voiceid`:{Va(r,[`kind`,`walletAuthMethodId`,`deviceKeyId`],t);let e=n(r.walletAuthMethodId);if(!e.ok)throw Error(`${t}.walletAuthMethodId is invalid`);return{kind:i,walletAuthMethodId:e.value,deviceKeyId:he(r.deviceKeyId)}}case`passkey`:return Va(r,[`kind`,`rpId`,`credentialIdB64u`],t),{kind:i,rpId:et(g(r.rpId,`${t}.rpId`,`must be a non-empty normalized string`)),credentialIdB64u:g(r.credentialIdB64u,`${t}.credentialIdB64u`,`must be a non-empty normalized string`)};case`email_otp`:return Va(r,[`kind`,`providerSubjectId`],t),{kind:i,providerSubjectId:g(r.providerSubjectId,`${t}.providerSubjectId`,`must be a non-empty normalized string`)};default:throw Error(`${t}.kind is invalid`)}}function Ga(e,n){let r=b(e,n);Va(r,[`walletId`,`nearAccountId`,`thresholdSessionId`,`runtimePolicyScope`,`materialActivation`],n);let i=u(r.materialActivation);if(!i.ok)throw Error(`${n}.materialActivation is invalid: ${i.error.message}`);let a=t(r.thresholdSessionId);if(!a.ok)throw Error(`${n}.thresholdSessionId is invalid`);let o=ue(r.runtimePolicyScope);if(!o)throw Error(`${n}.runtimePolicyScope is invalid`);return{walletId:Ce(g(r.walletId,`${n}.walletId`,`must be a non-empty normalized string`)),nearAccountId:Me(g(r.nearAccountId,`${n}.nearAccountId`,`must be a non-empty normalized string`)),thresholdSessionId:a.value,runtimePolicyScope:o,materialActivation:i.value}}function Ka(e,t){let n=b(e,t),r=Wa(n.auth,`${t}.auth`);Va(n,[`walletId`,`nearAccountId`,`thresholdSessionId`,`runtimePolicyScope`,`materialActivation`,`auth`,`nearEd25519SigningKeyId`,`signerSlot`,...r.kind===`email_otp`||r.kind===`voiceid`?[`remainingUses`,`expiresAtMs`]:[]],t);let i=Ga({walletId:n.walletId,nearAccountId:n.nearAccountId,thresholdSessionId:n.thresholdSessionId,runtimePolicyScope:n.runtimePolicyScope,materialActivation:n.materialActivation},t),a=lt(n.signerSlot);if(a===null)throw Error(`${t}.signerSlot is invalid`);let o={...i,nearEd25519SigningKeyId:st(g(n.nearEd25519SigningKeyId,`${t}.nearEd25519SigningKeyId`,`must be a non-empty normalized string`)),signerSlot:a};switch(r.kind){case`voiceid`:return{...o,auth:r,remainingUses:Ha(n.remainingUses,`${t}.remainingUses`),expiresAtMs:Ua(n.expiresAtMs,`${t}.expiresAtMs`)};case`email_otp`:return{...o,auth:r,remainingUses:Ha(n.remainingUses,`${t}.remainingUses`),expiresAtMs:Ua(n.expiresAtMs,`${t}.expiresAtMs`)};case`passkey`:return{...o,auth:r};default:throw Error(`${t}.auth is invalid`)}}function qa(e){let t=b(e,`Ed25519 Yao public capability references`);if(Va(t,[`kind`,`identities`],`Ed25519 Yao public capability references`),t.kind!==Ia)throw Error(`Ed25519 Yao public capability references kind is invalid`);if(!Array.isArray(t.identities))throw Error(`Ed25519 Yao public capability identities must be an array`);if(t.identities.length>64)throw Error(`Ed25519 Yao public capability reference capacity is exceeded`);let n=t.identities.map((e,t)=>Ga(e,`Ed25519 Yao public capability identity ${t}`));if(new Set(n.map(Za)).size!==n.length)throw Error(`Ed25519 Yao public capability references contain duplicate identities`);return{kind:Ia,identities:n}}function Ja(e){let t=b(e,`Ed25519 Yao public capability lanes`);if(Va(t,[`kind`,`lanes`],`Ed25519 Yao public capability lanes`),t.kind!==La)throw Error(`Ed25519 Yao public capability lanes kind is invalid`);if(!Array.isArray(t.lanes))throw Error(`Ed25519 Yao public capability lanes must be an array`);if(t.lanes.length>64)throw Error(`Ed25519 Yao public capability lane capacity is exceeded`);let n=t.lanes.map((e,t)=>Ka(e,`Ed25519 Yao public capability lane ${t}`));if(new Set(n.map(Za)).size!==n.length)throw Error(`Ed25519 Yao public capability lanes contain duplicate identities`);return{kind:La,lanes:n}}function Ya(){return{kind:Ia,identities:[]}}function Xa(){return{kind:La,lanes:[]}}function Za(e){let t=e.materialActivation;return JSON.stringify([String(e.walletId),String(e.nearAccountId),t.activationId,t.capability,t.materialOwner,t.keyBinding,t.lifecycleBinding,t.signingWorker])}function Qa(e){return Ga(e,`Ed25519 Yao public capability identity`)}function $a(e){return Ka(e,`Ed25519 Yao public capability lane`)}async function eo(e,t){let n=await e.get(Ra);if(n!==void 0&&n.key!==Ra)throw Error(`Ed25519 Yao public capability reference app-state key is inconsistent`);let r=n===void 0?Ya():qa(n.value),i=Qa(t),a=r.identities.filter(e=>String(e.walletId)!==String(i.walletId)||String(e.nearAccountId)!==String(i.nearAccountId));if(a.length>=64)throw Error(`Ed25519 Yao public capability reference capacity is exhausted`);await e.put({key:Ra,value:qa({kind:Ia,identities:[...a,i]})})}var to=class{constructor(e){this.appState=e}async readProjection(){if(this.appState.isDisabled())return Ya();let e=await this.appState.getAppState(Ra);return e==null?Ya():qa(e)}async writeProjection(e){this.appState.isDisabled()||await this.appState.setAppState(Ra,qa(e))}async readLaneProjection(){if(this.appState.isDisabled())return Xa();let e=await this.appState.getAppState(za);return e==null?Xa():Ja(e)}async writeLaneProjection(e){this.appState.isDisabled()||await this.appState.setAppState(za,Ja(e))}async upsert(e){let t=Qa(e),n=(await this.readProjection()).identities.filter(e=>String(e.walletId)!==String(t.walletId)||String(e.nearAccountId)!==String(t.nearAccountId));if(n.length>=64)throw Error(`Ed25519 Yao public capability reference capacity is exhausted`);await this.writeProjection({kind:Ia,identities:[...n,t]})}async remove(e){let t=Za(e),n=await this.readProjection();await this.writeProjection({kind:Ia,identities:n.identities.filter(e=>Za(e)!==t)})}async list(){return(await this.readProjection()).identities.map(Qa)}async upsertLane(e){let t=$a(e),n=(await this.readLaneProjection()).lanes.filter(e=>String(e.walletId)!==String(t.walletId)||String(e.nearAccountId)!==String(t.nearAccountId));if(n.length>=64)throw Error(`Ed25519 Yao public capability lane capacity is exhausted`);await this.writeLaneProjection({kind:La,lanes:[...n,t]})}async removeLane(e){let t=Za(e),n=await this.readLaneProjection();await this.writeLaneProjection({kind:La,lanes:n.lanes.filter(e=>Za(e)!==t)})}async listLanes(){return(await this.readLaneProjection()).lanes.map($a)}};async function no(e,t){let n=String(t||``).trim();if(!n)return null;let r=new Set;for(let t of await new to(e).listLanes()){if(t.auth.kind!==`email_otp`||String(t.walletId)!==n)continue;let e=String(t.auth.providerSubjectId||``).trim();e&&r.add(e)}return r.size===1?[...r][0]??null:null}function ro(e){return e.family===`near`?e.walletId:e.accountId}function io(e){return e.family===`near`?e.nearAccountId:``}function ao(e){let t=c(e.leaseId||``),n=c(e.laneKey||``),r=c(ro(e)||``),i=c(io(e)||``);if(!t||!n||!r)throw Error(`[SeamsWalletDB] nonce lease requires leaseId, laneKey, and wallet identity`);return{lease_id:t,lane_key:n,wallet_id:r,...i?{near_account_id:i}:{},state:e.state,expires_at_ms:Math.floor(Number(e.expiresAtMs)),record:e}}function oo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=E(Reflect.get(e,`lock_key`)),n=E(Reflect.get(e,`owner_id`)),r=E(Reflect.get(e,`fencing_token`)),i=Reflect.get(e,`acquired_at_ms`),a=Reflect.get(e,`expires_at_ms`),o=Reflect.get(e,`updated_at_ms`);return!t||!n||!r||!Number.isSafeInteger(i)||i<0||!Number.isSafeInteger(a)||a<0||!Number.isSafeInteger(o)||o<0?null:{lock_key:t,owner_id:n,fencing_token:r,acquired_at_ms:i,expires_at_ms:a,updated_at_ms:o}}function so(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{return Se({kind:Reflect.get(e,`kind`),namespace:Reflect.get(e,`namespace`),chainId:Reflect.get(e,`chainId`),networkSlug:Reflect.get(e,`networkSlug`)})}catch{return null}}function co(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`v`),n=E(Reflect.get(e,`leaseId`)),r=E(Reflect.get(e,`laneKey`)),i=E(Reflect.get(e,`networkKey`)),a=E(Reflect.get(e,`nonce`)),o=E(Reflect.get(e,`operationId`)),s=E(Reflect.get(e,`operationFingerprint`)),c=Reflect.get(e,`reservedAtMs`),l=Reflect.get(e,`expiresAtMs`),u=Reflect.get(e,`updatedAtMs`),d=Reflect.get(e,`state`);if(t!==1||!n||!r||!i||!a||!o||!s||!Number.isSafeInteger(c)||!Number.isSafeInteger(l)||!Number.isSafeInteger(u)||d!==`reserved`&&d!==`signed`&&d!==`broadcast_accepted`)return null;let f=Reflect.get(e,`txHash`);if(d===`broadcast_accepted`&&!E(f)||d!==`broadcast_accepted`&&f!==void 0)return null;let p=Reflect.get(e,`runtimeId`),m=Reflect.get(e,`fencingToken`),h=Reflect.get(e,`batchId`),g=Reflect.get(e,`txIndex`);if(p!==void 0&&!E(p)||m!==void 0&&!E(m)||h!==void 0&&!E(h)||g!==void 0&&!Number.isSafeInteger(g))return null;let _=Reflect.get(e,`family`);if(_===`near`){let t=E(Reflect.get(e,`walletId`)),_=E(Reflect.get(e,`nearAccountId`)),v=E(Reflect.get(e,`publicKey`));return!t||!_||!v?null:{v:1,leaseId:n,laneKey:r,networkKey:i,nonce:a,operationId:o,operationFingerprint:s,reservedAtMs:c,expiresAtMs:l,updatedAtMs:u,family:`near`,walletId:t,nearAccountId:_,publicKey:v,state:d,...p===void 0?{}:{runtimeId:p},...m===void 0?{}:{fencingToken:m},...h===void 0?{}:{batchId:h},...g===void 0?{}:{txIndex:g},...d===`broadcast_accepted`?{txHash:f}:{}}}if(_!==`evm`)return null;let v=so(Reflect.get(e,`chainTarget`)),y=E(Reflect.get(e,`sender`)),b=E(Reflect.get(e,`accountId`));if(!v||!y||!b)return null;let ee=Reflect.get(e,`nonceKey`);return ee!==void 0&&!E(ee)?null:{v:1,leaseId:n,laneKey:r,networkKey:i,nonce:a,operationId:o,operationFingerprint:s,reservedAtMs:c,expiresAtMs:l,updatedAtMs:u,family:`evm`,chainTarget:v,sender:y,accountId:b,state:d,...p===void 0?{}:{runtimeId:p},...m===void 0?{}:{fencingToken:m},...h===void 0?{}:{batchId:h},...g===void 0?{}:{txIndex:g},...ee===void 0?{}:{nonceKey:ee},...d===`broadcast_accepted`?{txHash:f}:{}}}function lo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=co(Reflect.get(e,`record`));return!t||Reflect.get(e,`lease_id`)!==t.leaseId||Reflect.get(e,`lane_key`)!==t.laneKey||Reflect.get(e,`wallet_id`)!==ro(t)||(Reflect.get(e,`near_account_id`)||``)!==io(t)||Reflect.get(e,`state`)!==t.state||Reflect.get(e,`expires_at_ms`)!==Math.floor(Number(t.expiresAtMs))?null:t}function uo(e){let t=c(e.opId||``),n=c(e.idempotencyKey||``),r=D(e.chainIdKey),i=O(e.accountAddress),a=c(e.signerId||``);if(!t||!n||!r||!i||!a)throw Error(`[SeamsWalletDB] signer op requires opId, idempotencyKey, chainIdKey, accountAddress, and signerId`);return{op_id:t,idempotency_key:n,status:e.status,next_attempt_at:e.nextAttemptAt,wallet_id:c(String(e.payload?.profileId||``)),chain_target_key:Ee({chainIdKey:r,accountAddress:i}),updated_at:e.updatedAt,record:{...e,opId:t,idempotencyKey:n,chainIdKey:r,accountAddress:i,signerId:a}}}function fo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=E(Reflect.get(e,`opId`)),n=E(Reflect.get(e,`idempotencyKey`)),r=E(Reflect.get(e,`opType`)),i=D(Reflect.get(e,`chainIdKey`)),a=O(Reflect.get(e,`accountAddress`)),o=E(Reflect.get(e,`signerId`)),s=Reflect.get(e,`status`),c=Reflect.get(e,`attemptCount`),l=Reflect.get(e,`nextAttemptAt`),u=Reflect.get(e,`createdAt`),d=Reflect.get(e,`updatedAt`);if(!t||!n||!r||!i||!a||!o||s!==`queued`&&s!==`submitted`&&s!==`confirmed`&&s!==`failed`&&s!==`dead-letter`||!Number.isSafeInteger(c)||Number(c)<0||!Number.isSafeInteger(l)||Number(l)<0||!Number.isSafeInteger(u)||Number(u)<0||!Number.isSafeInteger(d)||Number(d)<0)return null;let f=Reflect.get(e,`payload`),p=Ae(f);if(f!==void 0&&(typeof f!=`object`||!f||Array.isArray(f)))return null;let m=Reflect.get(e,`lastError`),h=Reflect.get(e,`txHash`);return m!==void 0&&typeof m!=`string`||h!==void 0&&typeof h!=`string`?null:{opId:t,idempotencyKey:n,opType:r,chainIdKey:i,accountAddress:a,signerId:o,status:s,attemptCount:Number(c),nextAttemptAt:Number(l),createdAt:Number(u),updatedAt:Number(d),...p===void 0?{}:{payload:p},...m===void 0?{}:{lastError:m},...h===void 0?{}:{txHash:h}}}function po(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=fo(Reflect.get(e,`record`));if(!t||Reflect.get(e,`op_id`)!==t.opId||Reflect.get(e,`idempotency_key`)!==t.idempotencyKey||Reflect.get(e,`status`)!==t.status||Reflect.get(e,`next_attempt_at`)!==t.nextAttemptAt||Reflect.get(e,`chain_target_key`)!==Ee({chainIdKey:t.chainIdKey,accountAddress:t.accountAddress}))return null;let n=c(String(t.payload&&Reflect.get(t.payload,`profileId`)?Reflect.get(t.payload,`profileId`):``));return Reflect.get(e,`wallet_id`)!==n||Reflect.get(e,`updated_at`)!==t.updatedAt?null:t}function mo(e){return`${e.chainIdKey}\0${e.accountAddress}`}function ho(e){return[e.chainIdKey,e.accountAddress,e.signerId].join(`\0`)}function go(e){if(typeof e!=`object`||!e||Array.isArray(e))return``;let t=c(Reflect.get(e,`kind`)||``),n=Number(Reflect.get(e,`chainId`));return!Number.isSafeInteger(n)||n<=0?``:t===`evm`?c(Reflect.get(e,`namespace`)||``)===`eip155`?De({kind:`evm`,namespace:`eip155`,chainId:n,networkSlug:c(Reflect.get(e,`networkSlug`)||``)}):``:t===`tempo`?De({kind:`tempo`,chainId:n,networkSlug:c(Reflect.get(e,`networkSlug`)||``)}):``}function _o(e){if(e.signerKind===ge.thresholdEcdsa){let t=e.metadata||{},n=c(t.keyHandle||``),r=c(t.ecdsaThresholdKeyId||``),i=O(t.thresholdOwnerAddress||``),a=go(t.chainTarget);if(!n||!r||!i||!a)throw Error(`[SeamsWalletDB] threshold ECDSA signer requires keyHandle, ecdsaThresholdKeyId, thresholdOwnerAddress, and chainTarget`);return{chainTargetKey:a,keyHandle:n,ecdsaThresholdKeyId:r,thresholdOwnerAddress:i}}let t=Number(e.signerSlot);if(!Number.isSafeInteger(t)||t<1)throw Error(`[SeamsWalletDB] Ed25519 signer requires a positive signerSlot`);let n=c(e.metadata?.nearEd25519SigningKeyId||``);if(!n)throw Error(`[SeamsWalletDB] Ed25519 signer requires nearEd25519SigningKeyId`);return{chainTargetKey:Ee({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress}),nearSignerSlot:t,nearEd25519SigningKeyId:n}}function vo(e,t){let n=c(e.profileId||``),r=D(e.chainIdKey),i=O(e.accountAddress),a=Te(e.accountModel);if(!n||!r||!i)throw Error(`[SeamsWalletDB] profileId, chainIdKey, and accountAddress are required`);if(!a)throw Error(`[SeamsWalletDB] accountModel is required`);let o=Date.now(),s={profileId:n,chainIdKey:r,accountAddress:i,accountModel:a,isPrimary:e.isPrimary??t?.isPrimary??!1,createdAt:t?.createdAt??o,updatedAt:o};return{wallet_id:n,near_account_id:mo({chainIdKey:r,accountAddress:i}),signer_slot:0,profile_id:n,chain_id_key:r,account_address:i,account_model:a,is_primary:!!s.isPrimary,updated_at:s.updatedAt,record:s}}function yo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=E(Reflect.get(e,`profileId`)),n=D(Reflect.get(e,`chainIdKey`)),r=O(Reflect.get(e,`accountAddress`)),i=Te(Reflect.get(e,`accountModel`)),a=Reflect.get(e,`createdAt`),o=Reflect.get(e,`updatedAt`),s=Reflect.get(e,`isPrimary`);return!t||!n||!r||!i||!Number.isSafeInteger(a)||Number(a)<0||!Number.isSafeInteger(o)||Number(o)<0||s!==void 0&&typeof s!=`boolean`?null:{profileId:t,chainIdKey:n,accountAddress:r,accountModel:i,...s===void 0?{}:{isPrimary:s},createdAt:Number(a),updatedAt:Number(o)}}function bo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=yo(Reflect.get(e,`record`));return!t||Reflect.get(e,`wallet_id`)!==t.profileId||Reflect.get(e,`profile_id`)!==t.profileId||Reflect.get(e,`chain_id_key`)!==t.chainIdKey||Reflect.get(e,`account_address`)!==t.accountAddress||Reflect.get(e,`account_model`)!==t.accountModel||Reflect.get(e,`is_primary`)!==!!t.isPrimary||Reflect.get(e,`updated_at`)!==t.updatedAt||Reflect.get(e,`near_account_id`)!==mo({chainIdKey:t.chainIdKey,accountAddress:t.accountAddress})?null:t}function xo(e){let t=c(e.profileId||``),n=D(e.chainIdKey),r=O(e.accountAddress),i=c(e.signerId||``),a=c(e.signerKind||``);if(!t||!n||!r||!i||!a)throw Error(`[SeamsWalletDB] signer requires profileId, chainIdKey, accountAddress, signerId, and signerKind`);let o=_o({...e,profileId:t,chainIdKey:n,accountAddress:r,signerId:i}),s=e.status===`active`;return{wallet_signer_id:ho({chainIdKey:n,accountAddress:r,signerId:i}),wallet_id:t,kind:a,chain_target_key:o.chainTargetKey,...s&&o.nearSignerSlot!=null?{near_signer_slot:o.nearSignerSlot}:{},...s&&o.nearEd25519SigningKeyId?{near_ed25519_signing_key_id:o.nearEd25519SigningKeyId}:{},...s&&o.keyHandle?{key_handle:o.keyHandle}:{},...s&&o.ecdsaThresholdKeyId?{ecdsa_threshold_key_id:o.ecdsaThresholdKeyId}:{},...s&&o.thresholdOwnerAddress?{threshold_owner_address:o.thresholdOwnerAddress}:{},status:e.status,updated_at:e.updatedAt,record:{...e,profileId:t,chainIdKey:n,accountAddress:r,signerId:i}}}function So(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=E(Reflect.get(e,`profileId`)),n=D(Reflect.get(e,`chainIdKey`)),r=O(Reflect.get(e,`accountAddress`)),i=E(Reflect.get(e,`signerId`)),a=Reflect.get(e,`signerSlot`),o=E(Reflect.get(e,`signerType`)),s=Reflect.get(e,`signerKind`),c=Reflect.get(e,`signerAuthMethod`),l=Reflect.get(e,`signerSource`),u=Reflect.get(e,`status`),d=Reflect.get(e,`addedAt`),f=Reflect.get(e,`updatedAt`);if(!t||!n||!r||!i||!Number.isSafeInteger(a)||Number(a)<1||!o||s!==ge.thresholdEd25519&&s!==ge.thresholdEcdsa||c!==`passkey`&&c!==`email_otp`||l!==`passkey_registration`&&l!==`email_otp_registration`&&l!==`self_hosted_import`||u!==`active`&&u!==`pending`&&u!==`revoked`||!Number.isSafeInteger(d)||Number(d)<0||!Number.isSafeInteger(f)||Number(f)<0)return null;let p=Reflect.get(e,`metadata`),m;if(p!==void 0){if(typeof p!=`object`||!p||Array.isArray(p))return null;m={};for(let e of Object.keys(p))m[e]=Reflect.get(p,e)}let h=Reflect.get(e,`removedAt`),g=Reflect.get(e,`revocationReason`);return h!==void 0&&(!Number.isSafeInteger(h)||Number(h)<0)||g!==void 0&&typeof g!=`string`?null:{profileId:t,chainIdKey:n,accountAddress:r,signerId:i,signerSlot:Number(a),signerType:o,signerKind:s,signerAuthMethod:c,signerSource:l,status:u,addedAt:Number(d),updatedAt:Number(f),...h===void 0?{}:{removedAt:Number(h)},...g===void 0?{}:{revocationReason:g},...m===void 0?{}:{metadata:m}}}function W(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=So(Reflect.get(e,`record`));if(!t||Reflect.get(e,`wallet_signer_id`)!==ho({chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId})||Reflect.get(e,`wallet_id`)!==t.profileId||Reflect.get(e,`kind`)!==t.signerKind)return null;let n;try{n=_o(t)}catch{return null}let r=t.status===`active`;if(t.signerKind===ge.thresholdEd25519){let t=Reflect.get(e,`chain_target_key`),i=Reflect.get(e,`near_signer_slot`),a=Reflect.get(e,`near_ed25519_signing_key_id`);if(t!==void 0&&t!==n.chainTargetKey||r&&i!==n.nearSignerSlot||!r&&i!==void 0&&i!==n.nearSignerSlot||r&&a!==n.nearEd25519SigningKeyId||!r&&a!==void 0&&a!==n.nearEd25519SigningKeyId)return null}else if(r&&Reflect.get(e,`chain_target_key`)!==n.chainTargetKey)return null;else if(!r&&Reflect.get(e,`chain_target_key`)!==void 0&&Reflect.get(e,`chain_target_key`)!==n.chainTargetKey)return null;let i=Reflect.get(e,`key_handle`),a=Reflect.get(e,`ecdsa_threshold_key_id`),o=Reflect.get(e,`threshold_owner_address`);return r&&i!==n.keyHandle||!r&&i!==void 0&&i!==n.keyHandle||r&&a!==n.ecdsaThresholdKeyId||!r&&a!==void 0&&a!==n.ecdsaThresholdKeyId||r&&o!==n.thresholdOwnerAddress||!r&&o!==void 0&&o!==n.thresholdOwnerAddress||Reflect.get(e,`status`)!==t.status||Reflect.get(e,`updated_at`)!==t.updatedAt?null:t}function G(e){throw Error(`Unhandled wallet auth method branch: ${String(e)}`)}function Co(e,t){if(t.binding.kind!==`ed25519_yao_client_root_v1`)return!1;switch(e.kind){case`passkey`:return t.factor.kind===`passkey`&&t.factor.rpId===e.rpId&&t.factor.credentialIdB64u===e.credentialIdB64u&&t.binding.targetFactor.kind===`passkey_prf`;case`email_otp`:return t.factor.kind===`email_otp`&&t.binding.targetFactor.kind===`email_otp`;case`voiceid`:return!1;default:return G(e)}}function wo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`key`);return typeof t!=`string`||t.length===0?null:{key:t,value:Reflect.get(e,`value`)}}function To(e){return`local-authority/pending-profile-projection/v1/${e}`}function Eo(e,t){return{kind:`wallet_selection_v1`,walletId:e.authority.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,lockGeneration:t?.record.lockGeneration??0,lockState:t?.record.lockState??`unlocked`,updatedAtMs:e.receipt.installedAtMs}}function Do(e,t){if(e.operation!==t.operation||e.registrationCeremonyId!==t.registrationCeremonyId||e.idempotencyKey!==t.idempotencyKey||e.walletId!==t.walletId||e.walletAuthMethodId!==t.walletAuthMethodId)throw Error(`pending wallet registration commit does not match the request`)}function Oo(e){let t=k(e.authority),n=A(e.authMethod);if(!t.ok||t.value.state!==`active`||!n||n.status!==`active`||t.value.provenance.kind!==`wallet_registration`||n.walletId!==t.value.walletId||n.walletAuthorityId!==t.value.authorityId)throw Error(`founding wallet authority records are invalid`);return{authority:t.value,authMethod:n}}async function ko(e){let t=e.pending,n=e.foundingAuthority.authMethod,r=e.registration.initialAuthMethod;if(Do(t,e.request),Er(t,{operation:e.request.operation,walletId:e.request.walletId,walletAuthMethodId:e.request.walletAuthMethodId,authority:e.authority}),n.walletId!==t.walletId||n.walletAuthMethodId!==t.walletAuthMethodId||r.walletId!==t.walletId||r.status!==`active`||r.localStatus!==`synced`||r.kind!==t.auth.kind||n.kind!==t.auth.kind||!e.registration.profiles.some(e=>e.profileId===t.walletId)||e.registration.lastProfileState.profileId!==t.walletId)throw Error(`registration finalize batch does not match the pending wallet`);let i=new Set(e.registration.profiles.map(e=>e.profileId));for(let n of e.registration.profiles)if(n.passkeyCredential&&(t.auth.kind!==`passkey`||n.passkeyCredential.rawId!==t.auth.credentialIdB64u))throw Error(`registration profile credential does not match the pending commit`);for(let t of e.registration.signerActivations)if(!i.has(t.account.profileId))throw Error(`registration signer account is outside the publication profiles`);for(let t of e.registration.keyMaterials)if(!i.has(t.profileId))throw Error(`registration key material is outside the publication profiles`);switch(t.auth.kind){case`passkey`:if(!Je(e.authority)||r.kind!==`passkey`||n.kind!==`passkey`||r.rpId!==t.auth.rpId||r.credentialIdB64u!==t.auth.credentialIdB64u||n.rpId!==t.auth.rpId||n.credentialIdB64u!==t.auth.credentialIdB64u||r.credentialPublicKeyB64u!==n.credentialPublicKeyB64u)throw Error(`registration passkey records do not match the pending commit`);for(let n of e.registration.authenticators)if(!i.has(n.profileId)||n.credentialId!==t.auth.credentialIdB64u||C(n.credentialPublicKey)!==r.credentialPublicKeyB64u)throw Error(`registration passkey authenticator does not match the pending commit`);return;case`email_otp`:{if(r.kind!==`email_otp`||n.kind!==`email_otp`)throw Error(`registration Email OTP method records are invalid`);let i=Xe(r.authority);if(!i||!Ze(e.authority))throw Error(`registration Email OTP authority records are invalid`);let a=await v(t.auth.email);if(r.registrationAuthorityId!==t.auth.registrationAuthorityId||n.registrationAuthorityId!==t.auth.registrationAuthorityId||r.emailHashHex!==a||n.emailHashHex!==a||e.authority.verifier.emailHashHex!==a||i.factor.providerUserId!==t.auth.providerSubject||i.factor.provider!==e.authority.factor.provider||!tt(i,e.authority)||e.registration.authenticators.length!==0)throw Error(`registration Email OTP records do not match the pending commit`);return}}}function Ao(e){let t=e.pending.projection;if(!gc(e.authority,t.authority)||!vc(e.authMethod,t.authMethod))throw Error(`recovery publication records do not match the committed projection`);let n=e.registration.initialAuthMethod,r=e.registration.profiles;if(n.status!==`active`||n.localStatus!==`synced`||n.walletId!==t.walletId||!r.some(e=>e.profileId===t.walletId)||e.registration.lastProfileState.profileId!==t.walletId||!Number.isSafeInteger(e.registration.lastProfileState.activeSignerSlot)||e.registration.lastProfileState.activeSignerSlot<1)throw Error(`recovery profile publication does not match the committed projection`);let i=new Set(r.map(e=>e.profileId));for(let e of r)if(e.passkeyCredential&&(t.kind!==`passkey`||e.passkeyCredential.rawId!==t.target.credentialIdB64u))throw Error(`recovery profile credential does not match the committed projection`);for(let t of e.registration.signerActivations)if(!i.has(t.account.profileId))throw Error(`recovery signer account is outside the publication profiles`);for(let t of e.registration.keyMaterials)if(!i.has(t.profileId))throw Error(`recovery key material is outside the publication profiles`);if(t.kind===`passkey`){if(n.kind!==`passkey`)throw Error(`recovery passkey publication method branch is invalid`);if(n.rpId!==t.target.rpId||n.credentialIdB64u!==t.target.credentialIdB64u||n.credentialPublicKeyB64u!==t.authMethod.credentialPublicKeyB64u||!e.registration.authenticators.some(e=>e.profileId===t.walletId&&e.credentialId===t.target.credentialIdB64u&&C(e.credentialPublicKey)===t.authMethod.credentialPublicKeyB64u))throw Error(`recovery passkey publication does not match the committed projection`);return}if(n.kind!==`email_otp`)throw Error(`recovery Email OTP publication method branch is invalid`);if(n.emailHashHex!==t.target.emailHashHex||n.registrationAuthorityId!==t.target.registrationAuthorityId||e.registration.authenticators.length!==0||r.some(e=>e.passkeyCredential!==void 0))throw Error(`recovery Email OTP publication does not match the committed projection`);let a=Xe(n.authority);if(!a||a.walletId!==t.walletId||a.factor.provider!==`google`||a.factor.providerUserId!==t.target.providerSubject||a.verifier.emailHashHex!==t.target.emailHashHex)throw Error(`recovery Email OTP factor does not match the committed projection`)}function jo(e){if(e.incoming.walletId!==e.existing.walletId||e.incoming.authorityId!==e.existing.authorityId||e.incoming.authMethodId!==e.existing.authMethodId||e.incoming.authorizationId!==e.existing.authorizationId||e.incoming.quotaId!==e.existing.quotaId||e.incoming.issuedAtMs!==e.existing.issuedAtMs||e.incoming.expiresAtMs!==e.existing.expiresAtMs||e.incoming.expiresAtMs<=Date.now()||e.incoming.authorityRevocationEpoch!==e.existing.authorityRevocationEpoch||!se(e.existing,e.incoming))throw Error(`Credential-free registration projection changed immutable session identity`)}const Mo=`lastProfileState`,No=[w.appState,w.wallets,w.walletAuthMethods,w.walletSigners,w.nearAccountProjections,w.signerOpsOutbox,w.keyMaterial],Po=[w.appState,w.wallets,w.walletAuthMethods,w.walletAuthorities,w.walletSelections,w.walletSigners,w.nearAccountProjections,w.signerOpsOutbox,w.keyMaterial,w.walletSessionAuthorizations,w.ecdsaClientPresignatures,w.ecdsaCapabilityManifests,w.ecdsaCurrentCapabilityManifests,w.ecdsaRoleLocalMaterial,w.ecdsaMaterialSealingKeys],Fo=[w.appState,w.wallets,w.walletAuthMethods,w.walletAuthorities,w.walletSelections,w.walletSigners,w.nearAccountProjections,w.signerOpsOutbox,w.keyMaterial,w.ecdsaCapabilityManifests,w.ecdsaCurrentCapabilityManifests,w.ecdsaRoleLocalMaterial,w.ecdsaMaterialSealingKeys,w.ecdsaClientPresignatures],Io=`local`;function Lo(e){let t=a(e);if(!t.ok)throw Error(t.error.message);return t.value}var Ro=class extends Error{code;details;constructor(e,t,n){super(t),this.name=`SeamsWalletDBConstraintError`,this.code=e,this.details=n}};function zo(e){return new Promise(t=>setTimeout(t,e))}function Bo(e){let t=new Uint8Array(16);return crypto.getRandomValues(t),`${e}-${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function Vo(e){return IDBKeyRange.upperBound(e)}async function Ho(e){let t=await e.store.index(e.indexName).getAllKeys(e.key);for(let n of t)await e.store.delete(n)}function Uo(e){let t=we(e);return t?`${Mo}::${t}`:Mo}function Wo(e){return e.accountModel===`near-native`||e.chainIdKey.startsWith(`near:`)}function K(e,t,n){return new Ro(e,t,n)}function Go(e,t){let n=c(e.profileId||``);if(!n)throw Error(`[SeamsWalletDB] profileId is required`);let r=Date.now(),i=e.passkeyCredential?.rawId?e.passkeyCredential:t?.passkeyCredential,a=t?.nearProvisioning?.status===`near_ready`&&e.nearProvisioning?.status!==`near_ready`?t.nearProvisioning:e.nearProvisioning??t?.nearProvisioning,o={profileId:n,defaultSignerSlot:e.defaultSignerSlot??t?.defaultSignerSlot??1,...i?{passkeyCredential:i}:{},preferences:e.preferences??t?.preferences,...a?{nearProvisioning:a}:{},createdAt:t?.createdAt??r,updatedAt:r};return{wallet_id:n,rp_id:Io,status:`active`,created_at:o.createdAt,updated_at:o.updatedAt,record:o}}function Ko(e){return{wallet_id:e.profileId,rp_id:Io,status:`active`,created_at:e.createdAt,updated_at:e.updatedAt,record:e}}function qo(e,t){return e===void 0||t===void 0?e===t:e.id===t.id&&e.rawId===t.rawId}function Jo(e,t){return e===void 0||t===void 0?e===t:e.useRelayer===t.useRelayer&&e.useNetwork===t.useNetwork&&e.confirmationConfig.uiMode===t.confirmationConfig.uiMode&&e.confirmationConfig.behavior===t.confirmationConfig.behavior&&e.confirmationConfig.autoProceedDelay===t.confirmationConfig.autoProceedDelay}function Yo(e,t){if(e===void 0||t===void 0)return e===t;if(e.status!==t.status||e.updatedAtMs!==t.updatedAtMs)return!1;switch(e.status){case`near_pending`:case`near_provisioning`:return!0;case`near_ready`:return t.status===`near_ready`&&e.nearAccountId===t.nearAccountId;case`near_failed_retryable`:return t.status===`near_failed_retryable`&&e.error===t.error&&e.errorCode===t.errorCode;default:return G(e)}}function Xo(e,t){return e.profileId===t.profileId&&e.defaultSignerSlot===t.defaultSignerSlot&&qo(e.passkeyCredential,t.passkeyCredential)&&Jo(e.preferences,t.preferences)&&Yo(e.nearProvisioning,t.nearProvisioning)&&e.createdAt===t.createdAt&&e.updatedAt===t.updatedAt}function Zo(e,t){return e.wallet_id===t.wallet_id&&e.rp_id===t.rp_id&&e.status===t.status&&e.created_at===t.created_at&&e.updated_at===t.updated_at&&Xo(e.record,t.record)}function Qo(e,t){return e===void 0||t===void 0?e===t:e.length===t.length?e.every((e,n)=>e===t[n]):!1}function $o(e,t){return e.profileId===t.profileId&&e.signerSlot===t.signerSlot&&e.credentialId===t.credentialId&&oc(e.credentialPublicKey,t.credentialPublicKey)&&Qo(e.transports,t.transports)&&e.name===t.name&&e.registered===t.registered&&e.syncedAt===t.syncedAt}function es(e,t){if(e.version!==t.version||e.kind!==t.kind||e.status!==t.status||e.localStatus!==t.localStatus||e.walletId!==t.walletId||e.createdAtMs!==t.createdAtMs||e.updatedAtMs!==t.updatedAtMs)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u&&e.credentialPublicKeyB64u===t.credentialPublicKeyB64u&&e.counter===t.counter;case`email_otp`:return t.kind===`email_otp`&&e.emailHashHex===t.emailHashHex&&e.registrationAuthorityId===t.registrationAuthorityId&&tt(e.authority,t.authority);default:return G(e)}}function ts(e,t){if(e.wallet_auth_method_id!==t.wallet_auth_method_id||e.wallet_id!==t.wallet_id||e.kind!==t.kind||e.auth_method!==t.auth_method||e.rp_id!==t.rp_id||e.auth_identifier_key!==t.auth_identifier_key||e.status!==t.status||e.updated_at!==t.updated_at||!es(e.record,t.record))return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.credential_id_b64u===t.credential_id_b64u&&e.credential_public_key_b64u===t.credential_public_key_b64u&&e.signer_slot===t.signer_slot&&$o(e.authenticator,t.authenticator);case`email_otp`:return t.kind===`email_otp`&&e.email_hash_hex===t.email_hash_hex&&e.challenge_id===t.challenge_id;default:return G(e)}}function ns(e){return e===void 0?{kind:`account_signer_rollback_metadata_absent_v1`}:{kind:`account_signer_rollback_metadata_json_v1`,json:JSON.stringify(e)}}function rs(e,t){switch(t.kind){case`account_signer_rollback_metadata_absent_v1`:return e===void 0;case`account_signer_rollback_metadata_json_v1`:return e!==void 0&&JSON.stringify(e)===t.json;default:return G(t)}}function is(e){return e===void 0?{kind:`key_material_rollback_payload_absent_v1`}:{kind:`key_material_rollback_payload_json_v1`,json:JSON.stringify(e)}}function as(e,t){switch(t.kind){case`key_material_rollback_payload_absent_v1`:return e===void 0;case`key_material_rollback_payload_json_v1`:return e!==void 0&&JSON.stringify(e)===t.json;default:return G(t)}}function os(e,t,n){return e.profileId===t.profileId&&e.chainIdKey===t.chainIdKey&&e.accountAddress===t.accountAddress&&e.signerId===t.signerId&&e.signerSlot===t.signerSlot&&e.signerType===t.signerType&&e.signerKind===t.signerKind&&e.signerAuthMethod===t.signerAuthMethod&&e.signerSource===t.signerSource&&e.status===t.status&&e.addedAt===t.addedAt&&e.updatedAt===t.updatedAt&&e.removedAt===t.removedAt&&e.revocationReason===t.revocationReason&&rs(e.metadata,n)}function ss(e,t,n){return e.profileId===t.profileId&&e.signerSlot===t.signerSlot&&e.chainIdKey===t.chainIdKey&&e.accountAddress===t.accountAddress&&e.keyKind===t.keyKind&&e.algorithm===t.algorithm&&e.publicKey===t.publicKey&&e.signerId===t.signerId&&e.wrapKeySalt===t.wrapKeySalt&&as(e.payload,n)&&cs(e.payloadEnvelope,t.payloadEnvelope)&&e.timestamp===t.timestamp&&e.schemaVersion===t.schemaVersion}function cs(e,t){return e===void 0||t===void 0?e===t:e.encVersion===t.encVersion&&e.alg===t.alg&&e.nonce===t.nonce&&e.ciphertext===t.ciphertext&&e.tag===t.tag&&e.aad.profileId===t.aad.profileId&&e.aad.signerSlot===t.aad.signerSlot&&e.aad.chainIdKey===t.aad.chainIdKey&&e.aad.accountAddress===t.aad.accountAddress&&e.aad.keyKind===t.aad.keyKind&&e.aad.schemaVersion===t.aad.schemaVersion&&e.aad.signerId===t.aad.signerId}function ls(e,t){return e.profileId===t.profileId&&e.activeSignerSlot===t.activeSignerSlot&&e.scope===t.scope}function us(e){if(e===void 0)return;if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`useRelayer`),n=Reflect.get(e,`useNetwork`),r=Reflect.get(e,`confirmationConfig`);if(t!==void 0&&typeof t!=`boolean`||n!==void 0&&n!==`testnet`&&n!==`mainnet`||typeof r!=`object`||!r||Array.isArray(r))return null;let i=Reflect.get(r,`uiMode`),a=Reflect.get(r,`behavior`),o=Reflect.get(r,`autoProceedDelay`),s=o===void 0?void 0:typeof o==`number`&&Number.isSafeInteger(o)&&o>=0?o:null;return i!==`none`&&i!==`modal`&&i!==`drawer`||a!==`requireClick`&&a!==`skipClick`||s===null?null:{...t===void 0?{}:{useRelayer:t},...n===void 0?{}:{useNetwork:n},confirmationConfig:{uiMode:i,behavior:a,...s===void 0?{}:{autoProceedDelay:s}}}}function ds(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`profileId`),n=p(t),r=Reflect.get(e,`defaultSignerSlot`),i=Reflect.get(e,`createdAt`),a=Reflect.get(e,`updatedAt`);if(!n.ok||n.value!==t||!Number.isSafeInteger(r)||Number(r)<1||!Number.isSafeInteger(i)||Number(i)<0||!Number.isSafeInteger(a)||Number(a)<0)return null;let o=Reflect.get(e,`passkeyCredential`),s;if(o!==void 0){if(typeof o!=`object`||!o||Array.isArray(o))return null;let e=Reflect.get(o,`id`),t=Reflect.get(o,`rawId`);if(typeof e!=`string`||typeof t!=`string`||!e||!t||e.trim()!==e||t.trim()!==t)return null;s={id:e,rawId:t}}let c=us(Reflect.get(e,`preferences`));if(c===null)return null;let l=Reflect.get(e,`nearProvisioning`),u;if(l!==void 0){let e=bt(l);if(e===null)return null;u=e}return{profileId:n.value,defaultSignerSlot:Number(r),...s===void 0?{}:{passkeyCredential:s},...c===void 0?{}:{preferences:c},...u===void 0?{}:{nearProvisioning:u},createdAt:Number(i),updatedAt:Number(a)}}function q(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=ds(Reflect.get(e,`record`));return!t||Reflect.get(e,`wallet_id`)!==t.profileId||Reflect.get(e,`created_at`)!==t.createdAt||Reflect.get(e,`updated_at`)!==t.updatedAt?null:t}function fs(e){if(typeof e!=`object`||!e||Array.isArray(e)||Reflect.get(e,`kind`)!==`local_authority_pending_profile_projection_v1`)return null;let t=ps(Reflect.get(e,`profile`)),n=Reflect.get(e,`authenticator`),r=Reflect.get(e,`localAuthMethod`),i=n===null?null:J(n),a=r===null?null:J(r);if(!t||n!==null&&(!i||i.kind!==`passkey`||i.status!==`active`)||r!==null&&(!a||a.kind!==`email_otp`||a.status!==`active`))return null;let o=Reflect.get(e,`authorityId`),s=Reflect.get(e,`walletId`),c=Reflect.get(e,`authMethodId`);return typeof o!=`string`||typeof s!=`string`||typeof c!=`string`||!o||!s||!c||o.trim()!==o||s.trim()!==s||c.trim()!==c||t.wallet_id!==s||i!==null&&i.wallet_id!==s||a!==null&&a.wallet_id!==s?null:{kind:`local_authority_pending_profile_projection_v1`,authorityId:o,walletId:s,authMethodId:c,profile:t,authenticator:i?.kind===`passkey`?i:null,localAuthMethod:a?.kind===`email_otp`?a:null}}function ps(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`status`),n=Reflect.get(e,`rp_id`);if(t!==`active`||typeof n!=`string`)return null;let r=q(e);return!r||Reflect.get(e,`wallet_id`)!==r.profileId?null:{wallet_id:r.profileId,rp_id:n,status:`active`,created_at:r.createdAt,updated_at:r.updatedAt,record:r}}function ms(e){switch(e.kind){case`passkey`:return c(e.credentialIdB64u||``);case`email_otp`:return c(e.emailHashHex||``);default:{let t=e;throw Error(`[SeamsWalletDB] Unsupported auth-method binding: ${String(t)}`)}}}function hs(e){return e.kind===`passkey`?[c(e.walletId||``),e.kind,c(e.rpId||``),ms(e)].join(`\0`):[c(e.walletId||``),e.kind,ms(e)].join(`\0`)}function gs(e){if(e.version!==`wallet_auth_method_v1`)throw Error(`[SeamsWalletDB] auth-method binding version is invalid`);let t=c(e.walletId||``),n=e.kind===`passkey`?c(e.rpId||``):``,r=ms(e),i=Math.floor(Number(e.createdAtMs)),a=Math.floor(Number(e.updatedAtMs));if(!t||!r||e.kind===`passkey`&&!n)throw Error(`[SeamsWalletDB] auth-method binding requires walletId and branch identity`);if(e.status!==`active`&&e.status!==`revoked`)throw Error(`[SeamsWalletDB] auth-method binding status is invalid`);if(e.localStatus!==`synced`&&e.localStatus!==`pending`)throw Error(`[SeamsWalletDB] auth-method binding localStatus is invalid`);if(!Number.isSafeInteger(i))throw Error(`[SeamsWalletDB] auth-method binding createdAtMs is invalid`);if(!Number.isSafeInteger(a))throw Error(`[SeamsWalletDB] auth-method binding updatedAtMs is invalid`);if(e.kind===`passkey`){if(e.emailHashHex!=null)throw Error(`[SeamsWalletDB] passkey auth-method binding has Email OTP fields`);if(!c(e.credentialPublicKeyB64u||``))throw Error(`[SeamsWalletDB] passkey auth-method binding requires credential public key`);if(!Number.isSafeInteger(e.counter)||e.counter<0)throw Error(`[SeamsWalletDB] passkey auth-method binding counter is invalid`)}if(e.kind===`email_otp`){if(e.credentialIdB64u!=null||e.credentialPublicKeyB64u!=null||e.counter!=null||e.rpId!=null)throw Error(`[SeamsWalletDB] Email OTP auth-method binding has passkey fields`);if(!c(e.registrationAuthorityId||``))throw Error(`[SeamsWalletDB] Email OTP auth-method binding requires registrationAuthorityId`);if(!e.authority)throw Error(`[SeamsWalletDB] Email OTP auth-method binding requires authority`);let t=Xe(e.authority);if(!t||t.walletId!==e.walletId||t.verifier.emailHashHex!==e.emailHashHex||!tt(t,e.authority))throw Error(`[SeamsWalletDB] Email OTP auth-method authority binding is invalid`)}return{wallet_auth_method_id:hs(e),wallet_id:t,kind:e.kind,auth_method:e.kind,rp_id:n,auth_identifier_key:r,status:e.status,updated_at:a,record:e}}function _s(e){return new Date(e).toISOString()}function vs(e,t){let n=Date.parse(e);return Number.isSafeInteger(n)?n:t}function ys(e){let t=c(e.profileId||``),n=c(e.credentialId||``),r=Number(e.signerSlot);if(!t||!n)throw Error(`[SeamsWalletDB] profileId and credentialId are required for authenticators`);if(!Number.isSafeInteger(r)||r<1)throw Error(`[SeamsWalletDB] authenticator signerSlot must be an integer >= 1`);let i=e.credentialPublicKey;if(!(i instanceof Uint8Array)||i.byteLength===0)throw Error(`[SeamsWalletDB] authenticator credentialPublicKey must be a non-empty Uint8Array`);return{profileId:t,signerSlot:r,credentialId:n,credentialPublicKey:i,...Array.isArray(e.transports)?{transports:e.transports}:{},...e.name?{name:String(e.name)}:{},registered:c(e.registered||``),syncedAt:c(e.syncedAt||``)}}function bs(e,t){let n=Number(t);if(!Number.isSafeInteger(n)||n<1)throw Error(`[SeamsWalletDB] passkey auth-method signerSlot must be an integer >= 1`);return ys({profileId:e.walletId,signerSlot:n,credentialId:e.credentialIdB64u,credentialPublicKey:ce(e.credentialPublicKeyB64u),registered:_s(e.createdAtMs),syncedAt:_s(e.updatedAtMs)})}function xs(e,t){let n=ys(e),r=C(n.credentialPublicKey);if(t){if(t.walletId!==n.profileId)throw Error(`[SeamsWalletDB] passkey auth-method walletId does not match authenticator profileId`);if(t.credentialIdB64u!==n.credentialId)throw Error(`[SeamsWalletDB] passkey auth-method credentialId does not match authenticator credentialId`);if(t.credentialPublicKeyB64u!==r)throw Error(`[SeamsWalletDB] passkey auth-method public key does not match authenticator public key`);return t}let i=Date.now();return{version:`wallet_auth_method_v1`,kind:`passkey`,status:`active`,localStatus:`synced`,walletId:ct(n.profileId),rpId:Lo(Io),credentialIdB64u:n.credentialId,credentialPublicKeyB64u:r,counter:0,createdAtMs:vs(n.registered,i),updatedAtMs:vs(n.syncedAt,i)}}function Ss(e){let t=gs(e.binding),n=ys(e.authenticator),r=C(n.credentialPublicKey);if(t.kind!==`passkey`)throw Error(`[SeamsWalletDB] passkey auth-method row requires a passkey binding`);if(n.profileId!==t.wallet_id)throw Error(`[SeamsWalletDB] passkey auth-method authenticator profileId mismatch`);if(n.credentialId!==e.binding.credentialIdB64u)throw Error(`[SeamsWalletDB] passkey auth-method authenticator credentialId mismatch`);if(r!==e.binding.credentialPublicKeyB64u)throw Error(`[SeamsWalletDB] passkey auth-method authenticator public key mismatch`);return{...t,kind:`passkey`,auth_method:`passkey`,record:e.binding,credential_id_b64u:e.binding.credentialIdB64u,credential_public_key_b64u:e.binding.credentialPublicKeyB64u,signer_slot:n.signerSlot,authenticator:n}}function Cs(e){let t=gs(e);if(t.kind!==`email_otp`)throw Error(`[SeamsWalletDB] Email OTP auth-method row requires an Email OTP binding`);return{...t,kind:`email_otp`,auth_method:`email_otp`,record:e,email_hash_hex:e.emailHashHex,challenge_id:e.registrationAuthorityId}}function ws(e,t){switch(e.kind){case`passkey`:return Ss({binding:e,authenticator:bs(e,t)});case`email_otp`:return Cs(e);default:{let t=e;throw Error(`[SeamsWalletDB] Unsupported auth-method row: ${String(t)}`)}}}function Ts(e,t){let n=ys(e);return Ss({binding:xs(n,t?.record),authenticator:n})}function Es(e){if(e.profile.wallet_id!==e.walletId||e.authenticator!==null&&e.authenticator.wallet_id!==e.walletId||e.localAuthMethod!==null&&e.localAuthMethod.wallet_id!==e.walletId)throw Error(`local authority profile projection identity does not match installation`);if(e.authenticator?.wallet_auth_method_id===e.authMethodId||e.localAuthMethod?.wallet_auth_method_id===e.authMethodId)throw Error(`local authority profile projection collides with the V2 auth-method key`);return{kind:`local_authority_pending_profile_projection_v1`,authorityId:e.authorityId,walletId:e.walletId,authMethodId:e.authMethodId,profile:e.profile,authenticator:e.authenticator,localAuthMethod:e.localAuthMethod}}function Ds(e,t){return e.authorityId===t.authorityId&&e.walletId===t.walletId&&e.authMethodId===t.authMethodId&&Zo(e.profile,t.profile)&&(e.authenticator===null?t.authenticator===null:t.authenticator!==null&&ts(e.authenticator,t.authenticator))&&(e.localAuthMethod===null?t.localAuthMethod===null:t.localAuthMethod!==null&&ts(e.localAuthMethod,t.localAuthMethod))}function Os(e,t){return e.authorityId===t.authority.authorityId&&e.walletId===t.authority.walletId&&e.authMethodId===t.authMethod.walletAuthMethodId&&e.profile.record.profileId===t.profile.profileId&&e.profile.record.defaultSignerSlot===(t.profile.defaultSignerSlot??1)&&(t.profile.passkeyCredential===void 0||e.profile.record.passkeyCredential?.id===t.profile.passkeyCredential.id&&e.profile.record.passkeyCredential.rawId===t.profile.passkeyCredential.rawId)&&(t.profile.preferences===void 0||Jo(e.profile.record.preferences,t.profile.preferences))&&(t.authenticator===null?e.authenticator===null:e.authenticator!==null&&$o(e.authenticator.authenticator,t.authenticator))&&(t.localAuthMethod===null?e.localAuthMethod===null:e.localAuthMethod!==null&&es(e.localAuthMethod.record,t.localAuthMethod))}function ks(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=E(Reflect.get(e,`profileId`)),n=Reflect.get(e,`signerSlot`),r=E(Reflect.get(e,`credentialId`)),i=Reflect.get(e,`credentialPublicKey`),a=E(Reflect.get(e,`registered`)),o=E(Reflect.get(e,`syncedAt`));if(!t||!Number.isSafeInteger(n)||n<1||!r||!(i instanceof Uint8Array)||i.byteLength===0||!a||!o)return null;let s=Reflect.get(e,`transports`),c=Reflect.get(e,`name`);return s!==void 0&&(!Array.isArray(s)||s.some(e=>typeof e!=`string`))||c!==void 0&&typeof c!=`string`?null:{profileId:t,signerSlot:Number(n),credentialId:r,credentialPublicKey:new Uint8Array(i),...s===void 0?{}:{transports:[...s]},...c===void 0?{}:{name:c},registered:a,syncedAt:o}}function As(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`version`),n=Reflect.get(e,`kind`),r=Reflect.get(e,`status`),o=Reflect.get(e,`localStatus`),s=Reflect.get(e,`walletId`),c=p(s),l=Reflect.get(e,`createdAtMs`),u=Reflect.get(e,`updatedAtMs`);if(t!==`wallet_auth_method_v1`||n!==`passkey`&&n!==`email_otp`||r!==`active`&&r!==`revoked`||o!==`synced`&&o!==`pending`||!c.ok||c.value!==s||!Number.isSafeInteger(l)||Number(l)<0||!Number.isSafeInteger(u)||Number(u)<0)return null;if(n===`passkey`){let t=Reflect.get(e,`rpId`),n=a(t),s=Reflect.get(e,`credentialIdB64u`),d=i(s),f=Reflect.get(e,`credentialPublicKeyB64u`),p=Reflect.get(e,`counter`);return!n.ok||n.value!==t||!d.ok||d.value!==s||typeof f!=`string`||!f||!Number.isSafeInteger(p)||Number(p)<0?null:{version:`wallet_auth_method_v1`,kind:`passkey`,status:r,localStatus:o,walletId:c.value,rpId:n.value,credentialIdB64u:d.value,credentialPublicKeyB64u:f,counter:Number(p),createdAtMs:Number(l),updatedAtMs:Number(u)}}let d=E(Reflect.get(e,`emailHashHex`)),f=E(Reflect.get(e,`registrationAuthorityId`)),m=Xe(Reflect.get(e,`authority`));return!d||!f||!m||m.walletId!==c.value||m.verifier.emailHashHex!==d?null:{version:`wallet_auth_method_v1`,kind:`email_otp`,status:r,localStatus:o,walletId:c.value,emailHashHex:d,registrationAuthorityId:f,authority:m,createdAtMs:Number(l),updatedAtMs:Number(u)}}function J(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=As(Reflect.get(e,`record`));if(!t)return null;let n;try{if(t.kind===`passkey`){let r=ks(Reflect.get(e,`authenticator`));if(!r)return null;n=Ss({binding:t,authenticator:r})}else if(t.kind===`email_otp`)n=Cs(t);else return null}catch{return null}if(Reflect.get(e,`wallet_auth_method_id`)!==n.wallet_auth_method_id||Reflect.get(e,`wallet_id`)!==n.wallet_id||Reflect.get(e,`kind`)!==n.kind||Reflect.get(e,`auth_method`)!==n.auth_method||n.kind===`passkey`&&Reflect.get(e,`rp_id`)!==n.rp_id||Reflect.get(e,`auth_identifier_key`)!==n.auth_identifier_key||Reflect.get(e,`status`)!==n.status||Reflect.get(e,`updated_at`)!==n.updated_at)return null;if(n.kind===`passkey`){if(Reflect.get(e,`credential_id_b64u`)!==n.credential_id_b64u||Reflect.get(e,`credential_public_key_b64u`)!==n.credential_public_key_b64u||Reflect.get(e,`signer_slot`)!==n.signer_slot)return null}else if(Reflect.get(e,`email_hash_hex`)!==n.email_hash_hex||Reflect.get(e,`challenge_id`)!==n.challenge_id)return null;return n}function js(e){let t=J(e);return t?t.record:null}function Ms(e){let t=J(e);return!t||t.kind!==`passkey`||t.status!==`active`?null:t.authenticator}function Ns(e,t){if(Object.keys(e).length!==t.length)return!1;for(let n of t)if(!Object.prototype.hasOwnProperty.call(e,n))return!1;return!0}function Y(e,t){if(!e.ok)throw Error(`${t}: ${e.error.message}`);return e.value}function Ps(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`${t} must be a non-empty canonical string`);return e}function Fs(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw Error(`${t} must be a non-negative safe integer`);return Number(e)}function Is(e){return e!==void 0}function X(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=k(Reflect.get(e,`record`));if(!t.ok)return null;let n=t.value;return Reflect.get(e,`authority_id`)!==n.authorityId||Reflect.get(e,`wallet_id`)!==n.walletId||Reflect.get(e,`state`)!==n.state||Reflect.get(e,`device_id`)!==n.principal.deviceId||Reflect.get(e,`updated_at`)!==n.updatedAtMs?null:{authority_id:n.authorityId,wallet_id:n.walletId,state:n.state,device_id:n.principal.deviceId,updated_at:n.updatedAtMs,record:n}}function Ls(e){return{authority_id:e.authorityId,wallet_id:e.walletId,state:e.state,device_id:e.principal.deviceId,updated_at:e.updatedAtMs,record:e}}function Rs(e){switch(e.kind){case`passkey`:return{version:`wallet_auth_method_local_presentation_v1`,kind:`passkey`};case`email_otp`:return{version:`wallet_auth_method_local_presentation_v1`,kind:`email_otp`,email:{kind:`unavailable`}};case`voiceid`:return{version:`wallet_auth_method_local_presentation_v1`,kind:`voiceid`};default:throw Error(`Wallet auth-method presentation kind is invalid`)}}function zs(e,t){if(e===void 0)return Rs(t);if(typeof e!=`object`||!e||Array.isArray(e)||Reflect.get(e,`version`)!==`wallet_auth_method_local_presentation_v1`||Reflect.get(e,`kind`)!==t.kind)return null;switch(t.kind){case`passkey`:return Ns(e,[`version`,`kind`])?{version:`wallet_auth_method_local_presentation_v1`,kind:`passkey`}:null;case`email_otp`:{if(!Ns(e,[`version`,`kind`,`email`]))return null;let t=Reflect.get(e,`email`);if(typeof t!=`object`||!t||Array.isArray(t))return null;switch(Reflect.get(t,`kind`)){case`unavailable`:return Ns(t,[`kind`])?{version:`wallet_auth_method_local_presentation_v1`,kind:`email_otp`,email:{kind:`unavailable`}}:null;case`verified`:{if(!Ns(t,[`kind`,`address`]))return null;let e=s(Reflect.get(t,`address`));return e.ok?{version:`wallet_auth_method_local_presentation_v1`,kind:`email_otp`,email:{kind:`verified`,address:e.value}}:null}default:return null}}case`voiceid`:return Ns(e,[`version`,`kind`])?{version:`wallet_auth_method_local_presentation_v1`,kind:`voiceid`}:null;default:return null}}function Z(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=A(Reflect.get(e,`record`));if(!t)return null;let n=zs(Reflect.get(e,`presentation`),t);return!n||Reflect.get(e,`wallet_auth_method_id`)!==t.walletAuthMethodId||Reflect.get(e,`wallet_id`)!==t.walletId||Reflect.get(e,`wallet_authority_id`)!==t.walletAuthorityId||Reflect.get(e,`kind`)!==t.kind||Reflect.get(e,`status`)!==t.status||Reflect.get(e,`updated_at`)!==t.updatedAtMs?null:Bs(Gs(t,n))}function Bs(e){switch(e.kind){case`passkey`:return{wallet_auth_method_id:e.record.walletAuthMethodId,wallet_id:e.record.walletId,wallet_authority_id:e.record.walletAuthorityId,kind:`passkey`,status:e.record.status,updated_at:e.record.updatedAtMs,presentation:e.presentation,record:e.record};case`email_otp`:return{wallet_auth_method_id:e.record.walletAuthMethodId,wallet_id:e.record.walletId,wallet_authority_id:e.record.walletAuthorityId,kind:`email_otp`,status:e.record.status,updated_at:e.record.updatedAtMs,presentation:e.presentation,record:e.record};case`voiceid`:return{wallet_auth_method_id:e.record.walletAuthMethodId,wallet_id:e.record.walletId,wallet_authority_id:e.record.walletAuthorityId,kind:`voiceid`,status:e.record.status,updated_at:e.record.updatedAtMs,presentation:e.presentation,record:e.record};default:throw Error(`Wallet auth-method projection kind is invalid`)}}function Vs(e,t){let n=new Set;for(let r of t){let t=J(r)?.record;if(!t||t.kind!==`email_otp`||t.emailHashHex!==e.emailHashHex||t.authority.bindingId!==e.walletAuthMethodId)continue;let i=s(t.authority.factor.providerUserId);i.ok&&n.add(String(i.value))}if(n.size!==1)return null;let r=s([...n][0]);return r.ok?{version:`wallet_auth_method_local_presentation_v1`,kind:`email_otp`,email:{kind:`verified`,address:r.value}}:null}function Hs(e,t,n){switch(e.kind){case`passkey`:return Rs(e);case`email_otp`:return Vs(e,t)??(n?.kind===`email_otp`&&n.email.kind===`verified`?n:Rs(e));case`voiceid`:return Rs(e);default:throw Error(`Wallet auth-method presentation kind is invalid`)}}function Us(e,t){return e.kind===t.kind?e.kind===`passkey`&&t.kind===`passkey`||e.kind===`voiceid`&&t.kind===`voiceid`?!0:e.kind!==`email_otp`||t.kind!==`email_otp`||e.email.kind!==t.email.kind?!1:e.email.kind===`unavailable`&&t.email.kind===`unavailable`?!0:e.email.kind===`verified`&&t.email.kind===`verified`&&e.email.address===t.email.address:!1}function Ws(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Reflect.get(e,`presentation`)!==void 0}function Gs(e,t){switch(e.kind){case`passkey`:if(t.kind!==`passkey`)throw Error(`Passkey auth method has non-passkey local presentation`);return{kind:`passkey`,record:e,presentation:t};case`email_otp`:if(t.kind!==`email_otp`)throw Error(`Email OTP auth method has non-email local presentation`);return{kind:`email_otp`,record:e,presentation:t};case`voiceid`:if(t.kind!==`voiceid`)throw Error(`VoiceID auth method has non-VoiceID local presentation`);return{kind:`voiceid`,record:e,presentation:t};default:throw Error(`Wallet auth-method projection kind is invalid`)}}async function Ks(e,t){let n=Z(await e.get(t.walletAuthMethodId));return Bs(Gs(t,Hs(t,await e.index(T.walletId).getAll(t.walletId),n?.presentation??null)))}function qs(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`signer material record must be an object`);let t=Reflect.get(e,`kind`),r=Reflect.get(e,`keyFamily`);if(t===`wallet_authority_linked_signer_material_v1`)return Mn(e);if(t!==`wallet_authority_signer_material_v1`)throw Error(`signer material record kind is invalid`);if(r!==`ed25519`&&r!==`ecdsa_secp256k1`)throw Error(`signer material keyFamily is invalid`);let i=[`kind`,`authorityId`,`walletAuthMethodId`,`activationId`,`keyFamily`,`materialActivation`,`sealedMaterialB64u`,`sealedMaterialDigestB64u`];if(!Ns(e,r===`ecdsa_secp256k1`?[...i,`ecdsaThresholdKeyId`]:i))throw Error(`signer material record fields are invalid`);let a=Y(o(Reflect.get(e,`authorityId`)),`authorityId`),s=Y(n(Reflect.get(e,`walletAuthMethodId`)),`walletAuthMethodId`),c=Y(u(Reflect.get(e,`materialActivation`)),`materialActivation`),l=Ps(Reflect.get(e,`activationId`),`activationId`),d=Ps(Reflect.get(e,`sealedMaterialB64u`),`sealedMaterialB64u`),f=he(Reflect.get(e,`sealedMaterialDigestB64u`));if(c.activationId!==l)throw Error(`signer material activationId does not match materialActivation`);return r===`ed25519`?{kind:`wallet_authority_signer_material_v1`,authorityId:a,walletAuthMethodId:s,activationId:c.activationId,keyFamily:`ed25519`,materialActivation:c,sealedMaterialB64u:d,sealedMaterialDigestB64u:f}:{kind:`wallet_authority_signer_material_v1`,authorityId:a,walletAuthMethodId:s,activationId:c.activationId,keyFamily:`ecdsa_secp256k1`,ecdsaThresholdKeyId:ft(Reflect.get(e,`ecdsaThresholdKeyId`)),materialActivation:c,sealedMaterialB64u:d,sealedMaterialDigestB64u:f}}function Js(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{let t=qs(Reflect.get(e,`record`));return Reflect.get(e,`wallet_authority_id`)!==t.authorityId||Reflect.get(e,`wallet_auth_method_id`)!==t.walletAuthMethodId||Reflect.get(e,`activation_id`)!==t.activationId||Reflect.get(e,`key_family`)!==t.keyFamily||Reflect.get(e,`ecdsa_threshold_key_id`)!==(t.keyFamily===`ecdsa_secp256k1`?t.ecdsaThresholdKeyId:void 0)||Reflect.get(e,`sealed_material_b64u`)!==t.sealedMaterialB64u||Reflect.get(e,`sealed_material_digest_b64u`)!==t.sealedMaterialDigestB64u?null:{wallet_authority_id:t.authorityId,wallet_auth_method_id:t.walletAuthMethodId,activation_id:t.activationId,key_family:t.keyFamily,ecdsa_threshold_key_id:t.keyFamily===`ecdsa_secp256k1`?t.ecdsaThresholdKeyId:void 0,sealed_material_b64u:t.sealedMaterialB64u,sealed_material_digest_b64u:t.sealedMaterialDigestB64u,record:t}}catch{return null}}function Ys(e){return{wallet_authority_id:e.authorityId,wallet_auth_method_id:e.walletAuthMethodId,activation_id:e.activationId,key_family:e.keyFamily,ecdsa_threshold_key_id:e.keyFamily===`ecdsa_secp256k1`?e.ecdsaThresholdKeyId:void 0,sealed_material_b64u:e.sealedMaterialB64u,sealed_material_digest_b64u:e.sealedMaterialDigestB64u,record:e}}function Xs(t){if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`export root record must be an object`);if(!Ns(t,[`kind`,`authorityId`,`walletAuthMethodId`,`walletKeyId`,`envelope`]))throw Error(`export root record fields are invalid`);if(Reflect.get(t,`kind`)!==`wallet_authority_export_root_v1`)throw Error(`export root record kind is invalid`);let r=Y(e(Reflect.get(t,`walletKeyId`)),`walletKeyId`),i=be(Reflect.get(t,`envelope`));if(i.binding.kind!==`ed25519_yao_client_root_v1`||i.binding.walletKeyId!==r)throw Error(`export root envelope does not match walletKeyId`);return{kind:`wallet_authority_export_root_v1`,authorityId:Y(o(Reflect.get(t,`authorityId`)),`authorityId`),walletAuthMethodId:Y(n(Reflect.get(t,`walletAuthMethodId`)),`walletAuthMethodId`),walletKeyId:r,envelope:i}}function Zs(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{let t=Xs(Reflect.get(e,`record`));return Reflect.get(e,`wallet_authority_id`)!==t.authorityId||Reflect.get(e,`wallet_auth_method_id`)!==t.walletAuthMethodId||Reflect.get(e,`wallet_key_id`)!==t.walletKeyId||Reflect.get(e,`sealed_root_b64u`)!==t.envelope.sealedCustodySecretB64u||Reflect.get(e,`sealed_root_digest_b64u`)!==t.envelope.ciphertextDigestB64u?null:{wallet_authority_id:t.authorityId,wallet_auth_method_id:t.walletAuthMethodId,wallet_key_id:t.walletKeyId,sealed_root_b64u:t.envelope.sealedCustodySecretB64u,sealed_root_digest_b64u:t.envelope.ciphertextDigestB64u,record:t}}catch{return null}}function Qs(e){return{wallet_authority_id:e.authorityId,wallet_auth_method_id:e.walletAuthMethodId,wallet_key_id:e.walletKeyId,sealed_root_b64u:e.envelope.sealedCustodySecretB64u,sealed_root_digest_b64u:e.envelope.ciphertextDigestB64u,record:e}}function $s(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{let t=ve(Reflect.get(e,`record`));return Reflect.get(e,`authority_id`)!==t.authorityId||Reflect.get(e,`wallet_id`)!==t.walletId||Reflect.get(e,`wallet_auth_method_id`)!==t.authMethodId||Reflect.get(e,`device_id`)!==t.deviceId||Reflect.get(e,`package_set_digest_b64u`)!==t.packageSetDigestB64u||Reflect.get(e,`installed_at_ms`)!==t.installedAtMs?null:{authority_id:t.authorityId,wallet_id:t.walletId,wallet_auth_method_id:t.authMethodId,device_id:t.deviceId,package_set_digest_b64u:t.packageSetDigestB64u,installed_at_ms:t.installedAtMs,record:t}}catch{return null}}function ec(e){return{authority_id:e.authorityId,wallet_id:e.walletId,wallet_auth_method_id:e.authMethodId,device_id:e.deviceId,package_set_digest_b64u:e.packageSetDigestB64u,installed_at_ms:e.installedAtMs,record:e}}function tc(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`wallet selection record must be an object`);if(!Ns(e,[`kind`,`walletId`,`walletAuthMethodId`,`lockGeneration`,`lockState`,`updatedAtMs`]))throw Error(`wallet selection record fields are invalid`);if(Reflect.get(e,`kind`)!==`wallet_selection_v1`)throw Error(`wallet selection record kind is invalid`);let t=Reflect.get(e,`lockState`);if(t!==`locked`&&t!==`unlocked`)throw Error(`wallet selection lockState is invalid`);return{kind:`wallet_selection_v1`,walletId:Y(p(Reflect.get(e,`walletId`)),`walletId`),walletAuthMethodId:Y(n(Reflect.get(e,`walletAuthMethodId`)),`walletAuthMethodId`),lockGeneration:Fs(Reflect.get(e,`lockGeneration`),`lockGeneration`),lockState:t,updatedAtMs:Fs(Reflect.get(e,`updatedAtMs`),`updatedAtMs`)}}function Q(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{let t=tc(Reflect.get(e,`record`));return Reflect.get(e,`wallet_id`)!==t.walletId||Reflect.get(e,`wallet_auth_method_id`)!==t.walletAuthMethodId||Reflect.get(e,`lock_generation`)!==t.lockGeneration||Reflect.get(e,`lock_state`)!==t.lockState||Reflect.get(e,`updated_at_ms`)!==t.updatedAtMs?null:{wallet_id:t.walletId,wallet_auth_method_id:t.walletAuthMethodId,lock_generation:t.lockGeneration,lock_state:t.lockState,updated_at_ms:t.updatedAtMs,record:t}}catch{return null}}function nc(e){return{wallet_id:e.walletId,wallet_auth_method_id:e.walletAuthMethodId,lock_generation:e.lockGeneration,lock_state:e.lockState,updated_at_ms:e.updatedAtMs,record:e}}function rc(e){if(e.keyFamilies.length===1&&e.keyFamilies[0]===`ed25519`&&e.ed25519)return[{keyFamily:`ed25519`,materialActivation:e.ed25519.materialActivation}];if(e.keyFamilies.length===1&&e.keyFamilies[0]===`ecdsa_secp256k1`&&e.ecdsa)return[{keyFamily:`ecdsa_secp256k1`,materialActivation:e.ecdsa.materialActivation}];if(e.keyFamilies.length===2&&e.ed25519&&e.ecdsa)return[{keyFamily:`ed25519`,materialActivation:e.ed25519.materialActivation},{keyFamily:`ecdsa_secp256k1`,materialActivation:e.ecdsa.materialActivation}];throw Error(`wallet signer activation families are invalid`)}function ic(e){if(e.keyFamilies.length===1&&e.keyFamilies[0]===`ed25519`||e.keyFamilies.length===2)return e.ed25519?e.ed25519.signer.walletKeyId:null;throw Error(`wallet signer activation families are invalid`)}function ac(e){return e.keyFamilies.length===2||e.keyFamilies[0]===`ed25519`}function oc(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}function sc(e,t){if(e.kind!==t.kind||e.walletAuthMethodId!==t.walletAuthMethodId||e.verificationDigestB64u!==t.verificationDigestB64u)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u;case`email_otp`:return t.kind===`email_otp`&&e.emailHashHex===t.emailHashHex&&e.registrationAuthorityId===t.registrationAuthorityId;default:return G(e)}}function cc(e,t){if(t.kind!==e.kind||e.authorityId!==t.authorityId||e.walletAuthMethodId!==t.walletAuthMethodId||e.activationId!==t.activationId||!d(e.materialActivation,t.materialActivation)||e.sealedMaterialB64u!==t.sealedMaterialB64u||e.sealedMaterialDigestB64u!==t.sealedMaterialDigestB64u||e.packageSetDigestB64u!==t.packageSetDigestB64u||!sc(e.targetFactor,t.targetFactor))return!1;switch(e.keyFamily){case`ed25519`:return t.keyFamily===`ed25519`;case`ecdsa_secp256k1`:return t.keyFamily===`ecdsa_secp256k1`&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId;default:return G(e)}}function lc(e,t){if(e.state!==t.state)return!1;switch(e.state){case`active`:return t.state===`active`&&e.activatedAtMs===t.activatedAtMs;case`retired`:return t.state===`retired`&&e.activatedAtMs===t.activatedAtMs&&e.retiredAtMs===t.retiredAtMs;case`revoked`:return t.state===`revoked`&&e.activatedAtMs===t.activatedAtMs&&e.revokedAtMs===t.revokedAtMs;default:return G(e)}}function uc(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u&&e.kekVersion===t.kekVersion;case`email_otp`:return t.kind===`email_otp`&&e.enrollmentId===t.enrollmentId&&e.enrollmentSealKeyVersion===t.enrollmentSealKeyVersion&&e.kekVersion===t.kekVersion;case`voiceid`:return t.kind===`voiceid`&&e.deviceKeyId===t.deviceKeyId&&e.kekVersion===t.kekVersion;default:return G(e)}}function dc(e,t){return e.kind!==t.kind||e.envelopeId!==t.envelopeId||e.walletId!==t.walletId||!ye(e.ownership,t.ownership)||e.envelopeVersion!==t.envelopeVersion||e.envelopeRevision!==t.envelopeRevision||e.nonceB64u!==t.nonceB64u||e.sealedCustodySecretB64u!==t.sealedCustodySecretB64u||e.ciphertextDigestB64u!==t.ciphertextDigestB64u||e.aadHashB64u!==t.aadHashB64u||!lc(e.lifecycle,t.lifecycle)||e.createdAtMs!==t.createdAtMs||e.updatedAtMs!==t.updatedAtMs?!1:e.binding.kind===`ed25519_yao_client_root_v1`&&t.binding.kind===`ed25519_yao_client_root_v1`&&e.binding.linkSessionId===t.binding.linkSessionId&&e.binding.walletKeyId===t.binding.walletKeyId&&e.binding.targetFactor.kind===t.binding.targetFactor.kind&&e.binding.applicationBindingDigestB64u===t.binding.applicationBindingDigestB64u&&e.binding.registeredPublicKeyB64u===t.binding.registeredPublicKeyB64u&&e.binding.enrollmentId===t.binding.enrollmentId&&e.binding.deviceId===t.binding.deviceId&&e.binding.revocationEpoch===t.binding.revocationEpoch&&uc(e.factor,t.factor)}function fc(e,t){return oc(Ge(e),Ge(t))}function pc(e,t){return ae({kind:`delegated_wallet_authority_v1`,permissions:e.permissions},{kind:`delegated_wallet_authority_v1`,permissions:t.permissions})}function mc(e,t){if(e.kind!==t.kind)return!1;switch(e.kind){case`wallet_registration`:return!0;case`device_link`:return t.kind===`device_link`&&e.enrollmentId===t.enrollmentId&&e.sourceAuthorityId===t.sourceAuthorityId&&e.linkSessionId===t.linkSessionId;case`wallet_recovery`:return t.kind===`wallet_recovery`&&e.recoveryOperationId===t.recoveryOperationId&&e.continuityAuthorityId===t.continuityAuthorityId;default:return G(e)}}function hc(e,t){if(e.state!==t.state)return!1;switch(e.state){case`pending_local_install`:return t.state===`pending_local_install`&&e.localInstallPackageSetDigestB64u===t.localInstallPackageSetDigestB64u;case`active`:return t.state===`active`&&e.activatedAtMs===t.activatedAtMs;case`revoked`:return t.state===`revoked`&&e.activatedAtMs===t.activatedAtMs&&e.revokedAtMs===t.revokedAtMs}return G(e)}function gc(e,t){return e.kind===t.kind&&e.authorityId===t.authorityId&&e.walletId===t.walletId&&e.principal.kind===t.principal.kind&&e.principal.deviceId===t.principal.deviceId&&mc(e.provenance,t.provenance)&&pc(e,t)&&hc(e,t)&&e.revocationEpoch===t.revocationEpoch&&e.createdAtMs===t.createdAtMs&&e.updatedAtMs===t.updatedAtMs&&e.signerActivationSetDigestB64u===t.signerActivationSetDigestB64u&&e.authorityDigestB64u===t.authorityDigestB64u&&fc(e.signerActivations,t.signerActivations)}function _c(e,t){return e.kind===t.kind&&e.authorityId===t.authorityId&&e.walletId===t.walletId&&e.principal.kind===t.principal.kind&&e.principal.deviceId===t.principal.deviceId&&mc(e.provenance,t.provenance)&&pc(e,t)&&fc(e.signerActivations,t.signerActivations)&&e.signerActivationSetDigestB64u===t.signerActivationSetDigestB64u&&e.revocationEpoch===t.revocationEpoch&&e.createdAtMs===t.createdAtMs}function vc(e,t){if(e.version!==t.version||e.walletAuthMethodId!==t.walletAuthMethodId||e.walletId!==t.walletId||e.walletAuthorityId!==t.walletAuthorityId||e.createdAtMs!==t.createdAtMs||e.updatedAtMs!==t.updatedAtMs||e.kind!==t.kind||e.status!==t.status)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u&&e.credentialPublicKeyB64u===t.credentialPublicKeyB64u&&e.counter===t.counter&&(e.status===`pending_local_install`||e.activatedAtMs===t.activatedAtMs)&&(e.status!==`revoked`||e.revokedAtMs===t.revokedAtMs);case`email_otp`:return t.kind===`email_otp`&&e.emailHashHex===t.emailHashHex&&e.registrationAuthorityId===t.registrationAuthorityId&&(e.status===`pending_local_install`||e.activatedAtMs===t.activatedAtMs)&&(e.status!==`revoked`||e.revokedAtMs===t.revokedAtMs);case`voiceid`:return t.kind===`voiceid`&&e.deviceKeyId===t.deviceKeyId&&e.devicePublicKeyB64u===t.devicePublicKeyB64u&&(e.status===`pending_local_install`||e.activatedAtMs===t.activatedAtMs)&&(e.status!==`revoked`||e.revokedAtMs===t.revokedAtMs)}return G(e)}function yc(e,t){if(e.version!==t.version||e.walletAuthMethodId!==t.walletAuthMethodId||e.walletId!==t.walletId||e.walletAuthorityId!==t.walletAuthorityId||e.kind!==t.kind||e.createdAtMs!==t.createdAtMs)return!1;switch(e.kind){case`passkey`:return t.kind===`passkey`&&e.rpId===t.rpId&&e.credentialIdB64u===t.credentialIdB64u&&e.credentialPublicKeyB64u===t.credentialPublicKeyB64u&&e.counter===t.counter;case`email_otp`:return t.kind===`email_otp`&&e.emailHashHex===t.emailHashHex&&e.registrationAuthorityId===t.registrationAuthorityId;case`voiceid`:return t.kind===`voiceid`&&e.deviceKeyId===t.deviceKeyId&&e.devicePublicKeyB64u===t.devicePublicKeyB64u}return G(e)}function bc(e,t){switch(e.kind){case`wallet_authority_signer_material_v1`:if(t.kind!==e.kind||e.authorityId!==t.authorityId||e.walletAuthMethodId!==t.walletAuthMethodId||e.activationId!==t.activationId||!d(e.materialActivation,t.materialActivation)||e.sealedMaterialB64u!==t.sealedMaterialB64u||e.sealedMaterialDigestB64u!==t.sealedMaterialDigestB64u)return!1;switch(e.keyFamily){case`ed25519`:return t.keyFamily===`ed25519`;case`ecdsa_secp256k1`:return t.keyFamily===`ecdsa_secp256k1`&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId;default:return G(e)}case`wallet_authority_linked_signer_material_v1`:return t.kind===`wallet_authority_linked_signer_material_v1`&&cc(e,t);default:return G(e)}}function xc(e,t){return e.kind===t.kind&&e.authorityId===t.authorityId&&e.walletAuthMethodId===t.walletAuthMethodId&&e.walletKeyId===t.walletKeyId&&dc(e.envelope,t.envelope)}function Sc(e,t){return e.kind===t.kind&&e.authorityId===t.authorityId&&e.walletId===t.walletId&&e.authMethodId===t.authMethodId&&e.deviceId===t.deviceId&&e.packageSetDigestB64u===t.packageSetDigestB64u&&fc(e.installedActivationRefs,t.installedActivationRefs)&&e.installedRecordSetDigestB64u===t.installedRecordSetDigestB64u&&e.targetFactorVerificationDigestB64u===t.targetFactorVerificationDigestB64u&&e.installedAtMs===t.installedAtMs}function Cc(e,t){if(e.kind!==t.kind||e.walletId!==t.walletId||e.authorityId!==t.authorityId||e.authMethodId!==t.authMethodId||e.authorizationId!==t.authorizationId||e.quotaId!==t.quotaId||e.authorityDigestB64u!==t.authorityDigestB64u||e.authorityRevocationEpoch!==t.authorityRevocationEpoch||e.issuedAtMs!==t.issuedAtMs||e.expiresAtMs!==t.expiresAtMs||e.capabilitySubjects.length!==t.capabilitySubjects.length)return!1;for(let n=0;n<e.capabilitySubjects.length;n+=1){let r=e.capabilitySubjects[n],i=t.capabilitySubjects[n];if(r.kind!==i.kind)return!1;if(r.kind===`link_devices`||r.kind===`revoke_devices`){if(i.kind!==r.kind)return!1;continue}if(i.kind!==r.kind||r.keyFamily!==i.keyFamily||!d(r.materialActivation,i.materialActivation))return!1}return!0}function wc(e){return e instanceof Error?e.message:`local authority installation input is invalid`}function Tc(e){let t=Cs(e.localAuthMethod);if(t.status!==`active`||t.record.localStatus!==`synced`)throw Error(`local Email OTP auth method must be active and synced`);if(t.record.walletId!==e.authority.walletId||t.record.emailHashHex!==e.authMethod.emailHashHex||t.record.registrationAuthorityId!==e.authMethod.registrationAuthorityId||t.record.authority.walletId!==e.authority.walletId||t.record.authority.bindingId!==e.authMethod.walletAuthMethodId)throw Error(`local Email OTP auth method does not match authMethod`);return t.record}function Ec(e){try{let t=Y(k(e.authority),`authority`);if(t.state!==`pending_local_install`)throw Error(`authority must be pending_local_install`);let n=A(e.authMethod);if(!n||n.status!==`pending_local_install`)throw Error(`authMethod must be a pending_local_install V2 record`);let r=c(e.profile.profileId||``);if(!r||r!==String(t.walletId))throw Error(`profile identity does not match authority`);let i=e.profile.defaultSignerSlot===void 0?1:Fs(e.profile.defaultSignerSlot,`profile.defaultSignerSlot`);if(i<1)throw Error(`profile.defaultSignerSlot must be a positive safe integer`);let a={profileId:r,defaultSignerSlot:i,...e.profile.passkeyCredential?{passkeyCredential:e.profile.passkeyCredential}:{},...e.profile.preferences?{preferences:e.profile.preferences}:{},...e.profile.nearProvisioning?{nearProvisioning:e.profile.nearProvisioning}:{}},o=e.authenticator===null?null:ys(e.authenticator),s=null;if(n.kind===`voiceid`)throw Error(`Linked-device VoiceID installation requires its own custody flow`);if(n.kind===`passkey`){if(e.localAuthMethod!==null)throw Error(`Passkey installation cannot include a local Email OTP auth method`);let t=a.passkeyCredential;if(!t||t.id!==n.credentialIdB64u||t.rawId!==n.credentialIdB64u)throw Error(`profile passkey credential does not match authMethod`);if(!o||o.profileId!==r||o.signerSlot!==i||o.credentialId!==n.credentialIdB64u||C(o.credentialPublicKey)!==n.credentialPublicKeyB64u)throw Error(`profile authenticator does not match authMethod`)}else{if(o!==null||a.passkeyCredential!==void 0)throw Error(`Email OTP installation cannot include passkey profile records`);if(e.localAuthMethod===null)throw Error(`Email OTP installation requires a local auth method`);s=Tc({localAuthMethod:e.localAuthMethod,authority:t,authMethod:n})}if(!Array.isArray(e.signerMaterials))throw Error(`signerMaterials must be an array`);let l=[];for(let t of e.signerMaterials)l.push(qs(t));let u=e.exportRoot===null?null:Xs(e.exportRoot),f=ve(e.receipt),p=Fs(e.expectedLockGeneration,`expectedLockGeneration`);if(n.walletId!==t.walletId||n.walletAuthorityId!==t.authorityId||f.walletId!==t.walletId||f.authorityId!==t.authorityId||f.authMethodId!==n.walletAuthMethodId||f.deviceId!==t.principal.deviceId||f.packageSetDigestB64u!==t.localInstallPackageSetDigestB64u)throw Error(`authority, authMethod, and receipt identities do not match`);if(!fc(f.installedActivationRefs,t.signerActivations))throw Error(`receipt signer activations do not match authority`);let m=rc(t.signerActivations);if(l.length!==m.length)throw Error(`signer material records do not match authority signer families`);for(let e=0;e<m.length;e+=1){let r=l[e],i=m[e];if(r.authorityId!==t.authorityId||r.walletAuthMethodId!==n.walletAuthMethodId||r.keyFamily!==i.keyFamily||!d(r.materialActivation,i.materialActivation))throw Error(`signer material record does not match authority activation`)}if((ac(t.signerActivations)&&t.permissions.includes(`export_keys`))!==(u!==null))throw Error(`Ed25519 export root presence does not match authority permissions`);if(u){let e=ic(t.signerActivations);if(e===null||u.authorityId!==t.authorityId||u.walletAuthMethodId!==n.walletAuthMethodId||u.walletKeyId!==e||u.envelope.walletId!==t.walletId||u.envelope.binding.kind!==`ed25519_yao_client_root_v1`||u.envelope.binding.walletKeyId!==e||u.envelope.binding.registeredPublicKeyB64u!==t.signerActivations.ed25519?.signer.registeredPublicKeyB64u||t.principal.kind!==`owner_device`||String(u.envelope.binding.deviceId)!==String(t.principal.deviceId)||u.envelope.lifecycle.state!==`active`||!Co(n,u.envelope))throw Error(`export root does not match the Ed25519 authority activation`)}return{ok:!0,value:{authority:t,authMethod:n,profile:a,authenticator:o,localAuthMethod:s,signerMaterials:l,exportRoot:u,receipt:f,expectedLockGeneration:p}}}catch(e){return{ok:!1,error:wc(e)}}}function Dc(e){return[`passkey`,e.rp_id,e.credential_id_b64u].join(`\0`)}function Oc(e){let t=e.authenticators.map(e=>ys(e)),n=new Map,r=new Map;if(e.initialAuthMethod.kind===`passkey`){let i=t.find(t=>t.profileId===e.initialAuthMethod.walletId&&t.credentialId===e.initialAuthMethod.credentialIdB64u);if(!i)throw Error(`[SeamsWalletDB] passkey registration finalize requires matching authenticator material`);let a=Ss({binding:e.initialAuthMethod,authenticator:i});n.set(a.wallet_auth_method_id,a),r.set(Dc(a),a)}else{let t=Cs(e.initialAuthMethod);n.set(t.wallet_auth_method_id,t)}for(let i of t){if(e.initialAuthMethod.kind===`passkey`&&i.profileId===e.initialAuthMethod.walletId&&i.credentialId===e.initialAuthMethod.credentialIdB64u){let t=Ss({binding:e.initialAuthMethod,authenticator:i});n.set(t.wallet_auth_method_id,t),r.set(Dc(t),t);continue}let t=Ts(i),a=Dc(t),o=r.get(a);if(o){if(o.credential_public_key_b64u!==t.credential_public_key_b64u)throw Error(`[SeamsWalletDB] duplicate passkey credential has conflicting public key`);o.wallet_auth_method_id===t.wallet_auth_method_id&&(n.set(t.wallet_auth_method_id,t),r.set(a,t));continue}n.set(t.wallet_auth_method_id,t),r.set(a,t)}return[...n.values()]}async function kc(e){let t=e.nextRow;if(t.kind!==ge.thresholdEcdsa||t.status===`revoked`||!t.key_handle||!t.ecdsa_threshold_key_id)return;let n=await e.store.index(T.walletId).getAll(t.wallet_id),r=new Set;for(let e of n){if(typeof e!=`object`||!e||Array.isArray(e)||!W(e))continue;let n=c(Reflect.get(e,`wallet_signer_id`)||``);!n||n===t.wallet_signer_id||Reflect.get(e,`kind`)!==t.kind||Reflect.get(e,`chain_target_key`)!==t.chain_target_key||(Reflect.get(e,`key_handle`)===t.key_handle||Reflect.get(e,`ecdsa_threshold_key_id`)===t.ecdsa_threshold_key_id)&&r.add(n)}for(let t of r)await e.store.delete(t)}function Ac(e){return[e.walletSignerId,e.keyKind].join(`\0`)}function jc(e){return ho({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId})}function Mc(e){let t=c(e.profileId||``),n=c(e.signerId||``),r=c(e.wrapKeySalt||``),i=c(e.chainIdKey||``).toLowerCase(),a=O(e.accountAddress),o=c(e.keyKind||``),s=c(e.algorithm||``),l=c(e.publicKey||``);if(!t)throw Error(`[SeamsWalletDB] Missing profileId for key material record`);if(!Number.isSafeInteger(e.signerSlot)||e.signerSlot<1)throw Error(`[SeamsWalletDB] Invalid signerSlot for key material record`);if(!i)throw Error(`[SeamsWalletDB] Missing chainIdKey for key material record`);if(!a)throw Error(`[SeamsWalletDB] Missing accountAddress for key material record`);if(!n)throw Error(`[SeamsWalletDB] Missing signerId for key material record`);if(!o)throw Error(`[SeamsWalletDB] Missing keyKind for key material record`);if(!s)throw Error(`[SeamsWalletDB] Missing algorithm for key material record`);if(!l)throw Error(`[SeamsWalletDB] Missing publicKey for key material record`);if(typeof e.timestamp!=`number`)throw Error(`[SeamsWalletDB] Missing timestamp for key material record`);if(!Number.isSafeInteger(e.schemaVersion)||e.schemaVersion<1)throw Error(`[SeamsWalletDB] Invalid schemaVersion for key material record`);let u=je({profileId:t,signerSlot:e.signerSlot,chainIdKey:i,accountAddress:a,keyKind:o,schemaVersion:e.schemaVersion,signerId:n}),d=ke(e.payloadEnvelope,u,`${t}/${e.signerSlot}/${i}/${o}`),f=Ae(e.payload),p={profileId:t,signerSlot:e.signerSlot,chainIdKey:i,accountAddress:a,keyKind:o,algorithm:s,publicKey:l,signerId:n,...r?{wrapKeySalt:r}:{},...f?{payload:f}:{},...d?{payloadEnvelope:d}:{},timestamp:e.timestamp,schemaVersion:e.schemaVersion},m=jc(p),h=Ee({chainIdKey:i,accountAddress:a});return{key_material_id:Ac({walletSignerId:m,keyKind:o}),wallet_id:t,wallet_signer_id:m,chain_target_key:h,key_handle:n,public_key:l,updated_at:e.timestamp,record:p}}function Nc(e){return[c(e.profileId||``),D(e.chainIdKey),O(e.accountAddress),c(e.signerId||``),String(Number(e.signerSlot))].join(`\0`)}function Pc(e){let t=new Set(e.signers.map(e=>Nc({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot}))),n=new Set(e.keyMaterials.filter(e=>e.keyKind===`threshold_share_v1`).map(e=>Nc({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot}))),r=e.signers.find(e=>e.status===`active`&&!n.has(Nc({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot})));if(r)throw Error(`[SeamsWalletDB] active signer ${r.signerId} requires matching threshold key material`);let i=e.keyMaterials.find(e=>e.keyKind===`threshold_share_v1`&&!t.has(Nc({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot})));if(i)throw Error(`[SeamsWalletDB] threshold key material for signer ${i.signerId} has no matching signer activation`)}function Fc(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=E(Reflect.get(e,`profileId`)),n=Reflect.get(e,`signerSlot`),r=D(Reflect.get(e,`chainIdKey`)),i=O(Reflect.get(e,`accountAddress`)),a=E(Reflect.get(e,`keyKind`)),o=E(Reflect.get(e,`algorithm`)),s=E(Reflect.get(e,`publicKey`)),c=E(Reflect.get(e,`signerId`)),l=Reflect.get(e,`timestamp`),u=Reflect.get(e,`schemaVersion`);if(!t||!Number.isSafeInteger(n)||Number(n)<1||!r||!i||!a||!o||!s||!c||typeof l!=`number`||!Number.isSafeInteger(u)||Number(u)<1)return null;let d=Reflect.get(e,`wrapKeySalt`);if(d!==void 0&&typeof d!=`string`)return null;let f=Reflect.get(e,`payload`),p=Ae(f);if(f!==void 0&&(typeof f!=`object`||!f||Array.isArray(f)))return null;let m=je({profileId:t,signerSlot:Number(n),chainIdKey:r,accountAddress:i,keyKind:a,schemaVersion:Number(u),signerId:c}),h;try{h=ke(Reflect.get(e,`payloadEnvelope`),m,`${t}/${n}/${r}/${a}`)}catch{return null}return{profileId:t,signerSlot:Number(n),chainIdKey:r,accountAddress:i,keyKind:a,algorithm:o,publicKey:s,signerId:c,...d===void 0?{}:{wrapKeySalt:d},...p===void 0?{}:{payload:p},...h===void 0?{}:{payloadEnvelope:h},timestamp:l,schemaVersion:Number(u)}}function Ic(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Fc(Reflect.get(e,`record`));return!t||Reflect.get(e,`key_material_id`)!==Ac({walletSignerId:jc(t),keyKind:t.keyKind})||Reflect.get(e,`wallet_id`)!==t.profileId||Reflect.get(e,`wallet_signer_id`)!==jc(t)||Reflect.get(e,`chain_target_key`)!==Ee({chainIdKey:t.chainIdKey,accountAddress:t.accountAddress})||Reflect.get(e,`key_handle`)!==c(t.signerId||``)||Reflect.get(e,`public_key`)!==t.publicKey||Reflect.get(e,`updated_at`)!==t.timestamp?null:t}function Lc(e){return Nc({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot})}function Rc(e){return Nc({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot})}function zc(e){let t=new Set;for(let n of e.signers){let e=c(n.profileId||``);e&&t.add(e)}for(let n of e.keyMaterials){let e=c(n.profileId||``);e&&t.add(e)}return[...t]}async function Bc(e,t){let n=e.store(w.walletSigners),r=[];for(let e of t){let t=await n.index(T.walletId).getAll(e);for(let e of t){let t=W(e);t?.status===`active`&&r.push(t)}}return r}async function Vc(e,t){let n=e.store(w.keyMaterial),r=[];for(let e of t){let t=await n.index(T.walletId).getAll(e);for(let e of t){let t=Ic(e);t?.keyKind===`threshold_share_v1`&&r.push(t)}}return r}function Hc(e){let t=new Map;for(let n of e.existing)t.set(Ac({walletSignerId:jc(n),keyKind:n.keyKind}),n);for(let n of e.incoming)t.set(Ac({walletSignerId:jc(n),keyKind:n.keyKind}),n);return[...t.values()]}async function Uc(e){let t=zc({signers:e.signers,keyMaterials:e.keyMaterials});if(t.length===0)return;let n=await Bc(e.ctx,t),r=new Set(n.map(Lc));Pc({signers:n,keyMaterials:Hc({existing:(await Vc(e.ctx,t)).filter(e=>r.has(Rc(e))),incoming:e.keyMaterials})})}function Wc(e){if(e.keyKind!==`threshold_share_v1`||e.algorithm!==`ed25519`)return!0;let t=e.payload||{};return!!c(t.relayerKeyId||``)&&!!c(t.keyVersion||``)}function Gc(e){let t=new Set(e.activeSigners.map(Lc));return e.matches.filter(e=>t.has(Rc(e))).find(Wc)||e.matches.find(Wc)||[...e.matches].sort((e,t)=>t.timestamp-e.timestamp)[0]||null}var Kc=class{constructor(e){this.manager=e}async installLocalAuthority(e){let t=Ec(e);return t.ok?await Ie(t.value.authority)?this.manager.runTransaction([w.appState,w.wallets,w.walletAuthMethods,w.walletAuthorities,w.walletAuthoritySignerMaterials,w.walletAuthorityExportRoots,w.walletAuthorityInstallationReceipts,w.walletSelections],`readwrite`,this.installLocalAuthorityInTransaction.bind(this,t.value)):{kind:`integrity_error`,reason:`authority digest does not match canonical encoding`}:{kind:`integrity_error`,reason:t.error}}async finalizeLocalAuthorityActivation(e){let t=k(e.authority);if(!t.ok||t.value.state!==`active`)throw Error(`active WalletAuthorityV1 is invalid`);let n=A(e.authMethod);if(!n||n.status!==`active`)throw Error(`active WalletAuthMethodRecordV2 is invalid`);let r=En(wn(e.walletSession,e.operationCredential))?.record??null;if(!r)throw Error(`active Wallet Session is invalid`);let i=Fs(e.expectedLockGeneration,`expectedLockGeneration`);if(n.walletId!==t.value.walletId||n.walletAuthorityId!==t.value.authorityId||r.walletId!==t.value.walletId||r.authorityId!==t.value.authorityId||r.authMethodId!==n.walletAuthMethodId||r.authorityDigestB64u!==t.value.authorityDigestB64u||r.authorityRevocationEpoch!==t.value.revocationEpoch)throw Error(`active authority, auth method, and Wallet Session identities differ`);return await this.manager.runTransaction([w.appState,w.wallets,w.walletAuthorities,w.walletAuthMethods,w.walletAuthorityInstallationReceipts,w.walletSelections,w.walletSessionAuthorizations],`readwrite`,this.finalizeLocalAuthorityActivationInTransaction.bind(this,{authority:t.value,authMethod:n,walletSession:r,operationCredential:e.operationCredential,expectedLockGeneration:i}))}async publishLocalAuthorityActivation(e){let t=k(e.authority);if(!t.ok||t.value.state!==`active`)throw Error(`active WalletAuthorityV1 is invalid`);let n=A(e.authMethod);if(!n||n.status!==`active`)throw Error(`active WalletAuthMethodRecordV2 is invalid`);let r=Fs(e.expectedLockGeneration,`expectedLockGeneration`);if(n.walletId!==t.value.walletId||n.walletAuthorityId!==t.value.authorityId)throw Error(`active authority and auth method identities differ`);if(!await Ie(t.value))throw Error(`active WalletAuthorityV1 digest is invalid`);return await this.manager.runTransaction([w.appState,w.wallets,w.walletAuthorities,w.walletAuthMethods,w.walletAuthorityInstallationReceipts,w.walletSelections],`readwrite`,this.publishLocalAuthorityActivationInTransaction.bind(this,{authority:t.value,authMethod:n,expectedLockGeneration:r}))}async advanceWalletLockGeneration(e){let t=Y(p(e.walletId),`walletId`),n=Fs(e.lockedAtMs,`lockedAtMs`);return this.manager.runTransaction([w.walletSelections],`readwrite`,this.advanceWalletLockGenerationInTransaction.bind(this,{walletId:t,lockedAtMs:n}))}async markWalletSelectionUnlocked(e){let t=Y(p(e.walletId),`walletId`),r=Y(n(e.walletAuthMethodId),`walletAuthMethodId`),i=Fs(e.unlockedAtMs,`unlockedAtMs`);await this.manager.runTransaction([w.walletSelections,w.walletAuthMethods],`readwrite`,this.markWalletSelectionUnlockedInTransaction.bind(this,{walletId:t,walletAuthMethodId:r,unlockedAtMs:i,expectedLockGeneration:null}))}async markWalletSelectionUnlockedAtGeneration(e){await this.manager.runTransaction([w.walletSelections,w.walletAuthMethods],`readwrite`,this.markWalletSelectionUnlockedInTransaction.bind(this,e))}async persistRecoveredWalletAuthority(e){let t=Y(k(e.authority),`authority`),n=A(e.authMethod),r=Fs(e.recoveredAtMs,`recoveredAtMs`);if(t.state!==`active`||!ze(t)||!n||n.status!==`active`||n.walletId!==t.walletId||n.walletAuthorityId!==t.authorityId)throw Error(`recovered Wallet Authority projection is invalid`);if(!await Ie(t))throw Error(`recovered Wallet Authority digest is invalid`);await this.manager.runTransaction([w.walletAuthorities,w.walletSelections,w.walletAuthMethods],`readwrite`,this.persistRecoveredWalletAuthorityInTransaction.bind(this,{authority:t,authMethod:n,recoveredAtMs:r}))}async getLocalAuthorityInstallationReceipt(e){let t=o(e);return t.ok&&$s(await(await this.manager.getDB()).get(w.walletAuthorityInstallationReceipts,t.value))?.record||null}async finalizeLocalAuthorityActivationInTransaction(e,t){let n=t.store(w.appState),r=t.store(w.walletAuthorities),i=t.store(w.walletAuthMethods),a=t.store(w.walletAuthorityInstallationReceipts),o=t.store(w.walletSelections),s=t.store(w.walletSessionAuthorizations),c=await r.get(e.authority.authorityId),l=await i.get(e.authMethod.walletAuthMethodId),u=await a.get(e.authority.authorityId),d=await s.get(e.operationCredential.walletSessionId),f=await n.get(To(e.authority.authorityId)),p=f===void 0?null:fs(f.value);if(f!==void 0&&!p)throw Error(`local authority profile projection is missing or corrupt`);let m=c===void 0?null:X(c),h=l===void 0?null:Z(l),g=u===void 0?null:$s(u),_=d===void 0?null:En(d),v=_?.record??null;if(!g)throw Error(`local authority installation receipt is missing or corrupt`);if(g.record.authorityId!==e.authority.authorityId||g.record.walletId!==e.authority.walletId||g.record.authMethodId!==e.authMethod.walletAuthMethodId||!fc(g.record.installedActivationRefs,e.authority.signerActivations))throw Error(`local authority installation receipt does not match active authority`);if(!m||!h)throw Error(`pending local authority records are missing`);if(m.record.state===`active`){if(!gc(m.record,e.authority)||h.record.status!==`active`||!vc(h.record,e.authMethod))throw Error(`active local authority replay conflicts with supplied records`);if(p&&await this.publishPendingLocalAuthorityProfileProjectionInTransaction(e.authority,e.authMethod,p,t),!v){let t=await o.get(e.authority.walletId);if(t===void 0)throw Error(`wallet selection is missing`);let n=Q(t);if(!n||n.wallet_id!==e.authority.walletId)throw Error(`wallet selection is corrupt`);return n.lock_generation===e.expectedLockGeneration?n.record.lockState===`locked`?{kind:`wallet_locked`,lockGeneration:n.lock_generation}:(await s.put(wn(e.walletSession,e.operationCredential)),await o.put(nc({kind:`wallet_selection_v1`,walletId:n.record.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,lockGeneration:n.record.lockGeneration,lockState:`unlocked`,updatedAtMs:e.walletSession.issuedAtMs})),{kind:`finalized`}):{kind:`stale_lock_generation`,expectedLockGeneration:e.expectedLockGeneration,actualLockGeneration:n.lock_generation}}if(v.kind!==`active_wallet_session_v1`||!Cc(v,e.walletSession)||_?.operationCredential.token!==e.operationCredential.token)throw Error(`active local authority replay conflicts with supplied Wallet Session`);return await s.put(wn(e.walletSession,e.operationCredential)),{kind:`finalized`}}if(m.record.state!==`pending_local_install`||h.record.status!==`pending_local_install`||!_c(m.record,e.authority)||!yc(h.record,e.authMethod))throw Error(`local authority records are not the expected pending installation`);if(v&&v.kind!==`active_wallet_session_v1`)throw Error(`Wallet Session authorization is not active`);if(v?.kind===`active_wallet_session_v1`&&(!Cc(v,e.walletSession)||_?.operationCredential.token!==e.operationCredential.token))throw Error(`Wallet Session authorization conflicts with finalization`);let y=await o.get(e.authority.walletId);if(y===void 0)throw Error(`wallet selection is missing`);let b=Q(y);if(!b||b.wallet_id!==e.authority.walletId)throw Error(`wallet selection is corrupt`);if(b.lock_generation!==e.expectedLockGeneration)return{kind:`stale_lock_generation`,expectedLockGeneration:e.expectedLockGeneration,actualLockGeneration:b.lock_generation};if(b.record.lockState===`locked`)return{kind:`wallet_locked`,lockGeneration:b.lock_generation};if(!p)throw Error(`local authority profile projection is missing or corrupt`);return await this.publishPendingLocalAuthorityProfileProjectionInTransaction(e.authority,e.authMethod,p,t),await r.put(Ls(e.authority)),await i.put(await Ks(i,e.authMethod)),await s.put(wn(e.walletSession,e.operationCredential)),await o.put(nc({kind:`wallet_selection_v1`,walletId:b.record.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,lockGeneration:b.record.lockGeneration,lockState:`unlocked`,updatedAtMs:e.walletSession.issuedAtMs})),{kind:`finalized`}}async publishPendingLocalAuthorityProfileProjectionInTransaction(e,t,n,r){if(n.authorityId!==e.authorityId||n.walletId!==e.walletId||n.authMethodId!==t.walletAuthMethodId)throw Error(`local authority profile projection identity does not match activation`);if(n.authenticator?.wallet_auth_method_id===t.walletAuthMethodId||n.localAuthMethod?.wallet_auth_method_id===t.walletAuthMethodId)throw Error(`local authority profile projection collides with the V2 auth-method key`);let i=r.store(w.wallets),a=r.store(w.walletAuthMethods),o=await i.get(n.profile.wallet_id),s=o===void 0?null:ps(o);if(o!==void 0&&!s)throw Error(`stored wallet profile is corrupt during authority publication`);if(s&&!Zo(s,n.profile))throw Error(`stored wallet profile changed during authority publication`);await i.put(n.profile);for(let e of[n.authenticator,n.localAuthMethod]){if(!e)continue;let t=await a.get(e.wallet_auth_method_id);if(t!==void 0){let n=J(t);if(!n||!ts(n,e))throw Error(`stored local auth method changed during authority publication`)}await a.put(e)}await a.put(await Ks(a,t)),await r.store(w.appState).delete(To(e.authorityId))}async publishLocalAuthorityActivationInTransaction(e,t){let n=await t.store(w.appState).get(To(e.authority.authorityId)),r=n===void 0?null:fs(n.value);if(n!==void 0&&!r)throw Error(`local authority profile projection is missing or corrupt`);let i=await t.store(w.walletAuthorities).get(e.authority.authorityId),a=await t.store(w.walletAuthMethods).get(e.authMethod.walletAuthMethodId),o=await t.store(w.walletAuthorityInstallationReceipts).get(e.authority.authorityId),s=i===void 0?null:X(i),c=a===void 0?null:Z(a),l=o===void 0?null:$s(o);if(!s||!c||!l)throw Error(`local authority publication prerequisites are missing`);if(l.record.authorityId!==e.authority.authorityId||l.record.walletId!==e.authority.walletId||l.record.authMethodId!==e.authMethod.walletAuthMethodId||!fc(l.record.installedActivationRefs,e.authority.signerActivations))throw Error(`local authority installation receipt does not match publication`);if(s.record.state===`active`){if(!gc(s.record,e.authority)||c.record.status!==`active`||!vc(c.record,e.authMethod))throw Error(`active local authority publication conflicts with stored records`);return r&&await this.publishPendingLocalAuthorityProfileProjectionInTransaction(e.authority,e.authMethod,r,t),{kind:`published`}}if(s.record.state!==`pending_local_install`||c.record.status!==`pending_local_install`||!_c(s.record,e.authority)||!yc(c.record,e.authMethod))throw Error(`local authority records are not the expected pending installation`);let u=await t.store(w.walletSelections).get(e.authority.walletId);if(u===void 0)throw Error(`wallet selection is missing`);let d=Q(u);if(!d||d.wallet_id!==e.authority.walletId)throw Error(`wallet selection is corrupt`);if(d.lock_generation!==e.expectedLockGeneration)return{kind:`stale_lock_generation`,expectedLockGeneration:e.expectedLockGeneration,actualLockGeneration:d.lock_generation};if(d.record.lockState===`locked`)return{kind:`wallet_locked`,lockGeneration:d.lock_generation};if(!r)throw Error(`local authority profile projection is missing or corrupt`);return await this.publishPendingLocalAuthorityProfileProjectionInTransaction(e.authority,e.authMethod,r,t),await t.store(w.walletAuthorities).put(Ls(e.authority)),{kind:`published`}}async advanceWalletLockGenerationInTransaction(e,t){let n=t.store(w.walletSelections),r=await n.get(e.walletId);if(r===void 0)throw Error(`wallet selection is missing`);let i=Q(r);if(!i||i.wallet_id!==e.walletId)throw Error(`wallet selection is corrupt`);if(i.record.lockGeneration>=2**53-1)throw Error(`wallet lock generation cannot advance`);let a=i.record.lockGeneration+1;return await n.put(nc({kind:`wallet_selection_v1`,walletId:i.record.walletId,walletAuthMethodId:i.record.walletAuthMethodId,lockGeneration:a,lockState:`locked`,updatedAtMs:e.lockedAtMs})),a}async assertSelectionMoveBetweenAuthorityMembers(e,t){let n=t.store(w.walletAuthMethods),r=await n.get(e.fromWalletAuthMethodId),i=await n.get(e.toWalletAuthMethodId),a=r===void 0?null:Z(r),o=i===void 0?null:Z(i);if(!a||!o||o.record.status!==`active`||o.record.walletId!==e.walletId||a.record.walletId!==e.walletId||a.record.walletAuthorityId!==o.record.walletAuthorityId)throw Error(`wallet selection is missing or corrupt`)}async markWalletSelectionUnlockedInTransaction(e,t){let n=t.store(w.walletSelections),r=await n.get(e.walletId),i=r===void 0?null:Q(r);if(!i||i.wallet_id!==e.walletId)throw Error(`wallet selection is missing or corrupt`);if(e.expectedLockGeneration!==null&&i.record.lockGeneration!==e.expectedLockGeneration)throw Error(`Wallet lock state changed during unlock.`);i.record.walletAuthMethodId!==e.walletAuthMethodId&&await this.assertSelectionMoveBetweenAuthorityMembers({walletId:e.walletId,fromWalletAuthMethodId:i.record.walletAuthMethodId,toWalletAuthMethodId:e.walletAuthMethodId},t),await n.put(nc({kind:`wallet_selection_v1`,walletId:i.record.walletId,walletAuthMethodId:e.walletAuthMethodId,lockGeneration:i.record.lockGeneration,lockState:`unlocked`,updatedAtMs:e.unlockedAtMs}))}async persistRecoveredWalletAuthorityInTransaction(e,t){let n=t.store(w.walletAuthorities),r=await n.get(e.authority.authorityId),i=r===void 0?null:X(r)?.record;if(r!==void 0&&!i)throw Error(`local Wallet Authority is corrupt`);if(i&&!gc(i,e.authority))throw Error(`recovered Wallet Authority conflicts with local authority`);await n.put(Ls(e.authority));let a=t.store(w.walletAuthMethods);await a.put(await Ks(a,e.authMethod));let o=t.store(w.walletSelections),s=await o.get(e.authority.walletId),c=s===void 0?null:Q(s);if(s!==void 0&&!c)throw Error(`recovered wallet selection is corrupt`);await o.put(nc({kind:`wallet_selection_v1`,walletId:e.authority.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,lockGeneration:c?.record.lockGeneration??0,lockState:`locked`,updatedAtMs:e.recoveredAtMs}))}async installLocalAuthorityInTransaction(e,t){let n=t.store(w.appState),r=await t.store(w.wallets).get(e.profile.profileId),i=r===void 0?null:q(r);if(r!==void 0&&!i)return{kind:`integrity_error`,reason:`wallet profile row is invalid`};let a=t.store(w.walletAuthMethods),o=e.authenticator?Ts(e.authenticator):null,s=e.localAuthMethod?ws(e.localAuthMethod,e.profile.defaultSignerSlot??1):null,c=o?await a.get(o.wallet_auth_method_id):void 0,l=c===void 0?null:J(c),u=e.authenticator?Ts(e.authenticator,l?.kind===`passkey`?l:void 0):null,d=s?await a.get(s.wallet_auth_method_id):void 0,f=d===void 0?null:J(d),p=t.store(w.walletSelections),m=await p.get(e.authority.walletId),h=m===void 0?null:Q(m);if(m!==void 0&&(!h||h.wallet_id!==e.authority.walletId))return{kind:`integrity_error`,reason:`wallet selection row is invalid`};if(h&&h.lock_generation!==e.expectedLockGeneration)return{kind:`stale_lock_generation`,expectedLockGeneration:e.expectedLockGeneration,actualLockGeneration:h.lock_generation};if(!h&&e.expectedLockGeneration!==0)return{kind:`integrity_error`,reason:`initial wallet selection requires lock generation zero`};let g=t.store(w.walletAuthorities),_=t.store(w.walletAuthMethods),v=t.store(w.walletAuthoritySignerMaterials),y=t.store(w.walletAuthorityExportRoots),b=t.store(w.walletAuthorityInstallationReceipts),ee=To(e.authority.authorityId),te=await n.get(ee),x=te===void 0?null:fs(te.value);if(te!==void 0&&!x)return{kind:`integrity_error`,reason:`local authority profile projection is missing or corrupt`};let ne=x??Es({authorityId:e.authority.authorityId,walletId:e.authority.walletId,authMethodId:e.authMethod.walletAuthMethodId,profile:Go(e.profile,i||void 0),authenticator:u,localAuthMethod:s?.kind===`email_otp`?s:null}),re=await g.get(e.authority.authorityId),ie=await _.get(e.authMethod.walletAuthMethodId),ae=[];for(let t of e.signerMaterials)ae.push(await v.get([t.authorityId,t.walletAuthMethodId,t.activationId]));let S=e.exportRoot?await y.get([e.exportRoot.authorityId,e.exportRoot.walletAuthMethodId,e.exportRoot.walletKeyId]):void 0,oe=await b.get(e.receipt.authorityId),se=re===void 0?null:X(re),C=ie===void 0?null:Z(ie),ce=[];for(let e=0;e<ae.length;e+=1){let t=ae[e];ce.push(t===void 0?null:Js(t)?.record||null)}let le=S===void 0?null:Zs(S)?.record||null,ue=oe===void 0?null:$s(oe)?.record||null;if(x&&!Os(x,e))return{kind:`integrity_error`,reason:`local authority profile projection conflicts with replay`};let de=re!==void 0||ie!==void 0||ae.some(Is)||S!==void 0||oe!==void 0||te!==void 0,fe=re!==void 0&&ie!==void 0&&ae.every(Is)&&(e.exportRoot===null?S===void 0:S!==void 0)&&oe!==void 0;if(de){if(!h||!fe||!se||!C||!ue||!x||!Ds(x,ne))return{kind:`integrity_error`,reason:`local authority replay is incomplete or malformed`};if(!gc(se.record,e.authority)||!vc(C.record,e.authMethod)||!Sc(ue,e.receipt))return{kind:`integrity_error`,reason:`local authority replay conflicts with stored records`};if(i&&!Xo(i,x.profile.record)||x.authenticator&&l!==null&&!ts(l,x.authenticator)||x.localAuthMethod&&f!==null&&!ts(f,x.localAuthMethod))return{kind:`integrity_error`,reason:`stored local profile projection conflicts with replay`};for(let t=0;t<e.signerMaterials.length;t+=1){let n=ce[t];if(!n||!bc(n,e.signerMaterials[t]))return{kind:`integrity_error`,reason:`stored signer material conflicts with replay`}}return e.exportRoot&&(!le||!xc(le,e.exportRoot))?{kind:`integrity_error`,reason:`stored export root conflicts with replay`}:(await p.put(nc(Eo(e,h))),{kind:`idempotent_replay`,receipt:ue})}await n.put({key:ee,value:ne}),await g.put(Ls(e.authority)),await _.put(await Ks(_,e.authMethod));for(let t of e.signerMaterials)await v.put(Ys(t));return e.exportRoot&&await y.put(Qs(e.exportRoot)),await b.put(ec(e.receipt)),await p.put(nc(Eo(e,h))),{kind:`installed`,receipt:e.receipt}}async getWalletAuthority(e){let t=o(e);if(!t.ok)return null;let n=X(await(await this.manager.getDB()).get(w.walletAuthorities,t.value));return!n||!await Ie(n.record)?null:n.record}async persistFoundingWalletAuthority(e){let t=Oo(e);await this.manager.runTransaction([w.appState,w.walletAuthorities,w.walletAuthMethods,w.wallets,w.walletSelections],`readwrite`,this.persistFoundingWalletAuthorityInTransaction.bind(this,t,`activate`))}async persistFoundingWalletAuthorityInTransaction(e,t,n){if(t===`preserve`){let t=Q(await n.store(w.walletSelections).get(e.authority.walletId));if(!t||t.record.lockState!==`unlocked`||t.record.walletAuthMethodId!==e.authMethod.walletAuthMethodId)throw Error(`Deferred registration publication was interrupted by wallet lock`)}await n.store(w.walletAuthorities).put(Ls(e.authority));let r=n.store(w.walletAuthMethods);if(await r.put(await Ks(r,e.authMethod)),t!==`preserve`){if(t===`restore_locked`){let t=n.store(w.walletSelections);await t.get(e.authority.walletId)||await t.put(nc({kind:`wallet_selection_v1`,walletId:e.authority.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,lockGeneration:0,lockState:`locked`,updatedAtMs:e.authMethod.activatedAtMs}));return}await n.store(w.walletSelections).put(nc({kind:`wallet_selection_v1`,walletId:e.authority.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,lockGeneration:0,lockState:`unlocked`,updatedAtMs:e.authMethod.activatedAtMs}))}}async getWalletAuthMethodV2(e){let t=n(e);return t.ok&&Z(await(await this.manager.getDB()).get(w.walletAuthMethods,t.value))?.record||null}async listWalletSelections(){return(await(await this.manager.getDB()).transaction(w.walletSelections,`readonly`).store.getAll()).flatMap(e=>{let t=Q(e);return t?[t.record]:[]})}async listWalletSelectionWalletIds(){return(await(await this.manager.getDB()).transaction(w.walletSelections,`readonly`).store.getAllKeys()).flatMap(e=>{let t=p(e);return t.ok?[t.value]:[]})}async listWalletAuthMethodsV2ForWallet(e){let t=c(e||``);return t?(await(await this.manager.getDB()).transaction(w.walletAuthMethods,`readonly`).store.index(T.walletId).getAll(t)).flatMap(e=>{let t=Z(e);return t?[t.record]:[]}):[]}async listLocalWalletAuthMethodProjectionsV2ForWallet(e){let t=c(e||``);return t?await this.manager.runTransaction([w.walletAuthMethods],`readwrite`,async e=>{let n=e.store(w.walletAuthMethods),r=await n.index(T.walletId).getAll(t),i=[];for(let e of r){let t=Z(e);if(!t)continue;let a=Hs(t.record,r,t.presentation);(!Ws(e)||!Us(t.presentation,a))&&await n.put(Bs(Gs(t.record,a))),i.push(Gs(t.record,a))}return i}):[]}async retainVerifiedEmailOtpLocalPresentation(e){let t=await v(String(e.emailAddress));return await this.manager.runTransaction([w.walletAuthMethods],`readwrite`,async n=>{let r=n.store(w.walletAuthMethods),i=Z(await r.get(e.walletAuthMethodId));if(!i)return{kind:`not_retained`,reason:`missing_auth_method`};if(i.record.walletId!==e.walletId)return{kind:`not_retained`,reason:`wallet_mismatch`};if(i.record.kind!==`email_otp`)return{kind:`not_retained`,reason:`auth_method_not_email_otp`};if(i.record.emailHashHex!==t)return{kind:`not_retained`,reason:`email_hash_mismatch`};let a={version:`wallet_auth_method_local_presentation_v1`,kind:`email_otp`,email:{kind:`verified`,address:e.emailAddress}};return await r.put(Bs({kind:`email_otp`,record:i.record,presentation:a})),{kind:`retained`,projection:{kind:`email_otp`,record:i.record,presentation:a}}})}async resolveSelectedWalletAuthority(e){return await this.resolveWalletAuthorityForSelection(e,null)}async resolveWalletAuthorityForMethod(e,t){let r=n(t);return r.ok?await this.resolveWalletAuthorityForSelection(e,r.value):{kind:`integrity_error`,reason:`walletAuthMethodId is invalid`}}async resolveWalletAuthorityForSelection(e,t){let n=p(e);return n.ok?this.manager.runTransaction([w.walletSelections,w.walletAuthMethods,w.walletAuthorities,w.walletAuthoritySignerMaterials,w.walletAuthorityExportRoots],`readonly`,e=>this.resolveSelectedWalletAuthorityInTransaction(n.value,e,t)):{kind:`integrity_error`,reason:`walletId is invalid`}}async resolveSelectedWalletAuthorityInTransaction(e,t,n=null){let r=await t.store(w.walletSelections).get(e);if(r===void 0)return{kind:`missing_selection`};let i=Q(r);if(!i||i.wallet_id!==e)return{kind:`integrity_error`,reason:`wallet selection row is invalid`};let a=n??i.record.walletAuthMethodId,o=await t.store(w.walletAuthMethods).get(String(a));if(o===void 0)return{kind:`missing_auth_method`,walletAuthMethodId:a};let s=Z(o);if(!s||s.wallet_id!==e)return{kind:`integrity_error`,reason:`selected V2 auth method row is invalid`};let c=await t.store(w.walletAuthorities).get(s.wallet_authority_id);if(c===void 0)return{kind:`missing_authority`,walletAuthorityId:s.record.walletAuthorityId};let l=X(c);if(!l||l.wallet_id!==e)return{kind:`integrity_error`,reason:`selected wallet authority row is invalid`};if(l.authority_id!==s.wallet_authority_id)return{kind:`integrity_error`,reason:`auth method authority reference does not resolve exactly`};if(l.record.provenance.kind===`wallet_registration`||l.record.provenance.kind===`wallet_recovery`)return await Ie(l.record)?{kind:`resolved`,selection:i.record,authMethod:s.record,authority:l.record,signerMaterials:[],exportRoot:null}:{kind:`integrity_error`,reason:`selected wallet authority digest is invalid`};let u=t.store(w.walletAuthoritySignerMaterials),f=[],p;try{p=rc(l.record.signerActivations)}catch{return{kind:`integrity_error`,reason:`selected authority signer activations are invalid`}}for(let e of p){let t=await u.get([l.record.authorityId,s.record.walletAuthMethodId,e.materialActivation.activationId]);if(t===void 0)return{kind:`integrity_error`,reason:`selected signer material row is missing`};let n=Js(t);if(!n||n.wallet_authority_id!==l.record.authorityId||n.wallet_auth_method_id!==s.record.walletAuthMethodId||n.activation_id!==e.materialActivation.activationId||n.key_family!==e.keyFamily||!d(n.record.materialActivation,e.materialActivation))return{kind:`integrity_error`,reason:`selected signer material row is invalid`};f.push(n.record)}let m=await t.store(w.walletAuthorityExportRoots).index(T.walletAuthorityAuthMethodId).getAll([l.record.authorityId,s.record.walletAuthMethodId]),h=ac(l.record.signerActivations)&&l.record.permissions.includes(`export_keys`);if(m.length!==(h?1:0))return{kind:`integrity_error`,reason:`selected authority export-root cardinality is invalid`};let g=null;if(h){let t=Zs(m[0]),n=ic(l.record.signerActivations);if(!t||n===null||t.wallet_authority_id!==l.record.authorityId||t.wallet_auth_method_id!==s.record.walletAuthMethodId||t.record.walletKeyId!==n||t.record.envelope.walletId!==e||t.record.envelope.binding.kind!==`ed25519_yao_client_root_v1`||t.record.envelope.binding.walletKeyId!==n||t.record.envelope.binding.registeredPublicKeyB64u!==l.record.signerActivations.ed25519?.signer.registeredPublicKeyB64u||l.record.principal.kind!==`owner_device`||String(t.record.envelope.binding.deviceId)!==String(l.record.principal.deviceId)||t.record.envelope.lifecycle.state!==`active`||!Co(s.record,t.record.envelope))return{kind:`integrity_error`,reason:`selected authority export root is invalid`};g=t.record}return await Ie(l.record)?{kind:`resolved`,selection:i.record,authMethod:s.record,authority:l.record,signerMaterials:f,exportRoot:g}:{kind:`integrity_error`,reason:`selected wallet authority digest is invalid`}}async getAppState(e){let t=c(e||``);if(t)return(await(await this.manager.getDB()).get(w.appState,t))?.value}async listAppStateEntriesByPrefix(e){let t=c(e||``);return t?(await(await this.manager.getDB()).getAll(w.appState)).flatMap(e=>{let n=wo(e);return n&&n.key.startsWith(t)?[n]:[]}):[]}async setAppState(e,t){let n=c(e||``);n&&await this.manager.runTransaction([w.appState],`readwrite`,async e=>{await e.store(w.appState).put({key:n,value:t})})}async putPendingWalletRegistrationCommits(e){let t=e.map(vr);await this.manager.runTransaction([w.appState],`readwrite`,async e=>{let n=e.store(w.appState);for(let e of t){if(await n.get(e.key))throw Error(`Registration checkpoint already exists`);await n.put(e)}})}async advancePendingNearRegistration(e){let t=e.expected,n=e.next;if(t.registrationCeremonyId!==n.registrationCeremonyId||t.walletId!==n.walletId||t.walletAuthMethodId!==n.walletAuthMethodId||t.signedSetup!==n.signedSetup||t.signerPlanKind!==n.signerPlanKind||t.createdAtMs!==n.createdAtMs||n.updatedAtMs<t.updatedAtMs||JSON.stringify(t.auth)!==JSON.stringify(n.auth)||!(t.phase===`planned`&&n.phase===`execution_prepared`||t.phase===`execution_prepared`&&n.phase===`joined`))throw Error(`Invalid NEAR registration checkpoint transition`);if(t.phase===`planned`&&n.phase===`execution_prepared`&&(t.idempotencyKey!==n.idempotencyKey||JSON.stringify(t.admissionRequest)!==JSON.stringify(n.admissionRequest)||JSON.stringify(t.baseCustodyCommit)!==JSON.stringify(n.baseCustodyCommit)))throw Error(`NEAR preparation changed its immutable request`);if(t.phase===`execution_prepared`&&n.phase===`joined`&&(n.completion.kind!==`encrypted_checkpoint`||JSON.stringify(n.completion.prepared)!==JSON.stringify(t)))throw Error(`Joined NEAR must retain its exact encrypted completion checkpoint`);let r=vr(t),i=vr(n);await this.manager.runTransaction([w.appState],`readwrite`,async e=>{let n=e.store(w.appState),a=yr(await n.get(r.key));if(!a||JSON.stringify(a.record)!==JSON.stringify(t))throw Error(`NEAR registration checkpoint changed concurrently`);await n.put(i)})}async putPendingWalletRegistrationCommit(e){let t=vr(e);await this.manager.runTransaction([w.appState],`readwrite`,async e=>{await e.store(w.appState).put(t)})}async migratePendingMixedRegistrationRows(){let e=await(await this.manager.getDB()).getAll(w.appState),t=await Promise.all(e.map(br));await this.manager.runTransaction([w.appState],`readwrite`,async e=>{let n=e.store(w.appState);for(let e of t){if(!e)continue;let t=vr(e.activation);if(JSON.stringify(await n.get(t.key))!==JSON.stringify(e.original))continue;let r=vr(e.near),i=await n.get(r.key);if(i&&JSON.stringify(i)!==JSON.stringify(r))throw Error(`Conflicting NEAR continuation during registration migration`);await n.put(r),await n.put(t)}})}async getPendingWalletRegistrationCommit(e){await this.migratePendingMixedRegistrationRows();let t=c(e.registrationCeremonyId||``);return t&&yr(await(await this.manager.getDB()).get(w.appState,_r({registrationCeremonyId:t,operation:e.operation})))?.record||null}async listPendingWalletRegistrationCommits(){return await this.migratePendingMixedRegistrationRows(),(await(await this.manager.getDB()).getAll(w.appState)).flatMap(e=>{let t=yr(e);return t?[t.record]:[]})}async deletePendingWalletRegistrationCommit(e){let t=c(e.registrationCeremonyId||``);t&&await this.manager.runTransaction([w.appState],`readwrite`,async n=>{await n.store(w.appState).delete(_r({registrationCeremonyId:t,operation:e.operation}))})}async adoptAddedEcdsaSignerAuthority(e){let t=k(e.authority);if(!t.ok||t.value.state!==`active`||!await Ie(t.value))throw Error(`Added ECDSA signer authority is invalid`);let n=t.value,r=n.signerActivations.ecdsa;if(!r||!d(r.materialActivation,e.materialActivation))throw Error(`Added ECDSA signer authority does not carry the activated signer`);await this.manager.runTransaction([w.walletAuthorities],`readwrite`,async e=>{let t=e.store(w.walletAuthorities),r=X(await t.get(n.authorityId));if(!r||r.record.state!==`active`)throw Error(`Added ECDSA signer has no active local authority to extend`);if(r.record.authorityDigestB64u!==n.authorityDigestB64u){if(!qe(r.record,n))throw Error(`Added ECDSA signer authority is not an extension of the local authority`);await t.put(Ls(n))}})}async replaceExactActiveWalletSessionFromStatus(e){return await this.manager.runTransaction([w.appState,w.walletAuthorities,w.walletSessionAuthorizations,w.ecdsaClientPresignatures,w.walletSelections],`readwrite`,this.replaceExactActiveWalletSessionFromStatusInTransaction.bind(this,e))}async replaceExactActiveWalletSessionFromStatusInTransaction(e,t){let n=X(await t.store(w.walletAuthorities).get(e.active.authorityId)),r=Q(await t.store(w.walletSelections).get(e.active.walletId));return!n||n.record.state!==`active`||n.record.walletId!==e.active.walletId||n.record.authorityDigestB64u!==e.active.authorityDigestB64u||n.record.revocationEpoch!==e.active.authorityRevocationEpoch||!r||r.record.lockState!==`unlocked`||r.record.walletAuthMethodId!==e.active.authMethodId?{kind:`superseded`}:(await Tn({ctx:t,active:e.active,operationCredential:e.operationCredential}),{kind:`replaced`})}async reconcilePendingNearRegistrationAuthority(t){let n=await this.getWalletAuthority(t.walletSession.authorityId);if(!n||n.state!==`active`||!Ve(n))return;let r=await this.listPendingWalletRegistrationCommits();for(let i of r){if(i.operation!==`near_provisioning`||i.phase!==`joined`||i.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`||i.walletId!==t.walletSession.walletId||i.walletAuthMethodId!==t.walletSession.authMethodId)continue;let r=i.localMaterial.ed25519.metadata,a=await Ue({authority:n,ed25519:{kind:`wallet_ed25519_signer_activation_v1`,signer:{kind:`exact_administered_ed25519_signer_v1`,keyFamily:`ed25519`,walletId:i.walletId,walletKeyId:Y(e(`wallet-key:ed25519:${i.walletId}:${r.nearEd25519SigningKeyId}`),`NEAR wallet key`),registeredPublicKeyB64u:x(r.registeredPublicKeyB64u)},materialActivation:r.materialActivation},now:Date.now()});if(!(a.authorityDigestB64u!==t.walletSession.authorityDigestB64u||a.revocationEpoch!==t.walletSession.authorityRevocationEpoch)){await this.manager.runTransaction([w.appState,w.walletAuthorities,w.walletSessionAuthorizations,w.ecdsaClientPresignatures,w.walletSelections],`readwrite`,this.reconcilePendingNearRegistrationAuthorityInTransaction.bind(this,{pending:i,authority:a,previousDigest:n.authorityDigestB64u,walletSession:t.walletSession,operationCredential:t.operationCredential}));return}}}async reconcilePendingNearRegistrationAuthorityInTransaction(e,t){let n=await Dn({ctx:t,walletId:e.pending.walletId,authorityId:e.authority.authorityId,authMethodId:e.pending.walletAuthMethodId}),r=Q(await t.store(w.walletSelections).get(e.pending.walletId)),i=X(await t.store(w.walletAuthorities).get(e.authority.authorityId)),a=yr(await t.store(w.appState).get(_r(e.pending)));if(n.kind!==`found`||n.operationCredential.token!==e.operationCredential.token||!r||r.record.lockState!==`unlocked`||r.record.walletAuthMethodId!==e.pending.walletAuthMethodId||!i||i.record.state!==`active`||i.record.authorityDigestB64u!==e.previousDigest&&i.record.authorityDigestB64u!==e.authority.authorityDigestB64u||!a||JSON.stringify(a.record)!==JSON.stringify(e.pending))throw Error(`NEAR authority reconciliation was superseded`);jo({incoming:e.walletSession,existing:n.record}),await t.store(w.walletAuthorities).put(Ls(e.authority)),await Tn({ctx:t,active:e.walletSession,operationCredential:n.operationCredential})}async completePendingNearRegistration(e){await this.manager.runTransaction([w.appState,w.wallets,w.walletSessionAuthorizations,w.ecdsaClientPresignatures,w.walletSelections],`readwrite`,this.completePendingNearRegistrationInTransaction.bind(this,e))}async completePendingNearRegistrationInTransaction(e,t){let n=await Dn({ctx:t,walletId:e.pending.walletId,authorityId:e.walletSession.authorityId,authMethodId:e.pending.walletAuthMethodId});if(n.kind!==`found`||n.operationCredential.token!==e.operationCredential.token||n.record.authorityDigestB64u!==e.walletSession.authorityDigestB64u)throw Error(`NEAR readiness requires the current Wallet Session`);jo({incoming:e.walletSession,existing:n.record});let r=Q(await t.store(w.walletSelections).get(e.pending.walletId));if(!r||r.record.lockState!==`unlocked`||r.record.walletAuthMethodId!==e.pending.walletAuthMethodId)throw Error(`NEAR readiness was interrupted by a wallet lock or selection change`);let i=_r(e.pending),a=yr(await t.store(w.appState).get(i));if(!a||JSON.stringify(a.record)!==JSON.stringify(e.pending))throw Error(`NEAR readiness journal changed concurrently`);let o=q(await t.store(w.wallets).get(e.pending.walletId));if(!o)throw Error(`NEAR readiness requires its committed wallet`);await t.store(w.wallets).put(Go({profileId:o.profileId,nearProvisioning:{status:`near_ready`,nearAccountId:e.nearAccountId,updatedAtMs:Date.now()}},o)),await t.store(w.appState).delete(i)}async putPendingWalletRecoveryCommit(e){let t=await Gi(e);await this.manager.runTransaction([w.appState],`readwrite`,async e=>{await e.store(w.appState).put(t)})}async advancePendingWalletRecoveryCommit(e){let t=await Wi(e.awaiting),n=await Wi(e.promoted);if(t.stage!==`awaiting_server_promotion`||n.stage!==`server_promoted`||!Mi(t,n))throw Error(`pending wallet recovery promotion changed its immutable identity`);let r=await Gi(t),i=await Gi(n);return this.manager.runTransaction([w.appState],`readwrite`,async e=>{let t=e.store(w.appState),a=await t.get(r.key);if(sa(a,r))return await t.put(i),n;if(sa(a,i))return n;throw Error(`stored pending wallet recovery commit does not match the expected stage`)})}async getPendingWalletRecoveryCommit(e){let t=Y(f(e),`recoveryOperationId`);return(await Ki(await(await this.manager.getDB()).get(w.appState,Ni(t))))?.record??null}async listPendingWalletRecoveryCommits(){let e=await this.manager.getDB();return(await Promise.all((await e.getAll(w.appState)).map(Ki))).flatMap(e=>e?[e.record]:[])}async deletePendingWalletRecoveryCommit(e){let t=Y(f(e),`recoveryOperationId`);await this.manager.runTransaction([w.appState],`readwrite`,async e=>{await e.store(w.appState).delete(Ni(t))})}async getProfile(e){let t=c(e||``);return t?q(await(await this.manager.getDB()).get(w.wallets,t)):null}async getWalletPreferences(e){return(await this.getProfile(e))?.preferences||{}}async listProfiles(e){let t=await this.manager.getDB(),n=Number.isSafeInteger(e?.limit)&&Number(e?.limit)>0?Number(e?.limit):void 0;return(n?await t.getAll(w.wallets,void 0,n):await t.getAll(w.wallets)).flatMap(e=>{let t=q(e);return t?[t]:[]})}async upsertProfile(e){let t=c(e.profileId||``);if(!t)throw Error(`[SeamsWalletDB] profileId is required`);let n=null;if(await this.manager.runTransaction([w.wallets],`readwrite`,async r=>{let i=r.store(w.wallets),a=Go(e,q(await i.get(t))||void 0);n=a.record,await i.put(a)}),!n)throw Error(`[SeamsWalletDB] profile write did not complete`);return n}async upsertWalletAuthMethod(e){let t=gs(e),n=null;if(await this.manager.runTransaction([w.wallets,w.walletAuthMethods],`readwrite`,async r=>{let i=q(await r.store(w.wallets).get(t.wallet_id));if(!i)throw K(`MISSING_PROFILE`,`Cannot upsert auth-method binding for unknown wallet: ${t.wallet_id}`,{profileId:t.wallet_id,authIdentifierKey:t.auth_identifier_key});let a=r.store(w.walletAuthMethods),o=J(await a.get(t.wallet_auth_method_id)),s=e.kind===`passkey`&&o?.kind===`passkey`?Ss({binding:e,authenticator:o.authenticator}):ws(e,i.defaultSignerSlot);await a.put(s),n=s.record}),!n)throw Error(`[SeamsWalletDB] auth-method write did not complete`);return n}async upsertWalletAuthMethodV2(e){let t=A(e);if(!t)throw Error(`[SeamsWalletDB] auth-method V2 record is invalid`);await this.manager.runTransaction([w.wallets,w.walletAuthMethods],`readwrite`,async e=>{if(!q(await e.store(w.wallets).get(t.walletId)))throw K(`MISSING_PROFILE`,`Cannot upsert auth-method V2 binding for unknown wallet: ${String(t.walletId)}`,{profileId:String(t.walletId)});let n=e.store(w.walletAuthMethods);await n.put(await Ks(n,t))})}async getWalletAuthMethod(e){let t=e.kind,n=c(e.rpId||``),r=c(e.authIdentifierKey||``);if(!n||!r)return null;let i=(await(await this.manager.getDB()).transaction(w.walletAuthMethods,`readonly`).store.index(T.kindRpIdAuthIdentifier).getAll([t,n,r])).flatMap(e=>{let t=js(e);return t?[t]:[]});return i.length===1?i[0]:null}async listWalletAuthMethodsForWallet(e){let t=c(e||``);return t?(await(await this.manager.getDB()).transaction(w.walletAuthMethods,`readonly`).store.index(T.walletId).getAll(t)).flatMap(e=>{let t=js(e);return t?[t]:[]}):[]}async upsertChainAccount(e){let t=c(e.profileId||``),n=D(e.chainIdKey),r=O(e.accountAddress);if(!t||!n||!r)throw Error(`[SeamsWalletDB] profileId, chainIdKey, and accountAddress are required`);let i=null;if(await this.manager.runTransaction([w.wallets,w.nearAccountProjections],`readwrite`,async a=>{if(!q(await a.store(w.wallets).get(t)))throw Error(`[SeamsWalletDB] Cannot upsert chain account for unknown profile: ${t}`);let o=a.store(w.nearAccountProjections),s=mo({chainIdKey:n,accountAddress:r}),c=vo(e,bo(await o.get([t,s,0]))||void 0);if(i=c.record,c.record.isPrimary){let e=await o.index(T.profileId).getAll(t);for(let t of e||[]){let e=bo(t);!e||e.chainIdKey!==n||!e.isPrimary||e.accountAddress!==r&&await o.put(vo({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,accountModel:e.accountModel,isPrimary:!1},e))}}await o.put(c)}),!i)throw Error(`[SeamsWalletDB] chain-account write did not complete`);return i}async listChainAccountsByProfile(e){let t=c(e||``);if(!t)return[];let n=(await this.manager.getDB()).transaction(w.nearAccountProjections,`readonly`),r=await n.store.index(T.profileId).getAll(t);return await n.done,r.flatMap(e=>{let t=bo(e);return t?[t]:[]})}async listChainAccountsByProfileAndChain(e,t){let n=D(t);return n?(await this.listChainAccountsByProfile(e)).filter(e=>e.chainIdKey===n):[]}async getChainAccount(e){let t=c(e.profileId||``),n=D(e.chainIdKey),r=O(e.accountAddress);return!t||!n||!r?null:bo(await(await this.manager.getDB()).get(w.nearAccountProjections,[t,mo({chainIdKey:n,accountAddress:r}),0]))}async resolveProfileAccountContext(e){let t=D(e.chainIdKey),n=O(e.accountAddress);if(!t||!n)return null;let r=(await(await this.manager.getDB()).getAll(w.nearAccountProjections)).flatMap(e=>{let t=bo(e);return t?[t]:[]}).find(e=>e.chainIdKey===t&&e.accountAddress===n);return r?.profileId?{profileId:r.profileId,accountRef:{chainIdKey:t,accountAddress:n}}:null}async listChainAccountsByChain(e){let t=D(e);return t?(await(await this.manager.getDB()).getAll(w.nearAccountProjections)).flatMap(e=>{let n=bo(e);return n&&n.chainIdKey===t?[n]:[]}):[]}buildAccountSignerRecord(e){let t=e.status===`revoked`?e.removedAt??e.existing?.removedAt??e.now:void 0;return{profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot,signerType:e.signerType,signerKind:e.signerKind,signerAuthMethod:e.signerAuthMethod,signerSource:e.signerSource,status:e.status,addedAt:e.existing?.addedAt??e.now,updatedAt:e.now,...t==null?{}:{removedAt:t},...e.revocationReason?{revocationReason:c(e.revocationReason)}:e.existing?.revocationReason?{revocationReason:e.existing.revocationReason}:{},...e.metadata==null?e.existing?.metadata==null?{}:{metadata:e.existing.metadata}:{metadata:e.metadata}}}assertSignerWriteInvariants(e){let{next:t}=e;if(t.status!==`revoked`&&(!t.signerKind||!t.signerAuthMethod||!t.signerSource))throw K(`MISSING_SIGNER_KIND`,`Active and pending account signers require signerKind, signerAuthMethod, and signerSource`,{chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId,status:t.status});if(t.status===`revoked`&&t.removedAt==null)throw K(`REVOKED_SIGNER_REQUIRES_REMOVED_AT`,`Revoked signer ${t.signerId} must include removedAt`,{chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId});if(t.status===`active`){let n=e.activeSigners.find(e=>e.signerId!==t.signerId&&e.signerSlot===t.signerSlot);if(n)throw K(`DUPLICATE_ACTIVE_SIGNER_SLOT`,`Active signer slot ${t.signerSlot} is already used for ${t.chainIdKey}/${t.accountAddress}`,{chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId,signerSlot:t.signerSlot,conflictingSignerId:n.signerId})}if(e.existingStatus&&e.existingStatus!==t.status&&!{pending:new Set([`pending`,`active`,`revoked`]),active:new Set([`active`,`revoked`]),revoked:new Set([`revoked`])}[e.existingStatus]?.has(t.status))throw K(`INVALID_SIGNER_STATUS_TRANSITION`,`Invalid signer status transition ${e.existingStatus} -> ${t.status}`,{chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId,previousStatus:e.existingStatus,nextStatus:t.status});if(t.status===`active`&&String(t.signerKind||``)===`threshold-ecdsa`){let e=t.metadata||{};if(!c(e.keyHandle))throw K(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer requires metadata.keyHandle`,{chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId});if(!c(e.ecdsaThresholdKeyId))throw K(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer requires metadata.ecdsaThresholdKeyId`,{chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId});let n=O(e.thresholdOwnerAddress);if(!n||n!==t.accountAddress)throw K(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer requires metadata.thresholdOwnerAddress matching accountAddress`,{chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId});let r=go(e.chainTarget);if(!r)throw K(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer requires metadata.chainTarget`,{chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId});if(r!==t.chainIdKey)throw K(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer metadata.chainTarget must match chainIdKey`,{chainIdKey:t.chainIdKey,chainTargetKey:r,accountAddress:t.accountAddress,signerId:t.signerId})}}async enqueueSignerOperationInTransaction(e,t){let n=c(t.opId||``),r=c(t.idempotencyKey||``),i=D(t.chainIdKey),a=O(t.accountAddress),o=c(t.signerId||``);if(!n||!r||!i||!a||!o)throw Error(`[SeamsWalletDB] opId, idempotencyKey, chainIdKey, accountAddress, and signerId are required`);let s=po(await e.get(n));if(!s){let t=po(await e.index(T.idempotencyKey).get(r));if(t)return t}let l=Date.now(),u={opId:n,idempotencyKey:r,opType:t.opType,chainIdKey:i,accountAddress:a,signerId:o,payload:t.payload??s?.payload,status:t.status??s?.status??`queued`,attemptCount:t.attemptCount??s?.attemptCount??0,nextAttemptAt:t.nextAttemptAt??s?.nextAttemptAt??l,lastError:t.lastError??s?.lastError,txHash:t.txHash??s?.txHash,createdAt:s?.createdAt??l,updatedAt:l};return await e.put(uo(u)),u}async activateAccountSignerInTransaction(e,t){let n=c(t.account.profileId||``),r=D(t.account.chainIdKey),i=O(t.account.accountAddress),a=Te(t.account.accountModel),o=c(t.signer.signerId||``),s=t.signer.signerKind,l=t.signer.signerAuthMethod,u=t.signer.signerSource;if(!n||!r||!i||!a||!o||!s||!l||!u)throw Error(`[SeamsWalletDB] profileId, chainIdKey, accountAddress, accountModel, signerId, signerKind, signerAuthMethod, and signerSource are required`);let d=e.store(w.walletSigners);if(!q(await e.store(w.wallets).get(n)))throw K(`MISSING_PROFILE`,`Cannot upsert signer without profile row: ${n}`,{profileId:n,chainIdKey:r,accountAddress:i,signerId:o});if(Wo({accountModel:a,chainIdKey:r})){let o=e.store(w.nearAccountProjections),s=bo(await o.get([n,mo({chainIdKey:r,accountAddress:i}),0])),c=vo({profileId:n,chainIdKey:r,accountAddress:i,accountModel:a,isPrimary:t.selectAsActive===!0?!0:s?.isPrimary??!0},s||void 0);await o.put(c)}let f=(await d.index(T.status).getAll(`active`)).flatMap(e=>{let t=W(e);return t?[t]:[]}),p=f.flatMap(e=>e.chainIdKey===r&&e.accountAddress===i?[e]:[]),m=ur({activeSigners:p,signer:{signerId:o,signerKind:s,signerAuthMethod:l,signerSource:u},activationPolicy:t.activationPolicy,...t.preferredSlot==null?{}:{preferredSlot:t.preferredSlot}}),h=Date.now();await this.revokeSignersForReplacement({signerStore:d,allActiveSigners:f,accountActiveSigners:p,profileId:n,chainIdKey:r,accountModel:a,signerId:o,activationPolicy:t.activationPolicy,now:h});let g=this.activeSignersAfterReplacement({allActiveSigners:f,accountActiveSigners:p,profileId:n,chainIdKey:r,signerId:o,activationPolicy:t.activationPolicy}),_=W(await d.get(ho({chainIdKey:r,accountAddress:i,signerId:o})));if(_&&_.profileId!==n)throw K(`CHAIN_ACCOUNT_PROFILE_MISMATCH`,`Signer row belongs to a different profile for ${r}/${i}/${o}`,{expectedProfileId:n,existingProfileId:_.profileId});let v=this.buildAccountSignerRecord({profileId:n,chainIdKey:r,accountAddress:i,signerId:o,signerSlot:m.signerSlot,signerType:t.signer.signerType,signerKind:s,signerAuthMethod:l,signerSource:u,status:`active`,existing:_||void 0,now:h,...t.signer.metadata?{metadata:t.signer.metadata}:{}});this.assertSignerWriteInvariants({next:v,accountModel:a,existingStatus:_?.status,activeSigners:g});let y=xo(v);if(await kc({store:d,nextRow:y}),await d.put(y),(t.selectAsActive??!0)&&await e.store(w.appState).put({key:Uo(),value:{profileId:n,activeSignerSlot:m.signerSlot}}),t.mutation?.routeThroughOutbox??!1){let n=c(t.mutation?.opId||``)||Bo(`add-signer`),r=c(t.mutation?.idempotencyKey||``)||`add-signer:${v.chainIdKey}:${v.accountAddress}:${v.signerId}:${v.signerSlot}`;await this.enqueueSignerOperationInTransaction(e.store(w.signerOpsOutbox),{opId:n,idempotencyKey:r,opType:`add-signer`,chainIdKey:v.chainIdKey,accountAddress:v.accountAddress,signerId:v.signerId,payload:this.signerOutboxPayload(v,t.mutation),status:t.mutation?.outboxStatus||`queued`})}return{signer:v,signerSlot:m.signerSlot}}activeSignersAfterReplacement(e){let t=new Set;for(let n of this.signersRetiredByActivationPolicy(e))t.add(n.signerId);if(t.size===0)return e.accountActiveSigners;let n=[];for(let r of e.accountActiveSigners)t.has(r.signerId)||n.push(r);return n}signersRetiredByActivationPolicy(e){let t=[];switch(e.activationPolicy.mode){case`replace_slot`:for(let n of e.accountActiveSigners)n.signerSlot===e.activationPolicy.signerSlot&&n.signerId!==e.signerId&&t.push(n);return t;case`replace_profile_chain_kind`:for(let n of e.allActiveSigners)n.profileId===e.profileId&&n.chainIdKey===e.chainIdKey&&n.signerKind===e.activationPolicy.replacedSignerKind&&n.signerId!==e.signerId&&t.push(n);return t;default:return t}}async revokeSignersForReplacement(e){let t=this.signersRetiredByActivationPolicy(e);if(t.length===0)return;let n=c(e.activationPolicy.mode===`replace_slot`||e.activationPolicy.mode===`replace_profile_chain_kind`?e.activationPolicy.revocationReason:``);for(let r of t){let t=this.buildAccountSignerRecord({...r,status:`revoked`,existing:r,now:e.now,removedAt:e.now,revocationReason:n});this.assertSignerWriteInvariants({next:t,accountModel:e.accountModel,existingStatus:r.status,activeSigners:e.accountActiveSigners}),await e.signerStore.put(xo(t))}}async activateAccountSigner(e){let t=null;if(await this.manager.runTransaction([w.appState,w.wallets,w.wallets,w.nearAccountProjections,w.walletSigners,w.appState,w.signerOpsOutbox],`readwrite`,async n=>{t=await this.activateAccountSignerInTransaction(n,e)}),!t)throw Error(`[SeamsWalletDB] signer activation did not complete`);return t}async stageAccountSigner(e){return this.writePreparedAccountSigner({account:e.account,signer:e.signer,status:`pending`,signerSlot:e.signer.signerSlot,mutation:e.mutation})}async writePreparedAccountSigner(e){let t=c(e.account.profileId||``),n=D(e.account.chainIdKey),r=O(e.account.accountAddress),i=Te(e.account.accountModel),a=c(e.signer.signerId||``),o=Number(e.signerSlot),s=e.signer.signerKind,l=e.signer.signerAuthMethod,u=e.signer.signerSource;if(!t||!n||!r||!i||!a||!s||!l||!u)throw Error(`[SeamsWalletDB] profileId, chainIdKey, accountAddress, accountModel, signerId, signerKind, signerAuthMethod, and signerSource are required`);if(!Number.isSafeInteger(o)||o<1)throw Error(`[SeamsWalletDB] signerSlot must be an integer >= 1`);let d=null;if(await this.manager.runTransaction([w.wallets,w.nearAccountProjections,w.walletSigners,w.signerOpsOutbox],`readwrite`,async f=>{if(!q(await f.store(w.wallets).get(t)))throw K(`MISSING_PROFILE`,`Cannot upsert signer without profile row: ${t}`,{profileId:t,chainIdKey:n,accountAddress:r,signerId:a});let p=f.store(w.nearAccountProjections),m=bo(await p.get([t,mo({chainIdKey:n,accountAddress:r}),0])),h=vo({profileId:t,chainIdKey:n,accountAddress:r,accountModel:i,isPrimary:m?.isPrimary},m||void 0);await p.put(h);let g=f.store(w.walletSigners),_=W(await g.get(ho({chainIdKey:n,accountAddress:r,signerId:a})));if(_&&_.profileId!==t)throw K(`CHAIN_ACCOUNT_PROFILE_MISMATCH`,`Signer row belongs to a different profile for ${n}/${r}/${a}`,{expectedProfileId:t,existingProfileId:_.profileId});let v=(await g.index(T.status).getAll(`active`)).flatMap(e=>{let t=W(e);return t&&t.chainIdKey===n&&t.accountAddress===r?[t]:[]}),y=Date.now(),b=this.buildAccountSignerRecord({profileId:t,chainIdKey:n,accountAddress:r,signerId:a,signerSlot:o,signerType:e.signer.signerType,signerKind:s,signerAuthMethod:l,signerSource:u,status:e.status,existing:_||void 0,now:y,...e.signer.metadata?{metadata:e.signer.metadata}:{}});this.assertSignerWriteInvariants({next:b,accountModel:i,existingStatus:_?.status,activeSigners:v});let ee=xo(b);if(await kc({store:g,nextRow:ee}),await g.put(ee),e.mutation?.routeThroughOutbox??!1){let t=c(e.mutation?.opId||``)||Bo(`add-signer`),n=c(e.mutation?.idempotencyKey||``)||`add-signer:${b.chainIdKey}:${b.accountAddress}:${b.signerId}:${b.signerSlot}`;await this.enqueueSignerOperationInTransaction(f.store(w.signerOpsOutbox),{opId:t,idempotencyKey:n,opType:`add-signer`,chainIdKey:b.chainIdKey,accountAddress:b.accountAddress,signerId:b.signerId,payload:this.signerOutboxPayload(b,e.mutation),status:e.mutation?.outboxStatus||`queued`})}d={signer:b,signerSlot:o}}),!d)throw Error(`[SeamsWalletDB] signer write did not complete`);return d}signerOutboxPayload(e,t){return{profileId:e.profileId,signerSlot:e.signerSlot,signerType:e.signerType,signerKind:e.signerKind,signerAuthMethod:e.signerAuthMethod,signerSource:e.signerSource,...e.metadata?{signerMetadata:e.metadata}:{},...t?.outboxPayload?t.outboxPayload:{}}}async listAccountSigners(e){let t=D(e.chainIdKey),n=O(e.accountAddress);if(!t||!n)return[];let r=await this.manager.getDB();return(e.status?await r.transaction(w.walletSigners,`readonly`).store.index(T.status).getAll(e.status):await r.getAll(w.walletSigners)).flatMap(e=>{let r=W(e);return r&&r.chainIdKey===t&&r.accountAddress===n?[r]:[]})}async listAccountSignersByProfile(e){let t=c(e.profileId||``);return t?(await(await this.manager.getDB()).transaction(w.walletSigners,`readonly`).store.index(T.walletId).getAll(t)).flatMap(t=>{let n=W(t);return n&&(!e.status||n.status===e.status)?[n]:[]}):[]}async listActiveWalletSigners(e){let t=c(e.walletId||``);if(!t)return[];let n=e.signerFamily===`ecdsa`?ge.thresholdEcdsa:ge.thresholdEd25519,r=[t],i=(await this.getProfile(t))?.nearProvisioning;i?.status===`near_ready`&&i.nearAccountId&&r.push(String(Oe(Me(i.nearAccountId))));let a=[],o=new Set;for(let e of r){let r=await this.listAccountSignersByProfile({profileId:e,status:`active`});for(let e of r){if(e.signerKind!==n)continue;let r=c(String(e.metadata?.walletId??``));if(r&&r!==t)continue;let i=`${e.chainIdKey}/${e.accountAddress}/${e.signerId}`;o.has(i)||(o.add(i),a.push(e))}}return a}async getActiveWalletSignerForChainTarget(e){let t=c(e.walletId||``);if(!t)return null;let n=De(e.chainTarget),r=(await this.listActiveWalletSigners({walletId:t,signerFamily:`ecdsa`})).filter(e=>e.chainIdKey===n);if(r.length>1)throw Error(`[SeamsWalletDB] ambiguous active ECDSA wallet signer for ${t}/${n}`);return r[0]||null}async getAccountSigner(e){let t=D(e.chainIdKey),n=O(e.accountAddress),r=c(e.signerId||``);return!t||!n||!r?null:W(await(await this.manager.getDB()).get(w.walletSigners,ho({chainIdKey:t,accountAddress:n,signerId:r})))}async setAccountSignerStatus(e){let t=await this.getAccountSigner(e);if(!t)return null;let n=await this.getChainAccount({profileId:t.profileId,chainIdKey:t.chainIdKey,accountAddress:t.accountAddress});if(!n)throw K(`MISSING_CHAIN_ACCOUNT`,`Cannot update signer status without chain account row: ${t.profileId}/${t.chainIdKey}/${t.accountAddress}`,{profileId:t.profileId,chainIdKey:t.chainIdKey,accountAddress:t.accountAddress,signerId:t.signerId});let r=null;return await this.manager.runTransaction([w.walletSigners,w.signerOpsOutbox],`readwrite`,async i=>{let a=i.store(w.walletSigners),o=(await a.index(T.status).getAll(`active`)).flatMap(e=>{let n=W(e);return n&&n.chainIdKey===t.chainIdKey&&n.accountAddress===t.accountAddress?[n]:[]}),s=this.buildAccountSignerRecord({...t,status:e.status,existing:t,now:Date.now(),...e.removedAt==null?{}:{removedAt:e.removedAt},...e.revocationReason?{revocationReason:e.revocationReason}:{}});if(this.assertSignerWriteInvariants({next:s,accountModel:n.accountModel,existingStatus:t.status,activeSigners:o}),await a.put(xo(s)),e.mutation?.routeThroughOutbox??!0){let t=e.status===`revoked`?`revoke-signer`:`add-signer`,n=c(e.mutation?.opId||``)||Bo(t),r=c(e.mutation?.idempotencyKey||``)||`signer-status:${e.status}:${s.chainIdKey}:${s.accountAddress}:${s.signerId}`;await this.enqueueSignerOperationInTransaction(i.store(w.signerOpsOutbox),{opId:n,idempotencyKey:r,opType:t,chainIdKey:s.chainIdKey,accountAddress:s.accountAddress,signerId:s.signerId,payload:{profileId:s.profileId,signerSlot:s.signerSlot,status:s.status,...s.removedAt==null?{}:{removedAt:s.removedAt},...s.revocationReason?{revocationReason:s.revocationReason}:{},...e.mutation?.outboxPayload?e.mutation.outboxPayload:{}},status:e.mutation?.outboxStatus||`queued`})}r=s}),r}async enqueueSignerOperation(e){let t=null;if(await this.manager.runTransaction([w.signerOpsOutbox],`readwrite`,async n=>{t=await this.enqueueSignerOperationInTransaction(n.store(w.signerOpsOutbox),e)}),!t)throw Error(`[SeamsWalletDB] signer op enqueue did not complete`);return t}async listSignerOperations(e){let t=e?.statuses&&e.statuses.length>0?e.statuses:[`queued`,`submitted`,`failed`],n=typeof e?.dueBefore==`number`?e.dueBefore:Date.now(),r=Number.isFinite(n)?n:2**53-1,i=Number.isSafeInteger(e?.limit)&&Number(e?.limit)>0?Number(e?.limit):100,a=await this.manager.getDB(),o=[];for(let e of t){let t=a.transaction(w.signerOpsOutbox,`readonly`),n=await t.store.index(T.statusNextAttemptAt).getAll(IDBKeyRange.bound([e,-(2**53-1)],[e,r]));await t.done,o.push(...(n||[]).flatMap(e=>{let t=po(e);return t?[t]:[]}))}return o.sort((e,t)=>{let n=(e.nextAttemptAt||0)-(t.nextAttemptAt||0);return n===0?String(e.opId||``).localeCompare(String(t.opId||``)):n}),o.slice(0,i)}async setSignerOperationStatus(e){let t=c(e.opId||``);if(!t)return null;let n=null;return await this.manager.runTransaction([w.signerOpsOutbox],`readwrite`,async r=>{let i=r.store(w.signerOpsOutbox),a=po(await i.get(t));if(!a)return;let o=Number.isFinite(e.attemptDelta)?Number(e.attemptDelta):0,s=Math.max(0,(a.attemptCount||0)+o),c={...a,status:e.status,attemptCount:s,nextAttemptAt:typeof e.nextAttemptAt==`number`?e.nextAttemptAt:a.nextAttemptAt,...e.lastError===null?{lastError:void 0}:typeof e.lastError==`string`?{lastError:e.lastError}:{lastError:a.lastError},...e.txHash===null?{txHash:void 0}:typeof e.txHash==`string`?{txHash:e.txHash}:{txHash:a.txHash},updatedAt:Date.now()};await i.put(uo(c)),n=c}),n}async getProfileContinuitySnapshot(e){let t=await this.getProfile(e);return t?{profile:t,chainAccounts:await this.listChainAccountsByProfile(t.profileId),accountSigners:await this.listAccountSignersByProfile({profileId:t.profileId})}:null}async listProfileAuthenticators(e){let t=c(e||``);if(!t)return[];let n=(await this.manager.getDB()).transaction(w.walletAuthMethods,`readonly`),r=await n.store.index(T.walletIdKind).getAll([t,`passkey`]);return await n.done,r.flatMap(e=>{let t=Ms(e);return t?[t]:[]})}async listWalletPasskeyAuthenticators(e){let t=await this.listProfileAuthenticators(e),n=(await this.getProfile(e))?.nearProvisioning;if(n?.status!==`near_ready`||!n.nearAccountId)return t;let r=String(Oe(Me(n.nearAccountId)));if(r===e)return t;let i=await this.listProfileAuthenticators(r),a=new Set(t.map(e=>e.credentialId));return[...t,...i.filter(e=>!a.has(e.credentialId))]}async getWalletPasskeyAuthenticator(e){let t=c(e.credentialId||``);return t?(await this.listWalletPasskeyAuthenticators(e.walletId)).find(e=>e.credentialId===t)??null:null}async upsertProfileAuthenticator(e){let t=ys(e);await this.manager.runTransaction([w.wallets,w.walletAuthMethods],`readwrite`,async e=>{if(!q(await e.store(w.wallets).get(t.profileId)))throw K(`MISSING_PROFILE`,`Cannot upsert authenticator for unknown profile: ${t.profileId}`,{profileId:t.profileId,credentialId:t.credentialId});let n=e.store(w.walletAuthMethods),r=J(await n.index(T.passkeyRpIdCredentialId).get([`passkey`,Io,t.credentialId])),i=Ts(t,r?.kind===`passkey`?r:void 0);await n.put(i)})}async getProfileAuthenticatorByCredentialId(e,t){let n=c(e||``),r=c(t||``);if(!n||!r)return null;let i=Ms(await(await this.manager.getDB()).transaction(w.walletAuthMethods,`readonly`).store.index(T.passkeyRpIdCredentialId).get([`passkey`,Io,r]));return i?.profileId===n?i:null}async persistWalletRegistrationFinalize(e){return this.manager.runTransaction(No,`readwrite`,this.persistWalletRegistrationFinalizeInTransaction.bind(this,e))}async publishPendingWalletRegistrationCommit(e){return await this.publishPendingWalletRegistrationCommitWithDisposition(e,!0)}async publishPendingWalletRegistrationCommitAndRetain(e){return await this.publishPendingWalletRegistrationCommitWithDisposition(e,!1)}async publishPendingWalletRegistrationCommitWithDisposition(e,t){let n=Sr(e.pending),r=at(e.authority);if(!r)throw Error(`registration wallet auth authority is invalid`);let i=Oo(e.foundingAuthority);await ko({request:e.request,pending:n,authority:r,foundingAuthority:i,registration:e.registration});let a=e.walletSessionPublication.walletSession;if(a.walletId!==n.walletId||a.authorityId!==i.authority.authorityId||a.authMethodId!==n.walletAuthMethodId||a.authorityDigestB64u!==i.authority.authorityDigestB64u||a.authorityRevocationEpoch!==i.authority.revocationEpoch)throw Error(`registration Wallet Session identity does not match the pending wallet`);return this.manager.runTransaction(Po,`readwrite`,this.publishPendingWalletRegistrationCommitInTransaction.bind(this,{request:e.request,pending:n,authority:r,foundingAuthority:i,registration:e.registration,ecdsaContinuity:e.ecdsaContinuity,walletSessionPublication:e.walletSessionPublication,deletePending:t}))}async publishPendingWalletRecoveryCommit(e){let t=await Wi(e.pending);if(t.stage!==`server_promoted`)throw Error(`pending wallet recovery commit is not server-promoted`);let n=Y(k(e.authority),`authority`);if(n.state!==`active`||!ze(n))throw Error(`recovered Wallet Authority projection is invalid`);let r=A(e.authMethod);if(!r||r.status!==`active`)throw Error(`recovered Wallet Auth Method projection is invalid`);if(!await Ie(n))throw Error(`recovered Wallet Authority digest is invalid`);let i={pending:t,authority:n,authMethod:r,registration:e.registration,ecdsaContinuity:e.ecdsaContinuity,ed25519PublicCapabilityReferences:e.ed25519PublicCapabilityReferences};Ao(i);let a=await Gi(t);return this.manager.runTransaction(Fo,`readwrite`,this.publishPendingWalletRecoveryCommitInTransaction.bind(this,{...i,pendingRow:a}))}async publishPendingWalletRegistrationCommitInTransaction(e,t){let n=_r({registrationCeremonyId:e.request.registrationCeremonyId,operation:e.request.operation}),r=yr(await t.store(w.appState).get(n)),i=r?.record;if(i&&Do(i,e.request),!r||!i||r?.registration_ceremony_id!==e.request.registrationCeremonyId||r.operation!==e.request.operation||r.wallet_id!==e.request.walletId||r.wallet_auth_method_id!==e.request.walletAuthMethodId||r.updated_at_ms!==e.pending.updatedAtMs||i.idempotencyKey!==e.pending.idempotencyKey||i.signerPlanKind!==e.pending.signerPlanKind)throw Error(`stored pending wallet registration commit does not match the expected row`);let a;if(e.walletSessionPublication.kind===`issued`)a=`issued`,await Tn({ctx:t,active:e.walletSessionPublication.walletSession,operationCredential:e.walletSessionPublication.operationCredential});else{let n=await Dn({ctx:t,walletId:e.pending.walletId,authorityId:e.foundingAuthority.authority.authorityId,authMethodId:e.pending.walletAuthMethodId});switch(n.kind){case`found`:jo({incoming:e.walletSessionPublication.walletSession,existing:n.record}),await Tn({ctx:t,active:e.walletSessionPublication.walletSession,operationCredential:n.operationCredential}),a=`reconciled`;break;case`missing`:if(e.pending.operation!==`near_provisioning`||e.pending.signerPlanKind!==`near_ed25519`)throw Error(`Credential-free registration projection has no exact local Wallet Session`);a=`locked_identity`;break;case`corrupt`:case`upgrade_required`:throw Error(`Credential-free registration projection cannot read the exact local Wallet Session`);default:return G(n)}}let o=await this.persistWalletRegistrationFinalizeInTransaction(e.registration,t),s;switch(a){case`issued`:s=`activate`;break;case`reconciled`:s=`preserve`;break;case`locked_identity`:s=`restore_locked`;break;default:return G(a)}await this.persistFoundingWalletAuthorityInTransaction(e.foundingAuthority,s,t);for(let n of e.ecdsaContinuity)await Oa(t,n);return e.deletePending&&await t.store(w.appState).delete(n),o}async publishPendingWalletRecoveryCommitInTransaction(e,t){if(!sa(await t.store(w.appState).get(e.pendingRow.key),e.pendingRow))throw Error(`stored pending wallet recovery commit does not match the expected row`);let n=await this.persistWalletRegistrationFinalizeInTransaction(e.registration,t);await this.persistRecoveredWalletAuthorityInTransaction({authority:e.authority,authMethod:e.authMethod,recoveredAtMs:e.pending.updatedAtMs},t),await Ho({store:t.store(w.ecdsaClientPresignatures),indexName:T.walletId,key:IDBKeyRange.only(String(e.authority.walletId))});for(let n of e.ecdsaContinuity)await Oa(t,n);let r=t.store(w.appState);for(let t of e.ed25519PublicCapabilityReferences)await eo(r,t);return await t.store(w.appState).delete(e.pendingRow.key),n}async persistWalletRegistrationFinalizeInTransaction(e,t){let n=Oc(e),r=e.keyMaterials.map(e=>Mc(e)),i=[],a=t.store(w.wallets);for(let t of e.profiles){let e=c(t.profileId||``);if(!e)throw Error(`[SeamsWalletDB] profileId is required`);let n=q(await a.get(e))||void 0;await a.put(Go(t,n))}let o=t.store(w.walletAuthMethods);for(let e of n){if(!q(await a.get(e.wallet_id)))throw K(`MISSING_PROFILE`,`Cannot upsert auth method for unknown wallet: ${e.wallet_id}`,{profileId:e.wallet_id,authIdentifierKey:e.auth_identifier_key});await o.put(e)}for(let n of e.signerActivations)i.push(await this.activateAccountSignerInTransaction(t,n));await Uc({ctx:t,signers:i.map(e=>e.signer),keyMaterials:e.keyMaterials});let s=t.store(w.keyMaterial);for(let e of r)await s.put(e);return e.lastProfileState&&await t.store(w.appState).put({key:Uo(e.lastProfileState.scope),value:{profileId:e.lastProfileState.profileId,activeSignerSlot:e.lastProfileState.activeSignerSlot,...e.lastProfileState.scope?{scope:we(e.lastProfileState.scope)}:{}}}),{signerActivations:i}}async persistWalletSignerFinalize(e){let t=e.keyMaterials.map(e=>Mc(e)),n=[],r=[],i=null;return await this.manager.runTransaction([w.appState,w.wallets,w.walletSigners,w.nearAccountProjections,w.signerOpsOutbox,w.keyMaterial],`readwrite`,async a=>{let o=a.store(w.wallets);if(e.lastProfileState){let t=a.store(w.appState),n=Uo(e.lastProfileState.scope),r=wo(await t.get(n));i={key:n,committed:{profileId:e.lastProfileState.profileId,activeSignerSlot:e.lastProfileState.activeSignerSlot,...e.lastProfileState.scope?{scope:we(e.lastProfileState.scope)}:{}},previousPresent:r!==null,previousValue:r?.value}}for(let t of e.profiles){let e=c(t.profileId||``);if(!e)throw Error(`[SeamsWalletDB] profileId is required`);let n=q(await o.get(e)),i=Go(t,n||void 0);await o.put(i),r.push({committed:i.record,previous:n})}for(let t of e.signerActivations)n.push(await this.activateAccountSignerInTransaction(a,t));await Uc({ctx:a,signers:n.map(e=>e.signer),keyMaterials:e.keyMaterials});let s=a.store(w.keyMaterial);for(let e of t)await s.put(e);if(e.lastProfileState){let e=a.store(w.appState);if(!i)throw Error(`[SeamsWalletDB] last profile rollback state was not captured`);await e.put({key:i.key,value:i.committed})}}),{signerActivations:n,rollbackReceipt:{kind:`wallet_signer_finalize_rollback_v1`,profiles:r,signers:n.map(e=>({committed:e.signer,metadataBaseline:ns(e.signer.metadata)})),keyMaterials:t.map(e=>({committed:e.record,payloadBaseline:is(e.record.payload)})),lastProfileState:i}}}async rollbackWalletSignerFinalize(e){if(e.kind!==`wallet_signer_finalize_rollback_v1`)throw Error(`[SeamsWalletDB] invalid wallet signer rollback receipt`);await this.manager.runTransaction([w.appState,w.wallets,w.walletSigners,w.keyMaterial],`readwrite`,async t=>{let n=t.store(w.wallets),r=t.store(w.walletSigners),i=t.store(w.keyMaterial),a=t.store(w.appState);for(let t of e.profiles){let e=q(await n.get(t.committed.profileId));if(e===null||!Xo(e,t.committed))throw Error(`[SeamsWalletDB] wallet signer rollback profile changed`)}for(let t of e.signers){let e=t.committed,n=ho({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId}),i=W(await r.get(n));if(i===null||!os(i,e,t.metadataBaseline))throw Error(`[SeamsWalletDB] wallet signer rollback signer changed`)}for(let t of e.keyMaterials){let e=t.committed,n=Ac({walletSignerId:jc(e),keyKind:e.keyKind}),r=Ic(await i.get(n));if(r===null||!ss(r,e,t.payloadBaseline))throw Error(`[SeamsWalletDB] wallet signer rollback key material changed`)}if(e.lastProfileState){let t=dr(wo(await a.get(e.lastProfileState.key))?.value);if(t===null||!ls(t,e.lastProfileState.committed))throw Error(`[SeamsWalletDB] wallet signer rollback selection changed`)}for(let t of e.signers){let e=t.committed;await r.delete(ho({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId}))}for(let t of e.keyMaterials){let e=t.committed;await i.delete(Ac({walletSignerId:jc(e),keyKind:e.keyKind}))}for(let t of e.profiles)t.previous?await n.put(Ko(t.previous)):await n.delete(t.committed.profileId);e.lastProfileState&&(e.lastProfileState.previousPresent?await a.put({key:e.lastProfileState.key,value:e.lastProfileState.previousValue}):await a.delete(e.lastProfileState.key))})}async clearProfileAuthenticators(e){let t=c(e||``);t&&await this.manager.runTransaction([w.walletAuthMethods],`readwrite`,async e=>{await Ho({store:e.store(w.walletAuthMethods),indexName:T.walletIdKind,key:IDBKeyRange.only([t,`passkey`])})})}async selectProfileAuthenticatorsForPrompt(e){let t=c(e.profileId||``),n=Array.isArray(e.authenticators)?e.authenticators:[];if(!t||n.length<=1)return{authenticatorsForPrompt:n};let r=await this.getLastProfileState().catch(()=>null);if(!r)return{authenticatorsForPrompt:n};let i=Number(r.activeSignerSlot),a=n.filter(e=>e.signerSlot===i),o=c(a[0]?.credentialId||n[0]?.credentialId||``),s=o?n.filter(e=>e.credentialId===o):[],l=s.length>0?s:a.length>0?a:n,u=c(e.selectedCredentialRawId||``),d=c(e.accountLabel||t);return{authenticatorsForPrompt:l,wrongPasskeyError:u&&o&&u!==o?`You have multiple passkeys for account ${d}, but used a different passkey than the most recently logged-in one. Please use the passkey for the most recently active signer.`:void 0}}async updatePreferences(e){let t=c(e.profileId||``);if(!t)return null;let n=null;return await this.manager.runTransaction([w.wallets],`readwrite`,async r=>{let i=r.store(w.wallets),a=q(await i.get(t));if(!a)return;n={...a.preferences||{},...e.preferences};let o=Go({profileId:a.profileId,defaultSignerSlot:a.defaultSignerSlot,preferences:n,...a.passkeyCredential?{passkeyCredential:a.passkeyCredential}:{}},a);await i.put(o)}),n}async updateWalletPreferences(e){let t=c(e.walletId||``);return t?await this.updatePreferences({profileId:t,preferences:e.preferences}):null}async deleteProfileData(e,t){let n=c(e||``);n&&await this.manager.runTransaction([w.appState,w.wallets,w.walletAuthMethods,w.walletSigners,w.nearAccountProjections,w.signerOpsOutbox,w.keyMaterial,w.ecdsaClientPresignatures],`readwrite`,async e=>{let r=e.store(w.appState);dr((await r.get(Uo()))?.value)?.profileId===n&&await r.put({key:Uo(),value:null});let i=Uo(t);i!==Uo()&&dr((await r.get(i))?.value)?.profileId===n&&await r.put({key:i,value:null}),await e.store(w.wallets).delete(n),await Ho({store:e.store(w.walletAuthMethods),indexName:T.walletId,key:IDBKeyRange.only(n)}),await Ho({store:e.store(w.walletSigners),indexName:T.walletId,key:IDBKeyRange.only(n)}),await Ho({store:e.store(w.nearAccountProjections),indexName:T.profileId,key:IDBKeyRange.only(n)}),await Ho({store:e.store(w.signerOpsOutbox),indexName:T.walletId,key:IDBKeyRange.only(n)}),await Ho({store:e.store(w.keyMaterial),indexName:T.walletId,key:IDBKeyRange.only(n)}),await Ho({store:e.store(w.ecdsaClientPresignatures),indexName:T.walletId,key:IDBKeyRange.only(n)})})}async getLastProfileState(e){let t=Uo(e);return dr(await this.getAppState(t).catch(()=>void 0))}async setLastProfileState(e,t){let n=Uo(t),r=e?dr(e):null;if(e&&!r)throw Error(`[SeamsWalletDB] invalid last profile state`);await this.setAppState(n,r)}async setLastProfileStateForProfile(e,t,n){let r=c(e||``),i=Number(t);if(!r)throw Error(`[SeamsWalletDB] profileId is required`);if(!Number.isSafeInteger(i)||i<1)throw Error(`[SeamsWalletDB] activeSignerSlot must be an integer >= 1`);let a=we(n);await this.setLastProfileState({profileId:r,activeSignerSlot:i,...a?{scope:a}:{}},a)}async clearLastProfileSelection(e){await this.setLastProfileState(null,e)}async storeKeyMaterial(e){let t=Mc(e);await this.manager.runTransaction([w.keyMaterial],`readwrite`,async e=>{await e.store(w.keyMaterial).put(t)})}async getKeyMaterial(e,t,n,r){let i=c(e||``),a=c(n||``).toLowerCase(),o=c(r||``);if(!i||!a||!o)return null;let s=null;return await this.manager.runTransaction([w.keyMaterial,w.walletSigners],`readonly`,async e=>{let n=(await e.store(w.keyMaterial).index(T.walletId).getAll(i)).flatMap(e=>{let n=Ic(e);return n&&n.signerSlot===t&&n.chainIdKey===a&&n.keyKind===o?[n]:[]});if(n.length===0){s=null;return}s=Gc({matches:n,activeSigners:(await e.store(w.walletSigners).index(T.walletId).getAll(i)).flatMap(e=>{let n=W(e);return n?.status===`active`&&n.signerSlot===t&&n.chainIdKey===a?[n]:[]})})}),s}async listKeyMaterialByProfile(e,t){let n=c(e||``),r=c(t||``).toLowerCase();if(!n)return[];let i=(await this.manager.getDB()).transaction(w.keyMaterial,`readonly`),a=await i.store.index(T.walletId).getAll(n);await i.done;let o=a.flatMap(e=>{let t=Ic(e);return t?[t]:[]});return r?o.filter(e=>e.chainIdKey===r):o}async listKeyMaterialByProfileAndSignerSlot(e,t,n){return!Number.isSafeInteger(t)||t<1?[]:(await this.listKeyMaterialByProfile(e,n)).filter(e=>e.signerSlot===t)}async deleteKeyMaterial(e,t,n,r){let i=c(e||``),a=c(n||``).toLowerCase(),o=c(r||``);!i||!a||!o||!Number.isSafeInteger(t)||t<1||await this.manager.runTransaction([w.keyMaterial],`readwrite`,async e=>{let n=e.store(w.keyMaterial),r=await n.index(T.walletId).getAll(i);for(let e of r){let r=Ic(e);r&&r.signerSlot===t&&r.chainIdKey===a&&r.keyKind===o&&await n.delete(Ac({walletSignerId:jc(r),keyKind:r.keyKind}))}})}async readNonceLaneLeaseRecords(e){let t=c(e||``);if(!t)return[];let n=(await this.manager.getDB()).transaction(w.nonceLaneLeases,`readonly`),r=await n.store.index(T.laneKey).getAll(t);return await n.done,r.flatMap(e=>{let t=lo(e);return t?[t]:[]})}async listNonceLaneLeaseRecords(e){let t=c(e?.walletId||``),n=(await this.manager.getDB()).transaction(w.nonceLaneLeases,`readonly`),r=t?await n.store.index(T.walletId).getAll(t):await n.store.getAll();return await n.done,r.flatMap(e=>{let t=lo(e);return t?[t]:[]})}async upsertNonceLaneLeaseRecord(e){let t=ao(e);await this.manager.runTransaction([w.nonceLaneLeases],`readwrite`,async e=>{await e.store(w.nonceLaneLeases).put(t)})}async removeNonceLaneLeaseRecord(e){let t=c(e.leaseId||``);t&&await this.manager.runTransaction([w.nonceLaneLeases],`readwrite`,async e=>{await e.store(w.nonceLaneLeases).delete(t)})}async clearNonceLaneLeaseRecordsForWallet(e){let t=c(e||``);t&&await this.manager.runTransaction([w.nonceLaneLeases],`readwrite`,async e=>{let n=e.store(w.nonceLaneLeases),r=await n.index(T.walletId).getAll(t);for(let e of r){let t=lo(e);t&&t.state!==`broadcast_accepted`&&await n.delete(t.leaseId)}})}async clearAllNonceLaneLeaseRecords(){await this.manager.runTransaction([w.nonceLaneLeases],`readwrite`,async e=>{await e.store(w.nonceLaneLeases).clear()})}async pruneExpiredNonceLaneLeaseRecords(e){let t=Math.floor(Number(e));Number.isSafeInteger(t)&&await this.manager.runTransaction([w.nonceLaneLeases],`readwrite`,async e=>{let n=e.store(w.nonceLaneLeases),r=await n.index(T.expiresAtMs).getAll(Vo(t));for(let e of r){let t=lo(e);t&&t.state!==`broadcast_accepted`&&await n.delete(t.leaseId)}})}async withNonceLaneCoordinationLock(e,t){let n=c(e.lockKey||``),r=c(e.ownerId||``);if(!n||!r)throw Error(`[SeamsWalletDB] nonce lane lock requires lockKey and ownerId`);let i=Math.max(1,Math.floor(Number(e.ttlMs)||5e3)),a=Math.max(1,Math.floor(Number(e.waitTimeoutMs)||3e3)),o=Bo(`nonce-lane-lock`),s=Date.now()+a,l=async()=>{let e=!1;return await this.manager.runTransaction([w.nonceLaneLocks],`readwrite`,async t=>{let a=t.store(w.nonceLaneLocks),s=Date.now(),c=oo(await a.get(n));if(c&&c.expires_at_ms>s)return;let l={lock_key:n,owner_id:r,fencing_token:o,acquired_at_ms:s,expires_at_ms:s+i,updated_at_ms:s};await a.put(l),e=!0}),e};for(;!await l();){if(Date.now()>=s){let e=Error(`[SeamsWalletDB] durable nonce lane lock timed out`);throw e.code=`durable_lock_timeout`,e}await zo(25)}try{return await t()}finally{await this.manager.runTransaction([w.nonceLaneLocks],`readwrite`,async e=>{let t=e.store(w.nonceLaneLocks);oo(await t.get(n))?.fencing_token===o&&await t.delete(n)}).catch(()=>void 0)}}};const qc=new Set(Object.values(ge));var Jc=class{seamsWalletDB;seamsWalletRepositories;registrationSetupRepository;eventListeners=new Set;_initialized=!1;lastUserScope=null;constructor(e){this.seamsWalletDB=e?.seamsWalletDB||xe,this.seamsWalletRepositories=new Kc(this.seamsWalletDB),this.registrationSetupRepository=new _e(this.seamsWalletDB)}async initialize(){if(!this._initialized)try{if(this.seamsWalletDB.isDisabled()){this._initialized=!0;return}await this.seamsWalletRepositories.getAppState(`_init_check`);try{await this.repairSignerMutationSagas({limit:64})}catch(e){console.warn(`IndexedDB saga repair failed during initialize:`,e)}try{await this.reconcileLocalSignerState({limitProfiles:64,logIssues:!0})}catch(e){console.warn(`IndexedDB local signer reconciliation failed during initialize:`,e)}this._initialized=!0}catch(e){console.warn(`Failed to initialize IndexedDB databases:`,e)}}get isInitialized(){return this._initialized}isDisabled(){return this.seamsWalletDB.isDisabled()}onChange(e){return this.eventListeners.add(e),()=>{this.eventListeners.delete(e)}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch(e){console.warn(`[UnifiedIndexedDBManager]: Error in event listener:`,e)}}async getAppState(e){return this.seamsWalletRepositories.getAppState(e)}async listAppStateEntriesByPrefix(e){return this.seamsWalletRepositories.listAppStateEntriesByPrefix(e)}async setAppState(e,t){return this.seamsWalletRepositories.setAppState(e,t)}async putPendingWalletRegistrationCommits(e){return this.seamsWalletRepositories.putPendingWalletRegistrationCommits(e)}async advancePendingNearRegistration(e){return this.seamsWalletRepositories.advancePendingNearRegistration(e)}async putPendingWalletRegistrationCommit(e){return this.seamsWalletRepositories.putPendingWalletRegistrationCommit(e)}async getPendingWalletRegistrationCommit(e){return this.seamsWalletRepositories.getPendingWalletRegistrationCommit(e)}async listPendingWalletRegistrationCommits(){return this.seamsWalletRepositories.listPendingWalletRegistrationCommits()}async deletePendingWalletRegistrationCommit(e){return this.seamsWalletRepositories.deletePendingWalletRegistrationCommit(e)}async putPendingWalletRecoveryCommit(e){return this.seamsWalletRepositories.putPendingWalletRecoveryCommit(e)}async advancePendingWalletRecoveryCommit(e){return this.seamsWalletRepositories.advancePendingWalletRecoveryCommit(e)}async getPendingWalletRecoveryCommit(e){return this.seamsWalletRepositories.getPendingWalletRecoveryCommit(e)}async listPendingWalletRecoveryCommits(){return this.seamsWalletRepositories.listPendingWalletRecoveryCommits()}async deletePendingWalletRecoveryCommit(e){return this.seamsWalletRepositories.deletePendingWalletRecoveryCommit(e)}setLastUserScope(e){this.lastUserScope=we(e)}getLastUserScope(){return this.lastUserScope}async getLastProfileState(){return this.seamsWalletRepositories.getLastProfileState(this.lastUserScope)}async setLastProfileState(e){return this.seamsWalletRepositories.setLastProfileState(e,this.lastUserScope)}async setLastProfileStateForProfile(e,t){return this.seamsWalletRepositories.setLastProfileStateForProfile(e,t,this.lastUserScope)}async clearLastProfileSelection(){return this.seamsWalletRepositories.clearLastProfileSelection(this.lastUserScope)}async readNonceLaneLeaseRecords(e){return this.seamsWalletRepositories.readNonceLaneLeaseRecords(e)}async listNonceLaneLeaseRecords(e){return this.seamsWalletRepositories.listNonceLaneLeaseRecords(e)}async upsertNonceLaneLeaseRecord(e){return this.seamsWalletRepositories.upsertNonceLaneLeaseRecord(e)}async removeNonceLaneLeaseRecord(e){return this.seamsWalletRepositories.removeNonceLaneLeaseRecord(e)}async clearNonceLaneLeaseRecordsForWallet(e){return this.seamsWalletRepositories.clearNonceLaneLeaseRecordsForWallet(e)}async clearAllNonceLaneLeaseRecords(){return this.seamsWalletRepositories.clearAllNonceLaneLeaseRecords()}async pruneExpiredNonceLaneLeaseRecords(e){return this.seamsWalletRepositories.pruneExpiredNonceLaneLeaseRecords(e)}async withNonceLaneCoordinationLock(e,t){return this.seamsWalletRepositories.withNonceLaneCoordinationLock(e,t)}async getProfile(e){return this.seamsWalletRepositories.getProfile(e)}async getWalletPreferences(e){return await this.seamsWalletRepositories.getWalletPreferences(e)}async listProfiles(e){return this.seamsWalletRepositories.listProfiles(e)}async upsertProfile(e){return this.seamsWalletRepositories.upsertProfile(e)}async upsertChainAccount(e){return this.seamsWalletRepositories.upsertChainAccount(e)}async listChainAccountsByProfile(e){return this.seamsWalletRepositories.listChainAccountsByProfile(e)}async listChainAccountsByProfileAndChain(e,t){return this.seamsWalletRepositories.listChainAccountsByProfileAndChain(e,t)}async listChainAccountsByChain(e){return this.seamsWalletRepositories.listChainAccountsByChain(e)}async getChainAccount(e){return this.seamsWalletRepositories.getChainAccount(e)}async resolveProfileAccountContext(e){return this.seamsWalletRepositories.resolveProfileAccountContext(e)}async getProfileContinuitySnapshot(e){return this.seamsWalletRepositories.getProfileContinuitySnapshot(e)}async activateAccountSigner(e){return this.seamsWalletRepositories.activateAccountSigner(e)}async stageAccountSigner(e){return this.seamsWalletRepositories.stageAccountSigner(e)}async listAccountSigners(e){return this.seamsWalletRepositories.listAccountSigners(e)}async listAccountSignersByProfile(e){return this.seamsWalletRepositories.listAccountSignersByProfile(e)}async listActiveWalletSigners(e){return this.seamsWalletRepositories.listActiveWalletSigners(e)}async getActiveWalletSignerForChainTarget(e){return this.seamsWalletRepositories.getActiveWalletSignerForChainTarget(e)}async getAccountSigner(e){return this.seamsWalletRepositories.getAccountSigner(e)}async setAccountSignerStatus(e){return this.seamsWalletRepositories.setAccountSignerStatus(e)}async enqueueSignerOperation(e){return this.seamsWalletRepositories.enqueueSignerOperation(e)}async listSignerOperations(e){return this.seamsWalletRepositories.listSignerOperations(e)}async setSignerOperationStatus(e){return this.seamsWalletRepositories.setSignerOperationStatus(e)}async listProfileAuthenticators(e){return this.seamsWalletRepositories.listProfileAuthenticators(e)}async listWalletPasskeyAuthenticators(e){return this.seamsWalletRepositories.listWalletPasskeyAuthenticators(e)}async upsertProfileAuthenticator(e){return this.seamsWalletRepositories.upsertProfileAuthenticator(e)}async getProfileAuthenticatorByCredentialId(e,t){return this.seamsWalletRepositories.getProfileAuthenticatorByCredentialId(e,t)}async getWalletPasskeyAuthenticator(e){return this.seamsWalletRepositories.getWalletPasskeyAuthenticator(e)}async upsertWalletAuthMethod(e){return this.seamsWalletRepositories.upsertWalletAuthMethod(e)}async upsertWalletAuthMethodV2(e){await this.seamsWalletRepositories.upsertWalletAuthMethodV2(e)}async listWalletAuthMethodsForWallet(e){return this.seamsWalletRepositories.listWalletAuthMethodsForWallet(e)}async listWalletAuthMethodsV2ForWallet(e){return this.seamsWalletRepositories.listWalletAuthMethodsV2ForWallet(e)}async listLocalWalletAuthMethodProjectionsV2ForWallet(e){return this.seamsWalletRepositories.listLocalWalletAuthMethodProjectionsV2ForWallet(e)}async retainVerifiedEmailOtpLocalPresentation(e){return this.seamsWalletRepositories.retainVerifiedEmailOtpLocalPresentation(e)}async installLocalAuthority(e){return this.seamsWalletRepositories.installLocalAuthority(e)}async finalizeLocalAuthorityActivation(e){return this.seamsWalletRepositories.finalizeLocalAuthorityActivation(e)}async publishLocalAuthorityActivation(e){return this.seamsWalletRepositories.publishLocalAuthorityActivation(e)}async advanceWalletLockGeneration(e){return this.seamsWalletRepositories.advanceWalletLockGeneration(e)}async markWalletSelectionUnlocked(e){await this.seamsWalletRepositories.markWalletSelectionUnlocked(e)}async markWalletSelectionUnlockedAtGeneration(e){await this.seamsWalletRepositories.markWalletSelectionUnlockedAtGeneration(e)}async persistRecoveredWalletAuthority(e){await this.seamsWalletRepositories.persistRecoveredWalletAuthority(e)}async getLocalAuthorityInstallationReceipt(e){return this.seamsWalletRepositories.getLocalAuthorityInstallationReceipt(e)}async getWalletAuthority(e){return this.seamsWalletRepositories.getWalletAuthority(e)}async persistFoundingWalletAuthority(e){await this.seamsWalletRepositories.persistFoundingWalletAuthority(e)}async getWalletAuthMethodV2(e){return this.seamsWalletRepositories.getWalletAuthMethodV2(e)}async listWalletSelections(){return this.seamsWalletRepositories.listWalletSelections()}async listWalletSelectionWalletIds(){return this.seamsWalletRepositories.listWalletSelectionWalletIds()}async resolveSelectedWalletAuthority(e){return this.seamsWalletRepositories.resolveSelectedWalletAuthority(e)}async resolveWalletAuthorityForMethod(e,t){return this.seamsWalletRepositories.resolveWalletAuthorityForMethod(e,t)}async persistWalletRegistrationFinalize(e){return this.seamsWalletRepositories.persistWalletRegistrationFinalize(e)}async publishPendingWalletRegistrationCommit(e){let t=await this.seamsWalletRepositories.publishPendingWalletRegistrationCommit(e);try{await this.registrationSetupRepository.complete(e.pending)}catch(e){console.warn(`Wallet registration committed; setup journal cleanup remains pending`,e)}return t}async publishPendingWalletRegistrationCommitAndRetain(e){return this.seamsWalletRepositories.publishPendingWalletRegistrationCommitAndRetain(e)}async adoptAddedEcdsaSignerAuthority(e){await this.seamsWalletRepositories.adoptAddedEcdsaSignerAuthority(e)}async replaceExactActiveWalletSessionFromStatus(e){return await this.seamsWalletRepositories.replaceExactActiveWalletSessionFromStatus(e)}async reconcilePendingNearRegistrationAuthority(e){await this.seamsWalletRepositories.reconcilePendingNearRegistrationAuthority(e)}async completePendingNearRegistration(e){await this.seamsWalletRepositories.completePendingNearRegistration(e)}async publishPendingWalletRecoveryCommit(e){return this.seamsWalletRepositories.publishPendingWalletRecoveryCommit(e)}async persistWalletSignerFinalize(e){return this.seamsWalletRepositories.persistWalletSignerFinalize(e)}async rollbackWalletSignerFinalize(e){return this.seamsWalletRepositories.rollbackWalletSignerFinalize(e)}async clearProfileAuthenticators(e){return this.seamsWalletRepositories.clearProfileAuthenticators(e)}async selectProfileAuthenticatorsForPrompt(e){return this.seamsWalletRepositories.selectProfileAuthenticatorsForPrompt(e)}async updatePreferences(e){let t=await this.seamsWalletRepositories.updatePreferences(e),n=c(e.eventAccountId||``);t&&n&&this.emitEvent({type:`preferences-updated`,accountId:n,data:{preferences:t}})}async updateWalletPreferences(e){let t=await this.seamsWalletRepositories.updateWalletPreferences(e);return t&&this.emitEvent({type:`preferences-updated`,accountId:e.walletId,data:{preferences:t}}),t}async deleteProfileData(e,t){await this.seamsWalletRepositories.deleteProfileData(e,this.lastUserScope);let n=c(t?.eventAccountId||``);n&&this.emitEvent({type:`user-deleted`,accountId:n})}async storeKeyMaterial(e){return this.seamsWalletRepositories.storeKeyMaterial(e)}async getKeyMaterial(e,t,n,r){return this.seamsWalletRepositories.getKeyMaterial(e,t,n,r)}async deleteKeyMaterial(e,t,n,r){return this.seamsWalletRepositories.deleteKeyMaterial(e,t,n,r)}async listKeyMaterialByProfile(e,t){return this.seamsWalletRepositories.listKeyMaterialByProfile(e,t)}async reconcileLocalSignerState(e){let t=typeof e?.now==`number`?e.now:Date.now(),n=Number.isSafeInteger(e?.stalePendingSignerMs)&&Number(e?.stalePendingSignerMs)>0?Number(e?.stalePendingSignerMs):864e5,r=c(e?.profileId||``),i=r?await this.getProfile(r).then(e=>e?[e]:[]):await this.listProfiles({limit:e?.limitProfiles}),a={scannedProfiles:0,scannedSigners:0,scannedKeyMaterials:0,issues:[],repairs:[]},o=e=>{a.issues.push(e)};for(let e of i){a.scannedProfiles+=1;let r=await this.listAccountSignersByProfile({profileId:e.profileId}),i=await this.seamsWalletRepositories.listKeyMaterialByProfile(e.profileId);a.scannedSigners+=r.length,a.scannedKeyMaterials+=i.length;let s=new Map,c=new Set;for(let e of r){if(e.status!==`active`)continue;let t=[e.chainIdKey,e.accountAddress,String(e.signerSlot)].join(`\0`);c.add(t);let n=s.get(t)||[];n.push(e),s.set(t,n)}for(let[t,n]of s.entries()){if(n.length<=1)continue;let[r,i,a]=t.split(`\0`);o({code:`duplicate_active_signer_slot`,profileId:e.profileId,chainIdKey:r,accountAddress:i,signerSlot:Number(a),message:`Multiple active signers share slot ${a} for ${r}/${i}`})}for(let a of r)a.status===`pending`&&t-Number(a.addedAt||0)>n&&o({code:`stale_pending_signer`,profileId:e.profileId,chainIdKey:a.chainIdKey,accountAddress:a.accountAddress,signerId:a.signerId,signerSlot:a.signerSlot,message:`Pending signer ${a.signerId} has been pending longer than ${n}ms`}),a.status===`active`&&qc.has(String(a.signerKind||``))&&i.filter(e=>e.chainIdKey===a.chainIdKey&&e.signerSlot===a.signerSlot&&e.keyKind===`threshold_share_v1`).length===0&&o({code:`active_signer_missing_key_material`,profileId:e.profileId,chainIdKey:a.chainIdKey,accountAddress:a.accountAddress,signerId:a.signerId,signerSlot:a.signerSlot,message:`Active ${a.signerKind} signer ${a.signerId} has no threshold key material`});for(let t of i){let n=[t.chainIdKey,t.payloadEnvelope?.aad?.accountAddress||``,String(t.signerSlot)].join(`\0`);c.has(n)||r.some(e=>e.status===`active`&&e.chainIdKey===t.chainIdKey&&e.signerSlot===t.signerSlot)||o({code:`key_material_without_active_signer`,profileId:e.profileId,chainIdKey:t.chainIdKey,signerSlot:t.signerSlot,keyKind:t.keyKind,message:`Key material ${t.keyKind} at slot ${t.signerSlot} has no active signer`})}}return e?.logIssues&&a.issues.length>0&&console.warn(`[IndexedDB] local signer reconciliation found issues`,{issueCount:a.issues.length,issues:a.issues.slice(0,20)}),a}computeSignerOpRetryDelayMs(e){let t=Math.max(1,Math.min(e,8));return Math.min(5*6e4,5e3*2**(t-1))}async repairSignerMutationSagas(e){return await this.repairSignerMutationSagasWithRuntime(e)}async repairSignerMutationSagasWithRuntime(e){let t=typeof e?.now==`number`?e.now:Date.now(),n=Number.isSafeInteger(e?.limit)&&Number(e?.limit)>0?Number(e?.limit):100,r={scanned:0,confirmed:0,failed:0,deadLettered:0},i=await this.listSignerOperations({statuses:[`queued`,`submitted`,`failed`],dueBefore:t,limit:n});for(let e of i){r.scanned+=1;let n=e.payload||{},i=await this.getAccountSigner({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId}),a=c(i?.profileId||n.profileId||``),o=Number(n.signerSlot??i?.signerSlot),s=Number.isSafeInteger(o)&&o>=1?o:null,l=async n=>{let i=(e.attemptCount||0)+1;await this.setSignerOperationStatus({opId:e.opId,status:`failed`,attemptDelta:1,lastError:n,nextAttemptAt:t+this.computeSignerOpRetryDelayMs(i)}),r.failed+=1},u=async n=>{await this.setSignerOperationStatus({opId:e.opId,status:`dead-letter`,lastError:n,nextAttemptAt:t}),r.deadLettered+=1},d=async()=>{await this.setSignerOperationStatus({opId:e.opId,status:`confirmed`,lastError:null,nextAttemptAt:t}),r.confirmed+=1};try{if(e.opType===`add-signer`||e.opType===`activate-recovery-signer`){if(!i){await u(`Missing signer row for add-signer operation`);continue}if(i.status===`revoked`){await u(`Cannot activate a revoked signer; create a new signer record`);continue}if(!a||s==null){await u(`Missing profileId/signerSlot metadata for add-signer operation`);continue}if(!await this.getChainAccount({profileId:i.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress})){await u(`Missing chain account row for add-signer operation`);continue}if((await this.seamsWalletRepositories.listKeyMaterialByProfileAndSignerSlot(a,s,e.chainIdKey)).length===0){await l(`Missing key material for signer operation`);continue}await d();continue}if(e.opType===`revoke-signer`){if(i&&(i.status!==`revoked`&&await this.setAccountSignerStatus({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,status:`revoked`,removedAt:t,mutation:{routeThroughOutbox:!1}}),a&&s!=null)){let t=await this.seamsWalletRepositories.listKeyMaterialByProfileAndSignerSlot(a,s,e.chainIdKey);for(let e of t)await this.seamsWalletRepositories.deleteKeyMaterial(e.profileId,e.signerSlot,e.chainIdKey,e.keyKind)}await d();continue}await u(`Unsupported signer operation type: ${String(e.opType||``)}`)}catch(e){await l(String(e?.message||e||`Unknown saga repair error`))}}return r}};function Yc(e){if(!e||typeof e!=`object`||Array.isArray(e))return rl({},``,``,``);let t=e,n=$(t.leaseId),r=$(t.laneKey),i=$(t.family),a=$(t.networkKey),o=$(t.accountId),s=$(t.nearAccountId);if(t.v!==1)return rl(t,r,n,i);let c=al(t.nonce),l=$c(t),u=$(t.operationId),d=$(t.operationFingerprint),f=ol(t.reservedAtMs),p=ol(t.expiresAtMs),m=ol(t.updatedAtMs);return!n||!r||i!==`evm`&&i!==`near`||!a||c==null||!l||!u||!d||f==null||p==null||m==null?rl(t,r,n,i):i===`evm`?Xc({obj:t,leaseId:n,laneKey:r,networkKey:a,accountId:o,nearAccountId:s,nonce:c,lifecycle:l,operationId:u,operationFingerprint:d,reservedAtMs:f,expiresAtMs:p,updatedAtMs:m}):Zc({obj:t,leaseId:n,laneKey:r,networkKey:a,accountId:o,nearAccountId:s,nonce:c,lifecycle:l,operationId:u,operationFingerprint:d,reservedAtMs:f,expiresAtMs:p,updatedAtMs:m})}function Xc(e){let t=nl(e.obj.chainTarget),n=il(e.obj.sender),r=el(e.lifecycle),i=e.obj.nonceKey===void 0||e.obj.nonceKey===null?void 0:al(e.obj.nonceKey);if(!t||!e.accountId||!n||!r||i===null)return rl(e.obj,e.laneKey,e.leaseId,`evm`);let a={...Qc(e,r),family:`evm`,chainTarget:t,accountId:Ce(e.accountId),sender:n};i!==void 0&&(a.nonceKey=i);let o={family:`evm`,chainTarget:a.chainTarget,subjectId:a.accountId,sender:a.sender};return a.nonceKey!=null&&(o.nonceKey=a.nonceKey),{ok:!0,parsed:{record:a,lane:o,canonicalLaneKey:kn(o),nonce:a.nonce}}}function Zc(e){let t=$(e.obj.publicKey),n=$(e.obj.walletId);if(!e.nearAccountId||!n||!t)return rl(e.obj,e.laneKey,e.leaseId,`near`);let r={...Qc(e,e.lifecycle),family:`near`,walletId:n,nearAccountId:e.nearAccountId,publicKey:t},i={family:`near`,networkKey:r.networkKey,walletId:r.walletId,nearAccountId:r.nearAccountId,publicKey:r.publicKey};return{ok:!0,parsed:{record:r,lane:i,canonicalLaneKey:kn(i),nonce:r.nonce}}}function Qc(e,t){let n={v:1,leaseId:e.leaseId,laneKey:e.laneKey,networkKey:e.networkKey,nonce:e.nonce,operationId:e.operationId,operationFingerprint:e.operationFingerprint,reservedAtMs:e.reservedAtMs,expiresAtMs:e.expiresAtMs,updatedAtMs:e.updatedAtMs},r=$(e.obj.runtimeId);r&&(n.runtimeId=r);let i=$(e.obj.fencingToken);i&&(n.fencingToken=i);let a=$(e.obj.batchId);a&&(n.batchId=a);let o=e.obj.txIndex==null?null:ol(e.obj.txIndex);switch(o!=null&&(n.txIndex=o),t.state){case F.Reserved:case F.Signed:return{...n,state:t.state};case F.BroadcastAccepted:return{...n,state:F.BroadcastAccepted,txHash:t.txHash}}}function $c(e){if(e.state===F.Reserved)return e.txHash===void 0?{state:F.Reserved}:null;if(e.state===F.Signed)return e.txHash===void 0?{state:F.Signed}:null;if(e.state===F.BroadcastAccepted){let t=$(e.txHash);return t?{state:F.BroadcastAccepted,txHash:t}:{state:F.Signed}}return null}function el(e){if(e.state!==F.BroadcastAccepted)return e;let t=tl(e.txHash);return t?{state:F.BroadcastAccepted,txHash:t}:{state:F.Signed}}function tl(e){let t=$(e).toLowerCase();return/^0x[0-9a-f]{64}$/.test(t)?t:null}function nl(e){try{return Se(e&&typeof e==`object`&&!Array.isArray(e)?e:{})}catch{return null}}function rl(e,t,n,r){let i={reason:On.MalformedDurableRecord,fallback:An.None};(r===`evm`||r===`near`)&&(i.laneFamily=r);let a=$(e.networkKey);a&&(i.networkKey=a);let o=$(e.walletId)||$(e.accountId);return o&&(i.accountId=o),{ok:!1,laneKey:t,leaseId:n,degradation:i}}function il(e){let t=$(e).toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:null}function $(e){return typeof e==`string`?e.trim():``}function al(e){return typeof e!=`string`||!/^\d+$/.test(e)?null:BigInt(e)}function ol(e){if(typeof e==`number`)return Number.isSafeInteger(e)?e:null;if(typeof e!=`string`||!/^\d+$/.test(e))return null;let t=Number(e);return Number.isSafeInteger(t)?t:null}function sl(e){return{readLane:async t=>(await e.indexedDB.readNonceLaneLeaseRecords(t)).flatMap(e=>{let t=Yc(e);return t.ok?[t.parsed]:[]}),readAll:async t=>(await e.indexedDB.listNonceLaneLeaseRecords(t)).flatMap(e=>{let t=Yc(e);return t.ok?[t.parsed]:[]}),readAllForRecovery:async t=>(await e.indexedDB.listNonceLaneLeaseRecords(t)).map(e=>Yc(e)),upsert:async t=>{if(t.family===`evm`){await e.indexedDB.upsertNonceLaneLeaseRecord(ll(t));return}await e.indexedDB.upsertNonceLaneLeaseRecord(ul(t))},remove:async t=>{await e.indexedDB.removeNonceLaneLeaseRecord({leaseId:t.leaseId})},clearForWallet:async t=>{await e.indexedDB.clearNonceLaneLeaseRecordsForWallet(t)},clearAll:async()=>{await e.indexedDB.clearAllNonceLaneLeaseRecords()},pruneExpired:async t=>{await e.indexedDB.pruneExpiredNonceLaneLeaseRecords(t)},withLock:async(t,n)=>await e.indexedDB.withNonceLaneCoordinationLock({lockKey:t.lockKey,ownerId:t.ownerId,...t.ttlMs==null?{}:{ttlMs:t.ttlMs},...t.waitTimeoutMs==null?{}:{waitTimeoutMs:t.waitTimeoutMs}},n)}}function cl(e){return{...e.runtimeId?{runtimeId:e.runtimeId}:{},...e.fencingToken?{fencingToken:e.fencingToken}:{},...e.batchId?{batchId:e.batchId}:{},...typeof e.txIndex==`number`&&Number.isSafeInteger(e.txIndex)?{txIndex:e.txIndex}:{}}}function ll(e){let t={v:1,laneKey:e.laneKey,leaseId:e.leaseId,networkKey:e.networkKey,nonce:e.nonce.toString(),operationId:e.operationId,operationFingerprint:e.operationFingerprint,reservedAtMs:e.reservedAtMs,expiresAtMs:e.expiresAtMs,updatedAtMs:e.updatedAtMs,family:`evm`,chainTarget:e.chainTarget,accountId:e.accountId,sender:e.sender,...e.nonceKey==null?{}:{nonceKey:e.nonceKey.toString()},...cl(e)};switch(e.state){case`reserved`:case`signed`:return{...t,state:e.state};case`broadcast_accepted`:return{...t,state:`broadcast_accepted`,txHash:e.txHash}}}function ul(e){let t={v:1,laneKey:e.laneKey,leaseId:e.leaseId,networkKey:e.networkKey,nonce:e.nonce.toString(),operationId:e.operationId,operationFingerprint:e.operationFingerprint,reservedAtMs:e.reservedAtMs,expiresAtMs:e.expiresAtMs,updatedAtMs:e.updatedAtMs,family:`near`,walletId:e.walletId,nearAccountId:e.nearAccountId,publicKey:e.publicKey,...cl(e)};switch(e.state){case`reserved`:case`signed`:return{...t,state:e.state};case`broadcast_accepted`:return{...t,state:`broadcast_accepted`,txHash:e.txHash}}}const dl={app:{walletDbName:de,disabled:!1},wallet:{walletDbName:de,disabled:!1},disabled:{walletDbName:de,disabled:!0}};let fl=null;function pl(e){let t=e?.mode,n=dl[t];if(!n)throw Error(`[IndexedDBManager] Unknown IndexedDBMode: ${String(t)}`);return fl?(fl.walletDbName===n.walletDbName&&fl.disabled===n.disabled||console.warn(`[IndexedDBManager] configureIndexedDB called multiple times; ignoring subsequent configuration`,{configured:fl,requested:n}),{walletDbName:fl.walletDbName}):(fl={mode:t,...n},xe.setDbName(n.walletDbName),xe.setDisabled(n.disabled),{walletDbName:fl.walletDbName})}const ml=new Jc({seamsWalletDB:xe});export{Jn as A,$n as C,Yn as D,Qn as E,Mn as F,I as M,qn as N,Hn as O,Nn as P,hr as S,tr as T,ii as _,Z as a,Tr as b,to as c,Pa as d,Na as f,li as g,oi as h,Kc as i,Gn as j,Kn as k,Ba as l,Mi as m,pl as n,X as o,Da as p,sl as r,Q as s,ml as t,no as u,ai as v,nr as w,pr as x,Er as y};