@seams/wallet 0.13.0 → 0.13.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.
Files changed (47) hide show
  1. package/README.md +3 -3
  2. package/dist/.build-inputs.sha256 +1 -1
  3. package/dist/esm/core/config/defaultConfigs.js +1 -1
  4. package/dist/esm/sdk/{host-GawN20iA.js → host-BAeJh9rB.js} +1 -1
  5. package/dist/{public/sdk/presignaturePool-CLHu7HaU.js → esm/sdk/presignaturePool-Bkk6bLFB.js} +1 -1
  6. package/dist/esm/sdk/routerAbNormalSigning-B35zb-P-.js +1 -0
  7. package/dist/{public/sdk/runtime-auth-TZw6JD8N.js → esm/sdk/runtime-auth-D7VqiZeg.js} +1 -1
  8. package/dist/esm/sdk/{runtime-device-link-DXjabXJb.js → runtime-device-link-BKc_MD5V.js} +1 -1
  9. package/dist/esm/sdk/{runtime-ecdsa-tempo-DlKMIbyP.js → runtime-ecdsa-tempo-DC51NDrh.js} +1 -1
  10. package/dist/esm/sdk/{runtime-email-otp-BBPghU2G.js → runtime-email-otp-C-wopKFf.js} +1 -1
  11. package/dist/esm/sdk/{runtime-export-pw-xJL8o.js → runtime-export-BtGy8BKi.js} +1 -1
  12. package/dist/esm/sdk/{runtime-near-B-vYxGjl.js → runtime-near-nq8pgRAl.js} +1 -1
  13. package/dist/esm/sdk/{runtime-preferences-D-hY0RfC.js → runtime-preferences-778ZfMmT.js} +1 -1
  14. package/dist/esm/sdk/{runtime-recovery-Vg1ND2nl.js → runtime-recovery-B-JsRiN0.js} +1 -1
  15. package/dist/esm/sdk/{secp256k1-C-AETUpI.js → secp256k1-CYQS0rj-.js} +1 -1
  16. package/dist/esm/sdk/{shared-6bpRPbcM.js → shared-B6BCLs8L.js} +1 -1
  17. package/dist/esm/sdk/{signEvmFamily-M0trbeZe.js → signEvmFamily-ttVfV0qm.js} +1 -1
  18. package/dist/{public/sdk/signNear-DGUQZ44s.js → esm/sdk/signNear-bcWIHxEY.js} +1 -1
  19. package/dist/esm/sdk/wallet-iframe-host-ecdsa.js +1 -1
  20. package/dist/esm/sdk/wallet-iframe-host-full.js +1 -1
  21. package/dist/esm/sdk/wallet-iframe-host-near.js +1 -1
  22. package/dist/esm/sdk/wallet-iframe-host-runtime.js +1 -1
  23. package/dist/public/headers.manifest.json +1 -1
  24. package/dist/public/sdk/{host-GawN20iA.js → host-BAeJh9rB.js} +1 -1
  25. package/dist/{esm/sdk/presignaturePool-CLHu7HaU.js → public/sdk/presignaturePool-Bkk6bLFB.js} +1 -1
  26. package/dist/public/sdk/routerAbNormalSigning-B35zb-P-.js +1 -0
  27. package/dist/{esm/sdk/runtime-auth-TZw6JD8N.js → public/sdk/runtime-auth-D7VqiZeg.js} +1 -1
  28. package/dist/public/sdk/{runtime-device-link-DXjabXJb.js → runtime-device-link-BKc_MD5V.js} +1 -1
  29. package/dist/public/sdk/{runtime-ecdsa-tempo-DlKMIbyP.js → runtime-ecdsa-tempo-DC51NDrh.js} +1 -1
  30. package/dist/public/sdk/{runtime-email-otp-BBPghU2G.js → runtime-email-otp-C-wopKFf.js} +1 -1
  31. package/dist/public/sdk/{runtime-export-pw-xJL8o.js → runtime-export-BtGy8BKi.js} +1 -1
  32. package/dist/public/sdk/{runtime-near-B-vYxGjl.js → runtime-near-nq8pgRAl.js} +1 -1
  33. package/dist/public/sdk/{runtime-preferences-D-hY0RfC.js → runtime-preferences-778ZfMmT.js} +1 -1
  34. package/dist/public/sdk/{runtime-recovery-Vg1ND2nl.js → runtime-recovery-B-JsRiN0.js} +1 -1
  35. package/dist/public/sdk/{secp256k1-C-AETUpI.js → secp256k1-CYQS0rj-.js} +1 -1
  36. package/dist/public/sdk/{shared-6bpRPbcM.js → shared-B6BCLs8L.js} +1 -1
  37. package/dist/public/sdk/{signEvmFamily-M0trbeZe.js → signEvmFamily-ttVfV0qm.js} +1 -1
  38. package/dist/{esm/sdk/signNear-DGUQZ44s.js → public/sdk/signNear-bcWIHxEY.js} +1 -1
  39. package/dist/public/sdk/wallet-iframe-host-ecdsa.js +1 -1
  40. package/dist/public/sdk/wallet-iframe-host-full.js +1 -1
  41. package/dist/public/sdk/wallet-iframe-host-near.js +1 -1
  42. package/dist/public/sdk/wallet-iframe-host-runtime.js +1 -1
  43. package/dist/public/wallet-assets.manifest.json +34 -34
  44. package/dist/public/wallet-service/index.html +4 -4
  45. package/package.json +1 -1
  46. package/dist/esm/sdk/routerAbNormalSigning-DVKFBYgV.js +0 -1
  47. package/dist/public/sdk/routerAbNormalSigning-DVKFBYgV.js +0 -1
@@ -1 +1 @@
1
- import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{t as e}from"./host-GawN20iA.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";e({supportedRuntimeRouteKinds:new Set([`auth`,`ecdsa`,`email_otp`,`export`,`recovery`,`preferences`])});
1
+ import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{t as e}from"./host-BAeJh9rB.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";e({supportedRuntimeRouteKinds:new Set([`auth`,`ecdsa`,`email_otp`,`export`,`recovery`,`preferences`])});
@@ -1 +1 @@
1
- import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{t as e}from"./host-GawN20iA.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";e();
1
+ import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{t as e}from"./host-BAeJh9rB.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";e();
@@ -1 +1 @@
1
- import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{t as e}from"./host-GawN20iA.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";e({supportedRuntimeRouteKinds:new Set([`auth`,`near`,`export`,`device_link`,`recovery`,`preferences`])});
1
+ import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{t as e}from"./host-BAeJh9rB.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";e({supportedRuntimeRouteKinds:new Set([`auth`,`near`,`export`,`device_link`,`recovery`,`preferences`])});
@@ -1 +1 @@
1
- import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{t as e}from"./host-GawN20iA.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";export{e as initWalletIFrame};
1
+ import"./primitives-CqrjmIAH.js";import"./sessionPolicy-CBTZQe1n.js";import"./signingSessionSeal-DX41aXUL.js";import{t as e}from"./host-BAeJh9rB.js";import"./activeWalletSession-WdZkhtBB.js";import"./capabilityKinds-N8xo_IEh.js";import"./errors-DIWY1KR9.js";export{e as initWalletIFrame};
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "packageName": "@seams/wallet",
4
- "packageVersion": "0.13.0",
4
+ "packageVersion": "0.13.1",
5
5
  "assetRoot": "dist/public",
6
6
  "routeClasses": [
7
7
  {
@@ -1 +1 @@
1
- import{C as e,S as t}from"./chains-C_X_fNuS.js";import{n}from"./walletRegistrationSetupPrewarm-B9kpnrbK.js";import{_ as r,c as i,f as a,g as o,h as s,l as c,m as l,n as u,o as d,t as f,v as p}from"./messages-DgJlG9NU.js";import{a as m,c as h,i as g,l as _,n as v,o as y,s as b,t as x,u as S}from"./transactionReviewAdmission-CIvR4W5_.js";import{t as C}from"./events-1dzC4Ocx.js";import{t as w}from"./walletIframeIdentity-Cz82I_Uh.js";import{t as T}from"./errors-DIWY1KR9.js";function E(){let e=globalThis;e.global===void 0&&(e.global=globalThis),!e.process||typeof e.process!=`object`?e.process={env:{}}:(!e.process.env||typeof e.process.env!=`object`)&&(e.process.env={})}function D(){E(),window.location.origin===`null`&&(window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`),console.warn(`[WalletHost] iframe is running with opaque (null) origin. Check COEP/CORP headers and ensure navigation succeeded.`)),O(),window.parent?.postMessage({type:`SERVICE_HOST_BOOTED`},`*`),window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`);let e=new URL(import.meta.url),t=e.searchParams.get(`v`);t&&l(t);let n=new URL(`.`,e).toString(),r=n.endsWith(`/`)?n:n+`/`;a()||s(r)}function O(){let e=()=>{let e=document;e.documentElement.classList.add(`seams-transparent`),e.body?.classList.add(`seams-transparent`),e.documentElement.classList.remove(`dark`),e.body?.classList.remove(`dark`)};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>e(),{once:!0}):e(),window.addEventListener(`load`,()=>e(),{once:!0})}const k={};let A=null,j=null;function M(e){return e.type===`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`?(A??=import(`./runtime-recovery-codes-rLR4Guy4.js`),A):(k[e.kind]??=P(e.kind),k[e.kind])}async function N(){A??=import(`./runtime-recovery-codes-rLR4Guy4.js`),j??=Promise.all([A,import(`./mountRecoveryCodeBackupSurface-D1G-iCPI.js`)]).then(()=>void 0),await j}function P(e){switch(e){case`auth`:return import(`./runtime-auth-TZw6JD8N.js`);case`near`:return import(`./runtime-near-B-vYxGjl.js`);case`ecdsa`:return import(`./runtime-ecdsa-tempo-DlKMIbyP.js`);case`email_otp`:return import(`./runtime-email-otp-BBPghU2G.js`);case`recovery`:return import(`./runtime-recovery-Vg1ND2nl.js`);case`export`:return import(`./runtime-export-pw-xJL8o.js`);case`device_link`:return import(`./runtime-device-link-DXjabXJb.js`);case`preferences`:return import(`./runtime-preferences-D-hY0RfC.js`)}return F(e)}function F(e){throw Error(`Unhandled wallet host runtime route: ${String(e)}`)}function I(e){throw Error(`Unhandled wallet host route: ${String(e)}`)}function L(e,t){if(e===null)throw Error(`Invalid ${t} payload`);return e}function R(e){try{return w(e)}catch{throw Error(`Hosted auth-menu request requires a non-empty requestId`)}}function z(e){switch(e.type){case`PM_ACTIVATE_TRANSACTION_REVIEW`:case`PING`:case`PM_SET_CONFIG`:case`PM_CANCEL`:case`PM_SET_TRANSACTION_VIEW`:case`PM_TRANSACTION_BROADCAST_STARTED`:return{kind:`boot`,type:e.type,request:e};case`PM_REGISTER_WALLET`:case`PM_ADD_WALLET_SIGNER`:case`PM_ADD_PASSKEY`:case`PM_ADD_EMAIL_OTP`:case`PM_REVOKE_AUTH_METHOD`:case`PM_GET_NEAR_PROVISIONING_STATE`:case`PM_SIGN_TX_WITH_ACTIONS`:case`PM_SIGN_AND_SEND_TX`:case`PM_SEND_TRANSACTION`:case`PM_SIGN_DELEGATE_ACTION`:case`PM_SIGN_NEP413`:return{kind:`near`,type:e.type,request:e};case`PM_OPEN_AUTH_MENU`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(c(e.payload),`hosted auth-menu open`)}}}case`PM_CANCEL_AUTH_MENU`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(d(e.payload),`hosted auth-menu cancellation`)}}}case`PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(i(e.payload),`hosted auth-menu external-auth resolution`)}}}case`PM_UNLOCK`:case`PM_LOCK`:case`PM_LOCK_EXACT_WALLET_SESSION`:case`PM_GET_LAST_WALLET_MOVE_REQUEST`:case`PM_MOVE_WALLET`:case`PM_GET_WALLET_MOVE`:case`PM_GET_WALLET_PLACEMENT`:case`PM_GET_WALLET_SESSION`:case`PM_GET_EXACT_WALLET_SESSION_STATE`:case`PM_GET_RECENT_UNLOCKS`:return{kind:`auth`,type:e.type,request:e};case`PM_SIGN_TEMPO`:case`PM_REPORT_TEMPO_BROADCAST_ACCEPTED`:case`PM_REPORT_TEMPO_BROADCAST_REJECTED`:case`PM_REPORT_TEMPO_FINALIZED`:case`PM_REPORT_TEMPO_DROPPED_OR_REPLACED`:case`PM_RECONCILE_TEMPO_NONCE_LANE`:return{kind:`ecdsa`,type:e.type,request:e};case`PM_REDEEM_HOSTED_WALLET_SEAMS_SESSION`:case`PM_REQUEST_EMAIL_OTP_CHALLENGE`:case`PM_BEGIN_GOOGLE_EMAIL_OTP_WALLET_AUTH`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_RESEND`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_REROLL_WALLET_ID`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_SUBMIT`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_COMPLETE_REGISTRATION`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_CANCEL`:case`PM_GET_WALLET_RECOVERY_CODE_STATUS`:case`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`:case`PM_ROTATE_WALLET_RECOVERY_CODES`:case`PM_REQUEST_WALLET_CUSTODY_EMAIL_OTP_CHALLENGE`:return{kind:`email_otp`,type:e.type,request:e};case`PM_SYNC_ACCOUNT_FLOW`:return{kind:`recovery`,type:e.type,request:e};case`PM_RESOLVE_EXACT_KEY_EXPORT_LANE`:case`PM_EXPORT_KEYPAIR_UI`:return{kind:`export`,type:e.type,request:e};case`PM_HAS_PASSKEY`:case`PM_LIST_LINKED_DEVICES`:case`PM_REVOKE_LINKED_DEVICE`:case`PM_SCAN_AND_LINK_DEVICE`:case`PM_START_DEVICE2_LINKING_FLOW`:case`PM_DEVICE_LINK_TARGET_FACTOR_ACTION`:case`PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION`:case`PM_CANCEL_DEVICE_LINKING`:return{kind:`device_link`,type:e.type,request:e};case`PM_SET_CONFIRM_BEHAVIOR`:case`PM_SET_CONFIRMATION_CONFIG`:case`PM_GET_CONFIRMATION_CONFIG`:return{kind:`preferences`,type:e.type,request:e}}return I(e)}function B(e){return e.kind!==`boot`}let V=!1;const H=[{selector:`.seams-auth-menu-surface`,cancellationKind:`native_cancel`},{selector:`.seams-confirmation-surface`,cancellationKind:`native_cancel`},{selector:`.seams-export-surface`,cancellationKind:`wallet_iframe_cancel`},{selector:`[data-seams-wallet-recovery-backup-dialog]`,cancellationKind:`native_cancel`}];function U(e,t){let n=new Set(t),r=Object.keys(e);return r.length===t.length&&r.every(e=>n.has(e))}function W(t){return!e(t)||!U(t,[`type`,`payload`])||t.type!==`CONNECT`||!e(t.payload)||!U(t.payload,[`protocolVersion`])?null:typeof t.payload.protocolVersion==`string`?{type:`CONNECT`,payload:{protocolVersion:t.payload.protocolVersion}}:null}function G(e){if(e===`null`)return!0;try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e}catch{return!1}}function K(e){try{e.close()}catch{}}function q(e,t){if(t===`15.0.0`)return!1;let n={expectedProtocolVersion:u,receivedProtocolVersion:t};try{e.postMessage({type:`ERROR`,payload:{code:f,message:`Wallet iframe protocol version mismatch: expected ${u}, received ${t??`missing`}`,details:n}})}catch{}return K(e),!0}function J(e,t){return!t||t.has(e.kind)}function Y(e,t,n,r){e.executionGeneration===t&&n(r)}function X(e,t,n,r){return e.executionGeneration!==t||n(r)}function Z(e={}){if(V)return;V=!0,D(),(!e.supportedRuntimeRouteKinds||e.supportedRuntimeRouteKinds.has(`email_otp`))&&N().catch(()=>void 0);let i=new Set,a=new Set,s={parentOrigin:null,port:null,configuration:{kind:`unconfigured`},executionGeneration:0,onConfigurationChanged:null},c=e=>{try{s.port?.postMessage(e)}catch{}},l=e=>{e&&i.add(e)},d=e=>!!e&&(i.has(e)||g(e)?.cancelled===!0),f=e=>{e&&i.delete(e)},w=e=>{e&&c({type:`ERROR`,requestId:e,payload:{code:`cancelled`,message:`Request cancelled`}})},E=e=>!e||!d(e)?!1:g(e)?.cancelled?!0:(w(e),f(e),!0),O=()=>{for(let e of H){let t=document.querySelectorAll(e.selector);for(let n of t)try{e.cancellationKind===`native_cancel`?n.dispatchEvent(new Event(`cancel`,{cancelable:!0})):n.dispatchEvent(new CustomEvent(C.TX_CONFIRMER_CANCEL,{bubbles:!0,composed:!0}))}catch{}}},k=async i=>{let u=i.data;if(!u||!t(u))return;let C=u.requestId,D=s.executionGeneration,k=Y.bind(null,s,D,c),A=null;try{if(`transactionReview`in u){if(u.type!==`PM_SIGN_AND_SEND_TX`&&u.type!==`PM_SIGN_TEMPO`)throw new m(`review_invalid_input`,`Review is unsupported for this request`);let e=h(u.transactionReview);if(e.requestId!==C)throw new m(`review_invalid_input`,`Review request identity mismatch`);let t=u.payload?.options?.confirmationConfig;if(t?.uiMode!==`modal`||t.behavior!==`requireClick`)throw new m(`review_unsupported_mode`,`Review requires modal presentation and explicit approval`);A=new x(e,u.type===`PM_SIGN_TEMPO`&&u.payload?.request.senderSignatureAlgorithm!==`secp256k1`?`credential`:`mpc`,e=>k({type:`TRANSACTION_REVIEW_STATE`,requestId:C,payload:e}),e=>k({type:`ERROR`,requestId:C,payload:{code:e instanceof m?e.code:`cancelled`,message:e.message}}))}(u.type===`PM_LOCK`||u.type===`PM_LOCK_EXACT_WALLET_SESSION`)&&v(new m(`review_identity_changed`,`The wallet session changed`));let t=z(u);if(!B(t))switch(t.type){case`PING`:c({type:`PONG`,requestId:C});return;case`PM_SET_CONFIG`:{let e=o(s.configuration,r(t.request.payload)),i=p(s.configuration.kind===`configured`?s.configuration.config:null)!==p(e.config);if(s.configuration=e,i){s.executionGeneration+=1;let t=e.config;t.registration.publishableKey&&t.registration.projectEnvironmentId&&n(t.network.relayer.url);for(let e of a)c({type:`ERROR`,requestId:e,payload:{code:`wallet_configuration_changed`,message:`Wallet configuration changed during request`}});a.clear()}s.onConfigurationChanged?.(),i&&(v(new m(`review_identity_changed`,`Wallet execution configuration changed`)),O()),c({type:`PONG`,requestId:C});return}case`PM_ACTIVATE_TRANSACTION_REVIEW`:{let e=b(t.request.payload);e&&g(e.requestId)?.activate(e);return}case`PM_CANCEL`:{let e=t.request.payload?.requestId,n=t.request.payload,r=n&&typeof n==`object`?Reflect.get(n,`transactionReview`):void 0;if(r!==void 0){let t=h(r),i=g(t.requestId);if(t.requestId===e&&i&&_(t,i.metadata)){let e=new m(S(n&&typeof n==`object`?Reflect.get(n,`reviewErrorCode`):void 0),`Reviewed request cancelled`);try{y(i.metadata.validity)}catch(t){t instanceof Error&&(e=t)}i.cancel(e)}c({type:`PONG`,requestId:C});return}let i=e?g(e):void 0;if(i){i.cancel(new m(`cancelled`,`Request cancelled`)),c({type:`PONG`,requestId:C});return}l(e),O(),e&&w(e),c({type:`PONG`,requestId:C});return}case`PM_SET_TRANSACTION_VIEW`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`requestId`):null,r=e&&typeof e==`object`?Reflect.get(e,`view`):null;typeof n==`string`&&(r===`toast`||r===`closed`)&&(await import(`./transaction-activity-xfeHKJoq.js`).then(e=>e.o)).setTransactionActivityView(n,r);return}case`PM_TRANSACTION_BROADCAST_STARTED`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`signedTransaction`):null;typeof n==`string`&&(await import(`./transaction-activity-xfeHKJoq.js`).then(e=>e.o)).transactionBroadcastStarted(n);return}}if(!J(t,e.supportedRuntimeRouteKinds)){c({type:`ERROR`,requestId:C,payload:{code:`unsupported_request`,message:`Unsupported wallet iframe request type: ${t.type}`}});return}C&&a.add(C);let i=await M(t);if(D!==s.executionGeneration)return;await i.handleWalletHostRuntimeRequest({transactionReview:A,state:s,executionGeneration:D,req:t.request,post:Y.bind(null,s,D,c),isCancelled:X.bind(null,s,D,d),respondIfCancelled:X.bind(null,s,D,E)})}catch(e){if(D!==s.executionGeneration&&u.type!==`PM_SET_CONFIG`||A?.cancelled)return;let t=await import(`./canonicalSignerErrorCode-Cz48v4oy.js`);if(D!==s.executionGeneration&&u.type!==`PM_SET_CONFIG`)return;let n=e&&typeof e==`object`&&`code`in e?e.code:void 0,r=T(e),i=t.resolveWalletBoundaryErrorCode({requestType:u.type,rawCode:n,message:r,defaultCode:`HOST_ERROR`}),a=t.resolveWalletBoundaryErrorMessage({requestType:u.type,rawCode:n,code:i,message:r}),o=t.resolveWalletBoundarySignerKind(u.type);c({type:`ERROR`,requestId:C,payload:{code:i,message:a,...t.isWalletSignerBoundaryRequestType(u.type)&&t.isCanonicalSignerSessionBoundaryCode(i)&&o?{signerKind:o}:{}}})}finally{C&&(a.delete(C),f(C)),A?.finish()}};window.addEventListener(`message`,e=>{let t=W(e.data),n=e.ports[0];if(!(!t||!n||s.port)){if(e.source!==window.parent||!G(e.origin)){K(n);return}if(!q(n,t.payload.protocolVersion)){typeof e.origin==`string`&&e.origin.length&&e.origin!==`null`&&(s.parentOrigin=e.origin),s.port=n;try{s.port.onmessage=k,s.port.start?.()}catch{}c({type:`READY`,payload:{protocolVersion:u}})}}})}try{Z()}catch(e){console.error(`[WalletHost] init failed`,e)}export{Z as t};
1
+ import{C as e,S as t}from"./chains-C_X_fNuS.js";import{n}from"./walletRegistrationSetupPrewarm-B9kpnrbK.js";import{_ as r,c as i,f as a,g as o,h as s,l as c,m as l,n as u,o as d,t as f,v as p}from"./messages-DgJlG9NU.js";import{a as m,c as h,i as g,l as _,n as v,o as y,s as b,t as x,u as S}from"./transactionReviewAdmission-CIvR4W5_.js";import{t as C}from"./events-1dzC4Ocx.js";import{t as w}from"./walletIframeIdentity-Cz82I_Uh.js";import{t as T}from"./errors-DIWY1KR9.js";function E(){let e=globalThis;e.global===void 0&&(e.global=globalThis),!e.process||typeof e.process!=`object`?e.process={env:{}}:(!e.process.env||typeof e.process.env!=`object`)&&(e.process.env={})}function D(){E(),window.location.origin===`null`&&(window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`),console.warn(`[WalletHost] iframe is running with opaque (null) origin. Check COEP/CORP headers and ensure navigation succeeded.`)),O(),window.parent?.postMessage({type:`SERVICE_HOST_BOOTED`},`*`),window.parent?.postMessage({type:`SERVICE_HOST_DEBUG_ORIGIN`,origin:window.location.origin,href:window.location.href},`*`);let e=new URL(import.meta.url),t=e.searchParams.get(`v`);t&&l(t);let n=new URL(`.`,e).toString(),r=n.endsWith(`/`)?n:n+`/`;a()||s(r)}function O(){let e=()=>{let e=document;e.documentElement.classList.add(`seams-transparent`),e.body?.classList.add(`seams-transparent`),e.documentElement.classList.remove(`dark`),e.body?.classList.remove(`dark`)};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>e(),{once:!0}):e(),window.addEventListener(`load`,()=>e(),{once:!0})}const k={};let A=null,j=null;function M(e){return e.type===`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`?(A??=import(`./runtime-recovery-codes-rLR4Guy4.js`),A):(k[e.kind]??=P(e.kind),k[e.kind])}async function N(){A??=import(`./runtime-recovery-codes-rLR4Guy4.js`),j??=Promise.all([A,import(`./mountRecoveryCodeBackupSurface-D1G-iCPI.js`)]).then(()=>void 0),await j}function P(e){switch(e){case`auth`:return import(`./runtime-auth-D7VqiZeg.js`);case`near`:return import(`./runtime-near-nq8pgRAl.js`);case`ecdsa`:return import(`./runtime-ecdsa-tempo-DC51NDrh.js`);case`email_otp`:return import(`./runtime-email-otp-C-wopKFf.js`);case`recovery`:return import(`./runtime-recovery-B-JsRiN0.js`);case`export`:return import(`./runtime-export-BtGy8BKi.js`);case`device_link`:return import(`./runtime-device-link-BKc_MD5V.js`);case`preferences`:return import(`./runtime-preferences-778ZfMmT.js`)}return F(e)}function F(e){throw Error(`Unhandled wallet host runtime route: ${String(e)}`)}function I(e){throw Error(`Unhandled wallet host route: ${String(e)}`)}function L(e,t){if(e===null)throw Error(`Invalid ${t} payload`);return e}function R(e){try{return w(e)}catch{throw Error(`Hosted auth-menu request requires a non-empty requestId`)}}function z(e){switch(e.type){case`PM_ACTIVATE_TRANSACTION_REVIEW`:case`PING`:case`PM_SET_CONFIG`:case`PM_CANCEL`:case`PM_SET_TRANSACTION_VIEW`:case`PM_TRANSACTION_BROADCAST_STARTED`:return{kind:`boot`,type:e.type,request:e};case`PM_REGISTER_WALLET`:case`PM_ADD_WALLET_SIGNER`:case`PM_ADD_PASSKEY`:case`PM_ADD_EMAIL_OTP`:case`PM_REVOKE_AUTH_METHOD`:case`PM_GET_NEAR_PROVISIONING_STATE`:case`PM_SIGN_TX_WITH_ACTIONS`:case`PM_SIGN_AND_SEND_TX`:case`PM_SEND_TRANSACTION`:case`PM_SIGN_DELEGATE_ACTION`:case`PM_SIGN_NEP413`:return{kind:`near`,type:e.type,request:e};case`PM_OPEN_AUTH_MENU`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(c(e.payload),`hosted auth-menu open`)}}}case`PM_CANCEL_AUTH_MENU`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(d(e.payload),`hosted auth-menu cancellation`)}}}case`PM_RESOLVE_AUTH_MENU_EXTERNAL_AUTH`:{let t=R(e.requestId);return{kind:`auth`,type:e.type,request:{...e,requestId:t,payload:L(i(e.payload),`hosted auth-menu external-auth resolution`)}}}case`PM_UNLOCK`:case`PM_LOCK`:case`PM_LOCK_EXACT_WALLET_SESSION`:case`PM_GET_LAST_WALLET_MOVE_REQUEST`:case`PM_MOVE_WALLET`:case`PM_GET_WALLET_MOVE`:case`PM_GET_WALLET_PLACEMENT`:case`PM_GET_WALLET_SESSION`:case`PM_GET_EXACT_WALLET_SESSION_STATE`:case`PM_GET_RECENT_UNLOCKS`:return{kind:`auth`,type:e.type,request:e};case`PM_SIGN_TEMPO`:case`PM_REPORT_TEMPO_BROADCAST_ACCEPTED`:case`PM_REPORT_TEMPO_BROADCAST_REJECTED`:case`PM_REPORT_TEMPO_FINALIZED`:case`PM_REPORT_TEMPO_DROPPED_OR_REPLACED`:case`PM_RECONCILE_TEMPO_NONCE_LANE`:return{kind:`ecdsa`,type:e.type,request:e};case`PM_REDEEM_HOSTED_WALLET_SEAMS_SESSION`:case`PM_REQUEST_EMAIL_OTP_CHALLENGE`:case`PM_BEGIN_GOOGLE_EMAIL_OTP_WALLET_AUTH`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_RESEND`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_REROLL_WALLET_ID`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_SUBMIT`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_COMPLETE_REGISTRATION`:case`PM_GOOGLE_EMAIL_OTP_WALLET_AUTH_CANCEL`:case`PM_GET_WALLET_RECOVERY_CODE_STATUS`:case`PM_ACKNOWLEDGE_WALLET_RECOVERY_CODE_BACKUP`:case`PM_ROTATE_WALLET_RECOVERY_CODES`:case`PM_REQUEST_WALLET_CUSTODY_EMAIL_OTP_CHALLENGE`:return{kind:`email_otp`,type:e.type,request:e};case`PM_SYNC_ACCOUNT_FLOW`:return{kind:`recovery`,type:e.type,request:e};case`PM_RESOLVE_EXACT_KEY_EXPORT_LANE`:case`PM_EXPORT_KEYPAIR_UI`:return{kind:`export`,type:e.type,request:e};case`PM_HAS_PASSKEY`:case`PM_LIST_LINKED_DEVICES`:case`PM_REVOKE_LINKED_DEVICE`:case`PM_SCAN_AND_LINK_DEVICE`:case`PM_START_DEVICE2_LINKING_FLOW`:case`PM_DEVICE_LINK_TARGET_FACTOR_ACTION`:case`PM_DEVICE_LINK_EMAIL_OTP_BASE_FACTOR_ACTION`:case`PM_CANCEL_DEVICE_LINKING`:return{kind:`device_link`,type:e.type,request:e};case`PM_SET_CONFIRM_BEHAVIOR`:case`PM_SET_CONFIRMATION_CONFIG`:case`PM_GET_CONFIRMATION_CONFIG`:return{kind:`preferences`,type:e.type,request:e}}return I(e)}function B(e){return e.kind!==`boot`}let V=!1;const H=[{selector:`.seams-auth-menu-surface`,cancellationKind:`native_cancel`},{selector:`.seams-confirmation-surface`,cancellationKind:`native_cancel`},{selector:`.seams-export-surface`,cancellationKind:`wallet_iframe_cancel`},{selector:`[data-seams-wallet-recovery-backup-dialog]`,cancellationKind:`native_cancel`}];function U(e,t){let n=new Set(t),r=Object.keys(e);return r.length===t.length&&r.every(e=>n.has(e))}function W(t){return!e(t)||!U(t,[`type`,`payload`])||t.type!==`CONNECT`||!e(t.payload)||!U(t.payload,[`protocolVersion`])?null:typeof t.payload.protocolVersion==`string`?{type:`CONNECT`,payload:{protocolVersion:t.payload.protocolVersion}}:null}function G(e){if(e===`null`)return!0;try{let t=new URL(e);return(t.protocol===`https:`||t.protocol===`http:`)&&t.origin===e}catch{return!1}}function K(e){try{e.close()}catch{}}function q(e,t){if(t===`15.0.0`)return!1;let n={expectedProtocolVersion:u,receivedProtocolVersion:t};try{e.postMessage({type:`ERROR`,payload:{code:f,message:`Wallet iframe protocol version mismatch: expected ${u}, received ${t??`missing`}`,details:n}})}catch{}return K(e),!0}function J(e,t){return!t||t.has(e.kind)}function Y(e,t,n,r){e.executionGeneration===t&&n(r)}function X(e,t,n,r){return e.executionGeneration!==t||n(r)}function Z(e={}){if(V)return;V=!0,D(),(!e.supportedRuntimeRouteKinds||e.supportedRuntimeRouteKinds.has(`email_otp`))&&N().catch(()=>void 0);let i=new Set,a=new Set,s={parentOrigin:null,port:null,configuration:{kind:`unconfigured`},executionGeneration:0,onConfigurationChanged:null},c=e=>{try{s.port?.postMessage(e)}catch{}},l=e=>{e&&i.add(e)},d=e=>!!e&&(i.has(e)||g(e)?.cancelled===!0),f=e=>{e&&i.delete(e)},w=e=>{e&&c({type:`ERROR`,requestId:e,payload:{code:`cancelled`,message:`Request cancelled`}})},E=e=>!e||!d(e)?!1:g(e)?.cancelled?!0:(w(e),f(e),!0),O=()=>{for(let e of H){let t=document.querySelectorAll(e.selector);for(let n of t)try{e.cancellationKind===`native_cancel`?n.dispatchEvent(new Event(`cancel`,{cancelable:!0})):n.dispatchEvent(new CustomEvent(C.TX_CONFIRMER_CANCEL,{bubbles:!0,composed:!0}))}catch{}}},k=async i=>{let u=i.data;if(!u||!t(u))return;let C=u.requestId,D=s.executionGeneration,k=Y.bind(null,s,D,c),A=null;try{if(`transactionReview`in u){if(u.type!==`PM_SIGN_AND_SEND_TX`&&u.type!==`PM_SIGN_TEMPO`)throw new m(`review_invalid_input`,`Review is unsupported for this request`);let e=h(u.transactionReview);if(e.requestId!==C)throw new m(`review_invalid_input`,`Review request identity mismatch`);let t=u.payload?.options?.confirmationConfig;if(t?.uiMode!==`modal`||t.behavior!==`requireClick`)throw new m(`review_unsupported_mode`,`Review requires modal presentation and explicit approval`);A=new x(e,u.type===`PM_SIGN_TEMPO`&&u.payload?.request.senderSignatureAlgorithm!==`secp256k1`?`credential`:`mpc`,e=>k({type:`TRANSACTION_REVIEW_STATE`,requestId:C,payload:e}),e=>k({type:`ERROR`,requestId:C,payload:{code:e instanceof m?e.code:`cancelled`,message:e.message}}))}(u.type===`PM_LOCK`||u.type===`PM_LOCK_EXACT_WALLET_SESSION`)&&v(new m(`review_identity_changed`,`The wallet session changed`));let t=z(u);if(!B(t))switch(t.type){case`PING`:c({type:`PONG`,requestId:C});return;case`PM_SET_CONFIG`:{let e=o(s.configuration,r(t.request.payload)),i=p(s.configuration.kind===`configured`?s.configuration.config:null)!==p(e.config);if(s.configuration=e,i){s.executionGeneration+=1;let t=e.config;t.registration.publishableKey&&t.registration.projectEnvironmentId&&n(t.network.relayer.url);for(let e of a)c({type:`ERROR`,requestId:e,payload:{code:`wallet_configuration_changed`,message:`Wallet configuration changed during request`}});a.clear()}s.onConfigurationChanged?.(),i&&(v(new m(`review_identity_changed`,`Wallet execution configuration changed`)),O()),c({type:`PONG`,requestId:C});return}case`PM_ACTIVATE_TRANSACTION_REVIEW`:{let e=b(t.request.payload);e&&g(e.requestId)?.activate(e);return}case`PM_CANCEL`:{let e=t.request.payload?.requestId,n=t.request.payload,r=n&&typeof n==`object`?Reflect.get(n,`transactionReview`):void 0;if(r!==void 0){let t=h(r),i=g(t.requestId);if(t.requestId===e&&i&&_(t,i.metadata)){let e=new m(S(n&&typeof n==`object`?Reflect.get(n,`reviewErrorCode`):void 0),`Reviewed request cancelled`);try{y(i.metadata.validity)}catch(t){t instanceof Error&&(e=t)}i.cancel(e)}c({type:`PONG`,requestId:C});return}let i=e?g(e):void 0;if(i){i.cancel(new m(`cancelled`,`Request cancelled`)),c({type:`PONG`,requestId:C});return}l(e),O(),e&&w(e),c({type:`PONG`,requestId:C});return}case`PM_SET_TRANSACTION_VIEW`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`requestId`):null,r=e&&typeof e==`object`?Reflect.get(e,`view`):null;typeof n==`string`&&(r===`toast`||r===`closed`)&&(await import(`./transaction-activity-xfeHKJoq.js`).then(e=>e.o)).setTransactionActivityView(n,r);return}case`PM_TRANSACTION_BROADCAST_STARTED`:{let e=t.request.payload,n=e&&typeof e==`object`?Reflect.get(e,`signedTransaction`):null;typeof n==`string`&&(await import(`./transaction-activity-xfeHKJoq.js`).then(e=>e.o)).transactionBroadcastStarted(n);return}}if(!J(t,e.supportedRuntimeRouteKinds)){c({type:`ERROR`,requestId:C,payload:{code:`unsupported_request`,message:`Unsupported wallet iframe request type: ${t.type}`}});return}C&&a.add(C);let i=await M(t);if(D!==s.executionGeneration)return;await i.handleWalletHostRuntimeRequest({transactionReview:A,state:s,executionGeneration:D,req:t.request,post:Y.bind(null,s,D,c),isCancelled:X.bind(null,s,D,d),respondIfCancelled:X.bind(null,s,D,E)})}catch(e){if(D!==s.executionGeneration&&u.type!==`PM_SET_CONFIG`||A?.cancelled)return;let t=await import(`./canonicalSignerErrorCode-Cz48v4oy.js`);if(D!==s.executionGeneration&&u.type!==`PM_SET_CONFIG`)return;let n=e&&typeof e==`object`&&`code`in e?e.code:void 0,r=T(e),i=t.resolveWalletBoundaryErrorCode({requestType:u.type,rawCode:n,message:r,defaultCode:`HOST_ERROR`}),a=t.resolveWalletBoundaryErrorMessage({requestType:u.type,rawCode:n,code:i,message:r}),o=t.resolveWalletBoundarySignerKind(u.type);c({type:`ERROR`,requestId:C,payload:{code:i,message:a,...t.isWalletSignerBoundaryRequestType(u.type)&&t.isCanonicalSignerSessionBoundaryCode(i)&&o?{signerKind:o}:{}}})}finally{C&&(a.delete(C),f(C)),A?.finish()}};window.addEventListener(`message`,e=>{let t=W(e.data),n=e.ports[0];if(!(!t||!n||s.port)){if(e.source!==window.parent||!G(e.origin)){K(n);return}if(!q(n,t.payload.protocolVersion)){typeof e.origin==`string`&&e.origin.length&&e.origin!==`null`&&(s.parentOrigin=e.origin),s.port=n;try{s.port.onmessage=k,s.port.start?.()}catch{}c({type:`READY`,payload:{protocolVersion:u}})}}})}try{Z()}catch(e){console.error(`[WalletHost] init failed`,e)}export{Z as t};
@@ -1 +1 @@
1
- import{B as e,V as t}from"./domainIds-BzkGsRqO.js";import{A as n,k as r}from"./primitives-CqrjmIAH.js";import{i,r as a}from"./base64-DW79QA0h.js";import{r as o}from"./secureRandomId-LwBFx84B.js";import{B as s,F as c,G as l,I as u,R as d,dt as ee,z as f}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{I as p,L as m,R as h}from"./ecdsaCapabilityManifest-ChszYCC0.js";import{ct as g,n as _,ut as v}from"./walletOwnershipGeneration-CAycHv-H.js";import{t as y}from"./presignatures-DZm0d6Wy.js";import{i as b,n as x,r as te,u as S}from"./trace-QLsbYdld.js";import{A as ne,C,D as re,E as ie,O as ae,S as w,T,k as E,w as oe,x as D,y as se}from"./ecdsaDerivationClientWasm-CpH-b3jx.js";import{t as O}from"./authorizationAdmission-CGinGhXH.js";import{t as k}from"./walletSessionFailure-YuhraC3P.js";import{c as ce,f as A,o as le,t as j}from"./routerAbNormalSigning-DVKFBYgV.js";import{o as M,s as ue,t as de}from"./evmCryptoWasm-DeobzyP-.js";async function fe(e){let t=e.clientShare.material;if(t.kind===`worker_loaded`)return;let n=await se({materialHandle:e.clientShare.handle.materialHandle,bindingDigest:e.clientShare.handle.bindingDigest,stateBlob:t.stateBlob,workerCtx:e.workerCtx});if(n.materialHandle!==e.clientShare.handle.materialHandle||n.bindingDigest!==e.clientShare.handle.bindingDigest)throw Error(`[multichain] ECDSA role-local worker material handle mismatch`)}async function pe(e){let t=e.signerSession,n=t.clientShare;if(n.kind===`linked_holder_worker_share`){let e=n.holderHandleId;return{signerSession:t,clientSigningMaterial:me(e),cleanupAfterSign:async()=>void 0}}let r=n;return{signerSession:t,clientSigningMaterial:{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:async t=>(await fe({workerCtx:e.workerCtx,clientShare:r}),await ae({materialHandle:r.handle.materialHandle,material:r.material.kind===`worker_loaded`?{kind:`persisted`,materialRef:r.material.materialRef}:{kind:`runtime_loaded`,expectedBindingDigest:r.handle.bindingDigest},...t})),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`role_local_derivation_handle`),computeSignatureShareFromPresignatureHandle:T},cleanupAfterSign:async()=>void 0}}async function N(e,t){return await D({holderHandleId:e,...t})}function me(e){return{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:N.bind(void 0,e),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`linked_holder_signing_material`),computeSignatureShareFromPresignatureHandle:T}}function P(e,t,n,r){let i=Math.floor(Number(e));return Number.isFinite(i)?i<n?n:i>r?r:i:t}function he(e,t){return P(e,t,1,5)}function ge(e,t,n){return P(e,t,0,n)}function _e(e){let t=e||A,n=he(t.targetDepth,A.targetDepth),r=ge(t.lowWatermark,A.lowWatermark,n);return{enabled:typeof t.enabled==`boolean`?t.enabled:A.enabled,targetDepth:n,lowWatermark:r,maxRefillInFlight:P(t.maxRefillInFlight,A.maxRefillInFlight,1,8),refillAttemptTimeoutMs:P(t.refillAttemptTimeoutMs,A.refillAttemptTimeoutMs,5e3,12e4)}}function ve(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:2e4}function ye(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||``)}function be(e){return Error(`[router-ab-ecdsa-derivation] ${e.operation} request timed out after ${e.timeoutMs}ms`)}async function xe(e){let t=ve(e.timeoutMs),r=typeof AbortController==`function`?new AbortController:null,i={...e.init},a=null,o=null,s=!1;try{let c;if(r){let l=e.init.signal;if(l){if(l.aborted)r.abort();else if(typeof l.addEventListener==`function`){let e=()=>r.abort();l.addEventListener(`abort`,e,{once:!0}),o=()=>l.removeEventListener(`abort`,e)}}a=setTimeout(()=>{s=!0,r.abort()},t),c=await n(new Request(e.url,{...i,signal:r.signal}))}else c=await Promise.race([n(new Request(e.url,i)),new Promise((n,r)=>{a=setTimeout(()=>{s=!0,r(be({operation:e.operation,timeoutMs:t}))},t)})]);let l=await c.json().catch(()=>({}));if(s)throw be({operation:e.operation,timeoutMs:t});return{response:c,data:l}}catch(n){if(s)throw be({operation:e.operation,timeoutMs:t});let r=ye(n);throw Error(r||`[router-ab-ecdsa-derivation] ${e.operation} request failed`)}finally{a&&clearTimeout(a),o?.()}}const Se=5e3;function Ce(e,t){let n=Math.min(e-Date.now(),t??Se,Se);return Number.isFinite(n)&&n>0?n:null}function we(n){return t(e(n))||null}function Te(e){let t={"Content-Type":`application/json`};switch(e.credential.kind){case`operation_step_up`:return{ok:!0,headers:t,credentials:`omit`};case`wallet_session_opaque`:{let n=String(e.credential.walletSessionToken||``).trim();return n?(Object.assign(t,r({token:n,home:e.credential.home})),{ok:!0,headers:t,credentials:`omit`}):{ok:!1,code:`invalid_args`,message:`Missing opaque Wallet Session token for Router A/B ECDSA derivation presign pool fill`}}}}function Ee(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function De(e){let t=String(e.keyHandle||``).trim();return t?{ok:!0,value:{keyHandle:t}}:{ok:!1,code:`invalid_args`,message:`Missing keyHandle for Router A/B ECDSA derivation pool-fill init`}}async function Oe(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill init`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill init`};let n=De(e);if(!n.ok)return n;let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.poolFill.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/init`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({...n.value,count:Number.isFinite(e.count)?Math.max(1,Math.floor(Number(e.count))):1,...r?{requestTag:r}:{},poolFill:e.poolFill,presignSessionId:e.presignSessionId,firstMessageB64u:e.firstMessageB64u,...Ee(e)})}});return typeof s.presignSessionId==`string`&&x(s.presignSessionId,`init`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,presignSessionId:s.presignSessionId,...Number.isSafeInteger(s.ceremonyExpiresAtMs)?{ceremonyExpiresAtMs:s.ceremonyExpiresAtMs}:{},...Number.isSafeInteger(s.materialExpiresAtMs)?{materialExpiresAtMs:s.materialExpiresAtMs}:{},stage:s.stage,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill init`)}}}async function ke(e){return Oe({...e,path:c})}async function Ae(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill step`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill step`};let n=String(e.presignSessionId||``).trim();if(!n)return{ok:!1,code:`invalid_args`,message:`Missing presignSessionId for Router A/B ECDSA derivation pool-fill step`};let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/step`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({presignSessionId:n,ceremonyExpiresAtMs:e.ceremonyExpiresAtMs,materialExpiresAtMs:e.materialExpiresAtMs,stage:e.stage,outgoingMessagesB64u:Array.isArray(e.outgoingMessagesB64u)?e.outgoingMessagesB64u:[],...r?{requestTag:r}:{},...Ee(e)})}});return x(n,`step`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,stage:s.stage,event:s.event,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.presignatureId?{presignatureId:s.presignatureId}:{},...s.bigRB64u?{bigRB64u:s.bigRB64u}:{},...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill step`)}}}async function je(e){return Ae({...e,path:u})}var Me=class{constructor(){this.state={kind:`refilling`,revision:0},this.waiters=new Map}snapshot(){return this.state}hasForegroundWaiters(){for(let e of this.waiters.values())if(e===`foreground`)return!0;return!1}publishAvailable(){this.state.kind!==`settled`&&(this.state={kind:`refilling`,revision:this.state.revision+1},this.flushWaiters())}settle(){this.state.kind!==`settled`&&(this.state={kind:`settled`,revision:this.state.revision},this.flushWaiters())}waitForChange(e,t){return this.state.kind===`settled`||this.state.revision!==e.revision?Promise.resolve(this.state):new Promise(n=>{this.waiters.set(n,t),(this.state.kind===`settled`||this.state.revision!==e.revision)&&(this.waiters.delete(n),n(this.state))})}flushWaiters(){let e=this.state,t=[...this.waiters.keys()];this.waiters.clear();for(let n of t)n(e)}};function Ne(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`WebCrypto getRandomValues is required for ECDSA rerandomization`);return e.getRandomValues(new Uint8Array(32))}function F(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function Pe(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||`signature recovery failed`)}function I(e){e instanceof Uint8Array&&e.fill(0)}function Fe(e){if(e?.kind!==`router_ab_ecdsa_derivation_client_signing_material_source_v1`)throw Error(`Router A/B ECDSA derivation client signing material source is required`)}const Ie=6e4,L=new Map,R=new Map,z=new Map,B=new Map,V=new Map,H=new Map;function Le(e){return e===`triples_done`||e===`presign`||e===`done`}function Re(e){return Le(e.clientStage)&&Le(e.serverStage)?`presign`:`triples`}function ze(e){let t=L.get(e);if(!t?.length)return null;let n=t.shift()??null;return t.length?L.set(e,t):L.delete(e),n}async function U(e){return await Ue(e),ze(e.poolKey)}function Be(e,t,n){if(!K(n))return`invalid`;let r=L.get(e)||[];for(let e of r)if(e.materialHandle===n.materialHandle)return`duplicate`;return r.filter(e=>K(e)).length>=5?`capacity_full`:(r.push(n),L.set(e,r),R.set(e,t),`stored`)}function Ve(e,t=Date.now()){let n=L.get(e);if(!n?.length)return[];let r=[],i=[];for(let e of n)K(e,t)?r.push(e):i.push(e);return r.length>0?L.set(e,r):L.delete(e),i}async function He(e){for(let t of e.refs)await e.clientSigningMaterial.destroyClientPresignature({materialHandle:t.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}async function Ue(e){await He({refs:Ve(e.poolKey),poolIdentity:e.poolIdentity,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}async function W(e,t,n){try{await _(e.walletId,e.ownershipGeneration)}catch(r){throw await qe({poolIdentity:e,poolKey:g(e),clientSigningMaterial:t,workerCtx:n}),r}}async function We(e){await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx);let t=V.get(e.poolKey);if(t){await t;return}let n=Ge(e);V.set(e.poolKey,n);try{await n}finally{V.get(e.poolKey)===n&&V.delete(e.poolKey)}}async function Ge(e){await Ue(e);let t;t=await e.clientSigningMaterial.listAvailableClientPresignatures({poolIdentity:e.poolIdentity,workerCtx:e.workerCtx});try{await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(e.poolKey)!==e.generation){for(let n of t)I(n.bigR33),await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{});return}for(let n of t){let t=Be(e.poolKey,e.poolIdentity,{presignatureId:n.presignatureId,materialHandle:n.materialHandle,bigRB64u:i(n.bigR33),createdAtMs:n.createdAtMs,expiresAtMs:n.expiresAtMs});I(n.bigR33),(t===`invalid`||t===`capacity_full`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}}function G(e){let t=L.get(e);return t?t.reduce((e,t)=>e+(K(t)?1:0),0):0}function K(e,t=Date.now()){let n=Math.floor(Number(e.expiresAtMs));return!!(e.presignatureId&&e.bigRB64u&&e.materialHandle)&&Number.isSafeInteger(n)&&n>t+2e3}function q(e){let t=H.get(e);return t===void 0?(H.set(e,0),0):t}function Ke(e){Z(e);let t=q(e)+1;return H.set(e,t),t}async function qe(e){let t=L.get(e.poolKey)??[];$e(e.poolKey),await He({...e,refs:t})}function J(e){return B.get(e)||0}function Je(e){let t=J(e);B.set(e,t+1)}function Ye(e){let t=J(e);if(t<=1){B.delete(e),Q(e,0);return}B.set(e,t-1)}async function Xe(e,t){let n=z.get(e);if(!n)return;let r=n.snapshot();for(;G(e)===0&&r.kind===`refilling`;)r=await n.waitForChange(r,t)}async function Ze(e){let t=g(v({ownershipGeneration:e.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.scope,materialActivation:e.materialActivation}));return G(t)>0?!0:(await Xe(t,`background`),G(t)>0)}function Y(e,t,n){return{scheduled:!1,reason:e,depth:t,targetDepth:n}}function Qe(){let e=new Set([...X.keys(),...L.keys(),...z.keys(),...B.keys(),...H.keys()]);for(let t of e)Ke(t);L.clear(),R.clear();for(let e of z.values())e.settle();z.clear(),B.clear()}function $e(e){L.delete(e),R.delete(e),Ke(e),z.get(e)?.settle(),z.delete(e)}function et(e){let t=String(e).trim();if(!t)throw Error(`ECDSA presignature wallet id is required`);for(let[e,n]of[...R])n.walletId===t&&$e(e)}const X=new Map;function Z(e){let t=X.get(e);t&&t.timer!==null&&clearTimeout(t.timer),X.delete(e),X.size===0&&typeof window<`u`&&(window.removeEventListener(`online`,$),document.removeEventListener(`visibilitychange`,$))}function Q(e,t){let n=X.get(e);if(!n)return;n.timer!==null&&clearTimeout(n.timer);let r=n.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs-Date.now();if(r<=0||q(e)!==n.generation){Z(e);return}n.timer=setTimeout(tt,Math.min(t,r),e)}function $(){if(!(typeof document<`u`&&document.visibilityState===`hidden`))for(let e of X.keys())Q(e,0)}function tt(e){let t=X.get(e);if(!t)return;if(t.timer=null,Date.now()>=t.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs){Z(e);return}if(typeof navigator<`u`&&navigator.onLine===!1){Q(e,3e4);return}let n=at(t.input);n.scheduled||Q(e,n.depth>=n.targetDepth?3e4:5e3)}function nt(e,t){t.authorization.kind===`reusable_wallet_session`&&X.get(e)?.input!==t&&(Z(e),X.size===0&&typeof window<`u`&&(window.addEventListener(`online`,$),document.addEventListener(`visibilitychange`,$)),X.set(e,{input:t,generation:q(e),failures:0,timer:null}),Q(e,3e4))}function rt(e,t,n){let r=X.get(e);if(!(!r||r!==t)){switch(n){case`network_error`:case`internal`:case`presign_timeout`:case`temporarily_unavailable`:case`service_unavailable`:case`wallet_session_unavailable`:if(r.failures+=1,r.failures<=3)return}Z(e)}}async function it(e){let{args:t,refillInput:n,poolKey:r,poolIdentity:i,scheduledGeneration:a,targetDepth:o,refillAttemptTimeoutMs:s,progress:c}=e,l=X.get(r)??null;try{for(await We({poolKey:r,poolIdentity:i,clientSigningMaterial:t.clientSigningMaterial,workerCtx:t.workerCtx,generation:a}),G(r)>0&&c.publishAvailable();Date.now()<t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs;){if(q(r)!==a||(X.get(r)??null)!==l||G(r)>=o||J(r)>0||typeof navigator<`u`&&navigator.onLine===!1)return;let e=Math.min(Date.now()+s,t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs),i=await _t({...n,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:n.routerAbEcdsaDerivationPoolFill.scope,ceremonyExpiresAtMs:e,materialExpiresAtMs:n.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs},trafficClass:`background`});if(S(`evm-family`,{event:`ecdsa_background_refill_result`,authorization:t.authorization.kind,outcome:i.ok?`available`:`failed`,code:i.ok?null:i.code,depth:G(r),targetDepth:o}),!i.ok){rt(r,l,i.code);return}let u=X.get(r);u&&u===l&&(u.failures=0),c.publishAvailable()}}catch{rt(r,l,`internal`)}finally{c.settle(),z.get(r)===c&&z.delete(r);let e=X.get(r);if(e){let t=e.failures>0?2e3*2**e.failures:1e3;G(r)>=o&&(t=3e4),e!==l&&(t=0),Q(r,t)}}}function at(e){try{let t=_e(e.poolPolicy),n=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),r=g(n);R.set(r,n);let i=he(e.targetDepth,t.targetDepth),a=ge(e.triggerIfDepthAtOrBelow,t.lowWatermark,i),o=G(r),s=q(r);if(!t.enabled)return Y(`disabled`,o,i);if(e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs<=Date.now())return Z(r),Y(`invalid_args`,o,i);if(nt(r,e),o>a)return Y(`depth_above_trigger`,o,i);if(o>=i)return Y(`depth_at_or_above_target`,o,i);if(z.has(r)||J(r)>0)return Y(`in_flight_for_pool_key`,o,i);if(z.size>=t.maxRefillInFlight)return Y(`global_in_flight_limit`,o,i);let c={relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,clientVerifyingShareB64u:e.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)},l=new Me;return z.set(r,l),it({args:e,refillInput:c,poolKey:r,poolIdentity:n,scheduledGeneration:s,targetDepth:i,refillAttemptTimeoutMs:t.refillAttemptTimeoutMs,progress:l}),{scheduled:!0,reason:`scheduled`,depth:o,targetDepth:i}}catch{return Y(`invalid_args`,0,0)}}function ot(e){return e.map(e=>i(e))}function st(e){return Array.isArray(e)?e.map(e=>String(e||``).trim()).filter(e=>!!e).map(e=>a(e)):[]}async function ct(e){let t=String(e.thresholdEcdsaPublicKeyB64u||``).trim();if(t){let n=a(t);if(n.length!==33)throw Error(`thresholdEcdsaPublicKeyB64u must decode to 33 bytes`);return await M({publicKey33:n,workerCtx:e.workerCtx})}let n=String(e.clientVerifyingShareB64u||``).trim(),r=String(e.relayerVerifyingShareB64u||``).trim();if(!n||!r)throw Error(`Missing thresholdEcdsaPublicKeyB64u (or relayerVerifyingShareB64u fallback) for Router A/B ECDSA derivation signing`);let i=a(n),o=a(r);if(i.length!==33)throw Error(`clientVerifyingShareB64u must decode to 33 bytes`);if(o.length!==33)throw Error(`relayerVerifyingShareB64u must decode to 33 bytes`);return await de({left33:await M({publicKey33:i,workerCtx:e.workerCtx}),right33:await M({publicKey33:o,workerCtx:e.workerCtx}),workerCtx:e.workerCtx})}function lt(e){return e.trafficClass===`foreground`||z.get(e.poolKey)?.hasForegroundWaiters()?`foreground_presign_pool_refill`:`background_presign_pool_refill`}async function ut(e){for(let t=0;t<2;t+=1){let n=await dt(e);if(n.ok||!ft(n)||t===1)return n}return{ok:!1,code:`stale_session_state`,message:`Router A/B ECDSA derivation pool-fill session stayed stale after retry`}}async function dt(e){Fe(e.clientSigningMaterial);let t=performance.now(),n=e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs,r=e.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs,a=`ecdsa-presign-v2:${n}:${i(crypto.getRandomValues(new Uint8Array(32)))}`,o=a,s=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),c=null,l=null,u=null,d=null,ee=!1,f=`triples`,p=[],m=!0,h=!1;try{let t=await e.clientSigningMaterial.initClientPresignSession({sessionId:o,groupPublicKey33:e.groupPublicKey33,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,poolIdentity:s,workerCtx:e.workerCtx});if(t.stage!==`triples`||t.outgoingMessages.length!==1)return{ok:!1,code:`presign_init_failed`,message:`Client presign init must emit exactly one first message`};f=t.stage;let g=await ke({relayerUrl:e.relayerUrl,...e.poolFillInitKeySelector,count:1,presignSessionId:a,firstMessageB64u:i(t.outgoingMessages[0]),credential:e.credential,requestTag:lt(e),poolFill:e.routerAbEcdsaDerivationPoolFill,...F(e)});if(!g.ok)return{ok:!1,code:g.code||`presign_init_failed`,message:g.message||`Presign initialization failed`};if(g.presignSessionId!==a||g.ceremonyExpiresAtMs!==n||g.materialExpiresAtMs!==r||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Presign initialization changed the bound identity or deadlines`};let _=g.stage||`triples`,v=st(g.outgoingMessagesB64u);for(let t=0;t<64;t++){if(v.length>0&&!c){let t=await e.clientSigningMaterial.stepClientPresignSession({sessionId:o,stage:Re({clientStage:f,serverStage:_}),incomingMessages:v,workerCtx:e.workerCtx});f=t.stage,v=[],p.push(...t.outgoingMessages),t.presignatureHandle&&t.presignatureBigR33&&(c=t.presignatureHandle,l=t.presignatureBigR33)}if(!ee){let i=performance.now(),o=lt(e),s={relayerUrl:e.relayerUrl,presignSessionId:a,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,stage:Re({clientStage:f,serverStage:_}),outgoingMessagesB64u:ot(p),credential:e.credential,requestTag:o,...F(e)},c=await je(s);if(S(`evm-family`,{event:`ecdsa_presignature_round`,requestTag:o,presignSessionId:a,authorization:e.authorization.kind,round:t,stage:s.stage,durationMs:performance.now()-i,outcome:c.ok?`succeeded`:`failed`}),p=[],!c.ok)return{ok:!1,code:c.code||`presign_step_failed`,message:c.message||`Router A/B ECDSA derivation pool-fill step failed`};v=st(c.outgoingMessagesB64u),_=c.stage||_,c.event===`presign_done`&&(u=String(c.presignatureId||``).trim()||null,d=String(c.bigRB64u||``).trim()||null,ee=!0)}if(c&&l&&u&&d)break}if(!c||!l)return{ok:!1,code:`presign_timeout`,message:`Client presign session did not reach done state`};if(!u||!d)return{ok:!1,code:`presign_timeout`,message:`Server presign session did not reach done state`};if(l.length!==33)return{ok:!1,code:`internal`,message:`Invalid local presignature bigR bytes (expected 33, got ${l.length})`};try{let t=Date.now(),n=i(l);if(n!==d)return{ok:!1,code:`presign_mismatch`,message:`Client/server presignature mismatch (bigR mismatch)`};let a=await e.clientSigningMaterial.admitClientPresignature({materialHandle:c,expectedPresignatureId:u,poolIdentity:s,admissionMode:e.authorization.kind===`operation_step_up`?`resident`:`durable`,workerCtx:e.workerCtx});return a.kind===`discarded_capacity`?{ok:!1,code:`pool_full`,message:`Router A/B ECDSA derivation client presignature pool is full`}:a.kind===`discarded_ambiguous`?{ok:!1,code:`presign_failed`,message:`Router A/B ECDSA derivation client presignature admission was ambiguous`}:(h=!0,m=!1,{ok:!0,kind:`available`,presignature:{presignatureId:u,bigRB64u:n,materialHandle:c,createdAtMs:t,expiresAtMs:r}})}finally{I(l)}}catch(e){return{ok:!1,code:`presign_failed`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation pool-fill handshake failed`)}}finally{S(`evm-family`,{event:`ecdsa_presignature_generation`,requestTag:lt(e),presignSessionId:a,authorization:e.authorization.kind,durationMs:performance.now()-t,outcome:h?`available`:`failed`}),I(l),!h&&c&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:c,poolIdentity:s,workerCtx:e.workerCtx}).catch(()=>{}),m&&await e.clientSigningMaterial.abortClientPresignSession({sessionId:o,workerCtx:e.workerCtx}).catch(()=>{})}}function ft(e){return e.code===`stale_session_state`||e.code===`stale_pool_fill_session`}function pt(e){let t=l(e);return{ecdsaThresholdKeyId:p(t.ecdsa_threshold_key_id),clientVerifyingShareB64u:h(t.public_identity.derivation_client_share_public_key33_b64u),thresholdEcdsaPublicKeyB64u:t.public_identity.threshold_public_key33_b64u}}function mt(e){let t=Math.floor(Number(e.materialExpiresAtMs)),n=Number.isSafeInteger(e.authorizationExpiresAtMs)?Math.floor(Number(e.authorizationExpiresAtMs)):e.nowMs+Ie,r=Math.min(t,n,e.nowMs+Ie);return Number.isSafeInteger(r)&&r>e.nowMs?r:null}async function ht(e,t,n){let r=null,c=null,l=null,u=null,d=null,p={kind:`unclaimed`},m=null,h={kind:`before_prepare`};try{let _=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!_)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation signing`};let y=pt(e.scope);if(!y.ecdsaThresholdKeyId)return{ok:!1,code:`invalid_args`,message:`Missing ecdsaThresholdKeyId for Router A/B ECDSA derivation signing`};let x=y.clientVerifyingShareB64u;if(!x)return{ok:!1,code:`invalid_args`,message:`Missing clientVerifyingShareB64u for Router A/B ECDSA derivation signing`};if(!(e.signingDigest32 instanceof Uint8Array)||e.signingDigest32.length!==32)return{ok:!1,code:`invalid_args`,message:`signingDigest32 must be 32 bytes for Router A/B ECDSA derivation signing`};let ne=performance.now(),C=await ct({clientVerifyingShareB64u:x,thresholdEcdsaPublicKeyB64u:y.thresholdEcdsaPublicKeyB64u,workerCtx:e.workerCtx});b(e.operationId,`public_key_validation`,ne),c=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:_,scope:e.scope,materialActivation:e.materialActivation}),await W(c,e.clientSigningMaterial,e.workerCtx),r=g(c),R.set(r,c),m=q(r);let re=performance.now();if(l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`pool_lookup`,re),!l){let t=performance.now();await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:m}),b(e.operationId,`pool_restore`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l){let t=performance.now();await Xe(r,`foreground`),b(e.operationId,`refill_wait`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l&&n.kind===`on_demand`){let t=performance.now();Je(r);try{let t=await _t({...n.refill,trafficClass:`foreground`});if(!t.ok&&t.code===`invalidated`&&(t=await _t({...n.refill,trafficClass:`foreground`})),!t.ok&&t.code!==`pool_full`)return t;!t.ok&&t.code===`pool_full`&&await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:q(r)})}finally{Ye(r)}m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`foreground_refill`,t)}if(S(`evm-family`,{event:`ecdsa_presignature_selection`,operationId:e.operationId,authorization:e.authorization.kind,outcome:l?`available`:`empty`,remainingDepth:G(r),attempt:t}),!l)return{ok:!1,code:`pool_empty`,message:`Router A/B ECDSA derivation client presignature pool is empty`};let ie=Date.now(),ae=mt({authorizationExpiresAtMs:e.expiresAtMs,materialExpiresAtMs:l.expiresAtMs,nowMs:ie});if(!ae)return{ok:!1,code:`pool_entry_expired`,message:`Router A/B ECDSA derivation client presignature is expired`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};d=Ne();let w=await ee(d),T=s({scope:e.scope,requestId:o(`router-ab-ecdsa-sign`,32,`Router A/B ECDSA derivation sign request`),operationId:e.operationId,operationDigests:e.operationDigests,authorization:e.authorization,materialActivation:e.materialActivation,clientPresignatureId:l.presignatureId,expiresAtMs:ae,signingDigest32:e.signingDigest32,clientRerandomizationCommitment32:w});I(w);let E=o(`router-ab-ecdsa-reservation`,32,`Router A/B ECDSA Client presignature reservation`);p={kind:`destroy`};let oe=performance.now(),D=await e.clientSigningMaterial.reserveClientPresignature({materialHandle:l.materialHandle,expectedPresignatureId:l.presignatureId,poolIdentity:c,requestBinding:T.request_id,reservationId:E,leaseExpiresAtMs:T.expires_at_ms,workerCtx:e.workerCtx});if(b(e.operationId,`presignature_reserve`,oe),D.kind===`unavailable`)return D.reason===`claimed_elsewhere`&&(p={kind:`owned_elsewhere`}),t<4?await ht(e,t+1,n):{ok:!1,code:D.reason===`expired`?`pool_entry_expired`:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature is unavailable: ${D.reason}`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};Q(r,0),h={kind:`prepare_submitted`};let se=performance.now(),O=await ce({relayServerUrl:_,credential:e.credential,request:T,onServerTiming:te.bind(void 0,e.operationId,`prepare`)});if(b(e.operationId,`prepare`,se),O.kind===`reusable_wallet_session`){if(!e.reconcileSession)throw Error(`Wallet Session reconciliation is required`);await e.reconcileSession(O.sessionStatus)}let k=O.signing;if(k.server_big_r33_b64u!==l.bigRB64u)return{ok:!1,code:`presign_mismatch`,message:`Router A/B ECDSA derivation SigningWorker returned a different presignature bigR`};let A=performance.now();await e.clientSigningMaterial.commitClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,workerCtx:e.workerCtx}),b(e.operationId,`presignature_commit`,A);let j=a(l.bigRB64u),M=a(k.signing_worker_rerandomization_contribution32_b64u);try{if(j.length!==33)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation presign bigR must decode to 33 bytes`};if(M.length!==32)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation SigningWorker rerandomization contribution must decode to 32 bytes`};let t=performance.now();u=await e.clientSigningMaterial.computeSignatureShareFromPresignatureHandle({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,groupPublicKey33:C,expectedPresignBigR33:j,digest32:e.signingDigest32,clientRerandomizationContribution32:d,signingWorkerRerandomizationContribution32:M,workerCtx:e.workerCtx}),b(e.operationId,`client_share`,t),p={kind:`consumed`}}finally{I(j),I(M)}if(u.length!==32)return{ok:!1,code:`internal`,message:`Invalid Router A/B ECDSA derivation client signature share length (expected 32, got ${u.length})`};let de=f({scope:e.scope,requestId:T.request_id,operationId:T.operation_id,operationDigests:T.operation_digests,authorization:e.authorization,materialActivation:e.materialActivation,expiresAtMs:T.expires_at_ms,signingDigest32:e.signingDigest32,serverPresignatureId:k.server_presignature_id,clientSignatureShare32:u,clientRerandomizationContribution32:d}),fe=performance.now(),pe=await le({relayServerUrl:_,credential:e.credential,request:de,onServerTiming:te.bind(void 0,e.operationId,`finalize`)});b(e.operationId,`finalize`,fe);let N=a(pe.signature65_b64u);if(N.length!==65)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned invalid signature length (expected 65, got ${N.length})`};try{let t=performance.now();await ue({digest32:e.signingDigest32,signature65:N,publicKey33:C,workerCtx:e.workerCtx}),b(e.operationId,`signature_verify`,t)}catch(e){return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned a signature that does not recover to the threshold group public key: ${Pe(e)}`}}return{ok:!0,signature65:N,signature65B64u:pe.signature65_b64u,rB64u:i(N.slice(0,32)),sB64u:i(N.slice(32,64)),recId:N[64]}}catch(t){if(t instanceof O||t instanceof k)throw t;let n=String(t&&typeof t==`object`&&`message`in t?t.message:t||`Router A/B ECDSA derivation signing failed`);return t instanceof j&&t.code===`expired_local_request`?{ok:!1,code:`pool_entry_expired`,message:n}:r&&c&&m!==null&&h.kind===`before_prepare`&&q(r)!==m?(await qe({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`}):{ok:!1,code:`router_ab_sign_failed`,message:n}}finally{if(I(u),I(d),l&&c&&p.kind!==`consumed`&&p.kind!==`owned_elsewhere`){let t=!1;if(p.kind===`unclaimed`&&r&&m!==null&&m===q(r)){let e=Be(r,c,l);t=e===`stored`||e===`duplicate`}t||await e.clientSigningMaterial.destroyClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,workerCtx:e.workerCtx}).catch(()=>{})}r&&Q(r,0)}}async function gt(e){let t=pt(e.scope),n=Math.floor(Number(e.expiresAtMs));if(!Number.isSafeInteger(n)||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Router A/B ECDSA derivation pool fill expiry is unavailable or expired`};let r={kind:`on_demand`,refill:{relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,clientVerifyingShareB64u:t.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:e.scope,ceremonyExpiresAtMs:Math.min(n,Date.now()+d-3e4),materialExpiresAtMs:e.authorization.kind===`operation_step_up`?n:Date.now()+y},workerCtx:e.workerCtx,...F(e)}},i=await ht(e,0,r);return!i.ok&&(i.code===`pool_entry_expired`||i.code===`pool_entry_unavailable`)?await ht(e,0,r):i}async function _t(e){try{let t=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation});await W(t,e.clientSigningMaterial,e.workerCtx);let n=g(t);await Ue({poolKey:n,poolIdentity:t,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx});let r=q(n),i=await ct({clientVerifyingShareB64u:e.clientVerifyingShareB64u,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,workerCtx:e.workerCtx}),a=await ut({relayerUrl:e.relayerUrl,poolFillInitKeySelector:{keyHandle:m(e.keyHandle)},clientSigningMaterial:e.clientSigningMaterial,groupPublicKey33:i,materialActivation:e.materialActivation,credential:e.credential,poolKey:n,trafficClass:e.trafficClass,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)});if(!a.ok)return a;try{await W(t,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(n)!==r)return await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!1,code:`invalidated`,message:`Router A/B ECDSA derivation presignature pool invalidated`};let o=Be(n,t,a.presignature);return(o===`capacity_full`||o===`invalid`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!0,presignatureId:a.presignature.presignatureId}}catch(e){return{ok:!1,code:`internal`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation presignature refill failed`)}}}export{Ze as a,pe as c,gt as i,et as n,_e as o,at as r,me as s,Qe as t};
1
+ import{B as e,V as t}from"./domainIds-BzkGsRqO.js";import{A as n,k as r}from"./primitives-CqrjmIAH.js";import{i,r as a}from"./base64-DW79QA0h.js";import{r as o}from"./secureRandomId-LwBFx84B.js";import{B as s,F as c,G as l,I as u,R as d,dt as ee,z as f}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{I as p,L as m,R as h}from"./ecdsaCapabilityManifest-ChszYCC0.js";import{ct as g,n as _,ut as v}from"./walletOwnershipGeneration-CAycHv-H.js";import{t as y}from"./presignatures-DZm0d6Wy.js";import{i as b,n as x,r as te,u as S}from"./trace-QLsbYdld.js";import{A as ne,C,D as re,E as ie,O as ae,S as w,T,k as E,w as oe,x as D,y as se}from"./ecdsaDerivationClientWasm-CpH-b3jx.js";import{t as O}from"./authorizationAdmission-CGinGhXH.js";import{t as k}from"./walletSessionFailure-YuhraC3P.js";import{c as ce,f as A,o as le,t as j}from"./routerAbNormalSigning-B35zb-P-.js";import{o as M,s as ue,t as de}from"./evmCryptoWasm-DeobzyP-.js";async function fe(e){let t=e.clientShare.material;if(t.kind===`worker_loaded`)return;let n=await se({materialHandle:e.clientShare.handle.materialHandle,bindingDigest:e.clientShare.handle.bindingDigest,stateBlob:t.stateBlob,workerCtx:e.workerCtx});if(n.materialHandle!==e.clientShare.handle.materialHandle||n.bindingDigest!==e.clientShare.handle.bindingDigest)throw Error(`[multichain] ECDSA role-local worker material handle mismatch`)}async function pe(e){let t=e.signerSession,n=t.clientShare;if(n.kind===`linked_holder_worker_share`){let e=n.holderHandleId;return{signerSession:t,clientSigningMaterial:me(e),cleanupAfterSign:async()=>void 0}}let r=n;return{signerSession:t,clientSigningMaterial:{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:async t=>(await fe({workerCtx:e.workerCtx,clientShare:r}),await ae({materialHandle:r.handle.materialHandle,material:r.material.kind===`worker_loaded`?{kind:`persisted`,materialRef:r.material.materialRef}:{kind:`runtime_loaded`,expectedBindingDigest:r.handle.bindingDigest},...t})),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`role_local_derivation_handle`),computeSignatureShareFromPresignatureHandle:T},cleanupAfterSign:async()=>void 0}}async function N(e,t){return await D({holderHandleId:e,...t})}function me(e){return{kind:`router_ab_ecdsa_derivation_client_signing_material_source_v1`,initClientPresignSession:N.bind(void 0,e),stepClientPresignSession:E,abortClientPresignSession:re,admitClientPresignature:C,destroyClientPresignature:ie,reserveClientPresignature:ne,commitClientPresignature:oe,listAvailableClientPresignatures:w.bind(void 0,`linked_holder_signing_material`),computeSignatureShareFromPresignatureHandle:T}}function P(e,t,n,r){let i=Math.floor(Number(e));return Number.isFinite(i)?i<n?n:i>r?r:i:t}function he(e,t){return P(e,t,1,5)}function ge(e,t,n){return P(e,t,0,n)}function _e(e){let t=e||A,n=he(t.targetDepth,A.targetDepth),r=ge(t.lowWatermark,A.lowWatermark,n);return{enabled:typeof t.enabled==`boolean`?t.enabled:A.enabled,targetDepth:n,lowWatermark:r,maxRefillInFlight:P(t.maxRefillInFlight,A.maxRefillInFlight,1,8),refillAttemptTimeoutMs:P(t.refillAttemptTimeoutMs,A.refillAttemptTimeoutMs,5e3,12e4)}}function ve(e){let t=Math.floor(Number(e));return Number.isFinite(t)&&t>0?t:2e4}function ye(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||``)}function be(e){return Error(`[router-ab-ecdsa-derivation] ${e.operation} request timed out after ${e.timeoutMs}ms`)}async function xe(e){let t=ve(e.timeoutMs),r=typeof AbortController==`function`?new AbortController:null,i={...e.init},a=null,o=null,s=!1;try{let c;if(r){let l=e.init.signal;if(l){if(l.aborted)r.abort();else if(typeof l.addEventListener==`function`){let e=()=>r.abort();l.addEventListener(`abort`,e,{once:!0}),o=()=>l.removeEventListener(`abort`,e)}}a=setTimeout(()=>{s=!0,r.abort()},t),c=await n(new Request(e.url,{...i,signal:r.signal}))}else c=await Promise.race([n(new Request(e.url,i)),new Promise((n,r)=>{a=setTimeout(()=>{s=!0,r(be({operation:e.operation,timeoutMs:t}))},t)})]);let l=await c.json().catch(()=>({}));if(s)throw be({operation:e.operation,timeoutMs:t});return{response:c,data:l}}catch(n){if(s)throw be({operation:e.operation,timeoutMs:t});let r=ye(n);throw Error(r||`[router-ab-ecdsa-derivation] ${e.operation} request failed`)}finally{a&&clearTimeout(a),o?.()}}const Se=5e3;function Ce(e,t){let n=Math.min(e-Date.now(),t??Se,Se);return Number.isFinite(n)&&n>0?n:null}function we(n){return t(e(n))||null}function Te(e){let t={"Content-Type":`application/json`};switch(e.credential.kind){case`operation_step_up`:return{ok:!0,headers:t,credentials:`omit`};case`wallet_session_opaque`:{let n=String(e.credential.walletSessionToken||``).trim();return n?(Object.assign(t,r({token:n,home:e.credential.home})),{ok:!0,headers:t,credentials:`omit`}):{ok:!1,code:`invalid_args`,message:`Missing opaque Wallet Session token for Router A/B ECDSA derivation presign pool fill`}}}}function Ee(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function De(e){let t=String(e.keyHandle||``).trim();return t?{ok:!0,value:{keyHandle:t}}:{ok:!1,code:`invalid_args`,message:`Missing keyHandle for Router A/B ECDSA derivation pool-fill init`}}async function Oe(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill init`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill init`};let n=De(e);if(!n.ok)return n;let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.poolFill.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/init`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({...n.value,count:Number.isFinite(e.count)?Math.max(1,Math.floor(Number(e.count))):1,...r?{requestTag:r}:{},poolFill:e.poolFill,presignSessionId:e.presignSessionId,firstMessageB64u:e.firstMessageB64u,...Ee(e)})}});return typeof s.presignSessionId==`string`&&x(s.presignSessionId,`init`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,presignSessionId:s.presignSessionId,...Number.isSafeInteger(s.ceremonyExpiresAtMs)?{ceremonyExpiresAtMs:s.ceremonyExpiresAtMs}:{},...Number.isSafeInteger(s.materialExpiresAtMs)?{materialExpiresAtMs:s.materialExpiresAtMs}:{},stage:s.stage,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill init`)}}}async function ke(e){return Oe({...e,path:c})}async function Ae(e){let t=we(e.relayerUrl);if(!t)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation pool-fill step`};if(typeof fetch!=`function`)return{ok:!1,code:`unsupported`,message:`fetch is not available for Router A/B ECDSA derivation pool-fill step`};let n=String(e.presignSessionId||``).trim();if(!n)return{ok:!1,code:`invalid_args`,message:`Missing presignSessionId for Router A/B ECDSA derivation pool-fill step`};let r=String(e.requestTag||``).trim(),i=Te(e);if(!i.ok)return i;let a=Ce(e.ceremonyExpiresAtMs,e.requestTimeoutMs);if(a===null)return{ok:!1,code:`presign_timeout`,message:`Presign ceremony deadline has elapsed`};try{let{response:o,data:s}=await xe({url:`${t}${e.path}`,operation:`presign/step`,timeoutMs:a,init:{method:`POST`,headers:i.headers,credentials:i.credentials,body:JSON.stringify({presignSessionId:n,ceremonyExpiresAtMs:e.ceremonyExpiresAtMs,materialExpiresAtMs:e.materialExpiresAtMs,stage:e.stage,outgoingMessagesB64u:Array.isArray(e.outgoingMessagesB64u)?e.outgoingMessagesB64u:[],...r?{requestTag:r}:{},...Ee(e)})}});return x(n,`step`,o.headers.get(`Server-Timing`)),o.ok?{ok:s.ok===!0,stage:s.stage,event:s.event,outgoingMessagesB64u:Array.isArray(s.outgoingMessagesB64u)?s.outgoingMessagesB64u:[],...s.presignatureId?{presignatureId:s.presignatureId}:{},...s.bigRB64u?{bigRB64u:s.bigRB64u}:{},...s.code?{code:s.code}:{},...s.message?{message:s.message}:{}}:{ok:!1,code:s.code||`http_error`,message:s.message||`HTTP ${o.status}`}}catch(e){return{ok:!1,code:`network_error`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Failed Router A/B ECDSA derivation pool-fill step`)}}}async function je(e){return Ae({...e,path:u})}var Me=class{constructor(){this.state={kind:`refilling`,revision:0},this.waiters=new Map}snapshot(){return this.state}hasForegroundWaiters(){for(let e of this.waiters.values())if(e===`foreground`)return!0;return!1}publishAvailable(){this.state.kind!==`settled`&&(this.state={kind:`refilling`,revision:this.state.revision+1},this.flushWaiters())}settle(){this.state.kind!==`settled`&&(this.state={kind:`settled`,revision:this.state.revision},this.flushWaiters())}waitForChange(e,t){return this.state.kind===`settled`||this.state.revision!==e.revision?Promise.resolve(this.state):new Promise(n=>{this.waiters.set(n,t),(this.state.kind===`settled`||this.state.revision!==e.revision)&&(this.waiters.delete(n),n(this.state))})}flushWaiters(){let e=this.state,t=[...this.waiters.keys()];this.waiters.clear();for(let n of t)n(e)}};function Ne(){let e=globalThis.crypto;if(!e||typeof e.getRandomValues!=`function`)throw Error(`WebCrypto getRandomValues is required for ECDSA rerandomization`);return e.getRandomValues(new Uint8Array(32))}function F(e){switch(e.authorization.kind){case`reusable_wallet_session`:return{authorization:e.authorization};case`operation_step_up`:{let t=e.operation;if(!t)throw Error(`Operation step-up pool fill requires exact operation preparation`);return{authorization:e.authorization,operation:t}}}}function Pe(e){return String(e&&typeof e==`object`&&`message`in e?e.message:e||`signature recovery failed`)}function I(e){e instanceof Uint8Array&&e.fill(0)}function Fe(e){if(e?.kind!==`router_ab_ecdsa_derivation_client_signing_material_source_v1`)throw Error(`Router A/B ECDSA derivation client signing material source is required`)}const Ie=6e4,L=new Map,R=new Map,z=new Map,B=new Map,V=new Map,H=new Map;function Le(e){return e===`triples_done`||e===`presign`||e===`done`}function Re(e){return Le(e.clientStage)&&Le(e.serverStage)?`presign`:`triples`}function ze(e){let t=L.get(e);if(!t?.length)return null;let n=t.shift()??null;return t.length?L.set(e,t):L.delete(e),n}async function U(e){return await Ue(e),ze(e.poolKey)}function Be(e,t,n){if(!K(n))return`invalid`;let r=L.get(e)||[];for(let e of r)if(e.materialHandle===n.materialHandle)return`duplicate`;return r.filter(e=>K(e)).length>=5?`capacity_full`:(r.push(n),L.set(e,r),R.set(e,t),`stored`)}function Ve(e,t=Date.now()){let n=L.get(e);if(!n?.length)return[];let r=[],i=[];for(let e of n)K(e,t)?r.push(e):i.push(e);return r.length>0?L.set(e,r):L.delete(e),i}async function He(e){for(let t of e.refs)await e.clientSigningMaterial.destroyClientPresignature({materialHandle:t.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}async function Ue(e){await He({refs:Ve(e.poolKey),poolIdentity:e.poolIdentity,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}async function W(e,t,n){try{await _(e.walletId,e.ownershipGeneration)}catch(r){throw await qe({poolIdentity:e,poolKey:g(e),clientSigningMaterial:t,workerCtx:n}),r}}async function We(e){await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx);let t=V.get(e.poolKey);if(t){await t;return}let n=Ge(e);V.set(e.poolKey,n);try{await n}finally{V.get(e.poolKey)===n&&V.delete(e.poolKey)}}async function Ge(e){await Ue(e);let t;t=await e.clientSigningMaterial.listAvailableClientPresignatures({poolIdentity:e.poolIdentity,workerCtx:e.workerCtx});try{await W(e.poolIdentity,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(e.poolKey)!==e.generation){for(let n of t)I(n.bigR33),await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{});return}for(let n of t){let t=Be(e.poolKey,e.poolIdentity,{presignatureId:n.presignatureId,materialHandle:n.materialHandle,bigRB64u:i(n.bigR33),createdAtMs:n.createdAtMs,expiresAtMs:n.expiresAtMs});I(n.bigR33),(t===`invalid`||t===`capacity_full`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:n.materialHandle,poolIdentity:e.poolIdentity,workerCtx:e.workerCtx}).catch(()=>{})}}function G(e){let t=L.get(e);return t?t.reduce((e,t)=>e+(K(t)?1:0),0):0}function K(e,t=Date.now()){let n=Math.floor(Number(e.expiresAtMs));return!!(e.presignatureId&&e.bigRB64u&&e.materialHandle)&&Number.isSafeInteger(n)&&n>t+2e3}function q(e){let t=H.get(e);return t===void 0?(H.set(e,0),0):t}function Ke(e){Z(e);let t=q(e)+1;return H.set(e,t),t}async function qe(e){let t=L.get(e.poolKey)??[];$e(e.poolKey),await He({...e,refs:t})}function J(e){return B.get(e)||0}function Je(e){let t=J(e);B.set(e,t+1)}function Ye(e){let t=J(e);if(t<=1){B.delete(e),Q(e,0);return}B.set(e,t-1)}async function Xe(e,t){let n=z.get(e);if(!n)return;let r=n.snapshot();for(;G(e)===0&&r.kind===`refilling`;)r=await n.waitForChange(r,t)}async function Ze(e){let t=g(v({ownershipGeneration:e.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.scope,materialActivation:e.materialActivation}));return G(t)>0?!0:(await Xe(t,`background`),G(t)>0)}function Y(e,t,n){return{scheduled:!1,reason:e,depth:t,targetDepth:n}}function Qe(){let e=new Set([...X.keys(),...L.keys(),...z.keys(),...B.keys(),...H.keys()]);for(let t of e)Ke(t);L.clear(),R.clear();for(let e of z.values())e.settle();z.clear(),B.clear()}function $e(e){L.delete(e),R.delete(e),Ke(e),z.get(e)?.settle(),z.delete(e)}function et(e){let t=String(e).trim();if(!t)throw Error(`ECDSA presignature wallet id is required`);for(let[e,n]of[...R])n.walletId===t&&$e(e)}const X=new Map;function Z(e){let t=X.get(e);t&&t.timer!==null&&clearTimeout(t.timer),X.delete(e),X.size===0&&typeof window<`u`&&(window.removeEventListener(`online`,$),document.removeEventListener(`visibilitychange`,$))}function Q(e,t){let n=X.get(e);if(!n)return;n.timer!==null&&clearTimeout(n.timer);let r=n.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs-Date.now();if(r<=0||q(e)!==n.generation){Z(e);return}n.timer=setTimeout(tt,Math.min(t,r),e)}function $(){if(!(typeof document<`u`&&document.visibilityState===`hidden`))for(let e of X.keys())Q(e,0)}function tt(e){let t=X.get(e);if(!t)return;if(t.timer=null,Date.now()>=t.input.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs){Z(e);return}if(typeof navigator<`u`&&navigator.onLine===!1){Q(e,3e4);return}let n=at(t.input);n.scheduled||Q(e,n.depth>=n.targetDepth?3e4:5e3)}function nt(e,t){t.authorization.kind===`reusable_wallet_session`&&X.get(e)?.input!==t&&(Z(e),X.size===0&&typeof window<`u`&&(window.addEventListener(`online`,$),document.addEventListener(`visibilitychange`,$)),X.set(e,{input:t,generation:q(e),failures:0,timer:null}),Q(e,3e4))}function rt(e,t,n){let r=X.get(e);if(!(!r||r!==t)){switch(n){case`network_error`:case`internal`:case`presign_timeout`:case`temporarily_unavailable`:case`service_unavailable`:case`wallet_session_unavailable`:if(r.failures+=1,r.failures<=3)return}Z(e)}}async function it(e){let{args:t,refillInput:n,poolKey:r,poolIdentity:i,scheduledGeneration:a,targetDepth:o,refillAttemptTimeoutMs:s,progress:c}=e,l=X.get(r)??null;try{for(await We({poolKey:r,poolIdentity:i,clientSigningMaterial:t.clientSigningMaterial,workerCtx:t.workerCtx,generation:a}),G(r)>0&&c.publishAvailable();Date.now()<t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs;){if(q(r)!==a||(X.get(r)??null)!==l||G(r)>=o||J(r)>0||typeof navigator<`u`&&navigator.onLine===!1)return;let e=Math.min(Date.now()+s,t.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs),i=await _t({...n,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:n.routerAbEcdsaDerivationPoolFill.scope,ceremonyExpiresAtMs:e,materialExpiresAtMs:n.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs},trafficClass:`background`});if(S(`evm-family`,{event:`ecdsa_background_refill_result`,authorization:t.authorization.kind,outcome:i.ok?`available`:`failed`,code:i.ok?null:i.code,depth:G(r),targetDepth:o}),!i.ok){rt(r,l,i.code);return}let u=X.get(r);u&&u===l&&(u.failures=0),c.publishAvailable()}}catch{rt(r,l,`internal`)}finally{c.settle(),z.get(r)===c&&z.delete(r);let e=X.get(r);if(e){let t=e.failures>0?2e3*2**e.failures:1e3;G(r)>=o&&(t=3e4),e!==l&&(t=0),Q(r,t)}}}function at(e){try{let t=_e(e.poolPolicy),n=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),r=g(n);R.set(r,n);let i=he(e.targetDepth,t.targetDepth),a=ge(e.triggerIfDepthAtOrBelow,t.lowWatermark,i),o=G(r),s=q(r);if(!t.enabled)return Y(`disabled`,o,i);if(e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs<=Date.now())return Z(r),Y(`invalid_args`,o,i);if(nt(r,e),o>a)return Y(`depth_above_trigger`,o,i);if(o>=i)return Y(`depth_at_or_above_target`,o,i);if(z.has(r)||J(r)>0)return Y(`in_flight_for_pool_key`,o,i);if(z.size>=t.maxRefillInFlight)return Y(`global_in_flight_limit`,o,i);let c={relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:e.ecdsaThresholdKeyId,clientVerifyingShareB64u:e.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)},l=new Me;return z.set(r,l),it({args:e,refillInput:c,poolKey:r,poolIdentity:n,scheduledGeneration:s,targetDepth:i,refillAttemptTimeoutMs:t.refillAttemptTimeoutMs,progress:l}),{scheduled:!0,reason:`scheduled`,depth:o,targetDepth:i}}catch{return Y(`invalid_args`,0,0)}}function ot(e){return e.map(e=>i(e))}function st(e){return Array.isArray(e)?e.map(e=>String(e||``).trim()).filter(e=>!!e).map(e=>a(e)):[]}async function ct(e){let t=String(e.thresholdEcdsaPublicKeyB64u||``).trim();if(t){let n=a(t);if(n.length!==33)throw Error(`thresholdEcdsaPublicKeyB64u must decode to 33 bytes`);return await M({publicKey33:n,workerCtx:e.workerCtx})}let n=String(e.clientVerifyingShareB64u||``).trim(),r=String(e.relayerVerifyingShareB64u||``).trim();if(!n||!r)throw Error(`Missing thresholdEcdsaPublicKeyB64u (or relayerVerifyingShareB64u fallback) for Router A/B ECDSA derivation signing`);let i=a(n),o=a(r);if(i.length!==33)throw Error(`clientVerifyingShareB64u must decode to 33 bytes`);if(o.length!==33)throw Error(`relayerVerifyingShareB64u must decode to 33 bytes`);return await de({left33:await M({publicKey33:i,workerCtx:e.workerCtx}),right33:await M({publicKey33:o,workerCtx:e.workerCtx}),workerCtx:e.workerCtx})}function lt(e){return e.trafficClass===`foreground`||z.get(e.poolKey)?.hasForegroundWaiters()?`foreground_presign_pool_refill`:`background_presign_pool_refill`}async function ut(e){for(let t=0;t<2;t+=1){let n=await dt(e);if(n.ok||!ft(n)||t===1)return n}return{ok:!1,code:`stale_session_state`,message:`Router A/B ECDSA derivation pool-fill session stayed stale after retry`}}async function dt(e){Fe(e.clientSigningMaterial);let t=performance.now(),n=e.routerAbEcdsaDerivationPoolFill.ceremonyExpiresAtMs,r=e.routerAbEcdsaDerivationPoolFill.materialExpiresAtMs,a=`ecdsa-presign-v2:${n}:${i(crypto.getRandomValues(new Uint8Array(32)))}`,o=a,s=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation}),c=null,l=null,u=null,d=null,ee=!1,f=`triples`,p=[],m=!0,h=!1;try{let t=await e.clientSigningMaterial.initClientPresignSession({sessionId:o,groupPublicKey33:e.groupPublicKey33,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,poolIdentity:s,workerCtx:e.workerCtx});if(t.stage!==`triples`||t.outgoingMessages.length!==1)return{ok:!1,code:`presign_init_failed`,message:`Client presign init must emit exactly one first message`};f=t.stage;let g=await ke({relayerUrl:e.relayerUrl,...e.poolFillInitKeySelector,count:1,presignSessionId:a,firstMessageB64u:i(t.outgoingMessages[0]),credential:e.credential,requestTag:lt(e),poolFill:e.routerAbEcdsaDerivationPoolFill,...F(e)});if(!g.ok)return{ok:!1,code:g.code||`presign_init_failed`,message:g.message||`Presign initialization failed`};if(g.presignSessionId!==a||g.ceremonyExpiresAtMs!==n||g.materialExpiresAtMs!==r||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Presign initialization changed the bound identity or deadlines`};let _=g.stage||`triples`,v=st(g.outgoingMessagesB64u);for(let t=0;t<64;t++){if(v.length>0&&!c){let t=await e.clientSigningMaterial.stepClientPresignSession({sessionId:o,stage:Re({clientStage:f,serverStage:_}),incomingMessages:v,workerCtx:e.workerCtx});f=t.stage,v=[],p.push(...t.outgoingMessages),t.presignatureHandle&&t.presignatureBigR33&&(c=t.presignatureHandle,l=t.presignatureBigR33)}if(!ee){let i=performance.now(),o=lt(e),s={relayerUrl:e.relayerUrl,presignSessionId:a,ceremonyExpiresAtMs:n,materialExpiresAtMs:r,stage:Re({clientStage:f,serverStage:_}),outgoingMessagesB64u:ot(p),credential:e.credential,requestTag:o,...F(e)},c=await je(s);if(S(`evm-family`,{event:`ecdsa_presignature_round`,requestTag:o,presignSessionId:a,authorization:e.authorization.kind,round:t,stage:s.stage,durationMs:performance.now()-i,outcome:c.ok?`succeeded`:`failed`}),p=[],!c.ok)return{ok:!1,code:c.code||`presign_step_failed`,message:c.message||`Router A/B ECDSA derivation pool-fill step failed`};v=st(c.outgoingMessagesB64u),_=c.stage||_,c.event===`presign_done`&&(u=String(c.presignatureId||``).trim()||null,d=String(c.bigRB64u||``).trim()||null,ee=!0)}if(c&&l&&u&&d)break}if(!c||!l)return{ok:!1,code:`presign_timeout`,message:`Client presign session did not reach done state`};if(!u||!d)return{ok:!1,code:`presign_timeout`,message:`Server presign session did not reach done state`};if(l.length!==33)return{ok:!1,code:`internal`,message:`Invalid local presignature bigR bytes (expected 33, got ${l.length})`};try{let t=Date.now(),n=i(l);if(n!==d)return{ok:!1,code:`presign_mismatch`,message:`Client/server presignature mismatch (bigR mismatch)`};let a=await e.clientSigningMaterial.admitClientPresignature({materialHandle:c,expectedPresignatureId:u,poolIdentity:s,admissionMode:e.authorization.kind===`operation_step_up`?`resident`:`durable`,workerCtx:e.workerCtx});return a.kind===`discarded_capacity`?{ok:!1,code:`pool_full`,message:`Router A/B ECDSA derivation client presignature pool is full`}:a.kind===`discarded_ambiguous`?{ok:!1,code:`presign_failed`,message:`Router A/B ECDSA derivation client presignature admission was ambiguous`}:(h=!0,m=!1,{ok:!0,kind:`available`,presignature:{presignatureId:u,bigRB64u:n,materialHandle:c,createdAtMs:t,expiresAtMs:r}})}finally{I(l)}}catch(e){return{ok:!1,code:`presign_failed`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation pool-fill handshake failed`)}}finally{S(`evm-family`,{event:`ecdsa_presignature_generation`,requestTag:lt(e),presignSessionId:a,authorization:e.authorization.kind,durationMs:performance.now()-t,outcome:h?`available`:`failed`}),I(l),!h&&c&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:c,poolIdentity:s,workerCtx:e.workerCtx}).catch(()=>{}),m&&await e.clientSigningMaterial.abortClientPresignSession({sessionId:o,workerCtx:e.workerCtx}).catch(()=>{})}}function ft(e){return e.code===`stale_session_state`||e.code===`stale_pool_fill_session`}function pt(e){let t=l(e);return{ecdsaThresholdKeyId:p(t.ecdsa_threshold_key_id),clientVerifyingShareB64u:h(t.public_identity.derivation_client_share_public_key33_b64u),thresholdEcdsaPublicKeyB64u:t.public_identity.threshold_public_key33_b64u}}function mt(e){let t=Math.floor(Number(e.materialExpiresAtMs)),n=Number.isSafeInteger(e.authorizationExpiresAtMs)?Math.floor(Number(e.authorizationExpiresAtMs)):e.nowMs+Ie,r=Math.min(t,n,e.nowMs+Ie);return Number.isSafeInteger(r)&&r>e.nowMs?r:null}async function ht(e,t,n){let r=null,c=null,l=null,u=null,d=null,p={kind:`unclaimed`},m=null,h={kind:`before_prepare`};try{let _=String(e.relayerUrl||``).trim().replace(/\/+$/g,``);if(!_)return{ok:!1,code:`invalid_args`,message:`Missing relayerUrl for Router A/B ECDSA derivation signing`};let y=pt(e.scope);if(!y.ecdsaThresholdKeyId)return{ok:!1,code:`invalid_args`,message:`Missing ecdsaThresholdKeyId for Router A/B ECDSA derivation signing`};let x=y.clientVerifyingShareB64u;if(!x)return{ok:!1,code:`invalid_args`,message:`Missing clientVerifyingShareB64u for Router A/B ECDSA derivation signing`};if(!(e.signingDigest32 instanceof Uint8Array)||e.signingDigest32.length!==32)return{ok:!1,code:`invalid_args`,message:`signingDigest32 must be 32 bytes for Router A/B ECDSA derivation signing`};let ne=performance.now(),C=await ct({clientVerifyingShareB64u:x,thresholdEcdsaPublicKeyB64u:y.thresholdEcdsaPublicKeyB64u,workerCtx:e.workerCtx});b(e.operationId,`public_key_validation`,ne),c=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:_,scope:e.scope,materialActivation:e.materialActivation}),await W(c,e.clientSigningMaterial,e.workerCtx),r=g(c),R.set(r,c),m=q(r);let re=performance.now();if(l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`pool_lookup`,re),!l){let t=performance.now();await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:m}),b(e.operationId,`pool_restore`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l){let t=performance.now();await Xe(r,`foreground`),b(e.operationId,`refill_wait`,t),m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx})}if(!l&&n.kind===`on_demand`){let t=performance.now();Je(r);try{let t=await _t({...n.refill,trafficClass:`foreground`});if(!t.ok&&t.code===`invalidated`&&(t=await _t({...n.refill,trafficClass:`foreground`})),!t.ok&&t.code!==`pool_full`)return t;!t.ok&&t.code===`pool_full`&&await We({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx,generation:q(r)})}finally{Ye(r)}m=q(r),l=await U({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),b(e.operationId,`foreground_refill`,t)}if(S(`evm-family`,{event:`ecdsa_presignature_selection`,operationId:e.operationId,authorization:e.authorization.kind,outcome:l?`available`:`empty`,remainingDepth:G(r),attempt:t}),!l)return{ok:!1,code:`pool_empty`,message:`Router A/B ECDSA derivation client presignature pool is empty`};let ie=Date.now(),ae=mt({authorizationExpiresAtMs:e.expiresAtMs,materialExpiresAtMs:l.expiresAtMs,nowMs:ie});if(!ae)return{ok:!1,code:`pool_entry_expired`,message:`Router A/B ECDSA derivation client presignature is expired`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};d=Ne();let w=await ee(d),T=s({scope:e.scope,requestId:o(`router-ab-ecdsa-sign`,32,`Router A/B ECDSA derivation sign request`),operationId:e.operationId,operationDigests:e.operationDigests,authorization:e.authorization,materialActivation:e.materialActivation,clientPresignatureId:l.presignatureId,expiresAtMs:ae,signingDigest32:e.signingDigest32,clientRerandomizationCommitment32:w});I(w);let E=o(`router-ab-ecdsa-reservation`,32,`Router A/B ECDSA Client presignature reservation`);p={kind:`destroy`};let oe=performance.now(),D=await e.clientSigningMaterial.reserveClientPresignature({materialHandle:l.materialHandle,expectedPresignatureId:l.presignatureId,poolIdentity:c,requestBinding:T.request_id,reservationId:E,leaseExpiresAtMs:T.expires_at_ms,workerCtx:e.workerCtx});if(b(e.operationId,`presignature_reserve`,oe),D.kind===`unavailable`)return D.reason===`claimed_elsewhere`&&(p={kind:`owned_elsewhere`}),t<4?await ht(e,t+1,n):{ok:!1,code:D.reason===`expired`?`pool_entry_expired`:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature is unavailable: ${D.reason}`};if(await W(c,e.clientSigningMaterial,e.workerCtx),m!==q(r))return{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`};Q(r,0),h={kind:`prepare_submitted`};let se=performance.now(),O=await ce({relayServerUrl:_,credential:e.credential,request:T,onServerTiming:te.bind(void 0,e.operationId,`prepare`)});if(b(e.operationId,`prepare`,se),O.kind===`reusable_wallet_session`){if(!e.reconcileSession)throw Error(`Wallet Session reconciliation is required`);await e.reconcileSession(O.sessionStatus)}let k=O.signing;if(k.server_big_r33_b64u!==l.bigRB64u)return{ok:!1,code:`presign_mismatch`,message:`Router A/B ECDSA derivation SigningWorker returned a different presignature bigR`};let A=performance.now();await e.clientSigningMaterial.commitClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,workerCtx:e.workerCtx}),b(e.operationId,`presignature_commit`,A);let j=a(l.bigRB64u),M=a(k.signing_worker_rerandomization_contribution32_b64u);try{if(j.length!==33)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation presign bigR must decode to 33 bytes`};if(M.length!==32)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation SigningWorker rerandomization contribution must decode to 32 bytes`};let t=performance.now();u=await e.clientSigningMaterial.computeSignatureShareFromPresignatureHandle({materialHandle:l.materialHandle,poolIdentity:c,requestBinding:T.request_id,reservationId:E,groupPublicKey33:C,expectedPresignBigR33:j,digest32:e.signingDigest32,clientRerandomizationContribution32:d,signingWorkerRerandomizationContribution32:M,workerCtx:e.workerCtx}),b(e.operationId,`client_share`,t),p={kind:`consumed`}}finally{I(j),I(M)}if(u.length!==32)return{ok:!1,code:`internal`,message:`Invalid Router A/B ECDSA derivation client signature share length (expected 32, got ${u.length})`};let de=f({scope:e.scope,requestId:T.request_id,operationId:T.operation_id,operationDigests:T.operation_digests,authorization:e.authorization,materialActivation:e.materialActivation,expiresAtMs:T.expires_at_ms,signingDigest32:e.signingDigest32,serverPresignatureId:k.server_presignature_id,clientSignatureShare32:u,clientRerandomizationContribution32:d}),fe=performance.now(),pe=await le({relayServerUrl:_,credential:e.credential,request:de,onServerTiming:te.bind(void 0,e.operationId,`finalize`)});b(e.operationId,`finalize`,fe);let N=a(pe.signature65_b64u);if(N.length!==65)return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned invalid signature length (expected 65, got ${N.length})`};try{let t=performance.now();await ue({digest32:e.signingDigest32,signature65:N,publicKey33:C,workerCtx:e.workerCtx}),b(e.operationId,`signature_verify`,t)}catch(e){return{ok:!1,code:`internal`,message:`Router A/B ECDSA derivation returned a signature that does not recover to the threshold group public key: ${Pe(e)}`}}return{ok:!0,signature65:N,signature65B64u:pe.signature65_b64u,rB64u:i(N.slice(0,32)),sB64u:i(N.slice(32,64)),recId:N[64]}}catch(t){if(t instanceof O||t instanceof k)throw t;let n=String(t&&typeof t==`object`&&`message`in t?t.message:t||`Router A/B ECDSA derivation signing failed`);return t instanceof j&&t.code===`expired_local_request`?{ok:!1,code:`pool_entry_expired`,message:n}:r&&c&&m!==null&&h.kind===`before_prepare`&&q(r)!==m?(await qe({poolKey:r,poolIdentity:c,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx}),{ok:!1,code:`pool_entry_unavailable`,message:`Router A/B ECDSA derivation client presignature pool was invalidated before prepare`}):{ok:!1,code:`router_ab_sign_failed`,message:n}}finally{if(I(u),I(d),l&&c&&p.kind!==`consumed`&&p.kind!==`owned_elsewhere`){let t=!1;if(p.kind===`unclaimed`&&r&&m!==null&&m===q(r)){let e=Be(r,c,l);t=e===`stored`||e===`duplicate`}t||await e.clientSigningMaterial.destroyClientPresignature({materialHandle:l.materialHandle,poolIdentity:c,workerCtx:e.workerCtx}).catch(()=>{})}r&&Q(r,0)}}async function gt(e){let t=pt(e.scope),n=Math.floor(Number(e.expiresAtMs));if(!Number.isSafeInteger(n)||n<=Date.now())return{ok:!1,code:`invalid_pool_fill_expiry`,message:`Router A/B ECDSA derivation pool fill expiry is unavailable or expired`};let r={kind:`on_demand`,refill:{relayerUrl:e.relayerUrl,keyHandle:e.keyHandle,ecdsaThresholdKeyId:t.ecdsaThresholdKeyId,clientVerifyingShareB64u:t.clientVerifyingShareB64u,clientSigningMaterial:e.clientSigningMaterial,thresholdEcdsaPublicKeyB64u:t.thresholdEcdsaPublicKeyB64u,credential:e.credential,materialActivation:e.materialActivation,routerAbEcdsaDerivationPoolFill:{kind:`router_ab_ecdsa_derivation_signing_worker_pool`,scope:e.scope,ceremonyExpiresAtMs:Math.min(n,Date.now()+d-3e4),materialExpiresAtMs:e.authorization.kind===`operation_step_up`?n:Date.now()+y},workerCtx:e.workerCtx,...F(e)}},i=await ht(e,0,r);return!i.ok&&(i.code===`pool_entry_expired`||i.code===`pool_entry_unavailable`)?await ht(e,0,r):i}async function _t(e){try{let t=v({ownershipGeneration:e.credential.ownershipGeneration,relayerUrl:e.relayerUrl,scope:e.routerAbEcdsaDerivationPoolFill.scope,materialActivation:e.materialActivation});await W(t,e.clientSigningMaterial,e.workerCtx);let n=g(t);await Ue({poolKey:n,poolIdentity:t,clientSigningMaterial:e.clientSigningMaterial,workerCtx:e.workerCtx});let r=q(n),i=await ct({clientVerifyingShareB64u:e.clientVerifyingShareB64u,thresholdEcdsaPublicKeyB64u:e.thresholdEcdsaPublicKeyB64u,relayerVerifyingShareB64u:e.relayerVerifyingShareB64u,workerCtx:e.workerCtx}),a=await ut({relayerUrl:e.relayerUrl,poolFillInitKeySelector:{keyHandle:m(e.keyHandle)},clientSigningMaterial:e.clientSigningMaterial,groupPublicKey33:i,materialActivation:e.materialActivation,credential:e.credential,poolKey:n,trafficClass:e.trafficClass,routerAbEcdsaDerivationPoolFill:e.routerAbEcdsaDerivationPoolFill,workerCtx:e.workerCtx,...F(e)});if(!a.ok)return a;try{await W(t,e.clientSigningMaterial,e.workerCtx)}catch{}if(q(n)!==r)return await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!1,code:`invalidated`,message:`Router A/B ECDSA derivation presignature pool invalidated`};let o=Be(n,t,a.presignature);return(o===`capacity_full`||o===`invalid`)&&await e.clientSigningMaterial.destroyClientPresignature({materialHandle:a.presignature.materialHandle,poolIdentity:t,workerCtx:e.workerCtx}).catch(()=>{}),{ok:!0,presignatureId:a.presignature.presignatureId}}catch(e){return{ok:!1,code:`internal`,message:String(e&&typeof e==`object`&&`message`in e?e.message:e||`Router A/B ECDSA derivation presignature refill failed`)}}}export{Ze as a,pe as c,gt as i,et as n,_e as o,at as r,me as s,Qe as t};
@@ -0,0 +1 @@
1
+ import{c as e,h as t,k as n}from"./chains-C_X_fNuS.js";import{A as r,D as i,j as a,k as o}from"./primitives-CqrjmIAH.js";import{i as s,r as c,t as l}from"./base64-DW79QA0h.js";import{n as u}from"./sessionPolicy-CBTZQe1n.js";import{d,h as f}from"./capabilityKinds-N8xo_IEh.js";import{$t as p,Qt as m,U as h,W as g,Z as _,ct as v,lt as y}from"./emailOtpEcdsaDerivationIdentity-p0C1CQva.js";import{t as b}from"./authenticatorOptions-C9aCKgeF.js";import{r as x,t as ee}from"./walletSessionAuthorizationStatus-BLyzJbU8.js";import{t as S}from"./authorizationAdmission-CGinGhXH.js";import{n as te}from"./walletSessionFailure-YuhraC3P.js";const C={enabled:!0,targetDepth:5,lowWatermark:4,maxRefillInFlight:1,refillAttemptTimeoutMs:3e4},ne={network:{chains:[{network:`near-testnet`,rpcUrl:`https://rpc.testnet.fastnear.com`,explorerUrl:`https://testnet.nearblocks.io`},{network:`tempo-testnet`,rpcUrl:`https://rpc.moderato.tempo.xyz`,explorerUrl:`https://explore.tempo.xyz`,chainId:42431},{network:`arc-testnet`,rpcUrl:`https://rpc.testnet.arc.io`,explorerUrl:`https://testnet.arcscan.app`,chainId:5042002},{network:`ethereum-sepolia`,rpcUrl:`https://ethereum-sepolia-rpc.publicnode.com`,explorerUrl:`https://sepolia.etherscan.io`,chainId:11155111}],relayer:{accountId:``,url:``,routes:{delegateAction:`/signed-delegate`}}},registration:{mode:`managed`,projectEnvironmentId:``,publishableKey:``,paymentMode:`disabled`,nearAccountProvisioning:{kind:`implicit_account`}},signing:{sessionDefaults:{ttlMs:u,remainingUses:3},emailOtp:{authPolicy:`session`},sessionPersistenceMode:`none`,sessionSeal:{mode:`none`},routerAb:{normalSigning:{mode:`disabled`}},routerAbEcdsaDerivation:{presignaturePool:C},thresholdEcdsa:{provisioningDefaults:{tempo:{enabled:!0,signingSession:{kind:`jwt`,ttlMs:u,remainingUses:3}},evm:{enabled:!0,signingSession:{kind:`jwt`,ttlMs:u,remainingUses:3}}}}},wallet:{mode:`iframe`,iframe:{origin:`https://wallet.example.localhost`,servicePath:`/wallet-service`,sdkBasePath:`/sdk`,walletHostVariant:`runtime`,rpIdOverride:`example.localhost`}},webauthn:{authenticatorOptions:{userVerification:b.Preferred,originPolicy:{single:void 0,all_subdomains:!0,multiple:void 0}}},ui:{appearance:{theme:{id:`default`,mode:`dark`,colors:{}},palette:`default`}}};async function re(e,t){let r=n(t,`ECDSA prepare response`);if(r.kind!==e.authorization.kind)throw Error(`ECDSA prepare authorization kind does not match the request`);let i=await h(e,r.signing);if(e.authorization.kind===`operation_step_up`){if(Object.keys(r).some(w))throw Error(`Invalid step-up prepare response`);return{kind:`operation_step_up`,signing:i}}if(Object.keys(r).some(ie))throw Error(`Invalid Wallet Session prepare response`);let a=n(r.session_status,`ECDSA prepare session status`),o=d(a.quotaId),s=f(e.authorization.wallet_session_id);if(!o.ok||!s.ok)throw Error(`Invalid prepare session identity`);let c=x(a,{walletSessionId:s.value,quotaId:o.value});if(!c||c.status!==`active`||c.authorization.walletId!==e.scope.wallet_id)throw Error(`ECDSA prepare did not return the admitted Wallet Session`);return{kind:`reusable_wallet_session`,signing:i,sessionStatus:c}}function w(e){return e!==`kind`&&e!==`signing`}function ie(e){return w(e)&&e!==`session_status`}var T=class extends Error{constructor(e){super(`Router A/B signing ${e.path} returned HTTP ${e.status}: ${e.message||e.code}`),this.name=`RouterAbSigningRequestError`,this.code=e.code,this.path=e.path,this.status=e.status}};function ae(e){let t=String(e.code||``).trim(),n=`Router A/B signing ${e.path} returned HTTP ${e.status}: ${e.message||t||`unknown admission failure`}`;if(e.authorizationDecision?.kind===`step_up_required`)return new S({kind:`exhausted`,source:`server_prepare`,detail:n},e.authorizationDecision);switch(t){case`wallet_budget_exhausted`:return new S({kind:`exhausted`,source:`server_prepare`,detail:n},e.authorizationDecision);case`wallet_budget_in_flight`:case`wallet_budget_reserved`:return new S({kind:`in_flight`,source:`server_prepare`,detail:n,retryAfterMs:150});default:return null}}function E(e,t){let n=Math.floor(Number(e));if(!Number.isSafeInteger(n)||n<=0)throw Error(`${t} must be a positive integer`);return n}function D(e,t,n){if(!Array.isArray(e))throw Error(`${t} must be a byte array`);let r=e.map(e=>Number(e));if(!r.every(e=>Number.isInteger(e)&&e>=0&&e<=255))throw Error(`${t} must contain bytes`);if(n!==void 0&&r.length!==n)throw Error(`${t} must contain ${n} bytes`);return r}function O(e,n){let r=t(e,n);if(c(r).length!==32)throw Error(`${n} must decode to 32 bytes`);return r}function k(e,n){let r=t(e,n);if(c(r).length===0)throw Error(`${n} must decode to non-empty bytes`);return r}function A(e,n){let r=t(e,n),i;try{i=l(r)}catch{i=c(r)}if(i.length!==32)throw Error(`${n} must decode to 32 bytes`);return s(i)}function j(e){return{bytes:[...D([...e],`digest bytes`,32)]}}function M(e,t){return s(Uint8Array.from(D(e.bytes,t)))}async function oe(t){return s(await Q(new TextEncoder().encode(e(t))))}function se(e){let n=t(e.message,`nep413.message`),r=t(e.recipient,`nep413.recipient`),i=c(A(e.nonce,`nep413.nonce`)),a=e.callbackUrl==null?void 0:t(e.callbackUrl,`callbackUrl`),o=[];return Z(o,2147484061),q(o,n),Y(o,i),q(o,r),a?(o.push(1),q(o,a)):o.push(0),s(Uint8Array.from(o))}async function ce(e){let n={scope:I(e.scope,`scope`),expires_at_ms:E(e.expiresAtMs,`expiresAtMs`),display_digest:j(c(O(e.displayDigestB64u,`displayDigestB64u`))),intent:{kind:`near_transaction_v1`,operation_id:t(e.operationId,`operationId`),operation_fingerprint:t(e.operationFingerprint,`operationFingerprint`),near_account_id:t(e.nearAccountId,`nearAccountId`),near_network_id:e.nearNetworkId,transactions:e.transactions.map((e,n)=>({receiver_id:t(e.receiverId,`transactions[${n}].receiverId`),action_fingerprint:t(e.actionFingerprint,`transactions[${n}].actionFingerprint`)})),unsigned_transaction_borsh_b64u:k(e.unsignedTransactionBorshB64u,`unsignedTransactionBorshB64u`)},signing_payload:{kind:`near_unsigned_transaction_borsh_v1`,unsigned_transaction_borsh_b64u:k(e.unsignedTransactionBorshB64u,`unsignedTransactionBorshB64u`),expected_signing_digest_b64u:O(e.expectedSigningDigestB64u,`expectedSigningDigestB64u`)}};return{request:n,admissionMaterial:await P(n)}}async function le(e){let n=A(e.nonce,`nonce`),r=e.callbackUrl==null?void 0:t(e.callbackUrl,`callbackUrl`),i=se({message:e.message,recipient:e.recipient,nonce:n,...r?{callbackUrl:r}:{}}),a={scope:I(e.scope,`scope`),expires_at_ms:E(e.expiresAtMs,`expiresAtMs`),display_digest:j(c(O(e.displayDigestB64u,`displayDigestB64u`))),intent:{kind:`nep413_v1`,operation_id:t(e.operationId,`operationId`),operation_fingerprint:t(e.operationFingerprint,`operationFingerprint`),near_account_id:t(e.nearAccountId,`nearAccountId`),near_network_id:e.nearNetworkId,recipient:t(e.recipient,`recipient`),message:t(e.message,`message`),nonce_b64u:n,...r?{callback_url:r}:{}},signing_payload:{kind:`nep413_message_v1`,canonical_message_b64u:i,expected_signing_digest_b64u:O(e.expectedSigningDigestB64u,`expectedSigningDigestB64u`)}};return{request:a,admissionMaterial:await P(a)}}async function ue(e){let n=k(e.delegate.canonicalDelegateBorshB64u,`canonicalDelegateBorshB64u`),r={scope:I(e.scope,`scope`),expires_at_ms:E(e.expiresAtMs,`expiresAtMs`),display_digest:j(c(O(e.displayDigestB64u,`displayDigestB64u`))),intent:{kind:`near_delegate_action_v1`,operation_id:t(e.operationId,`operationId`),operation_fingerprint:t(e.operationFingerprint,`operationFingerprint`),near_account_id:t(e.nearAccountId,`nearAccountId`),near_network_id:e.nearNetworkId,delegate:{sender_id:t(e.delegate.senderId,`delegate.senderId`),receiver_id:t(e.delegate.receiverId,`delegate.receiverId`),public_key:t(e.delegate.publicKey,`delegate.publicKey`),nonce:t(e.delegate.nonce,`delegate.nonce`),max_block_height:t(e.delegate.maxBlockHeight,`delegate.maxBlockHeight`),action_fingerprint:t(e.delegate.actionFingerprint,`delegate.actionFingerprint`),canonical_delegate_borsh_b64u:n}},signing_payload:{kind:`near_delegate_action_v1`,canonical_delegate_borsh_b64u:n,expected_signing_digest_b64u:O(e.expectedSigningDigestB64u,`expectedSigningDigestB64u`)}};return{request:r,admissionMaterial:await P(r)}}function N(e){let n=I(e.scope,`scope`),r={scope:n,expires_at_ms:E(e.expiresAtMs,`expiresAtMs`),prepare_binding:{server_round1_handle:t(e.prepareResponse.server_round1_handle,`server_round1_handle`),round1_binding_digest:L(e.prepareResponse.round1_binding_digest,`round1_binding_digest`),intent_digest:L(e.admissionMaterial.intentDigest,`intent_digest`),signing_payload_digest:L(e.admissionMaterial.signingPayloadDigest,`signing_payload_digest`)},protocol:{kind:`ed25519_two_party_frost_finalize_v1`,client_commitments:z(e.clientCommitments,`clientCommitments`),server_commitments:z(e.prepareResponse.server_commitments,`serverCommitments`),client_verifying_share_b64u:t(e.clientVerifyingShareB64u,`clientVerifyingShareB64u`),server_verifying_share_b64u:t(e.prepareResponse.server_verifying_share_b64u,`serverVerifyingShareB64u`),client_signature_share_b64u:t(e.clientSignatureShareB64u,`clientSignatureShareB64u`)}};if(n.authorization.kind===`reusable_wallet_session`&&e.prepareResponse.scope.authorization.kind===`reusable_wallet_session`)return{...r,scope:{...n,authorization:n.authorization},authorized_operation:V(e.prepareResponse.authorized_operation,`authorized_operation`)};if(n.authorization.kind===`operation_step_up`&&e.prepareResponse.scope.authorization.kind===`operation_step_up`)return{...r,scope:{...n,authorization:n.authorization},authorized_operation:H(e.prepareResponse.authorized_operation,`authorized_operation`)};throw Error(`Router A/B normal-signing authorization changed after prepare`)}async function P(e){let t=j(await Q(Se(e.intent))),n=j(await Q(Ce(e.signing_payload))),r=j(await Q(we(e.signing_payload))),i=c(Te(e.signing_payload));if(!De(r.bytes,i))throw Error(`Router A/B normal-signing expected signing digest drift`);return{intentDigest:t,signingPayloadDigest:n,admittedSigningDigest:r}}function F(e,t,n){let r=Object.keys(e).sort(),i=[...t].sort();if(r.length!==i.length||r.some((e,t)=>e!==i[t]))throw Error(`${n} has invalid fields`)}function I(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);F(r,[`request_id`,`account_id`,`authorization`,`material_activation`,`signing_worker_id`],n);let i={request_id:t(r.request_id,`${n}.request_id`),account_id:t(r.account_id,`${n}.account_id`),authorization:p(r.authorization),material_activation:m(r.material_activation),signing_worker_id:t(r.signing_worker_id,`${n}.signing_worker_id`)};if(i.material_activation.signing_worker!==i.signing_worker_id)throw Error(`${n} material activation SigningWorker mismatch`);return i}function L(e,t){let n=e&&typeof e==`object`?e:null;if(!n)throw Error(`${t} must be an object`);return{bytes:D(n.bytes,`${t}.bytes`,32)}}function R(e,t){let n=e&&typeof e==`object`?e:null;if(!n)throw Error(`${t} must be an object`);let r=D(n.bytes,`${t}.bytes`);if(r.length===0)throw Error(`${t}.bytes must be non-empty`);return{bytes:r}}function z(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);return{hiding:t(r.hiding,`${n}.hiding`),binding:t(r.binding,`${n}.binding`)}}function B(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);return{server_id:t(r.server_id,`${n}.server_id`),key_epoch:t(r.key_epoch,`${n}.key_epoch`),recipient_encryption_key:t(r.recipient_encryption_key,`${n}.recipient_encryption_key`)}}function V(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);F(r,[`kind`,`authorized_operation_id`,`operation_id`,`capability_kind`,`operation_kind`,`lane_digest_b64u`,`intent_digest_b64u`,`display_digest_b64u`,`operation_fingerprint_digest`],n);let i=t(r.kind,`${n}.kind`);if(i!==`reusable_wallet_session_authorized_operation_v1`)throw Error(`${n}.kind is invalid`);let a=t(r.capability_kind,`${n}.capability_kind`);if(a!==`near_ed25519_mpc_signing`)throw Error(`${n}.capability_kind is invalid`);let o=t(r.operation_kind,`${n}.operation_kind`);if(o!==`near.sign_transaction`&&o!==`near.sign_delegate_action`&&o!==`near.sign_nep413_message`)throw Error(`${n}.operation_kind is invalid`);return{kind:i,authorized_operation_id:t(r.authorized_operation_id,`${n}.authorized_operation_id`),operation_id:t(r.operation_id,`${n}.operation_id`),capability_kind:a,operation_kind:o,lane_digest_b64u:O(r.lane_digest_b64u,`${n}.lane_digest_b64u`),intent_digest_b64u:O(r.intent_digest_b64u,`${n}.intent_digest_b64u`),display_digest_b64u:O(r.display_digest_b64u,`${n}.display_digest_b64u`),operation_fingerprint_digest:O(r.operation_fingerprint_digest,`${n}.operation_fingerprint_digest`)}}function H(e,n){let r=e&&typeof e==`object`?e:null;if(!r)throw Error(`${n} must be an object`);if(F(r,[`kind`,`authorization_session_id`,`evidence_set_digest`,`authorized_operation_id`,`operation_id`,`capability_kind`,`operation_kind`,`lane_digest_b64u`,`intent_digest_b64u`,`display_digest_b64u`,`operation_fingerprint_digest`],n),t(r.kind,`${n}.kind`)!==`verified_step_up_authorized_operation_v1`)throw Error(`${n}.kind is invalid`);if(t(r.capability_kind,`${n}.capability_kind`)!==`near_ed25519_mpc_signing`)throw Error(`${n}.capability_kind is invalid`);let i=t(r.operation_kind,`${n}.operation_kind`);if(i!==`near.sign_transaction`&&i!==`near.sign_delegate_action`&&i!==`near.sign_nep413_message`)throw Error(`${n}.operation_kind is invalid`);return{kind:`verified_step_up_authorized_operation_v1`,authorization_session_id:t(r.authorization_session_id,`${n}.authorization_session_id`),evidence_set_digest:O(r.evidence_set_digest,`${n}.evidence_set_digest`),authorized_operation_id:t(r.authorized_operation_id,`${n}.authorized_operation_id`),operation_id:t(r.operation_id,`${n}.operation_id`),capability_kind:`near_ed25519_mpc_signing`,operation_kind:i,lane_digest_b64u:O(r.lane_digest_b64u,`${n}.lane_digest_b64u`),intent_digest_b64u:O(r.intent_digest_b64u,`${n}.intent_digest_b64u`),display_digest_b64u:O(r.display_digest_b64u,`${n}.display_digest_b64u`),operation_fingerprint_digest:O(r.operation_fingerprint_digest,`${n}.operation_fingerprint_digest`)}}function U(e){let n=e&&typeof e==`object`?e:null;if(!n)throw Error(`Router A/B normal-signing prepare response must be an object`);let r=t(n.signature_scheme,`signature_scheme`);if(r!==`ed25519_v1`)throw Error(`Unsupported Router A/B normal-signing signature scheme: ${r}`);let i=I(n.scope,`scope`),a={scope:i,signing_payload_digest:L(n.signing_payload_digest,`signing_payload_digest`),round1_binding_digest:L(n.round1_binding_digest,`round1_binding_digest`),signing_worker:B(n.signing_worker,`signing_worker`),server_round1_handle:t(n.server_round1_handle,`server_round1_handle`),server_commitments:z(n.server_commitments,`server_commitments`),server_verifying_share_b64u:t(n.server_verifying_share_b64u,`server_verifying_share_b64u`),signature_scheme:`ed25519_v1`,prepared_at_ms:E(n.prepared_at_ms,`prepared_at_ms`),expires_at_ms:E(n.expires_at_ms,`expires_at_ms`)};switch(i.authorization.kind){case`reusable_wallet_session`:return F(n,[`scope`,`signing_payload_digest`,`round1_binding_digest`,`signing_worker`,`server_round1_handle`,`server_commitments`,`server_verifying_share_b64u`,`signature_scheme`,`prepared_at_ms`,`expires_at_ms`,`authorized_operation`],`Router A/B reusable Wallet Session prepare response`),{...a,scope:{...i,authorization:i.authorization},authorized_operation:V(n.authorized_operation,`authorized_operation`)};case`operation_step_up`:return F(n,[`scope`,`signing_payload_digest`,`round1_binding_digest`,`signing_worker`,`server_round1_handle`,`server_commitments`,`server_verifying_share_b64u`,`signature_scheme`,`prepared_at_ms`,`expires_at_ms`,`authorized_operation`],`Router A/B operation step-up prepare response`),{...a,scope:{...i,authorization:i.authorization},authorized_operation:H(n.authorized_operation,`authorized_operation`)}}}function de(e){let n=e&&typeof e==`object`?e:null;if(!n)throw Error(`Router A/B normal-signing response must be an object`);F(n,[`scope`,`signing_payload_digest`,`signing_worker`,`signature_scheme`,`signature`,`signed_at_ms`],`Router A/B normal-signing response`);let r=t(n.signature_scheme,`signature_scheme`);if(r!==`ed25519_v1`)throw Error(`Unsupported Router A/B normal-signing signature scheme: ${r}`);return{scope:I(n.scope,`scope`),signing_payload_digest:L(n.signing_payload_digest,`signing_payload_digest`),signing_worker:B(n.signing_worker,`signing_worker`),signature_scheme:`ed25519_v1`,signature:R(n.signature,`signature`),signed_at_ms:E(n.signed_at_ms,`signed_at_ms`)}}function fe(e){let t=e.credential.kind===`wallet_session_opaque`?{token:e.credential.walletSessionToken,home:e.credential.home}:null;return i({...t?{headers:o(t)}:{},body:e.body})}function pe(e){if(!e.trim())return null;try{let t=JSON.parse(e),n=t&&typeof t==`object`?t:null;if(!n)return null;let r=String(n.code||``).trim(),i=String(n.message||``).trim();if(!r)return null;let a=n.authorization_decision===void 0?void 0:me(n.authorization_decision);return{code:r,message:i,...a?{authorizationDecision:a}:{}}}catch{return null}}function me(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Router A/B owner-operation authorization decision is invalid`);let t=e,n=t.kind;if(n===`step_up_required`){W(t,[`kind`,`reason`,`step_up`],`owner-operation step-up decision`);let e=t.reason;if(e!==`wallet_session_missing`&&e!==`wallet_session_expired`&&e!==`wallet_session_exhausted`&&e!==`wallet_session_ended`&&e!==`wallet_session_superseded`)throw Error(`owner-operation step-up decision reason is invalid`);let r=t.step_up;return r&&typeof r==`object`&&!Array.isArray(r)&&`operation_digests`in r?{kind:n,reason:e,step_up:_(r)}:{kind:n,reason:e,step_up:he(r)}}if(n===`denied`){if(W(t,[`kind`,`denial`],`owner-operation denial decision`),!t.denial||typeof t.denial!=`object`||Array.isArray(t.denial))throw Error(`owner-operation denial is invalid`);let e=t.denial;W(e,[`code`,`message`],`owner-operation denial`);let r=e.code;if(r!==`invalid_identity`&&r!==`invalid_authority`&&r!==`invalid_operation`&&r!==`inactive_material`&&r!==`replayed_step_up`&&r!==`authorization_unavailable`)throw Error(`owner-operation denial code is invalid`);if(typeof e.message!=`string`||e.message.trim()!==e.message)throw Error(`owner-operation denial message is invalid`);return{kind:n,denial:{code:r,message:e.message}}}if(n===`authorized`){if(W(t,[`kind`,`operation`,`source`],`owner-operation decision`),!t.operation||typeof t.operation!=`object`||Array.isArray(t.operation))throw Error(`owner-operation authorized operation is invalid`);let e=t.operation;if(W(e,[`kind`,`operation_id`,`authorized_operation_id`,`operation_fingerprint_digest`],`owner-operation authorized operation`),e.kind!==`authorized_operation`||typeof e.operation_id!=`string`||typeof e.authorized_operation_id!=`string`||typeof e.operation_fingerprint_digest!=`string`)throw Error(`owner-operation authorized operation is invalid`);if(!t.source||typeof t.source!=`object`||Array.isArray(t.source))throw Error(`owner-operation authorized source is invalid`);let r=t.source;if(W(r,[`kind`,`wallet_session_id`,`quota_id`],`owner-operation authorized source`),r.kind!==`reusable_wallet_session`||typeof r.wallet_session_id!=`string`||typeof r.quota_id!=`string`)throw Error(`owner-operation authorized source is invalid`);return{kind:n,operation:{kind:`authorized_operation`,operation_id:e.operation_id,authorized_operation_id:e.authorized_operation_id,operation_fingerprint_digest:e.operation_fingerprint_digest},source:{kind:`reusable_wallet_session`,wallet_session_id:r.wallet_session_id,quota_id:r.quota_id}}}throw Error(`owner-operation authorization decision kind is invalid`)}function he(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Ed25519 operation step-up preparation is invalid`);let t=e;W(t,[`wallet_id`,`operation_kind`,`operation_id`,`request_id`,`account_id`,`material_activation`,`signing_worker_id`,`near_account_id`,`signer_slot`,`participant_ids`,`expires_at_ms`],`Ed25519 owner-operation step-up preparation`);let n=t.operation_kind;if(n!==`near.sign_transaction`&&n!==`near.sign_delegate_action`&&n!==`near.sign_nep413_message`)throw Error(`Ed25519 operation step-up kind is invalid`);if(typeof t.wallet_id!=`string`||typeof t.operation_id!=`string`||typeof t.request_id!=`string`||typeof t.account_id!=`string`||typeof t.signing_worker_id!=`string`||typeof t.near_account_id!=`string`||!Number.isSafeInteger(t.signer_slot)||!Number.isSafeInteger(t.expires_at_ms)||!Array.isArray(t.participant_ids)||t.participant_ids.length!==2||!t.participant_ids.every(e=>Number.isSafeInteger(e)&&Number(e)>0))throw Error(`Ed25519 operation step-up preparation fields are invalid`);let[r,i]=t.participant_ids,a=t.signer_slot,o=t.expires_at_ms;if(typeof r!=`number`||typeof i!=`number`||typeof a!=`number`||typeof o!=`number`)throw Error(`Ed25519 operation step-up participants are invalid`);return{wallet_id:t.wallet_id,operation_kind:n,operation_id:t.operation_id,request_id:t.request_id,account_id:t.account_id,material_activation:m(t.material_activation),signing_worker_id:t.signing_worker_id,near_account_id:t.near_account_id,signer_slot:a,participant_ids:[r,i],expires_at_ms:o}}function W(e,t,n){let r=new Set(t);for(let t of Object.keys(e))if(!r.has(t))throw Error(`${n} contains unsupported field ${t}`);for(let r of t)if(!Object.hasOwn(e,r))throw Error(`${n} is missing ${r}`)}function ge(e){let t=pe(e.bodyText);return t?ae({code:t.code,message:t.message,path:e.path,status:e.status,authorizationDecision:t.authorizationDecision})||te({code:t.code,message:`Router A/B signing ${e.path} returned HTTP ${e.status}: ${t.message}`})||new T({code:t.code,message:t.message,path:e.path,status:e.status}):Error(`Router A/B signing ${e.path} returned HTTP ${e.status}${e.bodyText?`: ${e.bodyText}`:``}`)}async function G(e){if(typeof fetch!=`function`)throw Error(`fetch is not available for Router A/B normal-signing request`);let n=a(t(e.relayServerUrl,`relayServerUrl`)),i=await r(new Request(`${n}${e.path}`,{...fe({credential:e.credential,body:e.body}),signal:e.signal}));try{e.onServerTiming?.(i.headers.get(`Server-Timing`))}catch{}if(!i.ok){let t=await i.text().catch(()=>``),n=ge({path:e.path,status:i.status,bodyText:t});throw e.credential.kind===`wallet_session_opaque`&&n instanceof S&&n.failure.kind===`exhausted`&&ee.forgetCredential(e.credential.walletSessionToken),n}return e.parse(await i.json())}function _e(e,t){let r=n(t,`Ed25519 prepare response`);if(r.kind!==e.scope.authorization.kind)throw Error(`Ed25519 prepare authorization kind does not match the request`);let i=U(r.signing);if(e.scope.authorization.kind===`operation_step_up`)return W(r,[`kind`,`signing`],`Ed25519 step-up prepare response`),{kind:`operation_step_up`,signing:i};W(r,[`kind`,`signing`,`session_status`],`Ed25519 session prepare response`);let a=n(r.session_status,`Ed25519 prepare session status`),o=f(e.scope.authorization.wallet_session_id),s=d(a.quotaId);if(!o.ok||!s.ok)throw Error(`Invalid Ed25519 prepare session identity`);let c=x(a,{walletSessionId:o.value,quotaId:s.value});if(!c||c.status!==`active`)throw Error(`Ed25519 prepare did not return an active Wallet Session`);return{kind:`reusable_wallet_session`,signing:i,sessionStatus:c}}async function ve(e){return G({relayServerUrl:e.relayServerUrl,path:`/router-ab/ed25519/sign/prepare`,credential:e.credential,body:e.request,parse:_e.bind(null,e.request)})}async function ye(e){return await y(e.request),G({relayServerUrl:e.relayServerUrl,path:`/router-ab/ecdsa-derivation/sign/prepare`,onServerTiming:e.onServerTiming,credential:e.credential,body:e.request,parse:re.bind(null,e.request)})}async function be(e){return G({relayServerUrl:e.relayServerUrl,path:`/router-ab/ed25519/sign`,credential:e.credential,body:e.request,parse:de})}async function xe(e){return await v(e.request),G({relayServerUrl:e.relayServerUrl,path:`/router-ab/ecdsa-derivation/sign`,onServerTiming:e.onServerTiming,credential:e.credential,body:e.request,parse:t=>g(e.request,t)})}function Se(e){let t=[];switch(J(t,$(`router-ab-protocol/ed25519-normal-signing/intent/v2`)),e.kind){case`near_transaction_v1`:J(t,$(`near_transaction_v1`)),K(t,e),X(t,e.transactions.length);for(let n of e.transactions)J(t,$(n.receiver_id)),J(t,$(n.action_fingerprint));return J(t,$(e.unsigned_transaction_borsh_b64u)),Uint8Array.from(t);case`nep413_v1`:return J(t,$(`nep413_v1`)),K(t,e),J(t,$(e.recipient)),J(t,$(e.message)),J(t,$(e.nonce_b64u)),Ee(t,e.callback_url),Uint8Array.from(t);case`near_delegate_action_v1`:return J(t,$(`near_delegate_action_v1`)),K(t,e),J(t,$(e.delegate.sender_id)),J(t,$(e.delegate.receiver_id)),J(t,$(e.delegate.public_key)),J(t,$(e.delegate.nonce)),J(t,$(e.delegate.max_block_height)),J(t,$(e.delegate.action_fingerprint)),J(t,$(e.delegate.canonical_delegate_borsh_b64u)),Uint8Array.from(t)}}function Ce(e){let t=[];switch(J(t,$(`router-ab-protocol/ed25519-normal-signing/payload/v2`)),e.kind){case`near_unsigned_transaction_borsh_v1`:return J(t,$(`near_unsigned_transaction_borsh_v1`)),J(t,$(e.unsigned_transaction_borsh_b64u)),J(t,$(e.expected_signing_digest_b64u)),Uint8Array.from(t);case`nep413_message_v1`:return J(t,$(`nep413_message_v1`)),J(t,$(e.canonical_message_b64u)),J(t,$(e.expected_signing_digest_b64u)),Uint8Array.from(t);case`near_delegate_action_v1`:return J(t,$(`near_delegate_action_v1`)),J(t,$(e.canonical_delegate_borsh_b64u)),J(t,$(e.expected_signing_digest_b64u)),Uint8Array.from(t)}}function we(e){switch(e.kind){case`near_unsigned_transaction_borsh_v1`:return c(e.unsigned_transaction_borsh_b64u);case`nep413_message_v1`:return c(e.canonical_message_b64u);case`near_delegate_action_v1`:return c(e.canonical_delegate_borsh_b64u)}}function Te(e){switch(e.kind){case`near_unsigned_transaction_borsh_v1`:case`nep413_message_v1`:case`near_delegate_action_v1`:return e.expected_signing_digest_b64u}}function K(e,t){J(e,$(t.operation_id)),J(e,$(t.operation_fingerprint)),J(e,$(t.near_account_id)),J(e,$(t.near_network_id))}function Ee(e,t){t?(e.push(1),J(e,$(t))):e.push(0)}function q(e,t){let n=$(t);Z(e,n.length),Y(e,n)}function J(e,t){X(e,t.length),Y(e,t)}function Y(e,t){for(let n of t)e.push(n)}function X(e,t){e.push(t>>>24&255,t>>>16&255,t>>>8&255,t&255)}function Z(e,t){e.push(t&255,t>>>8&255,t>>>16&255,t>>>24&255)}async function Q(e){let t=globalThis.crypto?.subtle;if(!t)throw Error(`Web Crypto SHA-256 is unavailable for Router A/B normal signing`);let n=new Uint8Array(e.length);return n.set(e),new Uint8Array(await t.digest(`SHA-256`,n.buffer))}function $(e){return new TextEncoder().encode(e)}function De(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}export{N as a,ye as c,oe as d,C as f,le as i,ve as l,ue as n,xe as o,ne as p,ce as r,be as s,T as t,M as u};