@seams/wallet 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/.build-inputs.sha256 +1 -1
  2. package/dist/esm/SeamsWeb/publicApi/keyExport.js +0 -2
  3. package/dist/esm/SeamsWeb/walletIframe/client/router.js +0 -4
  4. package/dist/esm/SeamsWeb/walletIframe/shared/facadeBoundary.js +0 -4
  5. package/dist/esm/core/signingEngine/routerAb/ecdsaDerivation/presignaturePool.js +24 -27
  6. package/dist/esm/plugins/plugin-utils.js +2 -142
  7. package/dist/esm/react/components/AccountMenuButton/AccountMenuDialog.js +13 -89
  8. package/dist/esm/react/components/AccountMenuButton/AuthenticationMethodsModal.js +4 -17
  9. package/dist/esm/react/components/AccountMenuButton/LinkedDevicesModal.css +0 -68
  10. package/dist/esm/react/components/AccountMenuButton/LinkedDevicesModal.js +2 -11
  11. package/dist/esm/react/components/AccountMenuButton/index.js +4 -4
  12. package/dist/esm/sdk/ecdsaDerivationExport-DOGzq0qC.js +1 -0
  13. package/dist/esm/sdk/exportKeypairOperation-DzbjKbnk.js +1 -0
  14. package/dist/esm/sdk/{host-D3Q_NsmE.js → host-DYuu07E5.js} +1 -1
  15. package/dist/{public/sdk/presignaturePool-DX_hqZ6Z.js → esm/sdk/presignaturePool-V10fZpG3.js} +1 -1
  16. package/dist/esm/sdk/{runtime-auth-DDOPe7LO.js → runtime-auth-BNR1wI8E.js} +1 -1
  17. package/dist/esm/sdk/{runtime-device-link-Bkt5AJAI.js → runtime-device-link-Dq8g_UNb.js} +1 -1
  18. package/dist/{public/sdk/runtime-ecdsa-tempo-DUOkCNFT.js → esm/sdk/runtime-ecdsa-tempo-AGjT7Xpa.js} +1 -1
  19. package/dist/esm/sdk/{runtime-email-otp-Bsv55Gin.js → runtime-email-otp-BpBOuSsT.js} +1 -1
  20. package/dist/esm/sdk/{runtime-export-D7QKXvdg.js → runtime-export-CBsacCPY.js} +1 -1
  21. package/dist/esm/sdk/{runtime-near-Bl7bBU2g.js → runtime-near-J3hKjC7G.js} +1 -1
  22. package/dist/esm/sdk/{runtime-preferences-C2Rqmp7q.js → runtime-preferences-CVt5sLvm.js} +1 -1
  23. package/dist/esm/sdk/{runtime-recovery-BMY7AkJq.js → runtime-recovery-BzewdcoT.js} +1 -1
  24. package/dist/{public/sdk/secp256k1-CL273JMp.js → esm/sdk/secp256k1-CKq7_HD-.js} +1 -1
  25. package/dist/esm/sdk/shared-BywEqTsd.js +6 -0
  26. package/dist/esm/sdk/{signEvmFamily-BE0a14MT.js → signEvmFamily-Cpm3e6Zs.js} +1 -1
  27. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  28. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  29. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  30. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  31. package/dist/public/headers.manifest.json +1 -1
  32. package/dist/public/sdk/ecdsaDerivationExport-DOGzq0qC.js +1 -0
  33. package/dist/public/sdk/exportKeypairOperation-DzbjKbnk.js +1 -0
  34. package/dist/public/sdk/{host-D3Q_NsmE.js → host-DYuu07E5.js} +1 -1
  35. package/dist/{esm/sdk/presignaturePool-DX_hqZ6Z.js → public/sdk/presignaturePool-V10fZpG3.js} +1 -1
  36. package/dist/public/sdk/{runtime-auth-DDOPe7LO.js → runtime-auth-BNR1wI8E.js} +1 -1
  37. package/dist/public/sdk/{runtime-device-link-Bkt5AJAI.js → runtime-device-link-Dq8g_UNb.js} +1 -1
  38. package/dist/{esm/sdk/runtime-ecdsa-tempo-DUOkCNFT.js → public/sdk/runtime-ecdsa-tempo-AGjT7Xpa.js} +1 -1
  39. package/dist/public/sdk/{runtime-email-otp-Bsv55Gin.js → runtime-email-otp-BpBOuSsT.js} +1 -1
  40. package/dist/public/sdk/{runtime-export-D7QKXvdg.js → runtime-export-CBsacCPY.js} +1 -1
  41. package/dist/public/sdk/{runtime-near-Bl7bBU2g.js → runtime-near-J3hKjC7G.js} +1 -1
  42. package/dist/public/sdk/{runtime-preferences-C2Rqmp7q.js → runtime-preferences-CVt5sLvm.js} +1 -1
  43. package/dist/public/sdk/{runtime-recovery-BMY7AkJq.js → runtime-recovery-BzewdcoT.js} +1 -1
  44. package/dist/{esm/sdk/secp256k1-CL273JMp.js → public/sdk/secp256k1-CKq7_HD-.js} +1 -1
  45. package/dist/public/sdk/shared-BywEqTsd.js +6 -0
  46. package/dist/public/sdk/{signEvmFamily-BE0a14MT.js → signEvmFamily-Cpm3e6Zs.js} +1 -1
  47. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  48. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  49. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  50. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  51. package/dist/public/wallet-assets.manifest.json +32 -32
  52. package/dist/public/wallet-service/index.html +4 -4
  53. package/dist/types/shared-ts/src/device-linking/contracts.d.ts +0 -9
  54. package/dist/types/shared-ts/src/utils/routerAbEcdsaDerivation.d.ts +0 -1
  55. package/dist/types/wallet/src/SeamsWeb/operations/auth/login.d.ts +1 -2
  56. package/dist/types/wallet/src/SeamsWeb/publicApi/types.d.ts +2 -11
  57. package/dist/types/wallet/src/core/signingEngine/flows/recovery/keyExportFlow.d.ts +0 -3
  58. package/dist/types/wallet/src/core/signingEngine/routerAb/ecdsaDerivation/presignaturePool.d.ts +0 -19
  59. package/dist/types/wallet/src/core/signingEngine/session/identity/ownerLaneScope.d.ts +0 -27
  60. package/dist/types/wallet/src/plugins/plugin-utils.d.ts +0 -30
  61. package/dist/types/wallet/src/react/components/AccountMenuButton/AccountMenuDialog.d.ts +1 -9
  62. package/dist/types/wallet/src/react/components/AccountMenuButton/AuthenticationMethodsModal.d.ts +1 -1
  63. package/dist/types/wallet/src/react/components/AccountMenuButton/LinkedDevicesModal.d.ts +1 -1
  64. package/package.json +1 -1
  65. package/dist/esm/plugins/headers.js +0 -55
  66. package/dist/esm/plugins/next.js +0 -196
  67. package/dist/esm/plugins/shared-ts/src/utils/normalize.js +0 -31
  68. package/dist/esm/plugins/vite.js +0 -293
  69. package/dist/esm/react/components/AccountMenuButton/icons/LayersIcon.js +0 -8
  70. package/dist/esm/sdk/ecdsaDerivationExport-CuNIssOt.js +0 -1
  71. package/dist/esm/sdk/exportKeypairOperation-Bql0I-8U.js +0 -1
  72. package/dist/esm/sdk/shared-CNT5EU_h.js +0 -6
  73. package/dist/public/sdk/ecdsaDerivationExport-CuNIssOt.js +0 -1
  74. package/dist/public/sdk/exportKeypairOperation-Bql0I-8U.js +0 -1
  75. package/dist/public/sdk/shared-CNT5EU_h.js +0 -6
  76. package/dist/types/wallet/src/plugins/headers.d.ts +0 -25
  77. package/dist/types/wallet/src/plugins/next.d.ts +0 -66
  78. package/dist/types/wallet/src/plugins/vite.d.ts +0 -74
  79. package/dist/types/wallet/src/react/components/AccountMenuButton/icons/LayersIcon.d.ts +0 -2
  80. /package/dist/esm/plugins/{wallet/src/core → core}/browser/walletIframe/hostVariant.js +0 -0
@@ -0,0 +1 @@
1
+ import{r as e}from"./domainIds-BzkGsRqO.js";import{c as t,u as n}from"./chains-C_X_fNuS.js";import{i as r,r as i}from"./base64-DW79QA0h.js";import{r as a}from"./secureRandomId-LwBFx84B.js";import{s as o}from"./walletDbName-DtRewci9.js";import{g as s}from"./capabilityKinds-N8xo_IEh.js";import{r as c}from"./canonicalPrimitives-Dsbsxgxc.js";import{c as l,o as u}from"./ecdsaChainTarget-Bfatk3oP.js";import{i as d,n as f}from"./signerDomain-Dp7BhfmZ.js";import{$ as p,C as m,J as h,Kt as g,N as _,Z as v,en as y,h as ee,tn as b,v as x}from"./emailOtpEcdsaDerivationIdentity-Bik0N8v9.js";import{B as te,C as ne,E as S,I as re,R as ie,S as C,x as ae,y as w,z as oe}from"./ecdsaCapabilityManifest-DX6TflEz.js";import{r as T}from"./types-hKLqDUhR.js";import{o as se}from"./walletSessionAuthorizationStore-DmYe-cDR.js";import{t as ce}from"./thresholdEcdsa-CneSKcRt.js";import{p as le}from"./nearEd25519YaoSigningPreparation-RIfkYN0d.js";import{a as ue,i as de,r as fe}from"./walletSessionAuthorizationProjection-DuU6w0FP.js";import{a as pe,d as me,i as he,n as ge,u as _e}from"./ecdsaDerivationClientWasm-CpjnN4aK.js";import{a as ve,r as ye,t as be}from"./walletSessionFailure-YuhraC3P.js";import{a as E,o as D}from"./signingQueue-D_Ebmzcn.js";import{t as O}from"./bytes-DZRW2UDg.js";const xe=`router-ab-ed25519-yao-seed-export-v1`;function Se(e){if(typeof e!=`object`||!e||Array.isArray(e))return null;let t=e,n=typeof t.id==`string`&&t.id.trim()?t.id.trim():void 0;return t.success===!0&&`data`in t&&t.error===void 0?{id:n,success:!0,data:t.data}:t.success===!1&&typeof t.error==`string`&&t.data===void 0?{id:n,success:!1,error:t.error}:null}function k(e){return e.kind===`credential_free_ecdsa_session_activation_authorization_v1`}function Ce(e,t){return e.error||e.message||e.code||t}function A(e){return p({kind:`router_ab_ecdsa_post_registration_session_activation_v1`,public_capability:e.publicCapability,session_policy:{threshold_session_id:e.thresholdSessionId,wallet_session_mint_id:e.walletSessionMintId,ttl_ms:e.ttlMs,remaining_uses:e.remainingUses,runtime_policy_scope:e.runtimePolicyScope}})}function we(e,t){let n=t.public_identity;return e.applicationBindingDigestB64u===t.context.application_binding_digest_b64u&&e.contextBinding32B64u===n.context_binding_b64u&&e.derivationClientSharePublicKey33B64u===n.derivation_client_share_public_key33_b64u&&e.relayerPublicKey33B64u===n.server_public_key33_b64u&&e.groupPublicKey33B64u===n.threshold_public_key33_b64u&&e.ethereumAddress.toLowerCase()===O(i(n.ethereum_address20_b64u))&&w(e.publicCapability,t)}function Te(e,t){let n=e.normal_signing.scope;return n.wallet_id===String(t.walletId)&&n.ecdsa_threshold_key_id===String(t.ecdsaThresholdKeyId)&&n.signing_root_id===String(t.signingRootId)&&n.signing_root_version===String(t.signingRootVersion)}function Ee(e){let t=e.persistedRoleLocalMaterial.publicFacts;if(!w(e.sessionActivation.public_capability,e.publicCapability)||e.sessionActivation.session.threshold_session_id!==e.thresholdSessionId||!Te(e.sessionActivation,t))throw Error(`Strict ECDSA session activation returned a different registered key identity`)}function De(t){let n=t.sessionActivation.activation,r=t.sessionActivation.authorization,i=r.record,a=y(n.public_capability.material_activation),o=0;for(let t of i.capabilitySubjects)t.kind===`sign`&&t.keyFamily===`ecdsa_secp256k1`&&e(t.materialActivation,a)&&(o+=1);if(Ee({publicCapability:t.publicCapability,persistedRoleLocalMaterial:t.persistedRoleLocalMaterial,thresholdSessionId:t.thresholdSessionId,sessionActivation:n}),String(i.walletId)!==t.walletId||String(i.walletId)!==String(n.public_capability.client_id)||i.authMethodId!==t.persistedRoleLocalMaterial.authority.walletAuthMethodId||i.authorizationId!==n.session.authorization_id||i.quotaId!==n.session.quota_id||i.expiresAtMs!==n.session.expires_at_ms||n.session.remaining_uses!==t.remainingUses||r.operationCredential.walletSessionId!==n.session.wallet_session_id||!e(a,t.persistedRoleLocalMaterial.materialActivation)||o!==1)throw Error(`Strict ECDSA credential-free activation authority does not match its session`)}function j(e){let t=e.persistedRoleLocalMaterial.publicFacts;if(!e.walletId||!e.thresholdSessionId)throw Error(`Strict ECDSA session activation requires exact wallet and session identity`);if(!Number.isSafeInteger(e.ttlMs)||e.ttlMs<1)throw Error(`Strict ECDSA session activation requires a positive ttlMs`);if(!Number.isSafeInteger(e.remainingUses)||e.remainingUses<1)throw Error(`Strict ECDSA session activation requires positive remainingUses`);if(String(t.walletId)!==e.walletId||!we(t,e.publicCapability))throw Error(`Strict ECDSA session activation requires exact registered role-local material`)}function Oe(e){switch(e.kind){case`rehydrated`:return e;case`device_link_required`:throw Error(`device_link_required: registered ECDSA role-local material is unavailable on this device`);case`corrupt`:throw Error(`Registered ECDSA role-local material is corrupt (${e.reason}): ${e.message}`);default:{let t=e;throw Error(`Unsupported ECDSA role-local material resolution: ${String(t)}`)}}}async function M(e){let t=Oe(await D({purpose:`registration_activation`,source:E(e.persistedRoleLocalMaterial),workerCtx:e.workerCtx}));return{kind:`existing_ecdsa_role_local_material_activated_v1`,roleLocalMaterial:t.liveHandle,roleLocalMaterialRef:t.materialRef,publicFacts:e.persistedRoleLocalMaterial.publicFacts,publicCapability:e.publicCapability}}async function ke(e){j(e);let t=await ce(e.relayerUrl,{auth:e.routeAuth,request:A(e)});if(!t.ok)throw Error(Ce(t,`Strict ECDSA session activation failed`));return await N({workerCtx:e.workerCtx,publicCapability:e.publicCapability,persistedRoleLocalMaterial:e.persistedRoleLocalMaterial,walletId:e.walletId,thresholdSessionId:e.thresholdSessionId,ttlMs:e.ttlMs,remainingUses:e.remainingUses,runtimePolicyScope:e.runtimePolicyScope,sessionActivation:t.value})}async function N(e){return j(e),Ee({publicCapability:e.publicCapability,persistedRoleLocalMaterial:e.persistedRoleLocalMaterial,thresholdSessionId:e.thresholdSessionId,sessionActivation:e.sessionActivation}),{sessionActivation:e.sessionActivation,roleLocalActivation:await M(e)}}async function Ae(e){return j(e),De(e),{sessionActivation:e.sessionActivation.activation,authorization:e.sessionActivation.authorization,roleLocalActivation:await M(e)}}async function je(e,t){let n=o(e.lanePolicy.runtimePolicyScope);if(!n)throw Error(`Strict ECDSA session activation requires runtimePolicyScope`);let r={workerCtx:e.workerCtx,publicCapability:e.publicCapability,persistedRoleLocalMaterial:e.existingRoleLocalMaterial,walletId:String(e.key.walletId),thresholdSessionId:e.lanePolicy.thresholdSessionId,ttlMs:e.lanePolicy.ttlMs,remainingUses:e.lanePolicy.remainingUses,runtimePolicyScope:n},s=e.sessionActivation?k(e.sessionActivation)?await Ae({...r,sessionActivation:e.sessionActivation}):await N({...r,sessionActivation:e.sessionActivation}):await ke({...r,walletSessionMintId:Me(),relayerUrl:e.relayerUrl,routeAuth:e.bootstrapAuth}),c=s.sessionActivation.public_capability.public_identity,l=`authorization`in s?{thresholdSessionId:s.sessionActivation.session.threshold_session_id,authorizationSessionId:s.sessionActivation.session.authorization_session_id,authorizationId:s.sessionActivation.session.authorization_id,walletSessionId:s.sessionActivation.session.wallet_session_id,quotaId:s.sessionActivation.session.quota_id,expiresAtMs:s.sessionActivation.session.expires_at_ms,remainingUses:s.sessionActivation.session.remaining_uses,walletSession:s.authorization.record,operationCredential:s.authorization.operationCredential}:{thresholdSessionId:s.sessionActivation.session.threshold_session_id,authorizationSessionId:s.sessionActivation.session.authorization_session_id,authorizationId:s.sessionActivation.session.authorization_id,walletSessionId:s.sessionActivation.session.wallet_session_id,quotaId:s.sessionActivation.session.quota_id,expiresAtMs:s.sessionActivation.session.expires_at_ms,remainingUses:s.sessionActivation.session.remaining_uses,walletSession:s.sessionActivation.session.wallet_session,operationCredential:s.sessionActivation.session.operation_credential},u=await g({walletId:String(e.key.walletId),signingRootId:e.key.signingRootId,signingRootVersion:e.key.signingRootVersion});return{ok:!0,bootstrapKind:`strict_post_registration`,keygenSessionId:String(e.requestId||``).trim()||a(`tecdsa-keygen`,32,`threshold ECDSA session IDs`),rpId:t,keyHandle:String(e.keyHandle),clientVerifyingShareB64u:c.derivation_client_share_public_key33_b64u,thresholdEcdsaPublicKeyB64u:c.threshold_public_key33_b64u,ethereumAddress:O(i(c.ethereum_address20_b64u)),relayerKeyId:u,relayerVerifyingShareB64u:c.server_public_key33_b64u,participantIds:e.key.participantIds.map(Number),thresholdSessionId:l.thresholdSessionId,authorizationSessionId:l.authorizationSessionId,authorizationId:l.authorizationId,walletSessionId:l.walletSessionId,quotaId:l.quotaId,expiresAtMs:l.expiresAtMs,remainingUses:l.remainingUses,runtimePolicyScope:n,signingRootId:String(e.key.signingRootId),signingRootVersion:String(e.key.signingRootVersion),walletSession:l.walletSession,operationCredential:l.operationCredential,roleLocalActivation:s.roleLocalActivation,routerAbEcdsaDerivationNormalSigning:s.sessionActivation.normal_signing,secretSourceKind:`persisted_role_local`}}function Me(){let e=s(a(`wallet-session-mint`,32,`Wallet Session mint IDs`));if(!e.ok)throw Error(`Failed to create Wallet Session mint identity`);return e.value}async function Ne(e){let t=e.touchIdPrompt.getRpId();if(!t)return{ok:!1,code:`invalid_args`,message:`Missing rpId for WebAuthn`};try{return await je(e,t)}catch(e){return{ok:!1,code:`strict_post_registration_failed`,message:e instanceof Error?e.message:String(e)}}}const P=`stale_ecdsa_key_identity`;function Pe(e){if(!e)throw Error(`Strict ECDSA session bootstrap requires Wallet Session authority`);switch(e.kind){case`opaque_wallet_session_operation_credential_v1`:return e;case`publishable_key`:throw Error(`Strict ECDSA session bootstrap requires Wallet Session authority`)}throw Error(`Strict ECDSA session bootstrap authority is invalid`)}function Fe(e){let t=String(e.code||``).trim(),n=String(e.message||``).trim().toLowerCase();return t===`stale_session_state`&&n.includes(`threshold-ecdsa bootstrap`)&&n.includes(`client verifying share`)&&n.includes(`integrated key record`)}function Ie(e){let t=String(e.message||e.code||`threshold-ecdsa bootstrap failed`).trim(),n=Fe(e)?P:String(e.code||`threshold_ecdsa_bootstrap_failed`).trim()||`threshold_ecdsa_bootstrap_failed`,r=Error(t||`threshold-ecdsa bootstrap failed`);return r.code=n,r}function Le(e){let t=Error(e);return t.code=P,t}function Re(e){switch(e.authKind){case`email_otp`:return`email_otp`;case`passkey`:return`passkey`}return`unknown`}function ze(e){switch(e.bootstrap.secretSourceKind){case`persisted_role_local`:return e.request.authKind===`email_otp`?ae({authSubjectId:e.request.emailOtpWorkerSessionHandle.authSubjectId}):C({credentialIdB64u:e.request.passkeyCredentialIdB64u,rpId:e.bootstrap.rpId})}}function F(e,t){let n=String(e||``).trim().toLowerCase();if(!/^0x[0-9a-f]{40}$/.test(n))throw Error(`threshold-ecdsa exact activation returned invalid ${t}`);return n}function Be(e){let t=F(e.bootstrapOwnerAddress,`server owner address`);if(t!==F(e.key.thresholdOwnerAddress,`key owner address`))throw Le(`threshold-ecdsa exact activation owner address mismatches server bootstrap result`);return t}async function Ve(e,t){let n=l(String(t.key.walletId)),r=t.lanePolicy.chainTarget,i=String(t.lanePolicy.thresholdSessionId).trim();if(e.routerAbNormalSigning.mode!==`enabled`)throw Error(`Router A/B ECDSA derivation normal signing must be enabled for activation`);let a={walletId:n,chainTarget:r,targetKey:u(r),operationId:i||null,authMethod:Re(t),evmFamilyKeyFingerprint:ee(t.key),keyHandle:t.keyHandle,chainTargetKey:u(r),ecdsaThresholdKeyId:String(t.key.ecdsaThresholdKeyId),thresholdSessionId:i||null,freshAuthRetrySideEffectState:`not_applicable`,hasRequestedEcdsaThresholdKeyId:!0,requestedSessionId:i||null,authKind:t.walletSessionRouteAuth?.kind||`none`,passkeyCredentialBound:t.authKind===`passkey`},o;try{o=await Ne({touchIdPrompt:e.touchIdPrompt,relayerUrl:t.relayerUrl,requestId:t.requestId,workerCtx:e.workerCtx,...`preauthorizedSessionActivation`in t&&t.preauthorizedSessionActivation?{sessionActivation:t.preauthorizedSessionActivation}:{bootstrapAuth:Pe(t.walletSessionRouteAuth)},keyHandle:t.keyHandle,key:t.key,lanePolicy:t.lanePolicy,publicCapability:t.publicCapability,existingRoleLocalMaterial:t.existingRoleLocalMaterial})}catch(e){try{console.warn(`[threshold-ecdsa][bootstrap][exception]`,{...a,message:e instanceof Error?e.message:String(e)})}catch{}throw e}if(!o.ok){try{console.warn(`[threshold-ecdsa][bootstrap][failure]`,{...a,code:o.code||``,message:o.message||``})}catch{}throw Ie({code:o.code,message:o.message})}let s=String(t.key.ecdsaThresholdKeyId).trim();if(!s)throw Error(`threshold-ecdsa bootstrap returned empty ecdsaThresholdKeyId`);let c=re(s),d=oe(String(o.keyHandle||``).trim()),f=String(o.relayerKeyId||``).trim();if(!f)throw Error(`threshold-ecdsa bootstrap returned empty relayerKeyId`);let p=te(f),m=String(o.clientVerifyingShareB64u||``).trim();if(!m)throw Error(`threshold-ecdsa bootstrap returned empty clientVerifyingShareB64u`);let h=ie(m),g=String(o.thresholdSessionId||``).trim();if(!g)throw Error(`threshold-ecdsa bootstrap returned empty thresholdSessionId`);let _=Number(o.expiresAtMs);if(!Number.isFinite(_))throw Error(`threshold-ecdsa bootstrap returned invalid expiresAtMs`);let v=Number(o.remainingUses);if(!Number.isFinite(v))throw Error(`threshold-ecdsa bootstrap returned invalid remainingUses`);let y=t.key.participantIds.map(e=>Number(e));if(!y)throw Error(`threshold-ecdsa bootstrap returned empty participantIds`);let b=Be({key:t.key,bootstrapOwnerAddress:o.ethereumAddress}),x=ne({walletId:n,chainTarget:r,keyHandle:d,ecdsaThresholdKeyId:c,signingRootId:o.signingRootId,signingRootVersion:o.signingRootVersion,applicationBindingDigestB64u:o.roleLocalActivation.publicCapability.context.application_binding_digest_b64u,clientParticipantId:1,relayerParticipantId:2,participantIds:y,contextBinding32B64u:o.roleLocalActivation.publicFacts.contextBinding32B64u,derivationClientSharePublicKey33B64u:o.roleLocalActivation.publicFacts.derivationClientSharePublicKey33B64u,relayerPublicKey33B64u:o.roleLocalActivation.publicFacts.relayerPublicKey33B64u,groupPublicKey33B64u:o.roleLocalActivation.publicFacts.groupPublicKey33B64u,ethereumAddress:o.roleLocalActivation.publicFacts.ethereumAddress,publicCapability:o.roleLocalActivation.publicCapability}),S=o.routerAbEcdsaDerivationNormalSigning,C=o.roleLocalActivation.roleLocalMaterial,ae=ze({request:t,bootstrap:o}),w={ok:!0,thresholdSessionId:g,authorizationSessionId:o.authorizationSessionId,authorizationId:o.authorizationId,walletSessionId:o.walletSessionId,quotaId:o.quotaId,expiresAtMs:_,remainingUses:v,runtimePolicyScope:o.runtimePolicyScope,walletSession:o.walletSession,operationCredential:o.operationCredential,clientVerifyingShareB64u:h};return{thresholdEcdsaKeyRef:{type:`threshold-ecdsa-secp256k1`,userId:n,chainTarget:r,relayerUrl:t.relayerUrl,keyHandle:d,ecdsaThresholdKeyId:c,backendBinding:{materialKind:`role_local_worker_handle`,relayerKeyId:p,clientVerifyingShareB64u:h,roleLocalMaterialHandle:C,roleLocalMaterialRef:o.roleLocalActivation.roleLocalMaterialRef,publicFacts:x,authMethod:ae},participantIds:y,thresholdEcdsaPublicKeyB64u:o.thresholdEcdsaPublicKeyB64u,ethereumAddress:b,relayerVerifyingShareB64u:o.relayerVerifyingShareB64u,routerAbEcdsaDerivationNormalSigning:S},session:w}}async function He(e,t){return await Ve(e,t)}function Ue(e){let t;try{t=c(e.evidenceSetDigest)}catch(e){throw Error(e instanceof Error?e.message:`ECDSA explicit export evidence digest is invalid`)}let n=Math.floor(Number(e.expiresAtMs)),r=v(e.operation);if(r.operation_kind!==`evm.export_key`)throw Error(`ECDSA explicit export operation kind is invalid`);if(!Number.isSafeInteger(n)||n<=Date.now())throw Error(`ECDSA explicit export operation authorization expiry is invalid`);let i=We(e.unseal);return{kind:`verified_step_up`,evidenceSetDigest:t,operation:r,expiresAtMs:n,quotaUse:`none`,unseal:i}}function We(e){switch(e.kind){case`not_requested`:return{kind:`not_requested`};case`email_otp_grant`:{let t=String(e.grant||``).trim(),n=String(e.challenge_id||``).trim();if(!t||!n)throw Error(`ECDSA explicit export Email OTP unseal grant is invalid`);return{kind:`email_otp_grant`,grant:t,challenge_id:n}}default:{let t=e;throw Error(`Unsupported ECDSA explicit export unseal state: ${String(t)}`)}}}async function I(e){let t=String(e.relayerUrl||``).trim();if(!t)throw Error(`ECDSA explicit export relayer URL is required`);return{kind:`explicit_key_export_ecdsa_activation_result`,purpose:`explicit_key_export`,material:{kind:`auth_neutral_ecdsa_export_material_v1`,relayerUrl:t,persistedMaterial:e.existingRoleLocalMaterial},authorization:Ue(e.authorization)}}function L(e,t){let n=String(e||t||``).trim();if(!n)throw Error(`Missing relayer url (configs.network.relayer.url)`);return n}function R(e){return`key`in e&&!!e.key&&`keyHandle`in e&&!!String(e.keyHandle||``).trim()}function z(e){return R(e)?e.key.walletId:e.walletId}function B(e){return R(e)?e.lanePolicy.chainTarget:e.chainTarget}function Ge(e){return e.kind===`email_otp_ecdsa_bootstrap`?{authMethod:f.emailOtp,signerSource:d.emailOtpRegistration}:{authMethod:f.passkey,signerSource:d.passkeyRegistration}}function Ke(e){switch(e.kind){case`passkey_preauthorized_ecdsa_bootstrap`:case`wallet_session_reconnect_ecdsa_bootstrap`:return e.authorizationAuthority;case`passkey_fresh_ecdsa_bootstrap`:case`email_otp_ecdsa_bootstrap`:return e.existingRoleLocalMaterial.authority}}function qe(e){if(!(`sessionActivation`in e.request)||!e.request.sessionActivation)return;let t=e.request.sessionActivation,n=k(t)?t.activation:t,r=k(t)?t.authorization:{record:t.session.wallet_session,operationCredential:t.session.operation_credential};ue({walletId:e.walletId,authority:e.authority,walletSession:r.record,operationCredential:r.operationCredential,expectedAuthorizationId:n.session.authorization_id,expectedWalletSessionId:n.session.wallet_session_id,expectedQuotaId:n.session.quota_id,expectedExpiresAtMs:n.session.expires_at_ms}),e.request.kind===`passkey_preauthorized_ecdsa_bootstrap`&&de({expected:e.request.authorizationIdentity,walletSession:r.record})}function Je(e,t){let n=(e,n,r)=>({kind:`session_bootstrap`,purpose:`transaction_signing`,relayerUrl:t,keyHandle:m(e.keyHandle),key:e.key,lanePolicy:e.lanePolicy,publicCapability:e.publicCapability,existingRoleLocalMaterial:e.existingRoleLocalMaterial,...e.requestId?{requestId:e.requestId}:{},...r,...n?{walletSessionRouteAuth:n}:{}}),r=e=>({kind:`session_bootstrap`,purpose:`transaction_signing`,relayerUrl:t,keyHandle:m(e.keyHandle),key:e.key,lanePolicy:e.lanePolicy,publicCapability:e.publicCapability,existingRoleLocalMaterial:e.existingRoleLocalMaterial,...e.requestId?{requestId:e.requestId}:{},authKind:`passkey`,passkeyCredentialIdB64u:e.passkeyCredentialIdB64u,preauthorizedSessionActivation:e.sessionActivation});switch(e.kind){case`passkey_fresh_ecdsa_bootstrap`:return n(e,e.routeAuth,{authKind:`passkey`,passkeyCredentialIdB64u:e.passkeyCredentialIdB64u});case`passkey_preauthorized_ecdsa_bootstrap`:return r(e);case`wallet_session_reconnect_ecdsa_bootstrap`:return n(e,e.routeAuth,{authKind:`passkey`,passkeyCredentialIdB64u:e.passkeyCredentialIdB64u});case`email_otp_ecdsa_bootstrap`:{let r={authKind:`email_otp`,emailOtpWorkerSessionHandle:e.emailOtpWorkerSessionHandle};return e.sessionActivation?{kind:`session_bootstrap`,purpose:`transaction_signing`,relayerUrl:t,keyHandle:m(e.keyHandle),key:e.key,lanePolicy:e.lanePolicy,publicCapability:e.publicCapability,existingRoleLocalMaterial:e.existingRoleLocalMaterial,...e.requestId?{requestId:e.requestId}:{},...r,preauthorizedSessionActivation:e.sessionActivation}:n(e,e.routeAuth,r)}}throw Error(`[SigningEngine][ecdsa] unsupported ECDSA bootstrap request`)}function Ye(e,t){return{purpose:`explicit_key_export`,relayerUrl:t,existingRoleLocalMaterial:e.existingRoleLocalMaterial,authorization:e.authorization}}function Xe(e,t){return{purpose:`explicit_key_export`,relayerUrl:t,existingRoleLocalMaterial:e.existingRoleLocalMaterial,authorization:e.authorization}}async function Ze(e,t){if(t.kind===`reuse_warm_ecdsa_bootstrap`)throw Error(`[SigningEngine][ecdsa] reuse_warm bootstrap must resolve an existing exact material request before activation`);let n=Ke(t),r=l(z(t)),i=B(t),a=L(t.relayerUrl,e.defaultRelayerUrl),o=e.getSignerWorkerContext(),s={touchIdPrompt:e.touchIdPrompt,workerCtx:o,routerAbNormalSigning:e.routerAbNormalSigning};qe({request:t,walletId:r,authority:n});let c=await He(s,Je(t,a)),u=Ge(t);return await e.persistThresholdEcdsaBootstrapForWalletTarget({walletId:r,chainTarget:i,bootstrap:c,signerAuth:u}),await t.beforeAuthorizationPersistence?.(),await fe(se,{walletId:r,authority:n,bootstrap:c}),c}async function Qe(e,t){return await I(Ye(t,L(t.relayerUrl,e.defaultRelayerUrl)))}async function $e(e,t){return await I(Xe(t,L(t.relayerUrl,e.defaultRelayerUrl)))}async function V(e,t,n){let r=String(t),i=(e.get(r)||Promise.resolve()).catch(()=>void 0),a,o=new Promise(e=>{a=e}),s=i.then(()=>o);e.set(r,s),await i;try{return await n()}finally{a(),e.get(r)===s&&e.delete(r)}}function et(e,t){return t.runtimeScopeBootstrap&&(e.runtimeScopeBootstrap=t.runtimeScopeBootstrap),t.operationIntent&&(e.operationIntent=t.operationIntent),typeof t.ttlMs==`number`&&(e.ttlMs=t.ttlMs),e}function H(e){return et({kind:`email_otp_ecdsa_activation`,purpose:`transaction_signing`,walletKey:e.walletKey,lanePolicy:e.lanePolicy,publicCapability:e.publicCapability,existingRoleLocalMaterial:e.existingRoleLocalMaterial,source:e.source,relayerUrl:e.relayerUrl,sessionIdentity:e.sessionIdentity,sessionKind:e.sessionKind,sessionBudgetUses:e.sessionBudgetUses,runtimePolicy:e.runtimePolicy,emailOtpWorkerSessionHandle:e.emailOtpWorkerSessionHandle,emailOtpAuthContext:e.emailOtpAuthContext,...`preauthorizedSessionActivation`in e?{preauthorizedSessionActivation:e.preauthorizedSessionActivation}:{walletSessionRouteAuth:e.walletSessionRouteAuth}},e)}function U(e){if(le(e.context)!==e.expected)throw Error(`Email OTP ${e.label} activation requires ${e.expected} retention`)}function tt(e){return U({context:e.emailOtpAuthContext,expected:`session`,label:`session bootstrap`}),H(e)}function nt(e){return U({context:e.emailOtpAuthContext,expected:`session`,label:`recovered session`}),H(e)}function rt(e){return U({context:e.emailOtpAuthContext,expected:`session`,label:`preauthorized session bootstrap`}),H(e)}function it(e){return U({context:e.emailOtpAuthContext,expected:`single_use`,label:`per-operation reauth`}),H(e)}function at(e){return{kind:`email_otp_ecdsa_export_activation`,purpose:`explicit_key_export`,existingRoleLocalMaterial:e.existingRoleLocalMaterial,relayerUrl:e.relayerUrl,authorization:e.authorization}}function ot(e){return{kind:`passkey_ecdsa_export_activation`,purpose:`explicit_key_export`,existingRoleLocalMaterial:e.existingRoleLocalMaterial,relayerUrl:e.relayerUrl,authorization:e.authorization}}function st(e){switch(e.kind){case`default_policy`:return;case`scoped_policy`:return e.scope}throw Error(`[SigningEngine][ecdsa] unsupported ECDSA activation policy`)}function W(e,t){t.runtimeScopeBootstrap&&(e.runtimeScopeBootstrap=t.runtimeScopeBootstrap),t.operationIntent&&(e.operationIntent=t.operationIntent);let n=st(t.runtimePolicy);return`walletId`in e&&(typeof t.ttlMs==`number`&&(e.ttlMs=t.ttlMs),n&&(e.runtimePolicyScope=n)),e}function ct(e){switch(e.kind){case`passkey_ecdsa_activation`:return{kind:`passkey_existing_session_activation`,request:e};case`email_otp_ecdsa_activation`:return{kind:`email_otp_existing_session_activation`,request:e}}throw Error(`[SigningEngine][ecdsa] unsupported activation request`)}function lt(e){let t=String(e.webauthnAuthentication.rawId||e.webauthnAuthentication.id||``).trim();if(!t)throw Error(`[SigningEngine][ecdsa] passkey activation requires credential identity`);return t}function ut(e){let t=ct(e);switch(t.kind){case`passkey_existing_session_activation`:return W({kind:`passkey_fresh_ecdsa_bootstrap`,keyHandle:t.request.walletKey.keyHandle,key:x(t.request.walletKey),lanePolicy:t.request.lanePolicy,publicCapability:t.request.publicCapability,existingRoleLocalMaterial:t.request.existingRoleLocalMaterial,source:t.request.source,relayerUrl:t.request.relayerUrl,requestId:t.request.requestId,passkeyCredentialIdB64u:lt(t.request),routeAuth:t.request.walletSessionRouteAuth},t.request);case`email_otp_existing_session_activation`:{let e={kind:`email_otp_ecdsa_bootstrap`,keyHandle:t.request.walletKey.keyHandle,key:x(t.request.walletKey),lanePolicy:t.request.lanePolicy,publicCapability:t.request.publicCapability,existingRoleLocalMaterial:t.request.existingRoleLocalMaterial,source:`email_otp`,relayerUrl:t.request.relayerUrl,emailOtpWorkerSessionHandle:t.request.emailOtpWorkerSessionHandle,emailOtpAuthContext:t.request.emailOtpAuthContext};return t.request.preauthorizedSessionActivation?W({...e,sessionActivation:t.request.preauthorizedSessionActivation},t.request):W({...e,routeAuth:t.request.walletSessionRouteAuth},t.request)}}throw Error(`[SigningEngine][ecdsa] unsupported activation request`)}function dt(e){return{kind:`passkey_ecdsa_export_bootstrap`,purpose:`explicit_key_export`,existingRoleLocalMaterial:e.existingRoleLocalMaterial,relayerUrl:e.relayerUrl,authorization:e.authorization}}async function ft(e){let t=e.bootstrap.thresholdEcdsaKeyRef.backendBinding;if(!t)throw Error(`[WarmSessionStore] threshold ECDSA bootstrap is missing its backend binding`);let n=pt(t);if(!n)return;let r=await e.deps.persistEcdsaRoleLocalReadyRecord({record:n,storageKeyFacts:S(n)});if(!r.ok)throw Error(`[WarmSessionStore] threshold ECDSA role-local ready record persistence failed (${r.code}): ${r.message}`)}function pt(e){switch(e.materialKind){case`role_local_ready_state_blob`:return e.ecdsaRoleLocalReadyRecord;case`role_local_worker_handle`:case`role_local_durable_public_anchor`:case`role_local_durable_sealed_ref`:case`metadata_only`:return null;default:{let t=e;throw Error(`[WarmSessionStore] unsupported threshold ECDSA backend binding: ${JSON.stringify(t)}`)}}}async function G(e,t){let n=l(z(t));return await V(e.queueByWallet,n,async()=>{let n=await Ze(e.activationDeps,t);return await ft({deps:e,bootstrap:n}),n})}async function mt(e,t){return await G(e,ut(t))}async function ht(e,t){return await Qe(e.activationDeps,dt(t))}async function gt(e,t){let n={kind:`email_otp_ecdsa_export_bootstrap`,purpose:`explicit_key_export`,existingRoleLocalMaterial:t.existingRoleLocalMaterial,relayerUrl:t.relayerUrl,authorization:t.authorization};return await $e(e.activationDeps,n)}const K=`ecdsa-derivation:role-local:product-export-confirmation:v5`,q=`ecdsa-derivation:role-local:product-export-authorization:v5`;function J(e){return{kind:`operation_step_up`}}function Y(e){return{authorizationKind:e.kind,authorizationId:e.evidenceSetDigest}}function X(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`crypto.getRandomValues is required for threshold ECDSA export`);return r(e.getRandomValues(new Uint8Array(32)))}async function Z(e){let t=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!t)throw Error(`[SigningEngine][ecdsa-export] relayer URL is required`);if(e.authorization.kind===`wallet_session_bearer`&&!e.authorization.token.trim())throw Error(`[SigningEngine][ecdsa-export] Wallet Session operation credential is required`);let n={"Content-Type":`application/json`};e.authorization.kind===`wallet_session_bearer`&&(n.Authorization=`Bearer ${e.authorization.token}`);try{let r=await fetch(`${t}${_}`,{method:`POST`,credentials:e.authorization.kind===`legacy_cookie`?`include`:`omit`,headers:n,body:JSON.stringify({request:e.request,requestDigestB64u:e.requestDigestB64u})}),i=await r.json().catch(()=>null);if(!r.ok){let e=i&&typeof i==`object`&&!Array.isArray(i)?i:null;return{ok:!1,code:String(e?.code||`http_error`),message:String(e?.message||`HTTP ${r.status}`)}}return{ok:!0,value:h(i)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}}async function _t(e){return await Z({...e,authorization:{kind:`legacy_cookie`}})}async function vt(e){return await Z({relayerUrl:e.relayerUrl,request:e.request,requestDigestB64u:e.requestDigestB64u,authorization:{kind:`wallet_session_bearer`,token:e.operationCredential.token}})}function Q(e){let t=Math.min(e.issuedAtUnixMs+6e4,e.authorizationExpiresAtMsCeiling??1/0);if(Number.isFinite(t)&&t>e.issuedAtUnixMs)return t;throw new be({failure:ye(ve.expired),message:`Wallet Session expired before ECDSA export authorization`})}function yt(e){if(String(e.material.persistedMaterial.publicFacts.walletId)!==String(e.walletSessionUserId))throw Error(`[SigningEngine][ecdsa-export] explicit export wallet mismatch`)}async function $(e){return r(await n(t(e)))}function bt(e){switch(e.kind){case`rehydrated`:return e;case`device_link_required`:throw Error(`[SigningEngine][ecdsa-export] device_link_required: local threshold ECDSA material is unavailable`);case`corrupt`:throw Error(`[SigningEngine][ecdsa-export] local threshold ECDSA material is corrupt (${e.reason}): ${e.message}`);default:{let t=e;throw Error(`Unsupported ECDSA export material resolution: ${String(t)}`)}}}async function xt(e){return bt(await D({purpose:`explicit_key_export`,source:E(e.persistedMaterial),workerCtx:e.workerCtx}))}function St(e){let t=Y(e.material.operationAuthorization),n=e.material.persistedMaterial.publicFacts;return{version:q,operation:`explicit_key_export`,keyHandle:n.keyHandle,walletId:String(n.walletId),ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,relayerKeyId:n.publicCapability.signer_set.selected_server.server_id,signingRootId:e.signingRootId,signingRootVersion:e.signingRootVersion,contextBinding32B64u:e.contextBinding32B64u,publicIdentity:e.publicIdentity,exportRequestNonce32B64u:e.exportRequestNonce32B64u,confirmationDigest32B64u:e.confirmationDigest32B64u,issuedAtUnixMs:e.issuedAtUnixMs,expiresAtUnixMs:e.expiresAtUnixMs,authorizationKind:t.authorizationKind,authorizationId:t.authorizationId,materialActivation:b(e.material.persistedMaterial.materialActivation),participantIds:n.participantIds}}async function Ct(e,t){let n=t.persistedMaterial.publicFacts,r=b(t.persistedMaterial.materialActivation);switch(t.factorAuthorization.kind){case`passkey`:{let e=String(t.factorAuthorization.credential.rawId||t.factorAuthorization.credential.id||``).trim();if(!e)throw Error(`[SigningEngine][ecdsa-export] passkey authorization credential is missing`);if(e!==t.factorAuthorization.passkeyCredentialIdB64u)throw Error(`[SigningEngine][ecdsa-export] passkey export authorization credential mismatch`);break}case`email_otp_verified`:break;default:{let e=t.factorAuthorization;throw Error(`Unsupported ECDSA export authorization: ${String(e)}`)}}let i=Date.now(),a=Q({issuedAtUnixMs:i,authorizationExpiresAtMsCeiling:t.operationAuthorization.expiresAtMs}),o={derivationClientSharePublicKey33B64u:n.derivationClientSharePublicKey33B64u,relayerPublicKey33B64u:n.relayerPublicKey33B64u,groupPublicKey33B64u:n.groupPublicKey33B64u,ethereumAddress:n.ethereumAddress},s=X(),c=Y(t.operationAuthorization),l=await $({version:K,walletId:String(n.walletId),ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,relayerKeyId:n.publicCapability.signer_set.selected_server.server_id,contextBinding32B64u:n.contextBinding32B64u,publicIdentity:o,authorizationKind:c.authorizationKind,authorizationId:c.authorizationId,materialActivation:r,exportRequestNonce32B64u:s,issuedAtUnixMs:i,expiresAtUnixMs:a}),u=await $(St({ecdsaThresholdKeyId:n.ecdsaThresholdKeyId,signingRootId:n.signingRootId,signingRootVersion:n.signingRootVersion,contextBinding32B64u:n.contextBinding32B64u,publicIdentity:o,exportRequestNonce32B64u:s,confirmationDigest32B64u:l,issuedAtUnixMs:i,expiresAtUnixMs:a,material:t})),d=n.publicCapability,f=`ecdsa-export:${s}`,p=await pe({workerCtx:e.getSignerWorkerContext(),command:{kind:`create_router_ab_ecdsa_explicit_export_ceremony_v1`,ceremonyId:f,request:{context:d.context,lifecycle:{lifecycle_id:f,work_kind:`key_export`,primitive_request_kind:`export`,root_share_epoch:d.activation_epoch,account_id:String(n.walletId),session_id:T.thresholdEcdsaSession(f),signer_set_id:d.signer_set.signer_set_id,selected_server_id:d.signer_set.selected_server.server_id},public_identity:d.public_identity,signer_set:d.signer_set,router_id:d.router_id,client_id:d.client_id,authorization:J(t.operationAuthorization),authorization_id:t.operationAuthorization.evidenceSetDigest,operation:t.operationAuthorization.operation,material_activation:r,export_authorization_digest_b64u:u,export_nonce:s,expires_at_ms:a,deriver_recipient_keys:d.deriver_recipient_keys}}});if(p.kind!==`router_ab_ecdsa_explicit_export_ceremony_created_v1`)throw Error(`[SigningEngine][ecdsa-export] strict export ceremony kind mismatch`);try{let i=await _t({relayerUrl:t.relayerUrl,request:p.request,requestDigestB64u:p.requestDigestB64u});if(!i.ok)throw Error(i.error||i.message||i.code||`Strict ECDSA explicit export request failed`);let a=await me({workerCtx:e.getSignerWorkerContext(),command:{kind:`finalize_router_ab_ecdsa_explicit_export_v1`,ceremonyId:f,clientProofFinalization:{kind:`finalize_encrypted_client_proof_bundles_v2`,bundles:i.value.response.bundles},signingWorkerExport:i.value.signing_worker_export,authorizationKind:c.authorizationKind,authorizationId:c.authorizationId,materialActivation:r,roleLocalMaterial:t.liveMaterial.liveHandle,roleLocalMaterialRef:t.liveMaterial.materialRef,publicFacts:n}});return{publicKeyHex:a.publicKeyHex,privateKeyHex:a.privateKeyHex,ethereumAddress:a.ethereumAddress}}catch(t){throw await ge({workerCtx:e.getSignerWorkerContext(),command:{kind:`close_router_ab_ecdsa_post_registration_ceremony_v1`,ceremonyId:f}}).catch(()=>void 0),t}}async function wt(e,t){let n=t.exportProvision.material;yt({material:n,walletSessionUserId:t.walletSessionUserId});let r=String(n.relayerUrl||``).trim();if(!r)throw Error(`[SigningEngine][ecdsa-export] relayer URL is required`);let i=n.persistedMaterial;return await Ct(e,{persistedMaterial:i,liveMaterial:await xt({persistedMaterial:i,workerCtx:e.getSignerWorkerContext()}),relayerUrl:r,operationAuthorization:t.exportProvision.authorization,factorAuthorization:t.factorAuthorization})}function Tt(t){let n=t.runtime.normalSigning.scope,r=t.operationAuthorization.operation,i=y(r.material_activation);if(r.operation_kind!==`evm.export_key`||r.wallet_id!==String(t.runtime.walletId)||r.key_handle!==t.runtime.publicFacts.keyHandle||r.relayer_key_id!==t.runtime.relayerKeyId||r.participant_ids[0]!==t.runtime.publicFacts.participantIds[0]||r.participant_ids[1]!==t.runtime.publicFacts.participantIds[1]||r.signing_worker_id!==n.signing_worker.server_id||r.normal_signing_scope.wallet_id!==n.wallet_id||r.normal_signing_scope.context.application_binding_digest_b64u!==n.context.application_binding_digest_b64u||r.normal_signing_scope.public_identity.context_binding_b64u!==n.public_identity.context_binding_b64u||r.normal_signing_scope.public_identity.threshold_public_key33_b64u!==n.public_identity.threshold_public_key33_b64u||r.normal_signing_scope.signing_worker.server_id!==n.signing_worker.server_id||!e(i,t.runtime.materialActivation)||!e(y(r.normal_signing_scope.material_activation),t.runtime.materialActivation))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority operation identity changed`)}async function Et(e,t){Tt(t);let n=t.runtime,r=n.normalSigning.scope;if(t.operationAuthorization.exportTopology.signer_set.selected_server.server_id!==r.signing_worker.server_id)throw Error(`[SigningEngine][ecdsa-export] active export topology changed`);let i=r.material_activation,a=Date.now(),o=Q({issuedAtUnixMs:a,authorizationExpiresAtMsCeiling:t.operationAuthorization.expiresAtMs}),s={derivationClientSharePublicKey33B64u:r.public_identity.derivation_client_share_public_key33_b64u,relayerPublicKey33B64u:r.public_identity.server_public_key33_b64u,groupPublicKey33B64u:r.public_identity.threshold_public_key33_b64u,ethereumAddress:n.publicFacts.thresholdOwnerAddress},l=X(),u=Y(t.operationAuthorization),d=await $({version:K,walletId:String(n.walletId),ecdsaThresholdKeyId:r.ecdsa_threshold_key_id,relayerKeyId:n.relayerKeyId,contextBinding32B64u:r.public_identity.context_binding_b64u,publicIdentity:s,authorizationKind:u.authorizationKind,authorizationId:u.authorizationId,materialActivation:i,exportRequestNonce32B64u:l,issuedAtUnixMs:a,expiresAtUnixMs:o}),f=await $({version:q,operation:`explicit_key_export`,keyHandle:n.publicFacts.keyHandle,walletId:String(n.walletId),ecdsaThresholdKeyId:r.ecdsa_threshold_key_id,relayerKeyId:n.relayerKeyId,signingRootId:r.signing_root_id,signingRootVersion:r.signing_root_version,contextBinding32B64u:r.public_identity.context_binding_b64u,publicIdentity:s,exportRequestNonce32B64u:l,confirmationDigest32B64u:d,issuedAtUnixMs:a,expiresAtUnixMs:o,authorizationKind:u.authorizationKind,authorizationId:u.authorizationId,materialActivation:i,participantIds:n.publicFacts.participantIds}),p=`ecdsa-export:${l}`,m={context:r.context,lifecycle:{lifecycle_id:p,work_kind:`key_export`,primitive_request_kind:`export`,root_share_epoch:r.activation_epoch,account_id:r.wallet_id,session_id:T.thresholdEcdsaSession(p),signer_set_id:t.operationAuthorization.exportTopology.signer_set.signer_set_id,selected_server_id:t.operationAuthorization.exportTopology.signer_set.selected_server.server_id},public_identity:r.public_identity,signer_set:t.operationAuthorization.exportTopology.signer_set,router_id:t.operationAuthorization.exportTopology.router_id,client_id:String(n.walletId),authorization:J(t.operationAuthorization),operation:t.operationAuthorization.operation,authorization_id:c(t.operationAuthorization.evidenceSetDigest),material_activation:i,export_authorization_digest_b64u:f,export_nonce:l,expires_at_ms:o,deriver_recipient_keys:t.operationAuthorization.exportTopology.deriver_recipient_keys},h=await he({holderHandleId:n.holderRuntime.holderHandleId,request:m,workerCtx:e.getSignerWorkerContext()});if(h.kind!==`ecdsa_holder_ordinary_export_request_created_v1`)throw Error(`[SigningEngine][ecdsa-export] active holder export request kind mismatch`);let g=await vt({relayerUrl:t.relayerUrl,request:h.request,requestDigestB64u:h.requestDigestB64u,operationCredential:n.operationCredential});if(!g.ok)throw Error(g.error||g.message||g.code||`Active Wallet Authority ECDSA export request failed`);let _={wallet_id:r.wallet_id,key_handle:n.publicFacts.keyHandle,ecdsa_threshold_key_id:r.ecdsa_threshold_key_id,signing_root_id:r.signing_root_id,signing_root_version:r.signing_root_version,activation_epoch:r.activation_epoch,signing_worker_id:r.signing_worker.server_id,context_binding_b64u:r.public_identity.context_binding_b64u,threshold_public_key33_b64u:r.public_identity.threshold_public_key33_b64u,export_request_digest_b64u:h.requestDigestB64u,export_authorization_digest_b64u:f,export_nonce:l,authorization_kind:`verified_step_up`,authorization_id:t.operationAuthorization.evidenceSetDigest,material_activation:i,lifecycle_id:p,recipient_identity:h.request.client_id,recipient_public_key:h.request.client_ephemeral_public_key,expires_at_ms:h.request.expires_at_ms},v=await _e({holderHandleId:n.holderRuntime.holderHandleId,requestDigestB64u:h.requestDigestB64u,expectedBinding:_,forwardedResponse:g.value,workerCtx:e.getSignerWorkerContext()});return{publicKeyHex:v.publicKeyHex,privateKeyHex:v.privateKeyHex,ethereumAddress:v.ethereumAddress}}export{k as _,it as a,tt as c,mt as d,G as f,A as g,z as h,at as i,gt as l,B as m,wt as n,rt as o,V as p,ot as r,nt as s,Et as t,ht as u,xe as v,Se as y};
@@ -0,0 +1 @@
1
+ import{r as e}from"./domainIds-BzkGsRqO.js";import{c as t}from"./chains-C_X_fNuS.js";import"./primitives-CqrjmIAH.js";import{r as n}from"./secureRandomId-LwBFx84B.js";import"./walletDbName-DtRewci9.js";import"./signingSessionSeal-DX41aXUL.js";import{t as r}from"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import{o as i}from"./canonicalPrimitives-Dsbsxgxc.js";import{i as a,t as o}from"./errors-DIWY1KR9.js";import{d as s,t as c}from"./accountIds-Cpvlkvbe.js";import{c as l,o as u,s as ee,u as d}from"./ecdsaChainTarget-Bfatk3oP.js";import"./signerDomain-Dp7BhfmZ.js";import"./singletons-BXhnsqeY.js";import"./walletAuthority-CAiGuWW2.js";import{Dt as f,Et as p,Mt as m,a as h,en as te,g,ht as ne,tn as re}from"./emailOtpEcdsaDerivationIdentity-Bik0N8v9.js";import{t as ie}from"./challengeDelivery-CATQ4u6P.js";import"./digestEncoding-BX3VW9eF.js";import{i as ae}from"./walletAuthMethodRecord-LniOQQmj.js";import"./registrationIds-BaK3jUS6.js";import{a as oe,n as _,u as se}from"./sdkSentEvents-D4KtK7_I.js";import{s as ce}from"./types-hKLqDUhR.js";import{i as le}from"./helpers-B9fpZNAP.js";import{C as ue,D as v,b as de,j as fe,x as pe}from"./nearEd25519YaoSigningPreparation-RIfkYN0d.js";import{l as y,u as me}from"./trace-BBux0jtr.js";import{n as he,r as ge,t as _e,v as ve}from"./ecdsaDerivationExport-DOGzq0qC.js";import{i as ye}from"./walletSessionFailure-YuhraC3P.js";import{i as be,n as xe,r as Se,s as Ce}from"./signingQueue-D_Ebmzcn.js";import{h as b,i as x,l as we,n as Te,s as S}from"./clientSessionPersistenceState-CBylL1Ul.js";import{t as C}from"./types-Buoe6179.js";import{i as w}from"./appearance-4DmzKUWf.js";import{n as T,t as E}from"./export-viewer-host-CV-lSsQF.js";function D(e){return e.chainTarget.kind}function Ee(e){return e}function De(e){return!e||e.curve!==`ecdsa`||!e.chainTarget||!b(e)||!String(e.publicFacts.keyHandle||``).trim()?!1:e.source===`active_wallet_authority`?e.runtime.requiredCapability===`export_keys`&&e.state===`deferred`&&e.authorizationState===`authorization_required`:e.authorization?!0:e.state===`deferred`}function O(e){if(e.length!==2)throw Error(`[SigningEngine][ecdsa-export] ECDSA participant set must contain two parties`);let t=e[0],n=e[1];if(!Number.isSafeInteger(t)||!Number.isSafeInteger(n)||t<=0||n<=0||t===n)throw Error(`[SigningEngine][ecdsa-export] ECDSA participant set is invalid`);return[t,n]}function k(t){let{exportLane:n,label:r}=t,i=n.capability,a=i.manifest.signer;if(a.walletId!==n.key.walletId||!a.scope.targetMemberships.some(e=>ee(e,n.chainTarget)))throw Error(`[SigningEngine][ecdsa-export] ${r} capability target mismatch`);if(!t.authMatches())throw Error(`[SigningEngine][ecdsa-export] ${r} capability auth mismatch`);if(!e(i.manifest.activation.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] ${r} material activation mismatch`);h({expected:n.publicFacts,actual:a.registeredPublicFacts,context:`canonical ${r} export lane`});let o=i.material.publicFacts;if(o.walletId!==a.walletId||String(o.keyHandle)!==String(n.publicFacts.keyHandle)||String(o.groupPublicKey33B64u)!==String(n.publicFacts.publicKeyB64u)||String(o.ethereumAddress)!==String(n.publicFacts.thresholdOwnerAddress)||o.participantIds.length!==n.publicFacts.participantIds.length||o.participantIds.some((e,t)=>e!==n.publicFacts.participantIds[t]))throw Error(`[SigningEngine][ecdsa-export] canonical ${r} export material mismatch`);let s=i.manifest.durableMaterial,c=s.runtimePolicyScope,l=String(t.deps.relayerUrl).trim().replace(/\/+$/g,``);if(!c)throw Error(`[SigningEngine][ecdsa-export] ${r} runtime policy scope is missing`);if(!l)throw Error(`[SigningEngine][ecdsa-export] ${r} export relayer URL is missing`);return{durable:s,runtimePolicyScope:c,relayerUrl:l}}function Oe(e){let{exportLane:t}=e,n=t.capability,r=n.authority;if(!p(r))throw Error(`[SigningEngine][ecdsa-export] Email OTP capability authority mismatch`);let{durable:i,runtimePolicyScope:a,relayerUrl:o}=k({deps:e.deps,exportLane:t,label:`Email OTP`,authMatches:()=>t.laneIdentity.auth.kind===`email_otp`&&t.laneIdentity.auth.providerSubjectId===r.factor.providerUserId});return{source:`canonical_capability`,kind:`fresh_email_otp_route_auth_ready`,chainTarget:t.chainTarget,publicFacts:t.publicFacts,runtimePolicyScope:a,persistedMaterial:n.material,normalSigning:i.routerAbEcdsaDerivationNormalSigning,relayerKeyId:String(i.roleLocalBinding.relayerKeyId),participantIds:O(i.roleLocalBinding.participantIds),relayerUrl:o,authorization:{kind:`fresh_operation_authorization_required`,authority:r}}}function ke(e){let{exportLane:t}=e,n=t.capability,r=n.authority;if(!f(r))throw Error(`[SigningEngine][ecdsa-export] passkey capability authority mismatch`);let{durable:i,runtimePolicyScope:a,relayerUrl:o}=k({deps:e.deps,exportLane:t,label:`passkey`,authMatches:()=>t.laneIdentity.auth.kind===`passkey`&&t.laneIdentity.auth.credentialIdB64u===r.factor.credentialIdB64u});return{source:`canonical_capability`,kind:`fresh_passkey_needs_authorization`,chainTarget:t.chainTarget,publicFacts:t.publicFacts,runtimePolicyScope:a,publicCapability:i.roleLocalPublicFacts.publicCapability,existingRoleLocalMaterial:n.material,normalSigning:i.routerAbEcdsaDerivationNormalSigning,relayerKeyId:String(i.roleLocalBinding.relayerKeyId),participantIds:O(i.roleLocalBinding.participantIds),relayerUrl:o}}function Ae(t){let{exportLane:n,resolution:r}=t;if(n.laneIdentity.auth.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime auth mismatch`);if(r.runtime.authBinding.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime authority mismatch`);if(n.laneIdentity.auth.providerSubjectId!==r.runtime.authBinding.providerSubjectId)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime auth mismatch`);if(!e(r.runtime.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] Email OTP material activation mismatch`);let i=r.runtime.runtimePolicyScope;if(!i)throw Error(`[SigningEngine][ecdsa-export] Email OTP runtime policy scope is missing`);let a=be({authority:r.manifest.signer.authority,materialActivation:r.manifest.activation.materialActivation,publicFacts:r.manifest.durableMaterial.roleLocalPublicFacts});return{source:`canonical_capability`,kind:`fresh_email_otp_route_auth_ready`,chainTarget:n.chainTarget,publicFacts:n.publicFacts,runtimePolicyScope:i,persistedMaterial:a,normalSigning:r.runtime.normalSigning,relayerKeyId:r.runtime.relayerKeyId,participantIds:r.runtime.participantIds,relayerUrl:r.runtime.relayerUrl,authorization:{kind:`fresh_operation_authorization_required`,authority:r.runtime.authBinding.emailOtpAuthority}}}function je(t){let{exportLane:n}=t,r=n.runtime;if(r.requiredCapability!==`export_keys`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority lane lacks export_keys capability`);if(r.walletId!==n.key.walletId)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority wallet mismatch`);if(!e(r.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority material activation mismatch`);h({expected:n.publicFacts,actual:r.publicFacts,context:`active Wallet Authority ECDSA export lane`});let i=r.normalSigning,a=i.scope;if(a.wallet_id!==String(r.walletId)||a.ecdsa_threshold_key_id!==r.ecdsaThresholdKeyId||a.public_identity.threshold_public_key33_b64u!==r.publicFacts.publicKeyB64u||!e(te(a.material_activation),r.materialActivation))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority normal-signing identity mismatch`);let o=String(t.deps.relayerUrl).trim().replace(/\/+$/g,``);if(!o)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority export relayer URL is missing`);let s=O(r.publicFacts.participantIds);if(r.auth.kind===`passkey`){if(!f(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority mismatch`);if(r.factorAuthority.factor.credentialIdB64u!==r.auth.credentialIdB64u||r.factorAuthority.bindingId!==r.walletAuthMethodId)throw Error(`[SigningEngine][ecdsa-export] active passkey factor identity mismatch`);return{source:`active_wallet_authority`,kind:`active_wallet_authority_passkey_needs_authorization`,chainTarget:n.chainTarget,publicFacts:r.publicFacts,normalSigning:i,relayerKeyId:r.relayerKeyId,participantIds:s,relayerUrl:o,runtime:r,factorAuthority:r.factorAuthority,authMethod:`passkey`}}if(!p(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority mismatch`);if(r.factorAuthority.factor.providerUserId!==r.auth.providerSubjectId||r.factorAuthority.bindingId!==r.walletAuthMethodId)throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor identity mismatch`);return{source:`active_wallet_authority`,kind:`active_wallet_authority_email_otp_needs_authorization`,chainTarget:n.chainTarget,publicFacts:r.publicFacts,normalSigning:i,relayerKeyId:r.relayerKeyId,participantIds:s,relayerUrl:o,runtime:r,factorAuthority:r.factorAuthority,authMethod:`email_otp`}}async function A(e,t){if(t.source!==`canonical_capability`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority Email OTP material uses its holder runtime`);if(t.authMethod!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] fresh Email OTP export requires Email OTP lane`);let n=await e.resolveActiveEcdsaCapabilityRuntime({walletId:t.key.walletId,chainTarget:t.chainTarget});if(n.kind===`blocked`&&n.reason===`missing_material`)return Oe({deps:e,exportLane:t});if(n.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] Email OTP capability runtime unavailable: ${n.reason}`);return Ae({exportLane:t,resolution:n})}async function j(t,n){if(n.source===`active_wallet_authority`)return je({deps:t,exportLane:n});if(n.authMethod===`email_otp`)return await A(t,n);let r=await t.resolveActiveEcdsaCapabilityRuntime({walletId:n.key.walletId,chainTarget:n.chainTarget});if(r.kind===`blocked`&&r.reason===`missing_material`)return ke({deps:t,exportLane:n});if(r.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] passkey capability runtime unavailable: ${r.reason}`);if(!e(r.runtime.materialActivation,n.laneIdentity.signer.materialActivation))throw Error(`[SigningEngine][ecdsa-export] passkey material activation mismatch`);if(r.runtime.authBinding.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] passkey authority binding mismatch`);let i=r.manifest.signer.registeredPublicFacts;h({expected:n.publicFacts,actual:i,context:`canonical passkey export lane`});let a=r.runtime.runtimePolicyScope;if(!a)throw Error(`[SigningEngine][ecdsa-export] durable passkey export requires runtimePolicyScope`);return{source:`canonical_capability`,kind:`fresh_passkey_needs_authorization`,chainTarget:n.chainTarget,publicFacts:i,runtimePolicyScope:a,publicCapability:r.manifest.durableMaterial.roleLocalPublicFacts.publicCapability,existingRoleLocalMaterial:be({authority:r.manifest.signer.authority,materialActivation:r.manifest.durableMaterial.materialActivation,publicFacts:r.manifest.durableMaterial.roleLocalPublicFacts}),normalSigning:r.runtime.normalSigning,relayerKeyId:r.runtime.relayerKeyId,participantIds:r.runtime.participantIds,relayerUrl:r.runtime.relayerUrl}}function Me(e){return n(e,32,`Email OTP export UI request IDs`)}function Ne(e){switch(e.kind){case`near_account`:return String(c(e.nearAccountId));case`wallet_session`:{let t=String(e.walletId||``).trim();if(!t)throw Error(`Email OTP export requires wallet identity`);return t}default:return e}}function Pe(e){switch(e.kind){case`near_account`:if(!String(e.walletId||``).trim())throw Error(`Email OTP NEAR export requires wallet identity`);return{kind:`near_wallet`,walletId:String(e.walletId).trim(),nearAccountId:String(c(e.nearAccountId))};case`wallet_session`:{let t=String(e.walletId||``).trim();if(!t)throw Error(`Email OTP export requires wallet identity`);return{kind:`evm_wallet`,walletId:t}}default:return e}}function Fe(e){return{challengeId:e.challenge.challengeId,...e.challenge.emailHint?{emailHint:e.challenge.emailHint}:{},title:`Enter email code to export`,body:`This one-time code authorizes private key export only.`,helperText:`Enter the 6-digit code sent to your email`,onResend:e.onResend}}async function M(e){let t=Ne(e.identity),n=async()=>{let t=await e.challengeSource.requestChallenge(),n=String(t.challengeId||``).trim();if(!n)throw Error(`Email OTP export challenge response did not include challengeId`);let r=String(t.emailHint||``).trim();if(!r)throw Error(`Email OTP export challenge response did not include emailHint`);let i={challengeId:n,emailHint:r,delivery:t.delivery};return e.onChallenge?.(i),i},r=await n(),i=Fe({challenge:r,onResend:async()=>(r=await n(),r)}),a=Pe(e.identity),o=await e.confirmer.requestUserConfirmation({requestId:Me(`export-${e.curve}-email-otp-auth`),type:w.SIGN_INTENT_DIGEST,summary:{operation:`Export Private Key`,accountId:t,publicKey:e.publicKey,warning:`Enter the email code to export this key. Anyone with the private key can fully control the account.`},payload:{signingSubject:a,challengeB64u:r.challengeId,signingAuthPlan:{kind:C.EmailOtpReauth,method:`email_otp`,emailOtpPrompt:i},emailOtpPrompt:i},intentDigest:`export-keys:${t}:${e.chain}:${e.curve}:email-otp`});if(!o.confirmed)throw Error(o.error||`User cancelled Email OTP export request`);let s=String(o.otpCode||``).replace(/\D/g,``).slice(0,6);if(s.length!==6)throw Error(`Email OTP export requires a 6-digit code`);return{challengeId:String(o.emailOtpChallengeId||r.challengeId).trim(),otpCode:s}}function N(e){throw Error(`[SigningEngine][export] unsupported authorization identity: ${String(e)}`)}function Ie(e){throw Error(`[SigningEngine][export] unsupported step-up method: ${String(e)}`)}function Le(e){let t=String(e.walletSessionUserId||``).trim();if(!t)throw Error(`[SigningEngine][export] missing export step-up authorization identity`);let n=String(e.publicKey||``).trim();if(!n)throw Error(`[SigningEngine][export] missing export step-up authorization public key`);switch(e.curve){case`ecdsa`:return{walletSessionUserId:t,publicKey:n,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.chain};case`ed25519`:{let r={walletSessionUserId:t,publicKey:n,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:String(e.nearAccountId||``).trim(),nearEd25519SigningKeyId:String(e.nearEd25519SigningKeyId||``).trim(),signerSlot:Number(e.signerSlot)};if(!r.nearAccountId||!r.nearEd25519SigningKeyId||!Number.isSafeInteger(r.signerSlot)||r.signerSlot<1)throw Error(`[SigningEngine][export] Ed25519 export authorization identity is invalid`);return r}default:return N(e)}}function Re(e){let t={kind:C.EmailOtpReauth,method:`email_otp`,emailOtpPrompt:e.emailOtpPrompt},n=e.emailOtpPrompt.emailHint;switch(e.identity.curve){case`ecdsa`:return{kind:`email_otp`,signingAuthPlan:t,challengeId:e.challengeId,otpCode:e.otpCode,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.identity.chain,...n?{emailHint:n}:{}};case`ed25519`:return{kind:`email_otp`,signingAuthPlan:t,challengeId:e.challengeId,otpCode:e.otpCode,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,signerSlot:e.identity.signerSlot,...n?{emailHint:n}:{}};default:return N(e.identity)}}function ze(e){let t={kind:C.PasskeyReauth,method:`passkey`};switch(e.identity.curve){case`ecdsa`:return{kind:`passkey`,signingAuthPlan:t,credential:e.credential,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:e.identity.chain};case`ed25519`:return{kind:`passkey`,signingAuthPlan:t,credential:e.credential,walletSessionUserId:e.identity.walletSessionUserId,publicKey:e.identity.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:e.identity.nearAccountId,nearEd25519SigningKeyId:e.identity.nearEd25519SigningKeyId,signerSlot:e.identity.signerSlot};default:return N(e.identity)}}function P(e){let t=Le(e);switch(e.method){case`email_otp`:{if(!e.decision.confirmed)throw Error(e.decision.error||`User cancelled Email OTP export request`);let n=String(e.decision.otpCode||``).replace(/\D/g,``).slice(0,6);if(n.length!==6)throw Error(`Email OTP export requires a 6-digit code`);let r=String(e.decision.emailOtpChallengeId||e.emailOtpPrompt.challengeId||``).trim();if(!r)throw Error(`Email OTP export challenge response did not include challengeId`);return Re({identity:t,emailOtpPrompt:e.emailOtpPrompt,challengeId:r,otpCode:n})}case`passkey`:if(!e.decision.confirmed)throw Error(e.decision.error||`User cancelled export request`);if(!e.decision.credential)throw Error(`[SigningEngine][export] missing WebAuthn credential for export authorization`);return ze({identity:t,credential:le(e.decision.credential)});default:return Ie(e)}}function Be(e){switch(e.kind){case`ecdsa`:return{subject:`${String(e.walletSession.walletId)}:${u(e.chainTarget)}`,chain:e.chainTarget.kind,data:{curve:`ecdsa`,chain:e.chainTarget.kind,chainTarget:e.chainTarget}};case`ed25519`:return{subject:`${String(e.walletSession.walletId)}:near:${String(e.nearAccount.accountId)}`,chain:`near`,data:{curve:`ed25519`,chain:`near`,nearAccount:e.nearAccount}}}}function F(e,t){if(e)try{e(se(t))}catch{}}function I(e){return n(e,32,`key export UI request IDs`)}function Ve(e,t){return`key-export:${e}:${t}:${I(`flow`)}`}async function He(e,t){let n=Be(e),r=Ve(n.subject,n.chain),i=e.walletSession.walletId,s=n.data;F(e.options.onEvent,{phase:_.STEP_01_STARTED,status:`running`,flowId:r,accountId:String(i),interaction:{kind:`none`,overlay:`none`},data:s});try{return await t({...e,flowId:r})}catch(t){let n=a(t);throw F(e.options.onEvent,{phase:n?_.CANCELLED:_.FAILED,status:n?`cancelled`:`failed`,flowId:r,accountId:String(i),interaction:{kind:`none`,overlay:`hide`},error:{message:o(t)||(n?`Key export cancelled`:`Key export failed`)},data:s}),t}}async function Ue(e,t){return await e.requestExportChallenge({kind:`wallet_login_challenge`,walletSession:t.walletSession,chain:t.chain})}function L(e,t){let n=e.kind===`email_otp_ed25519_export_auth`?e.walletId:e.walletSession.walletSessionUserId;F(e.onEvent,{phase:_.STEP_02_AUTH_EMAIL_OTP_INPUT_REQUIRED,status:`waiting_for_user`,flowId:e.flowId,accountId:String(n),authMethod:`email_otp`,interaction:{kind:`otp_input`,overlay:`show`},data:{emailHint:t.emailHint,demoOtpCode:ie(t.delivery)}})}async function R(e,t){let n=t.walletSession.walletSessionUserId,r=await M({identity:{kind:`wallet_session`,walletId:n},chain:t.chain,publicKey:t.publicKey,curve:t.curve,challengeSource:{requestChallenge:async()=>await Ue(e,t)},confirmer:{requestUserConfirmation:async t=>await e.touchConfirm.requestUserConfirmation(t)},onChallenge:L.bind(void 0,t)}),i={challengeId:r.challengeId},a={confirmed:!0,otpCode:r.otpCode,emailOtpChallengeId:r.challengeId},o=P({method:`email_otp`,walletSessionUserId:n,chain:t.chain,publicKey:t.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,emailOtpPrompt:i,decision:a});if(o.kind!==`email_otp`)throw Error(`[SigningEngine][export] Email OTP export returned the wrong step-up method`);return o}async function We(e,t){let n=await M({identity:{kind:`near_account`,walletId:t.walletId,nearAccountId:t.nearAccountId},chain:`near`,publicKey:t.publicKey,curve:`ed25519`,challengeSource:{requestChallenge:async()=>await e.requestExportChallenge({kind:`wallet_export_challenge`,walletId:t.walletId,chain:`near`})},confirmer:{requestUserConfirmation:async t=>await e.touchConfirm.requestUserConfirmation(t)},onChallenge:L.bind(void 0,t)}),r=P({method:`email_otp`,walletSessionUserId:t.walletId,publicKey:t.publicKey,curve:`ed25519`,intent:`ed25519_export`,chain:`near`,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot,emailOtpPrompt:{challengeId:n.challengeId},decision:{confirmed:!0,otpCode:n.otpCode,emailOtpChallengeId:n.challengeId}});if(r.kind!==`email_otp`||r.curve!==`ed25519`)throw Error(`[SigningEngine][export] Ed25519 Email OTP export authorization changed kind`);return r}async function z(e,t){let n=t.state===`loading`,r=[{scheme:`ed25519`,label:`NEAR Ed25519 private key`,publicKey:t.publicKey,privateKey:n?``:t.privateKey}];await e.touchConfirm.requestUserConfirmation({requestId:I(`export-ed25519-yao-view`),type:w.SHOW_SECURE_PRIVATE_KEY_UI,summary:{operation:`Export Private Key`,accountId:t.nearAccountId,publicKey:t.publicKey,warning:`Anyone with your private key can fully control your account. Never share it.`},payload:{subject:{kind:`near_wallet`,nearAccountId:t.nearAccountId},viewerSessionId:t.viewerSessionId,publicKey:t.publicKey,keys:r,variant:t.variant,theme:t.theme??e.theme??`dark`,loading:n,onLifecycle:e=>{F(t.onEvent,{phase:e===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:e===`opened`?`waiting_for_user`:`succeeded`,flowId:t.flowId,accountId:t.nearAccountId,interaction:{kind:`key_export_viewer`,overlay:e===`opened`?`show`:`hide`},data:{chain:`near`,curve:`ed25519`,loading:n}}),e===`closed`&&F(t.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:t.flowId,accountId:t.nearAccountId,interaction:{kind:`none`,overlay:`hide`},data:{chain:`near`,curve:`ed25519`}})}},intentDigest:`export-keys:${t.walletId}:near:${t.nearAccountId}:ed25519`})}async function B(e,t){let n=t.chainTarget.kind,r=String(t.walletSessionUserId||``).trim();if(!r)throw Error(`[SigningEngine][export] missing ECDSA export wallet session user id`);return await Ge(e,{walletSessionUserId:t.walletSessionUserId,intent:`ecdsa_export`,curve:`ecdsa`,chain:n,publicKey:t.publicKey,flowId:t.flowId,onEvent:t.onEvent,request:{requestId:I(`export-threshold-ecdsa-auth`),type:w.AUTHORIZE_KEY_EXPORT,summary:{operation:`Export Private Key`,accountId:r,publicKey:t.publicKey,warning:n===`tempo`?`Confirm to reveal your Tempo private key export.`:`Confirm to reveal your EVM private key export.`},payload:{subject:{kind:`evm_wallet`,walletId:r},credentialIdB64u:t.credentialIdB64u,publicKey:t.publicKey,...t.challengeB64u?{challengeB64u:t.challengeB64u}:{}},intentDigest:`export-keys:${r}:${u(t.chainTarget)}:secp256k1`}})}async function V(e,t){let n=t.chainTarget.kind,r=n===`tempo`?`Tempo`:`EVM`,i=t.state===`loading`,a=i?[{scheme:`secp256k1`,label:r,publicKey:t.publicKeyHex,privateKey:``,address:t.ethereumAddress}]:[{scheme:`secp256k1`,label:r,publicKey:t.publicKeyHex,privateKey:t.privateKeyHex,address:t.ethereumAddress}];await e.touchConfirm.requestUserConfirmation({requestId:I(`export-threshold-ecdsa-view`),type:w.SHOW_SECURE_PRIVATE_KEY_UI,summary:{operation:`Export Private Key`,accountId:t.walletId,publicKey:t.publicKeyHex,warning:`Anyone with your private key can fully control your account. Never share it.`},payload:{subject:{kind:`evm_wallet`,walletId:t.walletId},viewerSessionId:t.viewerSessionId,publicKey:t.publicKeyHex,keys:a,variant:t.variant,theme:t.theme??e.theme??`dark`,loading:i,onLifecycle:e=>{F(t.onEvent,{phase:e===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:e===`opened`?`waiting_for_user`:`succeeded`,flowId:t.flowId,accountId:String(t.walletId),interaction:{kind:`key_export_viewer`,overlay:e===`opened`?`show`:`hide`},data:{chain:n,curve:`ecdsa`,loading:i}}),e===`closed`&&F(t.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:t.flowId,accountId:String(t.walletId),interaction:{kind:`none`,overlay:`hide`},data:{chain:n,curve:`ecdsa`}})}},intentDigest:`export-keys:${t.walletId}:${u(t.chainTarget)}:secp256k1`})}async function Ge(e,t){let n=String(t.walletSessionUserId||``).trim();if(!n)throw Error(`[SigningEngine][export] missing export account identity`);F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,flowId:t.flowId,accountId:String(n),authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`},data:{intent:t.intent,curve:t.curve}}),T();let r=await e.touchConfirm.requestUserConfirmation(t.request),i=P({method:`passkey`,walletSessionUserId:t.walletSessionUserId,publicKey:t.publicKey,curve:`ecdsa`,intent:`ecdsa_export`,chain:t.chain,decision:r});if(i.kind!==`passkey`)throw Error(`[SigningEngine][export] passkey export returned the wrong step-up method`);return F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:String(n),authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`hide`},data:{intent:t.intent,curve:t.curve}}),i}function Ke(e){F(e.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:e.flowId,accountId:String(e.walletId),interaction:{kind:`none`,overlay:`none`},data:{chain:e.chain,curve:`ecdsa`}})}function qe(e){F(e.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:e.flowId,accountId:String(e.walletId),interaction:{kind:`none`,overlay:`none`},data:{chain:e.chain,curve:`ecdsa`,...e.source?{source:e.source}:{}}})}async function Je(e,t){await V({touchConfirm:e.touchConfirm,theme:e.theme},{state:`ready`,walletId:t.walletId,chainTarget:t.exportLane.chainTarget,publicKeyHex:String(t.artifact.publicKeyHex||``).trim(),privateKeyHex:String(t.artifact.privateKeyHex||``).trim(),ethereumAddress:String(t.artifact.ethereumAddress||``).trim(),variant:t.options.variant,theme:t.options.theme,viewerSessionId:t.viewerSessionId,flowId:t.flowId,onEvent:t.onEvent})}async function Ye(e,t){await V({touchConfirm:e.touchConfirm,theme:e.theme},{state:`loading`,walletId:t.walletId,chainTarget:t.exportLane.chainTarget,publicKeyHex:String(t.publicKey||``).trim(),ethereumAddress:String(t.ethereumAddress||``).trim(),variant:t.options.variant,theme:t.options.theme,viewerSessionId:t.viewerSessionId,flowId:t.flowId,onEvent:t.onEvent})}async function H(t,n){let r=D(n.exportLane),i=I(`export-threshold-ecdsa-viewer-session`);Ke({flowId:n.flowId,walletId:n.walletId,chain:r,onEvent:n.onEvent});try{await Ye(t,{walletId:n.walletId,exportLane:n.exportLane,publicKey:n.exportPublicKey,ethereumAddress:n.exportLane.publicFacts.thresholdOwnerAddress,options:n.options,viewerSessionId:i,flowId:n.flowId,onEvent:n.onEvent});let a=n.exportLane.laneIdentity.signer.materialActivation,o=await t.withThresholdEcdsaSigningQueue({queueKey:x({materialActivation:a}),walletId:n.exportLane.key.walletId,enabled:!0,task:async()=>{if(n.exportLane.source===`active_wallet_authority`){let e=n.activeRuntime;if(!e)throw Error(`[SigningEngine][ecdsa-export] active runtime is missing`);await et({ports:t.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e})}else if(n.exportLane.authMethod===`email_otp`){if(!e((await A(t.sessionStore,n.exportLane)).persistedMaterial.materialActivation,a))throw Error(`[SigningEngine][ecdsa-export] prepared material activation was superseded`)}else{let r=await j(t.sessionStore,n.exportLane);if(r.kind!==`fresh_passkey_needs_authorization`)throw Error(`[SigningEngine][ecdsa-export] prepared export authority changed`);if(!e(r.existingRoleLocalMaterial.materialActivation,a))throw Error(`[SigningEngine][ecdsa-export] prepared material activation was superseded`)}return await n.prepareArtifact()}});return qe({flowId:n.flowId,walletId:n.walletId,chain:r,onEvent:n.onEvent}),E(i)&&await Je(t,{walletId:n.walletId,exportLane:n.exportLane,artifact:o,options:n.options,viewerSessionId:i,flowId:n.flowId,onEvent:n.onEvent}),{accountId:String(n.walletId),exportedSchemes:[`secp256k1`]}}catch(e){throw T(),e}}function U(e){let t=e.laneIdentity.auth;if(t.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] fresh passkey export requires passkey lane`);return t}async function W(e){return i(t(e))}async function G(e){let t=u(e.chainTarget);return await Se({walletId:e.walletId,operationKind:`evm.export_key`,operationId:e.requestId,operationDigests:{laneDigest:await W({walletId:e.walletId,chainTarget:t,materialActivation:e.materialActivation,keyHandle:e.keyHandle}),intentDigest:await W({operation:`explicit_key_export`,requestId:e.requestId,walletId:e.walletId,chainTarget:t}),displayDigest:await W({operation:`Export Private Key`,publicKey:e.displayPublicKey,address:e.displayAddress})},materialActivation:e.materialActivation,normalSigningScope:e.operationRuntime.normalSigning.scope,keyHandle:e.keyHandle,relayerKeyId:e.operationRuntime.relayerKeyId,participantIds:[Number(e.operationRuntime.participantIds[0]),Number(e.operationRuntime.participantIds[1])],expiresAtMs:e.operationExpiresAtMs})}async function K(e){return await G({walletId:e.walletId,chainTarget:e.chainTarget,requestId:e.requestId,keyHandle:e.keyHandle,displayPublicKey:e.displayPublicKey,displayAddress:e.displayAddress,materialActivation:e.materialActivation,operationRuntime:e.operationRuntime,operationExpiresAtMs:e.operationExpiresAtMs})}async function Xe(t){let n=await j(t.deps.sessionStore,t.exportLane);if(n.kind!==`fresh_passkey_needs_authorization`)throw Error(`[SigningEngine][ecdsa-export] passkey export authority changed`);if(!e(n.existingRoleLocalMaterial.materialActivation,t.expectedMaterialActivation))throw Error(`[SigningEngine][ecdsa-export] active material changed after authorization confirmation`)}async function Ze(t){if(!e((await A(t.deps.sessionStore,t.exportLane)).persistedMaterial.materialActivation,t.expectedMaterialActivation))throw Error(`[SigningEngine][ecdsa-export] active material changed after authorization confirmation`)}function Qe(e){if(!$e(e.expected,e.actual))throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority runtime was replaced after authorization`)}function $e(t,n){let i;switch(t.auth.kind){case`passkey`:i=n.auth.kind===`passkey`&&t.auth.rpId===n.auth.rpId&&t.auth.credentialIdB64u===n.auth.credentialIdB64u;break;case`email_otp`:i=n.auth.kind===`email_otp`&&t.auth.providerSubjectId===n.auth.providerSubjectId;break;default:return t.auth}return t.kind===n.kind&&t.walletId===n.walletId&&t.authorityId===n.authorityId&&t.walletAuthMethodId===n.walletAuthMethodId&&t.authorityDigestB64u===n.authorityDigestB64u&&t.factorAuthorityRef.kind===n.factorAuthorityRef.kind&&t.factorAuthorityRef.walletId===n.factorAuthorityRef.walletId&&t.factorAuthorityRef.authorityDigest===n.factorAuthorityRef.authorityDigest&&t.factorAuthorityRef.walletAuthMethodId===n.factorAuthorityRef.walletAuthMethodId&&t.authorityRevocationEpoch===n.authorityRevocationEpoch&&t.walletSessionId===n.walletSessionId&&t.requiredCapability===n.requiredCapability&&e(t.materialActivation,n.materialActivation)&&t.ecdsaThresholdKeyId===n.ecdsaThresholdKeyId&&t.relayerKeyId===n.relayerKeyId&&t.operationCredential.kind===n.operationCredential.kind&&t.operationCredential.token===n.operationCredential.token&&t.operationCredential.walletSessionId===n.operationCredential.walletSessionId&&r(t.session,n.session)&&ae(t.authMethod,n.authMethod)&&i&&m(t.factorAuthority,n.factorAuthority)&&t.holderRuntime.kind===n.holderRuntime.kind&&t.holderRuntime.walletId===n.holderRuntime.walletId&&t.holderRuntime.authorityId===n.holderRuntime.authorityId&&t.holderRuntime.walletAuthMethodId===n.holderRuntime.walletAuthMethodId&&m(t.holderRuntime.factorAuthority,n.holderRuntime.factorAuthority)&&e(t.holderRuntime.materialActivation,n.holderRuntime.materialActivation)&&t.holderRuntime.holderHandleId===n.holderRuntime.holderHandleId&&t.holderRuntime.ecdsaThresholdKeyId===n.holderRuntime.ecdsaThresholdKeyId&&ne(t.normalSigning,n.normalSigning)}async function q(e){let t=await Ce({ports:e.ports,input:{walletId:e.expectedRuntime.walletId,requiredCapability:`export_keys`,materialActivation:e.expectedRuntime.materialActivation}});if(t.kind!==`resolved`)throw Error(`[SigningEngine][ecdsa-export] active Wallet Authority runtime is ${t.reason}`);return Qe({expected:e.expectedRuntime,actual:t.runtime}),t.runtime}async function et(e){await q(e)}function J(e){let t=e.credential,n=String(t.rawId||t.id||``).trim();if(!n||n!==e.authority.factor.credentialIdB64u)throw Error(`[SigningEngine][ecdsa-export] passkey credential does not match authority`);return{kind:`passkey`,authority:e.authority,webauthn_authentication:{id:t.id,rawId:t.rawId,type:t.type,authenticatorAttachment:t.authenticatorAttachment??null,response:{clientDataJSON:t.response.clientDataJSON,authenticatorData:t.response.authenticatorData,signature:t.response.signature,userHandle:t.response.userHandle??null},clientExtensionResults:t.clientExtensionResults??null}}}function Y(e){if(!p(e.authority))throw Error(`[SigningEngine][ecdsa-export] Email OTP material authority mismatch`);return{kind:`email_otp`,authority:e.authority,challenge_id:e.challengeId,otp_code:e.otpCode}}async function X(e){let t=await xe({relayerUrl:e.relayerUrl,transport:e.transport,request:{kind:`router_ab_ecdsa_operation_step_up_v1`,operation:e.prepared.operation,proof:e.proof}});if(t.operation_kind!==`evm.export_key`)throw Error(`[SigningEngine][ecdsa-export] operation step-up kind mismatch`);let n=t.authorization.evidence_set_digest,r=tt({proofKind:e.proof.kind,unseal:t.authorization.unseal});return{kind:`verified_step_up`,evidenceSetDigest:n,operation:e.prepared.operation,expiresAtMs:t.expires_at_ms,quotaUse:`none`,unseal:r,exportTopology:t.export_topology}}function tt(e){switch(e.proofKind){case`passkey`:if(e.unseal.kind!==`not_requested`)throw Error(`[SigningEngine][ecdsa-export] passkey step-up returned Email OTP unseal material`);return{kind:`not_requested`};case`email_otp`:if(e.unseal.kind!==`email_otp_grant`)throw Error(`[SigningEngine][ecdsa-export] Email OTP step-up did not return an unseal grant`);return{kind:`email_otp_grant`,grant:e.unseal.grant,challenge_id:e.unseal.challenge_id};default:{let t=e.proofKind;throw Error(`Unsupported ECDSA export step-up proof: ${String(t)}`)}}}async function nt(e,t){U(t.exportLane);let n=I(`tecdsa-export`),r=await K({walletId:t.walletId,chainTarget:t.exportLane.chainTarget,requestId:n,keyHandle:t.material.existingRoleLocalMaterial.publicFacts.keyHandle,displayPublicKey:t.material.existingRoleLocalMaterial.publicFacts.groupPublicKey33B64u,displayAddress:t.material.existingRoleLocalMaterial.publicFacts.ethereumAddress,materialActivation:t.material.existingRoleLocalMaterial.materialActivation,operationRuntime:t.material,operationExpiresAtMs:Date.now()+5*6e4}),i=await B({touchConfirm:e.touchConfirm,theme:e.theme},{walletSessionUserId:t.walletId,credentialIdB64u:U(t.exportLane).credentialIdB64u,publicKey:t.exportPublicKey,chainTarget:t.exportLane.chainTarget,challengeB64u:r.challengeB64u,flowId:t.flowId,onEvent:t.onEvent});await Xe({deps:e,exportLane:t.exportLane,expectedMaterialActivation:t.material.existingRoleLocalMaterial.materialActivation});let a=t.exportLane.capability.authority;if(!f(a))throw Error(`[SigningEngine][ecdsa-export] exact Passkey capability authority changed`);let o=await X({relayerUrl:t.material.relayerUrl,prepared:r,transport:{kind:`factor_proof`},proof:J({authority:a,credential:i.credential})});return{exportActivation:ge({relayerUrl:t.material.relayerUrl,existingRoleLocalMaterial:t.material.existingRoleLocalMaterial,authorization:o}),credential:i.credential}}async function rt(e){let t=d({walletId:e.walletId,walletSessionUserId:e.walletId});return await e.deps.emailOtp.exportEcdsaKeyWithDurableAuthorization({walletSession:t,chainTarget:e.material.chainTarget,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode,publicFacts:e.material.publicFacts,runtimePolicyScope:e.material.runtimePolicyScope,authority:e.material.authorization.authority,persistedMaterial:e.persistedMaterial,explicitExportAuthorization:e.explicitExportAuthorization})}function Z(e){return{normalSigning:e.runtime.normalSigning,relayerKeyId:e.relayerKeyId,participantIds:e.participantIds}}function Q(e){return Math.min(Date.now()+5*6e4,e.session.expiresAtMs)}async function it(e){if(e.material.runtime.auth.kind!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] active passkey runtime auth mismatch`);if(!f(e.material.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority mismatch`);let t=await K({walletId:e.walletId,chainTarget:e.exportLane.chainTarget,requestId:I(`tecdsa-active-passkey-export`),keyHandle:e.material.runtime.publicFacts.keyHandle,displayPublicKey:e.material.runtime.publicFacts.publicKeyB64u,displayAddress:e.material.runtime.publicFacts.thresholdOwnerAddress,materialActivation:e.material.runtime.materialActivation,operationRuntime:Z(e.material),operationExpiresAtMs:Q(e.material.runtime)}),n=await B({touchConfirm:e.deps.touchConfirm,theme:e.deps.theme},{walletSessionUserId:e.walletId,credentialIdB64u:e.material.factorAuthority.factor.credentialIdB64u,publicKey:e.exportPublicKey,chainTarget:e.exportLane.chainTarget,challengeB64u:t.challengeB64u,flowId:e.flowId,onEvent:e.onEvent}),r=await q({ports:e.deps.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e.material.runtime});if(!f(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active passkey factor authority changed`);return{runtime:r,authorization:await X({relayerUrl:e.material.relayerUrl,prepared:t,transport:{kind:`wallet_session`,credential:r.operationCredential},proof:J({authority:r.factorAuthority,credential:n.credential})})}}async function at(e){if(e.material.runtime.auth.kind!==`email_otp`)throw Error(`[SigningEngine][ecdsa-export] active Email OTP runtime auth mismatch`);if(!p(e.material.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority mismatch`);let t=await K({walletId:e.walletId,chainTarget:e.exportLane.chainTarget,requestId:I(`tecdsa-active-email-otp-export`),keyHandle:e.material.runtime.publicFacts.keyHandle,displayPublicKey:e.material.runtime.publicFacts.publicKeyB64u,displayAddress:e.material.runtime.publicFacts.thresholdOwnerAddress,materialActivation:e.material.runtime.materialActivation,operationRuntime:Z(e.material),operationExpiresAtMs:Q(e.material.runtime)}),n=await R({touchConfirm:e.deps.touchConfirm,requestExportChallenge:e.deps.emailOtp.requestExportChallenge},{kind:`wallet_session_export_auth`,walletSession:d({walletId:e.walletId,walletSessionUserId:e.walletId}),chain:D(e.exportLane),publicKey:e.exportPublicKey,curve:`ecdsa`,flowId:e.flowId,onEvent:e.onEvent}),r=await q({ports:e.deps.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:e.material.runtime});if(!p(r.factorAuthority))throw Error(`[SigningEngine][ecdsa-export] active Email OTP factor authority changed`);return{runtime:r,authorization:await X({relayerUrl:e.material.relayerUrl,prepared:t,transport:{kind:`wallet_session`,credential:r.operationCredential},proof:Y({authority:r.factorAuthority,challengeId:n.challengeId,otpCode:n.otpCode})})}}async function ot(e){switch(e.material.kind){case`active_wallet_authority_passkey_needs_authorization`:return await it({deps:e.deps,walletId:e.walletId,exportLane:e.exportLane,material:e.material,exportPublicKey:e.exportPublicKey,flowId:e.flowId,onEvent:e.onEvent});case`active_wallet_authority_email_otp_needs_authorization`:return await at({deps:e.deps,walletId:e.walletId,exportLane:e.exportLane,material:e.material,exportPublicKey:e.exportPublicKey,flowId:e.flowId,onEvent:e.onEvent});default:return st(e.material)}}function st(e){throw Error(`[SigningEngine][ecdsa-export] unsupported active wallet authority material: ${String(e)}`)}async function ct(e,t){let n=String(t.material.publicFacts.publicKeyB64u),r=await ot({deps:e,walletId:t.walletId,exportLane:t.exportLane,material:t.material,exportPublicKey:n,flowId:t.flowId,onEvent:t.onEvent});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,activeRuntime:r.runtime,exportPublicKey:n,options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:async()=>{let n=await q({ports:e.activeWalletAuthorityEcdsaRuntimeReadPorts,expectedRuntime:r.runtime});return await _e({getSignerWorkerContext:e.getSignerWorkerContext},{runtime:n,operationAuthorization:r.authorization,relayerUrl:t.material.relayerUrl})}})}async function lt(e,t){let n=D(t.exportLane),r=await G({walletId:t.walletId,chainTarget:t.exportLane.chainTarget,requestId:I(`tecdsa-email-otp-export`),keyHandle:t.material.persistedMaterial.publicFacts.keyHandle,displayPublicKey:t.material.persistedMaterial.publicFacts.groupPublicKey33B64u,displayAddress:t.material.persistedMaterial.publicFacts.ethereumAddress,materialActivation:t.material.persistedMaterial.materialActivation,operationRuntime:t.material,operationExpiresAtMs:Date.now()+5*6e4}),i=await R({touchConfirm:e.touchConfirm,requestExportChallenge:e.emailOtp.requestExportChallenge},{kind:`wallet_session_export_auth`,walletSession:d({walletId:t.walletId,walletSessionUserId:t.walletId}),chain:n,publicKey:String(t.material.publicFacts.publicKeyB64u),curve:`ecdsa`,flowId:t.flowId,onEvent:t.onEvent});await Ze({deps:e,exportLane:t.exportLane,expectedMaterialActivation:t.material.persistedMaterial.materialActivation});let a=await X({relayerUrl:t.material.relayerUrl,prepared:r,transport:{kind:`factor_proof`},proof:Y({authority:t.material.authorization.authority,challengeId:i.challengeId,otpCode:i.otpCode})});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,exportPublicKey:String(t.material.publicFacts.publicKeyB64u),options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:rt.bind(void 0,{deps:e,walletId:t.walletId,material:t.material,authorization:i,persistedMaterial:t.material.persistedMaterial,explicitExportAuthorization:a})})}async function ut(e,t){if(t.exportLane.authMethod!==`passkey`)throw Error(`[SigningEngine][ecdsa-export] fresh passkey export requires passkey lane`);let n=String(t.material.publicFacts.publicKeyB64u),r=await nt(e,{walletId:t.walletId,exportLane:t.exportLane,material:t.material,exportPublicKey:n,flowId:t.flowId,onEvent:t.onEvent});return await H(e,{walletId:t.walletId,exportLane:t.exportLane,exportPublicKey:n,options:t.options,flowId:t.flowId,onEvent:t.onEvent,prepareArtifact:async()=>{let n=await e.provisionPasskeyEcdsaExplicitExportSession(r.exportActivation);return await he({getSignerWorkerContext:e.getSignerWorkerContext},{walletSessionUserId:t.walletId,exportProvision:n,factorAuthorization:{kind:`passkey`,passkeyCredentialIdB64u:String(r.credential.rawId||r.credential.id),credential:r.credential}})}})}function $(e){let t=e.source===`canonical_capability`?e.authorization:null;return{authMethod:S(e),curve:e.curve,chain:e.chainTarget.kind,chainTarget:e.chainTarget,state:e.state,source:e.source,...t?{remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}:{},updatedAtMs:e.updatedAtMs,evmFamilyKeyFingerprint:g({walletId:e.key.walletId,publicFacts:e.publicFacts})}}function dt(e,t){return String(e.key.walletId)===t.walletId?String(g({walletId:e.key.walletId,publicFacts:e.publicFacts})):``}function ft(e){if(!e.candidates.length)throw y(`evm-family`,{stage:`key_export.exact_lane_no_candidate`,context:e.context,candidateCount:e.candidates.length,candidates:e.candidates.map($)}),Error(`[SigningEngine][${e.context}] exact lane selection failed: no_candidate`);for(let t of e.candidates)if(!dt(t,e.ecdsaContext))return pt(e);if(e.candidates.length!==1)return pt(e);let[t]=e.candidates;return me(`evm-family`,{stage:`key_export.exact_lane_selected`,context:e.context,reason:`single_exact_candidate`,selectedLane:$(t),candidateCount:e.candidates.length}),t}function pt(e){throw y(`evm-family`,{stage:`key_export.exact_lane_ambiguous_material`,context:e.context,candidateCount:e.candidates.length,candidates:e.candidates.map($)}),Error(`[SigningEngine][${e.context}] exact lane selection failed: ambiguous_material`)}function mt(e){return pe({signer:de({walletId:e.lane.key.walletId,chainTarget:e.chainTarget||e.lane.chainTarget,keyHandle:e.lane.publicFacts.keyHandle,key:e.lane.key,materialActivation:e.lane.materialActivation}),auth:e.lane.auth})}function ht(e){return e.source===`active_wallet_authority`||e.state===`ready`?{kind:`loaded_worker_material`}:S(e)===`email_otp`?{kind:`material_pending`,reason:`email_otp_route_auth`}:{kind:`sealed_worker_material`}}function gt(e){if(e.lane.source===`active_wallet_authority`)return{chainTarget:e.chainTarget,authMethod:S(e.lane),material:{kind:`loaded_worker_material`},state:`deferred`};let t=S(e.lane),n=ht(e.lane);switch(e.lane.state){case`expired`:case`exhausted`:throw Error(`[SigningEngine][ecdsa-export] expired export lane requires durable public reauth authority`);case`ready`:case`deferred`:return{chainTarget:e.chainTarget,authMethod:t,material:n,state:e.lane.state}}}async function _t(e){let t=e.lane,n=mt({lane:t}),r=gt({lane:t,chainTarget:e.chainTarget});return t.source===`active_wallet_authority`?{curve:`ecdsa`,laneIdentity:n,source:`active_wallet_authority`,authorizationState:`authorization_required`,key:t.key,publicFacts:t.publicFacts,runtime:t.runtime,chainTarget:e.chainTarget,authMethod:S(t),material:{kind:`loaded_worker_material`},state:`deferred`}:t.authorization?{curve:`ecdsa`,laneIdentity:n,source:`canonical_capability`,authorizationState:`authorized`,authorization:t.authorization,capability:t.capability,key:t.key,publicFacts:t.publicFacts,...r}:{curve:`ecdsa`,laneIdentity:n,source:`canonical_capability`,authorizationState:`authorization_required`,capability:t.capability,key:t.key,publicFacts:t.publicFacts,...r}}function vt(e){return v(e.laneIdentity)===v(e.identity)}async function yt(e){return mt({lane:e})}function bt(e){return we(e.availableLanes,e.chainTarget).filter(e=>De(e))}async function xt(e,t){let n=bt({availableLanes:await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:t.walletId,ecdsaChainTargets:[t.signingTarget]}),chainTarget:t.signingTarget}),r=[];for(let e of n)vt({laneIdentity:await yt(e),identity:t.laneIdentity})&&r.push(e);let i=ft({context:`ecdsa-export`,candidates:r,ecdsaContext:{walletId:t.walletId}});return await _t({lane:i,chainTarget:i.chainTarget})}async function St(e,t){switch(t.kind){case`ecdsa`:return await Ct(e,t);case`ed25519`:return await Dt(e,t)}}async function Ct(e,t){let n=String(l(t.walletSession.walletId));return{kind:`ecdsa`,laneIdentity:await yt(ft({context:`ecdsa-export-resolve`,candidates:bt({availableLanes:await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:n,ecdsaChainTargets:[t.chainTarget]}),chainTarget:t.chainTarget}),ecdsaContext:{walletId:n}}))}}function wt(e){let t=e.lane.source===`durable_sealed_record`||e.lane.source===`public_capability_reference`;return String(e.lane.walletId)===e.walletId&&String(e.lane.nearAccountId)===e.nearAccountId&&t}function Tt(e){return ue({signer:fe({walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot}),auth:e.auth,thresholdSessionId:e.thresholdSessionId})}function Et(e){return[e.walletId,e.nearAccountId,e.nearEd25519SigningKeyId,e.signerSlot,ce(e.auth)].map(e=>String(e)).join(`|`)}async function Dt(e,t){let n=String(l(t.walletSession.walletId)),r=String(t.nearAccount.accountId),i=await e.readOwnerScopedAvailableSigningLanesForTargets({walletId:n,ecdsaChainTargets:[]}),a=i.lanes.ed25519.near;if(!b(a)||a.curve!==`ed25519`||!wt({lane:a,walletId:n,nearAccountId:r}))throw Error(`[SigningEngine][ed25519-export-resolve] exact Yao lane selection failed: no_candidate`);let o=i.candidates.ed25519.near.filter(e=>b(e)&&e.curve===`ed25519`&&wt({lane:e,walletId:n,nearAccountId:r})),s=Et(a);if(o.some(e=>Et(e)!==s))throw Error(`[SigningEngine][ed25519-export-resolve] exact Yao lane selection failed: ambiguous_material`);return{kind:`ed25519`,laneIdentity:Tt(a),materialActivation:a.materialActivation}}async function Ot(e,t){let n=await xt(e,{walletId:t.walletId,signingTarget:t.signingTarget,laneIdentity:t.laneIdentity});switch(n.material.kind){case`loaded_worker_material`:case`material_pending`:case`sealed_worker_material`:return n}throw n.material,Error(`[SigningEngine][ecdsa-export] unsupported material availability`)}function kt(e){return e.capability.materialActivation}function At(e){return e.material.materialActivation}function jt(e){return e.auth.kind===`passkey`}function Mt(e){if(!jt(e.laneIdentity))throw Error(`[SigningEngine][ed25519-export] export requires a passkey Yao lane`);if(e.laneIdentity.signer.account.wallet.walletId!==e.walletId||String(e.laneIdentity.signer.account.nearAccountId)!==String(e.nearAccountId))throw Error(`[SigningEngine][ed25519-export] exact lane subject mismatch`);return e.laneIdentity}function Nt(e){return e.auth.kind===`email_otp`}function Pt(e){if(!Nt(e.laneIdentity))throw Error(`[SigningEngine][ed25519-export] export requires an Email OTP Yao lane`);if(e.laneIdentity.signer.account.wallet.walletId!==e.walletId||String(e.laneIdentity.signer.account.nearAccountId)!==String(e.nearAccountId))throw Error(`[SigningEngine][ed25519-export] exact lane subject mismatch`);return e.laneIdentity}function Ft(e){let t=e.selected.signer,n=e.context.material;return String(t.account.wallet.walletId)===String(n.walletId)&&String(t.account.nearAccountId)===String(n.nearAccountId)&&String(t.nearEd25519SigningKeyId)===String(n.nearEd25519SigningKeyId)&&t.signerSlot===n.signerSlot&&String(e.selected.auth.rpId)===e.context.rpId&&e.selected.auth.credentialIdB64u===n.credentialIdB64u}function It(t){if(!Ft({selected:t.selectedLaneIdentity,context:t.context}))throw Error(`[SigningEngine][ed25519-export] durable Yao context identity mismatch`);let n=t.context.material;if(!e(t.selectedMaterialActivation,t.context.selectedLaneMaterialActivation))throw Error(`[SigningEngine][ed25519-export] durable Yao context activation mismatch`);let r=t.context.authorization.operationCredential.token;if(!r)throw Error(`[SigningEngine][ed25519-export] active Wallet Session authorization is unavailable`);let i=n.capability.lifecycle;return{laneIdentity:t.selectedLaneIdentity,relayerUrl:t.context.relayerUrl,walletSessionToken:r,walletCustodyEnvelope:t.context.walletCustodyEnvelope,capability:{materialActivation:n.capability.materialActivation,scope:{lifecycle_id:i.lifecycleId,root_share_epoch:i.rootShareEpoch,account_id:i.accountId,threshold_session_id:i.thresholdSessionId,signer_set_id:i.signerSetId,signing_worker_id:i.signingWorkerId,material_activation:re(n.capability.materialActivation)},applicationBinding:n.capability.applicationBinding,participantIds:n.capability.participantIds,registeredPublicKey:n.capability.registeredPublicKey,stateEpoch:n.capability.stateEpoch,activeCapabilityBinding:n.capability.activeCapabilityBinding,runtimePolicyScope:n.capability.runtimePolicyScope}}}async function Lt(e,t){let n=Mt(t),r=await e.resolvePasskeyExportContext({laneIdentity:n,materialActivation:t.materialActivation});switch(r.kind){case`ready`:return It({context:r.context,selectedLaneIdentity:n,selectedMaterialActivation:t.materialActivation});case`capability_recovery_required`:throw Error(`[SigningEngine][ed25519-export] passkey material recovery did not publish durable context`)}throw Error(`[SigningEngine][ed25519-export] unsupported passkey export context state`)}async function Rt(t,n){let r=Pt(n),i=await t.emailOtp.resolveExportContext({laneIdentity:r,materialActivation:n.materialActivation});if(!e(n.materialActivation,i.material.materialActivation)&&i.material.kind!==`sealed_export_root`)throw Error(`[SigningEngine][ed25519-export] Email OTP Yao context activation mismatch`);return{context:i,laneIdentity:r}}function zt(e){let t=e.resolved.laneIdentity.signer;return{artifactKind:ve,walletId:String(e.input.walletId),nearAccountId:String(e.input.nearAccountId),relayerUrl:e.resolved.relayerUrl,authorization:{kind:`opaque_wallet_session`,walletSessionToken:e.resolved.walletSessionToken},flowId:e.input.flowId,viewerSessionId:e.viewerSessionId,exactLane:{nearEd25519SigningKeyId:String(t.nearEd25519SigningKeyId),signerSlot:t.signerSlot,credentialIdB64u:e.resolved.laneIdentity.auth.credentialIdB64u,materialActivation:kt(e.resolved)},walletCustodyEnvelope:e.resolved.walletCustodyEnvelope,capability:e.resolved.capability,variant:e.input.options.variant,theme:e.input.options.theme??e.theme}}function Bt(e,t){let n=String(e.walletId);F(e.onEvent,{phase:t===`opened`?_.STEP_04_VIEWER_OPENED:_.STEP_05_VIEWER_CLOSED,status:t===`opened`?`waiting_for_user`:`succeeded`,flowId:e.flowId,accountId:n,interaction:{kind:`key_export_viewer`,overlay:t===`opened`?`show`:`hide`},data:{chain:`near`,curve:`ed25519`}}),t===`closed`&&F(e.onEvent,{phase:_.STEP_06_COMPLETED,status:`succeeded`,flowId:e.flowId,accountId:n,interaction:{kind:`none`,overlay:`hide`},data:{chain:`near`,curve:`ed25519`}})}async function Vt(e,t){switch(t.laneIdentity.auth.kind){case`passkey`:break;case`email_otp`:return await Ht(e,t);default:throw t.laneIdentity.auth,Error(`[SigningEngine][ed25519-export] unsupported lane authorization method`)}let n=Lt(e,t),r=e.touchConfirm.initialize(),[i]=await Promise.all([n,r]),a=String(t.walletId),o=I(`export-ed25519-yao-viewer-session`),s=Bt.bind(void 0,{flowId:t.flowId,walletId:t.walletId,onEvent:t.onEvent});F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_STARTED,status:`waiting_for_user`,flowId:t.flowId,accountId:a,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`show`},data:{intent:`ed25519_export`,chain:`near`,curve:`ed25519`}}),F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:t.flowId,accountId:a,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}});let c=await e.withThresholdEd25519CommitQueue({queueKey:x({materialActivation:kt(i)}),nearAccountId:t.nearAccountId,enabled:!0,task:()=>e.passkeyMpcExport.exportPrivateKeysWithUi(zt({resolved:i,viewerSessionId:o,input:t,theme:e.theme}),{onViewerLifecycle:s})});if(c.kind!==`completed`)throw Error(c.error);if(c.exportedSchemes.length!==1||c.exportedSchemes[0]!==`ed25519`)throw Error(`[SigningEngine][ed25519-export] secure export failed`);return F(t.onEvent,{phase:_.STEP_02_AUTH_PASSKEY_PROMPT_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:a,authMethod:`passkey`,interaction:{kind:`passkey_assert`,overlay:`none`},data:{intent:`ed25519_export`,chain:`near`,curve:`ed25519`}}),F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:a,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}}),{accountId:String(t.nearAccountId),exportedSchemes:[`ed25519`]}}async function Ht(e,t){let n=await Rt(e,t),r=`ed25519:${s(Uint8Array.from(n.context.material.capability.registeredPublicKey))}`,i=await We({touchConfirm:e.touchConfirm,requestExportChallenge:e.emailOtp.requestExportChallenge},{kind:`email_otp_ed25519_export_auth`,walletId:t.walletId,nearAccountId:String(t.nearAccountId),nearEd25519SigningKeyId:String(n.laneIdentity.signer.nearEd25519SigningKeyId),signerSlot:n.laneIdentity.signer.signerSlot,publicKey:r,curve:`ed25519`,chain:`near`,flowId:t.flowId,onEvent:t.onEvent});F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_STARTED,status:`running`,flowId:t.flowId,accountId:String(t.nearAccountId),interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}});let a=I(`export-ed25519-yao-viewer-session`);try{await z({touchConfirm:e.touchConfirm,theme:e.theme},{state:`loading`,walletId:String(t.walletId),nearAccountId:String(t.nearAccountId),publicKey:r,variant:t.options.variant,theme:t.options.theme,viewerSessionId:a,flowId:t.flowId,onEvent:t.onEvent});let o=await e.withThresholdEd25519CommitQueue({queueKey:x({materialActivation:At(n.context)}),nearAccountId:t.nearAccountId,enabled:n.context.material.kind===`active_capability`,task:()=>e.emailOtp.exportSeedWithFreshAuthorization({challengeId:i.challengeId,otpCode:i.otpCode,exportContext:n.context})});return F(t.onEvent,{phase:_.STEP_03_MATERIAL_PREPARE_SUCCEEDED,status:`succeeded`,flowId:t.flowId,accountId:String(t.nearAccountId),interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,curve:`ed25519`}}),E(a)&&await z({touchConfirm:e.touchConfirm,theme:e.theme},{state:`ready`,walletId:String(t.walletId),nearAccountId:String(t.nearAccountId),publicKey:o.publicKey,privateKey:o.privateKey,variant:t.options.variant,theme:t.options.theme,viewerSessionId:a,flowId:t.flowId,onEvent:t.onEvent}),{accountId:String(t.nearAccountId),exportedSchemes:[`ed25519`]}}catch(e){throw T(),e}}function Ut(e){switch(e.kind){case`active`:case`expired`:return e;case`missing`:case`unavailable`:case`invalid`:return null;default:return e}}async function Wt(e){await e.deps.sessionLifecycle.invalidateExpiredAuthorization({state:e.state,source:e.source})}async function Gt(e){let t=await e.deps.sessionLifecycle.readAuthorization(e.request);return t.kind===`expired`&&await Wt({deps:e.deps,state:t,source:oe.operationPreflight}),t}function Kt(e){let t=Ut(e.preflightState);return t?Te({source:e.source,expiresAtMs:t.expiresAtMs,detectedAtMs:e.detectedAtMs}):null}async function qt(e,t){let n=l(t.walletSession.walletId),r=await Ot(e.laneSelection,{walletId:n,signingTarget:Ee(t.chainTarget),laneIdentity:t.laneIdentity}),i=await j(e.ecdsa.sessionStore,r);if(r.source===`active_wallet_authority`){if(i.source!==`active_wallet_authority`)throw Error(`[SigningEngine][ecdsa-export] active lane material source changed`);return{kind:`active_wallet_authority`,exportLane:r,exportMaterial:i}}if(i.source!==`canonical_capability`)throw Error(`[SigningEngine][ecdsa-export] canonical lane material source changed`);return{kind:`canonical_capability`,exportLane:r,exportMaterial:i}}function Jt(e){if(!(!e||e.source!==`canonical_capability`||!e.authorization))return e.authorization.operationCredential.walletSessionId}function Yt(e){let t=e.exportLane?.publicFacts,n=e.exportLane?g({walletId:e.exportLane.key.walletId,publicFacts:e.exportLane.publicFacts}):void 0;try{console.warn(`[SigningEngine][ecdsa-export][failure]`,{operationId:e.flowId,authMethod:e.exportLane?.authMethod,...n?{evmFamilyKeyFingerprint:n}:{},...t?{keyHandle:String(t.keyHandle)}:{},chainTargetKey:u(e.input.chainTarget),...Jt(e.exportLane)?{walletSessionId:Jt(e.exportLane)}:{},materialActivationId:e.exportLane?.laneIdentity.signer.materialActivation.activationId,freshAuthRetrySideEffectState:`not_applicable`,error:e.error instanceof Error?e.error.message:String(e.error||`unknown error`)})}catch{}}async function Xt(e,t,n){let r=l(t.walletSession.walletId);if(n.kind===`active_wallet_authority`)return await ct(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});if(n.exportMaterial.kind===`fresh_email_otp_route_auth_ready`)return await lt(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});if(n.exportMaterial.kind===`fresh_passkey_needs_authorization`)return await ut(e.ecdsa,{walletId:r,exportLane:n.exportLane,material:n.exportMaterial,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent});throw n.exportMaterial,Error(`[SigningEngine][ecdsa-export] unsupported export material`)}async function Zt(e,t,n){let[r]=await Promise.all([qt(e,t),e.ecdsa.touchConfirm.initialize()]);if(r.exportLane.authorizationState===`authorization_required`)try{return await Xt(e,t,r)}catch(e){throw Yt({input:t,flowId:t.flowId,exportLane:r.exportLane,exportMaterial:r.exportMaterial,error:e}),e}let i={kind:`ecdsa`,laneIdentity:r.exportLane.laneIdentity,authorization:r.exportLane.authorization},a=await Gt({deps:e,request:{kind:`ecdsa`,laneIdentity:r.exportLane.laneIdentity,authorization:r.exportLane.authorization,nowMs:Date.now()}});try{return await Xt(e,t,r)}catch(o){Yt({input:t,flowId:t.flowId,exportLane:r.exportLane,exportMaterial:r.exportMaterial,error:o});let s=ye(o);if(n.kind===`fresh_auth_retry`||s?.kind!==`expired`)throw o;let c=Kt({source:i,preflightState:a,detectedAtMs:Date.now()});if(!c)throw o;return await Wt({deps:e,state:c,source:oe.serverRejection}),await Zt(e,t,{kind:`fresh_auth_retry`})}}async function Qt(e,t){return await Vt(e.ed25519Yao,{walletId:t.walletSession.walletId,nearAccountId:t.nearAccount.accountId,laneIdentity:t.laneIdentity,materialActivation:t.materialActivation,options:{variant:t.options.variant,theme:t.options.theme},flowId:t.flowId,onEvent:t.options.onEvent})}async function $t(e,t){return await He(t,async t=>{switch(t.kind){case`ecdsa`:return await Zt(e,t,{kind:`initial`});case`ed25519`:return await Qt(e,t)}})}async function en(e,t){return await St(e.laneSelection,t)}export{$t as exportKeypairWithUI,en as resolveExactKeyExportLane};
@@ -1 +1 @@
1
- import{C as e,S as t}from"./chains-C_X_fNuS.js";import{n}from"./walletRegistrationSetupPrewarm-B9kpnrbK.js";import{t as r}from"./walletDbName-DtRewci9.js";import{_ as i,b as a,c as o,d as s,g as c,i as l,m as u,n as d,r as f,t as p,u as m,v as ee,y as te}from"./sessionObservationRevision-CnEOLDbl.js";import{a as h,c as g,i as _,l as ne,n as v,o as re,s as y,t as ie,u as ae}from"./transactionReviewAdmission-CIvR4W5_.js";import{t as b}from"./events-1dzC4Ocx.js";import{t as x}from"./walletIframeIdentity-Cz82I_Uh.js";import{t as S}from"./errors-DIWY1KR9.js";import{t as C}from"./signer-worker-DlK58rEA.js";function w(){let e=globalThis;e.global===void 0&&(e.global=globalThis),!e.process||typeof e.process!=`object`?e.process={env:{}}:(!e.process.env||typeof e.process.env!=`object`)&&(e.process.env={})}function T(){w(),window.location.origin===`null`&&(window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`),console.warn(`[WalletHost] iframe is running with opaque (null) origin. Check COEP/CORP headers and ensure navigation succeeded.`)),oe(),window.parent?.postMessage({type:`SERVICE_HOST_BOOTED`},`*`),window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`);let e=new URL(import.meta.url),t=e.searchParams.get(`v`);t&&c(t);let n=new URL(`.`,e).toString(),r=n.endsWith(`/`)?n:n+`/`;u()||i(r)}function oe(){let e=()=>{let e=document;e.documentElement.classList.add(`seams-transparent`),e.body?.classList.add(`seams-transparent`),e.documentElement.classList.remove(`dark`),e.body?.classList.remove(`dark`)};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>e(),{once:!0}):e(),window.addEventListener(`load`,()=>e(),{once:!0})}const E={};let D=null,O=null;function se(e){return e.type===`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`?(D??=import(`./runtime-recovery-codes-GOytzExh.js`),D):k(e.kind)}function ce(){k(`auth`).catch(le)}function le(){}function k(e){let t=E[e];if(t)return t;let n=M(e);return E[e]=n,n.catch(A.bind(null,e,n)),n}function A(e,t){E[e]===t&&delete E[e]}async function j(){D??=import(`./runtime-recovery-codes-GOytzExh.js`),O??=Promise.all([D,import(`./mountRecoveryCodeBackupSurface-DlEb3uD7.js`)]).then(()=>void 0),await O}function M(e){switch(e){case`auth`:return import(`./runtime-auth-DDOPe7LO.js`);case`near`:return import(`./runtime-near-Bl7bBU2g.js`);case`ecdsa`:return import(`./runtime-ecdsa-tempo-DUOkCNFT.js`);case`email_otp`:return import(`./runtime-email-otp-Bsv55Gin.js`);case`recovery`:return import(`./runtime-recovery-BMY7AkJq.js`);case`export`:return import(`./runtime-export-D7QKXvdg.js`);case`device_link`:return import(`./runtime-device-link-Bkt5AJAI.js`);case`preferences`:return import(`./runtime-preferences-C2Rqmp7q.js`)}return N(e)}function N(e){throw Error(`Unhandled wallet host runtime route: ${String(e)}`)}function P(e){switch(e.type){case`PM_GET_RECENT_UNLOCKS`:case`PM_GET_CONFIRMATION_CONFIG`:return!0;case`PM_GET_EXACT_WALLET_SESSION_STATE`:{let t=e.request.payload;if(!t||typeof t!=`object`)return!1;let n=Reflect.get(t,`authenticationRead`),r=Reflect.get(t,`wallet`);return(n===`restore`||n===`current`)&&!!r&&typeof r==`object`&&Reflect.get(r,`kind`)===`current`}default:return!1}}function F(e){switch(e.type){case`PM_GET_EXACT_WALLET_SESSION_STATE`:return{revision:p(),walletId:null,state:{kind:`wallet_locked`},session:d()};case`PM_GET_RECENT_UNLOCKS`:return{walletIds:[],accountIds:[],accounts:[],lastUsedAccount:null};case`PM_GET_CONFIRMATION_CONFIG`:return{walletId:null,confirmationConfig:C,revision:0}}}let I=null;function L(){return I??=z().finally(R),I}function R(){I=null}async function z(){try{return typeof indexedDB>`u`||typeof indexedDB.databases!=`function`?!1:(await indexedDB.databases()).some(B)?await V():!0}catch{return!1}}function B(e){return e.name===r}function V(){return new Promise(e=>{let t=indexedDB.open(r);t.onupgradeneeded=()=>t.transaction?.abort(),t.onerror=()=>e(!1),t.onsuccess=()=>{let n=t.result;n.onversionchange=()=>n.close(),H(n).then(t=>{n.close(),e(t===0)},()=>{n.close(),e(!1)})}})}function H(e){let t=Array.from(e.objectStoreNames);return t.length===0?Promise.resolve(0):new Promise((n,r)=>{let i=e.transaction(t,`readonly`),a=0;for(let e of t){let t=i.objectStore(e).count();t.onsuccess=()=>{a+=t.result}}i.oncomplete=()=>n(a),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}function U(e){throw Error(`Unhandled wallet host route: ${String(e)}`)}function W(e,t){if(e===null)throw Error(`Invalid ${t} payload`);return e}function G(e){try{return x(e)}catch{throw Error(`Hosted auth-menu request requires a non-empty requestId`)}}function ue(e){switch(e.type){case`PM_ACTIVATE_TRANSACTION_REVIEW`:case`PING`:case`PM_PREPARE_WALLET_RUNTIME`:case`PM_SET_CONFIG`:case`PM_CANCEL`:case`PM_SET_TRANSACTION_VIEW`:case`PM_TRANSACTION_BROADCAST_STARTED`:return{kind:`boot`,type:e.type,request:e};case`PM_REGISTER_WALLET`:case`PM_ADD_WALLET_SIGNER`:case`PM_ADD_PASSKEY`:case`PM_ADD_EMAIL_OTP`:case`PM_REVOKE_AUTH_METHOD`:case`PM_GET_NEAR_PROVISIONING_STATE`:case`PM_SIGN_TX_WITH_ACTIONS`:case`PM_SIGN_AND_SEND_TX`:case`PM_SEND_TRANSACTION`:case`PM_SIGN_DELEGATE_ACTION`:case`PM_SIGN_NEP413`:return{kind:`near`,type:e.type,request:e};case`PM_OPEN_AUTH_MENU`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(s(e.payload),`hosted auth-menu open`)}}}case`PM_CANCEL_AUTH_MENU`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(o(e.payload),`hosted auth-menu cancellation`)}}}case`PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(m(e.payload),`hosted auth-menu external-auth resolution`)}}}case`PM_UNLOCK`:case`PM_LOCK`:case`PM_LOCK_EXACT_WALLET_SESSION`:case`PM_GET_LAST_WALLET_MOVE_REQUEST`:case`PM_MOVE_WALLET`:case`PM_GET_WALLET_MOVE`:case`PM_GET_WALLET_PLACEMENT`:case`PM_GET_WALLET_SESSION`:case`PM_GET_EXACT_WALLET_SESSION_STATE`:case`PM_GET_RECENT_UNLOCKS`:return{kind:`auth`,type:e.type,request:e};case`PM_SIGN_TEMPO`:case`PM_REPORT_TEMPO_BROADCAST_ACCEPTED`:case`PM_REPORT_TEMPO_BROADCAST_REJECTED`:case`PM_REPORT_TEMPO_FINALIZED`:case`PM_REPORT_TEMPO_DROPPED_OR_REPLACED`:case`PM_RECONCILE_TEMPO_NONCE_LANE`:return{kind:`ecdsa`,type:e.type,request:e};case`PM_REDEEM_HOSTED_WALLET_SEAMS_SESSION`:case`PM_REQUEST_EMAIL_OTP_CHALLENGE`:case`PM_BEGIN_GOOGLE_EMAIL_OTP_WALLET_AUTH`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_RESEND`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_REROLL_WALLET_ID`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_SUBMIT`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_COMPLETE_REGISTRATION`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_CANCEL`:case`PM_GET_WALLET_RECOVERY_CODE_STATUS`:case`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`:case`PM_ROTATE_WALLET_RECOVERY_CODES`:case`PM_REQUEST_WALLET_CUSTODY_EMAIL_OTP_CHALLENGE`:return{kind:`email_otp`,type:e.type,request:e};case`PM_SYNC_ACCOUNT_FLOW`:return{kind:`recovery`,type:e.type,request:e};case`PM_RESOLVE_EXACT_KEY_EXPORT_LANE`:case`PM_EXPORT_KEYPAIR_UI`:return{kind:`export`,type:e.type,request:e};case`PM_HAS_PASSKEY`:case`PM_LIST_LINKED_DEVICES`:case`PM_REVOKE_LINKED_DEVICE`:case`PM_SCAN_AND_LINK_DEVICE`:case`PM_START_DEVICE2_LINKING_FLOW`:case`PM_DEVICE_LINK_TARGET_FACTOR_ACTION`:case`PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION`:case`PM_CANCEL_DEVICE_LINKING`:return{kind:`device_link`,type:e.type,request:e};case`PM_SET_CONFIRM_BEHAVIOR`:case`PM_SET_CONFIRMATION_CONFIG`:case`PM_GET_CONFIRMATION_CONFIG`:return{kind:`preferences`,type:e.type,request:e}}return U(e)}function de(e){return e.kind!==`boot`}let K=!1;const fe=[{selector:`.seams-auth-menu-surface`,cancellationKind:`native_cancel`},{selector:`.seams-confirmation-surface`,cancellationKind:`native_cancel`},{selector:`.seams-export-surface`,cancellationKind:`wallet_iframe_cancel`},{selector:`[data-seams-wallet-recovery-backup-dialog]`,cancellationKind:`native_cancel`}];function q(e,t){let n=new Set(t),r=Object.keys(e);return r.length===t.length&&r.every(e=>n.has(e))}function pe(t){return!e(t)||!q(t,[`type`,`payload`])||t.type!==`CONNECT`||!e(t.payload)||!q(t.payload,[`protocolVersion`])?null:typeof t.payload.protocolVersion==`string`?{type:`CONNECT`,payload:{protocolVersion:t.payload.protocolVersion}}:null}function J(e){if(e===`null`)return!0;try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e}catch{return!1}}function Y(e){try{e.close()}catch{}}function me(e,t){if(t===`16.0.0`)return!1;let n={expectedProtocolVersion:l,receivedProtocolVersion:t};try{e.postMessage({type:`ERROR`,payload:{code:f,message:`Wallet iframe protocol version mismatch: expected ${l}, received ${t??`missing`}`,details:n}})}catch{}return Y(e),!0}function X(e,t){return!t||t.has(e)}function Z(e,t,n,r){e.executionGeneration===t&&n(r)}function Q(e,t,n,r){return e.executionGeneration!==t||n(r)}function $(e={}){if(K)return;K=!0,T(),(!e.supportedRuntimeRouteKinds||e.supportedRuntimeRouteKinds.has(`email_otp`))&&j().catch(()=>void 0);let r=new Set,i=new Set,o=!1,s={parentOrigin:null,port:null,configuration:{kind:`unconfigured`},executionGeneration:0,onConfigurationChanged:null},c=e=>{try{s.port?.postMessage(e)}catch{}},u=e=>{e&&r.add(e)},d=e=>!!e&&(r.has(e)||_(e)?.cancelled===!0),f=e=>{e&&r.delete(e)},p=e=>{e&&c({type:`ERROR`,requestId:e,payload:{code:`cancelled`,message:`Request cancelled`}})},m=e=>!e||!d(e)?!1:_(e)?.cancelled?!0:(p(e),f(e),!0),x=()=>{for(let e of fe){let t=document.querySelectorAll(e.selector);for(let n of t)try{e.cancellationKind===`native_cancel`?n.dispatchEvent(new Event(`cancel`,{cancelable:!0})):n.dispatchEvent(new CustomEvent(b.TX_CONFIRMER_CANCEL,{bubbles:!0,composed:!0}))}catch{}}},C=async r=>{let l=r.data;if(!l||!t(l))return;let b=l.requestId,C=s.executionGeneration,w=Z.bind(null,s,C,c),T=null;try{if(`transactionReview`in l){if(l.type!==`PM_SIGN_AND_SEND_TX`&&l.type!==`PM_SIGN_TEMPO`)throw new h(`review_invalid_input`,`Review is unsupported for this request`);let e=g(l.transactionReview);if(e.requestId!==b)throw new h(`review_invalid_input`,`Review request identity mismatch`);let t=l.payload?.options?.confirmationConfig;if(t?.uiMode!==`modal`||t.behavior!==`requireClick`)throw new h(`review_unsupported_mode`,`Review requires modal presentation and explicit approval`);T=new ie(e,l.type===`PM_SIGN_TEMPO`&&l.payload?.request.senderSignatureAlgorithm!==`secp256k1`?`credential`:`mpc`,e=>w({type:`TRANSACTION_REVIEW_STATE`,requestId:b,payload:e}),e=>w({type:`ERROR`,requestId:b,payload:{code:e instanceof h?e.code:`cancelled`,message:e.message}}))}(l.type===`PM_LOCK`||l.type===`PM_LOCK_EXACT_WALLET_SESSION`)&&v(new h(`review_identity_changed`,`The wallet session changed`));let t=ue(l);if(!de(t))switch(t.type){case`PING`:c({type:`PONG`,requestId:b});return;case`PM_PREPARE_WALLET_RUNTIME`:X(`auth`,e.supportedRuntimeRouteKinds)&&ce(),c({type:`PONG`,requestId:b});return;case`PM_SET_CONFIG`:{let e=ee(s.configuration,te(t.request.payload)),r=a(s.configuration.kind===`configured`?s.configuration.config:null)!==a(e.config);if(s.configuration=e,r){s.executionGeneration+=1;let t=e.config;t.registration.publishableKey&&t.registration.projectEnvironmentId&&n(t.network.relayer.url);for(let e of i)c({type:`ERROR`,requestId:e,payload:{code:`wallet_configuration_changed`,message:`Wallet configuration changed during request`}});i.clear()}s.onConfigurationChanged?.(),r&&(v(new h(`review_identity_changed`,`Wallet execution configuration changed`)),x()),c({type:`PONG`,requestId:b});return}case`PM_ACTIVATE_TRANSACTION_REVIEW`:{let e=y(t.request.payload);e&&_(e.requestId)?.activate(e);return}case`PM_CANCEL`:{let e=t.request.payload?.requestId,n=t.request.payload,r=n&&typeof n==`object`?Reflect.get(n,`transactionReview`):void 0;if(r!==void 0){let t=g(r),i=_(t.requestId);if(t.requestId===e&&i&&ne(t,i.metadata)){let e=new h(ae(n&&typeof n==`object`?Reflect.get(n,`reviewErrorCode`):void 0),`Reviewed request cancelled`);try{re(i.metadata.validity)}catch(t){t instanceof Error&&(e=t)}i.cancel(e)}c({type:`PONG`,requestId:b});return}let i=e?_(e):void 0;if(i){i.cancel(new h(`cancelled`,`Request cancelled`)),c({type:`PONG`,requestId:b});return}u(e),x(),e&&p(e),c({type:`PONG`,requestId:b});return}case`PM_SET_TRANSACTION_VIEW`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`requestId`):null,r=e&&typeof e==`object`?Reflect.get(e,`view`):null;typeof n==`string`&&(r===`toast`||r===`closed`)&&(await import(`./transaction-activity-Cccvec2J.js`).then(e=>e.o)).setTransactionActivityView(n,r);return}case`PM_TRANSACTION_BROADCAST_STARTED`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`signedTransaction`):null;typeof n==`string`&&(await import(`./transaction-activity-Cccvec2J.js`).then(e=>e.o)).transactionBroadcastStarted(n);return}}if(!X(t.kind,e.supportedRuntimeRouteKinds)){c({type:`ERROR`,requestId:b,payload:{code:`unsupported_request`,message:`Unsupported wallet iframe request type: ${t.type}`}});return}if(b&&i.add(b),!o&&P(t)&&await L()&&!o){if(C!==s.executionGeneration||m(b))return;w({type:`PM_RESULT`,requestId:b,payload:{ok:!0,result:F(t)}});return}o=!0;let r=await se(t);if(C!==s.executionGeneration)return;await r.handleWalletHostRuntimeRequest({transactionReview:T,state:s,executionGeneration:C,req:t.request,post:Z.bind(null,s,C,c),isCancelled:Q.bind(null,s,C,d),respondIfCancelled:Q.bind(null,s,C,m)})}catch(e){if(C!==s.executionGeneration&&l.type!==`PM_SET_CONFIG`||T?.cancelled)return;let t=await import(`./canonicalSignerErrorCode-Cz48v4oy.js`);if(C!==s.executionGeneration&&l.type!==`PM_SET_CONFIG`)return;let n=e&&typeof e==`object`&&`code`in e?e.code:void 0,r=S(e),i=t.resolveWalletBoundaryErrorCode({requestType:l.type,rawCode:n,message:r,defaultCode:`HOST_ERROR`}),a=t.resolveWalletBoundaryErrorMessage({requestType:l.type,rawCode:n,code:i,message:r}),o=t.resolveWalletBoundarySignerKind(l.type);c({type:`ERROR`,requestId:b,payload:{code:i,message:a,...t.isWalletSignerBoundaryRequestType(l.type)&&t.isCanonicalSignerSessionBoundaryCode(i)&&o?{signerKind:o}:{}}})}finally{b&&(i.delete(b),f(b)),T?.finish()}};window.addEventListener(`message`,e=>{let t=pe(e.data),n=e.ports[0];if(!(!t||!n||s.port)){if(e.source!==window.parent||!J(e.origin)){Y(n);return}if(!me(n,t.payload.protocolVersion)){typeof e.origin==`string`&&e.origin.length&&e.origin!==`null`&&(s.parentOrigin=e.origin),s.port=n;try{s.port.onmessage=C,s.port.start?.()}catch{}c({type:`READY`,payload:{protocolVersion:l}})}}})}try{$()}catch(e){console.error(`[WalletHost] init failed`,e)}export{$ as t};
1
+ import{C as e,S as t}from"./chains-C_X_fNuS.js";import{n}from"./walletRegistrationSetupPrewarm-B9kpnrbK.js";import{t as r}from"./walletDbName-DtRewci9.js";import{_ as i,b as a,c as o,d as s,g as c,i as l,m as u,n as d,r as f,t as p,u as m,v as ee,y as te}from"./sessionObservationRevision-CnEOLDbl.js";import{a as h,c as g,i as _,l as ne,n as v,o as re,s as y,t as ie,u as ae}from"./transactionReviewAdmission-CIvR4W5_.js";import{t as b}from"./events-1dzC4Ocx.js";import{t as x}from"./walletIframeIdentity-Cz82I_Uh.js";import{t as S}from"./errors-DIWY1KR9.js";import{t as C}from"./signer-worker-DlK58rEA.js";function w(){let e=globalThis;e.global===void 0&&(e.global=globalThis),!e.process||typeof e.process!=`object`?e.process={env:{}}:(!e.process.env||typeof e.process.env!=`object`)&&(e.process.env={})}function T(){w(),window.location.origin===`null`&&(window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`),console.warn(`[WalletHost] iframe is running with opaque (null) origin. Check COEP/CORP headers and ensure navigation succeeded.`)),oe(),window.parent?.postMessage({type:`SERVICE_HOST_BOOTED`},`*`),window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`);let e=new URL(import.meta.url),t=e.searchParams.get(`v`);t&&c(t);let n=new URL(`.`,e).toString(),r=n.endsWith(`/`)?n:n+`/`;u()||i(r)}function oe(){let e=()=>{let e=document;e.documentElement.classList.add(`seams-transparent`),e.body?.classList.add(`seams-transparent`),e.documentElement.classList.remove(`dark`),e.body?.classList.remove(`dark`)};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>e(),{once:!0}):e(),window.addEventListener(`load`,()=>e(),{once:!0})}const E={};let D=null,O=null;function se(e){return e.type===`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`?(D??=import(`./runtime-recovery-codes-GOytzExh.js`),D):k(e.kind)}function ce(){k(`auth`).catch(le)}function le(){}function k(e){let t=E[e];if(t)return t;let n=M(e);return E[e]=n,n.catch(A.bind(null,e,n)),n}function A(e,t){E[e]===t&&delete E[e]}async function j(){D??=import(`./runtime-recovery-codes-GOytzExh.js`),O??=Promise.all([D,import(`./mountRecoveryCodeBackupSurface-DlEb3uD7.js`)]).then(()=>void 0),await O}function M(e){switch(e){case`auth`:return import(`./runtime-auth-BNR1wI8E.js`);case`near`:return import(`./runtime-near-J3hKjC7G.js`);case`ecdsa`:return import(`./runtime-ecdsa-tempo-AGjT7Xpa.js`);case`email_otp`:return import(`./runtime-email-otp-BpBOuSsT.js`);case`recovery`:return import(`./runtime-recovery-BzewdcoT.js`);case`export`:return import(`./runtime-export-CBsacCPY.js`);case`device_link`:return import(`./runtime-device-link-Dq8g_UNb.js`);case`preferences`:return import(`./runtime-preferences-CVt5sLvm.js`)}return N(e)}function N(e){throw Error(`Unhandled wallet host runtime route: ${String(e)}`)}function P(e){switch(e.type){case`PM_GET_RECENT_UNLOCKS`:case`PM_GET_CONFIRMATION_CONFIG`:return!0;case`PM_GET_EXACT_WALLET_SESSION_STATE`:{let t=e.request.payload;if(!t||typeof t!=`object`)return!1;let n=Reflect.get(t,`authenticationRead`),r=Reflect.get(t,`wallet`);return(n===`restore`||n===`current`)&&!!r&&typeof r==`object`&&Reflect.get(r,`kind`)===`current`}default:return!1}}function F(e){switch(e.type){case`PM_GET_EXACT_WALLET_SESSION_STATE`:return{revision:p(),walletId:null,state:{kind:`wallet_locked`},session:d()};case`PM_GET_RECENT_UNLOCKS`:return{walletIds:[],accountIds:[],accounts:[],lastUsedAccount:null};case`PM_GET_CONFIRMATION_CONFIG`:return{walletId:null,confirmationConfig:C,revision:0}}}let I=null;function L(){return I??=z().finally(R),I}function R(){I=null}async function z(){try{return typeof indexedDB>`u`||typeof indexedDB.databases!=`function`?!1:(await indexedDB.databases()).some(B)?await V():!0}catch{return!1}}function B(e){return e.name===r}function V(){return new Promise(e=>{let t=indexedDB.open(r);t.onupgradeneeded=()=>t.transaction?.abort(),t.onerror=()=>e(!1),t.onsuccess=()=>{let n=t.result;n.onversionchange=()=>n.close(),H(n).then(t=>{n.close(),e(t===0)},()=>{n.close(),e(!1)})}})}function H(e){let t=Array.from(e.objectStoreNames);return t.length===0?Promise.resolve(0):new Promise((n,r)=>{let i=e.transaction(t,`readonly`),a=0;for(let e of t){let t=i.objectStore(e).count();t.onsuccess=()=>{a+=t.result}}i.oncomplete=()=>n(a),i.onerror=()=>r(i.error),i.onabort=()=>r(i.error)})}function U(e){throw Error(`Unhandled wallet host route: ${String(e)}`)}function W(e,t){if(e===null)throw Error(`Invalid ${t} payload`);return e}function G(e){try{return x(e)}catch{throw Error(`Hosted auth-menu request requires a non-empty requestId`)}}function ue(e){switch(e.type){case`PM_ACTIVATE_TRANSACTION_REVIEW`:case`PING`:case`PM_PREPARE_WALLET_RUNTIME`:case`PM_SET_CONFIG`:case`PM_CANCEL`:case`PM_SET_TRANSACTION_VIEW`:case`PM_TRANSACTION_BROADCAST_STARTED`:return{kind:`boot`,type:e.type,request:e};case`PM_REGISTER_WALLET`:case`PM_ADD_WALLET_SIGNER`:case`PM_ADD_PASSKEY`:case`PM_ADD_EMAIL_OTP`:case`PM_REVOKE_AUTH_METHOD`:case`PM_GET_NEAR_PROVISIONING_STATE`:case`PM_SIGN_TX_WITH_ACTIONS`:case`PM_SIGN_AND_SEND_TX`:case`PM_SEND_TRANSACTION`:case`PM_SIGN_DELEGATE_ACTION`:case`PM_SIGN_NEP413`:return{kind:`near`,type:e.type,request:e};case`PM_OPEN_AUTH_MENU`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(s(e.payload),`hosted auth-menu open`)}}}case`PM_CANCEL_AUTH_MENU`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(o(e.payload),`hosted auth-menu cancellation`)}}}case`PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH`:{let t=G(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:W(m(e.payload),`hosted auth-menu external-auth resolution`)}}}case`PM_UNLOCK`:case`PM_LOCK`:case`PM_LOCK_EXACT_WALLET_SESSION`:case`PM_GET_LAST_WALLET_MOVE_REQUEST`:case`PM_MOVE_WALLET`:case`PM_GET_WALLET_MOVE`:case`PM_GET_WALLET_PLACEMENT`:case`PM_GET_WALLET_SESSION`:case`PM_GET_EXACT_WALLET_SESSION_STATE`:case`PM_GET_RECENT_UNLOCKS`:return{kind:`auth`,type:e.type,request:e};case`PM_SIGN_TEMPO`:case`PM_REPORT_TEMPO_BROADCAST_ACCEPTED`:case`PM_REPORT_TEMPO_BROADCAST_REJECTED`:case`PM_REPORT_TEMPO_FINALIZED`:case`PM_REPORT_TEMPO_DROPPED_OR_REPLACED`:case`PM_RECONCILE_TEMPO_NONCE_LANE`:return{kind:`ecdsa`,type:e.type,request:e};case`PM_REDEEM_HOSTED_WALLET_SEAMS_SESSION`:case`PM_REQUEST_EMAIL_OTP_CHALLENGE`:case`PM_BEGIN_GOOGLE_EMAIL_OTP_WALLET_AUTH`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_RESEND`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_REROLL_WALLET_ID`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_SUBMIT`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_COMPLETE_REGISTRATION`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_CANCEL`:case`PM_GET_WALLET_RECOVERY_CODE_STATUS`:case`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`:case`PM_ROTATE_WALLET_RECOVERY_CODES`:case`PM_REQUEST_WALLET_CUSTODY_EMAIL_OTP_CHALLENGE`:return{kind:`email_otp`,type:e.type,request:e};case`PM_SYNC_ACCOUNT_FLOW`:return{kind:`recovery`,type:e.type,request:e};case`PM_RESOLVE_EXACT_KEY_EXPORT_LANE`:case`PM_EXPORT_KEYPAIR_UI`:return{kind:`export`,type:e.type,request:e};case`PM_HAS_PASSKEY`:case`PM_LIST_LINKED_DEVICES`:case`PM_REVOKE_LINKED_DEVICE`:case`PM_SCAN_AND_LINK_DEVICE`:case`PM_START_DEVICE2_LINKING_FLOW`:case`PM_DEVICE_LINK_TARGET_FACTOR_ACTION`:case`PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION`:case`PM_CANCEL_DEVICE_LINKING`:return{kind:`device_link`,type:e.type,request:e};case`PM_SET_CONFIRM_BEHAVIOR`:case`PM_SET_CONFIRMATION_CONFIG`:case`PM_GET_CONFIRMATION_CONFIG`:return{kind:`preferences`,type:e.type,request:e}}return U(e)}function de(e){return e.kind!==`boot`}let K=!1;const fe=[{selector:`.seams-auth-menu-surface`,cancellationKind:`native_cancel`},{selector:`.seams-confirmation-surface`,cancellationKind:`native_cancel`},{selector:`.seams-export-surface`,cancellationKind:`wallet_iframe_cancel`},{selector:`[data-seams-wallet-recovery-backup-dialog]`,cancellationKind:`native_cancel`}];function q(e,t){let n=new Set(t),r=Object.keys(e);return r.length===t.length&&r.every(e=>n.has(e))}function pe(t){return!e(t)||!q(t,[`type`,`payload`])||t.type!==`CONNECT`||!e(t.payload)||!q(t.payload,[`protocolVersion`])?null:typeof t.payload.protocolVersion==`string`?{type:`CONNECT`,payload:{protocolVersion:t.payload.protocolVersion}}:null}function J(e){if(e===`null`)return!0;try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e}catch{return!1}}function Y(e){try{e.close()}catch{}}function me(e,t){if(t===`16.0.0`)return!1;let n={expectedProtocolVersion:l,receivedProtocolVersion:t};try{e.postMessage({type:`ERROR`,payload:{code:f,message:`Wallet iframe protocol version mismatch: expected ${l}, received ${t??`missing`}`,details:n}})}catch{}return Y(e),!0}function X(e,t){return!t||t.has(e)}function Z(e,t,n,r){e.executionGeneration===t&&n(r)}function Q(e,t,n,r){return e.executionGeneration!==t||n(r)}function $(e={}){if(K)return;K=!0,T(),(!e.supportedRuntimeRouteKinds||e.supportedRuntimeRouteKinds.has(`email_otp`))&&j().catch(()=>void 0);let r=new Set,i=new Set,o=!1,s={parentOrigin:null,port:null,configuration:{kind:`unconfigured`},executionGeneration:0,onConfigurationChanged:null},c=e=>{try{s.port?.postMessage(e)}catch{}},u=e=>{e&&r.add(e)},d=e=>!!e&&(r.has(e)||_(e)?.cancelled===!0),f=e=>{e&&r.delete(e)},p=e=>{e&&c({type:`ERROR`,requestId:e,payload:{code:`cancelled`,message:`Request cancelled`}})},m=e=>!e||!d(e)?!1:_(e)?.cancelled?!0:(p(e),f(e),!0),x=()=>{for(let e of fe){let t=document.querySelectorAll(e.selector);for(let n of t)try{e.cancellationKind===`native_cancel`?n.dispatchEvent(new Event(`cancel`,{cancelable:!0})):n.dispatchEvent(new CustomEvent(b.TX_CONFIRMER_CANCEL,{bubbles:!0,composed:!0}))}catch{}}},C=async r=>{let l=r.data;if(!l||!t(l))return;let b=l.requestId,C=s.executionGeneration,w=Z.bind(null,s,C,c),T=null;try{if(`transactionReview`in l){if(l.type!==`PM_SIGN_AND_SEND_TX`&&l.type!==`PM_SIGN_TEMPO`)throw new h(`review_invalid_input`,`Review is unsupported for this request`);let e=g(l.transactionReview);if(e.requestId!==b)throw new h(`review_invalid_input`,`Review request identity mismatch`);let t=l.payload?.options?.confirmationConfig;if(t?.uiMode!==`modal`||t.behavior!==`requireClick`)throw new h(`review_unsupported_mode`,`Review requires modal presentation and explicit approval`);T=new ie(e,l.type===`PM_SIGN_TEMPO`&&l.payload?.request.senderSignatureAlgorithm!==`secp256k1`?`credential`:`mpc`,e=>w({type:`TRANSACTION_REVIEW_STATE`,requestId:b,payload:e}),e=>w({type:`ERROR`,requestId:b,payload:{code:e instanceof h?e.code:`cancelled`,message:e.message}}))}(l.type===`PM_LOCK`||l.type===`PM_LOCK_EXACT_WALLET_SESSION`)&&v(new h(`review_identity_changed`,`The wallet session changed`));let t=ue(l);if(!de(t))switch(t.type){case`PING`:c({type:`PONG`,requestId:b});return;case`PM_PREPARE_WALLET_RUNTIME`:X(`auth`,e.supportedRuntimeRouteKinds)&&ce(),c({type:`PONG`,requestId:b});return;case`PM_SET_CONFIG`:{let e=ee(s.configuration,te(t.request.payload)),r=a(s.configuration.kind===`configured`?s.configuration.config:null)!==a(e.config);if(s.configuration=e,r){s.executionGeneration+=1;let t=e.config;t.registration.publishableKey&&t.registration.projectEnvironmentId&&n(t.network.relayer.url);for(let e of i)c({type:`ERROR`,requestId:e,payload:{code:`wallet_configuration_changed`,message:`Wallet configuration changed during request`}});i.clear()}s.onConfigurationChanged?.(),r&&(v(new h(`review_identity_changed`,`Wallet execution configuration changed`)),x()),c({type:`PONG`,requestId:b});return}case`PM_ACTIVATE_TRANSACTION_REVIEW`:{let e=y(t.request.payload);e&&_(e.requestId)?.activate(e);return}case`PM_CANCEL`:{let e=t.request.payload?.requestId,n=t.request.payload,r=n&&typeof n==`object`?Reflect.get(n,`transactionReview`):void 0;if(r!==void 0){let t=g(r),i=_(t.requestId);if(t.requestId===e&&i&&ne(t,i.metadata)){let e=new h(ae(n&&typeof n==`object`?Reflect.get(n,`reviewErrorCode`):void 0),`Reviewed request cancelled`);try{re(i.metadata.validity)}catch(t){t instanceof Error&&(e=t)}i.cancel(e)}c({type:`PONG`,requestId:b});return}let i=e?_(e):void 0;if(i){i.cancel(new h(`cancelled`,`Request cancelled`)),c({type:`PONG`,requestId:b});return}u(e),x(),e&&p(e),c({type:`PONG`,requestId:b});return}case`PM_SET_TRANSACTION_VIEW`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`requestId`):null,r=e&&typeof e==`object`?Reflect.get(e,`view`):null;typeof n==`string`&&(r===`toast`||r===`closed`)&&(await import(`./transaction-activity-Cccvec2J.js`).then(e=>e.o)).setTransactionActivityView(n,r);return}case`PM_TRANSACTION_BROADCAST_STARTED`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`signedTransaction`):null;typeof n==`string`&&(await import(`./transaction-activity-Cccvec2J.js`).then(e=>e.o)).transactionBroadcastStarted(n);return}}if(!X(t.kind,e.supportedRuntimeRouteKinds)){c({type:`ERROR`,requestId:b,payload:{code:`unsupported_request`,message:`Unsupported wallet iframe request type: ${t.type}`}});return}if(b&&i.add(b),!o&&P(t)&&await L()&&!o){if(C!==s.executionGeneration||m(b))return;w({type:`PM_RESULT`,requestId:b,payload:{ok:!0,result:F(t)}});return}o=!0;let r=await se(t);if(C!==s.executionGeneration)return;await r.handleWalletHostRuntimeRequest({transactionReview:T,state:s,executionGeneration:C,req:t.request,post:Z.bind(null,s,C,c),isCancelled:Q.bind(null,s,C,d),respondIfCancelled:Q.bind(null,s,C,m)})}catch(e){if(C!==s.executionGeneration&&l.type!==`PM_SET_CONFIG`||T?.cancelled)return;let t=await import(`./canonicalSignerErrorCode-Cz48v4oy.js`);if(C!==s.executionGeneration&&l.type!==`PM_SET_CONFIG`)return;let n=e&&typeof e==`object`&&`code`in e?e.code:void 0,r=S(e),i=t.resolveWalletBoundaryErrorCode({requestType:l.type,rawCode:n,message:r,defaultCode:`HOST_ERROR`}),a=t.resolveWalletBoundaryErrorMessage({requestType:l.type,rawCode:n,code:i,message:r}),o=t.resolveWalletBoundarySignerKind(l.type);c({type:`ERROR`,requestId:b,payload:{code:i,message:a,...t.isWalletSignerBoundaryRequestType(l.type)&&t.isCanonicalSignerSessionBoundaryCode(i)&&o?{signerKind:o}:{}}})}finally{b&&(i.delete(b),f(b)),T?.finish()}};window.addEventListener(`message`,e=>{let t=pe(e.data),n=e.ports[0];if(!(!t||!n||s.port)){if(e.source!==window.parent||!J(e.origin)){Y(n);return}if(!me(n,t.payload.protocolVersion)){typeof e.origin==`string`&&e.origin.length&&e.origin!==`null`&&(s.parentOrigin=e.origin),s.port=n;try{s.port.onmessage=C,s.port.start?.()}catch{}c({type:`READY`,payload:{protocolVersion:l}})}}})}try{$()}catch(e){console.error(`[WalletHost] init failed`,e)}export{$ as t};
@@ -1 +1 @@
1
- import{B as e,V as t}from"./domainIds-BzkGsRqO.js";import{A as n,k as r}from"./primitives-CqrjmIAH.js";import{i,r as a}from"./base64-DW79QA0h.js";import{r as o}from"./secureRandomId-LwBFx84B.js";import{B as s,F as c,G as l,I as u,R as d,dt as ee,z as f}from"./emailOtpEcdsaDerivationIdentity-Bik0N8v9.js";import{I as p,L as m,R as h}from"./ecdsaCapabilityManifest-DX6TflEz.js";import{ct as g,n as _,ut as v}from"./walletOwnershipGeneration-B6HyR2rE.js";import{t as y}from"./presignatures-K-yuzOE0.js";import{i as b,n as x,r as te,u as S}from"./trace-BBux0jtr.js";import{A as ne,C,D as re,E as ie,O as ae,S as w,T,k as E,w as oe,x as D,y as se}from"./ecdsaDerivationClientWasm-CpjnN4aK.js";import{t as O}from"./authorizationAdmission-CGinGhXH.js";import{t as k}from"./walletSessionFailure-YuhraC3P.js";import{c as ce,f as A,o as le,t as j}from"./routerAbNormalSigning-C4P2tDU-.js";import{o as M,s as ue,t as de}from"./evmCryptoWasm-DeobzyP-.js";async function fe(e){let t=e.clientShare.material;if(t.kind===`worker_loaded`)return;let n=await se({materialHandle:e.clientShare.handle.materialHandle,bindingDigest:e.clientShare.handle.bindingDigest,stateBlob:t.stateBlob,workerCtx:e.workerCtx});if(n.materialHandle!==e.clientShare.handle.materialHandle||n.bindingDigest!==e.clientShare.handle.bindingDigest)throw Error(`[multichain] ECDSA role-local worker material handle mismatch`)}async function pe(e){let t=e.signerSession,n=t.clientShare;if(n.kind===`linked_holder_worker_share`){let e=n.holderHandleId;return{signerSession:t,clientSigningMaterial:me(e),cleanupAfterSign:async()=>void 0}}let r=n;return{signerSession:t,clientSigningMaterial:{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:async t=>(await fe({workerCtx:e.workerCtx,clientShare:r}),await ae({materialHandle:r.handle.materialHandle,material:r.material.kind===`worker_loaded`?{kind:`persisted`,materialRef:r.material.materialRef}:{kind:`runtime_loaded`,expectedBindingDigest:r.handle.bindingDigest},...t})),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`role_local_derivation_handle`),computeSignatureShareFromPresignatureHandle:T},cleanupAfterSign:async()=>void 0}}async function N(e,t){return await D({holderHandleId:e,...t})}function me(e){return{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:N.bind(void 0,e),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`linked_holder_signing_material`),computeSignatureShareFromPresignatureHandle:T}}function P(e,t,n,r){let i=Math.floor(Number(e));return Number.isFinite(i)?i<n?n:i>r?r:i:t}function he(e,t){return P(e,t,1,5)}function ge(e,t,n){return P(e,t,0,n)}function _e(e){let t=e||A,n=he(t.targetDepth,A.targetDepth),r=ge(t.lowWatermark,A.lowWatermark,n);return{enabled:typeof t.enabled==`boolean`?t.enabled:A.enabled,targetDepth:n,lowWatermark:r,maxRefillInFlight:P(t.maxRefillInFlight,A.maxRefillInFlight,1,8),refillAttemptTimeoutMs:P(t.refillAttemptTimeoutMs,A.refillAttemptTimeoutMs,5e3,12e4)}}function ve(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:2e4}function ye(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||``)}function be(e){return Error(`[router-ab-ecdsa-derivation] ${e.operation} request timed out after ${e.timeoutMs}ms`)}async function xe(e){let t=ve(e.timeoutMs),r=typeof AbortController==`function`?new AbortController:null,i={...e.init},a=null,o=null,s=!1;try{let c;if(r){let l=e.init.signal;if(l){if(l.aborted)r.abort();else if(typeof l.addEventListener==`function`){let e=()=>r.abort();l.addEventListener(`abort`,e,{once:!0}),o=()=>l.removeEventListener(`abort`,e)}}a=setTimeout(()=>{s=!0,r.abort()},t),c=await n(new Request(e.url,{...i,signal:r.signal}))}else c=await Promise.race([n(new Request(e.url,i)),new Promise((n,r)=>{a=setTimeout(()=>{s=!0,r(be({operation:e.operation,timeoutMs:t}))},t)})]);let l=await c.json().catch(()=>({}));if(s)throw be({operation:e.operation,timeoutMs:t});return{response:c,data:l}}catch(n){if(s)throw be({operation:e.operation,timeoutMs:t});let r=ye(n);throw Error(r||`[router-ab-ecdsa-derivation] ${e.operation} request failed`)}finally{a&&clearTimeout(a),o?.()}}const Se=5e3;function Ce(e,t){let n=Math.min(e-Date.now(),t??Se,Se);return Number.isFinite(n)&&n>0?n:null}function we(n){return t(e(n))||null}function Te(e){let t={"Content-Type":`application/json`};switch(e.credential.kind){case`operation_step_up`:return{ok:!0,headers:t,credentials:`omit`};case`wallet_session_opaque`:{let n=String(e.credential.walletSessionToken||``).trim();return n?(Object.assign(t,r({token:n,home:e.credential.home})),{ok:!0,headers:t,credentials:`omit`}):{ok:!1,code:`invalid_args`,message:`Missing opaque Wallet Session token for Router A/B ECDSA derivation presign pool fill`}}}}function Ee(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function De(e){let t=String(e.keyHandle||``).trim();return t?{ok:!0,value:{keyHandle:t}}:{ok:!1,code:`invalid_args`,message:`Missing keyHandle for Router A/B ECDSA derivation pool-fill init`}}async function Oe(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill init`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill init`};let n=De(e);if(!n.ok)return n;let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.poolFill.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/init`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({...n.value,count:Number.isFinite(e.count)?Math.max(1,Math.floor(Number(e.count))):1,...r?{requestTag:r}:{},poolFill:e.poolFill,presignSessionId:e.presignSessionId,firstMessageB64u:e.firstMessageB64u,...Ee(e)})}});return typeof s.presignSessionId==`string`&&x(s.presignSessionId,`init`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,presignSessionId:s.presignSessionId,...Number.isSafeInteger(s.ceremonyExpiresAtMs)?{ceremonyExpiresAtMs:s.ceremonyExpiresAtMs}:{},...Number.isSafeInteger(s.materialExpiresAtMs)?{materialExpiresAtMs:s.materialExpiresAtMs}:{},stage:s.stage,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill init`)}}}async function ke(e){return Oe({...e,path:c})}async function Ae(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill step`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill step`};let n=String(e.presignSessionId||``).trim();if(!n)return{ok:!1,code:`invalid_args`,message:`Missing presignSessionId for Router A/B ECDSA derivation pool-fill step`};let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/step`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({presignSessionId:n,ceremonyExpiresAtMs:e.ceremonyExpiresAtMs,materialExpiresAtMs:e.materialExpiresAtMs,stage:e.stage,outgoingMessagesB64u:Array.isArray(e.outgoingMessagesB64u)?e.outgoingMessagesB64u:[],...r?{requestTag:r}:{},...Ee(e)})}});return x(n,`step`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,stage:s.stage,event:s.event,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.presignatureId?{presignatureId:s.presignatureId}:{},...s.bigRB64u?{bigRB64u:s.bigRB64u}:{},...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill step`)}}}async function je(e){return Ae({...e,path:u})}var Me=class{constructor(){this.state={kind:`refilling`,revision:0},this.waiters=new Map}snapshot(){return this.state}hasForegroundWaiters(){for(let e of this.waiters.values())if(e===`foreground`)return!0;return!1}publishAvailable(){this.state.kind!==`settled`&&(this.state={kind:`refilling`,revision:this.state.revision+1},this.flushWaiters())}settle(){this.state.kind!==`settled`&&(this.state={kind:`settled`,revision:this.state.revision},this.flushWaiters())}waitForChange(e,t){return this.state.kind===`settled`||this.state.revision!==e.revision?Promise.resolve(this.state):new Promise(n=>{this.waiters.set(n,t),(this.state.kind===`settled`||this.state.revision!==e.revision)&&(this.waiters.delete(n),n(this.state))})}flushWaiters(){let e=this.state,t=[...this.waiters.keys()];this.waiters.clear();for(let n of t)n(e)}};function Ne(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`WebCrypto getRandomValues is required for ECDSA rerandomization`);return e.getRandomValues(new Uint8Array(32))}function F(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function Pe(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||`signature recovery failed`)}function I(e){e instanceof Uint8Array&&e.fill(0)}function Fe(e){if(e?.kind!==`router_ab_ecdsa_derivation_client_signing_material_source_v1`)throw Error(`Router A/B ECDSA derivation client signing material source is required`)}const Ie=6e4,L=new Map,R=new Map,z=new Map,B=new Map,V=new Map,H=new Map;function Le(e){return e===`triples_done`||e===`presign`||e===`done`}function Re(e){return Le(e.clientStage)&&Le(e.serverStage)?`presign`:`triples`}function ze(e){let t=L.get(e);if(!t?.length)return null;let n=t.shift()??null;return t.length?L.set(e,t):L.delete(e),n}async function U(e){return await Ue(e),ze(e.poolKey)}function Be(e,t,n){if(!K(n))return`invalid`;let r=L.get(e)||[];for(let e of r)if(e.materialHandle===n.materialHandle)return`duplicate`;return r.filter(e=>K(e)).length>=5?`capacity_full`:(r.push(n),L.set(e,r),R.set(e,t),`stored`)}function Ve(e,t=Date.now()){let n=L.get(e);if(!n?.length)return[];let r=[],i=[];for(let e of n)K(e,t)?r.push(e):i.push(e);return r.length>0?L.set(e,r):L.delete(e),i}async function He(e){for(let t of e.refs)await e.clientSigningMaterial.destroyClientPresignature({materialHandle:t.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}async function Ue(e){await He({refs:Ve(e.poolKey),poolIdentity:e.poolIdentity,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}async function W(e,t,n){try{await _(e.walletId,e.ownershipGeneration)}catch(r){throw await qe({poolIdentity:e,poolKey:g(e),clientSigningMaterial:t,workerCtx:n}),r}}async function We(e){await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx);let t=V.get(e.poolKey);if(t){await t;return}let n=Ge(e);V.set(e.poolKey,n);try{await n}finally{V.get(e.poolKey)===n&&V.delete(e.poolKey)}}async function Ge(e){await Ue(e);let t;t=await e.clientSigningMaterial.listAvailableClientPresignatures({poolIdentity:e.poolIdentity,workerCtx:e.workerCtx});try{await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(e.poolKey)!==e.generation){for(let n of t)I(n.bigR33),await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{});return}for(let n of t){let t=Be(e.poolKey,e.poolIdentity,{presignatureId:n.presignatureId,materialHandle:n.materialHandle,bigRB64u:i(n.bigR33),createdAtMs:n.createdAtMs,expiresAtMs:n.expiresAtMs});I(n.bigR33),(t===`invalid`||t===`capacity_full`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}}function G(e){let t=L.get(e);return t?t.reduce((e,t)=>e+(K(t)?1:0),0):0}function K(e,t=Date.now()){let n=Math.floor(Number(e.expiresAtMs));return!!(e.presignatureId&&e.bigRB64u&&e.materialHandle)&&Number.isSafeInteger(n)&&n>t+2e3}function q(e){let t=H.get(e);return t===void 0?(H.set(e,0),0):t}function Ke(e){Z(e);let t=q(e)+1;return H.set(e,t),t}async function qe(e){let t=L.get(e.poolKey)??[];$e(e.poolKey),await He({...e,refs:t})}function J(e){return B.get(e)||0}function Je(e){let t=J(e);B.set(e,t+1)}function Ye(e){let t=J(e);if(t<=1){B.delete(e),Q(e,0);return}B.set(e,t-1)}async function Xe(e,t){let n=z.get(e);if(!n)return;let r=n.snapshot();for(;G(e)===0&&r.kind===`refilling`;)r=await n.waitForChange(r,t)}async function Ze(e){let t=g(v({ownershipGeneration:e.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.scope,materialActivation:e.materialActivation}));return G(t)>0?!0:(await Xe(t,`background`),G(t)>0)}function Y(e,t,n){return{scheduled:!1,reason:e,depth:t,targetDepth:n}}function Qe(){let e=new Set([...X.keys(),...L.keys(),...z.keys(),...B.keys(),...H.keys()]);for(let t of e)Ke(t);L.clear(),R.clear();for(let e of z.values())e.settle();z.clear(),B.clear()}function $e(e){L.delete(e),R.delete(e),Ke(e),z.get(e)?.settle(),z.delete(e)}function et(e){let t=String(e).trim();if(!t)throw Error(`ECDSA presignature wallet id is required`);for(let[e,n]of[...R])n.walletId===t&&$e(e)}const X=new Map;function Z(e){let t=X.get(e);t&&t.timer!==null&&clearTimeout(t.timer),X.delete(e),X.size===0&&typeof window<`u`&&(window.removeEventListener(`online`,$),document.removeEventListener(`visibilitychange`,$))}function Q(e,t){let n=X.get(e);if(!n)return;n.timer!==null&&clearTimeout(n.timer);let r=n.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs-Date.now();if(r<=0||q(e)!==n.generation){Z(e);return}n.timer=setTimeout(tt,Math.min(t,r),e)}function $(){if(!(typeof document<`u`&&document.visibilityState===`hidden`))for(let e of X.keys())Q(e,0)}function tt(e){let t=X.get(e);if(!t)return;if(t.timer=null,Date.now()>=t.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs){Z(e);return}if(typeof navigator<`u`&&navigator.onLine===!1){Q(e,3e4);return}let n=at(t.input);n.scheduled||Q(e,n.depth>=n.targetDepth?3e4:5e3)}function nt(e,t){t.authorization.kind===`reusable_wallet_session`&&X.get(e)?.input!==t&&(Z(e),X.size===0&&typeof window<`u`&&(window.addEventListener(`online`,$),document.addEventListener(`visibilitychange`,$)),X.set(e,{input:t,generation:q(e),failures:0,timer:null}),Q(e,3e4))}function rt(e,t,n){let r=X.get(e);if(!(!r||r!==t)){switch(n){case`network_error`:case`internal`:case`presign_timeout`:case`temporarily_unavailable`:case`service_unavailable`:case`wallet_session_unavailable`:if(r.failures+=1,r.failures<=3)return}Z(e)}}async function it(e){let{args:t,refillInput:n,poolKey:r,poolIdentity:i,scheduledGeneration:a,targetDepth:o,refillAttemptTimeoutMs:s,progress:c}=e,l=X.get(r)??null;try{for(await We({poolKey:r,poolIdentity:i,clientSigningMaterial:t.clientSigningMaterial,workerCtx:t.workerCtx,generation:a}),G(r)>0&&c.publishAvailable();Date.now()<t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs;){if(q(r)!==a||(X.get(r)??null)!==l||G(r)>=o||J(r)>0||typeof navigator<`u`&&navigator.onLine===!1)return;let e=Math.min(Date.now()+s,t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs),i=await _t({...n,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:n.routerAbEcdsaDerivationPoolFill.scope,ceremonyExpiresAtMs:e,materialExpiresAtMs:n.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs},trafficClass:`background`});if(S(`evm-family`,{event:`ecdsa_background_refill_result`,authorization:t.authorization.kind,outcome:i.ok?`available`:`failed`,code:i.ok?null:i.code,depth:G(r),targetDepth:o}),!i.ok){rt(r,l,i.code);return}let u=X.get(r);u&&u===l&&(u.failures=0),c.publishAvailable()}}catch{rt(r,l,`internal`)}finally{c.settle(),z.get(r)===c&&z.delete(r);let e=X.get(r);if(e){let t=e.failures>0?2e3*2**e.failures:1e3;G(r)>=o&&(t=3e4),e!==l&&(t=0),Q(r,t)}}}function at(e){try{let t=_e(e.poolPolicy),n=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),r=g(n);R.set(r,n);let i=he(e.targetDepth,t.targetDepth),a=ge(e.triggerIfDepthAtOrBelow,t.lowWatermark,i),o=G(r),s=q(r);if(!t.enabled)return Y(`disabled`,o,i);if(e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs<=Date.now())return Z(r),Y(`invalid_args`,o,i);if(nt(r,e),o>a)return Y(`depth_above_trigger`,o,i);if(o>=i)return Y(`depth_at_or_above_target`,o,i);if(z.has(r)||J(r)>0)return Y(`in_flight_for_pool_key`,o,i);if(z.size>=t.maxRefillInFlight)return Y(`global_in_flight_limit`,o,i);let c={relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,clientVerifyingShareB64u:e.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)},l=new Me;return z.set(r,l),it({args:e,refillInput:c,poolKey:r,poolIdentity:n,scheduledGeneration:s,targetDepth:i,refillAttemptTimeoutMs:t.refillAttemptTimeoutMs,progress:l}),{scheduled:!0,reason:`scheduled`,depth:o,targetDepth:i}}catch{return Y(`invalid_args`,0,0)}}function ot(e){return e.map(e=>i(e))}function st(e){return Array.isArray(e)?e.map(e=>String(e||``).trim()).filter(e=>!!e).map(e=>a(e)):[]}async function ct(e){let t=String(e.thresholdEcdsaPublicKeyB64u||``).trim();if(t){let n=a(t);if(n.length!==33)throw Error(`thresholdEcdsaPublicKeyB64u must decode to 33 bytes`);return await M({publicKey33:n,workerCtx:e.workerCtx})}let n=String(e.clientVerifyingShareB64u||``).trim(),r=String(e.relayerVerifyingShareB64u||``).trim();if(!n||!r)throw Error(`Missing thresholdEcdsaPublicKeyB64u (or relayerVerifyingShareB64u fallback) for Router A/B ECDSA derivation signing`);let i=a(n),o=a(r);if(i.length!==33)throw Error(`clientVerifyingShareB64u must decode to 33 bytes`);if(o.length!==33)throw Error(`relayerVerifyingShareB64u must decode to 33 bytes`);return await de({left33:await M({publicKey33:i,workerCtx:e.workerCtx}),right33:await M({publicKey33:o,workerCtx:e.workerCtx}),workerCtx:e.workerCtx})}function lt(e){return e.trafficClass===`foreground`||z.get(e.poolKey)?.hasForegroundWaiters()?`foreground_presign_pool_refill`:`background_presign_pool_refill`}async function ut(e){for(let t=0;t<2;t+=1){let n=await dt(e);if(n.ok||!ft(n)||t===1)return n}return{ok:!1,code:`stale_session_state`,message:`Router A/B ECDSA derivation pool-fill session stayed stale after retry`}}async function dt(e){Fe(e.clientSigningMaterial);let t=performance.now(),n=e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs,r=e.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs,a=`ecdsa-presign-v2:${n}:${i(crypto.getRandomValues(new Uint8Array(32)))}`,o=a,s=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),c=null,l=null,u=null,d=null,ee=!1,f=`triples`,p=[],m=!0,h=!1;try{let t=await e.clientSigningMaterial.initClientPresignSession({sessionId:o,groupPublicKey33:e.groupPublicKey33,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,poolIdentity:s,workerCtx:e.workerCtx});if(t.stage!==`triples`||t.outgoingMessages.length!==1)return{ok:!1,code:`presign_init_failed`,message:`Client presign init must emit exactly one first message`};f=t.stage;let g=await ke({relayerUrl:e.relayerUrl,...e.poolFillInitKeySelector,count:1,presignSessionId:a,firstMessageB64u:i(t.outgoingMessages[0]),credential:e.credential,requestTag:lt(e),poolFill:e.routerAbEcdsaDerivationPoolFill,...F(e)});if(!g.ok)return{ok:!1,code:g.code||`presign_init_failed`,message:g.message||`Presign initialization failed`};if(g.presignSessionId!==a||g.ceremonyExpiresAtMs!==n||g.materialExpiresAtMs!==r||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Presign initialization changed the bound identity or deadlines`};let _=g.stage||`triples`,v=st(g.outgoingMessagesB64u);for(let t=0;t<64;t++){if(v.length>0&&!c){let t=await e.clientSigningMaterial.stepClientPresignSession({sessionId:o,stage:Re({clientStage:f,serverStage:_}),incomingMessages:v,workerCtx:e.workerCtx});f=t.stage,v=[],p.push(...t.outgoingMessages),t.presignatureHandle&&t.presignatureBigR33&&(c=t.presignatureHandle,l=t.presignatureBigR33)}if(!ee){let i=performance.now(),o=lt(e),s={relayerUrl:e.relayerUrl,presignSessionId:a,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,stage:Re({clientStage:f,serverStage:_}),outgoingMessagesB64u:ot(p),credential:e.credential,requestTag:o,...F(e)},c=await je(s);if(S(`evm-family`,{event:`ecdsa_presignature_round`,requestTag:o,presignSessionId:a,authorization:e.authorization.kind,round:t,stage:s.stage,durationMs:performance.now()-i,outcome:c.ok?`succeeded`:`failed`}),p=[],!c.ok)return{ok:!1,code:c.code||`presign_step_failed`,message:c.message||`Router A/B ECDSA derivation pool-fill step failed`};v=st(c.outgoingMessagesB64u),_=c.stage||_,c.event===`presign_done`&&(u=String(c.presignatureId||``).trim()||null,d=String(c.bigRB64u||``).trim()||null,ee=!0)}if(c&&l&&u&&d)break}if(!c||!l)return{ok:!1,code:`presign_timeout`,message:`Client presign session did not reach done state`};if(!u||!d)return{ok:!1,code:`presign_timeout`,message:`Server presign session did not reach done state`};if(l.length!==33)return{ok:!1,code:`internal`,message:`Invalid local presignature bigR bytes (expected 33, got ${l.length})`};try{let t=Date.now(),n=i(l);if(n!==d)return{ok:!1,code:`presign_mismatch`,message:`Client/server presignature mismatch (bigR mismatch)`};let a=await e.clientSigningMaterial.admitClientPresignature({materialHandle:c,expectedPresignatureId:u,poolIdentity:s,admissionMode:e.authorization.kind===`operation_step_up`?`resident`:`durable`,workerCtx:e.workerCtx});return a.kind===`discarded_capacity`?{ok:!1,code:`pool_full`,message:`Router A/B ECDSA derivation client presignature pool is full`}:a.kind===`discarded_ambiguous`?{ok:!1,code:`presign_failed`,message:`Router A/B ECDSA derivation client presignature admission was ambiguous`}:(h=!0,m=!1,{ok:!0,kind:`available`,presignature:{presignatureId:u,bigRB64u:n,materialHandle:c,createdAtMs:t,expiresAtMs:r}})}finally{I(l)}}catch(e){return{ok:!1,code:`presign_failed`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation pool-fill handshake failed`)}}finally{S(`evm-family`,{event:`ecdsa_presignature_generation`,requestTag:lt(e),presignSessionId:a,authorization:e.authorization.kind,durationMs:performance.now()-t,outcome:h?`available`:`failed`}),I(l),!h&&c&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:c,poolIdentity:s,workerCtx:e.workerCtx}).catch(()=>{}),m&&await e.clientSigningMaterial.abortClientPresignSession({sessionId:o,workerCtx:e.workerCtx}).catch(()=>{})}}function ft(e){return e.code===`stale_session_state`||e.code===`stale_pool_fill_session`}function pt(e){let t=l(e);return{ecdsaThresholdKeyId:p(t.ecdsa_threshold_key_id),clientVerifyingShareB64u:h(t.public_identity.derivation_client_share_public_key33_b64u),thresholdEcdsaPublicKeyB64u:t.public_identity.threshold_public_key33_b64u}}function mt(e){let t=Math.floor(Number(e.materialExpiresAtMs)),n=Number.isSafeInteger(e.authorizationExpiresAtMs)?Math.floor(Number(e.authorizationExpiresAtMs)):e.nowMs+Ie,r=Math.min(t,n,e.nowMs+Ie);return Number.isSafeInteger(r)&&r>e.nowMs?r:null}async function ht(e,t,n){let r=null,c=null,l=null,u=null,d=null,p={kind:`unclaimed`},m=null,h={kind:`before_prepare`};try{let _=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!_)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation signing`};let y=pt(e.scope);if(!y.ecdsaThresholdKeyId)return{ok:!1,code:`invalid_args`,message:`Missing ecdsaThresholdKeyId for Router A/B ECDSA derivation signing`};let x=y.clientVerifyingShareB64u;if(!x)return{ok:!1,code:`invalid_args`,message:`Missing clientVerifyingShareB64u for Router A/B ECDSA derivation signing`};if(!(e.signingDigest32 instanceof Uint8Array)||e.signingDigest32.length!==32)return{ok:!1,code:`invalid_args`,message:`signingDigest32 must be 32 bytes for Router A/B ECDSA derivation signing`};let ne=performance.now(),C=await ct({clientVerifyingShareB64u:x,thresholdEcdsaPublicKeyB64u:y.thresholdEcdsaPublicKeyB64u,workerCtx:e.workerCtx});b(e.operationId,`public_key_validation`,ne),c=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:_,scope:e.scope,materialActivation:e.materialActivation}),await W(c,e.clientSigningMaterial,e.workerCtx),r=g(c),R.set(r,c),m=q(r);let re=performance.now();if(l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`pool_lookup`,re),!l){let t=performance.now();await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:m}),b(e.operationId,`pool_restore`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l){let t=performance.now();await Xe(r,`foreground`),b(e.operationId,`refill_wait`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l&&n.kind===`on_demand`){let t=performance.now();Je(r);try{let t=await _t({...n.refill,trafficClass:`foreground`});if(!t.ok&&t.code===`invalidated`&&(t=await _t({...n.refill,trafficClass:`foreground`})),!t.ok&&t.code!==`pool_full`)return t;!t.ok&&t.code===`pool_full`&&await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:q(r)})}finally{Ye(r)}m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`foreground_refill`,t)}if(S(`evm-family`,{event:`ecdsa_presignature_selection`,operationId:e.operationId,authorization:e.authorization.kind,outcome:l?`available`:`empty`,remainingDepth:G(r),attempt:t}),!l)return{ok:!1,code:`pool_empty`,message:`Router A/B ECDSA derivation client presignature pool is empty`};let ie=Date.now(),ae=mt({authorizationExpiresAtMs:e.expiresAtMs,materialExpiresAtMs:l.expiresAtMs,nowMs:ie});if(!ae)return{ok:!1,code:`pool_entry_expired`,message:`Router A/B ECDSA derivation client presignature is expired`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};d=Ne();let w=await ee(d),T=s({scope:e.scope,requestId:o(`router-ab-ecdsa-sign`,32,`Router A/B ECDSA derivation sign request`),operationId:e.operationId,operationDigests:e.operationDigests,authorization:e.authorization,materialActivation:e.materialActivation,clientPresignatureId:l.presignatureId,expiresAtMs:ae,signingDigest32:e.signingDigest32,clientRerandomizationCommitment32:w});I(w);let E=o(`router-ab-ecdsa-reservation`,32,`Router A/B ECDSA Client presignature reservation`);p={kind:`destroy`};let oe=performance.now(),D=await e.clientSigningMaterial.reserveClientPresignature({materialHandle:l.materialHandle,expectedPresignatureId:l.presignatureId,poolIdentity:c,requestBinding:T.request_id,reservationId:E,leaseExpiresAtMs:T.expires_at_ms,workerCtx:e.workerCtx});if(b(e.operationId,`presignature_reserve`,oe),D.kind===`unavailable`)return D.reason===`claimed_elsewhere`&&(p={kind:`owned_elsewhere`}),t<4?await ht(e,t+1,n):{ok:!1,code:D.reason===`expired`?`pool_entry_expired`:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature is unavailable: ${D.reason}`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};Q(r,0),h={kind:`prepare_submitted`};let se=performance.now(),O=await ce({relayServerUrl:_,credential:e.credential,request:T,onServerTiming:te.bind(void 0,e.operationId,`prepare`)});if(b(e.operationId,`prepare`,se),O.kind===`reusable_wallet_session`){if(!e.reconcileSession)throw Error(`Wallet Session reconciliation is required`);await e.reconcileSession(O.sessionStatus)}let k=O.signing;if(k.server_big_r33_b64u!==l.bigRB64u)return{ok:!1,code:`presign_mismatch`,message:`Router A/B ECDSA derivation SigningWorker returned a different presignature bigR`};let A=performance.now();await e.clientSigningMaterial.commitClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,workerCtx:e.workerCtx}),b(e.operationId,`presignature_commit`,A);let j=a(l.bigRB64u),M=a(k.signing_worker_rerandomization_contribution32_b64u);try{if(j.length!==33)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation presign bigR must decode to 33 bytes`};if(M.length!==32)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation SigningWorker rerandomization contribution must decode to 32 bytes`};let t=performance.now();u=await e.clientSigningMaterial.computeSignatureShareFromPresignatureHandle({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,groupPublicKey33:C,expectedPresignBigR33:j,digest32:e.signingDigest32,clientRerandomizationContribution32:d,signingWorkerRerandomizationContribution32:M,workerCtx:e.workerCtx}),b(e.operationId,`client_share`,t),p={kind:`consumed`}}finally{I(j),I(M)}if(u.length!==32)return{ok:!1,code:`internal`,message:`Invalid Router A/B ECDSA derivation client signature share length (expected 32, got ${u.length})`};let de=f({scope:e.scope,requestId:T.request_id,operationId:T.operation_id,operationDigests:T.operation_digests,authorization:e.authorization,materialActivation:e.materialActivation,expiresAtMs:T.expires_at_ms,signingDigest32:e.signingDigest32,serverPresignatureId:k.server_presignature_id,clientSignatureShare32:u,clientRerandomizationContribution32:d}),fe=performance.now(),pe=await le({relayServerUrl:_,credential:e.credential,request:de,onServerTiming:te.bind(void 0,e.operationId,`finalize`)});b(e.operationId,`finalize`,fe);let N=a(pe.signature65_b64u);if(N.length!==65)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned invalid signature length (expected 65, got ${N.length})`};try{let t=performance.now();await ue({digest32:e.signingDigest32,signature65:N,publicKey33:C,workerCtx:e.workerCtx}),b(e.operationId,`signature_verify`,t)}catch(e){return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned a signature that does not recover to the threshold group public key: ${Pe(e)}`}}return{ok:!0,signature65:N,signature65B64u:pe.signature65_b64u,rB64u:i(N.slice(0,32)),sB64u:i(N.slice(32,64)),recId:N[64]}}catch(t){if(t instanceof O||t instanceof k)throw t;let n=String(t&&typeof t==`object`&&`message`in t?t.message:t||`Router A/B ECDSA derivation signing failed`);return t instanceof j&&t.code===`expired_local_request`?{ok:!1,code:`pool_entry_expired`,message:n}:r&&c&&m!==null&&h.kind===`before_prepare`&&q(r)!==m?(await qe({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`}):{ok:!1,code:`router_ab_sign_failed`,message:n}}finally{if(I(u),I(d),l&&c&&p.kind!==`consumed`&&p.kind!==`owned_elsewhere`){let t=!1;if(p.kind===`unclaimed`&&r&&m!==null&&m===q(r)){let e=Be(r,c,l);t=e===`stored`||e===`duplicate`}t||await e.clientSigningMaterial.destroyClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,workerCtx:e.workerCtx}).catch(()=>{})}r&&Q(r,0)}}async function gt(e){let t=pt(e.scope),n=Math.floor(Number(e.expiresAtMs));if(!Number.isSafeInteger(n)||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Router A/B ECDSA derivation pool fill expiry is unavailable or expired`};let r={kind:`on_demand`,refill:{relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,clientVerifyingShareB64u:t.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:e.scope,ceremonyExpiresAtMs:Math.min(n,Date.now()+d-3e4),materialExpiresAtMs:e.authorization.kind===`operation_step_up`?n:Date.now()+y},workerCtx:e.workerCtx,...F(e)}},i=await ht(e,0,r);return!i.ok&&(i.code===`pool_entry_expired`||i.code===`pool_entry_unavailable`)?await ht(e,0,r):i}async function _t(e){try{let t=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation});await W(t,e.clientSigningMaterial,e.workerCtx);let n=g(t);await Ue({poolKey:n,poolIdentity:t,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx});let r=q(n),i=await ct({clientVerifyingShareB64u:e.clientVerifyingShareB64u,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,workerCtx:e.workerCtx}),a=await ut({relayerUrl:e.relayerUrl,poolFillInitKeySelector:{keyHandle:m(e.keyHandle)},clientSigningMaterial:e.clientSigningMaterial,groupPublicKey33:i,materialActivation:e.materialActivation,credential:e.credential,poolKey:n,trafficClass:e.trafficClass,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)});if(!a.ok)return a;try{await W(t,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(n)!==r)return await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!1,code:`invalidated`,message:`Router A/B ECDSA derivation presignature pool invalidated`};let o=Be(n,t,a.presignature);return(o===`capacity_full`||o===`invalid`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!0,presignatureId:a.presignature.presignatureId}}catch(e){return{ok:!1,code:`internal`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation presignature refill failed`)}}}export{Ze as a,pe as c,gt as i,et as n,_e as o,at as r,me as s,Qe as t};
1
+ import{B as e,V as t}from"./domainIds-BzkGsRqO.js";import{A as n,k as r}from"./primitives-CqrjmIAH.js";import{i,r as a}from"./base64-DW79QA0h.js";import{r as o}from"./secureRandomId-LwBFx84B.js";import{B as s,F as c,G as l,I as u,R as d,dt as ee,z as f}from"./emailOtpEcdsaDerivationIdentity-Bik0N8v9.js";import{I as p,L as m,R as h}from"./ecdsaCapabilityManifest-DX6TflEz.js";import{ct as g,n as _,ut as v}from"./walletOwnershipGeneration-B6HyR2rE.js";import{t as y}from"./presignatures-K-yuzOE0.js";import{i as b,n as x,r as te,u as S}from"./trace-BBux0jtr.js";import{A as ne,C,D as re,E as ie,O as ae,S as w,T,k as E,w as oe,x as D,y as se}from"./ecdsaDerivationClientWasm-CpjnN4aK.js";import{t as O}from"./authorizationAdmission-CGinGhXH.js";import{t as k}from"./walletSessionFailure-YuhraC3P.js";import{c as ce,f as A,o as le,t as j}from"./routerAbNormalSigning-C4P2tDU-.js";import{o as M,s as ue,t as de}from"./evmCryptoWasm-DeobzyP-.js";async function fe(e){let t=e.clientShare.material;if(t.kind===`worker_loaded`)return;let n=await se({materialHandle:e.clientShare.handle.materialHandle,bindingDigest:e.clientShare.handle.bindingDigest,stateBlob:t.stateBlob,workerCtx:e.workerCtx});if(n.materialHandle!==e.clientShare.handle.materialHandle||n.bindingDigest!==e.clientShare.handle.bindingDigest)throw Error(`[multichain] ECDSA role-local worker material handle mismatch`)}async function pe(e){let t=e.signerSession,n=t.clientShare;if(n.kind===`linked_holder_worker_share`){let e=n.holderHandleId;return{signerSession:t,clientSigningMaterial:me(e),cleanupAfterSign:async()=>void 0}}let r=n;return{signerSession:t,clientSigningMaterial:{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:async t=>(await fe({workerCtx:e.workerCtx,clientShare:r}),await ae({materialHandle:r.handle.materialHandle,material:r.material.kind===`worker_loaded`?{kind:`persisted`,materialRef:r.material.materialRef}:{kind:`runtime_loaded`,expectedBindingDigest:r.handle.bindingDigest},...t})),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`role_local_derivation_handle`),computeSignatureShareFromPresignatureHandle:T},cleanupAfterSign:async()=>void 0}}async function N(e,t){return await D({holderHandleId:e,...t})}function me(e){return{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:N.bind(void 0,e),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`linked_holder_signing_material`),computeSignatureShareFromPresignatureHandle:T}}function P(e,t,n,r){let i=Math.floor(Number(e));return Number.isFinite(i)?i<n?n:i>r?r:i:t}function he(e,t){return P(e,t,1,5)}function ge(e,t,n){return P(e,t,0,n)}function _e(e){let t=e||A,n=he(t.targetDepth,A.targetDepth),r=ge(t.lowWatermark,A.lowWatermark,n);return{enabled:typeof t.enabled==`boolean`?t.enabled:A.enabled,targetDepth:n,lowWatermark:r,maxRefillInFlight:P(t.maxRefillInFlight,A.maxRefillInFlight,1,8),refillAttemptTimeoutMs:P(t.refillAttemptTimeoutMs,A.refillAttemptTimeoutMs,5e3,12e4)}}function ve(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:2e4}function ye(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||``)}function be(e){return Error(`[router-ab-ecdsa-derivation] ${e.operation} request timed out after ${e.timeoutMs}ms`)}async function xe(e){let t=ve(e.timeoutMs),r=typeof AbortController==`function`?new AbortController:null,i={...e.init},a=null,o=null,s=!1;try{let c;if(r){let l=e.init.signal;if(l){if(l.aborted)r.abort();else if(typeof l.addEventListener==`function`){let e=()=>r.abort();l.addEventListener(`abort`,e,{once:!0}),o=()=>l.removeEventListener(`abort`,e)}}a=setTimeout(()=>{s=!0,r.abort()},t),c=await n(new Request(e.url,{...i,signal:r.signal}))}else c=await Promise.race([n(new Request(e.url,i)),new Promise((n,r)=>{a=setTimeout(()=>{s=!0,r(be({operation:e.operation,timeoutMs:t}))},t)})]);let l=await c.json().catch(()=>({}));if(s)throw be({operation:e.operation,timeoutMs:t});return{response:c,data:l}}catch(n){if(s)throw be({operation:e.operation,timeoutMs:t});let r=ye(n);throw Error(r||`[router-ab-ecdsa-derivation] ${e.operation} request failed`)}finally{a&&clearTimeout(a),o?.()}}const Se=5e3;function Ce(e,t){let n=Math.min(e-Date.now(),t??Se,Se);return Number.isFinite(n)&&n>0?n:null}function we(n){return t(e(n))||null}function Te(e){let t={"Content-Type":`application/json`};switch(e.credential.kind){case`operation_step_up`:return{ok:!0,headers:t,credentials:`omit`};case`wallet_session_opaque`:{let n=String(e.credential.walletSessionToken||``).trim();return n?(Object.assign(t,r({token:n,home:e.credential.home})),{ok:!0,headers:t,credentials:`omit`}):{ok:!1,code:`invalid_args`,message:`Missing opaque Wallet Session token for Router A/B ECDSA derivation presign pool fill`}}}}function Ee(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function De(e){let t=String(e.keyHandle||``).trim();return t?{ok:!0,value:{keyHandle:t}}:{ok:!1,code:`invalid_args`,message:`Missing keyHandle for Router A/B ECDSA derivation pool-fill init`}}async function Oe(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill init`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill init`};let n=De(e);if(!n.ok)return n;let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.poolFill.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/init`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({...n.value,count:Number.isFinite(e.count)?Math.max(1,Math.floor(Number(e.count))):1,...r?{requestTag:r}:{},poolFill:e.poolFill,presignSessionId:e.presignSessionId,firstMessageB64u:e.firstMessageB64u,...Ee(e)})}});return typeof s.presignSessionId==`string`&&x(s.presignSessionId,`init`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,presignSessionId:s.presignSessionId,...Number.isSafeInteger(s.ceremonyExpiresAtMs)?{ceremonyExpiresAtMs:s.ceremonyExpiresAtMs}:{},...Number.isSafeInteger(s.materialExpiresAtMs)?{materialExpiresAtMs:s.materialExpiresAtMs}:{},stage:s.stage,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill init`)}}}async function ke(e){return Oe({...e,path:c})}async function Ae(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill step`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill step`};let n=String(e.presignSessionId||``).trim();if(!n)return{ok:!1,code:`invalid_args`,message:`Missing presignSessionId for Router A/B ECDSA derivation pool-fill step`};let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/step`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({presignSessionId:n,ceremonyExpiresAtMs:e.ceremonyExpiresAtMs,materialExpiresAtMs:e.materialExpiresAtMs,stage:e.stage,outgoingMessagesB64u:Array.isArray(e.outgoingMessagesB64u)?e.outgoingMessagesB64u:[],...r?{requestTag:r}:{},...Ee(e)})}});return x(n,`step`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,stage:s.stage,event:s.event,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.presignatureId?{presignatureId:s.presignatureId}:{},...s.bigRB64u?{bigRB64u:s.bigRB64u}:{},...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill step`)}}}async function je(e){return Ae({...e,path:u})}var Me=class{constructor(){this.state={kind:`refilling`,revision:0},this.waiters=new Map}snapshot(){return this.state}hasForegroundWaiters(){for(let e of this.waiters.values())if(e===`foreground`)return!0;return!1}publishAvailable(){this.state.kind!==`settled`&&(this.state={kind:`refilling`,revision:this.state.revision+1},this.flushWaiters())}settle(){this.state.kind!==`settled`&&(this.state={kind:`settled`,revision:this.state.revision},this.flushWaiters())}waitForChange(e,t){return this.state.kind===`settled`||this.state.revision!==e.revision?Promise.resolve(this.state):new Promise(n=>{this.waiters.set(n,t),(this.state.kind===`settled`||this.state.revision!==e.revision)&&(this.waiters.delete(n),n(this.state))})}flushWaiters(){let e=this.state,t=[...this.waiters.keys()];this.waiters.clear();for(let n of t)n(e)}};function Ne(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`WebCrypto getRandomValues is required for ECDSA rerandomization`);return e.getRandomValues(new Uint8Array(32))}function F(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function Pe(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||`signature recovery failed`)}function I(e){e instanceof Uint8Array&&e.fill(0)}function Fe(e){if(e?.kind!==`router_ab_ecdsa_derivation_client_signing_material_source_v1`)throw Error(`Router A/B ECDSA derivation client signing material source is required`)}const Ie=6e4,L=new Map,R=new Map,z=new Map,B=new Map,V=new Map,H=new Map;function Le(e){return e===`triples_done`||e===`presign`||e===`done`}function Re(e){return Le(e.clientStage)&&Le(e.serverStage)?`presign`:`triples`}function ze(e){let t=L.get(e);if(!t?.length)return null;let n=t.shift()??null;return t.length?L.set(e,t):L.delete(e),n}async function U(e){return await Ue(e),ze(e.poolKey)}function Be(e,t,n){if(!K(n))return`invalid`;let r=L.get(e)||[];for(let e of r)if(e.materialHandle===n.materialHandle)return`duplicate`;return r.filter(e=>K(e)).length>=5?`capacity_full`:(r.push(n),L.set(e,r),R.set(e,t),`stored`)}function Ve(e,t=Date.now()){let n=L.get(e);if(!n?.length)return[];let r=[],i=[];for(let e of n)K(e,t)?r.push(e):i.push(e);return r.length>0?L.set(e,r):L.delete(e),i}async function He(e){for(let t of e.refs)await e.clientSigningMaterial.destroyClientPresignature({materialHandle:t.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}async function Ue(e){await He({refs:Ve(e.poolKey),poolIdentity:e.poolIdentity,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}async function W(e,t,n){try{await _(e.walletId,e.ownershipGeneration)}catch(r){throw await qe({poolIdentity:e,poolKey:g(e),clientSigningMaterial:t,workerCtx:n}),r}}async function We(e){await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx);let t=V.get(e.poolKey);if(t){await t;return}let n=Ge(e);V.set(e.poolKey,n);try{await n}finally{V.get(e.poolKey)===n&&V.delete(e.poolKey)}}async function Ge(e){await Ue(e);let t;t=await e.clientSigningMaterial.listAvailableClientPresignatures({poolIdentity:e.poolIdentity,workerCtx:e.workerCtx});try{await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(e.poolKey)!==e.generation){for(let n of t)I(n.bigR33),await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{});return}for(let n of t){let t=Be(e.poolKey,e.poolIdentity,{presignatureId:n.presignatureId,materialHandle:n.materialHandle,bigRB64u:i(n.bigR33),createdAtMs:n.createdAtMs,expiresAtMs:n.expiresAtMs});I(n.bigR33),(t===`invalid`||t===`capacity_full`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}}function G(e){let t=L.get(e);return t?t.reduce((e,t)=>e+(K(t)?1:0),0):0}function K(e,t=Date.now()){let n=Math.floor(Number(e.expiresAtMs));return!!(e.presignatureId&&e.bigRB64u&&e.materialHandle)&&Number.isSafeInteger(n)&&n>t+2e3}function q(e){let t=H.get(e);return t===void 0?(H.set(e,0),0):t}function Ke(e){Z(e);let t=q(e)+1;return H.set(e,t),t}async function qe(e){let t=L.get(e.poolKey)??[];$e(e.poolKey),await He({...e,refs:t})}function J(e){return B.get(e)||0}function Je(e){let t=J(e);B.set(e,t+1)}function Ye(e){let t=J(e);if(t<=1){B.delete(e),Q(e,0);return}B.set(e,t-1)}async function Xe(e,t){let n=z.get(e);if(!n)return;let r=n.snapshot();for(;G(e)===0&&r.kind===`refilling`;)r=await n.waitForChange(r,t)}async function Ze(e){let t=g(v({ownershipGeneration:e.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.scope,materialActivation:e.materialActivation}));return G(t)>0?!0:(await Xe(t,`background`),G(t)>0)}function Y(e,t,n){return{scheduled:!1,reason:e,depth:t,targetDepth:n}}function Qe(){let e=new Set([...X.keys(),...L.keys(),...z.keys(),...B.keys(),...H.keys()]);for(let t of e)Ke(t);L.clear(),R.clear();for(let e of z.values())e.settle();z.clear(),B.clear()}function $e(e){L.delete(e),R.delete(e),Ke(e),z.get(e)?.settle(),z.delete(e)}function et(e){let t=String(e).trim();if(!t)throw Error(`ECDSA presignature wallet id is required`);for(let[e,n]of[...R])n.walletId===t&&$e(e)}const X=new Map;function Z(e){let t=X.get(e);t&&t.timer!==null&&clearTimeout(t.timer),X.delete(e),X.size===0&&typeof window<`u`&&(window.removeEventListener(`online`,$),document.removeEventListener(`visibilitychange`,$))}function Q(e,t){let n=X.get(e);if(!n)return;n.timer!==null&&clearTimeout(n.timer);let r=n.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs-Date.now();if(r<=0||q(e)!==n.generation){Z(e);return}n.timer=setTimeout(tt,Math.min(t,r),e)}function $(){if(!(typeof document<`u`&&document.visibilityState===`hidden`))for(let e of X.keys())Q(e,0)}function tt(e){let t=X.get(e);if(!t)return;if(t.timer=null,Date.now()>=t.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs){Z(e);return}if(typeof navigator<`u`&&navigator.onLine===!1){Q(e,3e4);return}let n=at(t.input);n.scheduled||Q(e,n.depth>=n.targetDepth?3e4:5e3)}function nt(e,t){t.authorization.kind===`reusable_wallet_session`&&X.get(e)?.input!==t&&(Z(e),X.size===0&&typeof window<`u`&&(window.addEventListener(`online`,$),document.addEventListener(`visibilitychange`,$)),X.set(e,{input:t,generation:q(e),failures:0,timer:null}),Q(e,3e4))}function rt(e,t,n){let r=X.get(e);if(!(!r||r!==t)){switch(n){case`network_error`:case`internal`:case`presign_timeout`:case`temporarily_unavailable`:case`service_unavailable`:case`wallet_session_unavailable`:if(r.failures+=1,r.failures<=3)return}Z(e)}}async function it(e){let{args:t,refillInput:n,poolKey:r,poolIdentity:i,scheduledGeneration:a,targetDepth:o,refillAttemptTimeoutMs:s,progress:c}=e,l=X.get(r)??null;try{for(await We({poolKey:r,poolIdentity:i,clientSigningMaterial:t.clientSigningMaterial,workerCtx:t.workerCtx,generation:a}),G(r)>0&&c.publishAvailable();Date.now()<t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs;){if(q(r)!==a||(X.get(r)??null)!==l||G(r)>=o||J(r)>0||typeof navigator<`u`&&navigator.onLine===!1)return;let e=Math.min(Date.now()+s,t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs),i=await _t({...n,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:n.routerAbEcdsaDerivationPoolFill.scope,ceremonyExpiresAtMs:e,materialExpiresAtMs:n.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs},trafficClass:`background`});if(S(`evm-family`,{event:`ecdsa_background_refill_result`,authorization:t.authorization.kind,outcome:i.ok?`available`:`failed`,code:i.ok?null:i.code,depth:G(r),targetDepth:o}),!i.ok){rt(r,l,i.code);return}let u=X.get(r);u&&u===l&&(u.failures=0),c.publishAvailable()}}catch{rt(r,l,`internal`)}finally{c.settle(),z.get(r)===c&&z.delete(r);let e=X.get(r);if(e){let t=e.failures>0?2e3*2**e.failures:1e3;G(r)>=o&&(t=3e4),e!==l&&(t=0),Q(r,t)}}}function at(e){try{let t=_e(e.poolPolicy),n=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),r=g(n);R.set(r,n);let i=he(e.targetDepth,t.targetDepth),a=ge(e.triggerIfDepthAtOrBelow,t.lowWatermark,i),o=G(r),s=q(r);if(!t.enabled)return Y(`disabled`,o,i);if(e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs<=Date.now())return Z(r),Y(`invalid_args`,o,i);if(nt(r,e),o>a)return Y(`depth_above_trigger`,o,i);if(o>=i)return Y(`depth_at_or_above_target`,o,i);if(z.has(r)||J(r)>0)return Y(`in_flight_for_pool_key`,o,i);if(z.size>=t.maxRefillInFlight)return Y(`global_in_flight_limit`,o,i);let c={relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,clientVerifyingShareB64u:e.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)},l=new Me;return z.set(r,l),it({args:e,refillInput:c,poolKey:r,poolIdentity:n,scheduledGeneration:s,targetDepth:i,refillAttemptTimeoutMs:t.refillAttemptTimeoutMs,progress:l}),{scheduled:!0,reason:`scheduled`,depth:o,targetDepth:i}}catch{return Y(`invalid_args`,0,0)}}function ot(e){return e.map(e=>i(e))}function st(e){return Array.isArray(e)?e.map(e=>String(e||``).trim()).filter(e=>!!e).map(e=>a(e)):[]}async function ct(e){let t=String(e.thresholdEcdsaPublicKeyB64u||``).trim();if(t){let n=a(t);if(n.length!==33)throw Error(`thresholdEcdsaPublicKeyB64u must decode to 33 bytes`);return await M({publicKey33:n,workerCtx:e.workerCtx})}let n=String(e.clientVerifyingShareB64u||``).trim(),r=String(e.relayerVerifyingShareB64u||``).trim();if(!n||!r)throw Error(`Missing thresholdEcdsaPublicKeyB64u (or relayerVerifyingShareB64u fallback) for Router A/B ECDSA derivation signing`);let i=a(n),o=a(r);if(i.length!==33)throw Error(`clientVerifyingShareB64u must decode to 33 bytes`);if(o.length!==33)throw Error(`relayerVerifyingShareB64u must decode to 33 bytes`);return await de({left33:await M({publicKey33:i,workerCtx:e.workerCtx}),right33:await M({publicKey33:o,workerCtx:e.workerCtx}),workerCtx:e.workerCtx})}function lt(e){return e.trafficClass===`foreground`||z.get(e.poolKey)?.hasForegroundWaiters()?`foreground_presign_pool_refill`:`background_presign_pool_refill`}async function ut(e){for(let t=0;t<2;t+=1){let n=await dt(e);if(n.ok||!ft(n)||t===1)return n}return{ok:!1,code:`stale_session_state`,message:`Router A/B ECDSA derivation pool-fill session stayed stale after retry`}}async function dt(e){Fe(e.clientSigningMaterial);let t=performance.now(),n=e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs,r=e.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs,a=`ecdsa-presign-v2:${n}:${i(crypto.getRandomValues(new Uint8Array(32)))}`,o=a,s=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),c=null,l=null,u=null,d=null,ee=!1,f=`triples`,p=[],m=!0,h=!1;try{let t=await e.clientSigningMaterial.initClientPresignSession({sessionId:o,groupPublicKey33:e.groupPublicKey33,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,poolIdentity:s,workerCtx:e.workerCtx});if(t.stage!==`triples`||t.outgoingMessages.length!==1)return{ok:!1,code:`presign_init_failed`,message:`Client presign init must emit exactly one first message`};f=t.stage;let g=await ke({relayerUrl:e.relayerUrl,...e.poolFillInitKeySelector,count:1,presignSessionId:a,firstMessageB64u:i(t.outgoingMessages[0]),credential:e.credential,requestTag:lt(e),poolFill:e.routerAbEcdsaDerivationPoolFill,...F(e)});if(!g.ok)return{ok:!1,code:g.code||`presign_init_failed`,message:g.message||`Presign initialization failed`};if(g.presignSessionId!==a||g.ceremonyExpiresAtMs!==n||g.materialExpiresAtMs!==r||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Presign initialization changed the bound identity or deadlines`};let _=g.stage||`triples`,v=st(g.outgoingMessagesB64u);for(let t=0;t<64;t++){if(v.length>0&&!c){let t=await e.clientSigningMaterial.stepClientPresignSession({sessionId:o,stage:Re({clientStage:f,serverStage:_}),incomingMessages:v,workerCtx:e.workerCtx});f=t.stage,v=[],p.push(...t.outgoingMessages),t.presignatureHandle&&t.presignatureBigR33&&(c=t.presignatureHandle,l=t.presignatureBigR33)}if(!ee){let i=performance.now(),o=lt(e),s={relayerUrl:e.relayerUrl,presignSessionId:a,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,stage:Re({clientStage:f,serverStage:_}),outgoingMessagesB64u:ot(p),credential:e.credential,requestTag:o,...F(e)},c=await je(s);if(S(`evm-family`,{event:`ecdsa_presignature_round`,requestTag:o,presignSessionId:a,authorization:e.authorization.kind,round:t,stage:s.stage,durationMs:performance.now()-i,outcome:c.ok?`succeeded`:`failed`}),p=[],!c.ok)return{ok:!1,code:c.code||`presign_step_failed`,message:c.message||`Router A/B ECDSA derivation pool-fill step failed`};v=st(c.outgoingMessagesB64u),_=c.stage||_,c.event===`presign_done`&&(u=String(c.presignatureId||``).trim()||null,d=String(c.bigRB64u||``).trim()||null,ee=!0)}if(c&&l&&u&&d)break}if(!c||!l)return{ok:!1,code:`presign_timeout`,message:`Client presign session did not reach done state`};if(!u||!d)return{ok:!1,code:`presign_timeout`,message:`Server presign session did not reach done state`};if(l.length!==33)return{ok:!1,code:`internal`,message:`Invalid local presignature bigR bytes (expected 33, got ${l.length})`};try{let t=Date.now(),n=i(l);if(n!==d)return{ok:!1,code:`presign_mismatch`,message:`Client/server presignature mismatch (bigR mismatch)`};let a=await e.clientSigningMaterial.admitClientPresignature({materialHandle:c,expectedPresignatureId:u,poolIdentity:s,admissionMode:e.authorization.kind===`operation_step_up`?`resident`:`durable`,workerCtx:e.workerCtx});return a.kind===`discarded_capacity`?{ok:!1,code:`pool_full`,message:`Router A/B ECDSA derivation client presignature pool is full`}:a.kind===`discarded_ambiguous`?{ok:!1,code:`presign_failed`,message:`Router A/B ECDSA derivation client presignature admission was ambiguous`}:(h=!0,m=!1,{ok:!0,kind:`available`,presignature:{presignatureId:u,bigRB64u:n,materialHandle:c,createdAtMs:t,expiresAtMs:r}})}finally{I(l)}}catch(e){return{ok:!1,code:`presign_failed`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation pool-fill handshake failed`)}}finally{S(`evm-family`,{event:`ecdsa_presignature_generation`,requestTag:lt(e),presignSessionId:a,authorization:e.authorization.kind,durationMs:performance.now()-t,outcome:h?`available`:`failed`}),I(l),!h&&c&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:c,poolIdentity:s,workerCtx:e.workerCtx}).catch(()=>{}),m&&await e.clientSigningMaterial.abortClientPresignSession({sessionId:o,workerCtx:e.workerCtx}).catch(()=>{})}}function ft(e){return e.code===`stale_session_state`||e.code===`stale_pool_fill_session`}function pt(e){let t=l(e);return{ecdsaThresholdKeyId:p(t.ecdsa_threshold_key_id),clientVerifyingShareB64u:h(t.public_identity.derivation_client_share_public_key33_b64u),thresholdEcdsaPublicKeyB64u:t.public_identity.threshold_public_key33_b64u}}function mt(e){let t=Math.floor(Number(e.materialExpiresAtMs)),n=Number.isSafeInteger(e.authorizationExpiresAtMs)?Math.floor(Number(e.authorizationExpiresAtMs)):e.nowMs+Ie,r=Math.min(t,n,e.nowMs+Ie);return Number.isSafeInteger(r)&&r>e.nowMs?r:null}async function ht(e,t,n){let r=null,c=null,l=null,u=null,d=null,p={kind:`unclaimed`},m=null,h={kind:`before_prepare`};try{let _=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!_)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation signing`};let y=pt(e.scope);if(!y.ecdsaThresholdKeyId)return{ok:!1,code:`invalid_args`,message:`Missing ecdsaThresholdKeyId for Router A/B ECDSA derivation signing`};let x=y.clientVerifyingShareB64u;if(!x)return{ok:!1,code:`invalid_args`,message:`Missing clientVerifyingShareB64u for Router A/B ECDSA derivation signing`};if(!(e.signingDigest32 instanceof Uint8Array)||e.signingDigest32.length!==32)return{ok:!1,code:`invalid_args`,message:`signingDigest32 must be 32 bytes for Router A/B ECDSA derivation signing`};let ne=performance.now(),C=await ct({clientVerifyingShareB64u:x,thresholdEcdsaPublicKeyB64u:y.thresholdEcdsaPublicKeyB64u,workerCtx:e.workerCtx});b(e.operationId,`public_key_validation`,ne),c=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:_,scope:e.scope,materialActivation:e.materialActivation}),await W(c,e.clientSigningMaterial,e.workerCtx),r=g(c),R.set(r,c),m=q(r);let re=performance.now();if(l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`pool_lookup`,re),!l){let t=performance.now();await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:m}),b(e.operationId,`pool_restore`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l){let t=performance.now();await Xe(r,`foreground`),b(e.operationId,`refill_wait`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l){let t=performance.now();Je(r);try{let t=await _t({...n,trafficClass:`foreground`});if(!t.ok&&t.code===`invalidated`&&(t=await _t({...n,trafficClass:`foreground`})),!t.ok&&t.code!==`pool_full`)return t;!t.ok&&t.code===`pool_full`&&await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:q(r)})}finally{Ye(r)}m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`foreground_refill`,t)}if(S(`evm-family`,{event:`ecdsa_presignature_selection`,operationId:e.operationId,authorization:e.authorization.kind,outcome:l?`available`:`empty`,remainingDepth:G(r),attempt:t}),!l)return{ok:!1,code:`pool_empty`,message:`Router A/B ECDSA derivation client presignature pool is empty`};let ie=Date.now(),ae=mt({authorizationExpiresAtMs:e.expiresAtMs,materialExpiresAtMs:l.expiresAtMs,nowMs:ie});if(!ae)return{ok:!1,code:`pool_entry_expired`,message:`Router A/B ECDSA derivation client presignature is expired`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};d=Ne();let w=await ee(d),T=s({scope:e.scope,requestId:o(`router-ab-ecdsa-sign`,32,`Router A/B ECDSA derivation sign request`),operationId:e.operationId,operationDigests:e.operationDigests,authorization:e.authorization,materialActivation:e.materialActivation,clientPresignatureId:l.presignatureId,expiresAtMs:ae,signingDigest32:e.signingDigest32,clientRerandomizationCommitment32:w});I(w);let E=o(`router-ab-ecdsa-reservation`,32,`Router A/B ECDSA Client presignature reservation`);p={kind:`destroy`};let oe=performance.now(),D=await e.clientSigningMaterial.reserveClientPresignature({materialHandle:l.materialHandle,expectedPresignatureId:l.presignatureId,poolIdentity:c,requestBinding:T.request_id,reservationId:E,leaseExpiresAtMs:T.expires_at_ms,workerCtx:e.workerCtx});if(b(e.operationId,`presignature_reserve`,oe),D.kind===`unavailable`)return D.reason===`claimed_elsewhere`&&(p={kind:`owned_elsewhere`}),t<4?await ht(e,t+1,n):{ok:!1,code:D.reason===`expired`?`pool_entry_expired`:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature is unavailable: ${D.reason}`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};Q(r,0),h={kind:`prepare_submitted`};let se=performance.now(),O=await ce({relayServerUrl:_,credential:e.credential,request:T,onServerTiming:te.bind(void 0,e.operationId,`prepare`)});if(b(e.operationId,`prepare`,se),O.kind===`reusable_wallet_session`){if(!e.reconcileSession)throw Error(`Wallet Session reconciliation is required`);await e.reconcileSession(O.sessionStatus)}let k=O.signing;if(k.server_big_r33_b64u!==l.bigRB64u)return{ok:!1,code:`presign_mismatch`,message:`Router A/B ECDSA derivation SigningWorker returned a different presignature bigR`};let A=performance.now();await e.clientSigningMaterial.commitClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,workerCtx:e.workerCtx}),b(e.operationId,`presignature_commit`,A);let j=a(l.bigRB64u),M=a(k.signing_worker_rerandomization_contribution32_b64u);try{if(j.length!==33)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation presign bigR must decode to 33 bytes`};if(M.length!==32)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation SigningWorker rerandomization contribution must decode to 32 bytes`};let t=performance.now();u=await e.clientSigningMaterial.computeSignatureShareFromPresignatureHandle({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,groupPublicKey33:C,expectedPresignBigR33:j,digest32:e.signingDigest32,clientRerandomizationContribution32:d,signingWorkerRerandomizationContribution32:M,workerCtx:e.workerCtx}),b(e.operationId,`client_share`,t),p={kind:`consumed`}}finally{I(j),I(M)}if(u.length!==32)return{ok:!1,code:`internal`,message:`Invalid Router A/B ECDSA derivation client signature share length (expected 32, got ${u.length})`};let de=f({scope:e.scope,requestId:T.request_id,operationId:T.operation_id,operationDigests:T.operation_digests,authorization:e.authorization,materialActivation:e.materialActivation,expiresAtMs:T.expires_at_ms,signingDigest32:e.signingDigest32,serverPresignatureId:k.server_presignature_id,clientSignatureShare32:u,clientRerandomizationContribution32:d}),fe=performance.now(),pe=await le({relayServerUrl:_,credential:e.credential,request:de,onServerTiming:te.bind(void 0,e.operationId,`finalize`)});b(e.operationId,`finalize`,fe);let N=a(pe.signature65_b64u);if(N.length!==65)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned invalid signature length (expected 65, got ${N.length})`};try{let t=performance.now();await ue({digest32:e.signingDigest32,signature65:N,publicKey33:C,workerCtx:e.workerCtx}),b(e.operationId,`signature_verify`,t)}catch(e){return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned a signature that does not recover to the threshold group public key: ${Pe(e)}`}}return{ok:!0,signature65:N,signature65B64u:pe.signature65_b64u,rB64u:i(N.slice(0,32)),sB64u:i(N.slice(32,64)),recId:N[64]}}catch(t){if(t instanceof O||t instanceof k)throw t;let n=String(t&&typeof t==`object`&&`message`in t?t.message:t||`Router A/B ECDSA derivation signing failed`);return t instanceof j&&t.code===`expired_local_request`?{ok:!1,code:`pool_entry_expired`,message:n}:r&&c&&m!==null&&h.kind===`before_prepare`&&q(r)!==m?(await qe({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`}):{ok:!1,code:`router_ab_sign_failed`,message:n}}finally{if(I(u),I(d),l&&c&&p.kind!==`consumed`&&p.kind!==`owned_elsewhere`){let t=!1;if(p.kind===`unclaimed`&&r&&m!==null&&m===q(r)){let e=Be(r,c,l);t=e===`stored`||e===`duplicate`}t||await e.clientSigningMaterial.destroyClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,workerCtx:e.workerCtx}).catch(()=>{})}r&&Q(r,0)}}async function gt(e){let t=pt(e.scope),n=Math.floor(Number(e.expiresAtMs));if(!Number.isSafeInteger(n)||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Router A/B ECDSA derivation pool fill expiry is unavailable or expired`};let r={relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,clientVerifyingShareB64u:t.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:e.scope,ceremonyExpiresAtMs:Math.min(n,Date.now()+d-3e4),materialExpiresAtMs:e.authorization.kind===`operation_step_up`?n:Date.now()+y},workerCtx:e.workerCtx,...F(e)},i=await ht(e,0,r);return!i.ok&&(i.code===`pool_entry_expired`||i.code===`pool_entry_unavailable`)?await ht(e,0,r):i}async function _t(e){try{let t=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation});await W(t,e.clientSigningMaterial,e.workerCtx);let n=g(t);await Ue({poolKey:n,poolIdentity:t,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx});let r=q(n),i=await ct({clientVerifyingShareB64u:e.clientVerifyingShareB64u,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,workerCtx:e.workerCtx}),a=await ut({relayerUrl:e.relayerUrl,poolFillInitKeySelector:{keyHandle:m(e.keyHandle)},clientSigningMaterial:e.clientSigningMaterial,groupPublicKey33:i,materialActivation:e.materialActivation,credential:e.credential,poolKey:n,trafficClass:e.trafficClass,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)});if(!a.ok)return a;try{await W(t,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(n)!==r)return await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!1,code:`invalidated`,message:`Router A/B ECDSA derivation presignature pool invalidated`};let o=Be(n,t,a.presignature);return(o===`capacity_full`||o===`invalid`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!0,presignatureId:a.presignature.presignatureId}}catch(e){return{ok:!1,code:`internal`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation presignature refill failed`)}}}export{Ze as a,pe as c,gt as i,et as n,_e as o,at as r,me as s,Qe as t};