@seams/wallet 0.9.2 → 0.9.4
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/README.md +3 -3
- package/THIRD_PARTY_NOTICES.md +33 -1
- package/dist/.build-inputs.sha256 +1 -1
- package/dist/esm/core/signingEngine/flows/signNear/shared/signatureOnlySigning.js +4 -9
- package/dist/esm/core/signingEngine/flows/signNear/signDelegate.js +10 -2
- package/dist/esm/core/signingEngine/flows/signNear/signNep413.js +6 -1
- package/dist/esm/react/components/VoiceAssistantCard.css +313 -0
- package/dist/esm/react/components/VoiceAssistantCard.js +150 -0
- package/dist/esm/react/index.js +3 -1
- package/dist/esm/react/styles/styles.css +314 -0
- package/dist/esm/react/styles.css +1 -0
- package/dist/esm/sdk/{ConfirmationDrawer-DY0_yeUV.js → ConfirmationDrawer-Frj3uEee.js} +1 -1
- package/dist/{public/sdk/NonceCoordinator-CFFq8-Q9.js → esm/sdk/NonceCoordinator-S5ZbrkDp.js} +1 -1
- package/dist/{public/sdk/accountLifecycle-CAMVowDl.js → esm/sdk/accountLifecycle-HEUmDLus.js} +1 -1
- package/dist/esm/sdk/activeWalletSession-WdZkhtBB.js +1 -0
- package/dist/esm/sdk/{adapters-DdDOQzl4.js → adapters-DYPu0nK9.js} +2 -2
- package/dist/esm/sdk/{canonicalPrimitives-CKPGgpxg.js → canonicalPrimitives-Dsbsxgxc.js} +1 -1
- package/dist/esm/sdk/{capabilityKinds-CKQ4Uqnv.js → capabilityKinds-N8xo_IEh.js} +1 -1
- package/dist/esm/sdk/{chains-CiYQT1K4.js → chains-C_X_fNuS.js} +1 -1
- package/dist/esm/sdk/challengeDelivery-5lIu9spR.js +1 -0
- package/dist/{public/sdk/clientSessionPersistenceState-CImFWDj6.js → esm/sdk/clientSessionPersistenceState-DRdve9rC.js} +1 -1
- package/dist/esm/sdk/{commitQueue-iBNUt9Bz.js → commitQueue-qjvY_zWn.js} +1 -1
- package/dist/esm/sdk/{configHelpers-D8Ivi6p8.js → configHelpers-B-hs0mTO.js} +1 -1
- package/dist/esm/sdk/digestEncoding-CkUc5vtR.js +1 -0
- package/dist/esm/sdk/{display-ClqZq-Xt.js → display-DjoWrSgE.js} +1 -1
- package/dist/esm/sdk/domainIds-BzkGsRqO.js +1 -0
- package/dist/{public/sdk/ecdsaCapabilityManifest-BlzJAQF8.js → esm/sdk/ecdsaCapabilityManifest-ChszYCC0.js} +1 -1
- package/dist/esm/sdk/{ecdsaChainTarget-C8ZtMZ8l.js → ecdsaChainTarget-DJBXHzbH.js} +1 -1
- package/dist/{public/sdk/ecdsaDerivationClientWasm-CVeNEou2.js → esm/sdk/ecdsaDerivationClientWasm-CpH-b3jx.js} +1 -1
- package/dist/{public/sdk/ecdsaDerivationExport-BZFHSMCv.js → esm/sdk/ecdsaDerivationExport-C1cE5m0t.js} +1 -1
- package/dist/esm/sdk/{ecdsaWalletRecords-D4WeYc7H.js → ecdsaWalletRecords-Di_NUxD_.js} +1 -1
- package/dist/esm/sdk/emailOtpEcdsaDerivationIdentity-p0C1CQva.js +1 -0
- package/dist/esm/sdk/{enrichDisplayModelWithAbi-69bNckvi.js → enrichDisplayModelWithAbi-DZIhvE-x.js} +1 -1
- package/dist/esm/sdk/{evmCryptoWasm-BXsIyRon.js → evmCryptoWasm-DeobzyP-.js} +1 -1
- package/dist/{public/sdk/export-viewer-host-CsFeiIhd.js → esm/sdk/export-viewer-host-DUMwD6zP.js} +1 -1
- package/dist/{public/sdk/exportKeypairOperation-DGQIYML3.js → esm/sdk/exportKeypairOperation-DYCzCbqL.js} +1 -1
- package/dist/esm/sdk/{helpers-Ddy72ULN.js → helpers-BnkILY2_.js} +1 -1
- package/dist/esm/sdk/host-h55onlkx.js +1 -0
- package/dist/esm/sdk/{intentDigest-CE-tLw87.js → intentDigest-DJBrMyLJ.js} +1 -1
- package/dist/esm/sdk/{lanes-DnBwWv4l.js → lanes-Ck81oEGv.js} +1 -1
- package/dist/esm/sdk/{localOnly-ClCo6602.js → localOnly-KvZeKkH5.js} +1 -1
- package/dist/{public/sdk/messages-vxz27Way.js → esm/sdk/messages-DgJlG9NU.js} +1 -1
- package/dist/esm/sdk/{mountExportPrivateKeySurface-CBZ0wRYj.js → mountExportPrivateKeySurface-B4gH1Sel.js} +1 -1
- package/dist/{public/sdk/mountRecoveryCodeBackupSurface-B1qhFF6G.js → esm/sdk/mountRecoveryCodeBackupSurface-BA2ttbTM.js} +1 -1
- package/dist/esm/sdk/nearEd25519YaoMaterialActivation-CvDs4RtV.js +1 -0
- package/dist/esm/sdk/{nearEd25519YaoSigningPreparation-B0d1AG3u.js → nearEd25519YaoSigningPreparation-Eiq_ikXk.js} +1 -1
- package/dist/esm/sdk/{nonceLaneKeys-Fkvk2UPy.js → nonceLaneKeys-Do5Vs-De.js} +1 -1
- package/dist/esm/sdk/{normalization-DCvuCvh0.js → normalization-DJPmcXTg.js} +1 -1
- package/dist/esm/sdk/{operationFingerprint-CTR9G1NT.js → operationFingerprint-CUrnoh-M.js} +1 -1
- package/dist/esm/sdk/passkey-custody-Cd_yyoRa.js +1 -0
- package/dist/esm/sdk/{pendingWalletRecoveryCodeBackup-yJN8VAHn.js → pendingWalletRecoveryCodeBackup-BkIrbd6Q.js} +1 -1
- package/dist/esm/sdk/presignaturePool-CLHu7HaU.js +1 -0
- package/dist/esm/sdk/{prfCache-BMpqZZ-v.js → prfCache-DCkuB8Lu.js} +1 -1
- package/dist/esm/sdk/primitives-CqrjmIAH.js +1 -0
- package/dist/{public/sdk/recovery-entrypoint-Bl5GgbW9.js → esm/sdk/recovery-entrypoint-DoXswV9I.js} +1 -1
- package/dist/esm/sdk/{registration-C4sALQZO.js → registration-BFHEYmgh.js} +1 -1
- package/dist/esm/sdk/registration-Cfg9rWhA.js +1 -0
- package/dist/esm/sdk/{registrationAccounts-D4RVetMz.js → registrationAccounts-DP-32yCK.js} +1 -1
- package/dist/esm/sdk/{registrationAuthMethodInput-6ccY2Vuh.js → registrationAuthMethodInput-BBCeWDmw.js} +1 -1
- package/dist/esm/sdk/{registrationIds-CdPqm-Ya.js → registrationIds-ByuReLUc.js} +1 -1
- package/dist/esm/sdk/registrationIntent-BHU5k2Q-.js +1 -0
- package/dist/esm/sdk/{registrationSignerPlan-B9GCvpTV.js → registrationSignerPlan-dY9Rp0m_.js} +1 -1
- package/dist/esm/sdk/{requireStepUpAuth-DCVqmeee.js → requireStepUpAuth-C67sluoC.js} +1 -1
- package/dist/esm/sdk/routerAbNormalSigning-DVKFBYgV.js +1 -0
- package/dist/esm/sdk/{runtime-auth-BKFyLISf.js → runtime-auth-Ch4qvKL2.js} +1 -1
- package/dist/{public/sdk/runtime-device-link-ENxdEXQW.js → esm/sdk/runtime-device-link-DtNpEjq5.js} +1 -1
- package/dist/{public/sdk/runtime-ecdsa-tempo-DhGEb9U7.js → esm/sdk/runtime-ecdsa-tempo-Bntp_Zgx.js} +1 -1
- package/dist/esm/sdk/{runtime-email-otp-dgsP7XZi.js → runtime-email-otp-DEFt-Y-_.js} +1 -1
- package/dist/esm/sdk/{runtime-export-D2RCm5Gk.js → runtime-export-DE_umiS1.js} +1 -1
- package/dist/{public/sdk/runtime-near-Bf-9MFBQ.js → esm/sdk/runtime-near-uXqcLEz8.js} +1 -1
- package/dist/esm/sdk/runtime-preferences-C49p0VLC.js +1 -0
- package/dist/esm/sdk/runtime-recovery-D7wklehP.js +1 -0
- package/dist/esm/sdk/{runtime-recovery-codes-BZMiAR_5.js → runtime-recovery-codes-Dn-NccpU.js} +1 -1
- package/dist/esm/sdk/{sdkSentEvents-D3q1h-Uo.js → sdkSentEvents-DiQ3YVlj.js} +1 -1
- package/dist/esm/sdk/{secp256k1-DSLttQND.js → secp256k1-C-AETUpI.js} +1 -1
- package/dist/esm/sdk/{secureRandomId-BIekT8bE.js → secureRandomId-LwBFx84B.js} +1 -1
- package/dist/esm/sdk/{sessionPolicy-J-RrlPZQ.js → sessionPolicy-CBTZQe1n.js} +1 -1
- package/dist/esm/sdk/shared-D6RYxvYR.js +6 -0
- package/dist/{public/sdk/signEvmFamily-KUNWKVeh.js → esm/sdk/signEvmFamily-DjD3tn8e.js} +1 -1
- package/dist/esm/sdk/{signEvmFamilyWithUiConfirmForTempo-Dc57bJ3V.js → signEvmFamilyWithUiConfirmForTempo-CwRFbaLM.js} +1 -1
- package/dist/esm/sdk/{signEvmWithUiConfirm-CqxL7UbT.js → signEvmWithUiConfirm-BHG0dwVG.js} +1 -1
- package/dist/esm/sdk/signNear-DR50cpes.js +1 -0
- package/dist/esm/sdk/{signatureUses-CjJ233KX.js → signatureUses-8c8Ku_Fw.js} +1 -1
- package/dist/esm/sdk/{signerDomain-vQmlnsbF.js → signerDomain-DqLCvI-D.js} +1 -1
- package/dist/esm/sdk/{signingFlow-vrXxrhlG.js → signingFlow-Mym5j6aw.js} +1 -1
- package/dist/esm/sdk/signingQueue-2pr7lAUS.js +1 -0
- package/dist/esm/sdk/thresholdEcdsa-D-QMyevW.js +1 -0
- package/dist/esm/sdk/{trace-BvbCxdXF.js → trace-QLsbYdld.js} +1 -1
- package/dist/esm/sdk/{transaction-activity-D40ih2j-.js → transaction-activity-Cb2JyYKv.js} +1 -1
- package/dist/{public/sdk/transactionReviewAdmission-C-a3ctCJ.js → esm/sdk/transactionReviewAdmission-CIvR4W5_.js} +1 -1
- package/dist/{public/sdk/transactionState-DVinJk4K.js → esm/sdk/transactionState-CGULLokO.js} +1 -1
- package/dist/esm/sdk/{types-D3GM-uHR.js → types-WGrFMQSw.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-D7ywcIHw.js +1 -0
- package/dist/{public/sdk/walletAuthMethodRecord-CXedSgpV.js → esm/sdk/walletAuthMethodRecord-CnBw27ED.js} +1 -1
- package/dist/esm/sdk/walletAuthority-BWvfaKIX.js +1 -0
- package/dist/esm/sdk/walletCustodyEcdsaContinuity-B8aO2NFb.js +1 -0
- package/dist/esm/sdk/{walletOwnershipGeneration-DoXVMDWe.js → walletOwnershipGeneration-CAycHv-H.js} +1 -1
- package/dist/esm/sdk/walletRecoveryCommit-C3EgMjo-.js +1 -0
- package/dist/esm/sdk/walletRecoveryRotate-D_1a8Agl.js +1 -0
- package/dist/esm/sdk/walletRegistrationSetupPrewarm-B9kpnrbK.js +1 -0
- package/dist/esm/sdk/walletSessionAuthorizationStatus-BLyzJbU8.js +1 -0
- package/dist/esm/sdk/{walletSessionAuthorizationStore-gEYPmu-G.js → walletSessionAuthorizationStore-BiKGIBWQ.js} +1 -1
- package/dist/esm/sdk/warmSessionHydration-B7-kCnJh.js +1 -0
- package/dist/esm/sdk/{webauthnP256-BEz4DEAs.js → webauthnP256-DZCusNY9.js} +1 -1
- package/dist/{public/sdk/webauthnPromptCoordinator-BEudHQBr.js → esm/sdk/webauthnPromptCoordinator-CS4Xc_jZ.js} +1 -1
- package/dist/public/headers.manifest.json +1 -1
- package/dist/public/sdk/{ConfirmationDrawer-DY0_yeUV.js → ConfirmationDrawer-Frj3uEee.js} +1 -1
- package/dist/{esm/sdk/NonceCoordinator-CFFq8-Q9.js → public/sdk/NonceCoordinator-S5ZbrkDp.js} +1 -1
- package/dist/{esm/sdk/accountLifecycle-CAMVowDl.js → public/sdk/accountLifecycle-HEUmDLus.js} +1 -1
- package/dist/public/sdk/activeWalletSession-WdZkhtBB.js +1 -0
- package/dist/public/sdk/{adapters-DdDOQzl4.js → adapters-DYPu0nK9.js} +2 -2
- package/dist/public/sdk/{canonicalPrimitives-CKPGgpxg.js → canonicalPrimitives-Dsbsxgxc.js} +1 -1
- package/dist/public/sdk/{capabilityKinds-CKQ4Uqnv.js → capabilityKinds-N8xo_IEh.js} +1 -1
- package/dist/public/sdk/{chains-CiYQT1K4.js → chains-C_X_fNuS.js} +1 -1
- package/dist/public/sdk/challengeDelivery-5lIu9spR.js +1 -0
- package/dist/{esm/sdk/clientSessionPersistenceState-CImFWDj6.js → public/sdk/clientSessionPersistenceState-DRdve9rC.js} +1 -1
- package/dist/public/sdk/{commitQueue-iBNUt9Bz.js → commitQueue-qjvY_zWn.js} +1 -1
- package/dist/public/sdk/{configHelpers-D8Ivi6p8.js → configHelpers-B-hs0mTO.js} +1 -1
- package/dist/public/sdk/digestEncoding-CkUc5vtR.js +1 -0
- package/dist/public/sdk/{display-ClqZq-Xt.js → display-DjoWrSgE.js} +1 -1
- package/dist/public/sdk/domainIds-BzkGsRqO.js +1 -0
- package/dist/{esm/sdk/ecdsaCapabilityManifest-BlzJAQF8.js → public/sdk/ecdsaCapabilityManifest-ChszYCC0.js} +1 -1
- package/dist/public/sdk/{ecdsaChainTarget-C8ZtMZ8l.js → ecdsaChainTarget-DJBXHzbH.js} +1 -1
- package/dist/{esm/sdk/ecdsaDerivationClientWasm-CVeNEou2.js → public/sdk/ecdsaDerivationClientWasm-CpH-b3jx.js} +1 -1
- package/dist/{esm/sdk/ecdsaDerivationExport-BZFHSMCv.js → public/sdk/ecdsaDerivationExport-C1cE5m0t.js} +1 -1
- package/dist/public/sdk/{ecdsaWalletRecords-D4WeYc7H.js → ecdsaWalletRecords-Di_NUxD_.js} +1 -1
- package/dist/public/sdk/emailOtpEcdsaDerivationIdentity-p0C1CQva.js +1 -0
- package/dist/public/sdk/{enrichDisplayModelWithAbi-69bNckvi.js → enrichDisplayModelWithAbi-DZIhvE-x.js} +1 -1
- package/dist/public/sdk/{evmCryptoWasm-BXsIyRon.js → evmCryptoWasm-DeobzyP-.js} +1 -1
- package/dist/{esm/sdk/export-viewer-host-CsFeiIhd.js → public/sdk/export-viewer-host-DUMwD6zP.js} +1 -1
- package/dist/{esm/sdk/exportKeypairOperation-DGQIYML3.js → public/sdk/exportKeypairOperation-DYCzCbqL.js} +1 -1
- package/dist/public/sdk/{helpers-Ddy72ULN.js → helpers-BnkILY2_.js} +1 -1
- package/dist/public/sdk/host-h55onlkx.js +1 -0
- package/dist/public/sdk/{intentDigest-CE-tLw87.js → intentDigest-DJBrMyLJ.js} +1 -1
- package/dist/public/sdk/{lanes-DnBwWv4l.js → lanes-Ck81oEGv.js} +1 -1
- package/dist/public/sdk/{localOnly-ClCo6602.js → localOnly-KvZeKkH5.js} +1 -1
- package/dist/{esm/sdk/messages-vxz27Way.js → public/sdk/messages-DgJlG9NU.js} +1 -1
- package/dist/public/sdk/{mountExportPrivateKeySurface-CBZ0wRYj.js → mountExportPrivateKeySurface-B4gH1Sel.js} +1 -1
- package/dist/{esm/sdk/mountRecoveryCodeBackupSurface-B1qhFF6G.js → public/sdk/mountRecoveryCodeBackupSurface-BA2ttbTM.js} +1 -1
- package/dist/public/sdk/nearEd25519YaoMaterialActivation-CvDs4RtV.js +1 -0
- package/dist/public/sdk/{nearEd25519YaoSigningPreparation-B0d1AG3u.js → nearEd25519YaoSigningPreparation-Eiq_ikXk.js} +1 -1
- package/dist/public/sdk/{nonceLaneKeys-Fkvk2UPy.js → nonceLaneKeys-Do5Vs-De.js} +1 -1
- package/dist/public/sdk/{normalization-DCvuCvh0.js → normalization-DJPmcXTg.js} +1 -1
- package/dist/public/sdk/{operationFingerprint-CTR9G1NT.js → operationFingerprint-CUrnoh-M.js} +1 -1
- package/dist/public/sdk/passkey-custody-Cd_yyoRa.js +1 -0
- package/dist/public/sdk/{pendingWalletRecoveryCodeBackup-yJN8VAHn.js → pendingWalletRecoveryCodeBackup-BkIrbd6Q.js} +1 -1
- package/dist/public/sdk/presignaturePool-CLHu7HaU.js +1 -0
- package/dist/public/sdk/{prfCache-BMpqZZ-v.js → prfCache-DCkuB8Lu.js} +1 -1
- package/dist/public/sdk/primitives-CqrjmIAH.js +1 -0
- package/dist/{esm/sdk/recovery-entrypoint-Bl5GgbW9.js → public/sdk/recovery-entrypoint-DoXswV9I.js} +1 -1
- package/dist/public/sdk/{registration-C4sALQZO.js → registration-BFHEYmgh.js} +1 -1
- package/dist/public/sdk/registration-Cfg9rWhA.js +1 -0
- package/dist/public/sdk/{registrationAccounts-D4RVetMz.js → registrationAccounts-DP-32yCK.js} +1 -1
- package/dist/public/sdk/{registrationAuthMethodInput-6ccY2Vuh.js → registrationAuthMethodInput-BBCeWDmw.js} +1 -1
- package/dist/public/sdk/{registrationIds-CdPqm-Ya.js → registrationIds-ByuReLUc.js} +1 -1
- package/dist/public/sdk/registrationIntent-BHU5k2Q-.js +1 -0
- package/dist/public/sdk/{registrationSignerPlan-B9GCvpTV.js → registrationSignerPlan-dY9Rp0m_.js} +1 -1
- package/dist/public/sdk/{requireStepUpAuth-DCVqmeee.js → requireStepUpAuth-C67sluoC.js} +1 -1
- package/dist/public/sdk/routerAbNormalSigning-DVKFBYgV.js +1 -0
- package/dist/public/sdk/{runtime-auth-BKFyLISf.js → runtime-auth-Ch4qvKL2.js} +1 -1
- package/dist/{esm/sdk/runtime-device-link-ENxdEXQW.js → public/sdk/runtime-device-link-DtNpEjq5.js} +1 -1
- package/dist/{esm/sdk/runtime-ecdsa-tempo-DhGEb9U7.js → public/sdk/runtime-ecdsa-tempo-Bntp_Zgx.js} +1 -1
- package/dist/public/sdk/{runtime-email-otp-dgsP7XZi.js → runtime-email-otp-DEFt-Y-_.js} +1 -1
- package/dist/public/sdk/{runtime-export-D2RCm5Gk.js → runtime-export-DE_umiS1.js} +1 -1
- package/dist/{esm/sdk/runtime-near-Bf-9MFBQ.js → public/sdk/runtime-near-uXqcLEz8.js} +1 -1
- package/dist/public/sdk/runtime-preferences-C49p0VLC.js +1 -0
- package/dist/public/sdk/runtime-recovery-D7wklehP.js +1 -0
- package/dist/public/sdk/{runtime-recovery-codes-BZMiAR_5.js → runtime-recovery-codes-Dn-NccpU.js} +1 -1
- package/dist/public/sdk/{sdkSentEvents-D3q1h-Uo.js → sdkSentEvents-DiQ3YVlj.js} +1 -1
- package/dist/public/sdk/{secp256k1-DSLttQND.js → secp256k1-C-AETUpI.js} +1 -1
- package/dist/public/sdk/{secureRandomId-BIekT8bE.js → secureRandomId-LwBFx84B.js} +1 -1
- package/dist/public/sdk/{sessionPolicy-J-RrlPZQ.js → sessionPolicy-CBTZQe1n.js} +1 -1
- package/dist/public/sdk/shared-D6RYxvYR.js +6 -0
- package/dist/{esm/sdk/signEvmFamily-KUNWKVeh.js → public/sdk/signEvmFamily-DjD3tn8e.js} +1 -1
- package/dist/public/sdk/{signEvmFamilyWithUiConfirmForTempo-Dc57bJ3V.js → signEvmFamilyWithUiConfirmForTempo-CwRFbaLM.js} +1 -1
- package/dist/public/sdk/{signEvmWithUiConfirm-CqxL7UbT.js → signEvmWithUiConfirm-BHG0dwVG.js} +1 -1
- package/dist/public/sdk/signNear-DR50cpes.js +1 -0
- package/dist/public/sdk/{signatureUses-CjJ233KX.js → signatureUses-8c8Ku_Fw.js} +1 -1
- package/dist/public/sdk/{signerDomain-vQmlnsbF.js → signerDomain-DqLCvI-D.js} +1 -1
- package/dist/public/sdk/{signingFlow-vrXxrhlG.js → signingFlow-Mym5j6aw.js} +1 -1
- package/dist/public/sdk/signingQueue-2pr7lAUS.js +1 -0
- package/dist/public/sdk/thresholdEcdsa-D-QMyevW.js +1 -0
- package/dist/public/sdk/{trace-BvbCxdXF.js → trace-QLsbYdld.js} +1 -1
- package/dist/public/sdk/{transaction-activity-D40ih2j-.js → transaction-activity-Cb2JyYKv.js} +1 -1
- package/dist/{esm/sdk/transactionReviewAdmission-C-a3ctCJ.js → public/sdk/transactionReviewAdmission-CIvR4W5_.js} +1 -1
- package/dist/{esm/sdk/transactionState-DVinJk4K.js → public/sdk/transactionState-CGULLokO.js} +1 -1
- package/dist/public/sdk/{types-D3GM-uHR.js → types-WGrFMQSw.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-D7ywcIHw.js +1 -0
- package/dist/{esm/sdk/walletAuthMethodRecord-CXedSgpV.js → public/sdk/walletAuthMethodRecord-CnBw27ED.js} +1 -1
- package/dist/public/sdk/walletAuthority-BWvfaKIX.js +1 -0
- package/dist/public/sdk/walletCustodyEcdsaContinuity-B8aO2NFb.js +1 -0
- package/dist/public/sdk/{walletOwnershipGeneration-DoXVMDWe.js → walletOwnershipGeneration-CAycHv-H.js} +1 -1
- package/dist/public/sdk/walletRecoveryCommit-C3EgMjo-.js +1 -0
- package/dist/public/sdk/walletRecoveryRotate-D_1a8Agl.js +1 -0
- package/dist/public/sdk/walletRegistrationSetupPrewarm-B9kpnrbK.js +1 -0
- package/dist/public/sdk/walletSessionAuthorizationStatus-BLyzJbU8.js +1 -0
- package/dist/public/sdk/{walletSessionAuthorizationStore-gEYPmu-G.js → walletSessionAuthorizationStore-BiKGIBWQ.js} +1 -1
- package/dist/public/sdk/warmSessionHydration-B7-kCnJh.js +1 -0
- package/dist/public/sdk/{webauthnP256-BEz4DEAs.js → webauthnP256-DZCusNY9.js} +1 -1
- package/dist/{esm/sdk/webauthnPromptCoordinator-BEudHQBr.js → public/sdk/webauthnPromptCoordinator-CS4Xc_jZ.js} +1 -1
- package/dist/public/sdk/workers/shamir3pass_runtime_bg.wasm +0 -0
- package/dist/public/wallet-assets.manifest.json +264 -240
- package/dist/public/wallet-service/index.html +4 -4
- package/dist/types/wallet/src/core/rpcClients/relayer/walletRegistrationSetupPrewarm.d.ts +4 -0
- package/dist/types/wallet/src/core/signingEngine/flows/signNear/shared/signatureOnlySigning.d.ts +2 -2
- package/dist/types/wallet/src/react/components/VoiceAssistantCard.d.ts +38 -0
- package/dist/types/wallet/src/react/components/VoiceAssistantCard.typecheck.d.ts +2 -0
- package/dist/types/wallet/src/react/index.d.ts +5 -1
- package/dist/workers/shamir3pass_runtime_bg.wasm +0 -0
- package/package.json +3 -2
- package/dist/esm/sdk/activeWalletSession-DiZcKjB_.js +0 -1
- package/dist/esm/sdk/challengeDelivery-DxXAkOfS.js +0 -1
- package/dist/esm/sdk/digestEncoding-Dzc1rzWV.js +0 -1
- package/dist/esm/sdk/emailOtpEcdsaDerivationIdentity-B8HzTh4T.js +0 -1
- package/dist/esm/sdk/host-c1__wJwz.js +0 -1
- package/dist/esm/sdk/nearEd25519YaoMaterialActivation-fWQI3rYj.js +0 -1
- package/dist/esm/sdk/normalize-kUDm5zfS.js +0 -1
- package/dist/esm/sdk/passkey-custody-BQj44jEM.js +0 -1
- package/dist/esm/sdk/presignaturePool-DwlTReFO.js +0 -1
- package/dist/esm/sdk/primitives-CAcl7ON7.js +0 -1
- package/dist/esm/sdk/registration-CEqVAgNJ.js +0 -1
- package/dist/esm/sdk/registrationIntent-DOkZcKSP.js +0 -1
- package/dist/esm/sdk/routerAbNormalSigning-BG75eyI2.js +0 -1
- package/dist/esm/sdk/runtime-preferences-LQ8SPE7o.js +0 -1
- package/dist/esm/sdk/runtime-recovery-BuEzJzuZ.js +0 -1
- package/dist/esm/sdk/shared-8ffIBYw2.js +0 -6
- package/dist/esm/sdk/signNear-BhTkDm2-.js +0 -1
- package/dist/esm/sdk/signingQueue-BrGJXBqe.js +0 -1
- package/dist/esm/sdk/thresholdEcdsa-CO7xo1So.js +0 -1
- package/dist/esm/sdk/wallet-recovery-C1kesLCF.js +0 -1
- package/dist/esm/sdk/walletAuthority-B5hXHWpK.js +0 -1
- package/dist/esm/sdk/walletCustodyEcdsaContinuity-abNZ_dvX.js +0 -1
- package/dist/esm/sdk/walletRecoveryCommit-Cc9AqHr0.js +0 -1
- package/dist/esm/sdk/walletRecoveryRotate-DWTAFYiv.js +0 -1
- package/dist/esm/sdk/walletSessionAuthorizationStatus-o1VgsLhA.js +0 -1
- package/dist/esm/sdk/warmSessionHydration-DgjuUacN.js +0 -1
- package/dist/public/sdk/activeWalletSession-DiZcKjB_.js +0 -1
- package/dist/public/sdk/challengeDelivery-DxXAkOfS.js +0 -1
- package/dist/public/sdk/digestEncoding-Dzc1rzWV.js +0 -1
- package/dist/public/sdk/emailOtpEcdsaDerivationIdentity-B8HzTh4T.js +0 -1
- package/dist/public/sdk/host-c1__wJwz.js +0 -1
- package/dist/public/sdk/nearEd25519YaoMaterialActivation-fWQI3rYj.js +0 -1
- package/dist/public/sdk/normalize-kUDm5zfS.js +0 -1
- package/dist/public/sdk/passkey-custody-BQj44jEM.js +0 -1
- package/dist/public/sdk/presignaturePool-DwlTReFO.js +0 -1
- package/dist/public/sdk/primitives-CAcl7ON7.js +0 -1
- package/dist/public/sdk/registration-CEqVAgNJ.js +0 -1
- package/dist/public/sdk/registrationIntent-DOkZcKSP.js +0 -1
- package/dist/public/sdk/routerAbNormalSigning-BG75eyI2.js +0 -1
- package/dist/public/sdk/runtime-preferences-LQ8SPE7o.js +0 -1
- package/dist/public/sdk/runtime-recovery-BuEzJzuZ.js +0 -1
- package/dist/public/sdk/shared-8ffIBYw2.js +0 -6
- package/dist/public/sdk/signNear-BhTkDm2-.js +0 -1
- package/dist/public/sdk/signingQueue-BrGJXBqe.js +0 -1
- package/dist/public/sdk/thresholdEcdsa-CO7xo1So.js +0 -1
- package/dist/public/sdk/wallet-recovery-C1kesLCF.js +0 -1
- package/dist/public/sdk/walletAuthority-B5hXHWpK.js +0 -1
- package/dist/public/sdk/walletCustodyEcdsaContinuity-abNZ_dvX.js +0 -1
- package/dist/public/sdk/walletRecoveryCommit-Cc9AqHr0.js +0 -1
- package/dist/public/sdk/walletRecoveryRotate-DWTAFYiv.js +0 -1
- package/dist/public/sdk/walletSessionAuthorizationStatus-o1VgsLhA.js +0 -1
- package/dist/public/sdk/warmSessionHydration-DgjuUacN.js +0 -1
- /package/dist/esm/sdk/{appearance-ZGVLwA4N.js → appearance-DITtYj-z.js} +0 -0
- /package/dist/esm/sdk/{authenticatorOptions-DMLnDWT2.js → authenticatorOptions-C9aCKgeF.js} +0 -0
- /package/dist/esm/sdk/{authorizationAdmission-Ckx6q6tp.js → authorizationAdmission-CGinGhXH.js} +0 -0
- /package/dist/esm/sdk/{base64-CsEj-_bC.js → base64-DW79QA0h.js} +0 -0
- /package/dist/esm/sdk/{browser-D4wUl_77.js → browser-DkCRXFkk.js} +0 -0
- /package/dist/esm/sdk/{bytes-BBYkulRB.js → bytes-DZRW2UDg.js} +0 -0
- /package/dist/esm/sdk/{canonicalSignerErrorCode-DEHsPxNm.js → canonicalSignerErrorCode-Cz48v4oy.js} +0 -0
- /package/dist/esm/sdk/{configBuilder-ZiZwFKt4.js → configBuilder-BMawmNpz.js} +0 -0
- /package/dist/esm/sdk/{errors-BZO3LF6G.js → errors-DIWY1KR9.js} +0 -0
- /package/dist/esm/sdk/{events-DsQJQ0Cl.js → events-1dzC4Ocx.js} +0 -0
- /package/dist/esm/sdk/{executeWorkerOperation-BInr8RYN.js → executeWorkerOperation-DKCRRq5E.js} +0 -0
- /package/dist/esm/sdk/{jsonRpc-DrCYQIM9.js → jsonRpc-YKL5n8VL.js} +0 -0
- /package/dist/esm/sdk/{jsxRuntime.module-BcZNe_OA.js → jsxRuntime.module-C8JOKu_4.js} +0 -0
- /package/dist/esm/sdk/{keccak-B02Fekdh.js → keccak-BArcwgbj.js} +0 -0
- /package/dist/esm/sdk/{normalization-CpLZcL2f.js → normalization-CeZT7ob0.js} +0 -0
- /package/dist/esm/sdk/{presignatures-DB2IPD-A.js → presignatures-DZm0d6Wy.js} +0 -0
- /package/dist/esm/sdk/{profileAccountProjection-DmmfMood.js → profileAccountProjection-B3LXAUmo.js} +0 -0
- /package/dist/esm/sdk/{promptText-D2f5Rg0h.js → promptText-B8RprJhO.js} +0 -0
- /package/dist/esm/sdk/{signerSlot-Dto7dObP.js → signerSlot-B4Eq8Oe2.js} +0 -0
- /package/dist/esm/sdk/{signingSessionSeal-CDLUmAFY.js → signingSessionSeal-DX41aXUL.js} +0 -0
- /package/dist/esm/sdk/{surface-measurement-reporter-IlPOI3QK.js → surface-measurement-reporter-DvVHPu_O.js} +0 -0
- /package/dist/esm/sdk/{theme-_AUTWLS_.js → theme-BKaFqCAj.js} +0 -0
- /package/dist/esm/sdk/{types-BNUuaUtl.js → types-DhtByIcQ.js} +0 -0
- /package/dist/esm/sdk/{walletIframeIdentity-DJ0KOBHg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
- /package/dist/esm/sdk/{walletSessionAuthorizationProjection-DWBksIJR.js → walletSessionAuthorizationProjection-DuU6w0FP.js} +0 -0
- /package/dist/esm/sdk/{walletSessionFailure-Bu4VPKTz.js → walletSessionFailure-YuhraC3P.js} +0 -0
- /package/dist/public/sdk/{appearance-ZGVLwA4N.js → appearance-DITtYj-z.js} +0 -0
- /package/dist/public/sdk/{authenticatorOptions-DMLnDWT2.js → authenticatorOptions-C9aCKgeF.js} +0 -0
- /package/dist/public/sdk/{authorizationAdmission-Ckx6q6tp.js → authorizationAdmission-CGinGhXH.js} +0 -0
- /package/dist/public/sdk/{base64-CsEj-_bC.js → base64-DW79QA0h.js} +0 -0
- /package/dist/public/sdk/{browser-D4wUl_77.js → browser-DkCRXFkk.js} +0 -0
- /package/dist/public/sdk/{bytes-BBYkulRB.js → bytes-DZRW2UDg.js} +0 -0
- /package/dist/public/sdk/{canonicalSignerErrorCode-DEHsPxNm.js → canonicalSignerErrorCode-Cz48v4oy.js} +0 -0
- /package/dist/public/sdk/{configBuilder-ZiZwFKt4.js → configBuilder-BMawmNpz.js} +0 -0
- /package/dist/public/sdk/{errors-BZO3LF6G.js → errors-DIWY1KR9.js} +0 -0
- /package/dist/public/sdk/{events-DsQJQ0Cl.js → events-1dzC4Ocx.js} +0 -0
- /package/dist/public/sdk/{executeWorkerOperation-BInr8RYN.js → executeWorkerOperation-DKCRRq5E.js} +0 -0
- /package/dist/public/sdk/{jsonRpc-DrCYQIM9.js → jsonRpc-YKL5n8VL.js} +0 -0
- /package/dist/public/sdk/{jsxRuntime.module-BcZNe_OA.js → jsxRuntime.module-C8JOKu_4.js} +0 -0
- /package/dist/public/sdk/{keccak-B02Fekdh.js → keccak-BArcwgbj.js} +0 -0
- /package/dist/public/sdk/{normalization-CpLZcL2f.js → normalization-CeZT7ob0.js} +0 -0
- /package/dist/public/sdk/{presignatures-DB2IPD-A.js → presignatures-DZm0d6Wy.js} +0 -0
- /package/dist/public/sdk/{profileAccountProjection-DmmfMood.js → profileAccountProjection-B3LXAUmo.js} +0 -0
- /package/dist/public/sdk/{promptText-D2f5Rg0h.js → promptText-B8RprJhO.js} +0 -0
- /package/dist/public/sdk/{signerSlot-Dto7dObP.js → signerSlot-B4Eq8Oe2.js} +0 -0
- /package/dist/public/sdk/{signingSessionSeal-CDLUmAFY.js → signingSessionSeal-DX41aXUL.js} +0 -0
- /package/dist/public/sdk/{surface-measurement-reporter-IlPOI3QK.js → surface-measurement-reporter-DvVHPu_O.js} +0 -0
- /package/dist/public/sdk/{theme-_AUTWLS_.js → theme-BKaFqCAj.js} +0 -0
- /package/dist/public/sdk/{types-BNUuaUtl.js → types-DhtByIcQ.js} +0 -0
- /package/dist/public/sdk/{walletIframeIdentity-DJ0KOBHg.js → walletIframeIdentity-Cz82I_Uh.js} +0 -0
- /package/dist/public/sdk/{walletSessionAuthorizationProjection-DWBksIJR.js → walletSessionAuthorizationProjection-DuU6w0FP.js} +0 -0
- /package/dist/public/sdk/{walletSessionFailure-Bu4VPKTz.js → walletSessionFailure-YuhraC3P.js} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-dVx5-UGu.js";import{c as t,f as n,j as r,l as i}from"./normalize-kUDm5zfS.js";import{C as a,S as o,a as s,c,h as l,k as u,m as d,s as f,u as p,x as m}from"./chains-CiYQT1K4.js";import{i as h,n as g,r as _,t as v}from"./base64-CsEj-_bC.js";import{n as y,r as b}from"./secureRandomId-BIekT8bE.js";import{w as x}from"./primitives-CAcl7ON7.js";import{o as S}from"./sessionPolicy-J-RrlPZQ.js";import{o as ee}from"./signingSessionSeal-CDLUmAFY.js";import{r as te}from"./transactionReviewAdmission-C-a3ctCJ.js";import{i as C,t as ne}from"./activeWalletSession-DiZcKjB_.js";import{c as w,d as T,f as E,h as D,m as O,p as k,s as re}from"./capabilityKinds-CKQ4Uqnv.js";import{r as A}from"./canonicalPrimitives-CKPGgpxg.js";import{t as j}from"./errors-BZO3LF6G.js";import{d as M,p as ie}from"./digestEncoding-Dzc1rzWV.js";import{d as ae,i as N,t as P,u as F}from"./accountIds-BzZs7YoX.js";import{a as oe,c as I}from"./ecdsaChainTarget-C8ZtMZ8l.js";import{n as se,t as ce}from"./signerDomain-vQmlnsbF.js";import{d as le,f as ue,g as de,h as fe,l as pe,m as me,p as he,u as ge}from"./registrationIntent-DOkZcKSP.js";import{Nt as _e,T as ve,i as L,kt as ye}from"./emailOtpEcdsaDerivationIdentity-B8HzTh4T.js";import{t as be}from"./challengeDelivery-DxXAkOfS.js";import{a as R,m as xe,o as z}from"./sdkSentEvents-D3q1h-Uo.js";import{t as Se}from"./signerSlot-Dto7dObP.js";import{t as Ce}from"./jsonRpc-DrCYQIM9.js";import{a as we,c as B,i as V,n as Te,o as Ee,r as H,s as De,t as Oe}from"./types-D3GM-uHR.js";import{p as ke}from"./nonceLaneKeys-Fkvk2UPy.js";import{a as Ae,i as je,l as Me,u as Ne}from"./helpers-Ddy72ULN.js";import{i as Pe,n as Fe}from"./profileAccountProjection-DmmfMood.js";import{b as Ie,s as Le,t as Re}from"./nearEd25519YaoMaterialActivation-fWQI3rYj.js";import{D as ze,T as Be,j as Ve}from"./nearEd25519YaoSigningPreparation-B0d1AG3u.js";import{n as He}from"./lanes-DnBwWv4l.js";import{t as Ue}from"./walletSessionAuthorizationStatus-o1VgsLhA.js";import{n as We,r as Ge,t as Ke}from"./operationFingerprint-CTR9G1NT.js";import{a as U,c as qe,o as Je,s as Ye,t as Xe}from"./trace-BvbCxdXF.js";import{d as Ze,i as Qe,n as $e,o as W,r as et,s as tt,u as nt}from"./intentDigest-CE-tLw87.js";import{n as rt}from"./NonceCoordinator-CFFq8-Q9.js";import{t as it}from"./executeWorkerOperation-BInr8RYN.js";import{a as at,i as ot,o as st,r as ct,t as lt}from"./authorizationAdmission-Ckx6q6tp.js";import{i as ut}from"./walletSessionFailure-Bu4VPKTz.js";import{a as dt,d as ft,i as pt,l as mt,n as ht,p as gt,r as _t,s as vt,u as yt}from"./routerAbNormalSigning-BG75eyI2.js";import{i as bt,n as xt}from"./clientSessionPersistenceState-CImFWDj6.js";import{a as St,i as Ct,r as wt,t as Tt}from"./types-BNUuaUtl.js";import{C as Et,b as Dt,c as Ot,g as kt,h as At,l as jt,n as Mt,o as Nt,s as Pt,t as Ft,u as It,x as Lt}from"./requireStepUpAuth-DCVqmeee.js";import{a as Rt,c as zt,i as Bt,n as Vt,r as Ht,s as Ut,t as Wt}from"./transactionState-DVinJk4K.js";let Gt=function(e){return e[e.SignTransactionsWithActionsSuccess=0]=`SignTransactionsWithActionsSuccess`,e[e.SignNep413MessageSuccess=1]=`SignNep413MessageSuccess`,e[e.SignDelegateActionSuccess=2]=`SignDelegateActionSuccess`,e}({});const Kt={ThresholdEd25519ComputeNep413SigningDigest:`thresholdEd25519ComputeNep413SigningDigest`,ThresholdEd25519ComputeDelegateSigningDigest:`thresholdEd25519ComputeDelegateSigningDigest`,ThresholdEd25519BuildDelegateSigningPayload:`thresholdEd25519BuildDelegateSigningPayload`,ThresholdEd25519FinalizeDelegateFromSignature:`thresholdEd25519FinalizeDelegateFromSignature`,ThresholdEd25519FinalizeNearTxFromSignature:`thresholdEd25519FinalizeNearTxFromSignature`,ThresholdEd25519BuildNearTxUnsignedBorsh:`thresholdEd25519BuildNearTxUnsignedBorsh`,ThresholdEd25519DecodeSignedNearTxBorsh:`thresholdEd25519DecodeSignedNearTxBorsh`},qt={uiMode:`modal`,behavior:`requireClick`,autoProceedDelay:0},Jt=Symbol(`ClientSecretSource`),Yt=Symbol(`EmailOtpWorkerSessionHandle`);function G(e,t){let n=String(e||``).trim();if(!n)throw Error(`[platform] ${t} is required`);return n}function Xt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`[platform] ${t} must be an object`);return e}function Zt(e){return Qt({prfFirstB64u:e.prf.prfFirstB64u,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u})}function Qt(e){return{kind:`webauthn_prf_first`,prfFirstB64u:G(e.prfFirstB64u,`prfFirstB64u`),rpId:e.rpId,credentialIdB64u:G(e.credentialIdB64u,`credentialIdB64u`),[Jt]:`webauthn_prf_first`}}function $t(e){let t=G(e.sessionId,`sessionId`);switch(e.action){case`threshold_ecdsa_bootstrap`:return{kind:`email_otp_worker_session_handle_v1`,sessionId:t,walletId:e.walletId,keyHandle:G(e.keyHandle,`keyHandle`),authSubjectId:e.authSubjectId,action:`threshold_ecdsa_bootstrap`,operation:e.operation,chainTarget:e.chainTarget,[Yt]:`email_otp_worker_session_handle`};case`threshold_ed25519_session`:return{kind:`email_otp_worker_session_handle_v1`,sessionId:t,walletId:e.walletId,rpId:e.rpId,authSubjectId:e.authSubjectId,action:`threshold_ed25519_session`,operation:e.operation,[Yt]:`email_otp_worker_session_handle`};default:{let t=e;throw Error(`[platform] unsupported email OTP worker-issued handle action: ${String(t)}`)}}}function en(e){let t=Xt(e,`email OTP worker-issued session handle`),n=G(String(t.kind||``),`email OTP worker-issued handle kind`);if(n!==`email_otp_worker_session_handle_v1`)throw Error(`[platform] unsupported email OTP worker-issued handle kind: ${n}`);let r=G(String(t.action||``),`email OTP worker-issued handle action`),i=G(String(t.operation||``),`email OTP worker-issued handle operation`);if(i!==`registration`&&i!==`wallet_unlock`&&i!==`sign`&&i!==`export`)throw Error(`[platform] unsupported email OTP worker-issued handle operation: ${i}`);let a=i,o={sessionId:G(String(t.sessionId||``),`email OTP worker-issued handle sessionId`),walletId:I(t.walletId),authSubjectId:L(t.authSubjectId),operation:a};if(r===`threshold_ecdsa_bootstrap`){if(`rpId`in t)throw Error(`[platform] email OTP ECDSA worker-issued handles cannot include rpId`);if(a===`registration`)throw Error(`[platform] registration Email OTP ECDSA worker-issued handles are retired`);let e=oe(Xt(t.chainTarget,`email OTP worker-issued handle chainTarget`));if(`evmFamilySigningKeySlotId`in t)throw Error(`[platform] runtime Email OTP ECDSA handles cannot include evmFamilySigningKeySlotId`);return $t({...o,action:r,operation:a,keyHandle:G(String(t.keyHandle||``),`email OTP worker-issued handle keyHandle`),chainTarget:e})}if(r===`threshold_ed25519_session`){if(`chainTarget`in t)throw Error(`[platform] email OTP Ed25519 worker-issued handles cannot include chainTarget`);if(`evmFamilySigningKeySlotId`in t||`keyHandle`in t)throw Error(`[platform] email OTP Ed25519 worker-issued handles cannot include ECDSA key identity`);return $t({...o,action:r,rpId:ve(t.rpId)})}throw Error(`[platform] unsupported email OTP worker-issued handle action: ${r}`)}function tn(e){return e.action===`threshold_ecdsa_bootstrap`&&e.operation===`export`}function nn(e){let t=en(e);if(!tn(t))throw Error(`[platform] Email OTP ECDSA export requires an export worker handle`);return t}const rn=15e3;function an(e){e.abort(`timeout`)}function on(e,t){let n=String(e??``).trim();if(!n)throw Error(`[threshold-ed25519] ${t} is required`);return n}function sn(e){let t=on(Me(e.credential),`prfFirstB64u`);return{ok:!0,operation:`get_passkey`,requirePrfFirst:!0,credential:e.credential,credentialIdB64u:on(e.credential.rawId||e.credential.id,`credentialIdB64u`),rawIdB64u:String(e.credential.rawId||``).trim(),rpId:ve(e.rpId),prf:{kind:`required`,prfFirstB64u:t}}}function cn(e){return{kind:`webauthn_prf_first_credential`,credential:e.credential,secretSource:Zt(sn(e))}}function ln(e){return e.policySecretSource.secretSource.prfFirstB64u}function un(e){if(typeof e!=`string`)return null;let t=Date.parse(e);return Number.isSafeInteger(t)&&t>Date.now()?t:null}function dn(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}async function fn(e){let n=i(t(e.relayerUrl));if(!n)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Wallet Session mint`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Wallet Session mint`};let o=Ne(e.auth.policySecretSource.credential),s=new AbortController,c=null;try{let t=`${n}${ee}`,i=e.existingOperationCredential,l=String(e.publishableKey||``).trim()||void 0,u=i?.token||l,d=!i&&l&&String(e.projectEnvironmentId||``).trim()||void 0;c=setTimeout(an,rn,s);let f=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...u?{Authorization:`Bearer ${u}`}:{}},credentials:`omit`,signal:s.signal,body:JSON.stringify({sessionKind:e.sessionKind,relayerKeyId:e.relayerKeyId,sessionPolicy:e.sessionPolicy,...d?{projectEnvironmentId:d}:{},walletSessionTarget:{kind:`new_wallet_session`},...o?{webauthn_authentication:o}:{}})}),p;try{let e=await f.json();p=a(e)?e:{}}catch(e){if(s.signal.aborted)throw e;p={}}if(!f.ok)return Le(p)||{ok:!1,code:typeof p.code==`string`?p.code:`http_error`,message:typeof p.message==`string`?p.message:`HTTP ${f.status}`};let m=Le(p);if(m)return m;if(p.ok!==!0)return{ok:!1,code:typeof p.code==`string`?p.code:`invalid_response`,message:typeof p.message==`string`?p.message:`Wallet Session mint returned an unsuccessful response`};let h=r(p.thresholdSessionId);if(!h.ok)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned an invalid thresholdSessionId`};let g=D(p.walletSessionId),_=O(p.authorizationId),v=T(p.quotaId);if(!g.ok||!_.ok||!v.ok)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned invalid authorization identity`};let y=un(p.expiresAt),b=dn(p.remainingUses),x=S(p.runtimePolicyScope);if(!y||!b||!x)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned invalid lifecycle or policy data`};let te={ok:!0,thresholdSessionId:h.value,walletSessionId:g.value,authorizationId:_.value,quotaId:v.value,expiresAtMs:y,remainingUses:b,runtimePolicyScope:x};if(p.sessionKind===`issued_exact_wallet_session`){let e;try{e=C(p.operationCredential)}catch(e){return{ok:!1,code:`invalid_response`,message:j(e)||`Wallet Session mint returned an invalid operation credential`}}return e.walletSessionId===g.value?{...te,sessionKind:p.sessionKind,operationCredential:e}:{ok:!1,code:`invalid_response`,message:`Wallet Session mint credential does not identify its session`}}return p.sessionKind!==`already_committed_exact_wallet_session`||p.operationCredential!==void 0?{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned an invalid session branch`}:i?i.walletSessionId===g.value?{...te,sessionKind:p.sessionKind}:{ok:!1,code:`invalid_response`,message:`Reused Wallet Session mint returned another lifecycle identity`}:{ok:!1,code:`invalid_response`,message:`Reused Wallet Session mint requires the credential the caller already holds`}}catch(e){let t=j(e)||`Failed to mint threshold session`,n=s.signal.aborted;return{ok:!1,code:n?`timeout`:`network_error`,message:n?`Wallet Session mint timed out after ${rn}ms`:t}}finally{c!==null&&clearTimeout(c)}}function pn(e){switch(e.kind){case`passkey`:return{kind:`passkey`,authority:e.authority,webauthn_authentication:Ne(e.credential)};case`email_otp`:return{kind:`email_otp`,authority_ref:e.authorityRef,provider_subject_id:on(e.providerSubjectId,`providerSubjectId`),challenge_id:on(e.challengeId,`challengeId`),otp_code:on(e.otpCode,`otpCode`)};default:throw Error(`[threshold-ed25519] unsupported operation step-up proof`)}}function mn(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`[threshold-ed25519] ${t} must be an object`);return e}function hn(e,t,n){let r=Object.keys(e).sort(),i=[...t].sort();if(r.length!==i.length)throw Error(`[threshold-ed25519] ${n} contains unexpected fields`);for(let e=0;e<r.length;e+=1)if(r[e]!==i[e])throw Error(`[threshold-ed25519] ${n} contains unexpected fields`)}function gn(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`[threshold-ed25519] ${t} must be a non-empty normalized string`);return e}function _n(e){switch(e.proof.kind){case`passkey`:if(e.materialRecovery.kind!==`not_requested`)throw Error(`[threshold-ed25519] passkey operation step-up cannot request material recovery`);return{kind:`not_requested`};case`email_otp`:switch(e.materialRecovery.kind){case`not_requested`:return{kind:`not_requested`};case`email_otp_factor_release_v1`:return{kind:`email_otp_factor_release_v1`,workerEphemeralPublicKey65B64u:gn(e.materialRecovery.workerEphemeralPublicKey65B64u,`workerEphemeralPublicKey65B64u`)};default:throw e.materialRecovery,Error(`[threshold-ed25519] unsupported material recovery request`)}default:throw e.proof,Error(`[threshold-ed25519] unsupported operation step-up proof`)}}function vn(e){let t=mn(e.value,`operation step-up material recovery`);switch(t.kind){case`not_requested`:if(hn(t,[`kind`],`operation step-up material recovery`),e.requested.kind!==`not_requested`)throw Error(`[threshold-ed25519] operation step-up material recovery response does not match the request`);return{kind:`not_requested`};case`email_otp_factor_release_v1`:if(hn(t,[`kind`,`challengeId`,`enrollmentId`,`enrollmentSealKeyVersion`,`serverEphemeralPublicKey65B64u`,`nonce12B64u`,`ciphertextB64u`],`operation step-up material recovery`),e.requested.kind!==`email_otp_factor_release_v1`)throw Error(`[threshold-ed25519] operation step-up material recovery response does not match the request`);return{kind:`email_otp_factor_release_v1`,challengeId:gn(t.challengeId,`materialRecovery.challengeId`),enrollmentId:gn(t.enrollmentId,`materialRecovery.enrollmentId`),enrollmentSealKeyVersion:gn(t.enrollmentSealKeyVersion,`materialRecovery.enrollmentSealKeyVersion`),serverEphemeralPublicKey65B64u:gn(t.serverEphemeralPublicKey65B64u,`materialRecovery.serverEphemeralPublicKey65B64u`),nonce12B64u:gn(t.nonce12B64u,`materialRecovery.nonce12B64u`),ciphertextB64u:gn(t.ciphertextB64u,`materialRecovery.ciphertextB64u`)};default:throw Error(`[threshold-ed25519] operation step-up material recovery kind is invalid`)}}function yn(e){let t=mn(e.body,`operation step-up response`);if(hn(t,[`ok`,`kind`,`authorization`,`expiresAtMs`,`materialRecovery`],`operation step-up response`),t.ok!==!0||t.kind!==`verified_step_up`)throw Error(`[threshold-ed25519] operation step-up response kind is invalid`);let n=mn(t.authorization,`operation step-up authorization`);if(hn(n,[`kind`,`evidence_set_digest`],`operation step-up authorization`),n.kind!==`operation_step_up`)throw Error(`[threshold-ed25519] operation step-up authorization marker is invalid`);let r=gn(n.evidence_set_digest,`operation step-up authorization.evidence_set_digest`);if(A(r),typeof t.expiresAtMs!=`number`||!Number.isSafeInteger(t.expiresAtMs)||t.expiresAtMs<=Date.now())throw Error(`[threshold-ed25519] operation step-up expiry is invalid`);return{kind:`verified_step_up`,authorization:{kind:`operation_step_up`,evidence_set_digest:r},expiresAtMs:t.expiresAtMs,materialRecovery:vn({value:t.materialRecovery,requested:e.requestedMaterialRecovery})}}async function bn(e){let n=i(t(e.relayerUrl));if(!n)throw Error(`[threshold-ed25519] operation step-up relayerUrl is required`);let r=_n(e),a=e.credential.kind===`wallet_session_opaque`?{token:e.credential.walletSessionToken,home:e.credential.home}:null,o=M({...a?{headers:ie(a)}:{},body:{kind:`router_ab_ed25519_yao_operation_step_up_grant_v1`,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:pn(e.proof),materialRecovery:r.kind===`email_otp_factor_release_v1`?{kind:r.kind,worker_ephemeral_public_key_65_b64u:r.workerEphemeralPublicKey65B64u}:r}}),s=await fetch(`${n}${ee}`,{...o}),c=await s.json().catch(()=>({}));if(!s.ok){let e=c&&typeof c==`object`&&!Array.isArray(c)?c:{};throw Error(`[threshold-ed25519] operation step-up failed: ${String(e.message||`HTTP ${s.status}`)}`)}return yn({body:c,requestedMaterialRecovery:r})}function xn(e){let t=e.lane,r=e.readiness;if(t.curve!==r.curve)throw Error(`[SigningSession] planner lane and readiness curves do not match`);if(t.curve===`ecdsa`&&r.curve===`ecdsa`){let e=t.authorization,i=r.authorization,a=e.session,o=i.session;if(!n(t.materialActivation,r.materialActivation)||e.selectedAuthority.authorityId!==i.selectedAuthority.authorityId||e.selectedAuthMethod.kind!==i.selectedAuthMethod.kind||e.selectedAuthMethod.walletAuthMethodId!==i.selectedAuthMethod.walletAuthMethodId||a.walletId!==o.walletId||a.authorityId!==o.authorityId||a.authMethodId!==o.authMethodId||a.authorizationId!==o.authorizationId||a.quotaId!==o.quotaId||a.authorityDigestB64u!==o.authorityDigestB64u||a.authorityRevocationEpoch!==o.authorityRevocationEpoch||e.operationCredential.walletSessionId!==i.operationCredential.walletSessionId||e.operationCredential.token!==i.operationCredential.token)throw Error(`[SigningSession] planner ECDSA readiness authority does not match its lane`)}let i=Cn(e);if(i)return{kind:V.NotReady,lane:t,reason:i};let a=e.forceFreshAuth||e.sensitiveOperationPolicy===`require_fresh_same_method`||t.retention===`single_use`;if(r.status===`ready`&&!a){if(t.curve===`ed25519`&&r.curve===`ed25519`)return{kind:V.WarmSession,lane:t,keyRef:{kind:Oe.Cached,curve:`ed25519`,thresholdSessionId:r.thresholdSessionId}};if(t.curve!==`ecdsa`||r.curve!==`ecdsa`)throw Error(`[SigningSession] planner lane and readiness curves do not match`);return{kind:V.WarmSession,lane:t,keyRef:{kind:Oe.Cached,curve:`ecdsa`,materialActivation:r.materialActivation,authorization:r.authorization}}}if(r.status===`auth_unavailable`||r.status===`status_unavailable`||r.status===`status_unknown`)return{kind:V.NotReady,lane:t,reason:r.status};if(B(t.auth)===`email_otp`)return{kind:V.EmailOtpReauth,lane:t,challenge:{chainFamily:t.chainFamily,lane:t}};if(t.curve===`ed25519`&&r.curve===`ed25519`)return{kind:V.PasskeyReauth,lane:t,reconnect:{lane:t,curve:`ed25519`,thresholdSessionId:r.thresholdSessionId}};if(t.curve!==`ecdsa`||r.curve!==`ecdsa`)throw Error(`[SigningSession] planner lane and readiness curves do not match`);return{kind:V.PasskeyReauth,lane:t,reconnect:{lane:t,curve:`ecdsa`,materialActivation:r.materialActivation,authorization:r.authorization}}}function Sn(e,t){return{event:`signing_planner_decision`,readinessStatus:e.readiness.status,forceFreshAuth:!!e.forceFreshAuth,...e.sensitiveOperationPolicy?{sensitiveOperationPolicy:e.sensitiveOperationPolicy}:{},plan:Ee(t),lane:we(e.lane),...t.kind===V.NotReady?{reason:t.reason}:{}}}function Cn(e){return B(e.lane.auth)===`email_otp`&&(e.sensitiveOperationPolicy===`deny_email_otp`||e.sensitiveOperationPolicy===`require_passkey`)?`policy_blocked`:null}async function wn(e,t){let n=P(e),r=await Fe(t,Pe(n)).catch(()=>null);if(!r?.profileId)throw Error(`No profile/account mapping for account ${n}`);let i=await t.getLastProfileState().catch(()=>null);if(!i?.profileId||i.profileId!==r.profileId)throw Error(`No last user session for account ${n}`);let a=Se(i.activeSignerSlot,{min:1});if(a===null)throw Error(`Invalid last-user signerSlot for account ${n}`);return a}var K=function(e){return e.Query=`query`,e.Send=`send_tx`,e.Block=`block`,e}(K||{}),Tn=class e{constructor(e){this.transaction=e.transaction,this.signature=e.signature,this.borsh_bytes=e.borsh_bytes,e.nonceLease&&(this.nonceLease=e.nonceLease),e.serverDispatch&&(this.serverDispatch=e.serverDispatch)}static fromPlain(t){return new e({transaction:t.transaction,signature:t.signature,borsh_bytes:t.borsh_bytes,...t.nonceLease?{nonceLease:t.nonceLease}:{},...t.serverDispatch?{serverDispatch:t.serverDispatch}:{}})}encode(){return new Uint8Array(this.borsh_bytes).buffer}base64Encode(){return g(this.encode())}};function En(e){if(!e)return null;if(Array.isArray(e))return new Uint8Array(e).buffer;if(ArrayBuffer.isView(e)){let t=e;return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}return e instanceof ArrayBuffer?e:null}function Dn(e){let t=e?.signedTransaction,n=t&&typeof t==`object`?t:e,r=n.base64Encode;if(m(r))return r.call(n);let i=n.encode;if(m(i))return g(i.call(n));let a=En(n.borsh_bytes);if(a)return g(a);let o=En(n.borshBytes);if(o)return g(o);throw Error(`Invalid signed transaction payload: cannot serialize to base64`)}var On=class e{constructor(t){this.rpcUrls=e.normalizeRpcUrls(t)}static normalizeRpcUrls(e){let t=(Array.isArray(e)?e:e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean)).map(e=>{try{return new URL(e).toString()}catch(t){let n=j(t)||`Invalid NEAR RPC URL: ${e}`;throw Error(n)}});if(!t.length)throw Error(`NEAR RPC URL cannot be empty`);return Array.from(new Set(t))}errorFromHttpStatus(e){return Error(`RPC request failed: ${e.status} ${e.statusText}`)}errorFromFailedCall(e,t){return t}sendWithRetry(e){return e()}buildRequestBody(e,t){return JSON.stringify({jsonrpc:`2.0`,id:b(`near-rpc`,32,`NEAR JSON-RPC request IDs`),method:e,params:t})}async postOnce(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:t});if(!n.ok)throw this.errorFromHttpStatus(n);let r=await n.text();if(!r?.trim())throw Error(`Empty response from RPC server`);let i=Ce(JSON.parse(r));if(!i.ok)throw Error(`Invalid NEAR JSON-RPC response: ${i.error}`);return i.value}async requestWithFallback(e){let t;for(let[n,r]of this.rpcUrls.entries())try{let t=await this.postOnce(r,e);return n>0&&console.warn(`[NearClient] RPC succeeded via fallback: ${r}`),t}catch(e){t=e;let i=n<this.rpcUrls.length-1;if(console.warn(`[NearClient] RPC call to ${r} failed${i?`, trying next`:``}: ${j(e)||`RPC request failed`}`),!i)throw e instanceof Error?e:Error(String(e))}throw Error(j(t)||`RPC request failed`)}unwrapRpcResult(e,t){if(e.kind===`failure`)throw this.errorFromRpc(t,e.error);let n=e.result;if(typeof n==`object`&&n&&`error`in n){let e=Reflect.get(n,`error`),r=typeof e==`string`?e:JSON.stringify(e);throw this.errorFromWrappedResult(`${t} Error: ${r}`)}return e.result}async makeRpcCall(e,t,n,r){let i=this.buildRequestBody(e,t);try{let e=await this.requestWithFallback(i);return r(this.unwrapRpcResult(e,n))}catch(e){throw this.errorFromFailedCall(n,e)}}async query(e,t){return this.makeRpcCall(K.Query,e,`Query`,t)}async viewAccessKey(e,t,n){let r={request_type:`view_access_key`,finality:n?.finality||`final`,account_id:e,public_key:t};return this.makeRpcCall(K.Query,r,`View Access Key`,ge)}async viewAccessKeyList(e,t){let n={request_type:`view_access_key_list`,finality:t?.finality||`final`,account_id:e};return this.makeRpcCall(K.Query,n,`View Access Key List`,pe)}async viewAccount(e){let t={request_type:`view_account`,finality:`final`,account_id:e};return this.makeRpcCall(K.Query,t,`View Account`,le)}async viewCode(e,t){let n={request_type:`view_code`,finality:t?.finality||`final`,account_id:e};return v(await this.makeRpcCall(K.Query,n,`View Code`,he))}async viewBlock(e){return this.makeRpcCall(K.Block,e,`View Block`,ue)}async sendTransaction(e,t=`EXECUTED_OPTIMISTIC`){let n={signed_tx_base64:Dn(e),wait_until:t};return this.sendWithRetry(async()=>{let e=await this.makeRpcCall(K.Send,n,`Send Transaction`,fe),t=e.status;if(t&&typeof t==`object`&&`Failure`in t)throw this.errorFromOutcome(`Send Transaction`,e,t.Failure);return e})}async txStatus(e,t){let n={tx_hash:e,sender_account_id:t};return this.makeRpcCall(`EXPERIMENTAL_tx_status`,n,`Tx Status`,fe)}async callFunction(e,t,n,r,i){let a={request_type:`call_function`,...i??{finality:`final`},account_id:e,method_name:t,args_base64:g(new TextEncoder().encode(JSON.stringify(n)).buffer)};return r(de((await this.makeRpcCall(K.Query,a,`View Function`,me)).result))}async view(e){return this.callFunction(e.account,e.method,e.args,e.decodeResult)}async getAccessKeys({account:e,block_id:t}){let n={request_type:`view_access_key_list`,account_id:e,finality:`final`};t&&(n.block_id=t,delete n.finality);let r=await this.makeRpcCall(K.Query,n,`View Access Key List`,pe),i=[],a=[];for(let e of r.keys)e.access_key.permission===`FullAccess`?i.push(e):e.access_key.permission&&typeof e.access_key.permission==`object`&&`FunctionCall`in e.access_key.permission&&a.push(e);return{fullAccessKeys:i,functionCallAccessKeys:a}}};function kn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function An(e){if(!e)return;let t=Object.keys(e);return t.length?t[0]:void 0}var jn=class e extends Error{constructor(e){super(e.message),this.name=e.name||`NearRpcError`,this.code=e.code,this.type=e.type||`Unknown`,this.kind=e.kind,this.index=e.index,this.short=e.short,this.details=e.details,this.operation=e.operation}static fromOutcome(t,n,r){let{message:i,type:a,kind:o,index:s,short:c}=Nn(t,r);return new e({message:i||`${t} failed`,short:c||o||`TxExecutionError`,type:a||`Failure`,kind:o,index:s,name:`TxExecutionFailure`,operation:t,details:{Failure:r,outcome:n}})}static fromRpcError(t,n){let r=n.data,{message:i,type:a,kind:o,index:s,short:c}=Mn(t,r,n.message);return new e({message:i||n.message||`${t} RPC error`,short:c||o||`RPC error`,type:a||`RpcError`,kind:o,index:s,code:typeof n.code==`number`?n.code:void 0,name:n.name||`NearRpcError`,operation:t,details:r})}};function Mn(e,t,n=``){let r=kn(t)?t:void 0,i=kn(r?.TxExecutionError)?r.TxExecutionError:void 0;if(!i){let i=typeof t==`string`&&t.trim()?t.trim():r?JSON.stringify(r):n.trim();return{message:`${e} RPC error${i?`: ${i}`:``}`}}return Pn(e,i)}function Nn(e,t){let n=kn(t)?t:void 0;return n?Pn(e,n):{message:`${e} failed (Unknown Failure)`}}function Pn(e,t){if(kn(t.InvalidTxError)){let n=t.InvalidTxError,r=An(n)||`InvalidTxError`;kn(n.ActionsValidation)&&(r=`ActionsValidation.${An(n.ActionsValidation)}`);let i=r.startsWith(`ActionsValidation.`)?`InvalidTxError: ${r.split(`.`)[1]||`ActionsValidation`}`:`InvalidTxError: ${r}`;return{message:`${e} failed (InvalidTxError: ${r})`,type:`InvalidTxError`,kind:r,short:i}}if(kn(t.ActionError)){let n=t.ActionError,r=typeof n.index==`number`?n.index:void 0,i=An(kn(n.kind)?n.kind:void 0)||`ActionError`,a=typeof r==`number`?` at action ${r}`:``,o=`ActionError: ${i}`;return{message:`${e} failed${a} (ActionError: ${i})`,type:`ActionError`,kind:i,index:r,short:o}}return{message:`${e} failed (TxExecutionError)`,type:`TxExecutionError`,kind:`TxExecutionError`,short:`TxExecutionError`}}var Fn=class e extends Tn{static fromPlain(t){return new e({transaction:t.transaction,signature:t.signature,borsh_bytes:t.borsh_bytes,...t.nonceLease?{nonceLease:t.nonceLease}:{},...t.serverDispatch?{serverDispatch:t.serverDispatch}:{}})}static decode(){throw Error(`SignedTransaction.decode(): borsh deserialization not implemented`)}},In=class extends On{errorFromRpc(e,t){return jn.fromRpcError(e,t)}errorFromWrappedResult(e){return new jn({message:e,short:`RpcError`,type:`RpcError`})}errorFromOutcome(e,t,n){return jn.fromOutcome(e,t,n)}errorFromHttpStatus(e){return e.status===429?Error(`RPC throttled; retry shortly`):super.errorFromHttpStatus(e)}async sendWithRetry(e){let t=null;for(let n=1;n<=5;n++)try{return await e()}catch(e){t=e;let r=j(e);if(!/server error|internal|temporar|timeout|throttl|too many requests|429|unavailable|bad gateway|gateway timeout/i.test(r||``)||n===5)throw e;let i=200*2**(n-1),a=Math.floor(Math.random()*150);await new Promise(e=>setTimeout(e,i+a))}throw t instanceof Error?t:Error(String(t))}};function Ln(e){try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,2)}catch{return String(e)}}function q(e,t,n){let r=String(t??``).trim();if(r)return{label:e,value:r,...typeof n==`string`&&n.trim()?{copyValue:n}:{}}}function Rn(e){switch(e.action_type){case W.Transfer:case W.FunctionCall:return BigInt(e.deposit||`0`);case W.Stake:return BigInt(e.stake||`0`);default:return BigInt(0)}}function zn(e){try{let t=JSON.parse(e)?.permission;if(t===`FullAccess`)return`FullAccess`;if(t&&typeof t==`object`){if(`FullAccess`in t)return`FullAccess`;if(`FunctionCall`in t)return`FunctionCall`}}catch{return`Unknown`}return`Unknown`}function Bn(e){let{action:t,txIndex:n,actionIndex:r,receiverId:i}=e,a=`near.tx.${n}.action.${r}`;switch(t.action_type){case W.CreateAccount:return{id:a,kind:`near.action`,actionType:`createAccount`,label:`Action ${r+1}: CreateAccount`,fields:[q(`Receiver`,i)].filter(Boolean)};case W.Transfer:return{id:a,kind:`near.action`,actionType:`transfer`,label:`Action ${r+1}: Transfer`,fields:[q(`Receiver`,i),q(`Amount (yoctoNEAR)`,t.deposit)].filter(Boolean)};case W.FunctionCall:{let e=String(t.args||``),n=e?[{id:`${a}.args`,kind:`raw.fallback`,label:`Function Arguments`,raw:e}]:[];return{id:a,kind:`near.action`,actionType:`functionCall`,label:`Action ${r+1}: FunctionCall`,fields:[q(`Receiver`,i),q(`Method`,t.method_name),q(`Gas`,t.gas),q(`Deposit (yoctoNEAR)`,t.deposit)].filter(Boolean),...n.length?{children:n}:{}}}case W.Stake:return{id:a,kind:`near.action`,actionType:`stake`,label:`Action ${r+1}: Stake`,fields:[q(`Receiver`,i),q(`Stake (yoctoNEAR)`,t.stake),q(`Validator Key`,t.public_key,t.public_key)].filter(Boolean)};case W.AddKey:return{id:a,kind:`near.action`,actionType:`addKey`,label:`Action ${r+1}: AddKey`,fields:[q(`Receiver`,i),q(`Public Key`,t.public_key,t.public_key),q(`Permission`,zn(t.access_key))].filter(Boolean)};case W.DeleteKey:return{id:a,kind:`near.action`,actionType:`deleteKey`,label:`Action ${r+1}: DeleteKey`,fields:[q(`Receiver`,i),q(`Public Key`,t.public_key,t.public_key)].filter(Boolean)};case W.DeployContract:return{id:a,kind:`near.action`,actionType:`deployContract`,label:`Action ${r+1}: DeployContract`,fields:[q(`Receiver`,i),q(`Code Bytes`,String(t.code?.length??0))].filter(Boolean)};case W.DeployGlobalContract:return{id:a,kind:`near.action`,actionType:`deployGlobalContract`,label:`Action ${r+1}: DeployGlobalContract`,fields:[q(`Receiver`,i),q(`Deploy Mode`,t.deploy_mode),q(`Code Bytes`,String(t.code?.length??0))].filter(Boolean)};case W.UseGlobalContract:return{id:a,kind:`near.action`,actionType:`useGlobalContract`,label:`Action ${r+1}: UseGlobalContract`,fields:[q(`Receiver`,i),q(`By Account`,t.account_id),q(`By Code Hash`,t.code_hash,t.code_hash)].filter(Boolean)};case W.DeleteAccount:return{id:a,kind:`near.action`,actionType:`deleteAccount`,label:`Action ${r+1}: DeleteAccount`,fields:[q(`Receiver`,i),q(`Beneficiary`,t.beneficiary_id)].filter(Boolean)};case W.SignedDelegate:return{id:a,kind:`near.action`,actionType:`signedDelegate`,label:`Action ${r+1}: SignedDelegate`,children:[{id:`${a}.delegate`,kind:`raw.fallback`,label:`Signed Delegate Payload`,raw:Ln(t)}]};default:return{id:a,kind:`raw.fallback`,label:`Action ${r+1}: Unsupported`,raw:Ln(t)}}}function Vn(e,t,n){let r=String(e.receiverId||``).trim()||`(unknown receiver)`,i=Array.isArray(e.actions)?e.actions:[],a=i.reduce((e,t)=>e+Rn(t),BigInt(0)),o=[q(`Receiver`,r),q(`Action Count`,String(i.length)),q(`Attached Value (yoctoNEAR)`,a>0?a.toString():void 0)].filter(Boolean);return{id:`near.tx.${t}`,kind:`generic.contractCall`,label:n>1?`Transaction ${t+1}`:`Transaction`,to:r,value:a>0?a.toString():void 0,fields:o,children:i.map((e,n)=>Bn({action:e,txIndex:t,actionIndex:n,receiverId:r}))}}function Hn(e){let t=Array.isArray(e.txSigningRequests)?e.txSigningRequests:[],n=t.map((e,n)=>Vn(e,n,t.length)),r=t.reduce((e,t)=>e+(Array.isArray(t.actions)?t.actions.reduce((e,t)=>e+Rn(t),BigInt(0)):BigInt(0)),BigInt(0));return{chain:`near`,intentDigest:e.intentDigest,signerAccount:e.signerAccount,title:e.title||`NEAR Transaction`,subtitle:e.subtitle,operations:n,...r>0?{totals:{nativeValue:r.toString(),nativeSymbol:`yoctoNEAR`}}:{}}}function Un(e){let t={id:`near.message`,kind:`near.message`,label:`Message signature`,fields:[q(`Signer`,e.signerAccount,e.signerAccount),q(`Recipient`,e.recipient,e.recipient),{label:`Message`,value:e.message,copyValue:e.message,renderAs:`file-content`,hideChevron:!0}].filter(Boolean)};return{chain:`near`,intentDigest:e.intentDigest,signerAccount:e.signerAccount,title:e.title||`NEP-413 message`,subtitle:e.subtitle,operations:[t]}}function Wn(e){try{return Hn(e)}catch{return{chain:`near`,signerAccount:e.signerAccount,...e.title?{title:e.title}:{},...e.subtitle?{subtitle:e.subtitle}:{},operations:[]}}}async function Gn(e){let t=P(e.nearAccount.accountId),n=Se(e.signerSlot,{min:1});if(n===null)throw Error(`Invalid signerSlot for ${e.operationLabel}: ${e.signerSlot}`);if(e.requestedSignerSlot!==void 0){let t=Se(e.requestedSignerSlot,{min:1});if(t===null||t!==n)throw Error(`Requested signerSlot does not match the selected signing lane for ${e.operationLabel}`)}let r=await e.materialExecutor.resolveSigningKeyMaterial();if(r.nearAccountId!==t||r.signerSlot!==n)throw Error(`[SigningEngine] threshold key material does not match the selected lane`);return{thresholdKeyMaterial:r}}function Kn(e){let t=Jn({nearAccountId:e.nearAccountId,tx:e.transaction,txIndex:0});return{txSigningRequest:t,confirmationTransaction:{receiverId:t.receiverId,actions:t.actions}}}function qn(e){let t=e.delegate.actions.map(nt);t.forEach((e,t)=>{try{Ze(e)}catch(e){throw Error(`Delegate action ${t} validation failed: ${e instanceof Error?e.message:String(e)}`)}});let n={senderId:e.delegate.senderId||e.nearAccountId,receiverId:e.delegate.receiverId,actions:t,nonce:e.delegate.nonce,maxBlockHeight:e.delegate.maxBlockHeight};return{confirmationDelegate:n,workerDelegate:{...n,nonce:e.delegate.nonce.toString(),maxBlockHeight:e.delegate.maxBlockHeight.toString(),publicKey:e.signingPublicKey}}}function Jn(e){let t=String(e.tx?.receiverId||``).trim();if(!t)throw Error(`[SigningEngine] transactions[${e.txIndex}].receiverId is required`);let n=Array.isArray(e.tx?.actions)?e.tx.actions:[];if(n.length===0)throw Error(`[SigningEngine] transactions[${e.txIndex}].actions must be non-empty`);for(let e=0;e<n.length;e++)Ze(n[e]);return{nearAccountId:e.nearAccountId,receiverId:t,actions:n}}async function Yn(e){return $n({kind:`near:transactions_with_actions:planning`,payload:{purpose:`near_transaction`,...er(e),transactions:tr(e.transactions)}})}async function Xn(e){return $n({kind:`near:transactions_with_actions`,payload:{purpose:`near_transaction`,...er(e),transactions:tr(e.transactions),unsignedTransactionBorshB64u:l(e.unsignedTransactionBorshB64u,`unsignedTransactionBorshB64u`),signingDigestB64u:l(e.signingDigestB64u,`signingDigestB64u`)}})}async function Zn(e){return $n({kind:`near:nep413`,payload:{purpose:`nep413_message`,...er(e),message:l(e.message,`message`),recipient:l(e.recipient,`recipient`),nonce:l(e.nonce,`nonce`),callbackUrl:e.callbackUrl}})}async function Qn(e){return $n({kind:`near:delegate_action`,payload:{purpose:`delegate_action`,...er(e),delegate:nr(e.delegate)}})}async function $n(e){return`sha256:${h(await p(c({kind:l(e.kind,`kind`),payload:hr(e.payload)})))}`}function er(e){return{nearAccountId:l(e.nearAccountId,`nearAccountId`),nearNetworkId:l(e.nearNetworkId,`nearNetworkId`),relayerKeyId:l(e.relayerKeyId,`relayerKeyId`),signerPublicKey:l(e.signerPublicKey,`signerPublicKey`)}}function tr(e){if(!Array.isArray(e)||e.length<1)throw Error(`transactions must be a non-empty array`);return e.map((e,t)=>rr(e,`transactions[${t}]`))}function nr(e){return{senderId:l(e.senderId,`delegate.senderId`),receiverId:l(e.receiverId,`delegate.receiverId`),actions:ir(e.actions,`delegate.actions`),nonce:l(e.nonce,`delegate.nonce`),maxBlockHeight:l(e.maxBlockHeight,`delegate.maxBlockHeight`),publicKey:l(e.publicKey,`delegate.publicKey`)}}function rr(e,t){let n=u(e,t);return{nearAccountId:l(n.nearAccountId,`${t}.nearAccountId`),receiverId:l(n.receiverId,`${t}.receiverId`),actions:ir(n.actions,`${t}.actions`)}}function ir(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e.map((e,n)=>ar(e,`${t}[${n}]`))}function ar(e,t){let n=u(e,t),r=l(n.action_type,`${t}.action_type`);switch(r){case`CreateAccount`:return{action_type:r};case`DeployContract`:return{action_type:r,code:ur(n.code,`${t}.code`)};case`FunctionCall`:return{action_type:r,method_name:l(n.method_name,`${t}.method_name`),args:l(n.args,`${t}.args`),gas:l(n.gas,`${t}.gas`),deposit:l(n.deposit,`${t}.deposit`)};case`Transfer`:return{action_type:r,deposit:l(n.deposit,`${t}.deposit`)};case`Stake`:return{action_type:r,stake:l(n.stake,`${t}.stake`),public_key:l(n.public_key,`${t}.public_key`)};case`AddKey`:return{action_type:r,public_key:l(n.public_key,`${t}.public_key`),access_key:l(n.access_key,`${t}.access_key`)};case`DeleteKey`:return{action_type:r,public_key:l(n.public_key,`${t}.public_key`)};case`DeleteAccount`:return{action_type:r,beneficiary_id:l(n.beneficiary_id,`${t}.beneficiary_id`)};case`SignedDelegate`:return{action_type:r,delegate_action:or(n.delegate_action,`${t}.delegate_action`),signature:cr(n.signature,`${t}.signature`)};case`DeployGlobalContract`:return{action_type:r,code:ur(n.code,`${t}.code`),deploy_mode:pr(n.deploy_mode,`${t}.deploy_mode`)};case`UseGlobalContract`:return lr(n,t)}throw Error(`${t}.action_type is unsupported`)}function or(e,t){let n=u(e,t);return{senderId:l(n.senderId,`${t}.senderId`),receiverId:l(n.receiverId,`${t}.receiverId`),actions:ir(n.actions,`${t}.actions`),nonce:fr(n.nonce,`${t}.nonce`),maxBlockHeight:fr(n.maxBlockHeight,`${t}.maxBlockHeight`),publicKey:sr(n.publicKey,`${t}.publicKey`)}}function sr(e,t){let n=u(e,t);return{keyType:dr(n.keyType,`${t}.keyType`),keyData:ur(n.keyData,`${t}.keyData`)}}function cr(e,t){let n=u(e,t);return{keyType:dr(n.keyType,`${t}.keyType`),signatureData:ur(n.signatureData,`${t}.signatureData`)}}function lr(e,t){let n=mr(e.account_id),r=mr(e.code_hash);if(n&&r)throw Error(`${t} requires exactly one of account_id or code_hash`);if(n)return{action_type:`UseGlobalContract`,account_id:n};if(r)return{action_type:`UseGlobalContract`,code_hash:r};throw Error(`${t} requires exactly one of account_id or code_hash`)}function ur(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e.map((e,n)=>{if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`${t}[${n}] must be a byte`);return e})}function dr(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e))throw Error(`${t} must be a safe integer`);return e}function fr(e,t){return typeof e==`bigint`||typeof e==`number`&&Number.isSafeInteger(e)?e:l(e,t)}function pr(e,t){let n=l(e,t);if(n===`CodeHash`||n===`AccountId`)return n;throw Error(`${t} is invalid`)}function mr(e){return String(e||``).trim()||null}function hr(e){if(typeof e==`bigint`)return e.toString(10);if(e instanceof Uint8Array)return{__bytesB64u:h(e)};if(ArrayBuffer.isView(e))return{__bytesB64u:h(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))};if(e instanceof ArrayBuffer)return{__bytesB64u:h(new Uint8Array(e))};if(Array.isArray(e))return e.map(hr);if(!e||typeof e!=`object`)return e;let t={};for(let n of Object.keys(e).sort()){let r=hr(e[n]);r!==void 0&&(t[n]=r)}return t}async function gr(e){if(wt(e.signingAuthPlan)&&!e.emailOtpEd25519StepUp)throw Error(`[SigningEngine][near] Email OTP step-up runner is unavailable`);if(Ct(e.signingAuthPlan)&&!e.passkeyEd25519OperationStepUp)throw Error(`[SigningEngine][near] Passkey operation step-up runner is unavailable`);let t=null,n=await Ft({operation:{kind:`near_ed25519_step_up`,requiredSignatureUses:e.requiredSignatureUses},selectedLane:{authMethod:B(e.signingLaneAuth)},policy:xr(e.signingAuthPlan),methods:{...e.emailOtpEd25519StepUp?{emailOtp:{method:`email_otp`,prepareChallenge:async()=>await e.emailOtpEd25519StepUp.prepare({operationFingerprintDigest:e.operationFingerprintDigest}),...e.emailOtpEd25519StepUp.resend?{resendChallenge:async()=>await e.emailOtpEd25519StepUp.resend({operationFingerprintDigest:e.operationFingerprintDigest})}:{},complete:vr}}:{},passkey:{method:`passkey`,prepare:async()=>{if(!e.passkeyEd25519OperationStepUp)throw Error(`[SigningEngine][near] Passkey operation step-up runner is unavailable`);return t=await e.passkeyEd25519OperationStepUp.prepare(),{}},complete:yr}}}),r=e.signingAuthPlan;if(n.method===`warm_session`){if(!Sr(r))throw Error(`[SigningEngine][near] warm-session step-up requires a warm-session plan`);return{kind:`warm_session`,confirmationAuthPayload:{signingAuthPlan:r}}}if(n.method===`email_otp`){if(!wt(r))throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP plan`);return{kind:`email_otp`,confirmationAuthPayload:{signingAuthPlan:{kind:`emailOtpReauth`,method:`email_otp`,emailOtpPrompt:n.prompt}},emailOtpPrompt:n.prompt}}if(!Ct(r))throw Error(`[SigningEngine][near] passkey step-up requires a passkey plan`);return{kind:`passkey`,confirmationAuthPayload:{signingAuthPlan:r},plannedPasskeyOperationStepUp:br(t)}}function _r(e){switch(e.kind){case`passkey`:return{kind:`passkeyReauth`,method:`passkey`};case`email_otp`:return{kind:`emailOtpReauth`,method:`email_otp`};default:throw Error(`[SigningEngine][near] unsupported material auth requirement`)}}async function vr(){}async function yr(){}function br(e){if(!e)throw Error(`[SigningEngine][near] Passkey operation step-up plan is required`);return e}function xr(e){if(St(e)){if(e.curve!==`ed25519`)throw Error(`[SigningEngine][near] warm-session step-up requires an Ed25519 auth plan`);return{kind:`reuse_warm_session`,authorization:{method:e.method,curve:`ed25519`,thresholdSessionId:e.thresholdSessionId,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses}}}return{kind:`use_selected_lane`}}function Sr(e){return St(e)&&e.curve===`ed25519`}function Cr(e,t,n){try{e?.(xe({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function wr(e,t){let n=Pt(e.signingAuthPlan);if(t.phase===`confirmation.complete`){if(n===`passkey`&&t.status===`succeeded`)return}else if(n!==`passkey`||t.phase!==`auth.passkey.prompt.started`&&t.phase!==`auth.passkey.prompt.succeeded`)return;let r=Nt(t,n);r&&Cr(e.onEvent,e.nearAccountId,{...r,authMethod:n})}function Tr(e){return{kind:`warm_session`,signingAuthPlan:e,thresholdSessionId:e.thresholdSessionId,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses}}function Er(e){if(e.prepared.kind===`warm_session`)return Tr(e.prepared.confirmationAuthPayload.signingAuthPlan);if(e.prepared.kind===`email_otp`)return{kind:`email_otp`,signingAuthPlan:e.prepared.confirmationAuthPayload.signingAuthPlan,challengeId:Or(e.confirmation.emailOtpChallengeId,e.prepared.emailOtpPrompt.challengeId),otpCode:Dr(e.confirmation.otpCode),...e.prepared.emailOtpPrompt.emailHint?{emailHint:e.prepared.emailOtpPrompt.emailHint}:{}};if(!e.confirmation.credential)throw Error(`[SigningEngine] missing WebAuthn credential for NEAR step-up authorization`);return{kind:`passkey`,signingAuthPlan:e.prepared.confirmationAuthPayload.signingAuthPlan,credential:je(e.confirmation.credential),plannedPasskeyOperationStepUp:e.prepared.plannedPasskeyOperationStepUp}}function Dr(e){let t=String(e||``).trim();if(!/^\d{6}$/.test(t))throw Error(`[SigningEngine] missing Email OTP code for NEAR step-up authorization`);return t}function Or(e,t){let n=String(e||t||``).trim();if(!n)throw Error(`[SigningEngine] missing Email OTP challenge id for NEAR step-up authorization`);return n}function kr(e){if(!e||!Array.isArray(e.actions)||e.actions.length===0)throw Error(`[SigningEngine][near] one NEAR transaction with actions is required`);return 1}function Ar(e){throw Error(`[SigningEngine][near] exactly one NEAR transaction is supported per signing operation; received ${e.length}`)}const jr=2e4;async function Mr(e){return zr(await it({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Kt.ThresholdEd25519ComputeNep413SigningDigest,timeoutMs:jr,payload:{message:e.message,recipient:e.recipient,nonce:e.nonce,callbackUrl:e.callbackUrl}}}))}async function Nr(e){return zr(await it({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Kt.ThresholdEd25519ComputeDelegateSigningDigest,timeoutMs:jr,payload:{delegate:e.delegate}}}))}async function Pr(e){return Br(await it({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Kt.ThresholdEd25519BuildDelegateSigningPayload,timeoutMs:jr,payload:{delegate:e.delegate}}}))}async function Fr(e){return Vr(await it({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Kt.ThresholdEd25519FinalizeDelegateFromSignature,timeoutMs:jr,payload:{delegate:e.delegate,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u}}}))}async function Ir(e){let t=Hr(await it({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Kt.ThresholdEd25519BuildNearTxUnsignedBorsh,timeoutMs:jr,payload:{txSigningRequests:[e.txSigningRequest],transactionContext:e.transactionContext}}})),n=t[0];if(!n||t.length!==1)throw Error(`near signer worker returned invalid single-transaction unsigned payload`);return n}async function Lr(e){return Ur(await it({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Kt.ThresholdEd25519FinalizeNearTxFromSignature,timeoutMs:jr,payload:{unsignedTransactionBorshB64u:e.unsignedTransactionBorshB64u,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u,expectedNearAccountId:e.expectedNearAccountId,expectedSignerPublicKey:e.expectedSignerPublicKey}}}))}async function Rr(e){return Wr(await it({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Kt.ThresholdEd25519DecodeSignedNearTxBorsh,timeoutMs:jr,payload:{signedTransactionBorshB64u:e.signedTransactionBorshB64u}}}))}function zr(e){let t=e;if(!t?.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 signing digest result`);return t}function Br(e){let t=e;if(!t?.canonicalDelegateBorshB64u||!t.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 delegate signing payload`);return t}function Vr(e){let t=e;if(!t?.delegateAction||!t.signature||!t.borshBytes)throw Error(`near signer worker returned invalid Ed25519 signed delegate result`);return t}function Hr(e){if(!Array.isArray(e))throw Error(`near signer worker returned invalid Ed25519 unsigned tx result`);return e.map(e=>{let t=e;if(!t?.unsignedTransactionBorshB64u||!t.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 unsigned tx item`);return t})}function Ur(e){let t=e;if(!t?.signedTransactionBorshB64u||!t.transactionHash)throw Error(`near signer worker returned invalid Ed25519 finalized tx result`);return t}function Wr(e){let t=e;if(!t?.signedTransaction?.transaction||!t.signedTransaction.signature||!t.signedTransaction.borshBytes||!t.transactionHash)throw Error(`near signer worker returned invalid Ed25519 signed tx decode result`);return t}function Gr(e,t){return e.request_id===t.request_id&&e.account_id===t.account_id&&e.authorization.kind===t.authorization.kind&&(e.authorization.kind===`reusable_wallet_session`?t.authorization.kind===`reusable_wallet_session`&&e.authorization.wallet_session_id===t.authorization.wallet_session_id:t.authorization.kind===`operation_step_up`)&&e.material_activation.kind===t.material_activation.kind&&e.material_activation.activation_id===t.material_activation.activation_id&&e.material_activation.capability===t.material_activation.capability&&e.material_activation.material_owner===t.material_activation.material_owner&&e.material_activation.key_binding===t.material_activation.key_binding&&e.material_activation.lifecycle_binding===t.material_activation.lifecycle_binding&&e.material_activation.signing_worker===t.material_activation.signing_worker&&e.signing_worker_id===t.signing_worker_id}function Kr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function qr(e){if(!Gr(e.request.scope,e.response.scope))throw Error(`Router A/B normal-signing prepare response scope mismatch`);if(e.request.expires_at_ms!==e.response.expires_at_ms)throw Error(`Router A/B normal-signing prepare response expiry mismatch`);if(e.response.signing_worker.server_id!==e.request.scope.signing_worker_id)throw Error(`Router A/B normal-signing prepare response SigningWorker mismatch`);if(!Kr(e.signingPayloadDigest.bytes,e.response.signing_payload_digest.bytes))throw Error(`Router A/B normal-signing prepare response payload digest mismatch`)}function Jr(e){if(!Gr(e.request.scope,e.response.scope))throw Error(`Router A/B normal-signing response scope mismatch`);if(e.response.signing_worker.server_id!==e.request.scope.signing_worker_id)throw Error(`Router A/B normal-signing response SigningWorker mismatch`);if(!Kr(e.signingPayloadDigest.bytes,e.response.signing_payload_digest.bytes))throw Error(`Router A/B normal-signing response payload digest mismatch`);if(e.response.signature.bytes.length!==64)throw Error(`Router A/B normal-signing response signature must be 64 bytes`)}function J(e,t){let n=String(e||``).trim();if(!n)throw Error(`Router A/B Ed25519 normal-signing ready state is missing ${t}`);return n}function Y(e,t,n){if(e!==t)throw Error(`Router A/B Ed25519 normal-signing ready state ${n} mismatch`)}function Yr(e,t){let n=Math.floor(Number(e));if(!Number.isFinite(n)||n<=Date.now())throw Error(`Router A/B Ed25519 normal-signing ready state ${t} is expired`);return n}function Xr(e,t){let n=Math.floor(Number(e));if(!Number.isSafeInteger(n)||n<=0)throw Error(`Router A/B Ed25519 normal-signing ready state ${t} is exhausted`);return n}function Zr(e){let t=e.state,n=t.signingWalletSession,r=J(e.thresholdSessionId,`thresholdSessionId`),i=J(t.thresholdSessionId,`state.thresholdSessionId`),a=J(t.signingLane.thresholdSessionId,`state.signingLane.thresholdSessionId`);Y(i,r,`thresholdSessionId`),Y(a,r,`lane thresholdSessionId`);let o=J(t.walletSessionId,`state.walletSessionId`),s=J(t.quotaId,`state.quotaId`);Y(t.signingLane.walletSessionId,o,`lane walletSessionId`),Y(t.signingLane.quotaId,s,`lane quotaId`);let c=J(e.nearAccountId,`nearAccountId`);J(t.signingLane.identity.signer.account.wallet.walletId,`state.signingLane.identity.signer.account.wallet.walletId`),Y(J(e.thresholdKeyMaterial.nearAccountId,`thresholdKeyMaterial.nearAccountId`),c,`threshold key accountId`);let l=n.routerAbNormalSigning,u=J(n.auth.walletSessionToken,`Wallet Session bearer token`),d=J(t.signingRootId,`state.signingRootId`),f=J(t.signingRootVersion,`state.signingRootVersion`);Y(n.thresholdSessionId,r,`Wallet Session thresholdSessionId`),Y(n.walletSessionId,o,`Wallet Session walletSessionId`),Y(n.quotaId,s,`Wallet Session quotaId`),Y(n.signingRootId,d,`signingRootId`),Y(n.signingRootVersion,f,`signingRootVersion`),Y(t.routerAbNormalSigning.signingWorkerId,l.signingWorkerId,`signingWorkerId`),Yr(n.expiresAtMs,`expiresAtMs`);let p=Xr(n.remainingUses,`remainingUses`);if(t.remainingUses!==p)throw Error(`Router A/B Ed25519 normal-signing ready state remainingUses mismatch`);return{kind:`router_ab_ed25519_normal_signing_ready_state_v1`,relayerUrl:J(t.relayerUrl,`relayerUrl`),signingWorkerId:J(l.signingWorkerId,`signingWorkerId`),signerPublicKey:J(e.thresholdKeyMaterial.publicKey,`signerPublicKey`),credential:{kind:`wallet_session_opaque`,walletSessionToken:u,home:n.auth.credential.home}}}function Qr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`operation step-up preparation ref must be an object`);let t=e;if(Object.keys(t).length!==3||t.kind!==`near_operation_step_up_prepared_v1`)throw Error(`operation step-up preparation ref is invalid`);let n=String(t.handle||``).trim();if(!n.startsWith(`near-operation-step-up:`)||/\s/.test(n))throw Error(`operation step-up preparation handle is invalid`);return{kind:`near_operation_step_up_prepared_v1`,handle:n,challengeB64u:A(t.challengeB64u)}}const $r=new Map,ei=new Map;function ti(e,t){let n=String(e||``).trim();if(!n)throw Error(`[SigningEngine][near] ${t} is required`);return n}function ni(e){$r.set(ti(e.requestId,`requestId`),e.build)}function ri(e){$r.delete(String(e||``).trim())}const ii={async prepare(e){let t=ti(e.requestId,`requestId`),n=$r.get(t);if(!n)throw Error(`[SigningEngine][near] operation step-up preparation is unavailable`);$r.delete(t);let r=e.kind===`near_transaction`?await n({kind:`near_transaction`,transactionContext:e.transactionContext,operationId:ti(e.operationId,`operationId`),operationFingerprint:ti(e.operationFingerprint,`operationFingerprint`),displayDigest:ti(e.displayDigest,`displayDigest`)}):await n({kind:`near_signature_only`,displayDigest:ti(e.displayDigest,`displayDigest`)}),i=await We(r.envelope),a=Qr({kind:`near_operation_step_up_prepared_v1`,handle:`near-operation-step-up:${y(24,`operation step-up handle`)}`,challengeB64u:i});return ei.set(a.handle,{requestId:t,operation:r.operation}),a},cancel(e){let t=String(e.requestId||``).trim();t&&$r.delete(t),e.handle&&ei.delete(e.handle);for(let[e,n]of ei)n.requestId===t&&ei.delete(e)}};function ai(e){let t=ti(e.requestId,`requestId`),n=ti(Qr(e.ref).handle,`operation step-up handle`),r=ei.get(n);if(ei.delete(n),!r||r.requestId!==t)throw Error(`[SigningEngine][near] prepared operation step-up is unavailable`);return r.operation}function oi(e){if(!n(e.expected,e.actual))throw Error(`[SigningEngine][near] operation assertion changed material activation`)}const si=12e4;async function ci(e){return await e.ctx.resolveOperationStepUpCredential({walletId:e.walletId,relayerUrl:e.relayerUrl,proof:e.proof})}function li(e){if(e.prepared.prepare.request.scope.authorization.kind!==`operation_step_up`)throw Error(`[SigningEngine][near] operation step-up authorization scope is missing`);if(e.issuedAuthorization.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] operation step-up authorization is invalid`)}function ui(e){let t=e.thresholdKeyMaterial.participants.find(t=>t.role===e.role)?.id;if(!t)throw Error(`threshold-ed25519 signing requires ${e.role} participant id`);return t}function di(e){return[..._(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function fi(e){return s(e.chains||gt.network.chains)}function pi(e){let t=globalThis.crypto;if(t&&typeof t.randomUUID==`function`)return`router-ab-normal-signing/${e}/${t.randomUUID()}`;if(t&&typeof t.getRandomValues==`function`){let n=new Uint8Array(16);return t.getRandomValues(n),`router-ab-normal-signing/${e}/${h(n)}`}throw Error(`secure randomness is unavailable for Router A/B normal-signing request id`)}function mi(e){if(!e.ok)throw Error(e.error.message);return e.value}function hi(e){let t=Math.floor(Number(e.walletSessionExpiresAtMs)),n=Math.floor(Number(e.requestedTtlMs));if(!Number.isFinite(t)||t<=Date.now())throw Error(`[SigningEngine][near] Router A/B Ed25519 Wallet Session is expired`);if(!Number.isFinite(n)||n<=0)throw Error(`[SigningEngine][near] Router A/B Ed25519 request TTL is invalid`);return Math.min(t,Date.now()+n)}function gi(e){let t=e.walletSessionState.routerAbNormalSigning;if(!t)return null;let n=String(e.walletId||``).trim();if(!n)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing wallet id`);let r=Re(e.activeClient.metadata());return{request_id:pi(e.operationId),account_id:n,authorization:{kind:`reusable_wallet_session`,wallet_session_id:e.walletSessionState.walletSessionId},material_activation:{kind:`mpc_material_activation_ref`,activation_id:r.activationId,capability:r.capability,material_owner:r.materialOwner,key_binding:r.keyBinding,lifecycle_binding:r.lifecycleBinding,signing_worker:r.signingWorker},signing_worker_id:t.signingWorkerId}}function _i(e){let t=e.materialFacts.routerAbNormalSigning;if(!t)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing`);return{request_id:pi(e.operationId),account_id:String(e.walletId),authorization:{kind:`operation_step_up`},material_activation:{kind:`mpc_material_activation_ref`,activation_id:e.materialActivation.activationId,capability:e.materialActivation.capability,material_owner:e.materialActivation.materialOwner,key_binding:e.materialActivation.keyBinding,lifecycle_binding:e.materialActivation.lifecycleBinding,signing_worker:e.materialActivation.signingWorker},signing_worker_id:t.signingWorkerId}}function vi(e){return e.map(e=>{switch(e.action_type){case`CreateAccount`:return{action_type:W.CreateAccount};case`DeployContract`:return{action_type:W.DeployContract,code:[...e.code]};case`FunctionCall`:return{action_type:W.FunctionCall,method_name:e.method_name,args:e.args,gas:e.gas,deposit:e.deposit};case`Transfer`:return{action_type:W.Transfer,deposit:e.deposit};case`Stake`:return{action_type:W.Stake,stake:e.stake,public_key:e.public_key};case`AddKey`:return{action_type:W.AddKey,public_key:e.public_key,access_key:e.access_key};case`DeleteKey`:return{action_type:W.DeleteKey,public_key:e.public_key};case`DeleteAccount`:return{action_type:W.DeleteAccount,beneficiary_id:e.beneficiary_id};case`SignedDelegate`:{let t=vi(e.delegate_action.actions).map(tt);return{action_type:W.SignedDelegate,delegate_action:{senderId:e.delegate_action.senderId,receiverId:e.delegate_action.receiverId,actions:t,nonce:e.delegate_action.nonce,maxBlockHeight:e.delegate_action.maxBlockHeight,publicKey:{keyType:e.delegate_action.publicKey.keyType,keyData:[...e.delegate_action.publicKey.keyData]}},signature:{keyType:e.signature.keyType,signatureData:[...e.signature.signatureData]}}}case`DeployGlobalContract`:return{action_type:W.DeployGlobalContract,code:[...e.code],deploy_mode:e.deploy_mode};case`UseGlobalContract`:return`account_id`in e?{action_type:W.UseGlobalContract,account_id:e.account_id}:{action_type:W.UseGlobalContract,code_hash:e.code_hash}}})}async function yi(e){return{signedDelegate:await Fr({delegate:e.delegate,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u,workerCtx:e.ctx}),hash:di(e.signingDigestB64u)}}function X(e,t,n){if(String(e)!==String(t))throw Error(`Router A/B Ed25519 active Client ${n} mismatch`)}function bi(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return n===0}function xi(e,t){if(e.length!==32||e.some(e=>!Number.isInteger(e)||e<0||e>255))throw Error(`Router A/B normal-signing ${t} must contain 32 bytes`);return Uint8Array.from(e)}function Si(e){let t=N(e);if(!t.startsWith(`ed25519:`))throw Error(`Router A/B Ed25519 signer public key must use ed25519`);let n=F(t.slice(8));if(n.length!==32)throw Error(`Router A/B Ed25519 signer public key must decode to 32 bytes`);return n}function Ci(e){let t=e.activeClient.metadata(),n=Re(t),r=e.materialFacts.signer,i=ui({thresholdKeyMaterial:e.thresholdKeyMaterial,role:`client`}),a=ui({thresholdKeyMaterial:e.thresholdKeyMaterial,role:`relayer`});if(e.thresholdKeyMaterial.participants.length!==2)throw Error(`Router A/B Ed25519 active Client requires exactly two participants`);X(t.scope.account_id,e.prepare.request.scope.account_id,`scope account`),X(t.scope.threshold_session_id,e.materialFacts.thresholdSessionId,`threshold session`),X(t.scope.account_id,e.walletId,`scope wallet`),X(n.activationId,e.prepare.request.scope.material_activation.activation_id,`material activation`),X(n.capability,e.prepare.request.scope.material_activation.capability,`material capability`),X(n.materialOwner,e.prepare.request.scope.material_activation.material_owner,`material owner`),X(n.keyBinding,e.prepare.request.scope.material_activation.key_binding,`material key binding`),X(n.lifecycleBinding,e.prepare.request.scope.material_activation.lifecycle_binding,`material lifecycle`),X(n.signingWorker,e.prepare.request.scope.material_activation.signing_worker,`material SigningWorker`);let o=e.prepare.request.scope.authorization;if(o.kind!==e.authorization.kind)throw Error(`Router A/B Ed25519 authorization kind mismatch`);switch(e.authorization.kind){case`reusable_wallet_session`:if(o.kind!==`reusable_wallet_session`)throw Error(`Router A/B Ed25519 reusable authorization is missing`);X(o.wallet_session_id,e.authorization.walletSessionId,`authorization session`);break;case`operation_step_up`:if(o.kind!==`operation_step_up`)throw Error(`Router A/B Ed25519 operation step-up authorization is missing`);break;default:e.authorization}X(t.scope.signing_worker_id,e.prepare.request.scope.signing_worker_id,`scope SigningWorker`),X(t.scope.signing_worker_id,e.signingWorkerId,`prepare SigningWorker`),X(t.applicationBinding.wallet_id,e.walletId,`application wallet`),X(t.applicationBinding.wallet_id,r.account.wallet.walletId,`lane wallet`),X(t.applicationBinding.near_ed25519_signing_key_id,r.nearEd25519SigningKeyId,`signing key`),X(t.applicationBinding.signing_root_id,e.materialFacts.signingRootId,`signing root`),X(t.applicationBinding.key_creation_signer_slot,r.signerSlot,`signer slot`),X(t.applicationBinding.key_creation_signer_slot,e.thresholdKeyMaterial.signerSlot,`key-material signer slot`),X(t.participantIds[0],i,`Client participant`),X(t.participantIds[1],a,`SigningWorker participant`);let s=Si(e.thresholdKeyMaterial.publicKey);if(!bi(t.registeredPublicKey,s))throw Error(`Router A/B Ed25519 active Client registered public key mismatch`);if(!bi(t.signingWorkerVerifyingShare,e.signingWorkerVerifyingShare))throw Error(`Router A/B Ed25519 active Client SigningWorker verifying share mismatch`)}async function wi(e){let t=e.prepare.request.intent.operation_id,n=performance.now(),r=`failed`;try{let n=await Ti(e,t);return r=`succeeded`,n}finally{U(t,`signature_total`,n,r)}}async function Ti(e,t){let n=_(e.signingDigestB64u);if(n.length!==32)throw Error(`Router A/B normal-signing ${e.signingPayloadLabel} must be 32 bytes`);let r=xi(e.prepare.admissionMaterial.admittedSigningDigest.bytes,`admitted digest`);if(!bi(n,r))throw Error(`Router A/B normal-signing admitted digest mismatch`);e.authorization===`reusable_wallet_session`&&Zr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial});let i=e.authorization===`reusable_wallet_session`?{thresholdSessionId:e.walletSessionState.thresholdSessionId,signer:e.walletSessionState.signingLane.identity.signer,signingRootId:e.walletSessionState.signingRootId,signingRootVersion:e.walletSessionState.signingRootVersion,routerAbNormalSigning:e.walletSessionState.routerAbNormalSigning,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,relayerUrl:e.walletSessionState.relayerUrl}:e.materialFacts,a=performance.now(),o=e.startedResponse?await e.startedResponse:await mt({relayServerUrl:i.relayerUrl,credential:e.credential,request:e.prepare.request});if(U(t,`prepare`,a),e.authorization===`reusable_wallet_session`){if(o.kind!==`reusable_wallet_session`)throw Error(`Ed25519 prepare returned the wrong authorization kind`);let t=await e.sessionCoordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:e.walletSessionState,nowMs:Date.now()}),n=o.sessionStatus;if(!t||n.walletSessionId!==t.walletSessionOperationCredential.walletSessionId||n.quotaId!==t.walletSessionAuthorization.quotaId||n.quotaLifecycle!==`active`||n.remainingUses<=0||n.expiresAtMs<=Date.now()||!ne(n.authorization,t.walletSessionAuthorization))throw Error(`Wallet Session authority changed before Ed25519 client signing`);let r={relayerUrl:i.relayerUrl,operationCredential:t.walletSessionOperationCredential};await Ue.fromPrepare(r,n).read(r,{walletSessionId:n.walletSessionId,quotaId:n.quotaId})}else if(o.kind!==`operation_step_up`)throw Error(`Ed25519 step-up prepare returned a reusable Wallet Session`);let s=o.signing;qr({request:e.prepare.request,signingPayloadDigest:e.prepare.admissionMaterial.signingPayloadDigest,response:s});let c=_(s.server_verifying_share_b64u);if(c.length!==32)throw Error(`Router A/B normal-signing SigningWorker verifying share must be 32 bytes`);Ci({activeClient:e.activeClient,authorization:e.authorization===`reusable_wallet_session`?{kind:`reusable_wallet_session`,walletSessionId:e.walletSessionState.signingWalletSession.walletSessionId}:{kind:`operation_step_up`},materialFacts:i,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,prepare:e.prepare,signingWorkerId:s.signing_worker.server_id,signingWorkerVerifyingShare:c});let l=performance.now(),u=await e.activeClient.createSigningShare({admittedDigest:r,signingWorkerCommitments:s.server_commitments,signingWorkerVerifyingShare:c});if(U(t,`client_share`,l),u.clientVerifyingShare.length!==32)throw Error(`Router A/B normal-signing Client verifying share must be 32 bytes`);let d=performance.now(),f=await vt({relayServerUrl:i.relayerUrl,credential:e.credential,request:dt({scope:e.prepare.request.scope,expiresAtMs:e.prepare.request.expires_at_ms,prepareResponse:s,admissionMaterial:e.prepare.admissionMaterial,clientCommitments:u.clientCommitments,clientVerifyingShareB64u:h(u.clientVerifyingShare),clientSignatureShareB64u:u.clientSignatureShareB64u})});return U(t,`finalize`,d),Jr({request:e.prepare.request,signingPayloadDigest:e.prepare.admissionMaterial.signingPayloadDigest,response:f}),{signatureB64u:yt(f.signature,`Router A/B normal-signing signature`),signerPublicKey:e.thresholdKeyMaterial.publicKey}}async function Ei(e){let t=fi(e.ctx);return e.intent.kind===`nep413_message_v1`?await pt({scope:e.scope,expiresAtMs:e.expiresAtMs,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:t,message:e.intent.message,recipient:e.intent.recipient,nonce:e.intent.nonce,callbackUrl:e.intent.callbackUrl,expectedSigningDigestB64u:e.signingDigestB64u}):await ht({scope:e.scope,expiresAtMs:e.expiresAtMs,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:t,delegate:{senderId:e.intent.delegate.senderId,receiverId:e.intent.delegate.receiverId,publicKey:e.intent.delegate.publicKey,nonce:e.intent.delegate.nonce,maxBlockHeight:e.intent.delegate.maxBlockHeight,actionFingerprint:await ft(e.intent.delegate.actions),canonicalDelegateBorshB64u:(await Pr({delegate:{senderId:e.intent.delegate.senderId,receiverId:e.intent.delegate.receiverId,actions:vi(e.intent.delegate.actions),nonce:e.intent.delegate.nonce,maxBlockHeight:e.intent.delegate.maxBlockHeight,publicKey:e.intent.delegate.publicKey},workerCtx:e.ctx})).canonicalDelegateBorshB64u},expectedSigningDigestB64u:e.signingDigestB64u})}async function Di(e){let t=_i({materialActivation:e.materialActivation,materialFacts:e.materialFacts,walletId:e.walletId,operationId:e.operationId}),n=await Ei({ctx:e.ctx,thresholdSessionId:e.thresholdSessionId,scope:t,expiresAtMs:Date.now()+si,nearAccountId:e.nearAccountId,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,intent:e.intent}),r=Ke({tenantId:mi(k(e.materialFacts.runtimePolicyScope.orgId)),principalId:mi(E(String(e.walletId))),capabilityId:mi(re(e.materialActivation.capability)),operationId:mi(w(String(e.operationId))),operation:{capabilityKind:`near_ed25519_mpc_signing`,operationKind:e.intent.kind===`nep413_message_v1`?`near.sign_nep413_message`:`near.sign_delegate_action`},digests:{laneDigest:Ge(e.operationFingerprint),intentDigest:A(h(Uint8Array.from(n.admissionMaterial.intentDigest.bytes))),displayDigest:A(e.displayDigest)}});return{operation:{kind:`near_signature_only`,prepare:n,signingDigestB64u:e.signingDigestB64u,materialActivation:e.materialActivation},envelope:r}}function Oi(e){if(e.auth.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP auth binding`);let t=e.preparation.hydration.authority;if(!t||String(t.walletId)!==String(e.walletId))throw Error(`[SigningEngine][near] Email OTP material authority changed`);return{kind:`email_otp`,authorityRef:t,providerSubjectId:e.auth.providerSubjectId,challengeId:e.challengeId,otpCode:e.otpCode}}function ki(e){switch(e.authorization.kind){case`passkey`:return{kind:`passkey`,authority:e.authorization.plannedPasskeyOperationStepUp.authority,credential:e.authorization.credential};case`email_otp`:return Oi({preparation:e.preparation,auth:Ai(e.auth),walletId:e.walletId,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode});default:throw e.authorization,Error(`[SigningEngine][near] unsupported operation step-up authorization`)}}function Ai(e){if(e.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP auth binding`);return e}function ji(e){if(!e)throw Error(`[SigningEngine][near] operation step-up proof is missing`);return e}function Mi(e){return e.authorization.kind===`operation_step_up`}async function Ni(e){if(e.issuedAuthorization)return e.issuedAuthorization;switch(e.proof.kind){case`passkey`:return await bn({relayerUrl:e.relayerUrl,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof,credential:e.credential,materialRecovery:{kind:`not_requested`}});case`email_otp`:return await bn({relayerUrl:e.relayerUrl,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof,credential:e.credential,materialRecovery:{kind:`not_requested`}});default:throw e.proof,Error(`[SigningEngine][near] unsupported operation step-up proof`)}}async function Pi(e){if(Mi(e)){let t=Re(e.activeClient.metadata());if(oi({expected:e.authorization.prepared.materialActivation,actual:t}),e.authorization.prepared.signingDigestB64u!==e.signingDigestB64u)throw Error(`[SigningEngine][near] signature-only operation digest changed`);let n=e.authorization.prepared.prepare,r=await ci({ctx:e.ctx,walletId:e.walletId,relayerUrl:e.materialFacts.relayerUrl,proof:e.authorization.proof}),i=await Ni({issuedAuthorization:e.authorization.issuedAuthorization,relayerUrl:e.materialFacts.relayerUrl,normalSigningRequest:n.request,displayDigest:e.displayDigest,proof:e.authorization.proof,credential:r});if(n.request.scope.authorization.kind!==`operation_step_up`||i.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] issued operation step-up evidence changed identity`);return{kind:`router_ab_ed25519_signature_only_normal_signing_result_v1`,authorization:`operation_step_up`,issuedAuthorization:i,...await wi({thresholdSessionId:e.thresholdSessionId,materialFacts:e.materialFacts,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:e.signingDigestB64u,signingPayloadLabel:`signature-only payload digest`,prepare:n,credential:r,authorization:`operation_step_up`})}}let t=e.startedPrepare&&e.startedPrepare.displayDigest===e.displayDigest&&e.startedPrepare.signingDigestB64u===e.signingDigestB64u?e.startedPrepare:null;e.startedPrepare&&!t&&Li(e.startedPrepare);let n=t?.prepare??await Fi(e);return n?{kind:`router_ab_ed25519_signature_only_normal_signing_result_v1`,authorization:`reusable_wallet_session`,...await wi({thresholdSessionId:e.thresholdSessionId,walletSessionState:e.walletSessionState,sessionCoordinator:e.sessionCoordinator,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:e.signingDigestB64u,signingPayloadLabel:`signature-only payload digest`,prepare:n,startedResponse:t?.response,credential:Zr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}).credential,authorization:e.authorization.kind})}:null}async function Fi(e){let t=gi({activeClient:e.activeClient,walletSessionState:e.walletSessionState,walletId:e.walletId,operationId:e.operationId});return t?await Ei({ctx:e.ctx,thresholdSessionId:e.thresholdSessionId,scope:t,expiresAtMs:hi({walletSessionExpiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs,requestedTtlMs:si}),nearAccountId:e.nearAccountId,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,intent:e.intent}):null}async function Ii(e){let t=await Fi(e);if(!t)return null;let n=Zr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}),r=performance.now(),i=mt({relayServerUrl:e.walletSessionState.relayerUrl,credential:n.credential,request:t.request});return i.catch(()=>{}),U(String(e.operationId),`prepare_sent`,r),{prepare:t,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,response:i}}function Li(e){e.response.catch(()=>{})}async function Ri(e){let t=await Ir({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx}),n=fi(e.ctx),r=rr(e.txSigningRequest,`txSigningRequest`),i=await _t({scope:_i({materialActivation:e.materialActivation,materialFacts:e.materialFacts,walletId:e.walletId,operationId:e.operationId}),expiresAtMs:Date.now()+si,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:n,transactions:[{receiverId:r.receiverId,actionFingerprint:await ft(r.actions)}],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,expectedSigningDigestB64u:t.signingDigestB64u}),a=Ke({tenantId:mi(k(e.materialFacts.runtimePolicyScope.orgId)),principalId:mi(E(String(e.walletId))),capabilityId:mi(re(e.materialActivation.capability)),operationId:mi(w(String(e.operationId))),operation:{capabilityKind:`near_ed25519_mpc_signing`,operationKind:`near.sign_transaction`},digests:{laneDigest:Ge(e.operationFingerprint),intentDigest:A(h(Uint8Array.from(i.admissionMaterial.intentDigest.bytes))),displayDigest:A(e.displayDigest)}});return{operation:{kind:`near_transaction`,prepare:i,unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,signingDigestB64u:t.signingDigestB64u,materialActivation:e.materialActivation},envelope:a}}function zi(e){return e.authorization.kind===`operation_step_up`}function Bi(e){return zi(e)?e.materialFacts:{thresholdSessionId:e.walletSessionState.thresholdSessionId,signer:e.walletSessionState.signingLane.identity.signer,signingRootId:e.walletSessionState.signingRootId,signingRootVersion:e.walletSessionState.signingRootVersion,routerAbNormalSigning:e.walletSessionState.routerAbNormalSigning,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,relayerUrl:e.walletSessionState.relayerUrl}}async function Vi(e,t){let n=fi(e.ctx),r=rr(e.txSigningRequest,`txSigningRequest`);return{nearNetworkId:n,parsedTransaction:r,operationFingerprint:H.signingOperationFingerprint(await Xn({nearAccountId:e.nearAccountId,nearNetworkId:n,relayerKeyId:e.thresholdKeyMaterial.relayerKeyId,signerPublicKey:e.thresholdKeyMaterial.publicKey,transactions:[r],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,signingDigestB64u:t.signingDigestB64u}))}}async function Hi(e,t,n){let r=gi({activeClient:e.activeClient,walletSessionState:e.walletSessionState,walletId:e.walletId,operationId:e.operationId});if(!r)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing`);return await _t({scope:r,expiresAtMs:hi({walletSessionExpiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs,requestedTtlMs:si}),operationId:e.operationId,operationFingerprint:n.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:n.nearNetworkId,transactions:[{receiverId:n.parsedTransaction.receiverId,actionFingerprint:await ft(n.parsedTransaction.actions)}],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,expectedSigningDigestB64u:t.signingDigestB64u})}async function Ui(e){let t=await Ir({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx}),n=await Hi(e,t,await Vi(e,t)),r=Zr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}),i=performance.now(),a=mt({relayServerUrl:e.walletSessionState.relayerUrl,credential:r.credential,request:n.request});return a.catch(()=>{}),U(String(e.operationId),`prepare_sent`,i),{prepare:n,displayDigest:e.displayDigest,signingDigestB64u:t.signingDigestB64u,response:a}}async function Wi(e){let t=Bi(e);if(!t.routerAbNormalSigning)throw Error(`[SigningEngine][near] Router A/B Ed25519 normal-signing state is missing`);if(!e.transactionContext)throw Error(`[SigningEngine][near] Router A/B Ed25519 transaction signing is missing transaction context from confirmation`);let n=zi(e),r=n?{unsignedTransactionBorshB64u:e.authorization.prepared.unsignedTransactionBorshB64u,signingDigestB64u:e.authorization.prepared.signingDigestB64u}:await Ir({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx});if(_(r.signingDigestB64u).length!==32)throw Error(`Router A/B normal-signing NEAR payload digest must be 32 bytes`);let i=await Vi(e,r),a=null,o,s,c;if(n){o=e.authorization.prepared.prepare,s=await ci({ctx:e.ctx,walletId:e.walletId,relayerUrl:t.relayerUrl,proof:e.authorization.proof});let n=await Ni({issuedAuthorization:e.authorization.issuedAuthorization,relayerUrl:t.relayerUrl,normalSigningRequest:o.request,displayDigest:e.authorization.displayDigest,proof:e.authorization.proof,credential:s});if(o.request.scope.authorization.kind!==`operation_step_up`||n.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] issued operation step-up evidence changed identity`);c=n}else a=e.startedPrepare&&e.startedPrepare.displayDigest===e.displayDigest&&e.startedPrepare.signingDigestB64u===r.signingDigestB64u?e.startedPrepare:null,e.startedPrepare&&!a&&Li(e.startedPrepare),o=a?a.prepare:await Hi(e,r,i),s=Zr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}).credential;e.ctx.beforeSigning?.();let l=zi(e)?await wi({thresholdSessionId:e.thresholdSessionId,materialFacts:t,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:r.signingDigestB64u,signingPayloadLabel:`NEAR payload digest`,prepare:o,credential:s,authorization:`operation_step_up`}):await wi({thresholdSessionId:e.thresholdSessionId,walletSessionState:e.walletSessionState,sessionCoordinator:e.sessionCoordinator,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:r.signingDigestB64u,signingPayloadLabel:`NEAR payload digest`,prepare:o,credential:s,authorization:`reusable_wallet_session`,startedResponse:a?.response}),u=await Lr({unsignedTransactionBorshB64u:r.unsignedTransactionBorshB64u,signingDigestB64u:r.signingDigestB64u,signatureB64u:l.signatureB64u,expectedNearAccountId:e.nearAccountId,expectedSignerPublicKey:e.thresholdKeyMaterial.publicKey,workerCtx:e.ctx}),d=await Rr({signedTransactionBorshB64u:u.signedTransactionBorshB64u,workerCtx:e.ctx}),f=u.transactionHash||d.transactionHash,p={type:Gt.SignTransactionsWithActionsSuccess,payload:{free:()=>void 0,success:!0,transactionHashes:[f],signedTransactions:[d.signedTransaction],logs:[`NEAR transaction signed through Router A/B normal signing`],error:void 0}};if(n){if(!c)throw Error(`[SigningEngine][near] operation step-up authorization was not issued`);return{kind:`router_ab_ed25519_near_transaction_normal_signing_result_v1`,authorization:`operation_step_up`,issuedAuthorization:c,okResponse:p}}return{kind:`router_ab_ed25519_near_transaction_normal_signing_result_v1`,authorization:`reusable_wallet_session`,okResponse:p}}const Gi=1e3,Ki=[120,180,250,350,500,700,1e3,1e3,1500,1500,2e3],qi=Symbol(`NearWalletSessionFundingAuthority`);function Ji(e=Gi){return new Promise(t=>{setTimeout(t,e)})}function Yi(e){let t=String(e.walletSessionToken||``).trim();if(!t)throw Error(`[SigningEngine][near] authenticated Wallet Session token is required for funding`);return t}function Xi(e){return{kind:`near_ed25519_funding_session`,signer:e.signingLane.identity.signer,thresholdSessionId:e.thresholdSessionId,walletSessionToken:e.walletSessionAuth.walletSessionToken}}function Zi(e){switch(e.kind){case`warm_session`:return`warm_session`;case`passkey`:return`passkey_reauth`;case`email_otp`:return`email_otp_reauth`;default:return $i(e)}}function Qi(e){switch(e){case`passkey`:return`passkey_reauth`;case`email_otp`:return`email_otp_reauth`;default:throw Error(`[SigningEngine][near] unsupported operation step-up funding method`)}}function $i(e){throw Error(`Unsupported NEAR funding authorization: ${String(e)}`)}function ea(e){let t=String(e.fundingSession.signer.account.wallet.walletId),n=String(e.fundingSession.signer.account.nearAccountId),r=e.request.operation;if(String(e.request.subject.walletId)!==t||String(e.request.subject.nearAccountId)!==n||e.request.subject.nearPublicKeyStr!==e.nearPublicKeyStr)throw Error(`[SigningEngine][near] funding request subject does not match authenticated lane`);if(String(r.operationId)!==String(e.signingOperation.operationId)||String(r.operationFingerprint)!==String(e.signingOperation.operationFingerprint)||r.intent!==e.signingOperation.intent||r.accountId!==n)throw Error(`[SigningEngine][near] funding request operation does not match signing operation`);if(e.request.signatureUses!==e.signatureUses)throw Error(`[SigningEngine][near] funding request signature use count mismatch`);if(String(e.fundingSession.thresholdSessionId).trim().length===0)throw Error(`[SigningEngine][near] funding authority threshold session mismatch`)}function ta(e){return{kind:`near_wallet_session_funding_authority`,provenance:e.provenance,request:e.request,thresholdSessionId:e.fundingSession.thresholdSessionId,walletSessionToken:Yi(e.fundingSession),[qi]:!0}}async function na(e){let t=e.authority.request,n=rt({chains:e.ctx.chains,walletId:String(t.subject.walletId),nearAccountId:String(t.subject.nearAccountId),nearPublicKeyStr:t.subject.nearPublicKeyStr}),r;for(let i=1;i<=12;i+=1)try{let r=await e.ctx.nonceCoordinator.reserveNearContext({lane:n,operation:t.operation,count:t.signatureUses,nearClient:e.ctx.nearClient});return{transactionContext:r.context,nonceLeases:r.leases.map(ke),reservedLeases:r.leases}}catch(e){r=e,i<12&&await Ji(Ki[i-1]??Gi)}throw r instanceof Error?r:Error(`Funded NEAR account access key did not become available`)}async function ra(e){let t=e.authority.request,n=await Ie({relayerUrl:e.ctx.relayerUrl,walletId:String(t.subject.walletId),nearAccountId:String(t.subject.nearAccountId),nearPublicKeyStr:t.subject.nearPublicKeyStr,walletSessionToken:e.authority.walletSessionToken});if(!n.ok)throw Error(n.message||n.code||`Failed to fund implicit NEAR account`);return await na(e)}async function ia(e){switch(e.confirmation.readiness.kind){case`context_ready`:return e.confirmation.readiness;case`funding_required`:{ea({request:e.confirmation.readiness.request,fundingSession:Xi(e.walletSessionState),nearPublicKeyStr:e.nearPublicKeyStr,signingOperation:e.signingOperation,signatureUses:e.signatureUses});let t=ta({request:e.confirmation.readiness.request,fundingSession:Xi(e.walletSessionState),provenance:Zi(e.authorization)}),n=await ra({ctx:e.ctx,authority:t});return{kind:`context_ready`,transactionContext:n.transactionContext,nonceLeases:n.nonceLeases}}default:return aa(e.confirmation.readiness)}}function aa(e){throw Error(`Unsupported confirmed NEAR transaction readiness: ${String(e)}`)}async function oa(e){ea({request:e.request,fundingSession:e.fundingSession,nearPublicKeyStr:e.nearPublicKeyStr,signingOperation:e.signingOperation,signatureUses:e.signatureUses});let t=ta({request:e.request,fundingSession:e.fundingSession,provenance:Qi(e.method)}),n=await ra({ctx:e.ctx,authority:t});return{readiness:{kind:`context_ready`,transactionContext:n.transactionContext,nonceLeases:n.nonceLeases},reservedNonceLeases:n.reservedLeases}}const sa=new Map;function ca(e){let t=String(e||``).trim();if(!t)throw Error(`[SigningEngine][near] requestId is required`);return t}function la(e){sa.set(ca(e.requestId),e.fund)}function ua(e){sa.delete(String(e||``).trim())}const da={async fund(e){let t=ca(e.requestId),n=sa.get(t);if(!n)throw Error(`[SigningEngine][near] implicit-account funding is unavailable`);return sa.delete(t),await n(e.request)}};function fa(e){switch(e.kind){case`passkey_live`:case`email_otp_live`:return e.material.facts;case`passkey_sealed`:case`email_otp_sealed`:return e.facts;default:throw Error(`[SigningEngine][near] unsupported operation material`)}}async function pa(e,t){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:return await t.resolve(e);case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] material requires public-anchor reauthorization`);case`blocked`:throw Error(`[SigningEngine][near] material hydration is blocked: ${e.hydration.reason}`);default:throw e.hydration,Error(`[SigningEngine][near] unsupported Ed25519 Yao hydration plan`)}}async function ma(e){if(e.method===`passkey`&&e.preparation.hydration.kind===`rehydrate_material_activation`){let t=await e.executor.preparePasskeyOperationStepUp(e.preparation);return{kind:`passkey_sealed`,materialActivation:t.materialActivation,facts:t.facts,rehydrate:t.rehydrate}}if(e.method===`email_otp`){let t=await e.executor.prepareEmailOtpOperationStepUp(e.preparation);switch(t.kind){case`live`:return{kind:`email_otp_live`,materialActivation:t.materialActivation,material:t.material};case`sealed`:return{kind:`email_otp_sealed`,materialActivation:t.materialActivation,facts:t.facts,authorizeAndRehydrate:t.authorizeAndRehydrate};default:throw Error(`[SigningEngine][near] unsupported Email OTP operation material`)}}let t=await pa(e.preparation,e.executor);return{kind:`passkey_live`,materialActivation:Re(t.activeClient.metadata()),material:t}}async function ha(e){oi({expected:e.expectedActivation,actual:e.material.materialActivation});let t,n=null;if(e.kind===`email_otp_live`||e.kind===`email_otp_sealed`)if(e.kind===`email_otp_live`)t=e.material.material;else{let r=await e.material.authorizeAndRehydrate({normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof});t=r.material,n=r.issuedAuthorization}else t=e.material.kind===`passkey_live`?e.material.material:await e.material.rehydrate(e.credential);try{return oi({expected:e.expectedActivation,actual:Re(t.activeClient.metadata())}),{material:t,issuedAuthorization:n}}catch(n){throw(e.material.kind===`passkey_sealed`||e.material.kind===`email_otp_sealed`)&&t.activeClient.dispose(),n}}async function ga(e){let t=await pa(e.preparation,e.executor);return{thresholdSessionId:t.facts.thresholdSessionId,material:t,walletSessionState:await e.executor.resolveWalletSessionState()}}function _a(e){if(!e)throw Error(`[SigningEngine][near] confirmed operation step-up is missing preparation`);return e}function va(e){if(!e)throw Error(`[SigningEngine][near] prepared operation step-up is missing`);if(e.kind!==`near_transaction`)throw Error(`[SigningEngine][near] prepared operation step-up is not a transaction`);return e}function ya(e){if(!e)throw Error(`[SigningEngine][near] transaction operation material is unavailable`);return e}function ba(e){e.owned&&e.resolved?.material.activeClient.dispose()}function xa(e,t){throw ba(e),t}async function Sa(e){return{material:await pa(e.preparation,e.executor),walletSessionState:await e.executor.resolveWalletSessionState()}}function Ca(e){if(!e)throw Error(`[SigningEngine][near] warm signing material was not prepared`);return e}async function wa(e){let t=await e.warmMaterial,n=await e.sessionCoordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:t.walletSessionState,nowMs:Date.now()});if(!n)return null;let r=await et([{receiverId:e.confirmationTransaction.receiverId,actions:e.confirmationTransaction.actions.map(Qe)}]);return await Ui({ctx:e.ctx,thresholdSessionId:t.material.facts.thresholdSessionId,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:t.material.activeClient,walletSessionState:n,operationId:e.operationId,displayDigest:r,txSigningRequest:e.txSigningRequest,transactionContext:e.readiness.transactionContext})}function Ta(){return null}async function Ea(e){if(e.authorization.kind===`passkey`){if(e.material.kind!==`passkey_live`&&e.material.kind!==`passkey_sealed`)throw Error(`[SigningEngine][near] passkey transaction material changed factor`);return await ha({kind:`passkey`,material:e.material,expectedActivation:e.prepared.materialActivation,credential:e.authorization.credential})}if(e.material.kind!==`email_otp_live`&&e.material.kind!==`email_otp_sealed`)throw Error(`[SigningEngine][near] Email OTP transaction material changed factor`);if(e.proof.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP transaction proof is missing`);return e.material.kind===`email_otp_live`?await ha({kind:`email_otp_live`,material:e.material,expectedActivation:e.prepared.materialActivation}):await ha({kind:`email_otp_sealed`,material:e.material,expectedActivation:e.prepared.materialActivation,normalSigningRequest:e.prepared.prepare.request,displayDigest:e.displayDigest,proof:e.proof})}function Z(e,t,n){try{e?.(xe({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}async function Da(e){let t=performance.now(),n=`failed`;try{if(!e.state)throw Error(`[SigningEngine][near] reusable Wallet Session state is unavailable`);let t=await e.coordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:e.state,nowMs:Date.now()});if(!t)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return n=`succeeded`,t}finally{U(e.operationId,`wallet_session_authorization`,t,n)}}async function Oa(e){let t=await ma({method:e.method,preparation:e.preparation,executor:e.executor}),n=fa(t);if(String(n.thresholdSessionId)!==e.expectedThresholdSessionId)throw Error(`[SigningEngine][near] prepared operation material changed threshold session`);return ni({requestId:e.requestId,build:async r=>{if(r.kind!==`near_transaction`)throw Error(`[SigningEngine][near] transaction step-up preparation kind changed`);if(r.operationId!==String(e.operation.operationId))throw Error(`[SigningEngine][near] operation step-up operation identity changed`);return await Ri({...e.operation,thresholdSessionId:n.thresholdSessionId,materialFacts:n,materialActivation:t.materialActivation,transactionContext:r.transactionContext,displayDigest:r.displayDigest})}}),la({requestId:e.requestId,fund:async t=>await oa({...e.funding,request:t,fundingSession:await e.executor.resolveFundingSession(),method:e.method})}),t}function ka(e){ri(e),ua(e)}function Aa(e){if(!e.readiness){ka(e.requestId);return}e.readiness.then(ka.bind(void 0,e.requestId),ka.bind(void 0,e.requestId))}function ja(e){return e.selection.kind===`authorization_required`}async function Ma(e){return ja(e)?await Na(e):await Pa(e)}async function Na(e){let{ctx:t,commandSubject:n,nearAccount:r,transaction:i,rpcCall:a,onEvent:o,confirmationConfigOverride:c,title:l,body:u,signerSlot:d,signingOperationState:p,signingSessionCoordinator:m,selection:h,yaoSigningPreparation:g,yaoMaterialExecutor:_,passkeyEd25519OperationStepUp:v,emailOtpEd25519StepUp:y}=e,b=p.operationId,x=h.candidate,S=P(r.accountId),ee=[];if(!t.touchConfirm)throw Error(`UiConfirm bridge not available for signing`);if(!m)throw Error(`[SigningEngine][near] production signing session coordinator is required`);let{thresholdKeyMaterial:te}=await Gn({materialExecutor:_,nearAccount:r,signerSlot:x.signerSlot,requestedSignerSlot:d,operationLabel:`signing`,warnings:ee}),C=Ra({nearAccountId:S,relayerUrl:t.relayerUrl,thresholdKeyMaterial:te}),ne={nearRpcUrl:a.nearRpcUrl||f(gt.network.chains),nearAccountId:S},{txSigningRequest:w,confirmationTransaction:T}=Kn({nearAccountId:String(S),transaction:i}),E=rr(w,`txSigningRequest`),D=H.signingOperationFingerprint(await Yn({nearAccountId:S,nearNetworkId:s(t.chains||gt.network.chains),relayerKeyId:C.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:C.threshold.thresholdKeyMaterial.publicKey,transactions:[E]}));m.bindCallerProvidedOperationIdToFingerprint({operationId:b,operationFingerprint:D});let O=Ge(D),k={kind:`deferred_ed25519_material_identity`,signer:Ve({walletId:x.walletId,nearAccountId:x.nearAccountId,nearEd25519SigningKeyId:x.nearEd25519SigningKeyId,signerSlot:x.signerSlot}),materialActivation:x.materialActivation,thresholdSessionId:H.thresholdEd25519Session(x.thresholdSessionId)},re={kind:V.OperationStepUp,lane:{identity:k,auth:x.auth,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,sessionOrigin:`per_operation`,storageSource:`sealed_restore`,retention:`single_use`,materialActivation:k.materialActivation,thresholdSessionId:k.thresholdSessionId}},A=_r(x.auth),j={operationId:b,operationFingerprint:D,intent:Te.TransactionSign},M=await gr({signingAuthPlan:A,signingLaneAuth:x.auth,requiredSignatureUses:kr(i),operationFingerprintDigest:O,...v?{passkeyEd25519OperationStepUp:v}:{},...y?{emailOtpEd25519StepUp:y}:{}});if(M.kind===`warm_session`)throw Error(`[SigningEngine][near] deferred Ed25519 transaction cannot use warm session`);let ie=kr(i),ae=Oa({requestId:String(b),expectedThresholdSessionId:String(k.thresholdSessionId),method:M.kind,preparation:g,executor:_,operation:{ctx:t,thresholdKeyMaterial:C.threshold.thresholdKeyMaterial,walletId:n.walletSession.walletId,nearAccountId:S,operationId:b,operationFingerprint:D,txSigningRequest:w},funding:{ctx:t,nearPublicKeyStr:C.signingNearPublicKeyStr,signingOperation:j,signatureUses:ie}}),N;try{N=await jt({signingSessionPlan:re,signingOperation:j,signingOperationState:p,runtime:t.touchConfirm,request:{ctx:{touchConfirm:t.touchConfirm},sessionId:String(b),chain:`near`,kind:`transaction`,...At({signingAuthPlan:M.confirmationAuthPayload.signingAuthPlan}),walletId:x.walletId,txSigningRequests:[T],rpcCall:ne,nearPublicKeyStr:C.signingNearPublicKeyStr,nearFundingRequest:{subject:{walletId:x.walletId,nearAccountId:S,nearPublicKeyStr:C.signingNearPublicKeyStr},operation:{...j,accountId:String(S)},signatureUses:ie},confirmationConfigOverride:Mt({signingAuthPlan:M.confirmationAuthPayload.signingAuthPlan,override:c}),title:l,body:u,confirmationReadiness:{promise:ae},onProgress:wr.bind(void 0,{onEvent:o,nearAccountId:S,signingAuthPlan:M.confirmationAuthPayload.signingAuthPlan})}})}finally{Aa({requestId:String(b),readiness:ae})}let F=await ae,oe=fa(F),I=Er({prepared:M,confirmation:N});if(I.kind===`warm_session`)throw Error(`[SigningEngine][near] deferred transaction requires operation step-up`);let se=ki({authorization:I,preparation:g,auth:x.auth,walletId:n.walletSession.walletId}),ce=va(ai({requestId:String(b),ref:_a(N.operationStepUpPreparation)})),le=await Ea({material:F,prepared:ce,displayDigest:N.intentDigest,authorization:I,proof:ji(se)});Z(o,S,{phase:z.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:Pt(M.confirmationAuthPayload.signingAuthPlan)});try{if(await t.nonceCoordinator.recoverDurableLeases({walletId:String(x.walletId)}),N.readiness.kind!==`context_ready`)throw Error(`[SigningEngine][near] implicit-account funding requires transaction context`);let e=await Wi({ctx:t,thresholdSessionId:oe.thresholdSessionId,activeClient:le.material.activeClient,materialFacts:oe,thresholdKeyMaterial:C.threshold.thresholdKeyMaterial,walletId:n.walletSession.walletId,nearAccountId:S,operationId:b,operationFingerprint:D,displayDigest:N.intentDigest,txSigningRequest:w,transactionContext:N.readiness.transactionContext,authorization:{kind:`operation_step_up`,prepared:ce,displayDigest:N.intentDigest,proof:ji(se),issuedAuthorization:le.issuedAuthorization}});if(!e||e.authorization!==`operation_step_up`)throw Error(`[SigningEngine][near] operation step-up transaction signing is unavailable`);li({prepared:ce,issuedAuthorization:e.issuedAuthorization});let r=La({okResponse:e.okResponse,nearAccountId:S,warnings:ee,nonceLeases:N.readiness.nonceLeases});return await Ia(t,N.readiness.nonceLeases),r}catch(e){throw ba({resolved:le,owned:F.kind===`passkey_sealed`||F.kind===`email_otp_sealed`}),e}}async function Pa({ctx:e,commandSubject:t,nearAccount:n,transaction:r,rpcCall:i,onEvent:a,confirmationConfigOverride:o,title:c,body:l,signerSlot:u,signingOperationState:d,signingSessionCoordinator:p,transactionOperation:m,ed25519SigningBoundary:h,passkeyEd25519OperationStepUp:g,emailOtpEd25519StepUp:_,yaoSigningPreparation:v,yaoMaterialExecutor:y}){let b=performance.now(),x=d.operationId,S=P(n.accountId),ee=e.relayerUrl,te=[],C=e.nonceCoordinator.recoverDurableLeases({walletId:String(t.walletSession.walletId)});C.catch(()=>{}),Z(a,S,{phase:z.STEP_02_REQUEST_PREPARED,status:`running`,message:`Loading threshold signing state`,interaction:{kind:`none`,overlay:`none`}});let{thresholdKeyMaterial:ne}=await Gn({materialExecutor:y,nearAccount:n,signerSlot:h.signingLane.identity.signer.signerSlot,requestedSignerSlot:u,operationLabel:`signing`,warnings:te}),w=Ra({nearAccountId:S,relayerUrl:ee,thresholdKeyMaterial:ne}),T={nearRpcUrl:i.nearRpcUrl||f(gt.network.chains),nearAccountId:S},{txSigningRequest:E,confirmationTransaction:D}=Kn({nearAccountId:String(T.nearAccountId),transaction:r}),O=rr(E,`txSigningRequest`),k=H.signingOperationFingerprint(await Yn({nearAccountId:S,nearNetworkId:s(e.chains||gt.network.chains),relayerKeyId:w.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:w.threshold.thresholdKeyMaterial.publicKey,transactions:[O]})),re=Ge(k);if(!e.touchConfirm)throw Error(`UiConfirm bridge not available for signing`);let A=e.touchConfirm;if(!p)throw Error(`[SigningEngine][near] production signing session coordinator is required`);p.bindCallerProvidedOperationIdToFingerprint({operationId:x,operationFingerprint:k});let j=kr(r),M={operationId:x,operationFingerprint:k,intent:Te.TransactionSign},ie=async e=>await Et({signingSessionPlan:h.signingSessionPlan,signingOperation:M,commandKind:e.commandKind,execute:e.execute}),ae=h.thresholdSessionId,N=String(ae||``).trim(),F=h.signingAuthPlan,oe=h.signingLane;if(!m)throw Error(`[SigningEngine][near] threshold transaction signing requires prepared transaction operation`);if(St(F)&&F.thresholdSessionId!==ae)throw Error(`[SigningEngine][near] warm-session auth plan must match prepared session identity`);let I={thresholdSessionId:St(F)?F.thresholdSessionId:ae,lane:oe,signingAuthPlan:F,confirmationAuthPayload:{signingAuthPlan:F},warmSessionReady:St(F)},se=oe,ce=new Set,le=e=>{ce.has(e)||(ce.add(e),Je(`near`,Xe({event:`auth_side_effect_started`,lane:se,sideEffect:e,phase:`confirmed`})))},ue=e=>{e.phase===`auth.passkey.prompt.started`&&le(`passkey_reauth`),wr({onEvent:a,nearAccountId:S,signingAuthPlan:I.confirmationAuthPayload.signingAuthPlan},e)},de=await gr({signingAuthPlan:F,signingLaneAuth:oe.auth,requiredSignatureUses:j,operationFingerprintDigest:re,...g?{passkeyEd25519OperationStepUp:g}:{},..._?{emailOtpEd25519StepUp:_}:{}}),fe=de.kind===`warm_session`?Sa({preparation:v,executor:y}):null;fe?.catch(()=>{});let pe=de.confirmationAuthPayload;St(pe.signingAuthPlan)&&Z(a,S,{phase:z.STEP_06_AUTH_WARM_SESSION_CLAIMED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{thresholdSessionId:pe.signingAuthPlan.thresholdSessionId,expiresAtMs:pe.signingAuthPlan.expiresAtMs,remainingUses:pe.signingAuthPlan.remainingUses}});let me=!Lt(d.current);me&&Z(a,S,{phase:z.STEP_05_CONFIRMATION_DISPLAYED,status:`waiting_for_user`,message:`Opening confirmation prompt`,interaction:{kind:`transaction_confirmation`,overlay:`show`}});let he=de.kind===`warm_session`?null:Oa({requestId:N,expectedThresholdSessionId:N,method:de.kind,preparation:v,executor:y,operation:{ctx:e,thresholdKeyMaterial:w.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:S,operationId:M.operationId,operationFingerprint:k,txSigningRequest:E},funding:{ctx:e,nearPublicKeyStr:w.signingNearPublicKeyStr,signingOperation:M,signatureUses:j}});U(String(x),`pre_confirmation`,b);let ge=null,_e=n=>{ge||!fe||(ge=wa({ctx:e,warmMaterial:fe,sessionCoordinator:p,thresholdKeyMaterial:w.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:S,operationId:M.operationId,txSigningRequest:E,confirmationTransaction:D,readiness:n}).catch(Ta))},ve=performance.now(),L;try{L=await jt({signingSessionPlan:h.signingSessionPlan,signingOperation:M,signingOperationState:d,runtime:A,request:{ctx:{touchConfirm:A},sessionId:N,chain:`near`,kind:`transaction`,...At({signingAuthPlan:pe.signingAuthPlan}),...fe?{onNearTransactionContextReady:_e}:{},walletId:String(oe.identity.signer.account.wallet.walletId),txSigningRequests:[D],rpcCall:T,nearPublicKeyStr:w.signingNearPublicKeyStr,nearFundingRequest:{subject:{walletId:oe.identity.signer.account.wallet.walletId,nearAccountId:S,nearPublicKeyStr:w.signingNearPublicKeyStr},operation:{...M,accountId:String(S)},signatureUses:j},confirmationConfigOverride:Mt({signingAuthPlan:pe.signingAuthPlan,override:o}),title:c,body:l,...he?{confirmationReadiness:{promise:he}}:{},onProgress:ue}})}finally{Aa({requestId:N,readiness:he})}let ye=performance.now();U(String(x),`confirmation`,ve);let be=he?await he:null;me&&Z(a,S,{phase:z.STEP_05_CONFIRMATION_APPROVED,status:`succeeded`,interaction:{kind:`transaction_confirmation`,overlay:`hide`}});let R=Er({prepared:de,confirmation:L}),xe=R.kind===`warm_session`?null:ki({authorization:R,preparation:v,auth:m.lane.auth,walletId:t.walletSession.walletId}),Se=R.kind===`warm_session`?null:ai({requestId:N,ref:_a(L.operationStepUpPreparation)}),Ce=R.kind===`warm_session`?null:await Ea({material:ya(be),prepared:va(Se),displayDigest:L.intentDigest,authorization:R,proof:ji(xe)}),we=be?.kind===`passkey_sealed`||be?.kind===`email_otp_sealed`,B=performance.now();try{await C,U(String(M.operationId),`durable_lease_recovery_wait`,B)}catch(e){throw U(String(M.operationId),`durable_lease_recovery_wait`,B,`failed`),ba({resolved:Ce,owned:we}),e}let V=!1,{canonicalThresholdSessionId:Ee,activeClient:De,walletSessionState:Oe,operationMaterialFacts:ke,issuedAuthorization:Ae,transactionContext:je,nonceLeaseRefs:Me}=await ie({commandKind:kt.PreparePayload,execute:async()=>{Z(a,S,{phase:z.STEP_08_SIGNER_PREPARE_STARTED,status:`running`,message:`Preparing NEAR signer`,interaction:{kind:`none`,overlay:`none`}});let t=performance.now(),n=R.kind===`warm_session`?{kind:`warm_session`,resolved:await Ca(fe)}:{kind:`operation_step_up`,resolved:Ce};U(String(M.operationId),`material_resolution_wait`,t);let r=(n.kind,n.resolved.material.facts.thresholdSessionId),i=(n.kind,n.resolved.material.activeClient),o=n.kind===`warm_session`?n.resolved.walletSessionState:null,s=performance.now(),c=n.kind===`warm_session`?await ia({confirmation:L,ctx:e,nearPublicKeyStr:w.signingNearPublicKeyStr,walletSessionState:o,authorization:R,signingOperation:M,signatureUses:j}):L.readiness.kind===`context_ready`?L.readiness:(()=>{throw Error(`[SigningEngine][near] operation step-up confirmation did not resolve a transaction context`)})();return U(String(M.operationId),`transaction_context`,s),Z(a,S,{phase:z.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:I.warmSessionReady?`warm_session`:I.signingAuthPlan.method}),Z(a,S,{phase:z.STEP_08_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`,message:`NEAR signer ready`,interaction:{kind:`none`,overlay:`none`},data:{signer:`threshold-ed25519`,thresholdSessionId:r,clientBaseSource:`yao_active_client`}}),{canonicalThresholdSessionId:r,activeClient:i,walletSessionState:o,operationMaterialFacts:n.kind===`operation_step_up`?n.resolved.material.facts:null,issuedAuthorization:n.kind===`operation_step_up`?n.resolved.issuedAuthorization:null,transactionContext:c.transactionContext,nonceLeaseRefs:c.nonceLeases}}}).catch(xa.bind(void 0,{resolved:Ce,owned:we})),Ne=async t=>{V||!Me.length||await Fa(e,Me,`signing_failed`).catch(e=>{console.warn(`[SigningEngine][near][transaction] failed to release nonce leases`,{originalError:t instanceof Error?t.message:String(t||``),releaseError:e instanceof Error?e.message:String(e||``)})})},Pe=async n=>{Z(a,S,{phase:z.STEP_10_COMMIT_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let r=R.kind===`warm_session`?await Wi({ctx:e,thresholdSessionId:Ee,activeClient:n,sessionCoordinator:p,walletSessionState:await Da({state:Oe,coordinator:p,operationId:String(M.operationId)}),thresholdKeyMaterial:w.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:S,operationId:M.operationId,operationFingerprint:k,displayDigest:L.intentDigest,txSigningRequest:E,transactionContext:je,authorization:{kind:`reusable_wallet_session`},startedPrepare:ge?await ge:null}):await Wi({ctx:e,thresholdSessionId:Ee,activeClient:n,materialFacts:ke,thresholdKeyMaterial:w.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:S,operationId:M.operationId,operationFingerprint:k,displayDigest:L.intentDigest,txSigningRequest:E,transactionContext:je,authorization:{kind:`operation_step_up`,prepared:va(Se),displayDigest:L.intentDigest,proof:R.kind===`passkey`?{kind:`passkey`,authority:R.plannedPasskeyOperationStepUp.authority,credential:R.credential}:{...Oi({preparation:v,auth:m.lane.auth,walletId:t.walletSession.walletId,challengeId:R.challengeId,otpCode:R.otpCode})},issuedAuthorization:Ae}});if(r)return r.okResponse;throw Error(`[SigningEngine][near] Router A/B Ed25519 signing is unavailable`)};return await ie({commandKind:kt.Sign,execute:async()=>{try{let t=await Pe(De);V=!0;let n=performance.now();await Ia(e,Me),U(String(M.operationId),`nonce_lease_commit`,n);let r=performance.now(),i=La({okResponse:t,nearAccountId:S,warnings:te,nonceLeases:Me});return U(String(M.operationId),`transaction_assembly`,r),U(String(M.operationId),`confirmed_to_signed`,ye),Z(a,S,{phase:z.STEP_11_TRANSACTION_SIGNED,status:`succeeded`,interaction:{kind:`none`,overlay:`hide`}}),Z(a,S,{phase:z.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`sign`}}),i}catch(e){let t=e instanceof Error?e:Error(String(e));throw await Ne(t),ba({resolved:Ce,owned:we}),t}}})}async function Fa(e,t,n){t.length&&await Promise.all(t.map(t=>e.nonceCoordinator.release({leaseId:t.leaseId,operationId:t.operationId,operationFingerprint:t.operationFingerprint,reason:n})))}async function Ia(e,t){t.length&&await Promise.all(t.map(t=>e.nonceCoordinator.markSigned({leaseId:t.leaseId,operationId:t.operationId,operationFingerprint:t.operationFingerprint})))}function La(e){let t=e.okResponse.payload.signedTransactions||[];if(t.length!==1)throw Error(`Expected one signed transaction but received ${t.length}`);let n=t[0];if(!n||!n.transaction||!n.signature)throw Error(`Incomplete signed transaction data received`);let r=e.nonceLeases?.[0],i=n.serverDispatch;return{signedTransaction:new Fn({transaction:n.transaction,signature:n.signature,borsh_bytes:Array.from(n.borshBytes||[]),...r?{nonceLease:r}:{},...i?{serverDispatch:i}:{}}),nearAccountId:P(e.nearAccountId),logs:[...e.okResponse.payload.logs||[],...e.warnings],...r?{nonceLease:r}:{}}}function Ra(e){let t=e.thresholdKeyMaterial;if(!t)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let n=String(t.publicKey||``).trim();if(!n)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);let r=String(e.relayerUrl||``).trim();if(!r)throw Error(`Missing relayerUrl (required for threshold-signer)`);let i=x(t.participants.map(e=>e.id));if(!i||i.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(i||[]).join(`,`)}])`);return{signingNearPublicKeyStr:n,threshold:{relayerUrl:r,thresholdKeyMaterial:t}}}const za=e=>typeof e==`string`?e:N(ae(e.keyData));function Q(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?null:Math.round(e)}function Ba(e){if(e==null||!o(e))return;let t=e;if(t.kind!==`registration_confirmation_diagnostics_v1`)return;let n=Q(t.workerReadyMs),r=Q(t.workerRequestRoundTripMs),i=Q(t.workerResponseValidationMs),a=Q(t.requestSetupMs),s=Q(t.promptUserMs),c=Q(t.promptElementDefineMs),l=Q(t.promptMountMs),u=Q(t.promptHostFirstUpdateMs),d=Q(t.promptHostInteractiveMs),f=Q(t.promptConfirmEventMs),p=Q(t.promptDecisionWaitMs),m=Q(t.credentialCreateStartMs),h=Q(t.credentialCreateMs),g=Q(t.credentialSerializeMs),_=Q(t.duplicateRetryCount),v=Q(t.mainThreadTotalMs);if(!(n==null||r==null||i==null||a==null||s==null||c==null||l==null||u==null||d==null||f==null||p==null||m==null||h==null||g==null||_==null||v==null))return{kind:`registration_confirmation_diagnostics_v1`,workerReadyMs:n,workerRequestRoundTripMs:r,workerResponseValidationMs:i,requestSetupMs:a,promptUserMs:s,promptElementDefineMs:c,promptMountMs:l,promptHostFirstUpdateMs:u,promptHostInteractiveMs:d,promptConfirmEventMs:f,promptDecisionWaitMs:p,credentialCreateStartMs:m,credentialCreateMs:h,credentialSerializeMs:g,duplicateRetryCount:_,mainThreadTotalMs:v}}function Va(e){if(e==null)return;if(!o(e))throw Error(`Invalid transactionContext: expected object`);let{nearPublicKeyStr:t,nextNonce:n,txBlockHeight:r,txBlockHash:i,accessKeyInfo:a}=e,s=d(t,`transactionContext.nearPublicKeyStr`),c=d(n,`transactionContext.nextNonce`),l=d(r,`transactionContext.txBlockHeight`),u=d(i,`transactionContext.txBlockHash`),f=a;if(f!=null&&!o(f))throw Error(`Invalid transactionContext.accessKeyInfo: expected object`);return f??={nonce:0},{nearPublicKeyStr:s,nextNonce:c,txBlockHeight:l,txBlockHash:u,accessKeyInfo:f}}function Ha(e){if(e==null)return;let t=Ae(e);if(t.type!==`public-key`)throw Error(`Invalid credential.type: expected "public-key"`);let{id:n,rawId:r,response:i,authenticatorAttachment:a}=t;if(d(n,`credential.id`),d(r,`credential.rawId`),!o(i))throw Error(`Invalid credential.response: expected object`);let{clientDataJSON:s,attestationObject:c,transports:l}=i;if(d(s,`credential.response.clientDataJSON`),d(c,`credential.response.attestationObject`),!Array.isArray(l))throw Error(`Invalid credential.response.transports: expected string[]`);for(let e of l)if(typeof e!=`string`)throw Error(`Invalid credential.response.transports item: expected string`);if(a!=null&&typeof a!=`string`)throw Error(`Invalid credential.authenticatorAttachment: expected string | undefined`);return t}function Ua(e){if(!o(e))throw Error(`Invalid response payload: expected object`);let{confirmed:t,requestId:n,intentDigest:r,credential:i,transactionContext:a,registrationDiagnostics:s,error:c}=e,l=d(n,`requestId`),u=r==null?``:d(r,`intentDigest`),f=i==null?void 0:Ha(i);if(!f)throw Error(`Missing registration credential`);let p=a==null?void 0:Va(a),m=Ba(s),h=c==null?void 0:d(c,`error`);return{confirmed:!!t,requestId:l,intentDigest:u,credential:f,...p?{transactionContext:p}:{},...m?{registrationDiagnostics:m}:{},...h==null?{}:{error:h}}}function Wa(e){let t=e.selectedLane.identity.signer,n=I(e.commandSubject.walletSession.walletId),r=String(e.commandSubject.nearAccount.accountId);if(t.account.wallet.walletId!==n||String(t.account.nearAccountId)!==r)throw Error(`[SigningEngine][near] selected Ed25519 lane does not match command subject`);return{walletId:n,nearAccountId:r}}function Ga(e){let t=e.selectedLane.identity.signer,n={walletId:t.account.wallet.walletId,nearAccountId:t.account.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot,walletSessionId:e.selectedLane.walletSessionId,quotaId:e.selectedLane.quotaId,thresholdSessionId:e.selectedLane.thresholdSessionId};switch(e.selectedLane.auth.kind){case`passkey`:return He({...n,auth:e.selectedLane.auth,storageSource:`login`});case`email_otp`:{let t=e.preparation.authorization.kind===`authorized`;return He({...n,auth:e.selectedLane.auth,retention:t?`session`:`single_use`,sessionOrigin:t?`login`:`per_operation`})}default:throw e.selectedLane.auth,Error(`[SigningEngine][near] unsupported selected Ed25519 auth binding`)}}function Ka(e){let t=H.thresholdEd25519Session(e.selectedLane.thresholdSessionId);switch(e.preparation.authorization.kind){case`authorized`:{let n=e.preparation.authorization.authorization.status,r=n.remainingUses,i=n.expiresAtMs,a=i<=Date.now()?`expired`:r<e.requiredSignatureUses?`exhausted`:`ready`;return{readiness:a===`expired`?{status:`expired`,curve:`ed25519`,thresholdSessionId:t,expiresAtMs:i}:{status:a,curve:`ed25519`,thresholdSessionId:t,remainingUses:r,expiresAtMs:i},expiresAtMs:i,remainingUses:r,forceFreshAuth:a!==`ready`}}case`authorization_required`:return{readiness:{status:`missing_session`,curve:`ed25519`,thresholdSessionId:t},expiresAtMs:0,remainingUses:0,forceFreshAuth:!0};default:throw e.preparation.authorization,Error(`[SigningEngine][near] unsupported material authorization state`)}}function qa(e){Wa(e);let t=Math.max(1,Math.floor(Number(e.requiredSignatureUses)||1)),n=Ga(e),r=Ka({selectedLane:e.selectedLane,preparation:e.preparation,requiredSignatureUses:t});return Ye(`near`,n,{reason:`near_threshold_auth_plan`}),{thresholdSessionId:H.thresholdEd25519Session(e.selectedLane.thresholdSessionId),lane:n,coordinatorInput:{lane:n,readiness:r.readiness,expiresAtMs:r.expiresAtMs,remainingUses:r.remainingUses,forceFreshAuth:e.forceFreshAuth||r.forceFreshAuth}}}function Ja(e){let{lane:t}=e.context,n=e.resolvedSigningSession,r=n.signingSessionPlan;if(r.kind===V.NotReady)throw Error(`[SigningEngine][near] signing session is not ready: ${r.reason}`);return{signingAuthPlan:It({plan:r,accountId:String(t.identity.signer.account.nearAccountId),intent:Te.TransactionSign,curve:`ed25519`,expiresAtMs:n.expiresAtMs,remainingUses:n.remainingUses})}}function Ya(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation step-up preparation is missing`);return t}function Xa(e,t){if(!t||t.kind!==`near_signature_only`)throw Error(`[SigningEngine][near] ${e} operation step-up preparation kind changed`);return t}function Za(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation step-up material is missing`);return t}function Qa(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation signing digest is missing`);return t}function $a(e){if(!e)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return e}async function eo(e){if(e.authorization.kind===`passkey`){if(e.material.kind!==`passkey_live`&&e.material.kind!==`passkey_sealed`)throw Error(`[SigningEngine][near] passkey ${e.label} material changed factor`);return await ha({kind:`passkey`,material:e.material,expectedActivation:e.prepared.materialActivation,credential:e.authorization.credential})}if(e.material.kind!==`email_otp_live`&&e.material.kind!==`email_otp_sealed`)throw Error(`[SigningEngine][near] Email OTP ${e.label} material changed factor`);if(!e.emailOtpProof)throw Error(`[SigningEngine][near] Email OTP ${e.label} proof is missing`);return e.material.kind===`email_otp_live`?await ha({kind:`email_otp_live`,material:e.material,expectedActivation:e.prepared.materialActivation}):await ha({kind:`email_otp_sealed`,material:e.material,expectedActivation:e.prepared.materialActivation,normalSigningRequest:e.prepared.prepare.request,displayDigest:e.displayDigest,proof:e.emailOtpProof})}function to(e){if(e.selection.kind===`authorized`){let t=qa({requiredSignatureUses:1,commandSubject:e.commandSubject,forceFreshAuth:e.forceFreshAuth,selectedLane:e.selection.selectedLane,preparation:e.preparation}),n={signingSessionPlan:xn({lane:t.coordinatorInput.lane,readiness:t.coordinatorInput.readiness,forceFreshAuth:t.coordinatorInput.forceFreshAuth}),readiness:t.coordinatorInput.readiness,expiresAtMs:t.coordinatorInput.expiresAtMs||0,remainingUses:t.coordinatorInput.remainingUses||0};return{signingAuthPlan:Ja({context:t,resolvedSigningSession:n}).signingAuthPlan,signingSessionPlan:n.signingSessionPlan}}let t=e.selection.candidate,n=_r(t.auth),r={kind:`deferred_ed25519_material_identity`,signer:Ve({walletId:t.walletId,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot}),materialActivation:t.materialActivation,thresholdSessionId:H.thresholdEd25519Session(t.thresholdSessionId)};return{signingAuthPlan:n,signingSessionPlan:{kind:V.OperationStepUp,lane:{identity:r,auth:t.auth,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,sessionOrigin:`per_operation`,storageSource:`sealed_restore`,retention:`single_use`,materialActivation:r.materialActivation,thresholdSessionId:r.thresholdSessionId}}}}async function no(e,t){let n=await gr({signingAuthPlan:t.signingAuthPlan,signingLaneAuth:e.auth,requiredSignatureUses:1,operationFingerprintDigest:Ge(e.signingOperation.operationFingerprint),passkeyEd25519OperationStepUp:t.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:t.emailOtpEd25519StepUp});if(n.kind===`warm_session`)return{preparedStepUp:n,operationStepUp:null};let r=await ma({method:n.kind,preparation:e.preparation,executor:e.executor}),i=fa(r),a=await e.computeSigningDigestB64u();return ni({requestId:String(e.signingOperation.operationId),build:async t=>{if(t.kind!==`near_signature_only`)throw Error(`[SigningEngine][near] ${e.label} operation step-up preparation kind changed`);return await Di({ctx:e.ctx,thresholdSessionId:i.thresholdSessionId,materialFacts:i,walletId:e.walletId,nearAccountId:e.nearAccountId,materialActivation:r.materialActivation,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:a,intent:e.intent})}}),{preparedStepUp:n,operationStepUp:{material:r,signingDigestB64u:a}}}async function ro(e,t){let n=String(e.signingOperation.operationId);try{return await Ot({signingSessionPlan:e.signingSessionPlan,signingOperation:e.signingOperation,runtime:t.touchConfirm,request:{ctx:{touchConfirm:t.touchConfirm},sessionId:n,chain:`near`,...t.request,...At({signingAuthPlan:t.signingAuthPlan}),walletId:String(e.walletId),nearAccountId:e.nearAccountId,nearPublicKeyStr:t.nearPublicKeyStr,title:t.title,body:t.body,confirmationConfigOverride:Mt({signingAuthPlan:t.signingAuthPlan,override:t.confirmationConfigOverride}),onProgress:wr.bind(void 0,{onEvent:t.onEvent,nearAccountId:e.nearAccountId,signingAuthPlan:t.signingAuthPlan})}})}finally{ri(n)}}function io(e,t,n){let r=Er({prepared:t.preparedStepUp,confirmation:n});if(r.kind===`warm_session`)return{kind:`warm_session`,displayDigest:n.intentDigest,stepUpAuthorization:r};let i=ki({authorization:r,preparation:e.preparation,auth:e.auth,walletId:e.walletId}),a=Xa(e.label,ai({requestId:String(e.signingOperation.operationId),ref:Ya(e.label,n.operationStepUpPreparation)}));return{kind:`operation_step_up`,displayDigest:n.intentDigest,stepUpAuthorization:r,proof:i,prepared:a,...Za(e.label,t.operationStepUp)}}async function ao(e,t,n){if(t.preparedStepUp.kind!==`warm_session`||e.intent.kind!==`nep413_message_v1`)return null;let r=await ga({preparation:e.preparation,executor:e.executor}),i=$a(await n.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:r.walletSessionState,nowMs:Date.now()})),a=await Ii({ctx:e.ctx,thresholdSessionId:r.thresholdSessionId,activeClient:r.material.activeClient,walletSessionState:i,walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:await $e({nearAccountId:e.nearAccountId,recipient:e.intent.recipient,message:e.intent.message}),signingDigestB64u:await e.computeSigningDigestB64u(),intent:e.intent});return a?{resolved:r,started:a}:null}async function oo(e,t,n=null){if(t.kind===`warm_session`){let r=n?.resolved??await ga({preparation:e.preparation,executor:e.executor});return{kind:`warm_session`,thresholdSessionId:r.thresholdSessionId,displayDigest:t.displayDigest,resolved:r,startedPrepare:n?.started}}return n&&Li(n.started),{kind:`operation_step_up`,thresholdSessionId:fa(t.material).thresholdSessionId,displayDigest:t.displayDigest,resolved:await eo({label:e.label,material:t.material,prepared:t.prepared,displayDigest:t.displayDigest,authorization:t.stepUpAuthorization,emailOtpProof:t.proof.kind===`email_otp`?t.proof:null}),proof:t.proof,prepared:t.prepared,signingDigestB64u:t.signingDigestB64u}}async function so(e,t,n){let r=t.kind===`warm_session`?await e.computeSigningDigestB64u():Qa(e.label,t.signingDigestB64u),i=t.kind===`warm_session`?await Pi({ctx:e.ctx,thresholdSessionId:t.thresholdSessionId,activeClient:t.resolved.material.activeClient,sessionCoordinator:n,walletSessionState:$a(await n.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:t.resolved.walletSessionState,nowMs:Date.now()})),walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:r,intent:e.intent,authorization:{kind:`reusable_wallet_session`},startedPrepare:t.startedPrepare}):await Pi({ctx:e.ctx,thresholdSessionId:t.thresholdSessionId,activeClient:t.resolved.material.activeClient,materialFacts:t.resolved.material.facts,walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:r,intent:e.intent,authorization:{kind:`operation_step_up`,prepared:t.prepared,proof:t.proof,issuedAuthorization:t.resolved.issuedAuthorization}});if(!i)throw Error(`[SigningEngine][near] Router A/B Ed25519 ${e.label} signing is unavailable`);return t.kind===`operation_step_up`&&i.authorization===`operation_step_up`&&li({prepared:t.prepared,issuedAuthorization:i.issuedAuthorization}),{signingDigestB64u:r,signatureB64u:i.signatureB64u,signerPublicKey:i.signerPublicKey}}async function co(e,t){return await Et({signingSessionPlan:e.signingSessionPlan,signingOperation:e.signingOperation,commandKind:kt.Sign,execute:async()=>{try{return await t()}catch(e){throw e instanceof Error?e:Error(String(e))}}})}function $(e,t,n){try{e?.(xe({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function lo(e){switch(e.kind){case`warm_session`:return`warm_session`;case`passkey`:return`passkey`;case`email_otp`:return`email_otp`;default:return uo(e)}}function uo(e){throw Error(`[SigningEngine][near] unsupported prepared step-up: ${String(e)}`)}async function fo({ctx:e,commandSubject:t,nearAccount:n,delegate:r,rpcCall:i,onEvent:a,confirmationConfigOverride:o,title:c,body:l,operationId:u,signerSlot:d,signingSessionCoordinator:p,forceFreshAuth:m,passkeyEd25519OperationStepUp:h,emailOtpEd25519StepUp:g,yaoSigningPreparation:_,yaoMaterialExecutor:v,selection:y}){let b=y.kind===`authorized`?y.selectedLane.auth:y.candidate.auth,x=y.kind===`authorized`?y.selectedLane.identity.signer.signerSlot:y.candidate.signerSlot,S=P(n.accountId),ee=e.relayerUrl,te={nearRpcUrl:i.nearRpcUrl||f(gt.network.chains),nearAccountId:S},C=[],ne=e.touchConfirm;if(!ne)throw Error(`UiConfirm bridge not available for delegate signing`);let{signingAuthPlan:w,signingSessionPlan:T}=to({selection:y,commandSubject:t,forceFreshAuth:m,preparation:_});$(a,S,{phase:z.STEP_02_REQUEST_PREPARED,status:`running`,message:`Loading threshold signing state`,interaction:{kind:`none`,overlay:`none`}});let{thresholdKeyMaterial:E}=await Gn({materialExecutor:v,nearAccount:n,signerSlot:x,requestedSignerSlot:d,operationLabel:`delegate signing`,warnings:C}),D=po({nearAccountId:S,relayerUrl:ee,thresholdKeyMaterial:E,providedDelegatePublicKey:r.publicKey,warnings:C}),O=qn({nearAccountId:S,delegate:r,signingPublicKey:D.delegatePublicKeyStr}),k={...O.workerDelegate,actions:O.workerDelegate.actions.map((e,t)=>ar(e,`delegate.actions[${t}]`))},re={operationId:u,operationFingerprint:H.signingOperationFingerprint(await Qn({nearAccountId:S,nearNetworkId:s(e.chains||gt.network.chains),relayerKeyId:D.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:D.delegatePublicKeyStr,delegate:k})),intent:Te.TransactionSign},A={label:`delegate`,ctx:e,walletId:t.walletSession.walletId,nearAccountId:S,auth:b,signingSessionPlan:T,signingOperation:re,thresholdKeyMaterial:D.threshold.thresholdKeyMaterial,preparation:_,executor:v,intent:{kind:`near_delegate_action_v1`,delegate:k},computeSigningDigestB64u:async()=>(await Nr({delegate:O.workerDelegate,workerCtx:e})).signingDigestB64u},j=await no(A,{signingAuthPlan:w,passkeyEd25519OperationStepUp:h,emailOtpEd25519StepUp:g}),M=j.preparedStepUp.confirmationAuthPayload;St(M.signingAuthPlan)&&$(a,S,{phase:z.STEP_06_AUTH_WARM_SESSION_CLAIMED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{thresholdSessionId:M.signingAuthPlan.thresholdSessionId,expiresAtMs:M.signingAuthPlan.expiresAtMs,remainingUses:M.signingAuthPlan.remainingUses}}),$(a,S,{phase:z.STEP_05_CONFIRMATION_DISPLAYED,status:`waiting_for_user`,message:`Opening confirmation prompt`,interaction:{kind:`transaction_confirmation`,overlay:`show`}});let ie=await ro(A,{touchConfirm:ne,signingAuthPlan:M.signingAuthPlan,nearPublicKeyStr:D.signingNearPublicKeyStr,onEvent:a,title:c,body:l,confirmationConfigOverride:o,request:{kind:`delegate`,delegate:O.confirmationDelegate,rpcCall:te}});$(a,S,{phase:z.STEP_05_CONFIRMATION_APPROVED,status:`succeeded`,interaction:{kind:`transaction_confirmation`,overlay:`hide`}});let ae=io(A,j,ie),N=await Et({signingSessionPlan:T,signingOperation:re,commandKind:kt.PreparePayload,execute:async()=>{$(a,S,{phase:z.STEP_08_SIGNER_PREPARE_STARTED,status:`running`,message:`Preparing NEAR signer`,interaction:{kind:`none`,overlay:`none`}});let e=await oo(A,ae);return $(a,S,{phase:z.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:lo(j.preparedStepUp)}),$(a,S,{phase:z.STEP_08_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`,message:`NEAR signer ready`,interaction:{kind:`none`,overlay:`none`},data:{signer:`threshold-ed25519`,thresholdSessionId:e.thresholdSessionId,clientBaseSource:`yao_active_client`}}),e}}),F=await co(A,async()=>{$(a,S,{phase:z.STEP_10_COMMIT_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let t=await so(A,N,p),n=await yi({ctx:e,delegate:O.workerDelegate,signingDigestB64u:t.signingDigestB64u,signatureB64u:t.signatureB64u});return{type:Gt.SignDelegateActionSuccess,payload:{success:!0,hash:n.hash,signedDelegate:n.signedDelegate,logs:[`Delegate action signed through Router A/B normal signing`],error:void 0}}});return $(a,S,{phase:z.STEP_11_TRANSACTION_SIGNED,status:`succeeded`,interaction:{kind:`none`,overlay:`hide`}}),$(a,S,{phase:z.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`sign_delegate`,hash:F.payload.hash}}),{signedDelegate:F.payload.signedDelegate,hash:F.payload.hash,nearAccountId:P(S),logs:[...F.payload.logs||[],...C]}}function po(e){let t=N(za(e.providedDelegatePublicKey)),n=e.thresholdKeyMaterial;if(!n)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let r=N(n.publicKey);if(!r)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);if(t&&t!==r&&e.warnings.push(`Delegate public key ${t} does not match threshold signer key; using ${r}`),!String(e.relayerUrl||``).trim())throw Error(`Missing relayerUrl (required for threshold-signer)`);let i=x(n.participants.map(e=>e.id));if(!i||i.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(i||[]).join(`,`)}])`);return{signingNearPublicKeyStr:r,delegatePublicKeyStr:r,threshold:{thresholdKeyMaterial:n}}}async function mo({ctx:e,commandSubject:t,nearAccount:n,signingSessionCoordinator:r,payload:i,forceFreshAuth:a,passkeyEd25519OperationStepUp:o,emailOtpEd25519StepUp:c,yaoSigningPreparation:l,yaoMaterialExecutor:u,selection:d,onEvent:f}){let p=d.kind===`authorized`?d.selectedLane.auth:d.candidate.auth,m=d.kind===`authorized`?d.selectedLane.identity.signer.signerSlot:d.candidate.signerSlot,h=i.operationId,v=performance.now(),y=e.relayerUrl,b=n.accountId,x=e.touchConfirm;if(!x)throw Error(`UiConfirm bridge not available for NEP-413 signing`);let{signingAuthPlan:S,signingSessionPlan:ee}=to({selection:d,commandSubject:t,forceFreshAuth:a,preparation:l}),{thresholdKeyMaterial:te}=await Gn({materialExecutor:u,nearAccount:n,signerSlot:m,requestedSignerSlot:i.signerSlot,operationLabel:`NEP-413 signing`}),C=ho({nearAccountId:b,relayerUrl:y,thresholdKeyMaterial:te}),ne={operationId:h,operationFingerprint:H.signingOperationFingerprint(await Zn({nearAccountId:b,nearNetworkId:s(e.chains||gt.network.chains),relayerKeyId:C.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:C.threshold.thresholdKeyMaterial.publicKey,message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl})),intent:Te.TransactionSign},w={label:`NEP-413`,ctx:e,walletId:t.walletSession.walletId,nearAccountId:b,auth:p,signingSessionPlan:ee,signingOperation:ne,thresholdKeyMaterial:C.threshold.thresholdKeyMaterial,preparation:l,executor:u,intent:{kind:`nep413_message_v1`,message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl},computeSigningDigestB64u:async()=>(await Mr({message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl,workerCtx:e})).signingDigestB64u},T=await no(w,{signingAuthPlan:S,passkeyEd25519OperationStepUp:o,emailOtpEd25519StepUp:c}),E=await ao(w,T,r);U(String(h),`pre_confirmation`,v);let D=performance.now(),O=await ro(w,{touchConfirm:x,signingAuthPlan:T.preparedStepUp.confirmationAuthPayload.signingAuthPlan,nearPublicKeyStr:C.nearPublicKey,onEvent:f,title:i.title,body:i.body,confirmationConfigOverride:i.confirmationConfigOverride,request:{kind:`nep413`,message:i.message,recipient:i.recipient}});U(String(h),`confirmation`,D);let k=performance.now(),re=io(w,T,O),A=await Et({signingSessionPlan:ee,signingOperation:ne,commandKind:kt.PreparePayload,execute:async()=>await oo(w,re,E)}),j=await co(w,async()=>{let e=await so(w,A,r);return{type:Gt.SignNep413MessageSuccess,payload:{accountId:b,publicKey:e.signerPublicKey,signature:g(_(e.signatureB64u)),state:i.state??void 0}}});return U(String(h),`confirmed_to_signed`,k),{success:!0,accountId:j.payload.accountId,publicKey:j.payload.publicKey,signature:j.payload.signature,state:j.payload.state}}function ho(e){let t=e.thresholdKeyMaterial;if(!t)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let n=String(t.publicKey||``).trim();if(!n)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);if(!String(e.relayerUrl||``).trim())throw Error(`Missing relayerUrl (required for threshold-signer)`);let r=x(t.participants.map(e=>e.id));if(!r||r.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(r||[]).join(`,`)}])`);return{nearPublicKey:n,threshold:{thresholdKeyMaterial:t}}}async function go(e){if(e.chain!==`near`)throw Error(`[NearSigningFlow] invalid chain`);return e.kind===`transactionWithActions`?(_o(e.payload),await Ma(e.payload)):e.kind===`delegateAction`?(yo(e.payload),await fo(e.payload)):e.kind===`nep413`?(bo(e.payload),await mo(e.payload)):e}function _o(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required`);if(String(e.rpcCall?.nearAccountId||``).trim()!==t)throw Error(`[NearSigningFlow] rpcCall.nearAccountId must match nearAccount.accountId`);let n=e.transactions;Array.isArray(n)&&Ar(n),vo(e.transaction,0)}function vo(e,t){if(!String(e?.receiverId||``).trim())throw Error(`[NearSigningFlow] transactions[${t}].receiverId is required`);let n=Array.isArray(e?.actions)?e.actions:[];if(n.length===0)throw Error(`[NearSigningFlow] transactions[${t}].actions must be non-empty`);n.forEach(Ze)}function yo(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required`);if(String(e.rpcCall?.nearAccountId||``).trim()!==t)throw Error(`[NearSigningFlow] rpcCall.nearAccountId must match nearAccount.accountId`);if(!String(e.delegate?.receiverId||``).trim())throw Error(`[NearSigningFlow] delegate.receiverId is required`);let n=Array.isArray(e.delegate?.actions)?e.delegate.actions:[];if(n.length===0)throw Error(`[NearSigningFlow] delegate.actions must be non-empty`);n.forEach(e=>Ze(nt(e)))}function bo(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required for NEP-413`);if(String(e.payload?.accountId||``).trim()!==t)throw Error(`[NearSigningFlow] payload.accountId must match nearAccount.accountId`);if(!String(e.payload?.recipient||``).trim())throw Error(`[NearSigningFlow] recipient is required for NEP-413`);if(!String(e.payload?.message||``).trim())throw Error(`[NearSigningFlow] message is required for NEP-413`)}var xo=e({signDelegateAction:()=>cs,signNear:()=>To});function So(e){if(!(e instanceof lt))return;let t=e.authorizationDecision;if(!(!t||t.kind!==`step_up_required`||!(`request_id`in t.step_up)))return{kind:`step_up_required`,reason:t.reason,step_up:t.step_up}}function Co(e){let t=So(e),n=ot(e);return t?at(n??{kind:`exhausted`,source:`server_prepare`,detail:`Server requires owner operation step-up`}):n?.kind===`in_flight`?at(n):null}async function wo(e){if(e.failure?.kind!==`expired`)return;let t=xt({source:{kind:`ed25519`,laneIdentity:Be(e.lane)},expiresAtMs:e.expiresAtMs,detectedAtMs:Date.now()});if((await e.coordinator.invalidateExpiredWalletSession({state:t,source:R.serverRejection})).kind===`unavailable`)throw Error(`[SigningEngine][near] expired Wallet Session cleanup failed`)}async function To(e,t){if(t.kind===`transactionWithActions`){let n=e.getSignerWorkerContext(),r=te(n.touchConfirm?.getContext().surfaceMeasurementBinding);return r&&(r.assertPending(),e={...e,getSignerWorkerContext:fs.bind(null,n,r.beforeSigning)}),await is(e,t.args)}if(t.kind===`delegateAction`)return await cs(e,t.args);if(t.kind===`nep413`)return await ds(e,t.args);throw Error(`[SigningEngine] unsupported near signing intent: ${String(t.kind||``)}`)}function Eo(){let e=y(32,`NEAR transaction signing operation IDs`);return H.signingOperation(`near-transaction-sign:${e}`)}function Do(e){return e.state===`missing`?{state:e.state,curve:e.curve,chain:e.chain}:{authMethod:B(e.auth),walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,state:e.state,source:e.source||`unknown`,...e.authorizationState===`authorized`?{walletSessionId:e.authorization.operationCredential.walletSessionId,quotaId:e.authorization.session.quotaId}:{},thresholdSessionId:e.thresholdSessionId,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}}function Oo(e){let t=e?.candidates.ed25519.near||[];return{generation:e?.generation||0,candidateCount:t.length,candidates:t.map(Do)}}function ko(e,t,n){try{e?.(xe({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function Ao(e){if(ze(e.signingLane.identity)!==ze(e.transactionLane.identity))throw Error(`[SigningEngine][near] prepared signing lane drifted from selected transaction lane`)}function jo(e,t){let n=e.identity.signer,r=t.identity.signer;return String(n.account.wallet.walletId)===String(r.account.wallet.walletId)&&String(n.account.nearAccountId)===String(r.account.nearAccountId)&&String(n.nearEd25519SigningKeyId)===String(r.nearEd25519SigningKeyId)&&n.signerSlot===r.signerSlot&&De(e.auth)===De(t.auth)}function Mo(e){let t=e.readiness.status;return t===`ready`?{status:`ready`,remainingUses:Math.max(0,Math.floor(Number(e.readiness.remainingUses)||0)),expiresAtMs:Math.max(0,Math.floor(Number(e.readiness.expiresAtMs)||0))}:t===`expired`||t===`exhausted`||t===`status_unknown`?t===`status_unknown`?{status:t,reason:`trusted wallet budget status is unavailable`}:{status:t}:t===`auth_unavailable`||t===`status_unavailable`?{status:t,reason:t}:{status:`status_unavailable`,reason:t}}function No(e){if(e.curve!==`ed25519`||e.keyKind!==`threshold_ed25519`)throw Error(`[SigningEngine][near] prepared signing lane is not Ed25519`);if(e.chainFamily!==`near`)throw Error(`[SigningEngine][near] prepared Ed25519 lane must target NEAR`);let t=String(e.thresholdSessionId||``).trim(),n=String(e.walletSessionId||``).trim(),r=String(e.quotaId||``).trim();if(!t||!n||!r)throw Error(`[SigningEngine][near] prepared Ed25519 lane is missing session identity`);return{...e,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,walletSessionId:H.walletSession(n),quotaId:H.walletSessionQuota(r),thresholdSessionId:H.thresholdEd25519Session(t)}}async function Po(e){let t=e.preparedOperation,n=t.lane;Ye(`near`,n,{reason:`near_transaction_auth_planning`});let r=e.commandSubject.nearAccount.accountId,i={accountId:r,intent:Te.TransactionSign,curve:`ed25519`},a=t.signingSessionPlan;if(a.kind===V.NotReady)throw console.warn(`[SigningEngine][near][ed25519] transaction auth planning not ready`,{nearAccountId:r,authMethod:B(n.auth),reason:a.reason,readiness:t.readiness.status,walletSessionId:n.walletSessionId,quotaId:n.quotaId,thresholdSessionId:n.thresholdSessionId,retention:n.retention,remainingUses:t.remainingUses,expiresAtMs:t.expiresAtMs}),a.reason===`policy_blocked`?Error(`[SigningEngine] NEAR operation requires passkey authentication after Email OTP login`):Error(`[SigningEngine][near] signing session is not ready: ${a.reason}`);return{signingAuthPlan:It({plan:a,accountId:i.accountId,intent:i.intent,curve:i.curve,expiresAtMs:t.expiresAtMs,remainingUses:t.remainingUses}),signingLane:n}}function Fo(e){let t=String(e.providedThresholdSessionId||``).trim(),n=String(e.identity.thresholdSessionId||``).trim();if(t&&t!==n)throw Error(`[SigningEngine][near] transaction thresholdSessionId must match prepared Ed25519 identity`);return n}function Io(e){switch(e.authorization.kind){case`authorized`:return!1;case`authorization_required`:return!0;default:throw e.authorization,Error(`[SigningEngine][near] unsupported material authorization state`)}}function Lo(e){if(e.authorization.kind!==`authorized`)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return e.authorization.authorization.status.expiresAtMs}async function Ro(e){let t={walletId:I(e.commandSubject.walletSession.walletId),nearAccountId:P(e.commandSubject.nearAccount.accountId)};return e.materialIdentity?await e.deps.prepareNearEd25519YaoMaterialBoundary({...t,materialIdentity:e.materialIdentity}):await e.deps.prepareNearEd25519YaoMaterialBoundary({...t,laneIdentity:e.selectedLane.identity,auth:e.selectedLane.auth})}function zo(e,t){return H.signingOperation(e.createSigningSessionId(`near-${t}-operation`))}function Bo(e){return{kind:`prepared_near_transaction_execution`,thresholdSessionId:e.thresholdSessionId,signingSessionPlan:e.preparedSigningSession.preparedOperation.signingSessionPlan,signingAuthPlan:e.preparedSigningSession.signingAuthPlan,signingLane:e.preparedSigningSession.signingLane,signingSessionCoordinator:e.signingSessionCoordinator,transactionOperation:e.preparedSigningSession.transactionOperation,passkeyEd25519OperationStepUp:e.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.emailOtpEd25519StepUp}}function Vo(e){return ct({walletId:String(e.walletId),curve:`ed25519`,walletSessionId:String(e.prepared.signingLane.walletSessionId),quotaId:String(e.prepared.signingLane.quotaId),projectionVersion:`server-owned`,authorityKey:De(e.prepared.signingLane.auth),targetKey:`near:${String(e.nearAccountId)}`})}function Ho(e){if(e.prepared.kind!==`authorized`)throw Error(`[SigningEngine][near] deferred Ed25519 material has no reusable session`);return ct({walletId:String(e.walletId),curve:`ed25519`,walletSessionId:String(e.prepared.selectedLane.walletSessionId),quotaId:String(e.prepared.selectedLane.quotaId),projectionVersion:`projection-unadmitted`,authorityKey:De(e.prepared.selectedLane.auth),targetKey:`near:${String(e.nearAccountId)}`})}function Uo(e){if(e.auth.kind!==`passkey`)return;let t=e.auth;return{prepare:async()=>{let n=e.signer,r=await Go({authorityRef:Wo(e.preparation),walletId:n.account.wallet.walletId,rpId:t.rpId,credentialIdB64u:t.credentialIdB64u});return{thresholdSessionId:e.thresholdSessionId,authority:r}}}}function Wo(e){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:case`reauthorize_public_anchor`:return e.hydration.authority;case`blocked`:throw Error(`[SigningEngine][near] blocked Passkey material has no authority`);default:throw e.hydration,Error(`[SigningEngine][near] unsupported Passkey material authority`)}}async function Go(e){let t=ye({walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:e.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.rpId},bindingId:e.authorityRef.walletAuthMethodId});if(!t)throw Error(`[SigningEngine][near] exact Passkey step-up authority is invalid`);let n=await _e({authority:t});if(n.walletId!==e.authorityRef.walletId||n.walletAuthMethodId!==e.authorityRef.walletAuthMethodId||n.authorityDigest!==e.authorityRef.authorityDigest)throw Error(`[SigningEngine][near] exact Passkey step-up authority changed`);return t}function Ko(e){if(e.auth.kind!==se.emailOtp||typeof e.deps.requestEmailOtpEd25519SigningChallenge!=`function`||!e.preparation.hydration.materialActivation)return;if(String(e.signer.account.wallet.walletId)!==String(e.commandSubject.walletSession.walletId)||String(e.signer.account.nearAccountId)!==String(e.commandSubject.nearAccount.accountId))throw Error(`[SigningEngine][near] Email OTP step-up lane changed subject`);let t=async t=>{let n=await e.deps.requestEmailOtpEd25519SigningChallenge({walletSession:e.commandSubject.walletSession,operationFingerprintDigest:t.operationFingerprintDigest});return ko(e.onEvent,e.commandSubject.nearAccount.accountId,{phase:z.STEP_06_AUTH_EMAIL_OTP_INPUT_REQUIRED,status:`waiting_for_user`,interaction:{kind:`otp_input`,overlay:`show`},data:{emailHint:n.emailHint,demoOtpCode:be(n.delivery)}}),n};return{prepare:t,resend:t}}async function qo(e){let t=Ut({availableLanes:await ts({deps:e.deps,commandSubject:e.commandSubject,authMethod:null}),intent:Qo({commandSubject:e.commandSubject,signerSlot:e.signerSlot,authSelectionPolicy:{kind:`any`},operationUsesNeeded:1})});if(!t.ok)throw Error(`[SigningEngine][near] signature-only signing requires exact Ed25519 material`);if(t.kind===`authorization_required`){let n=t.candidate,r=Ve({walletId:n.walletId,nearAccountId:n.nearAccountId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot}),i={kind:`near_ed25519_material_identity`,signer:r,auth:n.auth,thresholdSessionId:H.thresholdEd25519Session(n.thresholdSessionId)},a=await Ro({deps:e.deps,commandSubject:e.commandSubject,materialIdentity:i});return{kind:`authorization_required`,candidate:n,materialIdentity:i,forceFreshAuth:!0,passkeyEd25519OperationStepUp:Uo({auth:n.auth,signer:r,thresholdSessionId:i.thresholdSessionId,preparation:a.preparation})||null,emailOtpEd25519StepUp:Ko({deps:e.deps,commandSubject:e.commandSubject,auth:n.auth,signer:r,preparation:a.preparation,onEvent:e.onEvent})||null,yaoSigningPreparation:a.preparation,yaoMaterialExecutor:a.executor}}let n=t.lane,r=await Ro({deps:e.deps,commandSubject:e.commandSubject,selectedLane:n});return{kind:`authorized`,selectedLane:n,forceFreshAuth:e.attempt.forceFreshAuth||Io(r.preparation),passkeyEd25519OperationStepUp:Uo({auth:n.auth,signer:n.identity.signer,thresholdSessionId:n.identity.thresholdSessionId,preparation:r.preparation})||null,emailOtpEd25519StepUp:Ko({deps:e.deps,commandSubject:e.commandSubject,auth:n.auth,signer:n.identity.signer,preparation:r.preparation,onEvent:e.onEvent})||null,yaoSigningPreparation:r.preparation,yaoMaterialExecutor:r.executor}}async function Jo(e){let t=bt({materialActivation:e.materialActivation});return await e.deps.withThresholdEd25519CommitQueue({queueKey:t,nearAccountId:e.nearAccountId,enabled:!0,task:e.task})}async function Yo(e){let t=e.availableLanes,n=Ut({availableLanes:t,intent:Qo({commandSubject:e.commandSubject,signerSlot:e.input.signerSlot,authSelectionPolicy:{kind:`any`},operationUsesNeeded:kr(e.input.transaction)})});if(!n.ok||n.kind!==`authorization_required`)return null;let r=n.candidate,i=Ve({walletId:r.walletId,nearAccountId:r.nearAccountId,nearEd25519SigningKeyId:r.nearEd25519SigningKeyId,signerSlot:r.signerSlot}),a={kind:`near_ed25519_material_identity`,signer:i,auth:r.auth,thresholdSessionId:H.thresholdEd25519Session(r.thresholdSessionId)},o=await Ro({deps:e.deps,commandSubject:e.commandSubject,materialIdentity:a});return{candidate:r,preparation:o.preparation,executor:o.executor,passkeyEd25519OperationStepUp:Uo({auth:r.auth,signer:i,thresholdSessionId:a.thresholdSessionId,preparation:o.preparation})||null,emailOtpEd25519StepUp:Ko({deps:e.deps,commandSubject:e.commandSubject,auth:r.auth,signer:i,preparation:o.preparation,onEvent:e.input.onEvent})||null}}function Xo(e){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:return e.hydration.materialActivation;case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] retired public material cannot enter the material commit queue`);case`blocked`:throw Error(`[SigningEngine][near] blocked material cannot enter the material commit queue: ${e.hydration.reason}`)}throw e.hydration,Error(`[SigningEngine][near] unsupported material hydration plan`)}function Zo(e){let t=e.authSelectionPolicy||null;if(!t)return null;let n=zt(Rt(Bt(Qo({commandSubject:e.commandSubject,signerSlot:e.signerSlot,authSelectionPolicy:t,operationUsesNeeded:e.operationUsesNeeded})),{availableLanes:e.availableLanes}));if(n.tag===`LaneSelected`){if(n.lane.curve!==`ed25519`||n.availableLane.curve!==`ed25519`)throw Error(`[SigningEngine][near] Ed25519 selector returned a non-Ed25519 lane`);return n}if(n.failure.kind===`no_candidate`)return null;throw Error(`[SigningEngine][near] Ed25519 transaction lane selection failed: ${n.failure.kind}`)}function Qo(e){return{walletId:I(e.commandSubject.walletSession.walletId),curve:`ed25519`,chain:`near`,signerSelection:$o({nearAccountId:e.commandSubject.nearAccount.accountId,signerSlot:e.signerSlot}),authSelectionPolicy:e.authSelectionPolicy,operationUsesNeeded:e.operationUsesNeeded}}function $o(e){if(e.signerSlot===void 0)return{kind:`near_account`,nearAccountId:e.nearAccountId};let t=Se(e.signerSlot);if(t===null)throw Error(`[SigningEngine][near] signerSlot must be a positive safe integer`);return{kind:`signer_slot`,nearAccountId:e.nearAccountId,signerSlot:t}}function es(e){return Zo({availableLanes:e.availableLanes,authSelectionPolicy:{kind:`any`},commandSubject:e.commandSubject,signerSlot:e.signerSlot,operationUsesNeeded:e.operationUsesNeeded})}async function ts(e){let t=e.commandSubject.nearAccount.accountId,n=e.commandSubject.walletSession.walletId;if(typeof e.deps.readAvailableSigningLanesForSigning!=`function`)throw Error(`[SigningEngine][near] transaction signing requires available signing lanes reader`);let r=await e.deps.resolveOwnerLaneScope(n);return await e.deps.readAvailableSigningLanesForSigning({walletId:n,curve:`ed25519`,ownerScope:r,...e.authMethod?{authMethod:e.authMethod}:{}}).catch(e=>(console.warn(`[SigningEngine][near] available signing lanes read failed`,{nearAccountId:t,error:e instanceof Error?e.message:String(e||`unknown error`)}),null))}async function ns(e){let t=e.commandSubject.nearAccount.accountId,n=Math.max(1,Math.floor(Number(e.operationUsesNeeded)||1)),r=e.selectedLane.lane,i=qa({commandSubject:e.commandSubject,selectedLane:r,preparation:e.preparation,forceFreshAuth:e.forceFreshAuth,requiredSignatureUses:n}),a=i.lane;Ao({signingLane:a,transactionLane:e.selectedLane.lane});let o={readiness:i.coordinatorInput.readiness,expiresAtMs:i.coordinatorInput.expiresAtMs,remainingUses:i.coordinatorInput.remainingUses};r.auth.kind===`email_otp`&&o.readiness.status!==`ready`&&console.warn(`[SigningEngine][near][email-otp] Ed25519 pre-confirm readiness is not ready`,{nearAccountId:t,readiness:o.readiness.status,thresholdSessionId:r.thresholdSessionId,walletSessionId:r.walletSessionId,quotaId:r.quotaId,retention:a.retention,remainingUses:o.remainingUses,expiresAtMs:o.expiresAtMs,requiredSignatureUses:n}),Je(`near`,Xe({event:`pre_confirm_readiness_checked`,lane:a,readinessStatus:o.readiness.status,phase:`pre_confirm`}));let s=Wt(e.selectedLane,Mo({readiness:o.readiness,expiresAtMs:o.expiresAtMs,remainingUses:o.remainingUses})),c=Vt(s),l=No(a),u={readiness:o.readiness,expiresAtMs:o.expiresAtMs,remainingUses:o.remainingUses};return{lane:a,transactionLane:e.selectedLane.lane,transactionIntent:e.selectedLane.intent,readiness:u,availableLanesGeneration:e.availableLanes?.generation||0,metadata:{transactionLane:e.selectedLane.lane,transactionOperation:c,transactionReadinessState:s,identity:l,availableLanesGeneration:e.availableLanes?.generation||0,readiness:u}}}async function rs(e){let t=e.commandSubject.nearAccount.accountId,n=kr(e.input.transaction),r=e.availableLanes,i=es({commandSubject:e.commandSubject,availableLanes:r,signerSlot:e.input.signerSlot,operationUsesNeeded:n});if(!i)throw console.warn(`[SigningEngine][near][ed25519] exact transaction lane selection failed ${JSON.stringify({nearAccountId:t,signerSlot:e.input.signerSlot??null,requiredSignatureUses:n,availableLanes:Oo(r)})}`),Error(`[SigningEngine][near] Ed25519 transaction signing requires an exact selected lane`);let a={kind:`account_class`,authMethod:B(i.lane.auth)},o=await Ro({deps:e.deps,commandSubject:e.commandSubject,selectedLane:i.lane});if(o.preparation.authorization.kind===`authorized`){let t=o.preparation.authorization.authorization;if(i.lane.walletSessionId!==t.operationCredential.walletSessionId||i.lane.quotaId!==t.session.quotaId){r=await ts({deps:e.deps,commandSubject:e.commandSubject,authMethod:B(i.lane.auth)});let a=es({commandSubject:e.commandSubject,availableLanes:r,signerSlot:e.input.signerSlot,operationUsesNeeded:n});if(!a||!jo(i.lane,a.lane)||a.lane.walletSessionId!==t.operationCredential.walletSessionId||a.lane.quotaId!==t.session.quotaId)throw Error(`[SigningEngine][near] material restoration changed the Wallet Session without an exact refreshed lane`);i=a}}let s=e.forceFreshAuth===!0||Io(o.preparation),c=await Ht({intent:Qo({commandSubject:e.commandSubject,signerSlot:e.input.signerSlot,authSelectionPolicy:a,operationUsesNeeded:n}),coordinator:e.signingSessionCoordinator,forceFreshAuth:s,sensitiveOperationPolicy:e.input.sensitivePolicy||ce.inheritSessionPolicy,onPlannerTrace:e=>qe(`near`,e),lifecycleAdapter:{prepare:async()=>{let t=await ns({deps:e.deps,commandSubject:e.commandSubject,signingSessionCoordinator:e.signingSessionCoordinator,availableLanes:r,selectedLane:i,preparation:o.preparation,forceFreshAuth:s,operationUsesNeeded:n});return{...t,metadata:t.metadata}}}}),l=c.thresholdOperation,u=c.transactionOperation,d=l.lane,f=u.lane,p=l.metadata.identity,{signingAuthPlan:m}=await Po({commandSubject:e.commandSubject,preparedOperation:l});return{preparation:o.preparation,executor:o.executor,signingAuthPlan:m,signingLane:d,transactionLane:f,identity:p,thresholdSessionId:H.thresholdEd25519Session(Fo({providedThresholdSessionId:e.input.thresholdSessionId,identity:p})),availableLanesGeneration:l.availableLanesGeneration,preparedOperation:l,transactionOperation:u}}async function is(e,t){let n=performance.now();await e.touchConfirm.openTransactionPreparationModal({chain:`near`,walletLabel:String(t.commandSubject.nearAccount.accountId),txSigningRequests:[t.transaction],model:Wn({txSigningRequests:[t.transaction],signerAccount:String(t.commandSubject.nearAccount.accountId),title:t.title,subtitle:t.body}),confirmationConfigOverride:t.confirmationConfigOverride});try{let r=Eo();return U(String(r),`preparation_modal`,n),await as(e,t,{signingOperationState:Dt({operationId:r})})}finally{e.touchConfirm.closeTransactionPreparationModal()}}async function as(e,t,n){let r=t.commandSubject.nearAccount,i=P(r.accountId),a={signerSlot:t.signerSlot,confirmationConfigOverride:t.confirmationConfigOverride,title:t.title,body:t.body,onEvent:t.onEvent},o=n.signingOperationState.operationId,s=n.signingSessionCoordinator||e.signingSessionCoordinator,c=performance.now(),l=await ts({deps:e,commandSubject:t.commandSubject,authMethod:null}),u=await Yo({deps:e,availableLanes:l,input:t,commandSubject:t.commandSubject,operationId:o});if(U(String(o),`authorization_probe`,c),u){let o=e.getSignerWorkerContext();return await Jo({deps:e,nearAccountId:i,materialActivation:Xo(u.preparation),task:async()=>await go({chain:`near`,kind:`transactionWithActions`,payload:{ctx:o,commandSubject:t.commandSubject,nearAccount:r,transaction:t.transaction,rpcCall:t.rpcCall,signerSlot:a.signerSlot,confirmationConfigOverride:a.confirmationConfigOverride,title:a.title,body:a.body,onEvent:a.onEvent,signingOperationState:n.signingOperationState,signingSessionCoordinator:s,selection:{kind:`authorization_required`,candidate:u.candidate},passkeyEd25519OperationStepUp:u.passkeyEd25519OperationStepUp||void 0,emailOtpEd25519StepUp:u.emailOtpEd25519StepUp||void 0,sensitivePolicy:t.sensitivePolicy,yaoSigningPreparation:u.preparation,yaoMaterialExecutor:u.executor}})})}let d=performance.now(),f=await rs({deps:e,availableLanes:l,input:t,commandSubject:t.commandSubject,signingSessionCoordinator:s,operationId:o,forceFreshAuth:n.forceFreshAuth===!0});U(String(o),`lane_preparation`,d);let p=performance.now(),m=f.preparation.authorization,h=f.signingAuthPlan,g=f.signingLane,_=f.transactionLane,v=f.thresholdSessionId;Ao({signingLane:g,transactionLane:_});try{return await Jo({deps:e,nearAccountId:i,materialActivation:Xo(f.preparation),task:async()=>{let i=e.getSignerWorkerContext(),c=f,l=Uo({auth:_.auth,signer:_.identity.signer,thresholdSessionId:v,preparation:c.preparation}),u=Ko({deps:e,commandSubject:t.commandSubject,auth:_.auth,signer:_.identity.signer,preparation:c.preparation,onEvent:a.onEvent}),d=Bo({preparedSigningSession:f,thresholdSessionId:v,signingSessionCoordinator:s,passkeyEd25519OperationStepUp:l||null,emailOtpEd25519StepUp:u||null}),m={thresholdSessionId:d.thresholdSessionId,signingSessionPlan:d.signingSessionPlan,signingAuthPlan:d.signingAuthPlan,signingLane:d.signingLane},h={ctx:i,commandSubject:t.commandSubject,nearAccount:r,transaction:t.transaction,rpcCall:t.rpcCall,signerSlot:a.signerSlot,confirmationConfigOverride:a.confirmationConfigOverride,title:a.title,body:a.body,onEvent:a.onEvent,signingOperationState:n.signingOperationState,signingSessionCoordinator:d.signingSessionCoordinator,selection:{kind:`authorized`,selectedLane:_},transactionOperation:d.transactionOperation,ed25519SigningBoundary:m,yaoSigningPreparation:c.preparation,yaoMaterialExecutor:c.executor,...d.passkeyEd25519OperationStepUp?{passkeyEd25519OperationStepUp:d.passkeyEd25519OperationStepUp}:{},...d.emailOtpEd25519StepUp?{emailOtpEd25519StepUp:d.emailOtpEd25519StepUp}:{}};return U(String(o),`execution_setup`,p),await go({chain:`near`,kind:`transactionWithActions`,payload:h})}})}catch(r){let o=h.kind===Tt.PasskeyReauth||h.kind===Tt.EmailOtpReauth,c=So(r),l=Co(r),u=ut(r),d=c?.kind===`step_up_required`;if(!n.retryingFreshAuth&&!o&&m.kind===`authorized`&&(d||l)){if(l?.kind===`wait_and_retry_admission`)return await st(l.retryAfterMs),await as(e,t,{forceFreshAuth:!1,signingOperationState:n.signingOperationState,retryingFreshAuth:n.retryingFreshAuth,signingSessionCoordinator:s});await wo({failure:u,coordinator:s,lane:f.transactionLane,expiresAtMs:m.authorization.status.expiresAtMs});let r=_.auth.kind===`email_otp`,o=c?.kind===`step_up_required`?c.reason:void 0,d=l?l.reason===`stale_projection`?`wallet_signing_budget_stale_projection`:`wallet_signing_budget_exhausted`:o===`wallet_session_missing`?`threshold_session_missing`:`threshold_session_expired`;if(ko(a.onEvent,i,{phase:r?z.STEP_06_AUTH_EMAIL_OTP_CHALLENGE_STARTED:z.STEP_09_THRESHOLD_SESSION_RECONNECT_STARTED,status:`running`,message:r?`Signing session needs reauthorization; requesting Email OTP`:`Signing session needs reauthorization; requesting passkey`,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,reason:d}}),l?.kind===`request_fresh_step_up`){let r=Vo({walletId:t.commandSubject.walletSession.walletId,nearAccountId:i,prepared:f});return await s.runWalletSessionQuotaAdmissionRetry({queueKey:r,refresh:async()=>await as(e,t,{forceFreshAuth:!0,signingOperationState:n.signingOperationState,retryingFreshAuth:!0,signingSessionCoordinator:s}),retryAfterRefresh:async()=>await as(e,t,{forceFreshAuth:!1,signingOperationState:n.signingOperationState,retryingFreshAuth:n.retryingFreshAuth,signingSessionCoordinator:s})})}return await as(e,t,{forceFreshAuth:!0,signingOperationState:n.signingOperationState,retryingFreshAuth:!0,signingSessionCoordinator:s})}throw r}}async function os(e){return await go({chain:`near`,kind:`delegateAction`,payload:{ctx:e.deps.getSignerWorkerContext(),commandSubject:e.input.commandSubject,nearAccount:e.input.commandSubject.nearAccount,delegate:e.input.delegate,rpcCall:e.normalizedRpcCall,signingSessionCoordinator:e.deps.signingSessionCoordinator,signerSlot:e.input.signerSlot,confirmationConfigOverride:e.input.confirmationConfigOverride,title:e.input.title,body:e.input.body,onEvent:e.input.onEvent,operationId:e.operationId,forceFreshAuth:e.prepared.forceFreshAuth,selection:e.prepared.kind===`authorized`?{kind:`authorized`,selectedLane:e.prepared.selectedLane}:{kind:`authorization_required`,candidate:e.prepared.candidate},passkeyEd25519OperationStepUp:e.prepared.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.prepared.emailOtpEd25519StepUp,yaoSigningPreparation:e.prepared.yaoSigningPreparation,yaoMaterialExecutor:e.prepared.yaoMaterialExecutor}})}async function ss(e){let t=P(e.input.commandSubject.nearAccount.accountId),n=await qo({deps:e.deps,commandSubject:e.input.commandSubject,signerSlot:e.input.signerSlot,operationId:e.operationId,onEvent:e.input.onEvent,attempt:e.attempt}),r={nearRpcUrl:e.input.rpcCall.nearRpcUrl||e.deps.nearRpcUrl,nearAccountId:t};try{return await Jo({deps:e.deps,nearAccountId:t,materialActivation:Xo(n.yaoSigningPreparation),task:os.bind(void 0,{deps:e.deps,input:e.input,operationId:e.operationId,prepared:n,normalizedRpcCall:r})})}catch(r){let i=So(r),a=Co(r);if(e.attempt.kind===`initial`&&a){if(a.kind===`wait_and_retry_admission`)return await st(a.retryAfterMs),await ss(e);let r=Ho({walletId:e.input.commandSubject.walletSession.walletId,nearAccountId:t,prepared:n});return await e.deps.signingSessionCoordinator.runWalletSessionQuotaAdmissionRetry({queueKey:r,refresh:async()=>await ss({...e,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}}),retryAfterRefresh:async()=>await ss({...e,attempt:{kind:`initial`,forceFreshAuth:!1}})})}let o=ut(r);if(e.attempt.kind===`initial`&&!n.forceFreshAuth&&i)return await wo({failure:o,coordinator:e.deps.signingSessionCoordinator,lane:n.selectedLane,expiresAtMs:Lo(n.yaoSigningPreparation)}),await ss({deps:e.deps,input:e.input,operationId:e.operationId,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}});throw r}}async function cs(e,t){try{return await ss({deps:e,input:t,operationId:zo(e,`delegate`),attempt:{kind:`initial`,forceFreshAuth:!1}})}catch(e){throw console.error(`[SigningEngine][delegate] failed`,e),e}}async function ls(e){let t=e.input.commandSubject.nearAccount;return await go({chain:`near`,kind:`nep413`,payload:{ctx:e.deps.getSignerWorkerContext(),commandSubject:e.input.commandSubject,nearAccount:t,signingSessionCoordinator:e.deps.signingSessionCoordinator,onEvent:e.input.onEvent,forceFreshAuth:e.prepared.forceFreshAuth,selection:e.prepared.kind===`authorized`?{kind:`authorized`,selectedLane:e.prepared.selectedLane}:{kind:`authorization_required`,candidate:e.prepared.candidate},passkeyEd25519OperationStepUp:e.prepared.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.prepared.emailOtpEd25519StepUp,yaoSigningPreparation:e.prepared.yaoSigningPreparation,yaoMaterialExecutor:e.prepared.yaoMaterialExecutor,payload:{message:e.input.message,recipient:e.input.recipient,nonce:e.input.nonce,callbackUrl:e.input.callbackUrl,state:e.input.state,accountId:t.accountId,signerSlot:e.input.signerSlot,title:e.input.title,body:e.input.body,confirmationConfigOverride:e.input.confirmationConfigOverride,operationId:e.operationId}}})}async function us(e){let t=P(e.input.commandSubject.nearAccount.accountId),n=await qo({deps:e.deps,commandSubject:e.input.commandSubject,signerSlot:e.input.signerSlot,operationId:e.operationId,onEvent:e.input.onEvent,attempt:e.attempt});try{return await Jo({deps:e.deps,nearAccountId:t,materialActivation:Xo(n.yaoSigningPreparation),task:ls.bind(void 0,{deps:e.deps,input:e.input,operationId:e.operationId,prepared:n})})}catch(t){let r=So(t),i=ut(t);if(e.attempt.kind===`initial`&&!n.forceFreshAuth&&r!==void 0)return await wo({failure:i,coordinator:e.deps.signingSessionCoordinator,lane:n.selectedLane,expiresAtMs:Lo(n.yaoSigningPreparation)}),await us({deps:e.deps,input:e.input,operationId:e.operationId,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}});throw t}}async function ds(e,t){try{return await us({deps:e,input:t,operationId:zo(e,`nep413`),attempt:{kind:`initial`,forceFreshAuth:!1}})}catch(e){return console.error(`SigningEngine: NEP-413 signing error:`,e),{success:!1,error:e instanceof Error?e.message:String(e||`Unknown error`)}}}function fs(e,t){return{...e,beforeSigning:t}}export{en as _,ii as a,In as c,Sn as d,xn as f,nn as g,fn as h,da as i,Fn as l,ln as m,xo as n,Hn as o,cn as p,Ua as r,Un as s,To as t,wn as u,qt as v};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as e,w as t}from"./normalize-kUDm5zfS.js";import{k as n}from"./chains-CiYQT1K4.js";import{r}from"./base64-CsEj-_bC.js";import{d as i,m as a,p as o}from"./digestEncoding-Dzc1rzWV.js";import{c as s}from"./ecdsaChainTarget-C8ZtMZ8l.js";import{a as c,c as l}from"./walletAuthority-B5hXHWpK.js";import{D as u,Dt as d,Et as f,G as p,Kt as m,Nt as h,P as g,T as _,V as v,X as y,Y as b,d as x,en as S,f as C,jt as w,m as T,mt as E,o as ee,p as te,tn as D}from"./emailOtpEcdsaDerivationIdentity-B8HzTh4T.js";import{v as O,y as k}from"./challengeDelivery-DxXAkOfS.js";import{p as A}from"./ecdsaDerivationClientWasm-CVeNEou2.js";import{a as j,n as M}from"./walletSessionFailure-Bu4VPKTz.js";import{a as N}from"./clientSessionPersistenceState-CImFWDj6.js";import{t as P}from"./bytes-BBYkulRB.js";const F=new Map;function I(e){return`${String(e.walletId)}\0${e.materialActivation.activationId}`}function L(t){let n=I(t),r=F.get(n);if(r&&(r.authorityId!==t.authorityId||r.walletAuthMethodId!==t.walletAuthMethodId||r.factorAuthority.walletId!==t.factorAuthority.walletId||r.factorAuthority.bindingId!==t.factorAuthority.bindingId||r.holderHandleId!==t.holderHandleId||!e(r.materialActivation,t.materialActivation)))throw Error(`linked ECDSA holder runtime conflicts with the active authority`);F.set(n,t)}function R(e){return F.get(I(e))??null}function z(e){return[...F.values()].filter(t=>e===void 0||t.walletId===e)}function B(e){let t=I(e),n=F.get(t);if(n){if(n.holderHandleId!==e.holderHandleId)throw Error(`linked ECDSA holder runtime changed before removal`);F.delete(t)}}function V(e){if(!e){F.clear();return}for(let[t,n]of F)n.walletId===e&&F.delete(t)}function H(e,t){return t?{kind:`blocked`,reason:e,message:t}:{kind:`blocked`,reason:e}}function U(e){return c(e)||l(e.signerActivations)?e.signerActivations:null}function W(e){if(e.kind!==`resolved`)switch(e.kind){case`missing_selection`:return H(`missing_selected_authority`);case`missing_auth_method`:case`missing_authority`:case`integrity_error`:return H(`invalid_selected_authority`);default:return e}return e.selection.walletId!==e.authMethod.walletId||e.selection.walletAuthMethodId!==e.authMethod.walletAuthMethodId||e.authMethod.walletAuthorityId!==e.authority.authorityId||e.authority.walletId!==e.selection.walletId?H(`authority_identity_mismatch`):e.selection.lockState===`unlocked`?e.authMethod.status===`active`?e.authority.state===`active`?{authMethod:e.authMethod,authority:e.authority,signerMaterials:e.signerMaterials}:H(`authority_inactive`):H(`auth_method_inactive`):H(`wallet_locked`)}function G(t){let n=t.materials.filter(n=>n.kind===`wallet_authority_linked_signer_material_v1`&&n.keyFamily===`ecdsa_secp256k1`&&n.authorityId===t.authority.authorityId&&n.walletAuthMethodId===t.authMethod.walletAuthMethodId&&n.activationId===t.materialActivation.activationId&&e(n.materialActivation,t.materialActivation)),[r]=n;return n.length===1&&r?r:null}function K(e){let t=e.material.targetFactor;return t.walletAuthMethodId===e.authMethod.walletAuthMethodId?e.authMethod.kind===`passkey`?t.kind===`passkey`&&t.rpId===e.authMethod.rpId&&t.credentialIdB64u===e.authMethod.credentialIdB64u:t.kind===`email_otp`&&t.emailHashHex===e.authMethod.emailHashHex&&t.registrationAuthorityId===e.authMethod.registrationAuthorityId:!1}function ne(t){return t.session.capabilitySubjects.filter(n=>n.kind===t.capability&&n.keyFamily===`ecdsa_secp256k1`&&e(n.materialActivation,t.materialActivation)).length===1}function q(e){try{return S(e.scope.material_activation)}catch{return null}}function J(e){try{return P(r(e.scope.public_identity.ethereum_address20_b64u))}catch{return null}}function Y(e,t){return e.linkSessionId===t.linkSessionId&&e.enrollmentId===t.enrollmentId&&e.sourceAuthorityId===t.sourceAuthorityId&&O(e.source,t.source)&&k(e.target,t.target)&&e.targetClientPublicKey33B64u===t.targetClientPublicKey33B64u}function X(e,t){return e.kind===t.kind&&E(e.scope,t.scope)}function Z(e,t){return e.applicationBindingDigestB64u===t.applicationBindingDigestB64u&&e.clientShareRetryCounter===t.clientShareRetryCounter&&e.ecdsaThresholdKeyId===t.ecdsaThresholdKeyId&&X(e.sourceNormalSigning,t.sourceNormalSigning)}function re(e,t){return e.state===t.state&&Y(e.binding,t.binding)&&Z(e.sourceDerivation,t.sourceDerivation)&&e.targetRelayerPublicKey33B64u===t.targetRelayerPublicKey33B64u&&e.thresholdPublicKey33B64u===t.thresholdPublicKey33B64u&&e.thresholdEthereumAddress20B64u===t.thresholdEthereumAddress20B64u&&X(e.normalSigning,t.normalSigning)}function ie(t){let n=R({walletId:t.walletId,materialActivation:t.materialActivation});return!n||n.walletId!==t.walletId||n.authorityId!==t.authority.authorityId||n.walletAuthMethodId!==t.authMethod.walletAuthMethodId||n.factorAuthority.walletId!==t.walletId||n.factorAuthority.bindingId!==t.authMethod.walletAuthMethodId||n.ecdsaThresholdKeyId!==t.ecdsaThresholdKeyId||!e(n.materialActivation,t.materialActivation)||!K({material:t.material,authMethod:t.authMethod})||!re(n.activationReceipt,t.material.publicFacts.activationReceipt)?null:n}async function ae(t){let n=t.holderRuntime.activationReceipt.normalSigning,r=n.scope,i=q(n),a=J(n);if(!i||!a||!e(i,t.materialActivation)||t.signer.walletId!==t.selected.authority.walletId||r.wallet_id!==String(t.selected.authority.walletId)||r.ecdsa_threshold_key_id!==String(t.holderRuntime.ecdsaThresholdKeyId)||r.public_identity.threshold_public_key33_b64u!==String(t.signer.thresholdPublicKey33B64u)||a.toLowerCase()!==String(t.signer.evmAddress).trim().toLowerCase()||String(t.holderRuntime.activationReceipt.thresholdPublicKey33B64u)!==String(r.public_identity.threshold_public_key33_b64u)||String(t.holderRuntime.activationReceipt.thresholdEthereumAddress20B64u)!==String(r.public_identity.ethereum_address20_b64u))return H(`normal_signing_identity_mismatch`);let o,s,c,l;try{l=await T({ecdsaThresholdKeyId:r.ecdsa_threshold_key_id,signingRootId:r.signing_root_id,signingRootVersion:r.signing_root_version});let e=u(t.signer.evmAddress);o=ee({walletId:t.selected.authority.walletId,ecdsaThresholdKeyId:r.ecdsa_threshold_key_id,signingRootId:r.signing_root_id,signingRootVersion:r.signing_root_version,participantIds:[1,2],thresholdOwnerAddress:e}),s=te({keyHandle:l,publicKeyB64u:r.public_identity.threshold_public_key33_b64u,participantIds:[1,2],thresholdOwnerAddress:e}),c=await m({walletId:String(o.walletId),signingRootId:String(o.signingRootId),signingRootVersion:String(o.signingRootVersion)})}catch(e){return H(`invalid_public_facts`,e instanceof Error?e.message:String(e))}if(o.ecdsaThresholdKeyId!==t.holderRuntime.ecdsaThresholdKeyId)return H(`normal_signing_identity_mismatch`);let p;try{p=await h({authority:t.factorAuthority})}catch(e){return H(`authority_identity_mismatch`,e instanceof Error?e.message:String(e))}let g={kind:`active_wallet_authority_ecdsa_runtime_v1`,walletId:t.selected.authority.walletId,authorityId:t.selected.authority.authorityId,walletAuthMethodId:t.selected.authMethod.walletAuthMethodId,authorityDigestB64u:t.selected.authority.authorityDigestB64u,factorAuthorityRef:p,authorityRevocationEpoch:t.selected.authority.revocationEpoch,walletSessionId:t.operationCredential.walletSessionId,operationCredential:t.operationCredential,session:t.session,requiredCapability:t.requiredCapability,materialActivation:t.materialActivation,ecdsaThresholdKeyId:o.ecdsaThresholdKeyId,relayerKeyId:c,authority:t.selected.authority,authMethod:t.selected.authMethod,holderRuntime:t.holderRuntime,normalSigning:n,key:o,publicFacts:s};if(t.selected.authMethod.kind===`passkey`){let e={kind:`passkey`,rpId:_(t.selected.authMethod.rpId),credentialIdB64u:t.selected.authMethod.credentialIdB64u};if(!d(t.factorAuthority)||t.factorAuthority.walletId!==o.walletId||t.factorAuthority.bindingId!==t.selected.authMethod.walletAuthMethodId||t.factorAuthority.factor.credentialIdB64u!==e.credentialIdB64u||String(t.factorAuthority.verifier.rpId)!==String(e.rpId))return H(`authority_identity_mismatch`);let n=C({walletId:o.walletId,publicFacts:s,authBinding:x({rpId:e.rpId,credentialIdB64u:e.credentialIdB64u})});return{...g,auth:e,factorAuthority:t.factorAuthority,resolvedKey:n}}if(!f(t.factorAuthority)||t.factorAuthority.walletId!==o.walletId||t.factorAuthority.bindingId!==t.selected.authMethod.walletAuthMethodId||t.factorAuthority.verifier.emailHashHex!==t.selected.authMethod.emailHashHex)return H(`authority_identity_mismatch`);let v={kind:`email_otp`,providerSubjectId:String(t.factorAuthority.factor.providerUserId)};return{...g,auth:v,factorAuthority:t.factorAuthority}}function oe(e){if(!e.chainTarget)return null;let t={kind:`active_wallet_authority_ecdsa_lane_projection_v1`,source:`active_wallet_authority`,chainTarget:e.chainTarget,runtime:e.runtime,key:e.runtime.key,materialActivation:e.runtime.materialActivation,publicFacts:e.runtime.publicFacts,state:`deferred`,authorizationState:`authorization_required`};return e.runtime.auth.kind===`passkey`?e.runtime.resolvedKey?{...t,auth:e.runtime.auth,resolvedKey:e.runtime.resolvedKey}:null:{...t,auth:e.runtime.auth}}async function se(t){let{input:n,ports:r}=t,i=n.requiredCapability||`sign`,a=Math.floor(Number(n.nowMs)||Date.now()),o;try{o=s(n.walletId)}catch(e){return H(`invalid_selected_authority`,e instanceof Error?e.message:String(e))}let c;try{c=await r.resolveSelectedWalletAuthority(String(o))}catch(e){return H(`persistence_unavailable`,e instanceof Error?e.message:String(e))}let l=W(c);if(`kind`in l)return l;let u=U(l.authority);if(!u)return H(`missing_ecdsa_signer`);let d=u.ecdsa.signer,f=u.ecdsa.materialActivation;if(n.materialActivation&&!e(n.materialActivation,f))return H(`authority_identity_mismatch`);let p=G({materials:l.signerMaterials,authority:l.authority,authMethod:l.authMethod,materialActivation:f});if(!p||!K({material:p,authMethod:l.authMethod}))return H(`missing_holder_runtime`);if(String(p.publicFacts.ecdsaThresholdKeyId)!==String(p.ecdsaThresholdKeyId))return H(`holder_runtime_identity_mismatch`);let m=ie({walletId:o,authority:l.authority,authMethod:l.authMethod,materialActivation:f,ecdsaThresholdKeyId:String(p.ecdsaThresholdKeyId),material:p});if(!m)return H(`holder_runtime_identity_mismatch`);let h;try{h=await r.readExactWithOperationCredential({walletId:o,authorityId:l.authority.authorityId,authMethodId:l.authMethod.walletAuthMethodId})}catch(e){return H(`persistence_unavailable`,e instanceof Error?e.message:String(e))}switch(h.kind){case`found`:break;case`missing`:return H(`missing_wallet_session`);case`upgrade_required`:return H(`upgrade_required`,`Wallet Session authorization requires a newer client`)}let g=h.record,_=h.operationCredential;if(g.expiresAtMs<=a)return H(`wallet_session_expired`);if(g.walletId!==o||g.authorityId!==l.authority.authorityId||g.authMethodId!==l.authMethod.walletAuthMethodId||g.authorityDigestB64u!==l.authority.authorityDigestB64u||g.authorityRevocationEpoch!==l.authority.revocationEpoch||_.walletSessionId.length===0||_.token.trim().length===0)return H(`wallet_session_identity_mismatch`);if(!ne({session:g,capability:i,materialActivation:f}))return H(`wallet_session_capability_mismatch`);let v=m.factorAuthority,y=await ae({selected:l,session:g,operationCredential:_,requiredCapability:i,signer:d,materialActivation:f,holderRuntime:m,factorAuthority:v});return y.kind===`active_wallet_authority_ecdsa_runtime_v1`?{kind:`resolved`,runtime:y,lane:oe({runtime:y,chainTarget:n.chainTarget})}:y}const ce=Symbol(`persisted-ecdsa-role-local-material`);function le(e,t){return e.bindingDigest===t.contextBinding32B64u}function ue(e,t){return e.durableMaterialRef===t.durableMaterialRef&&e.bindingDigest===t.bindingDigest}function de(e){return e instanceof Error?e.message:String(e)}function Q(e){return{kind:`corrupt`,reason:e.reason,message:e.message}}function fe(e){switch(e.failure.reason){case`missing`:return{kind:`device_link_required`,reason:`missing_local_material`};case`expired`:return Q({reason:`expired`,message:`ECDSA role-local persisted material has expired`});case`binding_mismatch`:return Q({reason:`binding_mismatch`,message:`ECDSA role-local persisted material binding does not match its public facts`});case`corrupt`:return Q({reason:`corrupt_persistence`,message:`ECDSA role-local persisted material is corrupt`});default:{let t=e.failure.reason;throw Error(`Unsupported ECDSA role-local restoration failure: ${String(t)}`)}}}function pe(e){let n=w(e.authority);if(!n)throw Error(`ECDSA role-local persisted material authority is invalid`);let r=t(e.materialActivation);if(!r.ok)throw Error(r.error.message);if(n.walletId!==e.publicFacts.walletId)throw Error(`ECDSA role-local persisted material authority does not match its wallet`);return{[ce]:!0,kind:`persisted_ecdsa_role_local_material_v1`,authority:n,materialActivation:r.value,publicFacts:e.publicFacts}}function $(e){return{kind:`persisted`,authority:e.authority,materialActivation:e.materialActivation,publicFacts:e.publicFacts}}async function me(t){switch(t.source.kind){case`unavailable`:return{kind:`device_link_required`,reason:t.source.reason};case`persisted`:try{let n=await A({authority:t.source.authority,materialActivation:t.source.materialActivation,workerCtx:t.workerCtx});return n.ok?!e(n.materialRef.materialActivation,t.source.materialActivation)||!le(n.materialRef,t.source.publicFacts)?Q({reason:`worker_identity_mismatch`,message:`ECDSA role-local worker restored a different material identity`}):ue(n.liveHandle,n.materialRef)?{kind:`rehydrated`,liveHandle:n.liveHandle,materialRef:n.materialRef}:Q({reason:`worker_identity_mismatch`,message:`ECDSA role-local worker restored a different durable material`}):fe({failure:n})}catch(e){return Q({reason:`persistence_unavailable`,message:de(e)})}default:{let e=t.source;throw Error(`Unsupported ECDSA role-local material source: ${String(e)}`)}}}function he(e){try{return y(e)}catch(e){throw Error(e instanceof Error?e.message:`ECDSA operation step-up response is invalid`)}}function ge(e){let t=String(e||``).trim().replace(/\/+$/g,``);if(!t)throw Error(`ECDSA operation step-up relayerUrl is required`);return`${t}${g}`}function _e(e){let t=String(e.walletId||``).trim(),n=String(e.operationId||``).trim(),r=Math.floor(Number(e.expiresAtMs));if(!t||!n)throw Error(`ECDSA operation step-up identity is required`);if(!Number.isSafeInteger(r)||r<=Date.now())throw Error(`ECDSA operation step-up expiry is invalid`);let i=D(e.materialActivation),a=p(e.normalSigningScope),o=String(e.keyHandle||``).trim(),s=String(e.relayerKeyId||``).trim(),c=e.participantIds;if(a.wallet_id!==t||a.signing_worker.server_id!==i.signing_worker||!o||!s||c.length!==2||c.some(e=>!Number.isSafeInteger(e)||e<=0))throw Error(`ECDSA operation step-up signing identity is inconsistent`);return{wallet_id:t,operation_kind:e.operationKind,operation_id:n,operation_digests:{lane_digest_b64u:e.operationDigests.laneDigest,intent_digest_b64u:e.operationDigests.intentDigest,display_digest_b64u:e.operationDigests.displayDigest},material_activation:i,normal_signing_scope:a,signing_worker_id:i.signing_worker,key_handle:o,relayer_key_id:s,participant_ids:[c[0],c[1]],expires_at_ms:r}}async function ve(e){let t=_e(e);return{operation:t,challengeB64u:await v(t)}}function ye(e,t){switch(e){case j.expired:case j.missing:return`Signing session expired. Sign in again to continue.`;case j.budgetExhausted:return`Signing session budget is used up. Sign in again to continue.`;default:return`ECDSA operation step-up failed: ${t}`}}async function be(e){let t=b(e.request),r=e.transport.kind===`wallet_session`?o(e.transport.credential):{};if(e.transport.kind===`factor_proof`&&t.operation.operation_kind!==`evm.export_key`)throw Error(`ECDSA signing step-up requires its Wallet Session credential`);let s=new Request(ge(e.relayerUrl),i({headers:r,body:t})),c=e.transport.kind===`wallet_session`?await a(s):await fetch(s),l=await c.json().catch(()=>null);if(!c.ok){let e=n(l,`ECDSA operation step-up response`),t=String(e.message||`HTTP ${c.status}`);throw M({code:e.code,message:ye(e.code,t)})||Error(`ECDSA operation step-up failed: ${t}`)}return he(l)}async function xe(e){return await N({...e,labels:{queue:`threshold ECDSA signing queue`,queuedOperation:`threshold ECDSA queued signing operation`},owner:String(e.walletId).trim()})}export{$ as a,V as c,B as d,R as f,pe as i,L as l,be as n,me as o,ve as r,se as s,xe as t,z as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{O as e}from"./normalize-kUDm5zfS.js";import{t}from"./errors-BZO3LF6G.js";import{d as n,h as r,p as i,u as a}from"./digestEncoding-Dzc1rzWV.js";import{c as o}from"./ecdsaChainTarget-C8ZtMZ8l.js";import{L as s,et as c,ot as l,r as u}from"./emailOtpEcdsaDerivationIdentity-B8HzTh4T.js";const d=`Your worker restarted mid-request`;function f(t,n){let r=e(t);if(!r.ok)throw Error(`${n} is invalid`);return r.value}function p(e,t){let n=typeof e==`string`?e.trim():``;if(!n)throw Error(`Missing ${t}`);return n}function m(e,t){if(typeof e!=`number`||!Number.isFinite(e))throw Error(`Missing ${t}`);return e}function h(e,t){let n=m(e,t);if(!Number.isSafeInteger(n)||n<0)throw Error(`${t} must be a non-negative integer`);return n}function g(e){if(!Array.isArray(e)||e.length===0)throw Error(`participantIds must be a non-empty array`);return e.map(e=>{let t=Number(e);if(!Number.isSafeInteger(t)||t<=0)throw Error(`participantIds must contain positive integer ids`);return t})}function _(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e)||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)throw Error(`Missing ${n}`);let r=new Set(t),i=Object.keys(e);if(i.length!==r.size||i.some(e=>!r.has(e)))throw Error(`${n} contains unexpected fields`);return e}function v(e,t,n){let r=Object.getOwnPropertyDescriptor(e,t);if(!r||!(`value`in r))throw Error(`Missing ${n}`);return r.value}const y=[`formatVersion`,`walletId`,`evmFamilySigningKeySlotId`,`ecdsaThresholdKeyId`,`relayerKeyId`,`applicationBindingDigestB64u`,`contextBinding32B64u`,`publicIdentity`,`clientShareRetryCounter`,`relayerShareRetryCounter`,`keyHandle`,`signingRootId`,`signingRootVersion`,`thresholdEcdsaPublicKeyB64u`,`ethereumAddress`,`relayerVerifyingShareB64u`,`participantIds`,`thresholdSessionId`,`activationEpoch`,`expiresAtMs`,`expiresAt`,`remainingUses`,`routerAbEcdsaDerivationNormalSigning`];function b(e){let t=_(e,[`derivationClientSharePublicKey33B64u`,`relayerPublicKey33B64u`,`groupPublicKey33B64u`,`ethereumAddress`],`publicIdentity`);return{derivationClientSharePublicKey33B64u:p(v(t,`derivationClientSharePublicKey33B64u`,`publicIdentity.derivationClientSharePublicKey33B64u`),`publicIdentity.derivationClientSharePublicKey33B64u`),relayerPublicKey33B64u:p(v(t,`relayerPublicKey33B64u`,`publicIdentity.relayerPublicKey33B64u`),`publicIdentity.relayerPublicKey33B64u`),groupPublicKey33B64u:p(v(t,`groupPublicKey33B64u`,`publicIdentity.groupPublicKey33B64u`),`publicIdentity.groupPublicKey33B64u`),ethereumAddress:p(v(t,`ethereumAddress`,`publicIdentity.ethereumAddress`),`publicIdentity.ethereumAddress`)}}function x(e){let t=_(e,y,`value`);if(v(t,`formatVersion`,`value.formatVersion`)!==`ecdsa-derivation-role-local`)throw Error(`value.formatVersion is invalid`);let n=o(v(t,`walletId`,`value.walletId`)),r=p(v(t,`evmFamilySigningKeySlotId`,`value.evmFamilySigningKeySlotId`),`evmFamilySigningKeySlotId`),i=u(v(t,`ecdsaThresholdKeyId`,`value.ecdsaThresholdKeyId`)),a=p(v(t,`relayerKeyId`,`value.relayerKeyId`),`relayerKeyId`),s=p(v(t,`applicationBindingDigestB64u`,`value.applicationBindingDigestB64u`),`applicationBindingDigestB64u`),c=p(v(t,`contextBinding32B64u`,`value.contextBinding32B64u`),`contextBinding32B64u`),d=b(v(t,`publicIdentity`,`value.publicIdentity`)),x=h(v(t,`clientShareRetryCounter`,`value.clientShareRetryCounter`),`clientShareRetryCounter`),S=h(v(t,`relayerShareRetryCounter`,`value.relayerShareRetryCounter`),`relayerShareRetryCounter`),C=p(v(t,`keyHandle`,`value.keyHandle`),`keyHandle`),w=p(v(t,`signingRootId`,`value.signingRootId`),`signingRootId`),T=p(v(t,`signingRootVersion`,`value.signingRootVersion`),`signingRootVersion`),E=g(v(t,`participantIds`,`value.participantIds`)),D=p(v(t,`thresholdSessionId`,`value.thresholdSessionId`),`thresholdSessionId`),O=f(v(t,`activationEpoch`,`value.activationEpoch`),`activationEpoch`),k=m(v(t,`expiresAtMs`,`value.expiresAtMs`),`expiresAtMs`),A=l(v(t,`routerAbEcdsaDerivationNormalSigning`,`value.routerAbEcdsaDerivationNormalSigning`));return{formatVersion:`ecdsa-derivation-role-local`,walletId:n,evmFamilySigningKeySlotId:r,ecdsaThresholdKeyId:i,relayerKeyId:a,applicationBindingDigestB64u:s,contextBinding32B64u:c,publicIdentity:d,clientShareRetryCounter:x,relayerShareRetryCounter:S,keyHandle:C,signingRootId:w,signingRootVersion:T,thresholdEcdsaPublicKeyB64u:p(v(t,`thresholdEcdsaPublicKeyB64u`,`value.thresholdEcdsaPublicKeyB64u`),`thresholdEcdsaPublicKeyB64u`),ethereumAddress:p(v(t,`ethereumAddress`,`value.ethereumAddress`),`ethereumAddress`),relayerVerifyingShareB64u:p(v(t,`relayerVerifyingShareB64u`,`value.relayerVerifyingShareB64u`),`relayerVerifyingShareB64u`),participantIds:E,thresholdSessionId:D,activationEpoch:O,expiresAtMs:k,expiresAt:p(v(t,`expiresAt`,`value.expiresAt`),`expiresAt`),remainingUses:m(v(t,`remainingUses`,`value.remainingUses`),`remainingUses`),routerAbEcdsaDerivationNormalSigning:A}}function S(e){return e?e.kind===`opaque_wallet_session_operation_credential_v1`?e.token:String(e.token||``).trim():``}function C(e){if(e.auth?.kind===`opaque_wallet_session_operation_credential_v1`)return n({headers:i(e.auth),body:e.body});let t=S(e.auth),r=String(e.publishableKeyAuth||``).trim();return n({headers:t?a({token:t,missingMessage:`bearer token is required`}):r?a({token:r,missingMessage:`publishable key auth is required`}):void 0,body:e.body})}function w(e){return{code:`http_error`,message:`HTTP ${e}`}}function T(e){try{let t=_(e,[`ok`,`code`,`message`],`relayer failure`);if(v(t,`ok`,`relayer failure.ok`)!==!1)throw Error(`invalid ok`);let n=v(t,`code`,`relayer failure.code`),r=v(t,`message`,`relayer failure.message`);if(typeof n!=`string`||!n.trim())throw Error(`invalid code`);if(typeof r!=`string`||!r.trim())throw Error(`invalid message`);return{code:n.trim(),message:r.trim()}}catch{return null}}async function E(e){let t=await O(e);return k(t)?{ok:!1,code:`worker_restarted_mid_request`,message:d}:A(t)}async function D(e,n){try{let t=r(e);if(!t)throw Error(`Missing relayServerUrl`);let i=await fetch(`${t}${s}`,C({auth:n.auth,body:n.request})),a=await E(i);if(!i.ok){let e=T(a)??w(i.status);return{ok:!1,code:e.code,message:e.message}}return{ok:!0,value:c(a)}}catch(e){return{ok:!1,error:t(e)||`Router A/B ECDSA session activation failed`}}}async function O(e){try{return await e.text()}catch{return``}}function k(e){return e.includes(d)}function A(e){try{return JSON.parse(e||`{}`)}catch(e){throw Error(`Failed to parse threshold ECDSA relayer response JSON: ${t(e)}`)}}export{x as n,D as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{B as e,I as t,L as n,P as r,V as i,d as a,g as o,z as s}from"./normalize-kUDm5zfS.js";import{c,j as l,k as u,l as d,u as f}from"./chains-CiYQT1K4.js";import{i as p,r as m}from"./base64-CsEj-_bC.js";import{_ as h,i as g,r as _,t as v}from"./primitives-CAcl7ON7.js";import{l as ee}from"./capabilityKinds-CKQ4Uqnv.js";import{a as y,n as b,r as x}from"./canonicalPrimitives-CKPGgpxg.js";import{d as te,h as S,s as C}from"./walletAuthority-B5hXHWpK.js";import{r as w}from"./walletAuthMethodRecord-CXedSgpV.js";const T=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,E=Object.freeze(Array.from(T).reduce((e,t,n)=>(e[t]=n,e),{}));function D(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 O(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+=T[t>>n&31],t&=(1<<n)-1;return r}function k(e){let t=A(e),n=[],r=0;for(let e=0;e<8;e++)n.push(t.slice(r,r+4)),r+=4;return n.join(`-`)}function ne(e){if(e.length!==10)throw Error(`Email OTP recovery code set must contain 10 keys`);return[k(e[0]),k(e[1]),k(e[2]),k(e[3]),k(e[4]),k(e[5]),k(e[6]),k(e[7]),k(e[8]),k(e[9])]}function A(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(D(t))throw Error(`Email OTP recovery key must not be decimal-only`);for(let e=0;e<t.length;e++)if(E[t[e]]===void 0)throw Error(`Email OTP recovery key contains unsupported characters`);return t}function re(e){let t=A(e),n=new Uint8Array(20),r=0,i=0,a=0;for(let e=0;e<t.length;e++)r=r<<5|E[t[e]],i+=5,i>=8&&(i-=8,n[a]=r>>i&255,r&=(1<<i)-1,a+=1);return n}async function ie(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 b(`wallet-recovery-key-v1:${p(await f(c({domain:`seams/wallet-recovery/key-lifecycle/v1`,reservationId:e.reservationId,keySetId:t})))}`)}function ae(e){if(typeof e!=`string`||e.length===0||e.length>512||e.trim()!==e||a(e))throw Error(`recovery code reservation id must be a compact opaque identifier`);return e}function oe(e){return e.kind===`passkey`?se(e):ce(e)}function se(e){let t={version:`wallet_recovery_committed_projection_v1`,storeVersion:l(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 P(t),t}function ce(e){let t={version:`wallet_recovery_committed_projection_v1`,storeVersion:l(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:H(e.emailHashHex),registrationAuthorityId:l(e.registrationAuthorityId,`registrationAuthorityId`,`is invalid`),enrollment:M(e.enrollment)}};return P(t),t}async function le(e,i){let a=F(e);if(a.version!==`wallet_recovery_committed_projection_v1`)throw Error(`wallet recovery committed projection version is invalid`);if(a.kind!==i.kind)throw Error(`wallet recovery committed projection target changed`);let o=V(n(a.walletId),`walletId`),c=V(s(a.recoveryOperationId),`recoveryOperationId`),u=V(ee(a.targetDeviceId),`targetDeviceId`),d=V(t(a.targetAuthorityId),`targetAuthorityId`),f=V(r(a.targetWalletAuthMethodId),`targetWalletAuthMethodId`),p=te(a.authority);if(!p.ok)throw Error(`wallet recovery authority projection is invalid`);let m=p.value;if(m.state!==`active`||!C(m)||!await S(m))throw Error(`wallet recovery authority projection digest or lifecycle is invalid`);let h=w(a.authMethod);if(!h||h.status!==`active`)throw Error(`wallet recovery auth method projection is invalid`);let g={version:`wallet_recovery_committed_projection_v1`,storeVersion:l(a.storeVersion,`storeVersion`,`is invalid`),walletId:o,recoveryOperationId:c,targetDeviceId:u,targetAuthorityId:d,targetWalletAuthMethodId:f,authority:m};if(i.kind===`passkey`){if(h.kind!==`passkey`)throw Error(`wallet recovery target method family changed`);let e=ue(a.target),t={...g,kind:`passkey`,authMethod:h,target:e};return N(t,i),P(t),t}if(h.kind!==`email_otp`)throw Error(`wallet recovery target method family changed`);let _=j(a.target),v={...g,kind:`google_email_otp`,authMethod:h,target:_};return N(v,i),P(v),v}function ue(t){let n=I(t);if(n.kind!==`passkey`)throw Error(`wallet recovery passkey target is invalid`);return{kind:`passkey`,rpId:V(i(n.rpId),`target.rpId`),credentialIdB64u:V(e(n.credentialIdB64u),`target.credentialIdB64u`)}}function j(e){let t=L(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:V(o(t.providerSubject),`target.providerSubject`),emailHashHex:H(t.emailHashHex),registrationAuthorityId:l(t.registrationAuthorityId,`target.registrationAuthorityId`,`is invalid`),enrollment:M(t.enrollment)}}function M(e){let t=R(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:l(t.enrollmentId,`enrollment.enrollmentId`,`is invalid`),enrollmentSealKeyVersion:l(t.enrollmentSealKeyVersion,`enrollment.enrollmentSealKeyVersion`,`is invalid`)}}function N(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 P(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 F(e){let t=z(e);if(t===null)throw Error(`wallet recovery committed projection must be an object`);return B(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 I(e){let t=z(e);if(t===null)throw Error(`wallet recovery passkey target must be an object`);return B(t,[`kind`,`rpId`,`credentialIdB64u`],`wallet recovery passkey target`),{kind:Reflect.get(t,`kind`),rpId:Reflect.get(t,`rpId`),credentialIdB64u:Reflect.get(t,`credentialIdB64u`)}}function L(e){let t=z(e);if(t===null)throw Error(`wallet recovery Google Email OTP target must be an object`);return B(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 R(e){let t=z(e);if(t===null)throw Error(`wallet recovery Email OTP enrollment must be an object`);return B(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 z(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:null}function B(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 V(e,t){if(!e.ok)throw Error(`${t} is invalid`);return e.value}function H(e){let t=l(e,`emailHashHex`,`is invalid`);if(!/^[0-9a-f]{64}$/.test(t))throw Error(`emailHashHex is invalid`);return t}const U=/^wallet-rkid-v1-[A-Za-z0-9_-]{43}$/;function W(e,t=`recoveryKeyId`){if(typeof e!=`string`||!U.test(e))throw Error(`${t} must be a derived wallet recovery key id`);return e}function de(){let e=[],t=[];for(let n=0;n<10;n+=1){let n=pe();t.push(n),e.push(k(O(n)))}return{codes:e,codeBytes:t}}function fe(e){for(let t of e.codeBytes)t.fill(0)}function pe(){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 me(e,t=`recoveryCodeLocator`){try{return x(e)}catch(e){throw Error(`${t} ${e instanceof Error?e.message:`must be a canonical digest`}`)}}async function he(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),me(p(await d(t)))}finally{t?.fill(0)}}function ge(e){return{custodySecretKind:`wallet_custody_seed_v1`,nonceB64u:e.nonceB64u,wrappedCustodySecretB64u:e.wrappedCustodySecretB64u,aadHashB64u:e.aadHashB64u}}function _e(e,t){let r=t.label||`walletRecoverySetRotation`,i=u(e,r);h(i,be,r);let a=n(i.walletId);if(!a.ok)throw Error(`${r}.walletId ${a.error.message}`);if(String(a.value)!==String(t.expectedWalletId))throw Error(`${r}.walletId is outside the authenticated wallet`);if(!Array.isArray(i.manifestKekWraps))throw Error(`${r}.manifestKekWraps must be an array`);if(i.manifestKekWraps.length!==10)throw Error(`${r}.manifestKekWraps must carry exactly 10 recovery-code wraps`);let o=i.manifestKekWraps.map((e,t)=>{let n=u(e,`${r}.manifestKekWraps[${t}]`);return h(n,ye,`${r}.manifestKekWraps[${t}]`),{recoveryKeyId:W(n.recoveryKeyId,`${r}.manifestKekWraps[${t}].recoveryKeyId`),nonceB64u:g(n.nonceB64u,`${r}.manifestKekWraps[${t}].nonceB64u`),ciphertextB64u:_(n.ciphertextB64u,`${r}.manifestKekWraps[${t}].ciphertextB64u`),aadHashB64u:v(n.aadHashB64u,`${r}.manifestKekWraps[${t}].aadHashB64u`)}}),s=new Set;for(let e of o){let t=String(e.recoveryKeyId);if(!s.add(t))throw Error(`${r} contains duplicate recovery key ids`)}if(!Array.isArray(i.entries)||i.entries.length!==1)throw Error(`${r}.entries must carry exactly one wallet custody seed entry`);let c=G(i.entries[0],`${r}.entries[0]`);return{walletId:a.value,manifestKekWraps:o,entry:c}}const ve=[`custodySecretKind`,`nonceB64u`,`wrappedCustodySecretB64u`,`aadHashB64u`],ye=[`recoveryKeyId`,`nonceB64u`,`ciphertextB64u`,`aadHashB64u`],be=[`walletId`,`manifestKekWraps`,`entries`];function G(e,t){let n=u(e,t);if(h(n,ve,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 ge({nonceB64u:g(n.nonceB64u,`${t}.nonceB64u`),wrappedCustodySecretB64u:_(n.wrappedCustodySecretB64u,`${t}.wrappedCustodySecretB64u`),aadHashB64u:v(n.aadHashB64u,`${t}.aadHashB64u`)})}function K(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function q(e,t){let n=typeof e==`string`?e.trim():``;if(!n)throw Error(`${t} is required`);return n}function xe(e){let t=K(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:q(t.walletId,`rotation worker walletId`),recoveryManifestKekWraps:t.recoveryManifestKekWraps.map((e,t)=>{let n=K(e,`rotation worker wrap ${t}`);return{recoveryKeyId:q(n.recoveryKeyId,`rotation worker wrap ${t} recoveryKeyId`),nonceB64u:q(n.nonceB64u,`rotation worker wrap ${t} nonceB64u`),ciphertextB64u:q(n.ciphertextB64u,`rotation worker wrap ${t} ciphertextB64u`),aadHashB64u:q(n.aadHashB64u,`rotation worker wrap ${t} aadHashB64u`)}}),recoveryEntryNonceB64u:q(t.recoveryEntryNonceB64u,`rotation worker recoveryEntryNonceB64u`),recoveryEntryCiphertextB64u:q(t.recoveryEntryCiphertextB64u,`rotation worker recoveryEntryCiphertextB64u`),recoveryEntryAadHashB64u:q(t.recoveryEntryAadHashB64u,`rotation worker recoveryEntryAadHashB64u`)}}function Se(e){let t=xe(e),r=n(t.walletId);if(!r.ok)throw Error(`rotation worker wallet id is invalid: ${r.error.message}`);let i={custodySecretKind:`wallet_custody_seed_v1`,nonceB64u:g(t.recoveryEntryNonceB64u,`rotation.entry.nonceB64u`),wrappedCustodySecretB64u:_(t.recoveryEntryCiphertextB64u,`rotation.entry.wrappedCustodySecretB64u`),aadHashB64u:v(t.recoveryEntryAadHashB64u,`rotation.entry.aadHashB64u`)};return _e({walletId:r.value,manifestKekWraps:t.recoveryManifestKekWraps.map(e=>({recoveryKeyId:W(e.recoveryKeyId,`rotation.recoveryKeyId`),nonceB64u:g(e.nonceB64u,`rotation.wrap.nonceB64u`),ciphertextB64u:_(e.ciphertextB64u,`rotation.wrap.ciphertextB64u`),aadHashB64u:v(e.aadHashB64u,`rotation.wrap.aadHashB64u`)})),entries:[i]},{expectedWalletId:r.value,label:`rotation.workerResult`})}const J=`secp256k1_bip340_sha256_v1`;function Y(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 X(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 Z(e){return e.startsWith(`evm_family_ecdsa:`)&&e.length>17}function Ce(e,t){let n=X(e,t);if(!Z(n))throw Error(`${t} must identify an ECDSA key set`);return n}function Q(e,t){try{return x(e)}catch{throw Error(`${t} must be canonical base64url for 32 bytes`)}}function we(e,t){if(typeof e!=`string`||!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} must be canonical base64url`);let n;try{n=m(e)}catch{throw Error(`${t} must be valid base64url`)}if(n.length!==33||n[0]!==2&&n[0]!==3||p(n)!==e)throw Error(`${t} must be canonical compressed secp256k1 public key bytes`);return e}function Te(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive safe integer`);return e}function Ee(e,t){if(typeof e!=`string`||!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`${t} must be canonical base64url`);let n;try{n=m(e)}catch{throw Error(`${t} must be valid base64url`)}if(n.length!==64||p(n)!==e)throw Error(`${t} must be canonical base64url for 64 bytes`);return e}function $(e){let t=u(e,`walletRecoveryEcdsaPossessionChallenge`);if(Y(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=Ce(t.keySetId,`walletRecoveryEcdsaPossessionChallenge.keySetId`);return{kind:`wallet_recovery_ecdsa_possession_challenge_v1`,walletId:X(t.walletId,`walletRecoveryEcdsaPossessionChallenge.walletId`),reservationId:X(t.reservationId,`walletRecoveryEcdsaPossessionChallenge.reservationId`),replacementId:X(t.replacementId,`walletRecoveryEcdsaPossessionChallenge.replacementId`),keySetId:n,keyHandle:X(t.keyHandle,`walletRecoveryEcdsaPossessionChallenge.keyHandle`),recordedKeyManifestDigestB64u:Q(t.recordedKeyManifestDigestB64u,`walletRecoveryEcdsaPossessionChallenge.recordedKeyManifestDigestB64u`),publicCapabilityDigestB64u:Q(t.publicCapabilityDigestB64u,`walletRecoveryEcdsaPossessionChallenge.publicCapabilityDigestB64u`),authorityRefDigestB64u:Q(t.authorityRefDigestB64u,`walletRecoveryEcdsaPossessionChallenge.authorityRefDigestB64u`),derivationClientSharePublicKey33B64u:we(t.derivationClientSharePublicKey33B64u,`walletRecoveryEcdsaPossessionChallenge.derivationClientSharePublicKey33B64u`),expectedServerGeneration:X(t.expectedServerGeneration,`walletRecoveryEcdsaPossessionChallenge.expectedServerGeneration`),expiresAtMs:Te(t.expiresAtMs,`walletRecoveryEcdsaPossessionChallenge.expiresAtMs`),serverNonceB64u:Q(t.serverNonceB64u,`walletRecoveryEcdsaPossessionChallenge.serverNonceB64u`)}}function De(e){let t=u(e,`walletRecoveryEcdsaPossessionProof`);if(Y(t,`walletRecoveryEcdsaPossessionProof`,[`kind`,`scheme`,`signature64B64u`]),t.kind!==`wallet_recovery_ecdsa_possession_proof_v1`)throw Error(`walletRecoveryEcdsaPossessionProof.kind is invalid`);if(t.scheme!==J)throw Error(`walletRecoveryEcdsaPossessionProof.scheme is invalid`);return{kind:`wallet_recovery_ecdsa_possession_proof_v1`,scheme:J,signature64B64u:Ee(t.signature64B64u,`walletRecoveryEcdsaPossessionProof.signature64B64u`)}}function Oe(e){let t=$(e),n=[`seams/wallet-recovery/ecdsa-existing-material-possession/v1`,J,t.walletId,t.reservationId,t.replacementId,t.keySetId,t.keyHandle,m(t.recordedKeyManifestDigestB64u),m(t.publicCapabilityDigestB64u),m(t.authorityRefDigestB64u),m(t.derivationClientSharePublicKey33B64u),t.expectedServerGeneration,m(t.serverNonceB64u),ke(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 ke(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 Ae(e){return y(Oe(e))}export{G as a,fe as c,ie as d,ae as f,Se as i,oe as l,re as m,De as n,he as o,ne as p,Ae as r,de as s,$ as t,le as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{I as e,L as t,R as n,v as r,w as i,y as a,z as o}from"./normalize-kUDm5zfS.js";import{k as s,l as c}from"./chains-CiYQT1K4.js";import{i as l}from"./base64-CsEj-_bC.js";import{_ as u,l as d,m as ee,n as te,s as f}from"./primitives-CAcl7ON7.js";import{l as ne}from"./capabilityKinds-CKQ4Uqnv.js";import{r as p}from"./canonicalPrimitives-CKPGgpxg.js";import{a as m,i as re,n as h,o as g,r as ie,s as ae,t as _}from"./digestEncoding-Dzc1rzWV.js";const oe=[`kind`,`keyFamilies`,`signers`],se=[`kind`,`keyFamily`,`walletId`,`walletKeyId`,`registeredPublicKeyB64u`],ce=[`kind`,`keyFamily`,`walletId`,`walletKeyId`,`thresholdPublicKey33B64u`,`evmAddress`];function v(e){if(e.length===0)throw Error(`exact administered signer manifest must contain at least one active family`);let t,n,r,i=new Set;for(let a of e){if(t!==void 0&&t!==a.walletId)throw Error(`exact administered signer manifest must use one wallet identity`);if(t=a.walletId,i.has(a.walletKeyId))throw Error(`exact administered signer manifest repeats wallet key ${a.walletKeyId}`);switch(i.add(a.walletKeyId),a.keyFamily){case`ed25519`:if(n!==void 0)throw Error(`exact administered signer manifest repeats the ed25519 family`);if(a.kind!==`exact_administered_ed25519_signer_v1`)throw Error(`exact administered signer manifest has an invalid Ed25519 signer`);n=a;break;case`ecdsa_secp256k1`:if(r!==void 0)throw Error(`exact administered signer manifest repeats the ecdsa family`);if(a.kind!==`exact_administered_ecdsa_signer_v1`)throw Error(`exact administered signer manifest has an invalid ECDSA signer`);r=a;break}}if(n!==void 0&&r!==void 0)return{kind:`exact_administered_signer_manifest_v1`,keyFamilies:[`ed25519`,`ecdsa_secp256k1`],signers:[n,r]};if(n!==void 0)return{kind:`exact_administered_signer_manifest_v1`,keyFamilies:[`ed25519`],signers:[n]};if(r!==void 0)return{kind:`exact_administered_signer_manifest_v1`,keyFamilies:[`ecdsa_secp256k1`],signers:[r]};throw Error(`exact administered signer manifest must contain a supported family`)}function y(e){let t=pe(e,oe,`ExactAdministeredSignerManifestV1`);if(t.kind!==`exact_administered_signer_manifest_v1`)throw Error(`ExactAdministeredSignerManifestV1.kind is invalid`);let n=ue(t.keyFamilies);if(!Array.isArray(t.signers))throw Error(`ExactAdministeredSignerManifestV1.signers must be an array`);let r=[];for(let e=0;e<t.signers.length;e+=1)r.push(le(t.signers[e],`signers[${e}]`));let i=v(r);if(!de(n,i.keyFamilies))throw Error(`ExactAdministeredSignerManifestV1.keyFamilies do not match signers`);return i}function le(e,r){let i=s(e,r);switch(i.keyFamily){case`ed25519`:if(u(i,se,r),i.kind!==`exact_administered_ed25519_signer_v1`)throw Error(`${r}.kind is invalid for Ed25519`);return{kind:`exact_administered_ed25519_signer_v1`,keyFamily:`ed25519`,walletId:d(t(i.walletId),`${r}.walletId`),walletKeyId:d(n(i.walletKeyId),`${r}.walletKeyId`),registeredPublicKeyB64u:te(i.registeredPublicKeyB64u,`${r}.registeredPublicKeyB64u`)};case`ecdsa_secp256k1`:if(u(i,ce,r),i.kind!==`exact_administered_ecdsa_signer_v1`)throw Error(`${r}.kind is invalid for ECDSA`);return{kind:`exact_administered_ecdsa_signer_v1`,keyFamily:`ecdsa_secp256k1`,walletId:d(t(i.walletId),`${r}.walletId`),walletKeyId:d(n(i.walletKeyId),`${r}.walletKeyId`),thresholdPublicKey33B64u:f(i.thresholdPublicKey33B64u,`${r}.thresholdPublicKey33B64u`),evmAddress:fe(i.evmAddress,`${r}.evmAddress`)};default:throw Error(`${r}.keyFamily is unsupported`)}}function ue(e){if(!Array.isArray(e)||e.length===0||e.length>2)throw Error(`ExactAdministeredSignerManifestV1.keyFamilies must be non-empty`);if(e.length===1&&e[0]===`ed25519`)return[`ed25519`];if(e.length===1&&e[0]===`ecdsa_secp256k1`)return[`ecdsa_secp256k1`];if(e.length===2&&e[0]===`ed25519`&&e[1]===`ecdsa_secp256k1`)return[`ed25519`,`ecdsa_secp256k1`];throw Error(`ExactAdministeredSignerManifestV1.keyFamilies must be canonical and duplicate-free`)}function de(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 fe(e,t){if(typeof e!=`string`||!/^0x[0-9a-fA-F]{40}$/.test(e))throw Error(`${t} must be a 20-byte hexadecimal EVM address`);return e}function pe(e,t,n){let r=s(e,n);u(r,t,n);for(let e of t)if(!(e in r))throw Error(`${n}.${e} is required`);return r}function b(e){return K(e)}function x(e){return G(e.signerActivations)}function me(e){return W(e.signerActivations)}function he(e){return e.provenance.kind===`wallet_recovery`}function S(e){return{kind:`wallet_ed25519_signer_activation_v1`,signer:e.signer,materialActivation:e.materialActivation}}function C(e){return{kind:`wallet_ecdsa_signer_activation_v1`,signer:e.signer,materialActivation:e.materialActivation}}function w(e){let t=y(e.manifest),n=ze(e.materialActivations);if(!Me(t.keyFamilies,n.keyFamilies))throw Error(`wallet signer activation materials must match the signer manifest families`);if(Ne(t)){if(!Ie(n))throw Error(`Ed25519 signer activation requires one Ed25519 material activation`);return{kind:`wallet_signer_activation_set_v1`,keyFamilies:[`ed25519`],ed25519:S({signer:t.signers[0],materialActivation:n.ed25519})}}if(Pe(t)){if(!Le(n))throw Error(`ECDSA signer activation requires one ECDSA material activation`);return{kind:`wallet_signer_activation_set_v1`,keyFamilies:[`ecdsa_secp256k1`],ecdsa:C({signer:t.signers[0],materialActivation:n.ecdsa})}}if(!Fe(t)||!Re(n))throw Error(`wallet signer activation set has unsupported families`);if(n.ed25519.activationId===n.ecdsa.activationId)throw Error(`wallet signer activation references must be distinct`);return{kind:`wallet_signer_activation_set_v1`,keyFamilies:[`ed25519`,`ecdsa_secp256k1`],ed25519:S({signer:t.signers[0],materialActivation:n.ed25519}),ecdsa:C({signer:t.signers[1],materialActivation:n.ecdsa})}}function ge(e){try{let t=s(e,`WalletSignerActivationSetV1`);if(t.kind!==`wallet_signer_activation_set_v1`)return Z(`wallet signer activation set kind is unsupported`);if(!Object.prototype.hasOwnProperty.call(t,`keyFamilies`))return Z(`WalletSignerActivationSetV1.keyFamilies is required`);let n=je(t.keyFamilies,`WalletSignerActivationSetV1.keyFamilies`);if(n.length===1&&n[0]===`ed25519`)return U(t,[`kind`,`keyFamilies`,`ed25519`],`WalletSignerActivationSetV1`),{ok:!0,value:{kind:`wallet_signer_activation_set_v1`,keyFamilies:[`ed25519`],ed25519:N(t.ed25519,`ed25519`)}};if(n.length===1&&n[0]===`ecdsa_secp256k1`)return U(t,[`kind`,`keyFamilies`,`ecdsa`],`WalletSignerActivationSetV1`),{ok:!0,value:{kind:`wallet_signer_activation_set_v1`,keyFamilies:[`ecdsa_secp256k1`],ecdsa:P(t.ecdsa,`ecdsa`)}};U(t,[`kind`,`keyFamilies`,`ed25519`,`ecdsa`],`WalletSignerActivationSetV1`);let r=N(t.ed25519,`ed25519`),i=P(t.ecdsa,`ecdsa`);return r.materialActivation.activationId===i.materialActivation.activationId?Z(`wallet signer activation references must be distinct`):{ok:!0,value:{kind:`wallet_signer_activation_set_v1`,keyFamilies:[`ed25519`,`ecdsa_secp256k1`],ed25519:r,ecdsa:i}}}catch(e){return Z(Q(e,`wallet signer activation set is invalid`))}}function _e(e){let t=[m(`seams/wallet-signer-activation-set/v1`,`domain`),m(e.kind,`kind`),g(e.keyFamilies.length,`keyFamilies`)];for(let n of e.keyFamilies)t.push(m(n,`keyFamilies.item`));return(W(e)||K(e))&&t.push(h(I(e.ed25519),`ed25519`)),(G(e)||K(e))&&t.push(h(L(e.ecdsa),`ecdsa`)),_(t)}async function T(e){return p(l(await c(_e(e))))}function E(e){return{kind:`wallet_authority_v1`,authorityId:e.authorityId,walletId:e.walletId,principal:e.principal,provenance:e.provenance,permissions:e.permissions,signerActivations:e.signerActivations,signerActivationSetDigestB64u:e.signerActivationSetDigestB64u,authorityDigestB64u:e.authorityDigestB64u,revocationEpoch:e.revocationEpoch,createdAtMs:e.createdAtMs,updatedAtMs:e.updatedAtMs}}function ve(e){return j(e),{...E(e),state:`pending_local_install`,localInstallPackageSetDigestB64u:e.localInstallPackageSetDigestB64u}}function D(e){return j(e),{...E(e),state:`active`,activatedAtMs:e.activatedAtMs}}async function ye(e){let t=e.authority.signerActivations;if(!t.ed25519)throw Error(`active Wallet Authority has no Ed25519 material activation to replace`);let n=t.ecdsa?w({manifest:v([t.ed25519.signer,t.ecdsa.signer]),materialActivations:{keyFamilies:[`ed25519`,`ecdsa_secp256k1`],ed25519:e.materialActivation,ecdsa:t.ecdsa.materialActivation}}):w({manifest:v([t.ed25519.signer]),materialActivations:{keyFamilies:[`ed25519`],ed25519:e.materialActivation}}),r=await T(n),i={kind:e.authority.kind,authorityId:e.authority.authorityId,walletId:e.authority.walletId,principal:e.authority.principal,provenance:e.authority.provenance,permissions:e.authority.permissions,signerActivations:n,signerActivationSetDigestB64u:r,authorityDigestB64u:e.authority.authorityDigestB64u,revocationEpoch:e.authority.revocationEpoch,createdAtMs:e.authority.createdAtMs,updatedAtMs:Math.max(e.authority.updatedAtMs,e.updatedAtMs),state:`active`,activatedAtMs:e.authority.activatedAtMs};return D({...i,authorityDigestB64u:await k(i)})}function be(e){return j(e),{...E(e),state:`active`,activatedAtMs:e.activatedAtMs}}function xe(e){return j(e),{...E(e),state:`revoked`,activatedAtMs:e.activatedAtMs,revokedAtMs:e.revokedAtMs}}const O=[`kind`,`authorityId`,`walletId`,`principal`,`provenance`,`permissions`,`signerActivations`,`signerActivationSetDigestB64u`,`authorityDigestB64u`,`revocationEpoch`,`createdAtMs`,`updatedAtMs`,`state`];function Se(e){try{let t=s(e,`WalletAuthorityV1`),n=Te(t);switch(t.state){case`pending_local_install`:return U(t,[...O,`localInstallPackageSetDigestB64u`],`WalletAuthorityV1`),{ok:!0,value:ve({kind:`wallet_authority_v1`,...n,state:`pending_local_install`,localInstallPackageSetDigestB64u:q(t.localInstallPackageSetDigestB64u,`localInstallPackageSetDigestB64u`)})};case`active`:return U(t,[...O,`activatedAtMs`],`WalletAuthorityV1`),{ok:!0,value:D({kind:`wallet_authority_v1`,...n,state:`active`,activatedAtMs:J(t.activatedAtMs,`activatedAtMs`)})};case`revoked`:return U(t,[...O,`activatedAtMs`,`revokedAtMs`],`WalletAuthorityV1`),{ok:!0,value:xe({kind:`wallet_authority_v1`,...n,state:`revoked`,activatedAtMs:J(t.activatedAtMs,`activatedAtMs`),revokedAtMs:J(t.revokedAtMs,`revokedAtMs`)})};default:return Z(`WalletAuthorityV1.state is unsupported`)}}catch(e){return Z(Q(e,`wallet authority is invalid`))}}function Ce(e){return _([m(`seams/wallet-authority/v1`,`domain`),m(e.kind,`kind`),m(e.authorityId,`authorityId`),m(e.walletId,`walletId`),h(z(e.principal),`principal`),h(B(e.provenance),`provenance`),h(V(e.permissions),`permissions`),ie(e.signerActivationSetDigestB64u,`signerActivationSetDigestB64u`),m(e.state,`state`),ae(e.revocationEpoch,`revocationEpoch`)])}async function k(e){return p(l(await c(Ce(e))))}async function A(e){return await T(e.signerActivations)===e.signerActivationSetDigestB64u?await k(e)===e.authorityDigestB64u:!1}async function we(e,t){let[n,r]=await Promise.all([A(e),A(t)]);return n&&r&&e.authorityDigestB64u===t.authorityDigestB64u&&e.signerActivationSetDigestB64u===t.signerActivationSetDigestB64u&&e.createdAtMs===t.createdAtMs&&e.updatedAtMs===t.updatedAtMs&&e.activatedAtMs===t.activatedAtMs}function Te(n){if(n.kind!==`wallet_authority_v1`)throw Error(`WalletAuthorityV1.kind is unsupported`);let r=X(e(n.authorityId),`authorityId`),i=X(t(n.walletId),`walletId`),a=Ee(n.principal),o=De(n.provenance),s=X(ee(n.permissions),`permissions`),c=X(ge(n.signerActivations),`signerActivations`),l=q(n.signerActivationSetDigestB64u,`signerActivationSetDigestB64u`),u=q(n.authorityDigestB64u,`authorityDigestB64u`),d=J(n.revocationEpoch,`revocationEpoch`),te=J(n.createdAtMs,`createdAtMs`),f=J(n.updatedAtMs,`updatedAtMs`);return M(c,i),{authorityId:r,walletId:i,principal:a,provenance:o,permissions:s,signerActivations:c,signerActivationSetDigestB64u:l,authorityDigestB64u:u,revocationEpoch:d,createdAtMs:te,updatedAtMs:f}}function j(e){if(e.kind!==`wallet_authority_v1`)throw Error(`wallet authority kind is unsupported`);if(!Number.isSafeInteger(e.revocationEpoch)||e.revocationEpoch<0)throw Error(`wallet authority revocationEpoch must be a non-negative safe integer`);if(Y(e.createdAtMs,`createdAtMs`),Y(e.updatedAtMs,`updatedAtMs`),e.updatedAtMs<e.createdAtMs)throw Error(`wallet authority updatedAtMs cannot precede createdAtMs`);switch(q(e.signerActivationSetDigestB64u,`signerActivationSetDigestB64u`),q(e.authorityDigestB64u,`authorityDigestB64u`),M(e.signerActivations,e.walletId),Oe(e.provenance),e.state){case`pending_local_install`:q(e.localInstallPackageSetDigestB64u,`localInstallPackageSetDigestB64u`);break;case`active`:Y(e.activatedAtMs,`activatedAtMs`);break;case`revoked`:if(Y(e.activatedAtMs,`activatedAtMs`),Y(e.revokedAtMs,`revokedAtMs`),e.revokedAtMs<e.activatedAtMs)throw Error(`revokedAtMs cannot precede activatedAtMs`);break}}function Ee(e){let t=H(e,[`kind`,`deviceId`],`WalletAuthorityPrincipalV1`);if(t.kind!==`owner_device`)throw Error(`wallet authority principal kind is unsupported`);return{kind:`owner_device`,deviceId:X(ne(t.deviceId),`deviceId`)}}function De(t){let n=s(t,`WalletAuthorityProvenanceV1`);switch(n.kind){case`wallet_registration`:return U(n,[`kind`],`WalletAuthorityProvenanceV1`),{kind:`wallet_registration`};case`device_link`:return U(n,[`kind`,`enrollmentId`,`sourceAuthorityId`,`linkSessionId`],`WalletAuthorityProvenanceV1`),{kind:`device_link`,enrollmentId:X(a(n.enrollmentId),`enrollmentId`),sourceAuthorityId:X(e(n.sourceAuthorityId),`sourceAuthorityId`),linkSessionId:X(r(n.linkSessionId),`linkSessionId`)};case`wallet_recovery`:return U(n,[`kind`,`recoveryOperationId`,`continuityAuthorityId`],`WalletAuthorityProvenanceV1`),{kind:`wallet_recovery`,recoveryOperationId:X(o(n.recoveryOperationId),`recoveryOperationId`),continuityAuthorityId:X(e(n.continuityAuthorityId),`continuityAuthorityId`)};default:throw Error(`wallet authority provenance kind is unsupported`)}}function Oe(e){switch(e.kind){case`wallet_registration`:return;case`device_link`:if(!e.enrollmentId||!e.sourceAuthorityId||!e.linkSessionId)throw Error(`device-link provenance requires every audit identity`);return;case`wallet_recovery`:if(!e.recoveryOperationId||!e.continuityAuthorityId)throw Error(`wallet-recovery provenance requires every audit identity`);return}Be(e,`wallet authority provenance`)}function M(e,t){if(W(e)){if(e.ed25519.signer.walletId!==t)throw Error(`Ed25519 signer activation uses a different wallet id`);return}if(G(e)){if(e.ecdsa.signer.walletId!==t)throw Error(`ECDSA signer activation uses a different wallet id`);return}if(K(e)){if(e.ed25519.signer.walletId!==t||e.ecdsa.signer.walletId!==t)throw Error(`signer activations must use the authority wallet id`);return}throw Error(`wallet signer activation families are unsupported`)}function N(e,t){let n=H(e,[`kind`,`signer`,`materialActivation`],t);if(n.kind!==`wallet_ed25519_signer_activation_v1`)throw Error(`${t}.kind is invalid`);let r=F(n.signer,`ed25519`,`${t}.signer`);if(!Ne(r))throw Error(`${t}.signer is not Ed25519`);return S({signer:r.signers[0],materialActivation:X(i(n.materialActivation),`${t}.materialActivation`)})}function P(e,t){let n=H(e,[`kind`,`signer`,`materialActivation`],t);if(n.kind!==`wallet_ecdsa_signer_activation_v1`)throw Error(`${t}.kind is invalid`);let r=F(n.signer,`ecdsa_secp256k1`,`${t}.signer`);if(!Pe(r))throw Error(`${t}.signer is not ECDSA`);return C({signer:r.signers[0],materialActivation:X(i(n.materialActivation),`${t}.materialActivation`)})}function F(e,t,n){return y({kind:`exact_administered_signer_manifest_v1`,keyFamilies:[t],signers:[e]})}function I(e){return _([m(e.kind,`ed25519.kind`),h(ke(e.signer),`ed25519.signer`),h(R(e.materialActivation),`ed25519.materialActivation`)])}function L(e){return _([m(e.kind,`ecdsa.kind`),h(Ae(e.signer),`ecdsa.signer`),h(R(e.materialActivation),`ecdsa.materialActivation`)])}function ke(e){return _([m(e.kind,`ed25519.signer.kind`),m(e.keyFamily,`ed25519.signer.keyFamily`),m(e.walletId,`ed25519.signer.walletId`),m(e.walletKeyId,`ed25519.signer.walletKeyId`),h(re(e.registeredPublicKeyB64u,`ed25519.signer.registeredPublicKeyB64u`),`ed25519.signer.registeredPublicKeyB64u`)])}function Ae(e){return _([m(e.kind,`ecdsa.signer.kind`),m(e.keyFamily,`ecdsa.signer.keyFamily`),m(e.walletId,`ecdsa.signer.walletId`),m(e.walletKeyId,`ecdsa.signer.walletKeyId`),h(re(e.thresholdPublicKey33B64u,`ecdsa.signer.thresholdPublicKey33B64u`),`ecdsa.signer.thresholdPublicKey33B64u`),m(e.evmAddress,`ecdsa.signer.evmAddress`)])}function R(e){return _([m(e.kind,`materialActivation.kind`),m(e.activationId,`materialActivation.activationId`),m(e.capability,`materialActivation.capability`),m(e.materialOwner,`materialActivation.materialOwner`),m(e.keyBinding,`materialActivation.keyBinding`),m(e.lifecycleBinding,`materialActivation.lifecycleBinding`),m(e.signingWorker,`materialActivation.signingWorker`)])}function z(e){return _([m(e.kind,`principal.kind`),m(e.deviceId,`principal.deviceId`)])}function B(e){switch(e.kind){case`wallet_registration`:return m(e.kind,`provenance.kind`);case`device_link`:return _([m(e.kind,`provenance.kind`),m(e.enrollmentId,`provenance.enrollmentId`),m(e.sourceAuthorityId,`provenance.sourceAuthorityId`),m(e.linkSessionId,`provenance.linkSessionId`)]);case`wallet_recovery`:return _([m(e.kind,`provenance.kind`),m(e.recoveryOperationId,`provenance.recoveryOperationId`),m(e.continuityAuthorityId,`provenance.continuityAuthorityId`)])}return Be(e,`wallet authority provenance`)}function V(e){let t=[g(e.length,`permissions`)];for(let n of e)t.push(h(m(n,`permissions.item`),`permissions.item`));return _(t)}function H(e,t,n){let r=s(e,n);return U(r,t,n),r}function U(e,t,n){let r=new Set(t),i=Object.keys(e);if(i.length!==t.length)throw Error(`${n} contains unexpected fields`);for(let e of i)if(!r.has(e))throw Error(`${n}.${e} is not allowed`);for(let r of t)if(!Object.prototype.hasOwnProperty.call(e,r))throw Error(`${n}.${r} is required`)}function je(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);if(e.length===1&&e[0]===`ed25519`)return[`ed25519`];if(e.length===1&&e[0]===`ecdsa_secp256k1`)return[`ecdsa_secp256k1`];if(e.length===2&&e[0]===`ed25519`&&e[1]===`ecdsa_secp256k1`)return[`ed25519`,`ecdsa_secp256k1`];throw Error(`${t} must use canonical family order`)}function Me(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 Ne(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ed25519`}function Pe(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ecdsa_secp256k1`}function Fe(e){return e.keyFamilies.length===2}function Ie(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ed25519`}function Le(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ecdsa_secp256k1`}function Re(e){return e.keyFamilies.length===2}function ze(e){if(Ie(e))return{keyFamilies:[`ed25519`],ed25519:X(i(e.ed25519),`materialActivations.ed25519`)};if(Le(e))return{keyFamilies:[`ecdsa_secp256k1`],ecdsa:X(i(e.ecdsa),`materialActivations.ecdsa`)};if(Re(e))return{keyFamilies:[`ed25519`,`ecdsa_secp256k1`],ed25519:X(i(e.ed25519),`materialActivations.ed25519`),ecdsa:X(i(e.ecdsa),`materialActivations.ecdsa`)};throw Error(`wallet signer activation materials are unsupported`)}function W(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ed25519`}function G(e){return e.keyFamilies.length===1&&e.keyFamilies[0]===`ecdsa_secp256k1`}function K(e){return e.keyFamilies.length===2}function q(e,t){try{return p(e)}catch(e){throw Error(`${t} ${Q(e,`is invalid`)}`)}}function J(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative safe integer`);return e}function Y(e,t){if(!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative safe integer`)}function X(e,t){if(e.ok)return e.value;throw Error(`${t} ${e.error.message}`)}function Z(e){return{ok:!1,error:{code:`invalid`,message:e}}}function Q(e,t){return e instanceof Error?e.message:t}function Be(e,t){throw Error(`${t} branch is unsupported: ${String(e)}`)}async function Ve(e,t,n){let r=await T(t),i={kind:`wallet_authority_v1`,authorityId:e.authorityId,walletId:e.walletId,principal:e.principal,provenance:e.provenance,permissions:e.permissions,signerActivations:t,signerActivationSetDigestB64u:r,authorityDigestB64u:e.authorityDigestB64u,revocationEpoch:e.revocationEpoch,createdAtMs:e.createdAtMs,updatedAtMs:Math.max(e.updatedAtMs,n),state:`active`,activatedAtMs:e.activatedAtMs};return be({...i,authorityDigestB64u:await k(i)})}async function He(e){if(e.ed25519.signer.walletId!==e.authority.walletId)throw Error(`NEAR signer belongs to a different wallet authority`);let t=e.authority.signerActivations.ecdsa,n=e.ed25519.signer,r=w({manifest:v([n,t.signer]),materialActivations:{keyFamilies:[`ed25519`,`ecdsa_secp256k1`],ed25519:e.ed25519.materialActivation,ecdsa:t.materialActivation}});if(!b(r))throw Error(`Deferred Ed25519 activation did not produce a combined signer activation set`);return Ve(e.authority,r,e.now)}function $(e,t){return e.authorityId===t.authorityId&&e.walletId===t.walletId&&e.revocationEpoch===t.revocationEpoch&&e.createdAtMs===t.createdAtMs&&e.activatedAtMs===t.activatedAtMs&&l(z(e.principal))===l(z(t.principal))&&l(B(e.provenance))===l(B(t.provenance))&&l(V(e.permissions))===l(V(t.permissions))}function Ue(e,t){return me(e)&&b(t.signerActivations)&&$(e,t)&&l(I(e.signerActivations.ed25519))===l(I(t.signerActivations.ed25519))}function We(e,t){return x(e)&&b(t.signerActivations)&&e.provenance.kind===`wallet_registration`&&$(e,t)&&l(L(e.signerActivations.ecdsa))===l(L(t.signerActivations.ecdsa))}export{x as a,b as c,Se as d,ge as f,y as g,A as h,He as i,Ue as l,we as m,T as n,me as o,ye as p,_e as r,he as s,k as t,We as u};
|