@nexus-cross/crossx-sdk-core 1.5.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
- package/dist/crossx.global +79 -58
- package/dist/index.cjs +88 -67
- package/dist/index.js +484 -452
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var Gs=Object.defineProperty;var Ws=(r,e,s)=>e in r?Gs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var P=(r,e,s)=>Ws(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const tt=require("jose");var
|
|
1
|
+
"use strict";var Gs=Object.defineProperty;var Ws=(r,e,s)=>e in r?Gs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var P=(r,e,s)=>Ws(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const tt=require("jose");var p=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",r.SESSION_EXPIRED="SESSION_EXPIRED",r.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.BROADCAST_FAILED="BROADCAST_FAILED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",r.PIN_CANCELLED="PIN_CANCELLED",r.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",r.PIN_LOCKED="PIN_LOCKED",r.HMAC_REQUIRED="HMAC_REQUIRED",r.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",r.WITHDRAW_FAILED="WITHDRAW_FAILED",r.USER_NOT_FOUND="USER_NOT_FOUND",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class x extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,x.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Je={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},qs=Object.fromEntries(Object.entries(Je).map(([r,e])=>[r,e.caipId])),Ks=new Map(Object.values(Je).map(r=>[r.caipId,r]));new Map(Object.values(Je).map(r=>[r.chainId,r]));const Vs={symbol:"",decimals:18};function st(r){var e;return((e=Ks.get(r))==null?void 0:e.nativeCurrency)??Vs}class is{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new x(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new x(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let xe=null;function Rt(r){xe=r}const d={info(...r){if(xe){xe.log(...r);return}console.log(...r)},log(...r){if(xe){xe.log(...r);return}},warn(...r){if(xe){xe.warn(...r);return}},error(...r){if(xe){xe.error(...r);return}}},zs={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간",pinLocked_failureWarning:"추가 실패 시 계정이 잠금됩니다.",pinLocked_permanent:"너무 많은 시도 실패로 계정이 영구 잠금되었습니다.",alert_sessionExpired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_accountWithdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_walletNotFound:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_differentAccount:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
|
|
2
2
|
|
|
3
3
|
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_appleAccount:"Apple 계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},as={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"},zs={ko:js,en:as};function fe(r="en",e){return zs[r]??as}const Ot="crossx_access_token",Pt="crossx_refresh_token",Ct="crossx_user_info",Xe=class Xe{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}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 x(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let o="/login";n==="google"?o="/google":n==="apple"&&(o="/apple");const{oauthServiceUrl:i}=this.config,a=`${i}${o}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(i).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 o=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(o)?new x(h.OAUTH_POPUP_BLOCKED,o):new x(h.AUTH_FAILED,o)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var o,i,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:_}=await this.exchangeFirebaseToken(e,u);let p,b,E;try{const T=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(T).join(", ")),b=(o=T.firebase)==null?void 0:o.sign_in_provider;const R=((i=T.firebase)==null?void 0:i.identities)??{};E=T.email??((a=R.email)==null?void 0:a[0]),b==="google.com"?p=(c=R["google.com"])==null?void 0:c[0]:b==="apple.com"&&(p=(l=R["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",b,"hasProviderSub:",!!p,"email:",E??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const T=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",T.sub,"exp:",T.exp,"필드:",Object.keys(T).join(", "));const R=await this.crypto.verifyJWT(f);if(n=R.signatureVerified??!1,!R.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const F=R.payload,$=F.email??E??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",F.email??"(없음)","/ Firebase JWT:",E??"(없음)","/ OAuth 콜백:",s??"(없음)","→",$??"(없음)"),t={id:F.sub,email:$,signInProvider:b,providerSub:p},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const T=this.crypto.decodeJWT(e);t={id:T.sub,email:T.email??s,signInProvider:b,providerSub:p},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const v=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,v),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 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 o=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:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{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 o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}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 o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}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)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}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 x&&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`,o={};if(!t){const u=this.tokenStore.get()??"";u&&(o.access_token=u),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data,c=this.extractResponseErrorCode(a);if(c){const u=Xe.REFRESH_RELOGIN_CODES.has(c.code);throw new x(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 x(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.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 x&&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 o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.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,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;d.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.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(o){return d.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.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(Ct);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(Ot);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Pt);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Ct),await this.storage.remove(Ot),await this.storage.remove(Pt),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 o=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",o),o==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof x&&o.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof x&&(o.code===h.PROJECT_NOT_REGISTERED||o.code===h.PROJECT_ID_MISSING||o.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};Xe.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let ht=Xe;class Ys{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 Xs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new x(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 gt{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 o=0;o<s.length;o++)n[o]=s[o]^t[o];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 Js{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={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:o})).data;if(a!=null&&a.error)throw new x(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Zs{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()}}const Oe={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},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"},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"}};function Qs(r){const e=r.environment;return e&&e in Oe?Oe[e]:null}function er(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=Qs(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Oe)return Oe[r]}catch{}return Oe.production}const tr=2e3,Nt=6e4,sr=1e3,rr=1e4,nr="0x77359400",Lt="0x3B9ACA00",Dt=130,Mt=6,$t=18,Bt=3e4,or=5*60*1e3,ir=30*1e3;function De(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 J=class J extends Zs{constructor(e,s,t,n,o,i,a,c,l,u,f){var _,p;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,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._verifyPinMutex=null,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Rt(e.logger),this.confirmation=l,this.pinStore=f??new gt,this.chainRegistry=u,this.jsonRpc=new Js(u,o),this.signInUseCase=new ht(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Ys(this.internalConfig,t,c),this.migrateWalletUseCase=new Xs(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}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] v1.5.0 초기화 중..."),this.confirmation.setMessages(fe(this._config.locale));try{const n=er();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 o=await this.signInUseCase.restoreSession();if(o!=null&&o.success){this.applyAuthResult(o);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(i){if(!(i instanceof x&&i.code===h.PIN_CANCELLED))throw i;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v1.5.0 초기화 완료"),this.emit("initialized",{restored:!!(o!=null&&o.success)}),o??null}catch(n){throw new x(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({showConnectOtherWallets:this._config.showConnectOtherWallets});if(t==="external")throw this.emit("connectExternalWallet",{}),new x(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof x?t:new x(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}catch(t){throw t instanceof x&&t.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw new x(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new x(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(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 x&&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}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof x?s:new x(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(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 x(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.ensurePinForSigning();const n=s.length,i={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(i),i},e);return t&&(this.address=t.address,this.activeWalletIndex=t.index,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof x?e:new x(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof x?s:new x(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 o=n?"dark":"light";this.applyTheme(o,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(fe(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}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 x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({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}))throw new x(h.USER_REJECTED,"User rejected the message signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof x?i:new x(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 x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");J.validateTypedDataChainId(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({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}))throw new x(h.USER_REJECTED,"User rejected the typed data signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return J.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof x?i:new x(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData(J.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 x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=st(e);if(!await this.confirmation.requestConfirmation({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:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(h.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return J.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}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 x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=st(e);if(!await this.confirmation.requestConfirmation({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:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(h.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}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??sr,o=rr,i=t.timeoutMs??Nt,a=Date.now()+i;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,o)}throw new x(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var E,v;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((E=this._config.receiptPolling)==null?void 0:E.intervalMs)??tr,l=o??((v=this._config.receiptPolling)==null?void 0:v.timeoutMs)??Nt,u=st(e),f=s.from??"";let _,p;const b=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(T=>{_=T;const R=BigInt(T.gasUsed)*BigInt(T.effectiveGasPrice),F=s.value?BigInt(s.value):0n,$=J.formatTxAmount(s.value,u.symbol,u.decimals),K=J.formatTxAmount("0x"+R.toString(16),u.symbol,u.decimals),q=J.formatTxAmount("0x"+(F+R).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:T.from,to:T.to??s.to,amount:$,fees:K,total:q,nativeSymbol:u.symbol,status:T.status==="0x1"?"success":"reverted"}}).catch(T=>(p=T instanceof Error?T:new Error(String(T)),{chainId:e,txHash:a,from:f,to:s.to,amount:J.formatTxAmount(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},b),p)throw p;return{chainId:e,txHash:a,receipt:_}}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 x(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 x?n:new x(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 x(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 o=n instanceof Error?n.message:String(n);throw new x(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${o}`,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 x(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 x(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 x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(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:J.formatWei(n),chainId:e}}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt($t),n=s/t,i=(s%t).toString().padStart($t,"0").replace(/0+$/,"").slice(0,Mt);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new is(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof x)throw n;const o=n instanceof Error?n.message:String(n);throw new x(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,Mt).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:s});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,o=0,i=5,a=null;for(;;){o++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${i})`,n?`— 이전 메시지: ${n}`:"");const f=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:o>1?o-1:void 0,maxAttempts:i});if(f===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 _=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,f,e));if(!_){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=f;break}if(_.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=f;break}const p=_.pinStatus;if(i=p.maxAttempts,o=i-p.remainingAttempts,p.remainingAttempts===0&&p.lockExpiresAt){const b=p.lockExpiresAt*1e3,E=Math.max(1,Math.round((b-Date.now())/1e3)),v=E<=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 잠금 — ${E}초, 메시지: ${v}`),await this.confirmation.showRecoveryPinLockedPrompt(E,v),o=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${i})`),n="Incorrect PIN."}catch(_){if(!(_ instanceof x))throw _;if(_.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const p=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_sessionExpired,email:this.userEmail?De(this.userEmail,p.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),o--;continue}throw this.clearAuthState(),_}if(_.code===h.MIGRATION_PIN_LOCKED){const p=_.details;if(i=(p==null?void 0:p.maxAttempts)??5,(p==null?void 0:p.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const b=((p==null?void 0:p.lockExpiresAt)??0)*1e3,E=Math.max(1,Math.round((b-Date.now())/1e3)),v=E<=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 이미 잠금 — ${E}초`),await this.confirmation.showRecoveryPinLockedPrompt(E,v),o=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",_),_}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const f=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof x&&f.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof x&&f.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const _=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:_.sessionAlert_title,message:_.alert_sessionExpired,email:this.userEmail?De(this.userEmail,_.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const E=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",E.address),E}catch(E){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",E),E}}throw this.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}async withResolvedGasAndFee(e,s){const t=p=>!(p!=null&&p.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),o&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),i&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,f,_]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,o?this.estimateGas(e,s):null,i?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),o&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){const p=_;if(p){const b=Lt;c.maxFeePerGas="0x"+(BigInt(p)+BigInt(b)).toString(16),c.maxPriorityFeePerGas=b,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=nr,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Lt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=J.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${o})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Dt)throw new x(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Dt} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}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 x(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,o;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=J.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){var n,o;this.ensureInitialized();const e=this.providerSub,s=this.userId,t=this.loginType;this._isRecoveringSession=!0;try{this.authenticated=!1,this.tokenStore.clear();const i=t?{provider:t}:void 0;let a;try{a=await this.signInUseCase.execute(i)}catch(f){throw this.clearAuthState(),f}if(!a.success)return this.clearAuthState(),a;const c=((n=a.user)==null?void 0:n.providerSub)??null,l=((o=a.user)==null?void 0:o.id)??null;if(!(e?!!c&&c===e:s?!!l&&s===l:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const f=fe(this._config.locale??"en");return await this.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_differentAccount,email:this.userEmail?De(this.userEmail,f.sessionAlert_appleAccount):void 0})==="signin-again"?(this._isRecoveringSession=!1,this.signInAgain()):(this.clearAuthState(),{success:!1,error:"Different account signed in"})}this.applyAuthResult(a);try{await this.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),a}finally{this._isRecoveringSession=!1}}async withSessionRecovery(e){try{return await e()}catch(s){const t=fe(this._config.locale??"en"),n=this.userEmail?De(this.userEmail,t.sessionAlert_appleAccount):void 0;if(s instanceof x&&s.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(s instanceof x&&s.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(!(s instanceof x)||s.code!==h.SESSION_EXPIRED)throw s;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:n})==="signout")throw this.clearAuthState(),new x(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const i=await this.signInAgain();if(!i.success)throw new x(h.SESSION_EXPIRED,i.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new x(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,t,n){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let o,i;this._verifyPinMutex=new Promise((c,l)=>{o=c,i=l});const a=fe(this._config.locale??"en");try{if(typeof this.walletProvider.verifyPin!="function"){const l=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),o();return}const c=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.pinStore.set(l);try{return await this.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(u){if(this.pinStore.clear(),u instanceof x){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 J.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),o()}catch(c){if(c instanceof x&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:this.userEmail?De(this.userEmail,l.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success)throw i(c),c}throw i(c),c}finally{this._verifyPinMutex=null}}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=J.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...o}=t;return{ok:!1,error:n,...o}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const o=e!==void 0?t.find(i=>i.index===e)??t[0]:t[0];this.address=o.address,this.activeWalletIndex=o.index,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){const s=fe(this._config.locale??"en");let t=null;try{return await e()}catch(n){if(n instanceof x){if(t=J.parsePinError(n,s),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof x&&(t=J.parsePinError(n,s),t))continue;throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new x(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new x(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}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(),Rt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};J.OFFCHAIN_CHAIN_ID="0";let Ve=J;class ar{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 rt="crossx-sdk",cr=1,he="data",Ee="keys",He="aes-primary",lr=12;class Ut{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,cr);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(he)||o.createObjectStore(he),o.objectStoreNames.contains(Ee)||o.createObjectStore(Ee)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ee,He);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,He,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===rt)return null;try{const e=await this.openDB(rt),s=e.transaction([Ee,he],"readonly"),t=s.objectStore(Ee).get(He),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const o=s.objectStore(he).getAll(),i=s.objectStore(he).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)}),new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)})]);e.close(),await this.idbPut(Ee,He,n);for(let l=0;l<c.length;l++)await this.idbPut(he,String(c[l]),a[l]);return indexedDB.deleteDatabase(rt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(lr);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(he,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(he,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(he,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(he)}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 mt(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 V(r,e,s=""){const t=mt(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function cs(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 Ce(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 ls(r,e){V(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 dr(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Ne(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function nt(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function pe(r,e){return r<<32-e|r>>>e}const ur=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function pr(r){for(let e=0;e<r.length;e++)r[e]=hr(r[e]);return r}const Ht=ur?r=>r:pr,ds=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ue(r){if(V(r),ds)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=fr[r[s]];return e}const _e={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ft(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e.A&&r<=_e.F)return r-(_e.A-10);if(r>=_e.a&&r<=_e.f)return r-(_e.a-10)}function je(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ds)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,o=0;n<s;n++,o+=2){const i=Ft(r.charCodeAt(o)),a=Ft(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function ve(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];V(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function us(r,e={}){const s=(n,o)=>r(o).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 hs(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 _r=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function xr(r,e,s){return r&e^~r&s}function gr(r,e,s){return r&e^r&s^e&s}class mr{constructor(e,s,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=nt(this.buffer)}update(e){Ce(this),V(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=nt(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ce(this),ls(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Ne(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let f=i;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=nt(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],o)}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:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,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]),Fe=BigInt(2**32-1),Gt=BigInt(32);function wr(r,e=!1){return e?{h:Number(r&Fe),l:Number(r>>Gt&Fe)}:{h:Number(r>>Gt&Fe)|0,l:Number(r&Fe)|0}}function yr(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let o=0;o<s;o++){const{h:i,l:a}=wr(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const br=(r,e,s)=>r<<s|e>>>32-s,Sr=(r,e,s)=>e<<s|r>>>32-s,vr=(r,e,s)=>e<<s-32|r>>>64-s,Er=(r,e,s)=>r<<s-32|e>>>64-s,Ir=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 Ar extends mr{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|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 _=be[f-15],p=be[f-2],b=pe(_,7)^pe(_,18)^_>>>3,E=pe(p,17)^pe(p,19)^p>>>10;be[f]=E+be[f-7]+b+be[f-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const _=pe(a,6)^pe(a,11)^pe(a,25),p=u+_+xr(a,c,l)+Ir[f]+be[f]|0,E=(pe(t,2)^pe(t,13)^pe(t,22))+gr(t,n,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=n,n=t,t=p+E|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+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,o,i,a,c,l,u)}roundClean(){Ne(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Ne(this.buffer)}}class Tr extends Ar{constructor(){super(32);P(this,"A",ye[0]|0);P(this,"B",ye[1]|0);P(this,"C",ye[2]|0);P(this,"D",ye[3]|0);P(this,"E",ye[4]|0);P(this,"F",ye[5]|0);P(this,"G",ye[6]|0);P(this,"H",ye[7]|0)}}const kr=us(()=>new Tr,_r(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wt=BigInt(0),pt=BigInt(1);function ze(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function ps(r){if(typeof r=="bigint"){if(!Ke(r))throw new Error("positive bigint expected, got "+r)}else we(r);return r}function Ge(r){const e=ps(r).toString(16);return e.length&1?"0"+e:e}function fs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?wt:BigInt("0x"+r)}function Ze(r){return fs(Ue(r))}function _s(r){return fs(Ue(Rr(V(r)).reverse()))}function yt(r,e){we(e),r=ps(r);const s=je(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function xs(r,e){return yt(r,e).reverse()}function Rr(r){return Uint8Array.from(r)}const Ke=r=>typeof r=="bigint"&&wt<=r;function Or(r,e,s){return Ke(r)&&Ke(e)&&Ke(s)&&e<=r&&r<s}function Pr(r,e,s,t){if(!Or(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Cr(r){let e;for(e=0;r>wt;r>>=pt,e+=1);return e}const bt=r=>(pt<<BigInt(r))-pt;function Nr(r,e,s){if(we(r,"hashLen"),we(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=v=>new Uint8Array(v),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},_=(...v)=>s(l,ve(c,...v)),p=(v=n)=>{l=_(o,v),c=_(),v.length!==0&&(l=_(i,v),c=_())},b=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let v=0;const T=[];for(;v<e;){c=_();const R=c.slice();T.push(R),v+=c.length}return ve(...T)};return(v,T)=>{f(),p(v);let R;for(;!(R=T(b()));)p();return f(),R}}function St(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function Wt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ne=BigInt(0),se=BigInt(1),Te=BigInt(2),gs=BigInt(3),ms=BigInt(4),ws=BigInt(5),Lr=BigInt(7),ys=BigInt(8),Dr=BigInt(9),bs=BigInt(16);function ue(r,e){const s=r%e;return s>=ne?s:e+s}function ce(r,e,s){let t=r;for(;e-- >ne;)t*=t,t%=s;return t}function qt(r,e){if(r===ne)throw new Error("invert: expected non-zero number");if(e<=ne)throw new Error("invert: expected positive modulus, got "+e);let s=ue(r,e),t=e,n=ne,o=se;for(;s!==ne;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==se)throw new Error("invert: does not exist");return ue(n,e)}function vt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function Ss(r,e){const s=(r.ORDER+se)/ms,t=r.pow(e,s);return vt(r,t,e),t}function Mr(r,e){const s=(r.ORDER-ws)/ys,t=r.mul(e,Te),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,Te),n),a=r.mul(o,r.sub(i,r.ONE));return vt(r,a,e),a}function $r(r){const e=Qe(r),s=vs(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Lr)/bs;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,t);const f=a.mul(l,n),_=a.mul(l,o),p=a.eql(a.sqr(u),c),b=a.eql(a.sqr(f),c);l=a.cmov(l,u,p),u=a.cmov(_,f,b);const E=a.eql(a.sqr(u),c),v=a.cmov(l,u,E);return vt(a,v,c),v}}function vs(r){if(r<gs)throw new Error("sqrt is not defined for small field");let e=r-se,s=0;for(;e%Te===ne;)e/=Te,s++;let t=Te;const n=Qe(r);for(;Kt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Ss;let o=n.pow(t,e);const i=(e+se)/Te;return function(c,l){if(c.is0(l))return l;if(Kt(c,l)!==1)throw new Error("Cannot find square root");let u=s,f=c.mul(c.ONE,o),_=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let b=1,E=c.sqr(_);for(;!c.eql(E,c.ONE);)if(b++,E=c.sqr(E),b===u)throw new Error("Cannot find square root");const v=se<<BigInt(u-b-1),T=c.pow(f,v);u=b,f=c.sqr(T),_=c.mul(_,f),p=c.mul(p,T)}return p}}function Br(r){return r%ms===gs?Ss:r%ys===ws?Mr:r%bs===Dr?$r(r):vs(r)}const Ur=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Hr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Ur.reduce((t,n)=>(t[n]="function",t),e);return St(r,s),r}function Fr(r,e,s){if(s<ne)throw new Error("invalid exponent, negatives unsupported");if(s===ne)return r.ONE;if(s===se)return e;let t=r.ONE,n=e;for(;s>ne;)s&se&&(t=r.mul(t,n)),n=r.sqr(n),s>>=se;return t}function Es(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function Kt(r,e){const s=(r.ORDER-se)/Te,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function Gr(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 Wr{constructor(e,s={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ne);P(this,"ONE",se);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var i;if(e<=ne)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=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=Gr(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ne<=e&&e<this.ORDER}is0(e){return e===ne}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&se)===se}neg(e){return ue(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return ue(e*e,this.ORDER)}add(e,s){return ue(e+s,this.ORDER)}sub(e,s){return ue(e-s,this.ORDER)}mul(e,s){return ue(e*s,this.ORDER)}pow(e,s){return Fr(this,e,s)}div(e,s){return ue(e*qt(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 qt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Br(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?xs(e,this.BYTES):yt(e,this.BYTES)}fromBytes(e,s=!1){V(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_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,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?_s(e):Ze(e);if(a&&(c=ue(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Es(this,e)}cmov(e,s,t){return t?s:e}}function Qe(r,e={}){return new Wr(r,e)}function Is(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 As(r){const e=Is(r);return e+Math.ceil(e/2)}function qr(r,e,s=!1){V(r);const t=r.length,n=Is(e),o=As(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?_s(r):Ze(r),a=ue(i,e-se)+se;return s?xs(a,n):yt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Le=BigInt(0),ke=BigInt(1);function Ye(r,e){const s=e.negate();return r?s:e}function Vt(r,e){const s=Es(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function Ts(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function ot(r,e){Ts(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=bt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function jt(r,e,s){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=s;let a=Number(r&n),c=r>>i;a>t&&(a-=o,c+=ke);const l=e*t,u=l+Math.abs(a)-1,f=a===0,_=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:_,isNegF:p,offsetF:l}}const it=new WeakMap,ks=new WeakMap;function at(r){return ks.get(r)||1}function zt(r){if(r!==Le)throw new Error("invalid wNAF")}class Kr{constructor(e,s){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(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>Le;)s&ke&&(t=t.add(n)),n=n.double(),s>>=ke;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=ot(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=ot(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:_,offsetF:p}=jt(t,a,i);t=c,u?o=o.add(Ye(_,s[p])):n=n.add(Ye(f,s[l]))}return zt(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=ot(e,this.bits);for(let i=0;i<o.windows&&t!==Le;i++){const{nextN:a,offset:c,isZero:l,isNeg:u}=jt(t,i,o);if(t=a,!l){const f=s[c];n=n.add(u?f.negate():f)}}return zt(t),n}getPrecomputes(e,s,t){let n=it.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),it.set(s,n))),n}cached(e,s,t){const n=at(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=at(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){Ts(s,this.bits),ks.set(e,s),it.delete(e)}hasCache(e){return at(e)!==1}}function Vr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Le||t>Le;)s&ke&&(o=o.add(n)),t&ke&&(i=i.add(n)),n=n.double(),s>>=ke,t>>=ke;return{p1:o,p2:i}}function Yt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Hr(e),e}else return Qe(r,{isLE:s})}function jr(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>Le))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Yt(e.p,s.Fp,t),o=Yt(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:o}}function zr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Rs{constructor(e,s){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(cs(e),V(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 o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Ne(n)}update(e){return Ce(this),this.iHash.update(e),this}digestInto(e){Ce(this),V(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:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,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 Os=(r,e,s)=>new Rs(r,e).update(s).digest();Os.create=(r,e)=>new Rs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xt=(r,e)=>(r+(r>=0?e:-e)/Ps)/e;function Yr(r,e,s){const[[t,n],[o,i]]=e,a=Xt(i*r,s),c=Xt(-n*r,s);let l=r-a*t-c*o,u=-a*n-c*i;const f=l<ge,_=u<ge;f&&(l=-l),_&&(u=-u);const p=bt(Math.ceil(Cr(s)/2))+Pe;if(l<ge||l>=p||u<ge||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:_,k2:u}}function ft(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ct(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return ze(s.lowS,"lowS"),ze(s.prehash,"prehash"),s.format!==void 0&&ft(s.format),s}class Xr extends Error{constructor(e=""){super(e)}}const Se={Err:Xr,_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=Ge(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?Ge(n.length/2|128):"";return Ge(r)+o+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++],o=!!(n&128);let i=0;if(!o)i=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)i=i<<8|u;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=Se;if(r<ge)throw new e("integer: negative integers are not allowed");let s=Ge(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 Ze(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Se,n=V(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{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)),o=t+n;return e.encode(48,o)}},ge=BigInt(0),Pe=BigInt(1),Ps=BigInt(2),We=BigInt(3),Jr=BigInt(4);function Zr(r,e={}){const s=jr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;St(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ns(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(M,g,m){const{x:A,y:O}=g.toAffine(),L=t.toBytes(A);if(ze(m,"isCompressed"),m){u();const w=!t.isOdd(O);return ve(Cs(w),L)}else return ve(Uint8Array.of(4),L,t.toBytes(O))}function _(M){V(M,void 0,"Point");const{publicKey:g,publicKeyUncompressed:m}=l,A=M.length,O=M[0],L=M.subarray(1);if(A===g&&(O===2||O===3)){const w=t.fromBytes(L);if(!t.isValid(w))throw new Error("bad point: is not on curve, wrong x");const y=E(w);let S;try{S=t.sqrt(y)}catch(H){const B=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+B)}u();const I=t.isOdd(S);return(O&1)===1!==I&&(S=t.neg(S)),{x:w,y:S}}else if(A===m&&O===4){const w=t.BYTES,y=t.fromBytes(L.subarray(0,w)),S=t.fromBytes(L.subarray(w,w*2));if(!v(y,S))throw new Error("bad point: is not on curve");return{x:y,y:S}}else throw new Error(`bad point: got length ${A}, expected compressed=${g} or uncompressed=${m}`)}const p=e.toBytes||f,b=e.fromBytes||_;function E(M){const g=t.sqr(M),m=t.mul(g,M);return t.add(t.add(m,t.mul(M,o.a)),o.b)}function v(M,g){const m=t.sqr(g),A=E(M);return t.eql(m,A)}if(!v(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const T=t.mul(t.pow(o.a,We),Jr),R=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(T,R)))throw new Error("bad curve params: a or b");function F(M,g,m=!1){if(!t.isValid(g)||m&&t.is0(g))throw new Error(`bad point coordinate ${M}`);return g}function $(M){if(!(M instanceof X))throw new Error("Weierstrass Point expected")}function K(M){if(!c||!c.basises)throw new Error("no endo");return Yr(M,c.basises,n.ORDER)}const q=Wt((M,g)=>{const{X:m,Y:A,Z:O}=M;if(t.eql(O,t.ONE))return{x:m,y:A};const L=M.is0();g==null&&(g=L?t.ONE:t.inv(O));const w=t.mul(m,g),y=t.mul(A,g),S=t.mul(O,g);if(L)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:w,y}}),Q=Wt(M=>{if(M.is0()){if(e.allowInfinityPoint&&!t.is0(M.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:m}=M.toAffine();if(!t.isValid(g)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!v(g,m))throw new Error("bad point: equation left != right");if(!M.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function G(M,g,m,A,O){return m=new X(t.mul(m.X,M),m.Y,m.Z),g=Ye(A,g),m=Ye(O,m),g.add(m)}const C=class C{constructor(g,m,A){P(this,"X");P(this,"Y");P(this,"Z");this.X=F("x",g),this.Y=F("y",m,!0),this.Z=F("z",A),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){const{x:m,y:A}=g||{};if(!g||!t.isValid(m)||!t.isValid(A))throw new Error("invalid affine point");if(g instanceof C)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(A)?C.ZERO:new C(m,A,t.ONE)}static fromBytes(g){const m=C.fromAffine(b(V(g,void 0,"point")));return m.assertValidity(),m}static fromHex(g){return C.fromBytes(je(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return U.createCache(this,g),m||this.multiply(We),this}assertValidity(){Q(this)}hasEvenY(){const{y:g}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(g)}equals(g){$(g);const{X:m,Y:A,Z:O}=this,{X:L,Y:w,Z:y}=g,S=t.eql(t.mul(m,y),t.mul(L,O)),I=t.eql(t.mul(A,y),t.mul(w,O));return S&&I}negate(){return new C(this.X,t.neg(this.Y),this.Z)}double(){const{a:g,b:m}=o,A=t.mul(m,We),{X:O,Y:L,Z:w}=this;let y=t.ZERO,S=t.ZERO,I=t.ZERO,k=t.mul(O,O),H=t.mul(L,L),B=t.mul(w,w),N=t.mul(O,L);return N=t.add(N,N),I=t.mul(O,w),I=t.add(I,I),y=t.mul(g,I),S=t.mul(A,B),S=t.add(y,S),y=t.sub(H,S),S=t.add(H,S),S=t.mul(y,S),y=t.mul(N,y),I=t.mul(A,I),B=t.mul(g,B),N=t.sub(k,B),N=t.mul(g,N),N=t.add(N,I),I=t.add(k,k),k=t.add(I,k),k=t.add(k,B),k=t.mul(k,N),S=t.add(S,k),B=t.mul(L,w),B=t.add(B,B),k=t.mul(B,N),y=t.sub(y,k),I=t.mul(B,H),I=t.add(I,I),I=t.add(I,I),new C(y,S,I)}add(g){$(g);const{X:m,Y:A,Z:O}=this,{X:L,Y:w,Z:y}=g;let S=t.ZERO,I=t.ZERO,k=t.ZERO;const H=o.a,B=t.mul(o.b,We);let N=t.mul(m,L),W=t.mul(A,w),z=t.mul(O,y),ie=t.add(m,A),j=t.add(L,w);ie=t.mul(ie,j),j=t.add(N,W),ie=t.sub(ie,j),j=t.add(m,O);let te=t.add(L,y);return j=t.mul(j,te),te=t.add(N,z),j=t.sub(j,te),te=t.add(A,O),S=t.add(w,y),te=t.mul(te,S),S=t.add(W,z),te=t.sub(te,S),k=t.mul(H,j),S=t.mul(B,z),k=t.add(S,k),S=t.sub(W,k),k=t.add(W,k),I=t.mul(S,k),W=t.add(N,N),W=t.add(W,N),z=t.mul(H,z),j=t.mul(B,j),W=t.add(W,z),z=t.sub(N,z),z=t.mul(H,z),j=t.add(j,z),N=t.mul(W,j),I=t.add(I,N),N=t.mul(te,j),S=t.mul(ie,S),S=t.sub(S,N),N=t.mul(ie,W),k=t.mul(te,k),k=t.add(k,N),new C(S,I,k)}subtract(g){return this.add(g.negate())}is0(){return this.equals(C.ZERO)}multiply(g){const{endo:m}=e;if(!n.isValidNot0(g))throw new Error("invalid scalar: out of range");let A,O;const L=w=>U.cached(this,w,y=>Vt(C,y));if(m){const{k1neg:w,k1:y,k2neg:S,k2:I}=K(g),{p:k,f:H}=L(y),{p:B,f:N}=L(I);O=H.add(N),A=G(m.beta,k,B,w,S)}else{const{p:w,f:y}=L(g);A=w,O=y}return Vt(C,[A,O])[0]}multiplyUnsafe(g){const{endo:m}=e,A=this;if(!n.isValid(g))throw new Error("invalid scalar: out of range");if(g===ge||A.is0())return C.ZERO;if(g===Pe)return A;if(U.hasCache(this))return this.multiply(g);if(m){const{k1neg:O,k1:L,k2neg:w,k2:y}=K(g),{p1:S,p2:I}=Vr(C,A,L,y);return G(m.beta,S,I,O,w)}else return U.unsafe(A,g)}toAffine(g){return q(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return i===Pe?!0:g?g(C,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:g}=e;return i===Pe?this:g?g(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return ze(g,"isCompressed"),this.assertValidity(),p(C,this,g)}toHex(g=!0){return Ue(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(C,"BASE",new C(o.Gx,o.Gy,t.ONE)),P(C,"ZERO",new C(t.ZERO,t.ONE,t.ZERO)),P(C,"Fp",t),P(C,"Fn",n);let X=C;const ee=n.BITS,U=new Kr(X,e.endo?Math.ceil(ee/2):ee);return X.BASE.precompute(8),X}function Cs(r){return Uint8Array.of(r?2:3)}function Ns(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Qr(r,e={}){const{Fn:s}=r,t=e.randomBytes||hs,n=Object.assign(Ns(r.Fp,s),{seed:As(s.ORDER)});function o(p){try{const b=s.fromBytes(p);return s.isValidNot0(b)}catch{return!1}}function i(p,b){const{publicKey:E,publicKeyUncompressed:v}=n;try{const T=p.length;return b===!0&&T!==E||b===!1&&T!==v?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return qr(V(p,n.seed,"seed"),s.ORDER)}function c(p,b=!0){return r.BASE.multiply(s.fromBytes(p)).toBytes(b)}function l(p){const{secretKey:b,publicKey:E,publicKeyUncompressed:v}=n;if(!mt(p)||"_lengths"in s&&s._lengths||b===E)return;const T=V(p,void 0,"key").length;return T===E||T===v}function u(p,b,E=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(b)===!1)throw new Error("second arg must be public key");const v=s.fromBytes(p);return r.fromBytes(b).multiply(v).toBytes(E)}const f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},_=zr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:r,utils:f,lengths:n})}function en(r,e,s={}){cs(e),St(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||hs,n=s.hmac||((g,m)=>Os(e,g,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:_,lengths:p}=Qr(r,s),b={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},E=a*Ps<o.ORDER;function v(g){const m=a>>Pe;return g>m}function T(g,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return m}function R(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function F(g,m){ft(m);const A=p.signature,O=m==="compact"?A:m==="recovered"?A+1:void 0;return V(g,O)}class ${constructor(m,A,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=T("r",m),this.s=T("s",A),O!=null){if(R(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(m,A=b.format){F(m,A);let O;if(A==="der"){const{r:S,s:I}=Se.toSig(V(m));return new $(S,I)}A==="recovered"&&(O=m[0],A="compact",m=m.subarray(1));const L=p.signature/2,w=m.subarray(0,L),y=m.subarray(L,L*2);return new $(i.fromBytes(w),i.fromBytes(y),O)}static fromHex(m,A){return this.fromBytes(je(m),A)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new $(this.r,this.s,m)}recoverPublicKey(m){const{r:A,s:O}=this,L=this.assertRecovery(),w=L===2||L===3?A+a:A;if(!o.isValid(w))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const y=o.toBytes(w),S=r.fromBytes(ve(Cs((L&1)===0),y)),I=i.inv(w),k=q(V(m,void 0,"msgHash")),H=i.create(-k*I),B=i.create(O*I),N=r.BASE.multiplyUnsafe(H).add(S.multiplyUnsafe(B));if(N.is0())throw new Error("invalid recovery: point at infinify");return N.assertValidity(),N}hasHighS(){return v(this.s)}toBytes(m=b.format){if(ft(m),m==="der")return je(Se.hexFromSig(this));const{r:A,s:O}=this,L=i.toBytes(A),w=i.toBytes(O);return m==="recovered"?(R(),ve(Uint8Array.of(this.assertRecovery()),L,w)):ve(L,w)}toHex(m){return Ue(this.toBytes(m))}}const K=s.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const A=Ze(m),O=m.length*8-c;return O>0?A>>BigInt(O):A},q=s.bits2int_modN||function(m){return i.create(K(m))},Q=bt(c);function G(g){return Pr("num < 2^"+c,g,ge,Q),i.toBytes(g)}function X(g,m){return V(g,void 0,"message"),m?V(e(g),void 0,"prehashed message"):g}function ee(g,m,A){const{lowS:O,prehash:L,extraEntropy:w}=ct(A,b);g=X(g,L);const y=q(g),S=i.fromBytes(m);if(!i.isValidNot0(S))throw new Error("invalid private key");const I=[G(S),G(y)];if(w!=null&&w!==!1){const N=w===!0?t(p.secretKey):w;I.push(V(N,void 0,"extraEntropy"))}const k=ve(...I),H=y;function B(N){const W=K(N);if(!i.isValidNot0(W))return;const z=i.inv(W),ie=r.BASE.multiply(W).toAffine(),j=i.create(ie.x);if(j===ge)return;const te=i.create(z*i.create(H+j*S));if(te===ge)return;let Tt=(ie.x===j?0:2)|Number(ie.y&Pe),kt=te;return O&&v(te)&&(kt=i.neg(te),Tt^=1),new $(j,kt,E?void 0:Tt)}return{seed:k,k2sig:B}}function U(g,m,A={}){const{seed:O,k2sig:L}=ee(g,m,A);return Nr(e.outputLen,i.BYTES,n)(O,L).toBytes(A.format)}function C(g,m,A,O={}){const{lowS:L,prehash:w,format:y}=ct(O,b);if(A=V(A,void 0,"publicKey"),m=X(m,w),!mt(g)){const S=g instanceof $?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+S)}F(g,y);try{const S=$.fromBytes(g,y),I=r.fromBytes(A);if(L&&S.hasHighS())return!1;const{r:k,s:H}=S,B=q(m),N=i.inv(H),W=i.create(B*N),z=i.create(k*N),ie=r.BASE.multiplyUnsafe(W).add(I.multiplyUnsafe(z));return ie.is0()?!1:i.create(ie.x)===k}catch{return!1}}function M(g,m,A={}){const{prehash:O}=ct(A,b);return m=X(m,O),$.fromBytes(g,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:_,lengths:p,Point:r,sign:U,verify:C,recoverPublicKey:M,Signature:$,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Et={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},tn={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Jt=BigInt(2);function sn(r){const e=Et.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=ce(u,s,e)*u%e,_=ce(f,s,e)*u%e,p=ce(_,Jt,e)*l%e,b=ce(p,n,e)*p%e,E=ce(b,o,e)*b%e,v=ce(E,a,e)*E%e,T=ce(v,c,e)*v%e,R=ce(T,a,e)*E%e,F=ce(R,s,e)*u%e,$=ce(F,i,e)*b%e,K=ce($,t,e)*l%e,q=ce(K,Jt,e);if(!_t.eql(_t.sqr(q),r))throw new Error("Cannot find square root");return q}const _t=Qe(Et.p,{sqrt:sn}),rn=Zr(Et,{Fp:_t,endo:tn}),nn=en(rn,kr),on=BigInt(0),Me=BigInt(1),an=BigInt(2),cn=BigInt(7),ln=BigInt(256),dn=BigInt(113),Ls=[],Ds=[],Ms=[];for(let r=0,e=Me,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Ls.push(2*(5*t+s)),Ds.push((r+1)*(r+2)/2%64);let n=on;for(let o=0;o<7;o++)e=(e<<Me^(e>>cn)*dn)%ln,e&an&&(n^=Me<<(Me<<BigInt(o))-Me);Ms.push(n)}const $s=yr(Ms,!0),un=$s[0],hn=$s[1],Zt=(r,e,s)=>s>32?vr(r,e,s):br(r,e,s),Qt=(r,e,s)=>s>32?Er(r,e,s):Sr(r,e,s);function pn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],u=s[c+1],f=Zt(l,u,1)^s[a],_=Qt(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)r[i+p]^=f,r[i+p+1]^=_}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=Ds[i],c=Zt(n,o,a),l=Qt(n,o,a),u=Ls[i];n=r[u],o=r[u+1],r[u]=c,r[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=un[t],r[1]^=hn[t]}Ne(s)}class It{constructor(e,s,t,n=!1,o=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,we(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=dr(this.state)}clone(){return this._cloneInto()}keccak(){Ht(this.state32),pn(this.state32,this.rounds),Ht(this.state32),this.posOut=0,this.pos=0}update(e){Ce(this),V(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];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){Ce(this,!1),V(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}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(ls(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,Ne(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new It(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const fn=(r,e,s,t={})=>us(()=>new It(e,r,s),t),es=fn(1,136,32),_n=60;class xn{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=tt.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+_n<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:o}=await tt.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",o),{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 tt.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
-
${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=es(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=gn(a),l=c.slice(0,32),u=c.slice(32,64),f=c[64],_=f>=27?f-27:f,E=new nn.Signature(ts(l),ts(u)).addRecoveryBit(_).recoverPublicKey(i).toBytes(!1).slice(1),v=es(E);return"0x"+Ue(v.slice(12))}}function gn(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 ts(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const mn=3e4,wn=1e3;class yn{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,wn*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??mn);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 o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const bn=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Ie{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=Ie.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.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:o,keys:Object.keys(t)});return}if(o.includes("appleid.apple.com")){const i=await Ie.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)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:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=Ie.generateRandom16Hex(),l=Ie.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 _=window.open(f,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!_){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),$(),t(new Error("Authentication timeout"))},5*60*1e3),b=10,E=30;let v=0,T=null;const R=()=>{clearInterval(F),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),T=setTimeout(()=>{$(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},F=setInterval(()=>{v++;try{_.closed&&(v<=b?R():($(),t(new Error("로그인이 취소되었습니다"))))}catch{R()}},1e3),$=()=>{clearTimeout(p),clearInterval(F),T&&clearTimeout(T),window.removeEventListener("message",K)},K=q=>{if(q.origin!==e.expectedOrigin)return;if(!bn.has(q.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",q.origin),$(),t(new Error("Unauthorized OAuth origin"));return}$();const Q=typeof q.data.status=="string",G=Q?q.data.data??{}:q.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:Q?"wrapped":"flat",status:Q?q.data.status:"(flat)"});const X=(G==null?void 0:G.state)??q.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Q&&q.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",G==null?void 0:G.error),t(new Error((G==null?void 0:G.error)||"Authentication failed"));return}if(!Q&&(G!=null&&G.error)){d.error("[CROSSx] OAuth 실패:",G.error),t(new Error(G.error||"Authentication failed"));return}const ee=G==null?void 0:G.idToken,U=G==null?void 0:G.accessToken,C=U??ee,M=(G==null?void 0:G.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!U,hasIdToken:!!ee,hasEmail:!!M}),!C){d.error("[CROSSx] 토큰을 찾을 수 없음:",q.data),t(new Error("Token not found in response"));return}const g={token:C,email:M},m=A=>{Ie.verifyIdTokenNonce(A,l).then(()=>s(g)).catch(O=>{d.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};U?U.split(".").length===3?m(U):ee?m(ee):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(g)):ee?m(ee):t(new Error("Token not found in response"))};window.addEventListener("message",K)})}}const $e="crossx_wallet_data",Re="crossx_mock_pin_hash";class Sn{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($e)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get($e);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($e,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Re,o),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new x(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get($e);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,o,i){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,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(Re);return s&&s!==e?!1:(s||await this.storage.set(Re,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(h.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Re);if(n&&t&&n!==t)throw new x(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Re,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new x(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 x(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($e,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Re,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 Ae{constructor(e,s,t,n,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=o??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(Bt))return e;const s=!e||this.tokenStore.isExpiringSoon(Bt);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new x(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 o=await this.ensureValidToken(),i=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const p=(await this.transport.request({url:i,method:e,headers:a,body:t??void 0})).data;if(p&&typeof p.code=="number"){if(p.code<0||p.code>=400){const b=p.message||p.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:p.code,message:b,url:i,method:e});const E=Ae.mapGatewayError(p.code,p.data);if(E===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 x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(E===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new x(h.USER_NOT_FOUND,Ae.getGatewayErrorMessage(p.code,b));const v=E===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:E,T=v===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ae.getGatewayErrorMessage(p.code,b),R=p.data,F=E===h.PIN_LOCKED?Ae.extractLockDetails(R):R??void 0;throw new x(v,T,F)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:p.code,url:i,method:e}),p.data??p}return p}catch(_){if(_ instanceof x)throw _;const p=((l=_.response)==null?void 0:l.status)??_.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 x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=_.response)!=null&&u.data){const b=_.response.data,E=b.message||b.data||"API 요청에 실패했습니다",v=b.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:v,message:E,url:i,method:e,status:(f=_.response)==null?void 0:f.status}),new x(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${v}): ${E}`)}throw _}}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 x(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.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}))}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 x(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(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 x(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);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,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).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 x(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const o=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new x(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:o,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new x(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 x(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 o=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof o=="number"&&(t.remainingAttempts=o);const i=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof i=="number"&&(t.maxAttempts=i),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-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 Ae.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. 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-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class Be{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=Be.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?ir:or;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 x(Be.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Be.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Je).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 ss="__crossx-confirm-style",Z="__crossx-confirm-overlay",vn={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 rs(r,e){const s=vn[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 En=`
|
|
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"},js={ko:zs,en:as};function fe(r="en",e){return js[r]??as}const Ot="crossx_access_token",Pt="crossx_refresh_token",Ct="crossx_user_info",Xe=class Xe{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}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 x(p.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let o="/login";n==="google"?o="/google":n==="apple"&&(o="/apple");const{oauthServiceUrl:i}=this.config,a=`${i}${o}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(i).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 o=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(o)?new x(p.OAUTH_POPUP_BLOCKED,o):new x(p.AUTH_FAILED,o)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var o,i,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:_}=await this.exchangeFirebaseToken(e,u);let h,b,E;try{const T=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(T).join(", ")),b=(o=T.firebase)==null?void 0:o.sign_in_provider;const R=((i=T.firebase)==null?void 0:i.identities)??{};E=T.email??((a=R.email)==null?void 0:a[0]),b==="google.com"?h=(c=R["google.com"])==null?void 0:c[0]:b==="apple.com"&&(h=(l=R["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",b,"hasProviderSub:",!!h,"email:",E??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const T=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",T.sub,"exp:",T.exp,"필드:",Object.keys(T).join(", "));const R=await this.crypto.verifyJWT(f);if(n=R.signatureVerified??!1,!R.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const F=R.payload,$=F.email??E??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",F.email??"(없음)","/ Firebase JWT:",E??"(없음)","/ OAuth 콜백:",s??"(없음)","→",$??"(없음)"),t={id:F.sub,email:$,signInProvider:b,providerSub:h},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const T=this.crypto.decodeJWT(e);t={id:T.sub,email:T.email??s,signInProvider:b,providerSub:h},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const v=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,v),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 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 o=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:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{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 o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}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 o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}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)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}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 x&&e.code===p.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`,o={};if(!t){const u=this.tokenStore.get()??"";u&&(o.access_token=u),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data,c=this.extractResponseErrorCode(a);if(c){const u=Xe.REFRESH_RELOGIN_CODES.has(c.code);throw new x(u?p.SESSION_EXPIRED:p.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new x(p.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.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 x&&e.code===p.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 o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.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,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;d.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.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(o){return d.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.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(Ct);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(Ot);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Pt);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Ct),await this.storage.remove(Ot),await this.storage.remove(Pt),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 o=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",o),o==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof x&&o.code===p.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof x&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};Xe.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let ht=Xe;class Ys{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 Xs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new x(p.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 gt{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 o=0;o<s.length;o++)n[o]=s[o]^t[o];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 Js{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={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:o})).data;if(a!=null&&a.error)throw new x(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Zs{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()}}const Pe={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},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"},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"}};function Qs(r){const e=r.environment;return e&&e in Pe?Pe[e]:null}function er(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=Qs(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Pe)return Pe[r]}catch{}return Pe.production}const tr=2e3,Nt=6e4,sr=1e3,rr=1e4,nr="0x77359400",Lt="0x3B9ACA00",Dt=130,Mt=6,$t=18,Bt=3e4,or=5*60*1e3,ir=30*1e3;function Me(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 J=class J extends Zs{constructor(e,s,t,n,o,i,a,c,l,u,f){var _,h;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,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._verifyPinMutex=null,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Rt(e.logger),this.confirmation=l,this.pinStore=f??new gt,this.chainRegistry=u,this.jsonRpc=new Js(u,o),this.signInUseCase=new ht(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Ys(this.internalConfig,t,c),this.migrateWalletUseCase=new Xs(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(h=a.setTokenRefresher)==null||h.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}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.0.0 초기화 중..."),this.confirmation.setMessages(fe(this._config.locale));try{const n=er();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 o=await this.signInUseCase.restoreSession();if(o!=null&&o.success){this.applyAuthResult(o);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(i){if(!(i instanceof x&&i.code===p.PIN_CANCELLED))throw i;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v2.0.0 초기화 완료"),this.emit("initialized",{restored:!!(o!=null&&o.success)}),o??null}catch(n){throw new x(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new x(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({showConnectOtherWallets:this._config.showConnectOtherWallets});if(t==="external")throw this.emit("connectExternalWallet",{}),new x(p.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof x?t:new x(p.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}catch(t){throw t instanceof x&&t.code===p.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new x(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw new x(p.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new x(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new x(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(p.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 x&&s.code===p.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}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof x?s:new x(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(p.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 x(p.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.ensurePinForSigning();const n=s.length,i={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(i),i},e);return t&&(this.address=t.address,this.activeWalletIndex=t.index,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof x?e:new x(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof x?s:new x(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const o=n?"dark":"light";this.applyTheme(o,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(fe(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new x(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new x(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new x(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}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 x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({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}))throw new x(p.USER_REJECTED,"User rejected the message signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof x?i:new x(p.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 x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");J.validateTypedDataChainId(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({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}))throw new x(p.USER_REJECTED,"User rejected the typed data signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return J.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof x?i:new x(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData(J.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 x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=st(e);if(!await this.confirmation.requestConfirmation({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:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(p.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return J.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}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 x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=st(e);if(!await this.confirmation.requestConfirmation({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:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(p.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(p.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}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??sr,o=rr,i=t.timeoutMs??Nt,a=Date.now()+i;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,o)}throw new x(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var E,v;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((E=this._config.receiptPolling)==null?void 0:E.intervalMs)??tr,l=o??((v=this._config.receiptPolling)==null?void 0:v.timeoutMs)??Nt,u=st(e),f=s.from??"";let _,h;const b=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(T=>{_=T;const R=BigInt(T.gasUsed)*BigInt(T.effectiveGasPrice),F=s.value?BigInt(s.value):0n,$=J.formatTxAmount(s.value,u.symbol,u.decimals),K=J.formatTxAmount("0x"+R.toString(16),u.symbol,u.decimals),q=J.formatTxAmount("0x"+(F+R).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:T.from,to:T.to??s.to,amount:$,fees:K,total:q,nativeSymbol:u.symbol,status:T.status==="0x1"?"success":"reverted"}}).catch(T=>(h=T instanceof Error?T:new Error(String(T)),{chainId:e,txHash:a,from:f,to:s.to,amount:J.formatTxAmount(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},b),h)throw h;return{chainId:e,txHash:a,receipt:_}}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 x(p.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 x?n:new x(p.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 x(p.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 o=n instanceof Error?n.message:String(n);throw new x(p.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${o}`,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 x(p.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 x(p.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 x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(p.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:J.formatWei(n),chainId:e}}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(p.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt($t),n=s/t,i=(s%t).toString().padStart($t,"0").replace(/0+$/,"").slice(0,Mt);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new is(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof x)throw n;const o=n instanceof Error?n.message:String(n);throw new x(p.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,Mt).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:s});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,o=0,i=5,a=null;for(;;){o++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${i})`,n?`— 이전 메시지: ${n}`:"");const f=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:o>1?o-1:void 0,maxAttempts:i});if(f===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 _=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,f,e));if(!_){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=f;break}if(_.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=f;break}const h=_.pinStatus;if(i=h.maxAttempts,o=i-h.remainingAttempts,h.remainingAttempts===0&&h.lockExpiresAt){const b=h.lockExpiresAt*1e3,E=Math.max(1,Math.round((b-Date.now())/1e3)),v=E<=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 잠금 — ${E}초, 메시지: ${v}`),await this.confirmation.showRecoveryPinLockedPrompt(E,v),o=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${i})`),n="Incorrect PIN."}catch(_){if(!(_ instanceof x))throw _;if(_.code===p.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const h=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:h.sessionAlert_title,message:h.alert_sessionExpired,email:this.userEmail?Me(this.userEmail,h.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),o--;continue}throw this.clearAuthState(),_}if(_.code===p.MIGRATION_PIN_LOCKED){const h=_.details;if(i=(h==null?void 0:h.maxAttempts)??5,(h==null?void 0:h.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const b=((h==null?void 0:h.lockExpiresAt)??0)*1e3,E=Math.max(1,Math.round((b-Date.now())/1e3)),v=E<=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 이미 잠금 — ${E}초`),await this.confirmation.showRecoveryPinLockedPrompt(E,v),o=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",_),_}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const f=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof x&&f.code===p.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof x&&f.code===p.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const _=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:_.sessionAlert_title,message:_.alert_sessionExpired,email:this.userEmail?Me(this.userEmail,_.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const E=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",E.address),E}catch(E){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",E),E}}throw this.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}async withResolvedGasAndFee(e,s){const t=h=>!(h!=null&&h.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),o&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),i&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,f,_]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,o?this.estimateGas(e,s):null,i?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),o&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){const h=_;if(h){const b=Lt;c.maxFeePerGas="0x"+(BigInt(h)+BigInt(b)).toString(16),c.maxPriorityFeePerGas=b,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",h,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=nr,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Lt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=J.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new x(p.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new x(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new x(p.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${o})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Dt)throw new x(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Dt} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new x(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}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 x(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,o;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=J.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){var n,o;this.ensureInitialized();const e=this.providerSub,s=this.userId,t=this.loginType;this._isRecoveringSession=!0;try{this.authenticated=!1,this.tokenStore.clear();const i=t?{provider:t}:void 0;let a;try{a=await this.signInUseCase.execute(i)}catch(f){throw this.clearAuthState(),f}if(!a.success)return this.clearAuthState(),a;const c=((n=a.user)==null?void 0:n.providerSub)??null,l=((o=a.user)==null?void 0:o.id)??null;if(!(e?!!c&&c===e:s?!!l&&s===l:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const f=fe(this._config.locale??"en");return await this.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_differentAccount,email:this.userEmail?Me(this.userEmail,f.sessionAlert_appleAccount):void 0})==="signin-again"?(this._isRecoveringSession=!1,this.signInAgain()):(this.clearAuthState(),{success:!1,error:"Different account signed in"})}this.applyAuthResult(a);try{await this.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),a}finally{this._isRecoveringSession=!1}}async withSessionRecovery(e){try{return await e()}catch(s){const t=fe(this._config.locale??"en"),n=this.userEmail?Me(this.userEmail,t.sessionAlert_appleAccount):void 0;if(s instanceof x&&s.code===p.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(s instanceof x&&s.code===p.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(!(s instanceof x)||s.code!==p.SESSION_EXPIRED)throw s;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:n})==="signout")throw this.clearAuthState(),new x(p.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const i=await this.signInAgain();if(!i.success)throw new x(p.SESSION_EXPIRED,i.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new x(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new x(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,t,n){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let o,i;this._verifyPinMutex=new Promise((c,l)=>{o=c,i=l});const a=fe(this._config.locale??"en");try{if(typeof this.walletProvider.verifyPin!="function"){const l=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new x(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),o();return}const c=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.pinStore.set(l);try{return await this.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(u){if(this.pinStore.clear(),u instanceof x){if(u.code===p.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(u.code===p.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===p.PIN_LOCKED)return J.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new x(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),o()}catch(c){if(c instanceof x&&(c.code===p.AUTH_NOT_AUTHENTICATED||c.code===p.AUTH_TOKEN_EXPIRED||c.code===p.SESSION_EXPIRED)&&c.code!==p.SESSION_EXPIRED){const l=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:this.userEmail?Me(this.userEmail,l.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success)throw i(c),c}throw i(c),c}finally{this._verifyPinMutex=null}}static parsePinError(e,s){if(e.code===p.PIN_WRONG)return{errorMessage:s.pinInput_error};if(e.code===p.PIN_INVALID)return{errorMessage:e.message};if(e.code===p.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=J.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...o}=t;return{ok:!1,error:n,...o}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const o=e!==void 0?t.find(i=>i.index===e)??t[0]:t[0];this.address=o.address,this.activeWalletIndex=o.index,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){const s=fe(this._config.locale??"en");let t=null;try{return await e()}catch(n){if(n instanceof x){if(t=J.parsePinError(n,s),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof x&&(t=J.parsePinError(n,s),t))continue;throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new x(p.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new x(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}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(),Rt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};J.OFFCHAIN_CHAIN_ID="0";let Ve=J;class ar{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 rt="crossx-sdk",cr=1,he="data",Ee="keys",Fe="aes-primary",lr=12;class Ut{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,cr);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(he)||o.createObjectStore(he),o.objectStoreNames.contains(Ee)||o.createObjectStore(Ee)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ee,Fe);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,Fe,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===rt)return null;try{const e=await this.openDB(rt),s=e.transaction([Ee,he],"readonly"),t=s.objectStore(Ee).get(Fe),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const o=s.objectStore(he).getAll(),i=s.objectStore(he).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)}),new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)})]);e.close(),await this.idbPut(Ee,Fe,n);for(let l=0;l<c.length;l++)await this.idbPut(he,String(c[l]),a[l]);return indexedDB.deleteDatabase(rt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(lr);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(he,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(he,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(he,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(he)}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 mt(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 V(r,e,s=""){const t=mt(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function cs(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 Ne(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 ls(r,e){V(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 dr(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Le(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function nt(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function pe(r,e){return r<<32-e|r>>>e}const ur=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function hr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function pr(r){for(let e=0;e<r.length;e++)r[e]=hr(r[e]);return r}const Ht=ur?r=>r:pr,ds=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function He(r){if(V(r),ds)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=fr[r[s]];return e}const _e={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ft(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e.A&&r<=_e.F)return r-(_e.A-10);if(r>=_e.a&&r<=_e.f)return r-(_e.a-10)}function ze(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ds)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,o=0;n<s;n++,o+=2){const i=Ft(r.charCodeAt(o)),a=Ft(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function ve(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];V(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function us(r,e={}){const s=(n,o)=>r(o).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 hs(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 _r=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function xr(r,e,s){return r&e^~r&s}function gr(r,e,s){return r&e^r&s^e&s}class mr{constructor(e,s,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=nt(this.buffer)}update(e){Ne(this),V(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=nt(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ne(this),ls(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Le(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let f=i;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=nt(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],o)}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:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,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]),Ge=BigInt(2**32-1),Gt=BigInt(32);function wr(r,e=!1){return e?{h:Number(r&Ge),l:Number(r>>Gt&Ge)}:{h:Number(r>>Gt&Ge)|0,l:Number(r&Ge)|0}}function yr(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let o=0;o<s;o++){const{h:i,l:a}=wr(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const br=(r,e,s)=>r<<s|e>>>32-s,Sr=(r,e,s)=>e<<s|r>>>32-s,vr=(r,e,s)=>e<<s-32|r>>>64-s,Er=(r,e,s)=>r<<s-32|e>>>64-s,Ir=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 Ar extends mr{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|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 _=be[f-15],h=be[f-2],b=pe(_,7)^pe(_,18)^_>>>3,E=pe(h,17)^pe(h,19)^h>>>10;be[f]=E+be[f-7]+b+be[f-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const _=pe(a,6)^pe(a,11)^pe(a,25),h=u+_+xr(a,c,l)+Ir[f]+be[f]|0,E=(pe(t,2)^pe(t,13)^pe(t,22))+gr(t,n,o)|0;u=l,l=c,c=a,a=i+h|0,i=o,o=n,n=t,t=h+E|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+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,o,i,a,c,l,u)}roundClean(){Le(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Le(this.buffer)}}class Tr extends Ar{constructor(){super(32);P(this,"A",ye[0]|0);P(this,"B",ye[1]|0);P(this,"C",ye[2]|0);P(this,"D",ye[3]|0);P(this,"E",ye[4]|0);P(this,"F",ye[5]|0);P(this,"G",ye[6]|0);P(this,"H",ye[7]|0)}}const kr=us(()=>new Tr,_r(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wt=BigInt(0),pt=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 ps(r){if(typeof r=="bigint"){if(!Ke(r))throw new Error("positive bigint expected, got "+r)}else we(r);return r}function We(r){const e=ps(r).toString(16);return e.length&1?"0"+e:e}function fs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?wt:BigInt("0x"+r)}function Ze(r){return fs(He(r))}function _s(r){return fs(He(Rr(V(r)).reverse()))}function yt(r,e){we(e),r=ps(r);const s=ze(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function xs(r,e){return yt(r,e).reverse()}function Rr(r){return Uint8Array.from(r)}const Ke=r=>typeof r=="bigint"&&wt<=r;function Or(r,e,s){return Ke(r)&&Ke(e)&&Ke(s)&&e<=r&&r<s}function Pr(r,e,s,t){if(!Or(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Cr(r){let e;for(e=0;r>wt;r>>=pt,e+=1);return e}const bt=r=>(pt<<BigInt(r))-pt;function Nr(r,e,s){if(we(r,"hashLen"),we(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=v=>new Uint8Array(v),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},_=(...v)=>s(l,ve(c,...v)),h=(v=n)=>{l=_(o,v),c=_(),v.length!==0&&(l=_(i,v),c=_())},b=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let v=0;const T=[];for(;v<e;){c=_();const R=c.slice();T.push(R),v+=c.length}return ve(...T)};return(v,T)=>{f(),h(v);let R;for(;!(R=T(b()));)h();return f(),R}}function St(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function Wt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ne=BigInt(0),se=BigInt(1),Te=BigInt(2),gs=BigInt(3),ms=BigInt(4),ws=BigInt(5),Lr=BigInt(7),ys=BigInt(8),Dr=BigInt(9),bs=BigInt(16);function ue(r,e){const s=r%e;return s>=ne?s:e+s}function ce(r,e,s){let t=r;for(;e-- >ne;)t*=t,t%=s;return t}function qt(r,e){if(r===ne)throw new Error("invert: expected non-zero number");if(e<=ne)throw new Error("invert: expected positive modulus, got "+e);let s=ue(r,e),t=e,n=ne,o=se;for(;s!==ne;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==se)throw new Error("invert: does not exist");return ue(n,e)}function vt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function Ss(r,e){const s=(r.ORDER+se)/ms,t=r.pow(e,s);return vt(r,t,e),t}function Mr(r,e){const s=(r.ORDER-ws)/ys,t=r.mul(e,Te),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,Te),n),a=r.mul(o,r.sub(i,r.ONE));return vt(r,a,e),a}function $r(r){const e=Qe(r),s=vs(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Lr)/bs;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,t);const f=a.mul(l,n),_=a.mul(l,o),h=a.eql(a.sqr(u),c),b=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(_,f,b);const E=a.eql(a.sqr(u),c),v=a.cmov(l,u,E);return vt(a,v,c),v}}function vs(r){if(r<gs)throw new Error("sqrt is not defined for small field");let e=r-se,s=0;for(;e%Te===ne;)e/=Te,s++;let t=Te;const n=Qe(r);for(;Kt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Ss;let o=n.pow(t,e);const i=(e+se)/Te;return function(c,l){if(c.is0(l))return l;if(Kt(c,l)!==1)throw new Error("Cannot find square root");let u=s,f=c.mul(c.ONE,o),_=c.pow(l,e),h=c.pow(l,i);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let b=1,E=c.sqr(_);for(;!c.eql(E,c.ONE);)if(b++,E=c.sqr(E),b===u)throw new Error("Cannot find square root");const v=se<<BigInt(u-b-1),T=c.pow(f,v);u=b,f=c.sqr(T),_=c.mul(_,f),h=c.mul(h,T)}return h}}function Br(r){return r%ms===gs?Ss:r%ys===ws?Mr:r%bs===Dr?$r(r):vs(r)}const Ur=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Hr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Ur.reduce((t,n)=>(t[n]="function",t),e);return St(r,s),r}function Fr(r,e,s){if(s<ne)throw new Error("invalid exponent, negatives unsupported");if(s===ne)return r.ONE;if(s===se)return e;let t=r.ONE,n=e;for(;s>ne;)s&se&&(t=r.mul(t,n)),n=r.sqr(n),s>>=se;return t}function Es(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function Kt(r,e){const s=(r.ORDER-se)/Te,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function Gr(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 Wr{constructor(e,s={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ne);P(this,"ONE",se);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var i;if(e<=ne)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=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=Gr(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ne<=e&&e<this.ORDER}is0(e){return e===ne}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&se)===se}neg(e){return ue(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return ue(e*e,this.ORDER)}add(e,s){return ue(e+s,this.ORDER)}sub(e,s){return ue(e-s,this.ORDER)}mul(e,s){return ue(e*s,this.ORDER)}pow(e,s){return Fr(this,e,s)}div(e,s){return ue(e*qt(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 qt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Br(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?xs(e,this.BYTES):yt(e,this.BYTES)}fromBytes(e,s=!1){V(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_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,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?_s(e):Ze(e);if(a&&(c=ue(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Es(this,e)}cmov(e,s,t){return t?s:e}}function Qe(r,e={}){return new Wr(r,e)}function Is(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 As(r){const e=Is(r);return e+Math.ceil(e/2)}function qr(r,e,s=!1){V(r);const t=r.length,n=Is(e),o=As(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?_s(r):Ze(r),a=ue(i,e-se)+se;return s?xs(a,n):yt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const De=BigInt(0),ke=BigInt(1);function Ye(r,e){const s=e.negate();return r?s:e}function Vt(r,e){const s=Es(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function Ts(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function ot(r,e){Ts(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=bt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function zt(r,e,s){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=s;let a=Number(r&n),c=r>>i;a>t&&(a-=o,c+=ke);const l=e*t,u=l+Math.abs(a)-1,f=a===0,_=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:_,isNegF:h,offsetF:l}}const it=new WeakMap,ks=new WeakMap;function at(r){return ks.get(r)||1}function jt(r){if(r!==De)throw new Error("invalid wNAF")}class Kr{constructor(e,s){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(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>De;)s&ke&&(t=t.add(n)),n=n.double(),s>>=ke;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=ot(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=ot(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:_,offsetF:h}=zt(t,a,i);t=c,u?o=o.add(Ye(_,s[h])):n=n.add(Ye(f,s[l]))}return jt(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=ot(e,this.bits);for(let i=0;i<o.windows&&t!==De;i++){const{nextN:a,offset:c,isZero:l,isNeg:u}=zt(t,i,o);if(t=a,!l){const f=s[c];n=n.add(u?f.negate():f)}}return jt(t),n}getPrecomputes(e,s,t){let n=it.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),it.set(s,n))),n}cached(e,s,t){const n=at(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=at(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){Ts(s,this.bits),ks.set(e,s),it.delete(e)}hasCache(e){return at(e)!==1}}function Vr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>De||t>De;)s&ke&&(o=o.add(n)),t&ke&&(i=i.add(n)),n=n.double(),s>>=ke,t>>=ke;return{p1:o,p2:i}}function Yt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Hr(e),e}else return Qe(r,{isLE:s})}function zr(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>De))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Yt(e.p,s.Fp,t),o=Yt(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:o}}function jr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Rs{constructor(e,s){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(cs(e),V(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 o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Le(n)}update(e){return Ne(this),this.iHash.update(e),this}digestInto(e){Ne(this),V(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:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,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 Os=(r,e,s)=>new Rs(r,e).update(s).digest();Os.create=(r,e)=>new Rs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xt=(r,e)=>(r+(r>=0?e:-e)/Ps)/e;function Yr(r,e,s){const[[t,n],[o,i]]=e,a=Xt(i*r,s),c=Xt(-n*r,s);let l=r-a*t-c*o,u=-a*n-c*i;const f=l<ge,_=u<ge;f&&(l=-l),_&&(u=-u);const h=bt(Math.ceil(Cr(s)/2))+Ce;if(l<ge||l>=h||u<ge||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:_,k2:u}}function ft(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ct(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&&ft(s.format),s}class Xr extends Error{constructor(e=""){super(e)}}const Se={Err:Xr,_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=We(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?We(n.length/2|128):"";return We(r)+o+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++],o=!!(n&128);let i=0;if(!o)i=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)i=i<<8|u;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=Se;if(r<ge)throw new e("integer: negative integers are not allowed");let s=We(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 Ze(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Se,n=V(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{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)),o=t+n;return e.encode(48,o)}},ge=BigInt(0),Ce=BigInt(1),Ps=BigInt(2),qe=BigInt(3),Jr=BigInt(4);function Zr(r,e={}){const s=zr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;St(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ns(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(M,g,m){const{x:A,y:O}=g.toAffine(),L=t.toBytes(A);if(je(m,"isCompressed"),m){u();const w=!t.isOdd(O);return ve(Cs(w),L)}else return ve(Uint8Array.of(4),L,t.toBytes(O))}function _(M){V(M,void 0,"Point");const{publicKey:g,publicKeyUncompressed:m}=l,A=M.length,O=M[0],L=M.subarray(1);if(A===g&&(O===2||O===3)){const w=t.fromBytes(L);if(!t.isValid(w))throw new Error("bad point: is not on curve, wrong x");const y=E(w);let S;try{S=t.sqrt(y)}catch(H){const B=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+B)}u();const I=t.isOdd(S);return(O&1)===1!==I&&(S=t.neg(S)),{x:w,y:S}}else if(A===m&&O===4){const w=t.BYTES,y=t.fromBytes(L.subarray(0,w)),S=t.fromBytes(L.subarray(w,w*2));if(!v(y,S))throw new Error("bad point: is not on curve");return{x:y,y:S}}else throw new Error(`bad point: got length ${A}, expected compressed=${g} or uncompressed=${m}`)}const h=e.toBytes||f,b=e.fromBytes||_;function E(M){const g=t.sqr(M),m=t.mul(g,M);return t.add(t.add(m,t.mul(M,o.a)),o.b)}function v(M,g){const m=t.sqr(g),A=E(M);return t.eql(m,A)}if(!v(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const T=t.mul(t.pow(o.a,qe),Jr),R=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(T,R)))throw new Error("bad curve params: a or b");function F(M,g,m=!1){if(!t.isValid(g)||m&&t.is0(g))throw new Error(`bad point coordinate ${M}`);return g}function $(M){if(!(M instanceof X))throw new Error("Weierstrass Point expected")}function K(M){if(!c||!c.basises)throw new Error("no endo");return Yr(M,c.basises,n.ORDER)}const q=Wt((M,g)=>{const{X:m,Y:A,Z:O}=M;if(t.eql(O,t.ONE))return{x:m,y:A};const L=M.is0();g==null&&(g=L?t.ONE:t.inv(O));const w=t.mul(m,g),y=t.mul(A,g),S=t.mul(O,g);if(L)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:w,y}}),Z=Wt(M=>{if(M.is0()){if(e.allowInfinityPoint&&!t.is0(M.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:m}=M.toAffine();if(!t.isValid(g)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!v(g,m))throw new Error("bad point: equation left != right");if(!M.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function G(M,g,m,A,O){return m=new X(t.mul(m.X,M),m.Y,m.Z),g=Ye(A,g),m=Ye(O,m),g.add(m)}const C=class C{constructor(g,m,A){P(this,"X");P(this,"Y");P(this,"Z");this.X=F("x",g),this.Y=F("y",m,!0),this.Z=F("z",A),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){const{x:m,y:A}=g||{};if(!g||!t.isValid(m)||!t.isValid(A))throw new Error("invalid affine point");if(g instanceof C)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(A)?C.ZERO:new C(m,A,t.ONE)}static fromBytes(g){const m=C.fromAffine(b(V(g,void 0,"point")));return m.assertValidity(),m}static fromHex(g){return C.fromBytes(ze(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return U.createCache(this,g),m||this.multiply(qe),this}assertValidity(){Z(this)}hasEvenY(){const{y:g}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(g)}equals(g){$(g);const{X:m,Y:A,Z:O}=this,{X:L,Y:w,Z:y}=g,S=t.eql(t.mul(m,y),t.mul(L,O)),I=t.eql(t.mul(A,y),t.mul(w,O));return S&&I}negate(){return new C(this.X,t.neg(this.Y),this.Z)}double(){const{a:g,b:m}=o,A=t.mul(m,qe),{X:O,Y:L,Z:w}=this;let y=t.ZERO,S=t.ZERO,I=t.ZERO,k=t.mul(O,O),H=t.mul(L,L),B=t.mul(w,w),N=t.mul(O,L);return N=t.add(N,N),I=t.mul(O,w),I=t.add(I,I),y=t.mul(g,I),S=t.mul(A,B),S=t.add(y,S),y=t.sub(H,S),S=t.add(H,S),S=t.mul(y,S),y=t.mul(N,y),I=t.mul(A,I),B=t.mul(g,B),N=t.sub(k,B),N=t.mul(g,N),N=t.add(N,I),I=t.add(k,k),k=t.add(I,k),k=t.add(k,B),k=t.mul(k,N),S=t.add(S,k),B=t.mul(L,w),B=t.add(B,B),k=t.mul(B,N),y=t.sub(y,k),I=t.mul(B,H),I=t.add(I,I),I=t.add(I,I),new C(y,S,I)}add(g){$(g);const{X:m,Y:A,Z:O}=this,{X:L,Y:w,Z:y}=g;let S=t.ZERO,I=t.ZERO,k=t.ZERO;const H=o.a,B=t.mul(o.b,qe);let N=t.mul(m,L),W=t.mul(A,w),j=t.mul(O,y),ie=t.add(m,A),z=t.add(L,w);ie=t.mul(ie,z),z=t.add(N,W),ie=t.sub(ie,z),z=t.add(m,O);let te=t.add(L,y);return z=t.mul(z,te),te=t.add(N,j),z=t.sub(z,te),te=t.add(A,O),S=t.add(w,y),te=t.mul(te,S),S=t.add(W,j),te=t.sub(te,S),k=t.mul(H,z),S=t.mul(B,j),k=t.add(S,k),S=t.sub(W,k),k=t.add(W,k),I=t.mul(S,k),W=t.add(N,N),W=t.add(W,N),j=t.mul(H,j),z=t.mul(B,z),W=t.add(W,j),j=t.sub(N,j),j=t.mul(H,j),z=t.add(z,j),N=t.mul(W,z),I=t.add(I,N),N=t.mul(te,z),S=t.mul(ie,S),S=t.sub(S,N),N=t.mul(ie,W),k=t.mul(te,k),k=t.add(k,N),new C(S,I,k)}subtract(g){return this.add(g.negate())}is0(){return this.equals(C.ZERO)}multiply(g){const{endo:m}=e;if(!n.isValidNot0(g))throw new Error("invalid scalar: out of range");let A,O;const L=w=>U.cached(this,w,y=>Vt(C,y));if(m){const{k1neg:w,k1:y,k2neg:S,k2:I}=K(g),{p:k,f:H}=L(y),{p:B,f:N}=L(I);O=H.add(N),A=G(m.beta,k,B,w,S)}else{const{p:w,f:y}=L(g);A=w,O=y}return Vt(C,[A,O])[0]}multiplyUnsafe(g){const{endo:m}=e,A=this;if(!n.isValid(g))throw new Error("invalid scalar: out of range");if(g===ge||A.is0())return C.ZERO;if(g===Ce)return A;if(U.hasCache(this))return this.multiply(g);if(m){const{k1neg:O,k1:L,k2neg:w,k2:y}=K(g),{p1:S,p2:I}=Vr(C,A,L,y);return G(m.beta,S,I,O,w)}else return U.unsafe(A,g)}toAffine(g){return q(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return i===Ce?!0:g?g(C,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:g}=e;return i===Ce?this:g?g(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return je(g,"isCompressed"),this.assertValidity(),h(C,this,g)}toHex(g=!0){return He(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(C,"BASE",new C(o.Gx,o.Gy,t.ONE)),P(C,"ZERO",new C(t.ZERO,t.ONE,t.ZERO)),P(C,"Fp",t),P(C,"Fn",n);let X=C;const Q=n.BITS,U=new Kr(X,e.endo?Math.ceil(Q/2):Q);return X.BASE.precompute(8),X}function Cs(r){return Uint8Array.of(r?2:3)}function Ns(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Qr(r,e={}){const{Fn:s}=r,t=e.randomBytes||hs,n=Object.assign(Ns(r.Fp,s),{seed:As(s.ORDER)});function o(h){try{const b=s.fromBytes(h);return s.isValidNot0(b)}catch{return!1}}function i(h,b){const{publicKey:E,publicKeyUncompressed:v}=n;try{const T=h.length;return b===!0&&T!==E||b===!1&&T!==v?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=t(n.seed)){return qr(V(h,n.seed,"seed"),s.ORDER)}function c(h,b=!0){return r.BASE.multiply(s.fromBytes(h)).toBytes(b)}function l(h){const{secretKey:b,publicKey:E,publicKeyUncompressed:v}=n;if(!mt(h)||"_lengths"in s&&s._lengths||b===E)return;const T=V(h,void 0,"key").length;return T===E||T===v}function u(h,b,E=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(b)===!1)throw new Error("second arg must be public key");const v=s.fromBytes(h);return r.fromBytes(b).multiply(v).toBytes(E)}const f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},_=jr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:r,utils:f,lengths:n})}function en(r,e,s={}){cs(e),St(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||hs,n=s.hmac||((g,m)=>Os(e,g,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:_,lengths:h}=Qr(r,s),b={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},E=a*Ps<o.ORDER;function v(g){const m=a>>Ce;return g>m}function T(g,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return m}function R(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function F(g,m){ft(m);const A=h.signature,O=m==="compact"?A:m==="recovered"?A+1:void 0;return V(g,O)}class ${constructor(m,A,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=T("r",m),this.s=T("s",A),O!=null){if(R(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(m,A=b.format){F(m,A);let O;if(A==="der"){const{r:S,s:I}=Se.toSig(V(m));return new $(S,I)}A==="recovered"&&(O=m[0],A="compact",m=m.subarray(1));const L=h.signature/2,w=m.subarray(0,L),y=m.subarray(L,L*2);return new $(i.fromBytes(w),i.fromBytes(y),O)}static fromHex(m,A){return this.fromBytes(ze(m),A)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new $(this.r,this.s,m)}recoverPublicKey(m){const{r:A,s:O}=this,L=this.assertRecovery(),w=L===2||L===3?A+a:A;if(!o.isValid(w))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const y=o.toBytes(w),S=r.fromBytes(ve(Cs((L&1)===0),y)),I=i.inv(w),k=q(V(m,void 0,"msgHash")),H=i.create(-k*I),B=i.create(O*I),N=r.BASE.multiplyUnsafe(H).add(S.multiplyUnsafe(B));if(N.is0())throw new Error("invalid recovery: point at infinify");return N.assertValidity(),N}hasHighS(){return v(this.s)}toBytes(m=b.format){if(ft(m),m==="der")return ze(Se.hexFromSig(this));const{r:A,s:O}=this,L=i.toBytes(A),w=i.toBytes(O);return m==="recovered"?(R(),ve(Uint8Array.of(this.assertRecovery()),L,w)):ve(L,w)}toHex(m){return He(this.toBytes(m))}}const K=s.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const A=Ze(m),O=m.length*8-c;return O>0?A>>BigInt(O):A},q=s.bits2int_modN||function(m){return i.create(K(m))},Z=bt(c);function G(g){return Pr("num < 2^"+c,g,ge,Z),i.toBytes(g)}function X(g,m){return V(g,void 0,"message"),m?V(e(g),void 0,"prehashed message"):g}function Q(g,m,A){const{lowS:O,prehash:L,extraEntropy:w}=ct(A,b);g=X(g,L);const y=q(g),S=i.fromBytes(m);if(!i.isValidNot0(S))throw new Error("invalid private key");const I=[G(S),G(y)];if(w!=null&&w!==!1){const N=w===!0?t(h.secretKey):w;I.push(V(N,void 0,"extraEntropy"))}const k=ve(...I),H=y;function B(N){const W=K(N);if(!i.isValidNot0(W))return;const j=i.inv(W),ie=r.BASE.multiply(W).toAffine(),z=i.create(ie.x);if(z===ge)return;const te=i.create(j*i.create(H+z*S));if(te===ge)return;let Tt=(ie.x===z?0:2)|Number(ie.y&Ce),kt=te;return O&&v(te)&&(kt=i.neg(te),Tt^=1),new $(z,kt,E?void 0:Tt)}return{seed:k,k2sig:B}}function U(g,m,A={}){const{seed:O,k2sig:L}=Q(g,m,A);return Nr(e.outputLen,i.BYTES,n)(O,L).toBytes(A.format)}function C(g,m,A,O={}){const{lowS:L,prehash:w,format:y}=ct(O,b);if(A=V(A,void 0,"publicKey"),m=X(m,w),!mt(g)){const S=g instanceof $?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+S)}F(g,y);try{const S=$.fromBytes(g,y),I=r.fromBytes(A);if(L&&S.hasHighS())return!1;const{r:k,s:H}=S,B=q(m),N=i.inv(H),W=i.create(B*N),j=i.create(k*N),ie=r.BASE.multiplyUnsafe(W).add(I.multiplyUnsafe(j));return ie.is0()?!1:i.create(ie.x)===k}catch{return!1}}function M(g,m,A={}){const{prehash:O}=ct(A,b);return m=X(m,O),$.fromBytes(g,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:_,lengths:h,Point:r,sign:U,verify:C,recoverPublicKey:M,Signature:$,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Et={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},tn={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Jt=BigInt(2);function sn(r){const e=Et.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=ce(u,s,e)*u%e,_=ce(f,s,e)*u%e,h=ce(_,Jt,e)*l%e,b=ce(h,n,e)*h%e,E=ce(b,o,e)*b%e,v=ce(E,a,e)*E%e,T=ce(v,c,e)*v%e,R=ce(T,a,e)*E%e,F=ce(R,s,e)*u%e,$=ce(F,i,e)*b%e,K=ce($,t,e)*l%e,q=ce(K,Jt,e);if(!_t.eql(_t.sqr(q),r))throw new Error("Cannot find square root");return q}const _t=Qe(Et.p,{sqrt:sn}),rn=Zr(Et,{Fp:_t,endo:tn}),nn=en(rn,kr),on=BigInt(0),$e=BigInt(1),an=BigInt(2),cn=BigInt(7),ln=BigInt(256),dn=BigInt(113),Ls=[],Ds=[],Ms=[];for(let r=0,e=$e,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Ls.push(2*(5*t+s)),Ds.push((r+1)*(r+2)/2%64);let n=on;for(let o=0;o<7;o++)e=(e<<$e^(e>>cn)*dn)%ln,e&an&&(n^=$e<<($e<<BigInt(o))-$e);Ms.push(n)}const $s=yr(Ms,!0),un=$s[0],hn=$s[1],Zt=(r,e,s)=>s>32?vr(r,e,s):br(r,e,s),Qt=(r,e,s)=>s>32?Er(r,e,s):Sr(r,e,s);function pn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],u=s[c+1],f=Zt(l,u,1)^s[a],_=Qt(l,u,1)^s[a+1];for(let h=0;h<50;h+=10)r[i+h]^=f,r[i+h+1]^=_}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=Ds[i],c=Zt(n,o,a),l=Qt(n,o,a),u=Ls[i];n=r[u],o=r[u+1],r[u]=c,r[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=un[t],r[1]^=hn[t]}Le(s)}class It{constructor(e,s,t,n=!1,o=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,we(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=dr(this.state)}clone(){return this._cloneInto()}keccak(){Ht(this.state32),pn(this.state32,this.rounds),Ht(this.state32),this.posOut=0,this.pos=0}update(e){Ne(this),V(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];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){Ne(this,!1),V(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}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(ls(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,Le(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new It(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const fn=(r,e,s,t={})=>us(()=>new It(e,r,s),t),es=fn(1,136,32),_n=60;class xn{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=tt.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+_n<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:o}=await tt.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",o),{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 tt.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
+
${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=es(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=gn(a),l=c.slice(0,32),u=c.slice(32,64),f=c[64],_=f>=27?f-27:f,E=new nn.Signature(ts(l),ts(u)).addRecoveryBit(_).recoverPublicKey(i).toBytes(!1).slice(1),v=es(E);return"0x"+He(v.slice(12))}}function gn(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 ts(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const mn=3e4,wn=1e3;class yn{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,wn*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??mn);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 o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const bn=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Ie{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=Ie.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.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:o,keys:Object.keys(t)});return}if(o.includes("appleid.apple.com")){const i=await Ie.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)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:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=Ie.generateRandom16Hex(),l=Ie.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 _=window.open(f,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!_){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const h=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),$(),t(new Error("Authentication timeout"))},5*60*1e3),b=10,E=30;let v=0,T=null;const R=()=>{clearInterval(F),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),T=setTimeout(()=>{$(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},F=setInterval(()=>{v++;try{_.closed&&(v<=b?R():($(),t(new Error("로그인이 취소되었습니다"))))}catch{R()}},1e3),$=()=>{clearTimeout(h),clearInterval(F),T&&clearTimeout(T),window.removeEventListener("message",K)},K=q=>{if(q.origin!==e.expectedOrigin)return;if(!bn.has(q.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",q.origin),$(),t(new Error("Unauthorized OAuth origin"));return}$();const Z=typeof q.data.status=="string",G=Z?q.data.data??{}:q.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:Z?"wrapped":"flat",status:Z?q.data.status:"(flat)"});const X=(G==null?void 0:G.state)??q.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Z&&q.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",G==null?void 0:G.error),t(new Error((G==null?void 0:G.error)||"Authentication failed"));return}if(!Z&&(G!=null&&G.error)){d.error("[CROSSx] OAuth 실패:",G.error),t(new Error(G.error||"Authentication failed"));return}const Q=G==null?void 0:G.idToken,U=G==null?void 0:G.accessToken,C=U??Q,M=(G==null?void 0:G.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!U,hasIdToken:!!Q,hasEmail:!!M}),!C){d.error("[CROSSx] 토큰을 찾을 수 없음:",q.data),t(new Error("Token not found in response"));return}const g={token:C,email:M},m=A=>{Ie.verifyIdTokenNonce(A,l).then(()=>s(g)).catch(O=>{d.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};U?U.split(".").length===3?m(U):Q?m(Q):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(g)):Q?m(Q):t(new Error("Token not found in response"))};window.addEventListener("message",K)})}}const Be="crossx_wallet_data",Re="crossx_mock_pin_hash";class Sn{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(Be)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Be);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(Be,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Re,o),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new x(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Be);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,o,i){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,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(Re);return s&&s!==e?!1:(s||await this.storage.set(Re,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(p.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Re);if(n&&t&&n!==t)throw new x(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Re,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new x(p.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 x(p.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(Be,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Re,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 Ae{constructor(e,s,t,n,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=o??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(Bt))return e;const s=!e||this.tokenStore.isExpiringSoon(Bt);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new x(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new x(p.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 o=await this.ensureValidToken(),i=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const h=(await this.transport.request({url:i,method:e,headers:a,body:t??void 0})).data;if(h&&typeof h.code=="number"){if(h.code<0||h.code>=400){const b=h.message||h.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:h.code,message:b,url:i,method:e});const E=Ae.mapGatewayError(h.code,h.data);if(E===p.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new x(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(E===p.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new x(p.USER_NOT_FOUND,Ae.getGatewayErrorMessage(h.code,b));const v=E===p.AUTH_NOT_AUTHENTICATED?p.SESSION_EXPIRED:E,T=v===p.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ae.getGatewayErrorMessage(h.code,b),R=h.data,F=E===p.PIN_LOCKED?Ae.extractLockDetails(R):R??void 0;throw new x(v,T,F)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:h.code,url:i,method:e}),h.data??h}return h}catch(_){if(_ instanceof x)throw _;const h=((l=_.response)==null?void 0:l.status)??_.status;if((h===401||h===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${h} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new x(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=_.response)!=null&&u.data){const b=_.response.data,E=b.message||b.data||"API 요청에 실패했습니다",v=b.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:v,message:E,url:i,method:e,status:(f=_.response)==null?void 0:f.status}),new x(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${v}): ${E}`)}throw _}}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 x(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.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}))}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 x(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(p.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 x(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);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,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).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 x(p.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const o=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new x(p.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:o,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new x(p.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 x(p.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 o=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof o=="number"&&(t.remainingAttempts=o);const i=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof i=="number"&&(t.maxAttempts=i),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 p.AUTH_NOT_AUTHENTICATED;case-10001:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10007:return p.BROADCAST_FAILED;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10004:return p.WALLET_ALREADY_EXISTS;case-10005:return p.WALLET_NOT_FOUND;case-10011:return p.WALLET_NOT_FOUND;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10013:return p.WITHDRAW_FAILED;case-10033:return p.USER_NOT_FOUND;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10025:return p.INVALID_APP_TYPE;case-10028:return Ae.hasLockInfo(s)?p.PIN_LOCKED:p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10032:return p.PIN_REPEATED_PATTERN;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10040:return p.HMAC_REQUIRED;case-10041:return p.HMAC_VERIFICATION_FAILED;default:return p.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. 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-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class Ue{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=Ue.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?ir:or;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 x(Ue.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Ue.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Je).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const ss="__crossx-confirm-style",ee="__crossx-confirm-overlay",vn={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 rs(r,e){const s=vn[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 En=`
|
|
7
7
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
8
8
|
|
|
9
|
-
#${
|
|
9
|
+
#${ee} {
|
|
10
10
|
position: fixed;
|
|
11
11
|
inset: 0;
|
|
12
12
|
z-index: 2147483647;
|
|
@@ -1184,6 +1184,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1184
1184
|
.__crossx-wallet-item {
|
|
1185
1185
|
display: flex;
|
|
1186
1186
|
align-items: center;
|
|
1187
|
+
justify-content: space-between;
|
|
1187
1188
|
gap: 8px;
|
|
1188
1189
|
padding: 16px;
|
|
1189
1190
|
background: var(--cx-pill-bg);
|
|
@@ -1196,6 +1197,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1196
1197
|
box-shadow: none;
|
|
1197
1198
|
outline: none;
|
|
1198
1199
|
width: 100%;
|
|
1200
|
+
text-align: left;
|
|
1199
1201
|
font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1200
1202
|
}
|
|
1201
1203
|
.__crossx-wallet-item:hover,
|
|
@@ -1208,28 +1210,28 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1208
1210
|
transform: none !important;
|
|
1209
1211
|
background: var(--cx-pill-bg) !important;
|
|
1210
1212
|
}
|
|
1211
|
-
.__crossx-wallet-
|
|
1212
|
-
display:
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
font-size: 12px;
|
|
1219
|
-
font-weight: 700;
|
|
1220
|
-
line-height: 1;
|
|
1221
|
-
color: var(--cx-primary);
|
|
1222
|
-
background: color-mix(in srgb, var(--cx-primary) 12%, transparent);
|
|
1223
|
-
border-radius: 6px;
|
|
1224
|
-
flex-shrink: 0;
|
|
1213
|
+
.__crossx-wallet-info {
|
|
1214
|
+
display: flex;
|
|
1215
|
+
flex-direction: column;
|
|
1216
|
+
align-items: flex-start;
|
|
1217
|
+
gap: 2px;
|
|
1218
|
+
min-width: 0;
|
|
1219
|
+
flex: 1;
|
|
1225
1220
|
}
|
|
1226
|
-
.__crossx-wallet-
|
|
1221
|
+
.__crossx-wallet-idx {
|
|
1227
1222
|
font-size: 16px;
|
|
1228
1223
|
font-weight: 600;
|
|
1229
1224
|
line-height: 1.3;
|
|
1230
1225
|
color: var(--cx-value);
|
|
1231
1226
|
white-space: nowrap;
|
|
1232
1227
|
}
|
|
1228
|
+
.__crossx-wallet-addr {
|
|
1229
|
+
font-size: 13px;
|
|
1230
|
+
font-weight: 500;
|
|
1231
|
+
line-height: 1.3;
|
|
1232
|
+
color: var(--cx-label);
|
|
1233
|
+
white-space: nowrap;
|
|
1234
|
+
}
|
|
1233
1235
|
.__crossx-wallet-selected {
|
|
1234
1236
|
font-size: 14px;
|
|
1235
1237
|
font-weight: 600;
|
|
@@ -1287,18 +1289,23 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1287
1289
|
color: var(--cx-subtitle);
|
|
1288
1290
|
}
|
|
1289
1291
|
|
|
1292
|
+
/* ── Safe area fill (mobile only, created by JS in mountOverlay) ── */
|
|
1293
|
+
.__crossx-safe-area-fill {
|
|
1294
|
+
display: none;
|
|
1295
|
+
}
|
|
1290
1296
|
/* ── Mobile bottom sheet ───────────────────────────────────── */
|
|
1291
1297
|
@media (max-width: 480px) {
|
|
1292
|
-
#${
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
position:
|
|
1298
|
+
#${ee} { align-items: flex-end; }
|
|
1299
|
+
.__crossx-safe-area-fill {
|
|
1300
|
+
display: block;
|
|
1301
|
+
position: fixed;
|
|
1296
1302
|
bottom: 0;
|
|
1297
1303
|
left: 0;
|
|
1298
1304
|
right: 0;
|
|
1299
|
-
height:
|
|
1300
|
-
|
|
1305
|
+
height: calc(env(safe-area-inset-bottom, 0px) + 16px);
|
|
1306
|
+
min-height: 16px;
|
|
1301
1307
|
pointer-events: none;
|
|
1308
|
+
z-index: 2147483646;
|
|
1302
1309
|
}
|
|
1303
1310
|
.__crossx-card {
|
|
1304
1311
|
width: 100%;
|
|
@@ -1308,7 +1315,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1308
1315
|
box-sizing: border-box;
|
|
1309
1316
|
max-height: 85vh;
|
|
1310
1317
|
overflow-y: auto;
|
|
1311
|
-
padding-bottom: 16px;
|
|
1318
|
+
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 16px);
|
|
1312
1319
|
animation: __crossx-slide-up-mobile 0.25s ease;
|
|
1313
1320
|
}
|
|
1314
1321
|
.__crossx-card--wallet-selector {
|
|
@@ -1347,15 +1354,30 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1347
1354
|
.__crossx-card--send-tx,
|
|
1348
1355
|
.__crossx-card--sign-tx,
|
|
1349
1356
|
.__crossx-card--sign-msg,
|
|
1350
|
-
.__crossx-card--sign-typed {
|
|
1357
|
+
.__crossx-card--sign-typed {
|
|
1358
|
+
overflow: hidden !important;
|
|
1359
|
+
display: flex !important;
|
|
1360
|
+
flex-direction: column !important;
|
|
1361
|
+
}
|
|
1351
1362
|
.__crossx-card--send-tx .__crossx-body,
|
|
1352
1363
|
.__crossx-card--sign-tx .__crossx-body,
|
|
1353
1364
|
.__crossx-card--sign-msg .__crossx-body,
|
|
1354
|
-
.__crossx-card--sign-typed .__crossx-body {
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1365
|
+
.__crossx-card--sign-typed .__crossx-body {
|
|
1366
|
+
flex: 1;
|
|
1367
|
+
min-height: 0;
|
|
1368
|
+
overflow-y: auto;
|
|
1369
|
+
-webkit-overflow-scrolling: touch;
|
|
1370
|
+
}
|
|
1371
|
+
.__crossx-card--send-tx .__crossx-btn-row,
|
|
1372
|
+
.__crossx-card--sign-tx .__crossx-btn-row,
|
|
1373
|
+
.__crossx-card--sign-msg .__crossx-btn-row,
|
|
1374
|
+
.__crossx-card--sign-typed .__crossx-btn-row,
|
|
1375
|
+
.__crossx-card--send-tx .__crossx-body > .__crossx-approve-btn,
|
|
1376
|
+
.__crossx-card--sign-tx .__crossx-body > .__crossx-approve-btn,
|
|
1377
|
+
.__crossx-card--sign-msg .__crossx-body > .__crossx-approve-btn,
|
|
1378
|
+
.__crossx-card--sign-typed .__crossx-body > .__crossx-approve-btn {
|
|
1379
|
+
flex-shrink: 0;
|
|
1380
|
+
}
|
|
1359
1381
|
.__crossx-login-btn-row {
|
|
1360
1382
|
flex-direction: column;
|
|
1361
1383
|
}
|
|
@@ -1481,7 +1503,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1481
1503
|
|
|
1482
1504
|
/* ── Landscape for signing/transaction modals ──────────── */
|
|
1483
1505
|
@media (orientation: landscape) and (max-height: 500px) {
|
|
1484
|
-
#${
|
|
1506
|
+
#${ee} { align-items: center !important; overflow: hidden; }
|
|
1485
1507
|
.__crossx-card--send-tx,
|
|
1486
1508
|
.__crossx-card--sign-tx,
|
|
1487
1509
|
.__crossx-card--sign-msg,
|
|
@@ -1976,7 +1998,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1976
1998
|
color: var(--cx-title);
|
|
1977
1999
|
margin: 0;
|
|
1978
2000
|
}
|
|
1979
|
-
`;function le(){let r=document.getElementById(ss);r||(r=document.createElement("style"),r.id=ss,document.head.appendChild(r)),r.textContent=En}function de(r){const e=r.querySelector(".__crossx-card");if(e){const
|
|
2001
|
+
`;function le(){let r=document.getElementById(ss);r||(r=document.createElement("style"),r.id=ss,document.head.appendChild(r)),r.textContent=En}function de(r){const e=r.querySelector(".__crossx-card");if(e){const n=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(n){const o=n[1].trim();r.style.setProperty("--cx-bg",o);const i=document.createElement("div");i.className="__crossx-safe-area-fill",i.style.background=o,r.appendChild(i)}}const s=t=>t.stopPropagation();for(const t of["pointerdown","pointerup","mousedown","mouseup","click"])r.addEventListener(t,s);r.setAttribute("data-vaul-no-drag","");for(const t of["touchstart","touchend"])r.addEventListener(t,s);r.addEventListener("touchmove",t=>{t.stopPropagation();let n=t.target;for(;n&&n!==r;){const o=window.getComputedStyle(n);if((o.overflowY==="auto"||o.overflowY==="scroll")&&n.scrollHeight>n.clientHeight)return;n=n.parentElement}t.preventDefault()},{passive:!1}),document.body.appendChild(r)}const In=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Oe(){if(In()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}}function re(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function An(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=xt(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const ns={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Bs(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&ns[e]?ns[e]:r}function xt(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,i=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function lt(r){try{const e=BigInt(r),s=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${s}.${n}`:`${s}`}catch{return r}}function Tn(r){try{return BigInt(r).toLocaleString()}catch{return r}}function kn(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:o="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=Tn(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${xt(l,i)} ${o}`,maxFeeGwei:lt(t),maxPriorityFeeGwei:n?lt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${xt(l,i)} ${o}`,gasPriceGwei:lt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Us(r){const e=kn(r);if(!e)return Y("Estimated fee","<span>—</span>");let s=Y("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=Y("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=Y("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=Y("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=Y("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const me=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1980
2002
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
1981
2003
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
1982
2004
|
</svg>`,oe=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
@@ -2000,7 +2022,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2000
2022
|
<span class="__crossx-row-label">${r}</span>
|
|
2001
2023
|
<div class="__crossx-row-value">${e}</div>
|
|
2002
2024
|
</div>`}function Cn(r,e){const s=e,t=et(r.dappName),n=r.to?`<span class="__crossx-addr-text">${re(r.to)}</span>
|
|
2003
|
-
<button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${me}</button>`:"<span>—</span>",o=Us(r),i=r.data??"0x",a=document.createElement("div");return a.id=
|
|
2025
|
+
<button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${me}</button>`:"<span>—</span>",o=Us(r),i=r.data??"0x",a=document.createElement("div");return a.id=ee,a.innerHTML=`
|
|
2004
2026
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2005
2027
|
<div class="__crossx-header">
|
|
2006
2028
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -2036,7 +2058,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2036
2058
|
</div>
|
|
2037
2059
|
</div>
|
|
2038
2060
|
`,a}function Nn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=et(r.dappName),i=r.to?`<span class="__crossx-addr-text">${re(r.to)}</span>
|
|
2039
|
-
<button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${me}</button>`:"<span>—</span>",a=Us(r),l=An(r.value,t,n)??"—",u=document.createElement("div");return u.id=
|
|
2061
|
+
<button class="__crossx-copy-btn" data-copy="${D(r.to)}" title="Copy address">${me}</button>`:"<span>—</span>",a=Us(r),l=An(r.value,t,n)??"—",u=document.createElement("div");return u.id=ee,u.innerHTML=`
|
|
2040
2062
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2041
2063
|
<div class="__crossx-header">
|
|
2042
2064
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
@@ -2067,7 +2089,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2067
2089
|
<button class="__crossx-copy-btn" data-copy="${D(r.txHash)}" title="Copy hash">${me}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
|
|
2068
2090
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
2069
2091
|
<span class="__crossx-total-amount">${D(r.total)}</span>
|
|
2070
|
-
</div>`:"",c=document.createElement("div");return c.id=
|
|
2092
|
+
</div>`:"",c=document.createElement("div");return c.id=ee,c.innerHTML=`
|
|
2071
2093
|
<div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2072
2094
|
<div class="__crossx-header">
|
|
2073
2095
|
<p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
|
|
@@ -2086,7 +2108,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2086
2108
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
|
|
2087
2109
|
</div>
|
|
2088
2110
|
</div>
|
|
2089
|
-
`,c}function $n(r,e){const s=document.createElement("div");return s.id=
|
|
2111
|
+
`,c}function $n(r,e){const s=document.createElement("div");return s.id=ee,s.innerHTML=`
|
|
2090
2112
|
<div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2091
2113
|
<div class="__crossx-header">
|
|
2092
2114
|
<p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
|
|
@@ -2102,7 +2124,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2102
2124
|
`,s}function Bn(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(o){const b=n?Pn:t?"":On,E=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";b?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${b}<span>${E}</span>`):o.textContent=E}if(i&&!r.querySelector("#__crossx-close-btn")){const b=document.createElement("button");b.className="__crossx-close",b.id="__crossx-close-btn",b.setAttribute("aria-label","Close"),b.innerHTML=oe,i.appendChild(b)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?Y("From",`<span class="__crossx-addr-text">${re(e.from)}</span>
|
|
2103
2125
|
<button class="__crossx-copy-btn" data-copy="${D(e.from)}" title="Copy address">${me}</button>`):"",l=e.to?Y("To",`<span class="__crossx-addr-text">${re(e.to)}</span>
|
|
2104
2126
|
<button class="__crossx-copy-btn" data-copy="${D(e.to)}" title="Copy address">${me}</button>`):"",u=e.amount?Y("Transfer",`<span>${D(e.amount)}</span>`):"",f=e.fees?Y("Tx Fee",`<span>${D(e.fees)}</span>`):"",_=e.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${re(e.txHash)}</span>
|
|
2105
|
-
<button class="__crossx-copy-btn" data-copy="${D(e.txHash)}" title="Copy hash">${me}</button>`):"",
|
|
2127
|
+
<button class="__crossx-copy-btn" data-copy="${D(e.txHash)}" title="Copy hash">${me}</button>`):"",h=e.total?`<div class="__crossx-total-pill">
|
|
2106
2128
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
2107
2129
|
<span class="__crossx-total-amount">${D(e.total)}</span>
|
|
2108
2130
|
</div>`:"";a.innerHTML=`
|
|
@@ -2113,9 +2135,9 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2113
2135
|
${f}
|
|
2114
2136
|
${_}
|
|
2115
2137
|
</div>
|
|
2116
|
-
${
|
|
2138
|
+
${h}
|
|
2117
2139
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
2118
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(b=>{b.addEventListener("click",E=>{var T;E.stopPropagation();const v=b.dataset.copy;v&&((T=navigator.clipboard)==null||T.writeText(v).catch(()=>{}))})})}function Un(r,e){const s=e,t=et(r.dappName),n=D(r.message),o=document.createElement("div");return o.id=
|
|
2140
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(b=>{b.addEventListener("click",E=>{var T;E.stopPropagation();const v=b.dataset.copy;v&&((T=navigator.clipboard)==null||T.writeText(v).catch(()=>{}))})})}function Un(r,e){const s=e,t=et(r.dappName),n=D(r.message),o=document.createElement("div");return o.id=ee,o.innerHTML=`
|
|
2119
2141
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2120
2142
|
<div class="__crossx-header">
|
|
2121
2143
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -2147,12 +2169,12 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2147
2169
|
<div class="__crossx-td-row">
|
|
2148
2170
|
<span class="__crossx-td-label">Primary Type</span>
|
|
2149
2171
|
<span class="__crossx-td-value">${D(o)}</span>
|
|
2150
|
-
</div>`;for(const[l,u]of Object.entries(i)){const f=Dn(u),
|
|
2172
|
+
</div>`;for(const[l,u]of Object.entries(i)){const f=Dn(u),h=Ln(u)?`<span class="__crossx-addr-text">${re(u)}</span>
|
|
2151
2173
|
<button class="__crossx-copy-btn" data-copy="${D(String(u))}" title="Copy">${me}</button>`:`<span>${f}</span>`;a+=`
|
|
2152
2174
|
<div class="__crossx-td-row">
|
|
2153
2175
|
<span class="__crossx-td-label">${D(l)}</span>
|
|
2154
|
-
<div class="__crossx-td-value">${
|
|
2155
|
-
</div>`}const c=document.createElement("div");return c.id=
|
|
2176
|
+
<div class="__crossx-td-value">${h}</div>
|
|
2177
|
+
</div>`}const c=document.createElement("div");return c.id=ee,c.innerHTML=`
|
|
2156
2178
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2157
2179
|
<div class="__crossx-header">
|
|
2158
2180
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -2184,9 +2206,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2184
2206
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
2185
2207
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
2186
2208
|
</svg>`;function Gn(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(i=>{const a=t&&i.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${i.index}" data-wallet-address="${D(i.address)}">
|
|
2187
|
-
<span class="__crossx-wallet-idx"
|
|
2188
|
-
|
|
2189
|
-
</button>`}).join(""),o=document.createElement("div");return o.id=Z,o.innerHTML=`
|
|
2209
|
+
<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">Account ${i.index+1}</span><span class="__crossx-wallet-addr">${re(i.address)}</span></span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
2210
|
+
</button>`}).join(""),o=document.createElement("div");return o.id=ee,o.innerHTML=`
|
|
2190
2211
|
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2191
2212
|
<div class="__crossx-header">
|
|
2192
2213
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -2234,7 +2255,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2234
2255
|
<span class="__crossx-connect-other-title">Connect with Other Wallets</span>
|
|
2235
2256
|
<span class="__crossx-connect-other-desc">Connect your existing Web3 wallet to manage your assets.</span>
|
|
2236
2257
|
</div>
|
|
2237
|
-
</button>`:"",n=document.createElement("div");return n.id=
|
|
2258
|
+
</button>`:"",n=document.createElement("div");return n.id=ee,n.innerHTML=`
|
|
2238
2259
|
<div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2239
2260
|
<div class="__crossx-header">
|
|
2240
2261
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -2260,7 +2281,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2260
2281
|
</p>
|
|
2261
2282
|
</div>
|
|
2262
2283
|
</div>
|
|
2263
|
-
`,n}function Vn(r,e){const s=r,t=document.createElement("div");t.id=
|
|
2284
|
+
`,n}function Vn(r,e){const s=r,t=document.createElement("div");t.id=ee;const n=D(e.message).replace(/\n/g,"<br>"),o=e.email?`<div class="__crossx-session-account-card">
|
|
2264
2285
|
<p class="__crossx-session-account-label">${D(e.accountLabel)}</p>
|
|
2265
2286
|
<p class="__crossx-session-account-email">${D(e.email)}</p>
|
|
2266
2287
|
</div>`:"";return t.innerHTML=`
|
|
@@ -2282,7 +2303,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2282
2303
|
</div>
|
|
2283
2304
|
</div>
|
|
2284
2305
|
</div>
|
|
2285
|
-
`,t}function
|
|
2306
|
+
`,t}function zn(r,e=!0){const s=r,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",o=document.createElement("div");return o.id=ee,o.innerHTML=`
|
|
2286
2307
|
<div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2287
2308
|
<div class="__crossx-header">
|
|
2288
2309
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -2302,7 +2323,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2302
2323
|
${n}
|
|
2303
2324
|
</div>
|
|
2304
2325
|
</div>
|
|
2305
|
-
`,o}function
|
|
2326
|
+
`,o}function jn(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:o=5}=e??{},i=!!t,a=i?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${o}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=i?`<p class="__crossx-pin-error-text">${t}</p>`:"",f=document.createElement("div");return f.id=ee,f.innerHTML=`
|
|
2306
2327
|
<div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2307
2328
|
<div class="__crossx-header">
|
|
2308
2329
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2322,7 +2343,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2322
2343
|
${u}
|
|
2323
2344
|
</div>
|
|
2324
2345
|
</div>
|
|
2325
|
-
`,f}function Yn(r){const e=new Date(r),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=s[e.getDay()],o=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${o} ${i} ${a}:${c}`}function Xn(r,e,s){const t=r,n=e<=0,o=n?null:Date.now()+e*1e3,i=o?Yn(o):null,a=document.createElement("div");return a.id=
|
|
2346
|
+
`,f}function Yn(r){const e=new Date(r),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=s[e.getDay()],o=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${o} ${i} ${a}:${c}`}function Xn(r,e,s){const t=r,n=e<=0,o=n?null:Date.now()+e*1e3,i=o?Yn(o):null,a=document.createElement("div");return a.id=ee,a.innerHTML=`
|
|
2326
2347
|
<div class="__crossx-card __crossx-card--migration" style="${ae(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2327
2348
|
<div class="__crossx-header">
|
|
2328
2349
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2377,27 +2398,27 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2377
2398
|
`}function dt(r){const e=!!r.lockExpiresAt&&r.lockExpiresAt>Date.now(),s=r.lockExpiresAt?` data-lock-expires="${r.lockExpiresAt}"`:"",t=r.headerSubtitle?`<p class="__crossx-pin6-header-sub">${D(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${D(r.subtitle)}</p>`:"",o=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${D(r.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',i=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2378
2399
|
${Hs}
|
|
2379
2400
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2380
|
-
</p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${D(r.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${r.attemptCount}/${r.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",u=Array.from({length:6},(E,v)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${v+1}"${e?" disabled":""}>`).join(""),f=e?" --locked":"",_=Array.from({length:6},(E,v)=>`<div class="__crossx-pin6-dot${f}" data-dot-index="${v}" aria-label="PIN digit ${v+1}"></div>`).join(""),
|
|
2401
|
+
</p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${D(r.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${r.attemptCount}/${r.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",u=Array.from({length:6},(E,v)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${v+1}"${e?" disabled":""}>`).join(""),f=e?" --locked":"",_=Array.from({length:6},(E,v)=>`<div class="__crossx-pin6-dot${f}" data-dot-index="${v}" aria-label="PIN digit ${v+1}"></div>`).join(""),h=e?" --disabled":"",b=`
|
|
2381
2402
|
<div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
|
|
2382
2403
|
<div class="__crossx-pin6-numpad-row">
|
|
2383
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2384
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2385
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2404
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="1">1</button>
|
|
2405
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="2">2</button>
|
|
2406
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="3">3</button>
|
|
2386
2407
|
</div>
|
|
2387
2408
|
<div class="__crossx-pin6-numpad-row">
|
|
2388
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2389
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2390
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2409
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="4">4</button>
|
|
2410
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="5">5</button>
|
|
2411
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="6">6</button>
|
|
2391
2412
|
</div>
|
|
2392
2413
|
<div class="__crossx-pin6-numpad-row">
|
|
2393
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2394
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2395
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2414
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="7">7</button>
|
|
2415
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="8">8</button>
|
|
2416
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="9">9</button>
|
|
2396
2417
|
</div>
|
|
2397
2418
|
<div class="__crossx-pin6-numpad-row">
|
|
2398
2419
|
<button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
|
|
2399
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2400
|
-
<button type="button" class="__crossx-pin6-numpad-key --delete${
|
|
2420
|
+
<button type="button" class="__crossx-pin6-numpad-key${h}" data-key="0">0</button>
|
|
2421
|
+
<button type="button" class="__crossx-pin6-numpad-key --delete${h}" data-key="backspace" aria-label="Delete">${eo}</button>
|
|
2401
2422
|
</div>
|
|
2402
2423
|
</div>`;return`
|
|
2403
2424
|
<div class="__crossx-header">
|
|
@@ -2420,11 +2441,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2420
2441
|
${i}
|
|
2421
2442
|
</div>
|
|
2422
2443
|
${b}
|
|
2423
|
-
`}function os(r,e){const s=document.createElement("div");return s.id=
|
|
2444
|
+
`}function os(r,e){const s=document.createElement("div");return s.id=ee,s.innerHTML=`
|
|
2424
2445
|
<div class="__crossx-card __crossx-card--pin6" style="${ae(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2425
2446
|
${e}
|
|
2426
2447
|
</div>
|
|
2427
|
-
`,s}function Zn(r,e){if(r.length!==6)return e.tooShort;if(!/^\d+$/.test(r))return e.numbersOnly;if(/(.)\1{2}/.test(r))return e.repeatingDigit;const s=r.split("").map(Number),t=s.every((o,i)=>i===0||o===(s[i-1]+1)%10),n=s.every((o,i)=>i===0||o===(s[i-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function Qn(r){const e=Math.max(0,Math.ceil(r/1e3)),s=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return s>0?`${s}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function ut(r,e,s,t,n,o,i){var O,L;let a=!!(o&&o>Date.now()),c=!1;const l=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),u=()=>r.querySelector("#__crossx-pin6-boxes"),f=()=>r.querySelector("#__crossx-pin6-error"),_=()=>r.querySelector("#__crossx-pin6-lock-msg"),
|
|
2448
|
+
`,s}function Zn(r,e){if(r.length!==6)return e.tooShort;if(!/^\d+$/.test(r))return e.numbersOnly;if(/(.)\1{2}/.test(r))return e.repeatingDigit;const s=r.split("").map(Number),t=s.every((o,i)=>i===0||o===(s[i-1]+1)%10),n=s.every((o,i)=>i===0||o===(s[i-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function Qn(r){const e=Math.max(0,Math.ceil(r/1e3)),s=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return s>0?`${s}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function ut(r,e,s,t,n,o,i){var O,L;let a=!!(o&&o>Date.now()),c=!1;const l=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),u=()=>r.querySelector("#__crossx-pin6-boxes"),f=()=>r.querySelector("#__crossx-pin6-error"),_=()=>r.querySelector("#__crossx-pin6-lock-msg"),h=()=>r.querySelector("#__crossx-pin6-lock-countdown"),b=()=>r.querySelector(".__crossx-pin6-body"),E=()=>l().map(w=>w.value).join(""),v=()=>Array.from(r.querySelectorAll(".__crossx-pin6-dot")),T=()=>{var S;const w=l(),y=v();if(y.length&&(y.forEach((I,k)=>{const H=!!(w[k]&&w[k].value);I.classList.toggle("--filled",H),I.classList.toggle("--active",!1)}),!a&&!c)){const I=w.findIndex(H=>!H.value);(S=y[I===-1?5:I])==null||S.classList.add("--active")}},R=()=>{r.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(y=>y.classList.toggle("--disabled",a)),v().forEach(y=>y.classList.toggle("--locked",a)),T()},F=w=>{a=w,l().forEach(y=>{y.disabled=w,y.classList.toggle("--locked",w)})},$=()=>r.querySelector("#__crossx-pin6-attempt"),K=()=>{const w=f();w&&(w.textContent="")},q=()=>i??"Your account will be locked after further failures.",Z=()=>r.querySelector("#__crossx-pin6-warning"),G=w=>{var S;let y=Z();if(!y){y=document.createElement("p"),y.className="__crossx-pin6-warning",y.id="__crossx-pin6-warning";const I=f();I?I.insertAdjacentElement("afterend",y):(S=b())==null||S.appendChild(y)}y.textContent=w},X=()=>{const w=Z();w&&(w.textContent="")},Q=(w,y)=>{var I;let S=$();if(!S){S=document.createElement("p"),S.className="__crossx-pin6-attempt",S.id="__crossx-pin6-attempt";const k=Z()??f();k?k.insertAdjacentElement("afterend",S):(I=b())==null||I.appendChild(S)}S.textContent=`${w}/${y}`},U=()=>{const w=$();w&&(w.textContent="")},C=w=>{const y=f();y&&(y.textContent=w);const S=u();S==null||S.classList.add("--shake"),setTimeout(()=>S==null?void 0:S.classList.remove("--shake"),500),l().forEach(I=>{I.value=""}),setTimeout(()=>{var I;(I=l()[0])==null||I.focus(),T()},50)},M=w=>{var H;F(!0),l().forEach(B=>{B.value=""}),R();const y=f();if(y&&(y.textContent="Too many failed attempts. Please wait."),!_()){const B=document.createElement("p");B.className="__crossx-pin6-lock-msg",B.id="__crossx-pin6-lock-msg",B.innerHTML=`${Hs}<span id="__crossx-pin6-lock-countdown"></span>`;const N=f();N?N.insertAdjacentElement("afterend",B):(H=b())==null||H.appendChild(B)}const S=()=>{var W;const B=w-Date.now(),N=h();B<=0?(clearInterval(I),F(!1),(W=_())==null||W.remove(),y&&(y.textContent=""),R(),setTimeout(()=>{var j;return(j=l()[0])==null?void 0:j.focus()},50)):N&&(N.textContent=` ${Qn(B)}`)},I=setInterval(S,1e3);S();const k=new MutationObserver(()=>{document.contains(r)||(clearInterval(I),k.disconnect())});k.observe(document.body,{childList:!0,subtree:!1})},g=async()=>{if(a||c)return;const w=E();if(w.length===6){c=!0,l().forEach(y=>{y.disabled=!0});try{if(n){const y=await n(w);y.ok?e(w):y.lockExpiresAt?(U(),M(y.lockExpiresAt)):(C(y.error??"Incorrect PIN. Please try again."),y.attemptCount!=null&&y.maxAttempts!=null?(G(q()),Q(y.attemptCount,y.maxAttempts)):(X(),U()))}else e(w)}catch(y){t&&t(y)}finally{c=!1,a||l().forEach(y=>{y.disabled=!1}),T()}}};o&&o>Date.now()?M(o):setTimeout(()=>{var w;return(w=l()[0])==null?void 0:w.focus()},100);const m=()=>{if(a||c)return;const w=l(),y=w.find(S=>!S.value)??w[w.length-1];y==null||y.focus()};(O=u())==null||O.addEventListener("click",w=>{w.target.classList.contains("__crossx-pin6-box")||m()}),(L=b())==null||L.addEventListener("click",w=>{const y=w.target;y.classList.contains("__crossx-pin6-box")||y.closest("button")||m()}),l().forEach((w,y)=>{w.addEventListener("input",()=>{var I;const S=w.value.replace(/\D/g,"").slice(-1);w.value=S,K(),S&&y<5&&((I=l()[y+1])==null||I.focus()),T(),E().length===6&&setTimeout(g,80)}),w.addEventListener("keydown",S=>{var I,k;if(S.key==="Backspace"){if(S.preventDefault(),w.value)w.value="";else if(y>0){const H=l()[y-1];H.value="",H.focus()}T()}else S.key==="ArrowLeft"&&y>0?(S.preventDefault(),(I=l()[y-1])==null||I.focus()):S.key==="ArrowRight"&&y<5?(S.preventDefault(),(k=l()[y+1])==null||k.focus()):S.key==="Escape"&&s()}),w.addEventListener("paste",S=>{var H,B;S.preventDefault();const I=(((H=S.clipboardData)==null?void 0:H.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!I)return;const k=l();I.split("").forEach((N,W)=>{k[W]&&(k[W].value=N)}),(B=k[Math.min(I.length-1,5)])==null||B.focus(),K(),T(),E().length===6&&setTimeout(g,80)}),w.addEventListener("focus",()=>w.select())});const A=r.querySelector("#__crossx-pin6-numpad");if(A){let w=null;const y=()=>{w&&(w.classList.remove("--pressed"),w=null)};A.addEventListener("pointerdown",I=>{const k=I.target.closest(".__crossx-pin6-numpad-key");!k||a||c||(y(),w=k,k.classList.add("--pressed"),k.setPointerCapture(I.pointerId))});const S=I=>{const k=I.dataset.key;if(!k)return;if(k==="backspace"){const W=[...l()].reverse().find(j=>j.value);W&&(W.value="",K()),T();return}if(!/^\d$/.test(k))return;const B=l().find(N=>!N.value);B&&(B.value=k,K(),T(),E().length===6&&setTimeout(g,80))};A.addEventListener("pointerup",I=>{if(!w)return;const k=w;y();const H=k.getBoundingClientRect();I.clientX>=H.left&&I.clientX<=H.right&&I.clientY>=H.top&&I.clientY<=H.bottom&&!a&&!c&&S(k)}),A.addEventListener("pointercancel",y),A.addEventListener("pointerleave",y,!0),T(),o&&o>Date.now()&&R()}}const eo=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2428
2449
|
<path d="M7.36 0.5H19.5C20.6046 0.5 21.5 1.39543 21.5 2.5V14.5C21.5 15.6046 20.6046 16.5 19.5 16.5H7.36C6.76 16.5 6.19 16.24 5.8 15.79L0.94 10.02C0.35 9.32 0.35 8.3 0.94 7.6L5.8 1.71C6.19 1.26 6.76 0.5 7.36 0.5Z" stroke="currentColor" stroke-width="1.2" fill="none"/>
|
|
2429
2450
|
<line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
2430
2451
|
<line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
@@ -2434,4 +2455,4 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2434
2455
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
2435
2456
|
</svg>`,so=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2436
2457
|
<path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="currentColor"/>
|
|
2437
|
-
</svg>`;function ro(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((i,a)=>{i.addEventListener("input",()=>{const c=i.value.replace(/\D/g,"");i.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),i.addEventListener("keydown",c=>{c.key==="Backspace"&&!i.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),i.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),i.addEventListener("paste",c=>{var f;c.preventDefault();const l=(((f=c.clipboardData)==null?void 0:f.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,p)=>{t[p]&&(t[p].value=_)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",i=>{if(!i.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class no{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=rs(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=rs(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var E;le();const o=[...e],i=Gn(o,this.tokens,t),a=qe();de(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),a())},u=v=>{l(),n(v)},f=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(v=>{v.addEventListener("click",()=>{const T=v.dataset.walletAddress??"",R=parseInt(v.dataset.walletIndex??"0",10);u({address:T,index:R})})})})();const p=i.querySelector("#__crossx-add-wallet-btn");p&&p.addEventListener("click",async()=>{p.disabled=!0;try{const v=await s();o.push(v);const T=i.querySelector("#__crossx-wallet-list");if(T){const R=document.createElement("button");R.className="__crossx-wallet-item",R.dataset.walletIndex=String(v.index),R.dataset.walletAddress=v.address,R.innerHTML=`<span class="__crossx-wallet-idx">${v.index+1}</span><span class="__crossx-wallet-addr">${re(v.address)}</span>`,R.addEventListener("click",()=>u(v)),T.appendChild(R),R.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{p.disabled=!1}}),(E=i.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",f),i.addEventListener("click",v=>{v.target===i&&f()});const b=v=>{v.key==="Escape"&&(document.removeEventListener("keydown",b),f())};document.addEventListener("keydown",b)})}showLoginSelector(e){return new Promise(s=>{var c,l,u,f;le();const t=Kn(this.tokens,e==null?void 0:e.showConnectOtherWallets);de(t);const n=()=>t.remove(),o=_=>{n(),s(_)},i=()=>{n(),s(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>o("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>o("google")),(u=t.querySelector("#__crossx-connect-btn"))==null||u.addEventListener("click",()=>o("external")),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",i),t.addEventListener("click",_=>{_.target===t&&i()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(_=>{_.addEventListener("click",p=>p.stopPropagation())});const a=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}showSessionAlert(e){return new Promise(s=>{var u,f,_;le();const t=this.messages,n=Vn(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),o=qe();de(n);let i=!1;const a=()=>{i||(i=!0,n.remove(),o())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(f=n.querySelector("#__crossx-session-signin"))==null||f.addEventListener("click",l),(_=n.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",c)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;le();const n=jn(this.tokens,s);de(n);const o=()=>n.remove(),i=()=>{o(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",i),s){const u=()=>{o(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",_=>{_.target===n&&u()});const f=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)}})}showPinSetupPrompt(e){return new Promise(s=>{le();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.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.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},o={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},i={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=os(this.tokens,Jn(n)),c=qe();de(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},f=R=>{u(),s(R)},_=()=>{u(),s(null)},p=a.querySelector(".__crossx-card"),b={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},E=R=>{var F;p.innerHTML=dt({title:i.title,headerSubtitle:i.headerSubtitle}),(F=p.querySelector("#__crossx-close-btn"))==null||F.addEventListener("click",_),ut(p,$=>{$===R?f(R):v(o.mismatchError)},_)},v=R=>{var F;p.innerHTML=dt({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:R}),(F=p.querySelector("#__crossx-close-btn"))==null||F.addEventListener("click",_),ut(p,$=>{const K=Zn($,b);K?v(K):E($)},_)};(()=>{var ee;const R=Array.from(p.querySelectorAll(".__crossx-pw-notice-item")),F=p.querySelector("#__crossx-pin-notice-next"),$=new Set;F.removeAttribute("disabled");const K=F.dataset.nextLabel??"Next",q=F.dataset.submitLabel??"I Understand",Q=()=>{const U=$.size===R.length;F.classList.toggle("--disabled",!U),F.textContent=U?q:K},G=(U,C)=>{if($.has(C))return;const M=U.querySelector(`#__crossx-notice-check-${C}`);$.add(C),M.classList.add("--checked"),U.setAttribute("aria-checked","true"),Q()},X=(U,C)=>{if(!$.has(C))return;const M=U.querySelector(`#__crossx-notice-check-${C}`);$.delete(C),M.classList.remove("--checked"),U.setAttribute("aria-checked","false"),Q()};R.forEach(U=>{const C=parseInt(U.dataset.checkIndex??"0",10);U.addEventListener("click",()=>{$.has(C)?X(U,C):G(U,C)}),U.addEventListener("keydown",M=>{(M.key===" "||M.key==="Enter")&&(M.preventDefault(),$.has(C)?X(U,C):G(U,C))})}),F.addEventListener("click",()=>{if($.size===R.length){v(e==null?void 0:e.errorMessage);return}const U=R.find(M=>{const g=parseInt(M.dataset.checkIndex??"0",10);return!$.has(g)});if(!U)return;const C=parseInt(U.dataset.checkIndex??"0",10);U.scrollIntoView({behavior:"smooth",block:"nearest"}),U.classList.add("--highlight"),setTimeout(()=>{U.classList.remove("--highlight"),G(U,C)},400)}),(ee=p.querySelector("#__crossx-close-btn"))==null||ee.addEventListener("click",_)})(),a.addEventListener("click",R=>{R.target===a&&_()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var T;le();const n=this.messages,o=(e==null?void 0:e.verifyMode)===!0,i=o?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=o?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pinLocked_failureWarning)??"Your account will be locked after further failures.",l=os(this.tokens,dt({title:i,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=qe();de(l);let f=!1;const _=()=>{f||(f=!0,l.remove(),u())},p=R=>{_(),s(R)},b=()=>{_(),s(null)},E=R=>{_(),t(R)},v=l.querySelector(".__crossx-card");(T=v.querySelector("#__crossx-close-btn"))==null||T.addEventListener("click",b),ut(v,p,b,E,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",R=>{R.target===l&&b()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;le();const t=zn(this.tokens,e);de(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};ro(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;le();const{overlay:n,startCountdown:o}=Xn(this.tokens,e,s);de(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;le();const t=Mn(e,this.tokens);de(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const f=l.dataset.copy;f&&((_=navigator.clipboard)==null||_.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{le();const n=$n(e,this.tokens);de(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var u,f;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(Bn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,u;le();let t;e.type==="sign-message"?t=Un(e,this.tokens):e.type==="sign-typed-data"?t=Hn(e,this.tokens):e.type==="sign"?t=Cn(e,this.tokens):t=Nn(e,this.tokens),de(t);const n=()=>t.remove(),o=()=>{n(),s(!0)},i=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",_=>{var b;_.stopPropagation();const p=f.dataset.copy;p&&((b=navigator.clipboard)==null||b.writeText(p).catch(()=>{}))})}),t.addEventListener("click",f=>{f.target===t&&i()});const a=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class Fs{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function oo(r,e){r.debug;const s=Oe.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},o=t.authMode!=="cookie"&&Ut.isAvailable();!o&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const i=o?new Ut(r.projectId):new ar,a=new xn,c=new yn,l=new Ie,u=new Fs,f=new gt;let _;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new Sn(i,f)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new Ae(n,i,c,u,f));const p=new Be(n,c),b=new no(r.theme??"light",r.themeTokens),E=e!=null&&e.wrapConfirmation?e.wrapConfirmation(b):b,v=new Ve(t,n,i,a,c,l,_,u,E,p,f);return typeof window<"u"&&(window.__crossxSDK=v),v}function io(r){const e=ao(r),s=co(e),t=JSON.parse(s);uo(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function ao(r){if(r.includes("://")&&r.includes("?")){const e=new URL(r),s=e.searchParams.get("crossx_oauth_result");if(s)return s;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return r}function co(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=lo(r);return decodeURIComponent(e)}function lo(r){if(typeof atob=="function")return atob(r);if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function uo(r){if(typeof r!="object"||r===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=r;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const s=e.data;if(typeof s.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof s.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}exports.CROSSxError=x;exports.CROSSxEthereumProvider=is;exports.CROSSxSDK=Ve;exports.ChainId=qs;exports.ErrorCode=h;exports.PinMemoryStore=gt;exports.TokenMemoryStore=Fs;exports.createCROSSxSDK=oo;exports.parseOAuthDeeplink=io;
|
|
2458
|
+
</svg>`;function ro(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((i,a)=>{i.addEventListener("input",()=>{const c=i.value.replace(/\D/g,"");i.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),i.addEventListener("keydown",c=>{c.key==="Backspace"&&!i.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),i.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),i.addEventListener("paste",c=>{var f;c.preventDefault();const l=(((f=c.clipboardData)==null?void 0:f.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,h)=>{t[h]&&(t[h].value=_)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",i=>{if(!i.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class no{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=rs(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=rs(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var E;le();const o=[...e],i=Gn(o,this.tokens,t),a=Oe();de(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),a())},u=v=>{l(),n(v)},f=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(v=>{v.addEventListener("click",()=>{const T=v.dataset.walletAddress??"",R=parseInt(v.dataset.walletIndex??"0",10);u({address:T,index:R})})})})();const h=i.querySelector("#__crossx-add-wallet-btn");h&&h.addEventListener("click",async()=>{h.disabled=!0;try{const v=await s();o.push(v);const T=i.querySelector("#__crossx-wallet-list");if(T){const R=document.createElement("button");R.className="__crossx-wallet-item",R.dataset.walletIndex=String(v.index),R.dataset.walletAddress=v.address,R.innerHTML=`<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">Account ${v.index+1}</span><span class="__crossx-wallet-addr">${re(v.address)}</span></span>`,R.addEventListener("click",()=>u(v)),T.appendChild(R),R.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{h.disabled=!1}}),(E=i.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",f),i.addEventListener("click",v=>{v.target===i&&f()});const b=v=>{v.key==="Escape"&&(document.removeEventListener("keydown",b),f())};document.addEventListener("keydown",b)})}showLoginSelector(e){return new Promise(s=>{var l,u,f,_;le();const t=Kn(this.tokens,e==null?void 0:e.showConnectOtherWallets),n=Oe();de(t);const o=()=>{t.remove(),n()},i=h=>{o(),s(h)},a=()=>{o(),s(null)};(l=t.querySelector("#__crossx-apple-btn"))==null||l.addEventListener("click",()=>i("apple")),(u=t.querySelector("#__crossx-google-btn"))==null||u.addEventListener("click",()=>i("google")),(f=t.querySelector("#__crossx-connect-btn"))==null||f.addEventListener("click",()=>i("external")),(_=t.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",a),t.addEventListener("click",h=>{h.target===t&&a()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(h=>{h.addEventListener("click",b=>b.stopPropagation())});const c=h=>{h.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}showSessionAlert(e){return new Promise(s=>{var u,f,_;le();const t=this.messages,n=Vn(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),o=Oe();de(n);let i=!1;const a=()=>{i||(i=!0,n.remove(),o())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(f=n.querySelector("#__crossx-session-signin"))==null||f.addEventListener("click",l),(_=n.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",c)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;le();const n=zn(this.tokens,s);de(n);const o=()=>n.remove(),i=()=>{o(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",i),s){const u=()=>{o(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",_=>{_.target===n&&u()});const f=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)}})}showPinSetupPrompt(e){return new Promise(s=>{le();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.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.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},o={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},i={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=os(this.tokens,Jn(n)),c=Oe();de(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},f=R=>{u(),s(R)},_=()=>{u(),s(null)},h=a.querySelector(".__crossx-card"),b={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},E=R=>{var F;h.innerHTML=dt({title:i.title,headerSubtitle:i.headerSubtitle}),(F=h.querySelector("#__crossx-close-btn"))==null||F.addEventListener("click",_),ut(h,$=>{$===R?f(R):v(o.mismatchError)},_)},v=R=>{var F;h.innerHTML=dt({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:R}),(F=h.querySelector("#__crossx-close-btn"))==null||F.addEventListener("click",_),ut(h,$=>{const K=Zn($,b);K?v(K):E($)},_)};(()=>{var Q;const R=Array.from(h.querySelectorAll(".__crossx-pw-notice-item")),F=h.querySelector("#__crossx-pin-notice-next"),$=new Set;F.removeAttribute("disabled");const K=F.dataset.nextLabel??"Next",q=F.dataset.submitLabel??"I Understand",Z=()=>{const U=$.size===R.length;F.classList.toggle("--disabled",!U),F.textContent=U?q:K},G=(U,C)=>{if($.has(C))return;const M=U.querySelector(`#__crossx-notice-check-${C}`);$.add(C),M.classList.add("--checked"),U.setAttribute("aria-checked","true"),Z()},X=(U,C)=>{if(!$.has(C))return;const M=U.querySelector(`#__crossx-notice-check-${C}`);$.delete(C),M.classList.remove("--checked"),U.setAttribute("aria-checked","false"),Z()};R.forEach(U=>{const C=parseInt(U.dataset.checkIndex??"0",10);U.addEventListener("click",()=>{$.has(C)?X(U,C):G(U,C)}),U.addEventListener("keydown",M=>{(M.key===" "||M.key==="Enter")&&(M.preventDefault(),$.has(C)?X(U,C):G(U,C))})}),F.addEventListener("click",()=>{if($.size===R.length){v(e==null?void 0:e.errorMessage);return}const U=R.find(M=>{const g=parseInt(M.dataset.checkIndex??"0",10);return!$.has(g)});if(!U)return;const C=parseInt(U.dataset.checkIndex??"0",10);U.scrollIntoView({behavior:"smooth",block:"nearest"}),U.classList.add("--highlight"),setTimeout(()=>{U.classList.remove("--highlight"),G(U,C)},400)}),(Q=h.querySelector("#__crossx-close-btn"))==null||Q.addEventListener("click",_)})(),a.addEventListener("click",R=>{R.target===a&&_()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var T;le();const n=this.messages,o=(e==null?void 0:e.verifyMode)===!0,i=o?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=o?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pinLocked_failureWarning)??"Your account will be locked after further failures.",l=os(this.tokens,dt({title:i,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=Oe();de(l);let f=!1;const _=()=>{f||(f=!0,l.remove(),u())},h=R=>{_(),s(R)},b=()=>{_(),s(null)},E=R=>{_(),t(R)},v=l.querySelector(".__crossx-card");(T=v.querySelector("#__crossx-close-btn"))==null||T.addEventListener("click",b),ut(v,h,b,E,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",R=>{R.target===l&&b()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;le();const t=jn(this.tokens,e);de(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};ro(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;le();const{overlay:n,startCountdown:o}=Xn(this.tokens,e,s);de(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;le();const t=Mn(e,this.tokens);de(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const f=l.dataset.copy;f&&((_=navigator.clipboard)==null||_.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{le();const n=$n(e,this.tokens);de(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var u,f;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(Bn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var l,u,f;le();let t;e.type==="sign-message"?t=Un(e,this.tokens):e.type==="sign-typed-data"?t=Hn(e,this.tokens):e.type==="sign"?t=Cn(e,this.tokens):t=Nn(e,this.tokens);const n=Oe();de(t);const o=()=>{t.remove(),n()},i=()=>{o(),s(!0)},a=()=>{o(),s(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",i),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(_=>{_.addEventListener("click",h=>{var E;h.stopPropagation();const b=_.dataset.copy;b&&((E=navigator.clipboard)==null||E.writeText(b).catch(()=>{}))})}),t.addEventListener("click",_=>{_.target===t&&a()});const c=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Fs{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function oo(r,e){r.debug;const s=Pe.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},o=t.authMode!=="cookie"&&Ut.isAvailable();!o&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const i=o?new Ut(r.projectId):new ar,a=new xn,c=new yn,l=new Ie,u=new Fs,f=new gt;let _;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new Sn(i,f)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new Ae(n,i,c,u,f));const h=new Ue(n,c),b=new no(r.theme??"light",r.themeTokens),E=e!=null&&e.wrapConfirmation?e.wrapConfirmation(b):b,v=new Ve(t,n,i,a,c,l,_,u,E,h,f);return typeof window<"u"&&(window.__crossxSDK=v),v}function io(r){const e=ao(r),s=co(e),t=JSON.parse(s);uo(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function ao(r){if(r.includes("://")&&r.includes("?")){const e=new URL(r),s=e.searchParams.get("crossx_oauth_result");if(s)return s;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return r}function co(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=lo(r);return decodeURIComponent(e)}function lo(r){if(typeof atob=="function")return atob(r);if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function uo(r){if(typeof r!="object"||r===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=r;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const s=e.data;if(typeof s.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof s.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}exports.CROSSxError=x;exports.CROSSxEthereumProvider=is;exports.CROSSxSDK=Ve;exports.ChainId=qs;exports.ErrorCode=p;exports.PinMemoryStore=gt;exports.TokenMemoryStore=Fs;exports.createCROSSxSDK=oo;exports.parseOAuthDeeplink=io;
|