@nexus-cross/crossx-sdk-core 2.2.0-beta.1 → 2.2.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_appleAccount:"Apple 계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},gs={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",pinLocked_failureWarning:"Your account will be locked after further failures.",pinLocked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_sessionExpired:"Your session has expired. Please sign in again.",alert_accountWithdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_walletNotFound:"Wallet data could not be found. Please sign in again.",alert_differentAccount:`You signed in with a different Google/Apple account than before.
|
|
4
4
|
|
|
5
|
-
For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_appleAccount:"Apple account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},pr={ko:hr,en:gs};function xe(r="en",e){return pr[r]??gs}const Bt="crossx_access_token",Mt="crossx_refresh_token",$t="crossx_user_info",et=class et{constructor(e,s,t,n,i,o,a,c){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this._refreshPromise=null,this._migrated=!1;const l=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${l}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${l}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${l}_user_info`}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 s=this.crypto.decodeJWT(e);return s!=null&&s.exp?s.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredRNBridgeSession(){if(!await this.hasValidStoredAccessToken())return!1;try{return!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN)}catch{return!1}}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const s=e==null?void 0:e.data;if(typeof s=="object"&&s!==null&&"code"in s){const t=s;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,s){const t=this.extractResponseErrorCode(e);if(t)throw new g(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,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=`${o}${i}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.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 g(h.OAUTH_POPUP_BLOCKED,i):new g(h.AUTH_FAILED,i)}return this.processFirebaseToken(s,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 s;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 f=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=f.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 g(h.AUTH_FAILED,"Access token 검증 실패");const f=u.payload;s={id:f.sub,email:f.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),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:",s.id,"email:",s.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,s)}else throw new g(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:",s.id),this.loadWallet(s,!1)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:x}=await this.exchangeFirebaseToken(e,u);let p,_,v;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),_=(i=A.firebase)==null?void 0:i.sign_in_provider;const k=((o=A.firebase)==null?void 0:o.identities)??{};v=A.email??((a=k.email)==null?void 0:a[0]),_==="google.com"?p=(c=k["google.com"])==null?void 0:c[0]:_==="apple.com"&&(p=(l=k["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",_,"hasProviderSub:",!!p,"email:",v??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const A=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const k=await this.crypto.verifyJWT(f);if(n=k.signatureVerified??!1,!k.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const L=k.payload,P=L.email??v??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",L.email??"(없음)","/ Firebase JWT:",v??"(없음)","/ OAuth 콜백:",s??"(없음)","→",P??"(없음)"),t={id:L.sub,email:P,signInProvider:_,providerSub:p},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),x&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,x):x&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??s,signInProvider:_,providerSub:p},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const S=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,S),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,s){const t=`${s}/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 g(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 g(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/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 g(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 s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;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 s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;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 s=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){const s=e instanceof g&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",s?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),s&&(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:s}=this.config,t=this.useCookieAuth,n=`${s}/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=et.REFRESH_RELOGIN_CODES.has(c.code);throw new g(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 g(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){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),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof g&&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 g&&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,s){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)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(s);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),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),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($t);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(Bt);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Mt);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove($t),await this.storage.remove(Bt),await this.storage.remove(Mt),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){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 g&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof g&&(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:s}}};et.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let xt=et;class fr{constructor(e,s,t){this.config=e,this.storage=s,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 gr{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new g(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class vt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let i=0;i<s.length;i++)n[i]=s[i]^t[i];s.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 s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class _r{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:s,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 g(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class xr{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}function mr(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const s=new Uint8Array(16);return globalThis.crypto.getRandomValues(s),Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class ge{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const s=Date.now();for(;Date.now()-s<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 ge.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=ge.getBridge(),!this.bridge)throw new g(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 g(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const s=await this.handshake();return this.context=s,d.log("[RNBridge] Bootstrap initialization complete",{activated:s.isActivated,ttl:`${s.absoluteTtlMs/1e3/60}min`}),s}async handshake(){if(!this.bridge)throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=mr(),s=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:s,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new g(h.AUTH_FAILED,"Bridge handshake rejected by native");return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),walletAddress:n.walletAddress}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new g(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){var e;if(!this.bridge)throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not activated");try{const s=await this.bridge.requestFirebaseIdToken(),t=(s.expiresAt-Date.now())/1e3;if(t<60)throw new g(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:t});return s}catch(s){throw s instanceof g?s:(d.error("[RNBridge] Firebase token request failed",s),new g(h.AUTH_FAILED,"Firebase token request failed",s))}}async requestFreshFirebaseIdToken(){var e;if(!this.bridge)throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not activated");try{const s=await this.bridge.requestFreshFirebaseIdToken();if((s.expiresAt-Date.now())/1e3<60)throw new g(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return s}catch(s){throw s instanceof g?s:(d.error("[RNBridge] Fresh Firebase token request failed",s),new g(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",s))}}getContext(){return this.context}isActive(){var t;return!(!((t=this.context)!=null&&t.isActivated)||Date.now()-this.context.activatedAt>this.context.absoluteTtlMs)}}const Le={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://dev-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 wr(r){const e=r.environment;return e&&e in Le?Le[e]:null}function _s(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=wr(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Le)return Le[r]}catch{}return Le.production}const yr=2e3,Ft=6e4,br=1e3,Sr=1e4,vr="0x77359400",Ut="0x3B9ACA00",Ht=130,xs=6,Wt=18,Gt=3e4,Er=5*60*1e3,Ar=30*1e3,mt=100,Ir="crossx-sdk-js/2.2.0";function ms(r){let e=r.length;for(;e>0&&r.charCodeAt(e-1)===48;)e--;return r.slice(0,e)}function Tr(r){if(!r||r==="0x0"||r==="0x")return"0";try{const e=BigInt(r);if(e===0n)return"0";const s=10n**BigInt(Wt),t=e/s,i=(e%s).toString().padStart(Wt,"0"),o=ms(i).slice(0,xs);return o?`${t}.${o}`:`${t}`}catch{return"?"}}function Ge(r,e,s){if(!(!r||r==="0x"||r==="0x0"))try{const t=BigInt(r);if(t===0n)return;const n=10n**BigInt(s),i=t/n,a=(t%n).toString().padStart(s,"0"),c=ms(a.slice(0,xs));return`${c?`${i}.${c}`:`${i}`} ${e}`}catch{return}}function kr(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Ht)throw new g(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Ht} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Rr(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Or(r,e){const s=Nr(e);if(r==="0"){if(s!==void 0&&s!==0)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${s}`);return}const t=r.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(s===void 0)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${r})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(s!==n)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${s})가 chainId (${r}, 예상값: ${n})와 일치하지 않습니다`)}}function Nr(r){if(r==null||typeof r!="object")return;const e=r.domain;if(e==null||typeof e!="object")return;const s=e.chainId;if(s==null)return;const t=Number(s);return Number.isFinite(t)?t:void 0}class Ce{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 g(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 s=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,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=xe(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new g(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:s,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.pinInput_error})}catch(u){if(this.deps.pinStore.clear(),u instanceof g){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return Ce.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof g&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=xe(this.deps.getLocale()??"en"),u=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:u?this.deps.maskEmail(u,l.sessionAlert_appleAccount):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 s=xe(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof g){if(t=Ce.parsePinError(n,s),!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 g&&(t=Ce.parsePinError(n,s),t))continue;throw n}}}static parsePinError(e,s){if(e.code===h.PIN_WRONG)return{errorMessage:s.pinInput_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:s.pinLocked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:s.pinInput_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,s){const t=Ce.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Cr{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 g(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 Pr(r){return r==="google"||r==="apple"}class Lr{constructor(e){this.deps=e}async signInAgain(){var s,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=Pr(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=((s=i.user)==null?void 0:s.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=xe(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.sessionAlert_title,message:l.alert_differentAccount,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.sessionAlert_appleAccount):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(s){const t=xe(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.sessionAlert_appleAccount):void 0;if(s instanceof g&&s.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(s instanceof g&&s.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(!(s instanceof g)||s.code!==h.SESSION_EXPIRED)throw s;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:i})==="signout")throw this.deps.clearAuthState(),new g(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new g(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Dr{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,s){const t=this.deps.getUserId();if(!t)return;const n=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",n),n!=="exists")return;const i=await this.deps.walletProvider.getAddresses(t);if(i.length>0){const a=s?i.find(u=>u.address.toLowerCase()===s.toLowerCase()):void 0,c=e!==void 0?i.find(u=>u.index===e):void 0,l=a??c??i[0];d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address),this.deps.setActiveWallet(l.address,l.index);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(t,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class Br{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:s});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 f=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!f){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(f.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const x=f.pinStatus;if(o=x.maxAttempts,i=o-x.remainingAttempts,x.remainingAttempts===0&&x.lockExpiresAt){const p=x.lockExpiresAt*1e3,_=Math.max(1,Math.round((p-Date.now())/1e3)),v=_<=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 잠금 — ${_}초, 메시지: ${v}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(_,v),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(f){if(!(f instanceof g))throw f;if(f.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const x=xe(this.deps.getLocale()??"en"),p=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:x.sessionAlert_title,message:x.alert_sessionExpired,email:p?this.deps.maskEmail(p,x.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),f}if(f.code===h.MIGRATION_PIN_LOCKED){const x=f.details;if(o=(x==null?void 0:x.maxAttempts)??5,(x==null?void 0:x.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 p=((x==null?void 0:x.lockExpiresAt)??0)*1e3,_=Math.max(1,Math.round((p-Date.now())/1e3)),v=_<=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 이미 잠금 — ${_}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(_,v),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",f),f}}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 g&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof g&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const f=xe(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_sessionExpired,email:x?this.deps.maskEmail(x,f.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const v=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",v.address),v}catch(v){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",v),v}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class Mr{constructor(e){this.deps=e}async withResolvedGasAndFee(e,s){const t=p=>!(p!=null&&p.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,f,x]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],s):null,i?this.deps.estimateGas(e,s):null,o?this.deps.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const p=x;if(p){const _=Ut;c.maxFeePerGas=`0x${(BigInt(p)+BigInt(_)).toString(16)}`,c.maxPriorityFeePerGas=_,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=vr,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=Ut,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class $r{constructor(e){this.crypto=e}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new g(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof g)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Fr(r){return r?r.includes("google")?"google":r.includes("apple")?"apple":r:null}class Ur{constructor(e){this.deps=e}setActiveWallet(e,s){this.deps.setState({address:e,activeWalletIndex:s}),this.deps.emitAddressChanged({address:e,index:s}),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:s,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const s={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:Fr((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(s),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 Hr{constructor(e){this.deps=e}async resolveAddress(e){const s=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===s){if(!t)throw new g(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:s}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Wr{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new g(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new g(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Gr{constructor(e){this.deps=e}async createWallet(){const e=this.deps.getUserId();if(!e)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const s=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",s),s==="migration_required"){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",t);const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new g(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}return s==="exists"?(await this.deps.pinOrchestrator.ensureVerifiedPin(),this.tryGetOrCreateWalletWithMigrationFallback(e)):(await this.deps.pinOrchestrator.ensurePinSetup(),this.tryGetOrCreateWalletWithMigrationFallback(e))}async tryGetOrCreateWalletWithMigrationFallback(e){try{const s=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(s.address,0),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof g&&s.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};throw new g(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}}function qt(r,e){const s=r.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${s}/cross-auth${t}`}class qr{constructor(e){this.deps=e}async registerTokenHistory(e,s,t){if(!(e!=null&&e.trim()))throw new g(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(s!=null&&s.trim()))throw new g(h.TX_INVALID_PARAMS,"invalid param tx_hash");const n=s.startsWith("0x")?s:`0x${s}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new g(h.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new g(h.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=qt(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 g?c:new g(h.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const s=this.deps.getApiBaseUrl(),t=new URL(qt(s,"/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 g(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 g?i:new g(h.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,s,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,s,t);return}catch(c){if(c instanceof g&&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,s){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${s==="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 g(n.code,n.message)}}function at(r,e="Apple account"){if(r.endsWith("@privaterelay.appleid.com"))return e;const s=r.indexOf("@");if(s<0)return"*".repeat(r.length||3);const t=r.substring(0,s),n=r.substring(s);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Te=class Te extends xr{constructor(e,s,t,n,i,o,a,c,l,u,f){var x,p;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._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Dt(e.logger),this.confirmation=l,this.pinStore=f??new vt,this.stateManager=new Ur({setState:_=>{_.authenticated!==void 0&&(this.authenticated=_.authenticated),_.userId!==void 0&&(this.userId=_.userId),_.address!==void 0&&(this.address=_.address),_.activeWalletIndex!==void 0&&(this.activeWalletIndex=_.activeWalletIndex),_.userEmail!==void 0&&(this.userEmail=_.userEmail),_.providerSub!==void 0&&(this.providerSub=_.providerSub),_.loginType!==void 0&&(this.loginType=_.loginType),_.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=_.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:_,index:v})=>{this.emit("addressChanged",{address:_,index:v})},emitAuthChanged:({isAuthenticated:_,address:v,userId:S})=>{this.emit("authChanged",{isAuthenticated:_,address:v,userId:S})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Te.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ce({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:at,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Cr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Dr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(_,v)=>this.setActiveWallet(_,v)}),this.migrationOrchestrator=new Br({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(_,v)=>this.migrateWalletUseCase.execute(_,v),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:at,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var _;return((_=this._config.migration)==null?void 0:_.allowSkip)??!0}}),this.transactionLifecycleService=new Mr({getActiveAddress:()=>this.address,estimateGas:(_,v)=>this.estimateGas(_,v),getBaseFeePerGas:_=>this.getBaseFeePerGas(_),jsonRpcCall:(_,v,S)=>this.jsonRpc.call(_,v,S)}),this.signatureVerifier=new $r(this.crypto),this.addressResolverService=new Hr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Wr({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Gr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(_,v)=>this.setActiveWallet(_,v)}),this.tokenHistoryService=new qr({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Lr({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:_=>{this._isRecoveringSession=_},setAuthenticated:_=>{this.authenticated=_},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:_=>this.signInUseCase.execute(_),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:_=>this.confirmation.showSessionAlert(_),clearAuthState:()=>this.clearAuthState(),applyAuthResult:_=>this.applyAuthResult(_),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:at}),this.chainRegistry=u,this.jsonRpc=new _r(u,i),this.signInUseCase=new xt(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new fr(this.internalConfig,t,c),this.migrateWalletUseCase=new gr(t,a),(x=a.setOnUnauthorized)==null||x.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}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 s,t;d.log("[CROSSx SDK] v2.2.0 초기화 중..."),this.confirmation.setMessages(xe(this._config.locale));try{const n=_s();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Te.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(!(e!=null&&e.preferredWalletAddress)&&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)if(this.applyAuthResult(c),this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()))this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex);else try{await this.loadWalletAfterAuth(o,a)}catch(u){if(!(u instanceof g&&u.code===h.PIN_CANCELLED))throw u;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}return this.initialized=!0,d.info("[CROSSx SDK] v2.2.0 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new g(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!ge.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도");const e=new ge({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.2.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),s=await e.initialize();return this._rnBridgeService=e,this._rnBridgeWalletAddress=s.walletAddress,this.subscribeBridgeWalletChanged(),d.log("[CROSSx] RN Bridge Handshake 성공",{walletAddress:s.walletAddress??"(없음)"}),await this.signInUseCase.hasValidStoredAccessToken()?(await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 — native sign delegation 활성")),null):(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 s=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(s);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(s){const t=s instanceof Error?s.message:String(s);return t.includes("USER_REJECTED")||t.includes("rejected")?(d.log("[CROSSx] Bridge 로그인 거부 — bridge 비활성화, OAuth fallback"),this._rnBridgeService=null):d.warn("[CROSSx] Bridge 로그인 실패",s),null}}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new g(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFreshFirebaseIdToken()}catch(e){throw d.error("[CROSSx] Fresh Firebase token request failed:",e),new g(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return ge.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");if(this._rnBridgeService){const t=await this._tryBridgeSignIn();if(t!=null&&t.success)return t}let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:cr(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new g(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");s={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof g?t:new g(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:s,...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,s);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,s);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof g&&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 g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw s instanceof g?s:new g(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof g?t:new g(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=ge.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(s){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",s)}this._rnBridgeService=null,this._rnBridgeWalletAddress=void 0}catch(e){throw new g(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}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof g&&s.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}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 g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(s.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof g?s:new g(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(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 g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=s.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,s){if(e.length<2)return null;if(s){const t=e.find(n=>n.address.toLowerCase()===s.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 g?e:new g(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof g?s:new g(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(xe(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,s,t){return this.withSessionRecovery(()=>this._signMessage(e,s,t))}async _signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(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:s,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:s,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof g?i:new g(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){return this.withSessionRecovery(()=>this._signTypedData(e,s,t))}async _signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Or(e,s);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:s,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:s,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return kr(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof g?i:new g(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData(Te.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=ot(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 Rr(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof g)throw o;const a=o instanceof Error?o.message:String(o);throw new g(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,s,t){return this.withSessionRecovery(()=>this._sendTransaction(e,s,t))}async _sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=ot(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 f=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return f.txHash??f.signature}}),a=(s.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,Ir).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof g)throw o;const a=o instanceof Error?o.message:String(o);throw new g(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??br,i=Sr,o=t.timeoutMs??Ft,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new g(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var v,S;if(this._isAuthenticatedViaRNBridge){const A=ge.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,s,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((v=this._config.receiptPolling)==null?void 0:v.intervalMs)??yr,l=i??((S=this._config.receiptPolling)==null?void 0:S.timeoutMs)??Ft,u=ot(e),f=s.from??"";let x,p;const _=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{x=A;const k=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),L=s.value?BigInt(s.value):0n,P=Ge(s.value,u.symbol,u.decimals),G=Ge("0x"+k.toString(16),u.symbol,u.decimals),V=Ge("0x"+(L+k).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:A.from,to:A.to??s.to,amount:P,fees:G,total:V,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(p=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:f,to:s.to,amount:Ge(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:f,to:s.to},_),p)throw p;return{chainId:e,txHash:a,receipt:x}}async bridgeSendTransactionWithWaitForReceipt(e,s,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:s,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:s,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()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new g(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof g?n:new g(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){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],s)}catch(n){const i=n instanceof Error?n.message:String(n);throw new g(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:Tr(n),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let s=this._providers.get(e);return s||(s=new fs(this,e),this._providers.set(e,s)),s}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(s=>{try{s.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof g)throw n;const i=n instanceof Error?n.message:String(n);throw new g(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,s){const t=this.address;this.stateManager.setActiveWallet(e,s),t&&e&&t.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=ge.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",s=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!s||typeof s!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",s);return}const t=s,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}this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source}),this.setActiveWallet(n,0),this._rnBridgeWalletAddress=n)}),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,s){return this.walletLifecycleService.loadWalletAfterAuth(e,s)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,s,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,s,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(),Dt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Te.WALLET_PREF_KEY="wallet_preference",Te.OFFCHAIN_CHAIN_ID="0";let Ye=Te;class Vr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return d.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw d.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw d.error("Storage clear error:",e),e}}}const ct="crossx-sdk",Kr=1,ue="data",Ee="keys",qe="aes-primary",zr=12;class Vt{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((s,t)=>{const n=indexedDB.open(e,Kr);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ue)||i.createObjectStore(ue),i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ee,qe);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ee,qe,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===ct)return null;try{const e=await this.openDB(ct),s=e.transaction([Ee,ue],"readonly"),t=s.objectStore(Ee).get(qe),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=s.objectStore(ue).getAll(),o=s.objectStore(ue).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(Ee,qe,n);for(let l=0;l<c.length;l++)await this.idbPut(ue,String(c[l]),a[l]);return indexedDB.deleteDatabase(ct),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(zr);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(ue,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(ue,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return d.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ue,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(ue)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Et(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function we(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function K(r,e,s=""){const t=Et(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function ws(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");we(r.outputLen),we(r.blockLen)}function Be(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ys(r,e){K(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function jr(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Me(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function lt(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function he(r,e){return r<<32-e|r>>>e}const Yr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Xr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Jr(r){for(let e=0;e<r.length;e++)r[e]=Xr(r[e]);return r}const Kt=Yr?r=>r:Jr,bs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Zr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function We(r){if(K(r),bs)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Zr[r[s]];return e}const pe={_0:48,_9:57,A:65,F:70,a:97,f:102};function zt(r){if(r>=pe._0&&r<=pe._9)return r-pe._0;if(r>=pe.A&&r<=pe.F)return r-(pe.A-10);if(r>=pe.a&&r<=pe.f)return r-(pe.a-10)}function Xe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(bs)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,i=0;n<s;n++,i+=2){const o=zt(r.charCodeAt(i)),a=zt(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ve(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];K(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function Ss(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function vs(r=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(r))}const Qr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function en(r,e,s){return r&e^~r&s}function tn(r,e,s){return r&e^r&s^e&s}class sn{constructor(e,s,t,n){N(this,"blockLen");N(this,"outputLen");N(this,"padOffset");N(this,"isLE");N(this,"buffer");N(this,"view");N(this,"finished",!1);N(this,"length",0);N(this,"pos",0);N(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=lt(this.buffer)}update(e){Be(this),K(e);const{view:s,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=lt(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(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Be(this),ys(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,Me(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let f=o;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=lt(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 f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,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%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ve=BigInt(2**32-1),jt=BigInt(32);function rn(r,e=!1){return e?{h:Number(r&Ve),l:Number(r>>jt&Ve)}:{h:Number(r>>jt&Ve)|0,l:Number(r&Ve)|0}}function nn(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=rn(r[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const on=(r,e,s)=>r<<s|e>>>32-s,an=(r,e,s)=>e<<s|r>>>32-s,cn=(r,e,s)=>e<<s-32|r>>>64-s,ln=(r,e,s)=>r<<s-32|e>>>64-s,dn=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]),be=new Uint32Array(64);class un extends sn{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|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,s){for(let f=0;f<16;f++,s+=4)be[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const x=be[f-15],p=be[f-2],_=he(x,7)^he(x,18)^x>>>3,v=he(p,17)^he(p,19)^p>>>10;be[f]=v+be[f-7]+_+be[f-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const x=he(a,6)^he(a,11)^he(a,25),p=u+x+en(a,c,l)+dn[f]+be[f]|0,v=(he(t,2)^he(t,13)^he(t,22))+tn(t,n,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=n,n=t,t=p+v|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(){Me(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Me(this.buffer)}}class hn extends un{constructor(){super(32);N(this,"A",ye[0]|0);N(this,"B",ye[1]|0);N(this,"C",ye[2]|0);N(this,"D",ye[3]|0);N(this,"E",ye[4]|0);N(this,"F",ye[5]|0);N(this,"G",ye[6]|0);N(this,"H",ye[7]|0)}}const pn=Ss(()=>new hn,Qr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const At=BigInt(0),wt=BigInt(1);function Je(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Es(r){if(typeof r=="bigint"){if(!je(r))throw new Error("positive bigint expected, got "+r)}else we(r);return r}function Ke(r){const e=Es(r).toString(16);return e.length&1?"0"+e:e}function As(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?At:BigInt("0x"+r)}function st(r){return As(We(r))}function Is(r){return As(We(fn(K(r)).reverse()))}function It(r,e){we(e),r=Es(r);const s=Xe(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function Ts(r,e){return It(r,e).reverse()}function fn(r){return Uint8Array.from(r)}const je=r=>typeof r=="bigint"&&At<=r;function gn(r,e,s){return je(r)&&je(e)&&je(s)&&e<=r&&r<s}function _n(r,e,s,t){if(!gn(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function xn(r){let e;for(e=0;r>At;r>>=wt,e+=1);return e}const Tt=r=>(wt<<BigInt(r))-wt;function mn(r,e,s){if(we(r,"hashLen"),we(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=S=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},x=(...S)=>s(l,ve(c,...S)),p=(S=n)=>{l=x(i,S),c=x(),S.length!==0&&(l=x(o,S),c=x())},_=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const A=[];for(;S<e;){c=x();const k=c.slice();A.push(k),S+=c.length}return ve(...A)};return(S,A)=>{f(),p(S);let k;for(;!(k=A(_()));)p();return f(),k}}function kt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[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(s,!0)}function Yt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const se=BigInt(0),te=BigInt(1),ke=BigInt(2),ks=BigInt(3),Rs=BigInt(4),Os=BigInt(5),wn=BigInt(7),Ns=BigInt(8),yn=BigInt(9),Cs=BigInt(16);function le(r,e){const s=r%e;return s>=se?s:e+s}function oe(r,e,s){let t=r;for(;e-- >se;)t*=t,t%=s;return t}function Xt(r,e){if(r===se)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected positive modulus, got "+e);let s=le(r,e),t=e,n=se,i=te;for(;s!==se;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=l}if(t!==te)throw new Error("invert: does not exist");return le(n,e)}function Rt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function Ps(r,e){const s=(r.ORDER+te)/Rs,t=r.pow(e,s);return Rt(r,t,e),t}function bn(r,e){const s=(r.ORDER-Os)/Ns,t=r.mul(e,ke),n=r.pow(t,s),i=r.mul(e,n),o=r.mul(r.mul(i,ke),n),a=r.mul(i,r.sub(o,r.ONE));return Rt(r,a,e),a}function Sn(r){const e=rt(r),s=Ls(r),t=s(e,e.neg(e.ONE)),n=s(e,t),i=s(e,e.neg(t)),o=(r+wn)/Cs;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const f=a.mul(l,n),x=a.mul(l,i),p=a.eql(a.sqr(u),c),_=a.eql(a.sqr(f),c);l=a.cmov(l,u,p),u=a.cmov(x,f,_);const v=a.eql(a.sqr(u),c),S=a.cmov(l,u,v);return Rt(a,S,c),S}}function Ls(r){if(r<ks)throw new Error("sqrt is not defined for small field");let e=r-te,s=0;for(;e%ke===se;)e/=ke,s++;let t=ke;const n=rt(r);for(;Jt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Ps;let i=n.pow(t,e);const o=(e+te)/ke;return function(c,l){if(c.is0(l))return l;if(Jt(c,l)!==1)throw new Error("Cannot find square root");let u=s,f=c.mul(c.ONE,i),x=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(x,c.ONE);){if(c.is0(x))return c.ZERO;let _=1,v=c.sqr(x);for(;!c.eql(v,c.ONE);)if(_++,v=c.sqr(v),_===u)throw new Error("Cannot find square root");const S=te<<BigInt(u-_-1),A=c.pow(f,S);u=_,f=c.sqr(A),x=c.mul(x,f),p=c.mul(p,A)}return p}}function vn(r){return r%Rs===ks?Ps:r%Ns===Os?bn:r%Cs===yn?Sn(r):Ls(r)}const En=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function An(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=En.reduce((t,n)=>(t[n]="function",t),e);return kt(r,s),r}function In(r,e,s){if(s<se)throw new Error("invalid exponent, negatives unsupported");if(s===se)return r.ONE;if(s===te)return e;let t=r.ONE,n=e;for(;s>se;)s&te&&(t=r.mul(t,n)),n=r.sqr(n),s>>=te;return t}function Ds(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function Jt(r,e){const s=(r.ORDER-te)/ke,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Tn(r,e){e!==void 0&&we(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class kn{constructor(e,s={}){N(this,"ORDER");N(this,"BITS");N(this,"BYTES");N(this,"isLE");N(this,"ZERO",se);N(this,"ONE",te);N(this,"_lengths");N(this,"_sqrt");N(this,"_mod");var o;if(e<=se)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=Tn(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 le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&te)===te}neg(e){return le(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return le(e*e,this.ORDER)}add(e,s){return le(e+s,this.ORDER)}sub(e,s){return le(e-s,this.ORDER)}mul(e,s){return le(e*s,this.ORDER)}pow(e,s){return In(this,e,s)}div(e,s){return le(e*Xt(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return Xt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=vn(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Ts(e,this.BYTES):It(e,this.BYTES)}fromBytes(e,s=!1){K(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?Is(e):st(e);if(a&&(c=le(c,o)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ds(this,e)}cmov(e,s,t){return t?s:e}}function rt(r,e={}){return new kn(r,e)}function Bs(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function Ms(r){const e=Bs(r);return e+Math.ceil(e/2)}function Rn(r,e,s=!1){K(r);const t=r.length,n=Bs(e),i=Ms(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?Is(r):st(r),a=le(o,e-te)+te;return s?Ts(a,n):It(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $e=BigInt(0),Re=BigInt(1);function Ze(r,e){const s=e.negate();return r?s:e}function Zt(r,e){const s=Ds(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function $s(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function dt(r,e){$s(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=Tt(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function Qt(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=Re);const l=e*t,u=l+Math.abs(a)-1,f=a===0,x=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:x,isNegF:p,offsetF:l}}const ut=new WeakMap,Fs=new WeakMap;function ht(r){return Fs.get(r)||1}function es(r){if(r!==$e)throw new Error("invalid wNAF")}class On{constructor(e,s){N(this,"BASE");N(this,"ZERO");N(this,"Fn");N(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>$e;)s&Re&&(t=t.add(n)),n=n.double(),s>>=Re;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=dt(s,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,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=dt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:x,offsetF:p}=Qt(t,a,o);t=c,u?i=i.add(Ze(x,s[p])):n=n.add(Ze(f,s[l]))}return es(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=dt(e,this.bits);for(let o=0;o<i.windows&&t!==$e;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Qt(t,o,i);if(t=a,!l){const f=s[c];n=n.add(u?f.negate():f)}}return es(t),n}getPrecomputes(e,s,t){let n=ut.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),ut.set(s,n))),n}cached(e,s,t){const n=ht(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const i=ht(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){$s(s,this.bits),Fs.set(e,s),ut.delete(e)}hasCache(e){return ht(e)!==1}}function Nn(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>$e||t>$e;)s&Re&&(i=i.add(n)),t&Re&&(o=o.add(n)),n=n.double(),s>>=Re,t>>=Re;return{p1:i,p2:o}}function ts(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return An(e),e}else return rt(r,{isLE:s})}function Cn(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>$e))throw new Error(`CURVE.${c} must be positive bigint`)}const n=ts(e.p,s.Fp,t),i=ts(e.n,s.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 Pn(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Us{constructor(e,s){N(this,"oHash");N(this,"iHash");N(this,"blockLen");N(this,"outputLen");N(this,"finished",!1);N(this,"destroyed",!1);if(ws(e),K(s,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(s.length>t?e.create().update(s).digest():s);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),Me(n)}update(e){return Be(this),this.iHash.update(e),this}digestInto(e){Be(this),K(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:s,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=s._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 Hs=(r,e,s)=>new Us(r,e).update(s).digest();Hs.create=(r,e)=>new Us(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ss=(r,e)=>(r+(r>=0?e:-e)/Ws)/e;function Ln(r,e,s){const[[t,n],[i,o]]=e,a=ss(o*r,s),c=ss(-n*r,s);let l=r-a*t-c*i,u=-a*n-c*o;const f=l<_e,x=u<_e;f&&(l=-l),x&&(u=-u);const p=Tt(Math.ceil(xn(s)/2))+De;if(l<_e||l>=p||u<_e||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:x,k2:u}}function yt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function pt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Je(s.lowS,"lowS"),Je(s.prehash,"prehash"),s.format!==void 0&&yt(s.format),s}class Dn extends Error{constructor(e=""){super(e)}}const Se={Err:Dn,_tlv:{encode:(r,e)=>{const{Err:s}=Se;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=Ke(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?Ke(n.length/2|128):"";return Ke(r)+i+n+e},decode(r,e){const{Err:s}=Se;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("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 s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Se;if(r<_e)throw new e("integer: negative integers are not allowed");let s=Ke(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=Se;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return st(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Se,n=K(r,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:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Se,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},_e=BigInt(0),De=BigInt(1),Ws=BigInt(2),ze=BigInt(3),Bn=BigInt(4);function Mn(r,e={}){const s=Cn("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;kt(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=qs(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f($,m,w){const{x:T,y:O}=m.toAffine(),M=t.toBytes(T);if(Je(w,"isCompressed"),w){u();const y=!t.isOdd(O);return ve(Gs(y),M)}else return ve(Uint8Array.of(4),M,t.toBytes(O))}function x($){K($,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,T=$.length,O=$[0],M=$.subarray(1);if(T===m&&(O===2||O===3)){const y=t.fromBytes(M);if(!t.isValid(y))throw new Error("bad point: is not on curve, wrong x");const b=v(y);let E;try{E=t.sqrt(b)}catch(H){const F=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();const I=t.isOdd(E);return(O&1)===1!==I&&(E=t.neg(E)),{x:y,y:E}}else if(T===w&&O===4){const y=t.BYTES,b=t.fromBytes(M.subarray(0,y)),E=t.fromBytes(M.subarray(y,y*2));if(!S(b,E))throw new Error("bad point: is not on curve");return{x:b,y:E}}else throw new Error(`bad point: got length ${T}, expected compressed=${m} or uncompressed=${w}`)}const p=e.toBytes||f,_=e.fromBytes||x;function v($){const m=t.sqr($),w=t.mul(m,$);return t.add(t.add(w,t.mul($,i.a)),i.b)}function S($,m){const w=t.sqr(m),T=v($);return t.eql(w,T)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,ze),Bn),k=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,k)))throw new Error("bad curve params: a or b");function L($,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${$}`);return m}function P($){if(!($ instanceof X))throw new Error("Weierstrass Point expected")}function G($){if(!c||!c.basises)throw new Error("no endo");return Ln($,c.basises,n.ORDER)}const V=Yt(($,m)=>{const{X:w,Y:T,Z:O}=$;if(t.eql(O,t.ONE))return{x:w,y:T};const M=$.is0();m==null&&(m=M?t.ONE:t.inv(O));const y=t.mul(w,m),b=t.mul(T,m),E=t.mul(O,m);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:y,y:b}}),Z=Yt($=>{if($.is0()){if(e.allowInfinityPoint&&!t.is0($.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:w}=$.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!S(m,w))throw new Error("bad point: equation left != right");if(!$.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function W($,m,w,T,O){return w=new X(t.mul(w.X,$),w.Y,w.Z),m=Ze(T,m),w=Ze(O,w),m.add(w)}const D=class D{constructor(m,w,T){N(this,"X");N(this,"Y");N(this,"Z");this.X=L("x",m),this.Y=L("y",w,!0),this.Z=L("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:w,y:T}=m||{};if(!m||!t.isValid(w)||!t.isValid(T))throw new Error("invalid affine point");if(m instanceof D)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(T)?D.ZERO:new D(w,T,t.ONE)}static fromBytes(m){const w=D.fromAffine(_(K(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return D.fromBytes(Xe(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return U.createCache(this,m),w||this.multiply(ze),this}assertValidity(){Z(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){P(m);const{X:w,Y:T,Z:O}=this,{X:M,Y:y,Z:b}=m,E=t.eql(t.mul(w,b),t.mul(M,O)),I=t.eql(t.mul(T,b),t.mul(y,O));return E&&I}negate(){return new D(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=i,T=t.mul(w,ze),{X:O,Y:M,Z:y}=this;let b=t.ZERO,E=t.ZERO,I=t.ZERO,R=t.mul(O,O),H=t.mul(M,M),F=t.mul(y,y),B=t.mul(O,M);return B=t.add(B,B),I=t.mul(O,y),I=t.add(I,I),b=t.mul(m,I),E=t.mul(T,F),E=t.add(b,E),b=t.sub(H,E),E=t.add(H,E),E=t.mul(b,E),b=t.mul(B,b),I=t.mul(T,I),F=t.mul(m,F),B=t.sub(R,F),B=t.mul(m,B),B=t.add(B,I),I=t.add(R,R),R=t.add(I,R),R=t.add(R,F),R=t.mul(R,B),E=t.add(E,R),F=t.mul(M,y),F=t.add(F,F),R=t.mul(F,B),b=t.sub(b,R),I=t.mul(F,H),I=t.add(I,I),I=t.add(I,I),new D(b,E,I)}add(m){P(m);const{X:w,Y:T,Z:O}=this,{X:M,Y:y,Z:b}=m;let E=t.ZERO,I=t.ZERO,R=t.ZERO;const H=i.a,F=t.mul(i.b,ze);let B=t.mul(w,M),q=t.mul(T,y),Y=t.mul(O,b),ne=t.add(w,T),z=t.add(M,y);ne=t.mul(ne,z),z=t.add(B,q),ne=t.sub(ne,z),z=t.add(w,O);let ee=t.add(M,b);return z=t.mul(z,ee),ee=t.add(B,Y),z=t.sub(z,ee),ee=t.add(T,O),E=t.add(y,b),ee=t.mul(ee,E),E=t.add(q,Y),ee=t.sub(ee,E),R=t.mul(H,z),E=t.mul(F,Y),R=t.add(E,R),E=t.sub(q,R),R=t.add(q,R),I=t.mul(E,R),q=t.add(B,B),q=t.add(q,B),Y=t.mul(H,Y),z=t.mul(F,z),q=t.add(q,Y),Y=t.sub(B,Y),Y=t.mul(H,Y),z=t.add(z,Y),B=t.mul(q,z),I=t.add(I,B),B=t.mul(ee,z),E=t.mul(ne,E),E=t.sub(E,B),B=t.mul(ne,q),R=t.mul(ee,R),R=t.add(R,B),new D(E,I,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(D.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let T,O;const M=y=>U.cached(this,y,b=>Zt(D,b));if(w){const{k1neg:y,k1:b,k2neg:E,k2:I}=G(m),{p:R,f:H}=M(b),{p:F,f:B}=M(I);O=H.add(B),T=W(w.beta,R,F,y,E)}else{const{p:y,f:b}=M(m);T=y,O=b}return Zt(D,[T,O])[0]}multiplyUnsafe(m){const{endo:w}=e,T=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===_e||T.is0())return D.ZERO;if(m===De)return T;if(U.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:M,k2neg:y,k2:b}=G(m),{p1:E,p2:I}=Nn(D,T,M,b);return W(w.beta,E,I,O,y)}else return U.unsafe(T,m)}toAffine(m){return V(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===De?!0:m?m(D,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===De?this:m?m(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return Je(m,"isCompressed"),this.assertValidity(),p(D,this,m)}toHex(m=!0){return We(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};N(D,"BASE",new D(i.Gx,i.Gy,t.ONE)),N(D,"ZERO",new D(t.ZERO,t.ONE,t.ZERO)),N(D,"Fp",t),N(D,"Fn",n);let X=D;const Q=n.BITS,U=new On(X,e.endo?Math.ceil(Q/2):Q);return X.BASE.precompute(8),X}function Gs(r){return Uint8Array.of(r?2:3)}function qs(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function $n(r,e={}){const{Fn:s}=r,t=e.randomBytes||vs,n=Object.assign(qs(r.Fp,s),{seed:Ms(s.ORDER)});function i(p){try{const _=s.fromBytes(p);return s.isValidNot0(_)}catch{return!1}}function o(p,_){const{publicKey:v,publicKeyUncompressed:S}=n;try{const A=p.length;return _===!0&&A!==v||_===!1&&A!==S?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return Rn(K(p,n.seed,"seed"),s.ORDER)}function c(p,_=!0){return r.BASE.multiply(s.fromBytes(p)).toBytes(_)}function l(p){const{secretKey:_,publicKey:v,publicKeyUncompressed:S}=n;if(!Et(p)||"_lengths"in s&&s._lengths||_===v)return;const A=K(p,void 0,"key").length;return A===v||A===S}function u(p,_,v=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(_)===!1)throw new Error("second arg must be public key");const S=s.fromBytes(p);return r.fromBytes(_).multiply(S).toBytes(v)}const f={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},x=Pn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:x,Point:r,utils:f,lengths:n})}function Fn(r,e,s={}){ws(e),kt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||vs,n=s.hmac||((m,w)=>Hs(e,m,w)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:x,lengths:p}=$n(r,s),_={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},v=a*Ws<i.ORDER;function S(m){const w=a>>De;return m>w}function A(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function k(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function L(m,w){yt(w);const T=p.signature,O=w==="compact"?T:w==="recovered"?T+1:void 0;return K(m,O)}class P{constructor(w,T,O){N(this,"r");N(this,"s");N(this,"recovery");if(this.r=A("r",w),this.s=A("s",T),O!=null){if(k(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,T=_.format){L(w,T);let O;if(T==="der"){const{r:E,s:I}=Se.toSig(K(w));return new P(E,I)}T==="recovered"&&(O=w[0],T="compact",w=w.subarray(1));const M=p.signature/2,y=w.subarray(0,M),b=w.subarray(M,M*2);return new P(o.fromBytes(y),o.fromBytes(b),O)}static fromHex(w,T){return this.fromBytes(Xe(w),T)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new P(this.r,this.s,w)}recoverPublicKey(w){const{r:T,s:O}=this,M=this.assertRecovery(),y=M===2||M===3?T+a:T;if(!i.isValid(y))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const b=i.toBytes(y),E=r.fromBytes(ve(Gs((M&1)===0),b)),I=o.inv(y),R=V(K(w,void 0,"msgHash")),H=o.create(-R*I),F=o.create(O*I),B=r.BASE.multiplyUnsafe(H).add(E.multiplyUnsafe(F));if(B.is0())throw new Error("invalid recovery: point at infinify");return B.assertValidity(),B}hasHighS(){return S(this.s)}toBytes(w=_.format){if(yt(w),w==="der")return Xe(Se.hexFromSig(this));const{r:T,s:O}=this,M=o.toBytes(T),y=o.toBytes(O);return w==="recovered"?(k(),ve(Uint8Array.of(this.assertRecovery()),M,y)):ve(M,y)}toHex(w){return We(this.toBytes(w))}}const G=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const T=st(w),O=w.length*8-c;return O>0?T>>BigInt(O):T},V=s.bits2int_modN||function(w){return o.create(G(w))},Z=Tt(c);function W(m){return _n("num < 2^"+c,m,_e,Z),o.toBytes(m)}function X(m,w){return K(m,void 0,"message"),w?K(e(m),void 0,"prehashed message"):m}function Q(m,w,T){const{lowS:O,prehash:M,extraEntropy:y}=pt(T,_);m=X(m,M);const b=V(m),E=o.fromBytes(w);if(!o.isValidNot0(E))throw new Error("invalid private key");const I=[W(E),W(b)];if(y!=null&&y!==!1){const B=y===!0?t(p.secretKey):y;I.push(K(B,void 0,"extraEntropy"))}const R=ve(...I),H=b;function F(B){const q=G(B);if(!o.isValidNot0(q))return;const Y=o.inv(q),ne=r.BASE.multiply(q).toAffine(),z=o.create(ne.x);if(z===_e)return;const ee=o.create(Y*o.create(H+z*E));if(ee===_e)return;let Pt=(ne.x===z?0:2)|Number(ne.y&De),Lt=ee;return O&&S(ee)&&(Lt=o.neg(ee),Pt^=1),new P(z,Lt,v?void 0:Pt)}return{seed:R,k2sig:F}}function U(m,w,T={}){const{seed:O,k2sig:M}=Q(m,w,T);return mn(e.outputLen,o.BYTES,n)(O,M).toBytes(T.format)}function D(m,w,T,O={}){const{lowS:M,prehash:y,format:b}=pt(O,_);if(T=K(T,void 0,"publicKey"),w=X(w,y),!Et(m)){const E=m instanceof P?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+E)}L(m,b);try{const E=P.fromBytes(m,b),I=r.fromBytes(T);if(M&&E.hasHighS())return!1;const{r:R,s:H}=E,F=V(w),B=o.inv(H),q=o.create(F*B),Y=o.create(R*B),ne=r.BASE.multiplyUnsafe(q).add(I.multiplyUnsafe(Y));return ne.is0()?!1:o.create(ne.x)===R}catch{return!1}}function $(m,w,T={}){const{prehash:O}=pt(T,_);return w=X(w,O),P.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:x,lengths:p,Point:r,sign:U,verify:D,recoverPublicKey:$,Signature:P,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ot={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Un={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},rs=BigInt(2);function Hn(r){const e=Ot.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=oe(u,s,e)*u%e,x=oe(f,s,e)*u%e,p=oe(x,rs,e)*l%e,_=oe(p,n,e)*p%e,v=oe(_,i,e)*_%e,S=oe(v,a,e)*v%e,A=oe(S,c,e)*S%e,k=oe(A,a,e)*v%e,L=oe(k,s,e)*u%e,P=oe(L,o,e)*_%e,G=oe(P,t,e)*l%e,V=oe(G,rs,e);if(!bt.eql(bt.sqr(V),r))throw new Error("Cannot find square root");return V}const bt=rt(Ot.p,{sqrt:Hn}),Wn=Mn(Ot,{Fp:bt,endo:Un}),Gn=Fn(Wn,pn),qn=BigInt(0),Fe=BigInt(1),Vn=BigInt(2),Kn=BigInt(7),zn=BigInt(256),jn=BigInt(113),Vs=[],Ks=[],zs=[];for(let r=0,e=Fe,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Vs.push(2*(5*t+s)),Ks.push((r+1)*(r+2)/2%64);let n=qn;for(let i=0;i<7;i++)e=(e<<Fe^(e>>Kn)*jn)%zn,e&Vn&&(n^=Fe<<(Fe<<BigInt(i))-Fe);zs.push(n)}const js=nn(zs,!0),Yn=js[0],Xn=js[1],ns=(r,e,s)=>s>32?cn(r,e,s):on(r,e,s),is=(r,e,s)=>s>32?ln(r,e,s):an(r,e,s);function Jn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],f=ns(l,u,1)^s[a],x=is(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)r[o+p]^=f,r[o+p+1]^=x}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=Ks[o],c=ns(n,i,a),l=is(n,i,a),u=Vs[o];n=r[u],i=r[u+1],r[u]=c,r[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Yn[t],r[1]^=Xn[t]}Me(s)}class Nt{constructor(e,s,t,n=!1,i=24){N(this,"state");N(this,"pos",0);N(this,"posOut",0);N(this,"finished",!1);N(this,"state32");N(this,"destroyed",!1);N(this,"blockLen");N(this,"suffix");N(this,"outputLen");N(this,"enableXOF",!1);N(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,we(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=jr(this.state)}clone(){return this._cloneInto()}keccak(){Kt(this.state32),Jn(this.state32,this.rounds),Kt(this.state32),this.posOut=0,this.pos=0}update(e){Be(this),K(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Be(this,!1),K(e),this.finish();const s=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(s.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 we(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ys(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,Me(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Nt(s,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 Zn=(r,e,s,t={})=>Ss(()=>new Nt(e,r,s),t),os=Zn(1,136,32),Qn=60;class ei{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=it.createRemoteJWKSet(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){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+Qn<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 it.jwtVerify(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 it.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
5
|
+
For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_appleAccount:"Apple account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},pr={ko:hr,en:gs};function xe(r="en",e){return pr[r]??gs}const Bt="crossx_access_token",Mt="crossx_refresh_token",$t="crossx_user_info",et=class et{constructor(e,s,t,n,i,o,a,c){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this._refreshPromise=null,this._migrated=!1;const l=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${l}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${l}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${l}_user_info`}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 s=this.crypto.decodeJWT(e);return s!=null&&s.exp?s.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredRNBridgeSession(){if(!await this.hasValidStoredAccessToken())return!1;try{return!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN)}catch{return!1}}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const s=e==null?void 0:e.data;if(typeof s=="object"&&s!==null&&"code"in s){const t=s;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,s){const t=this.extractResponseErrorCode(e);if(t)throw new g(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,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=`${o}${i}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.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 g(h.OAUTH_POPUP_BLOCKED,i):new g(h.AUTH_FAILED,i)}return this.processFirebaseToken(s,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 s;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 f=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=f.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 g(h.AUTH_FAILED,"Access token 검증 실패");const f=u.payload;s={id:f.sub,email:f.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),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:",s.id,"email:",s.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,s)}else throw new g(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:",s.id),this.loadWallet(s,!1)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:x}=await this.exchangeFirebaseToken(e,u);let p,_,v;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),_=(i=A.firebase)==null?void 0:i.sign_in_provider;const k=((o=A.firebase)==null?void 0:o.identities)??{};v=A.email??((a=k.email)==null?void 0:a[0]),_==="google.com"?p=(c=k["google.com"])==null?void 0:c[0]:_==="apple.com"&&(p=(l=k["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",_,"hasProviderSub:",!!p,"email:",v??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const A=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const k=await this.crypto.verifyJWT(f);if(n=k.signatureVerified??!1,!k.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const L=k.payload,P=L.email??v??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",L.email??"(없음)","/ Firebase JWT:",v??"(없음)","/ OAuth 콜백:",s??"(없음)","→",P??"(없음)"),t={id:L.sub,email:P,signInProvider:_,providerSub:p},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),x&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,x):x&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??s,signInProvider:_,providerSub:p},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const S=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,S),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,s){const t=`${s}/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 g(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 g(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/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 g(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 s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;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 s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;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 s=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){const s=e instanceof g&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",s?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),s&&(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:s}=this.config,t=this.useCookieAuth,n=`${s}/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=et.REFRESH_RELOGIN_CODES.has(c.code);throw new g(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 g(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){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),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof g&&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 g&&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,s){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)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(s);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),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),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($t);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(Bt);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Mt);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove($t),await this.storage.remove(Bt),await this.storage.remove(Mt),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){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 g&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof g&&(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:s}}};et.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let xt=et;class fr{constructor(e,s,t){this.config=e,this.storage=s,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 gr{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new g(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class vt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let i=0;i<s.length;i++)n[i]=s[i]^t[i];s.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 s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class _r{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:s,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 g(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class xr{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}function mr(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const s=new Uint8Array(16);return globalThis.crypto.getRandomValues(s),Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class ge{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const s=Date.now();for(;Date.now()-s<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 ge.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=ge.getBridge(),!this.bridge)throw new g(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 g(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const s=await this.handshake();return this.context=s,d.log("[RNBridge] Bootstrap initialization complete",{activated:s.isActivated,ttl:`${s.absoluteTtlMs/1e3/60}min`}),s}async handshake(){if(!this.bridge)throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=mr(),s=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:s,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new g(h.AUTH_FAILED,"Bridge handshake rejected by native");return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),walletAddress:n.walletAddress}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new g(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){var e;if(!this.bridge)throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not activated");try{const s=await this.bridge.requestFirebaseIdToken(),t=(s.expiresAt-Date.now())/1e3;if(t<60)throw new g(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:t});return s}catch(s){if(s instanceof g)throw s;const t=s instanceof Error?s.message:String(s);throw t.includes("USER_REJECTED")||t.toLowerCase().includes("rejected")?new g(h.USER_REJECTED,"Firebase ID token request rejected by user",s):(d.error("[RNBridge] Firebase token request failed",s),new g(h.AUTH_FAILED,"Firebase token request failed",s))}}async requestFreshFirebaseIdToken(){var e;if(!this.bridge)throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new g(h.AUTH_NOT_INITIALIZED,"Bridge not activated");try{const s=await this.bridge.requestFreshFirebaseIdToken();if((s.expiresAt-Date.now())/1e3<60)throw new g(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return s}catch(s){throw s instanceof g?s:(d.error("[RNBridge] Fresh Firebase token request failed",s),new g(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",s))}}getContext(){return this.context}isActive(){var t;return!(!((t=this.context)!=null&&t.isActivated)||Date.now()-this.context.activatedAt>this.context.absoluteTtlMs)}}const Le={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://dev-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 wr(r){const e=r.environment;return e&&e in Le?Le[e]:null}function _s(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=wr(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Le)return Le[r]}catch{}return Le.production}const yr=2e3,Ft=6e4,br=1e3,Sr=1e4,vr="0x77359400",Ut="0x3B9ACA00",Ht=130,xs=6,Wt=18,Gt=3e4,Er=5*60*1e3,Ar=30*1e3,mt=100,Ir="crossx-sdk-js/2.2.0";function ms(r){let e=r.length;for(;e>0&&r.charCodeAt(e-1)===48;)e--;return r.slice(0,e)}function Tr(r){if(!r||r==="0x0"||r==="0x")return"0";try{const e=BigInt(r);if(e===0n)return"0";const s=10n**BigInt(Wt),t=e/s,i=(e%s).toString().padStart(Wt,"0"),o=ms(i).slice(0,xs);return o?`${t}.${o}`:`${t}`}catch{return"?"}}function Ge(r,e,s){if(!(!r||r==="0x"||r==="0x0"))try{const t=BigInt(r);if(t===0n)return;const n=10n**BigInt(s),i=t/n,a=(t%n).toString().padStart(s,"0"),c=ms(a.slice(0,xs));return`${c?`${i}.${c}`:`${i}`} ${e}`}catch{return}}function kr(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Ht)throw new g(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Ht} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Rr(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Or(r,e){const s=Nr(e);if(r==="0"){if(s!==void 0&&s!==0)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${s}`);return}const t=r.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(s===void 0)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${r})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(s!==n)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${s})가 chainId (${r}, 예상값: ${n})와 일치하지 않습니다`)}}function Nr(r){if(r==null||typeof r!="object")return;const e=r.domain;if(e==null||typeof e!="object")return;const s=e.chainId;if(s==null)return;const t=Number(s);return Number.isFinite(t)?t:void 0}class Ce{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 g(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 s=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,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=xe(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new g(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:s,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.pinInput_error})}catch(u){if(this.deps.pinStore.clear(),u instanceof g){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return Ce.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof g&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=xe(this.deps.getLocale()??"en"),u=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:u?this.deps.maskEmail(u,l.sessionAlert_appleAccount):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 s=xe(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof g){if(t=Ce.parsePinError(n,s),!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 g&&(t=Ce.parsePinError(n,s),t))continue;throw n}}}static parsePinError(e,s){if(e.code===h.PIN_WRONG)return{errorMessage:s.pinInput_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:s.pinLocked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:s.pinInput_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,s){const t=Ce.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Cr{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 g(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 Pr(r){return r==="google"||r==="apple"}class Lr{constructor(e){this.deps=e}async signInAgain(){var s,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=Pr(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=((s=i.user)==null?void 0:s.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=xe(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.sessionAlert_title,message:l.alert_differentAccount,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.sessionAlert_appleAccount):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(s){const t=xe(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.sessionAlert_appleAccount):void 0;if(s instanceof g&&s.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(s instanceof g&&s.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(!(s instanceof g)||s.code!==h.SESSION_EXPIRED)throw s;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:i})==="signout")throw this.deps.clearAuthState(),new g(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new g(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Dr{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,s){const t=this.deps.getUserId();if(!t)return;const n=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",n),n!=="exists")return;const i=await this.deps.walletProvider.getAddresses(t);if(i.length>0){const a=s?i.find(u=>u.address.toLowerCase()===s.toLowerCase()):void 0,c=e!==void 0?i.find(u=>u.index===e):void 0,l=a??c??i[0];d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address),this.deps.setActiveWallet(l.address,l.index);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(t,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class Br{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:s});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 f=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!f){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(f.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const x=f.pinStatus;if(o=x.maxAttempts,i=o-x.remainingAttempts,x.remainingAttempts===0&&x.lockExpiresAt){const p=x.lockExpiresAt*1e3,_=Math.max(1,Math.round((p-Date.now())/1e3)),v=_<=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 잠금 — ${_}초, 메시지: ${v}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(_,v),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(f){if(!(f instanceof g))throw f;if(f.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const x=xe(this.deps.getLocale()??"en"),p=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:x.sessionAlert_title,message:x.alert_sessionExpired,email:p?this.deps.maskEmail(p,x.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),f}if(f.code===h.MIGRATION_PIN_LOCKED){const x=f.details;if(o=(x==null?void 0:x.maxAttempts)??5,(x==null?void 0:x.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 p=((x==null?void 0:x.lockExpiresAt)??0)*1e3,_=Math.max(1,Math.round((p-Date.now())/1e3)),v=_<=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 이미 잠금 — ${_}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(_,v),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",f),f}}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 g&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof g&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const f=xe(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_sessionExpired,email:x?this.deps.maskEmail(x,f.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const v=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",v.address),v}catch(v){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",v),v}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class Mr{constructor(e){this.deps=e}async withResolvedGasAndFee(e,s){const t=p=>!(p!=null&&p.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,f,x]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],s):null,i?this.deps.estimateGas(e,s):null,o?this.deps.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const p=x;if(p){const _=Ut;c.maxFeePerGas=`0x${(BigInt(p)+BigInt(_)).toString(16)}`,c.maxPriorityFeePerGas=_,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=vr,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=Ut,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class $r{constructor(e){this.crypto=e}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new g(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof g)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Fr(r){return r?r.includes("google")?"google":r.includes("apple")?"apple":r:null}class Ur{constructor(e){this.deps=e}setActiveWallet(e,s){this.deps.setState({address:e,activeWalletIndex:s}),this.deps.emitAddressChanged({address:e,index:s}),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:s,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const s={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:Fr((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(s),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 Hr{constructor(e){this.deps=e}async resolveAddress(e){const s=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===s){if(!t)throw new g(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:s}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Wr{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new g(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new g(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Gr{constructor(e){this.deps=e}async createWallet(){const e=this.deps.getUserId();if(!e)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const s=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",s),s==="migration_required"){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",t);const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new g(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}return s==="exists"?(await this.deps.pinOrchestrator.ensureVerifiedPin(),this.tryGetOrCreateWalletWithMigrationFallback(e)):(await this.deps.pinOrchestrator.ensurePinSetup(),this.tryGetOrCreateWalletWithMigrationFallback(e))}async tryGetOrCreateWalletWithMigrationFallback(e){try{const s=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(s.address,0),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof g&&s.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};throw new g(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}}function qt(r,e){const s=r.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${s}/cross-auth${t}`}class qr{constructor(e){this.deps=e}async registerTokenHistory(e,s,t){if(!(e!=null&&e.trim()))throw new g(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(s!=null&&s.trim()))throw new g(h.TX_INVALID_PARAMS,"invalid param tx_hash");const n=s.startsWith("0x")?s:`0x${s}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new g(h.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new g(h.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=qt(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 g?c:new g(h.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const s=this.deps.getApiBaseUrl(),t=new URL(qt(s,"/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 g(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 g?i:new g(h.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,s,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,s,t);return}catch(c){if(c instanceof g&&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,s){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${s==="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 g(n.code,n.message)}}function at(r,e="Apple account"){if(r.endsWith("@privaterelay.appleid.com"))return e;const s=r.indexOf("@");if(s<0)return"*".repeat(r.length||3);const t=r.substring(0,s),n=r.substring(s);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Te=class Te extends xr{constructor(e,s,t,n,i,o,a,c,l,u,f){var x,p;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._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Dt(e.logger),this.confirmation=l,this.pinStore=f??new vt,this.stateManager=new Ur({setState:_=>{_.authenticated!==void 0&&(this.authenticated=_.authenticated),_.userId!==void 0&&(this.userId=_.userId),_.address!==void 0&&(this.address=_.address),_.activeWalletIndex!==void 0&&(this.activeWalletIndex=_.activeWalletIndex),_.userEmail!==void 0&&(this.userEmail=_.userEmail),_.providerSub!==void 0&&(this.providerSub=_.providerSub),_.loginType!==void 0&&(this.loginType=_.loginType),_.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=_.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:_,index:v})=>{this.emit("addressChanged",{address:_,index:v})},emitAuthChanged:({isAuthenticated:_,address:v,userId:S})=>{this.emit("authChanged",{isAuthenticated:_,address:v,userId:S})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Te.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ce({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:at,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Cr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Dr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(_,v)=>this.setActiveWallet(_,v)}),this.migrationOrchestrator=new Br({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(_,v)=>this.migrateWalletUseCase.execute(_,v),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:at,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var _;return((_=this._config.migration)==null?void 0:_.allowSkip)??!0}}),this.transactionLifecycleService=new Mr({getActiveAddress:()=>this.address,estimateGas:(_,v)=>this.estimateGas(_,v),getBaseFeePerGas:_=>this.getBaseFeePerGas(_),jsonRpcCall:(_,v,S)=>this.jsonRpc.call(_,v,S)}),this.signatureVerifier=new $r(this.crypto),this.addressResolverService=new Hr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Wr({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Gr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(_,v)=>this.setActiveWallet(_,v)}),this.tokenHistoryService=new qr({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Lr({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:_=>{this._isRecoveringSession=_},setAuthenticated:_=>{this.authenticated=_},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:_=>this.signInUseCase.execute(_),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:_=>this.confirmation.showSessionAlert(_),clearAuthState:()=>this.clearAuthState(),applyAuthResult:_=>this.applyAuthResult(_),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:at}),this.chainRegistry=u,this.jsonRpc=new _r(u,i),this.signInUseCase=new xt(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new fr(this.internalConfig,t,c),this.migrateWalletUseCase=new gr(t,a),(x=a.setOnUnauthorized)==null||x.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}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 s,t;d.log("[CROSSx SDK] v2.2.0 초기화 중..."),this.confirmation.setMessages(xe(this._config.locale));try{const n=_s();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Te.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(!(e!=null&&e.preferredWalletAddress)&&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)if(this.applyAuthResult(c),this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()))this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex);else try{await this.loadWalletAfterAuth(o,a)}catch(u){if(!(u instanceof g&&u.code===h.PIN_CANCELLED))throw u;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}return this.initialized=!0,d.info("[CROSSx SDK] v2.2.0 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new g(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!ge.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도");const e=new ge({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.2.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),s=await e.initialize();return this._rnBridgeService=e,this._rnBridgeWalletAddress=s.walletAddress,this.subscribeBridgeWalletChanged(),d.log("[CROSSx] RN Bridge Handshake 성공",{walletAddress:s.walletAddress??"(없음)"}),await this.signInUseCase.hasValidStoredAccessToken()?(await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 — native sign delegation 활성")),null):(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 s=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(s);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(s){return s instanceof g&&s.code===h.USER_REJECTED?(d.log("[CROSSx] Bridge 로그인 거부 — bridge 비활성화, OAuth fallback"),this._rnBridgeService=null,null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패 — OAuth fallback 차단",s),!1)}}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new g(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFreshFirebaseIdToken()}catch(e){throw d.error("[CROSSx] Fresh Firebase token request failed:",e),new g(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return ge.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(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 s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:cr(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new g(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");s={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof g?t:new g(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:s,...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,s);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,s);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof g&&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 g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw s instanceof g?s:new g(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof g?t:new g(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=ge.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(s){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",s)}this._rnBridgeService=null,this._rnBridgeWalletAddress=void 0}catch(e){throw new g(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}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof g&&s.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}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 g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(s.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof g?s:new g(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(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 g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=s.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,s){if(e.length<2)return null;if(s){const t=e.find(n=>n.address.toLowerCase()===s.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 g?e:new g(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof g?s:new g(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(xe(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,s,t){return this.withSessionRecovery(()=>this._signMessage(e,s,t))}async _signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(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:s,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:s,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof g?i:new g(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){return this.withSessionRecovery(()=>this._signTypedData(e,s,t))}async _signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Or(e,s);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:s,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:s,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return kr(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof g?i:new g(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData(Te.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=ot(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 Rr(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof g)throw o;const a=o instanceof Error?o.message:String(o);throw new g(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,s,t){return this.withSessionRecovery(()=>this._sendTransaction(e,s,t))}async _sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=ot(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 f=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return f.txHash??f.signature}}),a=(s.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,Ir).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof g)throw o;const a=o instanceof Error?o.message:String(o);throw new g(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??br,i=Sr,o=t.timeoutMs??Ft,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new g(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var v,S;if(this._isAuthenticatedViaRNBridge){const A=ge.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,s,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((v=this._config.receiptPolling)==null?void 0:v.intervalMs)??yr,l=i??((S=this._config.receiptPolling)==null?void 0:S.timeoutMs)??Ft,u=ot(e),f=s.from??"";let x,p;const _=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{x=A;const k=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),L=s.value?BigInt(s.value):0n,P=Ge(s.value,u.symbol,u.decimals),G=Ge("0x"+k.toString(16),u.symbol,u.decimals),V=Ge("0x"+(L+k).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:A.from,to:A.to??s.to,amount:P,fees:G,total:V,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(p=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:f,to:s.to,amount:Ge(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:f,to:s.to},_),p)throw p;return{chainId:e,txHash:a,receipt:x}}async bridgeSendTransactionWithWaitForReceipt(e,s,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:s,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:s,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()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new g(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof g?n:new g(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){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],s)}catch(n){const i=n instanceof Error?n.message:String(n);throw new g(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:Tr(n),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let s=this._providers.get(e);return s||(s=new fs(this,e),this._providers.set(e,s)),s}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(s=>{try{s.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof g)throw n;const i=n instanceof Error?n.message:String(n);throw new g(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,s){const t=this.address;this.stateManager.setActiveWallet(e,s),t&&e&&t.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=ge.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",s=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!s||typeof s!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",s);return}const t=s,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}this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source}),this.setActiveWallet(n,0),this._rnBridgeWalletAddress=n)}),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,s){return this.walletLifecycleService.loadWalletAfterAuth(e,s)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,s,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,s,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(),Dt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Te.WALLET_PREF_KEY="wallet_preference",Te.OFFCHAIN_CHAIN_ID="0";let Ye=Te;class Vr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return d.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw d.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw d.error("Storage clear error:",e),e}}}const ct="crossx-sdk",Kr=1,ue="data",Ee="keys",qe="aes-primary",zr=12;class Vt{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((s,t)=>{const n=indexedDB.open(e,Kr);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ue)||i.createObjectStore(ue),i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ee,qe);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ee,qe,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===ct)return null;try{const e=await this.openDB(ct),s=e.transaction([Ee,ue],"readonly"),t=s.objectStore(Ee).get(qe),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=s.objectStore(ue).getAll(),o=s.objectStore(ue).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(Ee,qe,n);for(let l=0;l<c.length;l++)await this.idbPut(ue,String(c[l]),a[l]);return indexedDB.deleteDatabase(ct),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(zr);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(ue,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(ue,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return d.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ue,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(ue)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Et(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function we(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function K(r,e,s=""){const t=Et(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function ws(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");we(r.outputLen),we(r.blockLen)}function Be(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ys(r,e){K(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function jr(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Me(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function lt(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function he(r,e){return r<<32-e|r>>>e}const Yr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Xr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Jr(r){for(let e=0;e<r.length;e++)r[e]=Xr(r[e]);return r}const Kt=Yr?r=>r:Jr,bs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Zr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function We(r){if(K(r),bs)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Zr[r[s]];return e}const pe={_0:48,_9:57,A:65,F:70,a:97,f:102};function zt(r){if(r>=pe._0&&r<=pe._9)return r-pe._0;if(r>=pe.A&&r<=pe.F)return r-(pe.A-10);if(r>=pe.a&&r<=pe.f)return r-(pe.a-10)}function Xe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(bs)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,i=0;n<s;n++,i+=2){const o=zt(r.charCodeAt(i)),a=zt(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ve(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];K(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function Ss(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function vs(r=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(r))}const Qr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function en(r,e,s){return r&e^~r&s}function tn(r,e,s){return r&e^r&s^e&s}class sn{constructor(e,s,t,n){N(this,"blockLen");N(this,"outputLen");N(this,"padOffset");N(this,"isLE");N(this,"buffer");N(this,"view");N(this,"finished",!1);N(this,"length",0);N(this,"pos",0);N(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=lt(this.buffer)}update(e){Be(this),K(e);const{view:s,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=lt(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(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Be(this),ys(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,Me(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let f=o;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=lt(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 f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,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%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ve=BigInt(2**32-1),jt=BigInt(32);function rn(r,e=!1){return e?{h:Number(r&Ve),l:Number(r>>jt&Ve)}:{h:Number(r>>jt&Ve)|0,l:Number(r&Ve)|0}}function nn(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=rn(r[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const on=(r,e,s)=>r<<s|e>>>32-s,an=(r,e,s)=>e<<s|r>>>32-s,cn=(r,e,s)=>e<<s-32|r>>>64-s,ln=(r,e,s)=>r<<s-32|e>>>64-s,dn=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]),be=new Uint32Array(64);class un extends sn{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|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,s){for(let f=0;f<16;f++,s+=4)be[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const x=be[f-15],p=be[f-2],_=he(x,7)^he(x,18)^x>>>3,v=he(p,17)^he(p,19)^p>>>10;be[f]=v+be[f-7]+_+be[f-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const x=he(a,6)^he(a,11)^he(a,25),p=u+x+en(a,c,l)+dn[f]+be[f]|0,v=(he(t,2)^he(t,13)^he(t,22))+tn(t,n,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=n,n=t,t=p+v|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(){Me(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Me(this.buffer)}}class hn extends un{constructor(){super(32);N(this,"A",ye[0]|0);N(this,"B",ye[1]|0);N(this,"C",ye[2]|0);N(this,"D",ye[3]|0);N(this,"E",ye[4]|0);N(this,"F",ye[5]|0);N(this,"G",ye[6]|0);N(this,"H",ye[7]|0)}}const pn=Ss(()=>new hn,Qr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const At=BigInt(0),wt=BigInt(1);function Je(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Es(r){if(typeof r=="bigint"){if(!je(r))throw new Error("positive bigint expected, got "+r)}else we(r);return r}function Ke(r){const e=Es(r).toString(16);return e.length&1?"0"+e:e}function As(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?At:BigInt("0x"+r)}function st(r){return As(We(r))}function Is(r){return As(We(fn(K(r)).reverse()))}function It(r,e){we(e),r=Es(r);const s=Xe(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function Ts(r,e){return It(r,e).reverse()}function fn(r){return Uint8Array.from(r)}const je=r=>typeof r=="bigint"&&At<=r;function gn(r,e,s){return je(r)&&je(e)&&je(s)&&e<=r&&r<s}function _n(r,e,s,t){if(!gn(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function xn(r){let e;for(e=0;r>At;r>>=wt,e+=1);return e}const Tt=r=>(wt<<BigInt(r))-wt;function mn(r,e,s){if(we(r,"hashLen"),we(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=S=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},x=(...S)=>s(l,ve(c,...S)),p=(S=n)=>{l=x(i,S),c=x(),S.length!==0&&(l=x(o,S),c=x())},_=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const A=[];for(;S<e;){c=x();const k=c.slice();A.push(k),S+=c.length}return ve(...A)};return(S,A)=>{f(),p(S);let k;for(;!(k=A(_()));)p();return f(),k}}function kt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[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(s,!0)}function Yt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const se=BigInt(0),te=BigInt(1),ke=BigInt(2),ks=BigInt(3),Rs=BigInt(4),Os=BigInt(5),wn=BigInt(7),Ns=BigInt(8),yn=BigInt(9),Cs=BigInt(16);function le(r,e){const s=r%e;return s>=se?s:e+s}function oe(r,e,s){let t=r;for(;e-- >se;)t*=t,t%=s;return t}function Xt(r,e){if(r===se)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected positive modulus, got "+e);let s=le(r,e),t=e,n=se,i=te;for(;s!==se;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=l}if(t!==te)throw new Error("invert: does not exist");return le(n,e)}function Rt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function Ps(r,e){const s=(r.ORDER+te)/Rs,t=r.pow(e,s);return Rt(r,t,e),t}function bn(r,e){const s=(r.ORDER-Os)/Ns,t=r.mul(e,ke),n=r.pow(t,s),i=r.mul(e,n),o=r.mul(r.mul(i,ke),n),a=r.mul(i,r.sub(o,r.ONE));return Rt(r,a,e),a}function Sn(r){const e=rt(r),s=Ls(r),t=s(e,e.neg(e.ONE)),n=s(e,t),i=s(e,e.neg(t)),o=(r+wn)/Cs;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const f=a.mul(l,n),x=a.mul(l,i),p=a.eql(a.sqr(u),c),_=a.eql(a.sqr(f),c);l=a.cmov(l,u,p),u=a.cmov(x,f,_);const v=a.eql(a.sqr(u),c),S=a.cmov(l,u,v);return Rt(a,S,c),S}}function Ls(r){if(r<ks)throw new Error("sqrt is not defined for small field");let e=r-te,s=0;for(;e%ke===se;)e/=ke,s++;let t=ke;const n=rt(r);for(;Jt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Ps;let i=n.pow(t,e);const o=(e+te)/ke;return function(c,l){if(c.is0(l))return l;if(Jt(c,l)!==1)throw new Error("Cannot find square root");let u=s,f=c.mul(c.ONE,i),x=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(x,c.ONE);){if(c.is0(x))return c.ZERO;let _=1,v=c.sqr(x);for(;!c.eql(v,c.ONE);)if(_++,v=c.sqr(v),_===u)throw new Error("Cannot find square root");const S=te<<BigInt(u-_-1),A=c.pow(f,S);u=_,f=c.sqr(A),x=c.mul(x,f),p=c.mul(p,A)}return p}}function vn(r){return r%Rs===ks?Ps:r%Ns===Os?bn:r%Cs===yn?Sn(r):Ls(r)}const En=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function An(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=En.reduce((t,n)=>(t[n]="function",t),e);return kt(r,s),r}function In(r,e,s){if(s<se)throw new Error("invalid exponent, negatives unsupported");if(s===se)return r.ONE;if(s===te)return e;let t=r.ONE,n=e;for(;s>se;)s&te&&(t=r.mul(t,n)),n=r.sqr(n),s>>=te;return t}function Ds(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function Jt(r,e){const s=(r.ORDER-te)/ke,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Tn(r,e){e!==void 0&&we(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class kn{constructor(e,s={}){N(this,"ORDER");N(this,"BITS");N(this,"BYTES");N(this,"isLE");N(this,"ZERO",se);N(this,"ONE",te);N(this,"_lengths");N(this,"_sqrt");N(this,"_mod");var o;if(e<=se)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=Tn(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 le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&te)===te}neg(e){return le(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return le(e*e,this.ORDER)}add(e,s){return le(e+s,this.ORDER)}sub(e,s){return le(e-s,this.ORDER)}mul(e,s){return le(e*s,this.ORDER)}pow(e,s){return In(this,e,s)}div(e,s){return le(e*Xt(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return Xt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=vn(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Ts(e,this.BYTES):It(e,this.BYTES)}fromBytes(e,s=!1){K(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?Is(e):st(e);if(a&&(c=le(c,o)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ds(this,e)}cmov(e,s,t){return t?s:e}}function rt(r,e={}){return new kn(r,e)}function Bs(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function Ms(r){const e=Bs(r);return e+Math.ceil(e/2)}function Rn(r,e,s=!1){K(r);const t=r.length,n=Bs(e),i=Ms(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?Is(r):st(r),a=le(o,e-te)+te;return s?Ts(a,n):It(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $e=BigInt(0),Re=BigInt(1);function Ze(r,e){const s=e.negate();return r?s:e}function Zt(r,e){const s=Ds(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function $s(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function dt(r,e){$s(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=Tt(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function Qt(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=Re);const l=e*t,u=l+Math.abs(a)-1,f=a===0,x=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:x,isNegF:p,offsetF:l}}const ut=new WeakMap,Fs=new WeakMap;function ht(r){return Fs.get(r)||1}function es(r){if(r!==$e)throw new Error("invalid wNAF")}class On{constructor(e,s){N(this,"BASE");N(this,"ZERO");N(this,"Fn");N(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>$e;)s&Re&&(t=t.add(n)),n=n.double(),s>>=Re;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=dt(s,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,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=dt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:x,offsetF:p}=Qt(t,a,o);t=c,u?i=i.add(Ze(x,s[p])):n=n.add(Ze(f,s[l]))}return es(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=dt(e,this.bits);for(let o=0;o<i.windows&&t!==$e;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Qt(t,o,i);if(t=a,!l){const f=s[c];n=n.add(u?f.negate():f)}}return es(t),n}getPrecomputes(e,s,t){let n=ut.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),ut.set(s,n))),n}cached(e,s,t){const n=ht(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const i=ht(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){$s(s,this.bits),Fs.set(e,s),ut.delete(e)}hasCache(e){return ht(e)!==1}}function Nn(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>$e||t>$e;)s&Re&&(i=i.add(n)),t&Re&&(o=o.add(n)),n=n.double(),s>>=Re,t>>=Re;return{p1:i,p2:o}}function ts(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return An(e),e}else return rt(r,{isLE:s})}function Cn(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>$e))throw new Error(`CURVE.${c} must be positive bigint`)}const n=ts(e.p,s.Fp,t),i=ts(e.n,s.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 Pn(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Us{constructor(e,s){N(this,"oHash");N(this,"iHash");N(this,"blockLen");N(this,"outputLen");N(this,"finished",!1);N(this,"destroyed",!1);if(ws(e),K(s,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(s.length>t?e.create().update(s).digest():s);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),Me(n)}update(e){return Be(this),this.iHash.update(e),this}digestInto(e){Be(this),K(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:s,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=s._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 Hs=(r,e,s)=>new Us(r,e).update(s).digest();Hs.create=(r,e)=>new Us(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ss=(r,e)=>(r+(r>=0?e:-e)/Ws)/e;function Ln(r,e,s){const[[t,n],[i,o]]=e,a=ss(o*r,s),c=ss(-n*r,s);let l=r-a*t-c*i,u=-a*n-c*o;const f=l<_e,x=u<_e;f&&(l=-l),x&&(u=-u);const p=Tt(Math.ceil(xn(s)/2))+De;if(l<_e||l>=p||u<_e||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:x,k2:u}}function yt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function pt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Je(s.lowS,"lowS"),Je(s.prehash,"prehash"),s.format!==void 0&&yt(s.format),s}class Dn extends Error{constructor(e=""){super(e)}}const Se={Err:Dn,_tlv:{encode:(r,e)=>{const{Err:s}=Se;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=Ke(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?Ke(n.length/2|128):"";return Ke(r)+i+n+e},decode(r,e){const{Err:s}=Se;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("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 s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Se;if(r<_e)throw new e("integer: negative integers are not allowed");let s=Ke(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=Se;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return st(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Se,n=K(r,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:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Se,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},_e=BigInt(0),De=BigInt(1),Ws=BigInt(2),ze=BigInt(3),Bn=BigInt(4);function Mn(r,e={}){const s=Cn("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;kt(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=qs(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f($,m,w){const{x:T,y:O}=m.toAffine(),M=t.toBytes(T);if(Je(w,"isCompressed"),w){u();const y=!t.isOdd(O);return ve(Gs(y),M)}else return ve(Uint8Array.of(4),M,t.toBytes(O))}function x($){K($,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,T=$.length,O=$[0],M=$.subarray(1);if(T===m&&(O===2||O===3)){const y=t.fromBytes(M);if(!t.isValid(y))throw new Error("bad point: is not on curve, wrong x");const b=v(y);let E;try{E=t.sqrt(b)}catch(H){const F=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();const I=t.isOdd(E);return(O&1)===1!==I&&(E=t.neg(E)),{x:y,y:E}}else if(T===w&&O===4){const y=t.BYTES,b=t.fromBytes(M.subarray(0,y)),E=t.fromBytes(M.subarray(y,y*2));if(!S(b,E))throw new Error("bad point: is not on curve");return{x:b,y:E}}else throw new Error(`bad point: got length ${T}, expected compressed=${m} or uncompressed=${w}`)}const p=e.toBytes||f,_=e.fromBytes||x;function v($){const m=t.sqr($),w=t.mul(m,$);return t.add(t.add(w,t.mul($,i.a)),i.b)}function S($,m){const w=t.sqr(m),T=v($);return t.eql(w,T)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,ze),Bn),k=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,k)))throw new Error("bad curve params: a or b");function L($,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${$}`);return m}function P($){if(!($ instanceof X))throw new Error("Weierstrass Point expected")}function G($){if(!c||!c.basises)throw new Error("no endo");return Ln($,c.basises,n.ORDER)}const V=Yt(($,m)=>{const{X:w,Y:T,Z:O}=$;if(t.eql(O,t.ONE))return{x:w,y:T};const M=$.is0();m==null&&(m=M?t.ONE:t.inv(O));const y=t.mul(w,m),b=t.mul(T,m),E=t.mul(O,m);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:y,y:b}}),Z=Yt($=>{if($.is0()){if(e.allowInfinityPoint&&!t.is0($.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:w}=$.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!S(m,w))throw new Error("bad point: equation left != right");if(!$.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function W($,m,w,T,O){return w=new X(t.mul(w.X,$),w.Y,w.Z),m=Ze(T,m),w=Ze(O,w),m.add(w)}const D=class D{constructor(m,w,T){N(this,"X");N(this,"Y");N(this,"Z");this.X=L("x",m),this.Y=L("y",w,!0),this.Z=L("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:w,y:T}=m||{};if(!m||!t.isValid(w)||!t.isValid(T))throw new Error("invalid affine point");if(m instanceof D)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(T)?D.ZERO:new D(w,T,t.ONE)}static fromBytes(m){const w=D.fromAffine(_(K(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return D.fromBytes(Xe(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return U.createCache(this,m),w||this.multiply(ze),this}assertValidity(){Z(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){P(m);const{X:w,Y:T,Z:O}=this,{X:M,Y:y,Z:b}=m,E=t.eql(t.mul(w,b),t.mul(M,O)),I=t.eql(t.mul(T,b),t.mul(y,O));return E&&I}negate(){return new D(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=i,T=t.mul(w,ze),{X:O,Y:M,Z:y}=this;let b=t.ZERO,E=t.ZERO,I=t.ZERO,R=t.mul(O,O),H=t.mul(M,M),F=t.mul(y,y),B=t.mul(O,M);return B=t.add(B,B),I=t.mul(O,y),I=t.add(I,I),b=t.mul(m,I),E=t.mul(T,F),E=t.add(b,E),b=t.sub(H,E),E=t.add(H,E),E=t.mul(b,E),b=t.mul(B,b),I=t.mul(T,I),F=t.mul(m,F),B=t.sub(R,F),B=t.mul(m,B),B=t.add(B,I),I=t.add(R,R),R=t.add(I,R),R=t.add(R,F),R=t.mul(R,B),E=t.add(E,R),F=t.mul(M,y),F=t.add(F,F),R=t.mul(F,B),b=t.sub(b,R),I=t.mul(F,H),I=t.add(I,I),I=t.add(I,I),new D(b,E,I)}add(m){P(m);const{X:w,Y:T,Z:O}=this,{X:M,Y:y,Z:b}=m;let E=t.ZERO,I=t.ZERO,R=t.ZERO;const H=i.a,F=t.mul(i.b,ze);let B=t.mul(w,M),q=t.mul(T,y),Y=t.mul(O,b),ne=t.add(w,T),z=t.add(M,y);ne=t.mul(ne,z),z=t.add(B,q),ne=t.sub(ne,z),z=t.add(w,O);let ee=t.add(M,b);return z=t.mul(z,ee),ee=t.add(B,Y),z=t.sub(z,ee),ee=t.add(T,O),E=t.add(y,b),ee=t.mul(ee,E),E=t.add(q,Y),ee=t.sub(ee,E),R=t.mul(H,z),E=t.mul(F,Y),R=t.add(E,R),E=t.sub(q,R),R=t.add(q,R),I=t.mul(E,R),q=t.add(B,B),q=t.add(q,B),Y=t.mul(H,Y),z=t.mul(F,z),q=t.add(q,Y),Y=t.sub(B,Y),Y=t.mul(H,Y),z=t.add(z,Y),B=t.mul(q,z),I=t.add(I,B),B=t.mul(ee,z),E=t.mul(ne,E),E=t.sub(E,B),B=t.mul(ne,q),R=t.mul(ee,R),R=t.add(R,B),new D(E,I,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(D.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let T,O;const M=y=>U.cached(this,y,b=>Zt(D,b));if(w){const{k1neg:y,k1:b,k2neg:E,k2:I}=G(m),{p:R,f:H}=M(b),{p:F,f:B}=M(I);O=H.add(B),T=W(w.beta,R,F,y,E)}else{const{p:y,f:b}=M(m);T=y,O=b}return Zt(D,[T,O])[0]}multiplyUnsafe(m){const{endo:w}=e,T=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===_e||T.is0())return D.ZERO;if(m===De)return T;if(U.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:M,k2neg:y,k2:b}=G(m),{p1:E,p2:I}=Nn(D,T,M,b);return W(w.beta,E,I,O,y)}else return U.unsafe(T,m)}toAffine(m){return V(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===De?!0:m?m(D,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===De?this:m?m(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return Je(m,"isCompressed"),this.assertValidity(),p(D,this,m)}toHex(m=!0){return We(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};N(D,"BASE",new D(i.Gx,i.Gy,t.ONE)),N(D,"ZERO",new D(t.ZERO,t.ONE,t.ZERO)),N(D,"Fp",t),N(D,"Fn",n);let X=D;const Q=n.BITS,U=new On(X,e.endo?Math.ceil(Q/2):Q);return X.BASE.precompute(8),X}function Gs(r){return Uint8Array.of(r?2:3)}function qs(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function $n(r,e={}){const{Fn:s}=r,t=e.randomBytes||vs,n=Object.assign(qs(r.Fp,s),{seed:Ms(s.ORDER)});function i(p){try{const _=s.fromBytes(p);return s.isValidNot0(_)}catch{return!1}}function o(p,_){const{publicKey:v,publicKeyUncompressed:S}=n;try{const A=p.length;return _===!0&&A!==v||_===!1&&A!==S?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return Rn(K(p,n.seed,"seed"),s.ORDER)}function c(p,_=!0){return r.BASE.multiply(s.fromBytes(p)).toBytes(_)}function l(p){const{secretKey:_,publicKey:v,publicKeyUncompressed:S}=n;if(!Et(p)||"_lengths"in s&&s._lengths||_===v)return;const A=K(p,void 0,"key").length;return A===v||A===S}function u(p,_,v=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(_)===!1)throw new Error("second arg must be public key");const S=s.fromBytes(p);return r.fromBytes(_).multiply(S).toBytes(v)}const f={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},x=Pn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:x,Point:r,utils:f,lengths:n})}function Fn(r,e,s={}){ws(e),kt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||vs,n=s.hmac||((m,w)=>Hs(e,m,w)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:x,lengths:p}=$n(r,s),_={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},v=a*Ws<i.ORDER;function S(m){const w=a>>De;return m>w}function A(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function k(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function L(m,w){yt(w);const T=p.signature,O=w==="compact"?T:w==="recovered"?T+1:void 0;return K(m,O)}class P{constructor(w,T,O){N(this,"r");N(this,"s");N(this,"recovery");if(this.r=A("r",w),this.s=A("s",T),O!=null){if(k(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,T=_.format){L(w,T);let O;if(T==="der"){const{r:E,s:I}=Se.toSig(K(w));return new P(E,I)}T==="recovered"&&(O=w[0],T="compact",w=w.subarray(1));const M=p.signature/2,y=w.subarray(0,M),b=w.subarray(M,M*2);return new P(o.fromBytes(y),o.fromBytes(b),O)}static fromHex(w,T){return this.fromBytes(Xe(w),T)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new P(this.r,this.s,w)}recoverPublicKey(w){const{r:T,s:O}=this,M=this.assertRecovery(),y=M===2||M===3?T+a:T;if(!i.isValid(y))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const b=i.toBytes(y),E=r.fromBytes(ve(Gs((M&1)===0),b)),I=o.inv(y),R=V(K(w,void 0,"msgHash")),H=o.create(-R*I),F=o.create(O*I),B=r.BASE.multiplyUnsafe(H).add(E.multiplyUnsafe(F));if(B.is0())throw new Error("invalid recovery: point at infinify");return B.assertValidity(),B}hasHighS(){return S(this.s)}toBytes(w=_.format){if(yt(w),w==="der")return Xe(Se.hexFromSig(this));const{r:T,s:O}=this,M=o.toBytes(T),y=o.toBytes(O);return w==="recovered"?(k(),ve(Uint8Array.of(this.assertRecovery()),M,y)):ve(M,y)}toHex(w){return We(this.toBytes(w))}}const G=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const T=st(w),O=w.length*8-c;return O>0?T>>BigInt(O):T},V=s.bits2int_modN||function(w){return o.create(G(w))},Z=Tt(c);function W(m){return _n("num < 2^"+c,m,_e,Z),o.toBytes(m)}function X(m,w){return K(m,void 0,"message"),w?K(e(m),void 0,"prehashed message"):m}function Q(m,w,T){const{lowS:O,prehash:M,extraEntropy:y}=pt(T,_);m=X(m,M);const b=V(m),E=o.fromBytes(w);if(!o.isValidNot0(E))throw new Error("invalid private key");const I=[W(E),W(b)];if(y!=null&&y!==!1){const B=y===!0?t(p.secretKey):y;I.push(K(B,void 0,"extraEntropy"))}const R=ve(...I),H=b;function F(B){const q=G(B);if(!o.isValidNot0(q))return;const Y=o.inv(q),ne=r.BASE.multiply(q).toAffine(),z=o.create(ne.x);if(z===_e)return;const ee=o.create(Y*o.create(H+z*E));if(ee===_e)return;let Pt=(ne.x===z?0:2)|Number(ne.y&De),Lt=ee;return O&&S(ee)&&(Lt=o.neg(ee),Pt^=1),new P(z,Lt,v?void 0:Pt)}return{seed:R,k2sig:F}}function U(m,w,T={}){const{seed:O,k2sig:M}=Q(m,w,T);return mn(e.outputLen,o.BYTES,n)(O,M).toBytes(T.format)}function D(m,w,T,O={}){const{lowS:M,prehash:y,format:b}=pt(O,_);if(T=K(T,void 0,"publicKey"),w=X(w,y),!Et(m)){const E=m instanceof P?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+E)}L(m,b);try{const E=P.fromBytes(m,b),I=r.fromBytes(T);if(M&&E.hasHighS())return!1;const{r:R,s:H}=E,F=V(w),B=o.inv(H),q=o.create(F*B),Y=o.create(R*B),ne=r.BASE.multiplyUnsafe(q).add(I.multiplyUnsafe(Y));return ne.is0()?!1:o.create(ne.x)===R}catch{return!1}}function $(m,w,T={}){const{prehash:O}=pt(T,_);return w=X(w,O),P.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:x,lengths:p,Point:r,sign:U,verify:D,recoverPublicKey:$,Signature:P,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ot={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Un={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},rs=BigInt(2);function Hn(r){const e=Ot.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=oe(u,s,e)*u%e,x=oe(f,s,e)*u%e,p=oe(x,rs,e)*l%e,_=oe(p,n,e)*p%e,v=oe(_,i,e)*_%e,S=oe(v,a,e)*v%e,A=oe(S,c,e)*S%e,k=oe(A,a,e)*v%e,L=oe(k,s,e)*u%e,P=oe(L,o,e)*_%e,G=oe(P,t,e)*l%e,V=oe(G,rs,e);if(!bt.eql(bt.sqr(V),r))throw new Error("Cannot find square root");return V}const bt=rt(Ot.p,{sqrt:Hn}),Wn=Mn(Ot,{Fp:bt,endo:Un}),Gn=Fn(Wn,pn),qn=BigInt(0),Fe=BigInt(1),Vn=BigInt(2),Kn=BigInt(7),zn=BigInt(256),jn=BigInt(113),Vs=[],Ks=[],zs=[];for(let r=0,e=Fe,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Vs.push(2*(5*t+s)),Ks.push((r+1)*(r+2)/2%64);let n=qn;for(let i=0;i<7;i++)e=(e<<Fe^(e>>Kn)*jn)%zn,e&Vn&&(n^=Fe<<(Fe<<BigInt(i))-Fe);zs.push(n)}const js=nn(zs,!0),Yn=js[0],Xn=js[1],ns=(r,e,s)=>s>32?cn(r,e,s):on(r,e,s),is=(r,e,s)=>s>32?ln(r,e,s):an(r,e,s);function Jn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],f=ns(l,u,1)^s[a],x=is(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)r[o+p]^=f,r[o+p+1]^=x}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=Ks[o],c=ns(n,i,a),l=is(n,i,a),u=Vs[o];n=r[u],i=r[u+1],r[u]=c,r[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Yn[t],r[1]^=Xn[t]}Me(s)}class Nt{constructor(e,s,t,n=!1,i=24){N(this,"state");N(this,"pos",0);N(this,"posOut",0);N(this,"finished",!1);N(this,"state32");N(this,"destroyed",!1);N(this,"blockLen");N(this,"suffix");N(this,"outputLen");N(this,"enableXOF",!1);N(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,we(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=jr(this.state)}clone(){return this._cloneInto()}keccak(){Kt(this.state32),Jn(this.state32,this.rounds),Kt(this.state32),this.posOut=0,this.pos=0}update(e){Be(this),K(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Be(this,!1),K(e),this.finish();const s=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(s.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 we(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ys(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,Me(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Nt(s,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 Zn=(r,e,s,t={})=>Ss(()=>new Nt(e,r,s),t),os=Zn(1,136,32),Qn=60;class ei{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=it.createRemoteJWKSet(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){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+Qn<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 it.jwtVerify(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 it.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
6
|
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=os(i),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=ti(a),l=c.slice(0,32),u=c.slice(32,64),f=c[64],x=f>=27?f-27:f,v=new Gn.Signature(as(l),as(u)).addRecoveryBit(x).recoverPublicKey(o).toBytes(!1).slice(1),S=os(v);return"0x"+We(S.slice(12))}}function ti(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function as(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const si=3e4,ri=1e3;class ni{async request(e){const s=e.retries??0;for(let t=0;t<=s;t++){try{const n=await this._doRequest(e);if(n.status<500||t===s)return n}catch(n){if(t===s)throw n}await new Promise(n=>setTimeout(n,ri*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??si);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.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 ii=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Ae{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const s=e.split(".");if(s.length<2)throw new Error("Invalid JWT format");const t=(s[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const s=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,s){const t=Ae.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 Ae.sha256Hex(s);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:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((s,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=Ae.generateRandom16Hex(),l=Ae.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",f=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const x=window.open(f,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),P(),t(new Error("Authentication timeout"))},5*60*1e3),_=10,v=30;let S=0,A=null;const k=()=>{clearInterval(L),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+v+"초간 대기합니다"),A=setTimeout(()=>{P(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},v*1e3)},L=setInterval(()=>{S++;try{x.closed&&(S<=_?k():(P(),t(new Error("로그인이 취소되었습니다"))))}catch{k()}},1e3),P=()=>{clearTimeout(p),clearInterval(L),A&&clearTimeout(A),window.removeEventListener("message",G)},G=V=>{if(V.origin!==e.expectedOrigin)return;if(!ii.has(V.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",V.origin),P(),t(new Error("Unauthorized OAuth origin"));return}P();const Z=typeof V.data.status=="string",W=Z?V.data.data??{}:V.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:Z?"wrapped":"flat",status:Z?V.data.status:"(flat)"});const X=(W==null?void 0:W.state)??V.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Z&&V.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",W==null?void 0:W.error),t(new Error((W==null?void 0:W.error)||"Authentication failed"));return}if(!Z&&(W!=null&&W.error)){d.error("[CROSSx] OAuth 실패:",W.error),t(new Error(W.error||"Authentication failed"));return}const Q=W==null?void 0:W.idToken,U=W==null?void 0:W.accessToken,D=U??Q,$=(W==null?void 0:W.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!U,hasIdToken:!!Q,hasEmail:!!$}),!D){d.error("[CROSSx] 토큰을 찾을 수 없음:",V.data),t(new Error("Token not found in response"));return}const m={token:D,email:$},w=T=>{Ae.verifyIdTokenNonce(T,l).then(()=>s(m)).catch(O=>{d.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};U?U.split(".").length===3?w(U):Q?w(Q):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(m)):Q?w(Q):t(new Error("Token not found in response"))};window.addEventListener("message",G)})}}const Ue="crossx_wallet_data",Oe="crossx_mock_pin_hash";class oi{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(Ue)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Ue);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(Ue,n);const i=(s=this.pinStore)==null?void 0:s.get();return i&&(await this.storage.set(Oe,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new g(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Ue);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${i} from=${o}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,i){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,s,t,n){return d.log(`[Mock] sendTransaction chainId=${s} 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 s=await this.storage.get(Oe);return s&&s!==e?!1:(s||await this.storage.set(Oe,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new g(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Oe);if(n&&t&&n!==t)throw new g(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Oe,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new g(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 g(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Ue,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Oe,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){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 Ie{constructor(e,s,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,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(Gt))return e;const s=!e||this.tokenStore.isExpiringSoon(Gt);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new g(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,s,t,n=!1){var c,l,u,f;const i=await this.ensureValidToken(),o=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const p=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(p&&typeof p.code=="number"){if(p.code<0||p.code>=400){const _=p.message||p.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:p.code,message:_,url:o,method:e});const v=Ie.mapGatewayError(p.code,p.data);if(v===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(v===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new g(h.USER_NOT_FOUND,Ie.getGatewayErrorMessage(p.code,_));const S=v===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:v,A=S===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ie.getGatewayErrorMessage(p.code,_),k=p.data;let L;throw v===h.PIN_LOCKED?L=Ie.extractLockDetails(k):v===h.ADDRESS_LIMIT_EXCEEDED?L={limit:mt,raw:k}:L=k??void 0,new g(S,A,L)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:p.code,url:o,method:e}),p.data??p}return p}catch(x){if(x instanceof g)throw x;const p=((l=x.response)==null?void 0:l.status)??x.status;if((p===401||p===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${p} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=x.response)!=null&&u.data){const _=x.response.data,v=_.message||_.data||"API 요청에 실패했습니다",S=_.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:S,message:v,url:o,method:e,status:(f=x.response)==null?void 0:f.status}),new g(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${S}): ${v}`)}throw x}}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 s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new g(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="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,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new g(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new g(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new g(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.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,s,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:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,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(s)}`,a);return{chainId:s,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,s,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(s)}`,o);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,i)).txHash}}async migrateWallet(e,s){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e},t=await this.request("POST","/mnemonic/verify-password",s);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new g(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 g(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 g(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,s){const t={password:this.requirePin(),newPassword:s};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,s){const t={recoveryPin:e,sub:s};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new g(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(s==null?void 0:s.permanent)=="boolean"&&(t.permanent=s.permanent),t}static hasLockInfo(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!s||typeof s!="object"?!1:typeof s.remainingAttempts=="number"||typeof s.remaining_attempts=="number"||typeof s.maxAttempts=="number"||typeof s.max_attempts=="number"}static mapGatewayError(e,s){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 Ie.hasLockInfo(s)?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,s){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 (${s}). 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 ${mt} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class ai{constructor(e,s,t){this.inner=e,this.getBridge=s,this.isAuthenticatedViaRNBridge=t,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(n,i)=>e.prepare(n,i)),e.migrateWallet&&(this.migrateWallet=(n,i)=>e.migrateWallet(n,i)),e.verifyPin&&(this.verifyPin=n=>e.verifyPin(n)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(n,i)=>e.verifyRecoveryPin(n,i))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,s,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){const c=await a.signMessage({chainId:s,message:t,from:o,index:n});return{chainId:s,signature:c.signature,format:"hex"}}return this.inner.signMessage(e,s,t,n,i,o)}async signTypedData(e,s,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){const c=await a.signTypedData({chainId:s,typedData:t,from:o,index:n});return{chainId:s,signature:c.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,s,t,n,i,o)}async signTransaction(e,s,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){const a=await o.signTransaction({chainId:s,tx:this.toBridgeTx(t),from:t.from,index:n});return{chainId:s,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,s,t,n,i)}async sendTransaction(e,s,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction)return{txHash:(await i.sendTransaction({chainId:s,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,s,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,s){return this.inner.getAddress(e,s)}setOnUnauthorized(e){var s,t;(t=(s=this.inner).setOnUnauthorized)==null||t.call(s,e)}setTokenRefresher(e){var s,t;(t=(s=this.inner).setTokenRefresher)==null||t.call(s,e)}}class He{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}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 s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=He.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?Ar:Er;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}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 s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new g(He.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=He.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new g(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(tt).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 cs="__crossx-confirm-style",J="__crossx-confirm-overlay",ci={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function ls(r,e){const s=ci[r],t=e==null?void 0:e[r];return t?{...s,...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},...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},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const li=`
|
|
7
7
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
8
8
|
|