@nexus-cross/crossx-sdk-core 1.4.2 → 1.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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
|
|
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 k=(r,e,s)=>Ws(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const tt=require("jose");var h=(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))(h||{});class g extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,g.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 os{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 g(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new g(h.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 kt(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
|
-
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",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:"
|
|
3
|
+
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",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_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,i,o,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,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 i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new x(h.OAUTH_POPUP_BLOCKED,i):new x(h.AUTH_FAILED,i)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:p,refreshToken:_}=await this.exchangeFirebaseToken(e,u);let f,w,S;try{const I=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(I).join(", ")),w=(i=I.firebase)==null?void 0:i.sign_in_provider;const P=((o=I.firebase)==null?void 0:o.identities)??{};S=I.email??((a=P.email)==null?void 0:a[0]),w==="google.com"?f=(c=P["google.com"])==null?void 0:c[0]:w==="apple.com"&&(f=(l=P["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",w,"hasProviderSub:",!!f,"email:",S??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const I=this.crypto.decodeJWT(p);d.log("[CROSSx] access_token 디코딩 — sub:",I.sub,"exp:",I.exp,"필드:",Object.keys(I).join(", "));const P=await this.crypto.verifyJWT(p);if(n=P.signatureVerified??!1,!P.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const H=P.payload,D=H.email??S??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",H.email??"(없음)","/ Firebase JWT:",S??"(없음)","/ OAuth 콜백:",s??"(없음)","→",D??"(없음)"),t={id:H.sub,email:D,signInProvider:w,providerSub:f},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const I=this.crypto.decodeJWT(e);t={id:I.sub,email:I.email??s,signInProvider:w,providerSub:f},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const y=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,y),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 i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}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`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=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 i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(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 i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof x&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof x&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};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 i=0;i<s.length;i++)n[i]=s[i]^t[i];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class 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),i={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new 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,ir=5*60*1e3,or=30*1e3;function De(r){const e=r.indexOf("@");if(e<0)return"***";const s=r.substring(0,e),t=r.substring(e);return s.length<=1?`${s}***${t}`:`${s[0]}***${t}`}const te=class te extends Zs{constructor(e,s,t,n,i,o,a,c,l,u,p){var _,f;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&kt(e.logger),this.confirmation=l,this.pinStore=p??new gt,this.chainRegistry=u,this.jsonRpc=new Js(u,i),this.signInUseCase=new ht(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new Ys(this.internalConfig,t,c),this.migrateWalletUseCase=new Xs(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(f=a.setTokenRefresher)==null||f.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.4.2 초기화 중..."),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 i=await this.signInUseCase.restoreSession();if(i!=null&&i.success){this.applyAuthResult(i);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(o){if(!(o instanceof x&&o.code===h.PIN_CANCELLED))throw o;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v1.4.2 초기화 완료"),this.emit("initialized",{restored:!!(i!=null&&i.success)}),i??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:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...s,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}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,o={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(o),o},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 i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(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 o=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,o.signature,n.address),{chainId:e,signature:o.signature,message:s,address:n.address}}catch(o){throw o instanceof x?o:new x(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}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가 구현되어 있지 않습니다");te.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 o=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 te.validateSignatureFormat(o.signature),{chainId:e,signature:o.signature,address:n.address}}catch(o){throw o instanceof x?o:new x(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,s){return this.signTypedData(te.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new 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 i=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:i.symbol,nativeDecimals:i.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 te.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 i=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:i.symbol,nativeDecimals:i.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,i=rr,o=t.timeoutMs??Nt,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new x(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var S,y;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((S=this._config.receiptPolling)==null?void 0:S.intervalMs)??tr,l=i??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??Nt,u=st(e),p=s.from??"";let _,f;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{_=I;const P=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),H=s.value?BigInt(s.value):0n,D=te.formatTxAmount(s.value,u.symbol,u.decimals),K=te.formatTxAmount("0x"+P.toString(16),u.symbol,u.decimals),G=te.formatTxAmount("0x"+(H+P).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:I.from,to:I.to??s.to,amount:D,fees:K,total:G,nativeSymbol:u.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(f=I instanceof Error?I:new Error(String(I)),{chainId:e,txHash:a,from:p,to:s.to,amount:te.formatTxAmount(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:s.to},w),f)throw f;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 i=n instanceof Error?n.message:String(n);throw new x(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new 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:te.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,o=(s%t).toString().padStart($t,"0").replace(/0+$/,"").slice(0,Mt);return o?`${n}.${o}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new os(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 i=n instanceof Error?n.message:String(n);throw new x(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const i=10n**BigInt(t),o=n/i,c=(n%i).toString().padStart(t,"0").slice(0,Mt).replace(/0+$/,"");return`${c?`${o}.${c}`:`${o}`} ${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,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const p=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(p===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,p,e));if(!_){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=p;break}if(_.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=p;break}const f=_.pinStatus;if(o=f.maxAttempts,i=o-f.remainingAttempts,f.remainingAttempts===0&&f.lockExpiresAt){const w=f.lockExpiresAt*1e3,S=Math.max(1,Math.round((w-Date.now())/1e3)),y=S<=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 잠금 — ${S}초, 메시지: ${y}`),await this.confirmation.showRecoveryPinLockedPrompt(S,y),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(_){if(!(_ instanceof x))throw _;if(_.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const f=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_sessionExpired,email:this.userEmail?De(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.clearAuthState(),_}if(_.code===h.MIGRATION_PIN_LOCKED){const f=_.details;if(o=(f==null?void 0:f.maxAttempts)??5,(f==null?void 0:f.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 w=((f==null?void 0:f.lockExpiresAt)??0)*1e3,S=Math.max(1,Math.round((w-Date.now())/1e3)),y=S<=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 이미 잠금 — ${S}초`),await this.confirmation.showRecoveryPinLockedPrompt(S,y),i=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 p=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",p.address),p}catch(p){if(p instanceof x&&p.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(p instanceof x&&p.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):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const S=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",S.address),S}catch(S){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",S),S}}throw this.clearAuthState(),p}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",p),p}}async withResolvedGasAndFee(e,s){const t=f=>!(f!=null&&f.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,p,_]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,i?this.estimateGas(e,s):null,o?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const f=_;if(f){const w=Lt;c.maxFeePerGas="0x"+(BigInt(f)+BigInt(w)).toString(16),c.maxPriorityFeePerGas=w,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",f,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=nr,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=Lt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=te.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 i=Number(n[1]);if(t===void 0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==i)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${i})와 일치하지 않습니다`)}}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,i;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=te.normalizeLoginType((i=e.user)==null?void 0:i.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,i;this.ensureInitialized();const e=this.providerSub,s=this.userId,t=this.loginType;this._isRecoveringSession=!0;try{this.authenticated=!1,this.tokenStore.clear();const o=t?{provider:t}:void 0;let a;try{a=await this.signInUseCase.execute(o)}catch(p){throw this.clearAuthState(),p}if(!a.success)return this.clearAuthState(),a;const c=((n=a.user)==null?void 0:n.providerSub)??null,l=((i=a.user)==null?void 0:i.id)??null;if(!(e?!!c&&c===e:s?!!l&&s===l:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const p=fe(this._config.locale??"en");return await this.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_differentAccount,email:this.userEmail?De(this.userEmail):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):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 o=await this.signInAgain();if(!o.success)throw new x(h.SESSION_EXPIRED,o.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 i,o;this._verifyPinMutex=new Promise((c,l)=>{i=c,o=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 미지원, 로컬 전용)"),i();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 te.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}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):void 0})==="signin-again"&&(await this.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this._verifyPinMutex=null}}static buildPinLockedResult(e,s){const t=e.details;if(t!=null&&t.permanent)return{ok:!1,error:s.pinLocked_permanent};if((t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts){const n=t.maxAttempts-t.remainingAttempts;return{ok:!1,error:s.pinLocked_failureWarning,attemptCount:n,maxAttempts:t.maxAttempts}}return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}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 i=e!==void 0?t.find(o=>o.index===e)??t[0]:t[0];this.address=i.address,this.activeWalletIndex=i.index,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:i.address,index:i.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,n,i,o;const a=c=>{if(c.code===h.PIN_WRONG)return t=s.pinInput_error,n=void 0,i=void 0,o=void 0,!0;if(c.code===h.PIN_INVALID)return t=c.message,n=void 0,i=void 0,o=void 0,!0;if(c.code===h.PIN_LOCKED){const l=c.details;return l!=null&&l.permanent?(t=s.pinLocked_permanent,n=void 0,i=void 0,o=void 0):(l==null?void 0:l.remainingAttempts)!=null&&l.remainingAttempts>0&&l.maxAttempts?(t=s.pinLocked_failureWarning,n=void 0,i=l.maxAttempts-l.remainingAttempts,o=l.maxAttempts):(t="Too many failed attempts. Your account is temporarily locked.",n=l==null?void 0:l.lockExpiresAt,i=void 0,o=void 0),!0}return!1};try{return await e()}catch(c){if(!(c instanceof x&&a(c)))throw c}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t),this.pinStore.clear(),await this.ensureVerifiedPin(t,n,i,o),n=void 0,i=void 0,o=void 0;try{return await e()}catch(c){if(c instanceof x&&a(c))continue;throw c}}}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(),kt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};te.OFFCHAIN_CHAIN_ID="0";let Ve=te;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 i=n.result;i.objectStoreNames.contains(he)||i.createObjectStore(he),i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ee,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 i=s.objectStore(he).getAll(),o=s.objectStore(he).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Ee,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 q(r,e,s=""){const t=mt(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function 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){q(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(q(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,i=0;n<s;n++,i+=2){const o=Ft(r.charCodeAt(i)),a=Ft(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ve(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];q(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function us(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function 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){R(this,"blockLen");R(this,"outputLen");R(this,"padOffset");R(this,"isLE");R(this,"buffer");R(this,"view");R(this,"finished",!1);R(this,"length",0);R(this,"pos",0);R(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),q(e);const{view:s,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=nt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ce(this),ls(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,Ne(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)s[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),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 p=0;p<l;p++)a.setUint32(4*p,u[p],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),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 i=0;i<s;i++){const{h:o,l:a}=wr(r[i],e);[t[i],n[i]]=[o,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:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let p=0;p<16;p++,s+=4)be[p]=e.getUint32(s,!1);for(let p=16;p<64;p++){const _=be[p-15],f=be[p-2],w=pe(_,7)^pe(_,18)^_>>>3,S=pe(f,17)^pe(f,19)^f>>>10;be[p]=S+be[p-7]+w+be[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let p=0;p<64;p++){const _=pe(a,6)^pe(a,11)^pe(a,25),f=u+_+xr(a,c,l)+Ir[p]+be[p]|0,S=(pe(t,2)^pe(t,13)^pe(t,22))+gr(t,n,i)|0;u=l,l=c,c=a,a=o+f|0,o=i,i=n,n=t,t=f+S|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){Ne(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Ne(this.buffer)}}class Tr extends Ar{constructor(){super(32);R(this,"A",ye[0]|0);R(this,"B",ye[1]|0);R(this,"C",ye[2]|0);R(this,"D",ye[3]|0);R(this,"E",ye[4]|0);R(this,"F",ye[5]|0);R(this,"G",ye[6]|0);R(this,"H",ye[7]|0)}}const Rr=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 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(kr(q(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 kr(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=y=>new Uint8Array(y),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const p=()=>{c.fill(1),l.fill(0),u=0},_=(...y)=>s(l,ve(c,...y)),f=(y=n)=>{l=_(i,y),c=_(),y.length!==0&&(l=_(o,y),c=_())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const I=[];for(;y<e;){c=_();const P=c.slice();I.push(P),y+=c.length}return ve(...I)};return(y,I)=>{p(),f(y);let P;for(;!(P=I(w()));)f();return p(),P}}function St(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(s,!0)}function Wt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const 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,i=se;for(;s!==ne;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=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),i=r.mul(e,n),o=r.mul(r.mul(i,Te),n),a=r.mul(i,r.sub(o,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),i=s(e,e.neg(t)),o=(r+Lr)/bs;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const p=a.mul(l,n),_=a.mul(l,i),f=a.eql(a.sqr(u),c),w=a.eql(a.sqr(p),c);l=a.cmov(l,u,f),u=a.cmov(_,p,w);const S=a.eql(a.sqr(u),c),y=a.cmov(l,u,S);return vt(a,y,c),y}}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 i=n.pow(t,e);const o=(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,p=c.mul(c.ONE,i),_=c.pow(l,e),f=c.pow(l,o);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let w=1,S=c.sqr(_);for(;!c.eql(S,c.ONE);)if(w++,S=c.sqr(S),w===u)throw new Error("Cannot find square root");const y=se<<BigInt(u-w-1),I=c.pow(p,y);u=w,p=c.sqr(I),_=c.mul(_,p),f=c.mul(f,I)}return f}}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((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function Kt(r,e){const s=(r.ORDER-se)/Te,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function 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={}){R(this,"ORDER");R(this,"BITS");R(this,"BYTES");R(this,"isLE");R(this,"ZERO",ne);R(this,"ONE",se);R(this,"_lengths");R(this,"_sqrt");R(this,"_mod");var o;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=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=Gr(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return 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){q(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?_s(e):Ze(e);if(a&&(c=ue(c,o)),!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){q(r);const t=r.length,n=Is(e),i=As(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?_s(r):Ze(r),a=ue(o,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),Re=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 it(r,e){Ts(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=bt(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function zt(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=Re);const l=e*t,u=l+Math.abs(a)-1,p=a===0,_=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:_,isNegF:f,offsetF:l}}const ot=new WeakMap,Rs=new WeakMap;function at(r){return Rs.get(r)||1}function jt(r){if(r!==Le)throw new Error("invalid wNAF")}class Kr{constructor(e,s){R(this,"BASE");R(this,"ZERO");R(this,"Fn");R(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&Re&&(t=t.add(n)),n=n.double(),s>>=Re;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=it(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=it(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:_,offsetF:f}=zt(t,a,o);t=c,u?i=i.add(Ye(_,s[f])):n=n.add(Ye(p,s[l]))}return jt(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=it(e,this.bits);for(let o=0;o<i.windows&&t!==Le;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=zt(t,o,i);if(t=a,!l){const p=s[c];n=n.add(u?p.negate():p)}}return jt(t),n}getPrecomputes(e,s,t){let n=ot.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),ot.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 i=at(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){Ts(s,this.bits),Rs.set(e,s),ot.delete(e)}hasCache(e){return at(e)!==1}}function Vr(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>Le||t>Le;)s&Re&&(i=i.add(n)),t&Re&&(o=o.add(n)),n=n.double(),s>>=Re,t>>=Re;return{p1:i,p2:o}}function 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>Le))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Yt(e.p,s.Fp,t),i=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:i}}function jr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class ks{constructor(e,s){R(this,"oHash");R(this,"iHash");R(this,"blockLen");R(this,"outputLen");R(this,"finished",!1);R(this,"destroyed",!1);if(cs(e),q(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Ne(n)}update(e){return Ce(this),this.iHash.update(e),this}digestInto(e){Ce(this),q(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Os=(r,e,s)=>new ks(r,e).update(s).digest();Os.create=(r,e)=>new ks(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],[i,o]]=e,a=Xt(o*r,s),c=Xt(-n*r,s);let l=r-a*t-c*i,u=-a*n-c*o;const p=l<ge,_=u<ge;p&&(l=-l),_&&(u=-u);const f=bt(Math.ceil(Cr(s)/2))+Pe;if(l<ge||l>=f||u<ge||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:p,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=Ge(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?Ge(n.length/2|128):"";return Ge(r)+i+n+e},decode(r,e){const{Err:s}=Se;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Se;if(r<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=q(r,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Se,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},ge=BigInt(0),Pe=BigInt(1),Ps=BigInt(2),We=BigInt(3),Jr=BigInt(4);function Zr(r,e={}){const s=zr("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;St(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ns(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(T,g,m){const{x:b,y:A}=g.toAffine(),N=t.toBytes(b);if(je(m,"isCompressed"),m){u();const C=!t.isOdd(A);return ve(Cs(C),N)}else return ve(Uint8Array.of(4),N,t.toBytes(A))}function _(T){q(T,void 0,"Point");const{publicKey:g,publicKeyUncompressed:m}=l,b=T.length,A=T[0],N=T.subarray(1);if(b===g&&(A===2||A===3)){const C=t.fromBytes(N);if(!t.isValid(C))throw new Error("bad point: is not on curve, wrong x");const M=S(C);let O;try{O=t.sqrt(M)}catch(Y){const W=Y instanceof Error?": "+Y.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}u();const $=t.isOdd(O);return(A&1)===1!==$&&(O=t.neg(O)),{x:C,y:O}}else if(b===m&&A===4){const C=t.BYTES,M=t.fromBytes(N.subarray(0,C)),O=t.fromBytes(N.subarray(C,C*2));if(!y(M,O))throw new Error("bad point: is not on curve");return{x:M,y:O}}else throw new Error(`bad point: got length ${b}, expected compressed=${g} or uncompressed=${m}`)}const f=e.toBytes||p,w=e.fromBytes||_;function S(T){const g=t.sqr(T),m=t.mul(g,T);return t.add(t.add(m,t.mul(T,i.a)),i.b)}function y(T,g){const m=t.sqr(g),b=S(T);return t.eql(m,b)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(i.a,We),Jr),P=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(I,P)))throw new Error("bad curve params: a or b");function H(T,g,m=!1){if(!t.isValid(g)||m&&t.is0(g))throw new Error(`bad point coordinate ${T}`);return g}function D(T){if(!(T instanceof z))throw new Error("Weierstrass Point expected")}function K(T){if(!c||!c.basises)throw new Error("no endo");return Yr(T,c.basises,n.ORDER)}const G=Wt((T,g)=>{const{X:m,Y:b,Z:A}=T;if(t.eql(A,t.ONE))return{x:m,y:b};const N=T.is0();g==null&&(g=N?t.ONE:t.inv(A));const C=t.mul(m,g),M=t.mul(b,g),O=t.mul(A,g);if(N)return{x:t.ZERO,y:t.ZERO};if(!t.eql(O,t.ONE))throw new Error("invZ was invalid");return{x:C,y:M}}),Z=Wt(T=>{if(T.is0()){if(e.allowInfinityPoint&&!t.is0(T.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:m}=T.toAffine();if(!t.isValid(g)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!y(g,m))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(T,g,m,b,A){return m=new z(t.mul(m.X,T),m.Y,m.Z),g=Ye(b,g),m=Ye(A,m),g.add(m)}const E=class E{constructor(g,m,b){R(this,"X");R(this,"Y");R(this,"Z");this.X=H("x",g),this.Y=H("y",m,!0),this.Z=H("z",b),Object.freeze(this)}static CURVE(){return i}static fromAffine(g){const{x:m,y:b}=g||{};if(!g||!t.isValid(m)||!t.isValid(b))throw new Error("invalid affine point");if(g instanceof E)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(b)?E.ZERO:new E(m,b,t.ONE)}static fromBytes(g){const m=E.fromAffine(w(q(g,void 0,"point")));return m.assertValidity(),m}static fromHex(g){return E.fromBytes(ze(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return v.createCache(this,g),m||this.multiply(We),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){D(g);const{X:m,Y:b,Z:A}=this,{X:N,Y:C,Z:M}=g,O=t.eql(t.mul(m,M),t.mul(N,A)),$=t.eql(t.mul(b,M),t.mul(C,A));return O&&$}negate(){return new E(this.X,t.neg(this.Y),this.Z)}double(){const{a:g,b:m}=i,b=t.mul(m,We),{X:A,Y:N,Z:C}=this;let M=t.ZERO,O=t.ZERO,$=t.ZERO,F=t.mul(A,A),Y=t.mul(N,N),W=t.mul(C,C),B=t.mul(A,N);return B=t.add(B,B),$=t.mul(A,C),$=t.add($,$),M=t.mul(g,$),O=t.mul(b,W),O=t.add(M,O),M=t.sub(Y,O),O=t.add(Y,O),O=t.mul(M,O),M=t.mul(B,M),$=t.mul(b,$),W=t.mul(g,W),B=t.sub(F,W),B=t.mul(g,B),B=t.add(B,$),$=t.add(F,F),F=t.add($,F),F=t.add(F,W),F=t.mul(F,B),O=t.add(O,F),W=t.mul(N,C),W=t.add(W,W),F=t.mul(W,B),M=t.sub(M,F),$=t.mul(W,Y),$=t.add($,$),$=t.add($,$),new E(M,O,$)}add(g){D(g);const{X:m,Y:b,Z:A}=this,{X:N,Y:C,Z:M}=g;let O=t.ZERO,$=t.ZERO,F=t.ZERO;const Y=i.a,W=t.mul(i.b,We);let B=t.mul(m,N),X=t.mul(b,C),Q=t.mul(A,M),oe=t.add(m,b),V=t.add(N,C);oe=t.mul(oe,V),V=t.add(B,X),oe=t.sub(oe,V),V=t.add(m,A);let ee=t.add(N,M);return V=t.mul(V,ee),ee=t.add(B,Q),V=t.sub(V,ee),ee=t.add(b,A),O=t.add(C,M),ee=t.mul(ee,O),O=t.add(X,Q),ee=t.sub(ee,O),F=t.mul(Y,V),O=t.mul(W,Q),F=t.add(O,F),O=t.sub(X,F),F=t.add(X,F),$=t.mul(O,F),X=t.add(B,B),X=t.add(X,B),Q=t.mul(Y,Q),V=t.mul(W,V),X=t.add(X,Q),Q=t.sub(B,Q),Q=t.mul(Y,Q),V=t.add(V,Q),B=t.mul(X,V),$=t.add($,B),B=t.mul(ee,V),O=t.mul(oe,O),O=t.sub(O,B),B=t.mul(oe,X),F=t.mul(ee,F),F=t.add(F,B),new E(O,$,F)}subtract(g){return this.add(g.negate())}is0(){return this.equals(E.ZERO)}multiply(g){const{endo:m}=e;if(!n.isValidNot0(g))throw new Error("invalid scalar: out of range");let b,A;const N=C=>v.cached(this,C,M=>Vt(E,M));if(m){const{k1neg:C,k1:M,k2neg:O,k2:$}=K(g),{p:F,f:Y}=N(M),{p:W,f:B}=N($);A=Y.add(B),b=U(m.beta,F,W,C,O)}else{const{p:C,f:M}=N(g);b=C,A=M}return Vt(E,[b,A])[0]}multiplyUnsafe(g){const{endo:m}=e,b=this;if(!n.isValid(g))throw new Error("invalid scalar: out of range");if(g===ge||b.is0())return E.ZERO;if(g===Pe)return b;if(v.hasCache(this))return this.multiply(g);if(m){const{k1neg:A,k1:N,k2neg:C,k2:M}=K(g),{p1:O,p2:$}=Vr(E,b,N,M);return U(m.beta,O,$,A,C)}else return v.unsafe(b,g)}toAffine(g){return G(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return o===Pe?!0:g?g(E,this):v.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:g}=e;return o===Pe?this:g?g(E,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(g=!0){return je(g,"isCompressed"),this.assertValidity(),f(E,this,g)}toHex(g=!0){return Ue(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};R(E,"BASE",new E(i.Gx,i.Gy,t.ONE)),R(E,"ZERO",new E(t.ZERO,t.ONE,t.ZERO)),R(E,"Fp",t),R(E,"Fn",n);let z=E;const k=n.BITS,v=new Kr(z,e.endo?Math.ceil(k/2):k);return z.BASE.precompute(8),z}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 i(f){try{const w=s.fromBytes(f);return s.isValidNot0(w)}catch{return!1}}function o(f,w){const{publicKey:S,publicKeyUncompressed:y}=n;try{const I=f.length;return w===!0&&I!==S||w===!1&&I!==y?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=t(n.seed)){return qr(q(f,n.seed,"seed"),s.ORDER)}function c(f,w=!0){return r.BASE.multiply(s.fromBytes(f)).toBytes(w)}function l(f){const{secretKey:w,publicKey:S,publicKeyUncompressed:y}=n;if(!mt(f)||"_lengths"in s&&s._lengths||w===S)return;const I=q(f,void 0,"key").length;return I===S||I===y}function u(f,w,S=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(f);return r.fromBytes(w).multiply(y).toBytes(S)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},_=jr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:r,utils:p,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:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:_,lengths:f}=Qr(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},S=a*Ps<i.ORDER;function y(g){const m=a>>Pe;return g>m}function I(g,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return m}function P(){if(S)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function H(g,m){ft(m);const b=f.signature,A=m==="compact"?b:m==="recovered"?b+1:void 0;return q(g,A)}class D{constructor(m,b,A){R(this,"r");R(this,"s");R(this,"recovery");if(this.r=I("r",m),this.s=I("s",b),A!=null){if(P(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(m,b=w.format){H(m,b);let A;if(b==="der"){const{r:O,s:$}=Se.toSig(q(m));return new D(O,$)}b==="recovered"&&(A=m[0],b="compact",m=m.subarray(1));const N=f.signature/2,C=m.subarray(0,N),M=m.subarray(N,N*2);return new D(o.fromBytes(C),o.fromBytes(M),A)}static fromHex(m,b){return this.fromBytes(ze(m),b)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new D(this.r,this.s,m)}recoverPublicKey(m){const{r:b,s:A}=this,N=this.assertRecovery(),C=N===2||N===3?b+a:b;if(!i.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=i.toBytes(C),O=r.fromBytes(ve(Cs((N&1)===0),M)),$=o.inv(C),F=G(q(m,void 0,"msgHash")),Y=o.create(-F*$),W=o.create(A*$),B=r.BASE.multiplyUnsafe(Y).add(O.multiplyUnsafe(W));if(B.is0())throw new Error("invalid recovery: point at infinify");return B.assertValidity(),B}hasHighS(){return y(this.s)}toBytes(m=w.format){if(ft(m),m==="der")return ze(Se.hexFromSig(this));const{r:b,s:A}=this,N=o.toBytes(b),C=o.toBytes(A);return m==="recovered"?(P(),ve(Uint8Array.of(this.assertRecovery()),N,C)):ve(N,C)}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 b=Ze(m),A=m.length*8-c;return A>0?b>>BigInt(A):b},G=s.bits2int_modN||function(m){return o.create(K(m))},Z=bt(c);function U(g){return Pr("num < 2^"+c,g,ge,Z),o.toBytes(g)}function z(g,m){return q(g,void 0,"message"),m?q(e(g),void 0,"prehashed message"):g}function k(g,m,b){const{lowS:A,prehash:N,extraEntropy:C}=ct(b,w);g=z(g,N);const M=G(g),O=o.fromBytes(m);if(!o.isValidNot0(O))throw new Error("invalid private key");const $=[U(O),U(M)];if(C!=null&&C!==!1){const B=C===!0?t(f.secretKey):C;$.push(q(B,void 0,"extraEntropy"))}const F=ve(...$),Y=M;function W(B){const X=K(B);if(!o.isValidNot0(X))return;const Q=o.inv(X),oe=r.BASE.multiply(X).toAffine(),V=o.create(oe.x);if(V===ge)return;const ee=o.create(Q*o.create(Y+V*O));if(ee===ge)return;let Tt=(oe.x===V?0:2)|Number(oe.y&Pe),Rt=ee;return A&&y(ee)&&(Rt=o.neg(ee),Tt^=1),new D(V,Rt,S?void 0:Tt)}return{seed:F,k2sig:W}}function v(g,m,b={}){const{seed:A,k2sig:N}=k(g,m,b);return Nr(e.outputLen,o.BYTES,n)(A,N).toBytes(b.format)}function E(g,m,b,A={}){const{lowS:N,prehash:C,format:M}=ct(A,w);if(b=q(b,void 0,"publicKey"),m=z(m,C),!mt(g)){const O=g instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}H(g,M);try{const O=D.fromBytes(g,M),$=r.fromBytes(b);if(N&&O.hasHighS())return!1;const{r:F,s:Y}=O,W=G(m),B=o.inv(Y),X=o.create(W*B),Q=o.create(F*B),oe=r.BASE.multiplyUnsafe(X).add($.multiplyUnsafe(Q));return oe.is0()?!1:o.create(oe.x)===F}catch{return!1}}function T(g,m,b={}){const{prehash:A}=ct(b,w);return m=z(m,A),D.fromBytes(g,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:_,lengths:f,Point:r,sign:v,verify:E,recoverPublicKey:T,Signature:D,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),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,p=ce(u,s,e)*u%e,_=ce(p,s,e)*u%e,f=ce(_,Jt,e)*l%e,w=ce(f,n,e)*f%e,S=ce(w,i,e)*w%e,y=ce(S,a,e)*S%e,I=ce(y,c,e)*y%e,P=ce(I,a,e)*S%e,H=ce(P,s,e)*u%e,D=ce(H,o,e)*w%e,K=ce(D,t,e)*l%e,G=ce(K,Jt,e);if(!_t.eql(_t.sqr(G),r))throw new Error("Cannot find square root");return G}const _t=Qe(Et.p,{sqrt:sn}),rn=Zr(Et,{Fp:_t,endo:tn}),nn=en(rn,Rr),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 i=0;i<7;i++)e=(e<<Me^(e>>cn)*dn)%ln,e&an&&(n^=Me<<(Me<<BigInt(i))-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 o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],p=Zt(l,u,1)^s[a],_=Qt(l,u,1)^s[a+1];for(let f=0;f<50;f+=10)r[o+f]^=p,r[o+f+1]^=_}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=Ds[o],c=Zt(n,i,a),l=Qt(n,i,a),u=Ls[o];n=r[u],i=r[u+1],r[u]=c,r[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=un[t],r[1]^=hn[t]}Ne(s)}class It{constructor(e,s,t,n=!1,i=24){R(this,"state");R(this,"pos",0);R(this,"posOut",0);R(this,"finished",!1);R(this,"state32");R(this,"destroyed",!1);R(this,"blockLen");R(this,"suffix");R(this,"outputLen");R(this,"enableXOF",!1);R(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,we(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=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),q(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ce(this,!1),q(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(s.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return we(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(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:i,enableXOF:o}=this;return e||(e=new It(s,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const 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:i}=await tt.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return tt.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
-
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=es(i),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),p=c[64],_=p>=27?p-27:p,S=new nn.Signature(ts(l),ts(u)).addRecoveryBit(_).recoverPublicKey(o).toBytes(!1).slice(1),y=es(S);return"0x"+Ue(y.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 i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const 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,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Ie.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Ie.generateRandom16Hex(),l=Ie.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",p=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const _=window.open(p,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!_){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const f=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),D(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,S=30;let y=0,I=null;const P=()=>{clearInterval(H),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+S+"초간 대기합니다"),I=setTimeout(()=>{D(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},S*1e3)},H=setInterval(()=>{y++;try{_.closed&&(y<=w?P():(D(),t(new Error("로그인이 취소되었습니다"))))}catch{P()}},1e3),D=()=>{clearTimeout(f),clearInterval(H),I&&clearTimeout(I),window.removeEventListener("message",K)},K=G=>{if(G.origin!==e.expectedOrigin)return;if(!bn.has(G.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",G.origin),D(),t(new Error("Unauthorized OAuth origin"));return}D();const Z=typeof G.data.status=="string",U=Z?G.data.data??{}:G.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:Z?"wrapped":"flat",status:Z?G.data.status:"(flat)"});const z=(U==null?void 0:U.state)??G.data.state;if(!z||z!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Z&&G.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",U==null?void 0:U.error),t(new Error((U==null?void 0:U.error)||"Authentication failed"));return}if(!Z&&(U!=null&&U.error)){d.error("[CROSSx] OAuth 실패:",U.error),t(new Error(U.error||"Authentication failed"));return}const k=U==null?void 0:U.idToken,v=U==null?void 0:U.accessToken,E=v??k,T=(U==null?void 0:U.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!v,hasIdToken:!!k,hasEmail:!!T}),!E){d.error("[CROSSx] 토큰을 찾을 수 없음:",G.data),t(new Error("Token not found in response"));return}const g={token:E,email:T},m=b=>{Ie.verifyIdTokenNonce(b,l).then(()=>s(g)).catch(A=>{d.error("[CROSSx] nonce 검증 실패:",A),t(A instanceof Error?A:new Error("nonce verification failed"))})};v?v.split(".").length===3?m(v):k?m(k):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(g)):k?m(k):t(new Error("Token not found in response"))};window.addEventListener("message",K)})}}const $e="crossx_wallet_data",ke="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 i=(s=this.pinStore)==null?void 0:s.get();return i&&(await this.storage.set(ke,i),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,i,o){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${i} from=${o}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,i){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,s,t,n){return d.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(ke);return s&&s!==e?!1:(s||await this.storage.set(ke,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(ke);if(n&&t&&n!==t)throw new x(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(ke,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new 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=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(ke,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,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(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,p;const i=await this.ensureValidToken(),o=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const f=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(f&&typeof f.code=="number"){if(f.code<0||f.code>=400){const w=f.message||f.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:f.code,message:w,url:o,method:e});const S=Ae.mapGatewayError(f.code,f.data);if(S===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(S===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(f.code,w));const y=S===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:S,I=y===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ae.getGatewayErrorMessage(f.code,w),P=f.data,H=S===h.PIN_LOCKED?Ae.extractLockDetails(P):P??void 0;throw new x(y,I,H)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:f.code,url:o,method:e}),f.data??f}return f}catch(_){if(_ instanceof x)throw _;const f=((l=_.response)==null?void 0:l.status)??_.status;if((f===401||f===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${f} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=_.response)!=null&&u.data){const w=_.response.data,S=w.message||w.data||"API 요청에 실패했습니다",y=w.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:y,message:S,url:o,method:e,status:(p=_.response)==null?void 0:p.status}),new x(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${y}): ${S}`)}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 i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}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},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,s,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,o);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,i)).txHash}}async migrateWallet(e,s){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e};return(await this.request("POST","/mnemonic/verify-password",s)).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 i=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(s==null?void 0:s.permanent)=="boolean"&&(t.permanent=s.permanent),t}static hasLockInfo(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!s||typeof s!="object"?!1:typeof s.remainingAttempts=="number"||typeof s.remaining_attempts=="number"||typeof s.maxAttempts=="number"||typeof s.max_attempts=="number"}static mapGatewayError(e,s){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-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?or:ir;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",J="__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_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,i,o,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,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 g(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new g(h.OAUTH_POPUP_BLOCKED,i):new g(h.AUTH_FAILED,i)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:x}=await this.exchangeFirebaseToken(e,u);let _,y,v;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),y=(i=A.firebase)==null?void 0:i.sign_in_provider;const T=((o=A.firebase)==null?void 0:o.identities)??{};v=A.email??((a=T.email)==null?void 0:a[0]),y==="google.com"?_=(c=T["google.com"])==null?void 0:c[0]:y==="apple.com"&&(_=(l=T["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",y,"hasProviderSub:",!!_,"email:",v??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const A=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const T=await this.crypto.verifyJWT(f);if(n=T.signatureVerified??!1,!T.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const H=T.payload,L=H.email??v??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",H.email??"(없음)","/ Firebase JWT:",v??"(없음)","/ OAuth 콜백:",s??"(없음)","→",L??"(없음)"),t={id:H.sub,email:L,signInProvider:y,providerSub:_},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),x&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,x):x&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??s,signInProvider:y,providerSub:_},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const S=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,S),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new g(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}const s=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){const s=e instanceof g&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",s?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),s&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=Xe.REFRESH_RELOGIN_CODES.has(c.code);throw new g(u?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new g(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof g&&e.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,s){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(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 i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof g&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof g&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};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 g(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class 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 i=0;i<s.length;i++)n[i]=s[i]^t[i];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class 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),i={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new g(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class 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,ir=5*60*1e3,or=30*1e3;function De(r){const e=r.indexOf("@");if(e<0)return"***";const s=r.substring(0,e),t=r.substring(e);return s.length<=1?`${s}***${t}`:`${s[0]}***${t}`}const ee=class ee extends Zs{constructor(e,s,t,n,i,o,a,c,l,u,f){var x,_;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&kt(e.logger),this.confirmation=l,this.pinStore=f??new gt,this.chainRegistry=u,this.jsonRpc=new Js(u,i),this.signInUseCase=new ht(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new Ys(this.internalConfig,t,c),this.migrateWalletUseCase=new Xs(t,a),(x=a.setOnUnauthorized)==null||x.call(a,()=>this.forceLogout()),(_=a.setTokenRefresher)==null||_.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.4.3 초기화 중..."),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 i=await this.signInUseCase.restoreSession();if(i!=null&&i.success){this.applyAuthResult(i);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(o){if(!(o instanceof g&&o.code===h.PIN_CANCELLED))throw o;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v1.4.3 초기화 완료"),this.emit("initialized",{restored:!!(i!=null&&i.success)}),i??null}catch(n){throw new g(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(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 g(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 g?t:new g(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:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...s,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}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 g&&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 g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw new g(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new g(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new g(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof g&&s.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.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 g?s:new g(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.ensurePinForSigning();const n=s.length,o={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(o),o},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 g?e:new g(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof g?s:new g(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(fe(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new g(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 g(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 g&&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 g(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 g&&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 g(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 g(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 g(h.USER_REJECTED,"User rejected the message signing request");try{const o=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,o.signature,n.address),{chainId:e,signature:o.signature,message:s,address:n.address}}catch(o){throw o instanceof g?o:new g(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,s,t){return this.withSessionRecovery(()=>this._signTypedData(e,s,t))}async _signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");ee.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 g(h.USER_REJECTED,"User rejected the typed data signing request");try{const o=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 ee.validateSignatureFormat(o.signature),{chainId:e,signature:o.signature,address:n.address}}catch(o){throw o instanceof g?o:new g(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,s){return this.signTypedData(ee.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=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:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(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 ee.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof g)throw a;const c=a instanceof Error?a.message:String(a);throw new g(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 g(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 i=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:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(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 g)throw a;const c=a instanceof Error?a.message:String(a);throw new g(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,i=rr,o=t.timeoutMs??Nt,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new g(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var v,S;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((v=this._config.receiptPolling)==null?void 0:v.intervalMs)??tr,l=i??((S=this._config.receiptPolling)==null?void 0:S.timeoutMs)??Nt,u=st(e),f=s.from??"";let x,_;const y=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{x=A;const T=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),H=s.value?BigInt(s.value):0n,L=ee.formatTxAmount(s.value,u.symbol,u.decimals),V=ee.formatTxAmount("0x"+T.toString(16),u.symbol,u.decimals),F=ee.formatTxAmount("0x"+(H+T).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:A.from,to:A.to??s.to,amount:L,fees:V,total:F,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(_=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:f,to:s.to,amount:ee.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},y),_)throw _;return{chainId:e,txHash:a,receipt:x}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new g(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof g?n:new g(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const i=n instanceof Error?n.message:String(n);throw new g(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:ee.formatWei(n),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}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,o=(s%t).toString().padStart($t,"0").replace(/0+$/,"").slice(0,Mt);return o?`${n}.${o}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new os(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof g)throw n;const i=n instanceof Error?n.message:String(n);throw new g(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const i=10n**BigInt(t),o=n/i,c=(n%i).toString().padStart(t,"0").slice(0,Mt).replace(/0+$/,"");return`${c?`${o}.${c}`:`${o}`} ${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,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const f=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});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 x=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,f,e));if(!x){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=f;break}if(x.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=f;break}const _=x.pinStatus;if(o=_.maxAttempts,i=o-_.remainingAttempts,_.remainingAttempts===0&&_.lockExpiresAt){const y=_.lockExpiresAt*1e3,v=Math.max(1,Math.round((y-Date.now())/1e3)),S=v<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${v}초, 메시지: ${S}`),await this.confirmation.showRecoveryPinLockedPrompt(v,S),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(x){if(!(x instanceof g))throw x;if(x.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const _=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:_.sessionAlert_title,message:_.alert_sessionExpired,email:this.userEmail?De(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.clearAuthState(),x}if(x.code===h.MIGRATION_PIN_LOCKED){const _=x.details;if(o=(_==null?void 0:_.maxAttempts)??5,(_==null?void 0:_.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 y=((_==null?void 0:_.lockExpiresAt)??0)*1e3,v=Math.max(1,Math.round((y-Date.now())/1e3)),S=v<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${v}초`),await this.confirmation.showRecoveryPinLockedPrompt(v,S),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",x),x}}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 g&&f.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof g&&f.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const x=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:x.sessionAlert_title,message:x.alert_sessionExpired,email:this.userEmail?De(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const v=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",v.address),v}catch(v){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",v),v}}throw this.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}async withResolvedGasAndFee(e,s){const t=_=>!(_!=null&&_.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,f,x]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,i?this.estimateGas(e,s):null,o?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const _=x;if(_){const y=Lt;c.maxFeePerGas="0x"+(BigInt(_)+BigInt(y)).toString(16),c.maxPriorityFeePerGas=y,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",_,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=nr,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=Lt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=ee.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const i=Number(n[1]);if(t===void 0)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==i)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${i})와 일치하지 않습니다`)}}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 g(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Dt)throw new g(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 g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new g(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 g(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof g)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,i;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=ee.normalizeLoginType((i=e.user)==null?void 0:i.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,i;this.ensureInitialized();const e=this.providerSub,s=this.userId,t=this.loginType;this._isRecoveringSession=!0;try{this.authenticated=!1,this.tokenStore.clear();const o=t?{provider:t}:void 0;let a;try{a=await this.signInUseCase.execute(o)}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=((i=a.user)==null?void 0:i.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):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):void 0;if(s instanceof g&&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 g&&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 g)||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 g(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const o=await this.signInAgain();if(!o.success)throw new g(h.SESSION_EXPIRED,o.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 g(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 g(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 i,o;this._verifyPinMutex=new Promise((c,l)=>{i=c,o=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 g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();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 g){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return ee.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof g&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:this.userEmail?De(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this._verifyPinMutex=null}}static buildPinLockedResult(e,s){const t=e.details;if(t!=null&&t.permanent)return{ok:!1,error:s.pinLocked_permanent};if((t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts){const n=t.maxAttempts-t.remainingAttempts;return{ok:!1,error:s.pinInput_error,attemptCount:n,maxAttempts:t.maxAttempts}}return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}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 i=e!==void 0?t.find(o=>o.index===e)??t[0]:t[0];this.address=i.address,this.activeWalletIndex=i.index,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:i.address,index:i.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,n,i,o;const a=c=>{if(c.code===h.PIN_WRONG)return t=s.pinInput_error,n=void 0,i=void 0,o=void 0,!0;if(c.code===h.PIN_INVALID)return t=c.message,n=void 0,i=void 0,o=void 0,!0;if(c.code===h.PIN_LOCKED){const l=c.details;return l!=null&&l.permanent?(t=s.pinLocked_permanent,n=void 0,i=void 0,o=void 0):(l==null?void 0:l.remainingAttempts)!=null&&l.remainingAttempts>0&&l.maxAttempts?(t=s.pinInput_error,n=void 0,i=l.maxAttempts-l.remainingAttempts,o=l.maxAttempts):(t="Too many failed attempts. Your account is temporarily locked.",n=l==null?void 0:l.lockExpiresAt,i=void 0,o=void 0),!0}return!1};try{return await e()}catch(c){if(!(c instanceof g&&a(c)))throw c}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t),this.pinStore.clear(),await this.ensureVerifiedPin(t,n,i,o),n=void 0,i=void 0,o=void 0;try{return await e()}catch(c){if(c instanceof g&&a(c))continue;throw c}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new g(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 g(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new g(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(),kt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};ee.OFFCHAIN_CHAIN_ID="0";let Ve=ee;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 i=n.result;i.objectStoreNames.contains(he)||i.createObjectStore(he),i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ee,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 i=s.objectStore(he).getAll(),o=s.objectStore(he).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Ee,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 W(r,e,s=""){const t=mt(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function 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){W(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(W(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,i=0;n<s;n++,i+=2){const o=Ft(r.charCodeAt(i)),a=Ft(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ve(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];W(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function us(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function 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){k(this,"blockLen");k(this,"outputLen");k(this,"padOffset");k(this,"isLE");k(this,"buffer");k(this,"view");k(this,"finished",!1);k(this,"length",0);k(this,"pos",0);k(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),W(e);const{view:s,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=nt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ce(this),ls(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,Ne(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let f=o;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=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],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),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 i=0;i<s;i++){const{h:o,l:a}=wr(r[i],e);[t[i],n[i]]=[o,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:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let f=0;f<16;f++,s+=4)be[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const x=be[f-15],_=be[f-2],y=pe(x,7)^pe(x,18)^x>>>3,v=pe(_,17)^pe(_,19)^_>>>10;be[f]=v+be[f-7]+y+be[f-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const x=pe(a,6)^pe(a,11)^pe(a,25),_=u+x+xr(a,c,l)+Ir[f]+be[f]|0,v=(pe(t,2)^pe(t,13)^pe(t,22))+gr(t,n,i)|0;u=l,l=c,c=a,a=o+_|0,o=i,i=n,n=t,t=_+v|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){Ne(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Ne(this.buffer)}}class Tr extends Ar{constructor(){super(32);k(this,"A",ye[0]|0);k(this,"B",ye[1]|0);k(this,"C",ye[2]|0);k(this,"D",ye[3]|0);k(this,"E",ye[4]|0);k(this,"F",ye[5]|0);k(this,"G",ye[6]|0);k(this,"H",ye[7]|0)}}const Rr=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 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(kr(W(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 kr(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=S=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},x=(...S)=>s(l,ve(c,...S)),_=(S=n)=>{l=x(i,S),c=x(),S.length!==0&&(l=x(o,S),c=x())},y=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const A=[];for(;S<e;){c=x();const T=c.slice();A.push(T),S+=c.length}return ve(...A)};return(S,A)=>{f(),_(S);let T;for(;!(T=A(y()));)_();return f(),T}}function St(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(s,!0)}function Wt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ne=BigInt(0),te=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,i=te;for(;s!==ne;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=l}if(t!==te)throw new Error("invert: does not exist");return 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+te)/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),i=r.mul(e,n),o=r.mul(r.mul(i,Te),n),a=r.mul(i,r.sub(o,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),i=s(e,e.neg(t)),o=(r+Lr)/bs;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const f=a.mul(l,n),x=a.mul(l,i),_=a.eql(a.sqr(u),c),y=a.eql(a.sqr(f),c);l=a.cmov(l,u,_),u=a.cmov(x,f,y);const v=a.eql(a.sqr(u),c),S=a.cmov(l,u,v);return vt(a,S,c),S}}function vs(r){if(r<gs)throw new Error("sqrt is not defined for small field");let e=r-te,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 i=n.pow(t,e);const o=(e+te)/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,i),x=c.pow(l,e),_=c.pow(l,o);for(;!c.eql(x,c.ONE);){if(c.is0(x))return c.ZERO;let y=1,v=c.sqr(x);for(;!c.eql(v,c.ONE);)if(y++,v=c.sqr(v),y===u)throw new Error("Cannot find square root");const S=te<<BigInt(u-y-1),A=c.pow(f,S);u=y,f=c.sqr(A),x=c.mul(x,f),_=c.mul(_,A)}return _}}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===te)return e;let t=r.ONE,n=e;for(;s>ne;)s&te&&(t=r.mul(t,n)),n=r.sqr(n),s>>=te;return t}function Es(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function Kt(r,e){const s=(r.ORDER-te)/Te,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function 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={}){k(this,"ORDER");k(this,"BITS");k(this,"BYTES");k(this,"isLE");k(this,"ZERO",ne);k(this,"ONE",te);k(this,"_lengths");k(this,"_sqrt");k(this,"_mod");var o;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=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=Gr(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return 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&te)===te}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){W(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?_s(e):Ze(e);if(a&&(c=ue(c,o)),!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){W(r);const t=r.length,n=Is(e),i=As(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?_s(r):Ze(r),a=ue(o,e-te)+te;return s?xs(a,n):yt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Le=BigInt(0),Re=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 it(r,e){Ts(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=bt(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function zt(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=Re);const l=e*t,u=l+Math.abs(a)-1,f=a===0,x=a<0,_=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:x,isNegF:_,offsetF:l}}const ot=new WeakMap,Rs=new WeakMap;function at(r){return Rs.get(r)||1}function jt(r){if(r!==Le)throw new Error("invalid wNAF")}class Kr{constructor(e,s){k(this,"BASE");k(this,"ZERO");k(this,"Fn");k(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&Re&&(t=t.add(n)),n=n.double(),s>>=Re;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=it(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=it(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:x,offsetF:_}=zt(t,a,o);t=c,u?i=i.add(Ye(x,s[_])):n=n.add(Ye(f,s[l]))}return jt(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=it(e,this.bits);for(let o=0;o<i.windows&&t!==Le;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=zt(t,o,i);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=ot.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),ot.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 i=at(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){Ts(s,this.bits),Rs.set(e,s),ot.delete(e)}hasCache(e){return at(e)!==1}}function Vr(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>Le||t>Le;)s&Re&&(i=i.add(n)),t&Re&&(o=o.add(n)),n=n.double(),s>>=Re,t>>=Re;return{p1:i,p2:o}}function 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>Le))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Yt(e.p,s.Fp,t),i=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:i}}function jr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class ks{constructor(e,s){k(this,"oHash");k(this,"iHash");k(this,"blockLen");k(this,"outputLen");k(this,"finished",!1);k(this,"destroyed",!1);if(cs(e),W(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Ne(n)}update(e){return Ce(this),this.iHash.update(e),this}digestInto(e){Ce(this),W(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Os=(r,e,s)=>new ks(r,e).update(s).digest();Os.create=(r,e)=>new ks(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],[i,o]]=e,a=Xt(o*r,s),c=Xt(-n*r,s);let l=r-a*t-c*i,u=-a*n-c*o;const f=l<ge,x=u<ge;f&&(l=-l),x&&(u=-u);const _=bt(Math.ceil(Cr(s)/2))+Pe;if(l<ge||l>=_||u<ge||u>=_)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:x,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=Ge(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?Ge(n.length/2|128):"";return Ge(r)+i+n+e},decode(r,e){const{Err:s}=Se;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Se;if(r<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=W(r,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Se,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},ge=BigInt(0),Pe=BigInt(1),Ps=BigInt(2),We=BigInt(3),Jr=BigInt(4);function Zr(r,e={}){const s=zr("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;St(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ns(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(D,w,p){const{x:m,y:b}=w.toAffine(),I=t.toBytes(m);if(je(p,"isCompressed"),p){u();const R=!t.isOdd(b);return ve(Cs(R),I)}else return ve(Uint8Array.of(4),I,t.toBytes(b))}function x(D){W(D,void 0,"Point");const{publicKey:w,publicKeyUncompressed:p}=l,m=D.length,b=D[0],I=D.subarray(1);if(m===w&&(b===2||b===3)){const R=t.fromBytes(I);if(!t.isValid(R))throw new Error("bad point: is not on curve, wrong x");const O=v(R);let E;try{E=t.sqrt(O)}catch(q){const G=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}u();const C=t.isOdd(E);return(b&1)===1!==C&&(E=t.neg(E)),{x:R,y:E}}else if(m===p&&b===4){const R=t.BYTES,O=t.fromBytes(I.subarray(0,R)),E=t.fromBytes(I.subarray(R,R*2));if(!S(O,E))throw new Error("bad point: is not on curve");return{x:O,y:E}}else throw new Error(`bad point: got length ${m}, expected compressed=${w} or uncompressed=${p}`)}const _=e.toBytes||f,y=e.fromBytes||x;function v(D){const w=t.sqr(D),p=t.mul(w,D);return t.add(t.add(p,t.mul(D,i.a)),i.b)}function S(D,w){const p=t.sqr(w),m=v(D);return t.eql(p,m)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,We),Jr),T=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,T)))throw new Error("bad curve params: a or b");function H(D,w,p=!1){if(!t.isValid(w)||p&&t.is0(w))throw new Error(`bad point coordinate ${D}`);return w}function L(D){if(!(D instanceof j))throw new Error("Weierstrass Point expected")}function V(D){if(!c||!c.basises)throw new Error("no endo");return Yr(D,c.basises,n.ORDER)}const F=Wt((D,w)=>{const{X:p,Y:m,Z:b}=D;if(t.eql(b,t.ONE))return{x:p,y:m};const I=D.is0();w==null&&(w=I?t.ONE:t.inv(b));const R=t.mul(p,w),O=t.mul(m,w),E=t.mul(b,w);if(I)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:R,y:O}}),re=Wt(D=>{if(D.is0()){if(e.allowInfinityPoint&&!t.is0(D.Y))return;throw new Error("bad point: ZERO")}const{x:w,y:p}=D.toAffine();if(!t.isValid(w)||!t.isValid(p))throw new Error("bad point: x or y not field elements");if(!S(w,p))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(D,w,p,m,b){return p=new j(t.mul(p.X,D),p.Y,p.Z),w=Ye(m,w),p=Ye(b,p),w.add(p)}const P=class P{constructor(w,p,m){k(this,"X");k(this,"Y");k(this,"Z");this.X=H("x",w),this.Y=H("y",p,!0),this.Z=H("z",m),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){const{x:p,y:m}=w||{};if(!w||!t.isValid(p)||!t.isValid(m))throw new Error("invalid affine point");if(w instanceof P)throw new Error("projective point not allowed");return t.is0(p)&&t.is0(m)?P.ZERO:new P(p,m,t.ONE)}static fromBytes(w){const p=P.fromAffine(y(W(w,void 0,"point")));return p.assertValidity(),p}static fromHex(w){return P.fromBytes(ze(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,p=!0){return $.createCache(this,w),p||this.multiply(We),this}assertValidity(){re(this)}hasEvenY(){const{y:w}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(w)}equals(w){L(w);const{X:p,Y:m,Z:b}=this,{X:I,Y:R,Z:O}=w,E=t.eql(t.mul(p,O),t.mul(I,b)),C=t.eql(t.mul(m,O),t.mul(R,b));return E&&C}negate(){return new P(this.X,t.neg(this.Y),this.Z)}double(){const{a:w,b:p}=i,m=t.mul(p,We),{X:b,Y:I,Z:R}=this;let O=t.ZERO,E=t.ZERO,C=t.ZERO,M=t.mul(b,b),q=t.mul(I,I),G=t.mul(R,R),B=t.mul(b,I);return B=t.add(B,B),C=t.mul(b,R),C=t.add(C,C),O=t.mul(w,C),E=t.mul(m,G),E=t.add(O,E),O=t.sub(q,E),E=t.add(q,E),E=t.mul(O,E),O=t.mul(B,O),C=t.mul(m,C),G=t.mul(w,G),B=t.sub(M,G),B=t.mul(w,B),B=t.add(B,C),C=t.add(M,M),M=t.add(C,M),M=t.add(M,G),M=t.mul(M,B),E=t.add(E,M),G=t.mul(I,R),G=t.add(G,G),M=t.mul(G,B),O=t.sub(O,M),C=t.mul(G,q),C=t.add(C,C),C=t.add(C,C),new P(O,E,C)}add(w){L(w);const{X:p,Y:m,Z:b}=this,{X:I,Y:R,Z:O}=w;let E=t.ZERO,C=t.ZERO,M=t.ZERO;const q=i.a,G=t.mul(i.b,We);let B=t.mul(p,I),X=t.mul(m,R),Z=t.mul(b,O),oe=t.add(p,m),K=t.add(I,R);oe=t.mul(oe,K),K=t.add(B,X),oe=t.sub(oe,K),K=t.add(p,b);let Q=t.add(I,O);return K=t.mul(K,Q),Q=t.add(B,Z),K=t.sub(K,Q),Q=t.add(m,b),E=t.add(R,O),Q=t.mul(Q,E),E=t.add(X,Z),Q=t.sub(Q,E),M=t.mul(q,K),E=t.mul(G,Z),M=t.add(E,M),E=t.sub(X,M),M=t.add(X,M),C=t.mul(E,M),X=t.add(B,B),X=t.add(X,B),Z=t.mul(q,Z),K=t.mul(G,K),X=t.add(X,Z),Z=t.sub(B,Z),Z=t.mul(q,Z),K=t.add(K,Z),B=t.mul(X,K),C=t.add(C,B),B=t.mul(Q,K),E=t.mul(oe,E),E=t.sub(E,B),B=t.mul(oe,X),M=t.mul(Q,M),M=t.add(M,B),new P(E,C,M)}subtract(w){return this.add(w.negate())}is0(){return this.equals(P.ZERO)}multiply(w){const{endo:p}=e;if(!n.isValidNot0(w))throw new Error("invalid scalar: out of range");let m,b;const I=R=>$.cached(this,R,O=>Vt(P,O));if(p){const{k1neg:R,k1:O,k2neg:E,k2:C}=V(w),{p:M,f:q}=I(O),{p:G,f:B}=I(C);b=q.add(B),m=U(p.beta,M,G,R,E)}else{const{p:R,f:O}=I(w);m=R,b=O}return Vt(P,[m,b])[0]}multiplyUnsafe(w){const{endo:p}=e,m=this;if(!n.isValid(w))throw new Error("invalid scalar: out of range");if(w===ge||m.is0())return P.ZERO;if(w===Pe)return m;if($.hasCache(this))return this.multiply(w);if(p){const{k1neg:b,k1:I,k2neg:R,k2:O}=V(w),{p1:E,p2:C}=Vr(P,m,I,O);return U(p.beta,E,C,b,R)}else return $.unsafe(m,w)}toAffine(w){return F(this,w)}isTorsionFree(){const{isTorsionFree:w}=e;return o===Pe?!0:w?w(P,this):$.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:w}=e;return o===Pe?this:w?w(P,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(w=!0){return je(w,"isCompressed"),this.assertValidity(),_(P,this,w)}toHex(w=!0){return Ue(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};k(P,"BASE",new P(i.Gx,i.Gy,t.ONE)),k(P,"ZERO",new P(t.ZERO,t.ONE,t.ZERO)),k(P,"Fp",t),k(P,"Fn",n);let j=P;const Y=n.BITS,$=new Kr(j,e.endo?Math.ceil(Y/2):Y);return j.BASE.precompute(8),j}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 i(_){try{const y=s.fromBytes(_);return s.isValidNot0(y)}catch{return!1}}function o(_,y){const{publicKey:v,publicKeyUncompressed:S}=n;try{const A=_.length;return y===!0&&A!==v||y===!1&&A!==S?!1:!!r.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return qr(W(_,n.seed,"seed"),s.ORDER)}function c(_,y=!0){return r.BASE.multiply(s.fromBytes(_)).toBytes(y)}function l(_){const{secretKey:y,publicKey:v,publicKeyUncompressed:S}=n;if(!mt(_)||"_lengths"in s&&s._lengths||y===v)return;const A=W(_,void 0,"key").length;return A===v||A===S}function u(_,y,v=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(y)===!1)throw new Error("second arg must be public key");const S=s.fromBytes(_);return r.fromBytes(y).multiply(S).toBytes(v)}const f={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},x=jr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:x,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||((w,p)=>Os(e,w,p)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:x,lengths:_}=Qr(r,s),y={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},v=a*Ps<i.ORDER;function S(w){const p=a>>Pe;return w>p}function A(w,p){if(!o.isValidNot0(p))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return p}function T(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function H(w,p){ft(p);const m=_.signature,b=p==="compact"?m:p==="recovered"?m+1:void 0;return W(w,b)}class L{constructor(p,m,b){k(this,"r");k(this,"s");k(this,"recovery");if(this.r=A("r",p),this.s=A("s",m),b!=null){if(T(),![0,1,2,3].includes(b))throw new Error("invalid recovery id");this.recovery=b}Object.freeze(this)}static fromBytes(p,m=y.format){H(p,m);let b;if(m==="der"){const{r:E,s:C}=Se.toSig(W(p));return new L(E,C)}m==="recovered"&&(b=p[0],m="compact",p=p.subarray(1));const I=_.signature/2,R=p.subarray(0,I),O=p.subarray(I,I*2);return new L(o.fromBytes(R),o.fromBytes(O),b)}static fromHex(p,m){return this.fromBytes(ze(p),m)}assertRecovery(){const{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new L(this.r,this.s,p)}recoverPublicKey(p){const{r:m,s:b}=this,I=this.assertRecovery(),R=I===2||I===3?m+a:m;if(!i.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const O=i.toBytes(R),E=r.fromBytes(ve(Cs((I&1)===0),O)),C=o.inv(R),M=F(W(p,void 0,"msgHash")),q=o.create(-M*C),G=o.create(b*C),B=r.BASE.multiplyUnsafe(q).add(E.multiplyUnsafe(G));if(B.is0())throw new Error("invalid recovery: point at infinify");return B.assertValidity(),B}hasHighS(){return S(this.s)}toBytes(p=y.format){if(ft(p),p==="der")return ze(Se.hexFromSig(this));const{r:m,s:b}=this,I=o.toBytes(m),R=o.toBytes(b);return p==="recovered"?(T(),ve(Uint8Array.of(this.assertRecovery()),I,R)):ve(I,R)}toHex(p){return Ue(this.toBytes(p))}}const V=s.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");const m=Ze(p),b=p.length*8-c;return b>0?m>>BigInt(b):m},F=s.bits2int_modN||function(p){return o.create(V(p))},re=bt(c);function U(w){return Pr("num < 2^"+c,w,ge,re),o.toBytes(w)}function j(w,p){return W(w,void 0,"message"),p?W(e(w),void 0,"prehashed message"):w}function Y(w,p,m){const{lowS:b,prehash:I,extraEntropy:R}=ct(m,y);w=j(w,I);const O=F(w),E=o.fromBytes(p);if(!o.isValidNot0(E))throw new Error("invalid private key");const C=[U(E),U(O)];if(R!=null&&R!==!1){const B=R===!0?t(_.secretKey):R;C.push(W(B,void 0,"extraEntropy"))}const M=ve(...C),q=O;function G(B){const X=V(B);if(!o.isValidNot0(X))return;const Z=o.inv(X),oe=r.BASE.multiply(X).toAffine(),K=o.create(oe.x);if(K===ge)return;const Q=o.create(Z*o.create(q+K*E));if(Q===ge)return;let Tt=(oe.x===K?0:2)|Number(oe.y&Pe),Rt=Q;return b&&S(Q)&&(Rt=o.neg(Q),Tt^=1),new L(K,Rt,v?void 0:Tt)}return{seed:M,k2sig:G}}function $(w,p,m={}){const{seed:b,k2sig:I}=Y(w,p,m);return Nr(e.outputLen,o.BYTES,n)(b,I).toBytes(m.format)}function P(w,p,m,b={}){const{lowS:I,prehash:R,format:O}=ct(b,y);if(m=W(m,void 0,"publicKey"),p=j(p,R),!mt(w)){const E=w instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+E)}H(w,O);try{const E=L.fromBytes(w,O),C=r.fromBytes(m);if(I&&E.hasHighS())return!1;const{r:M,s:q}=E,G=F(p),B=o.inv(q),X=o.create(G*B),Z=o.create(M*B),oe=r.BASE.multiplyUnsafe(X).add(C.multiplyUnsafe(Z));return oe.is0()?!1:o.create(oe.x)===M}catch{return!1}}function D(w,p,m={}){const{prehash:b}=ct(m,y);return p=j(p,b),L.fromBytes(w,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:x,lengths:_,Point:r,sign:$,verify:P,recoverPublicKey:D,Signature:L,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),i=BigInt(22),o=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,x=ce(f,s,e)*u%e,_=ce(x,Jt,e)*l%e,y=ce(_,n,e)*_%e,v=ce(y,i,e)*y%e,S=ce(v,a,e)*v%e,A=ce(S,c,e)*S%e,T=ce(A,a,e)*v%e,H=ce(T,s,e)*u%e,L=ce(H,o,e)*y%e,V=ce(L,t,e)*l%e,F=ce(V,Jt,e);if(!_t.eql(_t.sqr(F),r))throw new Error("Cannot find square root");return F}const _t=Qe(Et.p,{sqrt:sn}),rn=Zr(Et,{Fp:_t,endo:tn}),nn=en(rn,Rr),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 i=0;i<7;i++)e=(e<<Me^(e>>cn)*dn)%ln,e&an&&(n^=Me<<(Me<<BigInt(i))-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 o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],f=Zt(l,u,1)^s[a],x=Qt(l,u,1)^s[a+1];for(let _=0;_<50;_+=10)r[o+_]^=f,r[o+_+1]^=x}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=Ds[o],c=Zt(n,i,a),l=Qt(n,i,a),u=Ls[o];n=r[u],i=r[u+1],r[u]=c,r[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=un[t],r[1]^=hn[t]}Ne(s)}class It{constructor(e,s,t,n=!1,i=24){k(this,"state");k(this,"pos",0);k(this,"posOut",0);k(this,"finished",!1);k(this,"state32");k(this,"destroyed",!1);k(this,"blockLen");k(this,"suffix");k(this,"outputLen");k(this,"enableXOF",!1);k(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,we(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=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),W(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ce(this,!1),W(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(s.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return we(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(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:i,enableXOF:o}=this;return e||(e=new It(s,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const 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:i}=await tt.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return tt.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
+
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=es(i),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],x=f>=27?f-27:f,v=new nn.Signature(ts(l),ts(u)).addRecoveryBit(x).recoverPublicKey(o).toBytes(!1).slice(1),S=es(v);return"0x"+Ue(S.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 i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const 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,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Ie.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=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 x=window.open(f,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const _=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),L(),t(new Error("Authentication timeout"))},5*60*1e3),y=10,v=30;let S=0,A=null;const T=()=>{clearInterval(H),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+v+"초간 대기합니다"),A=setTimeout(()=>{L(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},v*1e3)},H=setInterval(()=>{S++;try{x.closed&&(S<=y?T():(L(),t(new Error("로그인이 취소되었습니다"))))}catch{T()}},1e3),L=()=>{clearTimeout(_),clearInterval(H),A&&clearTimeout(A),window.removeEventListener("message",V)},V=F=>{if(F.origin!==e.expectedOrigin)return;if(!bn.has(F.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",F.origin),L(),t(new Error("Unauthorized OAuth origin"));return}L();const re=typeof F.data.status=="string",U=re?F.data.data??{}:F.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:re?"wrapped":"flat",status:re?F.data.status:"(flat)"});const j=(U==null?void 0:U.state)??F.data.state;if(!j||j!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(re&&F.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",U==null?void 0:U.error),t(new Error((U==null?void 0:U.error)||"Authentication failed"));return}if(!re&&(U!=null&&U.error)){d.error("[CROSSx] OAuth 실패:",U.error),t(new Error(U.error||"Authentication failed"));return}const Y=U==null?void 0:U.idToken,$=U==null?void 0:U.accessToken,P=$??Y,D=(U==null?void 0:U.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!$,hasIdToken:!!Y,hasEmail:!!D}),!P){d.error("[CROSSx] 토큰을 찾을 수 없음:",F.data),t(new Error("Token not found in response"));return}const w={token:P,email:D},p=m=>{Ie.verifyIdTokenNonce(m,l).then(()=>s(w)).catch(b=>{d.error("[CROSSx] nonce 검증 실패:",b),t(b instanceof Error?b:new Error("nonce verification failed"))})};$?$.split(".").length===3?p($):Y?p(Y):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(w)):Y?p(Y):t(new Error("Token not found in response"))};window.addEventListener("message",V)})}}const $e="crossx_wallet_data",ke="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 i=(s=this.pinStore)==null?void 0:s.get();return i&&(await this.storage.set(ke,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new g(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get($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,i,o){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${i} from=${o}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,i){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,s,t,n){return d.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(ke);return s&&s!==e?!1:(s||await this.storage.set(ke,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new g(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(ke);if(n&&t&&n!==t)throw new g(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(ke,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new g(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new g(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set($e,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(ke,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,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(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 g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,s,t,n=!1){var c,l,u,f;const i=await this.ensureValidToken(),o=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const y=_.message||_.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:y,url:o,method:e});const v=Ae.mapGatewayError(_.code,_.data);if(v===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(v===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new g(h.USER_NOT_FOUND,Ae.getGatewayErrorMessage(_.code,y));const S=v===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:v,A=S===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ae.getGatewayErrorMessage(_.code,y),T=_.data,H=v===h.PIN_LOCKED?Ae.extractLockDetails(T):T??void 0;throw new g(S,A,H)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:o,method:e}),_.data??_}return _}catch(x){if(x instanceof g)throw x;const _=((l=x.response)==null?void 0:l.status)??x.status;if((_===401||_===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=x.response)!=null&&u.data){const y=x.response.data,v=y.message||y.data||"API 요청에 실패했습니다",S=y.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:S,message:v,url:o,method:e,status:(f=x.response)==null?void 0:f.status}),new g(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${S}): ${v}`)}throw x}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new g(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new g(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new g(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new g(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,s,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,o);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,i)).txHash}}async migrateWallet(e,s){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e},t=await this.request("POST","/mnemonic/verify-password",s);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new g(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new g(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new g(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,s){const t={password:this.requirePin(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,s){const t={recoveryPin:e,sub:s};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new g(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(s==null?void 0:s.permanent)=="boolean"&&(t.permanent=s.permanent),t}static hasLockInfo(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!s||typeof s!="object"?!1:typeof s.remainingAttempts=="number"||typeof s.remaining_attempts=="number"||typeof s.maxAttempts=="number"||typeof s.max_attempts=="number"}static mapGatewayError(e,s){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-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?or:ir;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new g(Be.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Be.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new g(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",J="__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
|
#${J} {
|
|
@@ -1847,7 +1847,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1847
1847
|
color: var(--cx-title);
|
|
1848
1848
|
margin: 0;
|
|
1849
1849
|
}
|
|
1850
|
-
`;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=s=>s.stopPropagation();for(const s of["pointerdown","pointerup","mousedown","mouseup","click"])r.addEventListener(s,e);r.setAttribute("data-vaul-no-drag","");for(const s of["touchstart","touchend"])r.addEventListener(s,e);r.addEventListener("touchmove",s=>{s.stopPropagation();let t=s.target;for(;t&&t!==r;){const n=window.getComputedStyle(t);if((n.overflowY==="auto"||n.overflowY==="scroll")&&t.scrollHeight>t.clientHeight)return;t=t.parentElement}s.preventDefault()},{passive:!1}),document.body.appendChild(r)}const In=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function qe(){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
|
|
1850
|
+
`;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=s=>s.stopPropagation();for(const s of["pointerdown","pointerup","mousedown","mouseup","click"])r.addEventListener(s,e);r.setAttribute("data-vaul-no-drag","");for(const s of["touchstart","touchend"])r.addEventListener(s,e);r.addEventListener("touchmove",s=>{s.stopPropagation();let t=s.target;for(;t&&t!==r;){const n=window.getComputedStyle(t);if((n.overflowY==="auto"||n.overflowY==="scroll")&&t.scrollHeight>t.clientHeight)return;t=t.parentElement}s.preventDefault()},{passive:!1}),document.body.appendChild(r)}const In=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function qe(){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 se(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,o=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return o?`${t}.${o}`:`${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 Rn(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:i="ETH",nativeDecimals:o=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,o)} ${i}`,maxFeeGwei:lt(t),maxPriorityFeeGwei:n?lt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${xt(l,o)} ${i}`,gasPriceGwei:lt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Us(r){const e=Rn(r);if(!e)return z("Estimated fee","<span>—</span>");let s=z("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=z("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=z("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=z("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=z("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">
|
|
1851
1851
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
1852
1852
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
1853
1853
|
</svg>`,ie=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
@@ -1866,12 +1866,12 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1866
1866
|
<circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
|
|
1867
1867
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
1868
1868
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
1869
|
-
</svg>`;function ae(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-surface-subtle:${r.surfaceSubtle}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-error:${r.errorColor}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function
|
|
1869
|
+
</svg>`;function ae(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-surface-subtle:${r.surfaceSubtle}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-error:${r.errorColor}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function z(r,e){return`
|
|
1870
1870
|
<div class="__crossx-row">
|
|
1871
1871
|
<span class="__crossx-row-label">${r}</span>
|
|
1872
1872
|
<div class="__crossx-row-value">${e}</div>
|
|
1873
|
-
</div>`}function Cn(r,e){const s=e,t=et(r.dappName),n=r.to?`<span class="__crossx-addr-text">${
|
|
1874
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1873
|
+
</div>`}function Cn(r,e){const s=e,t=et(r.dappName),n=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
|
|
1874
|
+
<button class="__crossx-copy-btn" data-copy="${N(r.to)}" title="Copy address">${me}</button>`:"<span>—</span>",i=Us(r),o=r.data??"0x",a=document.createElement("div");return a.id=J,a.innerHTML=`
|
|
1875
1875
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1876
1876
|
<div class="__crossx-header">
|
|
1877
1877
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1882,22 +1882,22 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1882
1882
|
<div class="__crossx-body-cols">
|
|
1883
1883
|
<div class="__crossx-col-left">
|
|
1884
1884
|
<p class="__crossx-sig-subtitle">
|
|
1885
|
-
<span class="__crossx-sig-origin">${
|
|
1885
|
+
<span class="__crossx-sig-origin">${N(t)} </span>is requesting a Signature
|
|
1886
1886
|
</p>
|
|
1887
1887
|
<div class="__crossx-addr-pill">
|
|
1888
1888
|
${At}
|
|
1889
|
-
<span class="__crossx-addr-pill-text">${
|
|
1889
|
+
<span class="__crossx-addr-pill-text">${se(r.from)}</span>
|
|
1890
1890
|
</div>
|
|
1891
1891
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
1892
1892
|
</div>
|
|
1893
1893
|
<hr class="__crossx-divider __crossx-divider--cols">
|
|
1894
1894
|
<div class="__crossx-col-right-sign">
|
|
1895
1895
|
<div class="__crossx-rows">
|
|
1896
|
-
${
|
|
1897
|
-
${
|
|
1896
|
+
${z("To",n)}
|
|
1897
|
+
${z("Network",`<span>${Bs(r.chainId)}</span>`)}
|
|
1898
1898
|
${i}
|
|
1899
1899
|
</div>
|
|
1900
|
-
<pre class="__crossx-raw-tx">${
|
|
1900
|
+
<pre class="__crossx-raw-tx">${N(o)}</pre>
|
|
1901
1901
|
</div>
|
|
1902
1902
|
</div>
|
|
1903
1903
|
<div class="__crossx-btn-row">
|
|
@@ -1906,8 +1906,8 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1906
1906
|
</div>
|
|
1907
1907
|
</div>
|
|
1908
1908
|
</div>
|
|
1909
|
-
`,a}function Nn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=et(r.dappName),o=r.to?`<span class="__crossx-addr-text">${
|
|
1910
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1909
|
+
`,a}function Nn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=et(r.dappName),o=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
|
|
1910
|
+
<button class="__crossx-copy-btn" data-copy="${N(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=J,u.innerHTML=`
|
|
1911
1911
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1912
1912
|
<div class="__crossx-header">
|
|
1913
1913
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
@@ -1916,28 +1916,28 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1916
1916
|
<hr class="__crossx-divider">
|
|
1917
1917
|
<div class="__crossx-body">
|
|
1918
1918
|
<p class="__crossx-tx-subtitle">
|
|
1919
|
-
<span class="__crossx-sig-origin">${
|
|
1919
|
+
<span class="__crossx-sig-origin">${N(i)}</span> wants your permission to approve the following transaction.
|
|
1920
1920
|
</p>
|
|
1921
1921
|
<div class="__crossx-body-cols">
|
|
1922
1922
|
<div class="__crossx-rows">
|
|
1923
|
-
${
|
|
1924
|
-
${
|
|
1923
|
+
${z("To",o)}
|
|
1924
|
+
${z("Network",`<span>${Bs(r.chainId)}</span>`)}
|
|
1925
1925
|
${a}
|
|
1926
1926
|
</div>
|
|
1927
1927
|
<div class="__crossx-pill">
|
|
1928
|
-
<span class="__crossx-pill-from">${
|
|
1928
|
+
<span class="__crossx-pill-from">${se(r.from)}</span>
|
|
1929
1929
|
<span class="__crossx-pill-amount">${l}</span>
|
|
1930
1930
|
</div>
|
|
1931
1931
|
</div>
|
|
1932
1932
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
1933
1933
|
</div>
|
|
1934
1934
|
</div>
|
|
1935
|
-
`,u}function et(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function
|
|
1936
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1937
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1938
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1935
|
+
`,u}function et(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function N(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ln(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function Dn(r){if(typeof r=="string")return N(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return N(JSON.stringify(r))}catch{return String(r)}}function Mn(r,e){const s=z("From",`<span class="__crossx-addr-text">${se(r.from)}</span>
|
|
1936
|
+
<button class="__crossx-copy-btn" data-copy="${N(r.from)}" title="Copy address">${me}</button>`),t=r.to?z("To",`<span class="__crossx-addr-text">${se(r.to)}</span>
|
|
1937
|
+
<button class="__crossx-copy-btn" data-copy="${N(r.to)}" title="Copy address">${me}</button>`):"",n=r.amount?z("Transfer",`<span>${N(r.amount)}</span>`):"",i=r.fees?z("Tx Fee",`<span>${N(r.fees)}</span>`):"",o=r.txHash?z("Tx Hash",`<span class="__crossx-addr-text">${se(r.txHash)}</span>
|
|
1938
|
+
<button class="__crossx-copy-btn" data-copy="${N(r.txHash)}" title="Copy hash">${me}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
|
|
1939
1939
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1940
|
-
<span class="__crossx-total-amount">${
|
|
1940
|
+
<span class="__crossx-total-amount">${N(r.total)}</span>
|
|
1941
1941
|
</div>`:"",c=document.createElement("div");return c.id=J,c.innerHTML=`
|
|
1942
1942
|
<div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1943
1943
|
<div class="__crossx-header">
|
|
@@ -1970,23 +1970,23 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1970
1970
|
</div>
|
|
1971
1971
|
</div>
|
|
1972
1972
|
</div>
|
|
1973
|
-
`,s}function Bn(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=r.querySelector("#__crossx-ttl"),o=r.querySelector(".__crossx-header");if(i){const
|
|
1974
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1975
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1976
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1973
|
+
`,s}function Bn(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=r.querySelector("#__crossx-ttl"),o=r.querySelector(".__crossx-header");if(i){const y=n?Pn:t?"":On,v=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";y?(i.style.display="flex",i.style.alignItems="center",i.style.gap="8px",i.innerHTML=`${y}<span>${v}</span>`):i.textContent=v}if(o&&!r.querySelector("#__crossx-close-btn")){const y=document.createElement("button");y.className="__crossx-close",y.id="__crossx-close-btn",y.setAttribute("aria-label","Close"),y.innerHTML=ie,o.appendChild(y)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?z("From",`<span class="__crossx-addr-text">${se(e.from)}</span>
|
|
1974
|
+
<button class="__crossx-copy-btn" data-copy="${N(e.from)}" title="Copy address">${me}</button>`):"",l=e.to?z("To",`<span class="__crossx-addr-text">${se(e.to)}</span>
|
|
1975
|
+
<button class="__crossx-copy-btn" data-copy="${N(e.to)}" title="Copy address">${me}</button>`):"",u=e.amount?z("Transfer",`<span>${N(e.amount)}</span>`):"",f=e.fees?z("Tx Fee",`<span>${N(e.fees)}</span>`):"",x=e.txHash?z("Tx Hash",`<span class="__crossx-addr-text">${se(e.txHash)}</span>
|
|
1976
|
+
<button class="__crossx-copy-btn" data-copy="${N(e.txHash)}" title="Copy hash">${me}</button>`):"",_=e.total?`<div class="__crossx-total-pill">
|
|
1977
1977
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1978
|
-
<span class="__crossx-total-amount">${
|
|
1978
|
+
<span class="__crossx-total-amount">${N(e.total)}</span>
|
|
1979
1979
|
</div>`:"";a.innerHTML=`
|
|
1980
1980
|
<div class="__crossx-rows">
|
|
1981
1981
|
${c}
|
|
1982
1982
|
${l}
|
|
1983
1983
|
${u}
|
|
1984
|
-
${
|
|
1985
|
-
${
|
|
1984
|
+
${f}
|
|
1985
|
+
${x}
|
|
1986
1986
|
</div>
|
|
1987
|
-
${
|
|
1987
|
+
${_}
|
|
1988
1988
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
1989
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(
|
|
1989
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(y=>{y.addEventListener("click",v=>{var A;v.stopPropagation();const S=y.dataset.copy;S&&((A=navigator.clipboard)==null||A.writeText(S).catch(()=>{}))})})}function Un(r,e){const s=e,t=et(r.dappName),n=N(r.message),i=document.createElement("div");return i.id=J,i.innerHTML=`
|
|
1990
1990
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1991
1991
|
<div class="__crossx-header">
|
|
1992
1992
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1997,11 +1997,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1997
1997
|
<div class="__crossx-body-cols">
|
|
1998
1998
|
<div class="__crossx-col-left">
|
|
1999
1999
|
<p class="__crossx-sig-subtitle">
|
|
2000
|
-
<span class="__crossx-sig-origin">${
|
|
2000
|
+
<span class="__crossx-sig-origin">${N(t)} </span>is requesting a Signature
|
|
2001
2001
|
</p>
|
|
2002
2002
|
<div class="__crossx-addr-pill">
|
|
2003
2003
|
${At}
|
|
2004
|
-
<span class="__crossx-addr-pill-text">${
|
|
2004
|
+
<span class="__crossx-addr-pill-text">${se(r.from)}</span>
|
|
2005
2005
|
</div>
|
|
2006
2006
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
2007
2007
|
</div>
|
|
@@ -2017,12 +2017,12 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2017
2017
|
`,i}function Hn(r,e){const s=e,t=et(r.dappName);let n={};if(typeof r.typedData=="string")try{n=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(n=r.typedData);const i=n.primaryType??"—",o=n.message??{};let a=`
|
|
2018
2018
|
<div class="__crossx-td-row">
|
|
2019
2019
|
<span class="__crossx-td-label">Primary Type</span>
|
|
2020
|
-
<span class="__crossx-td-value">${
|
|
2021
|
-
</div>`;for(const[l,u]of Object.entries(o)){const
|
|
2022
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2020
|
+
<span class="__crossx-td-value">${N(i)}</span>
|
|
2021
|
+
</div>`;for(const[l,u]of Object.entries(o)){const f=Dn(u),_=Ln(u)?`<span class="__crossx-addr-text">${se(u)}</span>
|
|
2022
|
+
<button class="__crossx-copy-btn" data-copy="${N(String(u))}" title="Copy">${me}</button>`:`<span>${f}</span>`;a+=`
|
|
2023
2023
|
<div class="__crossx-td-row">
|
|
2024
|
-
<span class="__crossx-td-label">${
|
|
2025
|
-
<div class="__crossx-td-value">${
|
|
2024
|
+
<span class="__crossx-td-label">${N(l)}</span>
|
|
2025
|
+
<div class="__crossx-td-value">${_}</div>
|
|
2026
2026
|
</div>`}const c=document.createElement("div");return c.id=J,c.innerHTML=`
|
|
2027
2027
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2028
2028
|
<div class="__crossx-header">
|
|
@@ -2034,11 +2034,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2034
2034
|
<div class="__crossx-body-cols">
|
|
2035
2035
|
<div class="__crossx-col-left">
|
|
2036
2036
|
<p class="__crossx-sig-subtitle">
|
|
2037
|
-
<span class="__crossx-sig-origin">${
|
|
2037
|
+
<span class="__crossx-sig-origin">${N(t)} </span>is requesting a Signature
|
|
2038
2038
|
</p>
|
|
2039
2039
|
<div class="__crossx-addr-pill">
|
|
2040
2040
|
${At}
|
|
2041
|
-
<span class="__crossx-addr-pill-text">${
|
|
2041
|
+
<span class="__crossx-addr-pill-text">${se(r.from)}</span>
|
|
2042
2042
|
</div>
|
|
2043
2043
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
2044
2044
|
</div>
|
|
@@ -2054,9 +2054,9 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2054
2054
|
`,c}const Fn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
2055
2055
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
2056
2056
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
2057
|
-
</svg>`;function Gn(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(o=>{const a=t&&o.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${o.index}" data-wallet-address="${
|
|
2057
|
+
</svg>`;function Gn(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(o=>{const a=t&&o.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${o.index}" data-wallet-address="${N(o.address)}">
|
|
2058
2058
|
<span class="__crossx-wallet-idx">${o.index+1}</span>
|
|
2059
|
-
<span class="__crossx-wallet-addr">${
|
|
2059
|
+
<span class="__crossx-wallet-addr">${se(o.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
2060
2060
|
</button>`}).join(""),i=document.createElement("div");return i.id=J,i.innerHTML=`
|
|
2061
2061
|
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2062
2062
|
<div class="__crossx-header">
|
|
@@ -2131,25 +2131,25 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2131
2131
|
</p>
|
|
2132
2132
|
</div>
|
|
2133
2133
|
</div>
|
|
2134
|
-
`,n}function Vn(r,e){const s=r,t=document.createElement("div");t.id=J;const n=
|
|
2135
|
-
<p class="__crossx-session-account-label">${
|
|
2136
|
-
<p class="__crossx-session-account-email">${
|
|
2134
|
+
`,n}function Vn(r,e){const s=r,t=document.createElement("div");t.id=J;const n=N(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
|
|
2135
|
+
<p class="__crossx-session-account-label">${N(e.accountLabel)}</p>
|
|
2136
|
+
<p class="__crossx-session-account-email">${N(e.email)}</p>
|
|
2137
2137
|
</div>`:"";return t.innerHTML=`
|
|
2138
2138
|
<div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
|
|
2139
2139
|
<div class="__crossx-header">
|
|
2140
|
-
<p class="__crossx-title" id="__crossx-session-header-title">${
|
|
2140
|
+
<p class="__crossx-title" id="__crossx-session-header-title">${N(e.title)}</p>
|
|
2141
2141
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
|
|
2142
2142
|
</div>
|
|
2143
2143
|
<hr class="__crossx-divider">
|
|
2144
2144
|
<div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
|
|
2145
2145
|
<div class="__crossx-session-hero">
|
|
2146
|
-
<p class="__crossx-session-hero-title">${
|
|
2146
|
+
<p class="__crossx-session-hero-title">${N(e.title)}</p>
|
|
2147
2147
|
<p class="__crossx-session-hero-message" id="__crossx-session-msg">${n}</p>
|
|
2148
2148
|
</div>
|
|
2149
2149
|
${i}
|
|
2150
2150
|
<div class="__crossx-btn-row">
|
|
2151
|
-
<button class="__crossx-cancel-btn" id="__crossx-session-signout">${
|
|
2152
|
-
<button class="__crossx-confirm-btn" id="__crossx-session-signin">${
|
|
2151
|
+
<button class="__crossx-cancel-btn" id="__crossx-session-signout">${N(e.signOutLabel)}</button>
|
|
2152
|
+
<button class="__crossx-confirm-btn" id="__crossx-session-signin">${N(e.signInAgainLabel)}</button>
|
|
2153
2153
|
</div>
|
|
2154
2154
|
</div>
|
|
2155
2155
|
</div>
|
|
@@ -2173,7 +2173,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2173
2173
|
${n}
|
|
2174
2174
|
</div>
|
|
2175
2175
|
</div>
|
|
2176
|
-
`,i}function jn(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",
|
|
2176
|
+
`,i}function jn(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",f=document.createElement("div");return f.id=J,f.innerHTML=`
|
|
2177
2177
|
<div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2178
2178
|
<div class="__crossx-header">
|
|
2179
2179
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2193,7 +2193,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2193
2193
|
${u}
|
|
2194
2194
|
</div>
|
|
2195
2195
|
</div>
|
|
2196
|
-
`,
|
|
2196
|
+
`,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()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function Xn(r,e,s){const t=r,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?Yn(i):null,a=document.createElement("div");return a.id=J,a.innerHTML=`
|
|
2197
2197
|
<div class="__crossx-card __crossx-card--migration" style="${ae(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2198
2198
|
<div class="__crossx-header">
|
|
2199
2199
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2213,15 +2213,15 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2213
2213
|
</div>
|
|
2214
2214
|
</div>
|
|
2215
2215
|
</div>
|
|
2216
|
-
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const
|
|
2216
|
+
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const f=setInterval(()=>{Date.now()>=i&&(clearInterval(f),l())},1e3);return()=>clearInterval(f)}}}function Jn(r){const s=[r.check1,r.check2].map((t,n)=>`
|
|
2217
2217
|
<div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
|
|
2218
2218
|
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${ei}</div>
|
|
2219
|
-
<span class="__crossx-pw-notice-item-text">${
|
|
2219
|
+
<span class="__crossx-pw-notice-item-text">${N(t)}</span>
|
|
2220
2220
|
</div>
|
|
2221
2221
|
`).join("");return`
|
|
2222
2222
|
<div class="__crossx-header">
|
|
2223
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2224
|
-
<p class="__crossx-pw-subtitle">${
|
|
2223
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${N(r.title)}</p>
|
|
2224
|
+
<p class="__crossx-pw-subtitle">${N(r.headerSubtitle)}</p>
|
|
2225
2225
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
|
|
2226
2226
|
</div>
|
|
2227
2227
|
<hr class="__crossx-divider">
|
|
@@ -2230,27 +2230,27 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2230
2230
|
<div class="__crossx-pw-notice-header">
|
|
2231
2231
|
<div class="__crossx-pw-notice-title-row">
|
|
2232
2232
|
<span class="__crossx-pw-notice-icon">${ti}</span>
|
|
2233
|
-
<p class="__crossx-pw-notice-title">${
|
|
2233
|
+
<p class="__crossx-pw-notice-title">${N(r.noticeTitle)}</p>
|
|
2234
2234
|
</div>
|
|
2235
|
-
<p class="__crossx-pw-notice-desc">${
|
|
2235
|
+
<p class="__crossx-pw-notice-desc">${N(r.noticeDesc)}</p>
|
|
2236
2236
|
</div>
|
|
2237
2237
|
<div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
|
|
2238
2238
|
${s}
|
|
2239
2239
|
</div>
|
|
2240
2240
|
</div>
|
|
2241
2241
|
<button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
|
|
2242
|
-
data-next-label="${
|
|
2243
|
-
data-submit-label="${
|
|
2244
|
-
${
|
|
2242
|
+
data-next-label="${N(r.nextButton)}"
|
|
2243
|
+
data-submit-label="${N(r.submitButton)}">
|
|
2244
|
+
${N(r.nextButton)}
|
|
2245
2245
|
</button>
|
|
2246
2246
|
</div>
|
|
2247
2247
|
<div class="__crossx-home-indicator"></div>
|
|
2248
|
-
`}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">${
|
|
2248
|
+
`}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">${N(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${N(r.subtitle)}</p>`:"",i=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${N(r.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2249
2249
|
${Hs}
|
|
2250
2250
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2251
|
-
</p>`:"",a=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>',
|
|
2251
|
+
</p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${N(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},(f,x)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${x+1}"${e?" disabled":""}>`).join("");return`
|
|
2252
2252
|
<div class="__crossx-header">
|
|
2253
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2253
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${N(r.title)}</p>
|
|
2254
2254
|
${t}
|
|
2255
2255
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
|
|
2256
2256
|
</div>
|
|
@@ -2258,10 +2258,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2258
2258
|
<div class="__crossx-pin6-body"${s}>
|
|
2259
2259
|
${n}
|
|
2260
2260
|
<div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
|
|
2261
|
-
${
|
|
2261
|
+
${u}
|
|
2262
2262
|
</div>
|
|
2263
2263
|
${i}
|
|
2264
2264
|
${a}
|
|
2265
|
+
${c}
|
|
2265
2266
|
${o}
|
|
2266
2267
|
</div>
|
|
2267
2268
|
<div class="__crossx-home-indicator"></div>
|
|
@@ -2269,10 +2270,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2269
2270
|
<div class="__crossx-card __crossx-card--pin6" style="${ae(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2270
2271
|
${e}
|
|
2271
2272
|
</div>
|
|
2272
|
-
`,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((i,o)=>o===0||i===(s[o-1]+1)%10),n=s.every((i,o)=>o===0||i===(s[o-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,i){var
|
|
2273
|
+
`,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((i,o)=>o===0||i===(s[o-1]+1)%10),n=s.every((i,o)=>o===0||i===(s[o-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,i,o){var D,w;let a=!!(i&&i>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"),x=()=>r.querySelector("#__crossx-pin6-lock-msg"),_=()=>r.querySelector("#__crossx-pin6-lock-countdown"),y=()=>r.querySelector(".__crossx-pin6-body"),v=()=>l().map(p=>p.value).join(""),S=p=>{a=p,l().forEach(m=>{m.disabled=p,m.classList.toggle("--locked",p)})},A=()=>r.querySelector("#__crossx-pin6-attempt"),T=()=>{const p=f();p&&(p.textContent="")},H=()=>o??"Your account will be locked after further failures.",L=()=>r.querySelector("#__crossx-pin6-warning"),V=p=>{var b;let m=L();if(!m){m=document.createElement("p"),m.className="__crossx-pin6-warning",m.id="__crossx-pin6-warning";const I=f();I?I.insertAdjacentElement("afterend",m):(b=y())==null||b.appendChild(m)}m.textContent=p},F=()=>{const p=L();p&&(p.textContent="")},re=(p,m)=>{var I;let b=A();if(!b){b=document.createElement("p"),b.className="__crossx-pin6-attempt",b.id="__crossx-pin6-attempt";const R=L()??f();R?R.insertAdjacentElement("afterend",b):(I=y())==null||I.appendChild(b)}b.textContent=`${p}/${m}`},U=()=>{const p=A();p&&(p.textContent="")},j=p=>{const m=f();m&&(m.textContent=p);const b=u();b==null||b.classList.add("--shake"),setTimeout(()=>b==null?void 0:b.classList.remove("--shake"),500),l().forEach(I=>{I.value=""}),setTimeout(()=>{var I;return(I=l()[0])==null?void 0:I.focus()},50)},Y=p=>{var O;S(!0),l().forEach(E=>{E.value=""});const m=f();if(m&&(m.textContent="Too many failed attempts. Please wait."),!x()){const E=document.createElement("p");E.className="__crossx-pin6-lock-msg",E.id="__crossx-pin6-lock-msg",E.innerHTML=`${Hs}<span id="__crossx-pin6-lock-countdown"></span>`;const C=f();C?C.insertAdjacentElement("afterend",E):(O=y())==null||O.appendChild(E)}const b=()=>{var M;const E=p-Date.now(),C=_();E<=0?(clearInterval(I),S(!1),(M=x())==null||M.remove(),m&&(m.textContent=""),setTimeout(()=>{var q;return(q=l()[0])==null?void 0:q.focus()},50)):C&&(C.textContent=` ${Qn(E)}`)},I=setInterval(b,1e3);b();const R=new MutationObserver(()=>{document.contains(r)||(clearInterval(I),R.disconnect())});R.observe(document.body,{childList:!0,subtree:!1})},$=async()=>{if(a||c)return;const p=v();if(p.length===6){c=!0,l().forEach(m=>{m.disabled=!0});try{if(n){const m=await n(p);m.ok?e(p):m.lockExpiresAt?(U(),Y(m.lockExpiresAt)):(j(m.error??"Incorrect PIN. Please try again."),m.attemptCount!=null&&m.maxAttempts!=null?(V(H()),re(m.attemptCount,m.maxAttempts)):(F(),U()))}else e(p)}catch(m){t&&t(m)}finally{c=!1,a||l().forEach(m=>{m.disabled=!1})}}};i&&i>Date.now()?Y(i):setTimeout(()=>{var p;return(p=l()[0])==null?void 0:p.focus()},100);const P=()=>{if(a||c)return;const p=l(),m=p.find(b=>!b.value)??p[p.length-1];m==null||m.focus()};(D=u())==null||D.addEventListener("click",p=>{p.target.classList.contains("__crossx-pin6-box")||P()}),(w=y())==null||w.addEventListener("click",p=>{const m=p.target;m.classList.contains("__crossx-pin6-box")||m.closest("button")||P()}),l().forEach((p,m)=>{p.addEventListener("input",()=>{var I;const b=p.value.replace(/\D/g,"").slice(-1);p.value=b,T(),b&&m<5&&((I=l()[m+1])==null||I.focus()),v().length===6&&setTimeout($,80)}),p.addEventListener("keydown",b=>{var I,R;if(b.key==="Backspace"){if(b.preventDefault(),p.value)p.value="";else if(m>0){const O=l()[m-1];O.value="",O.focus()}}else b.key==="ArrowLeft"&&m>0?(b.preventDefault(),(I=l()[m-1])==null||I.focus()):b.key==="ArrowRight"&&m<5?(b.preventDefault(),(R=l()[m+1])==null||R.focus()):b.key==="Escape"&&s()}),p.addEventListener("paste",b=>{var O,E;b.preventDefault();const I=(((O=b.clipboardData)==null?void 0:O.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!I)return;const R=l();I.split("").forEach((C,M)=>{R[M]&&(R[M].value=C)}),(E=R[Math.min(I.length-1,5)])==null||E.focus(),T(),v().length===6&&setTimeout($,80)}),p.addEventListener("focus",()=>p.select())})}const Hs=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2273
2274
|
<path d="M14.5 8.5H14V6.5C14 4.015 11.985 2 9.5 2C7.015 2 5 4.015 5 6.5V8.5H4.5C3.672 8.5 3 9.172 3 10V16.5C3 17.328 3.672 18 4.5 18H14.5C15.328 18 16 17.328 16 16.5V10C16 9.172 15.328 8.5 14.5 8.5ZM10.5 13.415V15C10.5 15.276 10.276 15.5 10 15.5H9C8.724 15.5 8.5 15.276 8.5 15V13.415C8.187 13.196 8 12.847 8 12.5C8 11.672 8.672 11 9.5 11C10.328 11 11 11.672 11 12.5C11 12.847 10.813 13.196 10.5 13.415ZM12.5 8.5H6.5V6.5C6.5 4.843 7.843 3.5 9.5 3.5C11.157 3.5 12.5 4.843 12.5 6.5V8.5Z" fill="currentColor"/>
|
|
2274
2275
|
</svg>`,ei=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2275
2276
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
2276
2277
|
</svg>`,ti=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2277
2278
|
<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"/>
|
|
2278
|
-
</svg>`;function si(r,e,s){var i;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.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)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var p;c.preventDefault();const l=(((p=c.clipboardData)==null?void 0:p.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,f)=>{t[f]&&(t[f].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",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class ri{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 S;le();const i=[...e],o=Gn(i,this.tokens,t),a=qe();de(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},u=y=>{l(),n(y)},p=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const I=y.dataset.walletAddress??"",P=parseInt(y.dataset.walletIndex??"0",10);u({address:I,index:P})})})})();const f=o.querySelector("#__crossx-add-wallet-btn");f&&f.addEventListener("click",async()=>{f.disabled=!0;try{const y=await s();i.push(y);const I=o.querySelector("#__crossx-wallet-list");if(I){const P=document.createElement("button");P.className="__crossx-wallet-item",P.dataset.walletIndex=String(y.index),P.dataset.walletAddress=y.address,P.innerHTML=`<span class="__crossx-wallet-idx">${y.index+1}</span><span class="__crossx-wallet-addr">${re(y.address)}</span>`,P.addEventListener("click",()=>u(y)),I.appendChild(P),P.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{f.disabled=!1}}),(S=o.querySelector("#__crossx-close-btn"))==null||S.addEventListener("click",p),o.addEventListener("click",y=>{y.target===o&&p()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),p())};document.addEventListener("keydown",w)})}showLoginSelector(e){return new Promise(s=>{var c,l,u,p;le();const t=Kn(this.tokens,e==null?void 0:e.showConnectOtherWallets);de(t);const n=()=>t.remove(),i=_=>{n(),s(_)},o=()=>{n(),s(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>i("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>i("google")),(u=t.querySelector("#__crossx-connect-btn"))==null||u.addEventListener("click",()=>i("external")),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",o),t.addEventListener("click",_=>{_.target===t&&o()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(_=>{_.addEventListener("click",f=>f.stopPropagation())});const a=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",a),o())};document.addEventListener("keydown",a)})}showSessionAlert(e){return new Promise(s=>{var u,p,_;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"}),i=qe();de(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.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 i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),s){const u=()=>{i(),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 p=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)}})}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"},i={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."},o={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=is(this.tokens,Jn(n)),c=qe();de(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},p=P=>{u(),s(P)},_=()=>{u(),s(null)},f=a.querySelector(".__crossx-card"),w={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."},S=P=>{var H;f.innerHTML=dt({title:o.title,headerSubtitle:o.headerSubtitle}),(H=f.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",_),ut(f,D=>{D===P?p(P):y(i.mismatchError)},_)},y=P=>{var H;f.innerHTML=dt({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:P}),(H=f.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",_),ut(f,D=>{const K=Zn(D,w);K?y(K):S(D)},_)};(()=>{var k;const P=Array.from(f.querySelectorAll(".__crossx-pw-notice-item")),H=f.querySelector("#__crossx-pin-notice-next"),D=new Set;H.removeAttribute("disabled");const K=H.dataset.nextLabel??"Next",G=H.dataset.submitLabel??"I Understand",Z=()=>{const v=D.size===P.length;H.classList.toggle("--disabled",!v),H.textContent=v?G:K},U=(v,E)=>{if(D.has(E))return;const T=v.querySelector(`#__crossx-notice-check-${E}`);D.add(E),T.classList.add("--checked"),v.setAttribute("aria-checked","true"),Z()},z=(v,E)=>{if(!D.has(E))return;const T=v.querySelector(`#__crossx-notice-check-${E}`);D.delete(E),T.classList.remove("--checked"),v.setAttribute("aria-checked","false"),Z()};P.forEach(v=>{const E=parseInt(v.dataset.checkIndex??"0",10);v.addEventListener("click",()=>{D.has(E)?z(v,E):U(v,E)}),v.addEventListener("keydown",T=>{(T.key===" "||T.key==="Enter")&&(T.preventDefault(),D.has(E)?z(v,E):U(v,E))})}),H.addEventListener("click",()=>{if(D.size===P.length){y(e==null?void 0:e.errorMessage);return}const v=P.find(T=>{const g=parseInt(T.dataset.checkIndex??"0",10);return!D.has(g)});if(!v)return;const E=parseInt(v.dataset.checkIndex??"0",10);v.scrollIntoView({behavior:"smooth",block:"nearest"}),v.classList.add("--highlight"),setTimeout(()=>{v.classList.remove("--highlight"),U(v,E)},400)}),(k=f.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",_)})(),a.addEventListener("click",P=>{P.target===a&&_()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var y;le();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(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=is(this.tokens,dt({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),l=qe();de(c);let u=!1;const p=()=>{u||(u=!0,c.remove(),l())},_=I=>{p(),s(I)},f=()=>{p(),s(null)},w=I=>{p(),t(I)},S=c.querySelector(".__crossx-card");(y=S.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",f),ut(S,_,f,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",I=>{I.target===c&&f()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;le();const t=jn(this.tokens,e);de(t);const n=()=>t.remove(),i=c=>{n(),s(c)},o=()=>{n(),s(null)};si(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;le();const{overlay:n,startCountdown:i}=Xn(this.tokens,e,s);de(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(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(),i=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const p=l.dataset.copy;p&&((_=navigator.clipboard)==null||_.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,s){return new Promise(t=>{le();const n=$n(e,this.tokens);de(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,p;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.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=>{o||(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(),i=()=>{n(),s(!0)},o=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",i),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",_=>{var w;_.stopPropagation();const f=p.dataset.copy;f&&((w=navigator.clipboard)==null||w.writeText(f).catch(()=>{}))})}),t.addEventListener("click",p=>{p.target===t&&o()});const a=p=>{p.key==="Escape"&&(document.removeEventListener("keydown",a),o())};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 ni(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},i=t.authMode!=="cookie"&&Ut.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new Ut(r.projectId):new ar,a=new xn,c=new yn,l=new Ie,u=new Fs,p=new gt;let _;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new Sn(o,p)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new Ae(n,o,c,u,p));const f=new Be(n,c),w=new ri(r.theme??"light",r.themeTokens),S=e!=null&&e.wrapConfirmation?e.wrapConfirmation(w):w,y=new Ve(t,n,o,a,c,l,_,u,S,f,p);return typeof window<"u"&&(window.__crossxSDK=y),y}function ii(r){const e=oi(r),s=ai(e),t=JSON.parse(s);li(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 oi(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 ai(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=ci(r);return decodeURIComponent(e)}function ci(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 li(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=os;exports.CROSSxSDK=Ve;exports.ChainId=qs;exports.ErrorCode=h;exports.PinMemoryStore=gt;exports.TokenMemoryStore=Fs;exports.createCROSSxSDK=ni;exports.parseOAuthDeeplink=ii;
|
|
2279
|
+
</svg>`;function si(r,e,s){var i;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.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)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.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((x,_)=>{t[_]&&(t[_].value=x)});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",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class ri{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 v;le();const i=[...e],o=Gn(i,this.tokens,t),a=qe();de(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},u=S=>{l(),n(S)},f=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(S=>{S.addEventListener("click",()=>{const A=S.dataset.walletAddress??"",T=parseInt(S.dataset.walletIndex??"0",10);u({address:A,index:T})})})})();const _=o.querySelector("#__crossx-add-wallet-btn");_&&_.addEventListener("click",async()=>{_.disabled=!0;try{const S=await s();i.push(S);const A=o.querySelector("#__crossx-wallet-list");if(A){const T=document.createElement("button");T.className="__crossx-wallet-item",T.dataset.walletIndex=String(S.index),T.dataset.walletAddress=S.address,T.innerHTML=`<span class="__crossx-wallet-idx">${S.index+1}</span><span class="__crossx-wallet-addr">${se(S.address)}</span>`,T.addEventListener("click",()=>u(S)),A.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{_.disabled=!1}}),(v=o.querySelector("#__crossx-close-btn"))==null||v.addEventListener("click",f),o.addEventListener("click",S=>{S.target===o&&f()});const y=S=>{S.key==="Escape"&&(document.removeEventListener("keydown",y),f())};document.addEventListener("keydown",y)})}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(),i=x=>{n(),s(x)},o=()=>{n(),s(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>i("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>i("google")),(u=t.querySelector("#__crossx-connect-btn"))==null||u.addEventListener("click",()=>i("external")),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",o),t.addEventListener("click",x=>{x.target===t&&o()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(x=>{x.addEventListener("click",_=>_.stopPropagation())});const a=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",a),o())};document.addEventListener("keydown",a)})}showSessionAlert(e){return new Promise(s=>{var u,f,x;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"}),i=qe();de(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},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),(x=n.querySelector("#__crossx-close-btn"))==null||x.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 i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),s){const u=()=>{i(),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",x=>{x.target===n&&u()});const f=x=>{x.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"},i={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."},o={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=is(this.tokens,Jn(n)),c=qe();de(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},f=T=>{u(),s(T)},x=()=>{u(),s(null)},_=a.querySelector(".__crossx-card"),y={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."},v=T=>{var H;_.innerHTML=dt({title:o.title,headerSubtitle:o.headerSubtitle}),(H=_.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",x),ut(_,L=>{L===T?f(T):S(i.mismatchError)},x)},S=T=>{var H;_.innerHTML=dt({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:T}),(H=_.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",x),ut(_,L=>{const V=Zn(L,y);V?S(V):v(L)},x)};(()=>{var Y;const T=Array.from(_.querySelectorAll(".__crossx-pw-notice-item")),H=_.querySelector("#__crossx-pin-notice-next"),L=new Set;H.removeAttribute("disabled");const V=H.dataset.nextLabel??"Next",F=H.dataset.submitLabel??"I Understand",re=()=>{const $=L.size===T.length;H.classList.toggle("--disabled",!$),H.textContent=$?F:V},U=($,P)=>{if(L.has(P))return;const D=$.querySelector(`#__crossx-notice-check-${P}`);L.add(P),D.classList.add("--checked"),$.setAttribute("aria-checked","true"),re()},j=($,P)=>{if(!L.has(P))return;const D=$.querySelector(`#__crossx-notice-check-${P}`);L.delete(P),D.classList.remove("--checked"),$.setAttribute("aria-checked","false"),re()};T.forEach($=>{const P=parseInt($.dataset.checkIndex??"0",10);$.addEventListener("click",()=>{L.has(P)?j($,P):U($,P)}),$.addEventListener("keydown",D=>{(D.key===" "||D.key==="Enter")&&(D.preventDefault(),L.has(P)?j($,P):U($,P))})}),H.addEventListener("click",()=>{if(L.size===T.length){S(e==null?void 0:e.errorMessage);return}const $=T.find(D=>{const w=parseInt(D.dataset.checkIndex??"0",10);return!L.has(w)});if(!$)return;const P=parseInt($.dataset.checkIndex??"0",10);$.scrollIntoView({behavior:"smooth",block:"nearest"}),$.classList.add("--highlight"),setTimeout(()=>{$.classList.remove("--highlight"),U($,P)},400)}),(Y=_.querySelector("#__crossx-close-btn"))==null||Y.addEventListener("click",x)})(),a.addEventListener("click",T=>{T.target===a&&x()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var A;le();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(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=is(this.tokens,dt({title:o,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 x=()=>{f||(f=!0,l.remove(),u())},_=T=>{x(),s(T)},y=()=>{x(),s(null)},v=T=>{x(),t(T)},S=l.querySelector(".__crossx-card");(A=S.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",y),ut(S,_,y,v,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",T=>{T.target===l&&y()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;le();const t=jn(this.tokens,e);de(t);const n=()=>t.remove(),i=c=>{n(),s(c)},o=()=>{n(),s(null)};si(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;le();const{overlay:n,startCountdown:i}=Xn(this.tokens,e,s);de(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(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(),i=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var x;u.stopPropagation();const f=l.dataset.copy;f&&((x=navigator.clipboard)==null||x.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,s){return new Promise(t=>{le();const n=$n(e,this.tokens);de(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),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",x=>{x.target===n&&a()});const l=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{o||(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(),i=()=>{n(),s(!0)},o=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",i),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",x=>{var y;x.stopPropagation();const _=f.dataset.copy;_&&((y=navigator.clipboard)==null||y.writeText(_).catch(()=>{}))})}),t.addEventListener("click",f=>{f.target===t&&o()});const a=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",a),o())};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 ni(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},i=t.authMode!=="cookie"&&Ut.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new Ut(r.projectId):new ar,a=new xn,c=new yn,l=new Ie,u=new Fs,f=new gt;let x;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),x=new Sn(o,f)):(d.log("[CROSSx] Remote Wallet Provider 사용"),x=new Ae(n,o,c,u,f));const _=new Be(n,c),y=new ri(r.theme??"light",r.themeTokens),v=e!=null&&e.wrapConfirmation?e.wrapConfirmation(y):y,S=new Ve(t,n,o,a,c,l,x,u,v,_,f);return typeof window<"u"&&(window.__crossxSDK=S),S}function ii(r){const e=oi(r),s=ai(e),t=JSON.parse(s);li(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 oi(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 ai(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=ci(r);return decodeURIComponent(e)}function ci(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 li(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=g;exports.CROSSxEthereumProvider=os;exports.CROSSxSDK=Ve;exports.ChainId=qs;exports.ErrorCode=h;exports.PinMemoryStore=gt;exports.TokenMemoryStore=Fs;exports.createCROSSxSDK=ni;exports.parseOAuthDeeplink=ii;
|