@seams/wallet 0.20.0 → 0.22.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.
- package/dist/.build-inputs.sha256 +1 -1
- package/dist/esm/SeamsWeb/SeamsWeb.js +2 -2
- package/dist/esm/SeamsWeb/operations/recovery/walletRecoveryCodeBackup.js +25 -5
- package/dist/esm/SeamsWeb/operations/tempo/executeEvmFamilyTransaction.js +4 -2
- package/dist/esm/SeamsWeb/walletIframe/client/router.js +5 -2
- package/dist/esm/core/rpcClients/evm/EvmClient.js +11 -9
- package/dist/esm/core/signingEngine/flows/signEvmFamily/thresholdAdmission.js +1 -1
- package/dist/esm/core/signingEngine/uiConfirm/ui/preact/RecoveryCodeBackupSurface.js +20 -9
- package/dist/esm/core/signingEngine/uiConfirm/ui/preact/TransactionReceipt.js +107 -43
- package/dist/esm/core/signingEngine/uiConfirm/ui/preact/mountConfirmationSurface.js +1 -1
- package/dist/esm/core/signingEngine/uiConfirm/ui/transaction-receipt.js +36 -6
- package/dist/esm/core/ui/messages.js +9 -14
- package/dist/esm/plugins/SeamsWeb/walletIframe/sanitization.js +18 -0
- package/dist/esm/plugins/plugin-utils.js +5 -2
- package/dist/esm/react/components/AccountMenuButton/AuthenticationMethodsModal.js +3 -9
- package/dist/esm/react/components/AccountMenuButton/LinkedDevicesModal.js +2 -2
- package/dist/esm/react/components/AccountMenuButton/ProfileDropdown.js +23 -9
- package/dist/esm/react/components/AccountMenuButton/TransactionSettingsSection.css +376 -84
- package/dist/esm/react/components/AccountMenuButton/TransactionSettingsSection.js +87 -167
- package/dist/esm/react/components/AccountMenuButton/WalletRegionSection.js +11 -9
- package/dist/esm/react/components/AccountMenuButton/WalletSettingsLayout.css +76 -74
- package/dist/esm/react/components/AccountMenuButton/WalletSettingsLayout.js +23 -22
- package/dist/esm/react/components/AccountMenuButton/Web3AuthProfileButton.css +1 -5
- package/dist/esm/react/components/AccountMenuButton/icons/MapPinIcon.js +12 -0
- package/dist/esm/react/components/AccountMenuButton/index.js +13 -2
- package/dist/esm/react/styles/styles.css +452 -162
- package/dist/esm/sdk/{ConfirmationDrawer-DCw0m-Iv.js → ConfirmationDrawer-Ck33ZmU-.js} +1 -1
- package/dist/esm/sdk/{NonceCoordinator-Dq-FZpBz.js → NonceCoordinator-Do23iTzQ.js} +1 -1
- package/dist/esm/sdk/accountLifecycle-CXTlwnAS.js +1 -0
- package/dist/esm/sdk/activeWalletSession-BtEHhe99.js +1 -0
- package/dist/esm/sdk/adapters-CgJpSAxH.js +2 -0
- package/dist/esm/sdk/appearance-token-vars-BA3KQyEE.js +2 -0
- package/dist/esm/sdk/challengeDelivery-C88JNwKf.js +1 -0
- package/dist/esm/sdk/clientSessionPersistenceState-DFGHXoKK.js +1 -0
- package/dist/esm/sdk/collectAuthenticationCredentialForChallengeB64u-CSwy9csE.js +1 -0
- package/dist/esm/sdk/{commitQueue-BW7BpYyA.js → commitQueue-BQPOhyGl.js} +1 -1
- package/dist/esm/sdk/{display-WtILOPQR.js → display-Dtugjeya.js} +1 -1
- package/dist/esm/sdk/ecdsaCapabilityManifest-B3u6J5gn.js +1 -0
- package/dist/{public/sdk/ecdsaDerivationClientWasm-DmwKWUEb.js → esm/sdk/ecdsaDerivationClientWasm-D1HzwUgV.js} +1 -1
- package/dist/esm/sdk/ecdsaDerivationExport-DrFESeRP.js +1 -0
- package/dist/esm/sdk/ecdsaWalletRecords-BmhuJF1y.js +1 -0
- package/dist/esm/sdk/emailOtpEcdsaDerivationIdentity-DreNrM6n.js +1 -0
- package/dist/esm/sdk/{enrichDisplayModelWithAbi-DSj4NAlY.js → enrichDisplayModelWithAbi-D0o0IL7_.js} +1 -1
- package/dist/esm/sdk/{evmCryptoWasm-DeobzyP-.js → evmCryptoWasm-S2gL5ht4.js} +1 -1
- package/dist/esm/sdk/{export-viewer-host-DsdzagKK.js → export-viewer-host-C9n-62Pi.js} +1 -1
- package/dist/esm/sdk/exportKeypairOperation-Du9HKB8f.js +1 -0
- package/dist/esm/sdk/host-DoftJdVQ.js +1 -0
- package/dist/esm/sdk/keyMaterialEnvelope-B3v6HLtz.js +1 -0
- package/dist/esm/sdk/{lanes-BzU7cv2T.js → lanes-l274pbT5.js} +1 -1
- package/dist/esm/sdk/localOnly-CvFSZFUy.js +1 -0
- package/dist/esm/sdk/{mountExportPrivateKeySurface-DQzFzhNu.js → mountExportPrivateKeySurface-DdJHWwqY.js} +1 -1
- package/dist/esm/sdk/mountRecoveryCodeBackupSurface-D3QFgMGE.js +2 -0
- package/dist/esm/sdk/nearEd25519YaoMaterialActivation-BK8_DxHs.js +1 -0
- package/dist/esm/sdk/nearEd25519YaoSigningPreparation-BgCxoh9S.js +1 -0
- package/dist/esm/sdk/{nonceLaneKeys-BzMBVxMU.js → nonceLaneKeys-CR2XEvnk.js} +1 -1
- package/dist/esm/sdk/{normalization-Ct9-AY13.js → normalization-Ctkj80dW.js} +1 -1
- package/dist/esm/sdk/{operationFingerprint-C4VX-0NI.js → operationFingerprint-DRPONhBD.js} +1 -1
- package/dist/esm/sdk/pendingWalletRecoveryCodeBackup-LbstFwcY.js +1 -0
- package/dist/esm/sdk/presignaturePool-DNiA3sgr.js +1 -0
- package/dist/esm/sdk/{singletons-CAsc9LvA.js → presignatures-DGLNs29C.js} +1 -1
- package/dist/esm/sdk/recovery-entrypoint-CNVjXz6A.js +1 -0
- package/dist/esm/sdk/recoveryAuthorization-BplZWc-N.js +1 -0
- package/dist/esm/sdk/{registration-DknFwoqn.js → registration-CIxJvbTo.js} +1 -1
- package/dist/esm/sdk/registration-CeOmKyCG.js +1 -0
- package/dist/esm/sdk/registrationAccounts-BfO6Ztye.js +1 -0
- package/dist/esm/sdk/registrationIntent-DW_kKWlx.js +1 -0
- package/dist/esm/sdk/{registrationSignerPlan-BHkqlian.js → registrationSignerPlan-B66FjqIp.js} +1 -1
- package/dist/esm/sdk/{requireStepUpAuth-CnSCFSOZ.js → requireStepUpAuth-DsNLml1i.js} +1 -1
- package/dist/esm/sdk/routerAbNormalSigning-DSAfCcND.js +1 -0
- package/dist/esm/sdk/runtime-auth-C0V-5znH.js +1 -0
- package/dist/{public/sdk/runtime-device-link-Dn_5hPCq.js → esm/sdk/runtime-device-link-B1jpHQSF.js} +1 -1
- package/dist/{public/sdk/runtime-ecdsa-tempo-lTFTb9Rh.js → esm/sdk/runtime-ecdsa-tempo-CDSZ3pxS.js} +1 -1
- package/dist/esm/sdk/runtime-email-otp-DXuxFOjL.js +1 -0
- package/dist/esm/sdk/{runtime-export-Brz53_oi.js → runtime-export-Ba12ChDI.js} +1 -1
- package/dist/{public/sdk/runtime-near-Da_xFUXx.js → esm/sdk/runtime-near-DRrdWzmr.js} +1 -1
- package/dist/esm/sdk/runtime-preferences-BWyhRaBA.js +1 -0
- package/dist/esm/sdk/runtime-recovery-DlJlaZlf.js +1 -0
- package/dist/esm/sdk/runtime-recovery-codes-CuqYWqK7.js +1 -0
- package/dist/esm/sdk/secp256k1-CYu8ENjP.js +1 -0
- package/dist/esm/sdk/sessionObservationRevision-abErAhd6.js +1 -0
- package/dist/esm/sdk/shared-B95wnpoD.js +6 -0
- package/dist/esm/sdk/signEvmFamily-C4XMiSue.js +1 -0
- package/dist/{public/sdk/signEvmFamilyWithUiConfirmForTempo-NYCFU6Li.js → esm/sdk/signEvmFamilyWithUiConfirmForTempo-4A3D9nKv.js} +1 -1
- package/dist/esm/sdk/{signEvmWithUiConfirm-D6nmJr_L.js → signEvmWithUiConfirm-lZyPfrGe.js} +1 -1
- package/dist/esm/sdk/signNear-B_UcqMRf.js +1 -0
- package/dist/esm/sdk/{signatureUses-B_nN17i7.js → signatureUses-CY4U-X6V.js} +1 -1
- package/dist/esm/sdk/{registrationIds-B1OpqRAt.js → signerSlot-CpyIfl3J.js} +1 -1
- package/dist/esm/sdk/signingFlow-Co_QtuHK.js +2 -0
- package/dist/esm/sdk/signingQueue-Cj9sCJLj.js +1 -0
- package/dist/esm/sdk/thresholdEcdsa-LvkD6z8-.js +1 -0
- package/dist/esm/sdk/{trace-CsRMlSh1.js → trace-CWTzEALZ.js} +1 -1
- package/dist/esm/sdk/transaction-activity-CpDMkSPm.js +1 -0
- package/dist/{public/sdk/transactionState-lB2qpkOm.js → esm/sdk/transactionState-BaFSiA9t.js} +1 -1
- package/dist/esm/sdk/tx-confirm-ui.js +186 -71
- package/dist/esm/sdk/{types-CQTWmtqu.js → types-BrEW276O.js} +1 -1
- package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
- package/dist/esm/sdk/wallet-recovery-BEui57xM.js +1 -0
- package/dist/esm/sdk/wallet-ui.css +1 -1
- package/dist/esm/sdk/{walletAuthMethodRecord-CWdqdY_s.js → walletAuthMethodRecord-Cv_MYpxt.js} +1 -1
- package/dist/esm/sdk/walletCapabilityBindings-CKOK39sP.js +1 -0
- package/dist/esm/sdk/walletCustodyEcdsaContinuity-5XsLsT8D.js +1 -0
- package/dist/esm/sdk/walletCustodyOperation-BO_tSfGY.js +1 -0
- package/dist/esm/sdk/walletDbName-BVZhb4xF.js +1 -0
- package/dist/esm/sdk/walletOwnershipGeneration-CQzaodhB.js +1 -0
- package/dist/esm/sdk/walletRecoveryAdminProof-CtH8_lph.js +1 -0
- package/dist/esm/sdk/walletRecoveryCommit-B_e4k5Pa.js +1 -0
- package/dist/esm/sdk/walletRegistrationSetupPrewarm-CQow9u8m.js +1 -0
- package/dist/esm/sdk/walletSessionAuthorizationStatus-_KtCVFYW.js +1 -0
- package/dist/esm/sdk/walletSessionAuthorizationStore-DYRMCkiT.js +1 -0
- package/dist/esm/sdk/warmSessionHydration-CY9ofEGr.js +1 -0
- package/dist/{public/sdk/webauthnP256-_ajaNl90.js → esm/sdk/webauthnP256-unqBoZCk.js} +1 -1
- package/dist/esm/shared-ts/src/device-linking/deviceManagement.js +2 -3
- package/dist/esm/shared-ts/src/utils/evmRpcResults.js +5 -3
- package/dist/esm/shared-ts/src/utils/routerAbEcdsaDerivation.js +2 -1
- package/dist/public/headers.manifest.json +1 -1
- package/dist/public/sdk/{ConfirmationDrawer-DCw0m-Iv.js → ConfirmationDrawer-Ck33ZmU-.js} +1 -1
- package/dist/public/sdk/{NonceCoordinator-Dq-FZpBz.js → NonceCoordinator-Do23iTzQ.js} +1 -1
- package/dist/public/sdk/accountLifecycle-CXTlwnAS.js +1 -0
- package/dist/public/sdk/activeWalletSession-BtEHhe99.js +1 -0
- package/dist/public/sdk/adapters-CgJpSAxH.js +2 -0
- package/dist/public/sdk/appearance-token-vars-BA3KQyEE.js +2 -0
- package/dist/public/sdk/challengeDelivery-C88JNwKf.js +1 -0
- package/dist/public/sdk/clientSessionPersistenceState-DFGHXoKK.js +1 -0
- package/dist/public/sdk/collectAuthenticationCredentialForChallengeB64u-CSwy9csE.js +1 -0
- package/dist/public/sdk/{commitQueue-BW7BpYyA.js → commitQueue-BQPOhyGl.js} +1 -1
- package/dist/public/sdk/{display-WtILOPQR.js → display-Dtugjeya.js} +1 -1
- package/dist/public/sdk/ecdsaCapabilityManifest-B3u6J5gn.js +1 -0
- package/dist/{esm/sdk/ecdsaDerivationClientWasm-DmwKWUEb.js → public/sdk/ecdsaDerivationClientWasm-D1HzwUgV.js} +1 -1
- package/dist/public/sdk/ecdsaDerivationExport-DrFESeRP.js +1 -0
- package/dist/public/sdk/ecdsaWalletRecords-BmhuJF1y.js +1 -0
- package/dist/public/sdk/emailOtpEcdsaDerivationIdentity-DreNrM6n.js +1 -0
- package/dist/public/sdk/{enrichDisplayModelWithAbi-DSj4NAlY.js → enrichDisplayModelWithAbi-D0o0IL7_.js} +1 -1
- package/dist/public/sdk/{evmCryptoWasm-DeobzyP-.js → evmCryptoWasm-S2gL5ht4.js} +1 -1
- package/dist/public/sdk/{export-viewer-host-DsdzagKK.js → export-viewer-host-C9n-62Pi.js} +1 -1
- package/dist/public/sdk/exportKeypairOperation-Du9HKB8f.js +1 -0
- package/dist/public/sdk/host-DoftJdVQ.js +1 -0
- package/dist/public/sdk/keyMaterialEnvelope-B3v6HLtz.js +1 -0
- package/dist/public/sdk/{lanes-BzU7cv2T.js → lanes-l274pbT5.js} +1 -1
- package/dist/public/sdk/localOnly-CvFSZFUy.js +1 -0
- package/dist/public/sdk/{mountExportPrivateKeySurface-DQzFzhNu.js → mountExportPrivateKeySurface-DdJHWwqY.js} +1 -1
- package/dist/public/sdk/mountRecoveryCodeBackupSurface-D3QFgMGE.js +2 -0
- package/dist/public/sdk/nearEd25519YaoMaterialActivation-BK8_DxHs.js +1 -0
- package/dist/public/sdk/nearEd25519YaoSigningPreparation-BgCxoh9S.js +1 -0
- package/dist/public/sdk/{nonceLaneKeys-BzMBVxMU.js → nonceLaneKeys-CR2XEvnk.js} +1 -1
- package/dist/public/sdk/{normalization-Ct9-AY13.js → normalization-Ctkj80dW.js} +1 -1
- package/dist/public/sdk/{operationFingerprint-C4VX-0NI.js → operationFingerprint-DRPONhBD.js} +1 -1
- package/dist/public/sdk/pendingWalletRecoveryCodeBackup-LbstFwcY.js +1 -0
- package/dist/public/sdk/presignaturePool-DNiA3sgr.js +1 -0
- package/dist/public/sdk/{singletons-CAsc9LvA.js → presignatures-DGLNs29C.js} +1 -1
- package/dist/public/sdk/recovery-entrypoint-CNVjXz6A.js +1 -0
- package/dist/public/sdk/recoveryAuthorization-BplZWc-N.js +1 -0
- package/dist/public/sdk/{registration-DknFwoqn.js → registration-CIxJvbTo.js} +1 -1
- package/dist/public/sdk/registration-CeOmKyCG.js +1 -0
- package/dist/public/sdk/registrationAccounts-BfO6Ztye.js +1 -0
- package/dist/public/sdk/registrationIntent-DW_kKWlx.js +1 -0
- package/dist/public/sdk/{registrationSignerPlan-BHkqlian.js → registrationSignerPlan-B66FjqIp.js} +1 -1
- package/dist/public/sdk/{requireStepUpAuth-CnSCFSOZ.js → requireStepUpAuth-DsNLml1i.js} +1 -1
- package/dist/public/sdk/routerAbNormalSigning-DSAfCcND.js +1 -0
- package/dist/public/sdk/runtime-auth-C0V-5znH.js +1 -0
- package/dist/{esm/sdk/runtime-device-link-Dn_5hPCq.js → public/sdk/runtime-device-link-B1jpHQSF.js} +1 -1
- package/dist/{esm/sdk/runtime-ecdsa-tempo-lTFTb9Rh.js → public/sdk/runtime-ecdsa-tempo-CDSZ3pxS.js} +1 -1
- package/dist/public/sdk/runtime-email-otp-DXuxFOjL.js +1 -0
- package/dist/public/sdk/{runtime-export-Brz53_oi.js → runtime-export-Ba12ChDI.js} +1 -1
- package/dist/{esm/sdk/runtime-near-Da_xFUXx.js → public/sdk/runtime-near-DRrdWzmr.js} +1 -1
- package/dist/public/sdk/runtime-preferences-BWyhRaBA.js +1 -0
- package/dist/public/sdk/runtime-recovery-DlJlaZlf.js +1 -0
- package/dist/public/sdk/runtime-recovery-codes-CuqYWqK7.js +1 -0
- package/dist/public/sdk/secp256k1-CYu8ENjP.js +1 -0
- package/dist/public/sdk/sessionObservationRevision-abErAhd6.js +1 -0
- package/dist/public/sdk/shared-B95wnpoD.js +6 -0
- package/dist/public/sdk/signEvmFamily-C4XMiSue.js +1 -0
- package/dist/{esm/sdk/signEvmFamilyWithUiConfirmForTempo-NYCFU6Li.js → public/sdk/signEvmFamilyWithUiConfirmForTempo-4A3D9nKv.js} +1 -1
- package/dist/public/sdk/{signEvmWithUiConfirm-D6nmJr_L.js → signEvmWithUiConfirm-lZyPfrGe.js} +1 -1
- package/dist/public/sdk/signNear-B_UcqMRf.js +1 -0
- package/dist/public/sdk/{signatureUses-B_nN17i7.js → signatureUses-CY4U-X6V.js} +1 -1
- package/dist/public/sdk/{registrationIds-B1OpqRAt.js → signerSlot-CpyIfl3J.js} +1 -1
- package/dist/public/sdk/signingFlow-Co_QtuHK.js +2 -0
- package/dist/public/sdk/signingQueue-Cj9sCJLj.js +1 -0
- package/dist/public/sdk/thresholdEcdsa-LvkD6z8-.js +1 -0
- package/dist/public/sdk/{trace-CsRMlSh1.js → trace-CWTzEALZ.js} +1 -1
- package/dist/public/sdk/transaction-activity-CpDMkSPm.js +1 -0
- package/dist/{esm/sdk/transactionState-lB2qpkOm.js → public/sdk/transactionState-BaFSiA9t.js} +1 -1
- package/dist/public/sdk/tx-confirm-ui.js +186 -71
- package/dist/public/sdk/{types-CQTWmtqu.js → types-BrEW276O.js} +1 -1
- package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
- package/dist/public/sdk/wallet-recovery-BEui57xM.js +1 -0
- package/dist/public/sdk/wallet-ui.css +1 -1
- package/dist/public/sdk/{walletAuthMethodRecord-CWdqdY_s.js → walletAuthMethodRecord-Cv_MYpxt.js} +1 -1
- package/dist/public/sdk/walletCapabilityBindings-CKOK39sP.js +1 -0
- package/dist/public/sdk/walletCustodyEcdsaContinuity-5XsLsT8D.js +1 -0
- package/dist/public/sdk/walletCustodyOperation-BO_tSfGY.js +1 -0
- package/dist/public/sdk/walletDbName-BVZhb4xF.js +1 -0
- package/dist/public/sdk/walletOwnershipGeneration-CQzaodhB.js +1 -0
- package/dist/public/sdk/walletRecoveryAdminProof-CtH8_lph.js +1 -0
- package/dist/public/sdk/walletRecoveryCommit-B_e4k5Pa.js +1 -0
- package/dist/public/sdk/walletRegistrationSetupPrewarm-CQow9u8m.js +1 -0
- package/dist/public/sdk/walletSessionAuthorizationStatus-_KtCVFYW.js +1 -0
- package/dist/public/sdk/walletSessionAuthorizationStore-DYRMCkiT.js +1 -0
- package/dist/public/sdk/warmSessionHydration-CY9ofEGr.js +1 -0
- package/dist/{esm/sdk/webauthnP256-_ajaNl90.js → public/sdk/webauthnP256-unqBoZCk.js} +1 -1
- package/dist/public/sdk/workers/email-otp.worker.js +6 -1
- package/dist/public/wallet-assets.manifest.json +253 -276
- package/dist/public/wallet-service/index.html +4 -4
- package/dist/types/shared-ts/src/authorization/walletCustodyOperation.d.ts +1 -1
- package/dist/types/shared-ts/src/device-linking/contracts.d.ts +1 -7
- package/dist/types/shared-ts/src/passkey-custody/ceremonyCommitPayload.d.ts +5 -0
- package/dist/types/shared-ts/src/utils/evmRpcResults.d.ts +3 -3
- package/dist/types/shared-ts/src/utils/routerAbEcdsaDerivation.d.ts +1 -1
- package/dist/types/wallet/src/SeamsWeb/operations/recovery/walletRecoveryAdminProof.d.ts +46 -0
- package/dist/types/wallet/src/SeamsWeb/operations/recovery/walletRecoveryCodeBackup.d.ts +4 -1
- package/dist/types/wallet/src/SeamsWeb/operations/recovery/walletRecoveryRotation.d.ts +11 -7
- package/dist/types/wallet/src/SeamsWeb/publicApi/types.d.ts +9 -1
- package/dist/types/wallet/src/SeamsWeb/signingSurface/BrowserSigningSurface.d.ts +4 -3
- package/dist/types/wallet/src/SeamsWeb/signingSurface/ports.d.ts +6 -4
- package/dist/types/wallet/src/SeamsWeb/signingSurface/types.d.ts +2 -2
- package/dist/types/wallet/src/SeamsWeb/walletIframe/client/router.d.ts +2 -6
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/WalletHostRuntime.d.ts +1 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/auth-menu/controller.d.ts +2 -0
- package/dist/types/wallet/src/SeamsWeb/walletIframe/host/requestWalletMove.d.ts +1 -1
- package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/messages.d.ts +5 -1
- package/dist/types/wallet/src/SeamsWeb/walletIframe/shared/recoveryAuthorization.d.ts +6 -0
- package/dist/types/wallet/src/core/indexedDB/seamsWalletDB/pendingWalletRecoveryCodeBackup.d.ts +14 -3
- package/dist/types/wallet/src/core/rpcClients/relayer/walletRecoveryRotate.d.ts +8 -0
- package/dist/types/wallet/src/core/signingEngine/uiConfirm/ui/preact/RecoveryCodeBackupSurface.d.ts +1 -0
- package/dist/types/wallet/src/core/signingEngine/uiConfirm/ui/transaction-activity.d.ts +2 -2
- package/dist/types/wallet/src/core/signingEngine/uiConfirm/ui/transaction-receipt.d.ts +25 -6
- package/dist/types/wallet/src/core/signingEngine/walletCustody/walletRecoveryRotation.d.ts +22 -3
- package/dist/types/wallet/src/core/signingEngine/workerManager/workerTypes.d.ts +1 -0
- package/dist/types/wallet/src/core/signingEngine/workerManager/workers/email-otp/unlock.d.ts +1 -0
- package/dist/types/wallet/src/core/types/sdkSentEvents.d.ts +8 -2
- package/dist/types/wallet/src/core/ui/messages.d.ts +1 -1
- package/dist/types/wallet/src/plugins/plugin-utils.d.ts +1 -1
- package/dist/types/wallet/src/react/components/AccountMenuButton/icons/MapPinIcon.d.ts +2 -0
- package/dist/workers/email-otp.worker.js +6 -1
- package/package.json +1 -1
- package/dist/esm/react/components/AccountMenuButton/SegmentedControl.js +0 -77
- package/dist/esm/sdk/accountLifecycle-fLNUdjct.js +0 -1
- package/dist/esm/sdk/activeWalletSession-BpbnpU9s.js +0 -1
- package/dist/esm/sdk/adapters-BNmcyf9K.js +0 -2
- package/dist/esm/sdk/appearance-token-vars-DxBm_cKA.js +0 -2
- package/dist/esm/sdk/challengeDelivery-CG2J5Qxs.js +0 -1
- package/dist/esm/sdk/clientSessionPersistenceState-BgO4P6CZ.js +0 -1
- package/dist/esm/sdk/digestEncoding-aC4dSf_x.js +0 -1
- package/dist/esm/sdk/ecdsaCapabilityManifest-DRc423SV.js +0 -1
- package/dist/esm/sdk/ecdsaDerivationExport-DX89rq_u.js +0 -1
- package/dist/esm/sdk/ecdsaWalletRecords-CxxUt3fS.js +0 -1
- package/dist/esm/sdk/emailOtpEcdsaDerivationIdentity-CupWCKNg.js +0 -1
- package/dist/esm/sdk/exportKeypairOperation-BwW_E4Lt.js +0 -1
- package/dist/esm/sdk/host-DMR4KDy9.js +0 -1
- package/dist/esm/sdk/localOnly-DO191vDh.js +0 -1
- package/dist/esm/sdk/mountRecoveryCodeBackupSurface-B1D0ovqx.js +0 -2
- package/dist/esm/sdk/nearEd25519YaoMaterialActivation-DgWDGRI_.js +0 -1
- package/dist/esm/sdk/nearEd25519YaoSigningPreparation-yKDLQXBS.js +0 -1
- package/dist/esm/sdk/passkey-custody-Ba-NQ_4C.js +0 -1
- package/dist/esm/sdk/pendingWalletRecoveryCodeBackup-DOeIn_Qj.js +0 -1
- package/dist/esm/sdk/presignaturePool-BHoxnbOA.js +0 -1
- package/dist/esm/sdk/presignatures-K-yuzOE0.js +0 -1
- package/dist/esm/sdk/primitives-CTmDwMNc.js +0 -1
- package/dist/esm/sdk/recovery-entrypoint-DWghFZrZ.js +0 -1
- package/dist/esm/sdk/registration-sQndIWRF.js +0 -1
- package/dist/esm/sdk/registrationAccounts-CD1u1ZqZ.js +0 -1
- package/dist/esm/sdk/registrationIntent-D4YDjf2U.js +0 -1
- package/dist/esm/sdk/routerAbNormalSigning-BV1t27aB.js +0 -1
- package/dist/esm/sdk/runtime-auth-BxG-J-BB.js +0 -1
- package/dist/esm/sdk/runtime-email-otp-CPqTCH8Q.js +0 -1
- package/dist/esm/sdk/runtime-preferences-riUZGaTs.js +0 -1
- package/dist/esm/sdk/runtime-recovery-CTj4nDAM.js +0 -1
- package/dist/esm/sdk/runtime-recovery-codes-D8T9LQ7-.js +0 -1
- package/dist/esm/sdk/secp256k1-wOOHtPcK.js +0 -1
- package/dist/esm/sdk/sessionObservationRevision-C7v-wN8_.js +0 -1
- package/dist/esm/sdk/shared-hx7KVyeq.js +0 -6
- package/dist/esm/sdk/signEvmFamily-DT34Vtpa.js +0 -1
- package/dist/esm/sdk/signNear-B000QxBd.js +0 -1
- package/dist/esm/sdk/signerSlot-FJAGOhmg.js +0 -1
- package/dist/esm/sdk/signingFlow-gl85GOW4.js +0 -2
- package/dist/esm/sdk/signingQueue-gW7wmOuL.js +0 -1
- package/dist/esm/sdk/thresholdEcdsa-Ci7yz395.js +0 -1
- package/dist/esm/sdk/transaction-activity-C0nCSW6c.js +0 -1
- package/dist/esm/sdk/wallet-recovery-DFaS3geI.js +0 -1
- package/dist/esm/sdk/walletAuthority-BY3kyKQ-.js +0 -1
- package/dist/esm/sdk/walletCustodyEcdsaContinuity-mGh1Ysko.js +0 -1
- package/dist/esm/sdk/walletDbName-BxWApBQF.js +0 -1
- package/dist/esm/sdk/walletOwnershipGeneration-DSGfjuV2.js +0 -1
- package/dist/esm/sdk/walletRecoveryCommit-DQA_wveK.js +0 -1
- package/dist/esm/sdk/walletRecoveryRotate-zvQThn37.js +0 -1
- package/dist/esm/sdk/walletRegistrationSetupPrewarm-DdVpKccU.js +0 -1
- package/dist/esm/sdk/walletSessionAuthorizationStatus-ONPRiEbK.js +0 -1
- package/dist/esm/sdk/walletSessionAuthorizationStore-DnUMtkev.js +0 -1
- package/dist/esm/sdk/warmSessionHydration-D8Vdro9n.js +0 -1
- package/dist/public/sdk/accountLifecycle-fLNUdjct.js +0 -1
- package/dist/public/sdk/activeWalletSession-BpbnpU9s.js +0 -1
- package/dist/public/sdk/adapters-BNmcyf9K.js +0 -2
- package/dist/public/sdk/appearance-token-vars-DxBm_cKA.js +0 -2
- package/dist/public/sdk/challengeDelivery-CG2J5Qxs.js +0 -1
- package/dist/public/sdk/clientSessionPersistenceState-BgO4P6CZ.js +0 -1
- package/dist/public/sdk/digestEncoding-aC4dSf_x.js +0 -1
- package/dist/public/sdk/ecdsaCapabilityManifest-DRc423SV.js +0 -1
- package/dist/public/sdk/ecdsaDerivationExport-DX89rq_u.js +0 -1
- package/dist/public/sdk/ecdsaWalletRecords-CxxUt3fS.js +0 -1
- package/dist/public/sdk/emailOtpEcdsaDerivationIdentity-CupWCKNg.js +0 -1
- package/dist/public/sdk/exportKeypairOperation-BwW_E4Lt.js +0 -1
- package/dist/public/sdk/host-DMR4KDy9.js +0 -1
- package/dist/public/sdk/localOnly-DO191vDh.js +0 -1
- package/dist/public/sdk/mountRecoveryCodeBackupSurface-B1D0ovqx.js +0 -2
- package/dist/public/sdk/nearEd25519YaoMaterialActivation-DgWDGRI_.js +0 -1
- package/dist/public/sdk/nearEd25519YaoSigningPreparation-yKDLQXBS.js +0 -1
- package/dist/public/sdk/passkey-custody-Ba-NQ_4C.js +0 -1
- package/dist/public/sdk/pendingWalletRecoveryCodeBackup-DOeIn_Qj.js +0 -1
- package/dist/public/sdk/presignaturePool-BHoxnbOA.js +0 -1
- package/dist/public/sdk/presignatures-K-yuzOE0.js +0 -1
- package/dist/public/sdk/primitives-CTmDwMNc.js +0 -1
- package/dist/public/sdk/recovery-entrypoint-DWghFZrZ.js +0 -1
- package/dist/public/sdk/registration-sQndIWRF.js +0 -1
- package/dist/public/sdk/registrationAccounts-CD1u1ZqZ.js +0 -1
- package/dist/public/sdk/registrationIntent-D4YDjf2U.js +0 -1
- package/dist/public/sdk/routerAbNormalSigning-BV1t27aB.js +0 -1
- package/dist/public/sdk/runtime-auth-BxG-J-BB.js +0 -1
- package/dist/public/sdk/runtime-email-otp-CPqTCH8Q.js +0 -1
- package/dist/public/sdk/runtime-preferences-riUZGaTs.js +0 -1
- package/dist/public/sdk/runtime-recovery-CTj4nDAM.js +0 -1
- package/dist/public/sdk/runtime-recovery-codes-D8T9LQ7-.js +0 -1
- package/dist/public/sdk/secp256k1-wOOHtPcK.js +0 -1
- package/dist/public/sdk/sessionObservationRevision-C7v-wN8_.js +0 -1
- package/dist/public/sdk/shared-hx7KVyeq.js +0 -6
- package/dist/public/sdk/signEvmFamily-DT34Vtpa.js +0 -1
- package/dist/public/sdk/signNear-B000QxBd.js +0 -1
- package/dist/public/sdk/signerSlot-FJAGOhmg.js +0 -1
- package/dist/public/sdk/signingFlow-gl85GOW4.js +0 -2
- package/dist/public/sdk/signingQueue-gW7wmOuL.js +0 -1
- package/dist/public/sdk/thresholdEcdsa-Ci7yz395.js +0 -1
- package/dist/public/sdk/transaction-activity-C0nCSW6c.js +0 -1
- package/dist/public/sdk/wallet-recovery-DFaS3geI.js +0 -1
- package/dist/public/sdk/walletAuthority-BY3kyKQ-.js +0 -1
- package/dist/public/sdk/walletCustodyEcdsaContinuity-mGh1Ysko.js +0 -1
- package/dist/public/sdk/walletDbName-BxWApBQF.js +0 -1
- package/dist/public/sdk/walletOwnershipGeneration-DSGfjuV2.js +0 -1
- package/dist/public/sdk/walletRecoveryCommit-DQA_wveK.js +0 -1
- package/dist/public/sdk/walletRecoveryRotate-zvQThn37.js +0 -1
- package/dist/public/sdk/walletRegistrationSetupPrewarm-DdVpKccU.js +0 -1
- package/dist/public/sdk/walletSessionAuthorizationStatus-ONPRiEbK.js +0 -1
- package/dist/public/sdk/walletSessionAuthorizationStore-DnUMtkev.js +0 -1
- package/dist/public/sdk/warmSessionHydration-D8Vdro9n.js +0 -1
- package/dist/types/wallet/src/react/components/AccountMenuButton/SegmentedControl.d.ts +0 -25
- /package/dist/esm/sdk/{accountIds-Cpvlkvbe.js → accountIds-BzZs7YoX.js} +0 -0
- /package/dist/esm/sdk/{appearance-4DmzKUWf.js → appearance-ZGVLwA4N.js} +0 -0
- /package/dist/esm/sdk/{authenticatorOptions-2_XK8aXv.js → authenticatorOptions-BB_sU4uA.js} +0 -0
- /package/dist/esm/sdk/{authorizationAdmission-Dd23mTx7.js → authorizationAdmission-D7nx2n4d.js} +0 -0
- /package/dist/esm/sdk/{browser-n3IVr7qu.js → browser-DkCRXFkk.js} +0 -0
- /package/dist/esm/sdk/{bytes-DZRW2UDg.js → bytes-Cv07P0Pu.js} +0 -0
- /package/dist/esm/sdk/{canonicalPrimitives-BMP5yILS.js → canonicalPrimitives-D_1HyEuJ.js} +0 -0
- /package/dist/esm/sdk/{canonicalSignerErrorCode-Cz48v4oy.js → canonicalSignerErrorCode-CqHi6ji6.js} +0 -0
- /package/dist/esm/sdk/{capabilityKinds-D0Yrp9uf.js → capabilityKinds-CqHVzVsJ.js} +0 -0
- /package/dist/esm/sdk/{ecdsaChainTarget-DkOrgv4y.js → ecdsaChainTarget-svSlzhze.js} +0 -0
- /package/dist/esm/sdk/{errors-ADOZT8oV.js → errors-CI1xdN0d.js} +0 -0
- /package/dist/esm/sdk/{executeWorkerOperation-DKCRRq5E.js → executeWorkerOperation-S6glYwAs.js} +0 -0
- /package/dist/esm/sdk/{helpers-DS0bksx9.js → helpers-BXezXx19.js} +0 -0
- /package/dist/esm/sdk/{intentDigest-Rh5Mg8X7.js → intentDigest--FZ63NBy.js} +0 -0
- /package/dist/esm/sdk/{jsonRpc-BVDv1wfm.js → jsonRpc-B5zMY6lE.js} +0 -0
- /package/dist/esm/sdk/{keccak-mS0Mejjx.js → keccak-CaPOCznk.js} +0 -0
- /package/dist/esm/sdk/{normalization-C6fQN6mW.js → normalization-CpLZcL2f.js} +0 -0
- /package/dist/esm/sdk/{prfCache-BAFh1skJ.js → prfCache-D25ZCg5n.js} +0 -0
- /package/dist/esm/sdk/{profileAccountProjection-BNVJLOt2.js → profileAccountProjection-C1z9sKHa.js} +0 -0
- /package/dist/esm/sdk/{promptText-CnyrLxgj.js → promptText-D2f5Rg0h.js} +0 -0
- /package/dist/esm/sdk/{registrationAuthMethodInput-B23_HRil.js → registrationAuthMethodInput-DKz6Mgg4.js} +0 -0
- /package/dist/esm/sdk/{sdkSentEvents-DujYAPEM.js → sdkSentEvents-BzMVO1AR.js} +0 -0
- /package/dist/esm/sdk/{signer-worker-DlK58rEA.js → signer-worker-Bh_5foqX.js} +0 -0
- /package/dist/esm/sdk/{signerDomain-BFqRQ0Jl.js → signerDomain-YEHkugWX.js} +0 -0
- /package/dist/esm/sdk/{surface-measurement-reporter-BJhfiPw6.js → surface-measurement-reporter-F-fVB7d3.js} +0 -0
- /package/dist/esm/sdk/{types-Buoe6179.js → types-BNUuaUtl.js} +0 -0
- /package/dist/esm/sdk/{walletIframeIdentity-Cz82I_Uh.js → walletIframeIdentity-DJ0KOBHg.js} +0 -0
- /package/dist/esm/sdk/{walletSessionAuthorizationProjection-DuU6w0FP.js → walletSessionAuthorizationProjection-UdGeS6x3.js} +0 -0
- /package/dist/esm/sdk/{walletSessionFailure-C6TAQTZn.js → walletSessionFailure-Ct412mDZ.js} +0 -0
- /package/dist/esm/sdk/{webauthnPromptCoordinator-9bVeHcTZ.js → webauthnPromptCoordinator-CBkTiMP0.js} +0 -0
- /package/dist/public/sdk/{accountIds-Cpvlkvbe.js → accountIds-BzZs7YoX.js} +0 -0
- /package/dist/public/sdk/{appearance-4DmzKUWf.js → appearance-ZGVLwA4N.js} +0 -0
- /package/dist/public/sdk/{authenticatorOptions-2_XK8aXv.js → authenticatorOptions-BB_sU4uA.js} +0 -0
- /package/dist/public/sdk/{authorizationAdmission-Dd23mTx7.js → authorizationAdmission-D7nx2n4d.js} +0 -0
- /package/dist/public/sdk/{browser-n3IVr7qu.js → browser-DkCRXFkk.js} +0 -0
- /package/dist/public/sdk/{bytes-DZRW2UDg.js → bytes-Cv07P0Pu.js} +0 -0
- /package/dist/public/sdk/{canonicalPrimitives-BMP5yILS.js → canonicalPrimitives-D_1HyEuJ.js} +0 -0
- /package/dist/public/sdk/{canonicalSignerErrorCode-Cz48v4oy.js → canonicalSignerErrorCode-CqHi6ji6.js} +0 -0
- /package/dist/public/sdk/{capabilityKinds-D0Yrp9uf.js → capabilityKinds-CqHVzVsJ.js} +0 -0
- /package/dist/public/sdk/{ecdsaChainTarget-DkOrgv4y.js → ecdsaChainTarget-svSlzhze.js} +0 -0
- /package/dist/public/sdk/{errors-ADOZT8oV.js → errors-CI1xdN0d.js} +0 -0
- /package/dist/public/sdk/{executeWorkerOperation-DKCRRq5E.js → executeWorkerOperation-S6glYwAs.js} +0 -0
- /package/dist/public/sdk/{helpers-DS0bksx9.js → helpers-BXezXx19.js} +0 -0
- /package/dist/public/sdk/{intentDigest-Rh5Mg8X7.js → intentDigest--FZ63NBy.js} +0 -0
- /package/dist/public/sdk/{jsonRpc-BVDv1wfm.js → jsonRpc-B5zMY6lE.js} +0 -0
- /package/dist/public/sdk/{keccak-mS0Mejjx.js → keccak-CaPOCznk.js} +0 -0
- /package/dist/public/sdk/{normalization-C6fQN6mW.js → normalization-CpLZcL2f.js} +0 -0
- /package/dist/public/sdk/{prfCache-BAFh1skJ.js → prfCache-D25ZCg5n.js} +0 -0
- /package/dist/public/sdk/{profileAccountProjection-BNVJLOt2.js → profileAccountProjection-C1z9sKHa.js} +0 -0
- /package/dist/public/sdk/{promptText-CnyrLxgj.js → promptText-D2f5Rg0h.js} +0 -0
- /package/dist/public/sdk/{registrationAuthMethodInput-B23_HRil.js → registrationAuthMethodInput-DKz6Mgg4.js} +0 -0
- /package/dist/public/sdk/{sdkSentEvents-DujYAPEM.js → sdkSentEvents-BzMVO1AR.js} +0 -0
- /package/dist/public/sdk/{signer-worker-DlK58rEA.js → signer-worker-Bh_5foqX.js} +0 -0
- /package/dist/public/sdk/{signerDomain-BFqRQ0Jl.js → signerDomain-YEHkugWX.js} +0 -0
- /package/dist/public/sdk/{surface-measurement-reporter-BJhfiPw6.js → surface-measurement-reporter-F-fVB7d3.js} +0 -0
- /package/dist/public/sdk/{types-Buoe6179.js → types-BNUuaUtl.js} +0 -0
- /package/dist/public/sdk/{walletIframeIdentity-Cz82I_Uh.js → walletIframeIdentity-DJ0KOBHg.js} +0 -0
- /package/dist/public/sdk/{walletSessionAuthorizationProjection-DuU6w0FP.js → walletSessionAuthorizationProjection-UdGeS6x3.js} +0 -0
- /package/dist/public/sdk/{walletSessionFailure-C6TAQTZn.js → walletSessionFailure-Ct412mDZ.js} +0 -0
- /package/dist/public/sdk/{webauthnPromptCoordinator-9bVeHcTZ.js → webauthnPromptCoordinator-CBkTiMP0.js} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as e,B as t,D as n,F as r,M as i,O as a,S as o,T as s,h as c,j as l,k as u,n as d,o as f,r as p,s as m,w as h}from"./domainIds-C3fUa33Q.js";import{D as g,c as _,d as v,j as y,k as b,l as ee,u as te}from"./chains-CPmd4s9f.js";import{B as x,D as ne,E as re,H as S,J as ie,K as ae,O as oe,U as se,W as ce,a as le,k as ue,z as de}from"./activeWalletSession-BtEHhe99.js";import{i as C,r as w}from"./base64-BmKR3UqU.js";import{r as fe}from"./secureRandomId-8LSc91aN.js";import{s as pe,t as me}from"./walletDbName-BVZhb4xF.js";import{l as he}from"./capabilityKinds-CqHVzVsJ.js";import{a as ge,n as _e,r as ve}from"./canonicalPrimitives-D_1HyEuJ.js";import{t as ye}from"./accountIds-BzZs7YoX.js";import{a as be,c as xe}from"./ecdsaChainTarget-svSlzhze.js";import{r as Se}from"./signerDomain-YEHkugWX.js";import{D as Ce,Mt as we,V as Te,k as Ee}from"./registrationIntent-DW_kKWlx.js";import{a as T,i as E,n as De}from"./presignatures-DGLNs29C.js";import{a as D,i as Oe,n as ke,o as Ae,r as O,s as je,t as k}from"./normalization-Ctkj80dW.js";import{i as Me,n as Ne,r as Pe,t as Fe}from"./keyMaterialEnvelope-B3v6HLtz.js";import{E as Ie,G as Le,U as Re,W as ze,X as Be,at as Ve,b as A,f as He,g as Ue,m as We,nt as Ge,p as Ke,rt as qe,st as Je,v as Ye,w as Xe}from"./walletCapabilityBindings-CKOK39sP.js";import{Ft as Ze,Kt as Qe,Lt as $e,Nt as et,Pt as tt,St as nt,T as rt,Xt as it,Yt as at,ft as ot,ln as st,zt as ct}from"./emailOtpEcdsaDerivationIdentity-DreNrM6n.js";import{i as lt,r as j}from"./walletAuthMethodRecord-Cv_MYpxt.js";import{i as ut,o as dt,t as ft}from"./signerSlot-CpyIfl3J.js";import{A as pt,C as mt,I as ht,P as gt,_ as _t,c as vt,n as yt,s as bt,t as xt,v as St}from"./ecdsaCapabilityManifest-B3u6J5gn.js";import{v as Ct}from"./sdkSentEvents-BzMVO1AR.js";import{$ as wt,A as Tt,B as Et,C as Dt,D as Ot,E as kt,F as At,G as jt,H as Mt,I as Nt,J as Pt,K as Ft,L as It,M as Lt,N as Rt,O as zt,P as Bt,Q as Vt,R as Ht,S as Ut,T as Wt,U as Gt,V as Kt,W as qt,X as Jt,Y as Yt,Z as Xt,_ as Zt,at as Qt,b as M,c as $t,ct as en,d as tn,dt as nn,et as rn,f as an,g as on,h as sn,it as cn,j as ln,k as un,l as dn,lt as fn,m as pn,nt as mn,o as hn,ot as gn,p as _n,q as vn,r as yn,rt as bn,s as xn,st as Sn,tt as Cn,u as wn,v as N,w as P,x as F,y as Tn,z as En}from"./walletOwnershipGeneration-CQzaodhB.js";import{a as Dn,i as On,n as kn,r as An}from"./walletSessionAuthorizationStore-DYRMCkiT.js";import{_ as jn,b as I,u as Mn,v as Nn}from"./nonceLaneKeys-CR2XEvnk.js";function Pn(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 Fn(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`];Hn(t,t.keyFamily===`ecdsa_secp256k1`?[...r,`ecdsaThresholdKeyId`]:r,`linked signer material record`);let i=Vn(n(t.authorityId),`authorityId`),a=Vn(s(t.walletAuthMethodId),`walletAuthMethodId`),o=Vn(c(t.materialActivation),`materialActivation`),l=g(t.activationId,`activationId`,`must be a non-empty canonical string`);if(o.activationId!==l)throw Error(`linked signer material activationId does not match materialActivation`);let u=Bn(t.sealedMaterialB64u,`sealedMaterialB64u`),d=ve(t.sealedMaterialDigestB64u),f=ve(t.packageSetDigestB64u),p=Ln(t.targetFactor);if(p.walletAuthMethodId!==a)throw Error(`linked signer material target factor auth method differs from record`);if(t.keyFamily===`ed25519`){let e=Rn(t.publicFacts,o);return{kind:`wallet_authority_linked_signer_material_v1`,authorityId:i,walletAuthMethodId:a,activationId:o.activationId,keyFamily:`ed25519`,materialActivation:o,sealedMaterialB64u:u,sealedMaterialDigestB64u:d,packageSetDigestB64u:f,targetFactor:p,publicFacts:e}}let m=ht(t.ecdsaThresholdKeyId),h=zn(t.publicFacts,o);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:o.activationId,keyFamily:`ecdsa_secp256k1`,ecdsaThresholdKeyId:m,materialActivation:o,sealedMaterialB64u:u,sealedMaterialDigestB64u:d,packageSetDigestB64u:f,targetFactor:p,publicFacts:h}}async function In(e){let t=e.record;if(t.authorityId!==e.expected.authorityId||t.walletAuthMethodId!==e.expected.walletAuthMethodId||t.keyFamily!==e.expected.keyFamily||!p(t.materialActivation,e.expected.materialActivation))return{kind:`wallet_authority_linked_signer_material_open_failed_v1`,reason:`identity_mismatch`};if(!Un(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=w(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 ge(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(Pn(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 Ln(e){let t=b(e,`linked signer material target factor`);if(t.kind===`passkey`)return Hn(t,[`kind`,`walletAuthMethodId`,`verificationDigestB64u`,`rpId`,`credentialIdB64u`],`linked signer material passkey target factor`),{kind:`passkey`,walletAuthMethodId:Vn(s(t.walletAuthMethodId),`targetFactor.walletAuthMethodId`),verificationDigestB64u:ve(t.verificationDigestB64u),rpId:Vn(i(t.rpId),`targetFactor.rpId`),credentialIdB64u:Bn(Vn(l(t.credentialIdB64u),`targetFactor.credentialIdB64u`),`targetFactor.credentialIdB64u`)};if(t.kind===`email_otp`){Hn(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:Vn(s(t.walletAuthMethodId),`targetFactor.walletAuthMethodId`),verificationDigestB64u:ve(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 Rn(e,t){let n=b(e,`linked signer material Ed25519 public facts`);if(Hn(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=Re(n.activationReceipt),i=Le(n.targetBinding),a=ze(n.applicationBinding);if(!p(t,st(r.material_activation)))throw Error(`linked signer material Ed25519 receipt activation differs`);return{keyFamily:`ed25519`,participantIds:Be(n.participantIds),targetBinding:i,applicationBinding:a,activationReceipt:r}}function zn(e,t){let n=b(e,`linked signer material ECDSA public facts`);if(Hn(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=Ie(n.activationReceipt);if(!p(t,r.binding.target.activation))throw Error(`linked signer material ECDSA receipt activation differs`);return{keyFamily:`ecdsa_secp256k1`,ecdsaThresholdKeyId:ht(n.ecdsaThresholdKeyId),activationReceipt:r}}function Bn(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=w(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 Vn(e,t){if(!e.ok)throw Error(`${t}: ${e.error.message}`);return e.value}function Hn(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 Un(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 Wn(e)}}function Wn(e){throw Error(`unsupported linked authority material target factor: ${String(e)}`)}const Gn=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,Kn=Object.freeze(Array.from(Gn).reduce((e,t,n)=>(e[t]=n,e),{}));function qn(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 Jn(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+=Gn[t>>n&31],t&=(1<<n)-1;return r}function L(e){let t=Xn(e),n=[],r=0;for(let e=0;e<8;e++)n.push(t.slice(r,r+4)),r+=4;return n.join(`-`)}function Yn(e){if(e.length!==10)throw Error(`Email OTP recovery code set must contain 10 keys`);return[L(e[0]),L(e[1]),L(e[2]),L(e[3]),L(e[4]),L(e[5]),L(e[6]),L(e[7]),L(e[8]),L(e[9])]}function Xn(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(qn(t))throw Error(`Email OTP recovery key must not be decimal-only`);for(let e=0;e<t.length;e++)if(Kn[t[e]]===void 0)throw Error(`Email OTP recovery key contains unsupported characters`);return t}function Zn(e){let t=Xn(e),n=new Uint8Array(20),r=0,i=0,a=0;for(let e=0;e<t.length;e++)r=r<<5|Kn[t[e]],i+=5,i>=8&&(i-=8,n[a]=r>>i&255,r&=(1<<i)-1,a+=1);return n}function Qn(e){return e.kind===`evm`?`evm:eip155:${e.chainId}`:`tempo:${e.chainId}`}function $n(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 er(e){let t=e.keyTargets.map(e=>({keyHandle:e.keyHandle,chainTarget:$n(e.chainTarget),targetKey:Qn(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 tr(e){return C(await te(er(e)))}const nr=`x-seams-trace-id`,rr=/^[0-9a-f]{32}$/;function ir(e){return e==null||e===``?{ok:!1,reason:`missing`,message:`Router trace ID is missing`}:typeof e!=`string`||!rr.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 ar(){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 R=class extends Error{code;details;constructor(e){super(e.message),this.name=`SignerLifecycleError`,this.code=e.code,this.details=e.details||{}}};function or(e,n){let r=t(e);if(!r)throw new R({code:`signer_lifecycle_invalid_input`,message:`${n} is required`,details:{label:n}});return r}function sr(e,t){if(e==null)return;let n=r(e);if(n==null||!Number.isSafeInteger(n)||n<1)throw new R({code:`signer_lifecycle_invalid_input`,message:`${t} must be an integer >= 1`,details:{label:t,value:e}});return n}function cr(e,t){let n=sr(e,t);if(n==null)throw new R({code:`signer_lifecycle_invalid_input`,message:`${t} is required`,details:{label:t}});return n}function lr(e){for(let t=1;t<1e3;t+=1)if(!e.has(t))return t;throw new R({code:`signer_lifecycle_no_available_slot`,message:`No available account signer slot`})}function ur(e){let t=e.metadata?.signerMaterialFingerprint;return typeof t==`string`?t.trim():``}function dr(e){let t=or(e.expectedFingerprint,`activationPolicy.materialFingerprint`),n=ur(e.existingSigner);if(!n)throw new R({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 R({code:`signer_lifecycle_material_mismatch`,message:`Existing signer material mismatch for ${e.existingSigner.signerId}`,details:{signerId:e.existingSigner.signerId,expectedFingerprint:t,existingFingerprint:n}})}function fr(e){let t=or(e.signer.signerId,`signerId`),n=or(e.signer.signerKind,`signerKind`);or(e.signer.signerAuthMethod,`signerAuthMethod`),or(e.signer.signerSource,`signerSource`);let r=Array.isArray(e.activeSigners)?e.activeSigners:[],i=r.find(e=>e.signerId===t),a=sr(e.preferredSlot,`preferredSlot`);if(e.activationPolicy.mode===`reuse_existing`){if(or(e.activationPolicy.signerId,`activationPolicy.signerId`),e.activationPolicy.signerId!==t)throw new R({code:`signer_lifecycle_invalid_input`,message:`reuse_existing activation policy signerId must match signer.signerId`,details:{policySignerId:e.activationPolicy.signerId,signerId:t}});or(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 R({code:`signer_lifecycle_invalid_input`,message:`replacement activation policy signer kind must match signer.signerKind`,details:{signerKind:n,replacedSignerKind:e.activationPolicy.replacedSignerKind}});or(e.activationPolicy.revocationReason,`activationPolicy.revocationReason`)}if(i)return e.activationPolicy.mode===`reuse_existing`&&dr({existingSigner:i,expectedFingerprint:e.activationPolicy.materialFingerprint}),{signerSlot:cr(i.signerSlot,`signerSlot`)};if(e.activationPolicy.mode===`reuse_existing`){let e=r.find(e=>e.signerKind===n);if(e)throw new R({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=cr(e.activationPolicy.signerSlot,`signerSlot`),n=r.find(e=>e.signerSlot===t);if(n)throw new R({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:cr(e.activationPolicy.signerSlot,`signerSlot`)};let o=new Set(r.map(e=>e.signerSlot));return{signerSlot:a&&!o.has(a)?a:lr(o)}}function pr(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=Oe(e.scope);return r==null?{profileId:t,activeSignerSlot:n}:{profileId:t,activeSignerSlot:n,scope:r}}function mr(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 hr(e,t){if(t.application_binding.wallet_id!==e.walletId)throw Error(`NEAR continuation wallet mismatch`);return{...mr(e),operation:`near_provisioning`,signerPlanKind:e.signerPlanKind,phase:`planned`,admissionRequest:t,baseCustodyCommit:e.localMaterial.custodyCommit}}function gr(e,t,n){try{let r=ti(JSON.parse(e),[`executeRequestJson`,`applicationBindingDigestB64u`,`nonceB64u`,`ciphertextB64u`]);if(!r)return!1;let i=z(r.get(`executeRequestJson`));if(!i||!z(r.get(`applicationBindingDigestB64u`))||!z(r.get(`nonceB64u`))||!z(r.get(`ciphertextB64u`)))return!1;let a=qe(JSON.parse(i));return a.ok&&Je(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 _r(e,t,n){if(!gr(n,t,e.admissionRequest))throw Error(`Invalid NEAR registration execution checkpoint`);return{...mr(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 vr=`pending_wallet_registration_commit_v1:`;function yr(e){return`${vr}${e.registrationCeremonyId}:${e.operation}`}function br(e){let t=Tr(e);return{key:yr({registrationCeremonyId:t.registration_ceremony_id,operation:t.operation}),value:t}}function xr(e){let t=ti(e,[`key`,`value`]);if(!t)return null;let n=t.get(`key`);if(typeof n!=`string`||!n.startsWith(vr))return null;let r=Er(t.get(`value`));return r&&yr({registrationCeremonyId:r.registration_ceremony_id,operation:r.operation})===n?r:null}async function Sr(e){let t=ri(e,`value`),n=ti(ri(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=Pr(n.get(`localMaterial`));if(!r||!Lr(r))return null;let i=Dr({...Object.fromEntries(n),localMaterial:{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:r.custodyCommit,ecdsa:r.ecdsa}});if(!i||i.operation!==`registration_activate`||ri(e,`key`)!==yr(i)||ri(t,`wallet_id`)!==i.walletId||ri(t,`wallet_auth_method_id`)!==i.walletAuthMethodId||ri(t,`registration_ceremony_id`)!==i.registrationCeremonyId||ri(t,`operation`)!==i.operation||ri(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(Cr).join(``)].join(`:`)),s=Dr({...mr(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 Cr(e){return e.toString(16).padStart(2,`0`)}function wr(e){return e}function Tr(e){let t=wr(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 Er(e){let t=ti(e,[`registration_ceremony_id`,`operation`,`wallet_id`,`wallet_auth_method_id`,`updated_at_ms`,`record`]);if(!t)return null;let n=Dr(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 Dr(e){let t=ni(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 n=kr(t.get(`operation`)),r=Ar(t.get(`signerPlanKind`)),i=z(t.get(`registrationCeremonyId`)),o=z(t.get(`idempotencyKey`)),c=z(t.get(`signedSetup`)),l=a(t.get(`walletId`)),u=s(t.get(`walletAuthMethodId`)),d=ei(jr(),t.get(`auth`)),f=Pr(t.get(`localMaterial`)),p=$r(t.get(`createdAtMs`)),m=$r(t.get(`updatedAtMs`));if(n!==`registration_activate`&&n!==`near_provisioning`||r===null||i===null||o===null||c===null||!l.ok||!u.ok||!d||p===null||m===null||m<p)return null;let h={kind:`pending_wallet_registration_commit_v1`,registrationCeremonyId:i,idempotencyKey:o,walletId:l.value,walletAuthMethodId:u.value,signedSetup:c,auth:d,createdAtMs:p,updatedAtMs:m},g=t.get(`phase`);if(n===`near_provisioning`&&(g===`planned`||g===`execution_prepared`)){let e=Ve(t.get(`admissionRequest`)),i=Gr(t.get(`baseCustodyCommit`));if(r!==`near_ed25519_and_evm_family_ecdsa`||t.has(`localMaterial`)||!e.ok||e.value.application_binding.wallet_id!==l.value||!i||i.keySet!==`evm_family_ecdsa_v1`||i.walletId!==l.value||!i.establishedCustody)return null;if(g===`planned`)return t.has(`admissionReceipt`)||t.has(`checkpointJson`)?null:{...h,operation:n,signerPlanKind:r,phase:g,admissionRequest:e.value,baseCustodyCommit:{...i,keySet:`evm_family_ecdsa_v1`}};let a=Ge(t.get(`admissionReceipt`)),o=z(t.get(`checkpointJson`));return!a.ok||!o||!gr(o,a.value,e.value)?null:{...h,operation:n,signerPlanKind:r,phase:g,admissionRequest:e.value,baseCustodyCommit:{...i,keySet:`evm_family_ecdsa_v1`},admissionReceipt:a.value,checkpointJson:o}}if(!f||f.custodyCommit.walletId!==l.value||t.has(`admissionRequest`)||t.has(`admissionReceipt`)||t.has(`baseCustodyCommit`)||t.has(`checkpointJson`)||Lr(f)&&f.ed25519.custodyCommit.walletId!==l.value)return null;if(n===`registration_activate`)return g!==void 0||r===`near_ed25519`?null:Ir(f)?{kind:`pending_wallet_registration_commit_v1`,operation:n,signerPlanKind:r,registrationCeremonyId:i,idempotencyKey:o,walletId:l.value,walletAuthMethodId:u.value,signedSetup:c,auth:d,localMaterial:f,createdAtMs:p,updatedAtMs:m}:null;if(n===`near_provisioning`){if(g!==void 0&&g!==`joined`||r!==`near_ed25519`&&r!==`near_ed25519_and_evm_family_ecdsa`||!Fr(f))return null;let e={kind:`sealed_material`},a=t.get(`completion`);if(a!==void 0){let t=ni(a,[`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(ri(n,`phase`)!==`execution_prepared`)return null;let a=Dr(n);if(!a||a.phase!==`execution_prepared`||a.registrationCeremonyId!==i||a.walletId!==l.value||a.walletAuthMethodId!==u.value||a.signedSetup!==c||r!==a.signerPlanKind)return null;e={kind:`encrypted_checkpoint`,prepared:a};break}default:return null}}return{kind:`pending_wallet_registration_commit_v1`,operation:n,phase:`joined`,completion:e,signerPlanKind:r,registrationCeremonyId:i,idempotencyKey:o,walletId:l.value,walletAuthMethodId:u.value,signedSetup:c,auth:d,localMaterial:f,createdAtMs:p,updatedAtMs:m}}return null}function Or(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(!tt(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(!et(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 kr(e){return e===`registration_activate`||e===`near_provisioning`?e:null}function Ar(e){return e===`near_ed25519`||e===`evm_family_ecdsa`||e===`near_ed25519_and_evm_family_ecdsa`?e:null}function jr(){return ce(`kind`,[S({kind:x(`passkey`),rpId:se(i),credentialIdB64u:se(l),transports:B(Mr)}),S({kind:x(`email_otp`),email:se(h),registrationAuthorityId:se(f),providerSubject:se(m),enrollment:Nr()})])}function Mr(e){let t=ii(e);if(!t)return null;let n=[],r=new Set;for(let e of t){let t=z(e);if(t===null||r.has(t))return null;r.add(t),n.push(t)}return n}function Nr(){let e=B(z);return S({enrollmentSealKeyVersion:e,serverSealedFactorCiphertextB64u:e,clientUnlockPublicKeyB64u:e,unlockKeyVersion:e})}function Pr(e){let t=ii(ri(e,`keyFamilies`));if(!t)return null;if(t.length===1&&t[0]===`ecdsa_secp256k1`){let t=ti(e,[`keyFamilies`,`custodyCommit`,`ecdsa`]);if(!t)return null;let n=Gr(t.get(`custodyCommit`)),r=ei(Hr(),t.get(`ecdsa`));return n&&Kr(n,`evm_family_ecdsa_v1`)&&r?{keyFamilies:[`ecdsa_secp256k1`],custodyCommit:n,ecdsa:r}:null}if(t.length===1&&t[0]===`ed25519`){let t=ti(e,[`keyFamilies`,`custodyCommit`,`ed25519`]);if(!t)return null;let n=Gr(t.get(`custodyCommit`)),r=ei(zr(),t.get(`ed25519`));return n&&Kr(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=ti(e,[`keyFamilies`,`custodyCommit`,`ed25519`,`ecdsa`]);if(!t)return null;let n=Gr(t.get(`custodyCommit`)),r=ei(Br(),t.get(`ed25519`)),i=ei(Hr(),t.get(`ecdsa`));return n&&Kr(n,`evm_family_ecdsa_v1`)&&r&&i?{keyFamilies:[`ed25519`,`ecdsa_secp256k1`],custodyCommit:n,ed25519:r,ecdsa:i}:null}return null}function Fr(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ed25519`}function Ir(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ecdsa_secp256k1`}function Lr(e){return e.keyFamilies.length===2&&e.keyFamilies[0]===`ed25519`&&e.keyFamilies[1]===`ecdsa_secp256k1`}function Rr(){let e=B(z);return{activationReference:Wr(),localMaterial:S({b64u:e,nonceB64u:e,applicationBindingDigestB64u:e}),metadata:Vr()}}function zr(){return S(Rr())}function Br(){return S({...Rr(),custodyCommit:B(e=>{let t=Gr(e);return t&&Kr(t,`near_ed25519_v1`)?t:null})})}function Vr(){let e=B(z);return S({materialActivation:se(c),registeredPublicKeyB64u:e,signingWorkerVerifyingShareB64u:e,stateEpoch:B(Qr),signingWorkerId:e,participantIds:(e,t)=>{let n=ii(e);if(!n||n.length!==2||n.some(e=>$r(e)===null))throw Error(`${t} is invalid`);return[Number(n[0]),Number(n[1])]},nearEd25519SigningKeyId:e,signerSlot:B($r)})}function Hr(){return S({activationJournalId:_e,clientActivation:ot,activationRequestDigestB64u:ve})}function Ur(){let e=B(z),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 Wr(){return S({kind:x(`router_ab_ed25519_yao_activation_reference_v1`),lifecycle_id:B(z),session_id:(e,t)=>{let n=ii(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 Gr(e){let t=ni(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=z(t.get(`walletId`)),r=z(t.get(`keySet`)),i=z(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:qr(o);if(o!==void 0&&!s)return null;let c=t.get(`recoveryReplacementEnvelope`),l=c===void 0?void 0:ei(Xr(),c);if(c!==void 0&&!l)return null;let u=t.get(`registeredPublicKeyB64u`),d=u===void 0?void 0:z(u);if(u!==void 0&&!d)return null;let f=t.get(`clientRootPublicKey33B64u`),p=f===void 0?void 0:z(f);if(f!==void 0&&!p)return null;let m=t.get(`ecdsaPublicFacts`),h=m===void 0?void 0:ei(Ur(),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 Kr(e,t){return e.keySet===t}function qr(e){let t=[`envelopeId`,`envelopeBindingJson`,`envelopeNonceB64u`,`sealedCustodySecretB64u`,`envelopeAadHashB64u`,`envelopeCiphertextDigestB64u`,`recoveryManifestKekWraps`,`recoveryCodeLocators`,`recoveryEntryNonceB64u`,`recoveryEntryCiphertextB64u`,`recoveryEntryAadHashB64u`],n=ni(e,t);if(!n||t.some(e=>e!==`recoveryCodeLocators`&&!n.has(e)))return null;let r=[z(n.get(`envelopeId`)),z(n.get(`envelopeBindingJson`)),z(n.get(`envelopeNonceB64u`)),z(n.get(`sealedCustodySecretB64u`)),z(n.get(`envelopeAadHashB64u`)),z(n.get(`envelopeCiphertextDigestB64u`)),z(n.get(`recoveryEntryNonceB64u`)),z(n.get(`recoveryEntryCiphertextB64u`)),z(n.get(`recoveryEntryAadHashB64u`))];if(r.some(e=>e===null))return null;let i=ii(n.get(`recoveryManifestKekWraps`));if(!i)return null;let a=i.map(e=>ei(Jr(),e));if(a.some(e=>e===null))return null;let o=a.filter(Zr),s;if(n.has(`recoveryCodeLocators`)){let e=ii(n.get(`recoveryCodeLocators`));if(!e)return null;let t=e.map(e=>ei(Yr(),e));if(t.some(e=>e===null))return null;s=t.filter(Zr)}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 Jr(){let e=B(z);return S({recoveryKeyId:e,nonceB64u:e,ciphertextB64u:e,aadHashB64u:e})}function Yr(){let e=B(z);return S({locatorB64u:e,recoveryKeyId:e})}function Xr(){let e=B(z);return S({envelopeId:e,envelopeBindingJson:e,envelopeNonceB64u:e,sealedCustodySecretB64u:e,envelopeAadHashB64u:e,envelopeCiphertextDigestB64u:e})}function Zr(e){return e!==null}function z(e){return typeof e==`string`&&e.length>0&&e.trim()===e&&!d(e)?e:null}function Qr(e){let t=z(e);return t&&/^[1-9][0-9]*$/u.test(t)?t:null}function $r(e){return Number.isSafeInteger(e)&&Number(e)>0?Number(e):null}function ei(e,t){try{return e(t,`journal`)}catch{return null}}function B(e){return(t,n)=>{let r=e(t);if(r===null)throw Error(`${n} is invalid`);return r}}function ti(e,t){let n=ni(e,t);return n&&n.size===t.length?n:null}function ni(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 ri(e,t){if(!(typeof e!=`object`||!e||Array.isArray(e)))return Reflect.get(e,t)}function ii(e){return Array.isArray(e)?e:null}function ai(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&&p(e.materialActivation,t.materialActivation)}function oi(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&&p(e.materialActivation,t.materialActivation)}async function si(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 _e(`wallet-recovery-key-v1:${C(await te(_({domain:`seams/wallet-recovery/key-lifecycle/v1`,reservationId:e.reservationId,keySetId:t})))}`)}function ci(e){if(typeof e!=`string`||e.length===0||e.length>512||e.trim()!==e||d(e))throw Error(`recovery code reservation id must be a compact opaque identifier`);return e}function li(e){return e.kind===`passkey`?ui(e):di(e)}function ui(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 _i(t),t}function di(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:Ti(e.emailHashHex),registrationAuthorityId:y(e.registrationAuthorityId,`registrationAuthorityId`,`is invalid`),enrollment:hi(e.enrollment)}};return _i(t),t}async function fi(t,r){let i=vi(t);if(i.version!==`wallet_recovery_committed_projection_v1`)throw Error(`wallet recovery committed projection version is invalid`);if(i.kind!==r.kind)throw Error(`wallet recovery committed projection target changed`);let o=wi(a(i.walletId),`walletId`),c=wi(e(i.recoveryOperationId),`recoveryOperationId`),l=wi(he(i.targetDeviceId),`targetDeviceId`),u=wi(n(i.targetAuthorityId),`targetAuthorityId`),d=wi(s(i.targetWalletAuthMethodId),`targetWalletAuthMethodId`),f=A(i.authority);if(!f.ok)throw Error(`wallet recovery authority projection is invalid`);let p=f.value;if(p.state!==`active`||!Ue(p)||!await Xe(p))throw Error(`wallet recovery authority projection digest or lifecycle is invalid`);let m=j(i.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(i.storeVersion,`storeVersion`,`is invalid`),walletId:o,recoveryOperationId:c,targetDeviceId:l,targetAuthorityId:u,targetWalletAuthMethodId:d,authority:p};if(r.kind===`passkey`){if(m.kind!==`passkey`)throw Error(`wallet recovery target method family changed`);let e=pi(i.target),t={...h,kind:`passkey`,authMethod:m,target:e};return gi(t,r),_i(t),t}if(m.kind!==`email_otp`)throw Error(`wallet recovery target method family changed`);let g=mi(i.target),_={...h,kind:`google_email_otp`,authMethod:m,target:g};return gi(_,r),_i(_),_}function pi(e){let t=yi(e);if(t.kind!==`passkey`)throw Error(`wallet recovery passkey target is invalid`);return{kind:`passkey`,rpId:wi(i(t.rpId),`target.rpId`),credentialIdB64u:wi(l(t.credentialIdB64u),`target.credentialIdB64u`)}}function mi(e){let t=bi(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:wi(m(t.providerSubject),`target.providerSubject`),emailHashHex:Ti(t.emailHashHex),registrationAuthorityId:y(t.registrationAuthorityId,`target.registrationAuthorityId`,`is invalid`),enrollment:hi(t.enrollment)}}function hi(e){let t=xi(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 gi(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 _i(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 vi(e){let t=Si(e);if(t===null)throw Error(`wallet recovery committed projection must be an object`);return Ci(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 yi(e){let t=Si(e);if(t===null)throw Error(`wallet recovery passkey target must be an object`);return Ci(t,[`kind`,`rpId`,`credentialIdB64u`],`wallet recovery passkey target`),{kind:Reflect.get(t,`kind`),rpId:Reflect.get(t,`rpId`),credentialIdB64u:Reflect.get(t,`credentialIdB64u`)}}function bi(e){let t=Si(e);if(t===null)throw Error(`wallet recovery Google Email OTP target must be an object`);return Ci(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 xi(e){let t=Si(e);if(t===null)throw Error(`wallet recovery Email OTP enrollment must be an object`);return Ci(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 Si(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function Ci(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 wi(e,t){if(!e.ok)throw Error(`${t} is invalid`);return e.value}function Ti(e){let t=y(e,`emailHashHex`,`is invalid`);if(!/^[0-9a-f]{64}$/.test(t))throw Error(`emailHashHex is invalid`);return t}const Ei=`pending_wallet_recovery_commit_v1`,Di=`${Ei}:`,Oi=[`version`,`kind`,`storeVersion`,`walletId`,`recoveryOperationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`authority`,`authMethod`,`target`],ki=[`version`,`walletAuthMethodId`,`walletId`,`walletAuthorityId`,`kind`,`status`,`createdAtMs`,`updatedAtMs`,`rpId`,`credentialIdB64u`,`credentialPublicKeyB64u`,`counter`,`activatedAtMs`],Ai=[`version`,`walletAuthMethodId`,`walletId`,`walletAuthorityId`,`kind`,`status`,`createdAtMs`,`updatedAtMs`,`emailHashHex`,`registrationAuthorityId`,`activatedAtMs`],ji=[`kind`,`rpId`,`credentialIdB64u`],Mi=[`kind`,`providerSubject`,`emailHashHex`,`registrationAuthorityId`,`enrollment`],Ni=[`kind`,`provider`,`providerSubject`,`emailHashHex`,`registrationAuthorityId`,`enrollment`],Pi=[`kind`,`enrollmentId`,`enrollmentSealKeyVersion`];function Fi(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 Ii(e){return`${Di}${String(e)}`}function V(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 Li(e,t){if(!(typeof e!=`object`||!e||Array.isArray(e)))return Reflect.get(e,t)}function Ri(e){return typeof e!=`string`||e.length===0||e.trim()!==e?null:e}function zi(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}function Bi(e){try{return ci(e)}catch{return null}}function Vi(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 Hi(e){let t=V(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`||!Vi(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 Ui(e){let t=V(e,[`kind`,`enrollmentId`,`enrollmentSealKeyVersion`]);if(!t||t.get(`kind`)!==`email_otp_enrollment_reference_v1`)return null;let n=Ri(t.get(`enrollmentId`)),r=Ri(t.get(`enrollmentSealKeyVersion`));return!n||!r?null:{kind:`email_otp_enrollment_reference_v1`,enrollmentId:n,enrollmentSealKeyVersion:r}}function Wi(e){let t=Li(e,`kind`);if(t===`passkey`){let t=V(e,ji);if(!t)return null;let n=i(t.get(`rpId`)),r=l(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=V(e,Mi);if(!n)return null;let r=n.get(`emailHashHex`);if(typeof r!=`string`||!/^[0-9a-f]{64}$/.test(r))return null;let a=m(n.get(`providerSubject`)),o=Ri(n.get(`registrationAuthorityId`)),s=Ui(n.get(`enrollment`));return a.ok&&o&&s?{kind:`google_email_otp`,providerSubject:a.value,emailHashHex:r,registrationAuthorityId:o,enrollment:s}:null}function Gi(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 Ki(t){let r=[`kind`,`version`,`stage`,`recoveryOperationId`,`walletId`,`reservationId`,`targetDeviceId`,`targetAuthorityId`,`targetWalletAuthMethodId`,`target`,`localMaterial`,`createdAtMs`,`updatedAtMs`],i=Li(t,`stage`),o=i===`server_promoted`?[...r,`projection`]:i===`awaiting_server_promotion`?r:null;if(!o)return null;let c=V(t,o);if(!c||c.get(`kind`)!==Ei||c.get(`version`)!==1)return null;let l=e(c.get(`recoveryOperationId`)),u=a(c.get(`walletId`)),d=Bi(c.get(`reservationId`)),f=he(c.get(`targetDeviceId`)),p=n(c.get(`targetAuthorityId`)),m=s(c.get(`targetWalletAuthMethodId`)),h=Wi(c.get(`target`)),g=Hi(c.get(`localMaterial`)),_=zi(c.get(`createdAtMs`)),v=zi(c.get(`updatedAtMs`));if(!l.ok||!u.ok||!d||!f.ok||!p.ok||!m.ok||!h||!g||_===null||v===null||v<_)return null;if(i===`awaiting_server_promotion`)return{kind:Ei,version:1,stage:i,recoveryOperationId:l.value,walletId:u.value,reservationId:d,targetDeviceId:f.value,targetAuthorityId:p.value,targetWalletAuthMethodId:m.value,target:h,localMaterial:g,createdAtMs:_,updatedAtMs:v};let y={kind:Ei,version:1,recoveryOperationId:l.value,walletId:u.value,reservationId:d,targetDeviceId:f.value,targetAuthorityId:p.value,targetWalletAuthMethodId:m.value,target:h,localMaterial:g,createdAtMs:_,updatedAtMs:v},b;try{b=await fi(c.get(`projection`),Gi(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:Ei,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 qi(e){let t=await Ki(e);if(!t)throw Error(`pending wallet recovery commit is invalid`);return t}async function Ji(e){let t=await qi(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:Ii(t.recoveryOperationId),value:n}}async function Yi(e){let t=V(e,[`key`,`value`]);if(!t)return null;let n=t.get(`key`);if(typeof n!=`string`||!n.startsWith(Di))return null;let r=V(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 Ki(r.get(`record`));return!i||n!==Ii(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 Xi(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 Zi(e,t){return e.kind===t.kind&&Xi(e.iv,t.iv)&&Xi(e.ciphertext,t.ciphertext)}function Qi(e,t){let n=V(e,Pi);return n!==null&&n.get(`kind`)===t.kind&&n.get(`enrollmentId`)===t.enrollmentId&&n.get(`enrollmentSealKeyVersion`)===t.enrollmentSealKeyVersion}function $i(e,t,n){let r=V(e,ji);return r!==null&&r.get(`kind`)===`passkey`&&r.get(`rpId`)===t&&r.get(`credentialIdB64u`)===n}function ea(e,t){if(t.kind===`passkey`)return $i(e,t.rpId,t.credentialIdB64u);let n=V(e,Mi);return n!==null&&n.get(`kind`)===t.kind&&n.get(`providerSubject`)===t.providerSubject&&n.get(`emailHashHex`)===t.emailHashHex&&n.get(`registrationAuthorityId`)===t.registrationAuthorityId&&Qi(n.get(`enrollment`),t.enrollment)}function ta(e,t){if(t.kind===`passkey`)return $i(e,t.rpId,t.credentialIdB64u);let n=V(e,Ni);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&&Qi(n.get(`enrollment`),t.enrollment)}function na(e,t){let n=V(e,t.kind===`passkey`?ki:Ai);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=j(e);return r!==null&<(r,t)}function ra(e,t){let n=V(e,Oi);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=A(n.get(`authority`));return!r.ok||r.value.state!==`active`||!Ue(r.value)?!1:ia(r.value,t.authority)&&na(n.get(`authMethod`),t.authMethod)&&ta(n.get(`target`),t.target)}function ia(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&&aa(e.permissions,t.permissions)&&oa(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 aa(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 oa(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&&ai(e.ed25519,t.ed25519);case`ecdsa_secp256k1`:return t.keyFamilies[0]===`ecdsa_secp256k1`&&e.ecdsa!==void 0&&t.ecdsa!==void 0&&oi(e.ecdsa,t.ecdsa);default:return sa(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:ai(e.ed25519,t.ed25519)&&oi(e.ecdsa,t.ecdsa)}function sa(e){throw Error(`unsupported pending recovery signer family: ${String(e)}`)}function ca(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=Hi(e.get(`localMaterial`));if(n===null||!Zi(n,t.localMaterial)||!ea(e.get(`target`),t.target))return!1;switch(t.stage){case`awaiting_server_promotion`:return!0;case`server_promoted`:return ra(e.get(`projection`),t.projection);default:return la(t)}}function la(e){throw Error(`unsupported pending wallet recovery branch`)}function ua(e,t){let n=V(e,[`key`,`value`]);if(!n||n.get(`key`)!==t.key)return!1;let r=V(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=V(r.get(`record`),s);return c!==null&&ca(c,a)}async function H(e,t,n){return ve(C(await te(_({category:e,...Xt(t),detail:n}))))}async function da(e,t){return{kind:`exact_record_conflict`,conflictDigest:await H(`journal_constraint_conflict`,e,U(t))}}function fa(){return _e(fe(`ecdsa-persistence-retry`,16,`ECDSA persistence retry correlations`))}function U(e){return e instanceof Error?e.message:String(e)}function pa(e){return e instanceof DOMException&&e.name===`ConstraintError`}async function ma(e,t){return await e.store(Ut).index(E.walletId).getAll(t)}async function ha(e){return await e.store(N).getAll()}async function ga(e,t){return await e.store(M).index(E.capabilityWalletAuthorityState).getAll([...Cn(t),`active`])}function _a(e,t){return p(e.manifest.activation.materialActivation,t)&&p(e.manifest.durableMaterial.materialActivation,t)&&p(e.material.binding.materialActivation,t)}function va(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 Wt(e)}async function ya(e,t){let n=await e.store(Ut).get(Cn(t));if(n===void 0)return await ba(e,t);let r;try{r=vn(n)}catch(e){return{kind:`corrupt`,detail:U(e)}}if(!mn(r.selector,t))return{kind:`exact_binding_mismatch`,detail:`current ECDSA pointer belongs to a different exact authority`};let i=await e.store(M).get(r.manifestId);if(i===void 0)return{kind:`exact_record_conflict`,detail:`current ECDSA pointer references a missing manifest`};let a;try{a=qt(i)}catch(e){return{kind:`corrupt`,detail:U(e)}}if(!mn(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 ga(e,t);if(o.length!==1)return{kind:`exact_record_conflict`,detail:`exact ECDSA authority has multiple current manifests`};let s;try{s=qt(o[0])}catch(e){return{kind:`corrupt`,detail:U(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(F).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=Ft(c,a.activeProof)}catch(e){return{kind:`corrupt`,detail:U(e)}}if(!En(l,a.manifest))return{kind:`exact_binding_mismatch`,detail:`active ECDSA material does not match its manifest`};let u=await e.store(P).get(l.sealingKeyId);if(u===void 0)return{kind:`missing`,subject:`material`,detail:`active ECDSA material is missing its sealing key`};try{if(Pt(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:U(e)}}return await Ot(l.ciphertextB64u)===l.binding.ciphertextDigest?{kind:`active`,manifest:a.manifest,material:l}:{kind:`corrupt`,detail:`active ECDSA material ciphertext digest is invalid`}}async function ba(e,t){let n=await e.store(M).index(E.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=qt(e)}catch(e){return{kind:`corrupt`,detail:U(e)}}if(mn(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 xa(e,t,n){let r=t.activationBinding;return Sn(e.signer.authority,r.signer.authority)&&ln(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&&Rt(e.signer.registeredPublicFacts,t.registeredPublicFacts)&&Nt(e.activation.serverActivation,n)&&p(e.activation.materialActivation,st(n.serverActivationReceipt.protocolReceipt.ecdsa_activation.material_activation))&&e.durableMaterial.bindingDigest===r.bindingDigest&&e.durableMaterial.durableMaterialRef===r.durableMaterialRef&&Bt(e.durableMaterial.roleLocalBinding,r.roleLocalBinding)&&At(e.durableMaterial.roleLocalPublicFacts,t.roleLocalPublicFacts)&&nt(e.durableMaterial.routerAbEcdsaDerivationNormalSigning,t.routerAbEcdsaDerivationNormalSigning)&&Jt(e.durableMaterial.runtimePolicyScope,ie(t.runtimePolicyScope))}var W=class extends Error{kind;constructor(e,t){super(t),this.name=`FinalizationControlError`,this.kind=e}};function Sa(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 Ca(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:Sa(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:Sa(e.candidate.activationBinding),created_at:e.createdAt}}function wa(e){return e.kind===`server_activation_committed`?Ta(e.candidate.activationBinding,e.serverActivation):Ta({targetManifest:e.identity,signer:e.signer,roleLocalBinding:e.durableMaterial.roleLocalBinding,bindingDigest:e.durableMaterial.bindingDigest,durableMaterialRef:e.durableMaterial.durableMaterialRef},e.activation.serverActivation)}function Ta(e,t){return{version:1,stage:`activation_ready`,activation_binding:Sa(e),server_activation:t}}function Ea(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 Da(e,t){return{record_version:Tn,manifest_id:e.activeManifest.identity.manifestId,manifest_revision:e.activeManifest.identity.manifestRevision,...Xt(wt(e.activeManifest)),manifest_state:t}}function Oa(e){return{...Da(e,`active`),active_proof:Ea(e)}}function ka(e,t){return{...Da(e,`replaced`),active_proof:Ea(e),replacement_proof:Ea(t)}}async function Aa(e){let t=bt({activationBinding:e.activationBinding,serverCommit:e.serverCommit}),n=at(fe(`ecdsa-material-sealing-key`,32,`ECDSA material sealing key identities`)),r=await Ht(),i=await It({key:r,stateBlobB64u:e.readyStateBlobB64u,aadProjection:Ta(e.activationBinding,t)}),a=yt({activationBinding:e.activationBinding,serverActivation:t,routerAbEcdsaDerivationNormalSigning:e.routerAbEcdsaDerivationNormalSigning,roleLocalPublicFacts:e.roleLocalPublicFacts,ciphertextDigest:Qe(i.digestB64u),runtimePolicyScope:e.runtimePolicyScope}),o=St({binding:a,sealingKeyId:n,iv12B64u:i.iv12B64u,ciphertextB64u:i.ciphertextB64u}),s=xt({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 ja(e,t){let n=wt(t.activeManifest),r=e.store(Ut),i=await r.get(Cn(n)),a=await ga(e,n);if(i!==void 0||a.length!==0)throw new W(`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(P).add(gn(t.readyMaterial.sealingKeyId,t.sealingKey)),await e.store(F).add(cn(t.readyMaterial,t.activeManifest)),await e.store(M).add(Oa(o)),await r.put(Qt(t.activeManifest))}function Ma(e){let t=Kt(Ea({activationBinding:e.committedJournal.candidate.activationBinding,serverActivation:e.committedJournal.serverActivation,durableMaterial:e.readyMaterial.binding,activeManifest:e.activeManifest,committedAt:e.activeManifest.committedAt}));if(!Tt(t.activeManifest,e.activeManifest)||!Lt(t.durableMaterial,e.readyMaterial.binding))throw Error(`ECDSA finalization input does not describe one exact active manifest`);return t}function Na(e,t,n){switch(e.kind){case`no_current_manifest`:if(t!==void 0)throw new W(`exact_record_conflict`,`initial ECDSA activation found an existing current pointer`);return null;case`exact_manifest`:{if(t===void 0)throw new W(`exact_record_conflict`,`replacement ECDSA activation is missing its expected current pointer`);let r;try{r=vn(t)}catch(e){throw new W(`corrupt`,U(e))}if(!mn(r.selector,n)||r.manifestId!==e.manifestId||r.manifestRevision!==e.manifestRevision)throw new W(`exact_record_conflict`,`replacement ECDSA activation pointer CAS did not match`);return r}}return Wt(e)}async function Pa(e,t){let n=t.store(N),r=await n.get(e.journalId);if(r===void 0)return{kind:`missing`};let i;try{i=Gt(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 un(i.journal,e)?(await t.store(P).delete(i.journal.candidate.encryptedPending.sealingKeyId),await n.delete(i.journal.journalId),{kind:`cancelled`}):{kind:`exact_record_conflict`}}return Wt(i.journal)}function Fa(e,t){return e.runTransaction([M,Ut,F,P],`readwrite`,e=>ja(e,t))}async function Ia(e,t,n){let r=bt({activationBinding:t.activationBinding,serverCommit:t.serverCommit}),i=rn(t.activationBinding.signer),a=await e.lookup(i);if(a.kind===`active`)return xa(a.manifest,t,r)?{kind:`committed`,manifest:a.manifest,material:a.material}:{kind:`exact_record_conflict`,selector:i,conflictDigest:await H(`custody_import_conflict`,i,`ECDSA custody import conflicts with the active manifest`)};try{let e=await Aa(t);return await n(e),{kind:`committed`,manifest:e.activeManifest,material:e.readyMaterial}}catch(n){if(n instanceof W||pa(n)){let a=await e.lookup(i);return a.kind===`active`&&xa(a.manifest,t,r)?{kind:`committed`,manifest:a.manifest,material:a.material}:{kind:`exact_record_conflict`,selector:i,conflictDigest:await H(`custody_import_conflict`,i,U(n))}}return{kind:`corrupt`,selector:i,corruptionDigest:await H(`custody_import_corrupt`,i,U(n))}}}var La=class{manager;constructor(e=De){this.manager=e}async admitClientPresignature(e){if(!Zt())return{kind:`persistence_unavailable`};let t=nn(e.poolIdentity),n=gt(e.durableMaterialRef);if(!dn(n,t)||e.groupPublicKey33.length!==33||e.bigR33.length!==33)return{kind:`persistence_unavailable`};let r=an(e.createdAtMs,`createdAtMs`),i=an(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`||!hn(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=tn(fe(`ecdsa-client-presignature`,32,`ECDSA durable presignature record`)),l=pt(C(e.groupPublicKey33)),u=pt(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 $t({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:en(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([Dt,F,T.appState],`readwrite`,async e=>{if(await yn(e,t.walletId,t.ownershipGeneration),(await sn(e,t,Date.now())).length>=5)return{kind:`capacity_full`};let r=await e.store(F).get(n.durableMaterialRef);if(r===void 0)return{kind:`persistence_unavailable`};try{let e=jt(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||at(i.sealing_key_id)!==o.material.sealingKeyId)return{kind:`persistence_unavailable`}}catch{return{kind:`persistence_unavailable`}}return await e.store(Dt).put(p),{kind:`stored`}},{durability:`strict`});return e.kind===`stored`?{kind:`stored`,metadata:d}:e}catch{return{kind:`persistence_ambiguous`}}}async listAvailableClientPresignatures(e){if(!Zt())return[];let t=nn(e),n=Date.now();try{return await this.manager.runTransaction([Dt,T.appState],`readwrite`,async e=>(await yn(e,t.walletId,t.ownershipGeneration),(await sn(e,t,n)).map(wn).sort((e,t)=>e.createdAtMs-t.createdAtMs)))}catch{return[]}}async takeClientPresignature(e){if(!Zt())return{kind:`persistence_unavailable`};let t=tn(e.recordId),n=nn(e.poolIdentity),r;try{let e=await this.manager.runTransaction([Dt,T.appState],`readwrite`,async e=>{let r=e.store(Dt);await yn(e,n.walletId,n.ownershipGeneration);let i=await r.get(t);if(i===void 0)return{kind:`claimed_elsewhere`};let a;try{a=_n(i)}catch{let e=pn(i);return e&&await r.delete(e),{kind:`corrupt`}}return fn(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`||!hn(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=wn(r);try{return{kind:`opened`,metadata:o,plaintext97:await xn({key:a,metadata:o,sealed:r.sealed})}}catch{return{kind:`corrupt`}}}async deleteClientPresignature(e){let t=tn(e.recordId),n=nn(e.poolIdentity);await this.manager.runTransaction([Dt],`readwrite`,async e=>{let r=e.store(Dt),i=await r.get(t);i!==void 0&&fn(_n(i).pool_identity,n)&&await r.delete(t)})}async listActiveWalletCapabilitySubjects(e){let t=a(e);if(!t.ok)return{kind:`invalid_current_state`};let n;try{n=await this.manager.runTransaction([Ut],`readonly`,e=>ma(e,t.value))}catch{return{kind:`persistence_unavailable`}}let r=[];try{for(let e of n){let n=vn(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=a(e);if(!t.ok)return{kind:`invalid_current_state`};let n;try{n=await this.manager.runTransaction([N],`readonly`,ha)}catch{return{kind:`persistence_unavailable`}}let r=[];try{for(let e of n){let n=Gt(e).journal.candidate.activationBinding.signer;n.authority.walletId===t.value&&r.push(rn(n))}}catch{return{kind:`invalid_current_state`}}return{kind:`resolved`,selectors:r}}async prepareActivation(e){let t=rn(e.activationBinding.signer);try{let t=at(fe(`ecdsa-material-key`,32,`ECDSA activation material sealing key`)),n=await Ht(),r=await It({key:n,stateBlobB64u:e.pendingPayloadB64u,aadProjection:Ca(e)}),i=kt({preparation:e,encryptedPending:vt({sealingKeyId:t,iv12B64u:r.iv12B64u,ciphertextB64u:r.ciphertextB64u,ciphertextDigest:it(r.digestB64u)})});return await this.manager.runTransaction([P,N],`readwrite`,async e=>{await e.store(P).add(gn(t,n)),await e.store(N).add(bn(i))}),{kind:`stored`,journal:i}}catch(e){return pa(e)?await da(t,e):e instanceof DOMException&&e.name===`OperationError`?{kind:`corrupt`,corruptionDigest:await H(`journal_encryption_failed`,t,U(e))}:e instanceof Error&&!(e instanceof DOMException)?{kind:`corrupt`,corruptionDigest:await H(`journal_preparation_invalid`,t,e.message)}:{kind:`persistence_unavailable`,retryCorrelation:fa()}}}async recordServerActivation(e){let t;try{t=_t(e)}catch(t){return{kind:`corrupt`,corruptionDigest:await H(`server_activation_commit_corrupt`,Vt(e.preparedJournal),U(t))}}return await this.putActivationJournal(t)}async putActivationJournal(e){let t;try{if(t=Mt(e),await Ot(t.candidate.encryptedPending.ciphertextB64u)!==t.candidate.encryptedPending.ciphertextDigest)throw Error(`ECDSA pending material ciphertext digest is invalid`)}catch(t){return{kind:`corrupt`,corruptionDigest:await H(`journal_input_corrupt`,Vt(e),U(t))}}let n=Vt(t);try{let e=await this.readMaterialSealingKey(t.candidate.encryptedPending.sealingKeyId);if(!e)throw new W(`corrupt`,`ECDSA activation journal references a missing sealing key`);return await zt({key:e,iv12B64u:t.candidate.encryptedPending.iv12B64u,ciphertextB64u:t.candidate.encryptedPending.ciphertextB64u,aadProjection:Ca(t)}),await this.manager.runTransaction([P,N],`readwrite`,async e=>{let r=await e.store(P).get(t.candidate.encryptedPending.sealingKeyId);if(r===void 0)throw new W(`corrupt`,`ECDSA activation journal references a missing sealing key`);try{Pt(r)}catch(e){throw new W(`corrupt`,U(e))}let i=e.store(N),a=await i.get(t.journalId);if(a===void 0)throw new W(`exact_record_conflict`,`ECDSA committed activation is missing its prepared journal`);let o;try{o=Gt(a)}catch(e){throw new W(`corrupt`,U(e))}if(!mn(o.selector,n)||o.journal.kind===`activation_prepared`&&!un(o.journal,Yt(t))||o.journal.kind===`server_activation_committed`&&!un(o.journal,t))throw new W(`exact_record_conflict`,`ECDSA activation journal conflicts with its existing correlation`);await i.put(bn(t))}),{kind:`stored`,journal:t}}catch(e){if(e instanceof W){let t=await H(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 pa(e)?await da(n,e):e instanceof DOMException&&e.name===`OperationError`?{kind:`corrupt`,corruptionDigest:await H(`journal_ciphertext_corrupt`,n,U(e))}:{kind:`persistence_unavailable`,retryCorrelation:fa()}}}async readActivationJournal(e){let t=_e(e);try{let e=await this.manager.runTransaction([N],`readonly`,async e=>await e.store(N).get(t));if(e===void 0)return{kind:`missing`};try{let n=Gt(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=Et(e)}catch{return{kind:`corrupt`}}try{let e=await this.manager.runTransaction([N],`readonly`,async e=>await e.store(N).index(E.capabilityWalletAuthority).get(Cn(t)));if(e===void 0)return{kind:`missing`};try{let n=Gt(e);return mn(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([P,N],`readwrite`,Pa.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 Ot(n.ciphertextB64u)!==n.ciphertextDigest)return{kind:`corrupt`};let e=await this.readMaterialSealingKey(n.sealingKeyId);return e?{kind:`found`,journal:t.journal,pendingPayloadB64u:await zt({key:e,iv12B64u:n.iv12B64u,ciphertextB64u:n.ciphertextB64u,aadProjection:Ca(t.journal)})}:{kind:`corrupt`}}catch{return{kind:`corrupt`}}}async lookup(e){let t=Et(e),n;try{n=await this.manager.runTransaction([M,Ut,F,P],`readonly`,async e=>await ya(e,t))}catch{return{kind:`persistence_unavailable`,selector:t,retryCorrelation:fa()}}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 H(n.kind,t,n.detail)};case`exact_record_conflict`:return{kind:`exact_record_conflict`,selector:t,conflictDigest:await H(n.kind,t,n.detail)};case`corrupt`:return{kind:`corrupt`,selector:t,corruptionDigest:await H(n.kind,t,n.detail)}}return Wt(n)}async lookupByMaterialActivation(e){let t=a(e.walletId),n=c(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,o=n.value,s;try{s=await this.manager.runTransaction([Ut],`readonly`,async e=>await ma(e,i))}catch{return{kind:`persistence_unavailable`,capability:r}}let l=[];try{for(let e of s){let t=vn(e);t.selector.authority.walletId===i&&l.push(t.selector)}}catch{return{kind:`corrupt`,capability:r}}if(l.length===0)return{kind:`missing`,subject:`capability`,capability:r};let u=[];for(let e of l){let t=await this.lookup(e);switch(t.kind){case`active`:_a(t,o)&&u.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 d=e.authority;if(d){let e=u.filter(e=>Sn(e.manifest.signer.authority,d));return e.length>1?{kind:`exact_record_conflict`,capability:r}:e[0]??{kind:`exact_binding_mismatch`,capability:r}}return u.length>1?{kind:`ambiguous_authority`,capability:r,authorities:u.map(e=>e.manifest.signer.authority)}:u[0]??{kind:`exact_binding_mismatch`,capability:r}}async openActiveMaterial(e){let t=Et(e),n=await this.lookup(t);return n.kind===`active`?await this.openActiveMaterialLookup(n):n}async lookupByMaterialRef(e){let t=gt(e),n=t.materialActivation.capability,r;try{r=await this.manager.runTransaction([F],`readonly`,async e=>await e.store(F).get(t.durableMaterialRef))}catch{return{kind:`persistence_unavailable`,capability:n}}if(r===void 0)return await this.lookupMissingMaterialByRef(t);let i;try{i=jt(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||!_a(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 Wt(a)}async lookupMissingMaterialByRef(e){let t=e.materialActivation.capability,n;try{n=await this.manager.runTransaction([M],`readonly`,async e=>await e.store(M).getAll())}catch{return{kind:`persistence_unavailable`,capability:t}}let r=[],i=!1;for(let a of n){let n;try{n=qt(a)}catch{return{kind:`corrupt`,capability:t}}let o=n.activeProof.durableMaterial;if(o.durableMaterialRef===e.durableMaterialRef){if(o.bindingDigest!==e.bindingDigest||!p(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=wt(e.manifest);try{if(await Ot(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 zt({key:t,iv12B64u:e.material.iv12B64u,ciphertextB64u:e.material.ciphertextB64u,aadProjection:wa(e.manifest)})}}catch(e){return{kind:`corrupt`,selector:t,corruptionDigest:await H(`active_material_open_corrupt`,t,U(e))}}}async openActiveMaterialByRef(e){let t;try{t=await this.lookupByMaterialRef(e)}catch{return{kind:`corrupt`}}if(t.kind!==`active`)return va(t);let n=await this.openActiveMaterialLookup(t);return n.kind===`active`?n:va(n)}async sealAndFinalizeActivation(e){let t=Vt(e.committedJournal);try{let t=Mt(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 It({key:r,stateBlobB64u:e.readyStateBlobB64u,aadProjection:wa(t)}),a=yt({activationBinding:t.candidate.activationBinding,serverActivation:t.serverActivation,routerAbEcdsaDerivationNormalSigning:e.routerAbEcdsaDerivationNormalSigning,roleLocalPublicFacts:mt(e.roleLocalPublicFacts),ciphertextDigest:Qe(i.digestB64u),runtimePolicyScope:e.runtimePolicyScope}),o=St({binding:a,sealingKeyId:n,iv12B64u:i.iv12B64u,ciphertextB64u:i.ciphertextB64u}),s=xt({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 H(`activation_seal_corrupt`,t,U(e))}}}async importCommittedWalletCustodyActivation(e){return await Ia(this,e,e=>Fa(this.manager,e))}async persistPreparedWalletCustodyEcdsaContinuity(e){await Fa(this.manager,e)}async readMaterialSealingKey(e){let t=at(e),n=await this.manager.runTransaction([P],`readonly`,async e=>await e.store(P).get(t));if(n===void 0)return null;let r=Pt(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=Ma(e)}catch(t){let n=Vt(e.committedJournal);return{kind:`corrupt`,selector:n,corruptionDigest:await H(`finalization_input_corrupt`,n,U(t))}}let n=wt(t.activeManifest);try{if(await Ot(e.readyMaterial.ciphertextB64u)!==e.readyMaterial.binding.ciphertextDigest)throw new W(`corrupt`,`ECDSA ready material ciphertext digest is invalid`);let r=await this.readMaterialSealingKey(e.readyMaterial.sealingKeyId);if(!r)throw new W(`corrupt`,`ECDSA ready material sealing key is missing`);return await zt({key:r,iv12B64u:e.readyMaterial.iv12B64u,ciphertextB64u:e.readyMaterial.ciphertextB64u,aadProjection:wa(e.committedJournal)}),await this.manager.runTransaction([M,Ut,F,N,P,Dt],`readwrite`,async r=>{await Ra(r,e,t,n)}),{kind:`committed`,manifest:t.activeManifest,material:e.readyMaterial}}catch(e){if(e instanceof W){let t=await H(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 pa(e)?{kind:`exact_record_conflict`,selector:n,conflictDigest:await H(`finalization_constraint_conflict`,n,U(e))}:{kind:`persistence_unavailable`,selector:n,retryCorrelation:fa()}}}};async function Ra(e,t,n,r){let i=e.store(N),a=await i.get(t.committedJournal.journalId);if(a===void 0)throw new W(`exact_record_conflict`,`ECDSA finalization is missing its durable activation journal`);let o;try{o=Gt(a)}catch(e){throw new W(`corrupt`,U(e))}if(o.journal.kind!==`server_activation_committed`||!mn(o.selector,r)||!un(o.journal,t.committedJournal))throw new W(`exact_record_conflict`,`ECDSA finalization journal does not match its committed activation`);let s=await e.store(P).get(t.readyMaterial.sealingKeyId);if(s===void 0)throw new W(`corrupt`,`ECDSA finalization is missing its material sealing key`);try{Pt(s)}catch(e){throw new W(`corrupt`,U(e))}let c=e.store(Ut),l=await c.get(Cn(r)),u=t.committedJournal.expectedManifest,d=Na(u,l,r),f=await ga(e,r),p=null,m=null;if(d===null){if(f.length!==0)throw new W(`exact_record_conflict`,`initial ECDSA activation found an unpointed active manifest`)}else{if(f.length!==1)throw new W(`exact_record_conflict`,`replacement ECDSA activation found conflicting current manifests`);let n;try{n=qt(f[0])}catch(e){throw new W(`corrupt`,U(e))}if(n.state!==`active`||n.manifest.identity.manifestId!==d.manifestId)throw new W(`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 W(`exact_record_conflict`,`replacement ECDSA activation server generation CAS did not match`);let r=await e.store(F).get(n.manifest.durableMaterial.durableMaterialRef);if(r===void 0)throw new W(`corrupt`,`replacement ECDSA activation is missing prior material`);try{let e=Ft(r,n.activeProof);if(!En(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 W(`corrupt`,U(e))}p=n.activeProof}let h=e.store(M),g=e.store(F);if(p){if(!m)throw new W(`corrupt`,`replacement ECDSA activation is missing its prior sealing key identity`);await on(e,String(p.durableMaterial.materialActivation.materialOwner),String(p.durableMaterial.materialActivation.activationId)),await h.put(ka(p,n)),await g.delete(p.durableMaterial.durableMaterialRef),await e.store(P).delete(m)}await g.add(cn(t.readyMaterial,n.activeManifest)),await h.add(Oa(n)),await c.put(Qt(n.activeManifest)),await i.delete(t.committedJournal.journalId)}const za=`ed25519_yao_public_capability_references_v1`,Ba=`ed25519_yao_public_capability_lanes_v1`,Va=`ed25519YaoPublicCapabilityReferencesV1`,Ha=`ed25519YaoPublicCapabilityLanesV1`;async function Ua(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 Wa(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 Ga(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return e}function Ka(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<1)throw Error(`${t} must be a positive integer`);return e}function qa(e,t){let n=b(e,t),r=g(n.kind,`${t}.kind`,`must be a non-empty normalized string`);switch(r){case`passkey`:return Wa(n,[`kind`,`rpId`,`credentialIdB64u`],t),{kind:r,rpId:rt(g(n.rpId,`${t}.rpId`,`must be a non-empty normalized string`)),credentialIdB64u:g(n.credentialIdB64u,`${t}.credentialIdB64u`,`must be a non-empty normalized string`)};case`email_otp`:return Wa(n,[`kind`,`providerSubjectId`],t),{kind:r,providerSubjectId:g(n.providerSubjectId,`${t}.providerSubjectId`,`must be a non-empty normalized string`)};default:throw Error(`${t}.kind is invalid`)}}function Ja(e,t){let n=b(e,t);Wa(n,[`walletId`,`nearAccountId`,`thresholdSessionId`,`runtimePolicyScope`,`materialActivation`],t);let r=c(n.materialActivation);if(!r.ok)throw Error(`${t}.materialActivation is invalid: ${r.error.message}`);let i=o(n.thresholdSessionId);if(!i.ok)throw Error(`${t}.thresholdSessionId is invalid`);let a=pe(n.runtimePolicyScope);if(!a)throw Error(`${t}.runtimePolicyScope is invalid`);return{walletId:xe(g(n.walletId,`${t}.walletId`,`must be a non-empty normalized string`)),nearAccountId:ye(g(n.nearAccountId,`${t}.nearAccountId`,`must be a non-empty normalized string`)),thresholdSessionId:i.value,runtimePolicyScope:a,materialActivation:r.value}}function Ya(e,t){let n=b(e,t),r=qa(n.auth,`${t}.auth`);Wa(n,[`walletId`,`nearAccountId`,`thresholdSessionId`,`runtimePolicyScope`,`materialActivation`,`auth`,`nearEd25519SigningKeyId`,`signerSlot`,...r.kind===`email_otp`?[`remainingUses`,`expiresAtMs`]:[]],t);let i=Ja({walletId:n.walletId,nearAccountId:n.nearAccountId,thresholdSessionId:n.thresholdSessionId,runtimePolicyScope:n.runtimePolicyScope,materialActivation:n.materialActivation},t),a=ft(n.signerSlot);if(a===null)throw Error(`${t}.signerSlot is invalid`);let o={...i,nearEd25519SigningKeyId:ut(g(n.nearEd25519SigningKeyId,`${t}.nearEd25519SigningKeyId`,`must be a non-empty normalized string`)),signerSlot:a};switch(r.kind){case`email_otp`:return{...o,auth:r,remainingUses:Ga(n.remainingUses,`${t}.remainingUses`),expiresAtMs:Ka(n.expiresAtMs,`${t}.expiresAtMs`)};case`passkey`:return{...o,auth:r};default:throw Error(`${t}.auth is invalid`)}}function Xa(e){let t=b(e,`Ed25519 Yao public capability references`);if(Wa(t,[`kind`,`identities`],`Ed25519 Yao public capability references`),t.kind!==za)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)=>Ja(e,`Ed25519 Yao public capability identity ${t}`));if(new Set(n.map(eo)).size!==n.length)throw Error(`Ed25519 Yao public capability references contain duplicate identities`);return{kind:za,identities:n}}function Za(e){let t=b(e,`Ed25519 Yao public capability lanes`);if(Wa(t,[`kind`,`lanes`],`Ed25519 Yao public capability lanes`),t.kind!==Ba)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)=>Ya(e,`Ed25519 Yao public capability lane ${t}`));if(new Set(n.map(eo)).size!==n.length)throw Error(`Ed25519 Yao public capability lanes contain duplicate identities`);return{kind:Ba,lanes:n}}function Qa(){return{kind:za,identities:[]}}function $a(){return{kind:Ba,lanes:[]}}function eo(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 to(e){return Ja(e,`Ed25519 Yao public capability identity`)}function no(e){return Ya(e,`Ed25519 Yao public capability lane`)}async function ro(e,t){let n=await e.get(Va);if(n!==void 0&&n.key!==Va)throw Error(`Ed25519 Yao public capability reference app-state key is inconsistent`);let r=n===void 0?Qa():Xa(n.value),i=to(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:Va,value:Xa({kind:za,identities:[...a,i]})})}var io=class{constructor(e){this.appState=e}async readProjection(){if(this.appState.isDisabled())return Qa();let e=await this.appState.getAppState(Va);return e==null?Qa():Xa(e)}async writeProjection(e){this.appState.isDisabled()||await this.appState.setAppState(Va,Xa(e))}async readLaneProjection(){if(this.appState.isDisabled())return $a();let e=await this.appState.getAppState(Ha);return e==null?$a():Za(e)}async writeLaneProjection(e){this.appState.isDisabled()||await this.appState.setAppState(Ha,Za(e))}async upsert(e){let t=to(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:za,identities:[...n,t]})}async remove(e){let t=eo(e),n=await this.readProjection();await this.writeProjection({kind:za,identities:n.identities.filter(e=>eo(e)!==t)})}async list(){return(await this.readProjection()).identities.map(to)}async upsertLane(e){let t=no(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:Ba,lanes:[...n,t]})}async removeLane(e){let t=eo(e),n=await this.readLaneProjection();await this.writeLaneProjection({kind:Ba,lanes:n.lanes.filter(e=>eo(e)!==t)})}async listLanes(){return(await this.readLaneProjection()).lanes.map(no)}};async function ao(e,t){let n=String(t||``).trim();if(!n)return null;let r=new Set;for(let t of await new io(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 oo(e){return e.family===`near`?e.walletId:e.accountId}function so(e){return e.family===`near`?e.nearAccountId:``}function co(e){let n=t(e.leaseId||``),r=t(e.laneKey||``),i=t(oo(e)||``),a=t(so(e)||``);if(!n||!r||!i)throw Error(`[SeamsWalletDB] nonce lease requires leaseId, laneKey, and wallet identity`);return{lease_id:n,lane_key:r,wallet_id:i,...a?{near_account_id:a}:{},state:e.state,expires_at_ms:Math.floor(Number(e.expiresAtMs)),record:e}}function lo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=D(Reflect.get(e,`lock_key`)),n=D(Reflect.get(e,`owner_id`)),r=D(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 uo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{return be({kind:Reflect.get(e,`kind`),namespace:Reflect.get(e,`namespace`),chainId:Reflect.get(e,`chainId`),networkSlug:Reflect.get(e,`networkSlug`)})}catch{return null}}function fo(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`v`),n=D(Reflect.get(e,`leaseId`)),r=D(Reflect.get(e,`laneKey`)),i=D(Reflect.get(e,`networkKey`)),a=D(Reflect.get(e,`nonce`)),o=D(Reflect.get(e,`operationId`)),s=D(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`&&!D(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&&!D(p)||m!==void 0&&!D(m)||h!==void 0&&!D(h)||g!==void 0&&!Number.isSafeInteger(g))return null;let _=Reflect.get(e,`family`);if(_===`near`){let t=D(Reflect.get(e,`walletId`)),_=D(Reflect.get(e,`nearAccountId`)),v=D(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=uo(Reflect.get(e,`chainTarget`)),y=D(Reflect.get(e,`sender`)),b=D(Reflect.get(e,`accountId`));if(!v||!y||!b)return null;let ee=Reflect.get(e,`nonceKey`);return ee!==void 0&&!D(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 po(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=fo(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`)!==oo(t)||(Reflect.get(e,`near_account_id`)||``)!==so(t)||Reflect.get(e,`state`)!==t.state||Reflect.get(e,`expires_at_ms`)!==Math.floor(Number(t.expiresAtMs))?null:t}function mo(e){let n=t(e.opId||``),r=t(e.idempotencyKey||``),i=O(e.chainIdKey),a=k(e.accountAddress),o=t(e.signerId||``);if(!n||!r||!i||!a||!o)throw Error(`[SeamsWalletDB] signer op requires opId, idempotencyKey, chainIdKey, accountAddress, and signerId`);return{op_id:n,idempotency_key:r,status:e.status,next_attempt_at:e.nextAttemptAt,wallet_id:t(String(e.payload?.profileId||``)),chain_target_key:Ae({chainIdKey:i,accountAddress:a}),updated_at:e.updatedAt,record:{...e,opId:n,idempotencyKey:r,chainIdKey:i,accountAddress:a,signerId:o}}}function ho(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=D(Reflect.get(e,`opId`)),n=D(Reflect.get(e,`idempotencyKey`)),r=D(Reflect.get(e,`opType`)),i=O(Reflect.get(e,`chainIdKey`)),a=k(Reflect.get(e,`accountAddress`)),o=D(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=Pe(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 go(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let n=ho(Reflect.get(e,`record`));if(!n||Reflect.get(e,`op_id`)!==n.opId||Reflect.get(e,`idempotency_key`)!==n.idempotencyKey||Reflect.get(e,`status`)!==n.status||Reflect.get(e,`next_attempt_at`)!==n.nextAttemptAt||Reflect.get(e,`chain_target_key`)!==Ae({chainIdKey:n.chainIdKey,accountAddress:n.accountAddress}))return null;let r=t(String(n.payload&&Reflect.get(n.payload,`profileId`)?Reflect.get(n.payload,`profileId`):``));return Reflect.get(e,`wallet_id`)!==r||Reflect.get(e,`updated_at`)!==n.updatedAt?null:n}function _o(e){return`${e.chainIdKey}\0${e.accountAddress}`}function vo(e){return[e.chainIdKey,e.accountAddress,e.signerId].join(`\0`)}function yo(e){if(typeof e!=`object`||!e||Array.isArray(e))return``;let n=t(Reflect.get(e,`kind`)||``),r=Number(Reflect.get(e,`chainId`));return!Number.isSafeInteger(r)||r<=0?``:n===`evm`?t(Reflect.get(e,`namespace`)||``)===`eip155`?je({kind:`evm`,namespace:`eip155`,chainId:r,networkSlug:t(Reflect.get(e,`networkSlug`)||``)}):``:n===`tempo`?je({kind:`tempo`,chainId:r,networkSlug:t(Reflect.get(e,`networkSlug`)||``)}):``}function bo(e){if(e.signerKind===Se.thresholdEcdsa){let n=e.metadata||{},r=t(n.keyHandle||``),i=t(n.ecdsaThresholdKeyId||``),a=k(n.thresholdOwnerAddress||``),o=yo(n.chainTarget);if(!r||!i||!a||!o)throw Error(`[SeamsWalletDB] threshold ECDSA signer requires keyHandle, ecdsaThresholdKeyId, thresholdOwnerAddress, and chainTarget`);return{chainTargetKey:o,keyHandle:r,ecdsaThresholdKeyId:i,thresholdOwnerAddress:a}}let n=Number(e.signerSlot);if(!Number.isSafeInteger(n)||n<1)throw Error(`[SeamsWalletDB] Ed25519 signer requires a positive signerSlot`);let r=t(e.metadata?.nearEd25519SigningKeyId||``);if(!r)throw Error(`[SeamsWalletDB] Ed25519 signer requires nearEd25519SigningKeyId`);return{chainTargetKey:Ae({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress}),nearSignerSlot:n,nearEd25519SigningKeyId:r}}function xo(e,n){let r=t(e.profileId||``),i=O(e.chainIdKey),a=k(e.accountAddress),o=ke(e.accountModel);if(!r||!i||!a)throw Error(`[SeamsWalletDB] profileId, chainIdKey, and accountAddress are required`);if(!o)throw Error(`[SeamsWalletDB] accountModel is required`);let s=Date.now(),c={profileId:r,chainIdKey:i,accountAddress:a,accountModel:o,isPrimary:e.isPrimary??n?.isPrimary??!1,createdAt:n?.createdAt??s,updatedAt:s};return{wallet_id:r,near_account_id:_o({chainIdKey:i,accountAddress:a}),signer_slot:0,profile_id:r,chain_id_key:i,account_address:a,account_model:o,is_primary:!!c.isPrimary,updated_at:c.updatedAt,record:c}}function So(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=D(Reflect.get(e,`profileId`)),n=O(Reflect.get(e,`chainIdKey`)),r=k(Reflect.get(e,`accountAddress`)),i=ke(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 Co(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=So(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`)!==_o({chainIdKey:t.chainIdKey,accountAddress:t.accountAddress})?null:t}function wo(e){let n=t(e.profileId||``),r=O(e.chainIdKey),i=k(e.accountAddress),a=t(e.signerId||``),o=t(e.signerKind||``);if(!n||!r||!i||!a||!o)throw Error(`[SeamsWalletDB] signer requires profileId, chainIdKey, accountAddress, signerId, and signerKind`);let s=bo({...e,profileId:n,chainIdKey:r,accountAddress:i,signerId:a}),c=e.status===`active`;return{wallet_signer_id:vo({chainIdKey:r,accountAddress:i,signerId:a}),wallet_id:n,kind:o,chain_target_key:s.chainTargetKey,...c&&s.nearSignerSlot!=null?{near_signer_slot:s.nearSignerSlot}:{},...c&&s.nearEd25519SigningKeyId?{near_ed25519_signing_key_id:s.nearEd25519SigningKeyId}:{},...c&&s.keyHandle?{key_handle:s.keyHandle}:{},...c&&s.ecdsaThresholdKeyId?{ecdsa_threshold_key_id:s.ecdsaThresholdKeyId}:{},...c&&s.thresholdOwnerAddress?{threshold_owner_address:s.thresholdOwnerAddress}:{},status:e.status,updated_at:e.updatedAt,record:{...e,profileId:n,chainIdKey:r,accountAddress:i,signerId:a}}}function To(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=D(Reflect.get(e,`profileId`)),n=O(Reflect.get(e,`chainIdKey`)),r=k(Reflect.get(e,`accountAddress`)),i=D(Reflect.get(e,`signerId`)),a=Reflect.get(e,`signerSlot`),o=D(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!==Se.thresholdEd25519&&s!==Se.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 G(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=To(Reflect.get(e,`record`));if(!t||Reflect.get(e,`wallet_signer_id`)!==vo({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=bo(t)}catch{return null}let r=t.status===`active`;if(t.signerKind===Se.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 K(e){throw Error(`Unhandled wallet auth method branch: ${String(e)}`)}function Eo(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`;default:return K(e)}}function Do(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 Oo(e){return`local-authority/pending-profile-projection/v1/${e}`}function ko(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 Ao(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 jo(e){let t=A(e.authority),n=j(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 Mo(e){let t=e.pending,n=e.foundingAuthority.authMethod,r=e.registration.initialAuthMethod;if(Ao(t,e.request),Or(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(!tt(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=Ze(r.authority);if(!i||!et(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||!ct(i,e.authority)||e.registration.authenticators.length!==0)throw Error(`registration Email OTP records do not match the pending commit`);return}}}function No(e){let t=e.pending.projection;if(!bc(e.authority,t.authority)||!Sc(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=Ze(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 Po(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||!le(e.existing,e.incoming))throw Error(`Credential-free registration projection changed immutable session identity`)}const Fo=`lastProfileState`,Io=[T.appState,T.wallets,T.walletAuthMethods,T.walletSigners,T.nearAccountProjections,T.signerOpsOutbox,T.keyMaterial],Lo=[T.appState,T.wallets,T.walletAuthMethods,T.walletAuthorities,T.walletSelections,T.walletSigners,T.nearAccountProjections,T.signerOpsOutbox,T.keyMaterial,T.walletSessionAuthorizations,T.ecdsaClientPresignatures,T.ecdsaCapabilityManifests,T.ecdsaCurrentCapabilityManifests,T.ecdsaRoleLocalMaterial,T.ecdsaMaterialSealingKeys],Ro=[T.appState,T.wallets,T.walletAuthMethods,T.walletAuthorities,T.walletSelections,T.walletSigners,T.nearAccountProjections,T.signerOpsOutbox,T.keyMaterial,T.ecdsaCapabilityManifests,T.ecdsaCurrentCapabilityManifests,T.ecdsaRoleLocalMaterial,T.ecdsaMaterialSealingKeys,T.ecdsaClientPresignatures],zo=`local`;function Bo(e){let t=i(e);if(!t.ok)throw Error(t.error.message);return t.value}var Vo=class extends Error{code;details;constructor(e,t,n){super(t),this.name=`SeamsWalletDBConstraintError`,this.code=e,this.details=n}};function Ho(e){return new Promise(t=>setTimeout(t,e))}function Uo(e){let t=new Uint8Array(16);return crypto.getRandomValues(t),`${e}-${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}function Wo(e){return IDBKeyRange.upperBound(e)}async function Go(e){let t=await e.store.index(e.indexName).getAllKeys(e.key);for(let n of t)await e.store.delete(n)}function Ko(e){let t=Oe(e);return t?`${Fo}::${t}`:Fo}function qo(e){return e.accountModel===`near-native`||e.chainIdKey.startsWith(`near:`)}function q(e,t,n){return new Vo(e,t,n)}function Jo(e,n){let r=t(e.profileId||``);if(!r)throw Error(`[SeamsWalletDB] profileId is required`);let i=Date.now(),a=e.passkeyCredential?.rawId?e.passkeyCredential:n?.passkeyCredential,o=n?.nearProvisioning?.status===`near_ready`&&e.nearProvisioning?.status!==`near_ready`?n.nearProvisioning:e.nearProvisioning??n?.nearProvisioning,s={profileId:r,defaultSignerSlot:e.defaultSignerSlot??n?.defaultSignerSlot??1,...a?{passkeyCredential:a}:{},preferences:e.preferences??n?.preferences,...o?{nearProvisioning:o}:{},createdAt:n?.createdAt??i,updatedAt:i};return{wallet_id:r,rp_id:zo,status:`active`,created_at:s.createdAt,updated_at:s.updatedAt,record:s}}function Yo(e){return{wallet_id:e.profileId,rp_id:zo,status:`active`,created_at:e.createdAt,updated_at:e.updatedAt,record:e}}function Xo(e,t){return e===void 0||t===void 0?e===t:e.id===t.id&&e.rawId===t.rawId}function Zo(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 Qo(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 K(e)}}function $o(e,t){return e.profileId===t.profileId&&e.defaultSignerSlot===t.defaultSignerSlot&&Xo(e.passkeyCredential,t.passkeyCredential)&&Zo(e.preferences,t.preferences)&&Qo(e.nearProvisioning,t.nearProvisioning)&&e.createdAt===t.createdAt&&e.updatedAt===t.updatedAt}function es(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&&$o(e.record,t.record)}function ts(e,t){return e===void 0||t===void 0?e===t:e.length===t.length?e.every((e,n)=>e===t[n]):!1}function ns(e,t){return e.profileId===t.profileId&&e.signerSlot===t.signerSlot&&e.credentialId===t.credentialId&&uc(e.credentialPublicKey,t.credentialPublicKey)&&ts(e.transports,t.transports)&&e.name===t.name&&e.registered===t.registered&&e.syncedAt===t.syncedAt}function rs(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&&ct(e.authority,t.authority);default:return K(e)}}function is(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||!rs(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&&ns(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 K(e)}}function as(e){return e===void 0?{kind:`account_signer_rollback_metadata_absent_v1`}:{kind:`account_signer_rollback_metadata_json_v1`,json:JSON.stringify(e)}}function os(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 K(t)}}function ss(e){return e===void 0?{kind:`key_material_rollback_payload_absent_v1`}:{kind:`key_material_rollback_payload_json_v1`,json:JSON.stringify(e)}}function cs(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 K(t)}}function ls(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&&os(e.metadata,n)}function us(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&&cs(e.payload,n)&&ds(e.payloadEnvelope,t.payloadEnvelope)&&e.timestamp===t.timestamp&&e.schemaVersion===t.schemaVersion}function ds(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 fs(e,t){return e.profileId===t.profileId&&e.activeSignerSlot===t.activeSignerSlot&&e.scope===t.scope}function ps(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 ms(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Reflect.get(e,`profileId`),n=a(t),r=Reflect.get(e,`defaultSignerSlot`),i=Reflect.get(e,`createdAt`),o=Reflect.get(e,`updatedAt`);if(!n.ok||n.value!==t||!Number.isSafeInteger(r)||Number(r)<1||!Number.isSafeInteger(i)||Number(i)<0||!Number.isSafeInteger(o)||Number(o)<0)return null;let s=Reflect.get(e,`passkeyCredential`),c;if(s!==void 0){if(typeof s!=`object`||!s||Array.isArray(s))return null;let e=Reflect.get(s,`id`),t=Reflect.get(s,`rawId`);if(typeof e!=`string`||typeof t!=`string`||!e||!t||e.trim()!==e||t.trim()!==t)return null;c={id:e,rawId:t}}let l=ps(Reflect.get(e,`preferences`));if(l===null)return null;let u=Reflect.get(e,`nearProvisioning`),d;if(u!==void 0){let e=Ct(u);if(e===null)return null;d=e}return{profileId:n.value,defaultSignerSlot:Number(r),...c===void 0?{}:{passkeyCredential:c},...l===void 0?{}:{preferences:l},...d===void 0?{}:{nearProvisioning:d},createdAt:Number(i),updatedAt:Number(o)}}function J(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=ms(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 hs(e){if(typeof e!=`object`||!e||Array.isArray(e)||Reflect.get(e,`kind`)!==`local_authority_pending_profile_projection_v1`)return null;let t=gs(Reflect.get(e,`profile`)),n=Reflect.get(e,`authenticator`),r=Reflect.get(e,`localAuthMethod`),i=n===null?null:Y(n),a=r===null?null:Y(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 gs(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=J(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 _s(e){switch(e.kind){case`passkey`:return t(e.credentialIdB64u||``);case`email_otp`:return t(e.emailHashHex||``);default:{let t=e;throw Error(`[SeamsWalletDB] Unsupported auth-method binding: ${String(t)}`)}}}function vs(e){return e.kind===`passkey`?[t(e.walletId||``),e.kind,t(e.rpId||``),_s(e)].join(`\0`):[t(e.walletId||``),e.kind,_s(e)].join(`\0`)}function ys(e){if(e.version!==`wallet_auth_method_v1`)throw Error(`[SeamsWalletDB] auth-method binding version is invalid`);let n=t(e.walletId||``),r=e.kind===`passkey`?t(e.rpId||``):``,i=_s(e),a=Math.floor(Number(e.createdAtMs)),o=Math.floor(Number(e.updatedAtMs));if(!n||!i||e.kind===`passkey`&&!r)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(a))throw Error(`[SeamsWalletDB] auth-method binding createdAtMs is invalid`);if(!Number.isSafeInteger(o))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(!t(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(!t(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 n=Ze(e.authority);if(!n||n.walletId!==e.walletId||n.verifier.emailHashHex!==e.emailHashHex||!ct(n,e.authority))throw Error(`[SeamsWalletDB] Email OTP auth-method authority binding is invalid`)}return{wallet_auth_method_id:vs(e),wallet_id:n,kind:e.kind,auth_method:e.kind,rp_id:r,auth_identifier_key:i,status:e.status,updated_at:o,record:e}}function bs(e){return new Date(e).toISOString()}function xs(e,t){let n=Date.parse(e);return Number.isSafeInteger(n)?n:t}function Ss(e){let n=t(e.profileId||``),r=t(e.credentialId||``),i=Number(e.signerSlot);if(!n||!r)throw Error(`[SeamsWalletDB] profileId and credentialId are required for authenticators`);if(!Number.isSafeInteger(i)||i<1)throw Error(`[SeamsWalletDB] authenticator signerSlot must be an integer >= 1`);let a=e.credentialPublicKey;if(!(a instanceof Uint8Array)||a.byteLength===0)throw Error(`[SeamsWalletDB] authenticator credentialPublicKey must be a non-empty Uint8Array`);return{profileId:n,signerSlot:i,credentialId:r,credentialPublicKey:a,...Array.isArray(e.transports)?{transports:e.transports}:{},...e.name?{name:String(e.name)}:{},registered:t(e.registered||``),syncedAt:t(e.syncedAt||``)}}function Cs(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 Ss({profileId:e.walletId,signerSlot:n,credentialId:e.credentialIdB64u,credentialPublicKey:w(e.credentialPublicKeyB64u),registered:bs(e.createdAtMs),syncedAt:bs(e.updatedAtMs)})}function ws(e,t){let n=Ss(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:dt(n.profileId),rpId:Bo(zo),credentialIdB64u:n.credentialId,credentialPublicKeyB64u:r,counter:0,createdAtMs:xs(n.registered,i),updatedAtMs:xs(n.syncedAt,i)}}function Ts(e){let t=ys(e.binding),n=Ss(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 Es(e){let t=ys(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 Ds(e,t){switch(e.kind){case`passkey`:return Ts({binding:e,authenticator:Cs(e,t)});case`email_otp`:return Es(e);default:{let t=e;throw Error(`[SeamsWalletDB] Unsupported auth-method row: ${String(t)}`)}}}function Os(e,t){let n=Ss(e);return Ts({binding:ws(n,t?.record),authenticator:n})}function ks(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 As(e,t){return e.authorityId===t.authorityId&&e.walletId===t.walletId&&e.authMethodId===t.authMethodId&&es(e.profile,t.profile)&&(e.authenticator===null?t.authenticator===null:t.authenticator!==null&&is(e.authenticator,t.authenticator))&&(e.localAuthMethod===null?t.localAuthMethod===null:t.localAuthMethod!==null&&is(e.localAuthMethod,t.localAuthMethod))}function js(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||Zo(e.profile.record.preferences,t.profile.preferences))&&(t.authenticator===null?e.authenticator===null:e.authenticator!==null&&ns(e.authenticator.authenticator,t.authenticator))&&(t.localAuthMethod===null?e.localAuthMethod===null:e.localAuthMethod!==null&&rs(e.localAuthMethod.record,t.localAuthMethod))}function Ms(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=D(Reflect.get(e,`profileId`)),n=Reflect.get(e,`signerSlot`),r=D(Reflect.get(e,`credentialId`)),i=Reflect.get(e,`credentialPublicKey`),a=D(Reflect.get(e,`registered`)),o=D(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 Ns(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=a(s),u=Reflect.get(e,`createdAtMs`),d=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(u)||Number(u)<0||!Number.isSafeInteger(d)||Number(d)<0)return null;if(n===`passkey`){let t=Reflect.get(e,`rpId`),n=i(t),a=Reflect.get(e,`credentialIdB64u`),s=l(a),f=Reflect.get(e,`credentialPublicKeyB64u`),p=Reflect.get(e,`counter`);return!n.ok||n.value!==t||!s.ok||s.value!==a||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:s.value,credentialPublicKeyB64u:f,counter:Number(p),createdAtMs:Number(u),updatedAtMs:Number(d)}}let f=D(Reflect.get(e,`emailHashHex`)),p=D(Reflect.get(e,`registrationAuthorityId`)),m=Ze(Reflect.get(e,`authority`));return!f||!p||!m||m.walletId!==c.value||m.verifier.emailHashHex!==f?null:{version:`wallet_auth_method_v1`,kind:`email_otp`,status:r,localStatus:o,walletId:c.value,emailHashHex:f,registrationAuthorityId:p,authority:m,createdAtMs:Number(u),updatedAtMs:Number(d)}}function Y(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=Ns(Reflect.get(e,`record`));if(!t)return null;let n;try{if(t.kind===`passkey`){let r=Ms(Reflect.get(e,`authenticator`));if(!r)return null;n=Ts({binding:t,authenticator:r})}else if(t.kind===`email_otp`)n=Es(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 Ps(e){let t=Y(e);return t?t.record:null}function Fs(e){let t=Y(e);return!t||t.kind!==`passkey`||t.status!==`active`?null:t.authenticator}function Is(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 X(e,t){if(!e.ok)throw Error(`${t}: ${e.error.message}`);return e.value}function Ls(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 Rs(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw Error(`${t} must be a non-negative safe integer`);return Number(e)}function zs(e){return e!==void 0}function Bs(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=A(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 Vs(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 Hs(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`}};default:throw Error(`Wallet auth-method presentation kind is invalid`)}}function Us(e,t){if(e===void 0)return Hs(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 Is(e,[`version`,`kind`])?{version:`wallet_auth_method_local_presentation_v1`,kind:`passkey`}:null;case`email_otp`:{if(!Is(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 Is(t,[`kind`])?{version:`wallet_auth_method_local_presentation_v1`,kind:`email_otp`,email:{kind:`unavailable`}}:null;case`verified`:{if(!Is(t,[`kind`,`address`]))return null;let e=h(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}}default:return null}}function Z(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=j(Reflect.get(e,`record`));if(!t)return null;let n=Us(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:Ws(Ys(t,n))}function Ws(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};default:throw Error(`Wallet auth-method projection kind is invalid`)}}function Gs(e,t){let n=new Set;for(let r of t){let t=Y(r)?.record;if(!t||t.kind!==`email_otp`||t.emailHashHex!==e.emailHashHex||t.authority.bindingId!==e.walletAuthMethodId)continue;let i=h(t.authority.factor.providerUserId);i.ok&&n.add(String(i.value))}if(n.size!==1)return null;let r=h([...n][0]);return r.ok?{version:`wallet_auth_method_local_presentation_v1`,kind:`email_otp`,email:{kind:`verified`,address:r.value}}:null}function Ks(e,t,n){switch(e.kind){case`passkey`:return Hs(e);case`email_otp`:return Gs(e,t)??(n?.kind===`email_otp`&&n.email.kind===`verified`?n:Hs(e));default:throw Error(`Wallet auth-method presentation kind is invalid`)}}function qs(e,t){return e.kind===t.kind?e.kind===`passkey`&&t.kind===`passkey`?!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 Js(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Reflect.get(e,`presentation`)!==void 0}function Ys(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};default:throw Error(`Wallet auth-method projection kind is invalid`)}}async function Xs(e,t){let n=Z(await e.get(t.walletAuthMethodId));return Ws(Ys(t,Ks(t,await e.index(E.walletId).getAll(t.walletId),n?.presentation??null)))}function Zs(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 Fn(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(!Is(e,r===`ecdsa_secp256k1`?[...i,`ecdsaThresholdKeyId`]:i))throw Error(`signer material record fields are invalid`);let a=X(n(Reflect.get(e,`authorityId`)),`authorityId`),o=X(s(Reflect.get(e,`walletAuthMethodId`)),`walletAuthMethodId`),l=X(c(Reflect.get(e,`materialActivation`)),`materialActivation`),u=Ls(Reflect.get(e,`activationId`),`activationId`),d=Ls(Reflect.get(e,`sealedMaterialB64u`),`sealedMaterialB64u`),f=ve(Reflect.get(e,`sealedMaterialDigestB64u`));if(l.activationId!==u)throw Error(`signer material activationId does not match materialActivation`);return r===`ed25519`?{kind:`wallet_authority_signer_material_v1`,authorityId:a,walletAuthMethodId:o,activationId:l.activationId,keyFamily:`ed25519`,materialActivation:l,sealedMaterialB64u:d,sealedMaterialDigestB64u:f}:{kind:`wallet_authority_signer_material_v1`,authorityId:a,walletAuthMethodId:o,activationId:l.activationId,keyFamily:`ecdsa_secp256k1`,ecdsaThresholdKeyId:ht(Reflect.get(e,`ecdsaThresholdKeyId`)),materialActivation:l,sealedMaterialB64u:d,sealedMaterialDigestB64u:f}}function Qs(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{let t=Zs(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 $s(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 ec(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`export root record must be an object`);if(!Is(e,[`kind`,`authorityId`,`walletAuthMethodId`,`walletKeyId`,`envelope`]))throw Error(`export root record fields are invalid`);if(Reflect.get(e,`kind`)!==`wallet_authority_export_root_v1`)throw Error(`export root record kind is invalid`);let t=X(u(Reflect.get(e,`walletKeyId`)),`walletKeyId`),r=Ce(Reflect.get(e,`envelope`));if(r.binding.kind!==`ed25519_yao_client_root_v1`||r.binding.walletKeyId!==t)throw Error(`export root envelope does not match walletKeyId`);return{kind:`wallet_authority_export_root_v1`,authorityId:X(n(Reflect.get(e,`authorityId`)),`authorityId`),walletAuthMethodId:X(s(Reflect.get(e,`walletAuthMethodId`)),`walletAuthMethodId`),walletKeyId:t,envelope:r}}function tc(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{let t=ec(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 nc(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 rc(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{let t=Te(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 ic(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 ac(e){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`wallet selection record must be an object`);if(!Is(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:X(a(Reflect.get(e,`walletId`)),`walletId`),walletAuthMethodId:X(s(Reflect.get(e,`walletAuthMethodId`)),`walletAuthMethodId`),lockGeneration:Rs(Reflect.get(e,`lockGeneration`),`lockGeneration`),lockState:t,updatedAtMs:Rs(Reflect.get(e,`updatedAtMs`),`updatedAtMs`)}}function Q(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;try{let t=ac(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 oc(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 sc(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 cc(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 lc(e){return e.keyFamilies.length===2||e.keyFamilies[0]===`ed25519`}function uc(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 dc(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 K(e)}}function fc(e,t){if(t.kind!==e.kind||e.authorityId!==t.authorityId||e.walletAuthMethodId!==t.walletAuthMethodId||e.activationId!==t.activationId||!p(e.materialActivation,t.materialActivation)||e.sealedMaterialB64u!==t.sealedMaterialB64u||e.sealedMaterialDigestB64u!==t.sealedMaterialDigestB64u||e.packageSetDigestB64u!==t.packageSetDigestB64u||!dc(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 K(e)}}function pc(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 K(e)}}function mc(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;default:return K(e)}}function hc(e,t){return e.kind!==t.kind||e.envelopeId!==t.envelopeId||e.walletId!==t.walletId||!Ee(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||!pc(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&&mc(e.factor,t.factor)}function gc(e,t){return uc(He(e),He(t))}function _c(e,t){return de({kind:`delegated_wallet_authority_v1`,permissions:e.permissions},{kind:`delegated_wallet_authority_v1`,permissions:t.permissions})}function vc(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 K(e)}}function yc(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 K(e)}function bc(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&&vc(e.provenance,t.provenance)&&_c(e,t)&&yc(e,t)&&e.revocationEpoch===t.revocationEpoch&&e.createdAtMs===t.createdAtMs&&e.updatedAtMs===t.updatedAtMs&&e.signerActivationSetDigestB64u===t.signerActivationSetDigestB64u&&e.authorityDigestB64u===t.authorityDigestB64u&&gc(e.signerActivations,t.signerActivations)}function xc(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&&vc(e.provenance,t.provenance)&&_c(e,t)&&gc(e.signerActivations,t.signerActivations)&&e.signerActivationSetDigestB64u===t.signerActivationSetDigestB64u&&e.revocationEpoch===t.revocationEpoch&&e.createdAtMs===t.createdAtMs}function Sc(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)}return K(e)}function Cc(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}return K(e)}function wc(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||!p(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 K(e)}case`wallet_authority_linked_signer_material_v1`:return t.kind===`wallet_authority_linked_signer_material_v1`&&fc(e,t);default:return K(e)}}function Tc(e,t){return e.kind===t.kind&&e.authorityId===t.authorityId&&e.walletAuthMethodId===t.walletAuthMethodId&&e.walletKeyId===t.walletKeyId&&hc(e.envelope,t.envelope)}function Ec(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&&gc(e.installedActivationRefs,t.installedActivationRefs)&&e.installedRecordSetDigestB64u===t.installedRecordSetDigestB64u&&e.targetFactorVerificationDigestB64u===t.targetFactorVerificationDigestB64u&&e.installedAtMs===t.installedAtMs}function Dc(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||!p(r.materialActivation,i.materialActivation))return!1}return!0}function Oc(e){return e instanceof Error?e.message:`local authority installation input is invalid`}function kc(e){let t=Es(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 Ac(e){try{let n=X(A(e.authority),`authority`);if(n.state!==`pending_local_install`)throw Error(`authority must be pending_local_install`);let r=j(e.authMethod);if(!r||r.status!==`pending_local_install`)throw Error(`authMethod must be a pending_local_install V2 record`);let i=t(e.profile.profileId||``);if(!i||i!==String(n.walletId))throw Error(`profile identity does not match authority`);let a=e.profile.defaultSignerSlot===void 0?1:Rs(e.profile.defaultSignerSlot,`profile.defaultSignerSlot`);if(a<1)throw Error(`profile.defaultSignerSlot must be a positive safe integer`);let o={profileId:i,defaultSignerSlot:a,...e.profile.passkeyCredential?{passkeyCredential:e.profile.passkeyCredential}:{},...e.profile.preferences?{preferences:e.profile.preferences}:{},...e.profile.nearProvisioning?{nearProvisioning:e.profile.nearProvisioning}:{}},s=e.authenticator===null?null:Ss(e.authenticator),c=null;if(r.kind===`passkey`){if(e.localAuthMethod!==null)throw Error(`Passkey installation cannot include a local Email OTP auth method`);let t=o.passkeyCredential;if(!t||t.id!==r.credentialIdB64u||t.rawId!==r.credentialIdB64u)throw Error(`profile passkey credential does not match authMethod`);if(!s||s.profileId!==i||s.signerSlot!==a||s.credentialId!==r.credentialIdB64u||C(s.credentialPublicKey)!==r.credentialPublicKeyB64u)throw Error(`profile authenticator does not match authMethod`)}else{if(s!==null||o.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`);c=kc({localAuthMethod:e.localAuthMethod,authority:n,authMethod:r})}if(!Array.isArray(e.signerMaterials))throw Error(`signerMaterials must be an array`);let l=[];for(let t of e.signerMaterials)l.push(Zs(t));let u=e.exportRoot===null?null:ec(e.exportRoot),d=Te(e.receipt),f=Rs(e.expectedLockGeneration,`expectedLockGeneration`);if(r.walletId!==n.walletId||r.walletAuthorityId!==n.authorityId||d.walletId!==n.walletId||d.authorityId!==n.authorityId||d.authMethodId!==r.walletAuthMethodId||d.deviceId!==n.principal.deviceId||d.packageSetDigestB64u!==n.localInstallPackageSetDigestB64u)throw Error(`authority, authMethod, and receipt identities do not match`);if(!gc(d.installedActivationRefs,n.signerActivations))throw Error(`receipt signer activations do not match authority`);let m=sc(n.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 t=l[e],i=m[e];if(t.authorityId!==n.authorityId||t.walletAuthMethodId!==r.walletAuthMethodId||t.keyFamily!==i.keyFamily||!p(t.materialActivation,i.materialActivation))throw Error(`signer material record does not match authority activation`)}if((lc(n.signerActivations)&&n.permissions.includes(`export_keys`))!==(u!==null))throw Error(`Ed25519 export root presence does not match authority permissions`);if(u){let e=cc(n.signerActivations);if(e===null||u.authorityId!==n.authorityId||u.walletAuthMethodId!==r.walletAuthMethodId||u.walletKeyId!==e||u.envelope.walletId!==n.walletId||u.envelope.binding.kind!==`ed25519_yao_client_root_v1`||u.envelope.binding.walletKeyId!==e||u.envelope.binding.registeredPublicKeyB64u!==n.signerActivations.ed25519?.signer.registeredPublicKeyB64u||n.principal.kind!==`owner_device`||String(u.envelope.binding.deviceId)!==String(n.principal.deviceId)||u.envelope.lifecycle.state!==`active`||!Eo(r,u.envelope))throw Error(`export root does not match the Ed25519 authority activation`)}return{ok:!0,value:{authority:n,authMethod:r,profile:o,authenticator:s,localAuthMethod:c,signerMaterials:l,exportRoot:u,receipt:d,expectedLockGeneration:f}}}catch(e){return{ok:!1,error:Oc(e)}}}function jc(e){return[`passkey`,e.rp_id,e.credential_id_b64u].join(`\0`)}function Mc(e){let t=e.authenticators.map(e=>Ss(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=Ts({binding:e.initialAuthMethod,authenticator:i});n.set(a.wallet_auth_method_id,a),r.set(jc(a),a)}else{let t=Es(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=Ts({binding:e.initialAuthMethod,authenticator:i});n.set(t.wallet_auth_method_id,t),r.set(jc(t),t);continue}let t=Os(i),a=jc(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 Nc(e){let n=e.nextRow;if(n.kind!==Se.thresholdEcdsa||n.status===`revoked`||!n.key_handle||!n.ecdsa_threshold_key_id)return;let r=await e.store.index(E.walletId).getAll(n.wallet_id),i=new Set;for(let e of r){if(typeof e!=`object`||!e||Array.isArray(e)||!G(e))continue;let r=t(Reflect.get(e,`wallet_signer_id`)||``);!r||r===n.wallet_signer_id||Reflect.get(e,`kind`)!==n.kind||Reflect.get(e,`chain_target_key`)!==n.chain_target_key||(Reflect.get(e,`key_handle`)===n.key_handle||Reflect.get(e,`ecdsa_threshold_key_id`)===n.ecdsa_threshold_key_id)&&i.add(r)}for(let t of i)await e.store.delete(t)}function Pc(e){return[e.walletSignerId,e.keyKind].join(`\0`)}function Fc(e){return vo({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId})}function Ic(e){let n=t(e.profileId||``),r=t(e.signerId||``),i=t(e.wrapKeySalt||``),a=t(e.chainIdKey||``).toLowerCase(),o=k(e.accountAddress),s=t(e.keyKind||``),c=t(e.algorithm||``),l=t(e.publicKey||``);if(!n)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(!a)throw Error(`[SeamsWalletDB] Missing chainIdKey for key material record`);if(!o)throw Error(`[SeamsWalletDB] Missing accountAddress for key material record`);if(!r)throw Error(`[SeamsWalletDB] Missing signerId for key material record`);if(!s)throw Error(`[SeamsWalletDB] Missing keyKind for key material record`);if(!c)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=Fe({profileId:n,signerSlot:e.signerSlot,chainIdKey:a,accountAddress:o,keyKind:s,schemaVersion:e.schemaVersion,signerId:r}),d=Ne(e.payloadEnvelope,u,`${n}/${e.signerSlot}/${a}/${s}`),f=Pe(e.payload),p={profileId:n,signerSlot:e.signerSlot,chainIdKey:a,accountAddress:o,keyKind:s,algorithm:c,publicKey:l,signerId:r,...i?{wrapKeySalt:i}:{},...f?{payload:f}:{},...d?{payloadEnvelope:d}:{},timestamp:e.timestamp,schemaVersion:e.schemaVersion},m=Fc(p),h=Ae({chainIdKey:a,accountAddress:o});return{key_material_id:Pc({walletSignerId:m,keyKind:s}),wallet_id:n,wallet_signer_id:m,chain_target_key:h,key_handle:r,public_key:l,updated_at:e.timestamp,record:p}}function Lc(e){return[t(e.profileId||``),O(e.chainIdKey),k(e.accountAddress),t(e.signerId||``),String(Number(e.signerSlot))].join(`\0`)}function Rc(e){let t=new Set(e.signers.map(e=>Lc({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=>Lc({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(Lc({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(Lc({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 zc(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=D(Reflect.get(e,`profileId`)),n=Reflect.get(e,`signerSlot`),r=O(Reflect.get(e,`chainIdKey`)),i=k(Reflect.get(e,`accountAddress`)),a=D(Reflect.get(e,`keyKind`)),o=D(Reflect.get(e,`algorithm`)),s=D(Reflect.get(e,`publicKey`)),c=D(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=Pe(f);if(f!==void 0&&(typeof f!=`object`||!f||Array.isArray(f)))return null;let m=Fe({profileId:t,signerSlot:Number(n),chainIdKey:r,accountAddress:i,keyKind:a,schemaVersion:Number(u),signerId:c}),h;try{h=Ne(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 Bc(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let n=zc(Reflect.get(e,`record`));return!n||Reflect.get(e,`key_material_id`)!==Pc({walletSignerId:Fc(n),keyKind:n.keyKind})||Reflect.get(e,`wallet_id`)!==n.profileId||Reflect.get(e,`wallet_signer_id`)!==Fc(n)||Reflect.get(e,`chain_target_key`)!==Ae({chainIdKey:n.chainIdKey,accountAddress:n.accountAddress})||Reflect.get(e,`key_handle`)!==t(n.signerId||``)||Reflect.get(e,`public_key`)!==n.publicKey||Reflect.get(e,`updated_at`)!==n.timestamp?null:n}function Vc(e){return Lc({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot})}function Hc(e){return Lc({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,signerSlot:e.signerSlot})}function Uc(e){let n=new Set;for(let r of e.signers){let e=t(r.profileId||``);e&&n.add(e)}for(let r of e.keyMaterials){let e=t(r.profileId||``);e&&n.add(e)}return[...n]}async function Wc(e,t){let n=e.store(T.walletSigners),r=[];for(let e of t){let t=await n.index(E.walletId).getAll(e);for(let e of t){let t=G(e);t?.status===`active`&&r.push(t)}}return r}async function Gc(e,t){let n=e.store(T.keyMaterial),r=[];for(let e of t){let t=await n.index(E.walletId).getAll(e);for(let e of t){let t=Bc(e);t?.keyKind===`threshold_share_v1`&&r.push(t)}}return r}function Kc(e){let t=new Map;for(let n of e.existing)t.set(Pc({walletSignerId:Fc(n),keyKind:n.keyKind}),n);for(let n of e.incoming)t.set(Pc({walletSignerId:Fc(n),keyKind:n.keyKind}),n);return[...t.values()]}async function qc(e){let t=Uc({signers:e.signers,keyMaterials:e.keyMaterials});if(t.length===0)return;let n=await Wc(e.ctx,t),r=new Set(n.map(Vc));Rc({signers:n,keyMaterials:Kc({existing:(await Gc(e.ctx,t)).filter(e=>r.has(Hc(e))),incoming:e.keyMaterials})})}function Jc(e){if(e.keyKind!==`threshold_share_v1`||e.algorithm!==`ed25519`)return!0;let n=e.payload||{};return!!t(n.relayerKeyId||``)&&!!t(n.keyVersion||``)}function Yc(e){let t=new Set(e.activeSigners.map(Vc));return e.matches.filter(e=>t.has(Hc(e))).find(Jc)||e.matches.find(Jc)||[...e.matches].sort((e,t)=>t.timestamp-e.timestamp)[0]||null}var Xc=class{constructor(e){this.manager=e}async installLocalAuthority(e){let t=Ac(e);return t.ok?await Xe(t.value.authority)?this.manager.runTransaction([T.appState,T.wallets,T.walletAuthMethods,T.walletAuthorities,T.walletAuthoritySignerMaterials,T.walletAuthorityExportRoots,T.walletAuthorityInstallationReceipts,T.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=A(e.authority);if(!t.ok||t.value.state!==`active`)throw Error(`active WalletAuthorityV1 is invalid`);let n=j(e.authMethod);if(!n||n.status!==`active`)throw Error(`active WalletAuthMethodRecordV2 is invalid`);let r=kn(Dn(e.walletSession,e.operationCredential))?.record??null;if(!r)throw Error(`active Wallet Session is invalid`);let i=Rs(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([T.appState,T.wallets,T.walletAuthorities,T.walletAuthMethods,T.walletAuthorityInstallationReceipts,T.walletSelections,T.walletSessionAuthorizations],`readwrite`,this.finalizeLocalAuthorityActivationInTransaction.bind(this,{authority:t.value,authMethod:n,walletSession:r,operationCredential:e.operationCredential,expectedLockGeneration:i}))}async publishLocalAuthorityActivation(e){let t=A(e.authority);if(!t.ok||t.value.state!==`active`)throw Error(`active WalletAuthorityV1 is invalid`);let n=j(e.authMethod);if(!n||n.status!==`active`)throw Error(`active WalletAuthMethodRecordV2 is invalid`);let r=Rs(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 Xe(t.value))throw Error(`active WalletAuthorityV1 digest is invalid`);return await this.manager.runTransaction([T.appState,T.wallets,T.walletAuthorities,T.walletAuthMethods,T.walletAuthorityInstallationReceipts,T.walletSelections],`readwrite`,this.publishLocalAuthorityActivationInTransaction.bind(this,{authority:t.value,authMethod:n,expectedLockGeneration:r}))}async advanceWalletLockGeneration(e){let t=X(a(e.walletId),`walletId`),n=Rs(e.lockedAtMs,`lockedAtMs`);return this.manager.runTransaction([T.walletSelections],`readwrite`,this.advanceWalletLockGenerationInTransaction.bind(this,{walletId:t,lockedAtMs:n}))}async markWalletSelectionUnlocked(e){let t=X(a(e.walletId),`walletId`),n=X(s(e.walletAuthMethodId),`walletAuthMethodId`),r=Rs(e.unlockedAtMs,`unlockedAtMs`);await this.manager.runTransaction([T.walletSelections,T.walletAuthMethods],`readwrite`,this.markWalletSelectionUnlockedInTransaction.bind(this,{walletId:t,walletAuthMethodId:n,unlockedAtMs:r}))}async persistRecoveredWalletAuthority(e){let t=X(A(e.authority),`authority`),n=j(e.authMethod),r=Rs(e.recoveredAtMs,`recoveredAtMs`);if(t.state!==`active`||!Ue(t)||!n||n.status!==`active`||n.walletId!==t.walletId||n.walletAuthorityId!==t.authorityId)throw Error(`recovered Wallet Authority projection is invalid`);if(!await Xe(t))throw Error(`recovered Wallet Authority digest is invalid`);await this.manager.runTransaction([T.walletAuthorities,T.walletSelections,T.walletAuthMethods],`readwrite`,this.persistRecoveredWalletAuthorityInTransaction.bind(this,{authority:t,authMethod:n,recoveredAtMs:r}))}async getLocalAuthorityInstallationReceipt(e){let t=n(e);return t.ok&&rc(await(await this.manager.getDB()).get(T.walletAuthorityInstallationReceipts,t.value))?.record||null}async finalizeLocalAuthorityActivationInTransaction(e,t){let n=t.store(T.appState),r=t.store(T.walletAuthorities),i=t.store(T.walletAuthMethods),a=t.store(T.walletAuthorityInstallationReceipts),o=t.store(T.walletSelections),s=t.store(T.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(Oo(e.authority.authorityId)),p=f===void 0?null:hs(f.value);if(f!==void 0&&!p)throw Error(`local authority profile projection is missing or corrupt`);let m=c===void 0?null:Bs(c),h=l===void 0?null:Z(l),g=u===void 0?null:rc(u),_=d===void 0?null:kn(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||!gc(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(!bc(m.record,e.authority)||h.record.status!==`active`||!Sc(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(Dn(e.walletSession,e.operationCredential)),await o.put(oc({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`||!Dc(v,e.walletSession)||_?.operationCredential.token!==e.operationCredential.token)throw Error(`active local authority replay conflicts with supplied Wallet Session`);return await s.put(Dn(e.walletSession,e.operationCredential)),{kind:`finalized`}}if(m.record.state!==`pending_local_install`||h.record.status!==`pending_local_install`||!xc(m.record,e.authority)||!Cc(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`&&(!Dc(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(Vs(e.authority)),await i.put(await Xs(i,e.authMethod)),await s.put(Dn(e.walletSession,e.operationCredential)),await o.put(oc({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(T.wallets),a=r.store(T.walletAuthMethods),o=await i.get(n.profile.wallet_id),s=o===void 0?null:gs(o);if(o!==void 0&&!s)throw Error(`stored wallet profile is corrupt during authority publication`);if(s&&!es(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=Y(t);if(!n||!is(n,e))throw Error(`stored local auth method changed during authority publication`)}await a.put(e)}await a.put(await Xs(a,t)),await r.store(T.appState).delete(Oo(e.authorityId))}async publishLocalAuthorityActivationInTransaction(e,t){let n=await t.store(T.appState).get(Oo(e.authority.authorityId)),r=n===void 0?null:hs(n.value);if(n!==void 0&&!r)throw Error(`local authority profile projection is missing or corrupt`);let i=await t.store(T.walletAuthorities).get(e.authority.authorityId),a=await t.store(T.walletAuthMethods).get(e.authMethod.walletAuthMethodId),o=await t.store(T.walletAuthorityInstallationReceipts).get(e.authority.authorityId),s=i===void 0?null:Bs(i),c=a===void 0?null:Z(a),l=o===void 0?null:rc(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||!gc(l.record.installedActivationRefs,e.authority.signerActivations))throw Error(`local authority installation receipt does not match publication`);if(s.record.state===`active`){if(!bc(s.record,e.authority)||c.record.status!==`active`||!Sc(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`||!xc(s.record,e.authority)||!Cc(c.record,e.authMethod))throw Error(`local authority records are not the expected pending installation`);let u=await t.store(T.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(T.walletAuthorities).put(Vs(e.authority)),{kind:`published`}}async advanceWalletLockGenerationInTransaction(e,t){let n=t.store(T.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(oc({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(T.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(T.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`);i.record.walletAuthMethodId!==e.walletAuthMethodId&&await this.assertSelectionMoveBetweenAuthorityMembers({walletId:e.walletId,fromWalletAuthMethodId:i.record.walletAuthMethodId,toWalletAuthMethodId:e.walletAuthMethodId},t),await n.put(oc({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(T.walletAuthorities),r=await n.get(e.authority.authorityId),i=r===void 0?null:Bs(r)?.record;if(r!==void 0&&!i)throw Error(`local Wallet Authority is corrupt`);if(i&&!bc(i,e.authority))throw Error(`recovered Wallet Authority conflicts with local authority`);await n.put(Vs(e.authority));let a=t.store(T.walletAuthMethods);await a.put(await Xs(a,e.authMethod));let o=t.store(T.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(oc({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(T.appState),r=await t.store(T.wallets).get(e.profile.profileId),i=r===void 0?null:J(r);if(r!==void 0&&!i)return{kind:`integrity_error`,reason:`wallet profile row is invalid`};let a=t.store(T.walletAuthMethods),o=e.authenticator?Os(e.authenticator):null,s=e.localAuthMethod?Ds(e.localAuthMethod,e.profile.defaultSignerSlot??1):null,c=o?await a.get(o.wallet_auth_method_id):void 0,l=c===void 0?null:Y(c),u=e.authenticator?Os(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:Y(d),p=t.store(T.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(T.walletAuthorities),_=t.store(T.walletAuthMethods),v=t.store(T.walletAuthoritySignerMaterials),y=t.store(T.walletAuthorityExportRoots),b=t.store(T.walletAuthorityInstallationReceipts),ee=Oo(e.authority.authorityId),te=await n.get(ee),x=te===void 0?null:hs(te.value);if(te!==void 0&&!x)return{kind:`integrity_error`,reason:`local authority profile projection is missing or corrupt`};let ne=x??ks({authorityId:e.authority.authorityId,walletId:e.authority.walletId,authMethodId:e.authMethod.walletAuthMethodId,profile:Jo(e.profile,i||void 0),authenticator:u,localAuthMethod:s?.kind===`email_otp`?s:null}),re=await g.get(e.authority.authorityId),S=await _.get(e.authMethod.walletAuthMethodId),ie=[];for(let t of e.signerMaterials)ie.push(await v.get([t.authorityId,t.walletAuthMethodId,t.activationId]));let ae=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:Bs(re),ce=S===void 0?null:Z(S),le=[];for(let e=0;e<ie.length;e+=1){let t=ie[e];le.push(t===void 0?null:Qs(t)?.record||null)}let ue=ae===void 0?null:tc(ae)?.record||null,de=oe===void 0?null:rc(oe)?.record||null;if(x&&!js(x,e))return{kind:`integrity_error`,reason:`local authority profile projection conflicts with replay`};let C=re!==void 0||S!==void 0||ie.some(zs)||ae!==void 0||oe!==void 0||te!==void 0,w=re!==void 0&&S!==void 0&&ie.every(zs)&&(e.exportRoot===null?ae===void 0:ae!==void 0)&&oe!==void 0;if(C){if(!h||!w||!se||!ce||!de||!x||!As(x,ne))return{kind:`integrity_error`,reason:`local authority replay is incomplete or malformed`};if(!bc(se.record,e.authority)||!Sc(ce.record,e.authMethod)||!Ec(de,e.receipt))return{kind:`integrity_error`,reason:`local authority replay conflicts with stored records`};if(i&&!$o(i,x.profile.record)||x.authenticator&&l!==null&&!is(l,x.authenticator)||x.localAuthMethod&&f!==null&&!is(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=le[t];if(!n||!wc(n,e.signerMaterials[t]))return{kind:`integrity_error`,reason:`stored signer material conflicts with replay`}}return e.exportRoot&&(!ue||!Tc(ue,e.exportRoot))?{kind:`integrity_error`,reason:`stored export root conflicts with replay`}:(await p.put(oc(ko(e,h))),{kind:`idempotent_replay`,receipt:de})}await n.put({key:ee,value:ne}),await g.put(Vs(e.authority)),await _.put(await Xs(_,e.authMethod));for(let t of e.signerMaterials)await v.put($s(t));return e.exportRoot&&await y.put(nc(e.exportRoot)),await b.put(ic(e.receipt)),await p.put(oc(ko(e,h))),{kind:`installed`,receipt:e.receipt}}async getWalletAuthority(e){let t=n(e);if(!t.ok)return null;let r=Bs(await(await this.manager.getDB()).get(T.walletAuthorities,t.value));return!r||!await Xe(r.record)?null:r.record}async persistFoundingWalletAuthority(e){let t=jo(e);await this.manager.runTransaction([T.appState,T.walletAuthorities,T.walletAuthMethods,T.wallets,T.walletSelections],`readwrite`,this.persistFoundingWalletAuthorityInTransaction.bind(this,t,`activate`))}async persistFoundingWalletAuthorityInTransaction(e,t,n){if(t===`preserve`){let t=Q(await n.store(T.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(T.walletAuthorities).put(Vs(e.authority));let r=n.store(T.walletAuthMethods);if(await r.put(await Xs(r,e.authMethod)),t!==`preserve`){if(t===`restore_locked`){let t=n.store(T.walletSelections);await t.get(e.authority.walletId)||await t.put(oc({kind:`wallet_selection_v1`,walletId:e.authority.walletId,walletAuthMethodId:e.authMethod.walletAuthMethodId,lockGeneration:0,lockState:`locked`,updatedAtMs:e.authMethod.activatedAtMs}));return}await n.store(T.walletSelections).put(oc({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=s(e);return t.ok&&Z(await(await this.manager.getDB()).get(T.walletAuthMethods,t.value))?.record||null}async listWalletSelections(){return(await(await this.manager.getDB()).transaction(T.walletSelections,`readonly`).store.getAll()).flatMap(e=>{let t=Q(e);return t?[t.record]:[]})}async listWalletSelectionWalletIds(){return(await(await this.manager.getDB()).transaction(T.walletSelections,`readonly`).store.getAllKeys()).flatMap(e=>{let t=a(e);return t.ok?[t.value]:[]})}async listWalletAuthMethodsV2ForWallet(e){let n=t(e||``);return n?(await(await this.manager.getDB()).transaction(T.walletAuthMethods,`readonly`).store.index(E.walletId).getAll(n)).flatMap(e=>{let t=Z(e);return t?[t.record]:[]}):[]}async listLocalWalletAuthMethodProjectionsV2ForWallet(e){let n=t(e||``);return n?await this.manager.runTransaction([T.walletAuthMethods],`readwrite`,async e=>{let t=e.store(T.walletAuthMethods),r=await t.index(E.walletId).getAll(n),i=[];for(let e of r){let n=Z(e);if(!n)continue;let a=Ks(n.record,r,n.presentation);(!Js(e)||!qs(n.presentation,a))&&await t.put(Ws(Ys(n.record,a))),i.push(Ys(n.record,a))}return i}):[]}async retainVerifiedEmailOtpLocalPresentation(e){let t=await v(String(e.emailAddress));return await this.manager.runTransaction([T.walletAuthMethods],`readwrite`,async n=>{let r=n.store(T.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(Ws({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 n=s(t);return n.ok?await this.resolveWalletAuthorityForSelection(e,n.value):{kind:`integrity_error`,reason:`walletAuthMethodId is invalid`}}async resolveWalletAuthorityForSelection(e,t){let n=a(e);return n.ok?this.manager.runTransaction([T.walletSelections,T.walletAuthMethods,T.walletAuthorities,T.walletAuthoritySignerMaterials,T.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(T.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(T.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(T.walletAuthorities).get(s.wallet_authority_id);if(c===void 0)return{kind:`missing_authority`,walletAuthorityId:s.record.walletAuthorityId};let l=Bs(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 Xe(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(T.walletAuthoritySignerMaterials),d=[],f;try{f=sc(l.record.signerActivations)}catch{return{kind:`integrity_error`,reason:`selected authority signer activations are invalid`}}for(let e of f){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=Qs(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||!p(n.record.materialActivation,e.materialActivation))return{kind:`integrity_error`,reason:`selected signer material row is invalid`};d.push(n.record)}let m=await t.store(T.walletAuthorityExportRoots).index(E.walletAuthorityAuthMethodId).getAll([l.record.authorityId,s.record.walletAuthMethodId]),h=lc(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=tc(m[0]),n=cc(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`||!Eo(s.record,t.record.envelope))return{kind:`integrity_error`,reason:`selected authority export root is invalid`};g=t.record}return await Xe(l.record)?{kind:`resolved`,selection:i.record,authMethod:s.record,authority:l.record,signerMaterials:d,exportRoot:g}:{kind:`integrity_error`,reason:`selected wallet authority digest is invalid`}}async getAppState(e){let n=t(e||``);if(n)return(await(await this.manager.getDB()).get(T.appState,n))?.value}async listAppStateEntriesByPrefix(e){let n=t(e||``);return n?(await(await this.manager.getDB()).getAll(T.appState)).flatMap(e=>{let t=Do(e);return t&&t.key.startsWith(n)?[t]:[]}):[]}async setAppState(e,n){let r=t(e||``);r&&await this.manager.runTransaction([T.appState],`readwrite`,async e=>{await e.store(T.appState).put({key:r,value:n})})}async putPendingWalletRegistrationCommits(e){let t=e.map(br);await this.manager.runTransaction([T.appState],`readwrite`,async e=>{let n=e.store(T.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=br(t),i=br(n);await this.manager.runTransaction([T.appState],`readwrite`,async e=>{let n=e.store(T.appState),a=xr(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=br(e);await this.manager.runTransaction([T.appState],`readwrite`,async e=>{await e.store(T.appState).put(t)})}async migratePendingMixedRegistrationRows(){let e=await(await this.manager.getDB()).getAll(T.appState),t=await Promise.all(e.map(Sr));await this.manager.runTransaction([T.appState],`readwrite`,async e=>{let n=e.store(T.appState);for(let e of t){if(!e)continue;let t=br(e.activation);if(JSON.stringify(await n.get(t.key))!==JSON.stringify(e.original))continue;let r=br(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 n=t(e.registrationCeremonyId||``);return n&&xr(await(await this.manager.getDB()).get(T.appState,yr({registrationCeremonyId:n,operation:e.operation})))?.record||null}async listPendingWalletRegistrationCommits(){return await this.migratePendingMixedRegistrationRows(),(await(await this.manager.getDB()).getAll(T.appState)).flatMap(e=>{let t=xr(e);return t?[t.record]:[]})}async deletePendingWalletRegistrationCommit(e){let n=t(e.registrationCeremonyId||``);n&&await this.manager.runTransaction([T.appState],`readwrite`,async t=>{await t.store(T.appState).delete(yr({registrationCeremonyId:n,operation:e.operation}))})}async adoptAddedEcdsaSignerAuthority(e){let t=A(e.authority);if(!t.ok||t.value.state!==`active`||!await Xe(t.value))throw Error(`Added ECDSA signer authority is invalid`);let n=t.value,r=n.signerActivations.ecdsa;if(!r||!p(r.materialActivation,e.materialActivation))throw Error(`Added ECDSA signer authority does not carry the activated signer`);await this.manager.runTransaction([T.walletAuthorities],`readwrite`,async e=>{let t=e.store(T.walletAuthorities),r=Bs(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(!Ye(r.record,n))throw Error(`Added ECDSA signer authority is not an extension of the local authority`);await t.put(Vs(n))}})}async replaceExactActiveWalletSessionFromStatus(e){return await this.manager.runTransaction([T.appState,T.walletAuthorities,T.walletSessionAuthorizations,T.ecdsaClientPresignatures,T.walletSelections],`readwrite`,this.replaceExactActiveWalletSessionFromStatusInTransaction.bind(this,e))}async replaceExactActiveWalletSessionFromStatusInTransaction(e,t){let n=Bs(await t.store(T.walletAuthorities).get(e.active.authorityId)),r=Q(await t.store(T.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 On({ctx:t,active:e.active,operationCredential:e.operationCredential}),{kind:`replaced`})}async reconcilePendingNearRegistrationAuthority(e){let t=await this.getWalletAuthority(e.walletSession.authorityId);if(!t||t.state!==`active`||!We(t))return;let n=await this.listPendingWalletRegistrationCommits();for(let r of n){if(r.operation!==`near_provisioning`||r.phase!==`joined`||r.signerPlanKind!==`near_ed25519_and_evm_family_ecdsa`||r.walletId!==e.walletSession.walletId||r.walletAuthMethodId!==e.walletSession.authMethodId)continue;let n=r.localMaterial.ed25519.metadata,i=await Ke({authority:t,ed25519:{kind:`wallet_ed25519_signer_activation_v1`,signer:{kind:`exact_administered_ed25519_signer_v1`,keyFamily:`ed25519`,walletId:r.walletId,walletKeyId:X(u(`wallet-key:ed25519:${r.walletId}:${n.nearEd25519SigningKeyId}`),`NEAR wallet key`),registeredPublicKeyB64u:ne(n.registeredPublicKeyB64u)},materialActivation:n.materialActivation},now:Date.now()});if(!(i.authorityDigestB64u!==e.walletSession.authorityDigestB64u||i.revocationEpoch!==e.walletSession.authorityRevocationEpoch)){await this.manager.runTransaction([T.appState,T.walletAuthorities,T.walletSessionAuthorizations,T.ecdsaClientPresignatures,T.walletSelections],`readwrite`,this.reconcilePendingNearRegistrationAuthorityInTransaction.bind(this,{pending:r,authority:i,previousDigest:t.authorityDigestB64u,walletSession:e.walletSession,operationCredential:e.operationCredential}));return}}}async reconcilePendingNearRegistrationAuthorityInTransaction(e,t){let n=await An({ctx:t,walletId:e.pending.walletId,authorityId:e.authority.authorityId,authMethodId:e.pending.walletAuthMethodId}),r=Q(await t.store(T.walletSelections).get(e.pending.walletId)),i=Bs(await t.store(T.walletAuthorities).get(e.authority.authorityId)),a=xr(await t.store(T.appState).get(yr(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`);Po({incoming:e.walletSession,existing:n.record}),await t.store(T.walletAuthorities).put(Vs(e.authority)),await On({ctx:t,active:e.walletSession,operationCredential:n.operationCredential})}async completePendingNearRegistration(e){await this.manager.runTransaction([T.appState,T.wallets,T.walletSessionAuthorizations,T.ecdsaClientPresignatures,T.walletSelections],`readwrite`,this.completePendingNearRegistrationInTransaction.bind(this,e))}async completePendingNearRegistrationInTransaction(e,t){let n=await An({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`);Po({incoming:e.walletSession,existing:n.record});let r=Q(await t.store(T.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=yr(e.pending),a=xr(await t.store(T.appState).get(i));if(!a||JSON.stringify(a.record)!==JSON.stringify(e.pending))throw Error(`NEAR readiness journal changed concurrently`);let o=J(await t.store(T.wallets).get(e.pending.walletId));if(!o)throw Error(`NEAR readiness requires its committed wallet`);await t.store(T.wallets).put(Jo({profileId:o.profileId,nearProvisioning:{status:`near_ready`,nearAccountId:e.nearAccountId,updatedAtMs:Date.now()}},o)),await t.store(T.appState).delete(i)}async putPendingWalletRecoveryCommit(e){let t=await Ji(e);await this.manager.runTransaction([T.appState],`readwrite`,async e=>{await e.store(T.appState).put(t)})}async advancePendingWalletRecoveryCommit(e){let t=await qi(e.awaiting),n=await qi(e.promoted);if(t.stage!==`awaiting_server_promotion`||n.stage!==`server_promoted`||!Fi(t,n))throw Error(`pending wallet recovery promotion changed its immutable identity`);let r=await Ji(t),i=await Ji(n);return this.manager.runTransaction([T.appState],`readwrite`,async e=>{let t=e.store(T.appState),a=await t.get(r.key);if(ua(a,r))return await t.put(i),n;if(ua(a,i))return n;throw Error(`stored pending wallet recovery commit does not match the expected stage`)})}async getPendingWalletRecoveryCommit(t){let n=X(e(t),`recoveryOperationId`);return(await Yi(await(await this.manager.getDB()).get(T.appState,Ii(n))))?.record??null}async listPendingWalletRecoveryCommits(){let e=await this.manager.getDB();return(await Promise.all((await e.getAll(T.appState)).map(Yi))).flatMap(e=>e?[e.record]:[])}async deletePendingWalletRecoveryCommit(t){let n=X(e(t),`recoveryOperationId`);await this.manager.runTransaction([T.appState],`readwrite`,async e=>{await e.store(T.appState).delete(Ii(n))})}async getProfile(e){let n=t(e||``);return n?J(await(await this.manager.getDB()).get(T.wallets,n)):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(T.wallets,void 0,n):await t.getAll(T.wallets)).flatMap(e=>{let t=J(e);return t?[t]:[]})}async upsertProfile(e){let n=t(e.profileId||``);if(!n)throw Error(`[SeamsWalletDB] profileId is required`);let r=null;if(await this.manager.runTransaction([T.wallets],`readwrite`,async t=>{let i=t.store(T.wallets),a=Jo(e,J(await i.get(n))||void 0);r=a.record,await i.put(a)}),!r)throw Error(`[SeamsWalletDB] profile write did not complete`);return r}async upsertWalletAuthMethod(e){let t=ys(e),n=null;if(await this.manager.runTransaction([T.wallets,T.walletAuthMethods],`readwrite`,async r=>{let i=J(await r.store(T.wallets).get(t.wallet_id));if(!i)throw q(`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(T.walletAuthMethods),o=Y(await a.get(t.wallet_auth_method_id)),s=e.kind===`passkey`&&o?.kind===`passkey`?Ts({binding:e,authenticator:o.authenticator}):Ds(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=j(e);if(!t)throw Error(`[SeamsWalletDB] auth-method V2 record is invalid`);await this.manager.runTransaction([T.wallets,T.walletAuthMethods],`readwrite`,async e=>{if(!J(await e.store(T.wallets).get(t.walletId)))throw q(`MISSING_PROFILE`,`Cannot upsert auth-method V2 binding for unknown wallet: ${String(t.walletId)}`,{profileId:String(t.walletId)});let n=e.store(T.walletAuthMethods);await n.put(await Xs(n,t))})}async getWalletAuthMethod(e){let n=e.kind,r=t(e.rpId||``),i=t(e.authIdentifierKey||``);if(!r||!i)return null;let a=(await(await this.manager.getDB()).transaction(T.walletAuthMethods,`readonly`).store.index(E.kindRpIdAuthIdentifier).getAll([n,r,i])).flatMap(e=>{let t=Ps(e);return t?[t]:[]});return a.length===1?a[0]:null}async listWalletAuthMethodsForWallet(e){let n=t(e||``);return n?(await(await this.manager.getDB()).transaction(T.walletAuthMethods,`readonly`).store.index(E.walletId).getAll(n)).flatMap(e=>{let t=Ps(e);return t?[t]:[]}):[]}async upsertChainAccount(e){let n=t(e.profileId||``),r=O(e.chainIdKey),i=k(e.accountAddress);if(!n||!r||!i)throw Error(`[SeamsWalletDB] profileId, chainIdKey, and accountAddress are required`);let a=null;if(await this.manager.runTransaction([T.wallets,T.nearAccountProjections],`readwrite`,async t=>{if(!J(await t.store(T.wallets).get(n)))throw Error(`[SeamsWalletDB] Cannot upsert chain account for unknown profile: ${n}`);let o=t.store(T.nearAccountProjections),s=_o({chainIdKey:r,accountAddress:i}),c=xo(e,Co(await o.get([n,s,0]))||void 0);if(a=c.record,c.record.isPrimary){let e=await o.index(E.profileId).getAll(n);for(let t of e||[]){let e=Co(t);!e||e.chainIdKey!==r||!e.isPrimary||e.accountAddress!==i&&await o.put(xo({profileId:e.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,accountModel:e.accountModel,isPrimary:!1},e))}}await o.put(c)}),!a)throw Error(`[SeamsWalletDB] chain-account write did not complete`);return a}async listChainAccountsByProfile(e){let n=t(e||``);if(!n)return[];let r=(await this.manager.getDB()).transaction(T.nearAccountProjections,`readonly`),i=await r.store.index(E.profileId).getAll(n);return await r.done,i.flatMap(e=>{let t=Co(e);return t?[t]:[]})}async listChainAccountsByProfileAndChain(e,t){let n=O(t);return n?(await this.listChainAccountsByProfile(e)).filter(e=>e.chainIdKey===n):[]}async getChainAccount(e){let n=t(e.profileId||``),r=O(e.chainIdKey),i=k(e.accountAddress);return!n||!r||!i?null:Co(await(await this.manager.getDB()).get(T.nearAccountProjections,[n,_o({chainIdKey:r,accountAddress:i}),0]))}async resolveProfileAccountContext(e){let t=O(e.chainIdKey),n=k(e.accountAddress);if(!t||!n)return null;let r=(await(await this.manager.getDB()).getAll(T.nearAccountProjections)).flatMap(e=>{let t=Co(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=O(e);return t?(await(await this.manager.getDB()).getAll(T.nearAccountProjections)).flatMap(e=>{let n=Co(e);return n&&n.chainIdKey===t?[n]:[]}):[]}buildAccountSignerRecord(e){let n=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,...n==null?{}:{removedAt:n},...e.revocationReason?{revocationReason:t(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:n}=e;if(n.status!==`revoked`&&(!n.signerKind||!n.signerAuthMethod||!n.signerSource))throw q(`MISSING_SIGNER_KIND`,`Active and pending account signers require signerKind, signerAuthMethod, and signerSource`,{chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId,status:n.status});if(n.status===`revoked`&&n.removedAt==null)throw q(`REVOKED_SIGNER_REQUIRES_REMOVED_AT`,`Revoked signer ${n.signerId} must include removedAt`,{chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId});if(n.status===`active`){let t=e.activeSigners.find(e=>e.signerId!==n.signerId&&e.signerSlot===n.signerSlot);if(t)throw q(`DUPLICATE_ACTIVE_SIGNER_SLOT`,`Active signer slot ${n.signerSlot} is already used for ${n.chainIdKey}/${n.accountAddress}`,{chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId,signerSlot:n.signerSlot,conflictingSignerId:t.signerId})}if(e.existingStatus&&e.existingStatus!==n.status&&!{pending:new Set([`pending`,`active`,`revoked`]),active:new Set([`active`,`revoked`]),revoked:new Set([`revoked`])}[e.existingStatus]?.has(n.status))throw q(`INVALID_SIGNER_STATUS_TRANSITION`,`Invalid signer status transition ${e.existingStatus} -> ${n.status}`,{chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId,previousStatus:e.existingStatus,nextStatus:n.status});if(n.status===`active`&&String(n.signerKind||``)===`threshold-ecdsa`){let e=n.metadata||{};if(!t(e.keyHandle))throw q(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer requires metadata.keyHandle`,{chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId});if(!t(e.ecdsaThresholdKeyId))throw q(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer requires metadata.ecdsaThresholdKeyId`,{chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId});let r=k(e.thresholdOwnerAddress);if(!r||r!==n.accountAddress)throw q(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer requires metadata.thresholdOwnerAddress matching accountAddress`,{chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId});let i=yo(e.chainTarget);if(!i)throw q(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer requires metadata.chainTarget`,{chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId});if(i!==n.chainIdKey)throw q(`INVALID_SIGNER_METADATA`,`Active threshold ECDSA signer metadata.chainTarget must match chainIdKey`,{chainIdKey:n.chainIdKey,chainTargetKey:i,accountAddress:n.accountAddress,signerId:n.signerId})}}async enqueueSignerOperationInTransaction(e,n){let r=t(n.opId||``),i=t(n.idempotencyKey||``),a=O(n.chainIdKey),o=k(n.accountAddress),s=t(n.signerId||``);if(!r||!i||!a||!o||!s)throw Error(`[SeamsWalletDB] opId, idempotencyKey, chainIdKey, accountAddress, and signerId are required`);let c=go(await e.get(r));if(!c){let t=go(await e.index(E.idempotencyKey).get(i));if(t)return t}let l=Date.now(),u={opId:r,idempotencyKey:i,opType:n.opType,chainIdKey:a,accountAddress:o,signerId:s,payload:n.payload??c?.payload,status:n.status??c?.status??`queued`,attemptCount:n.attemptCount??c?.attemptCount??0,nextAttemptAt:n.nextAttemptAt??c?.nextAttemptAt??l,lastError:n.lastError??c?.lastError,txHash:n.txHash??c?.txHash,createdAt:c?.createdAt??l,updatedAt:l};return await e.put(mo(u)),u}async activateAccountSignerInTransaction(e,n){let r=t(n.account.profileId||``),i=O(n.account.chainIdKey),a=k(n.account.accountAddress),o=ke(n.account.accountModel),s=t(n.signer.signerId||``),c=n.signer.signerKind,l=n.signer.signerAuthMethod,u=n.signer.signerSource;if(!r||!i||!a||!o||!s||!c||!l||!u)throw Error(`[SeamsWalletDB] profileId, chainIdKey, accountAddress, accountModel, signerId, signerKind, signerAuthMethod, and signerSource are required`);let d=e.store(T.walletSigners);if(!J(await e.store(T.wallets).get(r)))throw q(`MISSING_PROFILE`,`Cannot upsert signer without profile row: ${r}`,{profileId:r,chainIdKey:i,accountAddress:a,signerId:s});if(qo({accountModel:o,chainIdKey:i})){let t=e.store(T.nearAccountProjections),s=Co(await t.get([r,_o({chainIdKey:i,accountAddress:a}),0])),c=xo({profileId:r,chainIdKey:i,accountAddress:a,accountModel:o,isPrimary:n.selectAsActive===!0?!0:s?.isPrimary??!0},s||void 0);await t.put(c)}let f=(await d.index(E.status).getAll(`active`)).flatMap(e=>{let t=G(e);return t?[t]:[]}),p=f.flatMap(e=>e.chainIdKey===i&&e.accountAddress===a?[e]:[]),m=fr({activeSigners:p,signer:{signerId:s,signerKind:c,signerAuthMethod:l,signerSource:u},activationPolicy:n.activationPolicy,...n.preferredSlot==null?{}:{preferredSlot:n.preferredSlot}}),h=Date.now();await this.revokeSignersForReplacement({signerStore:d,allActiveSigners:f,accountActiveSigners:p,profileId:r,chainIdKey:i,accountModel:o,signerId:s,activationPolicy:n.activationPolicy,now:h});let g=this.activeSignersAfterReplacement({allActiveSigners:f,accountActiveSigners:p,profileId:r,chainIdKey:i,signerId:s,activationPolicy:n.activationPolicy}),_=G(await d.get(vo({chainIdKey:i,accountAddress:a,signerId:s})));if(_&&_.profileId!==r)throw q(`CHAIN_ACCOUNT_PROFILE_MISMATCH`,`Signer row belongs to a different profile for ${i}/${a}/${s}`,{expectedProfileId:r,existingProfileId:_.profileId});let v=this.buildAccountSignerRecord({profileId:r,chainIdKey:i,accountAddress:a,signerId:s,signerSlot:m.signerSlot,signerType:n.signer.signerType,signerKind:c,signerAuthMethod:l,signerSource:u,status:`active`,existing:_||void 0,now:h,...n.signer.metadata?{metadata:n.signer.metadata}:{}});this.assertSignerWriteInvariants({next:v,accountModel:o,existingStatus:_?.status,activeSigners:g});let y=wo(v);if(await Nc({store:d,nextRow:y}),await d.put(y),(n.selectAsActive??!0)&&await e.store(T.appState).put({key:Ko(),value:{profileId:r,activeSignerSlot:m.signerSlot}}),n.mutation?.routeThroughOutbox??!1){let r=t(n.mutation?.opId||``)||Uo(`add-signer`),i=t(n.mutation?.idempotencyKey||``)||`add-signer:${v.chainIdKey}:${v.accountAddress}:${v.signerId}:${v.signerSlot}`;await this.enqueueSignerOperationInTransaction(e.store(T.signerOpsOutbox),{opId:r,idempotencyKey:i,opType:`add-signer`,chainIdKey:v.chainIdKey,accountAddress:v.accountAddress,signerId:v.signerId,payload:this.signerOutboxPayload(v,n.mutation),status:n.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 n=this.signersRetiredByActivationPolicy(e);if(n.length===0)return;let r=t(e.activationPolicy.mode===`replace_slot`||e.activationPolicy.mode===`replace_profile_chain_kind`?e.activationPolicy.revocationReason:``);for(let t of n){let n=this.buildAccountSignerRecord({...t,status:`revoked`,existing:t,now:e.now,removedAt:e.now,revocationReason:r});this.assertSignerWriteInvariants({next:n,accountModel:e.accountModel,existingStatus:t.status,activeSigners:e.accountActiveSigners}),await e.signerStore.put(wo(n))}}async activateAccountSigner(e){let t=null;if(await this.manager.runTransaction([T.appState,T.wallets,T.wallets,T.nearAccountProjections,T.walletSigners,T.appState,T.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 n=t(e.account.profileId||``),r=O(e.account.chainIdKey),i=k(e.account.accountAddress),a=ke(e.account.accountModel),o=t(e.signer.signerId||``),s=Number(e.signerSlot),c=e.signer.signerKind,l=e.signer.signerAuthMethod,u=e.signer.signerSource;if(!n||!r||!i||!a||!o||!c||!l||!u)throw Error(`[SeamsWalletDB] profileId, chainIdKey, accountAddress, accountModel, signerId, signerKind, signerAuthMethod, and signerSource are required`);if(!Number.isSafeInteger(s)||s<1)throw Error(`[SeamsWalletDB] signerSlot must be an integer >= 1`);let d=null;if(await this.manager.runTransaction([T.wallets,T.nearAccountProjections,T.walletSigners,T.signerOpsOutbox],`readwrite`,async f=>{if(!J(await f.store(T.wallets).get(n)))throw q(`MISSING_PROFILE`,`Cannot upsert signer without profile row: ${n}`,{profileId:n,chainIdKey:r,accountAddress:i,signerId:o});let p=f.store(T.nearAccountProjections),m=Co(await p.get([n,_o({chainIdKey:r,accountAddress:i}),0])),h=xo({profileId:n,chainIdKey:r,accountAddress:i,accountModel:a,isPrimary:m?.isPrimary},m||void 0);await p.put(h);let g=f.store(T.walletSigners),_=G(await g.get(vo({chainIdKey:r,accountAddress:i,signerId:o})));if(_&&_.profileId!==n)throw q(`CHAIN_ACCOUNT_PROFILE_MISMATCH`,`Signer row belongs to a different profile for ${r}/${i}/${o}`,{expectedProfileId:n,existingProfileId:_.profileId});let v=(await g.index(E.status).getAll(`active`)).flatMap(e=>{let t=G(e);return t&&t.chainIdKey===r&&t.accountAddress===i?[t]:[]}),y=Date.now(),b=this.buildAccountSignerRecord({profileId:n,chainIdKey:r,accountAddress:i,signerId:o,signerSlot:s,signerType:e.signer.signerType,signerKind:c,signerAuthMethod:l,signerSource:u,status:e.status,existing:_||void 0,now:y,...e.signer.metadata?{metadata:e.signer.metadata}:{}});this.assertSignerWriteInvariants({next:b,accountModel:a,existingStatus:_?.status,activeSigners:v});let ee=wo(b);if(await Nc({store:g,nextRow:ee}),await g.put(ee),e.mutation?.routeThroughOutbox??!1){let n=t(e.mutation?.opId||``)||Uo(`add-signer`),r=t(e.mutation?.idempotencyKey||``)||`add-signer:${b.chainIdKey}:${b.accountAddress}:${b.signerId}:${b.signerSlot}`;await this.enqueueSignerOperationInTransaction(f.store(T.signerOpsOutbox),{opId:n,idempotencyKey:r,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:s}}),!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=O(e.chainIdKey),n=k(e.accountAddress);if(!t||!n)return[];let r=await this.manager.getDB();return(e.status?await r.transaction(T.walletSigners,`readonly`).store.index(E.status).getAll(e.status):await r.getAll(T.walletSigners)).flatMap(e=>{let r=G(e);return r&&r.chainIdKey===t&&r.accountAddress===n?[r]:[]})}async listAccountSignersByProfile(e){let n=t(e.profileId||``);return n?(await(await this.manager.getDB()).transaction(T.walletSigners,`readonly`).store.index(E.walletId).getAll(n)).flatMap(t=>{let n=G(t);return n&&(!e.status||n.status===e.status)?[n]:[]}):[]}async listActiveWalletSigners(e){let n=t(e.walletId||``);if(!n)return[];let r=e.signerFamily===`ecdsa`?Se.thresholdEcdsa:Se.thresholdEd25519,i=[n],a=(await this.getProfile(n))?.nearProvisioning;a?.status===`near_ready`&&a.nearAccountId&&i.push(String(Me(ye(a.nearAccountId))));let o=[],s=new Set;for(let e of i){let i=await this.listAccountSignersByProfile({profileId:e,status:`active`});for(let e of i){if(e.signerKind!==r)continue;let i=t(String(e.metadata?.walletId??``));if(i&&i!==n)continue;let a=`${e.chainIdKey}/${e.accountAddress}/${e.signerId}`;s.has(a)||(s.add(a),o.push(e))}}return o}async getActiveWalletSignerForChainTarget(e){let n=t(e.walletId||``);if(!n)return null;let r=je(e.chainTarget),i=(await this.listActiveWalletSigners({walletId:n,signerFamily:`ecdsa`})).filter(e=>e.chainIdKey===r);if(i.length>1)throw Error(`[SeamsWalletDB] ambiguous active ECDSA wallet signer for ${n}/${r}`);return i[0]||null}async getAccountSigner(e){let n=O(e.chainIdKey),r=k(e.accountAddress),i=t(e.signerId||``);return!n||!r||!i?null:G(await(await this.manager.getDB()).get(T.walletSigners,vo({chainIdKey:n,accountAddress:r,signerId:i})))}async setAccountSignerStatus(e){let n=await this.getAccountSigner(e);if(!n)return null;let r=await this.getChainAccount({profileId:n.profileId,chainIdKey:n.chainIdKey,accountAddress:n.accountAddress});if(!r)throw q(`MISSING_CHAIN_ACCOUNT`,`Cannot update signer status without chain account row: ${n.profileId}/${n.chainIdKey}/${n.accountAddress}`,{profileId:n.profileId,chainIdKey:n.chainIdKey,accountAddress:n.accountAddress,signerId:n.signerId});let i=null;return await this.manager.runTransaction([T.walletSigners,T.signerOpsOutbox],`readwrite`,async a=>{let o=a.store(T.walletSigners),s=(await o.index(E.status).getAll(`active`)).flatMap(e=>{let t=G(e);return t&&t.chainIdKey===n.chainIdKey&&t.accountAddress===n.accountAddress?[t]:[]}),c=this.buildAccountSignerRecord({...n,status:e.status,existing:n,now:Date.now(),...e.removedAt==null?{}:{removedAt:e.removedAt},...e.revocationReason?{revocationReason:e.revocationReason}:{}});if(this.assertSignerWriteInvariants({next:c,accountModel:r.accountModel,existingStatus:n.status,activeSigners:s}),await o.put(wo(c)),e.mutation?.routeThroughOutbox??!0){let n=e.status===`revoked`?`revoke-signer`:`add-signer`,r=t(e.mutation?.opId||``)||Uo(n),i=t(e.mutation?.idempotencyKey||``)||`signer-status:${e.status}:${c.chainIdKey}:${c.accountAddress}:${c.signerId}`;await this.enqueueSignerOperationInTransaction(a.store(T.signerOpsOutbox),{opId:r,idempotencyKey:i,opType:n,chainIdKey:c.chainIdKey,accountAddress:c.accountAddress,signerId:c.signerId,payload:{profileId:c.profileId,signerSlot:c.signerSlot,status:c.status,...c.removedAt==null?{}:{removedAt:c.removedAt},...c.revocationReason?{revocationReason:c.revocationReason}:{},...e.mutation?.outboxPayload?e.mutation.outboxPayload:{}},status:e.mutation?.outboxStatus||`queued`})}i=c}),i}async enqueueSignerOperation(e){let t=null;if(await this.manager.runTransaction([T.signerOpsOutbox],`readwrite`,async n=>{t=await this.enqueueSignerOperationInTransaction(n.store(T.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(T.signerOpsOutbox,`readonly`),n=await t.store.index(E.statusNextAttemptAt).getAll(IDBKeyRange.bound([e,-(2**53-1)],[e,r]));await t.done,o.push(...(n||[]).flatMap(e=>{let t=go(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 n=t(e.opId||``);if(!n)return null;let r=null;return await this.manager.runTransaction([T.signerOpsOutbox],`readwrite`,async t=>{let i=t.store(T.signerOpsOutbox),a=go(await i.get(n));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(mo(c)),r=c}),r}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 n=t(e||``);if(!n)return[];let r=(await this.manager.getDB()).transaction(T.walletAuthMethods,`readonly`),i=await r.store.index(E.walletIdKind).getAll([n,`passkey`]);return await r.done,i.flatMap(e=>{let t=Fs(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(Me(ye(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 n=t(e.credentialId||``);return n?(await this.listWalletPasskeyAuthenticators(e.walletId)).find(e=>e.credentialId===n)??null:null}async upsertProfileAuthenticator(e){let t=Ss(e);await this.manager.runTransaction([T.wallets,T.walletAuthMethods],`readwrite`,async e=>{if(!J(await e.store(T.wallets).get(t.profileId)))throw q(`MISSING_PROFILE`,`Cannot upsert authenticator for unknown profile: ${t.profileId}`,{profileId:t.profileId,credentialId:t.credentialId});let n=e.store(T.walletAuthMethods),r=Y(await n.index(E.passkeyRpIdCredentialId).get([`passkey`,zo,t.credentialId])),i=Os(t,r?.kind===`passkey`?r:void 0);await n.put(i)})}async getProfileAuthenticatorByCredentialId(e,n){let r=t(e||``),i=t(n||``);if(!r||!i)return null;let a=Fs(await(await this.manager.getDB()).transaction(T.walletAuthMethods,`readonly`).store.index(E.passkeyRpIdCredentialId).get([`passkey`,zo,i]));return a?.profileId===r?a:null}async persistWalletRegistrationFinalize(e){return this.manager.runTransaction(Io,`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=wr(e.pending),r=$e(e.authority);if(!r)throw Error(`registration wallet auth authority is invalid`);let i=jo(e.foundingAuthority);await Mo({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(Lo,`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 qi(e.pending);if(t.stage!==`server_promoted`)throw Error(`pending wallet recovery commit is not server-promoted`);let n=X(A(e.authority),`authority`);if(n.state!==`active`||!Ue(n))throw Error(`recovered Wallet Authority projection is invalid`);let r=j(e.authMethod);if(!r||r.status!==`active`)throw Error(`recovered Wallet Auth Method projection is invalid`);if(!await Xe(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};No(i);let a=await Ji(t);return this.manager.runTransaction(Ro,`readwrite`,this.publishPendingWalletRecoveryCommitInTransaction.bind(this,{...i,pendingRow:a}))}async publishPendingWalletRegistrationCommitInTransaction(e,t){let n=yr({registrationCeremonyId:e.request.registrationCeremonyId,operation:e.request.operation}),r=xr(await t.store(T.appState).get(n)),i=r?.record;if(i&&Ao(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 On({ctx:t,active:e.walletSessionPublication.walletSession,operationCredential:e.walletSessionPublication.operationCredential});else{let n=await An({ctx:t,walletId:e.pending.walletId,authorityId:e.foundingAuthority.authority.authorityId,authMethodId:e.pending.walletAuthMethodId});switch(n.kind){case`found`:Po({incoming:e.walletSessionPublication.walletSession,existing:n.record}),await On({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 K(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 K(a)}await this.persistFoundingWalletAuthorityInTransaction(e.foundingAuthority,s,t);for(let n of e.ecdsaContinuity)await ja(t,n);return e.deletePending&&await t.store(T.appState).delete(n),o}async publishPendingWalletRecoveryCommitInTransaction(e,t){if(!ua(await t.store(T.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 Go({store:t.store(T.ecdsaClientPresignatures),indexName:E.walletId,key:IDBKeyRange.only(String(e.authority.walletId))});for(let n of e.ecdsaContinuity)await ja(t,n);let r=t.store(T.appState);for(let t of e.ed25519PublicCapabilityReferences)await ro(r,t);return await t.store(T.appState).delete(e.pendingRow.key),n}async persistWalletRegistrationFinalizeInTransaction(e,n){let r=Mc(e),i=e.keyMaterials.map(e=>Ic(e)),a=[],o=n.store(T.wallets);for(let n of e.profiles){let e=t(n.profileId||``);if(!e)throw Error(`[SeamsWalletDB] profileId is required`);let r=J(await o.get(e))||void 0;await o.put(Jo(n,r))}let s=n.store(T.walletAuthMethods);for(let e of r){if(!J(await o.get(e.wallet_id)))throw q(`MISSING_PROFILE`,`Cannot upsert auth method for unknown wallet: ${e.wallet_id}`,{profileId:e.wallet_id,authIdentifierKey:e.auth_identifier_key});await s.put(e)}for(let t of e.signerActivations)a.push(await this.activateAccountSignerInTransaction(n,t));await qc({ctx:n,signers:a.map(e=>e.signer),keyMaterials:e.keyMaterials});let c=n.store(T.keyMaterial);for(let e of i)await c.put(e);return e.lastProfileState&&await n.store(T.appState).put({key:Ko(e.lastProfileState.scope),value:{profileId:e.lastProfileState.profileId,activeSignerSlot:e.lastProfileState.activeSignerSlot,...e.lastProfileState.scope?{scope:Oe(e.lastProfileState.scope)}:{}}}),{signerActivations:a}}async persistWalletSignerFinalize(e){let n=e.keyMaterials.map(e=>Ic(e)),r=[],i=[],a=null;return await this.manager.runTransaction([T.appState,T.wallets,T.walletSigners,T.nearAccountProjections,T.signerOpsOutbox,T.keyMaterial],`readwrite`,async o=>{let s=o.store(T.wallets);if(e.lastProfileState){let t=o.store(T.appState),n=Ko(e.lastProfileState.scope),r=Do(await t.get(n));a={key:n,committed:{profileId:e.lastProfileState.profileId,activeSignerSlot:e.lastProfileState.activeSignerSlot,...e.lastProfileState.scope?{scope:Oe(e.lastProfileState.scope)}:{}},previousPresent:r!==null,previousValue:r?.value}}for(let n of e.profiles){let e=t(n.profileId||``);if(!e)throw Error(`[SeamsWalletDB] profileId is required`);let r=J(await s.get(e)),a=Jo(n,r||void 0);await s.put(a),i.push({committed:a.record,previous:r})}for(let t of e.signerActivations)r.push(await this.activateAccountSignerInTransaction(o,t));await qc({ctx:o,signers:r.map(e=>e.signer),keyMaterials:e.keyMaterials});let c=o.store(T.keyMaterial);for(let e of n)await c.put(e);if(e.lastProfileState){let e=o.store(T.appState);if(!a)throw Error(`[SeamsWalletDB] last profile rollback state was not captured`);await e.put({key:a.key,value:a.committed})}}),{signerActivations:r,rollbackReceipt:{kind:`wallet_signer_finalize_rollback_v1`,profiles:i,signers:r.map(e=>({committed:e.signer,metadataBaseline:as(e.signer.metadata)})),keyMaterials:n.map(e=>({committed:e.record,payloadBaseline:ss(e.record.payload)})),lastProfileState:a}}}async rollbackWalletSignerFinalize(e){if(e.kind!==`wallet_signer_finalize_rollback_v1`)throw Error(`[SeamsWalletDB] invalid wallet signer rollback receipt`);await this.manager.runTransaction([T.appState,T.wallets,T.walletSigners,T.keyMaterial],`readwrite`,async t=>{let n=t.store(T.wallets),r=t.store(T.walletSigners),i=t.store(T.keyMaterial),a=t.store(T.appState);for(let t of e.profiles){let e=J(await n.get(t.committed.profileId));if(e===null||!$o(e,t.committed))throw Error(`[SeamsWalletDB] wallet signer rollback profile changed`)}for(let t of e.signers){let e=t.committed,n=vo({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId}),i=G(await r.get(n));if(i===null||!ls(i,e,t.metadataBaseline))throw Error(`[SeamsWalletDB] wallet signer rollback signer changed`)}for(let t of e.keyMaterials){let e=t.committed,n=Pc({walletSignerId:Fc(e),keyKind:e.keyKind}),r=Bc(await i.get(n));if(r===null||!us(r,e,t.payloadBaseline))throw Error(`[SeamsWalletDB] wallet signer rollback key material changed`)}if(e.lastProfileState){let t=pr(Do(await a.get(e.lastProfileState.key))?.value);if(t===null||!fs(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(vo({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId}))}for(let t of e.keyMaterials){let e=t.committed;await i.delete(Pc({walletSignerId:Fc(e),keyKind:e.keyKind}))}for(let t of e.profiles)t.previous?await n.put(Yo(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 n=t(e||``);n&&await this.manager.runTransaction([T.walletAuthMethods],`readwrite`,async e=>{await Go({store:e.store(T.walletAuthMethods),indexName:E.walletIdKind,key:IDBKeyRange.only([n,`passkey`])})})}async selectProfileAuthenticatorsForPrompt(e){let n=t(e.profileId||``),r=Array.isArray(e.authenticators)?e.authenticators:[];if(!n||r.length<=1)return{authenticatorsForPrompt:r};let i=await this.getLastProfileState().catch(()=>null);if(!i)return{authenticatorsForPrompt:r};let a=Number(i.activeSignerSlot),o=r.filter(e=>e.signerSlot===a),s=t(o[0]?.credentialId||r[0]?.credentialId||``),c=s?r.filter(e=>e.credentialId===s):[],l=c.length>0?c:o.length>0?o:r,u=t(e.selectedCredentialRawId||``),d=t(e.accountLabel||n);return{authenticatorsForPrompt:l,wrongPasskeyError:u&&s&&u!==s?`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 n=t(e.profileId||``);if(!n)return null;let r=null;return await this.manager.runTransaction([T.wallets],`readwrite`,async t=>{let i=t.store(T.wallets),a=J(await i.get(n));if(!a)return;r={...a.preferences||{},...e.preferences};let o=Jo({profileId:a.profileId,defaultSignerSlot:a.defaultSignerSlot,preferences:r,...a.passkeyCredential?{passkeyCredential:a.passkeyCredential}:{}},a);await i.put(o)}),r}async updateWalletPreferences(e){let n=t(e.walletId||``);return n?await this.updatePreferences({profileId:n,preferences:e.preferences}):null}async deleteProfileData(e,n){let r=t(e||``);r&&await this.manager.runTransaction([T.appState,T.wallets,T.walletAuthMethods,T.walletSigners,T.nearAccountProjections,T.signerOpsOutbox,T.keyMaterial,T.ecdsaClientPresignatures],`readwrite`,async e=>{let t=e.store(T.appState);pr((await t.get(Ko()))?.value)?.profileId===r&&await t.put({key:Ko(),value:null});let i=Ko(n);i!==Ko()&&pr((await t.get(i))?.value)?.profileId===r&&await t.put({key:i,value:null}),await e.store(T.wallets).delete(r),await Go({store:e.store(T.walletAuthMethods),indexName:E.walletId,key:IDBKeyRange.only(r)}),await Go({store:e.store(T.walletSigners),indexName:E.walletId,key:IDBKeyRange.only(r)}),await Go({store:e.store(T.nearAccountProjections),indexName:E.profileId,key:IDBKeyRange.only(r)}),await Go({store:e.store(T.signerOpsOutbox),indexName:E.walletId,key:IDBKeyRange.only(r)}),await Go({store:e.store(T.keyMaterial),indexName:E.walletId,key:IDBKeyRange.only(r)}),await Go({store:e.store(T.ecdsaClientPresignatures),indexName:E.walletId,key:IDBKeyRange.only(r)})})}async getLastProfileState(e){let t=Ko(e);return pr(await this.getAppState(t).catch(()=>void 0))}async setLastProfileState(e,t){let n=Ko(t),r=e?pr(e):null;if(e&&!r)throw Error(`[SeamsWalletDB] invalid last profile state`);await this.setAppState(n,r)}async setLastProfileStateForProfile(e,n,r){let i=t(e||``),a=Number(n);if(!i)throw Error(`[SeamsWalletDB] profileId is required`);if(!Number.isSafeInteger(a)||a<1)throw Error(`[SeamsWalletDB] activeSignerSlot must be an integer >= 1`);let o=Oe(r);await this.setLastProfileState({profileId:i,activeSignerSlot:a,...o?{scope:o}:{}},o)}async clearLastProfileSelection(e){await this.setLastProfileState(null,e)}async storeKeyMaterial(e){let t=Ic(e);await this.manager.runTransaction([T.keyMaterial],`readwrite`,async e=>{await e.store(T.keyMaterial).put(t)})}async getKeyMaterial(e,n,r,i){let a=t(e||``),o=t(r||``).toLowerCase(),s=t(i||``);if(!a||!o||!s)return null;let c=null;return await this.manager.runTransaction([T.keyMaterial,T.walletSigners],`readonly`,async e=>{let t=(await e.store(T.keyMaterial).index(E.walletId).getAll(a)).flatMap(e=>{let t=Bc(e);return t&&t.signerSlot===n&&t.chainIdKey===o&&t.keyKind===s?[t]:[]});if(t.length===0){c=null;return}c=Yc({matches:t,activeSigners:(await e.store(T.walletSigners).index(E.walletId).getAll(a)).flatMap(e=>{let t=G(e);return t?.status===`active`&&t.signerSlot===n&&t.chainIdKey===o?[t]:[]})})}),c}async listKeyMaterialByProfile(e,n){let r=t(e||``),i=t(n||``).toLowerCase();if(!r)return[];let a=(await this.manager.getDB()).transaction(T.keyMaterial,`readonly`),o=await a.store.index(E.walletId).getAll(r);await a.done;let s=o.flatMap(e=>{let t=Bc(e);return t?[t]:[]});return i?s.filter(e=>e.chainIdKey===i):s}async listKeyMaterialByProfileAndSignerSlot(e,t,n){return!Number.isSafeInteger(t)||t<1?[]:(await this.listKeyMaterialByProfile(e,n)).filter(e=>e.signerSlot===t)}async deleteKeyMaterial(e,n,r,i){let a=t(e||``),o=t(r||``).toLowerCase(),s=t(i||``);!a||!o||!s||!Number.isSafeInteger(n)||n<1||await this.manager.runTransaction([T.keyMaterial],`readwrite`,async e=>{let t=e.store(T.keyMaterial),r=await t.index(E.walletId).getAll(a);for(let e of r){let r=Bc(e);r&&r.signerSlot===n&&r.chainIdKey===o&&r.keyKind===s&&await t.delete(Pc({walletSignerId:Fc(r),keyKind:r.keyKind}))}})}async readNonceLaneLeaseRecords(e){let n=t(e||``);if(!n)return[];let r=(await this.manager.getDB()).transaction(T.nonceLaneLeases,`readonly`),i=await r.store.index(E.laneKey).getAll(n);return await r.done,i.flatMap(e=>{let t=po(e);return t?[t]:[]})}async listNonceLaneLeaseRecords(e){let n=t(e?.walletId||``),r=(await this.manager.getDB()).transaction(T.nonceLaneLeases,`readonly`),i=n?await r.store.index(E.walletId).getAll(n):await r.store.getAll();return await r.done,i.flatMap(e=>{let t=po(e);return t?[t]:[]})}async upsertNonceLaneLeaseRecord(e){let t=co(e);await this.manager.runTransaction([T.nonceLaneLeases],`readwrite`,async e=>{await e.store(T.nonceLaneLeases).put(t)})}async removeNonceLaneLeaseRecord(e){let n=t(e.leaseId||``);n&&await this.manager.runTransaction([T.nonceLaneLeases],`readwrite`,async e=>{await e.store(T.nonceLaneLeases).delete(n)})}async clearNonceLaneLeaseRecordsForWallet(e){let n=t(e||``);n&&await this.manager.runTransaction([T.nonceLaneLeases],`readwrite`,async e=>{let t=e.store(T.nonceLaneLeases),r=await t.index(E.walletId).getAll(n);for(let e of r){let n=po(e);n&&n.state!==`broadcast_accepted`&&await t.delete(n.leaseId)}})}async clearAllNonceLaneLeaseRecords(){await this.manager.runTransaction([T.nonceLaneLeases],`readwrite`,async e=>{await e.store(T.nonceLaneLeases).clear()})}async pruneExpiredNonceLaneLeaseRecords(e){let t=Math.floor(Number(e));Number.isSafeInteger(t)&&await this.manager.runTransaction([T.nonceLaneLeases],`readwrite`,async e=>{let n=e.store(T.nonceLaneLeases),r=await n.index(E.expiresAtMs).getAll(Wo(t));for(let e of r){let t=po(e);t&&t.state!==`broadcast_accepted`&&await n.delete(t.leaseId)}})}async withNonceLaneCoordinationLock(e,n){let r=t(e.lockKey||``),i=t(e.ownerId||``);if(!r||!i)throw Error(`[SeamsWalletDB] nonce lane lock requires lockKey and ownerId`);let a=Math.max(1,Math.floor(Number(e.ttlMs)||5e3)),o=Math.max(1,Math.floor(Number(e.waitTimeoutMs)||3e3)),s=Uo(`nonce-lane-lock`),c=Date.now()+o,l=async()=>{let e=!1;return await this.manager.runTransaction([T.nonceLaneLocks],`readwrite`,async t=>{let n=t.store(T.nonceLaneLocks),o=Date.now(),c=lo(await n.get(r));if(c&&c.expires_at_ms>o)return;let l={lock_key:r,owner_id:i,fencing_token:s,acquired_at_ms:o,expires_at_ms:o+a,updated_at_ms:o};await n.put(l),e=!0}),e};for(;!await l();){if(Date.now()>=c){let e=Error(`[SeamsWalletDB] durable nonce lane lock timed out`);throw e.code=`durable_lock_timeout`,e}await Ho(25)}try{return await n()}finally{await this.manager.runTransaction([T.nonceLaneLocks],`readwrite`,async e=>{let t=e.store(T.nonceLaneLocks);lo(await t.get(r))?.fencing_token===s&&await t.delete(r)}).catch(()=>void 0)}}};const Zc=new Set(Object.values(Se));var Qc=class{seamsWalletDB;seamsWalletRepositories;registrationSetupRepository;eventListeners=new Set;_initialized=!1;lastUserScope=null;constructor(e){this.seamsWalletDB=e?.seamsWalletDB||De,this.seamsWalletRepositories=new Xc(this.seamsWalletDB),this.registrationSetupRepository=new we(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=Oe(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 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 n=await this.seamsWalletRepositories.updatePreferences(e),r=t(e.eventAccountId||``);n&&r&&this.emitEvent({type:`preferences-updated`,accountId:r,data:{preferences:n}})}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,n){await this.seamsWalletRepositories.deleteProfileData(e,this.lastUserScope);let r=t(n?.eventAccountId||``);r&&this.emitEvent({type:`user-deleted`,accountId:r})}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 n=typeof e?.now==`number`?e.now:Date.now(),r=Number.isSafeInteger(e?.stalePendingSignerMs)&&Number(e?.stalePendingSignerMs)>0?Number(e?.stalePendingSignerMs):864e5,i=t(e?.profileId||``),a=i?await this.getProfile(i).then(e=>e?[e]:[]):await this.listProfiles({limit:e?.limitProfiles}),o={scannedProfiles:0,scannedSigners:0,scannedKeyMaterials:0,issues:[],repairs:[]},s=e=>{o.issues.push(e)};for(let e of a){o.scannedProfiles+=1;let t=await this.listAccountSignersByProfile({profileId:e.profileId}),i=await this.seamsWalletRepositories.listKeyMaterialByProfile(e.profileId);o.scannedSigners+=t.length,o.scannedKeyMaterials+=i.length;let a=new Map,c=new Set;for(let e of t){if(e.status!==`active`)continue;let t=[e.chainIdKey,e.accountAddress,String(e.signerSlot)].join(`\0`);c.add(t);let n=a.get(t)||[];n.push(e),a.set(t,n)}for(let[t,n]of a.entries()){if(n.length<=1)continue;let[r,i,a]=t.split(`\0`);s({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 t)a.status===`pending`&&n-Number(a.addedAt||0)>r&&s({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 ${r}ms`}),a.status===`active`&&Zc.has(String(a.signerKind||``))&&i.filter(e=>e.chainIdKey===a.chainIdKey&&e.signerSlot===a.signerSlot&&e.keyKind===`threshold_share_v1`).length===0&&s({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 n of i){let r=[n.chainIdKey,n.payloadEnvelope?.aad?.accountAddress||``,String(n.signerSlot)].join(`\0`);c.has(r)||t.some(e=>e.status===`active`&&e.chainIdKey===n.chainIdKey&&e.signerSlot===n.signerSlot)||s({code:`key_material_without_active_signer`,profileId:e.profileId,chainIdKey:n.chainIdKey,signerSlot:n.signerSlot,keyKind:n.keyKind,message:`Key material ${n.keyKind} at slot ${n.signerSlot} has no active signer`})}}return e?.logIssues&&o.issues.length>0&&console.warn(`[IndexedDB] local signer reconciliation found issues`,{issueCount:o.issues.length,issues:o.issues.slice(0,20)}),o}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 n=typeof e?.now==`number`?e.now:Date.now(),r=Number.isSafeInteger(e?.limit)&&Number(e?.limit)>0?Number(e?.limit):100,i={scanned:0,confirmed:0,failed:0,deadLettered:0},a=await this.listSignerOperations({statuses:[`queued`,`submitted`,`failed`],dueBefore:n,limit:r});for(let e of a){i.scanned+=1;let r=e.payload||{},a=await this.getAccountSigner({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId}),o=t(a?.profileId||r.profileId||``),s=Number(r.signerSlot??a?.signerSlot),c=Number.isSafeInteger(s)&&s>=1?s:null,l=async t=>{let r=(e.attemptCount||0)+1;await this.setSignerOperationStatus({opId:e.opId,status:`failed`,attemptDelta:1,lastError:t,nextAttemptAt:n+this.computeSignerOpRetryDelayMs(r)}),i.failed+=1},u=async t=>{await this.setSignerOperationStatus({opId:e.opId,status:`dead-letter`,lastError:t,nextAttemptAt:n}),i.deadLettered+=1},d=async()=>{await this.setSignerOperationStatus({opId:e.opId,status:`confirmed`,lastError:null,nextAttemptAt:n}),i.confirmed+=1};try{if(e.opType===`add-signer`||e.opType===`activate-recovery-signer`){if(!a){await u(`Missing signer row for add-signer operation`);continue}if(a.status===`revoked`){await u(`Cannot activate a revoked signer; create a new signer record`);continue}if(!o||c==null){await u(`Missing profileId/signerSlot metadata for add-signer operation`);continue}if(!await this.getChainAccount({profileId:a.profileId,chainIdKey:e.chainIdKey,accountAddress:e.accountAddress})){await u(`Missing chain account row for add-signer operation`);continue}if((await this.seamsWalletRepositories.listKeyMaterialByProfileAndSignerSlot(o,c,e.chainIdKey)).length===0){await l(`Missing key material for signer operation`);continue}await d();continue}if(e.opType===`revoke-signer`){if(a&&(a.status!==`revoked`&&await this.setAccountSignerStatus({chainIdKey:e.chainIdKey,accountAddress:e.accountAddress,signerId:e.signerId,status:`revoked`,removedAt:n,mutation:{routeThroughOutbox:!1}}),o&&c!=null)){let t=await this.seamsWalletRepositories.listKeyMaterialByProfileAndSignerSlot(o,c,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 i}};function $c(e){if(!e||typeof e!=`object`||Array.isArray(e))return sl({},``,``,``);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 sl(t,r,n,i);let c=ll(t.nonce),l=rl(t),u=$(t.operationId),d=$(t.operationFingerprint),f=ul(t.reservedAtMs),p=ul(t.expiresAtMs),m=ul(t.updatedAtMs);return!n||!r||i!==`evm`&&i!==`near`||!a||c==null||!l||!u||!d||f==null||p==null||m==null?sl(t,r,n,i):i===`evm`?el({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}):tl({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 el(e){let t=ol(e.obj.chainTarget),n=cl(e.obj.sender),r=il(e.lifecycle),i=e.obj.nonceKey===void 0||e.obj.nonceKey===null?void 0:ll(e.obj.nonceKey);if(!t||!e.accountId||!n||!r||i===null)return sl(e.obj,e.laneKey,e.leaseId,`evm`);let a={...nl(e,r),family:`evm`,chainTarget:t,accountId:xe(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:Mn(o),nonce:a.nonce}}}function tl(e){let t=$(e.obj.publicKey),n=$(e.obj.walletId);if(!e.nearAccountId||!n||!t)return sl(e.obj,e.laneKey,e.leaseId,`near`);let r={...nl(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:Mn(i),nonce:r.nonce}}}function nl(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:ul(e.obj.txIndex);switch(o!=null&&(n.txIndex=o),t.state){case I.Reserved:case I.Signed:return{...n,state:t.state};case I.BroadcastAccepted:return{...n,state:I.BroadcastAccepted,txHash:t.txHash}}}function rl(e){if(e.state===I.Reserved)return e.txHash===void 0?{state:I.Reserved}:null;if(e.state===I.Signed)return e.txHash===void 0?{state:I.Signed}:null;if(e.state===I.BroadcastAccepted){let t=$(e.txHash);return t?{state:I.BroadcastAccepted,txHash:t}:{state:I.Signed}}return null}function il(e){if(e.state!==I.BroadcastAccepted)return e;let t=al(e.txHash);return t?{state:I.BroadcastAccepted,txHash:t}:{state:I.Signed}}function al(e){let t=$(e).toLowerCase();return/^0x[0-9a-f]{64}$/.test(t)?t:null}function ol(e){try{return be(e&&typeof e==`object`&&!Array.isArray(e)?e:{})}catch{return null}}function sl(e,t,n,r){let i={reason:jn.MalformedDurableRecord,fallback:Nn.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 cl(e){let t=$(e).toLowerCase();return/^0x[0-9a-f]{40}$/.test(t)?t:null}function $(e){return typeof e==`string`?e.trim():``}function ll(e){return typeof e!=`string`||!/^\d+$/.test(e)?null:BigInt(e)}function ul(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 dl(e){return{readLane:async t=>(await e.indexedDB.readNonceLaneLeaseRecords(t)).flatMap(e=>{let t=$c(e);return t.ok?[t.parsed]:[]}),readAll:async t=>(await e.indexedDB.listNonceLaneLeaseRecords(t)).flatMap(e=>{let t=$c(e);return t.ok?[t.parsed]:[]}),readAllForRecovery:async t=>(await e.indexedDB.listNonceLaneLeaseRecords(t)).map(e=>$c(e)),upsert:async t=>{if(t.family===`evm`){await e.indexedDB.upsertNonceLaneLeaseRecord(pl(t));return}await e.indexedDB.upsertNonceLaneLeaseRecord(ml(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 fl(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 pl(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()},...fl(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 ml(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,...fl(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 hl={app:{walletDbName:me,disabled:!1},wallet:{walletDbName:me,disabled:!1},disabled:{walletDbName:me,disabled:!0}};let gl=null;function _l(e){let t=e?.mode,n=hl[t];if(!n)throw Error(`[IndexedDBManager] Unknown IndexedDBMode: ${String(t)}`);return gl?(gl.walletDbName===n.walletDbName&&gl.disabled===n.disabled||console.warn(`[IndexedDBManager] configureIndexedDB called multiple times; ignoring subsequent configuration`,{configured:gl,requested:n}),{walletDbName:gl.walletDbName}):(gl={mode:t,...n},De.setDbName(n.walletDbName),De.setDisabled(n.disabled),{walletDbName:gl.walletDbName})}const vl=new Qc({seamsWalletDB:De}),yl=/^wallet-rkid-v1-[A-Za-z0-9_-]{43}$/;function bl(e,t=`recoveryKeyId`){if(typeof e!=`string`||!yl.test(e))throw Error(`${t} must be a derived wallet recovery key id`);return e}function xl(){let e=[],t=[];for(let n=0;n<10;n+=1){let n=Cl();t.push(n),e.push(L(Jn(n)))}return{codes:e,codeBytes:t}}function Sl(e){for(let t of e.codeBytes)t.fill(0)}function Cl(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`a secure random source is required to issue wallet recovery codes`);return e.getRandomValues(new Uint8Array(20))}function wl(e,t=`recoveryCodeLocator`){try{return ve(e)}catch(e){throw Error(`${t} ${e instanceof Error?e.message:`must be a canonical digest`}`)}}async function Tl(e){if(!(e instanceof Uint8Array)||e.length!==20)throw Error(`recovery code bytes must be exactly 20 bytes`);let t=null;try{let n=new TextEncoder().encode(`seams/wallet-recovery/code-locator/v1`);t=new Uint8Array(8+n.length+e.length);let r=new DataView(t.buffer);return r.setUint32(0,n.length,!1),t.set(n,4),r.setUint32(4+n.length,e.length,!1),t.set(e,8+n.length),wl(C(await ee(t)))}finally{t?.fill(0)}}function El(e){return{custodySecretKind:`wallet_custody_seed_v1`,nonceB64u:e.nonceB64u,wrappedCustodySecretB64u:e.wrappedCustodySecretB64u,aadHashB64u:e.aadHashB64u}}function Dl(e,t){let n=t.label||`walletRecoverySetRotation`,r=b(e,n);ae(r,Al,n);let i=a(r.walletId);if(!i.ok)throw Error(`${n}.walletId ${i.error.message}`);if(String(i.value)!==String(t.expectedWalletId))throw Error(`${n}.walletId is outside the authenticated wallet`);if(!Array.isArray(r.manifestKekWraps))throw Error(`${n}.manifestKekWraps must be an array`);if(r.manifestKekWraps.length!==10)throw Error(`${n}.manifestKekWraps must carry exactly 10 recovery-code wraps`);let o=r.manifestKekWraps.map((e,t)=>{let r=b(e,`${n}.manifestKekWraps[${t}]`);return ae(r,kl,`${n}.manifestKekWraps[${t}]`),{recoveryKeyId:bl(r.recoveryKeyId,`${n}.manifestKekWraps[${t}].recoveryKeyId`),nonceB64u:ue(r.nonceB64u,`${n}.manifestKekWraps[${t}].nonceB64u`),ciphertextB64u:oe(r.ciphertextB64u,`${n}.manifestKekWraps[${t}].ciphertextB64u`),aadHashB64u:re(r.aadHashB64u,`${n}.manifestKekWraps[${t}].aadHashB64u`)}}),s=new Set;for(let e of o){let t=String(e.recoveryKeyId);if(!s.add(t))throw Error(`${n} contains duplicate recovery key ids`)}if(!Array.isArray(r.entries)||r.entries.length!==1)throw Error(`${n}.entries must carry exactly one wallet custody seed entry`);let c=jl(r.entries[0],`${n}.entries[0]`);return{walletId:i.value,manifestKekWraps:o,entry:c}}const Ol=[`custodySecretKind`,`nonceB64u`,`wrappedCustodySecretB64u`,`aadHashB64u`],kl=[`recoveryKeyId`,`nonceB64u`,`ciphertextB64u`,`aadHashB64u`],Al=[`walletId`,`manifestKekWraps`,`entries`];function jl(e,t){let n=b(e,t);if(ae(n,Ol,t),n.custodySecretKind!==`wallet_custody_seed_v1`)throw Error(`${t}.custodySecretKind must be wallet_custody_seed_v1; lane holder shares are reprovisioned, not recovered`);return El({nonceB64u:ue(n.nonceB64u,`${t}.nonceB64u`),wrappedCustodySecretB64u:oe(n.wrappedCustodySecretB64u,`${t}.wrappedCustodySecretB64u`),aadHashB64u:re(n.aadHashB64u,`${t}.aadHashB64u`)})}function Ml(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function Nl(e,t){let n=typeof e==`string`?e.trim():``;if(!n)throw Error(`${t} is required`);return n}function Pl(e){let t=Ml(e,`rotation worker result`);if(!Array.isArray(t.recoveryManifestKekWraps)||t.recoveryManifestKekWraps.length!==10)throw Error(`rotation worker result must contain exactly 10 recovery wraps`);return{walletId:Nl(t.walletId,`rotation worker walletId`),recoveryManifestKekWraps:t.recoveryManifestKekWraps.map((e,t)=>{let n=Ml(e,`rotation worker wrap ${t}`);return{recoveryKeyId:Nl(n.recoveryKeyId,`rotation worker wrap ${t} recoveryKeyId`),nonceB64u:Nl(n.nonceB64u,`rotation worker wrap ${t} nonceB64u`),ciphertextB64u:Nl(n.ciphertextB64u,`rotation worker wrap ${t} ciphertextB64u`),aadHashB64u:Nl(n.aadHashB64u,`rotation worker wrap ${t} aadHashB64u`)}}),recoveryEntryNonceB64u:Nl(t.recoveryEntryNonceB64u,`rotation worker recoveryEntryNonceB64u`),recoveryEntryCiphertextB64u:Nl(t.recoveryEntryCiphertextB64u,`rotation worker recoveryEntryCiphertextB64u`),recoveryEntryAadHashB64u:Nl(t.recoveryEntryAadHashB64u,`rotation worker recoveryEntryAadHashB64u`)}}function Fl(e){let t=Pl(e),n=a(t.walletId);if(!n.ok)throw Error(`rotation worker wallet id is invalid: ${n.error.message}`);let r={custodySecretKind:`wallet_custody_seed_v1`,nonceB64u:ue(t.recoveryEntryNonceB64u,`rotation.entry.nonceB64u`),wrappedCustodySecretB64u:oe(t.recoveryEntryCiphertextB64u,`rotation.entry.wrappedCustodySecretB64u`),aadHashB64u:re(t.recoveryEntryAadHashB64u,`rotation.entry.aadHashB64u`)};return Dl({walletId:n.value,manifestKekWraps:t.recoveryManifestKekWraps.map(e=>({recoveryKeyId:bl(e.recoveryKeyId,`rotation.recoveryKeyId`),nonceB64u:ue(e.nonceB64u,`rotation.wrap.nonceB64u`),ciphertextB64u:oe(e.ciphertextB64u,`rotation.wrap.ciphertextB64u`),aadHashB64u:re(e.aadHashB64u,`rotation.wrap.aadHashB64u`)})),entries:[r]},{expectedWalletId:n.value,label:`rotation.workerResult`})}const Il=`secp256k1_bip340_sha256_v1`;function Ll(e,t,n){let r=new Set(n);for(let n of Object.keys(e))if(!r.has(n))throw Error(`${t}.${n} is not a supported field`);for(let r of n)if(!Object.hasOwn(e,r))throw Error(`${t}.${r} is required`)}function Rl(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`${t} must be a non-empty canonical identifier`);for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r<33||r>126)throw Error(`${t} must contain visible ASCII bytes`)}return e}function zl(e){return e.startsWith(`evm_family_ecdsa:`)&&e.length>17}function Bl(e,t){let n=Rl(e,t);if(!zl(n))throw Error(`${t} must identify an ECDSA key set`);return n}function Vl(e,t){try{return ve(e)}catch{throw Error(`${t} must be canonical base64url for 32 bytes`)}}function Hl(e,t){if(typeof e!=`string`||!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} must be canonical base64url`);let n;try{n=w(e)}catch{throw Error(`${t} must be valid base64url`)}if(n.length!==33||n[0]!==2&&n[0]!==3||C(n)!==e)throw Error(`${t} must be canonical compressed secp256k1 public key bytes`);return e}function Ul(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive safe integer`);return e}function Wl(e,t){if(typeof e!=`string`||!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} must be canonical base64url`);let n;try{n=w(e)}catch{throw Error(`${t} must be valid base64url`)}if(n.length!==64||C(n)!==e)throw Error(`${t} must be canonical base64url for 64 bytes`);return e}function Gl(e){let t=b(e,`walletRecoveryEcdsaPossessionChallenge`);if(Ll(t,`walletRecoveryEcdsaPossessionChallenge`,[`kind`,`walletId`,`reservationId`,`replacementId`,`keySetId`,`keyHandle`,`recordedKeyManifestDigestB64u`,`publicCapabilityDigestB64u`,`authorityRefDigestB64u`,`derivationClientSharePublicKey33B64u`,`expectedServerGeneration`,`expiresAtMs`,`serverNonceB64u`]),t.kind!==`wallet_recovery_ecdsa_possession_challenge_v1`)throw Error(`walletRecoveryEcdsaPossessionChallenge.kind is invalid`);let n=Bl(t.keySetId,`walletRecoveryEcdsaPossessionChallenge.keySetId`);return{kind:`wallet_recovery_ecdsa_possession_challenge_v1`,walletId:Rl(t.walletId,`walletRecoveryEcdsaPossessionChallenge.walletId`),reservationId:Rl(t.reservationId,`walletRecoveryEcdsaPossessionChallenge.reservationId`),replacementId:Rl(t.replacementId,`walletRecoveryEcdsaPossessionChallenge.replacementId`),keySetId:n,keyHandle:Rl(t.keyHandle,`walletRecoveryEcdsaPossessionChallenge.keyHandle`),recordedKeyManifestDigestB64u:Vl(t.recordedKeyManifestDigestB64u,`walletRecoveryEcdsaPossessionChallenge.recordedKeyManifestDigestB64u`),publicCapabilityDigestB64u:Vl(t.publicCapabilityDigestB64u,`walletRecoveryEcdsaPossessionChallenge.publicCapabilityDigestB64u`),authorityRefDigestB64u:Vl(t.authorityRefDigestB64u,`walletRecoveryEcdsaPossessionChallenge.authorityRefDigestB64u`),derivationClientSharePublicKey33B64u:Hl(t.derivationClientSharePublicKey33B64u,`walletRecoveryEcdsaPossessionChallenge.derivationClientSharePublicKey33B64u`),expectedServerGeneration:Rl(t.expectedServerGeneration,`walletRecoveryEcdsaPossessionChallenge.expectedServerGeneration`),expiresAtMs:Ul(t.expiresAtMs,`walletRecoveryEcdsaPossessionChallenge.expiresAtMs`),serverNonceB64u:Vl(t.serverNonceB64u,`walletRecoveryEcdsaPossessionChallenge.serverNonceB64u`)}}function Kl(e){let t=b(e,`walletRecoveryEcdsaPossessionProof`);if(Ll(t,`walletRecoveryEcdsaPossessionProof`,[`kind`,`scheme`,`signature64B64u`]),t.kind!==`wallet_recovery_ecdsa_possession_proof_v1`)throw Error(`walletRecoveryEcdsaPossessionProof.kind is invalid`);if(t.scheme!==Il)throw Error(`walletRecoveryEcdsaPossessionProof.scheme is invalid`);return{kind:`wallet_recovery_ecdsa_possession_proof_v1`,scheme:Il,signature64B64u:Wl(t.signature64B64u,`walletRecoveryEcdsaPossessionProof.signature64B64u`)}}function ql(e){let t=Gl(e),n=[`seams/wallet-recovery/ecdsa-existing-material-possession/v1`,Il,t.walletId,t.reservationId,t.replacementId,t.keySetId,t.keyHandle,w(t.recordedKeyManifestDigestB64u),w(t.publicCapabilityDigestB64u),w(t.authorityRefDigestB64u),w(t.derivationClientSharePublicKey33B64u),t.expectedServerGeneration,w(t.serverNonceB64u),Jl(t.expiresAtMs)],r=[];for(let e of n){let t=typeof e==`string`?new TextEncoder().encode(e):e,n=t.length;if(n>4294967295)throw Error(`wallet recovery possession field is too large`);r.push(n>>>24&255,n>>>16&255,n>>>8&255,n&255,...t)}return Uint8Array.from(r)}function Jl(e){let t=BigInt(e),n=new Uint8Array(8);for(let e=n.length-1;e>=0;--e)n[e]=Number(t&255n),t>>=8n;return n}async function Yl(e){return ge(ql(e))}export{ir as A,ci as C,_r as D,hr as E,Zn as F,Xn as I,In as L,Qn as M,Gn as N,nr as O,Yn as P,Fn as R,si as S,Dr as T,Ia as _,jl as a,li as b,Sl as c,dl as d,Xc as f,La as g,ao as h,Fl as i,tr as j,ar as k,vl as l,Ua as m,Kl as n,Tl as o,io as p,Yl as r,xl as s,Gl as t,_l as u,Aa as v,Or as w,fi as x,Fi as y};
|