@nexus-cross/crossx-sdk-core 2.3.3 → 2.3.7-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/wallet/RNBridgeWalletProviderAdapter.d.ts +15 -1
- package/dist/core/config/environments.d.ts +6 -0
- package/dist/core/constants.d.ts +11 -1
- package/dist/core/types/chain.d.ts +2 -2
- package/dist/core/types/connectOtherWallet.d.ts +0 -5
- package/dist/core/types/index.d.ts +1 -1
- package/dist/crossx.global +82 -85
- package/dist/index.cjs +93 -96
- package/dist/index.d.ts +1 -1
- package/dist/index.js +685 -634
- package/dist/sdk/services/PinOrchestrator.d.ts +7 -0
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Te=require("jose"),Rt=require("@noble/curves/secp256k1.js"),Ye=require("@noble/hashes/sha3.js"),Nt=require("@noble/hashes/utils.js");var d=(i=>(i.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",i.AUTH_FAILED="AUTH_FAILED",i.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",i.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",i.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",i.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",i.SESSION_EXPIRED="SESSION_EXPIRED",i.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",i.WALLET_NOT_FOUND="WALLET_NOT_FOUND",i.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",i.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",i.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",i.SIGN_FAILED="SIGN_FAILED",i.SIGN_REJECTED="SIGN_REJECTED",i.TX_FAILED="TX_FAILED",i.TX_REJECTED="TX_REJECTED",i.BROADCAST_FAILED="BROADCAST_FAILED",i.USER_REJECTED="USER_REJECTED",i.TX_INVALID_PARAMS="TX_INVALID_PARAMS",i.NETWORK_ERROR="NETWORK_ERROR",i.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",i.INVALID_CHAIN="INVALID_CHAIN",i.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",i.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",i.NOT_IMPLEMENTED="NOT_IMPLEMENTED",i.SIGNATURE_FAILED="SIGNATURE_FAILED",i.TRANSACTION_FAILED="TRANSACTION_FAILED",i.PREPARE_FAILED="PREPARE_FAILED",i.PREPARE_EXPIRED="PREPARE_EXPIRED",i.PREPARE_MISMATCH="PREPARE_MISMATCH",i.MIGRATION_FAILED="MIGRATION_FAILED",i.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",i.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",i.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",i.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",i.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",i.PROJECT_ID_MISSING="PROJECT_ID_MISSING",i.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",i.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",i.INVALID_APP_TYPE="INVALID_APP_TYPE",i.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",i.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",i.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",i.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",i.PIN_NOT_SET="PIN_NOT_SET",i.PIN_WRONG="PIN_WRONG",i.PIN_INVALID="PIN_INVALID",i.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",i.PIN_CANCELLED="PIN_CANCELLED",i.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",i.PIN_LOCKED="PIN_LOCKED",i.HMAC_REQUIRED="HMAC_REQUIRED",i.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",i.WITHDRAW_FAILED="WITHDRAW_FAILED",i.USER_NOT_FOUND="USER_NOT_FOUND",i.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",i.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",i.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",i.INVALID_CONFIG="INVALID_CONFIG",i.UNKNOWN_ERROR="UNKNOWN_ERROR",i))(d||{});class h extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,h.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Ct=2e3,Xe=6e4,Pt=1e3,Ot=1e4,Lt="0x77359400",Je="0x3B9ACA00",Ze=130,We=6,Qe=18,et=3e4,Dt=5*60*1e3,Mt=30*1e3,ye=100,$t="crossx-sdk-js/2.3.7-beta.1",Ee="ONEwallet";var pe=(i=>(i.MetaMask="io.metamask",i.Binance="com.binance.wallet",i.CROSSx="crossx",i))(pe||{});const Ft={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:Ee},_t=["crossx","io.metamask","com.binance.wallet"];function ht(i){return Ft[i]??i}function Bt(i){return Array.isArray(i.connectOtherWallets)&&i.connectOtherWallets.length>0?[...i.connectOtherWallets]:i.showConnectOtherWallets===!0?[..._t]:[]}const Ae={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:"ONEchain Testnet",nativeCurrency:{symbol:"tONE",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}},Wt=Object.fromEntries(Object.entries(Ae).map(([i,e])=>[i,e.caipId])),Ut=new Map(Object.values(Ae).map(i=>[i.caipId,i]));new Map(Object.values(Ae).map(i=>[i.chainId,i]));const Ht={symbol:"",decimals:18};function Re(i){var e;return((e=Ut.get(i))==null?void 0:e.nativeCurrency)??Ht}class ut{constructor(e,r){this.sdk=e,this.chainId=r,this._listeners=new Map}async request({method:e,params:r=[]}){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(r[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new h(d.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new h(d.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(s=>s(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[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 X=null;function tt(i){X=i}const c={info(...i){if(X){X.log(...i);return}console.log(...i)},log(...i){if(X){X.log(...i);return}},warn(...i){if(X){X.warn(...i);return}},error(...i){if(X){X.error(...i);return}}},Gt={confirm:"확인",cancel:"취소",close:"닫기",signature_requesting:"이(가) 서명을 요청합니다",signature_warning:"서명 후에는 변경하거나 취소할 수 없습니다.",signature_sign_button:"서명",sign_message_title:"서명 요청",sign_typed_data_title:"서명 요청",sign_transaction_title:"서명 요청",send_transaction_title:"트랜잭션 승인",send_tx_permission_text:"이(가) 다음 트랜잭션 승인을 요청합니다.",send_tx_approve_button:"승인",send_tx_confirm_button:"확인",tx_pending:"트랜잭션을 처리하고 있습니다...",tx_success:"트랜잭션 완료",tx_failed:"트랜잭션 실패",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",tx_progress_waiting_title:"확인 대기 중",tx_progress_waiting_text:"트랜잭션 영수증을 기다리는 중...",tx_complete_done_button:"모두 완료",label_to:"받는 주소",label_from:"보내는 주소",label_network:"네트워크",label_value:"금액",label_estimated_fee:"예상 수수료",label_est_tx_fee:"예상 수수료",label_max_priority_fee:"최대 우선 수수료",label_max_gas_fee:"최대 가스 수수료",label_gas_price:"가스 가격",label_gas_limit:"가스 한도",label_transfer:"전송량",label_tx_fee:"수수료",label_tx_hash:"Tx 해시",label_total:"합계",label_including_fees:"(수수료 포함)",label_primary_type:"Primary Type",login_selector_title:"로그인 방법 선택",login_selector_subtitle:"소셜 계정으로 간편하게 로그인하세요",login_selector_google:"Google로 로그인",login_selector_apple:"Apple로 로그인",login_selector_or:"또는",login_selector_terms_template:"계속 진행하면 NEXUS {tos}에 동의하고 {pp}에 동의하게 됩니다.",login_selector_terms_tos:"이용약관",login_selector_terms_pp:"개인정보 처리방침",login_selector_connect_other_wallets:"다른 지갑으로 연결",login_selector_connect_other_wallets_desc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_found_title:"소셜 계정에서 지갑 발견",migration_found_description:`소셜 계정에 연결된 지갑을 발견했습니다.
|
|
2
2
|
4자리 PIN을 입력하여 자산을 복원하세요.`,migration_recover_button:"내 지갑 복구",migration_skip_button:"나중에 하기",recovery_pin_input_title:"내 지갑 복구",recovery_pin_input_placeholder:"지갑 복구를 위해 4자리 PIN을 입력하세요.",recovery_pin_input_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",wallet_selector_title:"연결된 지갑 선택",wallet_selector_description:"이전에 이 게임에서 사용한 지갑을 선택해야 계속 진행할 수 있습니다.",wallet_selector_info_title:"왜 지갑을 선택해야 하나요?",wallet_selector_info_desc:"이전에 연결된 지갑을 확인하면 게임 진행 상황과 자산이 올바르게 동기화됩니다.",wallet_selector_add_button:"지갑 추가",wallet_selector_selected:"선택됨",wallet_selector_add_error_limit_exceeded:"계정 한도에 도달했습니다. 최대 {limit}개의 계정을 사용할 수 있습니다.",wallet_selector_add_error_generic:"새 계정을 추가하지 못했습니다. 다시 시도해 주세요.",wallet_created_title:"지갑이 생성되었습니다!",wallet_created_button:"확인",pin_notice_header_subtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pin_notice_title:"PIN 설정 주의사항",pin_notice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pin_notice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pin_notice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pin_notice_next_button:"확인했습니다",pin_notice_submit_button:"확인했습니다",pin_setup_title:"PIN 만들기",pin_setup_header_subtitle:"이 PIN은 거래 승인에 사용됩니다.",pin_setup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pin_setup_confirm_title:"PIN 확인",pin_setup_confirm_subtitle:"6자리 PIN을 다시 입력하세요.",pin_setup_mismatch_error:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pin_validation_too_short:"6자리 PIN을 입력해 주세요.",pin_validation_numbers_only:"숫자(0-9)만 입력할 수 있습니다.",pin_validation_repeating_digit:"동일한 숫자를 3회 이상 연속으로 사용할 수 없습니다.",pin_validation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pin_validation_alternating_pattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pin_input_title:"PIN 입력",pin_input_subtitle:"거래 승인을 위해 PIN을 입력해 주세요.",pin_input_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verify_pin_title:"PIN 확인",verify_pin_subtitle:"계속하려면 PIN을 확인해 주세요.",pin_locked_message:"잠금이 해제된 후 다시 시도해 주세요.",pin_locked_available_from:"(%@ 이후 이용 가능)",pin_locked_failure_warning:"추가 실패 시 계정이 잠금됩니다.",pin_locked_permanent:"계정이 영구 잠금되었습니다. 고객센터에 문의해 주세요.",alert_session_expired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_account_withdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_wallet_not_found:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_different_account:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
|
|
3
3
|
|
|
4
|
-
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},
|
|
4
|
+
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},xt={confirm:"Confirm",cancel:"Cancel",close:"Close",signature_requesting:" is requesting a Signature",signature_warning:"After you sign, changes or cancellations are not possible.",signature_sign_button:"Sign",sign_message_title:"Sign Message",sign_typed_data_title:"Sign Data",sign_transaction_title:"Sign Transaction",send_transaction_title:"Send Transaction",send_tx_permission_text:" wants your permission to approve the following transaction.",send_tx_approve_button:"Approve",send_tx_confirm_button:"Confirm",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",tx_progress_waiting_title:"Waiting for confirmation",tx_progress_waiting_text:"Waiting for transaction receipt...",tx_complete_done_button:"All Done",label_to:"To",label_from:"From",label_network:"Network",label_value:"Value",label_estimated_fee:"Estimated fee",label_est_tx_fee:"Est. Tx Fee",label_max_priority_fee:"Max Priority Fee",label_max_gas_fee:"Max Gas Fee",label_gas_price:"Gas Price",label_gas_limit:"Gas Limit",label_transfer:"Transfer",label_tx_fee:"Tx Fee",label_tx_hash:"Tx Hash",label_total:"Total",label_including_fees:"(including fees)",label_primary_type:"Primary Type",login_selector_title:Ee,login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Connected Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",wallet_created_title:"Wallet Created!",wallet_created_button:"Got it",pin_notice_header_subtitle:"Required for transactions, PK/mnemonic export & account deletion.",pin_notice_title:"PIN Setup Notice",pin_notice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pin_notice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pin_notice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pin_notice_next_button:"I Understand",pin_notice_submit_button:"I Understand",pin_setup_title:"Create PIN",pin_setup_header_subtitle:"This PIN is used to authorize your transactions.",pin_setup_subtitle:"Set a 6-digit PIN to authorize transactions.",pin_setup_confirm_title:"Confirm PIN",pin_setup_confirm_subtitle:"Confirm your 6-digit PIN",pin_setup_mismatch_error:"PINs do not match. Please try again.",pin_validation_too_short:"Please enter a 6-digit PIN.",pin_validation_numbers_only:"Only numbers (0-9) are allowed.",pin_validation_repeating_digit:"Cannot use the same number 3+ times in a row.",pin_validation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pin_validation_alternating_pattern:"Repeating patterns (e.g., 121212) are not allowed.",pin_input_title:"Enter PIN",pin_input_subtitle:"Enter your 6-digit PIN to continue.",pin_input_error:"Incorrect PIN. Please try again.",verify_pin_title:"Verify Your PIN",verify_pin_subtitle:"To continue, please confirm your PIN.",pin_locked_message:"Please try again after the lock expires.",pin_locked_available_from:"Available from",pin_locked_failure_warning:"Your account will be locked after further failures.",pin_locked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_session_expired:"Your session has expired. Please sign in again.",alert_account_withdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_wallet_not_found:"Wallet data could not be found. Please sign in again.",alert_different_account:`You signed in with a different Google/Apple account than before.
|
|
5
5
|
|
|
6
|
-
For security, you must continue with the same account.`,session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},Nt={ko:Pt,en:dt};function J(i="en",e){return Nt[i]??dt}function Ot(i){return i==="ko"||i==="en"?i:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const ze="crossx_access_token",Ve="crossx_refresh_token",je="crossx_user_info",ve=class ve{constructor(e,r,t,s,o,n,a,l,p=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=s,this.transport=o,this.walletProvider=n,this.tokenStore=a,this.requestFreshTokenFromBridge=l,this.getLocale=p,this._refreshPromise=null,this._migrated=!1;const h=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${h}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${h}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${h}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${h}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new _(d.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const s=e==null?void 0:e.provider;let o="/login";s==="google"?o="/google":s==="apple"&&(o="/apple");const{oauthServiceUrl:n}=this.config,a=Ot(this.getLocale()),l=`${n}${o}`,p=l.includes("?")?"&":"?",h=`${l}${p}locale=${a}`;c.log(`[CROSSx] OAuth 팝업 열기 (${s||"일반"} 로그인)`),c.log(`[CROSSx] Auth URL: ${h}`);const u=await this.oauth.openAuth({authUrl:h,expectedOrigin:new URL(n).origin});r=u.token,t=u.email,c.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&c.log("[CROSSx] OAuth 콜백 email:",t)}catch(s){c.error("[CROSSx] SignIn 에러 (OAuth 단계):",s);const o=s instanceof Error?s.message:"Sign in failed";throw/팝업|popup/i.test(o)?new _(d.OAUTH_POPUP_BLOCKED,o):new _(d.AUTH_FAILED,o)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return c.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return c.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,s,o;let r;try{const{authApiUrl:n}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,n);let l,p;try{const h=this.crypto.decodeJWT(e.idToken);p=e.provider??((t=h.firebase)==null?void 0:t.sign_in_provider);const u=((s=h.firebase)==null?void 0:s.identities)??{};l=h.email??((o=u.email)==null?void 0:o[0]),c.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",p,"email:",l??"(없음)")}catch{c.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const h=await this.crypto.verifyJWT(a);if(!h.valid)throw new _(d.AUTH_FAILED,"Access token 검증 실패");const u=h.payload;r={id:u.sub,email:u.email??l,signInProvider:p,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),c.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),c.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new _(d.AUTH_FAILED,"Access token 교환 실패")}catch(n){const a=n instanceof Error?n.message:String(n),l=n instanceof Error?n.stack:void 0,p=n instanceof Error?n.name:"UnknownError";return c.error("[CROSSx] RN Bridge 로그인 실패 — name:",p,"message:",a,"stack:",l),{success:!1,error:a||"RN Bridge login failed"}}return c.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var o,n,a,l,p;let t,s=!1;try{const{authApiUrl:h}=this.config,{accessToken:u,refreshToken:g}=await this.exchangeFirebaseToken(e,h);let x,f,m;try{const v=this.crypto.decodeJWT(e);c.log("[CROSSx] Firebase JWT 필드:",Object.keys(v).join(", ")),f=(o=v.firebase)==null?void 0:o.sign_in_provider;const E=((n=v.firebase)==null?void 0:n.identities)??{};m=v.email??((a=E.email)==null?void 0:a[0]),f==="google.com"?x=(l=E["google.com"])==null?void 0:l[0]:f==="apple.com"&&(x=(p=E["apple.com"])==null?void 0:p[0]),c.log("[CROSSx] OAuth provider sub 추출 — provider:",f,"hasProviderSub:",!!x,"email:",m??"(없음)")}catch{c.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(u){const v=this.crypto.decodeJWT(u);c.log("[CROSSx] access_token 디코딩 — sub:",v.sub,"exp:",v.exp,"필드:",Object.keys(v).join(", "));const E=await this.crypto.verifyJWT(u);if(s=E.signatureVerified??!1,!E.valid)throw c.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const A=E.payload,I=A.email??m??r;c.log("[CROSSx] email 소스 — CROSSx JWT:",A.email??"(없음)","/ Firebase JWT:",m??"(없음)","/ OAuth 콜백:",r??"(없음)","→",I??"(없음)"),t={id:A.sub,email:I,signInProvider:f,providerSub:x},this.tokenStore.set(u),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,u),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&c.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const v=this.crypto.decodeJWT(e);t={id:v.sub,email:v.email??r,signInProvider:f,providerSub:x},c.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}c.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),await this.clearStoredRNBridgeSession(),c.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(h){return c.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",h),{success:!1,error:h instanceof Error?h.message:"Sign in failed"}}return c.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,s)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;c.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let s;try{s=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){c.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const l=a instanceof Error?a.message:String(a);throw new _(d.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${l}`,a)}c.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",s.status);const o=s.data;this.checkResponseError(o,"RN Bridge token exchange");const n=this.extractAccessToken(o);if(!n)throw new _(d.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return c.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:n}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,s=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;c.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:s,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});c.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const n=o.data;this.checkResponseError(n,"Token exchange");const a=this.extractAccessToken(n);if(t&&!a)return c.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(d.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");c.log("[CROSSx] access_token 교환 성공");let l;return t||(l=this.extractRefreshToken(n)),{accessToken:a,refreshToken:l}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,n=o.access_token??o.token;if(typeof n=="string")return n}const s=t.access_token??t.token;if(typeof s=="string")return s}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const o=t.data,n=o.refresh_token??o.refresh;if(typeof n=="string")return n}const s=t.refresh_token??t.refresh;if(typeof s=="string")return s}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 s=await this.storage.get(this.STORAGE_KEY_USER);if(s)return c.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(s,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){c.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),s=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(c.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",s?"있음":"없음"),s){t&&this.tokenStore.set(t);const o=await this.silentRefresh(s);c.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}else{if(!t)return c.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return c.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;c.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(c.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;c.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return c.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof _&&e.code===d.SESSION_EXPIRED;return c.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,s=`${r}/cross-auth/social/refresh/simple`,o={};if(!t){const h=this.tokenStore.get()??"";h&&(o.access_token=h),e&&(o.refresh_token=e)}const n=await this.transport.request({url:s,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});c.log("[CROSSx] silentRefresh 응답 — status:",n.status);const a=n.data,l=this.extractResponseErrorCode(a);if(l){const h=ve.REFRESH_RELOGIN_CODES.has(l.code);throw new _(h?d.SESSION_EXPIRED:d.AUTH_FAILED,`토큰 갱신 실패 (코드 ${l.code}): ${l.message}`)}const p=this.extractAccessToken(a);if(t&&!p){c.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!p)throw new _(d.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(p),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p);const h=this.extractRefreshToken(a);h&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,h)}return c.log("[CROSSx] silentRefresh 성공"),p}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){c.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:s}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return s?(this.tokenStore.set(s),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,s),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),c.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof _&&t.code===d.RN_NATIVE_SESSION_EXPIRED&&(c.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(c.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof _&&e.code===d.SESSION_EXPIRED?(c.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):c.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,s=!1;try{let o=await this.crypto.verifyJWT(e);if(s=o.signatureVerified??!1,!o.valid){if(!r)return c.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};c.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return c.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),s=o.signatureVerified??!1,!o.valid)return c.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};c.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const n=o.payload;c.log("[CROSSx] signInWithJWT — sub:",n.sub,"signatureVerified:",s),t={id:n.sub,email:n.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,t),c.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return c.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,s)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(je);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(ze);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const s=await this.storage.get(Ve);s&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s),await this.storage.remove(je),await this.storage.remove(ze),await this.storage.remove(Ve),c.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){c.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,s=!1;try{if(typeof this.walletProvider.checkWallet=="function"){c.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(c.log("[CROSSx] 지갑 상태:",o),o==="migration_required")c.log("[CROSSx] migration_required → needsMigration = true"),s=!0;else if(o==="exists")try{const n=await this.walletProvider.getAddresses(e.id);n.length>0?(t=n[0].address,c.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):c.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(n){c.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",n)}}else c.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,c.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof _&&o.code===d.MIGRATION_BACKUP_EXISTS)c.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),s=!0;else{if(o instanceof _&&(o.code===d.PROJECT_NOT_REGISTERED||o.code===d.PROJECT_ID_MISSING||o.code===d.ORIGIN_NOT_ALLOWED))throw c.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;c.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return c.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",s),{success:!0,address:t,user:e,needsMigration:s,tokenSignatureVerified:r}}};ve.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Le=ve;class Lt{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const s=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${s}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${s}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${s}_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 Dt{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new _(d.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");c.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return c.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Fe{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const s=new Uint8Array(r.length);for(let o=0;o<r.length;o++)s[o]=r[o]^t[o];r.fill(0),this.xorKey=t,this.encryptedBytes=s}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Mt{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const s=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:s.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new _(d.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class $t{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(s=>s(r))}removeAllListeners(){this.listeners.clear()}}function Ft(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class Y{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return c.log("[RNBridge] Bridge is ready"),!0;await new Promise(s=>setTimeout(s,50))}return c.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await Y.waitForBridgeReady(5e3)||c.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=Y.getBridge(),!this.bridge)throw new _(d.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw c.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new _(d.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,c.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new _(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=Ft(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const s=await this.bridge.handshake(t);if(!s.activated)throw new _(d.AUTH_FAILED,"Bridge handshake rejected by native");const o=typeof s.walletName=="string"?s.walletName.trim():"",n=o.length>0&&o.length<=64?o:void 0,a=s.provider==="google"||s.provider==="apple"?s.provider:void 0;return{isActivated:!0,absoluteTtlMs:s.absoluteTtlMs,idleTtlMs:s.idleTtlMs,protocolVersion:s.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:s.walletAddress,walletName:n,walletProvider:a}}catch(s){throw c.error("[RNBridge] Handshake failed",s),new _(d.AUTH_FAILED,"Bridge handshake failed",s)}}async requestFirebaseIdToken(){if(!this.bridge)throw new _(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),r=(e.expiresAt-Date.now())/1e3;if(r<60)throw new _(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof _)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new _(d.USER_REJECTED,"Firebase ID token request rejected by user",e):(c.error("[RNBridge] Firebase token request failed",e),new _(d.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new _(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new _(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof _?e:(c.error("[RNBridge] Fresh Firebase token request failed",e),new _(d.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new _(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new _(d.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new _(d.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const r=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((r.expiresAt-Date.now())/1e3<60)throw new _(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof _?r:(c.warn("[RNBridge] Session restore Firebase token request failed",r),new _(d.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",r))}}getContext(){return this.context}isActive(){var r;if(!((r=this.context)!=null&&r.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new _(d.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}const _e={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"}};function Bt(i){const e=i.environment;return e&&e in _e?_e[e]:null}function pt(){try{if(typeof __CROSSX_CONFIG__<"u"){const i=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=Bt(i);if(e)return e}}catch{}try{const i=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(i&&i in _e)return _e[i]}catch{}return _e.production}const Wt=2e3,Ye=6e4,Ut=1e3,Ht=1e4,Gt="0x77359400",Xe="0x3B9ACA00",Je=130,Be=6,Ze=18,Qe=3e4,Kt=5*60*1e3,qt=30*1e3,ye=100,zt="crossx-sdk-js/2.3.3";function _t(i){let e=i.length;for(;e>0&&i.charCodeAt(e-1)===48;)e--;return i.slice(0,e)}function Vt(i,e=Be){if(!i||i==="0x0"||i==="0x")return"0";try{const r=BigInt(i);if(r===0n)return"0";const t=10n**BigInt(Ze),s=r/t,n=(r%t).toString().padStart(Ze,"0"),a=_t(n).slice(0,e);return a?`${s}.${a}`:`${s}`}catch{return"?"}}function we(i,e,r,t=Be){if(!(!i||i==="0x"||i==="0x0"))try{const s=BigInt(i);if(s===0n)return;const o=10n**BigInt(r),n=s/o,l=(s%o).toString().padStart(r,"0"),p=_t(l.slice(0,t));return`${p?`${n}.${p}`:`${n}`} ${e}`}catch{return}}function jt(i){const e=i.startsWith("0x")?i.slice(2):i;if(!/^[0-9a-fA-F]+$/.test(e))throw new _(d.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Je)throw new _(d.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Je} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Yt(i){const e=i.startsWith("0x")?i.slice(2):i;if(!/^[0-9a-fA-F]+$/.test(e))throw new _(d.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new _(d.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Xt(i,e){const r=Jt(e);if(i==="0"){if(r!==void 0&&r!==0)throw new _(d.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=i.match(/^eip155:(\d+)$/);if(t){const s=Number(t[1]);if(r===void 0)throw new _(d.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${i})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==s)throw new _(d.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${i}, 예상값: ${s})와 일치하지 않습니다`)}}function Jt(i){if(i==null||typeof i!="object")return;const e=i.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class de{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new _(d.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),c.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new _(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),c.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,s){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){c.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let o,n;this.verifyPinMutex=new Promise((l,p)=>{o=l,n=p});const a=J(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const p=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:s});if(!p)throw new _(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(p),c.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),o();return}const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:s,onSubmit:async p=>{this.deps.pinStore.set(p);try{return await this.deps.walletProvider.verifyPin(p)?(c.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(h){if(this.deps.pinStore.clear(),h instanceof _){if(h.code===d.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(h.code===d.PIN_INVALID)return{ok:!1,error:h.message};if(h.code===d.PIN_LOCKED)return de.buildPinLockedResult(h,a)}throw h}}});if(!l)throw new _(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),c.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),o()}catch(l){if(l instanceof _&&(l.code===d.AUTH_NOT_AUTHENTICATED||l.code===d.AUTH_TOKEN_EXPIRED||l.code===d.SESSION_EXPIRED)&&l.code!==d.SESSION_EXPIRED){const p=J(this.deps.getLocale()??"en"),h=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:h?this.deps.maskEmail(h,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw n(l),l}throw n(l),l}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=J(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(s){if(s instanceof _){if(t=de.parsePinError(s,r),!t)throw s}else throw s}for(;;){c.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(s){if(s instanceof _&&(t=de.parsePinError(s,r),t))continue;throw s}}}static parsePinError(e,r){if(e.code===d.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===d.PIN_INVALID)return{errorMessage:e.message};if(e.code===d.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=de.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:s,...o}=t;return{ok:!1,error:s,...o}}}class Zt{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,s;if((s=(t=this.deps).isRNBridgeMode)!=null&&s.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new _(d.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let o;return this.deps.walletProvider.prepare&&(o=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(o)})}}function Qt(i){return i==="google"||i==="apple"}class er{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const s=Qt(e.loginType)?{provider:e.loginType}:void 0;let o;try{o=await this.deps.executeSignIn(s)}catch(p){throw this.deps.clearAuthState(),p}if(!o.success)return this.deps.clearAuthState(),o;const n=((r=o.user)==null?void 0:r.providerSub)??null,a=((t=o.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!n&&n===e.providerSub:e.userId?!!a&&e.userId===a:!0)){c.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const p=J(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:p.session_alert_title,message:p.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,p.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(o);try{await this.deps.loadWalletAfterAuth()}catch{c.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return c.log("[CROSSx] signInAgain: 세션 복구 성공"),o}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=J(this.deps.getLocale()??"en"),{userEmail:s}=this.deps.getSessionSnapshot(),o=s?this.deps.maskEmail(s,t.session_alert_apple_account):void 0;if(r instanceof _&&r.code===d.WITHDRAW_FAILED){if(c.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:o})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof _&&r.code===d.WALLET_NOT_FOUND){if(c.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:o})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof _)||r.code!==d.SESSION_EXPIRED)throw r;if(c.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:o})==="signout")throw this.deps.clearAuthState(),new _(d.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new _(d.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class tr{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return c.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const s=this.deps.getUserId();if(!s)return;const o=await this.fetchWalletStatus();if(c.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",o),o!=="exists")return;const n=await this.deps.walletProvider.getAddresses(s);if(n.length>0){let l,p=!1;if(r){const u=n.find(g=>g.address.toLowerCase()===r.toLowerCase());u?l=u:(l={address:r,index:0},p=!0)}else e!==void 0?l=n.find(u=>u.index===e)??n[0]:l=n[0];p?c.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",l.address):c.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address);const h=!!r&&!!t&&l.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(l.address,l.index,h?{walletName:t}:void 0);return}c.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(s,0);c.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class rr{constructor(e){this.deps=e}async handleMigrationFlow(e){var l,p;c.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(c.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return c.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let s,o=0,n=5,a=null;for(;;){o++,c.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${n})`,s?`— 이전 메시지: ${s}`:"");const h=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:s,attemptCount:o>1?o-1:void 0,maxAttempts:n});if(h===null)return c.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;c.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),s=void 0;try{const u=await((p=(l=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:p.call(l,h,e));if(!u){c.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=h;break}if(u.valid){c.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=h;break}const g=u.pinStatus;if(n=g.maxAttempts,o=n-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const x=g.lockExpiresAt*1e3,f=Math.max(1,Math.round((x-Date.now())/1e3)),m=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";c.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${f}초, 메시지: ${m}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,m),o=0,s="Your account lock has been lifted. You may try again."}else c.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${n})`),s="Incorrect PIN."}catch(u){if(!(u instanceof _))throw u;if(u.code===d.SESSION_EXPIRED){c.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=J(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:x?this.deps.maskEmail(x,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){c.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),o--;continue}throw this.deps.clearAuthState(),u}if(u.code===d.MIGRATION_PIN_LOCKED){const g=u.details;if(n=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return c.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const x=((g==null?void 0:g.lockExpiresAt)??0)*1e3,f=Math.max(1,Math.round((x-Date.now())/1e3)),m=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";c.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${f}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,m),o=0,s="Your account lock has been lifted. You may try again."}else throw c.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",u),u}}c.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const h=await this.deps.executeMigrate(a,e);return c.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",h.address),h}catch(h){if(h instanceof _&&h.code===d.MIGRATION_FAILED)return c.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(h instanceof _&&h.code===d.SESSION_EXPIRED){c.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const u=J(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:u.session_alert_title,message:u.alert_session_expired,email:g?this.deps.maskEmail(g,u.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){c.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const m=await this.deps.executeMigrate(a,e);return c.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",m.address),m}catch(m){throw c.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",m),m}}throw this.deps.clearAuthState(),h}throw c.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",h),h}}}class sr{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=x=>!(x!=null&&x.trim()),s=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),n=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!s&&!o&&!n&&!a)return e;const l={...e},p=s?l.from??this.deps.getActiveAddress()??void 0:void 0;p&&c.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",p,")"),o&&c.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),n&&c.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[h,u,g]=await Promise.all([p?this.deps.jsonRpcCall("eth_getTransactionCount",[p,"pending"],r):null,o?this.deps.estimateGas(e,r):null,n?this.deps.getBaseFeePerGas(r):null]);if(p&&(l.nonce=parseInt(h??"0x0",16),c.log("[CROSSx] nonce 결과:",l.nonce)),o&&(l.gasLimit=u,c.log("[CROSSx] estimateGas 결과:",l.gasLimit)),n){const x=g;if(x){const f=Xe;l.maxFeePerGas=`0x${(BigInt(x)+BigInt(f)).toString(16)}`,l.maxPriorityFeePerGas=f,c.log("[CROSSx] Dynamic 체인 감지 — baseFee:",x,"maxFeePerGas:",l.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else l.gasPrice=Gt,c.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!n&&a&&(l.maxPriorityFeePerGas=Xe,c.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),l}}class ir{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const s=this.crypto.recoverPersonalSignSigner(e,r);if(s.toLowerCase()!==t.toLowerCase())throw c.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:s}),new _(d.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${s}`);c.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(s){if(s instanceof _)throw s;c.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",s)}}}function or(i){return i?i.includes("google")?"google":i.includes("apple")?"apple":i:null}class nr{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const s={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(s.walletName=t.walletName),this.deps.emitAddressChanged(s),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e){var t,s,o,n,a;const r={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((s=e.user)==null?void 0:s.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:or((n=e.user)==null?void 0:n.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class ar{constructor(e){this.deps=e}async resolveAddress(e){const r=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===r){if(!t)throw new _(d.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class cr{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new _(d.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new _(d.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class lr{constructor(e){this.deps=e}async createWallet(){var s,o;const e=this.deps.getUserId();if(!e)throw new _(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");c.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(c.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const n=this.deps.getProviderSub()??e;c.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",n);const a=await this.deps.migrationOrchestrator.handleMigrationFlow(n);if(a)return this.deps.setActiveWallet(a.address,0),{address:a.address};throw new _(d.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((o=(s=this.deps).showWalletCreated)==null?void 0:o.call(s)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),c.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof _&&r.code===d.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;c.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const s=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(s)return this.deps.setActiveWallet(s.address,0),{address:s.address,migrated:!0};throw new _(d.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function et(i,e){const r=i.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class dr{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new _(d.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new _(d.TX_INVALID_PARAMS,"invalid param tx_hash");const s=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(s))throw new _(d.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new _(d.TX_INVALID_PARAMS,"invalid param body");const o=this.deps.getApiBaseUrl(),n=et(o,`/v2/token-historical/${e}/${s}`),a={clientVersion:t};try{c.log("[TokenHistory] Registering tx:",e,s);const l=await this.deps.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});l.status!==200&&this.handleError(l.status,"register"),c.log("[TokenHistory] Successfully registered:",e,s)}catch(l){throw l instanceof _?l:new _(d.UNKNOWN_ERROR,`Failed to register token history: ${l instanceof Error?l.message:String(l)}`)}}async getTokenHistory(e){var s;const r=this.deps.getApiBaseUrl(),t=new URL(et(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{c.log("[TokenHistory] Fetching token history");const o=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(o.status===404)throw new _(d.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return o.status!==200&&this.handleError(o.status,"fetch"),c.log("[TokenHistory] Successfully fetched history:",((s=o.data.rows)==null?void 0:s.length)??0,"items"),o.data.rows||[]}catch(o){throw o instanceof _?o:new _(d.UNKNOWN_ERROR,`Failed to fetch token history: ${o instanceof Error?o.message:String(o)}`)}}async registerHistoryFireAndForget(e,r,t,s){const o=(s==null?void 0:s.maxRetries)??3,n=(s==null?void 0:s.retryDelayMs)??2e3;for(let a=0;a<o;a++)try{await this.registerTokenHistory(e,r,t);return}catch(l){if(l instanceof _&&l.message.includes("404")&&a<o-1){c.log(`[TokenHistory] Retry ${a+1}/${o} (404 - tx not yet indexed)`),await new Promise(h=>setTimeout(h,n));continue}throw l}}handleError(e,r){const s={400:{code:d.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:d.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:d.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:d.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new _(s.code,s.message)}}function Re(i,e="Apple account"){if(i.endsWith("@privaterelay.appleid.com"))return e;const r=i.indexOf("@");if(r<0)return"*".repeat(i.length||3);const t=i.substring(0,r),s=i.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${s}`:`${t[0]}${"*".repeat(t.length-1)}${s}`}const oe=class oe extends $t{constructor(e,r,t,s,o,n,a,l,p,h,u){var g,x;super(),this.storage=t,this.crypto=s,this.transport=o,this.oauth=n,this.walletProvider=a,this.tokenStore=l,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._bridgeSessionRestorePromise=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&qe(e.logger),this.confirmation=p,this.pinStore=u??new Fe,this.stateManager=new nr({setState:f=>{f.authenticated!==void 0&&(this.authenticated=f.authenticated),f.userId!==void 0&&(this.userId=f.userId),f.address!==void 0&&(this.address=f.address),f.activeWalletIndex!==void 0&&(this.activeWalletIndex=f.activeWalletIndex),f.userEmail!==void 0&&(this.userEmail=f.userEmail),f.providerSub!==void 0&&(this.providerSub=f.providerSub),f.loginType!==void 0&&(this.loginType=f.loginType),f.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=f.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:f,index:m,walletName:y})=>{const v={address:f,index:m};y!==void 0&&(v.walletName=y),this.emit("addressChanged",v)},emitAuthChanged:({isAuthenticated:f,address:m,userId:y})=>{this.emit("authChanged",{isAuthenticated:f,address:m,userId:y})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:oe.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new de({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Re,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Zt({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new tr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(f,m,y)=>this.setActiveWallet(f,m,y)}),this.migrationOrchestrator=new rr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(f,m)=>this.migrateWalletUseCase.execute(f,m),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Re,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var f;return((f=this._config.migration)==null?void 0:f.allowSkip)??!0}}),this.transactionLifecycleService=new sr({getActiveAddress:()=>this.address,estimateGas:(f,m)=>this.estimateGas(f,m),getBaseFeePerGas:f=>this.getBaseFeePerGas(f),jsonRpcCall:(f,m,y)=>this.jsonRpc.call(f,m,y)}),this.signatureVerifier=new ir(this.crypto),this.addressResolverService=new ar({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new cr({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new lr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(f,m)=>this.setActiveWallet(f,m),showWalletCreated:()=>{var f,m;return((m=(f=this.confirmation).showWalletCreatedPrompt)==null?void 0:m.call(f))??Promise.resolve()}}),this.tokenHistoryService=new dr({transport:o,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new er({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:f=>{this._isRecoveringSession=f},setAuthenticated:f=>{this.authenticated=f},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:f=>this.signInUseCase.execute(f),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:f=>this.confirmation.showSessionAlert(f),clearAuthState:()=>this.clearAuthState(),applyAuthResult:f=>this.applyAuthResult(f),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:Re}),this.chainRegistry=h,this.jsonRpc=new Mt(h,o),this.signInUseCase=new Le(this.internalConfig,t,s,n,o,a,l,void 0,()=>this._config.locale),this.signOutUseCase=new Lt(this.internalConfig,t,l),this.migrateWalletUseCase=new Dt(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(x=a.setTokenRefresher)==null||x.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;c.log("[CROSSx SDK] v2.3.3 초기화 중..."),this.confirmation.setMessages(J(this._config.locale));try{const s=pt();this.internalConfig.oauthServiceUrl=s.oauthServiceUrl,this.internalConfig.authApiUrl=s.authApiUrl,this.internalConfig.walletGatewayUrl=s.walletGatewayUrl,this.adapterConfig.gatewayUrl=s.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${s.authApiUrl}/.well-known/jwks.json`);const o=this._config.persistWalletPreference!==!1?await this.storage.get(oe.WALLET_PREF_KEY).catch(()=>null):null,n=(e==null?void 0:e.preferredWalletIndex)??(o==null?void 0:o.index);let a=(e==null?void 0:e.preferredWalletAddress)??(o==null?void 0:o.address),l=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&c.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),l||(l=await this.signInUseCase.restoreSession()),l!=null&&l.success){this.applyAuthResult(l);const p=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),h=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(p)this.address&&this.setActiveWallet(this.address,n??this.activeWalletIndex,h?{walletName:h}:void 0);else try{await this.loadWalletAfterAuth(n,a,h)}catch(u){if(u instanceof _&&u.code===d.PIN_CANCELLED)c.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(u instanceof _&&(u.code===d.SESSION_EXPIRED||u.code===d.AUTH_NOT_AUTHENTICATED||u.code===d.USER_NOT_FOUND))c.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",u.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),l=null;else throw u}}return this.initialized=!0,c.info("[CROSSx SDK] v2.3.3 초기화 완료"),this.emit("initialized",{restored:!!(l!=null&&l.success)}),l??null}catch(s){throw new _(d.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async tryRNBridgeBootstrap(){if(!Y.isAvailable())return null;try{c.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),c.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.3",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new Y({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.3",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),c.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,c.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const s=await this._tryBridgeSessionRestore();if(s!=null&&s.success)return s}return c.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return c.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),c.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();c.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),c.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof _&&r.code===d.USER_REJECTED?(c.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):(c.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession()||(this._isAuthenticatedViaRNBridge=!0,await this.signInUseCase.hasValidStoredAccessToken()))return null;c.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,c.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(c.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return c.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new _(d.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw c.error("[CROSSx] Bridge session restore token request failed:",e),new _(d.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return Y.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new _(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&c.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const s=await this._tryBridgeSignIn();if(s===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(s!=null&&s.success)return s}let t=e;if(!(e!=null&&e.provider)){const s=await this.confirmation.showLoginSelector({connectOtherWallets:kt(this._config)});if(s===null)return{success:!1,error:"User cancelled login"};if(s.type==="external")throw this.emit("connectExternalWallet",{walletId:s.walletId}),new _(d.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:s.provider}}try{const s=await this.signInUseCase.execute(t);return s.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(s)),s}catch(s){throw s instanceof _?s:new _(d.AUTH_FAILED,"로그인에 실패했습니다",s)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},s=await this.signIn(t);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:a}=await this.createWallet(),l=await this.getAddresses(),p=await this.selectWalletIfMultiple(l,r);return{...s,address:(p==null?void 0:p.address)??a,needsMigration:!1,addresses:l}}const o=await this.getAddresses(),n=await this.selectWalletIfMultiple(o,r);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:o}}catch(o){throw o instanceof _&&o.code===d.PIN_CANCELLED&&(c.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>c.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),o}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new _(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r))}catch(t){throw t instanceof _?t:new _(d.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",t)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:o}=await this.createWallet(),n=await this.getAddresses(),a=await this.selectWalletIfMultiple(n);return{...r,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:n}}const t=await this.getAddresses(),s=await this.selectWalletIfMultiple(t);return{...r,address:(s==null?void 0:s.address)??r.address,addresses:t}}catch(t){throw t instanceof _&&t.code===d.PIN_CANCELLED&&(c.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(s=>c.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",s))),t}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new _(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof _?t:new _(d.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=Y.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),c.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){c.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new _(d.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(t){t instanceof _&&t.code===d.PIN_CANCELLED||c.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof _&&t.code===d.PIN_CANCELLED||c.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),c.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof _?r:new _(d.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(d.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 _(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const s=r.length,n={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,s)))).address,index:s};return r.push(n),n},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(s=>s.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(d.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof _?r:new _(d.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=s=>{const o=s?"dark":"light";this.applyTheme(o,this._config.themeTokens??{})};r(e.matches);const t=s=>r(s.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(J(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const s=Y.getBridge();if(s!=null&&s.signMessage){const n=await s.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:n.signature,message:r,address:this.address??""}}if(this.ensureAuthenticated(),!this.userId)throw new _(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const o=await this.resolveAddress(t==null?void 0:t.index);try{const n=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:o.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:o.address},execute:a=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,o.address)});return this.signatureVerifier.verifySignatureSigner(r,n.signature,o.address),{chainId:e,signature:n.signature,message:r,address:o.address}}catch(n){throw n instanceof _?n:new _(d.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,n)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new _(d.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Xt(e,r);const s=await this.resolveAddress(t==null?void 0:t.index);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:s.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:s.address},execute:n=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,n,s.address)});return jt(o.signature),{chainId:e,signature:o.signature,address:s.address}}catch(o){throw o instanceof _?o:new _(d.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,r){return this.signTypedData(oe.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);s.from||(s.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=Te(e);try{const n=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:s.from,to:s.to,value:s.value,data:s.data,gasLimit:s.gasLimit,gasPrice:s.gasPrice,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:s},execute:a=>this.walletProvider.signTransaction(this.userId,e,s,t==null?void 0:t.index,a)});return Yt(n.signature),{chainId:e,signedTx:n.signature,txHash:n.txHash??""}}catch(n){if(n instanceof _)throw n;const a=n instanceof Error?n.message:String(n);throw new _(d.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,n)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);s.from||(s.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=Te(e);try{const n=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:s.from,to:s.to,value:s.value,data:s.data,gasLimit:s.gasLimit,gasPrice:s.gasPrice,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:s},execute:async h=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,s,h)).txHash;const u=await this.walletProvider.signTransaction(this.userId,e,s,t==null?void 0:t.index,h);return u.txHash??u.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),l=a===""||a==="00000000",p=a.startsWith("a9059cbb");return(l||p)&&this.tokenHistoryService.registerHistoryFireAndForget(e,n,zt).catch(h=>c.log("[TokenHistory] register failed (non-critical):",h)),{chainId:e,txHash:n,status:"pending"}}catch(n){if(n instanceof _)throw n;const a=n instanceof Error?n.message:String(n);throw new _(d.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,n)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const s=t.intervalMs??Ut,o=Ht,n=t.timeoutMs??Ye,a=Date.now()+n;let l=s;for(;Date.now()<a;){const p=await this.getTransactionReceipt(e,r);if(p)return p;await new Promise(h=>setTimeout(h,l)),l=Math.min(l*2,o)}throw new _(d.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var m,y;if(this._isAuthenticatedViaRNBridge){const v=Y.getBridge();if(v!=null&&v.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(v,e,r,t)}const{intervalMs:s,timeoutMs:o,...n}=t,{txHash:a}=await this.sendTransaction(e,r,n),l=s??((m=this._config.receiptPolling)==null?void 0:m.intervalMs)??Wt,p=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??Ye,h=Te(e),u=r.from??"";let g,x;const f=this.waitForTxAndGetReceipt(a,e,{intervalMs:l,timeoutMs:p}).then(v=>{g=v;const E=BigInt(v.gasUsed)*BigInt(v.effectiveGasPrice),A=r.value?BigInt(r.value):0n,I=we(r.value,h.symbol,h.decimals,this._config.displayDecimals),T=we("0x"+E.toString(16),h.symbol,h.decimals,this._config.displayDecimals),C=we("0x"+(A+E).toString(16),h.symbol,h.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:v.from,to:v.to??r.to,amount:I,fees:T,total:C,nativeSymbol:h.symbol,status:v.status==="0x1"?"success":"reverted"}}).catch(v=>(x=v instanceof Error?v:new Error(String(v)),{chainId:e,txHash:a,from:u,to:r.to,amount:we(r.value,h.symbol,h.decimals,this._config.displayDecimals),nativeSymbol:h.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:u,to:r.to},f),x)throw x;return{chainId:e,txHash:a,receipt:g}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,s){const o=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:s.dappName,accountName:s.accountName,index:s.index,timeoutMs:s.timeoutMs,pollIntervalMs:s.intervalMs});return{chainId:r,txHash:o.txHash,receipt:{transactionHash:o.txHash,blockHash:o.blockHash??"",blockNumber:o.blockNumber??"",from:o.from??t.from??"",to:o.to??null,gasUsed:o.gasUsed??"0x0",effectiveGasPrice:o.effectiveGasPrice??"0x0",status:o.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new _(d.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),c.log("[CROSSx] PIN 변경 완료")}catch(s){throw s instanceof _?s:new _(d.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",s)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(d.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(s){const o=s instanceof Error?s.message:String(s);throw new _(d.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${o}`,s)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(d.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(d.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof _)throw t;const s=t instanceof Error?t.message:String(t);throw new _(d.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${s}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const s=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:s,formatted:Vt(s,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof _)throw t;const s=t instanceof Error?t.message:String(t);throw new _(d.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${s}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new lt(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){c.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(s){if(s instanceof _)throw s;const o=s instanceof Error?s.message:String(s);throw new _(d.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,s)}}setActiveWallet(e,r,t){const s=this.address;this.stateManager.setActiveWallet(e,r,t),s&&e&&s.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=Y.getBridge();if(!(e!=null&&e.onEvent)){c.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){c.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){c.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,s=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(s)){c.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){c.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){c.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const o=typeof t.walletName=="string"?t.walletName.trim():"",n=o.length>0&&o.length<=64?o:void 0;this.address&&this.address.toLowerCase()===s.toLowerCase()||(c.log("[CROSSx] Native walletChanged 수신",{address:s,walletId:t.walletId,source:t.source,walletName:n}),this.setActiveWallet(s,0,{walletName:n}),this._rnBridgeWalletAddress=s,this._rnBridgeWalletName=n)}),c.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(c.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),qe(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};oe.WALLET_PREF_KEY="wallet_preference",oe.OFFCHAIN_CHAIN_ID="0";let be=oe;class pr{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw c.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return c.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw c.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw c.error("Storage clear error:",e),e}}}const Ce="crossx-sdk",_r=1,j="data",te="keys",me="aes-primary",hr=12;class tt{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const s=indexedDB.open(e,_r);s.onupgradeneeded=()=>{const o=s.result;o.objectStoreNames.contains(j)||o.createObjectStore(j),o.objectStoreNames.contains(te)||o.createObjectStore(te)},s.onsuccess=()=>r(s.result),s.onerror=()=>t(s.error)})}idbGet(e,r){return new Promise((t,s)=>{const n=this.db.transaction(e,"readonly").objectStore(e).get(r);n.onsuccess=()=>t(n.result),n.onerror=()=>s(n.error)})}idbPut(e,r,t){return new Promise((s,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>s(),a.onerror=()=>o(a.error)})}idbDelete(e,r){return new Promise((t,s)=>{const n=this.db.transaction(e,"readwrite").objectStore(e).delete(r);n.onsuccess=()=>t(),n.onerror=()=>s(n.error)})}idbClear(e){return new Promise((r,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>r(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(te,me);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(te,me,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Ce)return null;try{const e=await this.openDB(Ce),r=e.transaction([te,j],"readonly"),t=r.objectStore(te).get(me),s=await new Promise((p,h)=>{t.onsuccess=()=>p(t.result),t.onerror=()=>h(t.error)});if(!s)return e.close(),null;const o=r.objectStore(j).getAll(),n=r.objectStore(j).getAllKeys(),[a,l]=await Promise.all([new Promise((p,h)=>{o.onsuccess=()=>p(o.result),o.onerror=()=>h(o.error)}),new Promise((p,h)=>{n.onsuccess=()=>p(n.result),n.onerror=()=>h(n.error)})]);e.close(),await this.idbPut(te,me,s);for(let p=0;p<l.length;p++)await this.idbPut(j,String(l[p]),a[p]);return indexedDB.deleteDatabase(Ce),c.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),s}catch(e){return c.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(hr);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:s}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),s=await this.encrypt(t);await this.idbPut(j,e,s)}catch(t){throw c.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(j,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return c.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(j,e)}catch(r){throw c.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(j)}catch(e){throw c.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const ur=60;class xr{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=ke.createRemoteJWKSet(new URL(e)),c.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){c.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);c.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const s=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+ur<s)return c.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:s,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return c.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:o}=await ke.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return c.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return c.error("[CROSSx] JWT 서명 검증 실패:",o),{payload:t,valid:!1,signatureVerified:!1};c.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return c.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw c.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return ke.decodeJwt(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),s=new TextEncoder().encode(`Ethereum Signed Message:
|
|
7
|
-
${t.length}`),o=new Uint8Array(s.length+t.length);o.set(s,0),o.set(t,s.length);const n=Ke.keccak_256(o),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const l=gr(a),p=l.slice(0,32),h=l.slice(32,64),u=l[64],g=u>=27?u-27:u,m=new Et.secp256k1.Signature(rt(p),rt(h)).addRecoveryBit(g).recoverPublicKey(n).toBytes(!1).slice(1),y=Ke.keccak_256(m);return"0x"+At.bytesToHex(y.slice(12))}}function gr(i){const e=new Uint8Array(i.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(i.substring(r*2,r*2+2),16);return e}function rt(i){let e="0x";for(const r of i)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const fr=3e4,wr=1e3;class mr{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const s=await this._doRequest(e);if(s.status<500||t===r)return s}catch(s){if(t===r)throw s}await new Promise(s=>setTimeout(s,wr*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??fr);try{const s=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let o;const n=await s.text();try{o=n?JSON.parse(n):null}catch{o={_raw:n}}return{status:s.status,data:o,headers:Object.fromEntries(s.headers.entries())}}finally{clearTimeout(t)}}}const yr=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class se{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),s=atob(t);return JSON.parse(s)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),s=>s.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=se.parseJwtPayload(e),s=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(c.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof s,nonceClaimPresent:typeof s=="string"&&s!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){c.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof s!="string"||s===""){c.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:o,keys:Object.keys(t)});return}if(o.includes("appleid.apple.com")){const n=await se.sha256Hex(r);if(c.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:n.length,receivedHashLength:s.length,match:s===n}),s!==n)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(c.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:s.length,match:s===r}),s!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");c.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((r,t)=>{const s=Math.max(e.width??500,500),o=Math.max(e.height??700,700),n=window.screenX+(window.outerWidth-s)/2,a=window.screenY+(window.outerHeight-o)/2,l=se.generateRandom16Hex(),p=se.generateRandom16Hex(),h=e.authUrl.includes("?")?"&":"?",u=`${e.authUrl}${h}state=${l}&nonce=${p}`;c.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:l.length,nonceLength:p.length,authUrlBase:e.authUrl});const g=window.open(u,"CROSSx OAuth",`width=${s},height=${o},left=${n},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const x=setTimeout(()=>{c.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),I(),t(new Error("Authentication timeout"))},5*60*1e3),f=10,m=30;let y=0,v=null;const E=()=>{clearInterval(A),c.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+m+"초간 대기합니다"),v=setTimeout(()=>{I(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},m*1e3)},A=setInterval(()=>{y++;try{if(!g.closed)return;const C=typeof document<"u"&&document.hasFocus();y<=f&&!C?E():(I(),t(new Error("로그인이 취소되었습니다")))}catch{E()}},1e3),I=()=>{clearTimeout(x),clearInterval(A),v&&clearTimeout(v),window.removeEventListener("message",T)},T=C=>{if(C.origin!==e.expectedOrigin)return;if(!yr.has(C.origin)){c.error("[CROSSx] postMessage origin이 허용 목록에 없음:",C.origin),I(),t(new Error("Unauthorized OAuth origin"));return}I();const U=typeof C.data.status=="string",N=U?C.data.data??{}:C.data;c.log("[CROSSx] OAuth postMessage 수신 —",{format:U?"wrapped":"flat",status:U?C.data.status:"(flat)"});const z=(N==null?void 0:N.state)??C.data.state;if(!z||z!==l){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(U&&C.data.status!=="success"){c.error("[CROSSx] OAuth 실패:",N==null?void 0:N.error),t(new Error((N==null?void 0:N.error)||"Authentication failed"));return}if(!U&&(N!=null&&N.error)){c.error("[CROSSx] OAuth 실패:",N.error),t(new Error(N.error||"Authentication failed"));return}const q=N==null?void 0:N.idToken,P=N==null?void 0:N.accessToken,L=P??q,W=(N==null?void 0:N.email)||void 0;if(c.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!P,hasIdToken:!!q,hasEmail:!!W}),!L){c.error("[CROSSx] 토큰을 찾을 수 없음:",C.data),t(new Error("Token not found in response"));return}const ne={token:L,email:W},ae=ge=>{se.verifyIdTokenNonce(ge,p).then(()=>r(ne)).catch(ce=>{c.error("[CROSSx] nonce 검증 실패:",ce),t(ce instanceof Error?ce:new Error("nonce verification failed"))})};P?P.split(".").length===3?ae(P):q?ae(q):(c.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(ne)):q?ae(q):t(new Error("Token not found in response"))};window.addEventListener("message",T)})}}const ue="crossx_wallet_data",le="crossx_mock_pin_hash";class br{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return c.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(ue)?"exists":"not_found";return c.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(ue);if(t)return t;const s={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ue,s);const o=(r=this.pinStore)==null?void 0:r.get();return o&&(await this.storage.set(le,o),c.log("[Mock] 지갑 생성 — PIN 저장됨")),s}catch(t){throw new _(d.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(ue);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return c.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,r,t,s=0,o,n){return c.log(`[Mock] signMessage chainId=${r} index=${s} uuid=${o} from=${n}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,s=0,o,n){return c.log(`[Mock] signTypedData chainId=${r} index=${s} uuid=${o} from=${n}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,s=0,o){c.log(`[Mock] signTransaction chainId=${r} index=${s} uuid=${o}:`,t);const n="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:n,format:"hex"}}async sendTransaction(e,r,t,s){return c.log(`[Mock] sendTransaction chainId=${r} uuid=${s}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(c.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(le);return r&&r!==e?!1:(r||await this.storage.set(le,e),(t=this.pinStore)==null||t.set(e),c.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var o;if(c.log("[Mock] changePin"),this.pinScenario==="wrong")throw new _(d.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),s=await this.storage.get(le);if(s&&t&&s!==t)throw new _(d.PIN_WRONG,"Incorrect PIN.");await this.storage.set(le,r),c.log("[Mock] changePin 완료")}async migrateWallet(e,r){var o;if(c.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new _(d.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 _(d.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ue,t);const s=(o=this.pinStore)==null?void 0:o.get();return s&&(await this.storage.set(le,s),c.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return c.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return c.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class ie{constructor(e,r,t,s,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=s,this.pinStore=o??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Qe))return e;const r=!e||this.tokenStore.isExpiringSoon(Qe);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const s=this.tokenStore.get();if(s)return s}if(r)throw new _(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return c.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new _(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(c.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,s=!1){var l,p,h,u;const o=await this.ensureValidToken(),n=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const x=(await this.transport.request({url:n,method:e,headers:a,body:t??void 0})).data;if(x&&typeof x.code=="number"){if(x.code<0||x.code>=400){const f=x.message||x.data||"API 요청에 실패했습니다";c.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:x.code,message:f,url:n,method:e});const m=ie.mapGatewayError(x.code,x.data);if(m===d.AUTH_NOT_AUTHENTICATED&&!s&&this._onTokenRefresh){if(c.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new _(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(m===d.USER_NOT_FOUND)throw c.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(l=this._onUnauthorized)==null||l.call(this),new _(d.USER_NOT_FOUND,ie.getGatewayErrorMessage(x.code,f));const y=m===d.AUTH_NOT_AUTHENTICATED?d.SESSION_EXPIRED:m,v=y===d.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":ie.getGatewayErrorMessage(x.code,f),E=x.data;let A;throw m===d.PIN_LOCKED?A=ie.extractLockDetails(E):m===d.ADDRESS_LIMIT_EXCEEDED?A={limit:ye,raw:E}:A=E??void 0,new _(y,v,A)}return c.log("[CROSSx] Wallet Gateway API 성공:",{code:x.code,url:n,method:e}),x.data??x}return x}catch(g){if(g instanceof _)throw g;const x=((p=g.response)==null?void 0:p.status)??g.status;if((x===401||x===403)&&!s&&this._onTokenRefresh){if(c.warn(`[CROSSx] HTTP ${x} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new _(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((h=g.response)!=null&&h.data){const f=g.response.data,m=f.message||f.data||"API 요청에 실패했습니다",y=f.code||"UNKNOWN";throw c.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:y,message:m,url:n,method:e,status:(u=g.response)==null?void 0:u.status}),new _(d.UNKNOWN_ERROR,`Wallet Gateway 오류 (${y}): ${m}`)}throw g}}async checkWallet(){c.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return c.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,c.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(c.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw c.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new _(d.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){c.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return c.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}c.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},s=await this.request("POST","/mnemonic/create",t);return c.log("[CROSSx] /mnemonic/create 완료 — address:",s.address),{id:e,address:s.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new _(d.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new _(d.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new _(d.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const s={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",s);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,r,t,s,o,n){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),n&&(a.from=n);const l=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:l.signature,format:"hex"}}async signTypedData(e,r,t,s,o,n){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),n&&(a.from=n);const l=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:l.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,s,o){const n={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(n.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,n);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,s){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return s&&(o.uuid=s),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,o)).txHash}}async migrateWallet(e,r){c.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},s=await this.request("POST","/mnemonic/migrate",t);return c.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",s.address),{id:r,address:s.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const s=t.passwordStatus;if(s.permanent)throw new _(d.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:s.lockExpiresAt,remainingAttempts:0,maxAttempts:s.maxAttempts});if(s.remainingAttempts===0&&s.lockExpiresAt){const o=s.lockExpiresAt>1e10?s.lockExpiresAt:s.lockExpiresAt*1e3;throw new _(d.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:o,remainingAttempts:0,maxAttempts:s.maxAttempts})}if(s.remainingAttempts!=null&&s.remainingAttempts>0)throw new _(d.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:s.remainingAttempts,maxAttempts:s.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new _(d.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},s=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);s&&(t.lockExpiresAt=s>1e10?s:s*1e3);const o=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof o=="number"&&(t.remainingAttempts=o);const n=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof n=="number"&&(t.maxAttempts=n),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return d.AUTH_NOT_AUTHENTICATED;case-10001:return d.UNKNOWN_ERROR;case-10006:return d.GATEWAY_INTERNAL_ERROR;case-10007:return d.BROADCAST_FAILED;case-10008:return d.GATEWAY_LOCK_CONFLICT;case-10004:return d.WALLET_ALREADY_EXISTS;case-10005:return d.WALLET_NOT_FOUND;case-10011:return d.WALLET_NOT_FOUND;case-10030:return d.WALLET_INCONSISTENT_STATE;case-10010:return d.MIGRATION_FAILED;case-10012:return d.MIGRATION_BACKUP_EXISTS;case-10013:return d.WITHDRAW_FAILED;case-10033:return d.USER_NOT_FOUND;case-10036:return d.ADDRESS_LIMIT_EXCEEDED;case-10027:return d.MIGRATION_PIN_LOCKED;case-10022:return d.PROJECT_NOT_REGISTERED;case-10023:return d.PROJECT_ID_MISSING;case-10024:return d.ORIGIN_NOT_ALLOWED;case-10025:return d.INVALID_APP_TYPE;case-10028:return ie.hasLockInfo(r)?d.PIN_LOCKED:d.PIN_WRONG;case-10029:return d.PIN_INVALID;case-10031:return d.PIN_LOCKED;case-10032:return d.PIN_REPEATED_PATTERN;case-10026:return d.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return d.PREPARE_FAILED;case-10016:return d.PREPARE_EXPIRED;case-10017:case-10018:return d.PREPARE_MISMATCH;case-10020:return d.CHAIN_NOT_SUPPORTED;case-10021:return d.INVALID_CHAIN;case-10040:return d.HMAC_REQUIRED;case-10041:return d.HMAC_VERIFICATION_FAILED;default:return d.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${ye} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class Sr{constructor(e,r,t,s=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=s,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(o,n)=>e.prepare(o,n)),e.migrateWallet&&(this.migrateWallet=(o,n)=>e.migrateWallet(o,n)),e.verifyPin&&(this.verifyPin=o=>e.verifyPin(o)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(o,n)=>e.verifyRecoveryPin(o,n))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,r,t,s,o,n){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();const l=await a.signMessage({chainId:r,message:t,from:n,index:s});return{chainId:r,signature:l.signature,format:"hex"}}return this.inner.signMessage(e,r,t,s,o,n)}async signTypedData(e,r,t,s,o,n){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();const l=await a.signTypedData({chainId:r,typedData:t,from:n,index:s});return{chainId:r,signature:l.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,s,o,n)}async signTransaction(e,r,t,s,o){const n=this.shouldUseBridge();if(n!=null&&n.signTransaction){this.assertBridgeSessionActive();const a=await n.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:s});return{chainId:r,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,r,t,s,o)}async sendTransaction(e,r,t,s){const o=this.shouldUseBridge();if(o!=null&&o.sendTransaction)return this.assertBridgeSessionActive(),{txHash:(await o.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,s)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class xe{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){return this.isCacheValid()?Array.from(this.cache.values()):this._fetchPromise?this._fetchPromise:(this._fetchPromise=this._doFetchChains().finally(()=>{this._fetchPromise=null}),this._fetchPromise)}async _doFetchChains(){try{const e=await this.request("/chains");this.handleEnvelopeError(e);const r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=xe.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(s=>s.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?qt:Kt;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new _(xe.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=xe.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new _(d.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Ee).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return d.CHAIN_NOT_SUPPORTED;case-10021:return d.INVALID_CHAIN;case-10022:return d.PROJECT_NOT_REGISTERED;case-10023:return d.PROJECT_ID_MISSING;case-10024:return d.APP_IDENTIFIER_MISSING;case-10025:return d.INVALID_APP_TYPE;default:return d.UNKNOWN_ERROR}}}const st="__crossx-confirm-style",$="__crossx-confirm-overlay",vr={light:{bg:"#FFFFFF",border:"rgba(0,0,0,0.07)",borderMedium:"rgba(0,0,0,0.18)",titleColor:"#000000",subtitleColor:"rgba(0,0,0,0.65)",labelColor:"rgba(0,0,0,0.65)",valueColor:"#000000",pillBg:"#F5F7FA",pillFromColor:"rgba(0,0,0,0.65)",pillAmtColor:"#000000",divider:"rgba(0,0,0,0.07)",closeColor:"rgba(0,0,0,0.40)",closeHoverBg:"#F5F7FA",copyColor:"rgba(0,0,0,0.65)",inputBg:"#F5F7FA",inputBorder:"rgba(0,0,0,0.07)",hintColor:"rgba(0,0,0,0.45)",surfaceSubtle:"#F5F7FA",surfaceHigh:"#EDF1F2",primary:"#00B4B7",primaryGlow:"rgba(0,180,183,0.18)",secondary:"#D20609",errorColor:"#D20609",noticeBg:"#FFF6F6",noticeBorder:"#DA0B2E",noticeTitleColor:"#D20609",onPrimary:"#FFFFFF"},dark:{bg:"#1E232E",border:"rgba(255,255,255,0.07)",borderMedium:"rgba(255,255,255,0.18)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.65)",labelColor:"rgba(255,255,255,0.65)",valueColor:"#FFFFFF",pillBg:"#252B39",pillFromColor:"rgba(255,255,255,0.65)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.07)",closeColor:"rgba(255,255,255,0.40)",closeHoverBg:"#252B39",copyColor:"rgba(255,255,255,0.65)",inputBg:"#252B39",inputBorder:"rgba(255,255,255,0.07)",hintColor:"rgba(255,255,255,0.45)",surfaceSubtle:"#252B39",surfaceHigh:"#363B4C",primary:"#00CEB2",primaryGlow:"rgba(0,206,178,0.18)",secondary:"#FF0F47",errorColor:"#FF0F47",noticeBg:"#39151E",noticeBorder:"#CD0C40",noticeTitleColor:"#FF0F47",onPrimary:"#000000"}};function it(i,e){const r=vr[i],t=e==null?void 0:e[i];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle,surfaceHigh:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const Er=`
|
|
6
|
+
For security, you must continue with the same account.`,session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},Kt={ko:Gt,en:xt};function J(i="en",e){return Kt[i]??xt}function qt(i){return i==="ko"||i==="en"?i:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const rt="crossx_access_token",st="crossx_refresh_token",it="crossx_user_info",Se=class Se{constructor(e,r,t,s,o,n,a,l,p=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=s,this.transport=o,this.walletProvider=n,this.tokenStore=a,this.requestFreshTokenFromBridge=l,this.getLocale=p,this._refreshPromise=null,this._migrated=!1;const _=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${_}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${_}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${_}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${_}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new h(d.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const s=e==null?void 0:e.provider;let o="/login";s==="google"?o="/google":s==="apple"&&(o="/apple");const{oauthServiceUrl:n}=this.config,a=qt(this.getLocale()),l=`${n}${o}`,p=l.includes("?")?"&":"?",_=`${l}${p}locale=${a}`;c.log(`[CROSSx] OAuth 팝업 열기 (${s||"일반"} 로그인)`),c.log(`[CROSSx] Auth URL: ${_}`);const u=await this.oauth.openAuth({authUrl:_,expectedOrigin:new URL(n).origin});r=u.token,t=u.email,c.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&c.log("[CROSSx] OAuth 콜백 email:",t)}catch(s){c.error("[CROSSx] SignIn 에러 (OAuth 단계):",s);const o=s instanceof Error?s.message:"Sign in failed";throw/팝업|popup/i.test(o)?new h(d.OAUTH_POPUP_BLOCKED,o):new h(d.AUTH_FAILED,o)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return c.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return c.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,s,o;let r;try{const{authApiUrl:n}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,n);let l,p;try{const _=this.crypto.decodeJWT(e.idToken);p=e.provider??((t=_.firebase)==null?void 0:t.sign_in_provider);const u=((s=_.firebase)==null?void 0:s.identities)??{};l=_.email??((o=u.email)==null?void 0:o[0]),c.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",p,"email:",l??"(없음)")}catch{c.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const _=await this.crypto.verifyJWT(a);if(!_.valid)throw new h(d.AUTH_FAILED,"Access token 검증 실패");const u=_.payload;r={id:u.sub,email:u.email??l,signInProvider:p,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),c.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),c.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new h(d.AUTH_FAILED,"Access token 교환 실패")}catch(n){const a=n instanceof Error?n.message:String(n),l=n instanceof Error?n.stack:void 0,p=n instanceof Error?n.name:"UnknownError";return c.error("[CROSSx] RN Bridge 로그인 실패 — name:",p,"message:",a,"stack:",l),{success:!1,error:a||"RN Bridge login failed"}}return c.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var o,n,a,l,p;let t,s=!1;try{const{authApiUrl:_}=this.config,{accessToken:u,refreshToken:x}=await this.exchangeFirebaseToken(e,_);let g,f,m;try{const S=this.crypto.decodeJWT(e);c.log("[CROSSx] Firebase JWT 필드:",Object.keys(S).join(", ")),f=(o=S.firebase)==null?void 0:o.sign_in_provider;const E=((n=S.firebase)==null?void 0:n.identities)??{};m=S.email??((a=E.email)==null?void 0:a[0]),f==="google.com"?g=(l=E["google.com"])==null?void 0:l[0]:f==="apple.com"&&(g=(p=E["apple.com"])==null?void 0:p[0]),c.log("[CROSSx] OAuth provider sub 추출 — provider:",f,"hasProviderSub:",!!g,"email:",m??"(없음)")}catch{c.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(u){const S=this.crypto.decodeJWT(u);c.log("[CROSSx] access_token 디코딩 — sub:",S.sub,"exp:",S.exp,"필드:",Object.keys(S).join(", "));const E=await this.crypto.verifyJWT(u);if(s=E.signatureVerified??!1,!E.valid)throw c.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const A=E.payload,k=A.email??m??r;c.log("[CROSSx] email 소스 — CROSSx JWT:",A.email??"(없음)","/ Firebase JWT:",m??"(없음)","/ OAuth 콜백:",r??"(없음)","→",k??"(없음)"),t={id:A.sub,email:k,signInProvider:f,providerSub:g},this.tokenStore.set(u),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,u),x&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,x):x&&c.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const S=this.crypto.decodeJWT(e);t={id:S.sub,email:S.email??r,signInProvider:f,providerSub:g},c.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}c.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),await this.clearStoredRNBridgeSession(),c.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(_){return c.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",_),{success:!1,error:_ instanceof Error?_.message:"Sign in failed"}}return c.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,s)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;c.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let s;try{s=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){c.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const l=a instanceof Error?a.message:String(a);throw new h(d.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${l}`,a)}c.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",s.status);const o=s.data;this.checkResponseError(o,"RN Bridge token exchange");const n=this.extractAccessToken(o);if(!n)throw new h(d.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return c.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:n}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,s=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;c.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:s,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});c.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const n=o.data;this.checkResponseError(n,"Token exchange");const a=this.extractAccessToken(n);if(t&&!a)return c.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new h(d.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");c.log("[CROSSx] access_token 교환 성공");let l;return t||(l=this.extractRefreshToken(n)),{accessToken:a,refreshToken:l}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,n=o.access_token??o.token;if(typeof n=="string")return n}const s=t.access_token??t.token;if(typeof s=="string")return s}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const o=t.data,n=o.refresh_token??o.refresh;if(typeof n=="string")return n}const s=t.refresh_token??t.refresh;if(typeof s=="string")return s}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 s=await this.storage.get(this.STORAGE_KEY_USER);if(s)return c.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(s,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){c.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),s=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(c.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",s?"있음":"없음"),s){t&&this.tokenStore.set(t);const o=await this.silentRefresh(s);c.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}else{if(!t)return c.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return c.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;c.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(c.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;c.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return c.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof h&&e.code===d.SESSION_EXPIRED;return c.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,s=`${r}/cross-auth/social/refresh/simple`,o={};if(!t){const _=this.tokenStore.get()??"";_&&(o.access_token=_),e&&(o.refresh_token=e)}const n=await this.transport.request({url:s,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});c.log("[CROSSx] silentRefresh 응답 — status:",n.status);const a=n.data,l=this.extractResponseErrorCode(a);if(l){const _=Se.REFRESH_RELOGIN_CODES.has(l.code);throw new h(_?d.SESSION_EXPIRED:d.AUTH_FAILED,`토큰 갱신 실패 (코드 ${l.code}): ${l.message}`)}const p=this.extractAccessToken(a);if(t&&!p){c.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!p)throw new h(d.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(p),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p);const _=this.extractRefreshToken(a);_&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_)}return c.log("[CROSSx] silentRefresh 성공"),p}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){c.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:s}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return s?(this.tokenStore.set(s),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,s),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),c.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof h&&t.code===d.RN_NATIVE_SESSION_EXPIRED&&(c.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(c.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof h&&e.code===d.SESSION_EXPIRED?(c.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):c.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,s=!1;try{let o=await this.crypto.verifyJWT(e);if(s=o.signatureVerified??!1,!o.valid){if(!r)return c.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};c.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return c.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),s=o.signatureVerified??!1,!o.valid)return c.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};c.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const n=o.payload;c.log("[CROSSx] signInWithJWT — sub:",n.sub,"signatureVerified:",s),t={id:n.sub,email:n.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,t),c.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return c.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,s)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(it);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(rt);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const s=await this.storage.get(st);s&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s),await this.storage.remove(it),await this.storage.remove(rt),await this.storage.remove(st),c.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){c.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,s=!1;try{if(typeof this.walletProvider.checkWallet=="function"){c.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(c.log("[CROSSx] 지갑 상태:",o),o==="migration_required")c.log("[CROSSx] migration_required → needsMigration = true"),s=!0;else if(o==="exists")try{const n=await this.walletProvider.getAddresses(e.id);n.length>0?(t=n[0].address,c.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):c.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(n){c.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",n)}}else c.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,c.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof h&&o.code===d.MIGRATION_BACKUP_EXISTS)c.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),s=!0;else{if(o instanceof h&&(o.code===d.PROJECT_NOT_REGISTERED||o.code===d.PROJECT_ID_MISSING||o.code===d.ORIGIN_NOT_ALLOWED))throw c.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;c.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return c.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",s),{success:!0,address:t,user:e,needsMigration:s,tokenSignatureVerified:r}}};Se.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Me=Se;class zt{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const s=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${s}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${s}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${s}_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 Vt{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new h(d.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");c.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return c.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Ue{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const s=new Uint8Array(r.length);for(let o=0;o<r.length;o++)s[o]=r[o]^t[o];r.fill(0),this.xorKey=t,this.encryptedBytes=s}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class jt{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const s=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:s.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new h(d.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Yt{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(s=>s(r))}removeAllListeners(){this.listeners.clear()}}function Xt(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class Y{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return c.log("[RNBridge] Bridge is ready"),!0;await new Promise(s=>setTimeout(s,50))}return c.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await Y.waitForBridgeReady(5e3)||c.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=Y.getBridge(),!this.bridge)throw new h(d.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw c.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new h(d.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,c.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new h(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=Xt(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const s=await this.bridge.handshake(t);if(!s.activated)throw new h(d.AUTH_FAILED,"Bridge handshake rejected by native");const o=typeof s.walletName=="string"?s.walletName.trim():"",n=o.length>0&&o.length<=64?o:void 0,a=s.provider==="google"||s.provider==="apple"?s.provider:void 0;return{isActivated:!0,absoluteTtlMs:s.absoluteTtlMs,idleTtlMs:s.idleTtlMs,protocolVersion:s.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:s.walletAddress,walletName:n,walletProvider:a}}catch(s){throw c.error("[RNBridge] Handshake failed",s),new h(d.AUTH_FAILED,"Bridge handshake failed",s)}}async requestFirebaseIdToken(){if(!this.bridge)throw new h(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),r=(e.expiresAt-Date.now())/1e3;if(r<60)throw new h(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof h)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new h(d.USER_REJECTED,"Firebase ID token request rejected by user",e):(c.error("[RNBridge] Firebase token request failed",e),new h(d.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new h(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new h(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof h?e:(c.error("[RNBridge] Fresh Firebase token request failed",e),new h(d.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new h(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new h(d.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new h(d.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const r=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((r.expiresAt-Date.now())/1e3<60)throw new h(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof h?r:(c.warn("[RNBridge] Session restore Firebase token request failed",r),new h(d.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",r))}}getContext(){return this.context}isActive(){var r;if(!((r=this.context)!=null&&r.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new h(d.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}const _e={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io",contentsBaseUrl:"https://contents.crosstoken.io/frontend/common/app-launcher"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher"}};function Jt(i){const e=i.environment;return e&&e in _e?_e[e]:null}function He(){try{if(typeof __CROSSX_CONFIG__<"u"){const i=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=Jt(i);if(e)return e}}catch{}try{const i=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(i&&i in _e)return _e[i]}catch{}return _e.production}function gt(i){let e=i.length;for(;e>0&&i.charCodeAt(e-1)===48;)e--;return i.slice(0,e)}function Zt(i,e=We){if(!i||i==="0x0"||i==="0x")return"0";try{const r=BigInt(i);if(r===0n)return"0";const t=10n**BigInt(Qe),s=r/t,n=(r%t).toString().padStart(Qe,"0"),a=gt(n).slice(0,e);return a?`${s}.${a}`:`${s}`}catch{return"?"}}function we(i,e,r,t=We){if(!(!i||i==="0x"||i==="0x0"))try{const s=BigInt(i);if(s===0n)return;const o=10n**BigInt(r),n=s/o,l=(s%o).toString().padStart(r,"0"),p=gt(l.slice(0,t));return`${p?`${n}.${p}`:`${n}`} ${e}`}catch{return}}function Qt(i){const e=i.startsWith("0x")?i.slice(2):i;if(!/^[0-9a-fA-F]+$/.test(e))throw new h(d.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Ze)throw new h(d.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Ze} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function er(i){const e=i.startsWith("0x")?i.slice(2):i;if(!/^[0-9a-fA-F]+$/.test(e))throw new h(d.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new h(d.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function tr(i,e){const r=rr(e);if(i==="0"){if(r!==void 0&&r!==0)throw new h(d.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=i.match(/^eip155:(\d+)$/);if(t){const s=Number(t[1]);if(r===void 0)throw new h(d.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${i})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==s)throw new h(d.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${i}, 예상값: ${s})와 일치하지 않습니다`)}}function rr(i){if(i==null||typeof i!="object")return;const e=i.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class de{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new h(d.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),c.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var t,s;if((s=(t=this.deps).isRNBridgeMode)!=null&&s.call(t)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new h(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),c.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,s){var l,p;if((p=(l=this.deps).isRNBridgeMode)!=null&&p.call(l))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){c.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let o,n;this.verifyPinMutex=new Promise((_,u)=>{o=_,n=u});const a=J(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const u=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:s});if(!u)throw new h(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(u),c.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),o();return}const _=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:s,onSubmit:async u=>{this.deps.pinStore.set(u);try{return await this.deps.walletProvider.verifyPin(u)?(c.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(x){if(this.deps.pinStore.clear(),x instanceof h){if(x.code===d.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(x.code===d.PIN_INVALID)return{ok:!1,error:x.message};if(x.code===d.PIN_LOCKED)return de.buildPinLockedResult(x,a)}throw x}}});if(!_)throw new h(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(_),c.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),o()}catch(_){if(_ instanceof h&&(_.code===d.AUTH_NOT_AUTHENTICATED||_.code===d.AUTH_TOKEN_EXPIRED||_.code===d.SESSION_EXPIRED)&&_.code!==d.SESSION_EXPIRED){const u=J(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:u.session_alert_title,message:u.alert_session_expired,email:x?this.deps.maskEmail(x,u.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw n(_),_}throw n(_),_}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=J(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(s){if(s instanceof h){if(t=de.parsePinError(s,r),!t)throw s}else throw s}for(;;){c.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(s){if(s instanceof h&&(t=de.parsePinError(s,r),t))continue;throw s}}}static parsePinError(e,r){if(e.code===d.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===d.PIN_INVALID)return{errorMessage:e.message};if(e.code===d.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=de.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:s,...o}=t;return{ok:!1,error:s,...o}}}class sr{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,s;if((s=(t=this.deps).isRNBridgeMode)!=null&&s.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new h(d.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let o;return this.deps.walletProvider.prepare&&(o=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(o)})}}function ir(i){return i==="google"||i==="apple"}class or{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const s=ir(e.loginType)?{provider:e.loginType}:void 0;let o;try{o=await this.deps.executeSignIn(s)}catch(p){throw this.deps.clearAuthState(),p}if(!o.success)return this.deps.clearAuthState(),o;const n=((r=o.user)==null?void 0:r.providerSub)??null,a=((t=o.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!n&&n===e.providerSub:e.userId?!!a&&e.userId===a:!0)){c.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const p=J(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:p.session_alert_title,message:p.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,p.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(o);try{await this.deps.loadWalletAfterAuth()}catch{c.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return c.log("[CROSSx] signInAgain: 세션 복구 성공"),o}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=J(this.deps.getLocale()??"en"),{userEmail:s}=this.deps.getSessionSnapshot(),o=s?this.deps.maskEmail(s,t.session_alert_apple_account):void 0;if(r instanceof h&&r.code===d.WITHDRAW_FAILED){if(c.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:o})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof h&&r.code===d.WALLET_NOT_FOUND){if(c.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:o})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof h)||r.code!==d.SESSION_EXPIRED)throw r;if(c.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:o})==="signout")throw this.deps.clearAuthState(),new h(d.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new h(d.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class nr{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return c.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const s=this.deps.getUserId();if(!s)return;const o=await this.fetchWalletStatus();if(c.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",o),o!=="exists")return;const n=await this.deps.walletProvider.getAddresses(s);if(n.length>0){let l,p=!1;if(r){const u=n.find(x=>x.address.toLowerCase()===r.toLowerCase());u?l=u:(l={address:r,index:0},p=!0)}else e!==void 0?l=n.find(u=>u.index===e)??n[0]:l=n[0];p?c.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",l.address):c.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address);const _=!!r&&!!t&&l.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(l.address,l.index,_?{walletName:t}:void 0);return}c.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(s,0);c.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class ar{constructor(e){this.deps=e}async handleMigrationFlow(e){var l,p;c.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(c.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return c.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let s,o=0,n=5,a=null;for(;;){o++,c.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${n})`,s?`— 이전 메시지: ${s}`:"");const _=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:s,attemptCount:o>1?o-1:void 0,maxAttempts:n});if(_===null)return c.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;c.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),s=void 0;try{const u=await((p=(l=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:p.call(l,_,e));if(!u){c.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=_;break}if(u.valid){c.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=_;break}const x=u.pinStatus;if(n=x.maxAttempts,o=n-x.remainingAttempts,x.remainingAttempts===0&&x.lockExpiresAt){const g=x.lockExpiresAt*1e3,f=Math.max(1,Math.round((g-Date.now())/1e3)),m=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";c.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${f}초, 메시지: ${m}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,m),o=0,s="Your account lock has been lifted. You may try again."}else c.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${n})`),s="Incorrect PIN."}catch(u){if(!(u instanceof h))throw u;if(u.code===d.SESSION_EXPIRED){c.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const x=J(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:x.session_alert_title,message:x.alert_session_expired,email:g?this.deps.maskEmail(g,x.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){c.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),o--;continue}throw this.deps.clearAuthState(),u}if(u.code===d.MIGRATION_PIN_LOCKED){const x=u.details;if(n=(x==null?void 0:x.maxAttempts)??5,(x==null?void 0:x.permanent)===!0)return c.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const g=((x==null?void 0:x.lockExpiresAt)??0)*1e3,f=Math.max(1,Math.round((g-Date.now())/1e3)),m=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";c.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${f}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,m),o=0,s="Your account lock has been lifted. You may try again."}else throw c.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",u),u}}c.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const _=await this.deps.executeMigrate(a,e);return c.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",_.address),_}catch(_){if(_ instanceof h&&_.code===d.MIGRATION_FAILED)return c.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(_ instanceof h&&_.code===d.SESSION_EXPIRED){c.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const u=J(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:u.session_alert_title,message:u.alert_session_expired,email:x?this.deps.maskEmail(x,u.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){c.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const m=await this.deps.executeMigrate(a,e);return c.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",m.address),m}catch(m){throw c.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",m),m}}throw this.deps.clearAuthState(),_}throw c.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",_),_}}}class cr{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=g=>!(g!=null&&g.trim()),s=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),n=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!s&&!o&&!n&&!a)return e;const l={...e},p=s?l.from??this.deps.getActiveAddress()??void 0:void 0;p&&c.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",p,")"),o&&c.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),n&&c.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[_,u,x]=await Promise.all([p?this.deps.jsonRpcCall("eth_getTransactionCount",[p,"pending"],r):null,o?this.deps.estimateGas(e,r):null,n?this.deps.getBaseFeePerGas(r):null]);if(p&&(l.nonce=parseInt(_??"0x0",16),c.log("[CROSSx] nonce 결과:",l.nonce)),o&&(l.gasLimit=u,c.log("[CROSSx] estimateGas 결과:",l.gasLimit)),n){const g=x;if(g){const f=Je;l.maxFeePerGas=`0x${(BigInt(g)+BigInt(f)).toString(16)}`,l.maxPriorityFeePerGas=f,c.log("[CROSSx] Dynamic 체인 감지 — baseFee:",g,"maxFeePerGas:",l.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else l.gasPrice=Lt,c.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!n&&a&&(l.maxPriorityFeePerGas=Je,c.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),l}}class lr{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const s=this.crypto.recoverPersonalSignSigner(e,r);if(s.toLowerCase()!==t.toLowerCase())throw c.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:s}),new h(d.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${s}`);c.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(s){if(s instanceof h)throw s;c.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",s)}}}function dr(i){return i?i.includes("google")?"google":i.includes("apple")?"apple":i:null}class pr{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const s={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(s.walletName=t.walletName),this.deps.emitAddressChanged(s),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e){var t,s,o,n,a;const r={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((s=e.user)==null?void 0:s.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:dr((n=e.user)==null?void 0:n.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class _r{constructor(e){this.deps=e}async resolveAddress(e){const r=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===r){if(!t)throw new h(d.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class hr{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new h(d.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new h(d.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class ur{constructor(e){this.deps=e}async createWallet(){var s,o;const e=this.deps.getUserId();if(!e)throw new h(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");c.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(c.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const n=this.deps.getProviderSub()??e;c.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",n);const a=await this.deps.migrationOrchestrator.handleMigrationFlow(n);if(a)return this.deps.setActiveWallet(a.address,0),{address:a.address};throw new h(d.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((o=(s=this.deps).showWalletCreated)==null?void 0:o.call(s)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),c.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof h&&r.code===d.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;c.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const s=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(s)return this.deps.setActiveWallet(s.address,0),{address:s.address,migrated:!0};throw new h(d.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function ot(i,e){const r=i.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class xr{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new h(d.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new h(d.TX_INVALID_PARAMS,"invalid param tx_hash");const s=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(s))throw new h(d.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new h(d.TX_INVALID_PARAMS,"invalid param body");const o=this.deps.getApiBaseUrl(),n=ot(o,`/v2/token-historical/${e}/${s}`),a={clientVersion:t};try{c.log("[TokenHistory] Registering tx:",e,s);const l=await this.deps.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});l.status!==200&&this.handleError(l.status,"register"),c.log("[TokenHistory] Successfully registered:",e,s)}catch(l){throw l instanceof h?l:new h(d.UNKNOWN_ERROR,`Failed to register token history: ${l instanceof Error?l.message:String(l)}`)}}async getTokenHistory(e){var s;const r=this.deps.getApiBaseUrl(),t=new URL(ot(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{c.log("[TokenHistory] Fetching token history");const o=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(o.status===404)throw new h(d.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return o.status!==200&&this.handleError(o.status,"fetch"),c.log("[TokenHistory] Successfully fetched history:",((s=o.data.rows)==null?void 0:s.length)??0,"items"),o.data.rows||[]}catch(o){throw o instanceof h?o:new h(d.UNKNOWN_ERROR,`Failed to fetch token history: ${o instanceof Error?o.message:String(o)}`)}}async registerHistoryFireAndForget(e,r,t,s){const o=(s==null?void 0:s.maxRetries)??3,n=(s==null?void 0:s.retryDelayMs)??2e3;for(let a=0;a<o;a++)try{await this.registerTokenHistory(e,r,t);return}catch(l){if(l instanceof h&&l.message.includes("404")&&a<o-1){c.log(`[TokenHistory] Retry ${a+1}/${o} (404 - tx not yet indexed)`),await new Promise(_=>setTimeout(_,n));continue}throw l}}handleError(e,r){const s={400:{code:d.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:d.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:d.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:d.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new h(s.code,s.message)}}function Ne(i,e="Apple account"){if(i.endsWith("@privaterelay.appleid.com"))return e;const r=i.indexOf("@");if(r<0)return"*".repeat(i.length||3);const t=i.substring(0,r),s=i.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${s}`:`${t[0]}${"*".repeat(t.length-1)}${s}`}const oe=class oe extends Yt{constructor(e,r,t,s,o,n,a,l,p,_,u){var x,g;super(),this.storage=t,this.crypto=s,this.transport=o,this.oauth=n,this.walletProvider=a,this.tokenStore=l,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._bridgeSessionRestorePromise=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&tt(e.logger),this.confirmation=p,this.pinStore=u??new Ue,this.stateManager=new pr({setState:f=>{f.authenticated!==void 0&&(this.authenticated=f.authenticated),f.userId!==void 0&&(this.userId=f.userId),f.address!==void 0&&(this.address=f.address),f.activeWalletIndex!==void 0&&(this.activeWalletIndex=f.activeWalletIndex),f.userEmail!==void 0&&(this.userEmail=f.userEmail),f.providerSub!==void 0&&(this.providerSub=f.providerSub),f.loginType!==void 0&&(this.loginType=f.loginType),f.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=f.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:f,index:m,walletName:y})=>{const S={address:f,index:m};y!==void 0&&(S.walletName=y),this.emit("addressChanged",S)},emitAuthChanged:({isAuthenticated:f,address:m,userId:y})=>{this.emit("authChanged",{isAuthenticated:f,address:m,userId:y})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:oe.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new de({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Ne,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.signingOrchestrator=new sr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new nr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(f,m,y)=>this.setActiveWallet(f,m,y)}),this.migrationOrchestrator=new ar({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(f,m)=>this.migrateWalletUseCase.execute(f,m),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Ne,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var f;return((f=this._config.migration)==null?void 0:f.allowSkip)??!0}}),this.transactionLifecycleService=new cr({getActiveAddress:()=>this.address,estimateGas:(f,m)=>this.estimateGas(f,m),getBaseFeePerGas:f=>this.getBaseFeePerGas(f),jsonRpcCall:(f,m,y)=>this.jsonRpc.call(f,m,y)}),this.signatureVerifier=new lr(this.crypto),this.addressResolverService=new _r({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new hr({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new ur({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(f,m)=>this.setActiveWallet(f,m),showWalletCreated:()=>{var f,m;return((m=(f=this.confirmation).showWalletCreatedPrompt)==null?void 0:m.call(f))??Promise.resolve()}}),this.tokenHistoryService=new xr({transport:o,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new or({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:f=>{this._isRecoveringSession=f},setAuthenticated:f=>{this.authenticated=f},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:f=>this.signInUseCase.execute(f),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:f=>this.confirmation.showSessionAlert(f),clearAuthState:()=>this.clearAuthState(),applyAuthResult:f=>this.applyAuthResult(f),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:Ne}),this.chainRegistry=_,this.jsonRpc=new jt(_,o),this.signInUseCase=new Me(this.internalConfig,t,s,n,o,a,l,void 0,()=>this._config.locale),this.signOutUseCase=new zt(this.internalConfig,t,l),this.migrateWalletUseCase=new Vt(t,a),(x=a.setOnUnauthorized)==null||x.call(a,()=>this.forceLogout()),(g=a.setTokenRefresher)==null||g.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;c.log("[CROSSx SDK] v2.3.7-beta.1 초기화 중..."),this.confirmation.setMessages(J(this._config.locale));try{const s=He();this.internalConfig.oauthServiceUrl=s.oauthServiceUrl,this.internalConfig.authApiUrl=s.authApiUrl,this.internalConfig.walletGatewayUrl=s.walletGatewayUrl,this.adapterConfig.gatewayUrl=s.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${s.authApiUrl}/.well-known/jwks.json`);const o=this._config.persistWalletPreference!==!1?await this.storage.get(oe.WALLET_PREF_KEY).catch(()=>null):null,n=(e==null?void 0:e.preferredWalletIndex)??(o==null?void 0:o.index);let a=(e==null?void 0:e.preferredWalletAddress)??(o==null?void 0:o.address),l=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&c.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),l||(l=await this.signInUseCase.restoreSession()),l!=null&&l.success){this.applyAuthResult(l);const p=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),_=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(p)this.address&&this.setActiveWallet(this.address,n??this.activeWalletIndex,_?{walletName:_}:void 0);else try{await this.loadWalletAfterAuth(n,a,_)}catch(u){if(u instanceof h&&u.code===d.PIN_CANCELLED)c.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(u instanceof h&&(u.code===d.SESSION_EXPIRED||u.code===d.AUTH_NOT_AUTHENTICATED||u.code===d.USER_NOT_FOUND))c.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",u.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),l=null;else throw u}}return this.initialized=!0,c.info("[CROSSx SDK] v2.3.7-beta.1 초기화 완료"),this.emit("initialized",{restored:!!(l!=null&&l.success)}),l??null}catch(s){throw new h(d.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async tryRNBridgeBootstrap(){if(!Y.isAvailable())return null;try{c.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),c.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.7-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new Y({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.7-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),c.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,c.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const s=await this._tryBridgeSessionRestore();if(s!=null&&s.success)return s}return c.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return c.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),c.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();c.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),c.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof h&&r.code===d.USER_REJECTED?(c.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):(c.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession()||(this._isAuthenticatedViaRNBridge=!0,await this.signInUseCase.hasValidStoredAccessToken()))return null;c.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,c.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(c.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return c.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new h(d.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw c.error("[CROSSx] Bridge session restore token request failed:",e),new h(d.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return Y.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new h(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&c.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const s=await this._tryBridgeSignIn();if(s===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(s!=null&&s.success)return s}let t=e;if(!(e!=null&&e.provider)){const s=await this.confirmation.showLoginSelector({connectOtherWallets:Bt(this._config)});if(s===null)return{success:!1,error:"User cancelled login"};if(s.type==="external")throw this.emit("connectExternalWallet",{walletId:s.walletId}),new h(d.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:s.provider}}try{const s=await this.signInUseCase.execute(t);return s.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(s)),s}catch(s){throw s instanceof h?s:new h(d.AUTH_FAILED,"로그인에 실패했습니다",s)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},s=await this.signIn(t);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:a}=await this.createWallet(),l=await this.getAddresses(),p=await this.selectWalletIfMultiple(l,r);return{...s,address:(p==null?void 0:p.address)??a,needsMigration:!1,addresses:l}}const o=await this.getAddresses(),n=await this.selectWalletIfMultiple(o,r);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:o}}catch(o){throw o instanceof h&&o.code===d.PIN_CANCELLED&&(c.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>c.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),o}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new h(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r))}catch(t){throw t instanceof h?t:new h(d.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",t)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:o}=await this.createWallet(),n=await this.getAddresses(),a=await this.selectWalletIfMultiple(n);return{...r,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:n}}const t=await this.getAddresses(),s=await this.selectWalletIfMultiple(t);return{...r,address:(s==null?void 0:s.address)??r.address,addresses:t}}catch(t){throw t instanceof h&&t.code===d.PIN_CANCELLED&&(c.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(s=>c.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",s))),t}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new h(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof h?t:new h(d.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=Y.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),c.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){c.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new h(d.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(t){t instanceof h&&t.code===d.PIN_CANCELLED||c.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof h&&t.code===d.PIN_CANCELLED||c.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new h(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),c.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof h?r:new h(d.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new h(d.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 h(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const s=r.length,n={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,s)))).address,index:s};return r.push(n),n},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(s=>s.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof h?e:new h(d.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof h?r:new h(d.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=s=>{const o=s?"dark":"light";this.applyTheme(o,this._config.themeTokens??{})};r(e.matches);const t=s=>r(s.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(J(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const s=Y.getBridge();if(s!=null&&s.signMessage){const n=await s.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:n.signature,message:r,address:this.address??""}}if(this.ensureAuthenticated(),!this.userId)throw new h(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const o=await this.resolveAddress(t==null?void 0:t.index);try{const n=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:o.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:o.address},execute:a=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,o.address)});return this.signatureVerifier.verifySignatureSigner(r,n.signature,o.address),{chainId:e,signature:n.signature,message:r,address:o.address}}catch(n){throw n instanceof h?n:new h(d.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,n)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new h(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new h(d.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");tr(e,r);const s=await this.resolveAddress(t==null?void 0:t.index);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:s.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:s.address},execute:n=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,n,s.address)});return Qt(o.signature),{chainId:e,signature:o.signature,address:s.address}}catch(o){throw o instanceof h?o:new h(d.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,r){return this.signTypedData(oe.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new h(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);s.from||(s.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=Re(e);try{const n=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:s.from,to:s.to,value:s.value,data:s.data,gasLimit:s.gasLimit,gasPrice:s.gasPrice,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:s},execute:a=>this.walletProvider.signTransaction(this.userId,e,s,t==null?void 0:t.index,a)});return er(n.signature),{chainId:e,signedTx:n.signature,txHash:n.txHash??""}}catch(n){if(n instanceof h)throw n;const a=n instanceof Error?n.message:String(n);throw new h(d.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,n)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new h(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);s.from||(s.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=Re(e);try{const n=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:s.from,to:s.to,value:s.value,data:s.data,gasLimit:s.gasLimit,gasPrice:s.gasPrice,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:s},execute:async _=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,s,_)).txHash;const u=await this.walletProvider.signTransaction(this.userId,e,s,t==null?void 0:t.index,_);return u.txHash??u.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),l=a===""||a==="00000000",p=a.startsWith("a9059cbb");return(l||p)&&this.tokenHistoryService.registerHistoryFireAndForget(e,n,$t).catch(_=>c.log("[TokenHistory] register failed (non-critical):",_)),{chainId:e,txHash:n,status:"pending"}}catch(n){if(n instanceof h)throw n;const a=n instanceof Error?n.message:String(n);throw new h(d.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,n)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const s=t.intervalMs??Pt,o=Ot,n=t.timeoutMs??Xe,a=Date.now()+n;let l=s;for(;Date.now()<a;){const p=await this.getTransactionReceipt(e,r);if(p)return p;await new Promise(_=>setTimeout(_,l)),l=Math.min(l*2,o)}throw new h(d.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var m,y;if(this._isAuthenticatedViaRNBridge){const S=Y.getBridge();if(S!=null&&S.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(S,e,r,t)}const{intervalMs:s,timeoutMs:o,...n}=t,{txHash:a}=await this.sendTransaction(e,r,n),l=s??((m=this._config.receiptPolling)==null?void 0:m.intervalMs)??Ct,p=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??Xe,_=Re(e),u=r.from??"";let x,g;const f=this.waitForTxAndGetReceipt(a,e,{intervalMs:l,timeoutMs:p}).then(S=>{x=S;const E=BigInt(S.gasUsed)*BigInt(S.effectiveGasPrice),A=r.value?BigInt(r.value):0n,k=we(r.value,_.symbol,_.decimals,this._config.displayDecimals),T=we("0x"+E.toString(16),_.symbol,_.decimals,this._config.displayDecimals),N=we("0x"+(A+E).toString(16),_.symbol,_.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:S.from,to:S.to??r.to,amount:k,fees:T,total:N,nativeSymbol:_.symbol,status:S.status==="0x1"?"success":"reverted"}}).catch(S=>(g=S instanceof Error?S:new Error(String(S)),{chainId:e,txHash:a,from:u,to:r.to,amount:we(r.value,_.symbol,_.decimals,this._config.displayDecimals),nativeSymbol:_.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:u,to:r.to},f),g)throw g;return{chainId:e,txHash:a,receipt:x}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,s){const o=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:s.dappName??this._config.appName,accountName:s.accountName,index:s.index,timeoutMs:s.timeoutMs,pollIntervalMs:s.intervalMs});return{chainId:r,txHash:o.txHash,receipt:{transactionHash:o.txHash,blockHash:o.blockHash??"",blockNumber:o.blockNumber??"",from:o.from??t.from??"",to:o.to??null,gasUsed:o.gasUsed??"0x0",effectiveGasPrice:o.effectiveGasPrice??"0x0",status:o.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new h(d.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),c.log("[CROSSx] PIN 변경 완료")}catch(s){throw s instanceof h?s:new h(d.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",s)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new h(d.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(s){const o=s instanceof Error?s.message:String(s);throw new h(d.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${o}`,s)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new h(d.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new h(d.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof h)throw t;const s=t instanceof Error?t.message:String(t);throw new h(d.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${s}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const s=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:s,formatted:Zt(s,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof h)throw t;const s=t instanceof Error?t.message:String(t);throw new h(d.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${s}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new ut(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){c.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(s){if(s instanceof h)throw s;const o=s instanceof Error?s.message:String(s);throw new h(d.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,s)}}setActiveWallet(e,r,t){const s=this.address;this.stateManager.setActiveWallet(e,r,t),s&&e&&s.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=Y.getBridge();if(!(e!=null&&e.onEvent)){c.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){c.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){c.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,s=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(s)){c.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){c.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){c.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const o=typeof t.walletName=="string"?t.walletName.trim():"",n=o.length>0&&o.length<=64?o:void 0;this.address&&this.address.toLowerCase()===s.toLowerCase()||(c.log("[CROSSx] Native walletChanged 수신",{address:s,walletId:t.walletId,source:t.source,walletName:n}),this.setActiveWallet(s,0,{walletName:n}),this._rnBridgeWalletAddress=s,this._rnBridgeWalletName=n)}),c.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(c.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),tt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};oe.WALLET_PREF_KEY="wallet_preference",oe.OFFCHAIN_CHAIN_ID="0";let be=oe;class gr{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw c.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return c.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw c.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw c.error("Storage clear error:",e),e}}}const Ce="crossx-sdk",fr=1,j="data",te="keys",me="aes-primary",wr=12;class nt{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const s=indexedDB.open(e,fr);s.onupgradeneeded=()=>{const o=s.result;o.objectStoreNames.contains(j)||o.createObjectStore(j),o.objectStoreNames.contains(te)||o.createObjectStore(te)},s.onsuccess=()=>r(s.result),s.onerror=()=>t(s.error)})}idbGet(e,r){return new Promise((t,s)=>{const n=this.db.transaction(e,"readonly").objectStore(e).get(r);n.onsuccess=()=>t(n.result),n.onerror=()=>s(n.error)})}idbPut(e,r,t){return new Promise((s,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>s(),a.onerror=()=>o(a.error)})}idbDelete(e,r){return new Promise((t,s)=>{const n=this.db.transaction(e,"readwrite").objectStore(e).delete(r);n.onsuccess=()=>t(),n.onerror=()=>s(n.error)})}idbClear(e){return new Promise((r,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>r(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(te,me);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(te,me,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Ce)return null;try{const e=await this.openDB(Ce),r=e.transaction([te,j],"readonly"),t=r.objectStore(te).get(me),s=await new Promise((p,_)=>{t.onsuccess=()=>p(t.result),t.onerror=()=>_(t.error)});if(!s)return e.close(),null;const o=r.objectStore(j).getAll(),n=r.objectStore(j).getAllKeys(),[a,l]=await Promise.all([new Promise((p,_)=>{o.onsuccess=()=>p(o.result),o.onerror=()=>_(o.error)}),new Promise((p,_)=>{n.onsuccess=()=>p(n.result),n.onerror=()=>_(n.error)})]);e.close(),await this.idbPut(te,me,s);for(let p=0;p<l.length;p++)await this.idbPut(j,String(l[p]),a[p]);return indexedDB.deleteDatabase(Ce),c.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),s}catch(e){return c.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(wr);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:s}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),s=await this.encrypt(t);await this.idbPut(j,e,s)}catch(t){throw c.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(j,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return c.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(j,e)}catch(r){throw c.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(j)}catch(e){throw c.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const mr=60;class yr{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Te.createRemoteJWKSet(new URL(e)),c.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){c.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);c.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const s=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+mr<s)return c.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:s,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return c.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:o}=await Te.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return c.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return c.error("[CROSSx] JWT 서명 검증 실패:",o),{payload:t,valid:!1,signatureVerified:!1};c.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return c.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw c.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Te.decodeJwt(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),s=new TextEncoder().encode(`Ethereum Signed Message:
|
|
7
|
+
${t.length}`),o=new Uint8Array(s.length+t.length);o.set(s,0),o.set(t,s.length);const n=Ye.keccak_256(o),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const l=br(a),p=l.slice(0,32),_=l.slice(32,64),u=l[64],x=u>=27?u-27:u,m=new Rt.secp256k1.Signature(at(p),at(_)).addRecoveryBit(x).recoverPublicKey(n).toBytes(!1).slice(1),y=Ye.keccak_256(m);return"0x"+Nt.bytesToHex(y.slice(12))}}function br(i){const e=new Uint8Array(i.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(i.substring(r*2,r*2+2),16);return e}function at(i){let e="0x";for(const r of i)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const vr=3e4,Sr=1e3;class Er{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const s=await this._doRequest(e);if(s.status<500||t===r)return s}catch(s){if(t===r)throw s}await new Promise(s=>setTimeout(s,Sr*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??vr);try{const s=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let o;const n=await s.text();try{o=n?JSON.parse(n):null}catch{o={_raw:n}}return{status:s.status,data:o,headers:Object.fromEntries(s.headers.entries())}}finally{clearTimeout(t)}}}const Ar=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io","https://cross-wallet-oauth.onechain.nexus","https://stg-cross-wallet-oauth.onechain.nexus","https://dev-cross-wallet-oauth.onechain.nexus"]);class se{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),s=atob(t);return JSON.parse(s)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),s=>s.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=se.parseJwtPayload(e),s=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(c.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof s,nonceClaimPresent:typeof s=="string"&&s!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){c.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof s!="string"||s===""){c.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:o,keys:Object.keys(t)});return}if(o.includes("appleid.apple.com")){const n=await se.sha256Hex(r);if(c.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:n.length,receivedHashLength:s.length,match:s===n}),s!==n)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(c.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:s.length,match:s===r}),s!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");c.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((r,t)=>{const s=Math.max(e.width??500,500),o=Math.max(e.height??700,700),n=window.screenX+(window.outerWidth-s)/2,a=window.screenY+(window.outerHeight-o)/2,l=se.generateRandom16Hex(),p=se.generateRandom16Hex(),_=e.authUrl.includes("?")?"&":"?",u=`${e.authUrl}${_}state=${l}&nonce=${p}`;c.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:l.length,nonceLength:p.length,authUrlBase:e.authUrl});const x=window.open(u,"CROSSx OAuth",`width=${s},height=${o},left=${n},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const g=setTimeout(()=>{c.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),k(),t(new Error("Authentication timeout"))},5*60*1e3),f=10,m=30;let y=0,S=null;const E=()=>{clearInterval(A),c.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+m+"초간 대기합니다"),S=setTimeout(()=>{k(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},m*1e3)},A=setInterval(()=>{y++;try{if(!x.closed)return;const N=typeof document<"u"&&document.hasFocus();y<=f&&!N?E():(k(),t(new Error("로그인이 취소되었습니다")))}catch{E()}},1e3),k=()=>{clearTimeout(g),clearInterval(A),S&&clearTimeout(S),window.removeEventListener("message",T)},T=N=>{if(!Ar.has(N.origin))return;k();const U=typeof N.data.status=="string",P=U?N.data.data??{}:N.data;c.log("[CROSSx] OAuth postMessage 수신 —",{format:U?"wrapped":"flat",status:U?N.data.status:"(flat)"});const z=(P==null?void 0:P.state)??N.data.state;if(!z||z!==l){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(U&&N.data.status!=="success"){c.error("[CROSSx] OAuth 실패:",P==null?void 0:P.error),t(new Error((P==null?void 0:P.error)||"Authentication failed"));return}if(!U&&(P!=null&&P.error)){c.error("[CROSSx] OAuth 실패:",P.error),t(new Error(P.error||"Authentication failed"));return}const q=P==null?void 0:P.idToken,C=P==null?void 0:P.accessToken,L=C??q,W=(P==null?void 0:P.email)||void 0;if(c.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!C,hasIdToken:!!q,hasEmail:!!W}),!L){c.error("[CROSSx] 토큰을 찾을 수 없음:",N.data),t(new Error("Token not found in response"));return}const ne={token:L,email:W},ae=ge=>{se.verifyIdTokenNonce(ge,p).then(()=>r(ne)).catch(ce=>{c.error("[CROSSx] nonce 검증 실패:",ce),t(ce instanceof Error?ce:new Error("nonce verification failed"))})};C?C.split(".").length===3?ae(C):q?ae(q):(c.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(ne)):q?ae(q):t(new Error("Token not found in response"))};window.addEventListener("message",T)})}}const ue="crossx_wallet_data",le="crossx_mock_pin_hash";class Ir{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return c.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(ue)?"exists":"not_found";return c.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(ue);if(t)return t;const s={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ue,s);const o=(r=this.pinStore)==null?void 0:r.get();return o&&(await this.storage.set(le,o),c.log("[Mock] 지갑 생성 — PIN 저장됨")),s}catch(t){throw new h(d.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(ue);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return c.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,r,t,s=0,o,n){return c.log(`[Mock] signMessage chainId=${r} index=${s} uuid=${o} from=${n}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,s=0,o,n){return c.log(`[Mock] signTypedData chainId=${r} index=${s} uuid=${o} from=${n}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,s=0,o){c.log(`[Mock] signTransaction chainId=${r} index=${s} uuid=${o}:`,t);const n="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:n,format:"hex"}}async sendTransaction(e,r,t,s){return c.log(`[Mock] sendTransaction chainId=${r} uuid=${s}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(c.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(le);return r&&r!==e?!1:(r||await this.storage.set(le,e),(t=this.pinStore)==null||t.set(e),c.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var o;if(c.log("[Mock] changePin"),this.pinScenario==="wrong")throw new h(d.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),s=await this.storage.get(le);if(s&&t&&s!==t)throw new h(d.PIN_WRONG,"Incorrect PIN.");await this.storage.set(le,r),c.log("[Mock] changePin 완료")}async migrateWallet(e,r){var o;if(c.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new h(d.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 h(d.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ue,t);const s=(o=this.pinStore)==null?void 0:o.get();return s&&(await this.storage.set(le,s),c.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return c.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return c.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class ie{constructor(e,r,t,s,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=s,this.pinStore=o??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(et))return e;const r=!e||this.tokenStore.isExpiringSoon(et);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const s=this.tokenStore.get();if(s)return s}if(r)throw new h(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return c.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new h(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(c.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,s=!1){var l,p,_,u;const o=await this.ensureValidToken(),n=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const g=(await this.transport.request({url:n,method:e,headers:a,body:t??void 0})).data;if(g&&typeof g.code=="number"){if(g.code<0||g.code>=400){const f=g.message||g.data||"API 요청에 실패했습니다";c.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:g.code,message:f,url:n,method:e});const m=ie.mapGatewayError(g.code,g.data);if(m===d.AUTH_NOT_AUTHENTICATED&&!s&&this._onTokenRefresh){if(c.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new h(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(m===d.USER_NOT_FOUND)throw c.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(l=this._onUnauthorized)==null||l.call(this),new h(d.USER_NOT_FOUND,ie.getGatewayErrorMessage(g.code,f));const y=m===d.AUTH_NOT_AUTHENTICATED?d.SESSION_EXPIRED:m,S=y===d.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":ie.getGatewayErrorMessage(g.code,f),E=g.data;let A;throw m===d.PIN_LOCKED?A=ie.extractLockDetails(E):m===d.ADDRESS_LIMIT_EXCEEDED?A={limit:ye,raw:E}:A=E??void 0,new h(y,S,A)}return c.log("[CROSSx] Wallet Gateway API 성공:",{code:g.code,url:n,method:e}),g.data??g}return g}catch(x){if(x instanceof h)throw x;const g=((p=x.response)==null?void 0:p.status)??x.status;if((g===401||g===403)&&!s&&this._onTokenRefresh){if(c.warn(`[CROSSx] HTTP ${g} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new h(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((_=x.response)!=null&&_.data){const f=x.response.data,m=f.message||f.data||"API 요청에 실패했습니다",y=f.code||"UNKNOWN";throw c.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:y,message:m,url:n,method:e,status:(u=x.response)==null?void 0:u.status}),new h(d.UNKNOWN_ERROR,`Wallet Gateway 오류 (${y}): ${m}`)}throw x}}async checkWallet(){c.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return c.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,c.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(c.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw c.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new h(d.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){c.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return c.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}c.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},s=await this.request("POST","/mnemonic/create",t);return c.log("[CROSSx] /mnemonic/create 완료 — address:",s.address),{id:e,address:s.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new h(d.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new h(d.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new h(d.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const s={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",s);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,r,t,s,o,n){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),n&&(a.from=n);const l=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:l.signature,format:"hex"}}async signTypedData(e,r,t,s,o,n){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),n&&(a.from=n);const l=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:l.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,s,o){const n={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(n.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,n);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,s){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return s&&(o.uuid=s),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,o)).txHash}}async migrateWallet(e,r){c.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},s=await this.request("POST","/mnemonic/migrate",t);return c.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",s.address),{id:r,address:s.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const s=t.passwordStatus;if(s.permanent)throw new h(d.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:s.lockExpiresAt,remainingAttempts:0,maxAttempts:s.maxAttempts});if(s.remainingAttempts===0&&s.lockExpiresAt){const o=s.lockExpiresAt>1e10?s.lockExpiresAt:s.lockExpiresAt*1e3;throw new h(d.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:o,remainingAttempts:0,maxAttempts:s.maxAttempts})}if(s.remainingAttempts!=null&&s.remainingAttempts>0)throw new h(d.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:s.remainingAttempts,maxAttempts:s.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new h(d.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},s=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);s&&(t.lockExpiresAt=s>1e10?s:s*1e3);const o=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof o=="number"&&(t.remainingAttempts=o);const n=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof n=="number"&&(t.maxAttempts=n),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return d.AUTH_NOT_AUTHENTICATED;case-10001:return d.UNKNOWN_ERROR;case-10006:return d.GATEWAY_INTERNAL_ERROR;case-10007:return d.BROADCAST_FAILED;case-10008:return d.GATEWAY_LOCK_CONFLICT;case-10004:return d.WALLET_ALREADY_EXISTS;case-10005:return d.WALLET_NOT_FOUND;case-10011:return d.WALLET_NOT_FOUND;case-10030:return d.WALLET_INCONSISTENT_STATE;case-10010:return d.MIGRATION_FAILED;case-10012:return d.MIGRATION_BACKUP_EXISTS;case-10013:return d.WITHDRAW_FAILED;case-10033:return d.USER_NOT_FOUND;case-10036:return d.ADDRESS_LIMIT_EXCEEDED;case-10027:return d.MIGRATION_PIN_LOCKED;case-10022:return d.PROJECT_NOT_REGISTERED;case-10023:return d.PROJECT_ID_MISSING;case-10024:return d.ORIGIN_NOT_ALLOWED;case-10025:return d.INVALID_APP_TYPE;case-10028:return ie.hasLockInfo(r)?d.PIN_LOCKED:d.PIN_WRONG;case-10029:return d.PIN_INVALID;case-10031:return d.PIN_LOCKED;case-10032:return d.PIN_REPEATED_PATTERN;case-10026:return d.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return d.PREPARE_FAILED;case-10016:return d.PREPARE_EXPIRED;case-10017:case-10018:return d.PREPARE_MISMATCH;case-10020:return d.CHAIN_NOT_SUPPORTED;case-10021:return d.INVALID_CHAIN;case-10040:return d.HMAC_REQUIRED;case-10041:return d.HMAC_VERIFICATION_FAILED;default:return d.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${ye} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class kr{constructor(e,r,t,s=()=>{},o=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=s,this.getAppName=o,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(n,a)=>e.prepare(n,a)),e.migrateWallet&&(this.migrateWallet=(n,a)=>e.migrateWallet(n,a)),e.verifyPin&&(this.verifyPin=n=>e.verifyPin(n)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(n,a)=>e.verifyRecoveryPin(n,a))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,r,t,s,o,n){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();const l=await a.signMessage({chainId:r,message:t,from:n,index:s,dappName:this.getAppName()});return{chainId:r,signature:l.signature,format:"hex"}}return this.inner.signMessage(e,r,t,s,o,n)}async signTypedData(e,r,t,s,o,n){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();const l=await a.signTypedData({chainId:r,typedData:t,from:n,index:s,dappName:this.getAppName()});return{chainId:r,signature:l.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,s,o,n)}async signTransaction(e,r,t,s,o){const n=this.shouldUseBridge();if(n!=null&&n.signTransaction){this.assertBridgeSessionActive();const a=await n.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:s,dappName:this.getAppName()});return{chainId:r,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,r,t,s,o)}async sendTransaction(e,r,t,s){const o=this.shouldUseBridge();if(o!=null&&o.sendTransaction)return this.assertBridgeSessionActive(),{txHash:(await o.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,dappName:this.getAppName()})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,s)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class xe{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){return this.isCacheValid()?Array.from(this.cache.values()):this._fetchPromise?this._fetchPromise:(this._fetchPromise=this._doFetchChains().finally(()=>{this._fetchPromise=null}),this._fetchPromise)}async _doFetchChains(){try{const e=await this.request("/chains");this.handleEnvelopeError(e);const r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=xe.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(s=>s.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?Mt:Dt;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new h(xe.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=xe.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new h(d.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Ae).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return d.CHAIN_NOT_SUPPORTED;case-10021:return d.INVALID_CHAIN;case-10022:return d.PROJECT_NOT_REGISTERED;case-10023:return d.PROJECT_ID_MISSING;case-10024:return d.APP_IDENTIFIER_MISSING;case-10025:return d.INVALID_APP_TYPE;default:return d.UNKNOWN_ERROR}}}const ct="__crossx-confirm-style",$="__crossx-confirm-overlay",Tr={light:{bg:"#FFFFFF",border:"rgba(0,0,0,0.07)",borderMedium:"rgba(0,0,0,0.18)",titleColor:"#000000",subtitleColor:"rgba(0,0,0,0.65)",labelColor:"rgba(0,0,0,0.65)",valueColor:"#000000",pillBg:"#F5F7FA",pillFromColor:"rgba(0,0,0,0.65)",pillAmtColor:"#000000",divider:"rgba(0,0,0,0.07)",closeColor:"rgba(0,0,0,0.40)",closeHoverBg:"#F5F7FA",copyColor:"rgba(0,0,0,0.65)",inputBg:"#F5F7FA",inputBorder:"rgba(0,0,0,0.07)",hintColor:"rgba(0,0,0,0.45)",surfaceSubtle:"#F5F7FA",surfaceHigh:"#EDF1F2",primary:"#FF823D",primaryGlow:"rgba(255,130,61,0.20)",primaryGradient:"linear-gradient(191.6deg, #FF2589 16%, #FF823D 84%)",secondary:"#D20609",errorColor:"#D20609",noticeBg:"#FFF6F6",noticeBorder:"#DA0B2E",noticeTitleColor:"#D20609",onPrimary:"#000000"},dark:{bg:"#1E232E",border:"rgba(255,255,255,0.07)",borderMedium:"rgba(255,255,255,0.18)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.65)",labelColor:"rgba(255,255,255,0.65)",valueColor:"#FFFFFF",pillBg:"#252B39",pillFromColor:"rgba(255,255,255,0.65)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.07)",closeColor:"rgba(255,255,255,0.40)",closeHoverBg:"#252B39",copyColor:"rgba(255,255,255,0.65)",inputBg:"#252B39",inputBorder:"rgba(255,255,255,0.07)",hintColor:"rgba(255,255,255,0.45)",surfaceSubtle:"#252B39",surfaceHigh:"#363B4C",primary:"#FF823D",primaryGlow:"rgba(255,130,61,0.20)",primaryGradient:"linear-gradient(191.6deg, #FF2589 16%, #FF823D 84%)",secondary:"#FF0F47",errorColor:"#FF0F47",noticeBg:"#39151E",noticeBorder:"#CD0C40",noticeTitleColor:"#FF0F47",onPrimary:"#000000"}};function lt(i,e){const r=Tr[i],t=e==null?void 0:e[i];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle,surfaceHigh:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const Rr=`
|
|
8
8
|
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400&family=Sora:wght@400;600&display=swap');
|
|
9
9
|
|
|
10
10
|
#${$} {
|
|
@@ -382,14 +382,15 @@ ${t.length}`),o=new Uint8Array(s.length+t.length);o.set(s,0),o.set(t,s.length);c
|
|
|
382
382
|
font-weight: 600;
|
|
383
383
|
font-family: inherit;
|
|
384
384
|
cursor: pointer;
|
|
385
|
-
transition:
|
|
386
|
-
|
|
387
|
-
|
|
385
|
+
transition: opacity 0.15s;
|
|
386
|
+
/* disabled 기본값 = 브랜드 그라데이션 50% 투명도 */
|
|
387
|
+
background: var(--cx-primary-gradient);
|
|
388
|
+
color: var(--cx-on-primary);
|
|
389
|
+
opacity: 0.5;
|
|
388
390
|
letter-spacing: -0.01em;
|
|
389
391
|
}
|
|
390
392
|
.__crossx-pw-btn:not(:disabled):not(.--disabled) {
|
|
391
|
-
|
|
392
|
-
color: var(--cx-on-primary);
|
|
393
|
+
opacity: 1;
|
|
393
394
|
}
|
|
394
395
|
.__crossx-pw-btn.--loading {
|
|
395
396
|
opacity: 0.6;
|
|
@@ -498,11 +499,9 @@ ${t.length}`),o=new Uint8Array(s.length+t.length);o.set(s,0),o.set(t,s.length);c
|
|
|
498
499
|
flex: 1;
|
|
499
500
|
letter-spacing: -0.01em;
|
|
500
501
|
}
|
|
501
|
-
/* Notice screen:
|
|
502
|
+
/* Notice screen: disabled 버튼은 50% 투명도로 표시하되 탭하면 미체크 항목을 안내 */
|
|
502
503
|
.__crossx-pw-body > .__crossx-pw-btn.--disabled {
|
|
503
|
-
|
|
504
|
-
color: var(--cx-on-primary);
|
|
505
|
-
opacity: 1;
|
|
504
|
+
opacity: 0.5;
|
|
506
505
|
cursor: pointer;
|
|
507
506
|
}
|
|
508
507
|
/* Home indicator bar (mobile only – shown via media query) */
|
|
@@ -869,7 +868,7 @@ ${t.length}`),o=new Uint8Array(s.length+t.length);o.set(s,0),o.set(t,s.length);c
|
|
|
869
868
|
padding: 16px;
|
|
870
869
|
border: 1px solid var(--cx-border);
|
|
871
870
|
border-radius: 12px;
|
|
872
|
-
background: var(--cx-primary);
|
|
871
|
+
background: var(--cx-primary-gradient);
|
|
873
872
|
color: var(--cx-on-primary);
|
|
874
873
|
font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
|
|
875
874
|
font-size: 18px;
|
|
@@ -885,7 +884,7 @@ ${t.length}`),o=new Uint8Array(s.length+t.length);o.set(s,0),o.set(t,s.length);c
|
|
|
885
884
|
outline: none !important;
|
|
886
885
|
filter: none !important;
|
|
887
886
|
transform: none !important;
|
|
888
|
-
background: var(--cx-primary) !important;
|
|
887
|
+
background: var(--cx-primary-gradient) !important;
|
|
889
888
|
color: var(--cx-on-primary) !important;
|
|
890
889
|
}
|
|
891
890
|
.__crossx-btn-row {
|
|
@@ -922,7 +921,7 @@ ${t.length}`),o=new Uint8Array(s.length+t.length);o.set(s,0),o.set(t,s.length);c
|
|
|
922
921
|
padding: 16px;
|
|
923
922
|
border: 1px solid var(--cx-border);
|
|
924
923
|
border-radius: 12px;
|
|
925
|
-
background: var(--cx-primary);
|
|
924
|
+
background: var(--cx-primary-gradient);
|
|
926
925
|
color: var(--cx-on-primary);
|
|
927
926
|
font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
|
|
928
927
|
font-size: 18px;
|
|
@@ -938,7 +937,7 @@ ${t.length}`),o=new Uint8Array(s.length+t.length);o.set(s,0),o.set(t,s.length);c
|
|
|
938
937
|
outline: none !important;
|
|
939
938
|
filter: none !important;
|
|
940
939
|
transform: none !important;
|
|
941
|
-
background: var(--cx-primary) !important;
|
|
940
|
+
background: var(--cx-primary-gradient) !important;
|
|
942
941
|
color: var(--cx-on-primary) !important;
|
|
943
942
|
}
|
|
944
943
|
|
|
@@ -2059,9 +2058,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2059
2058
|
box-sizing: border-box;
|
|
2060
2059
|
}
|
|
2061
2060
|
.__crossx-card--pin6 .__crossx-pw-btn.--disabled {
|
|
2062
|
-
|
|
2063
|
-
color: var(--cx-on-primary);
|
|
2064
|
-
opacity: 1;
|
|
2061
|
+
opacity: 0.5;
|
|
2065
2062
|
cursor: pointer;
|
|
2066
2063
|
}
|
|
2067
2064
|
.__crossx-pin6-header-sub {
|
|
@@ -2188,7 +2185,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2188
2185
|
.__crossx-pin6-next {
|
|
2189
2186
|
width: 100%;
|
|
2190
2187
|
padding: 16px;
|
|
2191
|
-
background: var(--cx-primary);
|
|
2188
|
+
background: var(--cx-primary-gradient);
|
|
2192
2189
|
color: var(--cx-on-primary);
|
|
2193
2190
|
border: none;
|
|
2194
2191
|
border-radius: 12px;
|
|
@@ -2562,7 +2559,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2562
2559
|
height: 48px;
|
|
2563
2560
|
border: none;
|
|
2564
2561
|
border-radius: 12px;
|
|
2565
|
-
background: var(--cx-primary);
|
|
2562
|
+
background: var(--cx-primary-gradient);
|
|
2566
2563
|
color: var(--cx-on-primary);
|
|
2567
2564
|
font-family: inherit;
|
|
2568
2565
|
font-size: 16px;
|
|
@@ -2579,7 +2576,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2579
2576
|
outline: none !important;
|
|
2580
2577
|
filter: none !important;
|
|
2581
2578
|
transform: none !important;
|
|
2582
|
-
background: var(--cx-primary) !important;
|
|
2579
|
+
background: var(--cx-primary-gradient) !important;
|
|
2583
2580
|
color: var(--cx-on-primary) !important;
|
|
2584
2581
|
}
|
|
2585
2582
|
|
|
@@ -2605,27 +2602,27 @@ button.__crossx-connect-other-block:active {
|
|
|
2605
2602
|
.__crossx-tip-overlay.--visible {
|
|
2606
2603
|
display: block;
|
|
2607
2604
|
}
|
|
2608
|
-
`;function G(){let i=document.getElementById(
|
|
2605
|
+
`;function G(){let i=document.getElementById(ct);i||(i=document.createElement("style"),i.id=ct,document.head.appendChild(i)),i.textContent=Rr}function Nr(){const i=`#${$}`,e=t=>{var s,o;(o=(s=t.target)==null?void 0:s.closest)!=null&&o.call(s,i)&&t.stopImmediatePropagation()},r=t=>{var s,o;(o=(s=t.relatedTarget)==null?void 0:s.closest)!=null&&o.call(s,i)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",r,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",r,!0)}}function K(i){const e=i.querySelector(".__crossx-card");if(e){const a=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(a){const l=a[1].trim();i.style.setProperty("--cx-bg",l);const p=document.createElement("div");p.className="__crossx-safe-area-fill",p.style.background=l,i.appendChild(p)}}const r=n=>n.stopPropagation();for(const n of["pointerdown","pointerup","mousedown","mouseup","click"])i.addEventListener(n,r);i.setAttribute("data-vaul-no-drag","");for(const n of["touchstart","touchend"])i.addEventListener(n,r);i.addEventListener("touchmove",n=>{n.stopPropagation();let a=n.target;for(;a&&a!==i;){const l=window.getComputedStyle(a);if((l.overflowY==="auto"||l.overflowY==="scroll")&&a.scrollHeight>a.clientHeight)return;a=a.parentElement}n.preventDefault()},{passive:!1});const t=Nr(),s=Cr(i),o=i.remove.bind(i);i.remove=()=>{s(),t(),o()},document.body.appendChild(i)}function Cr(i){if(typeof window>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};let r=-1;const t=()=>{const s=window.innerHeight,o=e.offsetTop+e.height,n=Math.max(0,Math.round(s-o));n!==r&&(r=n,i.style.setProperty("--cx-keyboard-inset",`${n}px`))};return t(),e.addEventListener("resize",t),e.addEventListener("scroll",t),()=>{e.removeEventListener("resize",t),e.removeEventListener("scroll",t),i.style.removeProperty("--cx-keyboard-inset")}}function Pr(i){const e=Array.from(i.querySelectorAll(".__crossx-amount-tip"));if(!e.length)return;const r=document.createElement("div");r.className="__crossx-tip-overlay",i.appendChild(r);let t=null;const s=n=>{const a=n.dataset.full;if(!a)return;r.textContent=a,r.classList.add("--visible");const l=n.getBoundingClientRect(),p=r.offsetWidth,_=r.offsetHeight;let u=l.right-p,x=l.top-_-6;u<8&&(u=8),x<8&&(x=l.bottom+6),r.style.left=`${u}px`,r.style.top=`${x}px`,t=n},o=()=>{r.classList.remove("--visible"),t=null};e.forEach(n=>{n.addEventListener("mouseenter",()=>s(n)),n.addEventListener("mouseleave",o),n.addEventListener("touchstart",a=>{a.stopPropagation(),t===n?o():s(n)},{passive:!0})}),i.addEventListener("touchstart",n=>{n.target.closest(".__crossx-amount-tip")||o()},{passive:!0})}const Or=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function re(){if(Or()){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 i=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=i}}function Q(i){return i?i.length<=13?i:`${i.slice(0,6)}…${i.slice(-4)}`:"—"}function ft(i){return i?i.length<=13?i:`${i.slice(0,6)}...${i.slice(-4)}`:"—"}function wt(i,e="ONE",r=18,t=6){if(!i||i==="0x"||i==="0x0")return null;try{const s=BigInt(i);if(s===0n)return null;const o=Be(s,r,t);if(o==="0")return null;const n=$e(s,r);return Fe(`${o} ${e}`,`${n} ${e}`)}catch{return null}}const dt={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:"ONEchain Testnet",612055:"CROSS Mainnet"},Ge=new Map;let Pe=!1;function Lr(){if(Pe||(Pe=!0,typeof fetch>"u"))return;const i=He().contentsBaseUrl;i&&fetch(`${i}/chains.json`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{const r=e==null?void 0:e.chains;if(r)for(const[t,s]of Object.entries(r)){const o=Number(t);!Number.isNaN(o)&&s&&Ge.set(o,s)}}).catch(()=>{Pe=!1})}function mt(i){return parseInt(i.split(":")[1]??"",10)}function yt(i){var r;const e=mt(i);if(!isNaN(e)){const t=(r=Ge.get(e))==null?void 0:r.name;if(t)return t;if(dt[e])return dt[e]}return i}function Ke(i,e){var r;if(i){const t=mt(i);if(!isNaN(t)){const s=(r=Ge.get(t))==null?void 0:r.nativeSymbol;if(s)return s}}return e}function $e(i,e){if(i===0n)return"0";const r=10n**BigInt(e),t=i/r,o=(i%r).toString().padStart(e,"0").replace(/0+$/,"");return o?`${t}.${o}`:`${t}`}function Fe(i,e){return i===e?w(i):`<span class="__crossx-amount-tip" data-full="${w(e)}">${w(i)}</span>`}function Be(i,e,r){if(i===0n)return"0";const t=10n**BigInt(e),s=i/t,a=(i%t).toString().padStart(e,"0").slice(0,r).replace(/0+$/,"");return a?`${s}.${a}`:`${s}`}function Oe(i){try{const e=BigInt(i),r=e/1000000000n,s=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return s?`${r}.${s}`:`${r}`}catch{return i}}function Dr(i){try{return BigInt(i).toLocaleString()}catch{return i}}function Mr(i,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:s,maxPriorityFeePerGas:o,nativeDecimals:n=18}=i,a=Ke(i.chainId,i.nativeSymbol??"ETH");if(!r)return null;try{const l=BigInt(r),p=Dr(r);if(s){const _=l*BigInt(s);return{isDynamic:!0,estTxFee:Fe(`${Be(_,n,e)} ${a}`,`${$e(_,n)} ${a}`),maxFeeGwei:Oe(s),maxPriorityFeeGwei:o?Oe(o):void 0,gasLimitFormatted:p}}if(t){const _=l*BigInt(t);return{isDynamic:!1,estTxFee:Fe(`${Be(_,n,e)} ${a}`,`${$e(_,n)} ${a}`),gasPriceGwei:Oe(t),gasLimitFormatted:p}}return{isDynamic:!1,estTxFee:`${l.toLocaleString()} gas`,gasLimitFormatted:p}}catch{return null}}function bt(i,e,r){const t=Mr(i,e);if(!t)return D((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let s=D((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(s+=D((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(s+=D((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(s+=D((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(s+=D((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),s}const Z=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
2609
2606
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
2610
2607
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
2611
2608
|
</svg>`,B=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
2612
2609
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
2613
2610
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
2614
|
-
</svg
|
|
2611
|
+
</svg>`,$r=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2615
2612
|
<circle cx="20" cy="20" r="20" fill="#00D5AA"/>
|
|
2616
2613
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/>
|
|
2617
|
-
</svg>`,
|
|
2614
|
+
</svg>`,Fr='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 318.6 318.6" aria-hidden="true"><style>.st1,.st6{fill:#e4761b;stroke:#e4761b;stroke-linecap:round;stroke-linejoin:round}.st6{fill:#f6851b;stroke:#f6851b}</style><path fill="#e2761b" stroke="#e2761b" stroke-linecap="round" stroke-linejoin="round" d="m274.1 35.5-99.5 73.9L193 65.8z"/><path d="m44.4 35.5 98.7 74.6-17.5-44.3zm193.9 171.3-26.5 40.6 56.7 15.6 16.3-55.3zm-204.4.9L50.1 263l56.7-15.6-26.5-40.6z" class="st1"/><path d="m103.6 138.2-15.8 23.9 56.3 2.5-2-60.5zm111.3 0-39-34.8-1.3 61.2 56.2-2.5zM106.8 247.4l33.8-16.5-29.2-22.8zm71.1-16.5 33.9 16.5-4.7-39.3z" class="st1"/><path fill="#d7c1b3" stroke="#d7c1b3" stroke-linecap="round" stroke-linejoin="round" d="m211.8 247.4-33.9-16.5 2.7 22.1-.3 9.3zm-105 0 31.5 14.9-.2-9.3 2.5-22.1z"/><path fill="#233447" stroke="#233447" stroke-linecap="round" stroke-linejoin="round" d="m138.8 193.5-28.2-8.3 19.9-9.1zm40.9 0 8.3-17.4 20 9.1z"/><path fill="#cd6116" stroke="#cd6116" stroke-linecap="round" stroke-linejoin="round" d="m106.8 247.4 4.8-40.6-31.3.9zM207 206.8l4.8 40.6 26.5-39.7zm23.8-44.7-56.2 2.5 5.2 28.9 8.3-17.4 20 9.1zm-120.2 23.1 20-9.1 8.2 17.4 5.3-28.9-56.3-2.5z"/><path fill="#e4751f" stroke="#e4751f" stroke-linecap="round" stroke-linejoin="round" d="m87.8 162.1 23.6 46-.8-22.9zm120.3 23.1-1 22.9 23.7-46zm-64-20.6-5.3 28.9 6.6 34.1 1.5-44.9zm30.5 0-2.7 18 1.2 45 6.7-34.1z"/><path d="m179.8 193.5-6.7 34.1 4.8 3.3 29.2-22.8 1-22.9zm-69.2-8.3.8 22.9 29.2 22.8 4.8-3.3-6.6-34.1z" class="st6"/><path fill="#c0ad9e" stroke="#c0ad9e" stroke-linecap="round" stroke-linejoin="round" d="m180.3 262.3.3-9.3-2.5-2.2h-37.7l-2.3 2.2.2 9.3-31.5-14.9 11 9 22.3 15.5h38.3l22.4-15.5 11-9z"/><path fill="#161616" stroke="#161616" stroke-linecap="round" stroke-linejoin="round" d="m177.9 230.9-4.8-3.3h-27.7l-4.8 3.3-2.5 22.1 2.3-2.2h37.7l2.5 2.2z"/><path fill="#763d16" stroke="#763d16" stroke-linecap="round" stroke-linejoin="round" d="m278.3 114.2 8.5-40.8-12.7-37.9-96.2 71.4 37 31.3 52.3 15.3 11.6-13.5-5-3.6 8-7.3-6.2-4.8 8-6.1zM31.8 73.4l8.5 40.8-5.4 4 8 6.1-6.1 4.8 8 7.3-5 3.6 11.5 13.5 52.3-15.3 37-31.3-96.2-71.4z"/><path d="m267.2 153.5-52.3-15.3 15.9 23.9-23.7 46 31.2-.4h46.5zm-163.6-15.3-52.3 15.3-17.4 54.2h46.4l31.1.4-23.6-46zm71 26.4 3.3-57.7 15.2-41.1h-67.5l15 41.1 3.5 57.7 1.2 18.2.1 44.8h27.7l.2-44.8z" class="st6"/></svg>',Br='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 126.611 126.611" aria-hidden="true"><polygon fill="#F3BA2F" points="38.171,53.203 62.759,28.616 87.36,53.216 101.667,38.909 62.759,0 23.864,38.896 "/><rect x="3.644" y="53.188" transform="matrix(0.7071 0.7071 -0.7071 0.7071 48.7933 8.8106)" fill="#F3BA2F" width="20.233" height="20.234"/><polygon fill="#F3BA2F" points="38.171,73.408 62.759,97.995 87.359,73.396 101.674,87.695 101.667,87.703 62.759,126.611 23.863,87.716 23.843,87.696 "/><rect x="101.64" y="53.189" transform="matrix(-0.7071 0.7071 -0.7071 -0.7071 235.5457 29.0503)" fill="#F3BA2F" width="20.234" height="20.233"/><polygon fill="#F3BA2F" points="77.271,63.298 77.277,63.298 62.759,48.78 52.03,59.509 52.029,59.509 50.797,60.742 48.254,63.285 48.254,63.285 48.234,63.305 48.254,63.326 62.759,77.831 77.277,63.313 77.284,63.305 "/></svg>',Wr='<svg width="16" height="16" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><circle cx="20" cy="20" r="20" fill="#00D5AA"/><path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/></svg>',Ur={[pe.MetaMask]:Fr,[pe.Binance]:Br,[pe.CROSSx]:Wr},vt='<path d="M22.6667 11.8333V10.1667C22.6667 9.2475 21.9192 8.5 21.0001 8.5H10.1667C8.78841 8.5 7.66675 9.62167 7.66675 11V21C7.66675 22.8342 9.16175 23.5 10.1667 23.5H22.6667C23.5859 23.5 24.3334 22.7525 24.3334 21.8333V13.5C24.3334 12.5808 23.5859 11.8333 22.6667 11.8333ZM21.0001 19.3333H19.3334V16H21.0001V19.3333ZM10.1667 11.8333C9.95218 11.8237 9.74959 11.7317 9.60114 11.5765C9.4527 11.4213 9.36986 11.2148 9.36986 11C9.36986 10.7852 9.4527 10.5787 9.60114 10.4235C9.74959 10.2683 9.95218 10.1763 10.1667 10.1667H21.0001V11.8333H10.1667Z"/>',qe=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${vt}</svg>`,Hr=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
2618
2615
|
<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="var(--cx-error)"/>
|
|
2619
|
-
</svg
|
|
2616
|
+
</svg>`,Gr=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
2620
2617
|
<circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
|
|
2621
2618
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
2622
2619
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
2623
|
-
</svg>`;function H(i){return[`--cx-bg:${i.bg}`,`--cx-border:${i.border}`,`--cx-border-medium:${i.borderMedium}`,`--cx-title:${i.titleColor}`,`--cx-subtitle:${i.subtitleColor}`,`--cx-label:${i.labelColor}`,`--cx-value:${i.valueColor}`,`--cx-pill-bg:${i.pillBg}`,`--cx-pill-from:${i.pillFromColor}`,`--cx-pill-amt:${i.pillAmtColor}`,`--cx-divider:${i.divider}`,`--cx-close:${i.closeColor}`,`--cx-close-hover:${i.closeHoverBg}`,`--cx-copy:${i.copyColor}`,`--cx-input-bg:${i.inputBg}`,`--cx-input-border:${i.inputBorder}`,`--cx-hint:${i.hintColor}`,`--cx-surface-subtle:${i.surfaceSubtle}`,`--cx-surface-high:${i.surfaceHigh}`,`--cx-primary:${i.primary}`,`--cx-primary-glow:${i.primaryGlow}`,`--cx-secondary:${i.secondary}`,`--cx-error:${i.errorColor}`,`--cx-notice-bg:${i.noticeBg}`,`--cx-notice-border:${i.noticeBorder}`,`--cx-notice-title:${i.noticeTitleColor}`,`--cx-on-primary:${i.onPrimary}`].join(";")}function
|
|
2620
|
+
</svg>`;function H(i){return[`--cx-bg:${i.bg}`,`--cx-border:${i.border}`,`--cx-border-medium:${i.borderMedium}`,`--cx-title:${i.titleColor}`,`--cx-subtitle:${i.subtitleColor}`,`--cx-label:${i.labelColor}`,`--cx-value:${i.valueColor}`,`--cx-pill-bg:${i.pillBg}`,`--cx-pill-from:${i.pillFromColor}`,`--cx-pill-amt:${i.pillAmtColor}`,`--cx-divider:${i.divider}`,`--cx-close:${i.closeColor}`,`--cx-close-hover:${i.closeHoverBg}`,`--cx-copy:${i.copyColor}`,`--cx-input-bg:${i.inputBg}`,`--cx-input-border:${i.inputBorder}`,`--cx-hint:${i.hintColor}`,`--cx-surface-subtle:${i.surfaceSubtle}`,`--cx-surface-high:${i.surfaceHigh}`,`--cx-primary:${i.primary}`,`--cx-primary-glow:${i.primaryGlow}`,`--cx-primary-gradient:${i.primaryGradient}`,`--cx-secondary:${i.secondary}`,`--cx-error:${i.errorColor}`,`--cx-notice-bg:${i.noticeBg}`,`--cx-notice-border:${i.noticeBorder}`,`--cx-notice-title:${i.noticeTitleColor}`,`--cx-on-primary:${i.onPrimary}`].join(";")}function Kr(i,e){i.style.setProperty("--cx-bg",e.bg),i.style.setProperty("--cx-border",e.border),i.style.setProperty("--cx-border-medium",e.borderMedium),i.style.setProperty("--cx-title",e.titleColor),i.style.setProperty("--cx-subtitle",e.subtitleColor),i.style.setProperty("--cx-label",e.labelColor),i.style.setProperty("--cx-value",e.valueColor),i.style.setProperty("--cx-pill-bg",e.pillBg),i.style.setProperty("--cx-pill-from",e.pillFromColor),i.style.setProperty("--cx-pill-amt",e.pillAmtColor),i.style.setProperty("--cx-divider",e.divider),i.style.setProperty("--cx-close",e.closeColor),i.style.setProperty("--cx-close-hover",e.closeHoverBg),i.style.setProperty("--cx-copy",e.copyColor),i.style.setProperty("--cx-input-bg",e.inputBg),i.style.setProperty("--cx-input-border",e.inputBorder),i.style.setProperty("--cx-hint",e.hintColor),i.style.setProperty("--cx-surface-subtle",e.surfaceSubtle),i.style.setProperty("--cx-surface-high",e.surfaceHigh),i.style.setProperty("--cx-primary",e.primary),i.style.setProperty("--cx-primary-glow",e.primaryGlow),i.style.setProperty("--cx-primary-gradient",e.primaryGradient),i.style.setProperty("--cx-secondary",e.secondary),i.style.setProperty("--cx-error",e.errorColor),i.style.setProperty("--cx-notice-bg",e.noticeBg),i.style.setProperty("--cx-notice-border",e.noticeBorder),i.style.setProperty("--cx-notice-title",e.noticeTitleColor),i.style.setProperty("--cx-on-primary",e.onPrimary)}function D(i,e){return`
|
|
2624
2621
|
<div class="__crossx-row">
|
|
2625
2622
|
<span class="__crossx-row-label">${i}</span>
|
|
2626
2623
|
<div class="__crossx-row-value">${e}</div>
|
|
2627
|
-
</div>`}function
|
|
2628
|
-
<button class="__crossx-copy-btn" data-copy="${w(i.to)}" title="Copy address">${Z}</button>`:"<span>—</span>",p=
|
|
2624
|
+
</div>`}function qr(i,e,r,t){const s=e,o=Ke(i.chainId,i.nativeSymbol??"ETH"),n=i.nativeDecimals??18,a=Ie(i.dappName),l=i.to?`<span class="__crossx-addr-text">${Q(i.to)}</span>
|
|
2625
|
+
<button class="__crossx-copy-btn" data-copy="${w(i.to)}" title="Copy address">${Z}</button>`:"<span>—</span>",p=bt(i,r,t),_=wt(i.value,o,n,r),u=_?D((t==null?void 0:t.label_value)??"Value",`<span>${_}</span>`):"",x=i.data??"0x",g=document.createElement("div");return g.id=$,g.innerHTML=`
|
|
2629
2626
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${H(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2630
2627
|
<div class="__crossx-header">
|
|
2631
2628
|
<p class="__crossx-title" id="__crossx-ttl">${w((t==null?void 0:t.sign_transaction_title)??"Signature Request")}</p>
|
|
@@ -2639,7 +2636,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2639
2636
|
<span class="__crossx-sig-origin">${w(a)}</span>${w((t==null?void 0:t.signature_requesting)??" is requesting a Signature")}
|
|
2640
2637
|
</p>
|
|
2641
2638
|
<div class="__crossx-addr-pill">
|
|
2642
|
-
${
|
|
2639
|
+
${qe}
|
|
2643
2640
|
<span class="__crossx-addr-pill-text">${Q(i.from)}</span>
|
|
2644
2641
|
</div>
|
|
2645
2642
|
<p class="__crossx-warning">${w((t==null?void 0:t.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
|
|
@@ -2648,11 +2645,11 @@ button.__crossx-connect-other-block:active {
|
|
|
2648
2645
|
<div class="__crossx-col-right-sign">
|
|
2649
2646
|
<div class="__crossx-rows">
|
|
2650
2647
|
${D((t==null?void 0:t.label_to)??"To",l)}
|
|
2651
|
-
${D((t==null?void 0:t.label_network)??"Network",`<span>${
|
|
2648
|
+
${D((t==null?void 0:t.label_network)??"Network",`<span>${yt(i.chainId)}</span>`)}
|
|
2652
2649
|
${u}
|
|
2653
2650
|
${p}
|
|
2654
2651
|
</div>
|
|
2655
|
-
<pre class="__crossx-raw-tx">${w(
|
|
2652
|
+
<pre class="__crossx-raw-tx">${w(x)}</pre>
|
|
2656
2653
|
</div>
|
|
2657
2654
|
</div>
|
|
2658
2655
|
<div class="__crossx-btn-row">
|
|
@@ -2661,8 +2658,8 @@ button.__crossx-connect-other-block:active {
|
|
|
2661
2658
|
</div>
|
|
2662
2659
|
</div>
|
|
2663
2660
|
</div>
|
|
2664
|
-
`,
|
|
2665
|
-
<button class="__crossx-copy-btn" data-copy="${w(i.to)}" title="Copy address">${Z}</button>`:"<span>—</span>",p=
|
|
2661
|
+
`,g}const zr=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function Vr(i){return i?zr.has(i.slice(0,10).toLowerCase()):!1}function jr(i,e,r,t){const s=e,o=Ke(i.chainId,i.nativeSymbol??"ETH"),n=i.nativeDecimals??18,a=Ie(i.dappName),l=i.to?`<span class="__crossx-addr-text">${Q(i.to)}</span>
|
|
2662
|
+
<button class="__crossx-copy-btn" data-copy="${w(i.to)}" title="Copy address">${Z}</button>`:"<span>—</span>",p=bt(i,r,t),u=wt(i.value,o,n,r)??"—",x=Vr(i.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",g=document.createElement("div");return g.id=$,g.innerHTML=`
|
|
2666
2663
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${H(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2667
2664
|
<div class="__crossx-header">
|
|
2668
2665
|
<p class="__crossx-title" id="__crossx-ttl">${w((t==null?void 0:t.send_transaction_title)??"Approve transaction")}</p>
|
|
@@ -2676,7 +2673,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2676
2673
|
<div class="__crossx-body-cols">
|
|
2677
2674
|
<div class="__crossx-rows">
|
|
2678
2675
|
${D((t==null?void 0:t.label_to)??"To",l)}
|
|
2679
|
-
${D((t==null?void 0:t.label_network)??"Network",`<span>${
|
|
2676
|
+
${D((t==null?void 0:t.label_network)??"Network",`<span>${yt(i.chainId)}</span>`)}
|
|
2680
2677
|
${p}
|
|
2681
2678
|
</div>
|
|
2682
2679
|
<div class="__crossx-pill">
|
|
@@ -2684,12 +2681,12 @@ button.__crossx-connect-other-block:active {
|
|
|
2684
2681
|
<span class="__crossx-pill-amount">${u}</span>
|
|
2685
2682
|
</div>
|
|
2686
2683
|
</div>
|
|
2687
|
-
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">${w(
|
|
2684
|
+
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">${w(x)}</button>
|
|
2688
2685
|
</div>
|
|
2689
2686
|
</div>
|
|
2690
|
-
`,
|
|
2691
|
-
<button class="__crossx-copy-btn" data-copy="${w(i.from)}" title="Copy address">${Z}</button>`),s=i.to?D((r==null?void 0:r.label_to)??"To",`${
|
|
2692
|
-
<button class="__crossx-copy-btn" data-copy="${w(i.to)}" title="Copy address">${Z}</button>`):"",o=i.amount?D((r==null?void 0:r.label_transfer)??"Transfer",`<span>${w(i.amount)}</span>`):"",n=i.fees?D((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${w(i.fees)}</span>`):"",a=i.txHash?D((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${
|
|
2687
|
+
`,g}function Ie(i){var e;if(i)return i;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function w(i){return i.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Yr(i){return typeof i=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(i)}function Xr(i){if(typeof i=="string")return w(i);if(typeof i=="number"||typeof i=="bigint"||typeof i=="boolean")return String(i);try{return w(JSON.stringify(i))}catch{return String(i)}}function Jr(i){return i.includes(":")?i.split(":")[1]??i:i}function Zr(i){return`https://www.crossscan.io/address/${i}?tab=txs`}function Qr(i,e){return`https://explorer.crosstoken.io/${Jr(i)}/tx/${e}`}function St(i,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${w(e)}" target="_blank" rel="noopener noreferrer">${w(i)}</a>`}function ve(i){return St(Q(i),Zr(i))}function Et(i,e){return St(Q(e),Qr(i,e))}function es(i,e,r){const t=D((r==null?void 0:r.label_from)??"From",`${ve(i.from)}
|
|
2688
|
+
<button class="__crossx-copy-btn" data-copy="${w(i.from)}" title="Copy address">${Z}</button>`),s=i.to?D((r==null?void 0:r.label_to)??"To",`${ve(i.to)}
|
|
2689
|
+
<button class="__crossx-copy-btn" data-copy="${w(i.to)}" title="Copy address">${Z}</button>`):"",o=i.amount?D((r==null?void 0:r.label_transfer)??"Transfer",`<span>${w(i.amount)}</span>`):"",n=i.fees?D((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${w(i.fees)}</span>`):"",a=i.txHash?D((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${Et(i.chainId,i.txHash)}
|
|
2693
2690
|
<button class="__crossx-copy-btn" data-copy="${w(i.txHash)}" title="Copy hash">${Z}</button>`):"",l=i.total?`<div class="__crossx-total-pill">
|
|
2694
2691
|
<span class="__crossx-total-label">${w((r==null?void 0:r.label_total)??"Total")}<br>${w((r==null?void 0:r.label_including_fees)??"(including fees)")}</span>
|
|
2695
2692
|
<span class="__crossx-total-amount">${w(i.total)}</span>
|
|
@@ -2712,7 +2709,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2712
2709
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${w((r==null?void 0:r.tx_complete_done_button)??"All Done")}</button>
|
|
2713
2710
|
</div>
|
|
2714
2711
|
</div>
|
|
2715
|
-
`,p}function
|
|
2712
|
+
`,p}function ts(i,e,r){const t=document.createElement("div");return t.id=$,t.innerHTML=`
|
|
2716
2713
|
<div class="__crossx-card __crossx-card--migration" style="${H(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2717
2714
|
<div class="__crossx-header">
|
|
2718
2715
|
<p class="__crossx-title" id="__crossx-ttl">${w((r==null?void 0:r.tx_progress_waiting_title)??"Waiting for confirmation")}</p>
|
|
@@ -2725,23 +2722,23 @@ button.__crossx-connect-other-block:active {
|
|
|
2725
2722
|
</div>
|
|
2726
2723
|
</div>
|
|
2727
2724
|
</div>
|
|
2728
|
-
`,t}function
|
|
2729
|
-
<button class="__crossx-copy-btn" data-copy="${w(e.from)}" title="Copy address">${Z}</button>`):"",
|
|
2730
|
-
<button class="__crossx-copy-btn" data-copy="${w(e.to)}" title="Copy address">${Z}</button>`):"",u=e.amount?D((t==null?void 0:t.label_transfer)??"Transfer",`<span>${w(e.amount)}</span>`):"",
|
|
2725
|
+
`,t}function rs(i,e,r,t){const s=e.status!=="reverted"&&e.status!=="timeout",o=e.status==="timeout",n=i.querySelector("#__crossx-ttl"),a=i.querySelector(".__crossx-header");if(n){const m=o?Gr:s?"":Hr,y=o?(t==null?void 0:t.tx_timeout)??"Transaction timeout":s?(t==null?void 0:t.tx_success)??"Transaction complete":(t==null?void 0:t.tx_failed)??"Transaction failed";m?(n.style.display="flex",n.style.alignItems="center",n.style.gap="8px",n.innerHTML=`${m}<span>${w(y)}</span>`):n.textContent=y}if(a&&!i.querySelector("#__crossx-close-btn")){const m=document.createElement("button");m.className="__crossx-close",m.id="__crossx-close-btn",m.setAttribute("aria-label","Close"),m.innerHTML=B,a.appendChild(m)}const l=i.querySelector("#__crossx-progress-body");if(!l)return;const p=e.from?D((t==null?void 0:t.label_from)??"From",`${ve(e.from)}
|
|
2726
|
+
<button class="__crossx-copy-btn" data-copy="${w(e.from)}" title="Copy address">${Z}</button>`):"",_=e.to?D((t==null?void 0:t.label_to)??"To",`${ve(e.to)}
|
|
2727
|
+
<button class="__crossx-copy-btn" data-copy="${w(e.to)}" title="Copy address">${Z}</button>`):"",u=e.amount?D((t==null?void 0:t.label_transfer)??"Transfer",`<span>${w(e.amount)}</span>`):"",x=e.fees?D((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${w(e.fees)}</span>`):"",g=e.txHash?D((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${Et(e.chainId,e.txHash)}
|
|
2731
2728
|
<button class="__crossx-copy-btn" data-copy="${w(e.txHash)}" title="Copy hash">${Z}</button>`):"",f=e.total?`<div class="__crossx-total-pill">
|
|
2732
2729
|
<span class="__crossx-total-label">${w((t==null?void 0:t.label_total)??"Total")}<br>${w((t==null?void 0:t.label_including_fees)??"(including fees)")}</span>
|
|
2733
2730
|
<span class="__crossx-total-amount">${w(e.total)}</span>
|
|
2734
2731
|
</div>`:"";l.innerHTML=`
|
|
2735
2732
|
<div class="__crossx-rows">
|
|
2736
2733
|
${p}
|
|
2737
|
-
${
|
|
2734
|
+
${_}
|
|
2738
2735
|
${u}
|
|
2739
|
-
${g}
|
|
2740
2736
|
${x}
|
|
2737
|
+
${g}
|
|
2741
2738
|
</div>
|
|
2742
2739
|
${f}
|
|
2743
2740
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${w((t==null?void 0:t.tx_complete_done_button)??(s?"All Done":"Done"))}</button>
|
|
2744
|
-
`,l.querySelectorAll(".__crossx-copy-btn").forEach(m=>{m.addEventListener("click",y=>{var E;y.stopPropagation();const
|
|
2741
|
+
`,l.querySelectorAll(".__crossx-copy-btn").forEach(m=>{m.addEventListener("click",y=>{var E;y.stopPropagation();const S=m.dataset.copy;S&&((E=navigator.clipboard)==null||E.writeText(S).catch(()=>{}))})})}function ss(i,e,r){const t=e,s=Ie(i.dappName),o=w(i.message),n=document.createElement("div");return n.id=$,n.innerHTML=`
|
|
2745
2742
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${H(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2746
2743
|
<div class="__crossx-header">
|
|
2747
2744
|
<p class="__crossx-title" id="__crossx-ttl">${w((r==null?void 0:r.sign_message_title)??"Signature Request")}</p>
|
|
@@ -2755,7 +2752,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2755
2752
|
<span class="__crossx-sig-origin">${w(s)}</span>${w((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
|
|
2756
2753
|
</p>
|
|
2757
2754
|
<div class="__crossx-addr-pill">
|
|
2758
|
-
${
|
|
2755
|
+
${qe}
|
|
2759
2756
|
<span class="__crossx-addr-pill-text">${Q(i.from)}</span>
|
|
2760
2757
|
</div>
|
|
2761
2758
|
<p class="__crossx-warning">${w((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
|
|
@@ -2769,14 +2766,14 @@ button.__crossx-connect-other-block:active {
|
|
|
2769
2766
|
</div>
|
|
2770
2767
|
</div>
|
|
2771
2768
|
</div>
|
|
2772
|
-
`,n}function
|
|
2769
|
+
`,n}function is(i,e,r){const t=e,s=Ie(i.dappName);let o={};if(typeof i.typedData=="string")try{o=JSON.parse(i.typedData)}catch{}else i.typedData&&typeof i.typedData=="object"&&(o=i.typedData);const n=o.primaryType??"—",a=o.message??{};let l=`
|
|
2773
2770
|
<div class="__crossx-td-row">
|
|
2774
2771
|
<span class="__crossx-td-label">${w((r==null?void 0:r.label_primary_type)??"Primary Type")}</span>
|
|
2775
2772
|
<span class="__crossx-td-value">${w(n)}</span>
|
|
2776
|
-
</div>`;for(const[
|
|
2777
|
-
<button class="__crossx-copy-btn" data-copy="${w(String(u))}" title="Copy">${Z}</button>`:`<span>${
|
|
2773
|
+
</div>`;for(const[_,u]of Object.entries(a)){const x=Xr(u),f=Yr(u)?`<span class="__crossx-addr-text">${Q(u)}</span>
|
|
2774
|
+
<button class="__crossx-copy-btn" data-copy="${w(String(u))}" title="Copy">${Z}</button>`:`<span>${x}</span>`;l+=`
|
|
2778
2775
|
<div class="__crossx-td-row">
|
|
2779
|
-
<span class="__crossx-td-label">${w(
|
|
2776
|
+
<span class="__crossx-td-label">${w(_)}</span>
|
|
2780
2777
|
<div class="__crossx-td-value">${f}</div>
|
|
2781
2778
|
</div>`}const p=document.createElement("div");return p.id=$,p.innerHTML=`
|
|
2782
2779
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${H(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
@@ -2792,7 +2789,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2792
2789
|
<span class="__crossx-sig-origin">${w(s)}</span>${w((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
|
|
2793
2790
|
</p>
|
|
2794
2791
|
<div class="__crossx-addr-pill">
|
|
2795
|
-
${
|
|
2792
|
+
${qe}
|
|
2796
2793
|
<span class="__crossx-addr-pill-text">${Q(i.from)}</span>
|
|
2797
2794
|
</div>
|
|
2798
2795
|
<p class="__crossx-warning">${w((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
|
|
@@ -2806,11 +2803,11 @@ button.__crossx-connect-other-block:active {
|
|
|
2806
2803
|
</div>
|
|
2807
2804
|
</div>
|
|
2808
2805
|
</div>
|
|
2809
|
-
`,p}const
|
|
2806
|
+
`,p}const os=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
2810
2807
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
2811
2808
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
2812
|
-
</svg>`,
|
|
2813
|
-
${
|
|
2809
|
+
</svg>`,ns='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="var(--cx-primary, #00ceb2)"/><path d="M7.5 12.5L10.5 15.5L16.5 8.5" stroke="var(--cx-on-primary, #000)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function At(i){return i.name||`Account ${i.index+1}`}function as(){return`<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect width="32" height="32" rx="16" fill="#121212" fill-opacity="0.1"/><g fill="#121212" fill-opacity="0.5">${vt}</g></svg>`}const cs=He().portraitBaseUrl;function ls(i,e){const r=e.replace("#","");return`${cs}/portrait/evm/${i}.png?size=256&bg=${r}`}function It(i,e,r){const t=ls(i,r),o=as().replace(/"/g,""");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${t}" alt="" onerror="this.style.display='none';this.nextElementSibling.innerHTML='${o}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function ds(i,e,r,t){const s=r==null?void 0:r.toLowerCase(),o=i.map(a=>{const l=s&&a.address.toLowerCase()===s,p=l?" __crossx-wallet-item--selected":"",_=l?`<span class="__crossx-wallet-selected">${w((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${ns}</span>`:"";return`<button class="__crossx-wallet-item${p}" data-wallet-index="${a.index}" data-wallet-address="${w(a.address)}">
|
|
2810
|
+
${It(a.address,a.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${w(At(a))}</span><span class="__crossx-wallet-addr">${ft(a.address)}</span></span>${_}
|
|
2814
2811
|
</button>`}).join(""),n=document.createElement("div");return n.id=$,n.className="__crossx-overlay--wallet-selector",n.innerHTML=`
|
|
2815
2812
|
<div class="__crossx-card __crossx-card--wallet-selector" style="${H(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2816
2813
|
<div class="__crossx-header">
|
|
@@ -2828,7 +2825,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2828
2825
|
${o}
|
|
2829
2826
|
</div>
|
|
2830
2827
|
<button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
|
|
2831
|
-
<span class="__crossx-wallet-add-icon">${
|
|
2828
|
+
<span class="__crossx-wallet-add-icon">${os}</span>
|
|
2832
2829
|
<span class="__crossx-wallet-add-label">${w((t==null?void 0:t.wallet_selector_add_button)??"Add Wallet")}</span>
|
|
2833
2830
|
</button>
|
|
2834
2831
|
<p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>
|
|
@@ -2841,28 +2838,28 @@ button.__crossx-connect-other-block:active {
|
|
|
2841
2838
|
</div>
|
|
2842
2839
|
</div>
|
|
2843
2840
|
</div>
|
|
2844
|
-
`,n}function
|
|
2841
|
+
`,n}function ps(i,e){const r=document.createElement("div");r.id=$;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",Kr(t,i),t.role="dialog",t.ariaModal="true",t.setAttribute("aria-labelledby","__crossx-ttl");const s=document.createElement("div");s.className="__crossx-header";const o=document.createElement("span");o.className="__crossx-wallet-created-sheet-handle",o.ariaHidden="true";const n=document.createElement("p");n.className="__crossx-title",n.id="__crossx-ttl",n.style.paddingRight="48px",n.textContent=(e==null?void 0:e.wallet_created_title)??"Wallet Created!";const a=document.createElement("button");a.className="__crossx-close",a.id="__crossx-close-btn",a.type="button",a.ariaLabel="Close",a.innerHTML=B,s.append(o,n,a);const l=document.createElement("hr");l.className="__crossx-divider";const p=document.createElement("div");p.className="__crossx-wallet-created-body";const _=document.createElement("div");_.className="__crossx-wallet-created-hero";const u=document.createElement("span");u.className="__crossx-wallet-created-illust",u.ariaHidden="true";const x=m=>{const y=document.createElement("span");return y.className=m,y};u.append(x("__crossx-wallet-created-shadow"),x("__crossx-wallet-created-wallet"),x("__crossx-wallet-created-coin"),x("__crossx-wallet-created-burst"),x("__crossx-wallet-created-pointer"),x("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--purple"),x("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--teal"),x("__crossx-wallet-created-dot __crossx-wallet-created-dot--one"),x("__crossx-wallet-created-dot __crossx-wallet-created-dot--two")),_.appendChild(u),p.appendChild(_);const g=document.createElement("div");g.className="__crossx-wallet-created-footer";const f=document.createElement("button");return f.className="__crossx-wallet-created-btn",f.id="__crossx-wallet-created-done",f.type="button",f.textContent=(e==null?void 0:e.wallet_created_button)??"Got it",g.appendChild(f),t.append(s,l,p,g),r.appendChild(t),r}const _s=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2845
2842
|
<path d="M26.693 21.193c-.028-3.168 2.587-4.712 2.706-4.786-1.477-2.16-3.77-2.454-4.58-2.484-1.944-.197-3.804 1.148-4.793 1.148-.992 0-2.52-1.12-4.147-1.09-2.13.032-4.1 1.239-5.198 3.133-2.222 3.855-.569 9.562 1.593 12.69 1.061 1.535 2.318 3.258 3.975 3.196 1.6-.064 2.2-1.03 4.133-1.03 1.928 0 2.48 1.03 4.172.997 1.72-.03 2.806-1.56 3.862-3.1 1.211-1.779 1.713-3.495 1.74-3.583-.037-.017-3.427-1.316-3.463-5.09z" fill="currentColor"/>
|
|
2846
2843
|
<path d="M23.527 11.876c.877-1.065 1.471-2.545 1.31-4.024-1.266.053-2.807.845-3.718 1.907-.813.946-1.53 2.468-1.34 3.915 1.41.107 2.852-.716 3.748-1.798z" fill="currentColor"/>
|
|
2847
|
-
</svg>`,
|
|
2844
|
+
</svg>`,hs=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2848
2845
|
<path d="M38.06 20.44c0-1.34-.12-2.63-.34-3.87H20.5v7.32h9.84c-.42 2.28-1.71 4.21-3.65 5.51v4.57h5.91c3.46-3.19 5.46-7.88 5.46-13.53z" fill="#4285F4"/>
|
|
2849
2846
|
<path d="M20.5 38.5c4.94 0 9.09-1.64 12.12-4.44l-5.91-4.57c-1.64 1.1-3.73 1.75-6.21 1.75-4.77 0-8.82-3.22-10.26-7.55H4.16v4.72A18.49 18.49 0 0 0 20.5 38.5z" fill="#34A853"/>
|
|
2850
2847
|
<path d="M10.24 23.69A11.16 11.16 0 0 1 9.66 20c0-1.28.22-2.52.58-3.69v-4.72H4.16A18.49 18.49 0 0 0 2 20c0 2.97.71 5.78 1.97 8.28l6.27-4.59z" fill="#FBBC05"/>
|
|
2851
2848
|
<path d="M20.5 8.76c2.69 0 5.1.92 7 2.73l5.24-5.24C29.58 3.36 25.43 1.5 20.5 1.5A18.49 18.49 0 0 0 4.16 11.59l6.08 4.72C11.68 11.98 15.73 8.76 20.5 8.76z" fill="#EA4335"/>
|
|
2852
|
-
</svg>`;function
|
|
2849
|
+
</svg>`;function us(i){const e=ht(i);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Ur[i]??""}</span><span class="__crossx-connect-other-wallet-name">${w(e)}</span></span>`}function xs(i){if(i.length===0)return"";const e=s=>us(i[s]),r="Supported wallets include ";if(i.length===1)return`${r}${e(0)}.`;if(i.length===2)return`${r}${e(0)} and ${e(1)}.`;if(i.length===3)return`${r}${e(0)}, ${e(1)} and ${e(2)}.`;const t=i.length-3;return`${r}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function gs(i,e=[],r){const t=i,s=w(String(e[0])),o=w((r==null?void 0:r.login_selector_or)??"or"),n=e.length>0?`
|
|
2853
2850
|
<div class="__crossx-login-or-divider">
|
|
2854
2851
|
<hr><span>${o}</span><hr>
|
|
2855
2852
|
</div>
|
|
2856
2853
|
<button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${s}" aria-labelledby="__crossx-connect-other-heading">
|
|
2857
2854
|
<span class="__crossx-connect-other-text">
|
|
2858
2855
|
<span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">${w((r==null?void 0:r.login_selector_connect_other_wallets)??"Connect with Other Wallets")}</span>
|
|
2859
|
-
<span class="__crossx-connect-other-desc __crossx-connect-other-summary">${
|
|
2856
|
+
<span class="__crossx-connect-other-desc __crossx-connect-other-summary">${xs(e)}</span>
|
|
2860
2857
|
</span>
|
|
2861
2858
|
</button>`:"",a=document.createElement("div");return a.id=$,a.innerHTML=`
|
|
2862
2859
|
<div class="__crossx-card __crossx-card--migration" style="${H(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2863
2860
|
<div class="__crossx-header">
|
|
2864
2861
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
2865
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${w((r==null?void 0:r.login_selector_title)??
|
|
2862
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${w((r==null?void 0:r.login_selector_title)??Ee)}</p>
|
|
2866
2863
|
<p class="__crossx-subtitle">${w((r==null?void 0:r.login_selector_subtitle)??"Sign in instantly with your social account")}</p>
|
|
2867
2864
|
</div>
|
|
2868
2865
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${B}</button>
|
|
@@ -2871,11 +2868,11 @@ button.__crossx-connect-other-block:active {
|
|
|
2871
2868
|
<div class="__crossx-body">
|
|
2872
2869
|
<div class="__crossx-login-btn-row">
|
|
2873
2870
|
<button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
|
|
2874
|
-
<span class="__crossx-login-icon" style="color:var(--cx-value);">${
|
|
2871
|
+
<span class="__crossx-login-icon" style="color:var(--cx-value);">${_s}</span>
|
|
2875
2872
|
<span class="__crossx-login-btn-label">${w((r==null?void 0:r.login_selector_apple)??"Sign in with Apple")}</span>
|
|
2876
2873
|
</button>
|
|
2877
2874
|
<button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
|
|
2878
|
-
<span class="__crossx-login-icon">${
|
|
2875
|
+
<span class="__crossx-login-icon">${hs}</span>
|
|
2879
2876
|
<span class="__crossx-login-btn-label">${w((r==null?void 0:r.login_selector_google)??"Sign in with Google")}</span>
|
|
2880
2877
|
</button>
|
|
2881
2878
|
</div>${n}
|
|
@@ -2884,7 +2881,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2884
2881
|
</p>
|
|
2885
2882
|
</div>
|
|
2886
2883
|
</div>
|
|
2887
|
-
`,a}function
|
|
2884
|
+
`,a}function fs(i,e){const r=i,t=document.createElement("div");t.id=$;const s=w(e.message).replace(/\n/g,"<br>"),o=e.email?`<div class="__crossx-session-account-card">
|
|
2888
2885
|
<p class="__crossx-session-account-label">${w(e.accountLabel)}</p>
|
|
2889
2886
|
<p class="__crossx-session-account-email">${w(e.email)}</p>
|
|
2890
2887
|
</div>`:"";return t.innerHTML=`
|
|
@@ -2906,7 +2903,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2906
2903
|
</div>
|
|
2907
2904
|
</div>
|
|
2908
2905
|
</div>
|
|
2909
|
-
`,t}function
|
|
2906
|
+
`,t}function ws(i,e=!0){const r=i,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${B}</button>`:"",s=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",o=document.createElement("div");return o.id=$,o.innerHTML=`
|
|
2910
2907
|
<div class="__crossx-card __crossx-card--migration" style="${H(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2911
2908
|
<div class="__crossx-header">
|
|
2912
2909
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -2920,13 +2917,13 @@ button.__crossx-connect-other-block:active {
|
|
|
2920
2917
|
<p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
|
|
2921
2918
|
</div>
|
|
2922
2919
|
<button class="__crossx-recover-btn" id="__crossx-recover-btn">
|
|
2923
|
-
<span class="__crossx-recover-icon">${
|
|
2920
|
+
<span class="__crossx-recover-icon">${$r}</span>
|
|
2924
2921
|
<span class="__crossx-recover-label">Import from Social Backup</span>
|
|
2925
2922
|
</button>
|
|
2926
2923
|
${s}
|
|
2927
2924
|
</div>
|
|
2928
2925
|
</div>
|
|
2929
|
-
`,o}function
|
|
2926
|
+
`,o}function ms(i,e){const r=i,{errorMessage:t,attemptCount:s,maxAttempts:o=5}=e??{},n=!!t,a=n?" --error":"",l=s!=null&&s>0?`<p class="__crossx-pin-attempt">${s}/${o}</p>`:"",p=s!=null&&s>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",_=n?`<p class="__crossx-pin-error-text">${t}</p>`:"",u=document.createElement("div");return u.id=$,u.innerHTML=`
|
|
2930
2927
|
<div class="__crossx-card __crossx-card--migration" style="${H(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2931
2928
|
<div class="__crossx-header">
|
|
2932
2929
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2943,10 +2940,10 @@ button.__crossx-connect-other-block:active {
|
|
|
2943
2940
|
<input class="__crossx-pin-input${a}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off">
|
|
2944
2941
|
</div>
|
|
2945
2942
|
<p class="__crossx-pin-hint">Enter your 4-digit PIN to recover your wallet.</p>
|
|
2946
|
-
${
|
|
2943
|
+
${_}
|
|
2947
2944
|
</div>
|
|
2948
2945
|
</div>
|
|
2949
|
-
`,u}function
|
|
2946
|
+
`,u}function ys(i){const e=new Date(i),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=r[e.getDay()],o=t[e.getMonth()],n=e.getDate(),a=String(e.getHours()).padStart(2,"0"),l=String(e.getMinutes()).padStart(2,"0");return`${s}, ${o} ${n} ${a}:${l}`}function bs(i,e,r){const t=i,s=e<=0,o=s?null:Date.now()+e*1e3,n=o?ys(o):null,a=document.createElement("div");return a.id=$,a.innerHTML=`
|
|
2950
2947
|
<div class="__crossx-card __crossx-card--migration" style="${H(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2951
2948
|
<div class="__crossx-header">
|
|
2952
2949
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2966,9 +2963,9 @@ button.__crossx-connect-other-block:active {
|
|
|
2966
2963
|
</div>
|
|
2967
2964
|
</div>
|
|
2968
2965
|
</div>
|
|
2969
|
-
`,{overlay:a,startCountdown:p=>{if(s||!o)return()=>{};const u=setInterval(()=>{Date.now()>=o&&(clearInterval(u),p())},1e3);return()=>clearInterval(u)}}}function
|
|
2966
|
+
`,{overlay:a,startCountdown:p=>{if(s||!o)return()=>{};const u=setInterval(()=>{Date.now()>=o&&(clearInterval(u),p())},1e3);return()=>clearInterval(u)}}}function vs(i){const r=[i.check1,i.check2].map((t,s)=>`
|
|
2970
2967
|
<div class="__crossx-pw-notice-item" data-check-index="${s}" role="checkbox" aria-checked="false" tabindex="0">
|
|
2971
|
-
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${s}">${
|
|
2968
|
+
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${s}">${Is}</div>
|
|
2972
2969
|
<span class="__crossx-pw-notice-item-text">${w(t)}</span>
|
|
2973
2970
|
</div>
|
|
2974
2971
|
`).join("");return`
|
|
@@ -2983,7 +2980,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2983
2980
|
<div class="__crossx-pw-fields __crossx-pw-fields--notice">
|
|
2984
2981
|
<div class="__crossx-pw-notice-header">
|
|
2985
2982
|
<div class="__crossx-pw-notice-title-row">
|
|
2986
|
-
<span class="__crossx-pw-notice-icon">${
|
|
2983
|
+
<span class="__crossx-pw-notice-icon">${ks}</span>
|
|
2987
2984
|
<p class="__crossx-pw-notice-title">${w(i.noticeTitle)}</p>
|
|
2988
2985
|
</div>
|
|
2989
2986
|
<p class="__crossx-pw-notice-desc">${w(i.noticeDesc)}</p>
|
|
@@ -3001,30 +2998,30 @@ button.__crossx-connect-other-block:active {
|
|
|
3001
2998
|
</button>
|
|
3002
2999
|
</div>
|
|
3003
3000
|
<div class="__crossx-home-indicator"></div>
|
|
3004
|
-
`}function
|
|
3005
|
-
${
|
|
3001
|
+
`}function Le(i){const e=!!i.lockExpiresAt&&i.lockExpiresAt>Date.now(),r=i.lockExpiresAt?` data-lock-expires="${i.lockExpiresAt}"`:"",t=i.headerSubtitle?`<p class="__crossx-pin6-header-sub">${w(i.headerSubtitle)}</p>`:"",s=i.subtitle?`<p class="__crossx-pin6-subtitle">${w(i.subtitle)}</p>`:"",o=i.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${w(i.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',n=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
3002
|
+
${kt}
|
|
3006
3003
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
3007
|
-
</p>`:"",a=i.warningMessage&&i.attemptCount!=null&&i.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${w(i.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',l=i.attemptCount!=null&&i.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${i.attemptCount}/${i.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',p=e?" --locked":"",
|
|
3004
|
+
</p>`:"",a=i.warningMessage&&i.attemptCount!=null&&i.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${w(i.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',l=i.attemptCount!=null&&i.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${i.attemptCount}/${i.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',p=e?" --locked":"",_=Array.from({length:6},(m,y)=>`<input class="__crossx-pin6-box${p}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" aria-label="PIN digit ${y+1}"${e?" disabled":""}>`).join(""),u=e?" --locked":"",x=Array.from({length:6},(m,y)=>`<div class="__crossx-pin6-dot${u}" data-dot-index="${y}" aria-label="PIN digit ${y+1}"></div>`).join(""),g=e?" --disabled":"",f=`
|
|
3008
3005
|
<div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
|
|
3009
3006
|
<div class="__crossx-pin6-numpad-row">
|
|
3010
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3011
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3012
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3007
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="1">1</button>
|
|
3008
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="2">2</button>
|
|
3009
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="3">3</button>
|
|
3013
3010
|
</div>
|
|
3014
3011
|
<div class="__crossx-pin6-numpad-row">
|
|
3015
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3016
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3017
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3012
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="4">4</button>
|
|
3013
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="5">5</button>
|
|
3014
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="6">6</button>
|
|
3018
3015
|
</div>
|
|
3019
3016
|
<div class="__crossx-pin6-numpad-row">
|
|
3020
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3021
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3022
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3017
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="7">7</button>
|
|
3018
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="8">8</button>
|
|
3019
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="9">9</button>
|
|
3023
3020
|
</div>
|
|
3024
3021
|
<div class="__crossx-pin6-numpad-row">
|
|
3025
3022
|
<button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
|
|
3026
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
3027
|
-
<button type="button" class="__crossx-pin6-numpad-key --delete${
|
|
3023
|
+
<button type="button" class="__crossx-pin6-numpad-key${g}" data-key="0">0</button>
|
|
3024
|
+
<button type="button" class="__crossx-pin6-numpad-key --delete${g}" data-key="backspace" aria-label="Delete">${As}</button>
|
|
3028
3025
|
</div>
|
|
3029
3026
|
</div>`;return`
|
|
3030
3027
|
<div class="__crossx-header">
|
|
@@ -3037,9 +3034,9 @@ button.__crossx-connect-other-block:active {
|
|
|
3037
3034
|
<div class="__crossx-pin6-body"${r}>
|
|
3038
3035
|
${s}
|
|
3039
3036
|
<div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
|
|
3040
|
-
${
|
|
3037
|
+
${_}
|
|
3041
3038
|
<div class="__crossx-pin6-dots" id="__crossx-pin6-dots">
|
|
3042
|
-
${
|
|
3039
|
+
${x}
|
|
3043
3040
|
</div>
|
|
3044
3041
|
</div>
|
|
3045
3042
|
${o}
|
|
@@ -3048,20 +3045,20 @@ button.__crossx-connect-other-block:active {
|
|
|
3048
3045
|
${n}
|
|
3049
3046
|
</div>
|
|
3050
3047
|
${f}
|
|
3051
|
-
`}function
|
|
3048
|
+
`}function pt(i,e){const r=document.createElement("div");return r.id=$,r.innerHTML=`
|
|
3052
3049
|
<div class="__crossx-card __crossx-card--pin6" style="${H(i)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
3053
3050
|
${e}
|
|
3054
3051
|
</div>
|
|
3055
|
-
`,r}function
|
|
3052
|
+
`,r}function Ss(i,e){if(i.length!==6)return e.tooShort;if(!/^\d+$/.test(i))return e.numbersOnly;if(/(.)\1{2}/.test(i))return e.repeatingDigit;const r=i.split("").map(Number),t=r.every((o,n)=>n===0||o===(r[n-1]+1)%10),s=r.every((o,n)=>n===0||o===(r[n-1]+9)%10);return t||s?e.sequential:i[0]!==i[1]&&i===i.slice(0,2).repeat(3)?e.alternatingPattern:null}function Es(i){const e=Math.max(0,Math.ceil(i/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),s=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(s).padStart(2,"0")}`}function De(i,e,r,t,s,o,n){var Ve,je;let a=!!(o&&o>Date.now()),l=!1;const p=()=>Array.from(i.querySelectorAll(".__crossx-pin6-box")),_=()=>i.querySelector("#__crossx-pin6-boxes"),u=()=>i.querySelector("#__crossx-pin6-error"),x=()=>i.querySelector("#__crossx-pin6-lock-msg"),g=()=>i.querySelector("#__crossx-pin6-lock-countdown"),f=()=>i.querySelector(".__crossx-pin6-body"),m="●",y=(b,v)=>{b.dataset.digit=v,b.value=m},S=b=>{delete b.dataset.digit,b.value=""},E=b=>b.dataset.digit??"",A=()=>p().map(E).join(""),k=()=>Array.from(i.querySelectorAll(".__crossx-pin6-dot")),T=()=>{var I;const b=p(),v=k();if(v.length&&(v.forEach((R,O)=>{const M=!!(b[O]&&E(b[O]));R.classList.toggle("--filled",M),R.classList.toggle("--active",!1)}),!a&&!l)){const R=b.findIndex(M=>!E(M));(I=v[R===-1?5:R])==null||I.classList.add("--active")}},N=()=>{i.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(v=>v.classList.toggle("--disabled",a)),k().forEach(v=>v.classList.toggle("--locked",a)),T()},U=b=>{a=b,p().forEach(v=>{v.disabled=b,v.classList.toggle("--locked",b)})},P=()=>i.querySelector("#__crossx-pin6-attempt"),z=()=>{const b=u();b&&(b.textContent="")},q=()=>n??"Your account will be locked after further failures.",C=()=>i.querySelector("#__crossx-pin6-warning"),L=b=>{var I;let v=C();if(!v){v=document.createElement("p"),v.className="__crossx-pin6-warning",v.id="__crossx-pin6-warning";const R=u();R?R.insertAdjacentElement("afterend",v):(I=f())==null||I.appendChild(v)}v.textContent=b},W=()=>{const b=C();b&&(b.textContent="")},ne=(b,v)=>{var R;let I=P();if(!I){I=document.createElement("p"),I.className="__crossx-pin6-attempt",I.id="__crossx-pin6-attempt";const O=C()??u();O?O.insertAdjacentElement("afterend",I):(R=f())==null||R.appendChild(I)}I.textContent=`${b}/${v}`},ae=()=>{const b=P();b&&(b.textContent="")},ge=b=>{const v=u();v&&(v.textContent=b);const I=_();I==null||I.classList.add("--shake"),setTimeout(()=>I==null?void 0:I.classList.remove("--shake"),500),p().forEach(S),setTimeout(()=>{var R;(R=p()[0])==null||R.focus(),T()},50)},ce=b=>{var M;U(!0),p().forEach(S),N();const v=u();if(v&&(v.textContent="Too many failed attempts. Please wait."),!x()){const F=document.createElement("p");F.className="__crossx-pin6-lock-msg",F.id="__crossx-pin6-lock-msg",F.innerHTML=`${kt}<span id="__crossx-pin6-lock-countdown"></span>`;const V=u();V?V.insertAdjacentElement("afterend",F):(M=f())==null||M.appendChild(F)}const I=()=>{var ee;const F=b-Date.now(),V=g();F<=0?(clearInterval(R),U(!1),(ee=x())==null||ee.remove(),v&&(v.textContent=""),N(),setTimeout(()=>{var fe;return(fe=p()[0])==null?void 0:fe.focus()},50)):V&&(V.textContent=` ${Es(F)}`)},R=setInterval(I,1e3);I();const O=new MutationObserver(()=>{document.contains(i)||(clearInterval(R),O.disconnect())});O.observe(document.body,{childList:!0,subtree:!1})},ke=async()=>{if(a||l)return;const b=A();if(b.length===6){l=!0,p().forEach(v=>{v.disabled=!0});try{if(s){const v=await s(b);v.ok?e(b):v.lockExpiresAt?(ae(),ce(v.lockExpiresAt)):(ge(v.error??"Incorrect PIN. Please try again."),v.attemptCount!=null&&v.maxAttempts!=null?(L(q()),ne(v.attemptCount,v.maxAttempts)):(W(),ae()))}else e(b)}catch(v){t&&t(v)}finally{l=!1,a||p().forEach(v=>{v.disabled=!1}),T()}}};o&&o>Date.now()?ce(o):setTimeout(()=>{var b;return(b=p()[0])==null?void 0:b.focus()},100);const ze=()=>{if(a||l)return;const b=p(),v=b.find(I=>!E(I))??b[b.length-1];v==null||v.focus()};(Ve=_())==null||Ve.addEventListener("click",b=>{b.target.classList.contains("__crossx-pin6-box")||ze()}),(je=f())==null||je.addEventListener("click",b=>{const v=b.target;v.classList.contains("__crossx-pin6-box")||v.closest("button")||ze()}),p().forEach((b,v)=>{b.addEventListener("input",()=>{var R;const I=b.value.replace(/\D/g,"").slice(-1);I?y(b,I):S(b),z(),I&&v<5&&((R=p()[v+1])==null||R.focus()),T(),A().length===6&&setTimeout(ke,80)}),b.addEventListener("keydown",I=>{var R,O;if(I.key==="Backspace"){if(I.preventDefault(),E(b))S(b);else if(v>0){const M=p()[v-1];S(M),M.focus()}T()}else I.key==="ArrowLeft"&&v>0?(I.preventDefault(),(R=p()[v-1])==null||R.focus()):I.key==="ArrowRight"&&v<5?(I.preventDefault(),(O=p()[v+1])==null||O.focus()):I.key==="Escape"&&r()}),b.addEventListener("paste",I=>{var M,F;I.preventDefault();const R=(((M=I.clipboardData)==null?void 0:M.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!R)return;const O=p();R.split("").forEach((V,ee)=>{O[ee]&&y(O[ee],V)}),(F=O[Math.min(R.length-1,5)])==null||F.focus(),z(),T(),A().length===6&&setTimeout(ke,80)}),b.addEventListener("focus",()=>b.select())});const he=i.querySelector("#__crossx-pin6-numpad");if(he){let b=null;const v=()=>{b&&(b.classList.remove("--pressed"),b=null)};he.addEventListener("pointerdown",R=>{const O=R.target.closest(".__crossx-pin6-numpad-key");!O||a||l||(v(),b=O,O.classList.add("--pressed"),O.setPointerCapture(R.pointerId))});const I=R=>{const O=R.dataset.key;if(!O)return;if(O==="backspace"){const ee=[...p()].reverse().find(fe=>E(fe));ee&&(S(ee),z()),T();return}if(!/^\d$/.test(O))return;const F=p().find(V=>!E(V));F&&(y(F,O),z(),T(),A().length===6&&setTimeout(ke,80))};he.addEventListener("pointerup",R=>{if(!b)return;const O=b;v();const M=O.getBoundingClientRect();R.clientX>=M.left&&R.clientX<=M.right&&R.clientY>=M.top&&R.clientY<=M.bottom&&!a&&!l&&I(O)}),he.addEventListener("pointercancel",v),he.addEventListener("pointerleave",v,!0),T(),o&&o>Date.now()&&N()}}const As=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
3056
3053
|
<path d="M7.36 0.5H19.5C20.6046 0.5 21.5 1.39543 21.5 2.5V14.5C21.5 15.6046 20.6046 16.5 19.5 16.5H7.36C6.76 16.5 6.19 16.24 5.8 15.79L0.94 10.02C0.35 9.32 0.35 8.3 0.94 7.6L5.8 1.71C6.19 1.26 6.76 0.5 7.36 0.5Z" stroke="currentColor" stroke-width="1.2" fill="none"/>
|
|
3057
3054
|
<line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
3058
3055
|
<line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
3059
|
-
</svg>`,
|
|
3056
|
+
</svg>`,kt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
3060
3057
|
<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"/>
|
|
3061
|
-
</svg>`,
|
|
3058
|
+
</svg>`,Is=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
3062
3059
|
<path d="M1 4.5L4 7.5L10 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
3063
|
-
</svg>`,
|
|
3060
|
+
</svg>`,ks=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
3064
3061
|
<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"/>
|
|
3065
|
-
</svg>`;function Ss(i,e,r){var o;const t=i.querySelectorAll(".__crossx-pin-input");t.forEach((n,a)=>{n.addEventListener("input",()=>{const l=n.value.replace(/\D/g,"");n.value=l?l[0]:"",l&&a<3&&t[a+1].focus();const p=Array.from(t).map(h=>h.value).join("");p.length===4&&setTimeout(()=>e(p),200)}),n.addEventListener("keydown",l=>{l.key==="Backspace"&&!n.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),l.key==="Escape"&&r()}),n.addEventListener("keypress",l=>{/[0-9]/.test(l.key)||l.preventDefault()}),n.addEventListener("paste",l=>{var u;l.preventDefault();const p=(((u=l.clipboardData)==null?void 0:u.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!p)return;p.split("").forEach((g,x)=>{t[x]&&(t[x].value=g)});const h=Math.min(p.length,3);t[h].focus(),p.length===4&&setTimeout(()=>e(p),200)})});const s=i.querySelector(".__crossx-pin-inputs");s==null||s.addEventListener("click",n=>{if(!n.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(l=>!l.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class vs{constructor(e="light",r,t=Be,s){this.theme=e,this.overrides=r,this.tokens=it(e,r),this.displayDecimals=t,this.pinKeyboard=s}setPinKeyboard(e){this.pinKeyboard=e}resolvePinKeyboardMode(){const e=this.pinKeyboard;if(typeof e=="function")try{return e()==="native"?"native":"virtual"}catch{return"virtual"}return e==="native"?"native":"virtual"}applyPinKeyboardMode(e){e&&e.classList.toggle("--native-keypad",this.resolvePinKeyboardMode()==="native")}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=it(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((s,o)=>{var E;G();const n=[...e],a=is(n,this.tokens,t,this.messages),l=re();K(a);let p=!1;const h=()=>{p||(p=!0,a.remove(),l())};let u=null;const g=A=>{h(),s(A)},x=()=>{h(),u?o(u):s(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(A=>{A.addEventListener("click",()=>{const I=A.dataset.walletAddress??"",T=parseInt(A.dataset.walletIndex??"0",10),C=n.find(U=>U.index===T);g({address:I,index:T,name:C==null?void 0:C.name})})})})();const m=a.querySelector("#__crossx-add-wallet-error"),y=a.querySelector("#__crossx-add-wallet-btn");y&&y.addEventListener("click",async()=>{y.disabled=!0,m&&(m.hidden=!0,m.textContent="");try{const A=await r();n.push(A);const I=a.querySelector("#__crossx-wallet-list");if(I){const T=document.createElement("button");T.className="__crossx-wallet-item",T.dataset.walletIndex=String(A.index),T.dataset.walletAddress=A.address,T.innerHTML=`${bt(A.address,A.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${w(yt(A))}</span><span class="__crossx-wallet-addr">${ht(A.address)}</span></span>`,T.addEventListener("click",()=>g(A)),I.appendChild(T);try{T.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}y.disabled=!1}catch(A){const I=A instanceof _&&A.code===d.ADDRESS_LIMIT_EXCEEDED,T=this.resolveAddWalletErrorMessage(A);m&&(m.textContent=T,m.hidden=!1),I?(y.disabled=!0,y.setAttribute("aria-disabled","true")):y.disabled=!1,u=A}}),(E=a.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",x),a.addEventListener("click",A=>{A.target===a&&x()});const v=A=>{A.key==="Escape"&&(document.removeEventListener("keydown",v),x())};document.addEventListener("keydown",v)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,l;G();const r=os(this.tokens,this.messages),t=re();K(r);let s=!1,o=null;const n=()=>{s||(s=!0,o&&document.removeEventListener("keydown",o),r.remove(),t(),e())};(a=r.querySelector("#__crossx-wallet-created-done"))==null||a.addEventListener("click",n),(l=r.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),r.addEventListener("click",p=>{p.target===r&&n()}),o=p=>{p.key==="Escape"&&n()},document.addEventListener("keydown",o)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof _&&e.code===d.ADDRESS_LIMIT_EXCEEDED){const s=e.details,o=typeof(s==null?void 0:s.limit)=="number"?s.limit:ye;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(o))}return(r==null?void 0:r.wallet_selector_add_error_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const r=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(s=>Object.values(pe).includes(s)&&String(s).trim()!==""))??[];return new Promise(s=>{var g,x,f,m;G();const o=ds(this.tokens,r,this.messages),n=re();K(o);const a=()=>{o.remove(),n()},l=y=>{a(),s({type:"oauth",provider:y})},p=y=>{a(),s({type:"external",walletId:y})},h=()=>{a(),s(null)};(g=o.querySelector("#__crossx-apple-btn"))==null||g.addEventListener("click",()=>l("apple")),(x=o.querySelector("#__crossx-google-btn"))==null||x.addEventListener("click",()=>l("google")),(f=o.querySelector("#__crossx-connect-other-wallet-btn"))==null||f.addEventListener("click",y=>{const E=y.currentTarget.dataset.walletId??"";E&&p(E)}),(m=o.querySelector("#__crossx-close-btn"))==null||m.addEventListener("click",h),o.addEventListener("click",y=>{y.target===o&&h()}),o.querySelectorAll(".__crossx-login-terms-link").forEach(y=>{y.addEventListener("click",v=>v.stopPropagation())});const u=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",u),h())};document.addEventListener("keydown",u)})}showSessionAlert(e){return new Promise(r=>{var h,u,g;G();const t=this.messages,s=ps(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.session_alert_account_label)??"Account",signOutLabel:(t==null?void 0:t.session_alert_sign_out_button)??"Sign out",signInAgainLabel:(t==null?void 0:t.session_alert_sign_in_again_button)??"Sign in again"}),o=re();K(s);let n=!1;const a=()=>{n||(n=!0,s.remove(),o())},l=()=>{a(),r("signout")},p=()=>{a(),r("signin-again")};(h=s.querySelector("#__crossx-session-signout"))==null||h.addEventListener("click",l),(u=s.querySelector("#__crossx-session-signin"))==null||u.addEventListener("click",p),(g=s.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",l)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,l,p;G();const s=_s(this.tokens,r);K(s);const o=()=>s.remove(),n=()=>{o(),t("recover")};if((a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),r){const h=()=>{o(),t("skip")};(l=s.querySelector("#__crossx-skip-btn"))==null||l.addEventListener("click",h),(p=s.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",h),s.addEventListener("click",g=>{g.target===s&&h()});const u=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",u),h())};document.addEventListener("keydown",u)}})}showPinSetupPrompt(e){return new Promise(r=>{G();const t=this.messages,s={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_notice_header_subtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pin_notice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pin_notice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pin_notice_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.pin_notice_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.pin_notice_next_button)??"Next",submitButton:(t==null?void 0:t.pin_notice_submit_button)??"I Understand"},o={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pin_setup_mismatch_error)??"PINs do not match. Please try again."},n={title:(t==null?void 0:t.pin_setup_confirm_title)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_confirm_subtitle)??"Confirm your 6-digit PIN"},a=nt(this.tokens,gs(s)),l=re();K(a);let p=!1;const h=()=>{p||(p=!0,a.remove(),l())},u=E=>{h(),r(E)},g=()=>{h(),r(null)},x=a.querySelector(".__crossx-card"),f={tooShort:(t==null?void 0:t.pin_validation_too_short)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pin_validation_numbers_only)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pin_validation_repeating_digit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pin_validation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pin_validation_alternating_pattern)??"Repeating patterns (e.g., 121212) are not allowed."},m=E=>{var A;x.innerHTML=Ne({title:n.title,headerSubtitle:n.headerSubtitle,subtitle:n.subtitle}),this.applyPinKeyboardMode(x),(A=x.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",g),Oe(x,I=>{I===E?u(E):y(o.mismatchError)},g)},y=E=>{var A;x.innerHTML=Ne({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:E}),this.applyPinKeyboardMode(x),(A=x.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",g),Oe(x,I=>{const T=fs(I,f);T?y(T):m(I)},g)};(()=>{var q;const E=Array.from(x.querySelectorAll(".__crossx-pw-notice-item")),A=x.querySelector("#__crossx-pin-notice-next"),I=new Set;A.removeAttribute("disabled");const T=A.dataset.nextLabel??"Next",C=A.dataset.submitLabel??"I Understand",U=()=>{const P=I.size===E.length;A.classList.toggle("--disabled",!P),A.textContent=C||T},N=(P,L)=>{if(I.has(L))return;const W=P.querySelector(`#__crossx-notice-check-${L}`);I.add(L),W.classList.add("--checked"),P.setAttribute("aria-checked","true"),U()},z=(P,L)=>{if(!I.has(L))return;const W=P.querySelector(`#__crossx-notice-check-${L}`);I.delete(L),W.classList.remove("--checked"),P.setAttribute("aria-checked","false"),U()};E.forEach(P=>{const L=parseInt(P.dataset.checkIndex??"0",10);P.addEventListener("click",()=>{I.has(L)?z(P,L):N(P,L)}),P.addEventListener("keydown",W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),I.has(L)?z(P,L):N(P,L))})}),A.addEventListener("click",()=>{if(I.size===E.length){y(e==null?void 0:e.errorMessage);return}const P=E.find(W=>{const ne=parseInt(W.dataset.checkIndex??"0",10);return!I.has(ne)});if(!P)return;const L=parseInt(P.dataset.checkIndex??"0",10);P.scrollIntoView({behavior:"smooth",block:"nearest"}),P.classList.add("--highlight"),setTimeout(()=>{P.classList.remove("--highlight"),N(P,L)},400)}),(q=x.querySelector("#__crossx-close-btn"))==null||q.addEventListener("click",g)})(),a.addEventListener("click",E=>{E.target===a&&g()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var v;G();const s=this.messages,o=(e==null?void 0:e.verifyMode)===!0,n=o?(s==null?void 0:s.verify_pin_title)??"Verify Your PIN":(s==null?void 0:s.pin_input_title)??"Enter PIN",a=o?(s==null?void 0:s.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(s==null?void 0:s.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",l=(s==null?void 0:s.pin_locked_failure_warning)??"Your account will be locked after further failures.",p=nt(this.tokens,Ne({title:n,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:l,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),h=re();K(p);let u=!1;const g=()=>{u||(u=!0,p.remove(),h())},x=E=>{g(),r(E)},f=()=>{g(),r(null)},m=E=>{g(),t(E)},y=p.querySelector(".__crossx-card");this.applyPinKeyboardMode(y),(v=y.querySelector("#__crossx-close-btn"))==null||v.addEventListener("click",f),Oe(y,x,f,m,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,l),p.addEventListener("click",E=>{E.target===p&&f()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var l;G();const t=hs(this.tokens,e);K(t);const s=()=>t.remove(),o=p=>{s(),r(p)},n=()=>{s(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),Ss(t,o,n),(l=t.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),t.addEventListener("click",p=>{p.target===t&&n()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var p;G();const{overlay:s,startCountdown:o}=xs(this.tokens,e,r);K(s);const n=()=>{l(),s.remove()},a=()=>{n(),t()},l=o(a);(p=s.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),s.addEventListener("click",h=>{h.target===s&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,l;G();const t=jr(e,this.tokens,this.messages);K(t);const s=()=>t.remove(),o=()=>{s(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(l=t.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",h=>{var g;h.stopPropagation();const u=p.dataset.copy;u&&((g=navigator.clipboard)==null||g.writeText(u).catch(()=>{}))})}),t.addEventListener("click",p=>{p.target===t&&o()});const n=p=>{p.key==="Escape"&&(document.removeEventListener("keydown",n),o())};document.addEventListener("keydown",n)})}showTransactionProgress(e,r){return new Promise(t=>{G();const s=Yr(e,this.tokens,this.messages);K(s);const o=()=>s.remove();let n=!1;const a=()=>{n||(n=!0,o(),t())},l=()=>{var h,u;(h=s.querySelector("#__crossx-done-btn"))==null||h.addEventListener("click",a),(u=s.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",a),s.addEventListener("click",g=>{g.target===s&&a()});const p=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",p),a())};document.addEventListener("keydown",p)};r.then(p=>{n||(Xr(s,p,this.tokens,this.messages),l())})})}requestConfirmation(e){return new Promise(r=>{var p,h,u;G();let t;e.type==="sign-message"?t=Jr(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=Zr(e,this.tokens,this.messages):e.type==="sign"?t=Br(e,this.tokens,this.displayDecimals,this.messages):t=Hr(e,this.tokens,this.displayDecimals,this.messages);const s=re();K(t);const o=()=>{t.remove(),s()},n=()=>{o(),r(!0)},a=()=>{o(),r(!1)};(p=t.querySelector("#__crossx-confirm-btn"))==null||p.addEventListener("click",n),(h=t.querySelector("#__crossx-cancel-btn"))==null||h.addEventListener("click",a),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",x=>{var m;x.stopPropagation();const f=g.dataset.copy;f&&((m=navigator.clipboard)==null||m.writeText(f).catch(()=>{}))})}),kr(t),t.addEventListener("click",g=>{g.target===t&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)})}}class Es{constructor(e,r,t,s=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=s}shouldDelegateToBridge(){var e;return this.isAuthenticatedViaRNBridge()&&!!((e=this.getBridge())!=null&&e.isInstalled)}async requestConfirmation(e){return this.shouldDelegateToBridge()?!0:this.browserConfirmation.requestConfirmation(e)}async requestNativeConfirmation(e){const r=this.getBridge();if(!r)return{approved:!1,reason:"Bridge not available"};const{operation:t,payload:s,chainId:o}=this.mapToNativeParams(e),n={operation:t,payload:s,dappOrigin:this.getOrigin(),chainId:o};return await r.requestUserConfirmation(n)}mapToNativeParams(e){const r=e.type;switch(r){case"sign-message":{const t=e;return{operation:"signMessage",payload:{message:t.message,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign-typed-data":{const t=e;return{operation:"signTypedData",payload:{typedData:t.typedData,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign":{const t=e;return{operation:"signTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"send":{const t=e;return{operation:"sendTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}default:throw new _(d.INVALID_CONFIG,`Unknown confirmation type: ${String(r)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,r){if(this.shouldDelegateToBridge()){try{await r}catch{}return}return this.browserConfirmation.showTransactionProgress(e,r)}async showLoginSelector(e){return this.browserConfirmation.showLoginSelector(e)}async showMigrationFoundPrompt(e){return this.browserConfirmation.showMigrationFoundPrompt(e)}async showRecoveryPinInputPrompt(e){return this.browserConfirmation.showRecoveryPinInputPrompt(e)}async showRecoveryPinLockedPrompt(e,r){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,r)}async showWalletSelector(e,r,t){const s=this.getBridge();if(this.shouldDelegateToBridge()&&(s!=null&&s.showWalletSelector))try{const o=await s.showWalletSelector({requiredAddress:t}),n=e.find(a=>a.address.toLowerCase()===o.address.toLowerCase());return{address:o.address,index:(n==null?void 0:n.index)??o.index,name:n==null?void 0:n.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,r,t)}async showWalletCreatedPrompt(){var e,r;if(!this.shouldDelegateToBridge())return((r=(e=this.browserConfirmation).showWalletCreatedPrompt)==null?void 0:r.call(e))??Promise.resolve()}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,r){return this.browserConfirmation.setTheme(e,r)}setMessages(e){return this.browserConfirmation.setMessages(e)}setPinKeyboard(e){var r,t;(t=(r=this.browserConfirmation).setPinKeyboard)==null||t.call(r,e)}}class vt{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.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 As(i,e){if(!i.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
|
|
3062
|
+
</svg>`;function Ts(i,e,r){var o;const t=i.querySelectorAll(".__crossx-pin-input");t.forEach((n,a)=>{n.addEventListener("input",()=>{const l=n.value.replace(/\D/g,"");n.value=l?l[0]:"",l&&a<3&&t[a+1].focus();const p=Array.from(t).map(_=>_.value).join("");p.length===4&&setTimeout(()=>e(p),200)}),n.addEventListener("keydown",l=>{l.key==="Backspace"&&!n.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),l.key==="Escape"&&r()}),n.addEventListener("keypress",l=>{/[0-9]/.test(l.key)||l.preventDefault()}),n.addEventListener("paste",l=>{var u;l.preventDefault();const p=(((u=l.clipboardData)==null?void 0:u.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!p)return;p.split("").forEach((x,g)=>{t[g]&&(t[g].value=x)});const _=Math.min(p.length,3);t[_].focus(),p.length===4&&setTimeout(()=>e(p),200)})});const s=i.querySelector(".__crossx-pin-inputs");s==null||s.addEventListener("click",n=>{if(!n.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(l=>!l.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class Rs{constructor(e="light",r,t=We,s){this.theme=e,this.overrides=r,this.tokens=lt(e,r),this.displayDecimals=t,this.pinKeyboard=s,Lr()}setPinKeyboard(e){this.pinKeyboard=e}resolvePinKeyboardMode(){const e=this.pinKeyboard;if(typeof e=="function")try{return e()==="native"?"native":"virtual"}catch{return"virtual"}return e==="native"?"native":"virtual"}applyPinKeyboardMode(e){e&&e.classList.toggle("--native-keypad",this.resolvePinKeyboardMode()==="native")}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=lt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((s,o)=>{var E;G();const n=[...e],a=ds(n,this.tokens,t,this.messages),l=re();K(a);let p=!1;const _=()=>{p||(p=!0,a.remove(),l())};let u=null;const x=A=>{_(),s(A)},g=()=>{_(),u?o(u):s(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(A=>{A.addEventListener("click",()=>{const k=A.dataset.walletAddress??"",T=parseInt(A.dataset.walletIndex??"0",10),N=n.find(U=>U.index===T);x({address:k,index:T,name:N==null?void 0:N.name})})})})();const m=a.querySelector("#__crossx-add-wallet-error"),y=a.querySelector("#__crossx-add-wallet-btn");y&&y.addEventListener("click",async()=>{y.disabled=!0,m&&(m.hidden=!0,m.textContent="");try{const A=await r();n.push(A);const k=a.querySelector("#__crossx-wallet-list");if(k){const T=document.createElement("button");T.className="__crossx-wallet-item",T.dataset.walletIndex=String(A.index),T.dataset.walletAddress=A.address,T.innerHTML=`${It(A.address,A.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${w(At(A))}</span><span class="__crossx-wallet-addr">${ft(A.address)}</span></span>`,T.addEventListener("click",()=>x(A)),k.appendChild(T);try{T.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}y.disabled=!1}catch(A){const k=A instanceof h&&A.code===d.ADDRESS_LIMIT_EXCEEDED,T=this.resolveAddWalletErrorMessage(A);m&&(m.textContent=T,m.hidden=!1),k?(y.disabled=!0,y.setAttribute("aria-disabled","true")):y.disabled=!1,u=A}}),(E=a.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",g),a.addEventListener("click",A=>{A.target===a&&g()});const S=A=>{A.key==="Escape"&&(document.removeEventListener("keydown",S),g())};document.addEventListener("keydown",S)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,l;G();const r=ps(this.tokens,this.messages),t=re();K(r);let s=!1,o=null;const n=()=>{s||(s=!0,o&&document.removeEventListener("keydown",o),r.remove(),t(),e())};(a=r.querySelector("#__crossx-wallet-created-done"))==null||a.addEventListener("click",n),(l=r.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),r.addEventListener("click",p=>{p.target===r&&n()}),o=p=>{p.key==="Escape"&&n()},document.addEventListener("keydown",o)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof h&&e.code===d.ADDRESS_LIMIT_EXCEEDED){const s=e.details,o=typeof(s==null?void 0:s.limit)=="number"?s.limit:ye;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(o))}return(r==null?void 0:r.wallet_selector_add_error_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const r=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(s=>Object.values(pe).includes(s)&&String(s).trim()!==""))??[];return new Promise(s=>{var x,g,f,m;G();const o=gs(this.tokens,r,this.messages),n=re();K(o);const a=()=>{o.remove(),n()},l=y=>{a(),s({type:"oauth",provider:y})},p=y=>{a(),s({type:"external",walletId:y})},_=()=>{a(),s(null)};(x=o.querySelector("#__crossx-apple-btn"))==null||x.addEventListener("click",()=>l("apple")),(g=o.querySelector("#__crossx-google-btn"))==null||g.addEventListener("click",()=>l("google")),(f=o.querySelector("#__crossx-connect-other-wallet-btn"))==null||f.addEventListener("click",y=>{const E=y.currentTarget.dataset.walletId??"";E&&p(E)}),(m=o.querySelector("#__crossx-close-btn"))==null||m.addEventListener("click",_),o.addEventListener("click",y=>{y.target===o&&_()}),o.querySelectorAll(".__crossx-login-terms-link").forEach(y=>{y.addEventListener("click",S=>S.stopPropagation())});const u=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",u),_())};document.addEventListener("keydown",u)})}showSessionAlert(e){return new Promise(r=>{var _,u,x;G();const t=this.messages,s=fs(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.session_alert_account_label)??"Account",signOutLabel:(t==null?void 0:t.session_alert_sign_out_button)??"Sign out",signInAgainLabel:(t==null?void 0:t.session_alert_sign_in_again_button)??"Sign in again"}),o=re();K(s);let n=!1;const a=()=>{n||(n=!0,s.remove(),o())},l=()=>{a(),r("signout")},p=()=>{a(),r("signin-again")};(_=s.querySelector("#__crossx-session-signout"))==null||_.addEventListener("click",l),(u=s.querySelector("#__crossx-session-signin"))==null||u.addEventListener("click",p),(x=s.querySelector("#__crossx-close-btn"))==null||x.addEventListener("click",l)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,l,p;G();const s=ws(this.tokens,r);K(s);const o=()=>s.remove(),n=()=>{o(),t("recover")};if((a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),r){const _=()=>{o(),t("skip")};(l=s.querySelector("#__crossx-skip-btn"))==null||l.addEventListener("click",_),(p=s.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",_),s.addEventListener("click",x=>{x.target===s&&_()});const u=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",u),_())};document.addEventListener("keydown",u)}})}showPinSetupPrompt(e){return new Promise(r=>{G();const t=this.messages,s={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_notice_header_subtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pin_notice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pin_notice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pin_notice_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.pin_notice_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.pin_notice_next_button)??"Next",submitButton:(t==null?void 0:t.pin_notice_submit_button)??"I Understand"},o={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pin_setup_mismatch_error)??"PINs do not match. Please try again."},n={title:(t==null?void 0:t.pin_setup_confirm_title)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_confirm_subtitle)??"Confirm your 6-digit PIN"},a=pt(this.tokens,vs(s)),l=re();K(a);let p=!1;const _=()=>{p||(p=!0,a.remove(),l())},u=E=>{_(),r(E)},x=()=>{_(),r(null)},g=a.querySelector(".__crossx-card"),f={tooShort:(t==null?void 0:t.pin_validation_too_short)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pin_validation_numbers_only)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pin_validation_repeating_digit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pin_validation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pin_validation_alternating_pattern)??"Repeating patterns (e.g., 121212) are not allowed."},m=E=>{var A;g.innerHTML=Le({title:n.title,headerSubtitle:n.headerSubtitle,subtitle:n.subtitle}),this.applyPinKeyboardMode(g),(A=g.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",x),De(g,k=>{k===E?u(E):y(o.mismatchError)},x)},y=E=>{var A;g.innerHTML=Le({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:E}),this.applyPinKeyboardMode(g),(A=g.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",x),De(g,k=>{const T=Ss(k,f);T?y(T):m(k)},x)};(()=>{var q;const E=Array.from(g.querySelectorAll(".__crossx-pw-notice-item")),A=g.querySelector("#__crossx-pin-notice-next"),k=new Set;A.removeAttribute("disabled");const T=A.dataset.nextLabel??"Next",N=A.dataset.submitLabel??"I Understand",U=()=>{const C=k.size===E.length;A.classList.toggle("--disabled",!C),A.textContent=N||T},P=(C,L)=>{if(k.has(L))return;const W=C.querySelector(`#__crossx-notice-check-${L}`);k.add(L),W.classList.add("--checked"),C.setAttribute("aria-checked","true"),U()},z=(C,L)=>{if(!k.has(L))return;const W=C.querySelector(`#__crossx-notice-check-${L}`);k.delete(L),W.classList.remove("--checked"),C.setAttribute("aria-checked","false"),U()};E.forEach(C=>{const L=parseInt(C.dataset.checkIndex??"0",10);C.addEventListener("click",()=>{k.has(L)?z(C,L):P(C,L)}),C.addEventListener("keydown",W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),k.has(L)?z(C,L):P(C,L))})}),A.addEventListener("click",()=>{if(k.size===E.length){y(e==null?void 0:e.errorMessage);return}const C=E.find(W=>{const ne=parseInt(W.dataset.checkIndex??"0",10);return!k.has(ne)});if(!C)return;const L=parseInt(C.dataset.checkIndex??"0",10);C.scrollIntoView({behavior:"smooth",block:"nearest"}),C.classList.add("--highlight"),setTimeout(()=>{C.classList.remove("--highlight"),P(C,L)},400)}),(q=g.querySelector("#__crossx-close-btn"))==null||q.addEventListener("click",x)})(),a.addEventListener("click",E=>{E.target===a&&x()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var S;G();const s=this.messages,o=(e==null?void 0:e.verifyMode)===!0,n=o?(s==null?void 0:s.verify_pin_title)??"Verify Your PIN":(s==null?void 0:s.pin_input_title)??"Enter PIN",a=o?(s==null?void 0:s.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(s==null?void 0:s.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",l=(s==null?void 0:s.pin_locked_failure_warning)??"Your account will be locked after further failures.",p=pt(this.tokens,Le({title:n,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:l,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),_=re();K(p);let u=!1;const x=()=>{u||(u=!0,p.remove(),_())},g=E=>{x(),r(E)},f=()=>{x(),r(null)},m=E=>{x(),t(E)},y=p.querySelector(".__crossx-card");this.applyPinKeyboardMode(y),(S=y.querySelector("#__crossx-close-btn"))==null||S.addEventListener("click",f),De(y,g,f,m,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,l),p.addEventListener("click",E=>{E.target===p&&f()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var l;G();const t=ms(this.tokens,e);K(t);const s=()=>t.remove(),o=p=>{s(),r(p)},n=()=>{s(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),Ts(t,o,n),(l=t.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),t.addEventListener("click",p=>{p.target===t&&n()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var p;G();const{overlay:s,startCountdown:o}=bs(this.tokens,e,r);K(s);const n=()=>{l(),s.remove()},a=()=>{n(),t()},l=o(a);(p=s.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),s.addEventListener("click",_=>{_.target===s&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,l;G();const t=es(e,this.tokens,this.messages);K(t);const s=()=>t.remove(),o=()=>{s(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(l=t.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",_=>{var x;_.stopPropagation();const u=p.dataset.copy;u&&((x=navigator.clipboard)==null||x.writeText(u).catch(()=>{}))})}),t.addEventListener("click",p=>{p.target===t&&o()});const n=p=>{p.key==="Escape"&&(document.removeEventListener("keydown",n),o())};document.addEventListener("keydown",n)})}showTransactionProgress(e,r){return new Promise(t=>{G();const s=ts(e,this.tokens,this.messages);K(s);const o=()=>s.remove();let n=!1;const a=()=>{n||(n=!0,o(),t())},l=()=>{var _,u;(_=s.querySelector("#__crossx-done-btn"))==null||_.addEventListener("click",a),(u=s.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",a),s.addEventListener("click",x=>{x.target===s&&a()});const p=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",p),a())};document.addEventListener("keydown",p)};r.then(p=>{n||(rs(s,p,this.tokens,this.messages),l())})})}requestConfirmation(e){return new Promise(r=>{var p,_,u;G();let t;e.type==="sign-message"?t=ss(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=is(e,this.tokens,this.messages):e.type==="sign"?t=qr(e,this.tokens,this.displayDecimals,this.messages):t=jr(e,this.tokens,this.displayDecimals,this.messages);const s=re();K(t);const o=()=>{t.remove(),s()},n=()=>{o(),r(!0)},a=()=>{o(),r(!1)};(p=t.querySelector("#__crossx-confirm-btn"))==null||p.addEventListener("click",n),(_=t.querySelector("#__crossx-cancel-btn"))==null||_.addEventListener("click",a),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",g=>{var m;g.stopPropagation();const f=x.dataset.copy;f&&((m=navigator.clipboard)==null||m.writeText(f).catch(()=>{}))})}),Pr(t),t.addEventListener("click",x=>{x.target===t&&a()});const l=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)})}}class Ns{constructor(e,r,t,s=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=s}shouldDelegateToBridge(){var e;return this.isAuthenticatedViaRNBridge()&&!!((e=this.getBridge())!=null&&e.isInstalled)}async requestConfirmation(e){return this.shouldDelegateToBridge()?!0:this.browserConfirmation.requestConfirmation(e)}async requestNativeConfirmation(e){const r=this.getBridge();if(!r)return{approved:!1,reason:"Bridge not available"};const{operation:t,payload:s,chainId:o}=this.mapToNativeParams(e),n={operation:t,payload:s,dappOrigin:this.getOrigin(),chainId:o};return await r.requestUserConfirmation(n)}mapToNativeParams(e){const r=e.type;switch(r){case"sign-message":{const t=e;return{operation:"signMessage",payload:{message:t.message,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign-typed-data":{const t=e;return{operation:"signTypedData",payload:{typedData:t.typedData,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign":{const t=e;return{operation:"signTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"send":{const t=e;return{operation:"sendTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}default:throw new h(d.INVALID_CONFIG,`Unknown confirmation type: ${String(r)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,r){if(this.shouldDelegateToBridge()){try{await r}catch{}return}return this.browserConfirmation.showTransactionProgress(e,r)}async showLoginSelector(e){return this.browserConfirmation.showLoginSelector(e)}async showMigrationFoundPrompt(e){return this.browserConfirmation.showMigrationFoundPrompt(e)}async showRecoveryPinInputPrompt(e){return this.browserConfirmation.showRecoveryPinInputPrompt(e)}async showRecoveryPinLockedPrompt(e,r){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,r)}async showWalletSelector(e,r,t){const s=this.getBridge();if(this.shouldDelegateToBridge()&&(s!=null&&s.showWalletSelector))try{const o=await s.showWalletSelector({requiredAddress:t}),n=e.find(a=>a.address.toLowerCase()===o.address.toLowerCase());return{address:o.address,index:(n==null?void 0:n.index)??o.index,name:n==null?void 0:n.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,r,t)}async showWalletCreatedPrompt(){var e,r;if(!this.shouldDelegateToBridge())return((r=(e=this.browserConfirmation).showWalletCreatedPrompt)==null?void 0:r.call(e))??Promise.resolve()}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,r){return this.browserConfirmation.setTheme(e,r)}setMessages(e){return this.browserConfirmation.setMessages(e)}setPinKeyboard(e){var r,t;(t=(r=this.browserConfirmation).setPinKeyboard)==null||t.call(r,e)}}class Tt{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.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 Cs(i,e){if(!i.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
|
|
3066
3063
|
Set the projectId field in SDKConfig when calling createCROSSxSDK().
|
|
3067
|
-
Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);i.debug;const r=_e.production,t={...i,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},s={gatewayUrl:r.walletGatewayUrl,projectId:i.projectId},o=t.authMode!=="cookie"&&
|
|
3064
|
+
Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);i.debug;const r=_e.production,t={...i,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},s={gatewayUrl:r.walletGatewayUrl,projectId:i.projectId},o=t.authMode!=="cookie"&&nt.isAvailable();!o&&t.authMode!=="cookie"&&c.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const n=o?new nt(i.projectId):new gr,a=new yr,l=new Er,p=new se,_=new Tt,u=new Ue;let x;i.useMockWallet?(c.log("[CROSSx] Mock Wallet Provider 사용"),x=new Ir(n,u)):(c.log("[CROSSx] Remote Wallet Provider 사용"),x=new ie(s,n,l,_,u));let g=null;const f=()=>{var N;return((N=g==null?void 0:g.isAuthenticatedViaRNBridge)==null?void 0:N.call(g))??!1},m=()=>{var N;return(N=g==null?void 0:g.assertRNBridgeSessionActive)==null?void 0:N.call(g)};x=new kr(x,()=>{var N;return(N=g==null?void 0:g.getRNBridge)==null?void 0:N.call(g)},f,m,()=>i.appName);const y=new xe(s,l),S=new Rs(i.theme??"light",i.themeTokens,i.displayDecimals,i.pinKeyboard),E=new Ns(S,()=>{var N;return(N=g==null?void 0:g.getRNBridge)==null?void 0:N.call(g)},()=>typeof window<"u"?window.location.origin:"http://localhost",f),A=e!=null&&e.wrapConfirmation?e.wrapConfirmation(E):E,k=new be(t,s,n,a,l,p,x,_,A,y,u);g=k;const T=k.signInUseCase;return T&&typeof T.setFreshTokenCallback=="function"&&T.setFreshTokenCallback(()=>k.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=k),k}function Ps(i){const e=Os(i),r=Ls(e),t=JSON.parse(r);Ms(t);const{data:s}=t;return{status:t.status,state:t.state,firebaseToken:s.accessToken,provider:s.provider,email:s.email,providerSub:s.sub,tokenType:s.tokenType,expiresIn:s.expiresIn,raw:t}}function Os(i){if(i.includes("://")&&i.includes("?")){const e=new URL(i),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return i}function Ls(i){if(i.startsWith("{"))return i;if(i.startsWith("%7B")||i.startsWith("%7b"))return decodeURIComponent(i);const e=Ds(i);return decodeURIComponent(e)}function Ds(i){if(typeof atob=="function")return atob(i);if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Ms(i){if(typeof i!="object"||i===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=i;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 r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}exports.CONNECT_OTHER_WALLET_DISPLAY_ORDER=_t;exports.CROSSxError=h;exports.CROSSxEthereumProvider=ut;exports.CROSSxSDK=be;exports.ChainId=Wt;exports.ConnectOtherWalletItem=pe;exports.ErrorCode=d;exports.MNEMONIC_ADDRESS_LIMIT=ye;exports.PinMemoryStore=Ue;exports.TokenMemoryStore=Tt;exports.WALLET_BRAND_NAME=Ee;exports.createCROSSxSDK=Cs;exports.getConnectOtherWalletLabel=ht;exports.parseOAuthDeeplink=Ps;
|