@nexus-cross/crossx-sdk-core 2.3.0-beta.4 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,7 +3,7 @@ var CROSSx=function(Z){"use strict";var sc=Object.defineProperty;var nc=(Z,h,f)=
3
3
 
4
4
  보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},fr={confirm:"Confirm",cancel:"Cancel",close:"Close",signature_requesting:" is requesting a Signature",signature_warning:"After you sign, changes or cancellations are not possible.",signature_sign_button:"Sign",sign_message_title:"Sign Message",sign_typed_data_title:"Sign Data",sign_transaction_title:"Sign Transaction",send_transaction_title:"Send Transaction",send_tx_permission_text:" wants your permission to approve the following transaction.",send_tx_approve_button:"Approve",send_tx_confirm_button:"Confirm",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",tx_progress_waiting_title:"Waiting for confirmation",tx_progress_waiting_text:"Waiting for transaction receipt...",tx_complete_done_button:"All Done",label_to:"To",label_from:"From",label_network:"Network",label_value:"Value",label_estimated_fee:"Estimated fee",label_est_tx_fee:"Est. Tx Fee",label_max_priority_fee:"Max Priority Fee",label_max_gas_fee:"Max Gas Fee",label_gas_price:"Gas Price",label_gas_limit:"Gas Limit",label_transfer:"Transfer",label_tx_fee:"Tx Fee",label_tx_hash:"Tx Hash",label_total:"Total",label_including_fees:"(including fees)",label_primary_type:"Primary Type",login_selector_title:"CROSS Wallet",login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Connected Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",wallet_created_title:"Wallet Created!",wallet_created_button:"Got it",pin_notice_header_subtitle:"Required for transactions, PK/mnemonic export & account deletion.",pin_notice_title:"PIN Setup Notice",pin_notice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pin_notice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pin_notice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pin_notice_next_button:"I Understand",pin_notice_submit_button:"I Understand",pin_setup_title:"Create PIN",pin_setup_header_subtitle:"This PIN is used to authorize your transactions.",pin_setup_subtitle:"Set a 6-digit PIN to authorize transactions.",pin_setup_confirm_title:"Confirm PIN",pin_setup_confirm_subtitle:"Confirm your 6-digit PIN",pin_setup_mismatch_error:"PINs do not match. Please try again.",pin_validation_too_short:"Please enter a 6-digit PIN.",pin_validation_numbers_only:"Only numbers (0-9) are allowed.",pin_validation_repeating_digit:"Cannot use the same number 3+ times in a row.",pin_validation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pin_validation_alternating_pattern:"Repeating patterns (e.g., 121212) are not allowed.",pin_input_title:"Enter PIN",pin_input_subtitle:"Enter your 6-digit PIN to continue.",pin_input_error:"Incorrect PIN. Please try again.",verify_pin_title:"Verify Your PIN",verify_pin_subtitle:"To continue, please confirm your PIN.",pin_locked_message:"Please try again after the lock expires.",pin_locked_available_from:"Available from",pin_locked_failure_warning:"Your account will be locked after further failures.",pin_locked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_session_expired:"Your session has expired. Please sign in again.",alert_account_withdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_wallet_not_found:"Wallet data could not be found. Please sign in again.",alert_different_account:`You signed in with a different Google/Apple account than before.
5
5
 
6
- For security, you must continue with the same account.`,session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},hn={ko:un,en:fr};function ye(s="en",e){return hn[s]??fr}function pn(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const gr="crossx_access_token",xr="crossx_refresh_token",wr="crossx_user_info",At=class At{constructor(e,r,t,n,i,o,a,c,l=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this.getLocale=l,this._refreshPromise=null,this._migrated=!1;const u=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${u}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${u}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${u}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${u}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new f(h.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=pn(this.getLocale()),c=`${o}${i}`,l=c.includes("?")?"&":"?",u=`${c}${l}locale=${a}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${u}`);const p=await this.oauth.openAuth({authUrl:u,expectedOrigin:new URL(o).origin});r=p.token,t=p.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new f(h.OAUTH_POPUP_BLOCKED,i):new f(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const u=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=u.firebase)==null?void 0:t.sign_in_provider);const p=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=p.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const u=await this.crypto.verifyJWT(a);if(!u.valid)throw new f(h.AUTH_FAILED,"Access token 검증 실패");const p=u.payload;r={id:p.sub,email:p.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new f(h.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0,l=o instanceof Error?o.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:p,refreshToken:g}=await this.exchangeFirebaseToken(e,u);let _,x,w;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),x=(i=A.firebase)==null?void 0:i.sign_in_provider;const R=((o=A.firebase)==null?void 0:o.identities)??{};w=A.email??((a=R.email)==null?void 0:a[0]),x==="google.com"?_=(c=R["google.com"])==null?void 0:c[0]:x==="apple.com"&&(_=(l=R["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!_,"email:",w??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const A=this.crypto.decodeJWT(p);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const R=await this.crypto.verifyJWT(p);if(n=R.signatureVerified??!1,!R.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const C=R.payload,L=C.email??w??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",C.email??"(없음)","/ Firebase JWT:",w??"(없음)","/ OAuth 콜백:",r??"(없음)","→",L??"(없음)"),t={id:C.sub,email:L,signInProvider:x,providerSub:_},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??r,signInProvider:x,providerSub:_},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const b=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,b),await this.clearStoredRNBridgeSession(),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new f(h.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new f(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new f(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof f&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=At.REFRESH_RELOGIN_CODES.has(c.code);throw new f(u?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new f(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof f&&t.code===h.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof f&&e.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(wr);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(gr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(xr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(wr),await this.storage.remove(gr),await this.storage.remove(xr),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof f&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof f&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};At.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Rt=At;class _n{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class fn{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new f(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class kt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class gn{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new f(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class xn{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}function wn(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class be{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await be.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=be.getBridge(),!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new f(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,d.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=wn(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new f(h.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:n.walletAddress,walletName:o}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new f(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),r=(e.expiresAt-Date.now())/1e3;if(r<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof f)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new f(h.USER_REJECTED,"Firebase ID token request rejected by user",e):(d.error("[RNBridge] Firebase token request failed",e),new f(h.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof f?e:(d.error("[RNBridge] Fresh Firebase token request failed",e),new f(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new f(h.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const r=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((r.expiresAt-Date.now())/1e3<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof f?r:(d.warn("[RNBridge] Session restore Firebase token request failed",r),new f(h.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",r))}}getContext(){return this.context}isActive(){var r;if(!((r=this.context)!=null&&r.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new f(h.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var ot={environment:"production"};const He={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"}};function mn(s){const e=s.environment;return e&&e in He?He[e]:null}function mr(){try{if(typeof ot<"u"){const s=typeof ot=="string"?JSON.parse(ot):ot,e=mn(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in He)return He[s]}catch{}return He.production}const yn=2e3,yr=6e4,bn=1e3,Sn=1e4,vn="0x77359400",br="0x3B9ACA00",Sr=130,Ct=6,vr=18,Er=3e4,En=5*60*1e3,An=30*1e3,at=100,In="crossx-sdk-js/2.3.0-beta.3";function Ar(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Tn(s,e=Ct){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(vr),n=r/t,o=(r%t).toString().padStart(vr,"0"),a=Ar(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function ct(s,e,r,t=Ct){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(r),o=n/i,c=(n%i).toString().padStart(r,"0"),l=Ar(c.slice(0,t));return`${l?`${o}.${l}`:`${o}`} ${e}`}catch{return}}function Rn(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Sr)throw new f(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Sr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function kn(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Cn(s,e){const r=Nn(e);if(s==="0"){if(r!==void 0&&r!==0)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=s.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(r===void 0)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==n)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function Nn(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class Ke{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new f(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=ye(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!l)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.deps.pinStore.set(l);try{return await this.deps.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(u){if(this.deps.pinStore.clear(),u instanceof f){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return Ke.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof f&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=ye(this.deps.getLocale()??"en"),u=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.session_alert_title,message:l.alert_session_expired,email:u?this.deps.maskEmail(u,l.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=ye(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof f){if(t=Ke.parsePinError(n,r),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof f&&(t=Ke.parsePinError(n,r),t))continue;throw n}}}static parsePinError(e,r){if(e.code===h.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===h.PIN_INVALID)return{errorMessage:e.message};if(e.code===h.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=Ke.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Pn{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new f(h.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}}function On(s){return s==="google"||s==="apple"}class Ln{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=On(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((r=i.user)==null?void 0:r.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=ye(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.session_alert_title,message:l.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=ye(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.session_alert_apple_account):void 0;if(r instanceof f&&r.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof f&&r.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof f)||r.code!==h.SESSION_EXPIRED)throw r;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new f(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new f(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Dn{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const o=await this.deps.walletProvider.getAddresses(n);if(o.length>0){let c,l=!1;if(r){const p=o.find(g=>g.address.toLowerCase()===r.toLowerCase());p?c=p:(c={address:r,index:0},l=!0)}else e!==void 0?c=o.find(p=>p.index===e)??o[0]:c=o[0];l?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const u=!!r&&!!t&&c.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(c.address,c.index,u?{walletName:t}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class Bn{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(u===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!p){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(p.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const g=p.pinStatus;if(o=g.maxAttempts,i=o-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const _=g.lockExpiresAt*1e3,x=Math.max(1,Math.round((_-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${x}초, 메시지: ${w}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof f))throw p;if(p.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=ye(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:_?this.deps.maskEmail(_,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const g=p.details;if(o=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const _=((g==null?void 0:g.lockExpiresAt)??0)*1e3,x=Math.max(1,Math.round((_-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${x}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof f&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof f&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=ye(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:g?this.deps.maskEmail(g,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const w=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",w.address),w}catch(w){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",w),w}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class $n{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=_=>!(_!=null&&_.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,p,g]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],r):null,i?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const _=g;if(_){const x=br;c.maxFeePerGas=`0x${(BigInt(_)+BigInt(x)).toString(16)}`,c.maxPriorityFeePerGas=x,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",_,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=vn,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=br,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Mn{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new f(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof f)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Fn(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class Wn{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const n={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(n.walletName=t.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const r={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((i=e.user)==null?void 0:i.providerSub)??null,loginType:Fn((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Un{constructor(e){this.deps=e}async resolveAddress(e){const r=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===r){if(!t)throw new f(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Hn{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new f(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new f(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Kn{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",o);const a=await this.deps.migrationOrchestrator.handleMigrationFlow(o);if(a)return this.deps.setActiveWallet(a.address,0),{address:a.address};throw new f(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof f&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new f(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function Ir(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class Gn{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new f(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new f(h.TX_INVALID_PARAMS,"invalid param tx_hash");const n=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new f(h.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new f(h.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=Ir(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof f?c:new f(h.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const r=this.deps.getApiBaseUrl(),t=new URL(Ir(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new f(h.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof f?i:new f(h.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,r,t,n){const i=(n==null?void 0:n.maxRetries)??3,o=(n==null?void 0:n.retryDelayMs)??2e3;for(let a=0;a<i;a++)try{await this.registerTokenHistory(e,r,t);return}catch(c){if(c instanceof f&&c.message.includes("404")&&a<i-1){d.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(u=>setTimeout(u,o));continue}throw c}}handleError(e,r){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:h.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:h.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:h.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new f(n.code,n.message)}}function Nt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const r=s.indexOf("@");if(r<0)return"*".repeat(s.length||3);const t=s.substring(0,r),n=s.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Fe=class Fe extends xn{constructor(e,r,t,n,i,o,a,c,l,u,p){var g,_;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._bridgeSessionRestorePromise=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&_r(e.logger),this.confirmation=l,this.pinStore=p??new kt,this.stateManager=new Wn({setState:x=>{x.authenticated!==void 0&&(this.authenticated=x.authenticated),x.userId!==void 0&&(this.userId=x.userId),x.address!==void 0&&(this.address=x.address),x.activeWalletIndex!==void 0&&(this.activeWalletIndex=x.activeWalletIndex),x.userEmail!==void 0&&(this.userEmail=x.userEmail),x.providerSub!==void 0&&(this.providerSub=x.providerSub),x.loginType!==void 0&&(this.loginType=x.loginType),x.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=x.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:x,index:w,walletName:b})=>{const A={address:x,index:w};b!==void 0&&(A.walletName=b),this.emit("addressChanged",A)},emitAuthChanged:({isAuthenticated:x,address:w,userId:b})=>{this.emit("authChanged",{isAuthenticated:x,address:w,userId:b})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Fe.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ke({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Nt,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Pn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Dn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,w,b)=>this.setActiveWallet(x,w,b)}),this.migrationOrchestrator=new Bn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,w)=>this.migrateWalletUseCase.execute(x,w),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Nt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new $n({getActiveAddress:()=>this.address,estimateGas:(x,w)=>this.estimateGas(x,w),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,w,b)=>this.jsonRpc.call(x,w,b)}),this.signatureVerifier=new Mn(this.crypto),this.addressResolverService=new Un({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Hn({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Kn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,w)=>this.setActiveWallet(x,w),showWalletCreated:()=>{var x,w;return((w=(x=this.confirmation).showWalletCreatedPrompt)==null?void 0:w.call(x))??Promise.resolve()}}),this.tokenHistoryService=new Gn({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Ln({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:x=>{this._isRecoveringSession=x},setAuthenticated:x=>{this.authenticated=x},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:x=>this.signInUseCase.execute(x),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:x=>this.confirmation.showSessionAlert(x),clearAuthState:()=>this.clearAuthState(),applyAuthResult:x=>this.applyAuthResult(x),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:Nt}),this.chainRegistry=u,this.jsonRpc=new gn(u,i),this.signInUseCase=new Rt(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new _n(this.internalConfig,t,c),this.migrateWalletUseCase=new fn(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(_=a.setTokenRefresher)==null||_.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v2.3.0-beta.3 초기화 중..."),this.confirmation.setMessages(ye(this._config.locale));try{const n=mr();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Fe.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const l=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),u=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(l)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,u?{walletName:u}:void 0);else try{await this.loadWalletAfterAuth(o,a,u)}catch(p){if(!(p instanceof f&&p.code===h.PIN_CANCELLED))throw p;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v2.3.0-beta.3 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new f(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!be.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도");const e=new be({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.0-beta.3",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof f&&r.code===h.USER_REJECTED?(d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession()||(this._isAuthenticatedViaRNBridge=!0,await this.signInUseCase.hasValidStoredAccessToken()))return null;d.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(d.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return d.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new f(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw d.error("[CROSSx] Bridge session restore token request failed:",e),new f(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return be.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");if(this._rnBridgeService){const t=await this._tryBridgeSignIn();if(t===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(t!=null&&t.success)return t}let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:an(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new f(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");r={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,r);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,r);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof f&&i.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r))}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",t)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...r,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof f&&t.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=be.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new f(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(t){t instanceof f&&t.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof f&&t.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof f?r:new f(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(n=>n.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof f?e:new f(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof f?r:new f(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(ye(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(r,i.signature,n.address),{chainId:e,signature:i.signature,message:r,address:n.address}}catch(i){throw i instanceof f?i:new f(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new f(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Cn(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return Rn(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof f?i:new f(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(Fe.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Tt(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return kn(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof f)throw o;const a=o instanceof Error?o.message:String(o);throw new f(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Tt(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async u=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,u)).txHash;const p=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return p.txHash??p.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,In).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof f)throw o;const a=o instanceof Error?o.message:String(o);throw new f(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??bn,i=Sn,o=t.timeoutMs??yr,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new f(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var w,b;if(this._isAuthenticatedViaRNBridge){const A=be.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((w=this._config.receiptPolling)==null?void 0:w.intervalMs)??yn,l=i??((b=this._config.receiptPolling)==null?void 0:b.timeoutMs)??yr,u=Tt(e),p=r.from??"";let g,_;const x=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{g=A;const R=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),C=r.value?BigInt(r.value):0n,L=ct(r.value,u.symbol,u.decimals,this._config.displayDecimals),W=ct("0x"+R.toString(16),u.symbol,u.decimals,this._config.displayDecimals),U=ct("0x"+(C+R).toString(16),u.symbol,u.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:A.from,to:A.to??r.to,amount:L,fees:W,total:U,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(_=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:p,to:r.to,amount:ct(r.value,u.symbol,u.decimals,this._config.displayDecimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:r.to},x),_)throw _;return{chainId:e,txHash:a,receipt:g}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs});return{chainId:r,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??t.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new f(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof f?n:new f(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new f(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:Tn(n,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new pr(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof f)throw n;const i=n instanceof Error?n.message:String(n);throw new f(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,r,t){const n=this.address;this.stateManager.setActiveWallet(e,r,t),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=be.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated){d.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const i=typeof t.walletName=="string"?t.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(n,0,{walletName:o}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=o)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),_r(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Fe.WALLET_PREF_KEY="wallet_preference",Fe.OFFCHAIN_CHAIN_ID="0";let lt=Fe;class qn{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Pt="crossx-sdk",Vn=1,_e="data",Oe="keys",dt="aes-primary",zn=12;class Tr{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,Vn);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_e)||i.createObjectStore(_e),i.objectStoreNames.contains(Oe)||i.createObjectStore(Oe)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Oe,dt);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Oe,dt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Pt)return null;try{const e=await this.openDB(Pt),r=e.transaction([Oe,_e],"readonly"),t=r.objectStore(Oe).get(dt),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(_e).getAll(),o=r.objectStore(_e).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Oe,dt,n);for(let l=0;l<c.length;l++)await this.idbPut(_e,String(c[l]),a[l]);return indexedDB.deleteDatabase(Pt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(zn);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(_e,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(_e,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(_e,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(_e)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const Ot=crypto,Rr=s=>s instanceof CryptoKey,ut=new TextEncoder,Qe=new TextDecoder;function Jn(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const jn=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Qe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return jn(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class re extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}re.code="ERR_JOSE_GENERIC";class he extends re{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Lt extends re{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}Lt.code="ERR_JWT_EXPIRED";class kr extends re{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}kr.code="ERR_JOSE_ALG_NOT_ALLOWED";class fe extends re{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}fe.code="ERR_JOSE_NOT_SUPPORTED";class Yn extends re{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}Yn.code="ERR_JWE_DECRYPTION_FAILED";class Xn extends re{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Xn.code="ERR_JWE_INVALID";class ee extends re{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}ee.code="ERR_JWS_INVALID";class ge extends re{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ge.code="ERR_JWT_INVALID";class Zn extends re{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Zn.code="ERR_JWK_INVALID";class Dt extends re{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Dt.code="ERR_JWKS_INVALID";class Bt extends re{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Bt.code="ERR_JWKS_NO_MATCHING_KEY";class Cr extends re{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Cr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Nr extends re{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}Nr.code="ERR_JWKS_TIMEOUT";class Pr extends re{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Pr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function xe(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function et(s,e){return s.name===e}function $t(s){return parseInt(s.name.slice(4),10)}function Qn(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ei(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function ti(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!et(s.algorithm,"HMAC"))throw xe("HMAC");const t=parseInt(e.slice(2),10);if($t(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!et(s.algorithm,"RSASSA-PKCS1-v1_5"))throw xe("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if($t(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!et(s.algorithm,"RSA-PSS"))throw xe("RSA-PSS");const t=parseInt(e.slice(2),10);if($t(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw xe("Ed25519 or Ed448");break}case"Ed25519":{if(!et(s.algorithm,"Ed25519"))throw xe("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!et(s.algorithm,"ECDSA"))throw xe("ECDSA");const t=Qn(e);if(s.algorithm.namedCurve!==t)throw xe(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ei(s,r)}function Or(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const Lr=(s,...e)=>Or("Key must be ",s,...e);function Dr(s,e,...r){return Or(`Key for the ${s} algorithm must be `,e,...r)}const Br=s=>Rr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ht=["CryptoKey"],ri=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function si(s){return typeof s=="object"&&s!==null}function Se(s){if(!si(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const ni=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ge(s){return Se(s)&&typeof s.kty=="string"}function ii(s){return s.kty!=="oct"&&typeof s.d=="string"}function oi(s){return s.kty!=="oct"&&typeof s.d>"u"}function ai(s){return Ge(s)&&s.kty==="oct"&&typeof s.k=="string"}function ci(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new fe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const $r=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=ci(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,Ot.subtle.importKey("jwk",n,...t)},Mr=s=>Re(s);let qe,Ve;const Fr=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",pt=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await $r({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},li={normalizePublicKey:(s,e)=>{if(Fr(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Mr(r.k):(Ve||(Ve=new WeakMap),pt(Ve,s,r,e))}return Ge(s)?s.k?Re(s.k):(Ve||(Ve=new WeakMap),pt(Ve,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(Fr(s)){let r=s.export({format:"jwk"});return r.k?Mr(r.k):(qe||(qe=new WeakMap),pt(qe,s,r,e))}return Ge(s)?s.k?Re(s.k):(qe||(qe=new WeakMap),pt(qe,s,s,e,!0)):s}};async function Wr(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new fe('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return $r({...s,alg:e});default:throw new fe('Unsupported "kty" (Key Type) Parameter value')}}const ze=s=>s==null?void 0:s[Symbol.toStringTag],Mt=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},di=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&Ge(e)){if(ai(e)&&Mt(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Br(e))throw new TypeError(Dr(s,e,...ht,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${ze(e)} instances for symmetric algorithms must be of type "secret"`)}},ui=(s,e,r,t)=>{if(t&&Ge(e))switch(r){case"sign":if(ii(e)&&Mt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(oi(e)&&Mt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Br(e))throw new TypeError(Dr(s,e,...ht,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${ze(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${ze(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${ze(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${ze(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${ze(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ur(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?di(e,r,t,s):ui(e,r,t,s)}Ur.bind(void 0,!1);const Hr=Ur.bind(void 0,!0);function hi(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new fe(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const pi=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function _i(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new fe(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function fi(s,e,r){if(e=await li.normalizePublicKey(e,s),Rr(e))return ti(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(Lr(e,...ht));return Ot.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(Lr(e,...ht,"Uint8Array","JSON Web Key"))}const gi=async(s,e,r,t)=>{const n=await fi(s,e,"verify");ni(s,n);const i=_i(s,n.algorithm);try{return await Ot.subtle.verify(i,n,r,t)}catch{return!1}};async function xi(s,e,r){if(!Se(s))throw new ee("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new ee('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new ee("JWS Protected Header incorrect type");if(s.payload===void 0)throw new ee("JWS Payload missing");if(typeof s.signature!="string")throw new ee("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new ee("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const w=Re(s.protected);t=JSON.parse(Qe.decode(w))}catch{throw new ee("JWS Protected Header is invalid")}if(!ri(t,s.header))throw new ee("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=hi(ee,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new ee('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new ee('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&pi("algorithms",r.algorithms);if(c&&!c.has(a))throw new kr('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new ee("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new ee("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,Hr(a,e,"verify"),Ge(e)&&(e=await Wr(e,a))):Hr(a,e,"verify");const u=Jn(ut.encode(s.protected??""),ut.encode("."),typeof s.payload=="string"?ut.encode(s.payload):s.payload);let p;try{p=Re(s.signature)}catch{throw new ee("Failed to base64url decode the signature")}if(!await gi(a,e,p,u))throw new Pr;let _;if(o)try{_=Re(s.payload)}catch{throw new ee("Failed to base64url decode the payload")}else typeof s.payload=="string"?_=ut.encode(s.payload):_=s.payload;const x={payload:_};return s.protected!==void 0&&(x.protectedHeader=t),s.header!==void 0&&(x.unprotectedHeader=s.header),l?{...x,key:e}:x}async function wi(s,e,r){if(s instanceof Uint8Array&&(s=Qe.decode(s)),typeof s!="string")throw new ee("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new ee("Invalid Compact JWS");const a=await xi({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const mi=s=>Math.floor(s.getTime()/1e3),Kr=60,Gr=Kr*60,Ft=Gr*24,yi=Ft*7,bi=Ft*365.25,Si=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,qr=s=>{const e=Si.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*Kr);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Gr);break;case"day":case"days":case"d":n=Math.round(r*Ft);break;case"week":case"weeks":case"w":n=Math.round(r*yi);break;default:n=Math.round(r*bi);break}return e[1]==="-"||e[4]==="ago"?-n:n},Vr=s=>s.toLowerCase().replace(/^application\//,""),vi=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Ei=(s,e,r={})=>{let t;try{t=JSON.parse(Qe.decode(e))}catch{}if(!Se(t))throw new ge("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||Vr(s.typ)!==Vr(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const x of new Set(u.reverse()))if(!(x in t))throw new he(`missing required "${x}" claim`,t,x,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!vi(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=qr(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:g}=r,_=mi(g||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>_+p)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=_-p)throw new Lt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const x=_-t.iat,w=typeof l=="number"?l:qr(l);if(x-p>w)throw new Lt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(x<0-p)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Ai(s,e,r){var o;const t=await wi(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new ge("JWTs MUST NOT use unencoded payload");const i={payload:Ei(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Ii(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new fe('Unsupported "alg" value for a JSON Web Key Set')}}function Ti(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Ri)}function Ri(s){return Se(s)}function zr(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class ki{constructor(e){if(this._cached=new WeakMap,!Ti(e))throw new Dt("JSON Web Key Set malformed");this._jwks=zr(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=Ii(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Bt;if(c!==1){const l=new Cr,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await Jr(u,p,t)}catch{}},l}return Jr(this._cached,a,t)}}async function Jr(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await Wr({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new Dt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function jr(s){const e=new ki(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>zr(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Ci=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new Nr:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new re("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new re("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Ni(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Wt;(typeof navigator>"u"||!((sn=(It=navigator.userAgent)==null?void 0:It.startsWith)!=null&&sn.call(It,"Mozilla/5.0 ")))&&(Wt="jose/v5.10.0");const Ut=Symbol();function Pi(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class Oi{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Ut])!==void 0&&(this._cache=r==null?void 0:r[Ut],Pi(r==null?void 0:r[Ut],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=jr(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Bt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Ni()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Wt&&!e.has("User-Agent")&&(e.set("User-Agent",Wt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Ci(this._url,this._timeoutDuration,this._options).then(r=>{this._local=jr(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Li(s,e){const r=new Oi(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Di=Re;function Bi(s){if(typeof s!="string")throw new ge("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new ge("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ge("Invalid JWT");if(!e)throw new ge("JWTs must contain a payload");let t;try{t=Di(e)}catch{throw new ge("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Qe.decode(t))}catch{throw new ge("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new ge("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ht(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function Y(s,e,r=""){const t=Ht(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function Yr(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function Je(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Xr(s,e){Y(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function $i(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function je(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Kt(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function we(s,e){return s<<32-e|s>>>e}const Mi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Fi(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Wi(s){for(let e=0;e<s.length;e++)s[e]=Fi(s[e]);return s}const Zr=Mi?s=>s:Wi,Qr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ui=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tt(s){if(Y(s),Qr)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Ui[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function es(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function _t(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Qr)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=es(s.charCodeAt(i)),a=es(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ke(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];Y(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function ts(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function rs(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const Hi=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Ki(s,e,r){return s&e^~s&r}function Gi(s,e,r){return s&e^s&r^e&r}class qi{constructor(e,r,t,n){O(this,"blockLen");O(this,"outputLen");O(this,"padOffset");O(this,"isLE");O(this,"buffer");O(this,"view");O(this,"finished",!1);O(this,"length",0);O(this,"pos",0);O(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Kt(this.buffer)}update(e){Je(this),Y(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Kt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Je(this),Xr(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,je(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)r[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Kt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,u[p],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ft=BigInt(2**32-1),ss=BigInt(32);function Vi(s,e=!1){return e?{h:Number(s&ft),l:Number(s>>ss&ft)}:{h:Number(s>>ss&ft)|0,l:Number(s&ft)|0}}function zi(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=Vi(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const Ji=(s,e,r)=>s<<r|e>>>32-r,ji=(s,e,r)=>e<<r|s>>>32-r,Yi=(s,e,r)=>e<<r-32|s>>>64-r,Xi=(s,e,r)=>s<<r-32|e>>>64-r,Zi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ne=new Uint32Array(64);class Qi extends qi{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let p=0;p<16;p++,r+=4)Ne[p]=e.getUint32(r,!1);for(let p=16;p<64;p++){const g=Ne[p-15],_=Ne[p-2],x=we(g,7)^we(g,18)^g>>>3,w=we(_,17)^we(_,19)^_>>>10;Ne[p]=w+Ne[p-7]+x+Ne[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let p=0;p<64;p++){const g=we(a,6)^we(a,11)^we(a,25),_=u+g+Ki(a,c,l)+Zi[p]+Ne[p]|0,w=(we(t,2)^we(t,13)^we(t,22))+Gi(t,n,i)|0;u=l,l=c,c=a,a=o+_|0,o=i,i=n,n=t,t=_+w|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){je(Ne)}destroy(){this.set(0,0,0,0,0,0,0,0),je(this.buffer)}}class eo extends Qi{constructor(){super(32);O(this,"A",Ce[0]|0);O(this,"B",Ce[1]|0);O(this,"C",Ce[2]|0);O(this,"D",Ce[3]|0);O(this,"E",Ce[4]|0);O(this,"F",Ce[5]|0);O(this,"G",Ce[6]|0);O(this,"H",Ce[7]|0)}}const to=ts(()=>new eo,Hi(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gt=BigInt(0),qt=BigInt(1);function gt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function ns(s){if(typeof s=="bigint"){if(!mt(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function xt(s){const e=ns(s).toString(16);return e.length&1?"0"+e:e}function is(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Gt:BigInt("0x"+s)}function wt(s){return is(tt(s))}function os(s){return is(tt(ro(Y(s)).reverse()))}function Vt(s,e){ve(e),s=ns(s);const r=_t(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function as(s,e){return Vt(s,e).reverse()}function ro(s){return Uint8Array.from(s)}const mt=s=>typeof s=="bigint"&&Gt<=s;function so(s,e,r){return mt(s)&&mt(e)&&mt(r)&&e<=s&&s<r}function no(s,e,r,t){if(!so(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function io(s){let e;for(e=0;s>Gt;s>>=qt,e+=1);return e}const zt=s=>(qt<<BigInt(s))-qt;function oo(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=b=>new Uint8Array(b),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const p=()=>{c.fill(1),l.fill(0),u=0},g=(...b)=>r(l,ke(c,...b)),_=(b=n)=>{l=g(i,b),c=g(),b.length!==0&&(l=g(o,b),c=g())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0;const A=[];for(;b<e;){c=g();const R=c.slice();A.push(R),b+=c.length}return ke(...A)};return(b,A)=>{p(),_(b);let R;for(;!(R=A(x()));)_();return p(),R}}function Jt(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function cs(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ae=BigInt(0),ie=BigInt(1),Le=BigInt(2),ls=BigInt(3),ds=BigInt(4),us=BigInt(5),ao=BigInt(7),hs=BigInt(8),co=BigInt(9),ps=BigInt(16);function pe(s,e){const r=s%e;return r>=ae?r:e+r}function le(s,e,r){let t=s;for(;e-- >ae;)t*=t,t%=r;return t}function _s(s,e){if(s===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let r=pe(s,e),t=e,n=ae,i=ie;for(;r!==ae;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==ie)throw new Error("invert: does not exist");return pe(n,e)}function jt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function fs(s,e){const r=(s.ORDER+ie)/ds,t=s.pow(e,r);return jt(s,t,e),t}function lo(s,e){const r=(s.ORDER-us)/hs,t=s.mul(e,Le),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Le),n),a=s.mul(i,s.sub(o,s.ONE));return jt(s,a,e),a}function uo(s){const e=yt(s),r=gs(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+ao)/ps;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const p=a.mul(l,n),g=a.mul(l,i),_=a.eql(a.sqr(u),c),x=a.eql(a.sqr(p),c);l=a.cmov(l,u,_),u=a.cmov(g,p,x);const w=a.eql(a.sqr(u),c),b=a.cmov(l,u,w);return jt(a,b,c),b}}function gs(s){if(s<ls)throw new Error("sqrt is not defined for small field");let e=s-ie,r=0;for(;e%Le===ae;)e/=Le,r++;let t=Le;const n=yt(s);for(;ws(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return fs;let i=n.pow(t,e);const o=(e+ie)/Le;return function(c,l){if(c.is0(l))return l;if(ws(c,l)!==1)throw new Error("Cannot find square root");let u=r,p=c.mul(c.ONE,i),g=c.pow(l,e),_=c.pow(l,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let x=1,w=c.sqr(g);for(;!c.eql(w,c.ONE);)if(x++,w=c.sqr(w),x===u)throw new Error("Cannot find square root");const b=ie<<BigInt(u-x-1),A=c.pow(p,b);u=x,p=c.sqr(A),g=c.mul(g,p),_=c.mul(_,A)}return _}}function ho(s){return s%ds===ls?fs:s%hs===us?lo:s%ps===co?uo(s):gs(s)}const po=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function _o(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=po.reduce((t,n)=>(t[n]="function",t),e);return Jt(s,r),s}function fo(s,e,r){if(r<ae)throw new Error("invalid exponent, negatives unsupported");if(r===ae)return s.ONE;if(r===ie)return e;let t=s.ONE,n=e;for(;r>ae;)r&ie&&(t=s.mul(t,n)),n=s.sqr(n),r>>=ie;return t}function xs(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function ws(s,e){const r=(s.ORDER-ie)/Le,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function go(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class xo{constructor(e,r={}){O(this,"ORDER");O(this,"BITS");O(this,"BYTES");O(this,"isLE");O(this,"ZERO",ae);O(this,"ONE",ie);O(this,"_lengths");O(this,"_sqrt");O(this,"_mod");var o;if(e<=ae)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=go(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return pe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ie)===ie}neg(e){return pe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return pe(e*e,this.ORDER)}add(e,r){return pe(e+r,this.ORDER)}sub(e,r){return pe(e-r,this.ORDER)}mul(e,r){return pe(e*r,this.ORDER)}pow(e,r){return fo(this,e,r)}div(e,r){return pe(e*_s(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return _s(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=ho(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?as(e,this.BYTES):Vt(e,this.BYTES)}fromBytes(e,r=!1){Y(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?os(e):wt(e);if(a&&(c=pe(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return xs(this,e)}cmov(e,r,t){return t?r:e}}function yt(s,e={}){return new xo(s,e)}function ms(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function ys(s){const e=ms(s);return e+Math.ceil(e/2)}function wo(s,e,r=!1){Y(s);const t=s.length,n=ms(e),i=ys(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?os(s):wt(s),a=pe(o,e-ie)+ie;return r?as(a,n):Vt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ye=BigInt(0),De=BigInt(1);function bt(s,e){const r=e.negate();return s?r:e}function bs(s,e){const r=xs(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function Ss(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Yt(s,e){Ss(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=zt(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function vs(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,p=a===0,g=a<0,_=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:g,isNegF:_,offsetF:l}}const Xt=new WeakMap,Es=new WeakMap;function Zt(s){return Es.get(s)||1}function As(s){if(s!==Ye)throw new Error("invalid wNAF")}class mo{constructor(e,r){O(this,"BASE");O(this,"ZERO");O(this,"Fn");O(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Ye;)r&De&&(t=t.add(n)),n=n.double(),r>>=De;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Yt(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Yt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:g,offsetF:_}=vs(t,a,o);t=c,u?i=i.add(bt(g,r[_])):n=n.add(bt(p,r[l]))}return As(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=Yt(e,this.bits);for(let o=0;o<i.windows&&t!==Ye;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=vs(t,o,i);if(t=a,!l){const p=r[c];n=n.add(u?p.negate():p)}}return As(t),n}getPrecomputes(e,r,t){let n=Xt.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),Xt.set(r,n))),n}cached(e,r,t){const n=Zt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=Zt(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){Ss(r,this.bits),Es.set(e,r),Xt.delete(e)}hasCache(e){return Zt(e)!==1}}function yo(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Ye||t>Ye;)r&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),r>>=De,t>>=De;return{p1:i,p2:o}}function Is(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return _o(e),e}else return yt(s,{isLE:r})}function bo(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ye))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Is(e.p,r.Fp,t),i=Is(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function So(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class Ts{constructor(e,r){O(this,"oHash");O(this,"iHash");O(this,"blockLen");O(this,"outputLen");O(this,"finished",!1);O(this,"destroyed",!1);if(Yr(e),Y(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),je(n)}update(e){return Je(this),this.iHash.update(e),this}digestInto(e){Je(this),Y(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Rs=(s,e,r)=>new Ts(s,e).update(r).digest();Rs.create=(s,e)=>new Ts(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ks=(s,e)=>(s+(s>=0?e:-e)/Cs)/e;function vo(s,e,r){const[[t,n],[i,o]]=e,a=ks(o*s,r),c=ks(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const p=l<Ae,g=u<Ae;p&&(l=-l),g&&(u=-u);const _=zt(Math.ceil(io(r)/2))+Xe;if(l<Ae||l>=_||u<Ae||u>=_)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:p,k1:l,k2neg:g,k2:u}}function Qt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function er(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return gt(r.lowS,"lowS"),gt(r.prehash,"prehash"),r.format!==void 0&&Qt(r.format),r}class Eo extends Error{constructor(e=""){super(e)}}const Pe={Err:Eo,_tlv:{encode:(s,e)=>{const{Err:r}=Pe;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=xt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?xt(n.length/2|128):"";return xt(s)+i+n+e},decode(s,e){const{Err:r}=Pe;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=Pe;if(s<Ae)throw new e("integer: negative integers are not allowed");let r=xt(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=Pe;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return wt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Pe,n=Y(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=Pe,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ae=BigInt(0),Xe=BigInt(1),Cs=BigInt(2),St=BigInt(3),Ao=BigInt(4);function Io(s,e={}){const r=bo("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Jt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ps(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(H,y,m){const{x:T,y:N}=y.toAffine(),M=t.toBytes(T);if(gt(m,"isCompressed"),m){u();const D=!t.isOdd(N);return ke(Ns(D),M)}else return ke(Uint8Array.of(4),M,t.toBytes(N))}function g(H){Y(H,void 0,"Point");const{publicKey:y,publicKeyUncompressed:m}=l,T=H.length,N=H[0],M=H.subarray(1);if(T===y&&(N===2||N===3)){const D=t.fromBytes(M);if(!t.isValid(D))throw new Error("bad point: is not on curve, wrong x");const $=w(D);let P;try{P=t.sqrt($)}catch(E){const k=E instanceof Error?": "+E.message:"";throw new Error("bad point: is not on curve, sqrt error"+k)}u();const K=t.isOdd(P);return(N&1)===1!==K&&(P=t.neg(P)),{x:D,y:P}}else if(T===m&&N===4){const D=t.BYTES,$=t.fromBytes(M.subarray(0,D)),P=t.fromBytes(M.subarray(D,D*2));if(!b($,P))throw new Error("bad point: is not on curve");return{x:$,y:P}}else throw new Error(`bad point: got length ${T}, expected compressed=${y} or uncompressed=${m}`)}const _=e.toBytes||p,x=e.fromBytes||g;function w(H){const y=t.sqr(H),m=t.mul(y,H);return t.add(t.add(m,t.mul(H,i.a)),i.b)}function b(H,y){const m=t.sqr(y),T=w(H);return t.eql(m,T)}if(!b(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,St),Ao),R=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,R)))throw new Error("bad curve params: a or b");function C(H,y,m=!1){if(!t.isValid(y)||m&&t.is0(y))throw new Error(`bad point coordinate ${H}`);return y}function L(H){if(!(H instanceof X))throw new Error("Weierstrass Point expected")}function W(H){if(!c||!c.basises)throw new Error("no endo");return vo(H,c.basises,n.ORDER)}const U=cs((H,y)=>{const{X:m,Y:T,Z:N}=H;if(t.eql(N,t.ONE))return{x:m,y:T};const M=H.is0();y==null&&(y=M?t.ONE:t.inv(N));const D=t.mul(m,y),$=t.mul(T,y),P=t.mul(N,y);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:D,y:$}}),se=cs(H=>{if(H.is0()){if(e.allowInfinityPoint&&!t.is0(H.Y))return;throw new Error("bad point: ZERO")}const{x:y,y:m}=H.toAffine();if(!t.isValid(y)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!b(y,m))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function q(H,y,m,T,N){return m=new X(t.mul(m.X,H),m.Y,m.Z),y=bt(T,y),m=bt(N,m),y.add(m)}const B=class B{constructor(y,m,T){O(this,"X");O(this,"Y");O(this,"Z");this.X=C("x",y),this.Y=C("y",m,!0),this.Z=C("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){const{x:m,y:T}=y||{};if(!y||!t.isValid(m)||!t.isValid(T))throw new Error("invalid affine point");if(y instanceof B)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(T)?B.ZERO:new B(m,T,t.ONE)}static fromBytes(y){const m=B.fromAffine(x(Y(y,void 0,"point")));return m.assertValidity(),m}static fromHex(y){return B.fromBytes(_t(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,m=!0){return G.createCache(this,y),m||this.multiply(St),this}assertValidity(){se(this)}hasEvenY(){const{y}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(y)}equals(y){L(y);const{X:m,Y:T,Z:N}=this,{X:M,Y:D,Z:$}=y,P=t.eql(t.mul(m,$),t.mul(M,N)),K=t.eql(t.mul(T,$),t.mul(D,N));return P&&K}negate(){return new B(this.X,t.neg(this.Y),this.Z)}double(){const{a:y,b:m}=i,T=t.mul(m,St),{X:N,Y:M,Z:D}=this;let $=t.ZERO,P=t.ZERO,K=t.ZERO,S=t.mul(N,N),E=t.mul(M,M),k=t.mul(D,D),I=t.mul(N,M);return I=t.add(I,I),K=t.mul(N,D),K=t.add(K,K),$=t.mul(y,K),P=t.mul(T,k),P=t.add($,P),$=t.sub(E,P),P=t.add(E,P),P=t.mul($,P),$=t.mul(I,$),K=t.mul(T,K),k=t.mul(y,k),I=t.sub(S,k),I=t.mul(y,I),I=t.add(I,K),K=t.add(S,S),S=t.add(K,S),S=t.add(S,k),S=t.mul(S,I),P=t.add(P,S),k=t.mul(M,D),k=t.add(k,k),S=t.mul(k,I),$=t.sub($,S),K=t.mul(k,E),K=t.add(K,K),K=t.add(K,K),new B($,P,K)}add(y){L(y);const{X:m,Y:T,Z:N}=this,{X:M,Y:D,Z:$}=y;let P=t.ZERO,K=t.ZERO,S=t.ZERO;const E=i.a,k=t.mul(i.b,St);let I=t.mul(m,M),F=t.mul(T,D),V=t.mul(N,$),J=t.add(m,T),z=t.add(M,D);J=t.mul(J,z),z=t.add(I,F),J=t.sub(J,z),z=t.add(m,N);let j=t.add(M,$);return z=t.mul(z,j),j=t.add(I,V),z=t.sub(z,j),j=t.add(T,N),P=t.add(D,$),j=t.mul(j,P),P=t.add(F,V),j=t.sub(j,P),S=t.mul(E,z),P=t.mul(k,V),S=t.add(P,S),P=t.sub(F,S),S=t.add(F,S),K=t.mul(P,S),F=t.add(I,I),F=t.add(F,I),V=t.mul(E,V),z=t.mul(k,z),F=t.add(F,V),V=t.sub(I,V),V=t.mul(E,V),z=t.add(z,V),I=t.mul(F,z),K=t.add(K,I),I=t.mul(j,z),P=t.mul(J,P),P=t.sub(P,I),I=t.mul(J,F),S=t.mul(j,S),S=t.add(S,I),new B(P,K,S)}subtract(y){return this.add(y.negate())}is0(){return this.equals(B.ZERO)}multiply(y){const{endo:m}=e;if(!n.isValidNot0(y))throw new Error("invalid scalar: out of range");let T,N;const M=D=>G.cached(this,D,$=>bs(B,$));if(m){const{k1neg:D,k1:$,k2neg:P,k2:K}=W(y),{p:S,f:E}=M($),{p:k,f:I}=M(K);N=E.add(I),T=q(m.beta,S,k,D,P)}else{const{p:D,f:$}=M(y);T=D,N=$}return bs(B,[T,N])[0]}multiplyUnsafe(y){const{endo:m}=e,T=this;if(!n.isValid(y))throw new Error("invalid scalar: out of range");if(y===Ae||T.is0())return B.ZERO;if(y===Xe)return T;if(G.hasCache(this))return this.multiply(y);if(m){const{k1neg:N,k1:M,k2neg:D,k2:$}=W(y),{p1:P,p2:K}=yo(B,T,M,$);return q(m.beta,P,K,N,D)}else return G.unsafe(T,y)}toAffine(y){return U(this,y)}isTorsionFree(){const{isTorsionFree:y}=e;return o===Xe?!0:y?y(B,this):G.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:y}=e;return o===Xe?this:y?y(B,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return gt(y,"isCompressed"),this.assertValidity(),_(B,this,y)}toHex(y=!0){return tt(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};O(B,"BASE",new B(i.Gx,i.Gy,t.ONE)),O(B,"ZERO",new B(t.ZERO,t.ONE,t.ZERO)),O(B,"Fp",t),O(B,"Fn",n);let X=B;const ne=n.BITS,G=new mo(X,e.endo?Math.ceil(ne/2):ne);return X.BASE.precompute(8),X}function Ns(s){return Uint8Array.of(s?2:3)}function Ps(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function To(s,e={}){const{Fn:r}=s,t=e.randomBytes||rs,n=Object.assign(Ps(s.Fp,r),{seed:ys(r.ORDER)});function i(_){try{const x=r.fromBytes(_);return r.isValidNot0(x)}catch{return!1}}function o(_,x){const{publicKey:w,publicKeyUncompressed:b}=n;try{const A=_.length;return x===!0&&A!==w||x===!1&&A!==b?!1:!!s.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return wo(Y(_,n.seed,"seed"),r.ORDER)}function c(_,x=!0){return s.BASE.multiply(r.fromBytes(_)).toBytes(x)}function l(_){const{secretKey:x,publicKey:w,publicKeyUncompressed:b}=n;if(!Ht(_)||"_lengths"in r&&r._lengths||x===w)return;const A=Y(_,void 0,"key").length;return A===w||A===b}function u(_,x,w=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const b=r.fromBytes(_);return s.fromBytes(x).multiply(b).toBytes(w)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=So(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:g,Point:s,utils:p,lengths:n})}function Ro(s,e,r={}){Yr(e),Jt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||rs,n=r.hmac||((y,m)=>Rs(e,y,m)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:g,lengths:_}=To(s,r),x={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},w=a*Cs<i.ORDER;function b(y){const m=a>>Xe;return y>m}function A(y,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return m}function R(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function C(y,m){Qt(m);const T=_.signature,N=m==="compact"?T:m==="recovered"?T+1:void 0;return Y(y,N)}class L{constructor(m,T,N){O(this,"r");O(this,"s");O(this,"recovery");if(this.r=A("r",m),this.s=A("s",T),N!=null){if(R(),![0,1,2,3].includes(N))throw new Error("invalid recovery id");this.recovery=N}Object.freeze(this)}static fromBytes(m,T=x.format){C(m,T);let N;if(T==="der"){const{r:P,s:K}=Pe.toSig(Y(m));return new L(P,K)}T==="recovered"&&(N=m[0],T="compact",m=m.subarray(1));const M=_.signature/2,D=m.subarray(0,M),$=m.subarray(M,M*2);return new L(o.fromBytes(D),o.fromBytes($),N)}static fromHex(m,T){return this.fromBytes(_t(m),T)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new L(this.r,this.s,m)}recoverPublicKey(m){const{r:T,s:N}=this,M=this.assertRecovery(),D=M===2||M===3?T+a:T;if(!i.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const $=i.toBytes(D),P=s.fromBytes(ke(Ns((M&1)===0),$)),K=o.inv(D),S=U(Y(m,void 0,"msgHash")),E=o.create(-S*K),k=o.create(N*K),I=s.BASE.multiplyUnsafe(E).add(P.multiplyUnsafe(k));if(I.is0())throw new Error("invalid recovery: point at infinify");return I.assertValidity(),I}hasHighS(){return b(this.s)}toBytes(m=x.format){if(Qt(m),m==="der")return _t(Pe.hexFromSig(this));const{r:T,s:N}=this,M=o.toBytes(T),D=o.toBytes(N);return m==="recovered"?(R(),ke(Uint8Array.of(this.assertRecovery()),M,D)):ke(M,D)}toHex(m){return tt(this.toBytes(m))}}const W=r.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const T=wt(m),N=m.length*8-c;return N>0?T>>BigInt(N):T},U=r.bits2int_modN||function(m){return o.create(W(m))},se=zt(c);function q(y){return no("num < 2^"+c,y,Ae,se),o.toBytes(y)}function X(y,m){return Y(y,void 0,"message"),m?Y(e(y),void 0,"prehashed message"):y}function ne(y,m,T){const{lowS:N,prehash:M,extraEntropy:D}=er(T,x);y=X(y,M);const $=U(y),P=o.fromBytes(m);if(!o.isValidNot0(P))throw new Error("invalid private key");const K=[q(P),q($)];if(D!=null&&D!==!1){const I=D===!0?t(_.secretKey):D;K.push(Y(I,void 0,"extraEntropy"))}const S=ke(...K),E=$;function k(I){const F=W(I);if(!o.isValidNot0(F))return;const V=o.inv(F),J=s.BASE.multiply(F).toAffine(),z=o.create(J.x);if(z===Ae)return;const j=o.create(V*o.create(E+z*P));if(j===Ae)return;let We=(J.x===z?0:2)|Number(J.y&Xe),nn=j;return N&&b(j)&&(nn=o.neg(j),We^=1),new L(z,nn,w?void 0:We)}return{seed:S,k2sig:k}}function G(y,m,T={}){const{seed:N,k2sig:M}=ne(y,m,T);return oo(e.outputLen,o.BYTES,n)(N,M).toBytes(T.format)}function B(y,m,T,N={}){const{lowS:M,prehash:D,format:$}=er(N,x);if(T=Y(T,void 0,"publicKey"),m=X(m,D),!Ht(y)){const P=y instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}C(y,$);try{const P=L.fromBytes(y,$),K=s.fromBytes(T);if(M&&P.hasHighS())return!1;const{r:S,s:E}=P,k=U(m),I=o.inv(E),F=o.create(k*I),V=o.create(S*I),J=s.BASE.multiplyUnsafe(F).add(K.multiplyUnsafe(V));return J.is0()?!1:o.create(J.x)===S}catch{return!1}}function H(y,m,T={}){const{prehash:N}=er(T,x);return m=X(m,N),L.fromBytes(y,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:g,lengths:_,Point:s,sign:G,verify:B,recoverPublicKey:H,Signature:L,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const tr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ko={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Os=BigInt(2);function Co(s){const e=tr.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,p=le(u,r,e)*u%e,g=le(p,r,e)*u%e,_=le(g,Os,e)*l%e,x=le(_,n,e)*_%e,w=le(x,i,e)*x%e,b=le(w,a,e)*w%e,A=le(b,c,e)*b%e,R=le(A,a,e)*w%e,C=le(R,r,e)*u%e,L=le(C,o,e)*x%e,W=le(L,t,e)*l%e,U=le(W,Os,e);if(!rr.eql(rr.sqr(U),s))throw new Error("Cannot find square root");return U}const rr=yt(tr.p,{sqrt:Co}),No=Ro(Io(tr,{Fp:rr,endo:ko}),to),Po=BigInt(0),rt=BigInt(1),Oo=BigInt(2),Lo=BigInt(7),Do=BigInt(256),Bo=BigInt(113),Ls=[],Ds=[],Bs=[];for(let s=0,e=rt,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],Ls.push(2*(5*t+r)),Ds.push((s+1)*(s+2)/2%64);let n=Po;for(let i=0;i<7;i++)e=(e<<rt^(e>>Lo)*Bo)%Do,e&Oo&&(n^=rt<<(rt<<BigInt(i))-rt);Bs.push(n)}const $s=zi(Bs,!0),$o=$s[0],Mo=$s[1],Ms=(s,e,r)=>r>32?Yi(s,e,r):Ji(s,e,r),Fs=(s,e,r)=>r>32?Xi(s,e,r):ji(s,e,r);function Fo(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],p=Ms(l,u,1)^r[a],g=Fs(l,u,1)^r[a+1];for(let _=0;_<50;_+=10)s[o+_]^=p,s[o+_+1]^=g}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=Ds[o],c=Ms(n,i,a),l=Fs(n,i,a),u=Ls[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=$o[t],s[1]^=Mo[t]}je(r)}class sr{constructor(e,r,t,n=!1,i=24){O(this,"state");O(this,"pos",0);O(this,"posOut",0);O(this,"finished",!1);O(this,"state32");O(this,"destroyed",!1);O(this,"blockLen");O(this,"suffix");O(this,"outputLen");O(this,"enableXOF",!1);O(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=$i(this.state)}clone(){return this._cloneInto()}keccak(){Zr(this.state32),Fo(this.state32,this.rounds),Zr(this.state32),this.posOut=0,this.pos=0}update(e){Je(this),Y(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Je(this,!1),Y(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Xr(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,je(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new sr(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Ws=((s,e,r,t={})=>ts(()=>new sr(e,s,r),t))(1,136,32),Wo=60;class Uo{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Li(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Wo<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Ai(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Bi(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
6
+ For security, you must continue with the same account.`,session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},hn={ko:un,en:fr};function ye(s="en",e){return hn[s]??fr}function pn(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const gr="crossx_access_token",xr="crossx_refresh_token",wr="crossx_user_info",At=class At{constructor(e,r,t,n,i,o,a,c,l=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this.getLocale=l,this._refreshPromise=null,this._migrated=!1;const u=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${u}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${u}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${u}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${u}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new f(h.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=pn(this.getLocale()),c=`${o}${i}`,l=c.includes("?")?"&":"?",u=`${c}${l}locale=${a}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${u}`);const p=await this.oauth.openAuth({authUrl:u,expectedOrigin:new URL(o).origin});r=p.token,t=p.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new f(h.OAUTH_POPUP_BLOCKED,i):new f(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const u=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=u.firebase)==null?void 0:t.sign_in_provider);const p=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=p.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const u=await this.crypto.verifyJWT(a);if(!u.valid)throw new f(h.AUTH_FAILED,"Access token 검증 실패");const p=u.payload;r={id:p.sub,email:p.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new f(h.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0,l=o instanceof Error?o.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:p,refreshToken:g}=await this.exchangeFirebaseToken(e,u);let _,x,w;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),x=(i=A.firebase)==null?void 0:i.sign_in_provider;const R=((o=A.firebase)==null?void 0:o.identities)??{};w=A.email??((a=R.email)==null?void 0:a[0]),x==="google.com"?_=(c=R["google.com"])==null?void 0:c[0]:x==="apple.com"&&(_=(l=R["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!_,"email:",w??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const A=this.crypto.decodeJWT(p);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const R=await this.crypto.verifyJWT(p);if(n=R.signatureVerified??!1,!R.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const C=R.payload,L=C.email??w??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",C.email??"(없음)","/ Firebase JWT:",w??"(없음)","/ OAuth 콜백:",r??"(없음)","→",L??"(없음)"),t={id:C.sub,email:L,signInProvider:x,providerSub:_},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??r,signInProvider:x,providerSub:_},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const b=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,b),await this.clearStoredRNBridgeSession(),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new f(h.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new f(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new f(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof f&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=At.REFRESH_RELOGIN_CODES.has(c.code);throw new f(u?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new f(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof f&&t.code===h.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof f&&e.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(wr);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(gr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(xr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(wr),await this.storage.remove(gr),await this.storage.remove(xr),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof f&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof f&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};At.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Rt=At;class _n{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class fn{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new f(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class kt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class gn{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new f(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class xn{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}function wn(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class be{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await be.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=be.getBridge(),!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new f(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,d.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=wn(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new f(h.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:n.walletAddress,walletName:o}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new f(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),r=(e.expiresAt-Date.now())/1e3;if(r<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof f)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new f(h.USER_REJECTED,"Firebase ID token request rejected by user",e):(d.error("[RNBridge] Firebase token request failed",e),new f(h.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof f?e:(d.error("[RNBridge] Fresh Firebase token request failed",e),new f(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new f(h.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const r=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((r.expiresAt-Date.now())/1e3<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof f?r:(d.warn("[RNBridge] Session restore Firebase token request failed",r),new f(h.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",r))}}getContext(){return this.context}isActive(){var r;if(!((r=this.context)!=null&&r.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new f(h.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var ot={environment:"production"};const He={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"}};function mn(s){const e=s.environment;return e&&e in He?He[e]:null}function mr(){try{if(typeof ot<"u"){const s=typeof ot=="string"?JSON.parse(ot):ot,e=mn(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in He)return He[s]}catch{}return He.production}const yn=2e3,yr=6e4,bn=1e3,Sn=1e4,vn="0x77359400",br="0x3B9ACA00",Sr=130,Ct=6,vr=18,Er=3e4,En=5*60*1e3,An=30*1e3,at=100,In="crossx-sdk-js/2.3.0-beta.3";function Ar(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Tn(s,e=Ct){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(vr),n=r/t,o=(r%t).toString().padStart(vr,"0"),a=Ar(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function ct(s,e,r,t=Ct){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(r),o=n/i,c=(n%i).toString().padStart(r,"0"),l=Ar(c.slice(0,t));return`${l?`${o}.${l}`:`${o}`} ${e}`}catch{return}}function Rn(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Sr)throw new f(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Sr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function kn(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Cn(s,e){const r=Nn(e);if(s==="0"){if(r!==void 0&&r!==0)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=s.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(r===void 0)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==n)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function Nn(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class Ke{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new f(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=ye(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!l)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.deps.pinStore.set(l);try{return await this.deps.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(u){if(this.deps.pinStore.clear(),u instanceof f){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return Ke.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof f&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=ye(this.deps.getLocale()??"en"),u=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.session_alert_title,message:l.alert_session_expired,email:u?this.deps.maskEmail(u,l.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=ye(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof f){if(t=Ke.parsePinError(n,r),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof f&&(t=Ke.parsePinError(n,r),t))continue;throw n}}}static parsePinError(e,r){if(e.code===h.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===h.PIN_INVALID)return{errorMessage:e.message};if(e.code===h.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=Ke.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Pn{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new f(h.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}}function On(s){return s==="google"||s==="apple"}class Ln{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=On(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((r=i.user)==null?void 0:r.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=ye(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.session_alert_title,message:l.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=ye(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.session_alert_apple_account):void 0;if(r instanceof f&&r.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof f&&r.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof f)||r.code!==h.SESSION_EXPIRED)throw r;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new f(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new f(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Dn{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const o=await this.deps.walletProvider.getAddresses(n);if(o.length>0){let c,l=!1;if(r){const p=o.find(g=>g.address.toLowerCase()===r.toLowerCase());p?c=p:(c={address:r,index:0},l=!0)}else e!==void 0?c=o.find(p=>p.index===e)??o[0]:c=o[0];l?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const u=!!r&&!!t&&c.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(c.address,c.index,u?{walletName:t}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class Bn{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(u===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!p){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(p.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const g=p.pinStatus;if(o=g.maxAttempts,i=o-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const _=g.lockExpiresAt*1e3,x=Math.max(1,Math.round((_-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${x}초, 메시지: ${w}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof f))throw p;if(p.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=ye(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:_?this.deps.maskEmail(_,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const g=p.details;if(o=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const _=((g==null?void 0:g.lockExpiresAt)??0)*1e3,x=Math.max(1,Math.round((_-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${x}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof f&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof f&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=ye(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:g?this.deps.maskEmail(g,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const w=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",w.address),w}catch(w){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",w),w}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class $n{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=_=>!(_!=null&&_.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,p,g]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],r):null,i?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const _=g;if(_){const x=br;c.maxFeePerGas=`0x${(BigInt(_)+BigInt(x)).toString(16)}`,c.maxPriorityFeePerGas=x,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",_,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=vn,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=br,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Mn{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new f(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof f)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Fn(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class Wn{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const n={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(n.walletName=t.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const r={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((i=e.user)==null?void 0:i.providerSub)??null,loginType:Fn((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Un{constructor(e){this.deps=e}async resolveAddress(e){const r=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===r){if(!t)throw new f(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Hn{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new f(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new f(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Kn{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",o);const a=await this.deps.migrationOrchestrator.handleMigrationFlow(o);if(a)return this.deps.setActiveWallet(a.address,0),{address:a.address};throw new f(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof f&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new f(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function Ir(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class Gn{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new f(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new f(h.TX_INVALID_PARAMS,"invalid param tx_hash");const n=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new f(h.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new f(h.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=Ir(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof f?c:new f(h.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const r=this.deps.getApiBaseUrl(),t=new URL(Ir(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new f(h.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof f?i:new f(h.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,r,t,n){const i=(n==null?void 0:n.maxRetries)??3,o=(n==null?void 0:n.retryDelayMs)??2e3;for(let a=0;a<i;a++)try{await this.registerTokenHistory(e,r,t);return}catch(c){if(c instanceof f&&c.message.includes("404")&&a<i-1){d.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(u=>setTimeout(u,o));continue}throw c}}handleError(e,r){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:h.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:h.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:h.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new f(n.code,n.message)}}function Nt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const r=s.indexOf("@");if(r<0)return"*".repeat(s.length||3);const t=s.substring(0,r),n=s.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Fe=class Fe extends xn{constructor(e,r,t,n,i,o,a,c,l,u,p){var g,_;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._bridgeSessionRestorePromise=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&_r(e.logger),this.confirmation=l,this.pinStore=p??new kt,this.stateManager=new Wn({setState:x=>{x.authenticated!==void 0&&(this.authenticated=x.authenticated),x.userId!==void 0&&(this.userId=x.userId),x.address!==void 0&&(this.address=x.address),x.activeWalletIndex!==void 0&&(this.activeWalletIndex=x.activeWalletIndex),x.userEmail!==void 0&&(this.userEmail=x.userEmail),x.providerSub!==void 0&&(this.providerSub=x.providerSub),x.loginType!==void 0&&(this.loginType=x.loginType),x.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=x.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:x,index:w,walletName:b})=>{const A={address:x,index:w};b!==void 0&&(A.walletName=b),this.emit("addressChanged",A)},emitAuthChanged:({isAuthenticated:x,address:w,userId:b})=>{this.emit("authChanged",{isAuthenticated:x,address:w,userId:b})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Fe.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ke({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Nt,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Pn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Dn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,w,b)=>this.setActiveWallet(x,w,b)}),this.migrationOrchestrator=new Bn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,w)=>this.migrateWalletUseCase.execute(x,w),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Nt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new $n({getActiveAddress:()=>this.address,estimateGas:(x,w)=>this.estimateGas(x,w),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,w,b)=>this.jsonRpc.call(x,w,b)}),this.signatureVerifier=new Mn(this.crypto),this.addressResolverService=new Un({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Hn({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Kn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,w)=>this.setActiveWallet(x,w),showWalletCreated:()=>{var x,w;return((w=(x=this.confirmation).showWalletCreatedPrompt)==null?void 0:w.call(x))??Promise.resolve()}}),this.tokenHistoryService=new Gn({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Ln({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:x=>{this._isRecoveringSession=x},setAuthenticated:x=>{this.authenticated=x},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:x=>this.signInUseCase.execute(x),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:x=>this.confirmation.showSessionAlert(x),clearAuthState:()=>this.clearAuthState(),applyAuthResult:x=>this.applyAuthResult(x),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:Nt}),this.chainRegistry=u,this.jsonRpc=new gn(u,i),this.signInUseCase=new Rt(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new _n(this.internalConfig,t,c),this.migrateWalletUseCase=new fn(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(_=a.setTokenRefresher)==null||_.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v2.3.0 초기화 중..."),this.confirmation.setMessages(ye(this._config.locale));try{const n=mr();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Fe.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const l=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),u=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(l)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,u?{walletName:u}:void 0);else try{await this.loadWalletAfterAuth(o,a,u)}catch(p){if(!(p instanceof f&&p.code===h.PIN_CANCELLED))throw p;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v2.3.0 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new f(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!be.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도");const e=new be({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof f&&r.code===h.USER_REJECTED?(d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession()||(this._isAuthenticatedViaRNBridge=!0,await this.signInUseCase.hasValidStoredAccessToken()))return null;d.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(d.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return d.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new f(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw d.error("[CROSSx] Bridge session restore token request failed:",e),new f(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return be.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");if(this._rnBridgeService){const t=await this._tryBridgeSignIn();if(t===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(t!=null&&t.success)return t}let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:an(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new f(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");r={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,r);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,r);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof f&&i.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r))}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",t)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...r,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof f&&t.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=be.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new f(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(t){t instanceof f&&t.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof f&&t.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof f?r:new f(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(n=>n.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof f?e:new f(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof f?r:new f(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(ye(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(r,i.signature,n.address),{chainId:e,signature:i.signature,message:r,address:n.address}}catch(i){throw i instanceof f?i:new f(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new f(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Cn(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return Rn(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof f?i:new f(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(Fe.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Tt(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return kn(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof f)throw o;const a=o instanceof Error?o.message:String(o);throw new f(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Tt(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async u=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,u)).txHash;const p=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return p.txHash??p.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,In).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof f)throw o;const a=o instanceof Error?o.message:String(o);throw new f(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??bn,i=Sn,o=t.timeoutMs??yr,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new f(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var w,b;if(this._isAuthenticatedViaRNBridge){const A=be.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((w=this._config.receiptPolling)==null?void 0:w.intervalMs)??yn,l=i??((b=this._config.receiptPolling)==null?void 0:b.timeoutMs)??yr,u=Tt(e),p=r.from??"";let g,_;const x=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{g=A;const R=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),C=r.value?BigInt(r.value):0n,L=ct(r.value,u.symbol,u.decimals,this._config.displayDecimals),W=ct("0x"+R.toString(16),u.symbol,u.decimals,this._config.displayDecimals),U=ct("0x"+(C+R).toString(16),u.symbol,u.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:A.from,to:A.to??r.to,amount:L,fees:W,total:U,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(_=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:p,to:r.to,amount:ct(r.value,u.symbol,u.decimals,this._config.displayDecimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:r.to},x),_)throw _;return{chainId:e,txHash:a,receipt:g}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs});return{chainId:r,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??t.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new f(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof f?n:new f(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new f(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:Tn(n,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new pr(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof f)throw n;const i=n instanceof Error?n.message:String(n);throw new f(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,r,t){const n=this.address;this.stateManager.setActiveWallet(e,r,t),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=be.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated){d.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const i=typeof t.walletName=="string"?t.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(n,0,{walletName:o}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=o)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),_r(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Fe.WALLET_PREF_KEY="wallet_preference",Fe.OFFCHAIN_CHAIN_ID="0";let lt=Fe;class qn{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Pt="crossx-sdk",Vn=1,_e="data",Oe="keys",dt="aes-primary",zn=12;class Tr{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,Vn);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_e)||i.createObjectStore(_e),i.objectStoreNames.contains(Oe)||i.createObjectStore(Oe)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Oe,dt);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Oe,dt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Pt)return null;try{const e=await this.openDB(Pt),r=e.transaction([Oe,_e],"readonly"),t=r.objectStore(Oe).get(dt),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(_e).getAll(),o=r.objectStore(_e).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Oe,dt,n);for(let l=0;l<c.length;l++)await this.idbPut(_e,String(c[l]),a[l]);return indexedDB.deleteDatabase(Pt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(zn);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(_e,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(_e,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(_e,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(_e)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const Ot=crypto,Rr=s=>s instanceof CryptoKey,ut=new TextEncoder,Qe=new TextDecoder;function Jn(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const jn=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Qe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return jn(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class re extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}re.code="ERR_JOSE_GENERIC";class he extends re{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Lt extends re{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}Lt.code="ERR_JWT_EXPIRED";class kr extends re{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}kr.code="ERR_JOSE_ALG_NOT_ALLOWED";class fe extends re{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}fe.code="ERR_JOSE_NOT_SUPPORTED";class Yn extends re{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}Yn.code="ERR_JWE_DECRYPTION_FAILED";class Xn extends re{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Xn.code="ERR_JWE_INVALID";class ee extends re{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}ee.code="ERR_JWS_INVALID";class ge extends re{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ge.code="ERR_JWT_INVALID";class Zn extends re{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Zn.code="ERR_JWK_INVALID";class Dt extends re{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Dt.code="ERR_JWKS_INVALID";class Bt extends re{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Bt.code="ERR_JWKS_NO_MATCHING_KEY";class Cr extends re{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Cr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Nr extends re{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}Nr.code="ERR_JWKS_TIMEOUT";class Pr extends re{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Pr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function xe(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function et(s,e){return s.name===e}function $t(s){return parseInt(s.name.slice(4),10)}function Qn(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ei(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function ti(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!et(s.algorithm,"HMAC"))throw xe("HMAC");const t=parseInt(e.slice(2),10);if($t(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!et(s.algorithm,"RSASSA-PKCS1-v1_5"))throw xe("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if($t(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!et(s.algorithm,"RSA-PSS"))throw xe("RSA-PSS");const t=parseInt(e.slice(2),10);if($t(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw xe("Ed25519 or Ed448");break}case"Ed25519":{if(!et(s.algorithm,"Ed25519"))throw xe("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!et(s.algorithm,"ECDSA"))throw xe("ECDSA");const t=Qn(e);if(s.algorithm.namedCurve!==t)throw xe(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ei(s,r)}function Or(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const Lr=(s,...e)=>Or("Key must be ",s,...e);function Dr(s,e,...r){return Or(`Key for the ${s} algorithm must be `,e,...r)}const Br=s=>Rr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ht=["CryptoKey"],ri=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function si(s){return typeof s=="object"&&s!==null}function Se(s){if(!si(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const ni=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ge(s){return Se(s)&&typeof s.kty=="string"}function ii(s){return s.kty!=="oct"&&typeof s.d=="string"}function oi(s){return s.kty!=="oct"&&typeof s.d>"u"}function ai(s){return Ge(s)&&s.kty==="oct"&&typeof s.k=="string"}function ci(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new fe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new fe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const $r=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=ci(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,Ot.subtle.importKey("jwk",n,...t)},Mr=s=>Re(s);let qe,Ve;const Fr=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",pt=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await $r({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},li={normalizePublicKey:(s,e)=>{if(Fr(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Mr(r.k):(Ve||(Ve=new WeakMap),pt(Ve,s,r,e))}return Ge(s)?s.k?Re(s.k):(Ve||(Ve=new WeakMap),pt(Ve,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(Fr(s)){let r=s.export({format:"jwk"});return r.k?Mr(r.k):(qe||(qe=new WeakMap),pt(qe,s,r,e))}return Ge(s)?s.k?Re(s.k):(qe||(qe=new WeakMap),pt(qe,s,s,e,!0)):s}};async function Wr(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new fe('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return $r({...s,alg:e});default:throw new fe('Unsupported "kty" (Key Type) Parameter value')}}const ze=s=>s==null?void 0:s[Symbol.toStringTag],Mt=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},di=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&Ge(e)){if(ai(e)&&Mt(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Br(e))throw new TypeError(Dr(s,e,...ht,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${ze(e)} instances for symmetric algorithms must be of type "secret"`)}},ui=(s,e,r,t)=>{if(t&&Ge(e))switch(r){case"sign":if(ii(e)&&Mt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(oi(e)&&Mt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Br(e))throw new TypeError(Dr(s,e,...ht,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${ze(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${ze(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${ze(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${ze(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${ze(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ur(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?di(e,r,t,s):ui(e,r,t,s)}Ur.bind(void 0,!1);const Hr=Ur.bind(void 0,!0);function hi(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new fe(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const pi=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function _i(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new fe(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function fi(s,e,r){if(e=await li.normalizePublicKey(e,s),Rr(e))return ti(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(Lr(e,...ht));return Ot.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(Lr(e,...ht,"Uint8Array","JSON Web Key"))}const gi=async(s,e,r,t)=>{const n=await fi(s,e,"verify");ni(s,n);const i=_i(s,n.algorithm);try{return await Ot.subtle.verify(i,n,r,t)}catch{return!1}};async function xi(s,e,r){if(!Se(s))throw new ee("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new ee('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new ee("JWS Protected Header incorrect type");if(s.payload===void 0)throw new ee("JWS Payload missing");if(typeof s.signature!="string")throw new ee("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new ee("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const w=Re(s.protected);t=JSON.parse(Qe.decode(w))}catch{throw new ee("JWS Protected Header is invalid")}if(!ri(t,s.header))throw new ee("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=hi(ee,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new ee('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new ee('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&pi("algorithms",r.algorithms);if(c&&!c.has(a))throw new kr('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new ee("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new ee("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,Hr(a,e,"verify"),Ge(e)&&(e=await Wr(e,a))):Hr(a,e,"verify");const u=Jn(ut.encode(s.protected??""),ut.encode("."),typeof s.payload=="string"?ut.encode(s.payload):s.payload);let p;try{p=Re(s.signature)}catch{throw new ee("Failed to base64url decode the signature")}if(!await gi(a,e,p,u))throw new Pr;let _;if(o)try{_=Re(s.payload)}catch{throw new ee("Failed to base64url decode the payload")}else typeof s.payload=="string"?_=ut.encode(s.payload):_=s.payload;const x={payload:_};return s.protected!==void 0&&(x.protectedHeader=t),s.header!==void 0&&(x.unprotectedHeader=s.header),l?{...x,key:e}:x}async function wi(s,e,r){if(s instanceof Uint8Array&&(s=Qe.decode(s)),typeof s!="string")throw new ee("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new ee("Invalid Compact JWS");const a=await xi({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const mi=s=>Math.floor(s.getTime()/1e3),Kr=60,Gr=Kr*60,Ft=Gr*24,yi=Ft*7,bi=Ft*365.25,Si=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,qr=s=>{const e=Si.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*Kr);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Gr);break;case"day":case"days":case"d":n=Math.round(r*Ft);break;case"week":case"weeks":case"w":n=Math.round(r*yi);break;default:n=Math.round(r*bi);break}return e[1]==="-"||e[4]==="ago"?-n:n},Vr=s=>s.toLowerCase().replace(/^application\//,""),vi=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Ei=(s,e,r={})=>{let t;try{t=JSON.parse(Qe.decode(e))}catch{}if(!Se(t))throw new ge("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||Vr(s.typ)!==Vr(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const x of new Set(u.reverse()))if(!(x in t))throw new he(`missing required "${x}" claim`,t,x,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!vi(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=qr(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:g}=r,_=mi(g||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>_+p)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=_-p)throw new Lt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const x=_-t.iat,w=typeof l=="number"?l:qr(l);if(x-p>w)throw new Lt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(x<0-p)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Ai(s,e,r){var o;const t=await wi(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new ge("JWTs MUST NOT use unencoded payload");const i={payload:Ei(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Ii(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new fe('Unsupported "alg" value for a JSON Web Key Set')}}function Ti(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Ri)}function Ri(s){return Se(s)}function zr(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class ki{constructor(e){if(this._cached=new WeakMap,!Ti(e))throw new Dt("JSON Web Key Set malformed");this._jwks=zr(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=Ii(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Bt;if(c!==1){const l=new Cr,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await Jr(u,p,t)}catch{}},l}return Jr(this._cached,a,t)}}async function Jr(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await Wr({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new Dt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function jr(s){const e=new ki(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>zr(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Ci=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new Nr:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new re("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new re("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Ni(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Wt;(typeof navigator>"u"||!((sn=(It=navigator.userAgent)==null?void 0:It.startsWith)!=null&&sn.call(It,"Mozilla/5.0 ")))&&(Wt="jose/v5.10.0");const Ut=Symbol();function Pi(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class Oi{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Ut])!==void 0&&(this._cache=r==null?void 0:r[Ut],Pi(r==null?void 0:r[Ut],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=jr(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Bt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Ni()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Wt&&!e.has("User-Agent")&&(e.set("User-Agent",Wt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Ci(this._url,this._timeoutDuration,this._options).then(r=>{this._local=jr(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Li(s,e){const r=new Oi(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Di=Re;function Bi(s){if(typeof s!="string")throw new ge("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new ge("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ge("Invalid JWT");if(!e)throw new ge("JWTs must contain a payload");let t;try{t=Di(e)}catch{throw new ge("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Qe.decode(t))}catch{throw new ge("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new ge("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ht(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function Y(s,e,r=""){const t=Ht(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function Yr(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function Je(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Xr(s,e){Y(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function $i(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function je(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Kt(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function we(s,e){return s<<32-e|s>>>e}const Mi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Fi(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Wi(s){for(let e=0;e<s.length;e++)s[e]=Fi(s[e]);return s}const Zr=Mi?s=>s:Wi,Qr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ui=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tt(s){if(Y(s),Qr)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Ui[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function es(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function _t(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Qr)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=es(s.charCodeAt(i)),a=es(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ke(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];Y(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function ts(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function rs(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const Hi=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Ki(s,e,r){return s&e^~s&r}function Gi(s,e,r){return s&e^s&r^e&r}class qi{constructor(e,r,t,n){O(this,"blockLen");O(this,"outputLen");O(this,"padOffset");O(this,"isLE");O(this,"buffer");O(this,"view");O(this,"finished",!1);O(this,"length",0);O(this,"pos",0);O(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Kt(this.buffer)}update(e){Je(this),Y(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Kt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Je(this),Xr(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,je(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)r[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Kt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,u[p],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ft=BigInt(2**32-1),ss=BigInt(32);function Vi(s,e=!1){return e?{h:Number(s&ft),l:Number(s>>ss&ft)}:{h:Number(s>>ss&ft)|0,l:Number(s&ft)|0}}function zi(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=Vi(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const Ji=(s,e,r)=>s<<r|e>>>32-r,ji=(s,e,r)=>e<<r|s>>>32-r,Yi=(s,e,r)=>e<<r-32|s>>>64-r,Xi=(s,e,r)=>s<<r-32|e>>>64-r,Zi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ne=new Uint32Array(64);class Qi extends qi{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let p=0;p<16;p++,r+=4)Ne[p]=e.getUint32(r,!1);for(let p=16;p<64;p++){const g=Ne[p-15],_=Ne[p-2],x=we(g,7)^we(g,18)^g>>>3,w=we(_,17)^we(_,19)^_>>>10;Ne[p]=w+Ne[p-7]+x+Ne[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let p=0;p<64;p++){const g=we(a,6)^we(a,11)^we(a,25),_=u+g+Ki(a,c,l)+Zi[p]+Ne[p]|0,w=(we(t,2)^we(t,13)^we(t,22))+Gi(t,n,i)|0;u=l,l=c,c=a,a=o+_|0,o=i,i=n,n=t,t=_+w|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){je(Ne)}destroy(){this.set(0,0,0,0,0,0,0,0),je(this.buffer)}}class eo extends Qi{constructor(){super(32);O(this,"A",Ce[0]|0);O(this,"B",Ce[1]|0);O(this,"C",Ce[2]|0);O(this,"D",Ce[3]|0);O(this,"E",Ce[4]|0);O(this,"F",Ce[5]|0);O(this,"G",Ce[6]|0);O(this,"H",Ce[7]|0)}}const to=ts(()=>new eo,Hi(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gt=BigInt(0),qt=BigInt(1);function gt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function ns(s){if(typeof s=="bigint"){if(!mt(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function xt(s){const e=ns(s).toString(16);return e.length&1?"0"+e:e}function is(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Gt:BigInt("0x"+s)}function wt(s){return is(tt(s))}function os(s){return is(tt(ro(Y(s)).reverse()))}function Vt(s,e){ve(e),s=ns(s);const r=_t(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function as(s,e){return Vt(s,e).reverse()}function ro(s){return Uint8Array.from(s)}const mt=s=>typeof s=="bigint"&&Gt<=s;function so(s,e,r){return mt(s)&&mt(e)&&mt(r)&&e<=s&&s<r}function no(s,e,r,t){if(!so(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function io(s){let e;for(e=0;s>Gt;s>>=qt,e+=1);return e}const zt=s=>(qt<<BigInt(s))-qt;function oo(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=b=>new Uint8Array(b),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const p=()=>{c.fill(1),l.fill(0),u=0},g=(...b)=>r(l,ke(c,...b)),_=(b=n)=>{l=g(i,b),c=g(),b.length!==0&&(l=g(o,b),c=g())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0;const A=[];for(;b<e;){c=g();const R=c.slice();A.push(R),b+=c.length}return ke(...A)};return(b,A)=>{p(),_(b);let R;for(;!(R=A(x()));)_();return p(),R}}function Jt(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function cs(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ae=BigInt(0),ie=BigInt(1),Le=BigInt(2),ls=BigInt(3),ds=BigInt(4),us=BigInt(5),ao=BigInt(7),hs=BigInt(8),co=BigInt(9),ps=BigInt(16);function pe(s,e){const r=s%e;return r>=ae?r:e+r}function le(s,e,r){let t=s;for(;e-- >ae;)t*=t,t%=r;return t}function _s(s,e){if(s===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let r=pe(s,e),t=e,n=ae,i=ie;for(;r!==ae;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==ie)throw new Error("invert: does not exist");return pe(n,e)}function jt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function fs(s,e){const r=(s.ORDER+ie)/ds,t=s.pow(e,r);return jt(s,t,e),t}function lo(s,e){const r=(s.ORDER-us)/hs,t=s.mul(e,Le),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Le),n),a=s.mul(i,s.sub(o,s.ONE));return jt(s,a,e),a}function uo(s){const e=yt(s),r=gs(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+ao)/ps;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const p=a.mul(l,n),g=a.mul(l,i),_=a.eql(a.sqr(u),c),x=a.eql(a.sqr(p),c);l=a.cmov(l,u,_),u=a.cmov(g,p,x);const w=a.eql(a.sqr(u),c),b=a.cmov(l,u,w);return jt(a,b,c),b}}function gs(s){if(s<ls)throw new Error("sqrt is not defined for small field");let e=s-ie,r=0;for(;e%Le===ae;)e/=Le,r++;let t=Le;const n=yt(s);for(;ws(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return fs;let i=n.pow(t,e);const o=(e+ie)/Le;return function(c,l){if(c.is0(l))return l;if(ws(c,l)!==1)throw new Error("Cannot find square root");let u=r,p=c.mul(c.ONE,i),g=c.pow(l,e),_=c.pow(l,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let x=1,w=c.sqr(g);for(;!c.eql(w,c.ONE);)if(x++,w=c.sqr(w),x===u)throw new Error("Cannot find square root");const b=ie<<BigInt(u-x-1),A=c.pow(p,b);u=x,p=c.sqr(A),g=c.mul(g,p),_=c.mul(_,A)}return _}}function ho(s){return s%ds===ls?fs:s%hs===us?lo:s%ps===co?uo(s):gs(s)}const po=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function _o(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=po.reduce((t,n)=>(t[n]="function",t),e);return Jt(s,r),s}function fo(s,e,r){if(r<ae)throw new Error("invalid exponent, negatives unsupported");if(r===ae)return s.ONE;if(r===ie)return e;let t=s.ONE,n=e;for(;r>ae;)r&ie&&(t=s.mul(t,n)),n=s.sqr(n),r>>=ie;return t}function xs(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function ws(s,e){const r=(s.ORDER-ie)/Le,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function go(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class xo{constructor(e,r={}){O(this,"ORDER");O(this,"BITS");O(this,"BYTES");O(this,"isLE");O(this,"ZERO",ae);O(this,"ONE",ie);O(this,"_lengths");O(this,"_sqrt");O(this,"_mod");var o;if(e<=ae)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=go(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return pe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ie)===ie}neg(e){return pe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return pe(e*e,this.ORDER)}add(e,r){return pe(e+r,this.ORDER)}sub(e,r){return pe(e-r,this.ORDER)}mul(e,r){return pe(e*r,this.ORDER)}pow(e,r){return fo(this,e,r)}div(e,r){return pe(e*_s(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return _s(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=ho(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?as(e,this.BYTES):Vt(e,this.BYTES)}fromBytes(e,r=!1){Y(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?os(e):wt(e);if(a&&(c=pe(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return xs(this,e)}cmov(e,r,t){return t?r:e}}function yt(s,e={}){return new xo(s,e)}function ms(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function ys(s){const e=ms(s);return e+Math.ceil(e/2)}function wo(s,e,r=!1){Y(s);const t=s.length,n=ms(e),i=ys(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?os(s):wt(s),a=pe(o,e-ie)+ie;return r?as(a,n):Vt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ye=BigInt(0),De=BigInt(1);function bt(s,e){const r=e.negate();return s?r:e}function bs(s,e){const r=xs(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function Ss(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Yt(s,e){Ss(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=zt(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function vs(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,p=a===0,g=a<0,_=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:g,isNegF:_,offsetF:l}}const Xt=new WeakMap,Es=new WeakMap;function Zt(s){return Es.get(s)||1}function As(s){if(s!==Ye)throw new Error("invalid wNAF")}class mo{constructor(e,r){O(this,"BASE");O(this,"ZERO");O(this,"Fn");O(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Ye;)r&De&&(t=t.add(n)),n=n.double(),r>>=De;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Yt(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Yt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:g,offsetF:_}=vs(t,a,o);t=c,u?i=i.add(bt(g,r[_])):n=n.add(bt(p,r[l]))}return As(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=Yt(e,this.bits);for(let o=0;o<i.windows&&t!==Ye;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=vs(t,o,i);if(t=a,!l){const p=r[c];n=n.add(u?p.negate():p)}}return As(t),n}getPrecomputes(e,r,t){let n=Xt.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),Xt.set(r,n))),n}cached(e,r,t){const n=Zt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=Zt(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){Ss(r,this.bits),Es.set(e,r),Xt.delete(e)}hasCache(e){return Zt(e)!==1}}function yo(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Ye||t>Ye;)r&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),r>>=De,t>>=De;return{p1:i,p2:o}}function Is(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return _o(e),e}else return yt(s,{isLE:r})}function bo(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ye))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Is(e.p,r.Fp,t),i=Is(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function So(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class Ts{constructor(e,r){O(this,"oHash");O(this,"iHash");O(this,"blockLen");O(this,"outputLen");O(this,"finished",!1);O(this,"destroyed",!1);if(Yr(e),Y(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),je(n)}update(e){return Je(this),this.iHash.update(e),this}digestInto(e){Je(this),Y(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Rs=(s,e,r)=>new Ts(s,e).update(r).digest();Rs.create=(s,e)=>new Ts(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ks=(s,e)=>(s+(s>=0?e:-e)/Cs)/e;function vo(s,e,r){const[[t,n],[i,o]]=e,a=ks(o*s,r),c=ks(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const p=l<Ae,g=u<Ae;p&&(l=-l),g&&(u=-u);const _=zt(Math.ceil(io(r)/2))+Xe;if(l<Ae||l>=_||u<Ae||u>=_)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:p,k1:l,k2neg:g,k2:u}}function Qt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function er(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return gt(r.lowS,"lowS"),gt(r.prehash,"prehash"),r.format!==void 0&&Qt(r.format),r}class Eo extends Error{constructor(e=""){super(e)}}const Pe={Err:Eo,_tlv:{encode:(s,e)=>{const{Err:r}=Pe;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=xt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?xt(n.length/2|128):"";return xt(s)+i+n+e},decode(s,e){const{Err:r}=Pe;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=Pe;if(s<Ae)throw new e("integer: negative integers are not allowed");let r=xt(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=Pe;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return wt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Pe,n=Y(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=Pe,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ae=BigInt(0),Xe=BigInt(1),Cs=BigInt(2),St=BigInt(3),Ao=BigInt(4);function Io(s,e={}){const r=bo("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Jt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ps(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(H,y,m){const{x:T,y:N}=y.toAffine(),M=t.toBytes(T);if(gt(m,"isCompressed"),m){u();const D=!t.isOdd(N);return ke(Ns(D),M)}else return ke(Uint8Array.of(4),M,t.toBytes(N))}function g(H){Y(H,void 0,"Point");const{publicKey:y,publicKeyUncompressed:m}=l,T=H.length,N=H[0],M=H.subarray(1);if(T===y&&(N===2||N===3)){const D=t.fromBytes(M);if(!t.isValid(D))throw new Error("bad point: is not on curve, wrong x");const $=w(D);let P;try{P=t.sqrt($)}catch(E){const k=E instanceof Error?": "+E.message:"";throw new Error("bad point: is not on curve, sqrt error"+k)}u();const K=t.isOdd(P);return(N&1)===1!==K&&(P=t.neg(P)),{x:D,y:P}}else if(T===m&&N===4){const D=t.BYTES,$=t.fromBytes(M.subarray(0,D)),P=t.fromBytes(M.subarray(D,D*2));if(!b($,P))throw new Error("bad point: is not on curve");return{x:$,y:P}}else throw new Error(`bad point: got length ${T}, expected compressed=${y} or uncompressed=${m}`)}const _=e.toBytes||p,x=e.fromBytes||g;function w(H){const y=t.sqr(H),m=t.mul(y,H);return t.add(t.add(m,t.mul(H,i.a)),i.b)}function b(H,y){const m=t.sqr(y),T=w(H);return t.eql(m,T)}if(!b(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,St),Ao),R=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,R)))throw new Error("bad curve params: a or b");function C(H,y,m=!1){if(!t.isValid(y)||m&&t.is0(y))throw new Error(`bad point coordinate ${H}`);return y}function L(H){if(!(H instanceof X))throw new Error("Weierstrass Point expected")}function W(H){if(!c||!c.basises)throw new Error("no endo");return vo(H,c.basises,n.ORDER)}const U=cs((H,y)=>{const{X:m,Y:T,Z:N}=H;if(t.eql(N,t.ONE))return{x:m,y:T};const M=H.is0();y==null&&(y=M?t.ONE:t.inv(N));const D=t.mul(m,y),$=t.mul(T,y),P=t.mul(N,y);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:D,y:$}}),se=cs(H=>{if(H.is0()){if(e.allowInfinityPoint&&!t.is0(H.Y))return;throw new Error("bad point: ZERO")}const{x:y,y:m}=H.toAffine();if(!t.isValid(y)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!b(y,m))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function q(H,y,m,T,N){return m=new X(t.mul(m.X,H),m.Y,m.Z),y=bt(T,y),m=bt(N,m),y.add(m)}const B=class B{constructor(y,m,T){O(this,"X");O(this,"Y");O(this,"Z");this.X=C("x",y),this.Y=C("y",m,!0),this.Z=C("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){const{x:m,y:T}=y||{};if(!y||!t.isValid(m)||!t.isValid(T))throw new Error("invalid affine point");if(y instanceof B)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(T)?B.ZERO:new B(m,T,t.ONE)}static fromBytes(y){const m=B.fromAffine(x(Y(y,void 0,"point")));return m.assertValidity(),m}static fromHex(y){return B.fromBytes(_t(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,m=!0){return G.createCache(this,y),m||this.multiply(St),this}assertValidity(){se(this)}hasEvenY(){const{y}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(y)}equals(y){L(y);const{X:m,Y:T,Z:N}=this,{X:M,Y:D,Z:$}=y,P=t.eql(t.mul(m,$),t.mul(M,N)),K=t.eql(t.mul(T,$),t.mul(D,N));return P&&K}negate(){return new B(this.X,t.neg(this.Y),this.Z)}double(){const{a:y,b:m}=i,T=t.mul(m,St),{X:N,Y:M,Z:D}=this;let $=t.ZERO,P=t.ZERO,K=t.ZERO,S=t.mul(N,N),E=t.mul(M,M),k=t.mul(D,D),I=t.mul(N,M);return I=t.add(I,I),K=t.mul(N,D),K=t.add(K,K),$=t.mul(y,K),P=t.mul(T,k),P=t.add($,P),$=t.sub(E,P),P=t.add(E,P),P=t.mul($,P),$=t.mul(I,$),K=t.mul(T,K),k=t.mul(y,k),I=t.sub(S,k),I=t.mul(y,I),I=t.add(I,K),K=t.add(S,S),S=t.add(K,S),S=t.add(S,k),S=t.mul(S,I),P=t.add(P,S),k=t.mul(M,D),k=t.add(k,k),S=t.mul(k,I),$=t.sub($,S),K=t.mul(k,E),K=t.add(K,K),K=t.add(K,K),new B($,P,K)}add(y){L(y);const{X:m,Y:T,Z:N}=this,{X:M,Y:D,Z:$}=y;let P=t.ZERO,K=t.ZERO,S=t.ZERO;const E=i.a,k=t.mul(i.b,St);let I=t.mul(m,M),F=t.mul(T,D),V=t.mul(N,$),J=t.add(m,T),z=t.add(M,D);J=t.mul(J,z),z=t.add(I,F),J=t.sub(J,z),z=t.add(m,N);let j=t.add(M,$);return z=t.mul(z,j),j=t.add(I,V),z=t.sub(z,j),j=t.add(T,N),P=t.add(D,$),j=t.mul(j,P),P=t.add(F,V),j=t.sub(j,P),S=t.mul(E,z),P=t.mul(k,V),S=t.add(P,S),P=t.sub(F,S),S=t.add(F,S),K=t.mul(P,S),F=t.add(I,I),F=t.add(F,I),V=t.mul(E,V),z=t.mul(k,z),F=t.add(F,V),V=t.sub(I,V),V=t.mul(E,V),z=t.add(z,V),I=t.mul(F,z),K=t.add(K,I),I=t.mul(j,z),P=t.mul(J,P),P=t.sub(P,I),I=t.mul(J,F),S=t.mul(j,S),S=t.add(S,I),new B(P,K,S)}subtract(y){return this.add(y.negate())}is0(){return this.equals(B.ZERO)}multiply(y){const{endo:m}=e;if(!n.isValidNot0(y))throw new Error("invalid scalar: out of range");let T,N;const M=D=>G.cached(this,D,$=>bs(B,$));if(m){const{k1neg:D,k1:$,k2neg:P,k2:K}=W(y),{p:S,f:E}=M($),{p:k,f:I}=M(K);N=E.add(I),T=q(m.beta,S,k,D,P)}else{const{p:D,f:$}=M(y);T=D,N=$}return bs(B,[T,N])[0]}multiplyUnsafe(y){const{endo:m}=e,T=this;if(!n.isValid(y))throw new Error("invalid scalar: out of range");if(y===Ae||T.is0())return B.ZERO;if(y===Xe)return T;if(G.hasCache(this))return this.multiply(y);if(m){const{k1neg:N,k1:M,k2neg:D,k2:$}=W(y),{p1:P,p2:K}=yo(B,T,M,$);return q(m.beta,P,K,N,D)}else return G.unsafe(T,y)}toAffine(y){return U(this,y)}isTorsionFree(){const{isTorsionFree:y}=e;return o===Xe?!0:y?y(B,this):G.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:y}=e;return o===Xe?this:y?y(B,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return gt(y,"isCompressed"),this.assertValidity(),_(B,this,y)}toHex(y=!0){return tt(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};O(B,"BASE",new B(i.Gx,i.Gy,t.ONE)),O(B,"ZERO",new B(t.ZERO,t.ONE,t.ZERO)),O(B,"Fp",t),O(B,"Fn",n);let X=B;const ne=n.BITS,G=new mo(X,e.endo?Math.ceil(ne/2):ne);return X.BASE.precompute(8),X}function Ns(s){return Uint8Array.of(s?2:3)}function Ps(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function To(s,e={}){const{Fn:r}=s,t=e.randomBytes||rs,n=Object.assign(Ps(s.Fp,r),{seed:ys(r.ORDER)});function i(_){try{const x=r.fromBytes(_);return r.isValidNot0(x)}catch{return!1}}function o(_,x){const{publicKey:w,publicKeyUncompressed:b}=n;try{const A=_.length;return x===!0&&A!==w||x===!1&&A!==b?!1:!!s.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return wo(Y(_,n.seed,"seed"),r.ORDER)}function c(_,x=!0){return s.BASE.multiply(r.fromBytes(_)).toBytes(x)}function l(_){const{secretKey:x,publicKey:w,publicKeyUncompressed:b}=n;if(!Ht(_)||"_lengths"in r&&r._lengths||x===w)return;const A=Y(_,void 0,"key").length;return A===w||A===b}function u(_,x,w=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const b=r.fromBytes(_);return s.fromBytes(x).multiply(b).toBytes(w)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=So(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:g,Point:s,utils:p,lengths:n})}function Ro(s,e,r={}){Yr(e),Jt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||rs,n=r.hmac||((y,m)=>Rs(e,y,m)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:g,lengths:_}=To(s,r),x={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},w=a*Cs<i.ORDER;function b(y){const m=a>>Xe;return y>m}function A(y,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return m}function R(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function C(y,m){Qt(m);const T=_.signature,N=m==="compact"?T:m==="recovered"?T+1:void 0;return Y(y,N)}class L{constructor(m,T,N){O(this,"r");O(this,"s");O(this,"recovery");if(this.r=A("r",m),this.s=A("s",T),N!=null){if(R(),![0,1,2,3].includes(N))throw new Error("invalid recovery id");this.recovery=N}Object.freeze(this)}static fromBytes(m,T=x.format){C(m,T);let N;if(T==="der"){const{r:P,s:K}=Pe.toSig(Y(m));return new L(P,K)}T==="recovered"&&(N=m[0],T="compact",m=m.subarray(1));const M=_.signature/2,D=m.subarray(0,M),$=m.subarray(M,M*2);return new L(o.fromBytes(D),o.fromBytes($),N)}static fromHex(m,T){return this.fromBytes(_t(m),T)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new L(this.r,this.s,m)}recoverPublicKey(m){const{r:T,s:N}=this,M=this.assertRecovery(),D=M===2||M===3?T+a:T;if(!i.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const $=i.toBytes(D),P=s.fromBytes(ke(Ns((M&1)===0),$)),K=o.inv(D),S=U(Y(m,void 0,"msgHash")),E=o.create(-S*K),k=o.create(N*K),I=s.BASE.multiplyUnsafe(E).add(P.multiplyUnsafe(k));if(I.is0())throw new Error("invalid recovery: point at infinify");return I.assertValidity(),I}hasHighS(){return b(this.s)}toBytes(m=x.format){if(Qt(m),m==="der")return _t(Pe.hexFromSig(this));const{r:T,s:N}=this,M=o.toBytes(T),D=o.toBytes(N);return m==="recovered"?(R(),ke(Uint8Array.of(this.assertRecovery()),M,D)):ke(M,D)}toHex(m){return tt(this.toBytes(m))}}const W=r.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const T=wt(m),N=m.length*8-c;return N>0?T>>BigInt(N):T},U=r.bits2int_modN||function(m){return o.create(W(m))},se=zt(c);function q(y){return no("num < 2^"+c,y,Ae,se),o.toBytes(y)}function X(y,m){return Y(y,void 0,"message"),m?Y(e(y),void 0,"prehashed message"):y}function ne(y,m,T){const{lowS:N,prehash:M,extraEntropy:D}=er(T,x);y=X(y,M);const $=U(y),P=o.fromBytes(m);if(!o.isValidNot0(P))throw new Error("invalid private key");const K=[q(P),q($)];if(D!=null&&D!==!1){const I=D===!0?t(_.secretKey):D;K.push(Y(I,void 0,"extraEntropy"))}const S=ke(...K),E=$;function k(I){const F=W(I);if(!o.isValidNot0(F))return;const V=o.inv(F),J=s.BASE.multiply(F).toAffine(),z=o.create(J.x);if(z===Ae)return;const j=o.create(V*o.create(E+z*P));if(j===Ae)return;let We=(J.x===z?0:2)|Number(J.y&Xe),nn=j;return N&&b(j)&&(nn=o.neg(j),We^=1),new L(z,nn,w?void 0:We)}return{seed:S,k2sig:k}}function G(y,m,T={}){const{seed:N,k2sig:M}=ne(y,m,T);return oo(e.outputLen,o.BYTES,n)(N,M).toBytes(T.format)}function B(y,m,T,N={}){const{lowS:M,prehash:D,format:$}=er(N,x);if(T=Y(T,void 0,"publicKey"),m=X(m,D),!Ht(y)){const P=y instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}C(y,$);try{const P=L.fromBytes(y,$),K=s.fromBytes(T);if(M&&P.hasHighS())return!1;const{r:S,s:E}=P,k=U(m),I=o.inv(E),F=o.create(k*I),V=o.create(S*I),J=s.BASE.multiplyUnsafe(F).add(K.multiplyUnsafe(V));return J.is0()?!1:o.create(J.x)===S}catch{return!1}}function H(y,m,T={}){const{prehash:N}=er(T,x);return m=X(m,N),L.fromBytes(y,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:g,lengths:_,Point:s,sign:G,verify:B,recoverPublicKey:H,Signature:L,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const tr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},ko={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Os=BigInt(2);function Co(s){const e=tr.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,p=le(u,r,e)*u%e,g=le(p,r,e)*u%e,_=le(g,Os,e)*l%e,x=le(_,n,e)*_%e,w=le(x,i,e)*x%e,b=le(w,a,e)*w%e,A=le(b,c,e)*b%e,R=le(A,a,e)*w%e,C=le(R,r,e)*u%e,L=le(C,o,e)*x%e,W=le(L,t,e)*l%e,U=le(W,Os,e);if(!rr.eql(rr.sqr(U),s))throw new Error("Cannot find square root");return U}const rr=yt(tr.p,{sqrt:Co}),No=Ro(Io(tr,{Fp:rr,endo:ko}),to),Po=BigInt(0),rt=BigInt(1),Oo=BigInt(2),Lo=BigInt(7),Do=BigInt(256),Bo=BigInt(113),Ls=[],Ds=[],Bs=[];for(let s=0,e=rt,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],Ls.push(2*(5*t+r)),Ds.push((s+1)*(s+2)/2%64);let n=Po;for(let i=0;i<7;i++)e=(e<<rt^(e>>Lo)*Bo)%Do,e&Oo&&(n^=rt<<(rt<<BigInt(i))-rt);Bs.push(n)}const $s=zi(Bs,!0),$o=$s[0],Mo=$s[1],Ms=(s,e,r)=>r>32?Yi(s,e,r):Ji(s,e,r),Fs=(s,e,r)=>r>32?Xi(s,e,r):ji(s,e,r);function Fo(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],p=Ms(l,u,1)^r[a],g=Fs(l,u,1)^r[a+1];for(let _=0;_<50;_+=10)s[o+_]^=p,s[o+_+1]^=g}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=Ds[o],c=Ms(n,i,a),l=Fs(n,i,a),u=Ls[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=$o[t],s[1]^=Mo[t]}je(r)}class sr{constructor(e,r,t,n=!1,i=24){O(this,"state");O(this,"pos",0);O(this,"posOut",0);O(this,"finished",!1);O(this,"state32");O(this,"destroyed",!1);O(this,"blockLen");O(this,"suffix");O(this,"outputLen");O(this,"enableXOF",!1);O(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=$i(this.state)}clone(){return this._cloneInto()}keccak(){Zr(this.state32),Fo(this.state32,this.rounds),Zr(this.state32),this.posOut=0,this.pos=0}update(e){Je(this),Y(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Je(this,!1),Y(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Xr(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,je(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new sr(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Ws=((s,e,r,t={})=>ts(()=>new sr(e,s,r),t))(1,136,32),Wo=60;class Uo{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Li(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Wo<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Ai(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Bi(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
7
7
  ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=Ws(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Ho(a),l=c.slice(0,32),u=c.slice(32,64),p=c[64],g=p>=27?p-27:p,w=new No.Signature(Us(l),Us(u)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),b=Ws(w);return"0x"+tt(b.slice(12))}}function Ho(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function Us(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Ko=3e4,Go=1e3;class qo{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,Go*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Ko);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const Vo=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Be{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=Be.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Be.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Be.generateRandom16Hex(),l=Be.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",p=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const g=window.open(p,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const _=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),L(),t(new Error("Authentication timeout"))},5*60*1e3),x=10,w=30;let b=0,A=null;const R=()=>{clearInterval(C),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+w+"초간 대기합니다"),A=setTimeout(()=>{L(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},w*1e3)},C=setInterval(()=>{b++;try{if(!g.closed)return;const U=typeof document<"u"&&document.hasFocus();b<=x&&!U?R():(L(),t(new Error("로그인이 취소되었습니다")))}catch{R()}},1e3),L=()=>{clearTimeout(_),clearInterval(C),A&&clearTimeout(A),window.removeEventListener("message",W)},W=U=>{if(U.origin!==e.expectedOrigin)return;if(!Vo.has(U.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",U.origin),L(),t(new Error("Unauthorized OAuth origin"));return}L();const se=typeof U.data.status=="string",q=se?U.data.data??{}:U.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:se?"wrapped":"flat",status:se?U.data.status:"(flat)"});const X=(q==null?void 0:q.state)??U.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(se&&U.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",q==null?void 0:q.error),t(new Error((q==null?void 0:q.error)||"Authentication failed"));return}if(!se&&(q!=null&&q.error)){d.error("[CROSSx] OAuth 실패:",q.error),t(new Error(q.error||"Authentication failed"));return}const ne=q==null?void 0:q.idToken,G=q==null?void 0:q.accessToken,B=G??ne,H=(q==null?void 0:q.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!G,hasIdToken:!!ne,hasEmail:!!H}),!B){d.error("[CROSSx] 토큰을 찾을 수 없음:",U.data),t(new Error("Token not found in response"));return}const y={token:B,email:H},m=T=>{Be.verifyIdTokenNonce(T,l).then(()=>r(y)).catch(N=>{d.error("[CROSSx] nonce 검증 실패:",N),t(N instanceof Error?N:new Error("nonce verification failed"))})};G?G.split(".").length===3?m(G):ne?m(ne):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(y)):ne?m(ne):t(new Error("Token not found in response"))};window.addEventListener("message",W)})}}const st="crossx_wallet_data",Ze="crossx_mock_pin_hash";class zo{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(st)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(st);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(st,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Ze,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new f(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(st);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Ze);return r&&r!==e?!1:(r||await this.storage.set(Ze,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new f(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ze);if(n&&t&&n!==t)throw new f(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ze,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new f(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new f(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(st,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ze,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class $e{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Er))return e;const r=!e||this.tokenStore.isExpiringSoon(Er);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u,p;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const x=_.message||_.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:x,url:o,method:e});const w=$e.mapGatewayError(_.code,_.data);if(w===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(w===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new f(h.USER_NOT_FOUND,$e.getGatewayErrorMessage(_.code,x));const b=w===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:w,A=b===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":$e.getGatewayErrorMessage(_.code,x),R=_.data;let C;throw w===h.PIN_LOCKED?C=$e.extractLockDetails(R):w===h.ADDRESS_LIMIT_EXCEEDED?C={limit:at,raw:R}:C=R??void 0,new f(b,A,C)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:o,method:e}),_.data??_}return _}catch(g){if(g instanceof f)throw g;const _=((l=g.response)==null?void 0:l.status)??g.status;if((_===401||_===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=g.response)!=null&&u.data){const x=g.response.data,w=x.message||x.data||"API 요청에 실패했습니다",b=x.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:b,message:w,url:o,method:e,status:(p=g.response)==null?void 0:p.status}),new f(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${b}): ${w}`)}throw g}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new f(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new f(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new f(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new f(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new f(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new f(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new f(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new f(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10036:return h.ADDRESS_LIMIT_EXCEEDED;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return $e.hasLockInfo(r)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${at} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class Jo{constructor(e,r,t,n=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=n,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(i,o)=>e.prepare(i,o)),e.migrateWallet&&(this.migrateWallet=(i,o)=>e.migrateWallet(i,o)),e.verifyPin&&(this.verifyPin=i=>e.verifyPin(i)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(i,o)=>e.verifyRecoveryPin(i,o))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();const c=await a.signMessage({chainId:r,message:t,from:o,index:n});return{chainId:r,signature:c.signature,format:"hex"}}return this.inner.signMessage(e,r,t,n,i,o)}async signTypedData(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n});return{chainId:r,signature:c.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,n,i,o)}async signTransaction(e,r,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){this.assertBridgeSessionActive();const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n});return{chainId:r,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction)return this.assertBridgeSessionActive(),{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,n)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class nt{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){return this.isCacheValid()?Array.from(this.cache.values()):this._fetchPromise?this._fetchPromise:(this._fetchPromise=this._doFetchChains().finally(()=>{this._fetchPromise=null}),this._fetchPromise)}async _doFetchChains(){try{const e=await this.request("/chains");this.handleEnvelopeError(e);const r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=nt.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?An:En;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new f(nt.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=nt.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new f(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(it).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const Hs="__crossx-confirm-style",te="__crossx-confirm-overlay",jo={light:{bg:"#FFFFFF",border:"rgba(0,0,0,0.07)",borderMedium:"rgba(0,0,0,0.18)",titleColor:"#000000",subtitleColor:"rgba(0,0,0,0.65)",labelColor:"rgba(0,0,0,0.65)",valueColor:"#000000",pillBg:"#F5F7FA",pillFromColor:"rgba(0,0,0,0.65)",pillAmtColor:"#000000",divider:"rgba(0,0,0,0.07)",closeColor:"rgba(0,0,0,0.40)",closeHoverBg:"#F5F7FA",copyColor:"rgba(0,0,0,0.65)",inputBg:"#F5F7FA",inputBorder:"rgba(0,0,0,0.07)",hintColor:"rgba(0,0,0,0.45)",surfaceSubtle:"#F5F7FA",surfaceHigh:"#EDF1F2",primary:"#00B4B7",primaryGlow:"rgba(0,180,183,0.18)",secondary:"#D20609",errorColor:"#D20609",noticeBg:"#FFF6F6",noticeBorder:"#DA0B2E",noticeTitleColor:"#D20609",onPrimary:"#FFFFFF"},dark:{bg:"#1E232E",border:"rgba(255,255,255,0.07)",borderMedium:"rgba(255,255,255,0.18)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.65)",labelColor:"rgba(255,255,255,0.65)",valueColor:"#FFFFFF",pillBg:"#252B39",pillFromColor:"rgba(255,255,255,0.65)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.07)",closeColor:"rgba(255,255,255,0.40)",closeHoverBg:"#252B39",copyColor:"rgba(255,255,255,0.65)",inputBg:"#252B39",inputBorder:"rgba(255,255,255,0.07)",hintColor:"rgba(255,255,255,0.45)",surfaceSubtle:"#252B39",surfaceHigh:"#363B4C",primary:"#00CEB2",primaryGlow:"rgba(0,206,178,0.18)",secondary:"#FF0F47",errorColor:"#FF0F47",noticeBg:"#39151E",noticeBorder:"#CD0C40",noticeTitleColor:"#FF0F47",onPrimary:"#000000"}};function Ks(s,e){const r=jo[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle,surfaceHigh:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const Yo=`
8
8
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400&family=Sora:wght@400;600&display=swap');
9
9