@seams/wallet 0.9.0 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/.build-inputs.sha256 +1 -1
- package/dist/esm/core/signingEngine/chains/evm/bytes.js +15 -1
- package/dist/esm/core/signingEngine/flows/signEvmFamily/signingFlow.js +1 -1
- package/dist/esm/core/signingEngine/flows/signNear/shared/ed25519YaoNormalSigning.js +84 -38
- package/dist/esm/core/signingEngine/flows/signNear/signTransactions.js +49 -2
- package/dist/esm/core/signingEngine/uiConfirm/ui/transaction-display/abi/abiDecode.js +315 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/transaction-display/abi/enrichDisplayModelWithAbi.js +77 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/transaction-display/formatters.js +10 -1
- package/dist/esm/core/signingEngine/uiConfirm/ui/transaction-display/renderers/fallback.js +52 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/transaction-display/renderers/types.js +62 -0
- package/dist/esm/core/signingEngine/uiConfirm/ui/transaction-display/tree.js +249 -0
- package/dist/esm/sdk/{host-B1CdRGoI.js → host-c1__wJwz.js} +1 -1
- package/dist/esm/sdk/{runtime-auth-tgfe70hU.js → runtime-auth-BKFyLISf.js} +1 -1
- package/dist/{public/sdk/runtime-device-link-BUxuQupR.js → esm/sdk/runtime-device-link-ENxdEXQW.js} +1 -1
- package/dist/{public/sdk/runtime-ecdsa-tempo-DOBk_EtI.js → esm/sdk/runtime-ecdsa-tempo-DhGEb9U7.js} +1 -1
- package/dist/esm/sdk/{runtime-email-otp-CsAJKvYC.js → runtime-email-otp-dgsP7XZi.js} +1 -1
- package/dist/esm/sdk/{runtime-export-7REbcnBl.js → runtime-export-D2RCm5Gk.js} +1 -1
- package/dist/esm/sdk/{runtime-near-BA0DQf6H.js → runtime-near-Bf-9MFBQ.js} +1 -1
- package/dist/esm/sdk/{runtime-preferences-cRViPE8a.js → runtime-preferences-LQ8SPE7o.js} +1 -1
- package/dist/esm/sdk/{runtime-recovery-RRc8Yz1y.js → runtime-recovery-BuEzJzuZ.js} +1 -1
- package/dist/esm/sdk/shared-8ffIBYw2.js +6 -0
- package/dist/esm/sdk/signNear-BhTkDm2-.js +1 -0
- package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
- package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
- package/dist/esm/utils/intentDigest.js +59 -1
- package/dist/public/headers.manifest.json +1 -1
- package/dist/public/sdk/{host-B1CdRGoI.js → host-c1__wJwz.js} +1 -1
- package/dist/public/sdk/{runtime-auth-tgfe70hU.js → runtime-auth-BKFyLISf.js} +1 -1
- package/dist/{esm/sdk/runtime-device-link-BUxuQupR.js → public/sdk/runtime-device-link-ENxdEXQW.js} +1 -1
- package/dist/{esm/sdk/runtime-ecdsa-tempo-DOBk_EtI.js → public/sdk/runtime-ecdsa-tempo-DhGEb9U7.js} +1 -1
- package/dist/public/sdk/{runtime-email-otp-CsAJKvYC.js → runtime-email-otp-dgsP7XZi.js} +1 -1
- package/dist/public/sdk/{runtime-export-7REbcnBl.js → runtime-export-D2RCm5Gk.js} +1 -1
- package/dist/public/sdk/{runtime-near-BA0DQf6H.js → runtime-near-Bf-9MFBQ.js} +1 -1
- package/dist/public/sdk/{runtime-preferences-cRViPE8a.js → runtime-preferences-LQ8SPE7o.js} +1 -1
- package/dist/public/sdk/{runtime-recovery-RRc8Yz1y.js → runtime-recovery-BuEzJzuZ.js} +1 -1
- package/dist/public/sdk/shared-8ffIBYw2.js +6 -0
- package/dist/public/sdk/signNear-BhTkDm2-.js +1 -0
- package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
- package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
- package/dist/public/wallet-assets.manifest.json +26 -26
- package/dist/public/wallet-service/index.html +4 -4
- package/dist/types/wallet/src/core/signingEngine/flows/signNear/shared/ed25519YaoNormalSigning.d.ts +16 -4
- package/dist/types/wallet/src/core/signingEngine/flows/signNear/shared/signatureOnlySigning.d.ts +3 -3
- package/dist/types/wallet/src/core/signingEngine/nonce/nearTransactionReadiness.d.ts +3 -0
- package/dist/types/wallet/src/core/signingEngine/stepUpConfirmation/confirmOperation.d.ts +3 -1
- package/dist/types/wallet/src/core/signingEngine/uiConfirm/handlers/flows/signing.d.ts +2 -0
- package/dist/types/wallet/src/core/signingEngine/uiConfirm/handlers/handlePromptFromWorker.d.ts +2 -0
- package/dist/types/wallet/src/core/signingEngine/uiConfirm/uiConfirm.types.d.ts +3 -0
- package/package.json +1 -1
- package/dist/esm/sdk/shared-DdfxBUGY.js +0 -6
- package/dist/esm/sdk/signNear-CO5bx24Z.js +0 -1
- package/dist/public/sdk/shared-DdfxBUGY.js +0 -6
- package/dist/public/sdk/signNear-CO5bx24Z.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./chunk-dVx5-UGu.js";import{c as t,f as n,j as r,l as i}from"./normalize-kUDm5zfS.js";import{C as a,S as o,a as s,c,h as l,k as u,m as d,s as f,u as p,x as m}from"./chains-CiYQT1K4.js";import{i as h,n as g,r as _,t as v}from"./base64-CsEj-_bC.js";import{n as y,r as b}from"./secureRandomId-BIekT8bE.js";import{w as x}from"./primitives-CAcl7ON7.js";import{o as S}from"./sessionPolicy-J-RrlPZQ.js";import{o as ee}from"./signingSessionSeal-CDLUmAFY.js";import{r as te}from"./transactionReviewAdmission-C-a3ctCJ.js";import{i as C,t as ne}from"./activeWalletSession-DiZcKjB_.js";import{c as w,d as T,f as E,h as D,m as O,p as k,s as re}from"./capabilityKinds-CKQ4Uqnv.js";import{r as A}from"./canonicalPrimitives-CKPGgpxg.js";import{t as j}from"./errors-BZO3LF6G.js";import{d as M,p as ie}from"./digestEncoding-Dzc1rzWV.js";import{d as ae,i as N,t as P,u as F}from"./accountIds-BzZs7YoX.js";import{a as oe,c as I}from"./ecdsaChainTarget-C8ZtMZ8l.js";import{n as se,t as ce}from"./signerDomain-vQmlnsbF.js";import{d as le,f as ue,g as de,h as fe,l as pe,m as me,p as he,u as ge}from"./registrationIntent-DOkZcKSP.js";import{Nt as L,T as _e,i as ve,kt as R}from"./emailOtpEcdsaDerivationIdentity-B8HzTh4T.js";import{t as ye}from"./challengeDelivery-DxXAkOfS.js";import{a as be,m as xe,o as z}from"./sdkSentEvents-D3q1h-Uo.js";import{t as Se}from"./signerSlot-Dto7dObP.js";import{t as Ce}from"./jsonRpc-DrCYQIM9.js";import{a as we,c as B,i as V,n as Te,o as Ee,r as H,s as De,t as Oe}from"./types-D3GM-uHR.js";import{p as ke}from"./nonceLaneKeys-Fkvk2UPy.js";import{a as Ae,i as je,l as Me,u as Ne}from"./helpers-Ddy72ULN.js";import{i as Pe,n as Fe}from"./profileAccountProjection-DmmfMood.js";import{b as Ie,s as Le,t as Re}from"./nearEd25519YaoMaterialActivation-fWQI3rYj.js";import{D as ze,T as Be,j as Ve}from"./nearEd25519YaoSigningPreparation-B0d1AG3u.js";import{n as He}from"./lanes-DnBwWv4l.js";import{t as Ue}from"./walletSessionAuthorizationStatus-o1VgsLhA.js";import{n as We,r as Ge,t as Ke}from"./operationFingerprint-CTR9G1NT.js";import{a as U,c as qe,o as Je,s as Ye,t as Xe}from"./trace-BvbCxdXF.js";import{d as Ze,n as Qe,o as W,s as $e,u as et}from"./intentDigest-CE-tLw87.js";import{n as tt}from"./NonceCoordinator-CFFq8-Q9.js";import{t as nt}from"./executeWorkerOperation-BInr8RYN.js";import{a as rt,i as it,o as at,r as ot,t as st}from"./authorizationAdmission-Ckx6q6tp.js";import{i as ct}from"./walletSessionFailure-Bu4VPKTz.js";import{a as lt,d as ut,i as dt,l as ft,n as pt,p as mt,r as ht,s as gt,u as _t}from"./routerAbNormalSigning-BG75eyI2.js";import{i as vt,n as yt}from"./clientSessionPersistenceState-CImFWDj6.js";import{a as bt,i as xt,r as St,t as Ct}from"./types-BNUuaUtl.js";import{C as wt,b as Tt,c as Et,g as Dt,h as Ot,l as kt,n as At,o as jt,s as Mt,t as Nt,u as Pt,x as Ft}from"./requireStepUpAuth-DCVqmeee.js";import{a as It,c as Lt,i as Rt,n as zt,r as Bt,s as Vt,t as Ht}from"./transactionState-DVinJk4K.js";let Ut=function(e){return e[e.SignTransactionsWithActionsSuccess=0]=`SignTransactionsWithActionsSuccess`,e[e.SignNep413MessageSuccess=1]=`SignNep413MessageSuccess`,e[e.SignDelegateActionSuccess=2]=`SignDelegateActionSuccess`,e}({});const Wt={ThresholdEd25519ComputeNep413SigningDigest:`thresholdEd25519ComputeNep413SigningDigest`,ThresholdEd25519ComputeDelegateSigningDigest:`thresholdEd25519ComputeDelegateSigningDigest`,ThresholdEd25519BuildDelegateSigningPayload:`thresholdEd25519BuildDelegateSigningPayload`,ThresholdEd25519FinalizeDelegateFromSignature:`thresholdEd25519FinalizeDelegateFromSignature`,ThresholdEd25519FinalizeNearTxFromSignature:`thresholdEd25519FinalizeNearTxFromSignature`,ThresholdEd25519BuildNearTxUnsignedBorsh:`thresholdEd25519BuildNearTxUnsignedBorsh`,ThresholdEd25519DecodeSignedNearTxBorsh:`thresholdEd25519DecodeSignedNearTxBorsh`},Gt={uiMode:`modal`,behavior:`requireClick`,autoProceedDelay:0},Kt=Symbol(`ClientSecretSource`),qt=Symbol(`EmailOtpWorkerSessionHandle`);function G(e,t){let n=String(e||``).trim();if(!n)throw Error(`[platform] ${t} is required`);return n}function Jt(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`[platform] ${t} must be an object`);return e}function Yt(e){return Xt({prfFirstB64u:e.prf.prfFirstB64u,rpId:e.rpId,credentialIdB64u:e.credentialIdB64u})}function Xt(e){return{kind:`webauthn_prf_first`,prfFirstB64u:G(e.prfFirstB64u,`prfFirstB64u`),rpId:e.rpId,credentialIdB64u:G(e.credentialIdB64u,`credentialIdB64u`),[Kt]:`webauthn_prf_first`}}function Zt(e){let t=G(e.sessionId,`sessionId`);switch(e.action){case`threshold_ecdsa_bootstrap`:return{kind:`email_otp_worker_session_handle_v1`,sessionId:t,walletId:e.walletId,keyHandle:G(e.keyHandle,`keyHandle`),authSubjectId:e.authSubjectId,action:`threshold_ecdsa_bootstrap`,operation:e.operation,chainTarget:e.chainTarget,[qt]:`email_otp_worker_session_handle`};case`threshold_ed25519_session`:return{kind:`email_otp_worker_session_handle_v1`,sessionId:t,walletId:e.walletId,rpId:e.rpId,authSubjectId:e.authSubjectId,action:`threshold_ed25519_session`,operation:e.operation,[qt]:`email_otp_worker_session_handle`};default:{let t=e;throw Error(`[platform] unsupported email OTP worker-issued handle action: ${String(t)}`)}}}function Qt(e){let t=Jt(e,`email OTP worker-issued session handle`),n=G(String(t.kind||``),`email OTP worker-issued handle kind`);if(n!==`email_otp_worker_session_handle_v1`)throw Error(`[platform] unsupported email OTP worker-issued handle kind: ${n}`);let r=G(String(t.action||``),`email OTP worker-issued handle action`),i=G(String(t.operation||``),`email OTP worker-issued handle operation`);if(i!==`registration`&&i!==`wallet_unlock`&&i!==`sign`&&i!==`export`)throw Error(`[platform] unsupported email OTP worker-issued handle operation: ${i}`);let a=i,o={sessionId:G(String(t.sessionId||``),`email OTP worker-issued handle sessionId`),walletId:I(t.walletId),authSubjectId:ve(t.authSubjectId),operation:a};if(r===`threshold_ecdsa_bootstrap`){if(`rpId`in t)throw Error(`[platform] email OTP ECDSA worker-issued handles cannot include rpId`);if(a===`registration`)throw Error(`[platform] registration Email OTP ECDSA worker-issued handles are retired`);let e=oe(Jt(t.chainTarget,`email OTP worker-issued handle chainTarget`));if(`evmFamilySigningKeySlotId`in t)throw Error(`[platform] runtime Email OTP ECDSA handles cannot include evmFamilySigningKeySlotId`);return Zt({...o,action:r,operation:a,keyHandle:G(String(t.keyHandle||``),`email OTP worker-issued handle keyHandle`),chainTarget:e})}if(r===`threshold_ed25519_session`){if(`chainTarget`in t)throw Error(`[platform] email OTP Ed25519 worker-issued handles cannot include chainTarget`);if(`evmFamilySigningKeySlotId`in t||`keyHandle`in t)throw Error(`[platform] email OTP Ed25519 worker-issued handles cannot include ECDSA key identity`);return Zt({...o,action:r,rpId:_e(t.rpId)})}throw Error(`[platform] unsupported email OTP worker-issued handle action: ${r}`)}function $t(e){return e.action===`threshold_ecdsa_bootstrap`&&e.operation===`export`}function en(e){let t=Qt(e);if(!$t(t))throw Error(`[platform] Email OTP ECDSA export requires an export worker handle`);return t}const tn=15e3;function nn(e){e.abort(`timeout`)}function rn(e,t){let n=String(e??``).trim();if(!n)throw Error(`[threshold-ed25519] ${t} is required`);return n}function an(e){let t=rn(Me(e.credential),`prfFirstB64u`);return{ok:!0,operation:`get_passkey`,requirePrfFirst:!0,credential:e.credential,credentialIdB64u:rn(e.credential.rawId||e.credential.id,`credentialIdB64u`),rawIdB64u:String(e.credential.rawId||``).trim(),rpId:_e(e.rpId),prf:{kind:`required`,prfFirstB64u:t}}}function on(e){return{kind:`webauthn_prf_first_credential`,credential:e.credential,secretSource:Yt(an(e))}}function sn(e){return e.policySecretSource.secretSource.prfFirstB64u}function cn(e){if(typeof e!=`string`)return null;let t=Date.parse(e);return Number.isSafeInteger(t)&&t>Date.now()?t:null}function ln(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0?e:null}async function un(e){let n=i(t(e.relayerUrl));if(!n)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Wallet Session mint`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Wallet Session mint`};let o=Ne(e.auth.policySecretSource.credential),s=new AbortController,c=null;try{let t=`${n}${ee}`,i=e.existingOperationCredential,l=String(e.publishableKey||``).trim()||void 0,u=i?.token||l,d=!i&&l&&String(e.projectEnvironmentId||``).trim()||void 0;c=setTimeout(nn,tn,s);let f=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,...u?{Authorization:`Bearer ${u}`}:{}},credentials:`omit`,signal:s.signal,body:JSON.stringify({sessionKind:e.sessionKind,relayerKeyId:e.relayerKeyId,sessionPolicy:e.sessionPolicy,...d?{projectEnvironmentId:d}:{},walletSessionTarget:{kind:`new_wallet_session`},...o?{webauthn_authentication:o}:{}})}),p;try{let e=await f.json();p=a(e)?e:{}}catch(e){if(s.signal.aborted)throw e;p={}}if(!f.ok)return Le(p)||{ok:!1,code:typeof p.code==`string`?p.code:`http_error`,message:typeof p.message==`string`?p.message:`HTTP ${f.status}`};let m=Le(p);if(m)return m;if(p.ok!==!0)return{ok:!1,code:typeof p.code==`string`?p.code:`invalid_response`,message:typeof p.message==`string`?p.message:`Wallet Session mint returned an unsuccessful response`};let h=r(p.thresholdSessionId);if(!h.ok)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned an invalid thresholdSessionId`};let g=D(p.walletSessionId),_=O(p.authorizationId),v=T(p.quotaId);if(!g.ok||!_.ok||!v.ok)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned invalid authorization identity`};let y=cn(p.expiresAt),b=ln(p.remainingUses),x=S(p.runtimePolicyScope);if(!y||!b||!x)return{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned invalid lifecycle or policy data`};let te={ok:!0,thresholdSessionId:h.value,walletSessionId:g.value,authorizationId:_.value,quotaId:v.value,expiresAtMs:y,remainingUses:b,runtimePolicyScope:x};if(p.sessionKind===`issued_exact_wallet_session`){let e;try{e=C(p.operationCredential)}catch(e){return{ok:!1,code:`invalid_response`,message:j(e)||`Wallet Session mint returned an invalid operation credential`}}return e.walletSessionId===g.value?{...te,sessionKind:p.sessionKind,operationCredential:e}:{ok:!1,code:`invalid_response`,message:`Wallet Session mint credential does not identify its session`}}return p.sessionKind!==`already_committed_exact_wallet_session`||p.operationCredential!==void 0?{ok:!1,code:`invalid_response`,message:`Wallet Session mint returned an invalid session branch`}:i?i.walletSessionId===g.value?{...te,sessionKind:p.sessionKind}:{ok:!1,code:`invalid_response`,message:`Reused Wallet Session mint returned another lifecycle identity`}:{ok:!1,code:`invalid_response`,message:`Reused Wallet Session mint requires the credential the caller already holds`}}catch(e){let t=j(e)||`Failed to mint threshold session`,n=s.signal.aborted;return{ok:!1,code:n?`timeout`:`network_error`,message:n?`Wallet Session mint timed out after ${tn}ms`:t}}finally{c!==null&&clearTimeout(c)}}function dn(e){switch(e.kind){case`passkey`:return{kind:`passkey`,authority:e.authority,webauthn_authentication:Ne(e.credential)};case`email_otp`:return{kind:`email_otp`,authority_ref:e.authorityRef,provider_subject_id:rn(e.providerSubjectId,`providerSubjectId`),challenge_id:rn(e.challengeId,`challengeId`),otp_code:rn(e.otpCode,`otpCode`)};default:throw Error(`[threshold-ed25519] unsupported operation step-up proof`)}}function fn(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`[threshold-ed25519] ${t} must be an object`);return e}function pn(e,t,n){let r=Object.keys(e).sort(),i=[...t].sort();if(r.length!==i.length)throw Error(`[threshold-ed25519] ${n} contains unexpected fields`);for(let e=0;e<r.length;e+=1)if(r[e]!==i[e])throw Error(`[threshold-ed25519] ${n} contains unexpected fields`)}function mn(e,t){if(typeof e!=`string`||e.length===0||e.trim()!==e)throw Error(`[threshold-ed25519] ${t} must be a non-empty normalized string`);return e}function hn(e){switch(e.proof.kind){case`passkey`:if(e.materialRecovery.kind!==`not_requested`)throw Error(`[threshold-ed25519] passkey operation step-up cannot request material recovery`);return{kind:`not_requested`};case`email_otp`:switch(e.materialRecovery.kind){case`not_requested`:return{kind:`not_requested`};case`email_otp_factor_release_v1`:return{kind:`email_otp_factor_release_v1`,workerEphemeralPublicKey65B64u:mn(e.materialRecovery.workerEphemeralPublicKey65B64u,`workerEphemeralPublicKey65B64u`)};default:throw e.materialRecovery,Error(`[threshold-ed25519] unsupported material recovery request`)}default:throw e.proof,Error(`[threshold-ed25519] unsupported operation step-up proof`)}}function gn(e){let t=fn(e.value,`operation step-up material recovery`);switch(t.kind){case`not_requested`:if(pn(t,[`kind`],`operation step-up material recovery`),e.requested.kind!==`not_requested`)throw Error(`[threshold-ed25519] operation step-up material recovery response does not match the request`);return{kind:`not_requested`};case`email_otp_factor_release_v1`:if(pn(t,[`kind`,`challengeId`,`enrollmentId`,`enrollmentSealKeyVersion`,`serverEphemeralPublicKey65B64u`,`nonce12B64u`,`ciphertextB64u`],`operation step-up material recovery`),e.requested.kind!==`email_otp_factor_release_v1`)throw Error(`[threshold-ed25519] operation step-up material recovery response does not match the request`);return{kind:`email_otp_factor_release_v1`,challengeId:mn(t.challengeId,`materialRecovery.challengeId`),enrollmentId:mn(t.enrollmentId,`materialRecovery.enrollmentId`),enrollmentSealKeyVersion:mn(t.enrollmentSealKeyVersion,`materialRecovery.enrollmentSealKeyVersion`),serverEphemeralPublicKey65B64u:mn(t.serverEphemeralPublicKey65B64u,`materialRecovery.serverEphemeralPublicKey65B64u`),nonce12B64u:mn(t.nonce12B64u,`materialRecovery.nonce12B64u`),ciphertextB64u:mn(t.ciphertextB64u,`materialRecovery.ciphertextB64u`)};default:throw Error(`[threshold-ed25519] operation step-up material recovery kind is invalid`)}}function _n(e){let t=fn(e.body,`operation step-up response`);if(pn(t,[`ok`,`kind`,`authorization`,`expiresAtMs`,`materialRecovery`],`operation step-up response`),t.ok!==!0||t.kind!==`verified_step_up`)throw Error(`[threshold-ed25519] operation step-up response kind is invalid`);let n=fn(t.authorization,`operation step-up authorization`);if(pn(n,[`kind`,`evidence_set_digest`],`operation step-up authorization`),n.kind!==`operation_step_up`)throw Error(`[threshold-ed25519] operation step-up authorization marker is invalid`);let r=mn(n.evidence_set_digest,`operation step-up authorization.evidence_set_digest`);if(A(r),typeof t.expiresAtMs!=`number`||!Number.isSafeInteger(t.expiresAtMs)||t.expiresAtMs<=Date.now())throw Error(`[threshold-ed25519] operation step-up expiry is invalid`);return{kind:`verified_step_up`,authorization:{kind:`operation_step_up`,evidence_set_digest:r},expiresAtMs:t.expiresAtMs,materialRecovery:gn({value:t.materialRecovery,requested:e.requestedMaterialRecovery})}}async function vn(e){let n=i(t(e.relayerUrl));if(!n)throw Error(`[threshold-ed25519] operation step-up relayerUrl is required`);let r=hn(e),a=e.credential.kind===`wallet_session_opaque`?{token:e.credential.walletSessionToken,home:e.credential.home}:null,o=M({...a?{headers:ie(a)}:{},body:{kind:`router_ab_ed25519_yao_operation_step_up_grant_v1`,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:dn(e.proof),materialRecovery:r.kind===`email_otp_factor_release_v1`?{kind:r.kind,worker_ephemeral_public_key_65_b64u:r.workerEphemeralPublicKey65B64u}:r}}),s=await fetch(`${n}${ee}`,{...o}),c=await s.json().catch(()=>({}));if(!s.ok){let e=c&&typeof c==`object`&&!Array.isArray(c)?c:{};throw Error(`[threshold-ed25519] operation step-up failed: ${String(e.message||`HTTP ${s.status}`)}`)}return _n({body:c,requestedMaterialRecovery:r})}function yn(e){let t=e.lane,r=e.readiness;if(t.curve!==r.curve)throw Error(`[SigningSession] planner lane and readiness curves do not match`);if(t.curve===`ecdsa`&&r.curve===`ecdsa`){let e=t.authorization,i=r.authorization,a=e.session,o=i.session;if(!n(t.materialActivation,r.materialActivation)||e.selectedAuthority.authorityId!==i.selectedAuthority.authorityId||e.selectedAuthMethod.kind!==i.selectedAuthMethod.kind||e.selectedAuthMethod.walletAuthMethodId!==i.selectedAuthMethod.walletAuthMethodId||a.walletId!==o.walletId||a.authorityId!==o.authorityId||a.authMethodId!==o.authMethodId||a.authorizationId!==o.authorizationId||a.quotaId!==o.quotaId||a.authorityDigestB64u!==o.authorityDigestB64u||a.authorityRevocationEpoch!==o.authorityRevocationEpoch||e.operationCredential.walletSessionId!==i.operationCredential.walletSessionId||e.operationCredential.token!==i.operationCredential.token)throw Error(`[SigningSession] planner ECDSA readiness authority does not match its lane`)}let i=xn(e);if(i)return{kind:V.NotReady,lane:t,reason:i};let a=e.forceFreshAuth||e.sensitiveOperationPolicy===`require_fresh_same_method`||t.retention===`single_use`;if(r.status===`ready`&&!a){if(t.curve===`ed25519`&&r.curve===`ed25519`)return{kind:V.WarmSession,lane:t,keyRef:{kind:Oe.Cached,curve:`ed25519`,thresholdSessionId:r.thresholdSessionId}};if(t.curve!==`ecdsa`||r.curve!==`ecdsa`)throw Error(`[SigningSession] planner lane and readiness curves do not match`);return{kind:V.WarmSession,lane:t,keyRef:{kind:Oe.Cached,curve:`ecdsa`,materialActivation:r.materialActivation,authorization:r.authorization}}}if(r.status===`auth_unavailable`||r.status===`status_unavailable`||r.status===`status_unknown`)return{kind:V.NotReady,lane:t,reason:r.status};if(B(t.auth)===`email_otp`)return{kind:V.EmailOtpReauth,lane:t,challenge:{chainFamily:t.chainFamily,lane:t}};if(t.curve===`ed25519`&&r.curve===`ed25519`)return{kind:V.PasskeyReauth,lane:t,reconnect:{lane:t,curve:`ed25519`,thresholdSessionId:r.thresholdSessionId}};if(t.curve!==`ecdsa`||r.curve!==`ecdsa`)throw Error(`[SigningSession] planner lane and readiness curves do not match`);return{kind:V.PasskeyReauth,lane:t,reconnect:{lane:t,curve:`ecdsa`,materialActivation:r.materialActivation,authorization:r.authorization}}}function bn(e,t){return{event:`signing_planner_decision`,readinessStatus:e.readiness.status,forceFreshAuth:!!e.forceFreshAuth,...e.sensitiveOperationPolicy?{sensitiveOperationPolicy:e.sensitiveOperationPolicy}:{},plan:Ee(t),lane:we(e.lane),...t.kind===V.NotReady?{reason:t.reason}:{}}}function xn(e){return B(e.lane.auth)===`email_otp`&&(e.sensitiveOperationPolicy===`deny_email_otp`||e.sensitiveOperationPolicy===`require_passkey`)?`policy_blocked`:null}async function Sn(e,t){let n=P(e),r=await Fe(t,Pe(n)).catch(()=>null);if(!r?.profileId)throw Error(`No profile/account mapping for account ${n}`);let i=await t.getLastProfileState().catch(()=>null);if(!i?.profileId||i.profileId!==r.profileId)throw Error(`No last user session for account ${n}`);let a=Se(i.activeSignerSlot,{min:1});if(a===null)throw Error(`Invalid last-user signerSlot for account ${n}`);return a}var K=function(e){return e.Query=`query`,e.Send=`send_tx`,e.Block=`block`,e}(K||{}),Cn=class e{constructor(e){this.transaction=e.transaction,this.signature=e.signature,this.borsh_bytes=e.borsh_bytes,e.nonceLease&&(this.nonceLease=e.nonceLease),e.serverDispatch&&(this.serverDispatch=e.serverDispatch)}static fromPlain(t){return new e({transaction:t.transaction,signature:t.signature,borsh_bytes:t.borsh_bytes,...t.nonceLease?{nonceLease:t.nonceLease}:{},...t.serverDispatch?{serverDispatch:t.serverDispatch}:{}})}encode(){return new Uint8Array(this.borsh_bytes).buffer}base64Encode(){return g(this.encode())}};function wn(e){if(!e)return null;if(Array.isArray(e))return new Uint8Array(e).buffer;if(ArrayBuffer.isView(e)){let t=e;return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}return e instanceof ArrayBuffer?e:null}function Tn(e){let t=e?.signedTransaction,n=t&&typeof t==`object`?t:e,r=n.base64Encode;if(m(r))return r.call(n);let i=n.encode;if(m(i))return g(i.call(n));let a=wn(n.borsh_bytes);if(a)return g(a);let o=wn(n.borshBytes);if(o)return g(o);throw Error(`Invalid signed transaction payload: cannot serialize to base64`)}var En=class e{constructor(t){this.rpcUrls=e.normalizeRpcUrls(t)}static normalizeRpcUrls(e){let t=(Array.isArray(e)?e:e.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean)).map(e=>{try{return new URL(e).toString()}catch(t){let n=j(t)||`Invalid NEAR RPC URL: ${e}`;throw Error(n)}});if(!t.length)throw Error(`NEAR RPC URL cannot be empty`);return Array.from(new Set(t))}errorFromHttpStatus(e){return Error(`RPC request failed: ${e.status} ${e.statusText}`)}errorFromFailedCall(e,t){return t}sendWithRetry(e){return e()}buildRequestBody(e,t){return JSON.stringify({jsonrpc:`2.0`,id:b(`near-rpc`,32,`NEAR JSON-RPC request IDs`),method:e,params:t})}async postOnce(e,t){let n=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:t});if(!n.ok)throw this.errorFromHttpStatus(n);let r=await n.text();if(!r?.trim())throw Error(`Empty response from RPC server`);let i=Ce(JSON.parse(r));if(!i.ok)throw Error(`Invalid NEAR JSON-RPC response: ${i.error}`);return i.value}async requestWithFallback(e){let t;for(let[n,r]of this.rpcUrls.entries())try{let t=await this.postOnce(r,e);return n>0&&console.warn(`[NearClient] RPC succeeded via fallback: ${r}`),t}catch(e){t=e;let i=n<this.rpcUrls.length-1;if(console.warn(`[NearClient] RPC call to ${r} failed${i?`, trying next`:``}: ${j(e)||`RPC request failed`}`),!i)throw e instanceof Error?e:Error(String(e))}throw Error(j(t)||`RPC request failed`)}unwrapRpcResult(e,t){if(e.kind===`failure`)throw this.errorFromRpc(t,e.error);let n=e.result;if(typeof n==`object`&&n&&`error`in n){let e=Reflect.get(n,`error`),r=typeof e==`string`?e:JSON.stringify(e);throw this.errorFromWrappedResult(`${t} Error: ${r}`)}return e.result}async makeRpcCall(e,t,n,r){let i=this.buildRequestBody(e,t);try{let e=await this.requestWithFallback(i);return r(this.unwrapRpcResult(e,n))}catch(e){throw this.errorFromFailedCall(n,e)}}async query(e,t){return this.makeRpcCall(K.Query,e,`Query`,t)}async viewAccessKey(e,t,n){let r={request_type:`view_access_key`,finality:n?.finality||`final`,account_id:e,public_key:t};return this.makeRpcCall(K.Query,r,`View Access Key`,ge)}async viewAccessKeyList(e,t){let n={request_type:`view_access_key_list`,finality:t?.finality||`final`,account_id:e};return this.makeRpcCall(K.Query,n,`View Access Key List`,pe)}async viewAccount(e){let t={request_type:`view_account`,finality:`final`,account_id:e};return this.makeRpcCall(K.Query,t,`View Account`,le)}async viewCode(e,t){let n={request_type:`view_code`,finality:t?.finality||`final`,account_id:e};return v(await this.makeRpcCall(K.Query,n,`View Code`,he))}async viewBlock(e){return this.makeRpcCall(K.Block,e,`View Block`,ue)}async sendTransaction(e,t=`EXECUTED_OPTIMISTIC`){let n={signed_tx_base64:Tn(e),wait_until:t};return this.sendWithRetry(async()=>{let e=await this.makeRpcCall(K.Send,n,`Send Transaction`,fe),t=e.status;if(t&&typeof t==`object`&&`Failure`in t)throw this.errorFromOutcome(`Send Transaction`,e,t.Failure);return e})}async txStatus(e,t){let n={tx_hash:e,sender_account_id:t};return this.makeRpcCall(`EXPERIMENTAL_tx_status`,n,`Tx Status`,fe)}async callFunction(e,t,n,r,i){let a={request_type:`call_function`,...i??{finality:`final`},account_id:e,method_name:t,args_base64:g(new TextEncoder().encode(JSON.stringify(n)).buffer)};return r(de((await this.makeRpcCall(K.Query,a,`View Function`,me)).result))}async view(e){return this.callFunction(e.account,e.method,e.args,e.decodeResult)}async getAccessKeys({account:e,block_id:t}){let n={request_type:`view_access_key_list`,account_id:e,finality:`final`};t&&(n.block_id=t,delete n.finality);let r=await this.makeRpcCall(K.Query,n,`View Access Key List`,pe),i=[],a=[];for(let e of r.keys)e.access_key.permission===`FullAccess`?i.push(e):e.access_key.permission&&typeof e.access_key.permission==`object`&&`FunctionCall`in e.access_key.permission&&a.push(e);return{fullAccessKeys:i,functionCallAccessKeys:a}}};function Dn(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function On(e){if(!e)return;let t=Object.keys(e);return t.length?t[0]:void 0}var kn=class e extends Error{constructor(e){super(e.message),this.name=e.name||`NearRpcError`,this.code=e.code,this.type=e.type||`Unknown`,this.kind=e.kind,this.index=e.index,this.short=e.short,this.details=e.details,this.operation=e.operation}static fromOutcome(t,n,r){let{message:i,type:a,kind:o,index:s,short:c}=jn(t,r);return new e({message:i||`${t} failed`,short:c||o||`TxExecutionError`,type:a||`Failure`,kind:o,index:s,name:`TxExecutionFailure`,operation:t,details:{Failure:r,outcome:n}})}static fromRpcError(t,n){let r=n.data,{message:i,type:a,kind:o,index:s,short:c}=An(t,r,n.message);return new e({message:i||n.message||`${t} RPC error`,short:c||o||`RPC error`,type:a||`RpcError`,kind:o,index:s,code:typeof n.code==`number`?n.code:void 0,name:n.name||`NearRpcError`,operation:t,details:r})}};function An(e,t,n=``){let r=Dn(t)?t:void 0,i=Dn(r?.TxExecutionError)?r.TxExecutionError:void 0;if(!i){let i=typeof t==`string`&&t.trim()?t.trim():r?JSON.stringify(r):n.trim();return{message:`${e} RPC error${i?`: ${i}`:``}`}}return Mn(e,i)}function jn(e,t){let n=Dn(t)?t:void 0;return n?Mn(e,n):{message:`${e} failed (Unknown Failure)`}}function Mn(e,t){if(Dn(t.InvalidTxError)){let n=t.InvalidTxError,r=On(n)||`InvalidTxError`;Dn(n.ActionsValidation)&&(r=`ActionsValidation.${On(n.ActionsValidation)}`);let i=r.startsWith(`ActionsValidation.`)?`InvalidTxError: ${r.split(`.`)[1]||`ActionsValidation`}`:`InvalidTxError: ${r}`;return{message:`${e} failed (InvalidTxError: ${r})`,type:`InvalidTxError`,kind:r,short:i}}if(Dn(t.ActionError)){let n=t.ActionError,r=typeof n.index==`number`?n.index:void 0,i=On(Dn(n.kind)?n.kind:void 0)||`ActionError`,a=typeof r==`number`?` at action ${r}`:``,o=`ActionError: ${i}`;return{message:`${e} failed${a} (ActionError: ${i})`,type:`ActionError`,kind:i,index:r,short:o}}return{message:`${e} failed (TxExecutionError)`,type:`TxExecutionError`,kind:`TxExecutionError`,short:`TxExecutionError`}}var Nn=class e extends Cn{static fromPlain(t){return new e({transaction:t.transaction,signature:t.signature,borsh_bytes:t.borsh_bytes,...t.nonceLease?{nonceLease:t.nonceLease}:{},...t.serverDispatch?{serverDispatch:t.serverDispatch}:{}})}static decode(){throw Error(`SignedTransaction.decode(): borsh deserialization not implemented`)}},Pn=class extends En{errorFromRpc(e,t){return kn.fromRpcError(e,t)}errorFromWrappedResult(e){return new kn({message:e,short:`RpcError`,type:`RpcError`})}errorFromOutcome(e,t,n){return kn.fromOutcome(e,t,n)}errorFromHttpStatus(e){return e.status===429?Error(`RPC throttled; retry shortly`):super.errorFromHttpStatus(e)}async sendWithRetry(e){let t=null;for(let n=1;n<=5;n++)try{return await e()}catch(e){t=e;let r=j(e);if(!/server error|internal|temporar|timeout|throttl|too many requests|429|unavailable|bad gateway|gateway timeout/i.test(r||``)||n===5)throw e;let i=200*2**(n-1),a=Math.floor(Math.random()*150);await new Promise(e=>setTimeout(e,i+a))}throw t instanceof Error?t:Error(String(t))}};function Fn(e){try{return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,2)}catch{return String(e)}}function q(e,t,n){let r=String(t??``).trim();if(r)return{label:e,value:r,...typeof n==`string`&&n.trim()?{copyValue:n}:{}}}function In(e){switch(e.action_type){case W.Transfer:case W.FunctionCall:return BigInt(e.deposit||`0`);case W.Stake:return BigInt(e.stake||`0`);default:return BigInt(0)}}function Ln(e){try{let t=JSON.parse(e)?.permission;if(t===`FullAccess`)return`FullAccess`;if(t&&typeof t==`object`){if(`FullAccess`in t)return`FullAccess`;if(`FunctionCall`in t)return`FunctionCall`}}catch{return`Unknown`}return`Unknown`}function Rn(e){let{action:t,txIndex:n,actionIndex:r,receiverId:i}=e,a=`near.tx.${n}.action.${r}`;switch(t.action_type){case W.CreateAccount:return{id:a,kind:`near.action`,actionType:`createAccount`,label:`Action ${r+1}: CreateAccount`,fields:[q(`Receiver`,i)].filter(Boolean)};case W.Transfer:return{id:a,kind:`near.action`,actionType:`transfer`,label:`Action ${r+1}: Transfer`,fields:[q(`Receiver`,i),q(`Amount (yoctoNEAR)`,t.deposit)].filter(Boolean)};case W.FunctionCall:{let e=String(t.args||``),n=e?[{id:`${a}.args`,kind:`raw.fallback`,label:`Function Arguments`,raw:e}]:[];return{id:a,kind:`near.action`,actionType:`functionCall`,label:`Action ${r+1}: FunctionCall`,fields:[q(`Receiver`,i),q(`Method`,t.method_name),q(`Gas`,t.gas),q(`Deposit (yoctoNEAR)`,t.deposit)].filter(Boolean),...n.length?{children:n}:{}}}case W.Stake:return{id:a,kind:`near.action`,actionType:`stake`,label:`Action ${r+1}: Stake`,fields:[q(`Receiver`,i),q(`Stake (yoctoNEAR)`,t.stake),q(`Validator Key`,t.public_key,t.public_key)].filter(Boolean)};case W.AddKey:return{id:a,kind:`near.action`,actionType:`addKey`,label:`Action ${r+1}: AddKey`,fields:[q(`Receiver`,i),q(`Public Key`,t.public_key,t.public_key),q(`Permission`,Ln(t.access_key))].filter(Boolean)};case W.DeleteKey:return{id:a,kind:`near.action`,actionType:`deleteKey`,label:`Action ${r+1}: DeleteKey`,fields:[q(`Receiver`,i),q(`Public Key`,t.public_key,t.public_key)].filter(Boolean)};case W.DeployContract:return{id:a,kind:`near.action`,actionType:`deployContract`,label:`Action ${r+1}: DeployContract`,fields:[q(`Receiver`,i),q(`Code Bytes`,String(t.code?.length??0))].filter(Boolean)};case W.DeployGlobalContract:return{id:a,kind:`near.action`,actionType:`deployGlobalContract`,label:`Action ${r+1}: DeployGlobalContract`,fields:[q(`Receiver`,i),q(`Deploy Mode`,t.deploy_mode),q(`Code Bytes`,String(t.code?.length??0))].filter(Boolean)};case W.UseGlobalContract:return{id:a,kind:`near.action`,actionType:`useGlobalContract`,label:`Action ${r+1}: UseGlobalContract`,fields:[q(`Receiver`,i),q(`By Account`,t.account_id),q(`By Code Hash`,t.code_hash,t.code_hash)].filter(Boolean)};case W.DeleteAccount:return{id:a,kind:`near.action`,actionType:`deleteAccount`,label:`Action ${r+1}: DeleteAccount`,fields:[q(`Receiver`,i),q(`Beneficiary`,t.beneficiary_id)].filter(Boolean)};case W.SignedDelegate:return{id:a,kind:`near.action`,actionType:`signedDelegate`,label:`Action ${r+1}: SignedDelegate`,children:[{id:`${a}.delegate`,kind:`raw.fallback`,label:`Signed Delegate Payload`,raw:Fn(t)}]};default:return{id:a,kind:`raw.fallback`,label:`Action ${r+1}: Unsupported`,raw:Fn(t)}}}function zn(e,t,n){let r=String(e.receiverId||``).trim()||`(unknown receiver)`,i=Array.isArray(e.actions)?e.actions:[],a=i.reduce((e,t)=>e+In(t),BigInt(0)),o=[q(`Receiver`,r),q(`Action Count`,String(i.length)),q(`Attached Value (yoctoNEAR)`,a>0?a.toString():void 0)].filter(Boolean);return{id:`near.tx.${t}`,kind:`generic.contractCall`,label:n>1?`Transaction ${t+1}`:`Transaction`,to:r,value:a>0?a.toString():void 0,fields:o,children:i.map((e,n)=>Rn({action:e,txIndex:t,actionIndex:n,receiverId:r}))}}function Bn(e){let t=Array.isArray(e.txSigningRequests)?e.txSigningRequests:[],n=t.map((e,n)=>zn(e,n,t.length)),r=t.reduce((e,t)=>e+(Array.isArray(t.actions)?t.actions.reduce((e,t)=>e+In(t),BigInt(0)):BigInt(0)),BigInt(0));return{chain:`near`,intentDigest:e.intentDigest,signerAccount:e.signerAccount,title:e.title||`NEAR Transaction`,subtitle:e.subtitle,operations:n,...r>0?{totals:{nativeValue:r.toString(),nativeSymbol:`yoctoNEAR`}}:{}}}function Vn(e){let t={id:`near.message`,kind:`near.message`,label:`Message signature`,fields:[q(`Signer`,e.signerAccount,e.signerAccount),q(`Recipient`,e.recipient,e.recipient),{label:`Message`,value:e.message,copyValue:e.message,renderAs:`file-content`,hideChevron:!0}].filter(Boolean)};return{chain:`near`,intentDigest:e.intentDigest,signerAccount:e.signerAccount,title:e.title||`NEP-413 message`,subtitle:e.subtitle,operations:[t]}}function Hn(e){try{return Bn(e)}catch{return{chain:`near`,signerAccount:e.signerAccount,...e.title?{title:e.title}:{},...e.subtitle?{subtitle:e.subtitle}:{},operations:[]}}}async function Un(e){let t=P(e.nearAccount.accountId),n=Se(e.signerSlot,{min:1});if(n===null)throw Error(`Invalid signerSlot for ${e.operationLabel}: ${e.signerSlot}`);if(e.requestedSignerSlot!==void 0){let t=Se(e.requestedSignerSlot,{min:1});if(t===null||t!==n)throw Error(`Requested signerSlot does not match the selected signing lane for ${e.operationLabel}`)}let r=await e.materialExecutor.resolveSigningKeyMaterial();if(r.nearAccountId!==t||r.signerSlot!==n)throw Error(`[SigningEngine] threshold key material does not match the selected lane`);return{thresholdKeyMaterial:r}}function Wn(e){let t=Kn({nearAccountId:e.nearAccountId,tx:e.transaction,txIndex:0});return{txSigningRequest:t,confirmationTransaction:{receiverId:t.receiverId,actions:t.actions}}}function Gn(e){let t=e.delegate.actions.map(et);t.forEach((e,t)=>{try{Ze(e)}catch(e){throw Error(`Delegate action ${t} validation failed: ${e instanceof Error?e.message:String(e)}`)}});let n={senderId:e.delegate.senderId||e.nearAccountId,receiverId:e.delegate.receiverId,actions:t,nonce:e.delegate.nonce,maxBlockHeight:e.delegate.maxBlockHeight};return{confirmationDelegate:n,workerDelegate:{...n,nonce:e.delegate.nonce.toString(),maxBlockHeight:e.delegate.maxBlockHeight.toString(),publicKey:e.signingPublicKey}}}function Kn(e){let t=String(e.tx?.receiverId||``).trim();if(!t)throw Error(`[SigningEngine] transactions[${e.txIndex}].receiverId is required`);let n=Array.isArray(e.tx?.actions)?e.tx.actions:[];if(n.length===0)throw Error(`[SigningEngine] transactions[${e.txIndex}].actions must be non-empty`);for(let e=0;e<n.length;e++)Ze(n[e]);return{nearAccountId:e.nearAccountId,receiverId:t,actions:n}}async function qn(e){return Zn({kind:`near:transactions_with_actions:planning`,payload:{purpose:`near_transaction`,...Qn(e),transactions:$n(e.transactions)}})}async function Jn(e){return Zn({kind:`near:transactions_with_actions`,payload:{purpose:`near_transaction`,...Qn(e),transactions:$n(e.transactions),unsignedTransactionBorshB64u:l(e.unsignedTransactionBorshB64u,`unsignedTransactionBorshB64u`),signingDigestB64u:l(e.signingDigestB64u,`signingDigestB64u`)}})}async function Yn(e){return Zn({kind:`near:nep413`,payload:{purpose:`nep413_message`,...Qn(e),message:l(e.message,`message`),recipient:l(e.recipient,`recipient`),nonce:l(e.nonce,`nonce`),callbackUrl:e.callbackUrl}})}async function Xn(e){return Zn({kind:`near:delegate_action`,payload:{purpose:`delegate_action`,...Qn(e),delegate:er(e.delegate)}})}async function Zn(e){return`sha256:${h(await p(c({kind:l(e.kind,`kind`),payload:pr(e.payload)})))}`}function Qn(e){return{nearAccountId:l(e.nearAccountId,`nearAccountId`),nearNetworkId:l(e.nearNetworkId,`nearNetworkId`),relayerKeyId:l(e.relayerKeyId,`relayerKeyId`),signerPublicKey:l(e.signerPublicKey,`signerPublicKey`)}}function $n(e){if(!Array.isArray(e)||e.length<1)throw Error(`transactions must be a non-empty array`);return e.map((e,t)=>tr(e,`transactions[${t}]`))}function er(e){return{senderId:l(e.senderId,`delegate.senderId`),receiverId:l(e.receiverId,`delegate.receiverId`),actions:nr(e.actions,`delegate.actions`),nonce:l(e.nonce,`delegate.nonce`),maxBlockHeight:l(e.maxBlockHeight,`delegate.maxBlockHeight`),publicKey:l(e.publicKey,`delegate.publicKey`)}}function tr(e,t){let n=u(e,t);return{nearAccountId:l(n.nearAccountId,`${t}.nearAccountId`),receiverId:l(n.receiverId,`${t}.receiverId`),actions:nr(n.actions,`${t}.actions`)}}function nr(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e.map((e,n)=>rr(e,`${t}[${n}]`))}function rr(e,t){let n=u(e,t),r=l(n.action_type,`${t}.action_type`);switch(r){case`CreateAccount`:return{action_type:r};case`DeployContract`:return{action_type:r,code:cr(n.code,`${t}.code`)};case`FunctionCall`:return{action_type:r,method_name:l(n.method_name,`${t}.method_name`),args:l(n.args,`${t}.args`),gas:l(n.gas,`${t}.gas`),deposit:l(n.deposit,`${t}.deposit`)};case`Transfer`:return{action_type:r,deposit:l(n.deposit,`${t}.deposit`)};case`Stake`:return{action_type:r,stake:l(n.stake,`${t}.stake`),public_key:l(n.public_key,`${t}.public_key`)};case`AddKey`:return{action_type:r,public_key:l(n.public_key,`${t}.public_key`),access_key:l(n.access_key,`${t}.access_key`)};case`DeleteKey`:return{action_type:r,public_key:l(n.public_key,`${t}.public_key`)};case`DeleteAccount`:return{action_type:r,beneficiary_id:l(n.beneficiary_id,`${t}.beneficiary_id`)};case`SignedDelegate`:return{action_type:r,delegate_action:ir(n.delegate_action,`${t}.delegate_action`),signature:or(n.signature,`${t}.signature`)};case`DeployGlobalContract`:return{action_type:r,code:cr(n.code,`${t}.code`),deploy_mode:dr(n.deploy_mode,`${t}.deploy_mode`)};case`UseGlobalContract`:return sr(n,t)}throw Error(`${t}.action_type is unsupported`)}function ir(e,t){let n=u(e,t);return{senderId:l(n.senderId,`${t}.senderId`),receiverId:l(n.receiverId,`${t}.receiverId`),actions:nr(n.actions,`${t}.actions`),nonce:ur(n.nonce,`${t}.nonce`),maxBlockHeight:ur(n.maxBlockHeight,`${t}.maxBlockHeight`),publicKey:ar(n.publicKey,`${t}.publicKey`)}}function ar(e,t){let n=u(e,t);return{keyType:lr(n.keyType,`${t}.keyType`),keyData:cr(n.keyData,`${t}.keyData`)}}function or(e,t){let n=u(e,t);return{keyType:lr(n.keyType,`${t}.keyType`),signatureData:cr(n.signatureData,`${t}.signatureData`)}}function sr(e,t){let n=fr(e.account_id),r=fr(e.code_hash);if(n&&r)throw Error(`${t} requires exactly one of account_id or code_hash`);if(n)return{action_type:`UseGlobalContract`,account_id:n};if(r)return{action_type:`UseGlobalContract`,code_hash:r};throw Error(`${t} requires exactly one of account_id or code_hash`)}function cr(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e.map((e,n)=>{if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>255)throw Error(`${t}[${n}] must be a byte`);return e})}function lr(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e))throw Error(`${t} must be a safe integer`);return e}function ur(e,t){return typeof e==`bigint`||typeof e==`number`&&Number.isSafeInteger(e)?e:l(e,t)}function dr(e,t){let n=l(e,t);if(n===`CodeHash`||n===`AccountId`)return n;throw Error(`${t} is invalid`)}function fr(e){return String(e||``).trim()||null}function pr(e){if(typeof e==`bigint`)return e.toString(10);if(e instanceof Uint8Array)return{__bytesB64u:h(e)};if(ArrayBuffer.isView(e))return{__bytesB64u:h(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))};if(e instanceof ArrayBuffer)return{__bytesB64u:h(new Uint8Array(e))};if(Array.isArray(e))return e.map(pr);if(!e||typeof e!=`object`)return e;let t={};for(let n of Object.keys(e).sort()){let r=pr(e[n]);r!==void 0&&(t[n]=r)}return t}async function mr(e){if(St(e.signingAuthPlan)&&!e.emailOtpEd25519StepUp)throw Error(`[SigningEngine][near] Email OTP step-up runner is unavailable`);if(xt(e.signingAuthPlan)&&!e.passkeyEd25519OperationStepUp)throw Error(`[SigningEngine][near] Passkey operation step-up runner is unavailable`);let t=null,n=await Nt({operation:{kind:`near_ed25519_step_up`,requiredSignatureUses:e.requiredSignatureUses},selectedLane:{authMethod:B(e.signingLaneAuth)},policy:yr(e.signingAuthPlan),methods:{...e.emailOtpEd25519StepUp?{emailOtp:{method:`email_otp`,prepareChallenge:async()=>await e.emailOtpEd25519StepUp.prepare({operationFingerprintDigest:e.operationFingerprintDigest}),...e.emailOtpEd25519StepUp.resend?{resendChallenge:async()=>await e.emailOtpEd25519StepUp.resend({operationFingerprintDigest:e.operationFingerprintDigest})}:{},complete:gr}}:{},passkey:{method:`passkey`,prepare:async()=>{if(!e.passkeyEd25519OperationStepUp)throw Error(`[SigningEngine][near] Passkey operation step-up runner is unavailable`);return t=await e.passkeyEd25519OperationStepUp.prepare(),{}},complete:_r}}}),r=e.signingAuthPlan;if(n.method===`warm_session`){if(!br(r))throw Error(`[SigningEngine][near] warm-session step-up requires a warm-session plan`);return{kind:`warm_session`,confirmationAuthPayload:{signingAuthPlan:r}}}if(n.method===`email_otp`){if(!St(r))throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP plan`);return{kind:`email_otp`,confirmationAuthPayload:{signingAuthPlan:{kind:`emailOtpReauth`,method:`email_otp`,emailOtpPrompt:n.prompt}},emailOtpPrompt:n.prompt}}if(!xt(r))throw Error(`[SigningEngine][near] passkey step-up requires a passkey plan`);return{kind:`passkey`,confirmationAuthPayload:{signingAuthPlan:r},plannedPasskeyOperationStepUp:vr(t)}}function hr(e){switch(e.kind){case`passkey`:return{kind:`passkeyReauth`,method:`passkey`};case`email_otp`:return{kind:`emailOtpReauth`,method:`email_otp`};default:throw Error(`[SigningEngine][near] unsupported material auth requirement`)}}async function gr(){}async function _r(){}function vr(e){if(!e)throw Error(`[SigningEngine][near] Passkey operation step-up plan is required`);return e}function yr(e){if(bt(e)){if(e.curve!==`ed25519`)throw Error(`[SigningEngine][near] warm-session step-up requires an Ed25519 auth plan`);return{kind:`reuse_warm_session`,authorization:{method:e.method,curve:`ed25519`,thresholdSessionId:e.thresholdSessionId,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses}}}return{kind:`use_selected_lane`}}function br(e){return bt(e)&&e.curve===`ed25519`}function xr(e,t,n){try{e?.(xe({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function Sr(e,t){let n=Mt(e.signingAuthPlan);if(t.phase===`confirmation.complete`){if(n===`passkey`&&t.status===`succeeded`)return}else if(n!==`passkey`||t.phase!==`auth.passkey.prompt.started`&&t.phase!==`auth.passkey.prompt.succeeded`)return;let r=jt(t,n);r&&xr(e.onEvent,e.nearAccountId,{...r,authMethod:n})}function Cr(e){return{kind:`warm_session`,signingAuthPlan:e,thresholdSessionId:e.thresholdSessionId,expiresAtMs:e.expiresAtMs,remainingUses:e.remainingUses}}function wr(e){if(e.prepared.kind===`warm_session`)return Cr(e.prepared.confirmationAuthPayload.signingAuthPlan);if(e.prepared.kind===`email_otp`)return{kind:`email_otp`,signingAuthPlan:e.prepared.confirmationAuthPayload.signingAuthPlan,challengeId:Er(e.confirmation.emailOtpChallengeId,e.prepared.emailOtpPrompt.challengeId),otpCode:Tr(e.confirmation.otpCode),...e.prepared.emailOtpPrompt.emailHint?{emailHint:e.prepared.emailOtpPrompt.emailHint}:{}};if(!e.confirmation.credential)throw Error(`[SigningEngine] missing WebAuthn credential for NEAR step-up authorization`);return{kind:`passkey`,signingAuthPlan:e.prepared.confirmationAuthPayload.signingAuthPlan,credential:je(e.confirmation.credential),plannedPasskeyOperationStepUp:e.prepared.plannedPasskeyOperationStepUp}}function Tr(e){let t=String(e||``).trim();if(!/^\d{6}$/.test(t))throw Error(`[SigningEngine] missing Email OTP code for NEAR step-up authorization`);return t}function Er(e,t){let n=String(e||t||``).trim();if(!n)throw Error(`[SigningEngine] missing Email OTP challenge id for NEAR step-up authorization`);return n}function Dr(e){if(!e||!Array.isArray(e.actions)||e.actions.length===0)throw Error(`[SigningEngine][near] one NEAR transaction with actions is required`);return 1}function Or(e){throw Error(`[SigningEngine][near] exactly one NEAR transaction is supported per signing operation; received ${e.length}`)}const kr=2e4;async function Ar(e){return Lr(await nt({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Wt.ThresholdEd25519ComputeNep413SigningDigest,timeoutMs:kr,payload:{message:e.message,recipient:e.recipient,nonce:e.nonce,callbackUrl:e.callbackUrl}}}))}async function jr(e){return Lr(await nt({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Wt.ThresholdEd25519ComputeDelegateSigningDigest,timeoutMs:kr,payload:{delegate:e.delegate}}}))}async function Mr(e){return Rr(await nt({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Wt.ThresholdEd25519BuildDelegateSigningPayload,timeoutMs:kr,payload:{delegate:e.delegate}}}))}async function Nr(e){return zr(await nt({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Wt.ThresholdEd25519FinalizeDelegateFromSignature,timeoutMs:kr,payload:{delegate:e.delegate,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u}}}))}async function Pr(e){let t=Br(await nt({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Wt.ThresholdEd25519BuildNearTxUnsignedBorsh,timeoutMs:kr,payload:{txSigningRequests:[e.txSigningRequest],transactionContext:e.transactionContext}}})),n=t[0];if(!n||t.length!==1)throw Error(`near signer worker returned invalid single-transaction unsigned payload`);return n}async function Fr(e){return Vr(await nt({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Wt.ThresholdEd25519FinalizeNearTxFromSignature,timeoutMs:kr,payload:{unsignedTransactionBorshB64u:e.unsignedTransactionBorshB64u,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u,expectedNearAccountId:e.expectedNearAccountId,expectedSignerPublicKey:e.expectedSignerPublicKey}}}))}async function Ir(e){return Hr(await nt({ctx:e.workerCtx,kind:`nearSigner`,request:{type:Wt.ThresholdEd25519DecodeSignedNearTxBorsh,timeoutMs:kr,payload:{signedTransactionBorshB64u:e.signedTransactionBorshB64u}}}))}function Lr(e){let t=e;if(!t?.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 signing digest result`);return t}function Rr(e){let t=e;if(!t?.canonicalDelegateBorshB64u||!t.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 delegate signing payload`);return t}function zr(e){let t=e;if(!t?.delegateAction||!t.signature||!t.borshBytes)throw Error(`near signer worker returned invalid Ed25519 signed delegate result`);return t}function Br(e){if(!Array.isArray(e))throw Error(`near signer worker returned invalid Ed25519 unsigned tx result`);return e.map(e=>{let t=e;if(!t?.unsignedTransactionBorshB64u||!t.signingDigestB64u)throw Error(`near signer worker returned invalid Ed25519 unsigned tx item`);return t})}function Vr(e){let t=e;if(!t?.signedTransactionBorshB64u||!t.transactionHash)throw Error(`near signer worker returned invalid Ed25519 finalized tx result`);return t}function Hr(e){let t=e;if(!t?.signedTransaction?.transaction||!t.signedTransaction.signature||!t.signedTransaction.borshBytes||!t.transactionHash)throw Error(`near signer worker returned invalid Ed25519 signed tx decode result`);return t}function Ur(e,t){return e.request_id===t.request_id&&e.account_id===t.account_id&&e.authorization.kind===t.authorization.kind&&(e.authorization.kind===`reusable_wallet_session`?t.authorization.kind===`reusable_wallet_session`&&e.authorization.wallet_session_id===t.authorization.wallet_session_id:t.authorization.kind===`operation_step_up`)&&e.material_activation.kind===t.material_activation.kind&&e.material_activation.activation_id===t.material_activation.activation_id&&e.material_activation.capability===t.material_activation.capability&&e.material_activation.material_owner===t.material_activation.material_owner&&e.material_activation.key_binding===t.material_activation.key_binding&&e.material_activation.lifecycle_binding===t.material_activation.lifecycle_binding&&e.material_activation.signing_worker===t.material_activation.signing_worker&&e.signing_worker_id===t.signing_worker_id}function Wr(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Gr(e){if(!Ur(e.request.scope,e.response.scope))throw Error(`Router A/B normal-signing prepare response scope mismatch`);if(e.request.expires_at_ms!==e.response.expires_at_ms)throw Error(`Router A/B normal-signing prepare response expiry mismatch`);if(e.response.signing_worker.server_id!==e.request.scope.signing_worker_id)throw Error(`Router A/B normal-signing prepare response SigningWorker mismatch`);if(!Wr(e.signingPayloadDigest.bytes,e.response.signing_payload_digest.bytes))throw Error(`Router A/B normal-signing prepare response payload digest mismatch`)}function Kr(e){if(!Ur(e.request.scope,e.response.scope))throw Error(`Router A/B normal-signing response scope mismatch`);if(e.response.signing_worker.server_id!==e.request.scope.signing_worker_id)throw Error(`Router A/B normal-signing response SigningWorker mismatch`);if(!Wr(e.signingPayloadDigest.bytes,e.response.signing_payload_digest.bytes))throw Error(`Router A/B normal-signing response payload digest mismatch`);if(e.response.signature.bytes.length!==64)throw Error(`Router A/B normal-signing response signature must be 64 bytes`)}function J(e,t){let n=String(e||``).trim();if(!n)throw Error(`Router A/B Ed25519 normal-signing ready state is missing ${t}`);return n}function Y(e,t,n){if(e!==t)throw Error(`Router A/B Ed25519 normal-signing ready state ${n} mismatch`)}function qr(e,t){let n=Math.floor(Number(e));if(!Number.isFinite(n)||n<=Date.now())throw Error(`Router A/B Ed25519 normal-signing ready state ${t} is expired`);return n}function Jr(e,t){let n=Math.floor(Number(e));if(!Number.isSafeInteger(n)||n<=0)throw Error(`Router A/B Ed25519 normal-signing ready state ${t} is exhausted`);return n}function Yr(e){let t=e.state,n=t.signingWalletSession,r=J(e.thresholdSessionId,`thresholdSessionId`),i=J(t.thresholdSessionId,`state.thresholdSessionId`),a=J(t.signingLane.thresholdSessionId,`state.signingLane.thresholdSessionId`);Y(i,r,`thresholdSessionId`),Y(a,r,`lane thresholdSessionId`);let o=J(t.walletSessionId,`state.walletSessionId`),s=J(t.quotaId,`state.quotaId`);Y(t.signingLane.walletSessionId,o,`lane walletSessionId`),Y(t.signingLane.quotaId,s,`lane quotaId`);let c=J(e.nearAccountId,`nearAccountId`);J(t.signingLane.identity.signer.account.wallet.walletId,`state.signingLane.identity.signer.account.wallet.walletId`),Y(J(e.thresholdKeyMaterial.nearAccountId,`thresholdKeyMaterial.nearAccountId`),c,`threshold key accountId`);let l=n.routerAbNormalSigning,u=J(n.auth.walletSessionToken,`Wallet Session bearer token`),d=J(t.signingRootId,`state.signingRootId`),f=J(t.signingRootVersion,`state.signingRootVersion`);Y(n.thresholdSessionId,r,`Wallet Session thresholdSessionId`),Y(n.walletSessionId,o,`Wallet Session walletSessionId`),Y(n.quotaId,s,`Wallet Session quotaId`),Y(n.signingRootId,d,`signingRootId`),Y(n.signingRootVersion,f,`signingRootVersion`),Y(t.routerAbNormalSigning.signingWorkerId,l.signingWorkerId,`signingWorkerId`),qr(n.expiresAtMs,`expiresAtMs`);let p=Jr(n.remainingUses,`remainingUses`);if(t.remainingUses!==p)throw Error(`Router A/B Ed25519 normal-signing ready state remainingUses mismatch`);return{kind:`router_ab_ed25519_normal_signing_ready_state_v1`,relayerUrl:J(t.relayerUrl,`relayerUrl`),signingWorkerId:J(l.signingWorkerId,`signingWorkerId`),signerPublicKey:J(e.thresholdKeyMaterial.publicKey,`signerPublicKey`),credential:{kind:`wallet_session_opaque`,walletSessionToken:u,home:n.auth.credential.home}}}function Xr(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`operation step-up preparation ref must be an object`);let t=e;if(Object.keys(t).length!==3||t.kind!==`near_operation_step_up_prepared_v1`)throw Error(`operation step-up preparation ref is invalid`);let n=String(t.handle||``).trim();if(!n.startsWith(`near-operation-step-up:`)||/\s/.test(n))throw Error(`operation step-up preparation handle is invalid`);return{kind:`near_operation_step_up_prepared_v1`,handle:n,challengeB64u:A(t.challengeB64u)}}const Zr=new Map,Qr=new Map;function $r(e,t){let n=String(e||``).trim();if(!n)throw Error(`[SigningEngine][near] ${t} is required`);return n}function ei(e){Zr.set($r(e.requestId,`requestId`),e.build)}function ti(e){Zr.delete(String(e||``).trim())}const ni={async prepare(e){let t=$r(e.requestId,`requestId`),n=Zr.get(t);if(!n)throw Error(`[SigningEngine][near] operation step-up preparation is unavailable`);Zr.delete(t);let r=e.kind===`near_transaction`?await n({kind:`near_transaction`,transactionContext:e.transactionContext,operationId:$r(e.operationId,`operationId`),operationFingerprint:$r(e.operationFingerprint,`operationFingerprint`),displayDigest:$r(e.displayDigest,`displayDigest`)}):await n({kind:`near_signature_only`,displayDigest:$r(e.displayDigest,`displayDigest`)}),i=await We(r.envelope),a=Xr({kind:`near_operation_step_up_prepared_v1`,handle:`near-operation-step-up:${y(24,`operation step-up handle`)}`,challengeB64u:i});return Qr.set(a.handle,{requestId:t,operation:r.operation}),a},cancel(e){let t=String(e.requestId||``).trim();t&&Zr.delete(t),e.handle&&Qr.delete(e.handle);for(let[e,n]of Qr)n.requestId===t&&Qr.delete(e)}};function ri(e){let t=$r(e.requestId,`requestId`),n=$r(Xr(e.ref).handle,`operation step-up handle`),r=Qr.get(n);if(Qr.delete(n),!r||r.requestId!==t)throw Error(`[SigningEngine][near] prepared operation step-up is unavailable`);return r.operation}function ii(e){if(!n(e.expected,e.actual))throw Error(`[SigningEngine][near] operation assertion changed material activation`)}const ai=12e4;async function oi(e){return await e.ctx.resolveOperationStepUpCredential({walletId:e.walletId,relayerUrl:e.relayerUrl,proof:e.proof})}function si(e){if(e.prepared.prepare.request.scope.authorization.kind!==`operation_step_up`)throw Error(`[SigningEngine][near] operation step-up authorization scope is missing`);if(e.issuedAuthorization.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] operation step-up authorization is invalid`)}function ci(e){let t=e.thresholdKeyMaterial.participants.find(t=>t.role===e.role)?.id;if(!t)throw Error(`threshold-ed25519 signing requires ${e.role} participant id`);return t}function li(e){return[..._(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function ui(e){return s(e.chains||mt.network.chains)}function di(e){let t=globalThis.crypto;if(t&&typeof t.randomUUID==`function`)return`router-ab-normal-signing/${e}/${t.randomUUID()}`;if(t&&typeof t.getRandomValues==`function`){let n=new Uint8Array(16);return t.getRandomValues(n),`router-ab-normal-signing/${e}/${h(n)}`}throw Error(`secure randomness is unavailable for Router A/B normal-signing request id`)}function fi(e){if(!e.ok)throw Error(e.error.message);return e.value}function pi(e){let t=Math.floor(Number(e.walletSessionExpiresAtMs)),n=Math.floor(Number(e.requestedTtlMs));if(!Number.isFinite(t)||t<=Date.now())throw Error(`[SigningEngine][near] Router A/B Ed25519 Wallet Session is expired`);if(!Number.isFinite(n)||n<=0)throw Error(`[SigningEngine][near] Router A/B Ed25519 request TTL is invalid`);return Math.min(t,Date.now()+n)}function mi(e){let t=e.walletSessionState.routerAbNormalSigning;if(!t)return null;let n=String(e.walletId||``).trim();if(!n)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing wallet id`);let r=Re(e.activeClient.metadata());return{request_id:di(e.operationId),account_id:n,authorization:{kind:`reusable_wallet_session`,wallet_session_id:e.walletSessionState.walletSessionId},material_activation:{kind:`mpc_material_activation_ref`,activation_id:r.activationId,capability:r.capability,material_owner:r.materialOwner,key_binding:r.keyBinding,lifecycle_binding:r.lifecycleBinding,signing_worker:r.signingWorker},signing_worker_id:t.signingWorkerId}}function hi(e){let t=e.materialFacts.routerAbNormalSigning;if(!t)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing`);return{request_id:di(e.operationId),account_id:String(e.walletId),authorization:{kind:`operation_step_up`},material_activation:{kind:`mpc_material_activation_ref`,activation_id:e.materialActivation.activationId,capability:e.materialActivation.capability,material_owner:e.materialActivation.materialOwner,key_binding:e.materialActivation.keyBinding,lifecycle_binding:e.materialActivation.lifecycleBinding,signing_worker:e.materialActivation.signingWorker},signing_worker_id:t.signingWorkerId}}function gi(e){return e.map(e=>{switch(e.action_type){case`CreateAccount`:return{action_type:W.CreateAccount};case`DeployContract`:return{action_type:W.DeployContract,code:[...e.code]};case`FunctionCall`:return{action_type:W.FunctionCall,method_name:e.method_name,args:e.args,gas:e.gas,deposit:e.deposit};case`Transfer`:return{action_type:W.Transfer,deposit:e.deposit};case`Stake`:return{action_type:W.Stake,stake:e.stake,public_key:e.public_key};case`AddKey`:return{action_type:W.AddKey,public_key:e.public_key,access_key:e.access_key};case`DeleteKey`:return{action_type:W.DeleteKey,public_key:e.public_key};case`DeleteAccount`:return{action_type:W.DeleteAccount,beneficiary_id:e.beneficiary_id};case`SignedDelegate`:{let t=gi(e.delegate_action.actions).map($e);return{action_type:W.SignedDelegate,delegate_action:{senderId:e.delegate_action.senderId,receiverId:e.delegate_action.receiverId,actions:t,nonce:e.delegate_action.nonce,maxBlockHeight:e.delegate_action.maxBlockHeight,publicKey:{keyType:e.delegate_action.publicKey.keyType,keyData:[...e.delegate_action.publicKey.keyData]}},signature:{keyType:e.signature.keyType,signatureData:[...e.signature.signatureData]}}}case`DeployGlobalContract`:return{action_type:W.DeployGlobalContract,code:[...e.code],deploy_mode:e.deploy_mode};case`UseGlobalContract`:return`account_id`in e?{action_type:W.UseGlobalContract,account_id:e.account_id}:{action_type:W.UseGlobalContract,code_hash:e.code_hash}}})}async function _i(e){return{signedDelegate:await Nr({delegate:e.delegate,signingDigestB64u:e.signingDigestB64u,signatureB64u:e.signatureB64u,workerCtx:e.ctx}),hash:li(e.signingDigestB64u)}}function X(e,t,n){if(String(e)!==String(t))throw Error(`Router A/B Ed25519 active Client ${n} mismatch`)}function vi(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e[r]^t[r];return n===0}function yi(e,t){if(e.length!==32||e.some(e=>!Number.isInteger(e)||e<0||e>255))throw Error(`Router A/B normal-signing ${t} must contain 32 bytes`);return Uint8Array.from(e)}function bi(e){let t=N(e);if(!t.startsWith(`ed25519:`))throw Error(`Router A/B Ed25519 signer public key must use ed25519`);let n=F(t.slice(8));if(n.length!==32)throw Error(`Router A/B Ed25519 signer public key must decode to 32 bytes`);return n}function xi(e){let t=e.activeClient.metadata(),n=Re(t),r=e.materialFacts.signer,i=ci({thresholdKeyMaterial:e.thresholdKeyMaterial,role:`client`}),a=ci({thresholdKeyMaterial:e.thresholdKeyMaterial,role:`relayer`});if(e.thresholdKeyMaterial.participants.length!==2)throw Error(`Router A/B Ed25519 active Client requires exactly two participants`);X(t.scope.account_id,e.prepare.request.scope.account_id,`scope account`),X(t.scope.threshold_session_id,e.materialFacts.thresholdSessionId,`threshold session`),X(t.scope.account_id,e.walletId,`scope wallet`),X(n.activationId,e.prepare.request.scope.material_activation.activation_id,`material activation`),X(n.capability,e.prepare.request.scope.material_activation.capability,`material capability`),X(n.materialOwner,e.prepare.request.scope.material_activation.material_owner,`material owner`),X(n.keyBinding,e.prepare.request.scope.material_activation.key_binding,`material key binding`),X(n.lifecycleBinding,e.prepare.request.scope.material_activation.lifecycle_binding,`material lifecycle`),X(n.signingWorker,e.prepare.request.scope.material_activation.signing_worker,`material SigningWorker`);let o=e.prepare.request.scope.authorization;if(o.kind!==e.authorization.kind)throw Error(`Router A/B Ed25519 authorization kind mismatch`);switch(e.authorization.kind){case`reusable_wallet_session`:if(o.kind!==`reusable_wallet_session`)throw Error(`Router A/B Ed25519 reusable authorization is missing`);X(o.wallet_session_id,e.authorization.walletSessionId,`authorization session`);break;case`operation_step_up`:if(o.kind!==`operation_step_up`)throw Error(`Router A/B Ed25519 operation step-up authorization is missing`);break;default:e.authorization}X(t.scope.signing_worker_id,e.prepare.request.scope.signing_worker_id,`scope SigningWorker`),X(t.scope.signing_worker_id,e.signingWorkerId,`prepare SigningWorker`),X(t.applicationBinding.wallet_id,e.walletId,`application wallet`),X(t.applicationBinding.wallet_id,r.account.wallet.walletId,`lane wallet`),X(t.applicationBinding.near_ed25519_signing_key_id,r.nearEd25519SigningKeyId,`signing key`),X(t.applicationBinding.signing_root_id,e.materialFacts.signingRootId,`signing root`),X(t.applicationBinding.key_creation_signer_slot,r.signerSlot,`signer slot`),X(t.applicationBinding.key_creation_signer_slot,e.thresholdKeyMaterial.signerSlot,`key-material signer slot`),X(t.participantIds[0],i,`Client participant`),X(t.participantIds[1],a,`SigningWorker participant`);let s=bi(e.thresholdKeyMaterial.publicKey);if(!vi(t.registeredPublicKey,s))throw Error(`Router A/B Ed25519 active Client registered public key mismatch`);if(!vi(t.signingWorkerVerifyingShare,e.signingWorkerVerifyingShare))throw Error(`Router A/B Ed25519 active Client SigningWorker verifying share mismatch`)}async function Si(e){let t=e.prepare.request.intent.operation_id,n=performance.now(),r=`failed`;try{let n=await Ci(e,t);return r=`succeeded`,n}finally{U(t,`signature_total`,n,r)}}async function Ci(e,t){let n=_(e.signingDigestB64u);if(n.length!==32)throw Error(`Router A/B normal-signing ${e.signingPayloadLabel} must be 32 bytes`);let r=yi(e.prepare.admissionMaterial.admittedSigningDigest.bytes,`admitted digest`);if(!vi(n,r))throw Error(`Router A/B normal-signing admitted digest mismatch`);e.authorization===`reusable_wallet_session`&&Yr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial});let i=e.authorization===`reusable_wallet_session`?{thresholdSessionId:e.walletSessionState.thresholdSessionId,signer:e.walletSessionState.signingLane.identity.signer,signingRootId:e.walletSessionState.signingRootId,signingRootVersion:e.walletSessionState.signingRootVersion,routerAbNormalSigning:e.walletSessionState.routerAbNormalSigning,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,relayerUrl:e.walletSessionState.relayerUrl}:e.materialFacts,a=performance.now(),o=e.startedResponse?await e.startedResponse:await ft({relayServerUrl:i.relayerUrl,credential:e.credential,request:e.prepare.request});if(U(t,`prepare`,a),e.authorization===`reusable_wallet_session`){if(o.kind!==`reusable_wallet_session`)throw Error(`Ed25519 prepare returned the wrong authorization kind`);let t=await e.sessionCoordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:e.walletSessionState,nowMs:Date.now()}),n=o.sessionStatus;if(!t||n.walletSessionId!==t.walletSessionOperationCredential.walletSessionId||n.quotaId!==t.walletSessionAuthorization.quotaId||n.quotaLifecycle!==`active`||n.remainingUses<=0||n.expiresAtMs<=Date.now()||!ne(n.authorization,t.walletSessionAuthorization))throw Error(`Wallet Session authority changed before Ed25519 client signing`);let r={relayerUrl:i.relayerUrl,operationCredential:t.walletSessionOperationCredential};await Ue.fromPrepare(r,n).read(r,{walletSessionId:n.walletSessionId,quotaId:n.quotaId})}else if(o.kind!==`operation_step_up`)throw Error(`Ed25519 step-up prepare returned a reusable Wallet Session`);let s=o.signing;Gr({request:e.prepare.request,signingPayloadDigest:e.prepare.admissionMaterial.signingPayloadDigest,response:s});let c=_(s.server_verifying_share_b64u);if(c.length!==32)throw Error(`Router A/B normal-signing SigningWorker verifying share must be 32 bytes`);xi({activeClient:e.activeClient,authorization:e.authorization===`reusable_wallet_session`?{kind:`reusable_wallet_session`,walletSessionId:e.walletSessionState.signingWalletSession.walletSessionId}:{kind:`operation_step_up`},materialFacts:i,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,prepare:e.prepare,signingWorkerId:s.signing_worker.server_id,signingWorkerVerifyingShare:c});let l=performance.now(),u=await e.activeClient.createSigningShare({admittedDigest:r,signingWorkerCommitments:s.server_commitments,signingWorkerVerifyingShare:c});if(U(t,`client_share`,l),u.clientVerifyingShare.length!==32)throw Error(`Router A/B normal-signing Client verifying share must be 32 bytes`);let d=performance.now(),f=await gt({relayServerUrl:i.relayerUrl,credential:e.credential,request:lt({scope:e.prepare.request.scope,expiresAtMs:e.prepare.request.expires_at_ms,prepareResponse:s,admissionMaterial:e.prepare.admissionMaterial,clientCommitments:u.clientCommitments,clientVerifyingShareB64u:h(u.clientVerifyingShare),clientSignatureShareB64u:u.clientSignatureShareB64u})});return U(t,`finalize`,d),Kr({request:e.prepare.request,signingPayloadDigest:e.prepare.admissionMaterial.signingPayloadDigest,response:f}),{signatureB64u:_t(f.signature,`Router A/B normal-signing signature`),signerPublicKey:e.thresholdKeyMaterial.publicKey}}async function wi(e){let t=ui(e.ctx);return e.intent.kind===`nep413_message_v1`?await dt({scope:e.scope,expiresAtMs:e.expiresAtMs,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:t,message:e.intent.message,recipient:e.intent.recipient,nonce:e.intent.nonce,callbackUrl:e.intent.callbackUrl,expectedSigningDigestB64u:e.signingDigestB64u}):await pt({scope:e.scope,expiresAtMs:e.expiresAtMs,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:t,delegate:{senderId:e.intent.delegate.senderId,receiverId:e.intent.delegate.receiverId,publicKey:e.intent.delegate.publicKey,nonce:e.intent.delegate.nonce,maxBlockHeight:e.intent.delegate.maxBlockHeight,actionFingerprint:await ut(e.intent.delegate.actions),canonicalDelegateBorshB64u:(await Mr({delegate:{senderId:e.intent.delegate.senderId,receiverId:e.intent.delegate.receiverId,actions:gi(e.intent.delegate.actions),nonce:e.intent.delegate.nonce,maxBlockHeight:e.intent.delegate.maxBlockHeight,publicKey:e.intent.delegate.publicKey},workerCtx:e.ctx})).canonicalDelegateBorshB64u},expectedSigningDigestB64u:e.signingDigestB64u})}async function Ti(e){let t=hi({materialActivation:e.materialActivation,materialFacts:e.materialFacts,walletId:e.walletId,operationId:e.operationId}),n=await wi({ctx:e.ctx,thresholdSessionId:e.thresholdSessionId,scope:t,expiresAtMs:Date.now()+ai,nearAccountId:e.nearAccountId,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,intent:e.intent}),r=Ke({tenantId:fi(k(e.materialFacts.runtimePolicyScope.orgId)),principalId:fi(E(String(e.walletId))),capabilityId:fi(re(e.materialActivation.capability)),operationId:fi(w(String(e.operationId))),operation:{capabilityKind:`near_ed25519_mpc_signing`,operationKind:e.intent.kind===`nep413_message_v1`?`near.sign_nep413_message`:`near.sign_delegate_action`},digests:{laneDigest:Ge(e.operationFingerprint),intentDigest:A(h(Uint8Array.from(n.admissionMaterial.intentDigest.bytes))),displayDigest:A(e.displayDigest)}});return{operation:{kind:`near_signature_only`,prepare:n,signingDigestB64u:e.signingDigestB64u,materialActivation:e.materialActivation},envelope:r}}function Ei(e){if(e.auth.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP auth binding`);let t=e.preparation.hydration.authority;if(!t||String(t.walletId)!==String(e.walletId))throw Error(`[SigningEngine][near] Email OTP material authority changed`);return{kind:`email_otp`,authorityRef:t,providerSubjectId:e.auth.providerSubjectId,challengeId:e.challengeId,otpCode:e.otpCode}}function Di(e){switch(e.authorization.kind){case`passkey`:return{kind:`passkey`,authority:e.authorization.plannedPasskeyOperationStepUp.authority,credential:e.authorization.credential};case`email_otp`:return Ei({preparation:e.preparation,auth:Oi(e.auth),walletId:e.walletId,challengeId:e.authorization.challengeId,otpCode:e.authorization.otpCode});default:throw e.authorization,Error(`[SigningEngine][near] unsupported operation step-up authorization`)}}function Oi(e){if(e.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP step-up requires an Email OTP auth binding`);return e}function ki(e){if(!e)throw Error(`[SigningEngine][near] operation step-up proof is missing`);return e}function Ai(e){return e.authorization.kind===`operation_step_up`}async function ji(e){if(e.issuedAuthorization)return e.issuedAuthorization;switch(e.proof.kind){case`passkey`:return await vn({relayerUrl:e.relayerUrl,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof,credential:e.credential,materialRecovery:{kind:`not_requested`}});case`email_otp`:return await vn({relayerUrl:e.relayerUrl,normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof,credential:e.credential,materialRecovery:{kind:`not_requested`}});default:throw e.proof,Error(`[SigningEngine][near] unsupported operation step-up proof`)}}async function Mi(e){if(Ai(e)){let t=Re(e.activeClient.metadata());if(ii({expected:e.authorization.prepared.materialActivation,actual:t}),e.authorization.prepared.signingDigestB64u!==e.signingDigestB64u)throw Error(`[SigningEngine][near] signature-only operation digest changed`);let n=e.authorization.prepared.prepare,r=await oi({ctx:e.ctx,walletId:e.walletId,relayerUrl:e.materialFacts.relayerUrl,proof:e.authorization.proof}),i=await ji({issuedAuthorization:e.authorization.issuedAuthorization,relayerUrl:e.materialFacts.relayerUrl,normalSigningRequest:n.request,displayDigest:e.displayDigest,proof:e.authorization.proof,credential:r});if(n.request.scope.authorization.kind!==`operation_step_up`||i.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] issued operation step-up evidence changed identity`);return{kind:`router_ab_ed25519_signature_only_normal_signing_result_v1`,authorization:`operation_step_up`,issuedAuthorization:i,...await Si({thresholdSessionId:e.thresholdSessionId,materialFacts:e.materialFacts,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:e.signingDigestB64u,signingPayloadLabel:`signature-only payload digest`,prepare:n,credential:r,authorization:`operation_step_up`})}}let t=e.startedPrepare&&e.startedPrepare.displayDigest===e.displayDigest&&e.startedPrepare.signingDigestB64u===e.signingDigestB64u?e.startedPrepare:null;e.startedPrepare&&!t&&Fi(e.startedPrepare);let n=t?.prepare??await Ni(e);return n?{kind:`router_ab_ed25519_signature_only_normal_signing_result_v1`,authorization:`reusable_wallet_session`,...await Si({thresholdSessionId:e.thresholdSessionId,walletSessionState:e.walletSessionState,sessionCoordinator:e.sessionCoordinator,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:e.signingDigestB64u,signingPayloadLabel:`signature-only payload digest`,prepare:n,startedResponse:t?.response,credential:Yr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}).credential,authorization:e.authorization.kind})}:null}async function Ni(e){let t=mi({activeClient:e.activeClient,walletSessionState:e.walletSessionState,walletId:e.walletId,operationId:e.operationId});return t?await wi({ctx:e.ctx,thresholdSessionId:e.thresholdSessionId,scope:t,expiresAtMs:pi({walletSessionExpiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs,requestedTtlMs:ai}),nearAccountId:e.nearAccountId,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,intent:e.intent}):null}async function Pi(e){let t=await Ni(e);if(!t)return null;let n=Yr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}),r=performance.now(),i=ft({relayServerUrl:e.walletSessionState.relayerUrl,credential:n.credential,request:t.request});return i.catch(()=>{}),U(String(e.operationId),`prepare_sent`,r),{prepare:t,displayDigest:e.displayDigest,signingDigestB64u:e.signingDigestB64u,response:i}}function Fi(e){e.response.catch(()=>{})}async function Ii(e){let t=await Pr({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx}),n=ui(e.ctx),r=tr(e.txSigningRequest,`txSigningRequest`),i=await ht({scope:hi({materialActivation:e.materialActivation,materialFacts:e.materialFacts,walletId:e.walletId,operationId:e.operationId}),expiresAtMs:Date.now()+ai,operationId:e.operationId,operationFingerprint:e.operationFingerprint,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:n,transactions:[{receiverId:r.receiverId,actionFingerprint:await ut(r.actions)}],unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,expectedSigningDigestB64u:t.signingDigestB64u}),a=Ke({tenantId:fi(k(e.materialFacts.runtimePolicyScope.orgId)),principalId:fi(E(String(e.walletId))),capabilityId:fi(re(e.materialActivation.capability)),operationId:fi(w(String(e.operationId))),operation:{capabilityKind:`near_ed25519_mpc_signing`,operationKind:`near.sign_transaction`},digests:{laneDigest:Ge(e.operationFingerprint),intentDigest:A(h(Uint8Array.from(i.admissionMaterial.intentDigest.bytes))),displayDigest:A(e.displayDigest)}});return{operation:{kind:`near_transaction`,prepare:i,unsignedTransactionBorshB64u:t.unsignedTransactionBorshB64u,signingDigestB64u:t.signingDigestB64u,materialActivation:e.materialActivation},envelope:a}}function Li(e){return e.authorization.kind===`operation_step_up`}function Ri(e){return Li(e)?e.materialFacts:{thresholdSessionId:e.walletSessionState.thresholdSessionId,signer:e.walletSessionState.signingLane.identity.signer,signingRootId:e.walletSessionState.signingRootId,signingRootVersion:e.walletSessionState.signingRootVersion,routerAbNormalSigning:e.walletSessionState.routerAbNormalSigning,runtimePolicyScope:e.walletSessionState.runtimePolicyScope,relayerUrl:e.walletSessionState.relayerUrl}}async function zi(e){let t=Ri(e);if(!t.routerAbNormalSigning)throw Error(`[SigningEngine][near] Router A/B Ed25519 normal-signing state is missing`);if(!e.transactionContext)throw Error(`[SigningEngine][near] Router A/B Ed25519 transaction signing is missing transaction context from confirmation`);let n=Li(e),r=n?{unsignedTransactionBorshB64u:e.authorization.prepared.unsignedTransactionBorshB64u,signingDigestB64u:e.authorization.prepared.signingDigestB64u}:await Pr({txSigningRequest:e.txSigningRequest,transactionContext:e.transactionContext,workerCtx:e.ctx});if(_(r.signingDigestB64u).length!==32)throw Error(`Router A/B normal-signing NEAR payload digest must be 32 bytes`);let i=ui(e.ctx),a=tr(e.txSigningRequest,`txSigningRequest`),o=H.signingOperationFingerprint(await Jn({nearAccountId:e.nearAccountId,nearNetworkId:i,relayerKeyId:e.thresholdKeyMaterial.relayerKeyId,signerPublicKey:e.thresholdKeyMaterial.publicKey,transactions:[a],unsignedTransactionBorshB64u:r.unsignedTransactionBorshB64u,signingDigestB64u:r.signingDigestB64u})),s,c,l;if(n){s=e.authorization.prepared.prepare,c=await oi({ctx:e.ctx,walletId:e.walletId,relayerUrl:t.relayerUrl,proof:e.authorization.proof});let n=await ji({issuedAuthorization:e.authorization.issuedAuthorization,relayerUrl:t.relayerUrl,normalSigningRequest:s.request,displayDigest:e.authorization.displayDigest,proof:e.authorization.proof,credential:c});if(s.request.scope.authorization.kind!==`operation_step_up`||n.kind!==`verified_step_up`)throw Error(`[SigningEngine][near] issued operation step-up evidence changed identity`);l=n}else{let t=mi({activeClient:e.activeClient,walletSessionState:e.walletSessionState,walletId:e.walletId,operationId:e.operationId});if(!t)throw Error(`[SigningEngine][near] Router A/B Ed25519 signing scope is missing`);s=await ht({scope:t,expiresAtMs:pi({walletSessionExpiresAtMs:e.walletSessionState.signingWalletSession.expiresAtMs,requestedTtlMs:ai}),operationId:e.operationId,operationFingerprint:o,displayDigestB64u:e.displayDigest,nearAccountId:e.nearAccountId,nearNetworkId:i,transactions:[{receiverId:a.receiverId,actionFingerprint:await ut(a.actions)}],unsignedTransactionBorshB64u:r.unsignedTransactionBorshB64u,expectedSigningDigestB64u:r.signingDigestB64u}),c=Yr({state:e.walletSessionState,thresholdSessionId:e.thresholdSessionId,nearAccountId:e.nearAccountId,thresholdKeyMaterial:e.thresholdKeyMaterial}).credential}e.ctx.beforeSigning?.();let u=Li(e)?await Si({thresholdSessionId:e.thresholdSessionId,materialFacts:t,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:r.signingDigestB64u,signingPayloadLabel:`NEAR payload digest`,prepare:s,credential:c,authorization:`operation_step_up`}):await Si({thresholdSessionId:e.thresholdSessionId,walletSessionState:e.walletSessionState,sessionCoordinator:e.sessionCoordinator,thresholdKeyMaterial:e.thresholdKeyMaterial,walletId:e.walletId,nearAccountId:e.nearAccountId,activeClient:e.activeClient,signingDigestB64u:r.signingDigestB64u,signingPayloadLabel:`NEAR payload digest`,prepare:s,credential:c,authorization:`reusable_wallet_session`}),d=await Fr({unsignedTransactionBorshB64u:r.unsignedTransactionBorshB64u,signingDigestB64u:r.signingDigestB64u,signatureB64u:u.signatureB64u,expectedNearAccountId:e.nearAccountId,expectedSignerPublicKey:e.thresholdKeyMaterial.publicKey,workerCtx:e.ctx}),f=await Ir({signedTransactionBorshB64u:d.signedTransactionBorshB64u,workerCtx:e.ctx}),p=d.transactionHash||f.transactionHash,m={type:Ut.SignTransactionsWithActionsSuccess,payload:{free:()=>void 0,success:!0,transactionHashes:[p],signedTransactions:[f.signedTransaction],logs:[`NEAR transaction signed through Router A/B normal signing`],error:void 0}};if(n){if(!l)throw Error(`[SigningEngine][near] operation step-up authorization was not issued`);return{kind:`router_ab_ed25519_near_transaction_normal_signing_result_v1`,authorization:`operation_step_up`,issuedAuthorization:l,okResponse:m}}return{kind:`router_ab_ed25519_near_transaction_normal_signing_result_v1`,authorization:`reusable_wallet_session`,okResponse:m}}const Bi=1e3,Vi=[120,180,250,350,500,700,1e3,1e3,1500,1500,2e3],Hi=Symbol(`NearWalletSessionFundingAuthority`);function Ui(e=Bi){return new Promise(t=>{setTimeout(t,e)})}function Wi(e){let t=String(e.walletSessionToken||``).trim();if(!t)throw Error(`[SigningEngine][near] authenticated Wallet Session token is required for funding`);return t}function Gi(e){return{kind:`near_ed25519_funding_session`,signer:e.signingLane.identity.signer,thresholdSessionId:e.thresholdSessionId,walletSessionToken:e.walletSessionAuth.walletSessionToken}}function Ki(e){switch(e.kind){case`warm_session`:return`warm_session`;case`passkey`:return`passkey_reauth`;case`email_otp`:return`email_otp_reauth`;default:return Ji(e)}}function qi(e){switch(e){case`passkey`:return`passkey_reauth`;case`email_otp`:return`email_otp_reauth`;default:throw Error(`[SigningEngine][near] unsupported operation step-up funding method`)}}function Ji(e){throw Error(`Unsupported NEAR funding authorization: ${String(e)}`)}function Yi(e){let t=String(e.fundingSession.signer.account.wallet.walletId),n=String(e.fundingSession.signer.account.nearAccountId),r=e.request.operation;if(String(e.request.subject.walletId)!==t||String(e.request.subject.nearAccountId)!==n||e.request.subject.nearPublicKeyStr!==e.nearPublicKeyStr)throw Error(`[SigningEngine][near] funding request subject does not match authenticated lane`);if(String(r.operationId)!==String(e.signingOperation.operationId)||String(r.operationFingerprint)!==String(e.signingOperation.operationFingerprint)||r.intent!==e.signingOperation.intent||r.accountId!==n)throw Error(`[SigningEngine][near] funding request operation does not match signing operation`);if(e.request.signatureUses!==e.signatureUses)throw Error(`[SigningEngine][near] funding request signature use count mismatch`);if(String(e.fundingSession.thresholdSessionId).trim().length===0)throw Error(`[SigningEngine][near] funding authority threshold session mismatch`)}function Xi(e){return{kind:`near_wallet_session_funding_authority`,provenance:e.provenance,request:e.request,thresholdSessionId:e.fundingSession.thresholdSessionId,walletSessionToken:Wi(e.fundingSession),[Hi]:!0}}async function Zi(e){let t=e.authority.request,n=tt({chains:e.ctx.chains,walletId:String(t.subject.walletId),nearAccountId:String(t.subject.nearAccountId),nearPublicKeyStr:t.subject.nearPublicKeyStr}),r;for(let i=1;i<=12;i+=1)try{let r=await e.ctx.nonceCoordinator.reserveNearContext({lane:n,operation:t.operation,count:t.signatureUses,nearClient:e.ctx.nearClient});return{transactionContext:r.context,nonceLeases:r.leases.map(ke),reservedLeases:r.leases}}catch(e){r=e,i<12&&await Ui(Vi[i-1]??Bi)}throw r instanceof Error?r:Error(`Funded NEAR account access key did not become available`)}async function Qi(e){let t=e.authority.request,n=await Ie({relayerUrl:e.ctx.relayerUrl,walletId:String(t.subject.walletId),nearAccountId:String(t.subject.nearAccountId),nearPublicKeyStr:t.subject.nearPublicKeyStr,walletSessionToken:e.authority.walletSessionToken});if(!n.ok)throw Error(n.message||n.code||`Failed to fund implicit NEAR account`);return await Zi(e)}async function $i(e){switch(e.confirmation.readiness.kind){case`context_ready`:return e.confirmation.readiness;case`funding_required`:{Yi({request:e.confirmation.readiness.request,fundingSession:Gi(e.walletSessionState),nearPublicKeyStr:e.nearPublicKeyStr,signingOperation:e.signingOperation,signatureUses:e.signatureUses});let t=Xi({request:e.confirmation.readiness.request,fundingSession:Gi(e.walletSessionState),provenance:Ki(e.authorization)}),n=await Qi({ctx:e.ctx,authority:t});return{kind:`context_ready`,transactionContext:n.transactionContext,nonceLeases:n.nonceLeases}}default:return ea(e.confirmation.readiness)}}function ea(e){throw Error(`Unsupported confirmed NEAR transaction readiness: ${String(e)}`)}async function ta(e){Yi({request:e.request,fundingSession:e.fundingSession,nearPublicKeyStr:e.nearPublicKeyStr,signingOperation:e.signingOperation,signatureUses:e.signatureUses});let t=Xi({request:e.request,fundingSession:e.fundingSession,provenance:qi(e.method)}),n=await Qi({ctx:e.ctx,authority:t});return{readiness:{kind:`context_ready`,transactionContext:n.transactionContext,nonceLeases:n.nonceLeases},reservedNonceLeases:n.reservedLeases}}const na=new Map;function ra(e){let t=String(e||``).trim();if(!t)throw Error(`[SigningEngine][near] requestId is required`);return t}function ia(e){na.set(ra(e.requestId),e.fund)}function aa(e){na.delete(String(e||``).trim())}const oa={async fund(e){let t=ra(e.requestId),n=na.get(t);if(!n)throw Error(`[SigningEngine][near] implicit-account funding is unavailable`);return na.delete(t),await n(e.request)}};function sa(e){switch(e.kind){case`passkey_live`:case`email_otp_live`:return e.material.facts;case`passkey_sealed`:case`email_otp_sealed`:return e.facts;default:throw Error(`[SigningEngine][near] unsupported operation material`)}}async function ca(e,t){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:return await t.resolve(e);case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] material requires public-anchor reauthorization`);case`blocked`:throw Error(`[SigningEngine][near] material hydration is blocked: ${e.hydration.reason}`);default:throw e.hydration,Error(`[SigningEngine][near] unsupported Ed25519 Yao hydration plan`)}}async function la(e){if(e.method===`passkey`&&e.preparation.hydration.kind===`rehydrate_material_activation`){let t=await e.executor.preparePasskeyOperationStepUp(e.preparation);return{kind:`passkey_sealed`,materialActivation:t.materialActivation,facts:t.facts,rehydrate:t.rehydrate}}if(e.method===`email_otp`){let t=await e.executor.prepareEmailOtpOperationStepUp(e.preparation);switch(t.kind){case`live`:return{kind:`email_otp_live`,materialActivation:t.materialActivation,material:t.material};case`sealed`:return{kind:`email_otp_sealed`,materialActivation:t.materialActivation,facts:t.facts,authorizeAndRehydrate:t.authorizeAndRehydrate};default:throw Error(`[SigningEngine][near] unsupported Email OTP operation material`)}}let t=await ca(e.preparation,e.executor);return{kind:`passkey_live`,materialActivation:Re(t.activeClient.metadata()),material:t}}async function ua(e){ii({expected:e.expectedActivation,actual:e.material.materialActivation});let t,n=null;if(e.kind===`email_otp_live`||e.kind===`email_otp_sealed`)if(e.kind===`email_otp_live`)t=e.material.material;else{let r=await e.material.authorizeAndRehydrate({normalSigningRequest:e.normalSigningRequest,displayDigest:e.displayDigest,proof:e.proof});t=r.material,n=r.issuedAuthorization}else t=e.material.kind===`passkey_live`?e.material.material:await e.material.rehydrate(e.credential);try{return ii({expected:e.expectedActivation,actual:Re(t.activeClient.metadata())}),{material:t,issuedAuthorization:n}}catch(n){throw(e.material.kind===`passkey_sealed`||e.material.kind===`email_otp_sealed`)&&t.activeClient.dispose(),n}}async function da(e){let t=await ca(e.preparation,e.executor);return{thresholdSessionId:t.facts.thresholdSessionId,material:t,walletSessionState:await e.executor.resolveWalletSessionState()}}function fa(e){if(!e)throw Error(`[SigningEngine][near] confirmed operation step-up is missing preparation`);return e}function pa(e){if(!e)throw Error(`[SigningEngine][near] prepared operation step-up is missing`);if(e.kind!==`near_transaction`)throw Error(`[SigningEngine][near] prepared operation step-up is not a transaction`);return e}function ma(e){if(!e)throw Error(`[SigningEngine][near] transaction operation material is unavailable`);return e}function ha(e){e.owned&&e.resolved?.material.activeClient.dispose()}function ga(e,t){throw ha(e),t}async function _a(e){return{material:await ca(e.preparation,e.executor),walletSessionState:await e.executor.resolveWalletSessionState()}}function va(e){if(!e)throw Error(`[SigningEngine][near] warm signing material was not prepared`);return e}async function ya(e){if(e.authorization.kind===`passkey`){if(e.material.kind!==`passkey_live`&&e.material.kind!==`passkey_sealed`)throw Error(`[SigningEngine][near] passkey transaction material changed factor`);return await ua({kind:`passkey`,material:e.material,expectedActivation:e.prepared.materialActivation,credential:e.authorization.credential})}if(e.material.kind!==`email_otp_live`&&e.material.kind!==`email_otp_sealed`)throw Error(`[SigningEngine][near] Email OTP transaction material changed factor`);if(e.proof.kind!==`email_otp`)throw Error(`[SigningEngine][near] Email OTP transaction proof is missing`);return e.material.kind===`email_otp_live`?await ua({kind:`email_otp_live`,material:e.material,expectedActivation:e.prepared.materialActivation}):await ua({kind:`email_otp_sealed`,material:e.material,expectedActivation:e.prepared.materialActivation,normalSigningRequest:e.prepared.prepare.request,displayDigest:e.displayDigest,proof:e.proof})}function Z(e,t,n){try{e?.(xe({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}async function ba(e){let t=performance.now(),n=`failed`;try{if(!e.state)throw Error(`[SigningEngine][near] reusable Wallet Session state is unavailable`);let t=await e.coordinator.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:e.state,nowMs:Date.now()});if(!t)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return n=`succeeded`,t}finally{U(e.operationId,`wallet_session_authorization`,t,n)}}async function xa(e){let t=await la({method:e.method,preparation:e.preparation,executor:e.executor}),n=sa(t);if(String(n.thresholdSessionId)!==e.expectedThresholdSessionId)throw Error(`[SigningEngine][near] prepared operation material changed threshold session`);return ei({requestId:e.requestId,build:async r=>{if(r.kind!==`near_transaction`)throw Error(`[SigningEngine][near] transaction step-up preparation kind changed`);if(r.operationId!==String(e.operation.operationId))throw Error(`[SigningEngine][near] operation step-up operation identity changed`);return await Ii({...e.operation,thresholdSessionId:n.thresholdSessionId,materialFacts:n,materialActivation:t.materialActivation,transactionContext:r.transactionContext,displayDigest:r.displayDigest})}}),ia({requestId:e.requestId,fund:async t=>await ta({...e.funding,request:t,fundingSession:await e.executor.resolveFundingSession(),method:e.method})}),t}function Sa(e){ti(e),aa(e)}function Ca(e){if(!e.readiness){Sa(e.requestId);return}e.readiness.then(Sa.bind(void 0,e.requestId),Sa.bind(void 0,e.requestId))}function wa(e){return e.selection.kind===`authorization_required`}async function Ta(e){return wa(e)?await Ea(e):await Da(e)}async function Ea(e){let{ctx:t,commandSubject:n,nearAccount:r,transaction:i,rpcCall:a,onEvent:o,confirmationConfigOverride:c,title:l,body:u,signerSlot:d,signingOperationState:p,signingSessionCoordinator:m,selection:h,yaoSigningPreparation:g,yaoMaterialExecutor:_,passkeyEd25519OperationStepUp:v,emailOtpEd25519StepUp:y}=e,b=p.operationId,x=h.candidate,S=P(r.accountId),ee=[];if(!t.touchConfirm)throw Error(`UiConfirm bridge not available for signing`);if(!m)throw Error(`[SigningEngine][near] production signing session coordinator is required`);let{thresholdKeyMaterial:te}=await Un({materialExecutor:_,nearAccount:r,signerSlot:x.signerSlot,requestedSignerSlot:d,operationLabel:`signing`,warnings:ee}),C=ja({nearAccountId:S,relayerUrl:t.relayerUrl,thresholdKeyMaterial:te}),ne={nearRpcUrl:a.nearRpcUrl||f(mt.network.chains),nearAccountId:S},{txSigningRequest:w,confirmationTransaction:T}=Wn({nearAccountId:String(S),transaction:i}),E=tr(w,`txSigningRequest`),D=H.signingOperationFingerprint(await qn({nearAccountId:S,nearNetworkId:s(t.chains||mt.network.chains),relayerKeyId:C.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:C.threshold.thresholdKeyMaterial.publicKey,transactions:[E]}));m.bindCallerProvidedOperationIdToFingerprint({operationId:b,operationFingerprint:D});let O=Ge(D),k={kind:`deferred_ed25519_material_identity`,signer:Ve({walletId:x.walletId,nearAccountId:x.nearAccountId,nearEd25519SigningKeyId:x.nearEd25519SigningKeyId,signerSlot:x.signerSlot}),materialActivation:x.materialActivation,thresholdSessionId:H.thresholdEd25519Session(x.thresholdSessionId)},re={kind:V.OperationStepUp,lane:{identity:k,auth:x.auth,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,sessionOrigin:`per_operation`,storageSource:`sealed_restore`,retention:`single_use`,materialActivation:k.materialActivation,thresholdSessionId:k.thresholdSessionId}},A=hr(x.auth),j={operationId:b,operationFingerprint:D,intent:Te.TransactionSign},M=await mr({signingAuthPlan:A,signingLaneAuth:x.auth,requiredSignatureUses:Dr(i),operationFingerprintDigest:O,...v?{passkeyEd25519OperationStepUp:v}:{},...y?{emailOtpEd25519StepUp:y}:{}});if(M.kind===`warm_session`)throw Error(`[SigningEngine][near] deferred Ed25519 transaction cannot use warm session`);let ie=Dr(i),ae=xa({requestId:String(b),expectedThresholdSessionId:String(k.thresholdSessionId),method:M.kind,preparation:g,executor:_,operation:{ctx:t,thresholdKeyMaterial:C.threshold.thresholdKeyMaterial,walletId:n.walletSession.walletId,nearAccountId:S,operationId:b,operationFingerprint:D,txSigningRequest:w},funding:{ctx:t,nearPublicKeyStr:C.signingNearPublicKeyStr,signingOperation:j,signatureUses:ie}}),N;try{N=await kt({signingSessionPlan:re,signingOperation:j,signingOperationState:p,runtime:t.touchConfirm,request:{ctx:{touchConfirm:t.touchConfirm},sessionId:String(b),chain:`near`,kind:`transaction`,...Ot({signingAuthPlan:M.confirmationAuthPayload.signingAuthPlan}),walletId:x.walletId,txSigningRequests:[T],rpcCall:ne,nearPublicKeyStr:C.signingNearPublicKeyStr,nearFundingRequest:{subject:{walletId:x.walletId,nearAccountId:S,nearPublicKeyStr:C.signingNearPublicKeyStr},operation:{...j,accountId:String(S)},signatureUses:ie},confirmationConfigOverride:At({signingAuthPlan:M.confirmationAuthPayload.signingAuthPlan,override:c}),title:l,body:u,confirmationReadiness:{promise:ae},onProgress:Sr.bind(void 0,{onEvent:o,nearAccountId:S,signingAuthPlan:M.confirmationAuthPayload.signingAuthPlan})}})}finally{Ca({requestId:String(b),readiness:ae})}let F=await ae,oe=sa(F),I=wr({prepared:M,confirmation:N});if(I.kind===`warm_session`)throw Error(`[SigningEngine][near] deferred transaction requires operation step-up`);let se=Di({authorization:I,preparation:g,auth:x.auth,walletId:n.walletSession.walletId}),ce=pa(ri({requestId:String(b),ref:fa(N.operationStepUpPreparation)})),le=await ya({material:F,prepared:ce,displayDigest:N.intentDigest,authorization:I,proof:ki(se)});Z(o,S,{phase:z.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:Mt(M.confirmationAuthPayload.signingAuthPlan)});try{if(await t.nonceCoordinator.recoverDurableLeases({walletId:String(x.walletId)}),N.readiness.kind!==`context_ready`)throw Error(`[SigningEngine][near] implicit-account funding requires transaction context`);let e=await zi({ctx:t,thresholdSessionId:oe.thresholdSessionId,activeClient:le.material.activeClient,materialFacts:oe,thresholdKeyMaterial:C.threshold.thresholdKeyMaterial,walletId:n.walletSession.walletId,nearAccountId:S,operationId:b,operationFingerprint:D,displayDigest:N.intentDigest,txSigningRequest:w,transactionContext:N.readiness.transactionContext,authorization:{kind:`operation_step_up`,prepared:ce,displayDigest:N.intentDigest,proof:ki(se),issuedAuthorization:le.issuedAuthorization}});if(!e||e.authorization!==`operation_step_up`)throw Error(`[SigningEngine][near] operation step-up transaction signing is unavailable`);si({prepared:ce,issuedAuthorization:e.issuedAuthorization});let r=Aa({okResponse:e.okResponse,nearAccountId:S,warnings:ee,nonceLeases:N.readiness.nonceLeases});return await ka(t,N.readiness.nonceLeases),r}catch(e){throw ha({resolved:le,owned:F.kind===`passkey_sealed`||F.kind===`email_otp_sealed`}),e}}async function Da({ctx:e,commandSubject:t,nearAccount:n,transaction:r,rpcCall:i,onEvent:a,confirmationConfigOverride:o,title:c,body:l,signerSlot:u,signingOperationState:d,signingSessionCoordinator:p,transactionOperation:m,ed25519SigningBoundary:h,passkeyEd25519OperationStepUp:g,emailOtpEd25519StepUp:_,yaoSigningPreparation:v,yaoMaterialExecutor:y}){let b=performance.now(),x=d.operationId,S=P(n.accountId),ee=e.relayerUrl,te=[],C=e.nonceCoordinator.recoverDurableLeases({walletId:String(t.walletSession.walletId)});C.catch(()=>{}),Z(a,S,{phase:z.STEP_02_REQUEST_PREPARED,status:`running`,message:`Loading threshold signing state`,interaction:{kind:`none`,overlay:`none`}});let{thresholdKeyMaterial:ne}=await Un({materialExecutor:y,nearAccount:n,signerSlot:h.signingLane.identity.signer.signerSlot,requestedSignerSlot:u,operationLabel:`signing`,warnings:te}),w=ja({nearAccountId:S,relayerUrl:ee,thresholdKeyMaterial:ne}),T={nearRpcUrl:i.nearRpcUrl||f(mt.network.chains),nearAccountId:S},{txSigningRequest:E,confirmationTransaction:D}=Wn({nearAccountId:String(T.nearAccountId),transaction:r}),O=tr(E,`txSigningRequest`),k=H.signingOperationFingerprint(await qn({nearAccountId:S,nearNetworkId:s(e.chains||mt.network.chains),relayerKeyId:w.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:w.threshold.thresholdKeyMaterial.publicKey,transactions:[O]})),re=Ge(k);if(!e.touchConfirm)throw Error(`UiConfirm bridge not available for signing`);let A=e.touchConfirm;if(!p)throw Error(`[SigningEngine][near] production signing session coordinator is required`);p.bindCallerProvidedOperationIdToFingerprint({operationId:x,operationFingerprint:k});let j=Dr(r),M={operationId:x,operationFingerprint:k,intent:Te.TransactionSign},ie=async e=>await wt({signingSessionPlan:h.signingSessionPlan,signingOperation:M,commandKind:e.commandKind,execute:e.execute}),ae=h.thresholdSessionId,N=String(ae||``).trim(),F=h.signingAuthPlan,oe=h.signingLane;if(!m)throw Error(`[SigningEngine][near] threshold transaction signing requires prepared transaction operation`);if(bt(F)&&F.thresholdSessionId!==ae)throw Error(`[SigningEngine][near] warm-session auth plan must match prepared session identity`);let I={thresholdSessionId:bt(F)?F.thresholdSessionId:ae,lane:oe,signingAuthPlan:F,confirmationAuthPayload:{signingAuthPlan:F},warmSessionReady:bt(F)},se=oe,ce=new Set,le=e=>{ce.has(e)||(ce.add(e),Je(`near`,Xe({event:`auth_side_effect_started`,lane:se,sideEffect:e,phase:`confirmed`})))},ue=e=>{e.phase===`auth.passkey.prompt.started`&&le(`passkey_reauth`),Sr({onEvent:a,nearAccountId:S,signingAuthPlan:I.confirmationAuthPayload.signingAuthPlan},e)},de=await mr({signingAuthPlan:F,signingLaneAuth:oe.auth,requiredSignatureUses:j,operationFingerprintDigest:re,...g?{passkeyEd25519OperationStepUp:g}:{},..._?{emailOtpEd25519StepUp:_}:{}}),fe=de.kind===`warm_session`?_a({preparation:v,executor:y}):null;fe?.catch(()=>{});let pe=de.confirmationAuthPayload;bt(pe.signingAuthPlan)&&Z(a,S,{phase:z.STEP_06_AUTH_WARM_SESSION_CLAIMED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{thresholdSessionId:pe.signingAuthPlan.thresholdSessionId,expiresAtMs:pe.signingAuthPlan.expiresAtMs,remainingUses:pe.signingAuthPlan.remainingUses}});let me=!Ft(d.current);me&&Z(a,S,{phase:z.STEP_05_CONFIRMATION_DISPLAYED,status:`waiting_for_user`,message:`Opening confirmation prompt`,interaction:{kind:`transaction_confirmation`,overlay:`show`}});let he=de.kind===`warm_session`?null:xa({requestId:N,expectedThresholdSessionId:N,method:de.kind,preparation:v,executor:y,operation:{ctx:e,thresholdKeyMaterial:w.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:S,operationId:M.operationId,operationFingerprint:k,txSigningRequest:E},funding:{ctx:e,nearPublicKeyStr:w.signingNearPublicKeyStr,signingOperation:M,signatureUses:j}});U(String(x),`pre_confirmation`,b);let ge=performance.now(),L;try{L=await kt({signingSessionPlan:h.signingSessionPlan,signingOperation:M,signingOperationState:d,runtime:A,request:{ctx:{touchConfirm:A},sessionId:N,chain:`near`,kind:`transaction`,...Ot({signingAuthPlan:pe.signingAuthPlan}),walletId:String(oe.identity.signer.account.wallet.walletId),txSigningRequests:[D],rpcCall:T,nearPublicKeyStr:w.signingNearPublicKeyStr,nearFundingRequest:{subject:{walletId:oe.identity.signer.account.wallet.walletId,nearAccountId:S,nearPublicKeyStr:w.signingNearPublicKeyStr},operation:{...M,accountId:String(S)},signatureUses:j},confirmationConfigOverride:At({signingAuthPlan:pe.signingAuthPlan,override:o}),title:c,body:l,...he?{confirmationReadiness:{promise:he}}:{},onProgress:ue}})}finally{Ca({requestId:N,readiness:he})}let _e=performance.now();U(String(x),`confirmation`,ge);let ve=he?await he:null;me&&Z(a,S,{phase:z.STEP_05_CONFIRMATION_APPROVED,status:`succeeded`,interaction:{kind:`transaction_confirmation`,overlay:`hide`}});let R=wr({prepared:de,confirmation:L}),ye=R.kind===`warm_session`?null:Di({authorization:R,preparation:v,auth:m.lane.auth,walletId:t.walletSession.walletId}),be=R.kind===`warm_session`?null:ri({requestId:N,ref:fa(L.operationStepUpPreparation)}),xe=R.kind===`warm_session`?null:await ya({material:ma(ve),prepared:pa(be),displayDigest:L.intentDigest,authorization:R,proof:ki(ye)}),Se=ve?.kind===`passkey_sealed`||ve?.kind===`email_otp_sealed`,Ce=performance.now();try{await C,U(String(M.operationId),`durable_lease_recovery_wait`,Ce)}catch(e){throw U(String(M.operationId),`durable_lease_recovery_wait`,Ce,`failed`),ha({resolved:xe,owned:Se}),e}let we=!1,{canonicalThresholdSessionId:B,activeClient:V,walletSessionState:Ee,operationMaterialFacts:De,issuedAuthorization:Oe,transactionContext:ke,nonceLeaseRefs:Ae}=await ie({commandKind:Dt.PreparePayload,execute:async()=>{Z(a,S,{phase:z.STEP_08_SIGNER_PREPARE_STARTED,status:`running`,message:`Preparing NEAR signer`,interaction:{kind:`none`,overlay:`none`}});let t=performance.now(),n=R.kind===`warm_session`?{kind:`warm_session`,resolved:await va(fe)}:{kind:`operation_step_up`,resolved:xe};U(String(M.operationId),`material_resolution_wait`,t);let r=(n.kind,n.resolved.material.facts.thresholdSessionId),i=(n.kind,n.resolved.material.activeClient),o=n.kind===`warm_session`?n.resolved.walletSessionState:null,s=performance.now(),c=n.kind===`warm_session`?await $i({confirmation:L,ctx:e,nearPublicKeyStr:w.signingNearPublicKeyStr,walletSessionState:o,authorization:R,signingOperation:M,signatureUses:j}):L.readiness.kind===`context_ready`?L.readiness:(()=>{throw Error(`[SigningEngine][near] operation step-up confirmation did not resolve a transaction context`)})();return U(String(M.operationId),`transaction_context`,s),Z(a,S,{phase:z.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:I.warmSessionReady?`warm_session`:I.signingAuthPlan.method}),Z(a,S,{phase:z.STEP_08_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`,message:`NEAR signer ready`,interaction:{kind:`none`,overlay:`none`},data:{signer:`threshold-ed25519`,thresholdSessionId:r,clientBaseSource:`yao_active_client`}}),{canonicalThresholdSessionId:r,activeClient:i,walletSessionState:o,operationMaterialFacts:n.kind===`operation_step_up`?n.resolved.material.facts:null,issuedAuthorization:n.kind===`operation_step_up`?n.resolved.issuedAuthorization:null,transactionContext:c.transactionContext,nonceLeaseRefs:c.nonceLeases}}}).catch(ga.bind(void 0,{resolved:xe,owned:Se})),je=async t=>{we||!Ae.length||await Oa(e,Ae,`signing_failed`).catch(e=>{console.warn(`[SigningEngine][near][transaction] failed to release nonce leases`,{originalError:t instanceof Error?t.message:String(t||``),releaseError:e instanceof Error?e.message:String(e||``)})})},Me=async n=>{Z(a,S,{phase:z.STEP_10_COMMIT_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let r=R.kind===`warm_session`?await zi({ctx:e,thresholdSessionId:B,activeClient:n,sessionCoordinator:p,walletSessionState:await ba({state:Ee,coordinator:p,operationId:String(M.operationId)}),thresholdKeyMaterial:w.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:S,operationId:M.operationId,operationFingerprint:k,displayDigest:L.intentDigest,txSigningRequest:E,transactionContext:ke,authorization:{kind:`reusable_wallet_session`}}):await zi({ctx:e,thresholdSessionId:B,activeClient:n,materialFacts:De,thresholdKeyMaterial:w.threshold.thresholdKeyMaterial,walletId:t.walletSession.walletId,nearAccountId:S,operationId:M.operationId,operationFingerprint:k,displayDigest:L.intentDigest,txSigningRequest:E,transactionContext:ke,authorization:{kind:`operation_step_up`,prepared:pa(be),displayDigest:L.intentDigest,proof:R.kind===`passkey`?{kind:`passkey`,authority:R.plannedPasskeyOperationStepUp.authority,credential:R.credential}:{...Ei({preparation:v,auth:m.lane.auth,walletId:t.walletSession.walletId,challengeId:R.challengeId,otpCode:R.otpCode})},issuedAuthorization:Oe}});if(r)return r.okResponse;throw Error(`[SigningEngine][near] Router A/B Ed25519 signing is unavailable`)};return await ie({commandKind:Dt.Sign,execute:async()=>{try{let t=await Me(V);we=!0;let n=performance.now();await ka(e,Ae),U(String(M.operationId),`nonce_lease_commit`,n);let r=performance.now(),i=Aa({okResponse:t,nearAccountId:S,warnings:te,nonceLeases:Ae});return U(String(M.operationId),`transaction_assembly`,r),U(String(M.operationId),`confirmed_to_signed`,_e),Z(a,S,{phase:z.STEP_11_TRANSACTION_SIGNED,status:`succeeded`,interaction:{kind:`none`,overlay:`hide`}}),Z(a,S,{phase:z.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`sign`}}),i}catch(e){let t=e instanceof Error?e:Error(String(e));throw await je(t),ha({resolved:xe,owned:Se}),t}}})}async function Oa(e,t,n){t.length&&await Promise.all(t.map(t=>e.nonceCoordinator.release({leaseId:t.leaseId,operationId:t.operationId,operationFingerprint:t.operationFingerprint,reason:n})))}async function ka(e,t){t.length&&await Promise.all(t.map(t=>e.nonceCoordinator.markSigned({leaseId:t.leaseId,operationId:t.operationId,operationFingerprint:t.operationFingerprint})))}function Aa(e){let t=e.okResponse.payload.signedTransactions||[];if(t.length!==1)throw Error(`Expected one signed transaction but received ${t.length}`);let n=t[0];if(!n||!n.transaction||!n.signature)throw Error(`Incomplete signed transaction data received`);let r=e.nonceLeases?.[0],i=n.serverDispatch;return{signedTransaction:new Nn({transaction:n.transaction,signature:n.signature,borsh_bytes:Array.from(n.borshBytes||[]),...r?{nonceLease:r}:{},...i?{serverDispatch:i}:{}}),nearAccountId:P(e.nearAccountId),logs:[...e.okResponse.payload.logs||[],...e.warnings],...r?{nonceLease:r}:{}}}function ja(e){let t=e.thresholdKeyMaterial;if(!t)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let n=String(t.publicKey||``).trim();if(!n)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);let r=String(e.relayerUrl||``).trim();if(!r)throw Error(`Missing relayerUrl (required for threshold-signer)`);let i=x(t.participants.map(e=>e.id));if(!i||i.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(i||[]).join(`,`)}])`);return{signingNearPublicKeyStr:n,threshold:{relayerUrl:r,thresholdKeyMaterial:t}}}const Ma=e=>typeof e==`string`?e:N(ae(e.keyData));function Q(e){return typeof e!=`number`||!Number.isFinite(e)||e<0?null:Math.round(e)}function Na(e){if(e==null||!o(e))return;let t=e;if(t.kind!==`registration_confirmation_diagnostics_v1`)return;let n=Q(t.workerReadyMs),r=Q(t.workerRequestRoundTripMs),i=Q(t.workerResponseValidationMs),a=Q(t.requestSetupMs),s=Q(t.promptUserMs),c=Q(t.promptElementDefineMs),l=Q(t.promptMountMs),u=Q(t.promptHostFirstUpdateMs),d=Q(t.promptHostInteractiveMs),f=Q(t.promptConfirmEventMs),p=Q(t.promptDecisionWaitMs),m=Q(t.credentialCreateStartMs),h=Q(t.credentialCreateMs),g=Q(t.credentialSerializeMs),_=Q(t.duplicateRetryCount),v=Q(t.mainThreadTotalMs);if(!(n==null||r==null||i==null||a==null||s==null||c==null||l==null||u==null||d==null||f==null||p==null||m==null||h==null||g==null||_==null||v==null))return{kind:`registration_confirmation_diagnostics_v1`,workerReadyMs:n,workerRequestRoundTripMs:r,workerResponseValidationMs:i,requestSetupMs:a,promptUserMs:s,promptElementDefineMs:c,promptMountMs:l,promptHostFirstUpdateMs:u,promptHostInteractiveMs:d,promptConfirmEventMs:f,promptDecisionWaitMs:p,credentialCreateStartMs:m,credentialCreateMs:h,credentialSerializeMs:g,duplicateRetryCount:_,mainThreadTotalMs:v}}function Pa(e){if(e==null)return;if(!o(e))throw Error(`Invalid transactionContext: expected object`);let{nearPublicKeyStr:t,nextNonce:n,txBlockHeight:r,txBlockHash:i,accessKeyInfo:a}=e,s=d(t,`transactionContext.nearPublicKeyStr`),c=d(n,`transactionContext.nextNonce`),l=d(r,`transactionContext.txBlockHeight`),u=d(i,`transactionContext.txBlockHash`),f=a;if(f!=null&&!o(f))throw Error(`Invalid transactionContext.accessKeyInfo: expected object`);return f??={nonce:0},{nearPublicKeyStr:s,nextNonce:c,txBlockHeight:l,txBlockHash:u,accessKeyInfo:f}}function Fa(e){if(e==null)return;let t=Ae(e);if(t.type!==`public-key`)throw Error(`Invalid credential.type: expected "public-key"`);let{id:n,rawId:r,response:i,authenticatorAttachment:a}=t;if(d(n,`credential.id`),d(r,`credential.rawId`),!o(i))throw Error(`Invalid credential.response: expected object`);let{clientDataJSON:s,attestationObject:c,transports:l}=i;if(d(s,`credential.response.clientDataJSON`),d(c,`credential.response.attestationObject`),!Array.isArray(l))throw Error(`Invalid credential.response.transports: expected string[]`);for(let e of l)if(typeof e!=`string`)throw Error(`Invalid credential.response.transports item: expected string`);if(a!=null&&typeof a!=`string`)throw Error(`Invalid credential.authenticatorAttachment: expected string | undefined`);return t}function Ia(e){if(!o(e))throw Error(`Invalid response payload: expected object`);let{confirmed:t,requestId:n,intentDigest:r,credential:i,transactionContext:a,registrationDiagnostics:s,error:c}=e,l=d(n,`requestId`),u=r==null?``:d(r,`intentDigest`),f=i==null?void 0:Fa(i);if(!f)throw Error(`Missing registration credential`);let p=a==null?void 0:Pa(a),m=Na(s),h=c==null?void 0:d(c,`error`);return{confirmed:!!t,requestId:l,intentDigest:u,credential:f,...p?{transactionContext:p}:{},...m?{registrationDiagnostics:m}:{},...h==null?{}:{error:h}}}function La(e){let t=e.selectedLane.identity.signer,n=I(e.commandSubject.walletSession.walletId),r=String(e.commandSubject.nearAccount.accountId);if(t.account.wallet.walletId!==n||String(t.account.nearAccountId)!==r)throw Error(`[SigningEngine][near] selected Ed25519 lane does not match command subject`);return{walletId:n,nearAccountId:r}}function Ra(e){let t=e.selectedLane.identity.signer,n={walletId:t.account.wallet.walletId,nearAccountId:t.account.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot,walletSessionId:e.selectedLane.walletSessionId,quotaId:e.selectedLane.quotaId,thresholdSessionId:e.selectedLane.thresholdSessionId};switch(e.selectedLane.auth.kind){case`passkey`:return He({...n,auth:e.selectedLane.auth,storageSource:`login`});case`email_otp`:{let t=e.preparation.authorization.kind===`authorized`;return He({...n,auth:e.selectedLane.auth,retention:t?`session`:`single_use`,sessionOrigin:t?`login`:`per_operation`})}default:throw e.selectedLane.auth,Error(`[SigningEngine][near] unsupported selected Ed25519 auth binding`)}}function za(e){let t=H.thresholdEd25519Session(e.selectedLane.thresholdSessionId);switch(e.preparation.authorization.kind){case`authorized`:{let n=e.preparation.authorization.authorization.status,r=n.remainingUses,i=n.expiresAtMs,a=i<=Date.now()?`expired`:r<e.requiredSignatureUses?`exhausted`:`ready`;return{readiness:a===`expired`?{status:`expired`,curve:`ed25519`,thresholdSessionId:t,expiresAtMs:i}:{status:a,curve:`ed25519`,thresholdSessionId:t,remainingUses:r,expiresAtMs:i},expiresAtMs:i,remainingUses:r,forceFreshAuth:a!==`ready`}}case`authorization_required`:return{readiness:{status:`missing_session`,curve:`ed25519`,thresholdSessionId:t},expiresAtMs:0,remainingUses:0,forceFreshAuth:!0};default:throw e.preparation.authorization,Error(`[SigningEngine][near] unsupported material authorization state`)}}function Ba(e){La(e);let t=Math.max(1,Math.floor(Number(e.requiredSignatureUses)||1)),n=Ra(e),r=za({selectedLane:e.selectedLane,preparation:e.preparation,requiredSignatureUses:t});return Ye(`near`,n,{reason:`near_threshold_auth_plan`}),{thresholdSessionId:H.thresholdEd25519Session(e.selectedLane.thresholdSessionId),lane:n,coordinatorInput:{lane:n,readiness:r.readiness,expiresAtMs:r.expiresAtMs,remainingUses:r.remainingUses,forceFreshAuth:e.forceFreshAuth||r.forceFreshAuth}}}function Va(e){let{lane:t}=e.context,n=e.resolvedSigningSession,r=n.signingSessionPlan;if(r.kind===V.NotReady)throw Error(`[SigningEngine][near] signing session is not ready: ${r.reason}`);return{signingAuthPlan:Pt({plan:r,accountId:String(t.identity.signer.account.nearAccountId),intent:Te.TransactionSign,curve:`ed25519`,expiresAtMs:n.expiresAtMs,remainingUses:n.remainingUses})}}function Ha(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation step-up preparation is missing`);return t}function Ua(e,t){if(!t||t.kind!==`near_signature_only`)throw Error(`[SigningEngine][near] ${e} operation step-up preparation kind changed`);return t}function Wa(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation step-up material is missing`);return t}function Ga(e,t){if(!t)throw Error(`[SigningEngine][near] ${e} operation signing digest is missing`);return t}function Ka(e){if(!e)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return e}async function qa(e){if(e.authorization.kind===`passkey`){if(e.material.kind!==`passkey_live`&&e.material.kind!==`passkey_sealed`)throw Error(`[SigningEngine][near] passkey ${e.label} material changed factor`);return await ua({kind:`passkey`,material:e.material,expectedActivation:e.prepared.materialActivation,credential:e.authorization.credential})}if(e.material.kind!==`email_otp_live`&&e.material.kind!==`email_otp_sealed`)throw Error(`[SigningEngine][near] Email OTP ${e.label} material changed factor`);if(!e.emailOtpProof)throw Error(`[SigningEngine][near] Email OTP ${e.label} proof is missing`);return e.material.kind===`email_otp_live`?await ua({kind:`email_otp_live`,material:e.material,expectedActivation:e.prepared.materialActivation}):await ua({kind:`email_otp_sealed`,material:e.material,expectedActivation:e.prepared.materialActivation,normalSigningRequest:e.prepared.prepare.request,displayDigest:e.displayDigest,proof:e.emailOtpProof})}function Ja(e){if(e.selection.kind===`authorized`){let t=Ba({requiredSignatureUses:1,commandSubject:e.commandSubject,forceFreshAuth:e.forceFreshAuth,selectedLane:e.selection.selectedLane,preparation:e.preparation}),n={signingSessionPlan:yn({lane:t.coordinatorInput.lane,readiness:t.coordinatorInput.readiness,forceFreshAuth:t.coordinatorInput.forceFreshAuth}),readiness:t.coordinatorInput.readiness,expiresAtMs:t.coordinatorInput.expiresAtMs||0,remainingUses:t.coordinatorInput.remainingUses||0};return{signingAuthPlan:Va({context:t,resolvedSigningSession:n}).signingAuthPlan,signingSessionPlan:n.signingSessionPlan}}let t=e.selection.candidate,n=hr(t.auth),r={kind:`deferred_ed25519_material_identity`,signer:Ve({walletId:t.walletId,nearAccountId:t.nearAccountId,nearEd25519SigningKeyId:t.nearEd25519SigningKeyId,signerSlot:t.signerSlot}),materialActivation:t.materialActivation,thresholdSessionId:H.thresholdEd25519Session(t.thresholdSessionId)};return{signingAuthPlan:n,signingSessionPlan:{kind:V.OperationStepUp,lane:{identity:r,auth:t.auth,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,sessionOrigin:`per_operation`,storageSource:`sealed_restore`,retention:`single_use`,materialActivation:r.materialActivation,thresholdSessionId:r.thresholdSessionId}}}}async function Ya(e,t){let n=await mr({signingAuthPlan:t.signingAuthPlan,signingLaneAuth:e.auth,requiredSignatureUses:1,operationFingerprintDigest:Ge(e.signingOperation.operationFingerprint),passkeyEd25519OperationStepUp:t.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:t.emailOtpEd25519StepUp});if(n.kind===`warm_session`)return{preparedStepUp:n,operationStepUp:null};let r=await la({method:n.kind,preparation:e.preparation,executor:e.executor}),i=sa(r),a=await e.computeSigningDigestB64u();return ei({requestId:String(e.signingOperation.operationId),build:async t=>{if(t.kind!==`near_signature_only`)throw Error(`[SigningEngine][near] ${e.label} operation step-up preparation kind changed`);return await Ti({ctx:e.ctx,thresholdSessionId:i.thresholdSessionId,materialFacts:i,walletId:e.walletId,nearAccountId:e.nearAccountId,materialActivation:r.materialActivation,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:a,intent:e.intent})}}),{preparedStepUp:n,operationStepUp:{material:r,signingDigestB64u:a}}}async function Xa(e,t){let n=String(e.signingOperation.operationId);try{return await Et({signingSessionPlan:e.signingSessionPlan,signingOperation:e.signingOperation,runtime:t.touchConfirm,request:{ctx:{touchConfirm:t.touchConfirm},sessionId:n,chain:`near`,...t.request,...Ot({signingAuthPlan:t.signingAuthPlan}),walletId:String(e.walletId),nearAccountId:e.nearAccountId,nearPublicKeyStr:t.nearPublicKeyStr,title:t.title,body:t.body,confirmationConfigOverride:At({signingAuthPlan:t.signingAuthPlan,override:t.confirmationConfigOverride}),onProgress:Sr.bind(void 0,{onEvent:t.onEvent,nearAccountId:e.nearAccountId,signingAuthPlan:t.signingAuthPlan})}})}finally{ti(n)}}function Za(e,t,n){let r=wr({prepared:t.preparedStepUp,confirmation:n});if(r.kind===`warm_session`)return{kind:`warm_session`,displayDigest:n.intentDigest,stepUpAuthorization:r};let i=Di({authorization:r,preparation:e.preparation,auth:e.auth,walletId:e.walletId}),a=Ua(e.label,ri({requestId:String(e.signingOperation.operationId),ref:Ha(e.label,n.operationStepUpPreparation)}));return{kind:`operation_step_up`,displayDigest:n.intentDigest,stepUpAuthorization:r,proof:i,prepared:a,...Wa(e.label,t.operationStepUp)}}async function Qa(e,t,n){if(t.preparedStepUp.kind!==`warm_session`||e.intent.kind!==`nep413_message_v1`)return null;let r=await da({preparation:e.preparation,executor:e.executor}),i=Ka(await n.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:r.walletSessionState,nowMs:Date.now()})),a=await Pi({ctx:e.ctx,thresholdSessionId:r.thresholdSessionId,activeClient:r.material.activeClient,walletSessionState:i,walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:await Qe({nearAccountId:e.nearAccountId,recipient:e.intent.recipient,message:e.intent.message}),signingDigestB64u:await e.computeSigningDigestB64u(),intent:e.intent});return a?{resolved:r,started:a}:null}async function $a(e,t,n=null){if(t.kind===`warm_session`){let r=n?.resolved??await da({preparation:e.preparation,executor:e.executor});return{kind:`warm_session`,thresholdSessionId:r.thresholdSessionId,displayDigest:t.displayDigest,resolved:r,startedPrepare:n?.started}}return n&&Fi(n.started),{kind:`operation_step_up`,thresholdSessionId:sa(t.material).thresholdSessionId,displayDigest:t.displayDigest,resolved:await qa({label:e.label,material:t.material,prepared:t.prepared,displayDigest:t.displayDigest,authorization:t.stepUpAuthorization,emailOtpProof:t.proof.kind===`email_otp`?t.proof:null}),proof:t.proof,prepared:t.prepared,signingDigestB64u:t.signingDigestB64u}}async function eo(e,t,n){let r=t.kind===`warm_session`?await e.computeSigningDigestB64u():Ga(e.label,t.signingDigestB64u),i=t.kind===`warm_session`?await Mi({ctx:e.ctx,thresholdSessionId:t.thresholdSessionId,activeClient:t.resolved.material.activeClient,sessionCoordinator:n,walletSessionState:Ka(await n.resolveActiveAuthorizedRouterAbEd25519WalletSessionState({state:t.resolved.walletSessionState,nowMs:Date.now()})),walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:r,intent:e.intent,authorization:{kind:`reusable_wallet_session`},startedPrepare:t.startedPrepare}):await Mi({ctx:e.ctx,thresholdSessionId:t.thresholdSessionId,activeClient:t.resolved.material.activeClient,materialFacts:t.resolved.material.facts,walletId:e.walletId,thresholdKeyMaterial:e.thresholdKeyMaterial,nearAccountId:e.nearAccountId,operationId:e.signingOperation.operationId,operationFingerprint:e.signingOperation.operationFingerprint,displayDigest:t.displayDigest,signingDigestB64u:r,intent:e.intent,authorization:{kind:`operation_step_up`,prepared:t.prepared,proof:t.proof,issuedAuthorization:t.resolved.issuedAuthorization}});if(!i)throw Error(`[SigningEngine][near] Router A/B Ed25519 ${e.label} signing is unavailable`);return t.kind===`operation_step_up`&&i.authorization===`operation_step_up`&&si({prepared:t.prepared,issuedAuthorization:i.issuedAuthorization}),{signingDigestB64u:r,signatureB64u:i.signatureB64u,signerPublicKey:i.signerPublicKey}}async function to(e,t){return await wt({signingSessionPlan:e.signingSessionPlan,signingOperation:e.signingOperation,commandKind:Dt.Sign,execute:async()=>{try{return await t()}catch(e){throw e instanceof Error?e:Error(String(e))}}})}function $(e,t,n){try{e?.(xe({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function no(e){switch(e.kind){case`warm_session`:return`warm_session`;case`passkey`:return`passkey`;case`email_otp`:return`email_otp`;default:return ro(e)}}function ro(e){throw Error(`[SigningEngine][near] unsupported prepared step-up: ${String(e)}`)}async function io({ctx:e,commandSubject:t,nearAccount:n,delegate:r,rpcCall:i,onEvent:a,confirmationConfigOverride:o,title:c,body:l,operationId:u,signerSlot:d,signingSessionCoordinator:p,forceFreshAuth:m,passkeyEd25519OperationStepUp:h,emailOtpEd25519StepUp:g,yaoSigningPreparation:_,yaoMaterialExecutor:v,selection:y}){let b=y.kind===`authorized`?y.selectedLane.auth:y.candidate.auth,x=y.kind===`authorized`?y.selectedLane.identity.signer.signerSlot:y.candidate.signerSlot,S=P(n.accountId),ee=e.relayerUrl,te={nearRpcUrl:i.nearRpcUrl||f(mt.network.chains),nearAccountId:S},C=[],ne=e.touchConfirm;if(!ne)throw Error(`UiConfirm bridge not available for delegate signing`);let{signingAuthPlan:w,signingSessionPlan:T}=Ja({selection:y,commandSubject:t,forceFreshAuth:m,preparation:_});$(a,S,{phase:z.STEP_02_REQUEST_PREPARED,status:`running`,message:`Loading threshold signing state`,interaction:{kind:`none`,overlay:`none`}});let{thresholdKeyMaterial:E}=await Un({materialExecutor:v,nearAccount:n,signerSlot:x,requestedSignerSlot:d,operationLabel:`delegate signing`,warnings:C}),D=ao({nearAccountId:S,relayerUrl:ee,thresholdKeyMaterial:E,providedDelegatePublicKey:r.publicKey,warnings:C}),O=Gn({nearAccountId:S,delegate:r,signingPublicKey:D.delegatePublicKeyStr}),k={...O.workerDelegate,actions:O.workerDelegate.actions.map((e,t)=>rr(e,`delegate.actions[${t}]`))},re={operationId:u,operationFingerprint:H.signingOperationFingerprint(await Xn({nearAccountId:S,nearNetworkId:s(e.chains||mt.network.chains),relayerKeyId:D.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:D.delegatePublicKeyStr,delegate:k})),intent:Te.TransactionSign},A={label:`delegate`,ctx:e,walletId:t.walletSession.walletId,nearAccountId:S,auth:b,signingSessionPlan:T,signingOperation:re,thresholdKeyMaterial:D.threshold.thresholdKeyMaterial,preparation:_,executor:v,intent:{kind:`near_delegate_action_v1`,delegate:k},computeSigningDigestB64u:async()=>(await jr({delegate:O.workerDelegate,workerCtx:e})).signingDigestB64u},j=await Ya(A,{signingAuthPlan:w,passkeyEd25519OperationStepUp:h,emailOtpEd25519StepUp:g}),M=j.preparedStepUp.confirmationAuthPayload;bt(M.signingAuthPlan)&&$(a,S,{phase:z.STEP_06_AUTH_WARM_SESSION_CLAIMED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{thresholdSessionId:M.signingAuthPlan.thresholdSessionId,expiresAtMs:M.signingAuthPlan.expiresAtMs,remainingUses:M.signingAuthPlan.remainingUses}}),$(a,S,{phase:z.STEP_05_CONFIRMATION_DISPLAYED,status:`waiting_for_user`,message:`Opening confirmation prompt`,interaction:{kind:`transaction_confirmation`,overlay:`show`}});let ie=await Xa(A,{touchConfirm:ne,signingAuthPlan:M.signingAuthPlan,nearPublicKeyStr:D.signingNearPublicKeyStr,onEvent:a,title:c,body:l,confirmationConfigOverride:o,request:{kind:`delegate`,delegate:O.confirmationDelegate,rpcCall:te}});$(a,S,{phase:z.STEP_05_CONFIRMATION_APPROVED,status:`succeeded`,interaction:{kind:`transaction_confirmation`,overlay:`hide`}});let ae=Za(A,j,ie),N=await wt({signingSessionPlan:T,signingOperation:re,commandKind:Dt.PreparePayload,execute:async()=>{$(a,S,{phase:z.STEP_08_SIGNER_PREPARE_STARTED,status:`running`,message:`Preparing NEAR signer`,interaction:{kind:`none`,overlay:`none`}});let e=await $a(A,ae);return $(a,S,{phase:z.STEP_07_AUTHENTICATION_COMPLETE,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},authMethod:no(j.preparedStepUp)}),$(a,S,{phase:z.STEP_08_SIGNER_PREPARE_SUCCEEDED,status:`succeeded`,message:`NEAR signer ready`,interaction:{kind:`none`,overlay:`none`},data:{signer:`threshold-ed25519`,thresholdSessionId:e.thresholdSessionId,clientBaseSource:`yao_active_client`}}),e}}),F=await to(A,async()=>{$(a,S,{phase:z.STEP_10_COMMIT_STARTED,status:`running`,interaction:{kind:`none`,overlay:`none`}});let t=await eo(A,N,p),n=await _i({ctx:e,delegate:O.workerDelegate,signingDigestB64u:t.signingDigestB64u,signatureB64u:t.signatureB64u});return{type:Ut.SignDelegateActionSuccess,payload:{success:!0,hash:n.hash,signedDelegate:n.signedDelegate,logs:[`Delegate action signed through Router A/B normal signing`],error:void 0}}});return $(a,S,{phase:z.STEP_11_TRANSACTION_SIGNED,status:`succeeded`,interaction:{kind:`none`,overlay:`hide`}}),$(a,S,{phase:z.STEP_15_COMPLETED,status:`succeeded`,interaction:{kind:`none`,overlay:`none`},data:{operation:`sign_delegate`,hash:F.payload.hash}}),{signedDelegate:F.payload.signedDelegate,hash:F.payload.hash,nearAccountId:P(S),logs:[...F.payload.logs||[],...C]}}function ao(e){let t=N(Ma(e.providedDelegatePublicKey)),n=e.thresholdKeyMaterial;if(!n)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let r=N(n.publicKey);if(!r)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);if(t&&t!==r&&e.warnings.push(`Delegate public key ${t} does not match threshold signer key; using ${r}`),!String(e.relayerUrl||``).trim())throw Error(`Missing relayerUrl (required for threshold-signer)`);let i=x(n.participants.map(e=>e.id));if(!i||i.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(i||[]).join(`,`)}])`);return{signingNearPublicKeyStr:r,delegatePublicKeyStr:r,threshold:{thresholdKeyMaterial:n}}}async function oo({ctx:e,commandSubject:t,nearAccount:n,signingSessionCoordinator:r,payload:i,forceFreshAuth:a,passkeyEd25519OperationStepUp:o,emailOtpEd25519StepUp:c,yaoSigningPreparation:l,yaoMaterialExecutor:u,selection:d,onEvent:f}){let p=d.kind===`authorized`?d.selectedLane.auth:d.candidate.auth,m=d.kind===`authorized`?d.selectedLane.identity.signer.signerSlot:d.candidate.signerSlot,h=i.operationId,v=performance.now(),y=e.relayerUrl,b=n.accountId,x=e.touchConfirm;if(!x)throw Error(`UiConfirm bridge not available for NEP-413 signing`);let{signingAuthPlan:S,signingSessionPlan:ee}=Ja({selection:d,commandSubject:t,forceFreshAuth:a,preparation:l}),{thresholdKeyMaterial:te}=await Un({materialExecutor:u,nearAccount:n,signerSlot:m,requestedSignerSlot:i.signerSlot,operationLabel:`NEP-413 signing`}),C=so({nearAccountId:b,relayerUrl:y,thresholdKeyMaterial:te}),ne={operationId:h,operationFingerprint:H.signingOperationFingerprint(await Yn({nearAccountId:b,nearNetworkId:s(e.chains||mt.network.chains),relayerKeyId:C.threshold.thresholdKeyMaterial.relayerKeyId,signerPublicKey:C.threshold.thresholdKeyMaterial.publicKey,message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl})),intent:Te.TransactionSign},w={label:`NEP-413`,ctx:e,walletId:t.walletSession.walletId,nearAccountId:b,auth:p,signingSessionPlan:ee,signingOperation:ne,thresholdKeyMaterial:C.threshold.thresholdKeyMaterial,preparation:l,executor:u,intent:{kind:`nep413_message_v1`,message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl},computeSigningDigestB64u:async()=>(await Ar({message:i.message,recipient:i.recipient,nonce:i.nonce,callbackUrl:i.callbackUrl,workerCtx:e})).signingDigestB64u},T=await Ya(w,{signingAuthPlan:S,passkeyEd25519OperationStepUp:o,emailOtpEd25519StepUp:c}),E=await Qa(w,T,r);U(String(h),`pre_confirmation`,v);let D=performance.now(),O=await Xa(w,{touchConfirm:x,signingAuthPlan:T.preparedStepUp.confirmationAuthPayload.signingAuthPlan,nearPublicKeyStr:C.nearPublicKey,onEvent:f,title:i.title,body:i.body,confirmationConfigOverride:i.confirmationConfigOverride,request:{kind:`nep413`,message:i.message,recipient:i.recipient}});U(String(h),`confirmation`,D);let k=performance.now(),re=Za(w,T,O),A=await wt({signingSessionPlan:ee,signingOperation:ne,commandKind:Dt.PreparePayload,execute:async()=>await $a(w,re,E)}),j=await to(w,async()=>{let e=await eo(w,A,r);return{type:Ut.SignNep413MessageSuccess,payload:{accountId:b,publicKey:e.signerPublicKey,signature:g(_(e.signatureB64u)),state:i.state??void 0}}});return U(String(h),`confirmed_to_signed`,k),{success:!0,accountId:j.payload.accountId,publicKey:j.payload.publicKey,signature:j.payload.signature,state:j.payload.state}}function so(e){let t=e.thresholdKeyMaterial;if(!t)throw Error(`Missing threshold key material for ${e.nearAccountId}`);let n=String(t.publicKey||``).trim();if(!n)throw Error(`Missing threshold signing public key for ${e.nearAccountId}`);if(!String(e.relayerUrl||``).trim())throw Error(`Missing relayerUrl (required for threshold-signer)`);let r=x(t.participants.map(e=>e.id));if(!r||r.length<2)throw Error(`Invalid threshold signing participantIds (expected >=2 participants, got [${(r||[]).join(`,`)}])`);return{nearPublicKey:n,threshold:{thresholdKeyMaterial:t}}}async function co(e){if(e.chain!==`near`)throw Error(`[NearSigningFlow] invalid chain`);return e.kind===`transactionWithActions`?(lo(e.payload),await Ta(e.payload)):e.kind===`delegateAction`?(fo(e.payload),await io(e.payload)):e.kind===`nep413`?(po(e.payload),await oo(e.payload)):e}function lo(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required`);if(String(e.rpcCall?.nearAccountId||``).trim()!==t)throw Error(`[NearSigningFlow] rpcCall.nearAccountId must match nearAccount.accountId`);let n=e.transactions;Array.isArray(n)&&Or(n),uo(e.transaction,0)}function uo(e,t){if(!String(e?.receiverId||``).trim())throw Error(`[NearSigningFlow] transactions[${t}].receiverId is required`);let n=Array.isArray(e?.actions)?e.actions:[];if(n.length===0)throw Error(`[NearSigningFlow] transactions[${t}].actions must be non-empty`);n.forEach(Ze)}function fo(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required`);if(String(e.rpcCall?.nearAccountId||``).trim()!==t)throw Error(`[NearSigningFlow] rpcCall.nearAccountId must match nearAccount.accountId`);if(!String(e.delegate?.receiverId||``).trim())throw Error(`[NearSigningFlow] delegate.receiverId is required`);let n=Array.isArray(e.delegate?.actions)?e.delegate.actions:[];if(n.length===0)throw Error(`[NearSigningFlow] delegate.actions must be non-empty`);n.forEach(e=>Ze(et(e)))}function po(e){let t=String(e.nearAccount?.accountId||``).trim();if(!t)throw Error(`[NearSigningFlow] nearAccount is required for NEP-413`);if(String(e.payload?.accountId||``).trim()!==t)throw Error(`[NearSigningFlow] payload.accountId must match nearAccount.accountId`);if(!String(e.payload?.recipient||``).trim())throw Error(`[NearSigningFlow] recipient is required for NEP-413`);if(!String(e.payload?.message||``).trim())throw Error(`[NearSigningFlow] message is required for NEP-413`)}var mo=e({signDelegateAction:()=>ts,signNear:()=>vo});function ho(e){if(!(e instanceof st))return;let t=e.authorizationDecision;if(!(!t||t.kind!==`step_up_required`||!(`request_id`in t.step_up)))return{kind:`step_up_required`,reason:t.reason,step_up:t.step_up}}function go(e){let t=ho(e),n=it(e);return t?rt(n??{kind:`exhausted`,source:`server_prepare`,detail:`Server requires owner operation step-up`}):n?.kind===`in_flight`?rt(n):null}async function _o(e){if(e.failure?.kind!==`expired`)return;let t=yt({source:{kind:`ed25519`,laneIdentity:Be(e.lane)},expiresAtMs:e.expiresAtMs,detectedAtMs:Date.now()});if((await e.coordinator.invalidateExpiredWalletSession({state:t,source:be.serverRejection})).kind===`unavailable`)throw Error(`[SigningEngine][near] expired Wallet Session cleanup failed`)}async function vo(e,t){if(t.kind===`transactionWithActions`){let n=e.getSignerWorkerContext(),r=te(n.touchConfirm?.getContext().surfaceMeasurementBinding);return r&&(r.assertPending(),e={...e,getSignerWorkerContext:as.bind(null,n,r.beforeSigning)}),await Zo(e,t.args)}if(t.kind===`delegateAction`)return await ts(e,t.args);if(t.kind===`nep413`)return await is(e,t.args);throw Error(`[SigningEngine] unsupported near signing intent: ${String(t.kind||``)}`)}function yo(){let e=y(32,`NEAR transaction signing operation IDs`);return H.signingOperation(`near-transaction-sign:${e}`)}function bo(e){return e.state===`missing`?{state:e.state,curve:e.curve,chain:e.chain}:{authMethod:B(e.auth),walletId:e.walletId,nearAccountId:e.nearAccountId,nearEd25519SigningKeyId:e.nearEd25519SigningKeyId,signerSlot:e.signerSlot,state:e.state,source:e.source||`unknown`,...e.authorizationState===`authorized`?{walletSessionId:e.authorization.operationCredential.walletSessionId,quotaId:e.authorization.session.quotaId}:{},thresholdSessionId:e.thresholdSessionId,remainingUses:e.remainingUses,expiresAtMs:e.expiresAtMs}}function xo(e){let t=e?.candidates.ed25519.near||[];return{generation:e?.generation||0,candidateCount:t.length,candidates:t.map(bo)}}function So(e,t,n){try{e?.(xe({...n,flowId:`signing:near:${String(t)}:${n.phase}`,accountId:String(t)}))}catch{}}function Co(e){if(ze(e.signingLane.identity)!==ze(e.transactionLane.identity))throw Error(`[SigningEngine][near] prepared signing lane drifted from selected transaction lane`)}function wo(e,t){let n=e.identity.signer,r=t.identity.signer;return String(n.account.wallet.walletId)===String(r.account.wallet.walletId)&&String(n.account.nearAccountId)===String(r.account.nearAccountId)&&String(n.nearEd25519SigningKeyId)===String(r.nearEd25519SigningKeyId)&&n.signerSlot===r.signerSlot&&De(e.auth)===De(t.auth)}function To(e){let t=e.readiness.status;return t===`ready`?{status:`ready`,remainingUses:Math.max(0,Math.floor(Number(e.readiness.remainingUses)||0)),expiresAtMs:Math.max(0,Math.floor(Number(e.readiness.expiresAtMs)||0))}:t===`expired`||t===`exhausted`||t===`status_unknown`?t===`status_unknown`?{status:t,reason:`trusted wallet budget status is unavailable`}:{status:t}:t===`auth_unavailable`||t===`status_unavailable`?{status:t,reason:t}:{status:`status_unavailable`,reason:t}}function Eo(e){if(e.curve!==`ed25519`||e.keyKind!==`threshold_ed25519`)throw Error(`[SigningEngine][near] prepared signing lane is not Ed25519`);if(e.chainFamily!==`near`)throw Error(`[SigningEngine][near] prepared Ed25519 lane must target NEAR`);let t=String(e.thresholdSessionId||``).trim(),n=String(e.walletSessionId||``).trim(),r=String(e.quotaId||``).trim();if(!t||!n||!r)throw Error(`[SigningEngine][near] prepared Ed25519 lane is missing session identity`);return{...e,curve:`ed25519`,keyKind:`threshold_ed25519`,chainFamily:`near`,walletSessionId:H.walletSession(n),quotaId:H.walletSessionQuota(r),thresholdSessionId:H.thresholdEd25519Session(t)}}async function Do(e){let t=e.preparedOperation,n=t.lane;Ye(`near`,n,{reason:`near_transaction_auth_planning`});let r=e.commandSubject.nearAccount.accountId,i={accountId:r,intent:Te.TransactionSign,curve:`ed25519`},a=t.signingSessionPlan;if(a.kind===V.NotReady)throw console.warn(`[SigningEngine][near][ed25519] transaction auth planning not ready`,{nearAccountId:r,authMethod:B(n.auth),reason:a.reason,readiness:t.readiness.status,walletSessionId:n.walletSessionId,quotaId:n.quotaId,thresholdSessionId:n.thresholdSessionId,retention:n.retention,remainingUses:t.remainingUses,expiresAtMs:t.expiresAtMs}),a.reason===`policy_blocked`?Error(`[SigningEngine] NEAR operation requires passkey authentication after Email OTP login`):Error(`[SigningEngine][near] signing session is not ready: ${a.reason}`);return{signingAuthPlan:Pt({plan:a,accountId:i.accountId,intent:i.intent,curve:i.curve,expiresAtMs:t.expiresAtMs,remainingUses:t.remainingUses}),signingLane:n}}function Oo(e){let t=String(e.providedThresholdSessionId||``).trim(),n=String(e.identity.thresholdSessionId||``).trim();if(t&&t!==n)throw Error(`[SigningEngine][near] transaction thresholdSessionId must match prepared Ed25519 identity`);return n}function ko(e){switch(e.authorization.kind){case`authorized`:return!1;case`authorization_required`:return!0;default:throw e.authorization,Error(`[SigningEngine][near] unsupported material authorization state`)}}function Ao(e){if(e.authorization.kind!==`authorized`)throw Error(`[SigningEngine][near] reusable Wallet Session authorization is unavailable`);return e.authorization.authorization.status.expiresAtMs}async function jo(e){let t={walletId:I(e.commandSubject.walletSession.walletId),nearAccountId:P(e.commandSubject.nearAccount.accountId)};return e.materialIdentity?await e.deps.prepareNearEd25519YaoMaterialBoundary({...t,materialIdentity:e.materialIdentity}):await e.deps.prepareNearEd25519YaoMaterialBoundary({...t,laneIdentity:e.selectedLane.identity,auth:e.selectedLane.auth})}function Mo(e,t){return H.signingOperation(e.createSigningSessionId(`near-${t}-operation`))}function No(e){return{kind:`prepared_near_transaction_execution`,thresholdSessionId:e.thresholdSessionId,signingSessionPlan:e.preparedSigningSession.preparedOperation.signingSessionPlan,signingAuthPlan:e.preparedSigningSession.signingAuthPlan,signingLane:e.preparedSigningSession.signingLane,signingSessionCoordinator:e.signingSessionCoordinator,transactionOperation:e.preparedSigningSession.transactionOperation,passkeyEd25519OperationStepUp:e.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.emailOtpEd25519StepUp}}function Po(e){return ot({walletId:String(e.walletId),curve:`ed25519`,walletSessionId:String(e.prepared.signingLane.walletSessionId),quotaId:String(e.prepared.signingLane.quotaId),projectionVersion:`server-owned`,authorityKey:De(e.prepared.signingLane.auth),targetKey:`near:${String(e.nearAccountId)}`})}function Fo(e){if(e.prepared.kind!==`authorized`)throw Error(`[SigningEngine][near] deferred Ed25519 material has no reusable session`);return ot({walletId:String(e.walletId),curve:`ed25519`,walletSessionId:String(e.prepared.selectedLane.walletSessionId),quotaId:String(e.prepared.selectedLane.quotaId),projectionVersion:`projection-unadmitted`,authorityKey:De(e.prepared.selectedLane.auth),targetKey:`near:${String(e.nearAccountId)}`})}function Io(e){if(e.auth.kind!==`passkey`)return;let t=e.auth;return{prepare:async()=>{let n=e.signer,r=await Ro({authorityRef:Lo(e.preparation),walletId:n.account.wallet.walletId,rpId:t.rpId,credentialIdB64u:t.credentialIdB64u});return{thresholdSessionId:e.thresholdSessionId,authority:r}}}}function Lo(e){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:case`reauthorize_public_anchor`:return e.hydration.authority;case`blocked`:throw Error(`[SigningEngine][near] blocked Passkey material has no authority`);default:throw e.hydration,Error(`[SigningEngine][near] unsupported Passkey material authority`)}}async function Ro(e){let t=R({walletId:e.walletId,factor:{kind:`passkey`,credentialIdB64u:e.credentialIdB64u},verifier:{kind:`webauthn`,rpId:e.rpId},bindingId:e.authorityRef.walletAuthMethodId});if(!t)throw Error(`[SigningEngine][near] exact Passkey step-up authority is invalid`);let n=await L({authority:t});if(n.walletId!==e.authorityRef.walletId||n.walletAuthMethodId!==e.authorityRef.walletAuthMethodId||n.authorityDigest!==e.authorityRef.authorityDigest)throw Error(`[SigningEngine][near] exact Passkey step-up authority changed`);return t}function zo(e){if(e.auth.kind!==se.emailOtp||typeof e.deps.requestEmailOtpEd25519SigningChallenge!=`function`||!e.preparation.hydration.materialActivation)return;if(String(e.signer.account.wallet.walletId)!==String(e.commandSubject.walletSession.walletId)||String(e.signer.account.nearAccountId)!==String(e.commandSubject.nearAccount.accountId))throw Error(`[SigningEngine][near] Email OTP step-up lane changed subject`);let t=async t=>{let n=await e.deps.requestEmailOtpEd25519SigningChallenge({walletSession:e.commandSubject.walletSession,operationFingerprintDigest:t.operationFingerprintDigest});return So(e.onEvent,e.commandSubject.nearAccount.accountId,{phase:z.STEP_06_AUTH_EMAIL_OTP_INPUT_REQUIRED,status:`waiting_for_user`,interaction:{kind:`otp_input`,overlay:`show`},data:{emailHint:n.emailHint,demoOtpCode:ye(n.delivery)}}),n};return{prepare:t,resend:t}}async function Bo(e){let t=Vt({availableLanes:await Jo({deps:e.deps,commandSubject:e.commandSubject,authMethod:null}),intent:Go({commandSubject:e.commandSubject,signerSlot:e.signerSlot,authSelectionPolicy:{kind:`any`},operationUsesNeeded:1})});if(!t.ok)throw Error(`[SigningEngine][near] signature-only signing requires exact Ed25519 material`);if(t.kind===`authorization_required`){let n=t.candidate,r=Ve({walletId:n.walletId,nearAccountId:n.nearAccountId,nearEd25519SigningKeyId:n.nearEd25519SigningKeyId,signerSlot:n.signerSlot}),i={kind:`near_ed25519_material_identity`,signer:r,auth:n.auth,thresholdSessionId:H.thresholdEd25519Session(n.thresholdSessionId)},a=await jo({deps:e.deps,commandSubject:e.commandSubject,materialIdentity:i});return{kind:`authorization_required`,candidate:n,materialIdentity:i,forceFreshAuth:!0,passkeyEd25519OperationStepUp:Io({auth:n.auth,signer:r,thresholdSessionId:i.thresholdSessionId,preparation:a.preparation})||null,emailOtpEd25519StepUp:zo({deps:e.deps,commandSubject:e.commandSubject,auth:n.auth,signer:r,preparation:a.preparation,onEvent:e.onEvent})||null,yaoSigningPreparation:a.preparation,yaoMaterialExecutor:a.executor}}let n=t.lane,r=await jo({deps:e.deps,commandSubject:e.commandSubject,selectedLane:n});return{kind:`authorized`,selectedLane:n,forceFreshAuth:e.attempt.forceFreshAuth||ko(r.preparation),passkeyEd25519OperationStepUp:Io({auth:n.auth,signer:n.identity.signer,thresholdSessionId:n.identity.thresholdSessionId,preparation:r.preparation})||null,emailOtpEd25519StepUp:zo({deps:e.deps,commandSubject:e.commandSubject,auth:n.auth,signer:n.identity.signer,preparation:r.preparation,onEvent:e.onEvent})||null,yaoSigningPreparation:r.preparation,yaoMaterialExecutor:r.executor}}async function Vo(e){let t=vt({materialActivation:e.materialActivation});return await e.deps.withThresholdEd25519CommitQueue({queueKey:t,nearAccountId:e.nearAccountId,enabled:!0,task:e.task})}async function Ho(e){let t=e.availableLanes,n=Vt({availableLanes:t,intent:Go({commandSubject:e.commandSubject,signerSlot:e.input.signerSlot,authSelectionPolicy:{kind:`any`},operationUsesNeeded:Dr(e.input.transaction)})});if(!n.ok||n.kind!==`authorization_required`)return null;let r=n.candidate,i=Ve({walletId:r.walletId,nearAccountId:r.nearAccountId,nearEd25519SigningKeyId:r.nearEd25519SigningKeyId,signerSlot:r.signerSlot}),a={kind:`near_ed25519_material_identity`,signer:i,auth:r.auth,thresholdSessionId:H.thresholdEd25519Session(r.thresholdSessionId)},o=await jo({deps:e.deps,commandSubject:e.commandSubject,materialIdentity:a});return{candidate:r,preparation:o.preparation,executor:o.executor,passkeyEd25519OperationStepUp:Io({auth:r.auth,signer:i,thresholdSessionId:a.thresholdSessionId,preparation:o.preparation})||null,emailOtpEd25519StepUp:zo({deps:e.deps,commandSubject:e.commandSubject,auth:r.auth,signer:i,preparation:o.preparation,onEvent:e.input.onEvent})||null}}function Uo(e){switch(e.hydration.kind){case`use_live_runtime`:case`rehydrate_material_activation`:return e.hydration.materialActivation;case`reauthorize_public_anchor`:throw Error(`[SigningEngine][near] retired public material cannot enter the material commit queue`);case`blocked`:throw Error(`[SigningEngine][near] blocked material cannot enter the material commit queue: ${e.hydration.reason}`)}throw e.hydration,Error(`[SigningEngine][near] unsupported material hydration plan`)}function Wo(e){let t=e.authSelectionPolicy||null;if(!t)return null;let n=Lt(It(Rt(Go({commandSubject:e.commandSubject,signerSlot:e.signerSlot,authSelectionPolicy:t,operationUsesNeeded:e.operationUsesNeeded})),{availableLanes:e.availableLanes}));if(n.tag===`LaneSelected`){if(n.lane.curve!==`ed25519`||n.availableLane.curve!==`ed25519`)throw Error(`[SigningEngine][near] Ed25519 selector returned a non-Ed25519 lane`);return n}if(n.failure.kind===`no_candidate`)return null;throw Error(`[SigningEngine][near] Ed25519 transaction lane selection failed: ${n.failure.kind}`)}function Go(e){return{walletId:I(e.commandSubject.walletSession.walletId),curve:`ed25519`,chain:`near`,signerSelection:Ko({nearAccountId:e.commandSubject.nearAccount.accountId,signerSlot:e.signerSlot}),authSelectionPolicy:e.authSelectionPolicy,operationUsesNeeded:e.operationUsesNeeded}}function Ko(e){if(e.signerSlot===void 0)return{kind:`near_account`,nearAccountId:e.nearAccountId};let t=Se(e.signerSlot);if(t===null)throw Error(`[SigningEngine][near] signerSlot must be a positive safe integer`);return{kind:`signer_slot`,nearAccountId:e.nearAccountId,signerSlot:t}}function qo(e){return Wo({availableLanes:e.availableLanes,authSelectionPolicy:{kind:`any`},commandSubject:e.commandSubject,signerSlot:e.signerSlot,operationUsesNeeded:e.operationUsesNeeded})}async function Jo(e){let t=e.commandSubject.nearAccount.accountId,n=e.commandSubject.walletSession.walletId;if(typeof e.deps.readAvailableSigningLanesForSigning!=`function`)throw Error(`[SigningEngine][near] transaction signing requires available signing lanes reader`);let r=await e.deps.resolveOwnerLaneScope(n);return await e.deps.readAvailableSigningLanesForSigning({walletId:n,curve:`ed25519`,ownerScope:r,...e.authMethod?{authMethod:e.authMethod}:{}}).catch(e=>(console.warn(`[SigningEngine][near] available signing lanes read failed`,{nearAccountId:t,error:e instanceof Error?e.message:String(e||`unknown error`)}),null))}async function Yo(e){let t=e.commandSubject.nearAccount.accountId,n=Math.max(1,Math.floor(Number(e.operationUsesNeeded)||1)),r=e.selectedLane.lane,i=Ba({commandSubject:e.commandSubject,selectedLane:r,preparation:e.preparation,forceFreshAuth:e.forceFreshAuth,requiredSignatureUses:n}),a=i.lane;Co({signingLane:a,transactionLane:e.selectedLane.lane});let o={readiness:i.coordinatorInput.readiness,expiresAtMs:i.coordinatorInput.expiresAtMs,remainingUses:i.coordinatorInput.remainingUses};r.auth.kind===`email_otp`&&o.readiness.status!==`ready`&&console.warn(`[SigningEngine][near][email-otp] Ed25519 pre-confirm readiness is not ready`,{nearAccountId:t,readiness:o.readiness.status,thresholdSessionId:r.thresholdSessionId,walletSessionId:r.walletSessionId,quotaId:r.quotaId,retention:a.retention,remainingUses:o.remainingUses,expiresAtMs:o.expiresAtMs,requiredSignatureUses:n}),Je(`near`,Xe({event:`pre_confirm_readiness_checked`,lane:a,readinessStatus:o.readiness.status,phase:`pre_confirm`}));let s=Ht(e.selectedLane,To({readiness:o.readiness,expiresAtMs:o.expiresAtMs,remainingUses:o.remainingUses})),c=zt(s),l=Eo(a),u={readiness:o.readiness,expiresAtMs:o.expiresAtMs,remainingUses:o.remainingUses};return{lane:a,transactionLane:e.selectedLane.lane,transactionIntent:e.selectedLane.intent,readiness:u,availableLanesGeneration:e.availableLanes?.generation||0,metadata:{transactionLane:e.selectedLane.lane,transactionOperation:c,transactionReadinessState:s,identity:l,availableLanesGeneration:e.availableLanes?.generation||0,readiness:u}}}async function Xo(e){let t=e.commandSubject.nearAccount.accountId,n=Dr(e.input.transaction),r=e.availableLanes,i=qo({commandSubject:e.commandSubject,availableLanes:r,signerSlot:e.input.signerSlot,operationUsesNeeded:n});if(!i)throw console.warn(`[SigningEngine][near][ed25519] exact transaction lane selection failed ${JSON.stringify({nearAccountId:t,signerSlot:e.input.signerSlot??null,requiredSignatureUses:n,availableLanes:xo(r)})}`),Error(`[SigningEngine][near] Ed25519 transaction signing requires an exact selected lane`);let a={kind:`account_class`,authMethod:B(i.lane.auth)},o=await jo({deps:e.deps,commandSubject:e.commandSubject,selectedLane:i.lane});if(o.preparation.authorization.kind===`authorized`){let t=o.preparation.authorization.authorization;if(i.lane.walletSessionId!==t.operationCredential.walletSessionId||i.lane.quotaId!==t.session.quotaId){r=await Jo({deps:e.deps,commandSubject:e.commandSubject,authMethod:B(i.lane.auth)});let a=qo({commandSubject:e.commandSubject,availableLanes:r,signerSlot:e.input.signerSlot,operationUsesNeeded:n});if(!a||!wo(i.lane,a.lane)||a.lane.walletSessionId!==t.operationCredential.walletSessionId||a.lane.quotaId!==t.session.quotaId)throw Error(`[SigningEngine][near] material restoration changed the Wallet Session without an exact refreshed lane`);i=a}}let s=e.forceFreshAuth===!0||ko(o.preparation),c=await Bt({intent:Go({commandSubject:e.commandSubject,signerSlot:e.input.signerSlot,authSelectionPolicy:a,operationUsesNeeded:n}),coordinator:e.signingSessionCoordinator,forceFreshAuth:s,sensitiveOperationPolicy:e.input.sensitivePolicy||ce.inheritSessionPolicy,onPlannerTrace:e=>qe(`near`,e),lifecycleAdapter:{prepare:async()=>{let t=await Yo({deps:e.deps,commandSubject:e.commandSubject,signingSessionCoordinator:e.signingSessionCoordinator,availableLanes:r,selectedLane:i,preparation:o.preparation,forceFreshAuth:s,operationUsesNeeded:n});return{...t,metadata:t.metadata}}}}),l=c.thresholdOperation,u=c.transactionOperation,d=l.lane,f=u.lane,p=l.metadata.identity,{signingAuthPlan:m}=await Do({commandSubject:e.commandSubject,preparedOperation:l});return{preparation:o.preparation,executor:o.executor,signingAuthPlan:m,signingLane:d,transactionLane:f,identity:p,thresholdSessionId:H.thresholdEd25519Session(Oo({providedThresholdSessionId:e.input.thresholdSessionId,identity:p})),availableLanesGeneration:l.availableLanesGeneration,preparedOperation:l,transactionOperation:u}}async function Zo(e,t){let n=performance.now();await e.touchConfirm.openTransactionPreparationModal({chain:`near`,walletLabel:String(t.commandSubject.nearAccount.accountId),txSigningRequests:[t.transaction],model:Hn({txSigningRequests:[t.transaction],signerAccount:String(t.commandSubject.nearAccount.accountId),title:t.title,subtitle:t.body}),confirmationConfigOverride:t.confirmationConfigOverride});try{let r=yo();return U(String(r),`preparation_modal`,n),await Qo(e,t,{signingOperationState:Tt({operationId:r})})}finally{e.touchConfirm.closeTransactionPreparationModal()}}async function Qo(e,t,n){let r=t.commandSubject.nearAccount,i=P(r.accountId),a={signerSlot:t.signerSlot,confirmationConfigOverride:t.confirmationConfigOverride,title:t.title,body:t.body,onEvent:t.onEvent},o=n.signingOperationState.operationId,s=n.signingSessionCoordinator||e.signingSessionCoordinator,c=performance.now(),l=await Jo({deps:e,commandSubject:t.commandSubject,authMethod:null}),u=await Ho({deps:e,availableLanes:l,input:t,commandSubject:t.commandSubject,operationId:o});if(U(String(o),`authorization_probe`,c),u){let o=e.getSignerWorkerContext();return await Vo({deps:e,nearAccountId:i,materialActivation:Uo(u.preparation),task:async()=>await co({chain:`near`,kind:`transactionWithActions`,payload:{ctx:o,commandSubject:t.commandSubject,nearAccount:r,transaction:t.transaction,rpcCall:t.rpcCall,signerSlot:a.signerSlot,confirmationConfigOverride:a.confirmationConfigOverride,title:a.title,body:a.body,onEvent:a.onEvent,signingOperationState:n.signingOperationState,signingSessionCoordinator:s,selection:{kind:`authorization_required`,candidate:u.candidate},passkeyEd25519OperationStepUp:u.passkeyEd25519OperationStepUp||void 0,emailOtpEd25519StepUp:u.emailOtpEd25519StepUp||void 0,sensitivePolicy:t.sensitivePolicy,yaoSigningPreparation:u.preparation,yaoMaterialExecutor:u.executor}})})}let d=performance.now(),f=await Xo({deps:e,availableLanes:l,input:t,commandSubject:t.commandSubject,signingSessionCoordinator:s,operationId:o,forceFreshAuth:n.forceFreshAuth===!0});U(String(o),`lane_preparation`,d);let p=performance.now(),m=f.preparation.authorization,h=f.signingAuthPlan,g=f.signingLane,_=f.transactionLane,v=f.thresholdSessionId;Co({signingLane:g,transactionLane:_});try{return await Vo({deps:e,nearAccountId:i,materialActivation:Uo(f.preparation),task:async()=>{let i=e.getSignerWorkerContext(),c=f,l=Io({auth:_.auth,signer:_.identity.signer,thresholdSessionId:v,preparation:c.preparation}),u=zo({deps:e,commandSubject:t.commandSubject,auth:_.auth,signer:_.identity.signer,preparation:c.preparation,onEvent:a.onEvent}),d=No({preparedSigningSession:f,thresholdSessionId:v,signingSessionCoordinator:s,passkeyEd25519OperationStepUp:l||null,emailOtpEd25519StepUp:u||null}),m={thresholdSessionId:d.thresholdSessionId,signingSessionPlan:d.signingSessionPlan,signingAuthPlan:d.signingAuthPlan,signingLane:d.signingLane},h={ctx:i,commandSubject:t.commandSubject,nearAccount:r,transaction:t.transaction,rpcCall:t.rpcCall,signerSlot:a.signerSlot,confirmationConfigOverride:a.confirmationConfigOverride,title:a.title,body:a.body,onEvent:a.onEvent,signingOperationState:n.signingOperationState,signingSessionCoordinator:d.signingSessionCoordinator,selection:{kind:`authorized`,selectedLane:_},transactionOperation:d.transactionOperation,ed25519SigningBoundary:m,yaoSigningPreparation:c.preparation,yaoMaterialExecutor:c.executor,...d.passkeyEd25519OperationStepUp?{passkeyEd25519OperationStepUp:d.passkeyEd25519OperationStepUp}:{},...d.emailOtpEd25519StepUp?{emailOtpEd25519StepUp:d.emailOtpEd25519StepUp}:{}};return U(String(o),`execution_setup`,p),await co({chain:`near`,kind:`transactionWithActions`,payload:h})}})}catch(r){let o=h.kind===Ct.PasskeyReauth||h.kind===Ct.EmailOtpReauth,c=ho(r),l=go(r),u=ct(r),d=c?.kind===`step_up_required`;if(!n.retryingFreshAuth&&!o&&m.kind===`authorized`&&(d||l)){if(l?.kind===`wait_and_retry_admission`)return await at(l.retryAfterMs),await Qo(e,t,{forceFreshAuth:!1,signingOperationState:n.signingOperationState,retryingFreshAuth:n.retryingFreshAuth,signingSessionCoordinator:s});await _o({failure:u,coordinator:s,lane:f.transactionLane,expiresAtMs:m.authorization.status.expiresAtMs});let r=_.auth.kind===`email_otp`,o=c?.kind===`step_up_required`?c.reason:void 0,d=l?l.reason===`stale_projection`?`wallet_signing_budget_stale_projection`:`wallet_signing_budget_exhausted`:o===`wallet_session_missing`?`threshold_session_missing`:`threshold_session_expired`;if(So(a.onEvent,i,{phase:r?z.STEP_06_AUTH_EMAIL_OTP_CHALLENGE_STARTED:z.STEP_09_THRESHOLD_SESSION_RECONNECT_STARTED,status:`running`,message:r?`Signing session needs reauthorization; requesting Email OTP`:`Signing session needs reauthorization; requesting passkey`,interaction:{kind:`none`,overlay:`none`},data:{chain:`near`,reason:d}}),l?.kind===`request_fresh_step_up`){let r=Po({walletId:t.commandSubject.walletSession.walletId,nearAccountId:i,prepared:f});return await s.runWalletSessionQuotaAdmissionRetry({queueKey:r,refresh:async()=>await Qo(e,t,{forceFreshAuth:!0,signingOperationState:n.signingOperationState,retryingFreshAuth:!0,signingSessionCoordinator:s}),retryAfterRefresh:async()=>await Qo(e,t,{forceFreshAuth:!1,signingOperationState:n.signingOperationState,retryingFreshAuth:n.retryingFreshAuth,signingSessionCoordinator:s})})}return await Qo(e,t,{forceFreshAuth:!0,signingOperationState:n.signingOperationState,retryingFreshAuth:!0,signingSessionCoordinator:s})}throw r}}async function $o(e){return await co({chain:`near`,kind:`delegateAction`,payload:{ctx:e.deps.getSignerWorkerContext(),commandSubject:e.input.commandSubject,nearAccount:e.input.commandSubject.nearAccount,delegate:e.input.delegate,rpcCall:e.normalizedRpcCall,signingSessionCoordinator:e.deps.signingSessionCoordinator,signerSlot:e.input.signerSlot,confirmationConfigOverride:e.input.confirmationConfigOverride,title:e.input.title,body:e.input.body,onEvent:e.input.onEvent,operationId:e.operationId,forceFreshAuth:e.prepared.forceFreshAuth,selection:e.prepared.kind===`authorized`?{kind:`authorized`,selectedLane:e.prepared.selectedLane}:{kind:`authorization_required`,candidate:e.prepared.candidate},passkeyEd25519OperationStepUp:e.prepared.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.prepared.emailOtpEd25519StepUp,yaoSigningPreparation:e.prepared.yaoSigningPreparation,yaoMaterialExecutor:e.prepared.yaoMaterialExecutor}})}async function es(e){let t=P(e.input.commandSubject.nearAccount.accountId),n=await Bo({deps:e.deps,commandSubject:e.input.commandSubject,signerSlot:e.input.signerSlot,operationId:e.operationId,onEvent:e.input.onEvent,attempt:e.attempt}),r={nearRpcUrl:e.input.rpcCall.nearRpcUrl||e.deps.nearRpcUrl,nearAccountId:t};try{return await Vo({deps:e.deps,nearAccountId:t,materialActivation:Uo(n.yaoSigningPreparation),task:$o.bind(void 0,{deps:e.deps,input:e.input,operationId:e.operationId,prepared:n,normalizedRpcCall:r})})}catch(r){let i=ho(r),a=go(r);if(e.attempt.kind===`initial`&&a){if(a.kind===`wait_and_retry_admission`)return await at(a.retryAfterMs),await es(e);let r=Fo({walletId:e.input.commandSubject.walletSession.walletId,nearAccountId:t,prepared:n});return await e.deps.signingSessionCoordinator.runWalletSessionQuotaAdmissionRetry({queueKey:r,refresh:async()=>await es({...e,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}}),retryAfterRefresh:async()=>await es({...e,attempt:{kind:`initial`,forceFreshAuth:!1}})})}let o=ct(r);if(e.attempt.kind===`initial`&&!n.forceFreshAuth&&i)return await _o({failure:o,coordinator:e.deps.signingSessionCoordinator,lane:n.selectedLane,expiresAtMs:Ao(n.yaoSigningPreparation)}),await es({deps:e.deps,input:e.input,operationId:e.operationId,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}});throw r}}async function ts(e,t){try{return await es({deps:e,input:t,operationId:Mo(e,`delegate`),attempt:{kind:`initial`,forceFreshAuth:!1}})}catch(e){throw console.error(`[SigningEngine][delegate] failed`,e),e}}async function ns(e){let t=e.input.commandSubject.nearAccount;return await co({chain:`near`,kind:`nep413`,payload:{ctx:e.deps.getSignerWorkerContext(),commandSubject:e.input.commandSubject,nearAccount:t,signingSessionCoordinator:e.deps.signingSessionCoordinator,onEvent:e.input.onEvent,forceFreshAuth:e.prepared.forceFreshAuth,selection:e.prepared.kind===`authorized`?{kind:`authorized`,selectedLane:e.prepared.selectedLane}:{kind:`authorization_required`,candidate:e.prepared.candidate},passkeyEd25519OperationStepUp:e.prepared.passkeyEd25519OperationStepUp,emailOtpEd25519StepUp:e.prepared.emailOtpEd25519StepUp,yaoSigningPreparation:e.prepared.yaoSigningPreparation,yaoMaterialExecutor:e.prepared.yaoMaterialExecutor,payload:{message:e.input.message,recipient:e.input.recipient,nonce:e.input.nonce,callbackUrl:e.input.callbackUrl,state:e.input.state,accountId:t.accountId,signerSlot:e.input.signerSlot,title:e.input.title,body:e.input.body,confirmationConfigOverride:e.input.confirmationConfigOverride,operationId:e.operationId}}})}async function rs(e){let t=P(e.input.commandSubject.nearAccount.accountId),n=await Bo({deps:e.deps,commandSubject:e.input.commandSubject,signerSlot:e.input.signerSlot,operationId:e.operationId,onEvent:e.input.onEvent,attempt:e.attempt});try{return await Vo({deps:e.deps,nearAccountId:t,materialActivation:Uo(n.yaoSigningPreparation),task:ns.bind(void 0,{deps:e.deps,input:e.input,operationId:e.operationId,prepared:n})})}catch(t){let r=ho(t),i=ct(t);if(e.attempt.kind===`initial`&&!n.forceFreshAuth&&r!==void 0)return await _o({failure:i,coordinator:e.deps.signingSessionCoordinator,lane:n.selectedLane,expiresAtMs:Ao(n.yaoSigningPreparation)}),await rs({deps:e.deps,input:e.input,operationId:e.operationId,attempt:{kind:`fresh_auth_retry`,forceFreshAuth:!0}});throw t}}async function is(e,t){try{return await rs({deps:e,input:t,operationId:Mo(e,`nep413`),attempt:{kind:`initial`,forceFreshAuth:!1}})}catch(e){return console.error(`SigningEngine: NEP-413 signing error:`,e),{success:!1,error:e instanceof Error?e.message:String(e||`Unknown error`)}}}function as(e,t){return{...e,beforeSigning:t}}export{Qt as _,ni as a,Pn as c,bn as d,yn as f,en as g,un as h,oa as i,Nn as l,sn as m,mo as n,Bn as o,on as p,Ia as r,Vn as s,vo as t,Sn as u,Gt as v};
|